builtin / merge.con commit Merge branch 'tg/push-all-in-mirror-forbidden' (fe048e4)
   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#define USE_THE_INDEX_COMPATIBILITY_MACROS
  10#include "cache.h"
  11#include "config.h"
  12#include "parse-options.h"
  13#include "builtin.h"
  14#include "lockfile.h"
  15#include "run-command.h"
  16#include "diff.h"
  17#include "refs.h"
  18#include "refspec.h"
  19#include "commit.h"
  20#include "diffcore.h"
  21#include "revision.h"
  22#include "unpack-trees.h"
  23#include "cache-tree.h"
  24#include "dir.h"
  25#include "utf8.h"
  26#include "log-tree.h"
  27#include "color.h"
  28#include "rerere.h"
  29#include "help.h"
  30#include "merge-recursive.h"
  31#include "resolve-undo.h"
  32#include "remote.h"
  33#include "fmt-merge-msg.h"
  34#include "gpg-interface.h"
  35#include "sequencer.h"
  36#include "string-list.h"
  37#include "packfile.h"
  38#include "tag.h"
  39#include "alias.h"
  40#include "branch.h"
  41#include "commit-reach.h"
  42#include "wt-status.h"
  43
  44#define DEFAULT_TWOHEAD (1<<0)
  45#define DEFAULT_OCTOPUS (1<<1)
  46#define NO_FAST_FORWARD (1<<2)
  47#define NO_TRIVIAL      (1<<3)
  48
  49struct strategy {
  50        const char *name;
  51        unsigned attr;
  52};
  53
  54static const char * const builtin_merge_usage[] = {
  55        N_("git merge [<options>] [<commit>...]"),
  56        N_("git merge --abort"),
  57        N_("git merge --continue"),
  58        NULL
  59};
  60
  61static int show_diffstat = 1, shortlog_len = -1, squash;
  62static int option_commit = -1;
  63static int option_edit = -1;
  64static int allow_trivial = 1, have_message, verify_signatures;
  65static int overwrite_ignore = 1;
  66static struct strbuf merge_msg = STRBUF_INIT;
  67static struct strategy **use_strategies;
  68static size_t use_strategies_nr, use_strategies_alloc;
  69static const char **xopts;
  70static size_t xopts_nr, xopts_alloc;
  71static const char *branch;
  72static char *branch_mergeoptions;
  73static int option_renormalize;
  74static int verbosity;
  75static int allow_rerere_auto;
  76static int abort_current_merge;
  77static int quit_current_merge;
  78static int continue_current_merge;
  79static int allow_unrelated_histories;
  80static int show_progress = -1;
  81static int default_to_upstream = 1;
  82static int signoff;
  83static const char *sign_commit;
  84static int no_verify;
  85
  86static struct strategy all_strategy[] = {
  87        { "recursive",  DEFAULT_TWOHEAD | NO_TRIVIAL },
  88        { "octopus",    DEFAULT_OCTOPUS },
  89        { "resolve",    0 },
  90        { "ours",       NO_FAST_FORWARD | NO_TRIVIAL },
  91        { "subtree",    NO_FAST_FORWARD | NO_TRIVIAL },
  92};
  93
  94static const char *pull_twohead, *pull_octopus;
  95
  96enum ff_type {
  97        FF_NO,
  98        FF_ALLOW,
  99        FF_ONLY
 100};
 101
 102static enum ff_type fast_forward = FF_ALLOW;
 103
 104static const char *cleanup_arg;
 105static enum commit_msg_cleanup_mode cleanup_mode;
 106
 107static int option_parse_message(const struct option *opt,
 108                                const char *arg, int unset)
 109{
 110        struct strbuf *buf = opt->value;
 111
 112        if (unset)
 113                strbuf_setlen(buf, 0);
 114        else if (arg) {
 115                strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
 116                have_message = 1;
 117        } else
 118                return error(_("switch `m' requires a value"));
 119        return 0;
 120}
 121
 122static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
 123                                                 const struct option *opt,
 124                                                 const char *arg_not_used,
 125                                                 int unset)
 126{
 127        struct strbuf *buf = opt->value;
 128        const char *arg;
 129
 130        BUG_ON_OPT_ARG(arg_not_used);
 131        if (unset)
 132                BUG("-F cannot be negated");
 133
 134        if (ctx->opt) {
 135                arg = ctx->opt;
 136                ctx->opt = NULL;
 137        } else if (ctx->argc > 1) {
 138                ctx->argc--;
 139                arg = *++ctx->argv;
 140        } else
 141                return error(_("option `%s' requires a value"), opt->long_name);
 142
 143        if (buf->len)
 144                strbuf_addch(buf, '\n');
 145        if (ctx->prefix && !is_absolute_path(arg))
 146                arg = prefix_filename(ctx->prefix, arg);
 147        if (strbuf_read_file(buf, arg, 0) < 0)
 148                return error(_("could not read file '%s'"), arg);
 149        have_message = 1;
 150
 151        return 0;
 152}
 153
 154static struct strategy *get_strategy(const char *name)
 155{
 156        int i;
 157        struct strategy *ret;
 158        static struct cmdnames main_cmds, other_cmds;
 159        static int loaded;
 160
 161        if (!name)
 162                return NULL;
 163
 164        for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
 165                if (!strcmp(name, all_strategy[i].name))
 166                        return &all_strategy[i];
 167
 168        if (!loaded) {
 169                struct cmdnames not_strategies;
 170                loaded = 1;
 171
 172                memset(&not_strategies, 0, sizeof(struct cmdnames));
 173                load_command_list("git-merge-", &main_cmds, &other_cmds);
 174                for (i = 0; i < main_cmds.cnt; i++) {
 175                        int j, found = 0;
 176                        struct cmdname *ent = main_cmds.names[i];
 177                        for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
 178                                if (!strncmp(ent->name, all_strategy[j].name, ent->len)
 179                                                && !all_strategy[j].name[ent->len])
 180                                        found = 1;
 181                        if (!found)
 182                                add_cmdname(&not_strategies, ent->name, ent->len);
 183                }
 184                exclude_cmds(&main_cmds, &not_strategies);
 185        }
 186        if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
 187                fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
 188                fprintf(stderr, _("Available strategies are:"));
 189                for (i = 0; i < main_cmds.cnt; i++)
 190                        fprintf(stderr, " %s", main_cmds.names[i]->name);
 191                fprintf(stderr, ".\n");
 192                if (other_cmds.cnt) {
 193                        fprintf(stderr, _("Available custom strategies are:"));
 194                        for (i = 0; i < other_cmds.cnt; i++)
 195                                fprintf(stderr, " %s", other_cmds.names[i]->name);
 196                        fprintf(stderr, ".\n");
 197                }
 198                exit(1);
 199        }
 200
 201        ret = xcalloc(1, sizeof(struct strategy));
 202        ret->name = xstrdup(name);
 203        ret->attr = NO_TRIVIAL;
 204        return ret;
 205}
 206
 207static void append_strategy(struct strategy *s)
 208{
 209        ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
 210        use_strategies[use_strategies_nr++] = s;
 211}
 212
 213static int option_parse_strategy(const struct option *opt,
 214                                 const char *name, int unset)
 215{
 216        if (unset)
 217                return 0;
 218
 219        append_strategy(get_strategy(name));
 220        return 0;
 221}
 222
 223static int option_parse_x(const struct option *opt,
 224                          const char *arg, int unset)
 225{
 226        if (unset)
 227                return 0;
 228
 229        ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
 230        xopts[xopts_nr++] = xstrdup(arg);
 231        return 0;
 232}
 233
 234static int option_parse_n(const struct option *opt,
 235                          const char *arg, int unset)
 236{
 237        BUG_ON_OPT_ARG(arg);
 238        show_diffstat = unset;
 239        return 0;
 240}
 241
 242static struct option builtin_merge_options[] = {
 243        { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
 244                N_("do not show a diffstat at the end of the merge"),
 245                PARSE_OPT_NOARG, option_parse_n },
 246        OPT_BOOL(0, "stat", &show_diffstat,
 247                N_("show a diffstat at the end of the merge")),
 248        OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
 249        { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
 250          N_("add (at most <n>) entries from shortlog to merge commit message"),
 251          PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
 252        OPT_BOOL(0, "squash", &squash,
 253                N_("create a single commit instead of doing a merge")),
 254        OPT_BOOL(0, "commit", &option_commit,
 255                N_("perform a commit if the merge succeeds (default)")),
 256        OPT_BOOL('e', "edit", &option_edit,
 257                N_("edit message before committing")),
 258        OPT_CLEANUP(&cleanup_arg),
 259        OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
 260        OPT_SET_INT_F(0, "ff-only", &fast_forward,
 261                      N_("abort if fast-forward is not possible"),
 262                      FF_ONLY, PARSE_OPT_NONEG),
 263        OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
 264        OPT_BOOL(0, "verify-signatures", &verify_signatures,
 265                N_("verify that the named commit has a valid GPG signature")),
 266        OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
 267                N_("merge strategy to use"), option_parse_strategy),
 268        OPT_CALLBACK('X', "strategy-option", &xopts, N_("option=value"),
 269                N_("option for selected merge strategy"), option_parse_x),
 270        OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
 271                N_("merge commit message (for a non-fast-forward merge)"),
 272                option_parse_message),
 273        { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
 274                N_("read message from file"), PARSE_OPT_NONEG,
 275                NULL, 0, option_read_message },
 276        OPT__VERBOSITY(&verbosity),
 277        OPT_BOOL(0, "abort", &abort_current_merge,
 278                N_("abort the current in-progress merge")),
 279        OPT_BOOL(0, "quit", &quit_current_merge,
 280                N_("--abort but leave index and working tree alone")),
 281        OPT_BOOL(0, "continue", &continue_current_merge,
 282                N_("continue the current in-progress merge")),
 283        OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
 284                 N_("allow merging unrelated histories")),
 285        OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
 286        { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
 287          N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
 288        OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
 289        OPT_BOOL(0, "signoff", &signoff, N_("add Signed-off-by:")),
 290        OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
 291        OPT_END()
 292};
 293
 294static int save_state(struct object_id *stash)
 295{
 296        int len;
 297        struct child_process cp = CHILD_PROCESS_INIT;
 298        struct strbuf buffer = STRBUF_INIT;
 299        const char *argv[] = {"stash", "create", NULL};
 300        int rc = -1;
 301
 302        cp.argv = argv;
 303        cp.out = -1;
 304        cp.git_cmd = 1;
 305
 306        if (start_command(&cp))
 307                die(_("could not run stash."));
 308        len = strbuf_read(&buffer, cp.out, 1024);
 309        close(cp.out);
 310
 311        if (finish_command(&cp) || len < 0)
 312                die(_("stash failed"));
 313        else if (!len)          /* no changes */
 314                goto out;
 315        strbuf_setlen(&buffer, buffer.len-1);
 316        if (get_oid(buffer.buf, stash))
 317                die(_("not a valid object: %s"), buffer.buf);
 318        rc = 0;
 319out:
 320        strbuf_release(&buffer);
 321        return rc;
 322}
 323
 324static void read_empty(const struct object_id *oid, int verbose)
 325{
 326        int i = 0;
 327        const char *args[7];
 328
 329        args[i++] = "read-tree";
 330        if (verbose)
 331                args[i++] = "-v";
 332        args[i++] = "-m";
 333        args[i++] = "-u";
 334        args[i++] = empty_tree_oid_hex();
 335        args[i++] = oid_to_hex(oid);
 336        args[i] = NULL;
 337
 338        if (run_command_v_opt(args, RUN_GIT_CMD))
 339                die(_("read-tree failed"));
 340}
 341
 342static void reset_hard(const struct object_id *oid, int verbose)
 343{
 344        int i = 0;
 345        const char *args[6];
 346
 347        args[i++] = "read-tree";
 348        if (verbose)
 349                args[i++] = "-v";
 350        args[i++] = "--reset";
 351        args[i++] = "-u";
 352        args[i++] = oid_to_hex(oid);
 353        args[i] = NULL;
 354
 355        if (run_command_v_opt(args, RUN_GIT_CMD))
 356                die(_("read-tree failed"));
 357}
 358
 359static void restore_state(const struct object_id *head,
 360                          const struct object_id *stash)
 361{
 362        struct strbuf sb = STRBUF_INIT;
 363        const char *args[] = { "stash", "apply", NULL, NULL };
 364
 365        if (is_null_oid(stash))
 366                return;
 367
 368        reset_hard(head, 1);
 369
 370        args[2] = oid_to_hex(stash);
 371
 372        /*
 373         * It is OK to ignore error here, for example when there was
 374         * nothing to restore.
 375         */
 376        run_command_v_opt(args, RUN_GIT_CMD);
 377
 378        strbuf_release(&sb);
 379        refresh_cache(REFRESH_QUIET);
 380}
 381
 382/* This is called when no merge was necessary. */
 383static void finish_up_to_date(const char *msg)
 384{
 385        if (verbosity >= 0)
 386                printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
 387        remove_merge_branch_state(the_repository);
 388}
 389
 390static void squash_message(struct commit *commit, struct commit_list *remoteheads)
 391{
 392        struct rev_info rev;
 393        struct strbuf out = STRBUF_INIT;
 394        struct commit_list *j;
 395        struct pretty_print_context ctx = {0};
 396
 397        printf(_("Squash commit -- not updating HEAD\n"));
 398
 399        repo_init_revisions(the_repository, &rev, NULL);
 400        rev.ignore_merges = 1;
 401        rev.commit_format = CMIT_FMT_MEDIUM;
 402
 403        commit->object.flags |= UNINTERESTING;
 404        add_pending_object(&rev, &commit->object, NULL);
 405
 406        for (j = remoteheads; j; j = j->next)
 407                add_pending_object(&rev, &j->item->object, NULL);
 408
 409        setup_revisions(0, NULL, &rev, NULL);
 410        if (prepare_revision_walk(&rev))
 411                die(_("revision walk setup failed"));
 412
 413        ctx.abbrev = rev.abbrev;
 414        ctx.date_mode = rev.date_mode;
 415        ctx.fmt = rev.commit_format;
 416
 417        strbuf_addstr(&out, "Squashed commit of the following:\n");
 418        while ((commit = get_revision(&rev)) != NULL) {
 419                strbuf_addch(&out, '\n');
 420                strbuf_addf(&out, "commit %s\n",
 421                        oid_to_hex(&commit->object.oid));
 422                pretty_print_commit(&ctx, commit, &out);
 423        }
 424        write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
 425        strbuf_release(&out);
 426}
 427
 428static void finish(struct commit *head_commit,
 429                   struct commit_list *remoteheads,
 430                   const struct object_id *new_head, const char *msg)
 431{
 432        struct strbuf reflog_message = STRBUF_INIT;
 433        const struct object_id *head = &head_commit->object.oid;
 434
 435        if (!msg)
 436                strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
 437        else {
 438                if (verbosity >= 0)
 439                        printf("%s\n", msg);
 440                strbuf_addf(&reflog_message, "%s: %s",
 441                        getenv("GIT_REFLOG_ACTION"), msg);
 442        }
 443        if (squash) {
 444                squash_message(head_commit, remoteheads);
 445        } else {
 446                if (verbosity >= 0 && !merge_msg.len)
 447                        printf(_("No merge message -- not updating HEAD\n"));
 448                else {
 449                        const char *argv_gc_auto[] = { "gc", "--auto", NULL };
 450                        update_ref(reflog_message.buf, "HEAD", new_head, head,
 451                                   0, UPDATE_REFS_DIE_ON_ERR);
 452                        /*
 453                         * We ignore errors in 'gc --auto', since the
 454                         * user should see them.
 455                         */
 456                        close_object_store(the_repository->objects);
 457                        run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
 458                }
 459        }
 460        if (new_head && show_diffstat) {
 461                struct diff_options opts;
 462                repo_diff_setup(the_repository, &opts);
 463                opts.stat_width = -1; /* use full terminal width */
 464                opts.stat_graph_width = -1; /* respect statGraphWidth config */
 465                opts.output_format |=
 466                        DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
 467                opts.detect_rename = DIFF_DETECT_RENAME;
 468                diff_setup_done(&opts);
 469                diff_tree_oid(head, new_head, "", &opts);
 470                diffcore_std(&opts);
 471                diff_flush(&opts);
 472        }
 473
 474        /* Run a post-merge hook */
 475        run_hook_le(NULL, "post-merge", squash ? "1" : "0", NULL);
 476
 477        strbuf_release(&reflog_message);
 478}
 479
 480/* Get the name for the merge commit's message. */
 481static void merge_name(const char *remote, struct strbuf *msg)
 482{
 483        struct commit *remote_head;
 484        struct object_id branch_head;
 485        struct strbuf buf = STRBUF_INIT;
 486        struct strbuf bname = STRBUF_INIT;
 487        struct merge_remote_desc *desc;
 488        const char *ptr;
 489        char *found_ref;
 490        int len, early;
 491
 492        strbuf_branchname(&bname, remote, 0);
 493        remote = bname.buf;
 494
 495        oidclr(&branch_head);
 496        remote_head = get_merge_parent(remote);
 497        if (!remote_head)
 498                die(_("'%s' does not point to a commit"), remote);
 499
 500        if (dwim_ref(remote, strlen(remote), &branch_head, &found_ref) > 0) {
 501                if (starts_with(found_ref, "refs/heads/")) {
 502                        strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
 503                                    oid_to_hex(&branch_head), remote);
 504                        goto cleanup;
 505                }
 506                if (starts_with(found_ref, "refs/tags/")) {
 507                        strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
 508                                    oid_to_hex(&branch_head), remote);
 509                        goto cleanup;
 510                }
 511                if (starts_with(found_ref, "refs/remotes/")) {
 512                        strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
 513                                    oid_to_hex(&branch_head), remote);
 514                        goto cleanup;
 515                }
 516        }
 517
 518        /* See if remote matches <name>^^^.. or <name>~<number> */
 519        for (len = 0, ptr = remote + strlen(remote);
 520             remote < ptr && ptr[-1] == '^';
 521             ptr--)
 522                len++;
 523        if (len)
 524                early = 1;
 525        else {
 526                early = 0;
 527                ptr = strrchr(remote, '~');
 528                if (ptr) {
 529                        int seen_nonzero = 0;
 530
 531                        len++; /* count ~ */
 532                        while (*++ptr && isdigit(*ptr)) {
 533                                seen_nonzero |= (*ptr != '0');
 534                                len++;
 535                        }
 536                        if (*ptr)
 537                                len = 0; /* not ...~<number> */
 538                        else if (seen_nonzero)
 539                                early = 1;
 540                        else if (len == 1)
 541                                early = 1; /* "name~" is "name~1"! */
 542                }
 543        }
 544        if (len) {
 545                struct strbuf truname = STRBUF_INIT;
 546                strbuf_addf(&truname, "refs/heads/%s", remote);
 547                strbuf_setlen(&truname, truname.len - len);
 548                if (ref_exists(truname.buf)) {
 549                        strbuf_addf(msg,
 550                                    "%s\t\tbranch '%s'%s of .\n",
 551                                    oid_to_hex(&remote_head->object.oid),
 552                                    truname.buf + 11,
 553                                    (early ? " (early part)" : ""));
 554                        strbuf_release(&truname);
 555                        goto cleanup;
 556                }
 557                strbuf_release(&truname);
 558        }
 559
 560        desc = merge_remote_util(remote_head);
 561        if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
 562                strbuf_addf(msg, "%s\t\t%s '%s'\n",
 563                            oid_to_hex(&desc->obj->oid),
 564                            type_name(desc->obj->type),
 565                            remote);
 566                goto cleanup;
 567        }
 568
 569        strbuf_addf(msg, "%s\t\tcommit '%s'\n",
 570                oid_to_hex(&remote_head->object.oid), remote);
 571cleanup:
 572        strbuf_release(&buf);
 573        strbuf_release(&bname);
 574}
 575
 576static void parse_branch_merge_options(char *bmo)
 577{
 578        const char **argv;
 579        int argc;
 580
 581        if (!bmo)
 582                return;
 583        argc = split_cmdline(bmo, &argv);
 584        if (argc < 0)
 585                die(_("Bad branch.%s.mergeoptions string: %s"), branch,
 586                    _(split_cmdline_strerror(argc)));
 587        REALLOC_ARRAY(argv, argc + 2);
 588        MOVE_ARRAY(argv + 1, argv, argc + 1);
 589        argc++;
 590        argv[0] = "branch.*.mergeoptions";
 591        parse_options(argc, argv, NULL, builtin_merge_options,
 592                      builtin_merge_usage, 0);
 593        free(argv);
 594}
 595
 596static int git_merge_config(const char *k, const char *v, void *cb)
 597{
 598        int status;
 599
 600        if (branch && starts_with(k, "branch.") &&
 601                starts_with(k + 7, branch) &&
 602                !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
 603                free(branch_mergeoptions);
 604                branch_mergeoptions = xstrdup(v);
 605                return 0;
 606        }
 607
 608        if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
 609                show_diffstat = git_config_bool(k, v);
 610        else if (!strcmp(k, "merge.verifysignatures"))
 611                verify_signatures = git_config_bool(k, v);
 612        else if (!strcmp(k, "pull.twohead"))
 613                return git_config_string(&pull_twohead, k, v);
 614        else if (!strcmp(k, "pull.octopus"))
 615                return git_config_string(&pull_octopus, k, v);
 616        else if (!strcmp(k, "commit.cleanup"))
 617                return git_config_string(&cleanup_arg, k, v);
 618        else if (!strcmp(k, "merge.renormalize"))
 619                option_renormalize = git_config_bool(k, v);
 620        else if (!strcmp(k, "merge.ff")) {
 621                int boolval = git_parse_maybe_bool(v);
 622                if (0 <= boolval) {
 623                        fast_forward = boolval ? FF_ALLOW : FF_NO;
 624                } else if (v && !strcmp(v, "only")) {
 625                        fast_forward = FF_ONLY;
 626                } /* do not barf on values from future versions of git */
 627                return 0;
 628        } else if (!strcmp(k, "merge.defaulttoupstream")) {
 629                default_to_upstream = git_config_bool(k, v);
 630                return 0;
 631        } else if (!strcmp(k, "commit.gpgsign")) {
 632                sign_commit = git_config_bool(k, v) ? "" : NULL;
 633                return 0;
 634        }
 635
 636        status = fmt_merge_msg_config(k, v, cb);
 637        if (status)
 638                return status;
 639        status = git_gpg_config(k, v, NULL);
 640        if (status)
 641                return status;
 642        return git_diff_ui_config(k, v, cb);
 643}
 644
 645static int read_tree_trivial(struct object_id *common, struct object_id *head,
 646                             struct object_id *one)
 647{
 648        int i, nr_trees = 0;
 649        struct tree *trees[MAX_UNPACK_TREES];
 650        struct tree_desc t[MAX_UNPACK_TREES];
 651        struct unpack_trees_options opts;
 652
 653        memset(&opts, 0, sizeof(opts));
 654        opts.head_idx = 2;
 655        opts.src_index = &the_index;
 656        opts.dst_index = &the_index;
 657        opts.update = 1;
 658        opts.verbose_update = 1;
 659        opts.trivial_merges_only = 1;
 660        opts.merge = 1;
 661        trees[nr_trees] = parse_tree_indirect(common);
 662        if (!trees[nr_trees++])
 663                return -1;
 664        trees[nr_trees] = parse_tree_indirect(head);
 665        if (!trees[nr_trees++])
 666                return -1;
 667        trees[nr_trees] = parse_tree_indirect(one);
 668        if (!trees[nr_trees++])
 669                return -1;
 670        opts.fn = threeway_merge;
 671        cache_tree_free(&active_cache_tree);
 672        for (i = 0; i < nr_trees; i++) {
 673                parse_tree(trees[i]);
 674                init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
 675        }
 676        if (unpack_trees(nr_trees, t, &opts))
 677                return -1;
 678        return 0;
 679}
 680
 681static void write_tree_trivial(struct object_id *oid)
 682{
 683        if (write_cache_as_tree(oid, 0, NULL))
 684                die(_("git write-tree failed to write a tree"));
 685}
 686
 687static int try_merge_strategy(const char *strategy, struct commit_list *common,
 688                              struct commit_list *remoteheads,
 689                              struct commit *head)
 690{
 691        struct lock_file lock = LOCK_INIT;
 692        const char *head_arg = "HEAD";
 693
 694        hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
 695        refresh_cache(REFRESH_QUIET);
 696        if (write_locked_index(&the_index, &lock,
 697                               COMMIT_LOCK | SKIP_IF_UNCHANGED))
 698                return error(_("Unable to write index."));
 699
 700        if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
 701                int clean, x;
 702                struct commit *result;
 703                struct commit_list *reversed = NULL;
 704                struct merge_options o;
 705                struct commit_list *j;
 706
 707                if (remoteheads->next) {
 708                        error(_("Not handling anything other than two heads merge."));
 709                        return 2;
 710                }
 711
 712                init_merge_options(&o, the_repository);
 713                if (!strcmp(strategy, "subtree"))
 714                        o.subtree_shift = "";
 715
 716                o.renormalize = option_renormalize;
 717                o.show_rename_progress =
 718                        show_progress == -1 ? isatty(2) : show_progress;
 719
 720                for (x = 0; x < xopts_nr; x++)
 721                        if (parse_merge_opt(&o, xopts[x]))
 722                                die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
 723
 724                o.branch1 = head_arg;
 725                o.branch2 = merge_remote_util(remoteheads->item)->name;
 726
 727                for (j = common; j; j = j->next)
 728                        commit_list_insert(j->item, &reversed);
 729
 730                hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
 731                clean = merge_recursive(&o, head,
 732                                remoteheads->item, reversed, &result);
 733                if (clean < 0)
 734                        exit(128);
 735                if (write_locked_index(&the_index, &lock,
 736                                       COMMIT_LOCK | SKIP_IF_UNCHANGED))
 737                        die(_("unable to write %s"), get_index_file());
 738                return clean ? 0 : 1;
 739        } else {
 740                return try_merge_command(the_repository,
 741                                         strategy, xopts_nr, xopts,
 742                                         common, head_arg, remoteheads);
 743        }
 744}
 745
 746static void count_diff_files(struct diff_queue_struct *q,
 747                             struct diff_options *opt, void *data)
 748{
 749        int *count = data;
 750
 751        (*count) += q->nr;
 752}
 753
 754static int count_unmerged_entries(void)
 755{
 756        int i, ret = 0;
 757
 758        for (i = 0; i < active_nr; i++)
 759                if (ce_stage(active_cache[i]))
 760                        ret++;
 761
 762        return ret;
 763}
 764
 765static void add_strategies(const char *string, unsigned attr)
 766{
 767        int i;
 768
 769        if (string) {
 770                struct string_list list = STRING_LIST_INIT_DUP;
 771                struct string_list_item *item;
 772                string_list_split(&list, string, ' ', -1);
 773                for_each_string_list_item(item, &list)
 774                        append_strategy(get_strategy(item->string));
 775                string_list_clear(&list, 0);
 776                return;
 777        }
 778        for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
 779                if (all_strategy[i].attr & attr)
 780                        append_strategy(&all_strategy[i]);
 781
 782}
 783
 784static void read_merge_msg(struct strbuf *msg)
 785{
 786        const char *filename = git_path_merge_msg(the_repository);
 787        strbuf_reset(msg);
 788        if (strbuf_read_file(msg, filename, 0) < 0)
 789                die_errno(_("Could not read from '%s'"), filename);
 790}
 791
 792static void write_merge_state(struct commit_list *);
 793static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
 794{
 795        if (err_msg)
 796                error("%s", err_msg);
 797        fprintf(stderr,
 798                _("Not committing merge; use 'git commit' to complete the merge.\n"));
 799        write_merge_state(remoteheads);
 800        exit(1);
 801}
 802
 803static const char merge_editor_comment[] =
 804N_("Please enter a commit message to explain why this merge is necessary,\n"
 805   "especially if it merges an updated upstream into a topic branch.\n"
 806   "\n");
 807
 808static const char scissors_editor_comment[] =
 809N_("An empty message aborts the commit.\n");
 810
 811static const char no_scissors_editor_comment[] =
 812N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
 813   "the commit.\n");
 814
 815static void write_merge_heads(struct commit_list *);
 816static void prepare_to_commit(struct commit_list *remoteheads)
 817{
 818        struct strbuf msg = STRBUF_INIT;
 819        const char *index_file = get_index_file();
 820
 821        if (!no_verify && run_commit_hook(0 < option_edit, index_file, "pre-merge-commit", NULL))
 822                abort_commit(remoteheads, NULL);
 823        /*
 824         * Re-read the index as pre-merge-commit hook could have updated it,
 825         * and write it out as a tree.  We must do this before we invoke
 826         * the editor and after we invoke run_status above.
 827         */
 828        if (find_hook("pre-merge-commit"))
 829                discard_cache();
 830        read_cache_from(index_file);
 831        strbuf_addbuf(&msg, &merge_msg);
 832        if (squash)
 833                BUG("the control must not reach here under --squash");
 834        if (0 < option_edit) {
 835                strbuf_addch(&msg, '\n');
 836                if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
 837                        wt_status_append_cut_line(&msg);
 838                        strbuf_commented_addf(&msg, "\n");
 839                }
 840                strbuf_commented_addf(&msg, _(merge_editor_comment));
 841                strbuf_commented_addf(&msg, _(cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS ?
 842                        scissors_editor_comment :
 843                        no_scissors_editor_comment), comment_line_char);
 844        }
 845        if (signoff)
 846                append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
 847        write_merge_heads(remoteheads);
 848        write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
 849        if (run_commit_hook(0 < option_edit, get_index_file(), "prepare-commit-msg",
 850                            git_path_merge_msg(the_repository), "merge", NULL))
 851                abort_commit(remoteheads, NULL);
 852        if (0 < option_edit) {
 853                if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
 854                        abort_commit(remoteheads, NULL);
 855        }
 856
 857        if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
 858                                          "commit-msg",
 859                                          git_path_merge_msg(the_repository), NULL))
 860                abort_commit(remoteheads, NULL);
 861
 862        read_merge_msg(&msg);
 863        cleanup_message(&msg, cleanup_mode, 0);
 864        if (!msg.len)
 865                abort_commit(remoteheads, _("Empty commit message."));
 866        strbuf_release(&merge_msg);
 867        strbuf_addbuf(&merge_msg, &msg);
 868        strbuf_release(&msg);
 869}
 870
 871static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
 872{
 873        struct object_id result_tree, result_commit;
 874        struct commit_list *parents, **pptr = &parents;
 875        struct lock_file lock = LOCK_INIT;
 876
 877        hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
 878        refresh_cache(REFRESH_QUIET);
 879        if (write_locked_index(&the_index, &lock,
 880                               COMMIT_LOCK | SKIP_IF_UNCHANGED))
 881                return error(_("Unable to write index."));
 882
 883        write_tree_trivial(&result_tree);
 884        printf(_("Wonderful.\n"));
 885        pptr = commit_list_append(head, pptr);
 886        pptr = commit_list_append(remoteheads->item, pptr);
 887        prepare_to_commit(remoteheads);
 888        if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
 889                        &result_commit, NULL, sign_commit))
 890                die(_("failed to write commit object"));
 891        finish(head, remoteheads, &result_commit, "In-index merge");
 892        remove_merge_branch_state(the_repository);
 893        return 0;
 894}
 895
 896static int finish_automerge(struct commit *head,
 897                            int head_subsumed,
 898                            struct commit_list *common,
 899                            struct commit_list *remoteheads,
 900                            struct object_id *result_tree,
 901                            const char *wt_strategy)
 902{
 903        struct commit_list *parents = NULL;
 904        struct strbuf buf = STRBUF_INIT;
 905        struct object_id result_commit;
 906
 907        write_tree_trivial(result_tree);
 908        free_commit_list(common);
 909        parents = remoteheads;
 910        if (!head_subsumed || fast_forward == FF_NO)
 911                commit_list_insert(head, &parents);
 912        prepare_to_commit(remoteheads);
 913        if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
 914                        &result_commit, NULL, sign_commit))
 915                die(_("failed to write commit object"));
 916        strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
 917        finish(head, remoteheads, &result_commit, buf.buf);
 918        strbuf_release(&buf);
 919        remove_merge_branch_state(the_repository);
 920        return 0;
 921}
 922
 923static int suggest_conflicts(void)
 924{
 925        const char *filename;
 926        FILE *fp;
 927        struct strbuf msgbuf = STRBUF_INIT;
 928
 929        filename = git_path_merge_msg(the_repository);
 930        fp = xfopen(filename, "a");
 931
 932        /*
 933         * We can't use cleanup_mode because if we're not using the editor,
 934         * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
 935         * though the message is meant to be processed later by git-commit.
 936         * Thus, we will get the cleanup mode which is returned when we _are_
 937         * using an editor.
 938         */
 939        append_conflicts_hint(&the_index, &msgbuf,
 940                              get_cleanup_mode(cleanup_arg, 1));
 941        fputs(msgbuf.buf, fp);
 942        strbuf_release(&msgbuf);
 943        fclose(fp);
 944        repo_rerere(the_repository, allow_rerere_auto);
 945        printf(_("Automatic merge failed; "
 946                        "fix conflicts and then commit the result.\n"));
 947        return 1;
 948}
 949
 950static int evaluate_result(void)
 951{
 952        int cnt = 0;
 953        struct rev_info rev;
 954
 955        /* Check how many files differ. */
 956        repo_init_revisions(the_repository, &rev, "");
 957        setup_revisions(0, NULL, &rev, NULL);
 958        rev.diffopt.output_format |=
 959                DIFF_FORMAT_CALLBACK;
 960        rev.diffopt.format_callback = count_diff_files;
 961        rev.diffopt.format_callback_data = &cnt;
 962        run_diff_files(&rev, 0);
 963
 964        /*
 965         * Check how many unmerged entries are
 966         * there.
 967         */
 968        cnt += count_unmerged_entries();
 969
 970        return cnt;
 971}
 972
 973/*
 974 * Pretend as if the user told us to merge with the remote-tracking
 975 * branch we have for the upstream of the current branch
 976 */
 977static int setup_with_upstream(const char ***argv)
 978{
 979        struct branch *branch = branch_get(NULL);
 980        int i;
 981        const char **args;
 982
 983        if (!branch)
 984                die(_("No current branch."));
 985        if (!branch->remote_name)
 986                die(_("No remote for the current branch."));
 987        if (!branch->merge_nr)
 988                die(_("No default upstream defined for the current branch."));
 989
 990        args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
 991        for (i = 0; i < branch->merge_nr; i++) {
 992                if (!branch->merge[i]->dst)
 993                        die(_("No remote-tracking branch for %s from %s"),
 994                            branch->merge[i]->src, branch->remote_name);
 995                args[i] = branch->merge[i]->dst;
 996        }
 997        args[i] = NULL;
 998        *argv = args;
 999        return i;
1000}
1001
1002static void write_merge_heads(struct commit_list *remoteheads)
1003{
1004        struct commit_list *j;
1005        struct strbuf buf = STRBUF_INIT;
1006
1007        for (j = remoteheads; j; j = j->next) {
1008                struct object_id *oid;
1009                struct commit *c = j->item;
1010                struct merge_remote_desc *desc;
1011
1012                desc = merge_remote_util(c);
1013                if (desc && desc->obj) {
1014                        oid = &desc->obj->oid;
1015                } else {
1016                        oid = &c->object.oid;
1017                }
1018                strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1019        }
1020        write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1021
1022        strbuf_reset(&buf);
1023        if (fast_forward == FF_NO)
1024                strbuf_addstr(&buf, "no-ff");
1025        write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1026        strbuf_release(&buf);
1027}
1028
1029static void write_merge_state(struct commit_list *remoteheads)
1030{
1031        write_merge_heads(remoteheads);
1032        strbuf_addch(&merge_msg, '\n');
1033        write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1034                       merge_msg.len);
1035}
1036
1037static int default_edit_option(void)
1038{
1039        static const char name[] = "GIT_MERGE_AUTOEDIT";
1040        const char *e = getenv(name);
1041        struct stat st_stdin, st_stdout;
1042
1043        if (have_message)
1044                /* an explicit -m msg without --[no-]edit */
1045                return 0;
1046
1047        if (e) {
1048                int v = git_parse_maybe_bool(e);
1049                if (v < 0)
1050                        die(_("Bad value '%s' in environment '%s'"), e, name);
1051                return v;
1052        }
1053
1054        /* Use editor if stdin and stdout are the same and is a tty */
1055        return (!fstat(0, &st_stdin) &&
1056                !fstat(1, &st_stdout) &&
1057                isatty(0) && isatty(1) &&
1058                st_stdin.st_dev == st_stdout.st_dev &&
1059                st_stdin.st_ino == st_stdout.st_ino &&
1060                st_stdin.st_mode == st_stdout.st_mode);
1061}
1062
1063static struct commit_list *reduce_parents(struct commit *head_commit,
1064                                          int *head_subsumed,
1065                                          struct commit_list *remoteheads)
1066{
1067        struct commit_list *parents, **remotes;
1068
1069        /*
1070         * Is the current HEAD reachable from another commit being
1071         * merged?  If so we do not want to record it as a parent of
1072         * the resulting merge, unless --no-ff is given.  We will flip
1073         * this variable to 0 when we find HEAD among the independent
1074         * tips being merged.
1075         */
1076        *head_subsumed = 1;
1077
1078        /* Find what parents to record by checking independent ones. */
1079        parents = reduce_heads(remoteheads);
1080        free_commit_list(remoteheads);
1081
1082        remoteheads = NULL;
1083        remotes = &remoteheads;
1084        while (parents) {
1085                struct commit *commit = pop_commit(&parents);
1086                if (commit == head_commit)
1087                        *head_subsumed = 0;
1088                else
1089                        remotes = &commit_list_insert(commit, remotes)->next;
1090        }
1091        return remoteheads;
1092}
1093
1094static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1095{
1096        struct fmt_merge_msg_opts opts;
1097
1098        memset(&opts, 0, sizeof(opts));
1099        opts.add_title = !have_message;
1100        opts.shortlog_len = shortlog_len;
1101        opts.credit_people = (0 < option_edit);
1102
1103        fmt_merge_msg(merge_names, merge_msg, &opts);
1104        if (merge_msg->len)
1105                strbuf_setlen(merge_msg, merge_msg->len - 1);
1106}
1107
1108static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1109{
1110        const char *filename;
1111        int fd, pos, npos;
1112        struct strbuf fetch_head_file = STRBUF_INIT;
1113        const unsigned hexsz = the_hash_algo->hexsz;
1114
1115        if (!merge_names)
1116                merge_names = &fetch_head_file;
1117
1118        filename = git_path_fetch_head(the_repository);
1119        fd = open(filename, O_RDONLY);
1120        if (fd < 0)
1121                die_errno(_("could not open '%s' for reading"), filename);
1122
1123        if (strbuf_read(merge_names, fd, 0) < 0)
1124                die_errno(_("could not read '%s'"), filename);
1125        if (close(fd) < 0)
1126                die_errno(_("could not close '%s'"), filename);
1127
1128        for (pos = 0; pos < merge_names->len; pos = npos) {
1129                struct object_id oid;
1130                char *ptr;
1131                struct commit *commit;
1132
1133                ptr = strchr(merge_names->buf + pos, '\n');
1134                if (ptr)
1135                        npos = ptr - merge_names->buf + 1;
1136                else
1137                        npos = merge_names->len;
1138
1139                if (npos - pos < hexsz + 2 ||
1140                    get_oid_hex(merge_names->buf + pos, &oid))
1141                        commit = NULL; /* bad */
1142                else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1143                        continue; /* not-for-merge */
1144                else {
1145                        char saved = merge_names->buf[pos + hexsz];
1146                        merge_names->buf[pos + hexsz] = '\0';
1147                        commit = get_merge_parent(merge_names->buf + pos);
1148                        merge_names->buf[pos + hexsz] = saved;
1149                }
1150                if (!commit) {
1151                        if (ptr)
1152                                *ptr = '\0';
1153                        die(_("not something we can merge in %s: %s"),
1154                            filename, merge_names->buf + pos);
1155                }
1156                remotes = &commit_list_insert(commit, remotes)->next;
1157        }
1158
1159        if (merge_names == &fetch_head_file)
1160                strbuf_release(&fetch_head_file);
1161}
1162
1163static struct commit_list *collect_parents(struct commit *head_commit,
1164                                           int *head_subsumed,
1165                                           int argc, const char **argv,
1166                                           struct strbuf *merge_msg)
1167{
1168        int i;
1169        struct commit_list *remoteheads = NULL;
1170        struct commit_list **remotes = &remoteheads;
1171        struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1172
1173        if (merge_msg && (!have_message || shortlog_len))
1174                autogen = &merge_names;
1175
1176        if (head_commit)
1177                remotes = &commit_list_insert(head_commit, remotes)->next;
1178
1179        if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1180                handle_fetch_head(remotes, autogen);
1181                remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1182        } else {
1183                for (i = 0; i < argc; i++) {
1184                        struct commit *commit = get_merge_parent(argv[i]);
1185                        if (!commit)
1186                                help_unknown_ref(argv[i], "merge",
1187                                                 _("not something we can merge"));
1188                        remotes = &commit_list_insert(commit, remotes)->next;
1189                }
1190                remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1191                if (autogen) {
1192                        struct commit_list *p;
1193                        for (p = remoteheads; p; p = p->next)
1194                                merge_name(merge_remote_util(p->item)->name, autogen);
1195                }
1196        }
1197
1198        if (autogen) {
1199                prepare_merge_message(autogen, merge_msg);
1200                strbuf_release(autogen);
1201        }
1202
1203        return remoteheads;
1204}
1205
1206static int merging_a_throwaway_tag(struct commit *commit)
1207{
1208        char *tag_ref;
1209        struct object_id oid;
1210        int is_throwaway_tag = 0;
1211
1212        /* Are we merging a tag? */
1213        if (!merge_remote_util(commit) ||
1214            !merge_remote_util(commit)->obj ||
1215            merge_remote_util(commit)->obj->type != OBJ_TAG)
1216                return is_throwaway_tag;
1217
1218        /*
1219         * Now we know we are merging a tag object.  Are we downstream
1220         * and following the tags from upstream?  If so, we must have
1221         * the tag object pointed at by "refs/tags/$T" where $T is the
1222         * tagname recorded in the tag object.  We want to allow such
1223         * a "just to catch up" merge to fast-forward.
1224         *
1225         * Otherwise, we are playing an integrator's role, making a
1226         * merge with a throw-away tag from a contributor with
1227         * something like "git pull $contributor $signed_tag".
1228         * We want to forbid such a merge from fast-forwarding
1229         * by default; otherwise we would not keep the signature
1230         * anywhere.
1231         */
1232        tag_ref = xstrfmt("refs/tags/%s",
1233                          ((struct tag *)merge_remote_util(commit)->obj)->tag);
1234        if (!read_ref(tag_ref, &oid) &&
1235            oideq(&oid, &merge_remote_util(commit)->obj->oid))
1236                is_throwaway_tag = 0;
1237        else
1238                is_throwaway_tag = 1;
1239        free(tag_ref);
1240        return is_throwaway_tag;
1241}
1242
1243int cmd_merge(int argc, const char **argv, const char *prefix)
1244{
1245        struct object_id result_tree, stash, head_oid;
1246        struct commit *head_commit;
1247        struct strbuf buf = STRBUF_INIT;
1248        int i, ret = 0, head_subsumed;
1249        int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1250        struct commit_list *common = NULL;
1251        const char *best_strategy = NULL, *wt_strategy = NULL;
1252        struct commit_list *remoteheads, *p;
1253        void *branch_to_free;
1254        int orig_argc = argc;
1255
1256        if (argc == 2 && !strcmp(argv[1], "-h"))
1257                usage_with_options(builtin_merge_usage, builtin_merge_options);
1258
1259        /*
1260         * Check if we are _not_ on a detached HEAD, i.e. if there is a
1261         * current branch.
1262         */
1263        branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1264        if (branch)
1265                skip_prefix(branch, "refs/heads/", &branch);
1266
1267        init_diff_ui_defaults();
1268        git_config(git_merge_config, NULL);
1269
1270        if (!branch || is_null_oid(&head_oid))
1271                head_commit = NULL;
1272        else
1273                head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1274
1275        if (branch_mergeoptions)
1276                parse_branch_merge_options(branch_mergeoptions);
1277        argc = parse_options(argc, argv, prefix, builtin_merge_options,
1278                        builtin_merge_usage, 0);
1279        if (shortlog_len < 0)
1280                shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1281
1282        if (verbosity < 0 && show_progress == -1)
1283                show_progress = 0;
1284
1285        if (abort_current_merge) {
1286                int nargc = 2;
1287                const char *nargv[] = {"reset", "--merge", NULL};
1288
1289                if (orig_argc != 2)
1290                        usage_msg_opt(_("--abort expects no arguments"),
1291                              builtin_merge_usage, builtin_merge_options);
1292
1293                if (!file_exists(git_path_merge_head(the_repository)))
1294                        die(_("There is no merge to abort (MERGE_HEAD missing)."));
1295
1296                /* Invoke 'git reset --merge' */
1297                ret = cmd_reset(nargc, nargv, prefix);
1298                goto done;
1299        }
1300
1301        if (quit_current_merge) {
1302                if (orig_argc != 2)
1303                        usage_msg_opt(_("--quit expects no arguments"),
1304                                      builtin_merge_usage,
1305                                      builtin_merge_options);
1306
1307                remove_merge_branch_state(the_repository);
1308                goto done;
1309        }
1310
1311        if (continue_current_merge) {
1312                int nargc = 1;
1313                const char *nargv[] = {"commit", NULL};
1314
1315                if (orig_argc != 2)
1316                        usage_msg_opt(_("--continue expects no arguments"),
1317                              builtin_merge_usage, builtin_merge_options);
1318
1319                if (!file_exists(git_path_merge_head(the_repository)))
1320                        die(_("There is no merge in progress (MERGE_HEAD missing)."));
1321
1322                /* Invoke 'git commit' */
1323                ret = cmd_commit(nargc, nargv, prefix);
1324                goto done;
1325        }
1326
1327        if (read_cache_unmerged())
1328                die_resolve_conflict("merge");
1329
1330        if (file_exists(git_path_merge_head(the_repository))) {
1331                /*
1332                 * There is no unmerged entry, don't advise 'git
1333                 * add/rm <file>', just 'git commit'.
1334                 */
1335                if (advice_resolve_conflict)
1336                        die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1337                                  "Please, commit your changes before you merge."));
1338                else
1339                        die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1340        }
1341        if (file_exists(git_path_cherry_pick_head(the_repository))) {
1342                if (advice_resolve_conflict)
1343                        die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1344                            "Please, commit your changes before you merge."));
1345                else
1346                        die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1347        }
1348        resolve_undo_clear();
1349
1350        if (option_edit < 0)
1351                option_edit = default_edit_option();
1352
1353        cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1354
1355        if (verbosity < 0)
1356                show_diffstat = 0;
1357
1358        if (squash) {
1359                if (fast_forward == FF_NO)
1360                        die(_("You cannot combine --squash with --no-ff."));
1361                if (option_commit > 0)
1362                        die(_("You cannot combine --squash with --commit."));
1363                /*
1364                 * squash can now silently disable option_commit - this is not
1365                 * a problem as it is only overriding the default, not a user
1366                 * supplied option.
1367                 */
1368                option_commit = 0;
1369        }
1370
1371        if (option_commit < 0)
1372                option_commit = 1;
1373
1374        if (!argc) {
1375                if (default_to_upstream)
1376                        argc = setup_with_upstream(&argv);
1377                else
1378                        die(_("No commit specified and merge.defaultToUpstream not set."));
1379        } else if (argc == 1 && !strcmp(argv[0], "-")) {
1380                argv[0] = "@{-1}";
1381        }
1382
1383        if (!argc)
1384                usage_with_options(builtin_merge_usage,
1385                        builtin_merge_options);
1386
1387        if (!head_commit) {
1388                /*
1389                 * If the merged head is a valid one there is no reason
1390                 * to forbid "git merge" into a branch yet to be born.
1391                 * We do the same for "git pull".
1392                 */
1393                struct object_id *remote_head_oid;
1394                if (squash)
1395                        die(_("Squash commit into empty head not supported yet"));
1396                if (fast_forward == FF_NO)
1397                        die(_("Non-fast-forward commit does not make sense into "
1398                            "an empty head"));
1399                remoteheads = collect_parents(head_commit, &head_subsumed,
1400                                              argc, argv, NULL);
1401                if (!remoteheads)
1402                        die(_("%s - not something we can merge"), argv[0]);
1403                if (remoteheads->next)
1404                        die(_("Can merge only exactly one commit into empty head"));
1405
1406                if (verify_signatures)
1407                        verify_merge_signature(remoteheads->item, verbosity);
1408
1409                remote_head_oid = &remoteheads->item->object.oid;
1410                read_empty(remote_head_oid, 0);
1411                update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1412                           UPDATE_REFS_DIE_ON_ERR);
1413                goto done;
1414        }
1415
1416        /*
1417         * All the rest are the commits being merged; prepare
1418         * the standard merge summary message to be appended
1419         * to the given message.
1420         */
1421        remoteheads = collect_parents(head_commit, &head_subsumed,
1422                                      argc, argv, &merge_msg);
1423
1424        if (!head_commit || !argc)
1425                usage_with_options(builtin_merge_usage,
1426                        builtin_merge_options);
1427
1428        if (verify_signatures) {
1429                for (p = remoteheads; p; p = p->next) {
1430                        verify_merge_signature(p->item, verbosity);
1431                }
1432        }
1433
1434        strbuf_addstr(&buf, "merge");
1435        for (p = remoteheads; p; p = p->next)
1436                strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1437        setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1438        strbuf_reset(&buf);
1439
1440        for (p = remoteheads; p; p = p->next) {
1441                struct commit *commit = p->item;
1442                strbuf_addf(&buf, "GITHEAD_%s",
1443                            oid_to_hex(&commit->object.oid));
1444                setenv(buf.buf, merge_remote_util(commit)->name, 1);
1445                strbuf_reset(&buf);
1446                if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1447                        fast_forward = FF_NO;
1448        }
1449
1450        if (!use_strategies) {
1451                if (!remoteheads)
1452                        ; /* already up-to-date */
1453                else if (!remoteheads->next)
1454                        add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1455                else
1456                        add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1457        }
1458
1459        for (i = 0; i < use_strategies_nr; i++) {
1460                if (use_strategies[i]->attr & NO_FAST_FORWARD)
1461                        fast_forward = FF_NO;
1462                if (use_strategies[i]->attr & NO_TRIVIAL)
1463                        allow_trivial = 0;
1464        }
1465
1466        if (!remoteheads)
1467                ; /* already up-to-date */
1468        else if (!remoteheads->next)
1469                common = get_merge_bases(head_commit, remoteheads->item);
1470        else {
1471                struct commit_list *list = remoteheads;
1472                commit_list_insert(head_commit, &list);
1473                common = get_octopus_merge_bases(list);
1474                free(list);
1475        }
1476
1477        update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1478                   &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1479
1480        if (remoteheads && !common) {
1481                /* No common ancestors found. */
1482                if (!allow_unrelated_histories)
1483                        die(_("refusing to merge unrelated histories"));
1484                /* otherwise, we need a real merge. */
1485        } else if (!remoteheads ||
1486                 (!remoteheads->next && !common->next &&
1487                  common->item == remoteheads->item)) {
1488                /*
1489                 * If head can reach all the merge then we are up to date.
1490                 * but first the most common case of merging one remote.
1491                 */
1492                finish_up_to_date(_("Already up to date."));
1493                goto done;
1494        } else if (fast_forward != FF_NO && !remoteheads->next &&
1495                        !common->next &&
1496                        oideq(&common->item->object.oid, &head_commit->object.oid)) {
1497                /* Again the most common case of merging one remote. */
1498                struct strbuf msg = STRBUF_INIT;
1499                struct commit *commit;
1500
1501                if (verbosity >= 0) {
1502                        printf(_("Updating %s..%s\n"),
1503                               find_unique_abbrev(&head_commit->object.oid,
1504                                                  DEFAULT_ABBREV),
1505                               find_unique_abbrev(&remoteheads->item->object.oid,
1506                                                  DEFAULT_ABBREV));
1507                }
1508                strbuf_addstr(&msg, "Fast-forward");
1509                if (have_message)
1510                        strbuf_addstr(&msg,
1511                                " (no commit created; -m option ignored)");
1512                commit = remoteheads->item;
1513                if (!commit) {
1514                        ret = 1;
1515                        goto done;
1516                }
1517
1518                if (checkout_fast_forward(the_repository,
1519                                          &head_commit->object.oid,
1520                                          &commit->object.oid,
1521                                          overwrite_ignore)) {
1522                        ret = 1;
1523                        goto done;
1524                }
1525
1526                finish(head_commit, remoteheads, &commit->object.oid, msg.buf);
1527                remove_merge_branch_state(the_repository);
1528                goto done;
1529        } else if (!remoteheads->next && common->next)
1530                ;
1531                /*
1532                 * We are not doing octopus and not fast-forward.  Need
1533                 * a real merge.
1534                 */
1535        else if (!remoteheads->next && !common->next && option_commit) {
1536                /*
1537                 * We are not doing octopus, not fast-forward, and have
1538                 * only one common.
1539                 */
1540                refresh_cache(REFRESH_QUIET);
1541                if (allow_trivial && fast_forward != FF_ONLY) {
1542                        /* See if it is really trivial. */
1543                        git_committer_info(IDENT_STRICT);
1544                        printf(_("Trying really trivial in-index merge...\n"));
1545                        if (!read_tree_trivial(&common->item->object.oid,
1546                                               &head_commit->object.oid,
1547                                               &remoteheads->item->object.oid)) {
1548                                ret = merge_trivial(head_commit, remoteheads);
1549                                goto done;
1550                        }
1551                        printf(_("Nope.\n"));
1552                }
1553        } else {
1554                /*
1555                 * An octopus.  If we can reach all the remote we are up
1556                 * to date.
1557                 */
1558                int up_to_date = 1;
1559                struct commit_list *j;
1560
1561                for (j = remoteheads; j; j = j->next) {
1562                        struct commit_list *common_one;
1563
1564                        /*
1565                         * Here we *have* to calculate the individual
1566                         * merge_bases again, otherwise "git merge HEAD^
1567                         * HEAD^^" would be missed.
1568                         */
1569                        common_one = get_merge_bases(head_commit, j->item);
1570                        if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1571                                up_to_date = 0;
1572                                break;
1573                        }
1574                }
1575                if (up_to_date) {
1576                        finish_up_to_date(_("Already up to date. Yeeah!"));
1577                        goto done;
1578                }
1579        }
1580
1581        if (fast_forward == FF_ONLY)
1582                die(_("Not possible to fast-forward, aborting."));
1583
1584        /* We are going to make a new commit. */
1585        git_committer_info(IDENT_STRICT);
1586
1587        /*
1588         * At this point, we need a real merge.  No matter what strategy
1589         * we use, it would operate on the index, possibly affecting the
1590         * working tree, and when resolved cleanly, have the desired
1591         * tree in the index -- this means that the index must be in
1592         * sync with the head commit.  The strategies are responsible
1593         * to ensure this.
1594         */
1595        if (use_strategies_nr == 1 ||
1596            /*
1597             * Stash away the local changes so that we can try more than one.
1598             */
1599            save_state(&stash))
1600                oidclr(&stash);
1601
1602        for (i = 0; !merge_was_ok && i < use_strategies_nr; i++) {
1603                int ret, cnt;
1604                if (i) {
1605                        printf(_("Rewinding the tree to pristine...\n"));
1606                        restore_state(&head_commit->object.oid, &stash);
1607                }
1608                if (use_strategies_nr != 1)
1609                        printf(_("Trying merge strategy %s...\n"),
1610                                use_strategies[i]->name);
1611                /*
1612                 * Remember which strategy left the state in the working
1613                 * tree.
1614                 */
1615                wt_strategy = use_strategies[i]->name;
1616
1617                ret = try_merge_strategy(use_strategies[i]->name,
1618                                         common, remoteheads,
1619                                         head_commit);
1620                /*
1621                 * The backend exits with 1 when conflicts are
1622                 * left to be resolved, with 2 when it does not
1623                 * handle the given merge at all.
1624                 */
1625                if (ret < 2) {
1626                        if (!ret) {
1627                                if (option_commit) {
1628                                        /* Automerge succeeded. */
1629                                        automerge_was_ok = 1;
1630                                        break;
1631                                }
1632                                merge_was_ok = 1;
1633                        }
1634                        cnt = evaluate_result();
1635                        if (best_cnt <= 0 || cnt <= best_cnt) {
1636                                best_strategy = use_strategies[i]->name;
1637                                best_cnt = cnt;
1638                        }
1639                }
1640        }
1641
1642        /*
1643         * If we have a resulting tree, that means the strategy module
1644         * auto resolved the merge cleanly.
1645         */
1646        if (automerge_was_ok) {
1647                ret = finish_automerge(head_commit, head_subsumed,
1648                                       common, remoteheads,
1649                                       &result_tree, wt_strategy);
1650                goto done;
1651        }
1652
1653        /*
1654         * Pick the result from the best strategy and have the user fix
1655         * it up.
1656         */
1657        if (!best_strategy) {
1658                restore_state(&head_commit->object.oid, &stash);
1659                if (use_strategies_nr > 1)
1660                        fprintf(stderr,
1661                                _("No merge strategy handled the merge.\n"));
1662                else
1663                        fprintf(stderr, _("Merge with strategy %s failed.\n"),
1664                                use_strategies[0]->name);
1665                ret = 2;
1666                goto done;
1667        } else if (best_strategy == wt_strategy)
1668                ; /* We already have its result in the working tree. */
1669        else {
1670                printf(_("Rewinding the tree to pristine...\n"));
1671                restore_state(&head_commit->object.oid, &stash);
1672                printf(_("Using the %s to prepare resolving by hand.\n"),
1673                        best_strategy);
1674                try_merge_strategy(best_strategy, common, remoteheads,
1675                                   head_commit);
1676        }
1677
1678        if (squash)
1679                finish(head_commit, remoteheads, NULL, NULL);
1680        else
1681                write_merge_state(remoteheads);
1682
1683        if (merge_was_ok)
1684                fprintf(stderr, _("Automatic merge went well; "
1685                        "stopped before committing as requested\n"));
1686        else
1687                ret = suggest_conflicts();
1688
1689done:
1690        free(branch_to_free);
1691        return ret;
1692}