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