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