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