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