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