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