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