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