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