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