b2e702a11fe0c1849caf0da508f9f2febecb5439
   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
  25#define DEFAULT_TWOHEAD (1<<0)
  26#define DEFAULT_OCTOPUS (1<<1)
  27#define NO_FAST_FORWARD (1<<2)
  28#define NO_TRIVIAL      (1<<3)
  29
  30struct strategy {
  31        const char *name;
  32        unsigned attr;
  33};
  34
  35static const char * const builtin_merge_usage[] = {
  36        "git-merge [options] <remote>...",
  37        "git-merge [options] <msg> HEAD <remote>",
  38        NULL
  39};
  40
  41static int show_diffstat = 1, option_log, squash;
  42static int option_commit = 1, allow_fast_forward = 1;
  43static int allow_trivial = 1, have_message;
  44static struct strbuf merge_msg;
  45static struct commit_list *remoteheads;
  46static unsigned char head[20], stash[20];
  47static struct strategy **use_strategies;
  48static size_t use_strategies_nr, use_strategies_alloc;
  49static const char *branch;
  50
  51static struct strategy all_strategy[] = {
  52        { "recur",      NO_TRIVIAL },
  53        { "recursive",  DEFAULT_TWOHEAD | NO_TRIVIAL },
  54        { "octopus",    DEFAULT_OCTOPUS },
  55        { "resolve",    0 },
  56        { "stupid",     0 },
  57        { "ours",       NO_FAST_FORWARD | NO_TRIVIAL },
  58        { "subtree",    NO_FAST_FORWARD | NO_TRIVIAL },
  59};
  60
  61static const char *pull_twohead, *pull_octopus;
  62
  63static int option_parse_message(const struct option *opt,
  64                                const char *arg, int unset)
  65{
  66        struct strbuf *buf = opt->value;
  67
  68        if (unset)
  69                strbuf_setlen(buf, 0);
  70        else {
  71                strbuf_addf(buf, "%s\n\n", arg);
  72                have_message = 1;
  73        }
  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        return git_diff_ui_config(k, v, cb);
 468}
 469
 470static int read_tree_trivial(unsigned char *common, unsigned char *head,
 471                             unsigned char *one)
 472{
 473        int i, nr_trees = 0;
 474        struct tree *trees[MAX_UNPACK_TREES];
 475        struct tree_desc t[MAX_UNPACK_TREES];
 476        struct unpack_trees_options opts;
 477
 478        memset(&opts, 0, sizeof(opts));
 479        opts.head_idx = 2;
 480        opts.src_index = &the_index;
 481        opts.dst_index = &the_index;
 482        opts.update = 1;
 483        opts.verbose_update = 1;
 484        opts.trivial_merges_only = 1;
 485        opts.merge = 1;
 486        trees[nr_trees] = parse_tree_indirect(common);
 487        if (!trees[nr_trees++])
 488                return -1;
 489        trees[nr_trees] = parse_tree_indirect(head);
 490        if (!trees[nr_trees++])
 491                return -1;
 492        trees[nr_trees] = parse_tree_indirect(one);
 493        if (!trees[nr_trees++])
 494                return -1;
 495        opts.fn = threeway_merge;
 496        cache_tree_free(&active_cache_tree);
 497        for (i = 0; i < nr_trees; i++) {
 498                parse_tree(trees[i]);
 499                init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
 500        }
 501        if (unpack_trees(nr_trees, t, &opts))
 502                return -1;
 503        return 0;
 504}
 505
 506static void write_tree_trivial(unsigned char *sha1)
 507{
 508        if (write_cache_as_tree(sha1, 0, NULL))
 509                die("git write-tree failed to write a tree");
 510}
 511
 512static int try_merge_strategy(const char *strategy, struct commit_list *common,
 513                              const char *head_arg)
 514{
 515        const char **args;
 516        int i = 0, ret;
 517        struct commit_list *j;
 518        struct strbuf buf;
 519
 520        args = xmalloc((4 + commit_list_count(common) +
 521                        commit_list_count(remoteheads)) * sizeof(char *));
 522        strbuf_init(&buf, 0);
 523        strbuf_addf(&buf, "merge-%s", strategy);
 524        args[i++] = buf.buf;
 525        for (j = common; j; j = j->next)
 526                args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
 527        args[i++] = "--";
 528        args[i++] = head_arg;
 529        for (j = remoteheads; j; j = j->next)
 530                args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
 531        args[i] = NULL;
 532        ret = run_command_v_opt(args, RUN_GIT_CMD);
 533        strbuf_release(&buf);
 534        i = 1;
 535        for (j = common; j; j = j->next)
 536                free((void *)args[i++]);
 537        i += 2;
 538        for (j = remoteheads; j; j = j->next)
 539                free((void *)args[i++]);
 540        free(args);
 541        return -ret;
 542}
 543
 544static void count_diff_files(struct diff_queue_struct *q,
 545                             struct diff_options *opt, void *data)
 546{
 547        int *count = data;
 548
 549        (*count) += q->nr;
 550}
 551
 552static int count_unmerged_entries(void)
 553{
 554        const struct index_state *state = &the_index;
 555        int i, ret = 0;
 556
 557        for (i = 0; i < state->cache_nr; i++)
 558                if (ce_stage(state->cache[i]))
 559                        ret++;
 560
 561        return ret;
 562}
 563
 564static int checkout_fast_forward(unsigned char *head, unsigned char *remote)
 565{
 566        struct tree *trees[MAX_UNPACK_TREES];
 567        struct unpack_trees_options opts;
 568        struct tree_desc t[MAX_UNPACK_TREES];
 569        int i, fd, nr_trees = 0;
 570        struct dir_struct dir;
 571        struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
 572
 573        if (read_cache_unmerged())
 574                die("you need to resolve your current index first");
 575
 576        fd = hold_locked_index(lock_file, 1);
 577
 578        memset(&trees, 0, sizeof(trees));
 579        memset(&opts, 0, sizeof(opts));
 580        memset(&t, 0, sizeof(t));
 581        dir.show_ignored = 1;
 582        dir.exclude_per_dir = ".gitignore";
 583        opts.dir = &dir;
 584
 585        opts.head_idx = 1;
 586        opts.src_index = &the_index;
 587        opts.dst_index = &the_index;
 588        opts.update = 1;
 589        opts.verbose_update = 1;
 590        opts.merge = 1;
 591        opts.fn = twoway_merge;
 592
 593        trees[nr_trees] = parse_tree_indirect(head);
 594        if (!trees[nr_trees++])
 595                return -1;
 596        trees[nr_trees] = parse_tree_indirect(remote);
 597        if (!trees[nr_trees++])
 598                return -1;
 599        for (i = 0; i < nr_trees; i++) {
 600                parse_tree(trees[i]);
 601                init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
 602        }
 603        if (unpack_trees(nr_trees, t, &opts))
 604                return -1;
 605        if (write_cache(fd, active_cache, active_nr) ||
 606                commit_locked_index(lock_file))
 607                die("unable to write new index file");
 608        return 0;
 609}
 610
 611static void split_merge_strategies(const char *string, struct strategy **list,
 612                                   int *nr, int *alloc)
 613{
 614        char *p, *q, *buf;
 615
 616        if (!string)
 617                return;
 618
 619        buf = xstrdup(string);
 620        q = buf;
 621        for (;;) {
 622                p = strchr(q, ' ');
 623                if (!p) {
 624                        ALLOC_GROW(*list, *nr + 1, *alloc);
 625                        (*list)[(*nr)++].name = xstrdup(q);
 626                        free(buf);
 627                        return;
 628                } else {
 629                        *p = '\0';
 630                        ALLOC_GROW(*list, *nr + 1, *alloc);
 631                        (*list)[(*nr)++].name = xstrdup(q);
 632                        q = ++p;
 633                }
 634        }
 635}
 636
 637static void add_strategies(const char *string, unsigned attr)
 638{
 639        struct strategy *list = NULL;
 640        int list_alloc = 0, list_nr = 0, i;
 641
 642        memset(&list, 0, sizeof(list));
 643        split_merge_strategies(string, &list, &list_nr, &list_alloc);
 644        if (list != NULL) {
 645                for (i = 0; i < list_nr; i++) {
 646                        struct strategy *s;
 647
 648                        s = get_strategy(list[i].name);
 649                        if (s)
 650                                append_strategy(s);
 651                }
 652                return;
 653        }
 654        for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
 655                if (all_strategy[i].attr & attr)
 656                        append_strategy(&all_strategy[i]);
 657
 658}
 659
 660static int merge_trivial(void)
 661{
 662        unsigned char result_tree[20], result_commit[20];
 663        struct commit_list parent;
 664
 665        write_tree_trivial(result_tree);
 666        printf("Wonderful.\n");
 667        parent.item = remoteheads->item;
 668        parent.next = NULL;
 669        commit_tree(merge_msg.buf, result_tree, &parent, result_commit);
 670        finish(result_commit, "In-index merge");
 671        drop_save();
 672        return 0;
 673}
 674
 675static int finish_automerge(struct commit_list *common,
 676                            unsigned char *result_tree,
 677                            const char *wt_strategy)
 678{
 679        struct commit_list *parents = NULL, *j;
 680        struct strbuf buf = STRBUF_INIT;
 681        unsigned char result_commit[20];
 682
 683        free_commit_list(common);
 684        if (allow_fast_forward) {
 685                parents = remoteheads;
 686                commit_list_insert(lookup_commit(head), &parents);
 687                parents = reduce_heads(parents);
 688        } else {
 689                struct commit_list **pptr = &parents;
 690
 691                pptr = &commit_list_insert(lookup_commit(head),
 692                                pptr)->next;
 693                for (j = remoteheads; j; j = j->next)
 694                        pptr = &commit_list_insert(j->item, pptr)->next;
 695        }
 696        free_commit_list(remoteheads);
 697        strbuf_addch(&merge_msg, '\n');
 698        commit_tree(merge_msg.buf, result_tree, parents, result_commit);
 699        strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
 700        finish(result_commit, buf.buf);
 701        strbuf_release(&buf);
 702        drop_save();
 703        return 0;
 704}
 705
 706static int suggest_conflicts(void)
 707{
 708        FILE *fp;
 709        int pos;
 710
 711        fp = fopen(git_path("MERGE_MSG"), "a");
 712        if (!fp)
 713                die("Could open %s for writing", git_path("MERGE_MSG"));
 714        fprintf(fp, "\nConflicts:\n");
 715        for (pos = 0; pos < active_nr; pos++) {
 716                struct cache_entry *ce = active_cache[pos];
 717
 718                if (ce_stage(ce)) {
 719                        fprintf(fp, "\t%s\n", ce->name);
 720                        while (pos + 1 < active_nr &&
 721                                        !strcmp(ce->name,
 722                                                active_cache[pos + 1]->name))
 723                                pos++;
 724                }
 725        }
 726        fclose(fp);
 727        rerere();
 728        printf("Automatic merge failed; "
 729                        "fix conflicts and then commit the result.\n");
 730        return 1;
 731}
 732
 733static struct commit *is_old_style_invocation(int argc, const char **argv)
 734{
 735        struct commit *second_token = NULL;
 736        if (argc > 1) {
 737                unsigned char second_sha1[20];
 738
 739                if (get_sha1(argv[1], second_sha1))
 740                        return NULL;
 741                second_token = lookup_commit_reference_gently(second_sha1, 0);
 742                if (!second_token)
 743                        die("'%s' is not a commit", argv[1]);
 744                if (hashcmp(second_token->object.sha1, head))
 745                        return NULL;
 746        }
 747        return second_token;
 748}
 749
 750static int evaluate_result(void)
 751{
 752        int cnt = 0;
 753        struct rev_info rev;
 754
 755        if (read_cache() < 0)
 756                die("failed to read the cache");
 757
 758        /* Check how many files differ. */
 759        init_revisions(&rev, "");
 760        setup_revisions(0, NULL, &rev, NULL);
 761        rev.diffopt.output_format |=
 762                DIFF_FORMAT_CALLBACK;
 763        rev.diffopt.format_callback = count_diff_files;
 764        rev.diffopt.format_callback_data = &cnt;
 765        run_diff_files(&rev, 0);
 766
 767        /*
 768         * Check how many unmerged entries are
 769         * there.
 770         */
 771        cnt += count_unmerged_entries();
 772
 773        return cnt;
 774}
 775
 776int cmd_merge(int argc, const char **argv, const char *prefix)
 777{
 778        unsigned char result_tree[20];
 779        struct strbuf buf;
 780        const char *head_arg;
 781        int flag, head_invalid = 0, i;
 782        int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
 783        struct commit_list *common = NULL;
 784        const char *best_strategy = NULL, *wt_strategy = NULL;
 785        struct commit_list **remotes = &remoteheads;
 786
 787        setup_work_tree();
 788        if (unmerged_cache())
 789                die("You are in the middle of a conflicted merge.");
 790
 791        /*
 792         * Check if we are _not_ on a detached HEAD, i.e. if there is a
 793         * current branch.
 794         */
 795        branch = resolve_ref("HEAD", head, 0, &flag);
 796        if (branch && !prefixcmp(branch, "refs/heads/"))
 797                branch += 11;
 798        if (is_null_sha1(head))
 799                head_invalid = 1;
 800
 801        git_config(git_merge_config, NULL);
 802
 803        /* for color.ui */
 804        if (diff_use_color_default == -1)
 805                diff_use_color_default = git_use_color_default;
 806
 807        argc = parse_options(argc, argv, builtin_merge_options,
 808                        builtin_merge_usage, 0);
 809
 810        if (squash) {
 811                if (!allow_fast_forward)
 812                        die("You cannot combine --squash with --no-ff.");
 813                option_commit = 0;
 814        }
 815
 816        if (!argc)
 817                usage_with_options(builtin_merge_usage,
 818                        builtin_merge_options);
 819
 820        /*
 821         * This could be traditional "merge <msg> HEAD <commit>..."  and
 822         * the way we can tell it is to see if the second token is HEAD,
 823         * but some people might have misused the interface and used a
 824         * committish that is the same as HEAD there instead.
 825         * Traditional format never would have "-m" so it is an
 826         * additional safety measure to check for it.
 827         */
 828        strbuf_init(&buf, 0);
 829
 830        if (!have_message && is_old_style_invocation(argc, argv)) {
 831                strbuf_addstr(&merge_msg, argv[0]);
 832                head_arg = argv[1];
 833                argv += 2;
 834                argc -= 2;
 835        } else if (head_invalid) {
 836                struct object *remote_head;
 837                /*
 838                 * If the merged head is a valid one there is no reason
 839                 * to forbid "git merge" into a branch yet to be born.
 840                 * We do the same for "git pull".
 841                 */
 842                if (argc != 1)
 843                        die("Can merge only exactly one commit into "
 844                                "empty head");
 845                remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
 846                if (!remote_head)
 847                        die("%s - not something we can merge", argv[0]);
 848                update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
 849                                DIE_ON_ERR);
 850                reset_hard(remote_head->sha1, 0);
 851                return 0;
 852        } else {
 853                struct strbuf msg;
 854
 855                /* We are invoked directly as the first-class UI. */
 856                head_arg = "HEAD";
 857
 858                /*
 859                 * All the rest are the commits being merged;
 860                 * prepare the standard merge summary message to
 861                 * be appended to the given message.  If remote
 862                 * is invalid we will die later in the common
 863                 * codepath so we discard the error in this
 864                 * loop.
 865                 */
 866                strbuf_init(&msg, 0);
 867                for (i = 0; i < argc; i++)
 868                        merge_name(argv[i], &msg);
 869                fmt_merge_msg(option_log, &msg, &merge_msg);
 870                if (merge_msg.len)
 871                        strbuf_setlen(&merge_msg, merge_msg.len-1);
 872        }
 873
 874        if (head_invalid || !argc)
 875                usage_with_options(builtin_merge_usage,
 876                        builtin_merge_options);
 877
 878        strbuf_addstr(&buf, "merge");
 879        for (i = 0; i < argc; i++)
 880                strbuf_addf(&buf, " %s", argv[i]);
 881        setenv("GIT_REFLOG_ACTION", buf.buf, 0);
 882        strbuf_reset(&buf);
 883
 884        for (i = 0; i < argc; i++) {
 885                struct object *o;
 886
 887                o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
 888                if (!o)
 889                        die("%s - not something we can merge", argv[i]);
 890                remotes = &commit_list_insert(lookup_commit(o->sha1),
 891                        remotes)->next;
 892
 893                strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
 894                setenv(buf.buf, argv[i], 1);
 895                strbuf_reset(&buf);
 896        }
 897
 898        if (!use_strategies) {
 899                if (!remoteheads->next)
 900                        add_strategies(pull_twohead, DEFAULT_TWOHEAD);
 901                else
 902                        add_strategies(pull_octopus, DEFAULT_OCTOPUS);
 903        }
 904
 905        for (i = 0; i < use_strategies_nr; i++) {
 906                if (use_strategies[i]->attr & NO_FAST_FORWARD)
 907                        allow_fast_forward = 0;
 908                if (use_strategies[i]->attr & NO_TRIVIAL)
 909                        allow_trivial = 0;
 910        }
 911
 912        if (!remoteheads->next)
 913                common = get_merge_bases(lookup_commit(head),
 914                                remoteheads->item, 1);
 915        else {
 916                struct commit_list *list = remoteheads;
 917                commit_list_insert(lookup_commit(head), &list);
 918                common = get_octopus_merge_bases(list);
 919                free(list);
 920        }
 921
 922        update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
 923                DIE_ON_ERR);
 924
 925        if (!common)
 926                ; /* No common ancestors found. We need a real merge. */
 927        else if (!remoteheads->next && !common->next &&
 928                        common->item == remoteheads->item) {
 929                /*
 930                 * If head can reach all the merge then we are up to date.
 931                 * but first the most common case of merging one remote.
 932                 */
 933                finish_up_to_date("Already up-to-date.");
 934                return 0;
 935        } else if (allow_fast_forward && !remoteheads->next &&
 936                        !common->next &&
 937                        !hashcmp(common->item->object.sha1, head)) {
 938                /* Again the most common case of merging one remote. */
 939                struct strbuf msg;
 940                struct object *o;
 941                char hex[41];
 942
 943                strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
 944
 945                printf("Updating %s..%s\n",
 946                        hex,
 947                        find_unique_abbrev(remoteheads->item->object.sha1,
 948                        DEFAULT_ABBREV));
 949                refresh_cache(REFRESH_QUIET);
 950                strbuf_init(&msg, 0);
 951                strbuf_addstr(&msg, "Fast forward");
 952                if (have_message)
 953                        strbuf_addstr(&msg,
 954                                " (no commit created; -m option ignored)");
 955                o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
 956                        0, NULL, OBJ_COMMIT);
 957                if (!o)
 958                        return 1;
 959
 960                if (checkout_fast_forward(head, remoteheads->item->object.sha1))
 961                        return 1;
 962
 963                finish(o->sha1, msg.buf);
 964                drop_save();
 965                return 0;
 966        } else if (!remoteheads->next && common->next)
 967                ;
 968                /*
 969                 * We are not doing octopus and not fast forward.  Need
 970                 * a real merge.
 971                 */
 972        else if (!remoteheads->next && !common->next && option_commit) {
 973                /*
 974                 * We are not doing octopus, not fast forward, and have
 975                 * only one common.
 976                 */
 977                refresh_cache(REFRESH_QUIET);
 978                if (allow_trivial) {
 979                        /* See if it is really trivial. */
 980                        git_committer_info(IDENT_ERROR_ON_NO_NAME);
 981                        printf("Trying really trivial in-index merge...\n");
 982                        if (!read_tree_trivial(common->item->object.sha1,
 983                                        head, remoteheads->item->object.sha1))
 984                                return merge_trivial();
 985                        printf("Nope.\n");
 986                }
 987        } else {
 988                /*
 989                 * An octopus.  If we can reach all the remote we are up
 990                 * to date.
 991                 */
 992                int up_to_date = 1;
 993                struct commit_list *j;
 994
 995                for (j = remoteheads; j; j = j->next) {
 996                        struct commit_list *common_one;
 997
 998                        /*
 999                         * Here we *have* to calculate the individual
1000                         * merge_bases again, otherwise "git merge HEAD^
1001                         * HEAD^^" would be missed.
1002                         */
1003                        common_one = get_merge_bases(lookup_commit(head),
1004                                j->item, 1);
1005                        if (hashcmp(common_one->item->object.sha1,
1006                                j->item->object.sha1)) {
1007                                up_to_date = 0;
1008                                break;
1009                        }
1010                }
1011                if (up_to_date) {
1012                        finish_up_to_date("Already up-to-date. Yeeah!");
1013                        return 0;
1014                }
1015        }
1016
1017        /* We are going to make a new commit. */
1018        git_committer_info(IDENT_ERROR_ON_NO_NAME);
1019
1020        /*
1021         * At this point, we need a real merge.  No matter what strategy
1022         * we use, it would operate on the index, possibly affecting the
1023         * working tree, and when resolved cleanly, have the desired
1024         * tree in the index -- this means that the index must be in
1025         * sync with the head commit.  The strategies are responsible
1026         * to ensure this.
1027         */
1028        if (use_strategies_nr != 1) {
1029                /*
1030                 * Stash away the local changes so that we can try more
1031                 * than one.
1032                 */
1033                save_state();
1034        } else {
1035                memcpy(stash, null_sha1, 20);
1036        }
1037
1038        for (i = 0; i < use_strategies_nr; i++) {
1039                int ret;
1040                if (i) {
1041                        printf("Rewinding the tree to pristine...\n");
1042                        restore_state();
1043                }
1044                if (use_strategies_nr != 1)
1045                        printf("Trying merge strategy %s...\n",
1046                                use_strategies[i]->name);
1047                /*
1048                 * Remember which strategy left the state in the working
1049                 * tree.
1050                 */
1051                wt_strategy = use_strategies[i]->name;
1052
1053                ret = try_merge_strategy(use_strategies[i]->name,
1054                        common, head_arg);
1055                if (!option_commit && !ret) {
1056                        merge_was_ok = 1;
1057                        /*
1058                         * This is necessary here just to avoid writing
1059                         * the tree, but later we will *not* exit with
1060                         * status code 1 because merge_was_ok is set.
1061                         */
1062                        ret = 1;
1063                }
1064
1065                if (ret) {
1066                        /*
1067                         * The backend exits with 1 when conflicts are
1068                         * left to be resolved, with 2 when it does not
1069                         * handle the given merge at all.
1070                         */
1071                        if (ret == 1) {
1072                                int cnt = evaluate_result();
1073
1074                                if (best_cnt <= 0 || cnt <= best_cnt) {
1075                                        best_strategy = use_strategies[i]->name;
1076                                        best_cnt = cnt;
1077                                }
1078                        }
1079                        if (merge_was_ok)
1080                                break;
1081                        else
1082                                continue;
1083                }
1084
1085                /* Automerge succeeded. */
1086                write_tree_trivial(result_tree);
1087                automerge_was_ok = 1;
1088                break;
1089        }
1090
1091        /*
1092         * If we have a resulting tree, that means the strategy module
1093         * auto resolved the merge cleanly.
1094         */
1095        if (automerge_was_ok)
1096                return finish_automerge(common, result_tree, wt_strategy);
1097
1098        /*
1099         * Pick the result from the best strategy and have the user fix
1100         * it up.
1101         */
1102        if (!best_strategy) {
1103                restore_state();
1104                if (use_strategies_nr > 1)
1105                        fprintf(stderr,
1106                                "No merge strategy handled the merge.\n");
1107                else
1108                        fprintf(stderr, "Merge with strategy %s failed.\n",
1109                                use_strategies[0]->name);
1110                return 2;
1111        } else if (best_strategy == wt_strategy)
1112                ; /* We already have its result in the working tree. */
1113        else {
1114                printf("Rewinding the tree to pristine...\n");
1115                restore_state();
1116                printf("Using the %s to prepare resolving by hand.\n",
1117                        best_strategy);
1118                try_merge_strategy(best_strategy, common, head_arg);
1119        }
1120
1121        if (squash)
1122                finish(NULL, NULL);
1123        else {
1124                int fd;
1125                struct commit_list *j;
1126
1127                for (j = remoteheads; j; j = j->next)
1128                        strbuf_addf(&buf, "%s\n",
1129                                sha1_to_hex(j->item->object.sha1));
1130                fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1131                if (fd < 0)
1132                        die("Could open %s for writing",
1133                                git_path("MERGE_HEAD"));
1134                if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1135                        die("Could not write to %s", git_path("MERGE_HEAD"));
1136                close(fd);
1137                strbuf_addch(&merge_msg, '\n');
1138                fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1139                if (fd < 0)
1140                        die("Could open %s for writing", git_path("MERGE_MSG"));
1141                if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1142                        merge_msg.len)
1143                        die("Could not write to %s", git_path("MERGE_MSG"));
1144                close(fd);
1145        }
1146
1147        if (merge_was_ok) {
1148                fprintf(stderr, "Automatic merge went well; "
1149                        "stopped before committing as requested\n");
1150                return 0;
1151        } else
1152                return suggest_conflicts();
1153}