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