completion: improve handling of -c/-C and -b/-B in switch/checkout
[alt-git.git] / builtin / merge.c
blobdf83ba2a807a88fa5904a2acbe64a7caa7188224
1 /*
2 * Builtin "git merge"
4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
7 */
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"
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)
49 struct strategy {
50 const char *name;
51 unsigned attr;
54 static const char * const builtin_merge_usage[] = {
55 N_("git merge [<options>] [<commit>...]"),
56 N_("git merge --abort"),
57 N_("git merge --continue"),
58 NULL
61 static int show_diffstat = 1, shortlog_len = -1, squash;
62 static int option_commit = -1;
63 static int option_edit = -1;
64 static int allow_trivial = 1, have_message, verify_signatures;
65 static int check_trust_level = 1;
66 static int overwrite_ignore = 1;
67 static struct strbuf merge_msg = STRBUF_INIT;
68 static struct strategy **use_strategies;
69 static size_t use_strategies_nr, use_strategies_alloc;
70 static const char **xopts;
71 static size_t xopts_nr, xopts_alloc;
72 static const char *branch;
73 static char *branch_mergeoptions;
74 static int option_renormalize;
75 static int verbosity;
76 static int allow_rerere_auto;
77 static int abort_current_merge;
78 static int quit_current_merge;
79 static int continue_current_merge;
80 static int allow_unrelated_histories;
81 static int show_progress = -1;
82 static int default_to_upstream = 1;
83 static int signoff;
84 static const char *sign_commit;
85 static int no_verify;
87 static struct strategy all_strategy[] = {
88 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
89 { "octopus", DEFAULT_OCTOPUS },
90 { "resolve", 0 },
91 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
92 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
95 static const char *pull_twohead, *pull_octopus;
97 enum ff_type {
98 FF_NO,
99 FF_ALLOW,
100 FF_ONLY
103 static enum ff_type fast_forward = FF_ALLOW;
105 static const char *cleanup_arg;
106 static enum commit_msg_cleanup_mode cleanup_mode;
108 static int option_parse_message(const struct option *opt,
109 const char *arg, int unset)
111 struct strbuf *buf = opt->value;
113 if (unset)
114 strbuf_setlen(buf, 0);
115 else if (arg) {
116 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
117 have_message = 1;
118 } else
119 return error(_("switch `m' requires a value"));
120 return 0;
123 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
124 const struct option *opt,
125 const char *arg_not_used,
126 int unset)
128 struct strbuf *buf = opt->value;
129 const char *arg;
131 BUG_ON_OPT_ARG(arg_not_used);
132 if (unset)
133 BUG("-F cannot be negated");
135 if (ctx->opt) {
136 arg = ctx->opt;
137 ctx->opt = NULL;
138 } else if (ctx->argc > 1) {
139 ctx->argc--;
140 arg = *++ctx->argv;
141 } else
142 return error(_("option `%s' requires a value"), opt->long_name);
144 if (buf->len)
145 strbuf_addch(buf, '\n');
146 if (ctx->prefix && !is_absolute_path(arg))
147 arg = prefix_filename(ctx->prefix, arg);
148 if (strbuf_read_file(buf, arg, 0) < 0)
149 return error(_("could not read file '%s'"), arg);
150 have_message = 1;
152 return 0;
155 static struct strategy *get_strategy(const char *name)
157 int i;
158 struct strategy *ret;
159 static struct cmdnames main_cmds, other_cmds;
160 static int loaded;
162 if (!name)
163 return NULL;
165 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
166 if (!strcmp(name, all_strategy[i].name))
167 return &all_strategy[i];
169 if (!loaded) {
170 struct cmdnames not_strategies;
171 loaded = 1;
173 memset(&not_strategies, 0, sizeof(struct cmdnames));
174 load_command_list("git-merge-", &main_cmds, &other_cmds);
175 for (i = 0; i < main_cmds.cnt; i++) {
176 int j, found = 0;
177 struct cmdname *ent = main_cmds.names[i];
178 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
179 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
180 && !all_strategy[j].name[ent->len])
181 found = 1;
182 if (!found)
183 add_cmdname(&not_strategies, ent->name, ent->len);
185 exclude_cmds(&main_cmds, &not_strategies);
187 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
188 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
189 fprintf(stderr, _("Available strategies are:"));
190 for (i = 0; i < main_cmds.cnt; i++)
191 fprintf(stderr, " %s", main_cmds.names[i]->name);
192 fprintf(stderr, ".\n");
193 if (other_cmds.cnt) {
194 fprintf(stderr, _("Available custom strategies are:"));
195 for (i = 0; i < other_cmds.cnt; i++)
196 fprintf(stderr, " %s", other_cmds.names[i]->name);
197 fprintf(stderr, ".\n");
199 exit(1);
202 ret = xcalloc(1, sizeof(struct strategy));
203 ret->name = xstrdup(name);
204 ret->attr = NO_TRIVIAL;
205 return ret;
208 static void append_strategy(struct strategy *s)
210 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
211 use_strategies[use_strategies_nr++] = s;
214 static int option_parse_strategy(const struct option *opt,
215 const char *name, int unset)
217 if (unset)
218 return 0;
220 append_strategy(get_strategy(name));
221 return 0;
224 static int option_parse_x(const struct option *opt,
225 const char *arg, int unset)
227 if (unset)
228 return 0;
230 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
231 xopts[xopts_nr++] = xstrdup(arg);
232 return 0;
235 static int option_parse_n(const struct option *opt,
236 const char *arg, int unset)
238 BUG_ON_OPT_ARG(arg);
239 show_diffstat = unset;
240 return 0;
243 static struct option builtin_merge_options[] = {
244 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
245 N_("do not show a diffstat at the end of the merge"),
246 PARSE_OPT_NOARG, option_parse_n },
247 OPT_BOOL(0, "stat", &show_diffstat,
248 N_("show a diffstat at the end of the merge")),
249 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
250 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
251 N_("add (at most <n>) entries from shortlog to merge commit message"),
252 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
253 OPT_BOOL(0, "squash", &squash,
254 N_("create a single commit instead of doing a merge")),
255 OPT_BOOL(0, "commit", &option_commit,
256 N_("perform a commit if the merge succeeds (default)")),
257 OPT_BOOL('e', "edit", &option_edit,
258 N_("edit message before committing")),
259 OPT_CLEANUP(&cleanup_arg),
260 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
261 OPT_SET_INT_F(0, "ff-only", &fast_forward,
262 N_("abort if fast-forward is not possible"),
263 FF_ONLY, PARSE_OPT_NONEG),
264 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
265 OPT_BOOL(0, "verify-signatures", &verify_signatures,
266 N_("verify that the named commit has a valid GPG signature")),
267 OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
268 N_("merge strategy to use"), option_parse_strategy),
269 OPT_CALLBACK('X', "strategy-option", &xopts, N_("option=value"),
270 N_("option for selected merge strategy"), option_parse_x),
271 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
272 N_("merge commit message (for a non-fast-forward merge)"),
273 option_parse_message),
274 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
275 N_("read message from file"), PARSE_OPT_NONEG,
276 NULL, 0, option_read_message },
277 OPT__VERBOSITY(&verbosity),
278 OPT_BOOL(0, "abort", &abort_current_merge,
279 N_("abort the current in-progress merge")),
280 OPT_BOOL(0, "quit", &quit_current_merge,
281 N_("--abort but leave index and working tree alone")),
282 OPT_BOOL(0, "continue", &continue_current_merge,
283 N_("continue the current in-progress merge")),
284 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
285 N_("allow merging unrelated histories")),
286 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
287 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
288 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
289 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
290 OPT_BOOL(0, "signoff", &signoff, N_("add Signed-off-by:")),
291 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
292 OPT_END()
295 static int save_state(struct object_id *stash)
297 int len;
298 struct child_process cp = CHILD_PROCESS_INIT;
299 struct strbuf buffer = STRBUF_INIT;
300 const char *argv[] = {"stash", "create", NULL};
301 int rc = -1;
303 cp.argv = argv;
304 cp.out = -1;
305 cp.git_cmd = 1;
307 if (start_command(&cp))
308 die(_("could not run stash."));
309 len = strbuf_read(&buffer, cp.out, 1024);
310 close(cp.out);
312 if (finish_command(&cp) || len < 0)
313 die(_("stash failed"));
314 else if (!len) /* no changes */
315 goto out;
316 strbuf_setlen(&buffer, buffer.len-1);
317 if (get_oid(buffer.buf, stash))
318 die(_("not a valid object: %s"), buffer.buf);
319 rc = 0;
320 out:
321 strbuf_release(&buffer);
322 return rc;
325 static void read_empty(const struct object_id *oid, int verbose)
327 int i = 0;
328 const char *args[7];
330 args[i++] = "read-tree";
331 if (verbose)
332 args[i++] = "-v";
333 args[i++] = "-m";
334 args[i++] = "-u";
335 args[i++] = empty_tree_oid_hex();
336 args[i++] = oid_to_hex(oid);
337 args[i] = NULL;
339 if (run_command_v_opt(args, RUN_GIT_CMD))
340 die(_("read-tree failed"));
343 static void reset_hard(const struct object_id *oid, int verbose)
345 int i = 0;
346 const char *args[6];
348 args[i++] = "read-tree";
349 if (verbose)
350 args[i++] = "-v";
351 args[i++] = "--reset";
352 args[i++] = "-u";
353 args[i++] = oid_to_hex(oid);
354 args[i] = NULL;
356 if (run_command_v_opt(args, RUN_GIT_CMD))
357 die(_("read-tree failed"));
360 static void restore_state(const struct object_id *head,
361 const struct object_id *stash)
363 struct strbuf sb = STRBUF_INIT;
364 const char *args[] = { "stash", "apply", NULL, NULL };
366 if (is_null_oid(stash))
367 return;
369 reset_hard(head, 1);
371 args[2] = oid_to_hex(stash);
374 * It is OK to ignore error here, for example when there was
375 * nothing to restore.
377 run_command_v_opt(args, RUN_GIT_CMD);
379 strbuf_release(&sb);
380 refresh_cache(REFRESH_QUIET);
383 /* This is called when no merge was necessary. */
384 static void finish_up_to_date(const char *msg)
386 if (verbosity >= 0)
387 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
388 remove_merge_branch_state(the_repository);
391 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
393 struct rev_info rev;
394 struct strbuf out = STRBUF_INIT;
395 struct commit_list *j;
396 struct pretty_print_context ctx = {0};
398 printf(_("Squash commit -- not updating HEAD\n"));
400 repo_init_revisions(the_repository, &rev, NULL);
401 rev.ignore_merges = 1;
402 rev.commit_format = CMIT_FMT_MEDIUM;
404 commit->object.flags |= UNINTERESTING;
405 add_pending_object(&rev, &commit->object, NULL);
407 for (j = remoteheads; j; j = j->next)
408 add_pending_object(&rev, &j->item->object, NULL);
410 setup_revisions(0, NULL, &rev, NULL);
411 if (prepare_revision_walk(&rev))
412 die(_("revision walk setup failed"));
414 ctx.abbrev = rev.abbrev;
415 ctx.date_mode = rev.date_mode;
416 ctx.fmt = rev.commit_format;
418 strbuf_addstr(&out, "Squashed commit of the following:\n");
419 while ((commit = get_revision(&rev)) != NULL) {
420 strbuf_addch(&out, '\n');
421 strbuf_addf(&out, "commit %s\n",
422 oid_to_hex(&commit->object.oid));
423 pretty_print_commit(&ctx, commit, &out);
425 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
426 strbuf_release(&out);
429 static void finish(struct commit *head_commit,
430 struct commit_list *remoteheads,
431 const struct object_id *new_head, const char *msg)
433 struct strbuf reflog_message = STRBUF_INIT;
434 const struct object_id *head = &head_commit->object.oid;
436 if (!msg)
437 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
438 else {
439 if (verbosity >= 0)
440 printf("%s\n", msg);
441 strbuf_addf(&reflog_message, "%s: %s",
442 getenv("GIT_REFLOG_ACTION"), msg);
444 if (squash) {
445 squash_message(head_commit, remoteheads);
446 } else {
447 if (verbosity >= 0 && !merge_msg.len)
448 printf(_("No merge message -- not updating HEAD\n"));
449 else {
450 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
451 update_ref(reflog_message.buf, "HEAD", new_head, head,
452 0, UPDATE_REFS_DIE_ON_ERR);
454 * We ignore errors in 'gc --auto', since the
455 * user should see them.
457 close_object_store(the_repository->objects);
458 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
461 if (new_head && show_diffstat) {
462 struct diff_options opts;
463 repo_diff_setup(the_repository, &opts);
464 opts.stat_width = -1; /* use full terminal width */
465 opts.stat_graph_width = -1; /* respect statGraphWidth config */
466 opts.output_format |=
467 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
468 opts.detect_rename = DIFF_DETECT_RENAME;
469 diff_setup_done(&opts);
470 diff_tree_oid(head, new_head, "", &opts);
471 diffcore_std(&opts);
472 diff_flush(&opts);
475 /* Run a post-merge hook */
476 run_hook_le(NULL, "post-merge", squash ? "1" : "0", NULL);
478 strbuf_release(&reflog_message);
481 /* Get the name for the merge commit's message. */
482 static void merge_name(const char *remote, struct strbuf *msg)
484 struct commit *remote_head;
485 struct object_id branch_head;
486 struct strbuf buf = STRBUF_INIT;
487 struct strbuf bname = STRBUF_INIT;
488 struct merge_remote_desc *desc;
489 const char *ptr;
490 char *found_ref;
491 int len, early;
493 strbuf_branchname(&bname, remote, 0);
494 remote = bname.buf;
496 oidclr(&branch_head);
497 remote_head = get_merge_parent(remote);
498 if (!remote_head)
499 die(_("'%s' does not point to a commit"), remote);
501 if (dwim_ref(remote, strlen(remote), &branch_head, &found_ref) > 0) {
502 if (starts_with(found_ref, "refs/heads/")) {
503 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
504 oid_to_hex(&branch_head), remote);
505 goto cleanup;
507 if (starts_with(found_ref, "refs/tags/")) {
508 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
509 oid_to_hex(&branch_head), remote);
510 goto cleanup;
512 if (starts_with(found_ref, "refs/remotes/")) {
513 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
514 oid_to_hex(&branch_head), remote);
515 goto cleanup;
519 /* See if remote matches <name>^^^.. or <name>~<number> */
520 for (len = 0, ptr = remote + strlen(remote);
521 remote < ptr && ptr[-1] == '^';
522 ptr--)
523 len++;
524 if (len)
525 early = 1;
526 else {
527 early = 0;
528 ptr = strrchr(remote, '~');
529 if (ptr) {
530 int seen_nonzero = 0;
532 len++; /* count ~ */
533 while (*++ptr && isdigit(*ptr)) {
534 seen_nonzero |= (*ptr != '0');
535 len++;
537 if (*ptr)
538 len = 0; /* not ...~<number> */
539 else if (seen_nonzero)
540 early = 1;
541 else if (len == 1)
542 early = 1; /* "name~" is "name~1"! */
545 if (len) {
546 struct strbuf truname = STRBUF_INIT;
547 strbuf_addf(&truname, "refs/heads/%s", remote);
548 strbuf_setlen(&truname, truname.len - len);
549 if (ref_exists(truname.buf)) {
550 strbuf_addf(msg,
551 "%s\t\tbranch '%s'%s of .\n",
552 oid_to_hex(&remote_head->object.oid),
553 truname.buf + 11,
554 (early ? " (early part)" : ""));
555 strbuf_release(&truname);
556 goto cleanup;
558 strbuf_release(&truname);
561 desc = merge_remote_util(remote_head);
562 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
563 strbuf_addf(msg, "%s\t\t%s '%s'\n",
564 oid_to_hex(&desc->obj->oid),
565 type_name(desc->obj->type),
566 remote);
567 goto cleanup;
570 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
571 oid_to_hex(&remote_head->object.oid), remote);
572 cleanup:
573 strbuf_release(&buf);
574 strbuf_release(&bname);
577 static void parse_branch_merge_options(char *bmo)
579 const char **argv;
580 int argc;
582 if (!bmo)
583 return;
584 argc = split_cmdline(bmo, &argv);
585 if (argc < 0)
586 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
587 _(split_cmdline_strerror(argc)));
588 REALLOC_ARRAY(argv, argc + 2);
589 MOVE_ARRAY(argv + 1, argv, argc + 1);
590 argc++;
591 argv[0] = "branch.*.mergeoptions";
592 parse_options(argc, argv, NULL, builtin_merge_options,
593 builtin_merge_usage, 0);
594 free(argv);
597 static int git_merge_config(const char *k, const char *v, void *cb)
599 int status;
600 const char *str;
602 if (branch &&
603 skip_prefix(k, "branch.", &str) &&
604 skip_prefix(str, branch, &str) &&
605 !strcmp(str, ".mergeoptions")) {
606 free(branch_mergeoptions);
607 branch_mergeoptions = xstrdup(v);
608 return 0;
611 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
612 show_diffstat = git_config_bool(k, v);
613 else if (!strcmp(k, "merge.verifysignatures"))
614 verify_signatures = git_config_bool(k, v);
615 else if (!strcmp(k, "pull.twohead"))
616 return git_config_string(&pull_twohead, k, v);
617 else if (!strcmp(k, "pull.octopus"))
618 return git_config_string(&pull_octopus, k, v);
619 else if (!strcmp(k, "commit.cleanup"))
620 return git_config_string(&cleanup_arg, k, v);
621 else if (!strcmp(k, "merge.renormalize"))
622 option_renormalize = git_config_bool(k, v);
623 else if (!strcmp(k, "merge.ff")) {
624 int boolval = git_parse_maybe_bool(v);
625 if (0 <= boolval) {
626 fast_forward = boolval ? FF_ALLOW : FF_NO;
627 } else if (v && !strcmp(v, "only")) {
628 fast_forward = FF_ONLY;
629 } /* do not barf on values from future versions of git */
630 return 0;
631 } else if (!strcmp(k, "merge.defaulttoupstream")) {
632 default_to_upstream = git_config_bool(k, v);
633 return 0;
634 } else if (!strcmp(k, "commit.gpgsign")) {
635 sign_commit = git_config_bool(k, v) ? "" : NULL;
636 return 0;
637 } else if (!strcmp(k, "gpg.mintrustlevel")) {
638 check_trust_level = 0;
641 status = fmt_merge_msg_config(k, v, cb);
642 if (status)
643 return status;
644 status = git_gpg_config(k, v, NULL);
645 if (status)
646 return status;
647 return git_diff_ui_config(k, v, cb);
650 static int read_tree_trivial(struct object_id *common, struct object_id *head,
651 struct object_id *one)
653 int i, nr_trees = 0;
654 struct tree *trees[MAX_UNPACK_TREES];
655 struct tree_desc t[MAX_UNPACK_TREES];
656 struct unpack_trees_options opts;
658 memset(&opts, 0, sizeof(opts));
659 opts.head_idx = 2;
660 opts.src_index = &the_index;
661 opts.dst_index = &the_index;
662 opts.update = 1;
663 opts.verbose_update = 1;
664 opts.trivial_merges_only = 1;
665 opts.merge = 1;
666 trees[nr_trees] = parse_tree_indirect(common);
667 if (!trees[nr_trees++])
668 return -1;
669 trees[nr_trees] = parse_tree_indirect(head);
670 if (!trees[nr_trees++])
671 return -1;
672 trees[nr_trees] = parse_tree_indirect(one);
673 if (!trees[nr_trees++])
674 return -1;
675 opts.fn = threeway_merge;
676 cache_tree_free(&active_cache_tree);
677 for (i = 0; i < nr_trees; i++) {
678 parse_tree(trees[i]);
679 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
681 if (unpack_trees(nr_trees, t, &opts))
682 return -1;
683 return 0;
686 static void write_tree_trivial(struct object_id *oid)
688 if (write_cache_as_tree(oid, 0, NULL))
689 die(_("git write-tree failed to write a tree"));
692 static int try_merge_strategy(const char *strategy, struct commit_list *common,
693 struct commit_list *remoteheads,
694 struct commit *head)
696 const char *head_arg = "HEAD";
698 if (refresh_and_write_cache(REFRESH_QUIET, SKIP_IF_UNCHANGED, 0) < 0)
699 return error(_("Unable to write index."));
701 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
702 struct lock_file lock = LOCK_INIT;
703 int clean, x;
704 struct commit *result;
705 struct commit_list *reversed = NULL;
706 struct merge_options o;
707 struct commit_list *j;
709 if (remoteheads->next) {
710 error(_("Not handling anything other than two heads merge."));
711 return 2;
714 init_merge_options(&o, the_repository);
715 if (!strcmp(strategy, "subtree"))
716 o.subtree_shift = "";
718 o.renormalize = option_renormalize;
719 o.show_rename_progress =
720 show_progress == -1 ? isatty(2) : show_progress;
722 for (x = 0; x < xopts_nr; x++)
723 if (parse_merge_opt(&o, xopts[x]))
724 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
726 o.branch1 = head_arg;
727 o.branch2 = merge_remote_util(remoteheads->item)->name;
729 for (j = common; j; j = j->next)
730 commit_list_insert(j->item, &reversed);
732 hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
733 clean = merge_recursive(&o, head,
734 remoteheads->item, reversed, &result);
735 if (clean < 0)
736 exit(128);
737 if (write_locked_index(&the_index, &lock,
738 COMMIT_LOCK | SKIP_IF_UNCHANGED))
739 die(_("unable to write %s"), get_index_file());
740 return clean ? 0 : 1;
741 } else {
742 return try_merge_command(the_repository,
743 strategy, xopts_nr, xopts,
744 common, head_arg, remoteheads);
748 static void count_diff_files(struct diff_queue_struct *q,
749 struct diff_options *opt, void *data)
751 int *count = data;
753 (*count) += q->nr;
756 static int count_unmerged_entries(void)
758 int i, ret = 0;
760 for (i = 0; i < active_nr; i++)
761 if (ce_stage(active_cache[i]))
762 ret++;
764 return ret;
767 static void add_strategies(const char *string, unsigned attr)
769 int i;
771 if (string) {
772 struct string_list list = STRING_LIST_INIT_DUP;
773 struct string_list_item *item;
774 string_list_split(&list, string, ' ', -1);
775 for_each_string_list_item(item, &list)
776 append_strategy(get_strategy(item->string));
777 string_list_clear(&list, 0);
778 return;
780 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
781 if (all_strategy[i].attr & attr)
782 append_strategy(&all_strategy[i]);
786 static void read_merge_msg(struct strbuf *msg)
788 const char *filename = git_path_merge_msg(the_repository);
789 strbuf_reset(msg);
790 if (strbuf_read_file(msg, filename, 0) < 0)
791 die_errno(_("Could not read from '%s'"), filename);
794 static void write_merge_state(struct commit_list *);
795 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
797 if (err_msg)
798 error("%s", err_msg);
799 fprintf(stderr,
800 _("Not committing merge; use 'git commit' to complete the merge.\n"));
801 write_merge_state(remoteheads);
802 exit(1);
805 static const char merge_editor_comment[] =
806 N_("Please enter a commit message to explain why this merge is necessary,\n"
807 "especially if it merges an updated upstream into a topic branch.\n"
808 "\n");
810 static const char scissors_editor_comment[] =
811 N_("An empty message aborts the commit.\n");
813 static const char no_scissors_editor_comment[] =
814 N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
815 "the commit.\n");
817 static void write_merge_heads(struct commit_list *);
818 static void prepare_to_commit(struct commit_list *remoteheads)
820 struct strbuf msg = STRBUF_INIT;
821 const char *index_file = get_index_file();
823 if (!no_verify && run_commit_hook(0 < option_edit, index_file, "pre-merge-commit", NULL))
824 abort_commit(remoteheads, NULL);
826 * Re-read the index as pre-merge-commit hook could have updated it,
827 * and write it out as a tree. We must do this before we invoke
828 * the editor and after we invoke run_status above.
830 if (find_hook("pre-merge-commit"))
831 discard_cache();
832 read_cache_from(index_file);
833 strbuf_addbuf(&msg, &merge_msg);
834 if (squash)
835 BUG("the control must not reach here under --squash");
836 if (0 < option_edit) {
837 strbuf_addch(&msg, '\n');
838 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
839 wt_status_append_cut_line(&msg);
840 strbuf_commented_addf(&msg, "\n");
842 strbuf_commented_addf(&msg, _(merge_editor_comment));
843 strbuf_commented_addf(&msg, _(cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS ?
844 scissors_editor_comment :
845 no_scissors_editor_comment), comment_line_char);
847 if (signoff)
848 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
849 write_merge_heads(remoteheads);
850 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
851 if (run_commit_hook(0 < option_edit, get_index_file(), "prepare-commit-msg",
852 git_path_merge_msg(the_repository), "merge", NULL))
853 abort_commit(remoteheads, NULL);
854 if (0 < option_edit) {
855 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
856 abort_commit(remoteheads, NULL);
859 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
860 "commit-msg",
861 git_path_merge_msg(the_repository), NULL))
862 abort_commit(remoteheads, NULL);
864 read_merge_msg(&msg);
865 cleanup_message(&msg, cleanup_mode, 0);
866 if (!msg.len)
867 abort_commit(remoteheads, _("Empty commit message."));
868 strbuf_release(&merge_msg);
869 strbuf_addbuf(&merge_msg, &msg);
870 strbuf_release(&msg);
873 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
875 struct object_id result_tree, result_commit;
876 struct commit_list *parents, **pptr = &parents;
878 if (refresh_and_write_cache(REFRESH_QUIET, SKIP_IF_UNCHANGED, 0) < 0)
879 return error(_("Unable to write index."));
881 write_tree_trivial(&result_tree);
882 printf(_("Wonderful.\n"));
883 pptr = commit_list_append(head, pptr);
884 pptr = commit_list_append(remoteheads->item, pptr);
885 prepare_to_commit(remoteheads);
886 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
887 &result_commit, NULL, sign_commit))
888 die(_("failed to write commit object"));
889 finish(head, remoteheads, &result_commit, "In-index merge");
890 remove_merge_branch_state(the_repository);
891 return 0;
894 static int finish_automerge(struct commit *head,
895 int head_subsumed,
896 struct commit_list *common,
897 struct commit_list *remoteheads,
898 struct object_id *result_tree,
899 const char *wt_strategy)
901 struct commit_list *parents = NULL;
902 struct strbuf buf = STRBUF_INIT;
903 struct object_id result_commit;
905 write_tree_trivial(result_tree);
906 free_commit_list(common);
907 parents = remoteheads;
908 if (!head_subsumed || fast_forward == FF_NO)
909 commit_list_insert(head, &parents);
910 prepare_to_commit(remoteheads);
911 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
912 &result_commit, NULL, sign_commit))
913 die(_("failed to write commit object"));
914 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
915 finish(head, remoteheads, &result_commit, buf.buf);
916 strbuf_release(&buf);
917 remove_merge_branch_state(the_repository);
918 return 0;
921 static int suggest_conflicts(void)
923 const char *filename;
924 FILE *fp;
925 struct strbuf msgbuf = STRBUF_INIT;
927 filename = git_path_merge_msg(the_repository);
928 fp = xfopen(filename, "a");
931 * We can't use cleanup_mode because if we're not using the editor,
932 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
933 * though the message is meant to be processed later by git-commit.
934 * Thus, we will get the cleanup mode which is returned when we _are_
935 * using an editor.
937 append_conflicts_hint(&the_index, &msgbuf,
938 get_cleanup_mode(cleanup_arg, 1));
939 fputs(msgbuf.buf, fp);
940 strbuf_release(&msgbuf);
941 fclose(fp);
942 repo_rerere(the_repository, allow_rerere_auto);
943 printf(_("Automatic merge failed; "
944 "fix conflicts and then commit the result.\n"));
945 return 1;
948 static int evaluate_result(void)
950 int cnt = 0;
951 struct rev_info rev;
953 /* Check how many files differ. */
954 repo_init_revisions(the_repository, &rev, "");
955 setup_revisions(0, NULL, &rev, NULL);
956 rev.diffopt.output_format |=
957 DIFF_FORMAT_CALLBACK;
958 rev.diffopt.format_callback = count_diff_files;
959 rev.diffopt.format_callback_data = &cnt;
960 run_diff_files(&rev, 0);
963 * Check how many unmerged entries are
964 * there.
966 cnt += count_unmerged_entries();
968 return cnt;
972 * Pretend as if the user told us to merge with the remote-tracking
973 * branch we have for the upstream of the current branch
975 static int setup_with_upstream(const char ***argv)
977 struct branch *branch = branch_get(NULL);
978 int i;
979 const char **args;
981 if (!branch)
982 die(_("No current branch."));
983 if (!branch->remote_name)
984 die(_("No remote for the current branch."));
985 if (!branch->merge_nr)
986 die(_("No default upstream defined for the current branch."));
988 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
989 for (i = 0; i < branch->merge_nr; i++) {
990 if (!branch->merge[i]->dst)
991 die(_("No remote-tracking branch for %s from %s"),
992 branch->merge[i]->src, branch->remote_name);
993 args[i] = branch->merge[i]->dst;
995 args[i] = NULL;
996 *argv = args;
997 return i;
1000 static void write_merge_heads(struct commit_list *remoteheads)
1002 struct commit_list *j;
1003 struct strbuf buf = STRBUF_INIT;
1005 for (j = remoteheads; j; j = j->next) {
1006 struct object_id *oid;
1007 struct commit *c = j->item;
1008 struct merge_remote_desc *desc;
1010 desc = merge_remote_util(c);
1011 if (desc && desc->obj) {
1012 oid = &desc->obj->oid;
1013 } else {
1014 oid = &c->object.oid;
1016 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1018 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1020 strbuf_reset(&buf);
1021 if (fast_forward == FF_NO)
1022 strbuf_addstr(&buf, "no-ff");
1023 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1024 strbuf_release(&buf);
1027 static void write_merge_state(struct commit_list *remoteheads)
1029 write_merge_heads(remoteheads);
1030 strbuf_addch(&merge_msg, '\n');
1031 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1032 merge_msg.len);
1035 static int default_edit_option(void)
1037 static const char name[] = "GIT_MERGE_AUTOEDIT";
1038 const char *e = getenv(name);
1039 struct stat st_stdin, st_stdout;
1041 if (have_message)
1042 /* an explicit -m msg without --[no-]edit */
1043 return 0;
1045 if (e) {
1046 int v = git_parse_maybe_bool(e);
1047 if (v < 0)
1048 die(_("Bad value '%s' in environment '%s'"), e, name);
1049 return v;
1052 /* Use editor if stdin and stdout are the same and is a tty */
1053 return (!fstat(0, &st_stdin) &&
1054 !fstat(1, &st_stdout) &&
1055 isatty(0) && isatty(1) &&
1056 st_stdin.st_dev == st_stdout.st_dev &&
1057 st_stdin.st_ino == st_stdout.st_ino &&
1058 st_stdin.st_mode == st_stdout.st_mode);
1061 static struct commit_list *reduce_parents(struct commit *head_commit,
1062 int *head_subsumed,
1063 struct commit_list *remoteheads)
1065 struct commit_list *parents, **remotes;
1068 * Is the current HEAD reachable from another commit being
1069 * merged? If so we do not want to record it as a parent of
1070 * the resulting merge, unless --no-ff is given. We will flip
1071 * this variable to 0 when we find HEAD among the independent
1072 * tips being merged.
1074 *head_subsumed = 1;
1076 /* Find what parents to record by checking independent ones. */
1077 parents = reduce_heads(remoteheads);
1078 free_commit_list(remoteheads);
1080 remoteheads = NULL;
1081 remotes = &remoteheads;
1082 while (parents) {
1083 struct commit *commit = pop_commit(&parents);
1084 if (commit == head_commit)
1085 *head_subsumed = 0;
1086 else
1087 remotes = &commit_list_insert(commit, remotes)->next;
1089 return remoteheads;
1092 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1094 struct fmt_merge_msg_opts opts;
1096 memset(&opts, 0, sizeof(opts));
1097 opts.add_title = !have_message;
1098 opts.shortlog_len = shortlog_len;
1099 opts.credit_people = (0 < option_edit);
1101 fmt_merge_msg(merge_names, merge_msg, &opts);
1102 if (merge_msg->len)
1103 strbuf_setlen(merge_msg, merge_msg->len - 1);
1106 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1108 const char *filename;
1109 int fd, pos, npos;
1110 struct strbuf fetch_head_file = STRBUF_INIT;
1111 const unsigned hexsz = the_hash_algo->hexsz;
1113 if (!merge_names)
1114 merge_names = &fetch_head_file;
1116 filename = git_path_fetch_head(the_repository);
1117 fd = open(filename, O_RDONLY);
1118 if (fd < 0)
1119 die_errno(_("could not open '%s' for reading"), filename);
1121 if (strbuf_read(merge_names, fd, 0) < 0)
1122 die_errno(_("could not read '%s'"), filename);
1123 if (close(fd) < 0)
1124 die_errno(_("could not close '%s'"), filename);
1126 for (pos = 0; pos < merge_names->len; pos = npos) {
1127 struct object_id oid;
1128 char *ptr;
1129 struct commit *commit;
1131 ptr = strchr(merge_names->buf + pos, '\n');
1132 if (ptr)
1133 npos = ptr - merge_names->buf + 1;
1134 else
1135 npos = merge_names->len;
1137 if (npos - pos < hexsz + 2 ||
1138 get_oid_hex(merge_names->buf + pos, &oid))
1139 commit = NULL; /* bad */
1140 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1141 continue; /* not-for-merge */
1142 else {
1143 char saved = merge_names->buf[pos + hexsz];
1144 merge_names->buf[pos + hexsz] = '\0';
1145 commit = get_merge_parent(merge_names->buf + pos);
1146 merge_names->buf[pos + hexsz] = saved;
1148 if (!commit) {
1149 if (ptr)
1150 *ptr = '\0';
1151 die(_("not something we can merge in %s: %s"),
1152 filename, merge_names->buf + pos);
1154 remotes = &commit_list_insert(commit, remotes)->next;
1157 if (merge_names == &fetch_head_file)
1158 strbuf_release(&fetch_head_file);
1161 static struct commit_list *collect_parents(struct commit *head_commit,
1162 int *head_subsumed,
1163 int argc, const char **argv,
1164 struct strbuf *merge_msg)
1166 int i;
1167 struct commit_list *remoteheads = NULL;
1168 struct commit_list **remotes = &remoteheads;
1169 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1171 if (merge_msg && (!have_message || shortlog_len))
1172 autogen = &merge_names;
1174 if (head_commit)
1175 remotes = &commit_list_insert(head_commit, remotes)->next;
1177 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1178 handle_fetch_head(remotes, autogen);
1179 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1180 } else {
1181 for (i = 0; i < argc; i++) {
1182 struct commit *commit = get_merge_parent(argv[i]);
1183 if (!commit)
1184 help_unknown_ref(argv[i], "merge",
1185 _("not something we can merge"));
1186 remotes = &commit_list_insert(commit, remotes)->next;
1188 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1189 if (autogen) {
1190 struct commit_list *p;
1191 for (p = remoteheads; p; p = p->next)
1192 merge_name(merge_remote_util(p->item)->name, autogen);
1196 if (autogen) {
1197 prepare_merge_message(autogen, merge_msg);
1198 strbuf_release(autogen);
1201 return remoteheads;
1204 static int merging_a_throwaway_tag(struct commit *commit)
1206 char *tag_ref;
1207 struct object_id oid;
1208 int is_throwaway_tag = 0;
1210 /* Are we merging a tag? */
1211 if (!merge_remote_util(commit) ||
1212 !merge_remote_util(commit)->obj ||
1213 merge_remote_util(commit)->obj->type != OBJ_TAG)
1214 return is_throwaway_tag;
1217 * Now we know we are merging a tag object. Are we downstream
1218 * and following the tags from upstream? If so, we must have
1219 * the tag object pointed at by "refs/tags/$T" where $T is the
1220 * tagname recorded in the tag object. We want to allow such
1221 * a "just to catch up" merge to fast-forward.
1223 * Otherwise, we are playing an integrator's role, making a
1224 * merge with a throw-away tag from a contributor with
1225 * something like "git pull $contributor $signed_tag".
1226 * We want to forbid such a merge from fast-forwarding
1227 * by default; otherwise we would not keep the signature
1228 * anywhere.
1230 tag_ref = xstrfmt("refs/tags/%s",
1231 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1232 if (!read_ref(tag_ref, &oid) &&
1233 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1234 is_throwaway_tag = 0;
1235 else
1236 is_throwaway_tag = 1;
1237 free(tag_ref);
1238 return is_throwaway_tag;
1241 int cmd_merge(int argc, const char **argv, const char *prefix)
1243 struct object_id result_tree, stash, head_oid;
1244 struct commit *head_commit;
1245 struct strbuf buf = STRBUF_INIT;
1246 int i, ret = 0, head_subsumed;
1247 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1248 struct commit_list *common = NULL;
1249 const char *best_strategy = NULL, *wt_strategy = NULL;
1250 struct commit_list *remoteheads, *p;
1251 void *branch_to_free;
1252 int orig_argc = argc;
1254 if (argc == 2 && !strcmp(argv[1], "-h"))
1255 usage_with_options(builtin_merge_usage, builtin_merge_options);
1258 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1259 * current branch.
1261 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1262 if (branch)
1263 skip_prefix(branch, "refs/heads/", &branch);
1265 init_diff_ui_defaults();
1266 git_config(git_merge_config, NULL);
1268 if (!branch || is_null_oid(&head_oid))
1269 head_commit = NULL;
1270 else
1271 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1273 if (branch_mergeoptions)
1274 parse_branch_merge_options(branch_mergeoptions);
1275 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1276 builtin_merge_usage, 0);
1277 if (shortlog_len < 0)
1278 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1280 if (verbosity < 0 && show_progress == -1)
1281 show_progress = 0;
1283 if (abort_current_merge) {
1284 int nargc = 2;
1285 const char *nargv[] = {"reset", "--merge", NULL};
1287 if (orig_argc != 2)
1288 usage_msg_opt(_("--abort expects no arguments"),
1289 builtin_merge_usage, builtin_merge_options);
1291 if (!file_exists(git_path_merge_head(the_repository)))
1292 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1294 /* Invoke 'git reset --merge' */
1295 ret = cmd_reset(nargc, nargv, prefix);
1296 goto done;
1299 if (quit_current_merge) {
1300 if (orig_argc != 2)
1301 usage_msg_opt(_("--quit expects no arguments"),
1302 builtin_merge_usage,
1303 builtin_merge_options);
1305 remove_merge_branch_state(the_repository);
1306 goto done;
1309 if (continue_current_merge) {
1310 int nargc = 1;
1311 const char *nargv[] = {"commit", NULL};
1313 if (orig_argc != 2)
1314 usage_msg_opt(_("--continue expects no arguments"),
1315 builtin_merge_usage, builtin_merge_options);
1317 if (!file_exists(git_path_merge_head(the_repository)))
1318 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1320 /* Invoke 'git commit' */
1321 ret = cmd_commit(nargc, nargv, prefix);
1322 goto done;
1325 if (read_cache_unmerged())
1326 die_resolve_conflict("merge");
1328 if (file_exists(git_path_merge_head(the_repository))) {
1330 * There is no unmerged entry, don't advise 'git
1331 * add/rm <file>', just 'git commit'.
1333 if (advice_resolve_conflict)
1334 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1335 "Please, commit your changes before you merge."));
1336 else
1337 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1339 if (file_exists(git_path_cherry_pick_head(the_repository))) {
1340 if (advice_resolve_conflict)
1341 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1342 "Please, commit your changes before you merge."));
1343 else
1344 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1346 resolve_undo_clear();
1348 if (option_edit < 0)
1349 option_edit = default_edit_option();
1351 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1353 if (verbosity < 0)
1354 show_diffstat = 0;
1356 if (squash) {
1357 if (fast_forward == FF_NO)
1358 die(_("You cannot combine --squash with --no-ff."));
1359 if (option_commit > 0)
1360 die(_("You cannot combine --squash with --commit."));
1362 * squash can now silently disable option_commit - this is not
1363 * a problem as it is only overriding the default, not a user
1364 * supplied option.
1366 option_commit = 0;
1369 if (option_commit < 0)
1370 option_commit = 1;
1372 if (!argc) {
1373 if (default_to_upstream)
1374 argc = setup_with_upstream(&argv);
1375 else
1376 die(_("No commit specified and merge.defaultToUpstream not set."));
1377 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1378 argv[0] = "@{-1}";
1381 if (!argc)
1382 usage_with_options(builtin_merge_usage,
1383 builtin_merge_options);
1385 if (!head_commit) {
1387 * If the merged head is a valid one there is no reason
1388 * to forbid "git merge" into a branch yet to be born.
1389 * We do the same for "git pull".
1391 struct object_id *remote_head_oid;
1392 if (squash)
1393 die(_("Squash commit into empty head not supported yet"));
1394 if (fast_forward == FF_NO)
1395 die(_("Non-fast-forward commit does not make sense into "
1396 "an empty head"));
1397 remoteheads = collect_parents(head_commit, &head_subsumed,
1398 argc, argv, NULL);
1399 if (!remoteheads)
1400 die(_("%s - not something we can merge"), argv[0]);
1401 if (remoteheads->next)
1402 die(_("Can merge only exactly one commit into empty head"));
1404 if (verify_signatures)
1405 verify_merge_signature(remoteheads->item, verbosity,
1406 check_trust_level);
1408 remote_head_oid = &remoteheads->item->object.oid;
1409 read_empty(remote_head_oid, 0);
1410 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1411 UPDATE_REFS_DIE_ON_ERR);
1412 goto done;
1416 * All the rest are the commits being merged; prepare
1417 * the standard merge summary message to be appended
1418 * to the given message.
1420 remoteheads = collect_parents(head_commit, &head_subsumed,
1421 argc, argv, &merge_msg);
1423 if (!head_commit || !argc)
1424 usage_with_options(builtin_merge_usage,
1425 builtin_merge_options);
1427 if (verify_signatures) {
1428 for (p = remoteheads; p; p = p->next) {
1429 verify_merge_signature(p->item, verbosity,
1430 check_trust_level);
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);
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;
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);
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;
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);
1477 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1478 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
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)) {
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.
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;
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));
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;
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;
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)
1532 * We are not doing octopus and not fast-forward. Need
1533 * a real merge.
1535 else if (!remoteheads->next && !common->next && option_commit) {
1537 * We are not doing octopus, not fast-forward, and have
1538 * only one common.
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;
1551 printf(_("Nope.\n"));
1553 } else {
1555 * An octopus. If we can reach all the remote we are up
1556 * to date.
1558 int up_to_date = 1;
1559 struct commit_list *j;
1561 for (j = remoteheads; j; j = j->next) {
1562 struct commit_list *common_one;
1565 * Here we *have* to calculate the individual
1566 * merge_bases again, otherwise "git merge HEAD^
1567 * HEAD^^" would be missed.
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;
1575 if (up_to_date) {
1576 finish_up_to_date(_("Already up to date. Yeeah!"));
1577 goto done;
1581 if (fast_forward == FF_ONLY)
1582 die(_("Not possible to fast-forward, aborting."));
1584 /* We are going to make a new commit. */
1585 git_committer_info(IDENT_STRICT);
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.
1595 if (use_strategies_nr == 1 ||
1597 * Stash away the local changes so that we can try more than one.
1599 save_state(&stash))
1600 oidclr(&stash);
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);
1608 if (use_strategies_nr != 1)
1609 printf(_("Trying merge strategy %s...\n"),
1610 use_strategies[i]->name);
1612 * Remember which strategy left the state in the working
1613 * tree.
1615 wt_strategy = use_strategies[i]->name;
1617 ret = try_merge_strategy(use_strategies[i]->name,
1618 common, remoteheads,
1619 head_commit);
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.
1625 if (ret < 2) {
1626 if (!ret) {
1627 if (option_commit) {
1628 /* Automerge succeeded. */
1629 automerge_was_ok = 1;
1630 break;
1632 merge_was_ok = 1;
1634 cnt = evaluate_result();
1635 if (best_cnt <= 0 || cnt <= best_cnt) {
1636 best_strategy = use_strategies[i]->name;
1637 best_cnt = cnt;
1643 * If we have a resulting tree, that means the strategy module
1644 * auto resolved the merge cleanly.
1646 if (automerge_was_ok) {
1647 ret = finish_automerge(head_commit, head_subsumed,
1648 common, remoteheads,
1649 &result_tree, wt_strategy);
1650 goto done;
1654 * Pick the result from the best strategy and have the user fix
1655 * it up.
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);
1678 if (squash)
1679 finish(head_commit, remoteheads, NULL, NULL);
1680 else
1681 write_merge_state(remoteheads);
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();
1689 done:
1690 free(branch_to_free);
1691 return ret;