4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
10 #include "parse-options.h"
13 #include "run-command.h"
19 #include "unpack-trees.h"
20 #include "cache-tree.h"
27 #include "merge-recursive.h"
28 #include "resolve-undo.h"
30 #include "fmt-merge-msg.h"
31 #include "gpg-interface.h"
32 #include "sequencer.h"
33 #include "string-list.h"
35 #define DEFAULT_TWOHEAD (1<<0)
36 #define DEFAULT_OCTOPUS (1<<1)
37 #define NO_FAST_FORWARD (1<<2)
38 #define NO_TRIVIAL (1<<3)
45 static const char * const builtin_merge_usage[] = {
46 N_("git merge [<options>] [<commit>...]"),
47 N_("git merge [<options>] <msg> HEAD <commit>"),
48 N_("git merge --abort"),
52 static int show_diffstat = 1, shortlog_len = -1, squash;
53 static int option_commit = 1;
54 static int option_edit = -1;
55 static int allow_trivial = 1, have_message, verify_signatures;
56 static int overwrite_ignore = 1;
57 static struct strbuf merge_msg = STRBUF_INIT;
58 static struct strategy **use_strategies;
59 static size_t use_strategies_nr, use_strategies_alloc;
60 static const char **xopts;
61 static size_t xopts_nr, xopts_alloc;
62 static const char *branch;
63 static char *branch_mergeoptions;
64 static int option_renormalize;
66 static int allow_rerere_auto;
67 static int abort_current_merge;
68 static int allow_unrelated_histories;
69 static int show_progress = -1;
70 static int default_to_upstream = 1;
71 static const char *sign_commit;
73 static struct strategy all_strategy[] = {
74 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
75 { "octopus", DEFAULT_OCTOPUS },
77 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
78 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
81 static const char *pull_twohead, *pull_octopus;
89 static enum ff_type fast_forward = FF_ALLOW;
91 static int option_parse_message(const struct option *opt,
92 const char *arg, int unset)
94 struct strbuf *buf = opt->value;
97 strbuf_setlen(buf, 0);
99 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
102 return error(_("switch `m' requires a value"));
106 static struct strategy *get_strategy(const char *name)
109 struct strategy *ret;
110 static struct cmdnames main_cmds, other_cmds;
116 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
117 if (!strcmp(name, all_strategy[i].name))
118 return &all_strategy[i];
121 struct cmdnames not_strategies;
124 memset(¬_strategies, 0, sizeof(struct cmdnames));
125 load_command_list("git-merge-", &main_cmds, &other_cmds);
126 for (i = 0; i < main_cmds.cnt; i++) {
128 struct cmdname *ent = main_cmds.names[i];
129 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
130 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
131 && !all_strategy[j].name[ent->len])
134 add_cmdname(¬_strategies, ent->name, ent->len);
136 exclude_cmds(&main_cmds, ¬_strategies);
138 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
139 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
140 fprintf(stderr, _("Available strategies are:"));
141 for (i = 0; i < main_cmds.cnt; i++)
142 fprintf(stderr, " %s", main_cmds.names[i]->name);
143 fprintf(stderr, ".\n");
144 if (other_cmds.cnt) {
145 fprintf(stderr, _("Available custom strategies are:"));
146 for (i = 0; i < other_cmds.cnt; i++)
147 fprintf(stderr, " %s", other_cmds.names[i]->name);
148 fprintf(stderr, ".\n");
153 ret = xcalloc(1, sizeof(struct strategy));
154 ret->name = xstrdup(name);
155 ret->attr = NO_TRIVIAL;
159 static void append_strategy(struct strategy *s)
161 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
162 use_strategies[use_strategies_nr++] = s;
165 static int option_parse_strategy(const struct option *opt,
166 const char *name, int unset)
171 append_strategy(get_strategy(name));
175 static int option_parse_x(const struct option *opt,
176 const char *arg, int unset)
181 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
182 xopts[xopts_nr++] = xstrdup(arg);
186 static int option_parse_n(const struct option *opt,
187 const char *arg, int unset)
189 show_diffstat = unset;
193 static struct option builtin_merge_options[] = {
194 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
195 N_("do not show a diffstat at the end of the merge"),
196 PARSE_OPT_NOARG, option_parse_n },
197 OPT_BOOL(0, "stat", &show_diffstat,
198 N_("show a diffstat at the end of the merge")),
199 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
200 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
201 N_("add (at most <n>) entries from shortlog to merge commit message"),
202 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
203 OPT_BOOL(0, "squash", &squash,
204 N_("create a single commit instead of doing a merge")),
205 OPT_BOOL(0, "commit", &option_commit,
206 N_("perform a commit if the merge succeeds (default)")),
207 OPT_BOOL('e', "edit", &option_edit,
208 N_("edit message before committing")),
209 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
210 { OPTION_SET_INT, 0, "ff-only", &fast_forward, NULL,
211 N_("abort if fast-forward is not possible"),
212 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, FF_ONLY },
213 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
214 OPT_BOOL(0, "verify-signatures", &verify_signatures,
215 N_("verify that the named commit has a valid GPG signature")),
216 OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
217 N_("merge strategy to use"), option_parse_strategy),
218 OPT_CALLBACK('X', "strategy-option", &xopts, N_("option=value"),
219 N_("option for selected merge strategy"), option_parse_x),
220 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
221 N_("merge commit message (for a non-fast-forward merge)"),
222 option_parse_message),
223 OPT__VERBOSITY(&verbosity),
224 OPT_BOOL(0, "abort", &abort_current_merge,
225 N_("abort the current in-progress merge")),
226 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
227 N_("allow merging unrelated histories")),
228 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
229 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
230 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
231 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
235 /* Cleans up metadata that is uninteresting after a succeeded merge. */
236 static void drop_save(void)
238 unlink(git_path_merge_head());
239 unlink(git_path_merge_msg());
240 unlink(git_path_merge_mode());
243 static int save_state(unsigned char *stash)
246 struct child_process cp = CHILD_PROCESS_INIT;
247 struct strbuf buffer = STRBUF_INIT;
248 const char *argv[] = {"stash", "create", NULL};
254 if (start_command(&cp))
255 die(_("could not run stash."));
256 len = strbuf_read(&buffer, cp.out, 1024);
259 if (finish_command(&cp) || len < 0)
260 die(_("stash failed"));
261 else if (!len) /* no changes */
263 strbuf_setlen(&buffer, buffer.len-1);
264 if (get_sha1(buffer.buf, stash))
265 die(_("not a valid object: %s"), buffer.buf);
269 static void read_empty(unsigned const char *sha1, int verbose)
274 args[i++] = "read-tree";
279 args[i++] = EMPTY_TREE_SHA1_HEX;
280 args[i++] = sha1_to_hex(sha1);
283 if (run_command_v_opt(args, RUN_GIT_CMD))
284 die(_("read-tree failed"));
287 static void reset_hard(unsigned const char *sha1, int verbose)
292 args[i++] = "read-tree";
295 args[i++] = "--reset";
297 args[i++] = sha1_to_hex(sha1);
300 if (run_command_v_opt(args, RUN_GIT_CMD))
301 die(_("read-tree failed"));
304 static void restore_state(const unsigned char *head,
305 const unsigned char *stash)
307 struct strbuf sb = STRBUF_INIT;
308 const char *args[] = { "stash", "apply", NULL, NULL };
310 if (is_null_sha1(stash))
315 args[2] = sha1_to_hex(stash);
318 * It is OK to ignore error here, for example when there was
319 * nothing to restore.
321 run_command_v_opt(args, RUN_GIT_CMD);
324 refresh_cache(REFRESH_QUIET);
327 /* This is called when no merge was necessary. */
328 static void finish_up_to_date(const char *msg)
331 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
335 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
338 struct strbuf out = STRBUF_INIT;
339 struct commit_list *j;
340 struct pretty_print_context ctx = {0};
342 printf(_("Squash commit -- not updating HEAD\n"));
344 init_revisions(&rev, NULL);
345 rev.ignore_merges = 1;
346 rev.commit_format = CMIT_FMT_MEDIUM;
348 commit->object.flags |= UNINTERESTING;
349 add_pending_object(&rev, &commit->object, NULL);
351 for (j = remoteheads; j; j = j->next)
352 add_pending_object(&rev, &j->item->object, NULL);
354 setup_revisions(0, NULL, &rev, NULL);
355 if (prepare_revision_walk(&rev))
356 die(_("revision walk setup failed"));
358 ctx.abbrev = rev.abbrev;
359 ctx.date_mode = rev.date_mode;
360 ctx.fmt = rev.commit_format;
362 strbuf_addstr(&out, "Squashed commit of the following:\n");
363 while ((commit = get_revision(&rev)) != NULL) {
364 strbuf_addch(&out, '\n');
365 strbuf_addf(&out, "commit %s\n",
366 oid_to_hex(&commit->object.oid));
367 pretty_print_commit(&ctx, commit, &out);
369 write_file_buf(git_path_squash_msg(), out.buf, out.len);
370 strbuf_release(&out);
373 static void finish(struct commit *head_commit,
374 struct commit_list *remoteheads,
375 const unsigned char *new_head, const char *msg)
377 struct strbuf reflog_message = STRBUF_INIT;
378 const unsigned char *head = head_commit->object.oid.hash;
381 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
385 strbuf_addf(&reflog_message, "%s: %s",
386 getenv("GIT_REFLOG_ACTION"), msg);
389 squash_message(head_commit, remoteheads);
391 if (verbosity >= 0 && !merge_msg.len)
392 printf(_("No merge message -- not updating HEAD\n"));
394 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
395 update_ref(reflog_message.buf, "HEAD",
397 UPDATE_REFS_DIE_ON_ERR);
399 * We ignore errors in 'gc --auto', since the
400 * user should see them.
403 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
406 if (new_head && show_diffstat) {
407 struct diff_options opts;
409 opts.stat_width = -1; /* use full terminal width */
410 opts.stat_graph_width = -1; /* respect statGraphWidth config */
411 opts.output_format |=
412 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
413 opts.detect_rename = DIFF_DETECT_RENAME;
414 diff_setup_done(&opts);
415 diff_tree_sha1(head, new_head, "", &opts);
420 /* Run a post-merge hook */
421 run_hook_le(NULL, "post-merge", squash ? "1" : "0", NULL);
423 strbuf_release(&reflog_message);
426 /* Get the name for the merge commit's message. */
427 static void merge_name(const char *remote, struct strbuf *msg)
429 struct commit *remote_head;
430 unsigned char branch_head[20];
431 struct strbuf buf = STRBUF_INIT;
432 struct strbuf bname = STRBUF_INIT;
437 strbuf_branchname(&bname, remote);
440 memset(branch_head, 0, sizeof(branch_head));
441 remote_head = get_merge_parent(remote);
443 die(_("'%s' does not point to a commit"), remote);
445 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
446 if (starts_with(found_ref, "refs/heads/")) {
447 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
448 sha1_to_hex(branch_head), remote);
451 if (starts_with(found_ref, "refs/tags/")) {
452 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
453 sha1_to_hex(branch_head), remote);
456 if (starts_with(found_ref, "refs/remotes/")) {
457 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
458 sha1_to_hex(branch_head), remote);
463 /* See if remote matches <name>^^^.. or <name>~<number> */
464 for (len = 0, ptr = remote + strlen(remote);
465 remote < ptr && ptr[-1] == '^';
472 ptr = strrchr(remote, '~');
474 int seen_nonzero = 0;
477 while (*++ptr && isdigit(*ptr)) {
478 seen_nonzero |= (*ptr != '0');
482 len = 0; /* not ...~<number> */
483 else if (seen_nonzero)
486 early = 1; /* "name~" is "name~1"! */
490 struct strbuf truname = STRBUF_INIT;
491 strbuf_addf(&truname, "refs/heads/%s", remote);
492 strbuf_setlen(&truname, truname.len - len);
493 if (ref_exists(truname.buf)) {
495 "%s\t\tbranch '%s'%s of .\n",
496 oid_to_hex(&remote_head->object.oid),
498 (early ? " (early part)" : ""));
499 strbuf_release(&truname);
502 strbuf_release(&truname);
505 if (remote_head->util) {
506 struct merge_remote_desc *desc;
507 desc = merge_remote_util(remote_head);
508 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
509 strbuf_addf(msg, "%s\t\t%s '%s'\n",
510 oid_to_hex(&desc->obj->oid),
511 typename(desc->obj->type),
517 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
518 oid_to_hex(&remote_head->object.oid), remote);
520 strbuf_release(&buf);
521 strbuf_release(&bname);
524 static void parse_branch_merge_options(char *bmo)
531 argc = split_cmdline(bmo, &argv);
533 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
534 split_cmdline_strerror(argc));
535 REALLOC_ARRAY(argv, argc + 2);
536 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
538 argv[0] = "branch.*.mergeoptions";
539 parse_options(argc, argv, NULL, builtin_merge_options,
540 builtin_merge_usage, 0);
544 static int git_merge_config(const char *k, const char *v, void *cb)
548 if (branch && starts_with(k, "branch.") &&
549 starts_with(k + 7, branch) &&
550 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
551 free(branch_mergeoptions);
552 branch_mergeoptions = xstrdup(v);
556 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
557 show_diffstat = git_config_bool(k, v);
558 else if (!strcmp(k, "pull.twohead"))
559 return git_config_string(&pull_twohead, k, v);
560 else if (!strcmp(k, "pull.octopus"))
561 return git_config_string(&pull_octopus, k, v);
562 else if (!strcmp(k, "merge.renormalize"))
563 option_renormalize = git_config_bool(k, v);
564 else if (!strcmp(k, "merge.ff")) {
565 int boolval = git_config_maybe_bool(k, v);
567 fast_forward = boolval ? FF_ALLOW : FF_NO;
568 } else if (v && !strcmp(v, "only")) {
569 fast_forward = FF_ONLY;
570 } /* do not barf on values from future versions of git */
572 } else if (!strcmp(k, "merge.defaulttoupstream")) {
573 default_to_upstream = git_config_bool(k, v);
575 } else if (!strcmp(k, "commit.gpgsign")) {
576 sign_commit = git_config_bool(k, v) ? "" : NULL;
580 status = fmt_merge_msg_config(k, v, cb);
583 status = git_gpg_config(k, v, NULL);
586 return git_diff_ui_config(k, v, cb);
589 static int read_tree_trivial(unsigned char *common, unsigned char *head,
593 struct tree *trees[MAX_UNPACK_TREES];
594 struct tree_desc t[MAX_UNPACK_TREES];
595 struct unpack_trees_options opts;
597 memset(&opts, 0, sizeof(opts));
599 opts.src_index = &the_index;
600 opts.dst_index = &the_index;
602 opts.verbose_update = 1;
603 opts.trivial_merges_only = 1;
605 trees[nr_trees] = parse_tree_indirect(common);
606 if (!trees[nr_trees++])
608 trees[nr_trees] = parse_tree_indirect(head);
609 if (!trees[nr_trees++])
611 trees[nr_trees] = parse_tree_indirect(one);
612 if (!trees[nr_trees++])
614 opts.fn = threeway_merge;
615 cache_tree_free(&active_cache_tree);
616 for (i = 0; i < nr_trees; i++) {
617 parse_tree(trees[i]);
618 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
620 if (unpack_trees(nr_trees, t, &opts))
625 static void write_tree_trivial(unsigned char *sha1)
627 if (write_cache_as_tree(sha1, 0, NULL))
628 die(_("git write-tree failed to write a tree"));
631 static int try_merge_strategy(const char *strategy, struct commit_list *common,
632 struct commit_list *remoteheads,
633 struct commit *head, const char *head_arg)
635 static struct lock_file lock;
637 hold_locked_index(&lock, 1);
638 refresh_cache(REFRESH_QUIET);
639 if (active_cache_changed &&
640 write_locked_index(&the_index, &lock, COMMIT_LOCK))
641 return error(_("Unable to write index."));
642 rollback_lock_file(&lock);
644 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
646 struct commit *result;
647 struct commit_list *reversed = NULL;
648 struct merge_options o;
649 struct commit_list *j;
651 if (remoteheads->next) {
652 error(_("Not handling anything other than two heads merge."));
656 init_merge_options(&o);
657 if (!strcmp(strategy, "subtree"))
658 o.subtree_shift = "";
660 o.renormalize = option_renormalize;
661 o.show_rename_progress =
662 show_progress == -1 ? isatty(2) : show_progress;
664 for (x = 0; x < xopts_nr; x++)
665 if (parse_merge_opt(&o, xopts[x]))
666 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
668 o.branch1 = head_arg;
669 o.branch2 = merge_remote_util(remoteheads->item)->name;
671 for (j = common; j; j = j->next)
672 commit_list_insert(j->item, &reversed);
674 hold_locked_index(&lock, 1);
675 clean = merge_recursive(&o, head,
676 remoteheads->item, reversed, &result);
679 if (active_cache_changed &&
680 write_locked_index(&the_index, &lock, COMMIT_LOCK))
681 die (_("unable to write %s"), get_index_file());
682 rollback_lock_file(&lock);
683 return clean ? 0 : 1;
685 return try_merge_command(strategy, xopts_nr, xopts,
686 common, head_arg, remoteheads);
690 static void count_diff_files(struct diff_queue_struct *q,
691 struct diff_options *opt, void *data)
698 static int count_unmerged_entries(void)
702 for (i = 0; i < active_nr; i++)
703 if (ce_stage(active_cache[i]))
709 static void add_strategies(const char *string, unsigned attr)
714 struct string_list list = STRING_LIST_INIT_DUP;
715 struct string_list_item *item;
716 string_list_split(&list, string, ' ', -1);
717 for_each_string_list_item(item, &list)
718 append_strategy(get_strategy(item->string));
719 string_list_clear(&list, 0);
722 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
723 if (all_strategy[i].attr & attr)
724 append_strategy(&all_strategy[i]);
728 static void read_merge_msg(struct strbuf *msg)
730 const char *filename = git_path_merge_msg();
732 if (strbuf_read_file(msg, filename, 0) < 0)
733 die_errno(_("Could not read from '%s'"), filename);
736 static void write_merge_state(struct commit_list *);
737 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
740 error("%s", err_msg);
742 _("Not committing merge; use 'git commit' to complete the merge.\n"));
743 write_merge_state(remoteheads);
747 static const char merge_editor_comment[] =
748 N_("Please enter a commit message to explain why this merge is necessary,\n"
749 "especially if it merges an updated upstream into a topic branch.\n"
751 "Lines starting with '%c' will be ignored, and an empty message aborts\n"
754 static void prepare_to_commit(struct commit_list *remoteheads)
756 struct strbuf msg = STRBUF_INIT;
757 strbuf_addbuf(&msg, &merge_msg);
758 strbuf_addch(&msg, '\n');
760 strbuf_commented_addf(&msg, _(merge_editor_comment), comment_line_char);
761 write_file_buf(git_path_merge_msg(), msg.buf, msg.len);
762 if (run_commit_hook(0 < option_edit, get_index_file(), "prepare-commit-msg",
763 git_path_merge_msg(), "merge", NULL))
764 abort_commit(remoteheads, NULL);
765 if (0 < option_edit) {
766 if (launch_editor(git_path_merge_msg(), NULL, NULL))
767 abort_commit(remoteheads, NULL);
769 read_merge_msg(&msg);
770 strbuf_stripspace(&msg, 0 < option_edit);
772 abort_commit(remoteheads, _("Empty commit message."));
773 strbuf_release(&merge_msg);
774 strbuf_addbuf(&merge_msg, &msg);
775 strbuf_release(&msg);
778 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
780 unsigned char result_tree[20], result_commit[20];
781 struct commit_list *parents, **pptr = &parents;
782 static struct lock_file lock;
784 hold_locked_index(&lock, 1);
785 refresh_cache(REFRESH_QUIET);
786 if (active_cache_changed &&
787 write_locked_index(&the_index, &lock, COMMIT_LOCK))
788 return error(_("Unable to write index."));
789 rollback_lock_file(&lock);
791 write_tree_trivial(result_tree);
792 printf(_("Wonderful.\n"));
793 pptr = commit_list_append(head, pptr);
794 pptr = commit_list_append(remoteheads->item, pptr);
795 prepare_to_commit(remoteheads);
796 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
797 result_commit, NULL, sign_commit))
798 die(_("failed to write commit object"));
799 finish(head, remoteheads, result_commit, "In-index merge");
804 static int finish_automerge(struct commit *head,
806 struct commit_list *common,
807 struct commit_list *remoteheads,
808 unsigned char *result_tree,
809 const char *wt_strategy)
811 struct commit_list *parents = NULL;
812 struct strbuf buf = STRBUF_INIT;
813 unsigned char result_commit[20];
815 free_commit_list(common);
816 parents = remoteheads;
817 if (!head_subsumed || fast_forward == FF_NO)
818 commit_list_insert(head, &parents);
819 strbuf_addch(&merge_msg, '\n');
820 prepare_to_commit(remoteheads);
821 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
822 result_commit, NULL, sign_commit))
823 die(_("failed to write commit object"));
824 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
825 finish(head, remoteheads, result_commit, buf.buf);
826 strbuf_release(&buf);
831 static int suggest_conflicts(void)
833 const char *filename;
835 struct strbuf msgbuf = STRBUF_INIT;
837 filename = git_path_merge_msg();
838 fp = fopen(filename, "a");
840 die_errno(_("Could not open '%s' for writing"), filename);
842 append_conflicts_hint(&msgbuf);
843 fputs(msgbuf.buf, fp);
844 strbuf_release(&msgbuf);
846 rerere(allow_rerere_auto);
847 printf(_("Automatic merge failed; "
848 "fix conflicts and then commit the result.\n"));
852 static struct commit *is_old_style_invocation(int argc, const char **argv,
853 const unsigned char *head)
855 struct commit *second_token = NULL;
857 unsigned char second_sha1[20];
859 if (get_sha1(argv[1], second_sha1))
861 second_token = lookup_commit_reference_gently(second_sha1, 0);
863 die(_("'%s' is not a commit"), argv[1]);
864 if (hashcmp(second_token->object.oid.hash, head))
870 static int evaluate_result(void)
875 /* Check how many files differ. */
876 init_revisions(&rev, "");
877 setup_revisions(0, NULL, &rev, NULL);
878 rev.diffopt.output_format |=
879 DIFF_FORMAT_CALLBACK;
880 rev.diffopt.format_callback = count_diff_files;
881 rev.diffopt.format_callback_data = &cnt;
882 run_diff_files(&rev, 0);
885 * Check how many unmerged entries are
888 cnt += count_unmerged_entries();
894 * Pretend as if the user told us to merge with the remote-tracking
895 * branch we have for the upstream of the current branch
897 static int setup_with_upstream(const char ***argv)
899 struct branch *branch = branch_get(NULL);
904 die(_("No current branch."));
905 if (!branch->remote_name)
906 die(_("No remote for the current branch."));
907 if (!branch->merge_nr)
908 die(_("No default upstream defined for the current branch."));
910 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
911 for (i = 0; i < branch->merge_nr; i++) {
912 if (!branch->merge[i]->dst)
913 die(_("No remote-tracking branch for %s from %s"),
914 branch->merge[i]->src, branch->remote_name);
915 args[i] = branch->merge[i]->dst;
922 static void write_merge_state(struct commit_list *remoteheads)
924 struct commit_list *j;
925 struct strbuf buf = STRBUF_INIT;
927 for (j = remoteheads; j; j = j->next) {
928 struct object_id *oid;
929 struct commit *c = j->item;
930 if (c->util && merge_remote_util(c)->obj) {
931 oid = &merge_remote_util(c)->obj->oid;
933 oid = &c->object.oid;
935 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
937 write_file_buf(git_path_merge_head(), buf.buf, buf.len);
938 strbuf_addch(&merge_msg, '\n');
939 write_file_buf(git_path_merge_msg(), merge_msg.buf, merge_msg.len);
942 if (fast_forward == FF_NO)
943 strbuf_addf(&buf, "no-ff");
944 write_file_buf(git_path_merge_mode(), buf.buf, buf.len);
947 static int default_edit_option(void)
949 static const char name[] = "GIT_MERGE_AUTOEDIT";
950 const char *e = getenv(name);
951 struct stat st_stdin, st_stdout;
954 /* an explicit -m msg without --[no-]edit */
958 int v = git_config_maybe_bool(name, e);
960 die(_("Bad value '%s' in environment '%s'"), e, name);
964 /* Use editor if stdin and stdout are the same and is a tty */
965 return (!fstat(0, &st_stdin) &&
966 !fstat(1, &st_stdout) &&
967 isatty(0) && isatty(1) &&
968 st_stdin.st_dev == st_stdout.st_dev &&
969 st_stdin.st_ino == st_stdout.st_ino &&
970 st_stdin.st_mode == st_stdout.st_mode);
973 static struct commit_list *reduce_parents(struct commit *head_commit,
975 struct commit_list *remoteheads)
977 struct commit_list *parents, **remotes;
980 * Is the current HEAD reachable from another commit being
981 * merged? If so we do not want to record it as a parent of
982 * the resulting merge, unless --no-ff is given. We will flip
983 * this variable to 0 when we find HEAD among the independent
988 /* Find what parents to record by checking independent ones. */
989 parents = reduce_heads(remoteheads);
992 remotes = &remoteheads;
994 struct commit *commit = pop_commit(&parents);
995 if (commit == head_commit)
998 remotes = &commit_list_insert(commit, remotes)->next;
1003 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1005 struct fmt_merge_msg_opts opts;
1007 memset(&opts, 0, sizeof(opts));
1008 opts.add_title = !have_message;
1009 opts.shortlog_len = shortlog_len;
1010 opts.credit_people = (0 < option_edit);
1012 fmt_merge_msg(merge_names, merge_msg, &opts);
1014 strbuf_setlen(merge_msg, merge_msg->len - 1);
1017 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1019 const char *filename;
1021 struct strbuf fetch_head_file = STRBUF_INIT;
1024 merge_names = &fetch_head_file;
1026 filename = git_path_fetch_head();
1027 fd = open(filename, O_RDONLY);
1029 die_errno(_("could not open '%s' for reading"), filename);
1031 if (strbuf_read(merge_names, fd, 0) < 0)
1032 die_errno(_("could not read '%s'"), filename);
1034 die_errno(_("could not close '%s'"), filename);
1036 for (pos = 0; pos < merge_names->len; pos = npos) {
1037 unsigned char sha1[20];
1039 struct commit *commit;
1041 ptr = strchr(merge_names->buf + pos, '\n');
1043 npos = ptr - merge_names->buf + 1;
1045 npos = merge_names->len;
1047 if (npos - pos < 40 + 2 ||
1048 get_sha1_hex(merge_names->buf + pos, sha1))
1049 commit = NULL; /* bad */
1050 else if (memcmp(merge_names->buf + pos + 40, "\t\t", 2))
1051 continue; /* not-for-merge */
1053 char saved = merge_names->buf[pos + 40];
1054 merge_names->buf[pos + 40] = '\0';
1055 commit = get_merge_parent(merge_names->buf + pos);
1056 merge_names->buf[pos + 40] = saved;
1061 die(_("not something we can merge in %s: %s"),
1062 filename, merge_names->buf + pos);
1064 remotes = &commit_list_insert(commit, remotes)->next;
1067 if (merge_names == &fetch_head_file)
1068 strbuf_release(&fetch_head_file);
1071 static struct commit_list *collect_parents(struct commit *head_commit,
1073 int argc, const char **argv,
1074 struct strbuf *merge_msg)
1077 struct commit_list *remoteheads = NULL;
1078 struct commit_list **remotes = &remoteheads;
1079 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1081 if (merge_msg && (!have_message || shortlog_len))
1082 autogen = &merge_names;
1085 remotes = &commit_list_insert(head_commit, remotes)->next;
1087 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1088 handle_fetch_head(remotes, autogen);
1089 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1091 for (i = 0; i < argc; i++) {
1092 struct commit *commit = get_merge_parent(argv[i]);
1094 help_unknown_ref(argv[i], "merge",
1095 _("not something we can merge"));
1096 remotes = &commit_list_insert(commit, remotes)->next;
1098 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1100 struct commit_list *p;
1101 for (p = remoteheads; p; p = p->next)
1102 merge_name(merge_remote_util(p->item)->name, autogen);
1107 prepare_merge_message(autogen, merge_msg);
1108 strbuf_release(autogen);
1114 int cmd_merge(int argc, const char **argv, const char *prefix)
1116 unsigned char result_tree[20];
1117 unsigned char stash[20];
1118 unsigned char head_sha1[20];
1119 struct commit *head_commit;
1120 struct strbuf buf = STRBUF_INIT;
1121 const char *head_arg;
1122 int i, ret = 0, head_subsumed;
1123 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1124 struct commit_list *common = NULL;
1125 const char *best_strategy = NULL, *wt_strategy = NULL;
1126 struct commit_list *remoteheads, *p;
1127 void *branch_to_free;
1129 if (argc == 2 && !strcmp(argv[1], "-h"))
1130 usage_with_options(builtin_merge_usage, builtin_merge_options);
1133 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1136 branch = branch_to_free = resolve_refdup("HEAD", 0, head_sha1, NULL);
1137 if (branch && starts_with(branch, "refs/heads/"))
1139 if (!branch || is_null_sha1(head_sha1))
1142 head_commit = lookup_commit_or_die(head_sha1, "HEAD");
1144 init_diff_ui_defaults();
1145 git_config(git_merge_config, NULL);
1147 if (branch_mergeoptions)
1148 parse_branch_merge_options(branch_mergeoptions);
1149 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1150 builtin_merge_usage, 0);
1151 if (shortlog_len < 0)
1152 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1154 if (verbosity < 0 && show_progress == -1)
1157 if (abort_current_merge) {
1159 const char *nargv[] = {"reset", "--merge", NULL};
1161 if (!file_exists(git_path_merge_head()))
1162 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1164 /* Invoke 'git reset --merge' */
1165 ret = cmd_reset(nargc, nargv, prefix);
1169 if (read_cache_unmerged())
1170 die_resolve_conflict("merge");
1172 if (file_exists(git_path_merge_head())) {
1174 * There is no unmerged entry, don't advise 'git
1175 * add/rm <file>', just 'git commit'.
1177 if (advice_resolve_conflict)
1178 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1179 "Please, commit your changes before you merge."));
1181 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1183 if (file_exists(git_path_cherry_pick_head())) {
1184 if (advice_resolve_conflict)
1185 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1186 "Please, commit your changes before you merge."));
1188 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1190 resolve_undo_clear();
1196 if (fast_forward == FF_NO)
1197 die(_("You cannot combine --squash with --no-ff."));
1202 if (default_to_upstream)
1203 argc = setup_with_upstream(&argv);
1205 die(_("No commit specified and merge.defaultToUpstream not set."));
1206 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1211 usage_with_options(builtin_merge_usage,
1212 builtin_merge_options);
1216 * If the merged head is a valid one there is no reason
1217 * to forbid "git merge" into a branch yet to be born.
1218 * We do the same for "git pull".
1220 unsigned char *remote_head_sha1;
1222 die(_("Squash commit into empty head not supported yet"));
1223 if (fast_forward == FF_NO)
1224 die(_("Non-fast-forward commit does not make sense into "
1226 remoteheads = collect_parents(head_commit, &head_subsumed,
1229 die(_("%s - not something we can merge"), argv[0]);
1230 if (remoteheads->next)
1231 die(_("Can merge only exactly one commit into empty head"));
1232 remote_head_sha1 = remoteheads->item->object.oid.hash;
1233 read_empty(remote_head_sha1, 0);
1234 update_ref("initial pull", "HEAD", remote_head_sha1,
1235 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1240 * This could be traditional "merge <msg> HEAD <commit>..." and
1241 * the way we can tell it is to see if the second token is HEAD,
1242 * but some people might have misused the interface and used a
1243 * commit-ish that is the same as HEAD there instead.
1244 * Traditional format never would have "-m" so it is an
1245 * additional safety measure to check for it.
1247 if (!have_message &&
1248 is_old_style_invocation(argc, argv, head_commit->object.oid.hash)) {
1249 warning("old-style 'git merge <msg> HEAD <commit>' is deprecated.");
1250 strbuf_addstr(&merge_msg, argv[0]);
1254 remoteheads = collect_parents(head_commit, &head_subsumed,
1257 /* We are invoked directly as the first-class UI. */
1261 * All the rest are the commits being merged; prepare
1262 * the standard merge summary message to be appended
1263 * to the given message.
1265 remoteheads = collect_parents(head_commit, &head_subsumed,
1266 argc, argv, &merge_msg);
1269 if (!head_commit || !argc)
1270 usage_with_options(builtin_merge_usage,
1271 builtin_merge_options);
1273 if (verify_signatures) {
1274 for (p = remoteheads; p; p = p->next) {
1275 struct commit *commit = p->item;
1276 char hex[GIT_SHA1_HEXSZ + 1];
1277 struct signature_check signature_check;
1278 memset(&signature_check, 0, sizeof(signature_check));
1280 check_commit_signature(commit, &signature_check);
1282 find_unique_abbrev_r(hex, commit->object.oid.hash, DEFAULT_ABBREV);
1283 switch (signature_check.result) {
1287 die(_("Commit %s has an untrusted GPG signature, "
1288 "allegedly by %s."), hex, signature_check.signer);
1290 die(_("Commit %s has a bad GPG signature "
1291 "allegedly by %s."), hex, signature_check.signer);
1293 die(_("Commit %s does not have a GPG signature."), hex);
1295 if (verbosity >= 0 && signature_check.result == 'G')
1296 printf(_("Commit %s has a good GPG signature by %s\n"),
1297 hex, signature_check.signer);
1299 signature_check_clear(&signature_check);
1303 strbuf_addstr(&buf, "merge");
1304 for (p = remoteheads; p; p = p->next)
1305 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1306 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1309 for (p = remoteheads; p; p = p->next) {
1310 struct commit *commit = p->item;
1311 strbuf_addf(&buf, "GITHEAD_%s",
1312 oid_to_hex(&commit->object.oid));
1313 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1315 if (fast_forward != FF_ONLY &&
1316 merge_remote_util(commit) &&
1317 merge_remote_util(commit)->obj &&
1318 merge_remote_util(commit)->obj->type == OBJ_TAG)
1319 fast_forward = FF_NO;
1322 if (option_edit < 0)
1323 option_edit = default_edit_option();
1325 if (!use_strategies) {
1327 ; /* already up-to-date */
1328 else if (!remoteheads->next)
1329 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1331 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1334 for (i = 0; i < use_strategies_nr; i++) {
1335 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1336 fast_forward = FF_NO;
1337 if (use_strategies[i]->attr & NO_TRIVIAL)
1342 ; /* already up-to-date */
1343 else if (!remoteheads->next)
1344 common = get_merge_bases(head_commit, remoteheads->item);
1346 struct commit_list *list = remoteheads;
1347 commit_list_insert(head_commit, &list);
1348 common = get_octopus_merge_bases(list);
1352 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.oid.hash,
1353 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1355 if (remoteheads && !common) {
1356 /* No common ancestors found. */
1357 if (!allow_unrelated_histories)
1358 die(_("refusing to merge unrelated histories"));
1359 /* otherwise, we need a real merge. */
1360 } else if (!remoteheads ||
1361 (!remoteheads->next && !common->next &&
1362 common->item == remoteheads->item)) {
1364 * If head can reach all the merge then we are up to date.
1365 * but first the most common case of merging one remote.
1367 finish_up_to_date(_("Already up-to-date."));
1369 } else if (fast_forward != FF_NO && !remoteheads->next &&
1371 !oidcmp(&common->item->object.oid, &head_commit->object.oid)) {
1372 /* Again the most common case of merging one remote. */
1373 struct strbuf msg = STRBUF_INIT;
1374 struct commit *commit;
1376 if (verbosity >= 0) {
1377 char from[GIT_SHA1_HEXSZ + 1], to[GIT_SHA1_HEXSZ + 1];
1378 find_unique_abbrev_r(from, head_commit->object.oid.hash,
1380 find_unique_abbrev_r(to, remoteheads->item->object.oid.hash,
1382 printf(_("Updating %s..%s\n"), from, to);
1384 strbuf_addstr(&msg, "Fast-forward");
1387 " (no commit created; -m option ignored)");
1388 commit = remoteheads->item;
1394 if (checkout_fast_forward(head_commit->object.oid.hash,
1395 commit->object.oid.hash,
1396 overwrite_ignore)) {
1401 finish(head_commit, remoteheads, commit->object.oid.hash, msg.buf);
1404 } else if (!remoteheads->next && common->next)
1407 * We are not doing octopus and not fast-forward. Need
1410 else if (!remoteheads->next && !common->next && option_commit) {
1412 * We are not doing octopus, not fast-forward, and have
1415 refresh_cache(REFRESH_QUIET);
1416 if (allow_trivial && fast_forward != FF_ONLY) {
1417 /* See if it is really trivial. */
1418 git_committer_info(IDENT_STRICT);
1419 printf(_("Trying really trivial in-index merge...\n"));
1420 if (!read_tree_trivial(common->item->object.oid.hash,
1421 head_commit->object.oid.hash,
1422 remoteheads->item->object.oid.hash)) {
1423 ret = merge_trivial(head_commit, remoteheads);
1426 printf(_("Nope.\n"));
1430 * An octopus. If we can reach all the remote we are up
1434 struct commit_list *j;
1436 for (j = remoteheads; j; j = j->next) {
1437 struct commit_list *common_one;
1440 * Here we *have* to calculate the individual
1441 * merge_bases again, otherwise "git merge HEAD^
1442 * HEAD^^" would be missed.
1444 common_one = get_merge_bases(head_commit, j->item);
1445 if (oidcmp(&common_one->item->object.oid, &j->item->object.oid)) {
1451 finish_up_to_date(_("Already up-to-date. Yeeah!"));
1456 if (fast_forward == FF_ONLY)
1457 die(_("Not possible to fast-forward, aborting."));
1459 /* We are going to make a new commit. */
1460 git_committer_info(IDENT_STRICT);
1463 * At this point, we need a real merge. No matter what strategy
1464 * we use, it would operate on the index, possibly affecting the
1465 * working tree, and when resolved cleanly, have the desired
1466 * tree in the index -- this means that the index must be in
1467 * sync with the head commit. The strategies are responsible
1470 if (use_strategies_nr == 1 ||
1472 * Stash away the local changes so that we can try more than one.
1477 for (i = 0; i < use_strategies_nr; i++) {
1480 printf(_("Rewinding the tree to pristine...\n"));
1481 restore_state(head_commit->object.oid.hash, stash);
1483 if (use_strategies_nr != 1)
1484 printf(_("Trying merge strategy %s...\n"),
1485 use_strategies[i]->name);
1487 * Remember which strategy left the state in the working
1490 wt_strategy = use_strategies[i]->name;
1492 ret = try_merge_strategy(use_strategies[i]->name,
1493 common, remoteheads,
1494 head_commit, head_arg);
1495 if (!option_commit && !ret) {
1498 * This is necessary here just to avoid writing
1499 * the tree, but later we will *not* exit with
1500 * status code 1 because merge_was_ok is set.
1507 * The backend exits with 1 when conflicts are
1508 * left to be resolved, with 2 when it does not
1509 * handle the given merge at all.
1512 int cnt = evaluate_result();
1514 if (best_cnt <= 0 || cnt <= best_cnt) {
1515 best_strategy = use_strategies[i]->name;
1525 /* Automerge succeeded. */
1526 write_tree_trivial(result_tree);
1527 automerge_was_ok = 1;
1532 * If we have a resulting tree, that means the strategy module
1533 * auto resolved the merge cleanly.
1535 if (automerge_was_ok) {
1536 ret = finish_automerge(head_commit, head_subsumed,
1537 common, remoteheads,
1538 result_tree, wt_strategy);
1543 * Pick the result from the best strategy and have the user fix
1546 if (!best_strategy) {
1547 restore_state(head_commit->object.oid.hash, stash);
1548 if (use_strategies_nr > 1)
1550 _("No merge strategy handled the merge.\n"));
1552 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1553 use_strategies[0]->name);
1556 } else if (best_strategy == wt_strategy)
1557 ; /* We already have its result in the working tree. */
1559 printf(_("Rewinding the tree to pristine...\n"));
1560 restore_state(head_commit->object.oid.hash, stash);
1561 printf(_("Using the %s to prepare resolving by hand.\n"),
1563 try_merge_strategy(best_strategy, common, remoteheads,
1564 head_commit, head_arg);
1568 finish(head_commit, remoteheads, NULL, NULL);
1570 write_merge_state(remoteheads);
1573 fprintf(stderr, _("Automatic merge went well; "
1574 "stopped before committing as requested\n"));
1576 ret = suggest_conflicts();
1579 free(branch_to_free);