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