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