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