builtin / merge.con commit revert: fix off by one read when searching the end of a commit subject (2c048a3)
   1/*
   2 * Builtin "git merge"
   3 *
   4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
   5 *
   6 * Based on git-merge.sh by Junio C Hamano.
   7 */
   8
   9#include "cache.h"
  10#include "parse-options.h"
  11#include "builtin.h"
  12#include "run-command.h"
  13#include "diff.h"
  14#include "refs.h"
  15#include "commit.h"
  16#include "diffcore.h"
  17#include "revision.h"
  18#include "unpack-trees.h"
  19#include "cache-tree.h"
  20#include "dir.h"
  21#include "utf8.h"
  22#include "log-tree.h"
  23#include "color.h"
  24#include "rerere.h"
  25#include "help.h"
  26#include "merge-recursive.h"
  27#include "resolve-undo.h"
  28
  29#define DEFAULT_TWOHEAD (1<<0)
  30#define DEFAULT_OCTOPUS (1<<1)
  31#define NO_FAST_FORWARD (1<<2)
  32#define NO_TRIVIAL      (1<<3)
  33
  34struct strategy {
  35        const char *name;
  36        unsigned attr;
  37};
  38
  39static const char * const builtin_merge_usage[] = {
  40        "git merge [options] <remote>...",
  41        "git merge [options] <msg> HEAD <remote>",
  42        NULL
  43};
  44
  45static int show_diffstat = 1, option_log, squash;
  46static int option_commit = 1, allow_fast_forward = 1;
  47static int fast_forward_only;
  48static int allow_trivial = 1, have_message;
  49static struct strbuf merge_msg;
  50static struct commit_list *remoteheads;
  51static unsigned char head[20], stash[20];
  52static struct strategy **use_strategies;
  53static size_t use_strategies_nr, use_strategies_alloc;
  54static const char **xopts;
  55static size_t xopts_nr, xopts_alloc;
  56static const char *branch;
  57static int verbosity;
  58static int allow_rerere_auto;
  59
  60static struct strategy all_strategy[] = {
  61        { "recursive",  DEFAULT_TWOHEAD | NO_TRIVIAL },
  62        { "octopus",    DEFAULT_OCTOPUS },
  63        { "resolve",    0 },
  64        { "ours",       NO_FAST_FORWARD | NO_TRIVIAL },
  65        { "subtree",    NO_FAST_FORWARD | NO_TRIVIAL },
  66};
  67
  68static const char *pull_twohead, *pull_octopus;
  69
  70static int option_parse_message(const struct option *opt,
  71                                const char *arg, int unset)
  72{
  73        struct strbuf *buf = opt->value;
  74
  75        if (unset)
  76                strbuf_setlen(buf, 0);
  77        else if (arg) {
  78                strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
  79                have_message = 1;
  80        } else
  81                return error("switch `m' requires a value");
  82        return 0;
  83}
  84
  85static struct strategy *get_strategy(const char *name)
  86{
  87        int i;
  88        struct strategy *ret;
  89        static struct cmdnames main_cmds, other_cmds;
  90        static int loaded;
  91
  92        if (!name)
  93                return NULL;
  94
  95        for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
  96                if (!strcmp(name, all_strategy[i].name))
  97                        return &all_strategy[i];
  98
  99        if (!loaded) {
 100                struct cmdnames not_strategies;
 101                loaded = 1;
 102
 103                memset(&not_strategies, 0, sizeof(struct cmdnames));
 104                load_command_list("git-merge-", &main_cmds, &other_cmds);
 105                for (i = 0; i < main_cmds.cnt; i++) {
 106                        int j, found = 0;
 107                        struct cmdname *ent = main_cmds.names[i];
 108                        for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
 109                                if (!strncmp(ent->name, all_strategy[j].name, ent->len)
 110                                                && !all_strategy[j].name[ent->len])
 111                                        found = 1;
 112                        if (!found)
 113                                add_cmdname(&not_strategies, ent->name, ent->len);
 114                }
 115                exclude_cmds(&main_cmds, &not_strategies);
 116        }
 117        if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
 118                fprintf(stderr, "Could not find merge strategy '%s'.\n", name);
 119                fprintf(stderr, "Available strategies are:");
 120                for (i = 0; i < main_cmds.cnt; i++)
 121                        fprintf(stderr, " %s", main_cmds.names[i]->name);
 122                fprintf(stderr, ".\n");
 123                if (other_cmds.cnt) {
 124                        fprintf(stderr, "Available custom strategies are:");
 125                        for (i = 0; i < other_cmds.cnt; i++)
 126                                fprintf(stderr, " %s", other_cmds.names[i]->name);
 127                        fprintf(stderr, ".\n");
 128                }
 129                exit(1);
 130        }
 131
 132        ret = xcalloc(1, sizeof(struct strategy));
 133        ret->name = xstrdup(name);
 134        return ret;
 135}
 136
 137static void append_strategy(struct strategy *s)
 138{
 139        ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
 140        use_strategies[use_strategies_nr++] = s;
 141}
 142
 143static int option_parse_strategy(const struct option *opt,
 144                                 const char *name, int unset)
 145{
 146        if (unset)
 147                return 0;
 148
 149        append_strategy(get_strategy(name));
 150        return 0;
 151}
 152
 153static int option_parse_x(const struct option *opt,
 154                          const char *arg, int unset)
 155{
 156        if (unset)
 157                return 0;
 158
 159        ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
 160        xopts[xopts_nr++] = xstrdup(arg);
 161        return 0;
 162}
 163
 164static int option_parse_n(const struct option *opt,
 165                          const char *arg, int unset)
 166{
 167        show_diffstat = unset;
 168        return 0;
 169}
 170
 171static struct option builtin_merge_options[] = {
 172        { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
 173                "do not show a diffstat at the end of the merge",
 174                PARSE_OPT_NOARG, option_parse_n },
 175        OPT_BOOLEAN(0, "stat", &show_diffstat,
 176                "show a diffstat at the end of the merge"),
 177        OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
 178        OPT_BOOLEAN(0, "log", &option_log,
 179                "add list of one-line log to merge commit message"),
 180        OPT_BOOLEAN(0, "squash", &squash,
 181                "create a single commit instead of doing a merge"),
 182        OPT_BOOLEAN(0, "commit", &option_commit,
 183                "perform a commit if the merge succeeds (default)"),
 184        OPT_BOOLEAN(0, "ff", &allow_fast_forward,
 185                "allow fast-forward (default)"),
 186        OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
 187                "abort if fast-forward is not possible"),
 188        OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
 189        OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
 190                "merge strategy to use", option_parse_strategy),
 191        OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
 192                "option for selected merge strategy", option_parse_x),
 193        OPT_CALLBACK('m', "message", &merge_msg, "message",
 194                "message to be used for the merge commit (if any)",
 195                option_parse_message),
 196        OPT__VERBOSITY(&verbosity),
 197        OPT_END()
 198};
 199
 200/* Cleans up metadata that is uninteresting after a succeeded merge. */
 201static void drop_save(void)
 202{
 203        unlink(git_path("MERGE_HEAD"));
 204        unlink(git_path("MERGE_MSG"));
 205        unlink(git_path("MERGE_MODE"));
 206}
 207
 208static void save_state(void)
 209{
 210        int len;
 211        struct child_process cp;
 212        struct strbuf buffer = STRBUF_INIT;
 213        const char *argv[] = {"stash", "create", NULL};
 214
 215        memset(&cp, 0, sizeof(cp));
 216        cp.argv = argv;
 217        cp.out = -1;
 218        cp.git_cmd = 1;
 219
 220        if (start_command(&cp))
 221                die("could not run stash.");
 222        len = strbuf_read(&buffer, cp.out, 1024);
 223        close(cp.out);
 224
 225        if (finish_command(&cp) || len < 0)
 226                die("stash failed");
 227        else if (!len)
 228                return;
 229        strbuf_setlen(&buffer, buffer.len-1);
 230        if (get_sha1(buffer.buf, stash))
 231                die("not a valid object: %s", buffer.buf);
 232}
 233
 234static void reset_hard(unsigned const char *sha1, int verbose)
 235{
 236        int i = 0;
 237        const char *args[6];
 238
 239        args[i++] = "read-tree";
 240        if (verbose)
 241                args[i++] = "-v";
 242        args[i++] = "--reset";
 243        args[i++] = "-u";
 244        args[i++] = sha1_to_hex(sha1);
 245        args[i] = NULL;
 246
 247        if (run_command_v_opt(args, RUN_GIT_CMD))
 248                die("read-tree failed");
 249}
 250
 251static void restore_state(void)
 252{
 253        struct strbuf sb = STRBUF_INIT;
 254        const char *args[] = { "stash", "apply", NULL, NULL };
 255
 256        if (is_null_sha1(stash))
 257                return;
 258
 259        reset_hard(head, 1);
 260
 261        args[2] = sha1_to_hex(stash);
 262
 263        /*
 264         * It is OK to ignore error here, for example when there was
 265         * nothing to restore.
 266         */
 267        run_command_v_opt(args, RUN_GIT_CMD);
 268
 269        strbuf_release(&sb);
 270        refresh_cache(REFRESH_QUIET);
 271}
 272
 273/* This is called when no merge was necessary. */
 274static void finish_up_to_date(const char *msg)
 275{
 276        if (verbosity >= 0)
 277                printf("%s%s\n", squash ? " (nothing to squash)" : "", msg);
 278        drop_save();
 279}
 280
 281static void squash_message(void)
 282{
 283        struct rev_info rev;
 284        struct commit *commit;
 285        struct strbuf out = STRBUF_INIT;
 286        struct commit_list *j;
 287        int fd;
 288        struct pretty_print_context ctx = {0};
 289
 290        printf("Squash commit -- not updating HEAD\n");
 291        fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
 292        if (fd < 0)
 293                die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
 294
 295        init_revisions(&rev, NULL);
 296        rev.ignore_merges = 1;
 297        rev.commit_format = CMIT_FMT_MEDIUM;
 298
 299        commit = lookup_commit(head);
 300        commit->object.flags |= UNINTERESTING;
 301        add_pending_object(&rev, &commit->object, NULL);
 302
 303        for (j = remoteheads; j; j = j->next)
 304                add_pending_object(&rev, &j->item->object, NULL);
 305
 306        setup_revisions(0, NULL, &rev, NULL);
 307        if (prepare_revision_walk(&rev))
 308                die("revision walk setup failed");
 309
 310        ctx.abbrev = rev.abbrev;
 311        ctx.date_mode = rev.date_mode;
 312
 313        strbuf_addstr(&out, "Squashed commit of the following:\n");
 314        while ((commit = get_revision(&rev)) != NULL) {
 315                strbuf_addch(&out, '\n');
 316                strbuf_addf(&out, "commit %s\n",
 317                        sha1_to_hex(commit->object.sha1));
 318                pretty_print_commit(rev.commit_format, commit, &out, &ctx);
 319        }
 320        if (write(fd, out.buf, out.len) < 0)
 321                die_errno("Writing SQUASH_MSG");
 322        if (close(fd))
 323                die_errno("Finishing SQUASH_MSG");
 324        strbuf_release(&out);
 325}
 326
 327static void finish(const unsigned char *new_head, const char *msg)
 328{
 329        struct strbuf reflog_message = STRBUF_INIT;
 330
 331        if (!msg)
 332                strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
 333        else {
 334                if (verbosity >= 0)
 335                        printf("%s\n", msg);
 336                strbuf_addf(&reflog_message, "%s: %s",
 337                        getenv("GIT_REFLOG_ACTION"), msg);
 338        }
 339        if (squash) {
 340                squash_message();
 341        } else {
 342                if (verbosity >= 0 && !merge_msg.len)
 343                        printf("No merge message -- not updating HEAD\n");
 344                else {
 345                        const char *argv_gc_auto[] = { "gc", "--auto", NULL };
 346                        update_ref(reflog_message.buf, "HEAD",
 347                                new_head, head, 0,
 348                                DIE_ON_ERR);
 349                        /*
 350                         * We ignore errors in 'gc --auto', since the
 351                         * user should see them.
 352                         */
 353                        run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
 354                }
 355        }
 356        if (new_head && show_diffstat) {
 357                struct diff_options opts;
 358                diff_setup(&opts);
 359                opts.output_format |=
 360                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
 361                opts.detect_rename = DIFF_DETECT_RENAME;
 362                if (diff_use_color_default > 0)
 363                        DIFF_OPT_SET(&opts, COLOR_DIFF);
 364                if (diff_setup_done(&opts) < 0)
 365                        die("diff_setup_done failed");
 366                diff_tree_sha1(head, new_head, "", &opts);
 367                diffcore_std(&opts);
 368                diff_flush(&opts);
 369        }
 370
 371        /* Run a post-merge hook */
 372        run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
 373
 374        strbuf_release(&reflog_message);
 375}
 376
 377/* Get the name for the merge commit's message. */
 378static void merge_name(const char *remote, struct strbuf *msg)
 379{
 380        struct object *remote_head;
 381        unsigned char branch_head[20], buf_sha[20];
 382        struct strbuf buf = STRBUF_INIT;
 383        struct strbuf bname = STRBUF_INIT;
 384        const char *ptr;
 385        char *found_ref;
 386        int len, early;
 387
 388        strbuf_branchname(&bname, remote);
 389        remote = bname.buf;
 390
 391        memset(branch_head, 0, sizeof(branch_head));
 392        remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
 393        if (!remote_head)
 394                die("'%s' does not point to a commit", remote);
 395
 396        if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
 397                if (!prefixcmp(found_ref, "refs/heads/")) {
 398                        strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
 399                                    sha1_to_hex(branch_head), remote);
 400                        goto cleanup;
 401                }
 402                if (!prefixcmp(found_ref, "refs/remotes/")) {
 403                        strbuf_addf(msg, "%s\t\tremote branch '%s' of .\n",
 404                                    sha1_to_hex(branch_head), remote);
 405                        goto cleanup;
 406                }
 407        }
 408
 409        /* See if remote matches <name>^^^.. or <name>~<number> */
 410        for (len = 0, ptr = remote + strlen(remote);
 411             remote < ptr && ptr[-1] == '^';
 412             ptr--)
 413                len++;
 414        if (len)
 415                early = 1;
 416        else {
 417                early = 0;
 418                ptr = strrchr(remote, '~');
 419                if (ptr) {
 420                        int seen_nonzero = 0;
 421
 422                        len++; /* count ~ */
 423                        while (*++ptr && isdigit(*ptr)) {
 424                                seen_nonzero |= (*ptr != '0');
 425                                len++;
 426                        }
 427                        if (*ptr)
 428                                len = 0; /* not ...~<number> */
 429                        else if (seen_nonzero)
 430                                early = 1;
 431                        else if (len == 1)
 432                                early = 1; /* "name~" is "name~1"! */
 433                }
 434        }
 435        if (len) {
 436                struct strbuf truname = STRBUF_INIT;
 437                strbuf_addstr(&truname, "refs/heads/");
 438                strbuf_addstr(&truname, remote);
 439                strbuf_setlen(&truname, truname.len - len);
 440                if (resolve_ref(truname.buf, buf_sha, 0, NULL)) {
 441                        strbuf_addf(msg,
 442                                    "%s\t\tbranch '%s'%s of .\n",
 443                                    sha1_to_hex(remote_head->sha1),
 444                                    truname.buf + 11,
 445                                    (early ? " (early part)" : ""));
 446                        strbuf_release(&truname);
 447                        goto cleanup;
 448                }
 449        }
 450
 451        if (!strcmp(remote, "FETCH_HEAD") &&
 452                        !access(git_path("FETCH_HEAD"), R_OK)) {
 453                FILE *fp;
 454                struct strbuf line = STRBUF_INIT;
 455                char *ptr;
 456
 457                fp = fopen(git_path("FETCH_HEAD"), "r");
 458                if (!fp)
 459                        die_errno("could not open '%s' for reading",
 460                                  git_path("FETCH_HEAD"));
 461                strbuf_getline(&line, fp, '\n');
 462                fclose(fp);
 463                ptr = strstr(line.buf, "\tnot-for-merge\t");
 464                if (ptr)
 465                        strbuf_remove(&line, ptr-line.buf+1, 13);
 466                strbuf_addbuf(msg, &line);
 467                strbuf_release(&line);
 468                goto cleanup;
 469        }
 470        strbuf_addf(msg, "%s\t\tcommit '%s'\n",
 471                sha1_to_hex(remote_head->sha1), remote);
 472cleanup:
 473        strbuf_release(&buf);
 474        strbuf_release(&bname);
 475}
 476
 477static int git_merge_config(const char *k, const char *v, void *cb)
 478{
 479        if (branch && !prefixcmp(k, "branch.") &&
 480                !prefixcmp(k + 7, branch) &&
 481                !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
 482                const char **argv;
 483                int argc;
 484                char *buf;
 485
 486                buf = xstrdup(v);
 487                argc = split_cmdline(buf, &argv);
 488                if (argc < 0)
 489                        die("Bad branch.%s.mergeoptions string", branch);
 490                argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
 491                memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
 492                argc++;
 493                parse_options(argc, argv, NULL, builtin_merge_options,
 494                              builtin_merge_usage, 0);
 495                free(buf);
 496        }
 497
 498        if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
 499                show_diffstat = git_config_bool(k, v);
 500        else if (!strcmp(k, "pull.twohead"))
 501                return git_config_string(&pull_twohead, k, v);
 502        else if (!strcmp(k, "pull.octopus"))
 503                return git_config_string(&pull_octopus, k, v);
 504        else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary"))
 505                option_log = git_config_bool(k, v);
 506        return git_diff_ui_config(k, v, cb);
 507}
 508
 509static int read_tree_trivial(unsigned char *common, unsigned char *head,
 510                             unsigned char *one)
 511{
 512        int i, nr_trees = 0;
 513        struct tree *trees[MAX_UNPACK_TREES];
 514        struct tree_desc t[MAX_UNPACK_TREES];
 515        struct unpack_trees_options opts;
 516
 517        memset(&opts, 0, sizeof(opts));
 518        opts.head_idx = 2;
 519        opts.src_index = &the_index;
 520        opts.dst_index = &the_index;
 521        opts.update = 1;
 522        opts.verbose_update = 1;
 523        opts.trivial_merges_only = 1;
 524        opts.merge = 1;
 525        trees[nr_trees] = parse_tree_indirect(common);
 526        if (!trees[nr_trees++])
 527                return -1;
 528        trees[nr_trees] = parse_tree_indirect(head);
 529        if (!trees[nr_trees++])
 530                return -1;
 531        trees[nr_trees] = parse_tree_indirect(one);
 532        if (!trees[nr_trees++])
 533                return -1;
 534        opts.fn = threeway_merge;
 535        cache_tree_free(&active_cache_tree);
 536        for (i = 0; i < nr_trees; i++) {
 537                parse_tree(trees[i]);
 538                init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
 539        }
 540        if (unpack_trees(nr_trees, t, &opts))
 541                return -1;
 542        return 0;
 543}
 544
 545static void write_tree_trivial(unsigned char *sha1)
 546{
 547        if (write_cache_as_tree(sha1, 0, NULL))
 548                die("git write-tree failed to write a tree");
 549}
 550
 551static int try_merge_strategy(const char *strategy, struct commit_list *common,
 552                              const char *head_arg)
 553{
 554        const char **args;
 555        int i = 0, x = 0, ret;
 556        struct commit_list *j;
 557        struct strbuf buf = STRBUF_INIT;
 558        int index_fd;
 559        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 560
 561        index_fd = hold_locked_index(lock, 1);
 562        refresh_cache(REFRESH_QUIET);
 563        if (active_cache_changed &&
 564                        (write_cache(index_fd, active_cache, active_nr) ||
 565                         commit_locked_index(lock)))
 566                return error("Unable to write index.");
 567        rollback_lock_file(lock);
 568
 569        if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
 570                int clean;
 571                struct commit *result;
 572                struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 573                int index_fd;
 574                struct commit_list *reversed = NULL;
 575                struct merge_options o;
 576
 577                if (remoteheads->next) {
 578                        error("Not handling anything other than two heads merge.");
 579                        return 2;
 580                }
 581
 582                init_merge_options(&o);
 583                if (!strcmp(strategy, "subtree"))
 584                        o.subtree_shift = "";
 585
 586                for (x = 0; x < xopts_nr; x++) {
 587                        if (!strcmp(xopts[x], "ours"))
 588                                o.recursive_variant = MERGE_RECURSIVE_OURS;
 589                        else if (!strcmp(xopts[x], "theirs"))
 590                                o.recursive_variant = MERGE_RECURSIVE_THEIRS;
 591                        else if (!strcmp(xopts[x], "subtree"))
 592                                o.subtree_shift = "";
 593                        else if (!prefixcmp(xopts[x], "subtree="))
 594                                o.subtree_shift = xopts[x]+8;
 595                        else
 596                                die("Unknown option for merge-recursive: -X%s", xopts[x]);
 597                }
 598
 599                o.branch1 = head_arg;
 600                o.branch2 = remoteheads->item->util;
 601
 602                for (j = common; j; j = j->next)
 603                        commit_list_insert(j->item, &reversed);
 604
 605                index_fd = hold_locked_index(lock, 1);
 606                clean = merge_recursive(&o, lookup_commit(head),
 607                                remoteheads->item, reversed, &result);
 608                if (active_cache_changed &&
 609                                (write_cache(index_fd, active_cache, active_nr) ||
 610                                 commit_locked_index(lock)))
 611                        die ("unable to write %s", get_index_file());
 612                rollback_lock_file(lock);
 613                return clean ? 0 : 1;
 614        } else {
 615                args = xmalloc((4 + xopts_nr + commit_list_count(common) +
 616                                        commit_list_count(remoteheads)) * sizeof(char *));
 617                strbuf_addf(&buf, "merge-%s", strategy);
 618                args[i++] = buf.buf;
 619                for (x = 0; x < xopts_nr; x++) {
 620                        char *s = xmalloc(strlen(xopts[x])+2+1);
 621                        strcpy(s, "--");
 622                        strcpy(s+2, xopts[x]);
 623                        args[i++] = s;
 624                }
 625                for (j = common; j; j = j->next)
 626                        args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
 627                args[i++] = "--";
 628                args[i++] = head_arg;
 629                for (j = remoteheads; j; j = j->next)
 630                        args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
 631                args[i] = NULL;
 632                ret = run_command_v_opt(args, RUN_GIT_CMD);
 633                strbuf_release(&buf);
 634                i = 1;
 635                for (x = 0; x < xopts_nr; x++)
 636                        free((void *)args[i++]);
 637                for (j = common; j; j = j->next)
 638                        free((void *)args[i++]);
 639                i += 2;
 640                for (j = remoteheads; j; j = j->next)
 641                        free((void *)args[i++]);
 642                free(args);
 643                discard_cache();
 644                if (read_cache() < 0)
 645                        die("failed to read the cache");
 646                resolve_undo_clear();
 647                return ret;
 648        }
 649}
 650
 651static void count_diff_files(struct diff_queue_struct *q,
 652                             struct diff_options *opt, void *data)
 653{
 654        int *count = data;
 655
 656        (*count) += q->nr;
 657}
 658
 659static int count_unmerged_entries(void)
 660{
 661        int i, ret = 0;
 662
 663        for (i = 0; i < active_nr; i++)
 664                if (ce_stage(active_cache[i]))
 665                        ret++;
 666
 667        return ret;
 668}
 669
 670int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
 671{
 672        struct tree *trees[MAX_UNPACK_TREES];
 673        struct unpack_trees_options opts;
 674        struct tree_desc t[MAX_UNPACK_TREES];
 675        int i, fd, nr_trees = 0;
 676        struct dir_struct dir;
 677        struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
 678
 679        refresh_cache(REFRESH_QUIET);
 680
 681        fd = hold_locked_index(lock_file, 1);
 682
 683        memset(&trees, 0, sizeof(trees));
 684        memset(&opts, 0, sizeof(opts));
 685        memset(&t, 0, sizeof(t));
 686        memset(&dir, 0, sizeof(dir));
 687        dir.flags |= DIR_SHOW_IGNORED;
 688        dir.exclude_per_dir = ".gitignore";
 689        opts.dir = &dir;
 690
 691        opts.head_idx = 1;
 692        opts.src_index = &the_index;
 693        opts.dst_index = &the_index;
 694        opts.update = 1;
 695        opts.verbose_update = 1;
 696        opts.merge = 1;
 697        opts.fn = twoway_merge;
 698        opts.msgs = get_porcelain_error_msgs();
 699
 700        trees[nr_trees] = parse_tree_indirect(head);
 701        if (!trees[nr_trees++])
 702                return -1;
 703        trees[nr_trees] = parse_tree_indirect(remote);
 704        if (!trees[nr_trees++])
 705                return -1;
 706        for (i = 0; i < nr_trees; i++) {
 707                parse_tree(trees[i]);
 708                init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
 709        }
 710        if (unpack_trees(nr_trees, t, &opts))
 711                return -1;
 712        if (write_cache(fd, active_cache, active_nr) ||
 713                commit_locked_index(lock_file))
 714                die("unable to write new index file");
 715        return 0;
 716}
 717
 718static void split_merge_strategies(const char *string, struct strategy **list,
 719                                   int *nr, int *alloc)
 720{
 721        char *p, *q, *buf;
 722
 723        if (!string)
 724                return;
 725
 726        buf = xstrdup(string);
 727        q = buf;
 728        for (;;) {
 729                p = strchr(q, ' ');
 730                if (!p) {
 731                        ALLOC_GROW(*list, *nr + 1, *alloc);
 732                        (*list)[(*nr)++].name = xstrdup(q);
 733                        free(buf);
 734                        return;
 735                } else {
 736                        *p = '\0';
 737                        ALLOC_GROW(*list, *nr + 1, *alloc);
 738                        (*list)[(*nr)++].name = xstrdup(q);
 739                        q = ++p;
 740                }
 741        }
 742}
 743
 744static void add_strategies(const char *string, unsigned attr)
 745{
 746        struct strategy *list = NULL;
 747        int list_alloc = 0, list_nr = 0, i;
 748
 749        memset(&list, 0, sizeof(list));
 750        split_merge_strategies(string, &list, &list_nr, &list_alloc);
 751        if (list) {
 752                for (i = 0; i < list_nr; i++)
 753                        append_strategy(get_strategy(list[i].name));
 754                return;
 755        }
 756        for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
 757                if (all_strategy[i].attr & attr)
 758                        append_strategy(&all_strategy[i]);
 759
 760}
 761
 762static int merge_trivial(void)
 763{
 764        unsigned char result_tree[20], result_commit[20];
 765        struct commit_list *parent = xmalloc(sizeof(*parent));
 766
 767        write_tree_trivial(result_tree);
 768        printf("Wonderful.\n");
 769        parent->item = lookup_commit(head);
 770        parent->next = xmalloc(sizeof(*parent->next));
 771        parent->next->item = remoteheads->item;
 772        parent->next->next = NULL;
 773        commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
 774        finish(result_commit, "In-index merge");
 775        drop_save();
 776        return 0;
 777}
 778
 779static int finish_automerge(struct commit_list *common,
 780                            unsigned char *result_tree,
 781                            const char *wt_strategy)
 782{
 783        struct commit_list *parents = NULL, *j;
 784        struct strbuf buf = STRBUF_INIT;
 785        unsigned char result_commit[20];
 786
 787        free_commit_list(common);
 788        if (allow_fast_forward) {
 789                parents = remoteheads;
 790                commit_list_insert(lookup_commit(head), &parents);
 791                parents = reduce_heads(parents);
 792        } else {
 793                struct commit_list **pptr = &parents;
 794
 795                pptr = &commit_list_insert(lookup_commit(head),
 796                                pptr)->next;
 797                for (j = remoteheads; j; j = j->next)
 798                        pptr = &commit_list_insert(j->item, pptr)->next;
 799        }
 800        free_commit_list(remoteheads);
 801        strbuf_addch(&merge_msg, '\n');
 802        commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
 803        strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
 804        finish(result_commit, buf.buf);
 805        strbuf_release(&buf);
 806        drop_save();
 807        return 0;
 808}
 809
 810static int suggest_conflicts(void)
 811{
 812        FILE *fp;
 813        int pos;
 814
 815        fp = fopen(git_path("MERGE_MSG"), "a");
 816        if (!fp)
 817                die_errno("Could not open '%s' for writing",
 818                          git_path("MERGE_MSG"));
 819        fprintf(fp, "\nConflicts:\n");
 820        for (pos = 0; pos < active_nr; pos++) {
 821                struct cache_entry *ce = active_cache[pos];
 822
 823                if (ce_stage(ce)) {
 824                        fprintf(fp, "\t%s\n", ce->name);
 825                        while (pos + 1 < active_nr &&
 826                                        !strcmp(ce->name,
 827                                                active_cache[pos + 1]->name))
 828                                pos++;
 829                }
 830        }
 831        fclose(fp);
 832        rerere(allow_rerere_auto);
 833        printf("Automatic merge failed; "
 834                        "fix conflicts and then commit the result.\n");
 835        return 1;
 836}
 837
 838static struct commit *is_old_style_invocation(int argc, const char **argv)
 839{
 840        struct commit *second_token = NULL;
 841        if (argc > 2) {
 842                unsigned char second_sha1[20];
 843
 844                if (get_sha1(argv[1], second_sha1))
 845                        return NULL;
 846                second_token = lookup_commit_reference_gently(second_sha1, 0);
 847                if (!second_token)
 848                        die("'%s' is not a commit", argv[1]);
 849                if (hashcmp(second_token->object.sha1, head))
 850                        return NULL;
 851        }
 852        return second_token;
 853}
 854
 855static int evaluate_result(void)
 856{
 857        int cnt = 0;
 858        struct rev_info rev;
 859
 860        /* Check how many files differ. */
 861        init_revisions(&rev, "");
 862        setup_revisions(0, NULL, &rev, NULL);
 863        rev.diffopt.output_format |=
 864                DIFF_FORMAT_CALLBACK;
 865        rev.diffopt.format_callback = count_diff_files;
 866        rev.diffopt.format_callback_data = &cnt;
 867        run_diff_files(&rev, 0);
 868
 869        /*
 870         * Check how many unmerged entries are
 871         * there.
 872         */
 873        cnt += count_unmerged_entries();
 874
 875        return cnt;
 876}
 877
 878int cmd_merge(int argc, const char **argv, const char *prefix)
 879{
 880        unsigned char result_tree[20];
 881        struct strbuf buf = STRBUF_INIT;
 882        const char *head_arg;
 883        int flag, head_invalid = 0, i;
 884        int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
 885        struct commit_list *common = NULL;
 886        const char *best_strategy = NULL, *wt_strategy = NULL;
 887        struct commit_list **remotes = &remoteheads;
 888
 889        if (read_cache_unmerged()) {
 890                die_resolve_conflict("merge");
 891        }
 892        if (file_exists(git_path("MERGE_HEAD"))) {
 893                /*
 894                 * There is no unmerged entry, don't advise 'git
 895                 * add/rm <file>', just 'git commit'.
 896                 */
 897                if (advice_resolve_conflict)
 898                        die("You have not concluded your merge (MERGE_HEAD exists).\n"
 899                            "Please, commit your changes before you can merge.");
 900                else
 901                        die("You have not concluded your merge (MERGE_HEAD exists).");
 902        }
 903
 904        resolve_undo_clear();
 905        /*
 906         * Check if we are _not_ on a detached HEAD, i.e. if there is a
 907         * current branch.
 908         */
 909        branch = resolve_ref("HEAD", head, 0, &flag);
 910        if (branch && !prefixcmp(branch, "refs/heads/"))
 911                branch += 11;
 912        if (is_null_sha1(head))
 913                head_invalid = 1;
 914
 915        git_config(git_merge_config, NULL);
 916
 917        /* for color.ui */
 918        if (diff_use_color_default == -1)
 919                diff_use_color_default = git_use_color_default;
 920
 921        argc = parse_options(argc, argv, prefix, builtin_merge_options,
 922                        builtin_merge_usage, 0);
 923        if (verbosity < 0)
 924                show_diffstat = 0;
 925
 926        if (squash) {
 927                if (!allow_fast_forward)
 928                        die("You cannot combine --squash with --no-ff.");
 929                option_commit = 0;
 930        }
 931
 932        if (!allow_fast_forward && fast_forward_only)
 933                die("You cannot combine --no-ff with --ff-only.");
 934
 935        if (!argc)
 936                usage_with_options(builtin_merge_usage,
 937                        builtin_merge_options);
 938
 939        /*
 940         * This could be traditional "merge <msg> HEAD <commit>..."  and
 941         * the way we can tell it is to see if the second token is HEAD,
 942         * but some people might have misused the interface and used a
 943         * committish that is the same as HEAD there instead.
 944         * Traditional format never would have "-m" so it is an
 945         * additional safety measure to check for it.
 946         */
 947
 948        if (!have_message && is_old_style_invocation(argc, argv)) {
 949                strbuf_addstr(&merge_msg, argv[0]);
 950                head_arg = argv[1];
 951                argv += 2;
 952                argc -= 2;
 953        } else if (head_invalid) {
 954                struct object *remote_head;
 955                /*
 956                 * If the merged head is a valid one there is no reason
 957                 * to forbid "git merge" into a branch yet to be born.
 958                 * We do the same for "git pull".
 959                 */
 960                if (argc != 1)
 961                        die("Can merge only exactly one commit into "
 962                                "empty head");
 963                if (squash)
 964                        die("Squash commit into empty head not supported yet");
 965                if (!allow_fast_forward)
 966                        die("Non-fast-forward commit does not make sense into "
 967                            "an empty head");
 968                remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
 969                if (!remote_head)
 970                        die("%s - not something we can merge", argv[0]);
 971                update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
 972                                DIE_ON_ERR);
 973                reset_hard(remote_head->sha1, 0);
 974                return 0;
 975        } else {
 976                struct strbuf merge_names = STRBUF_INIT;
 977
 978                /* We are invoked directly as the first-class UI. */
 979                head_arg = "HEAD";
 980
 981                /*
 982                 * All the rest are the commits being merged;
 983                 * prepare the standard merge summary message to
 984                 * be appended to the given message.  If remote
 985                 * is invalid we will die later in the common
 986                 * codepath so we discard the error in this
 987                 * loop.
 988                 */
 989                for (i = 0; i < argc; i++)
 990                        merge_name(argv[i], &merge_names);
 991
 992                if (have_message && option_log)
 993                        fmt_merge_msg_shortlog(&merge_names, &merge_msg);
 994                else if (!have_message)
 995                        fmt_merge_msg(option_log, &merge_names, &merge_msg);
 996
 997
 998                if (!(have_message && !option_log) && merge_msg.len)
 999                        strbuf_setlen(&merge_msg, merge_msg.len-1);
1000        }
1001
1002        if (head_invalid || !argc)
1003                usage_with_options(builtin_merge_usage,
1004                        builtin_merge_options);
1005
1006        strbuf_addstr(&buf, "merge");
1007        for (i = 0; i < argc; i++)
1008                strbuf_addf(&buf, " %s", argv[i]);
1009        setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1010        strbuf_reset(&buf);
1011
1012        for (i = 0; i < argc; i++) {
1013                struct object *o;
1014                struct commit *commit;
1015
1016                o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
1017                if (!o)
1018                        die("%s - not something we can merge", argv[i]);
1019                commit = lookup_commit(o->sha1);
1020                commit->util = (void *)argv[i];
1021                remotes = &commit_list_insert(commit, remotes)->next;
1022
1023                strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1024                setenv(buf.buf, argv[i], 1);
1025                strbuf_reset(&buf);
1026        }
1027
1028        if (!use_strategies) {
1029                if (!remoteheads->next)
1030                        add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1031                else
1032                        add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1033        }
1034
1035        for (i = 0; i < use_strategies_nr; i++) {
1036                if (use_strategies[i]->attr & NO_FAST_FORWARD)
1037                        allow_fast_forward = 0;
1038                if (use_strategies[i]->attr & NO_TRIVIAL)
1039                        allow_trivial = 0;
1040        }
1041
1042        if (!remoteheads->next)
1043                common = get_merge_bases(lookup_commit(head),
1044                                remoteheads->item, 1);
1045        else {
1046                struct commit_list *list = remoteheads;
1047                commit_list_insert(lookup_commit(head), &list);
1048                common = get_octopus_merge_bases(list);
1049                free(list);
1050        }
1051
1052        update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1053                DIE_ON_ERR);
1054
1055        if (!common)
1056                ; /* No common ancestors found. We need a real merge. */
1057        else if (!remoteheads->next && !common->next &&
1058                        common->item == remoteheads->item) {
1059                /*
1060                 * If head can reach all the merge then we are up to date.
1061                 * but first the most common case of merging one remote.
1062                 */
1063                finish_up_to_date("Already up-to-date.");
1064                return 0;
1065        } else if (allow_fast_forward && !remoteheads->next &&
1066                        !common->next &&
1067                        !hashcmp(common->item->object.sha1, head)) {
1068                /* Again the most common case of merging one remote. */
1069                struct strbuf msg = STRBUF_INIT;
1070                struct object *o;
1071                char hex[41];
1072
1073                strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1074
1075                if (verbosity >= 0)
1076                        printf("Updating %s..%s\n",
1077                                hex,
1078                                find_unique_abbrev(remoteheads->item->object.sha1,
1079                                DEFAULT_ABBREV));
1080                strbuf_addstr(&msg, "Fast-forward");
1081                if (have_message)
1082                        strbuf_addstr(&msg,
1083                                " (no commit created; -m option ignored)");
1084                o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1085                        0, NULL, OBJ_COMMIT);
1086                if (!o)
1087                        return 1;
1088
1089                if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1090                        return 1;
1091
1092                finish(o->sha1, msg.buf);
1093                drop_save();
1094                return 0;
1095        } else if (!remoteheads->next && common->next)
1096                ;
1097                /*
1098                 * We are not doing octopus and not fast-forward.  Need
1099                 * a real merge.
1100                 */
1101        else if (!remoteheads->next && !common->next && option_commit) {
1102                /*
1103                 * We are not doing octopus, not fast-forward, and have
1104                 * only one common.
1105                 */
1106                refresh_cache(REFRESH_QUIET);
1107                if (allow_trivial && !fast_forward_only) {
1108                        /* See if it is really trivial. */
1109                        git_committer_info(IDENT_ERROR_ON_NO_NAME);
1110                        printf("Trying really trivial in-index merge...\n");
1111                        if (!read_tree_trivial(common->item->object.sha1,
1112                                        head, remoteheads->item->object.sha1))
1113                                return merge_trivial();
1114                        printf("Nope.\n");
1115                }
1116        } else {
1117                /*
1118                 * An octopus.  If we can reach all the remote we are up
1119                 * to date.
1120                 */
1121                int up_to_date = 1;
1122                struct commit_list *j;
1123
1124                for (j = remoteheads; j; j = j->next) {
1125                        struct commit_list *common_one;
1126
1127                        /*
1128                         * Here we *have* to calculate the individual
1129                         * merge_bases again, otherwise "git merge HEAD^
1130                         * HEAD^^" would be missed.
1131                         */
1132                        common_one = get_merge_bases(lookup_commit(head),
1133                                j->item, 1);
1134                        if (hashcmp(common_one->item->object.sha1,
1135                                j->item->object.sha1)) {
1136                                up_to_date = 0;
1137                                break;
1138                        }
1139                }
1140                if (up_to_date) {
1141                        finish_up_to_date("Already up-to-date. Yeeah!");
1142                        return 0;
1143                }
1144        }
1145
1146        if (fast_forward_only)
1147                die("Not possible to fast-forward, aborting.");
1148
1149        /* We are going to make a new commit. */
1150        git_committer_info(IDENT_ERROR_ON_NO_NAME);
1151
1152        /*
1153         * At this point, we need a real merge.  No matter what strategy
1154         * we use, it would operate on the index, possibly affecting the
1155         * working tree, and when resolved cleanly, have the desired
1156         * tree in the index -- this means that the index must be in
1157         * sync with the head commit.  The strategies are responsible
1158         * to ensure this.
1159         */
1160        if (use_strategies_nr != 1) {
1161                /*
1162                 * Stash away the local changes so that we can try more
1163                 * than one.
1164                 */
1165                save_state();
1166        } else {
1167                memcpy(stash, null_sha1, 20);
1168        }
1169
1170        for (i = 0; i < use_strategies_nr; i++) {
1171                int ret;
1172                if (i) {
1173                        printf("Rewinding the tree to pristine...\n");
1174                        restore_state();
1175                }
1176                if (use_strategies_nr != 1)
1177                        printf("Trying merge strategy %s...\n",
1178                                use_strategies[i]->name);
1179                /*
1180                 * Remember which strategy left the state in the working
1181                 * tree.
1182                 */
1183                wt_strategy = use_strategies[i]->name;
1184
1185                ret = try_merge_strategy(use_strategies[i]->name,
1186                        common, head_arg);
1187                if (!option_commit && !ret) {
1188                        merge_was_ok = 1;
1189                        /*
1190                         * This is necessary here just to avoid writing
1191                         * the tree, but later we will *not* exit with
1192                         * status code 1 because merge_was_ok is set.
1193                         */
1194                        ret = 1;
1195                }
1196
1197                if (ret) {
1198                        /*
1199                         * The backend exits with 1 when conflicts are
1200                         * left to be resolved, with 2 when it does not
1201                         * handle the given merge at all.
1202                         */
1203                        if (ret == 1) {
1204                                int cnt = evaluate_result();
1205
1206                                if (best_cnt <= 0 || cnt <= best_cnt) {
1207                                        best_strategy = use_strategies[i]->name;
1208                                        best_cnt = cnt;
1209                                }
1210                        }
1211                        if (merge_was_ok)
1212                                break;
1213                        else
1214                                continue;
1215                }
1216
1217                /* Automerge succeeded. */
1218                write_tree_trivial(result_tree);
1219                automerge_was_ok = 1;
1220                break;
1221        }
1222
1223        /*
1224         * If we have a resulting tree, that means the strategy module
1225         * auto resolved the merge cleanly.
1226         */
1227        if (automerge_was_ok)
1228                return finish_automerge(common, result_tree, wt_strategy);
1229
1230        /*
1231         * Pick the result from the best strategy and have the user fix
1232         * it up.
1233         */
1234        if (!best_strategy) {
1235                restore_state();
1236                if (use_strategies_nr > 1)
1237                        fprintf(stderr,
1238                                "No merge strategy handled the merge.\n");
1239                else
1240                        fprintf(stderr, "Merge with strategy %s failed.\n",
1241                                use_strategies[0]->name);
1242                return 2;
1243        } else if (best_strategy == wt_strategy)
1244                ; /* We already have its result in the working tree. */
1245        else {
1246                printf("Rewinding the tree to pristine...\n");
1247                restore_state();
1248                printf("Using the %s to prepare resolving by hand.\n",
1249                        best_strategy);
1250                try_merge_strategy(best_strategy, common, head_arg);
1251        }
1252
1253        if (squash)
1254                finish(NULL, NULL);
1255        else {
1256                int fd;
1257                struct commit_list *j;
1258
1259                for (j = remoteheads; j; j = j->next)
1260                        strbuf_addf(&buf, "%s\n",
1261                                sha1_to_hex(j->item->object.sha1));
1262                fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1263                if (fd < 0)
1264                        die_errno("Could not open '%s' for writing",
1265                                  git_path("MERGE_HEAD"));
1266                if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1267                        die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1268                close(fd);
1269                strbuf_addch(&merge_msg, '\n');
1270                fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1271                if (fd < 0)
1272                        die_errno("Could not open '%s' for writing",
1273                                  git_path("MERGE_MSG"));
1274                if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1275                        merge_msg.len)
1276                        die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1277                close(fd);
1278                fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1279                if (fd < 0)
1280                        die_errno("Could not open '%s' for writing",
1281                                  git_path("MERGE_MODE"));
1282                strbuf_reset(&buf);
1283                if (!allow_fast_forward)
1284                        strbuf_addf(&buf, "no-ff");
1285                if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1286                        die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1287                close(fd);
1288        }
1289
1290        if (merge_was_ok) {
1291                fprintf(stderr, "Automatic merge went well; "
1292                        "stopped before committing as requested\n");
1293                return 0;
1294        } else
1295                return suggest_conflicts();
1296}