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