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