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