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