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