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