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