4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
10 #include "parse-options.h"
12 #include "run-command.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
26 #include "merge-recursive.h"
27 #include "resolve-undo.h"
29 #include "fmt-merge-msg.h"
31 #define DEFAULT_TWOHEAD (1<<0)
32 #define DEFAULT_OCTOPUS (1<<1)
33 #define NO_FAST_FORWARD (1<<2)
34 #define NO_TRIVIAL (1<<3)
41 static const char * const builtin_merge_usage[] = {
42 "git merge [options] [<commit>...]",
43 "git merge [options] <msg> HEAD <commit>",
48 static int show_diffstat = 1, shortlog_len = -1, squash;
49 static int option_commit = 1, allow_fast_forward = 1;
50 static int fast_forward_only, option_edit;
51 static int allow_trivial = 1, have_message;
52 static struct strbuf merge_msg;
53 static struct commit_list *remoteheads;
54 static struct strategy **use_strategies;
55 static size_t use_strategies_nr, use_strategies_alloc;
56 static const char **xopts;
57 static size_t xopts_nr, xopts_alloc;
58 static const char *branch;
59 static char *branch_mergeoptions;
60 static int option_renormalize;
62 static int allow_rerere_auto;
63 static int abort_current_merge;
64 static int show_progress = -1;
65 static int default_to_upstream;
67 static struct strategy all_strategy[] = {
68 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
69 { "octopus", DEFAULT_OCTOPUS },
71 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
72 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
75 static const char *pull_twohead, *pull_octopus;
77 static int option_parse_message(const struct option *opt,
78 const char *arg, int unset)
80 struct strbuf *buf = opt->value;
83 strbuf_setlen(buf, 0);
85 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
88 return error(_("switch `m' requires a value"));
92 static struct strategy *get_strategy(const char *name)
96 static struct cmdnames main_cmds, other_cmds;
102 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
103 if (!strcmp(name, all_strategy[i].name))
104 return &all_strategy[i];
107 struct cmdnames not_strategies;
110 memset(¬_strategies, 0, sizeof(struct cmdnames));
111 load_command_list("git-merge-", &main_cmds, &other_cmds);
112 for (i = 0; i < main_cmds.cnt; i++) {
114 struct cmdname *ent = main_cmds.names[i];
115 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
116 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
117 && !all_strategy[j].name[ent->len])
120 add_cmdname(¬_strategies, ent->name, ent->len);
122 exclude_cmds(&main_cmds, ¬_strategies);
124 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
125 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
126 fprintf(stderr, _("Available strategies are:"));
127 for (i = 0; i < main_cmds.cnt; i++)
128 fprintf(stderr, " %s", main_cmds.names[i]->name);
129 fprintf(stderr, ".\n");
130 if (other_cmds.cnt) {
131 fprintf(stderr, _("Available custom strategies are:"));
132 for (i = 0; i < other_cmds.cnt; i++)
133 fprintf(stderr, " %s", other_cmds.names[i]->name);
134 fprintf(stderr, ".\n");
139 ret = xcalloc(1, sizeof(struct strategy));
140 ret->name = xstrdup(name);
141 ret->attr = NO_TRIVIAL;
145 static void append_strategy(struct strategy *s)
147 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
148 use_strategies[use_strategies_nr++] = s;
151 static int option_parse_strategy(const struct option *opt,
152 const char *name, int unset)
157 append_strategy(get_strategy(name));
161 static int option_parse_x(const struct option *opt,
162 const char *arg, int unset)
167 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
168 xopts[xopts_nr++] = xstrdup(arg);
172 static int option_parse_n(const struct option *opt,
173 const char *arg, int unset)
175 show_diffstat = unset;
179 static struct option builtin_merge_options[] = {
180 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
181 "do not show a diffstat at the end of the merge",
182 PARSE_OPT_NOARG, option_parse_n },
183 OPT_BOOLEAN(0, "stat", &show_diffstat,
184 "show a diffstat at the end of the merge"),
185 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
186 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
187 "add (at most <n>) entries from shortlog to merge commit message",
188 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
189 OPT_BOOLEAN(0, "squash", &squash,
190 "create a single commit instead of doing a merge"),
191 OPT_BOOLEAN(0, "commit", &option_commit,
192 "perform a commit if the merge succeeds (default)"),
193 OPT_BOOLEAN('e', "edit", &option_edit,
194 "edit message before committing"),
195 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
196 "allow fast-forward (default)"),
197 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
198 "abort if fast-forward is not possible"),
199 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
200 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
201 "merge strategy to use", option_parse_strategy),
202 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
203 "option for selected merge strategy", option_parse_x),
204 OPT_CALLBACK('m', "message", &merge_msg, "message",
205 "merge commit message (for a non-fast-forward merge)",
206 option_parse_message),
207 OPT__VERBOSITY(&verbosity),
208 OPT_BOOLEAN(0, "abort", &abort_current_merge,
209 "abort the current in-progress merge"),
210 OPT_SET_INT(0, "progress", &show_progress, "force progress reporting", 1),
214 /* Cleans up metadata that is uninteresting after a succeeded merge. */
215 static void drop_save(void)
217 unlink(git_path("MERGE_HEAD"));
218 unlink(git_path("MERGE_MSG"));
219 unlink(git_path("MERGE_MODE"));
222 static int save_state(unsigned char *stash)
225 struct child_process cp;
226 struct strbuf buffer = STRBUF_INIT;
227 const char *argv[] = {"stash", "create", NULL};
229 memset(&cp, 0, sizeof(cp));
234 if (start_command(&cp))
235 die(_("could not run stash."));
236 len = strbuf_read(&buffer, cp.out, 1024);
239 if (finish_command(&cp) || len < 0)
240 die(_("stash failed"));
241 else if (!len) /* no changes */
243 strbuf_setlen(&buffer, buffer.len-1);
244 if (get_sha1(buffer.buf, stash))
245 die(_("not a valid object: %s"), buffer.buf);
249 static void read_empty(unsigned const char *sha1, int verbose)
254 args[i++] = "read-tree";
259 args[i++] = EMPTY_TREE_SHA1_HEX;
260 args[i++] = sha1_to_hex(sha1);
263 if (run_command_v_opt(args, RUN_GIT_CMD))
264 die(_("read-tree failed"));
267 static void reset_hard(unsigned const char *sha1, int verbose)
272 args[i++] = "read-tree";
275 args[i++] = "--reset";
277 args[i++] = sha1_to_hex(sha1);
280 if (run_command_v_opt(args, RUN_GIT_CMD))
281 die(_("read-tree failed"));
284 static void restore_state(const unsigned char *head,
285 const unsigned char *stash)
287 struct strbuf sb = STRBUF_INIT;
288 const char *args[] = { "stash", "apply", NULL, NULL };
290 if (is_null_sha1(stash))
295 args[2] = sha1_to_hex(stash);
298 * It is OK to ignore error here, for example when there was
299 * nothing to restore.
301 run_command_v_opt(args, RUN_GIT_CMD);
304 refresh_cache(REFRESH_QUIET);
307 /* This is called when no merge was necessary. */
308 static void finish_up_to_date(const char *msg)
311 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
315 static void squash_message(struct commit *commit)
318 struct strbuf out = STRBUF_INIT;
319 struct commit_list *j;
320 const char *filename;
322 struct pretty_print_context ctx = {0};
324 printf(_("Squash commit -- not updating HEAD\n"));
325 filename = git_path("SQUASH_MSG");
326 fd = open(filename, O_WRONLY | O_CREAT, 0666);
328 die_errno(_("Could not write to '%s'"), filename);
330 init_revisions(&rev, NULL);
331 rev.ignore_merges = 1;
332 rev.commit_format = CMIT_FMT_MEDIUM;
334 commit->object.flags |= UNINTERESTING;
335 add_pending_object(&rev, &commit->object, NULL);
337 for (j = remoteheads; j; j = j->next)
338 add_pending_object(&rev, &j->item->object, NULL);
340 setup_revisions(0, NULL, &rev, NULL);
341 if (prepare_revision_walk(&rev))
342 die(_("revision walk setup failed"));
344 ctx.abbrev = rev.abbrev;
345 ctx.date_mode = rev.date_mode;
346 ctx.fmt = rev.commit_format;
348 strbuf_addstr(&out, "Squashed commit of the following:\n");
349 while ((commit = get_revision(&rev)) != NULL) {
350 strbuf_addch(&out, '\n');
351 strbuf_addf(&out, "commit %s\n",
352 sha1_to_hex(commit->object.sha1));
353 pretty_print_commit(&ctx, commit, &out);
355 if (write(fd, out.buf, out.len) < 0)
356 die_errno(_("Writing SQUASH_MSG"));
358 die_errno(_("Finishing SQUASH_MSG"));
359 strbuf_release(&out);
362 static void finish(struct commit *head_commit,
363 const unsigned char *new_head, const char *msg)
365 struct strbuf reflog_message = STRBUF_INIT;
366 const unsigned char *head = head_commit->object.sha1;
369 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
373 strbuf_addf(&reflog_message, "%s: %s",
374 getenv("GIT_REFLOG_ACTION"), msg);
377 squash_message(head_commit);
379 if (verbosity >= 0 && !merge_msg.len)
380 printf(_("No merge message -- not updating HEAD\n"));
382 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
383 update_ref(reflog_message.buf, "HEAD",
387 * We ignore errors in 'gc --auto', since the
388 * user should see them.
390 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
393 if (new_head && show_diffstat) {
394 struct diff_options opts;
396 opts.output_format |=
397 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
398 opts.detect_rename = DIFF_DETECT_RENAME;
399 if (diff_setup_done(&opts) < 0)
400 die(_("diff_setup_done failed"));
401 diff_tree_sha1(head, new_head, "", &opts);
406 /* Run a post-merge hook */
407 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
409 strbuf_release(&reflog_message);
412 static struct object *want_commit(const char *name)
415 unsigned char sha1[20];
416 if (get_sha1(name, sha1))
418 obj = parse_object(sha1);
419 return peel_to_type(name, 0, obj, OBJ_COMMIT);
422 /* Get the name for the merge commit's message. */
423 static void merge_name(const char *remote, struct strbuf *msg)
425 struct object *remote_head;
426 unsigned char branch_head[20], buf_sha[20];
427 struct strbuf buf = STRBUF_INIT;
428 struct strbuf bname = STRBUF_INIT;
433 strbuf_branchname(&bname, remote);
436 memset(branch_head, 0, sizeof(branch_head));
437 remote_head = want_commit(remote);
439 die(_("'%s' does not point to a commit"), remote);
441 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
442 if (!prefixcmp(found_ref, "refs/heads/")) {
443 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
444 sha1_to_hex(branch_head), remote);
447 if (!prefixcmp(found_ref, "refs/remotes/")) {
448 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
449 sha1_to_hex(branch_head), remote);
454 /* See if remote matches <name>^^^.. or <name>~<number> */
455 for (len = 0, ptr = remote + strlen(remote);
456 remote < ptr && ptr[-1] == '^';
463 ptr = strrchr(remote, '~');
465 int seen_nonzero = 0;
468 while (*++ptr && isdigit(*ptr)) {
469 seen_nonzero |= (*ptr != '0');
473 len = 0; /* not ...~<number> */
474 else if (seen_nonzero)
477 early = 1; /* "name~" is "name~1"! */
481 struct strbuf truname = STRBUF_INIT;
482 strbuf_addstr(&truname, "refs/heads/");
483 strbuf_addstr(&truname, remote);
484 strbuf_setlen(&truname, truname.len - len);
485 if (resolve_ref(truname.buf, buf_sha, 1, NULL)) {
487 "%s\t\tbranch '%s'%s of .\n",
488 sha1_to_hex(remote_head->sha1),
490 (early ? " (early part)" : ""));
491 strbuf_release(&truname);
496 if (!strcmp(remote, "FETCH_HEAD") &&
497 !access(git_path("FETCH_HEAD"), R_OK)) {
498 const char *filename;
500 struct strbuf line = STRBUF_INIT;
503 filename = git_path("FETCH_HEAD");
504 fp = fopen(filename, "r");
506 die_errno(_("could not open '%s' for reading"),
508 strbuf_getline(&line, fp, '\n');
510 ptr = strstr(line.buf, "\tnot-for-merge\t");
512 strbuf_remove(&line, ptr-line.buf+1, 13);
513 strbuf_addbuf(msg, &line);
514 strbuf_release(&line);
517 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
518 sha1_to_hex(remote_head->sha1), 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 argv = xrealloc(argv, sizeof(*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 && !prefixcmp(k, "branch.") &&
549 !prefixcmp(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 allow_fast_forward = boolval;
568 } else if (v && !strcmp(v, "only")) {
569 allow_fast_forward = 1;
570 fast_forward_only = 1;
571 } /* do not barf on values from future versions of git */
573 } else if (!strcmp(k, "merge.defaulttoupstream")) {
574 default_to_upstream = git_config_bool(k, v);
577 status = fmt_merge_msg_config(k, v, cb);
580 return git_diff_ui_config(k, v, cb);
583 static int read_tree_trivial(unsigned char *common, unsigned char *head,
587 struct tree *trees[MAX_UNPACK_TREES];
588 struct tree_desc t[MAX_UNPACK_TREES];
589 struct unpack_trees_options opts;
591 memset(&opts, 0, sizeof(opts));
593 opts.src_index = &the_index;
594 opts.dst_index = &the_index;
596 opts.verbose_update = 1;
597 opts.trivial_merges_only = 1;
599 trees[nr_trees] = parse_tree_indirect(common);
600 if (!trees[nr_trees++])
602 trees[nr_trees] = parse_tree_indirect(head);
603 if (!trees[nr_trees++])
605 trees[nr_trees] = parse_tree_indirect(one);
606 if (!trees[nr_trees++])
608 opts.fn = threeway_merge;
609 cache_tree_free(&active_cache_tree);
610 for (i = 0; i < nr_trees; i++) {
611 parse_tree(trees[i]);
612 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
614 if (unpack_trees(nr_trees, t, &opts))
619 static void write_tree_trivial(unsigned char *sha1)
621 if (write_cache_as_tree(sha1, 0, NULL))
622 die(_("git write-tree failed to write a tree"));
625 static const char *merge_argument(struct commit *commit)
628 return sha1_to_hex(commit->object.sha1);
630 return EMPTY_TREE_SHA1_HEX;
633 int try_merge_command(const char *strategy, size_t xopts_nr,
634 const char **xopts, struct commit_list *common,
635 const char *head_arg, struct commit_list *remotes)
638 int i = 0, x = 0, ret;
639 struct commit_list *j;
640 struct strbuf buf = STRBUF_INIT;
642 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
643 commit_list_count(remotes)) * sizeof(char *));
644 strbuf_addf(&buf, "merge-%s", strategy);
646 for (x = 0; x < xopts_nr; x++) {
647 char *s = xmalloc(strlen(xopts[x])+2+1);
649 strcpy(s+2, xopts[x]);
652 for (j = common; j; j = j->next)
653 args[i++] = xstrdup(merge_argument(j->item));
655 args[i++] = head_arg;
656 for (j = remotes; j; j = j->next)
657 args[i++] = xstrdup(merge_argument(j->item));
659 ret = run_command_v_opt(args, RUN_GIT_CMD);
660 strbuf_release(&buf);
662 for (x = 0; x < xopts_nr; x++)
663 free((void *)args[i++]);
664 for (j = common; j; j = j->next)
665 free((void *)args[i++]);
667 for (j = remotes; j; j = j->next)
668 free((void *)args[i++]);
671 if (read_cache() < 0)
672 die(_("failed to read the cache"));
673 resolve_undo_clear();
678 static int try_merge_strategy(const char *strategy, struct commit_list *common,
679 struct commit *head, const char *head_arg)
682 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
684 index_fd = hold_locked_index(lock, 1);
685 refresh_cache(REFRESH_QUIET);
686 if (active_cache_changed &&
687 (write_cache(index_fd, active_cache, active_nr) ||
688 commit_locked_index(lock)))
689 return error(_("Unable to write index."));
690 rollback_lock_file(lock);
692 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
694 struct commit *result;
695 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
697 struct commit_list *reversed = NULL;
698 struct merge_options o;
699 struct commit_list *j;
701 if (remoteheads->next) {
702 error(_("Not handling anything other than two heads merge."));
706 init_merge_options(&o);
707 if (!strcmp(strategy, "subtree"))
708 o.subtree_shift = "";
710 o.renormalize = option_renormalize;
711 o.show_rename_progress =
712 show_progress == -1 ? isatty(2) : show_progress;
714 for (x = 0; x < xopts_nr; x++)
715 if (parse_merge_opt(&o, xopts[x]))
716 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
718 o.branch1 = head_arg;
719 o.branch2 = remoteheads->item->util;
721 for (j = common; j; j = j->next)
722 commit_list_insert(j->item, &reversed);
724 index_fd = hold_locked_index(lock, 1);
725 clean = merge_recursive(&o, head,
726 remoteheads->item, reversed, &result);
727 if (active_cache_changed &&
728 (write_cache(index_fd, active_cache, active_nr) ||
729 commit_locked_index(lock)))
730 die (_("unable to write %s"), get_index_file());
731 rollback_lock_file(lock);
732 return clean ? 0 : 1;
734 return try_merge_command(strategy, xopts_nr, xopts,
735 common, head_arg, remoteheads);
739 static void count_diff_files(struct diff_queue_struct *q,
740 struct diff_options *opt, void *data)
747 static int count_unmerged_entries(void)
751 for (i = 0; i < active_nr; i++)
752 if (ce_stage(active_cache[i]))
758 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
760 struct tree *trees[MAX_UNPACK_TREES];
761 struct unpack_trees_options opts;
762 struct tree_desc t[MAX_UNPACK_TREES];
763 int i, fd, nr_trees = 0;
764 struct dir_struct dir;
765 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
767 refresh_cache(REFRESH_QUIET);
769 fd = hold_locked_index(lock_file, 1);
771 memset(&trees, 0, sizeof(trees));
772 memset(&opts, 0, sizeof(opts));
773 memset(&t, 0, sizeof(t));
774 memset(&dir, 0, sizeof(dir));
775 dir.flags |= DIR_SHOW_IGNORED;
776 setup_standard_excludes(&dir);
780 opts.src_index = &the_index;
781 opts.dst_index = &the_index;
783 opts.verbose_update = 1;
785 opts.fn = twoway_merge;
786 setup_unpack_trees_porcelain(&opts, "merge");
788 trees[nr_trees] = parse_tree_indirect(head);
789 if (!trees[nr_trees++])
791 trees[nr_trees] = parse_tree_indirect(remote);
792 if (!trees[nr_trees++])
794 for (i = 0; i < nr_trees; i++) {
795 parse_tree(trees[i]);
796 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
798 if (unpack_trees(nr_trees, t, &opts))
800 if (write_cache(fd, active_cache, active_nr) ||
801 commit_locked_index(lock_file))
802 die(_("unable to write new index file"));
806 static void split_merge_strategies(const char *string, struct strategy **list,
814 buf = xstrdup(string);
819 ALLOC_GROW(*list, *nr + 1, *alloc);
820 (*list)[(*nr)++].name = xstrdup(q);
825 ALLOC_GROW(*list, *nr + 1, *alloc);
826 (*list)[(*nr)++].name = xstrdup(q);
832 static void add_strategies(const char *string, unsigned attr)
834 struct strategy *list = NULL;
835 int list_alloc = 0, list_nr = 0, i;
837 memset(&list, 0, sizeof(list));
838 split_merge_strategies(string, &list, &list_nr, &list_alloc);
840 for (i = 0; i < list_nr; i++)
841 append_strategy(get_strategy(list[i].name));
844 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
845 if (all_strategy[i].attr & attr)
846 append_strategy(&all_strategy[i]);
850 static void write_merge_msg(struct strbuf *msg)
852 const char *filename = git_path("MERGE_MSG");
853 int fd = open(filename, O_WRONLY | O_CREAT, 0666);
855 die_errno(_("Could not open '%s' for writing"),
857 if (write_in_full(fd, msg->buf, msg->len) != msg->len)
858 die_errno(_("Could not write to '%s'"), filename);
862 static void read_merge_msg(struct strbuf *msg)
864 const char *filename = git_path("MERGE_MSG");
866 if (strbuf_read_file(msg, filename, 0) < 0)
867 die_errno(_("Could not read from '%s'"), filename);
870 static void write_merge_state(void);
871 static void abort_commit(const char *err_msg)
874 error("%s", err_msg);
876 _("Not committing merge; use 'git commit' to complete the merge.\n"));
881 static void prepare_to_commit(void)
883 struct strbuf msg = STRBUF_INIT;
884 strbuf_addbuf(&msg, &merge_msg);
885 strbuf_addch(&msg, '\n');
886 write_merge_msg(&msg);
887 run_hook(get_index_file(), "prepare-commit-msg",
888 git_path("MERGE_MSG"), "merge", NULL, NULL);
890 if (launch_editor(git_path("MERGE_MSG"), NULL, NULL))
893 read_merge_msg(&msg);
894 stripspace(&msg, option_edit);
896 abort_commit(_("Empty commit message."));
897 strbuf_release(&merge_msg);
898 strbuf_addbuf(&merge_msg, &msg);
899 strbuf_release(&msg);
902 static int merge_trivial(struct commit *head)
904 unsigned char result_tree[20], result_commit[20];
905 struct commit_list *parent = xmalloc(sizeof(*parent));
907 write_tree_trivial(result_tree);
908 printf(_("Wonderful.\n"));
910 parent->next = xmalloc(sizeof(*parent->next));
911 parent->next->item = remoteheads->item;
912 parent->next->next = NULL;
914 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
915 finish(head, result_commit, "In-index merge");
920 static int finish_automerge(struct commit *head,
921 struct commit_list *common,
922 unsigned char *result_tree,
923 const char *wt_strategy)
925 struct commit_list *parents = NULL, *j;
926 struct strbuf buf = STRBUF_INIT;
927 unsigned char result_commit[20];
929 free_commit_list(common);
930 if (allow_fast_forward) {
931 parents = remoteheads;
932 commit_list_insert(head, &parents);
933 parents = reduce_heads(parents);
935 struct commit_list **pptr = &parents;
937 pptr = &commit_list_insert(head,
939 for (j = remoteheads; j; j = j->next)
940 pptr = &commit_list_insert(j->item, pptr)->next;
942 strbuf_addch(&merge_msg, '\n');
944 free_commit_list(remoteheads);
945 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
946 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
947 finish(head, result_commit, buf.buf);
948 strbuf_release(&buf);
953 static int suggest_conflicts(int renormalizing)
955 const char *filename;
959 filename = git_path("MERGE_MSG");
960 fp = fopen(filename, "a");
962 die_errno(_("Could not open '%s' for writing"), filename);
963 fprintf(fp, "\nConflicts:\n");
964 for (pos = 0; pos < active_nr; pos++) {
965 struct cache_entry *ce = active_cache[pos];
968 fprintf(fp, "\t%s\n", ce->name);
969 while (pos + 1 < active_nr &&
971 active_cache[pos + 1]->name))
976 rerere(allow_rerere_auto);
977 printf(_("Automatic merge failed; "
978 "fix conflicts and then commit the result.\n"));
982 static struct commit *is_old_style_invocation(int argc, const char **argv,
983 const unsigned char *head)
985 struct commit *second_token = NULL;
987 unsigned char second_sha1[20];
989 if (get_sha1(argv[1], second_sha1))
991 second_token = lookup_commit_reference_gently(second_sha1, 0);
993 die(_("'%s' is not a commit"), argv[1]);
994 if (hashcmp(second_token->object.sha1, head))
1000 static int evaluate_result(void)
1003 struct rev_info rev;
1005 /* Check how many files differ. */
1006 init_revisions(&rev, "");
1007 setup_revisions(0, NULL, &rev, NULL);
1008 rev.diffopt.output_format |=
1009 DIFF_FORMAT_CALLBACK;
1010 rev.diffopt.format_callback = count_diff_files;
1011 rev.diffopt.format_callback_data = &cnt;
1012 run_diff_files(&rev, 0);
1015 * Check how many unmerged entries are
1018 cnt += count_unmerged_entries();
1024 * Pretend as if the user told us to merge with the tracking
1025 * branch we have for the upstream of the current branch
1027 static int setup_with_upstream(const char ***argv)
1029 struct branch *branch = branch_get(NULL);
1034 die(_("No current branch."));
1035 if (!branch->remote)
1036 die(_("No remote for the current branch."));
1037 if (!branch->merge_nr)
1038 die(_("No default upstream defined for the current branch."));
1040 args = xcalloc(branch->merge_nr + 1, sizeof(char *));
1041 for (i = 0; i < branch->merge_nr; i++) {
1042 if (!branch->merge[i]->dst)
1043 die(_("No remote tracking branch for %s from %s"),
1044 branch->merge[i]->src, branch->remote_name);
1045 args[i] = branch->merge[i]->dst;
1052 static void write_merge_state(void)
1054 const char *filename;
1056 struct commit_list *j;
1057 struct strbuf buf = STRBUF_INIT;
1059 for (j = remoteheads; j; j = j->next)
1060 strbuf_addf(&buf, "%s\n",
1061 sha1_to_hex(j->item->object.sha1));
1062 filename = git_path("MERGE_HEAD");
1063 fd = open(filename, O_WRONLY | O_CREAT, 0666);
1065 die_errno(_("Could not open '%s' for writing"), filename);
1066 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1067 die_errno(_("Could not write to '%s'"), filename);
1069 strbuf_addch(&merge_msg, '\n');
1070 write_merge_msg(&merge_msg);
1072 filename = git_path("MERGE_MODE");
1073 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
1075 die_errno(_("Could not open '%s' for writing"), filename);
1077 if (!allow_fast_forward)
1078 strbuf_addf(&buf, "no-ff");
1079 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1080 die_errno(_("Could not write to '%s'"), filename);
1084 int cmd_merge(int argc, const char **argv, const char *prefix)
1086 unsigned char result_tree[20];
1087 unsigned char stash[20];
1088 unsigned char head_sha1[20];
1089 struct commit *head_commit;
1090 struct strbuf buf = STRBUF_INIT;
1091 const char *head_arg;
1093 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1094 struct commit_list *common = NULL;
1095 const char *best_strategy = NULL, *wt_strategy = NULL;
1096 struct commit_list **remotes = &remoteheads;
1098 if (argc == 2 && !strcmp(argv[1], "-h"))
1099 usage_with_options(builtin_merge_usage, builtin_merge_options);
1102 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1105 branch = resolve_ref("HEAD", head_sha1, 0, &flag);
1106 if (branch && !prefixcmp(branch, "refs/heads/"))
1108 if (!branch || is_null_sha1(head_sha1))
1111 head_commit = lookup_commit_or_die(head_sha1, "HEAD");
1113 git_config(git_merge_config, NULL);
1115 if (branch_mergeoptions)
1116 parse_branch_merge_options(branch_mergeoptions);
1117 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1118 builtin_merge_usage, 0);
1119 if (shortlog_len < 0)
1120 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1122 if (verbosity < 0 && show_progress == -1)
1125 if (abort_current_merge) {
1127 const char *nargv[] = {"reset", "--merge", NULL};
1129 if (!file_exists(git_path("MERGE_HEAD")))
1130 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1132 /* Invoke 'git reset --merge' */
1133 return cmd_reset(nargc, nargv, prefix);
1136 if (read_cache_unmerged())
1137 die_resolve_conflict("merge");
1139 if (file_exists(git_path("MERGE_HEAD"))) {
1141 * There is no unmerged entry, don't advise 'git
1142 * add/rm <file>', just 'git commit'.
1144 if (advice_resolve_conflict)
1145 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1146 "Please, commit your changes before you can merge."));
1148 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1150 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1151 if (advice_resolve_conflict)
1152 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1153 "Please, commit your changes before you can merge."));
1155 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1157 resolve_undo_clear();
1163 if (!allow_fast_forward)
1164 die(_("You cannot combine --squash with --no-ff."));
1168 if (!allow_fast_forward && fast_forward_only)
1169 die(_("You cannot combine --no-ff with --ff-only."));
1171 if (!abort_current_merge) {
1173 if (default_to_upstream)
1174 argc = setup_with_upstream(&argv);
1176 die(_("No commit specified and merge.defaultToUpstream not set."));
1177 } else if (argc == 1 && !strcmp(argv[0], "-"))
1181 usage_with_options(builtin_merge_usage,
1182 builtin_merge_options);
1185 * This could be traditional "merge <msg> HEAD <commit>..." and
1186 * the way we can tell it is to see if the second token is HEAD,
1187 * but some people might have misused the interface and used a
1188 * committish that is the same as HEAD there instead.
1189 * Traditional format never would have "-m" so it is an
1190 * additional safety measure to check for it.
1193 if (!have_message && head_commit &&
1194 is_old_style_invocation(argc, argv, head_commit->object.sha1)) {
1195 strbuf_addstr(&merge_msg, argv[0]);
1199 } else if (!head_commit) {
1200 struct object *remote_head;
1202 * If the merged head is a valid one there is no reason
1203 * to forbid "git merge" into a branch yet to be born.
1204 * We do the same for "git pull".
1207 die(_("Can merge only exactly one commit into "
1210 die(_("Squash commit into empty head not supported yet"));
1211 if (!allow_fast_forward)
1212 die(_("Non-fast-forward commit does not make sense into "
1214 remote_head = want_commit(argv[0]);
1216 die(_("%s - not something we can merge"), argv[0]);
1217 read_empty(remote_head->sha1, 0);
1218 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
1222 struct strbuf merge_names = STRBUF_INIT;
1224 /* We are invoked directly as the first-class UI. */
1228 * All the rest are the commits being merged;
1229 * prepare the standard merge summary message to
1230 * be appended to the given message. If remote
1231 * is invalid we will die later in the common
1232 * codepath so we discard the error in this
1235 for (i = 0; i < argc; i++)
1236 merge_name(argv[i], &merge_names);
1238 if (!have_message || shortlog_len) {
1239 fmt_merge_msg(&merge_names, &merge_msg, !have_message,
1242 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1246 if (!head_commit || !argc)
1247 usage_with_options(builtin_merge_usage,
1248 builtin_merge_options);
1250 strbuf_addstr(&buf, "merge");
1251 for (i = 0; i < argc; i++)
1252 strbuf_addf(&buf, " %s", argv[i]);
1253 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1256 for (i = 0; i < argc; i++) {
1258 struct commit *commit;
1260 o = want_commit(argv[i]);
1262 die(_("%s - not something we can merge"), argv[i]);
1263 commit = lookup_commit(o->sha1);
1264 commit->util = (void *)argv[i];
1265 remotes = &commit_list_insert(commit, remotes)->next;
1267 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1268 setenv(buf.buf, argv[i], 1);
1272 if (!use_strategies) {
1273 if (!remoteheads->next)
1274 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1276 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1279 for (i = 0; i < use_strategies_nr; i++) {
1280 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1281 allow_fast_forward = 0;
1282 if (use_strategies[i]->attr & NO_TRIVIAL)
1286 if (!remoteheads->next)
1287 common = get_merge_bases(head_commit, remoteheads->item, 1);
1289 struct commit_list *list = remoteheads;
1290 commit_list_insert(head_commit, &list);
1291 common = get_octopus_merge_bases(list);
1295 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.sha1,
1296 NULL, 0, DIE_ON_ERR);
1299 ; /* No common ancestors found. We need a real merge. */
1300 else if (!remoteheads->next && !common->next &&
1301 common->item == remoteheads->item) {
1303 * If head can reach all the merge then we are up to date.
1304 * but first the most common case of merging one remote.
1306 finish_up_to_date("Already up-to-date.");
1308 } else if (allow_fast_forward && !remoteheads->next &&
1310 !hashcmp(common->item->object.sha1, head_commit->object.sha1)) {
1311 /* Again the most common case of merging one remote. */
1312 struct strbuf msg = STRBUF_INIT;
1316 strcpy(hex, find_unique_abbrev(head_commit->object.sha1, DEFAULT_ABBREV));
1319 printf(_("Updating %s..%s\n"),
1321 find_unique_abbrev(remoteheads->item->object.sha1,
1323 strbuf_addstr(&msg, "Fast-forward");
1326 " (no commit created; -m option ignored)");
1327 o = want_commit(sha1_to_hex(remoteheads->item->object.sha1));
1331 if (checkout_fast_forward(head_commit->object.sha1, remoteheads->item->object.sha1))
1334 finish(head_commit, o->sha1, msg.buf);
1337 } else if (!remoteheads->next && common->next)
1340 * We are not doing octopus and not fast-forward. Need
1343 else if (!remoteheads->next && !common->next && option_commit) {
1345 * We are not doing octopus, not fast-forward, and have
1348 refresh_cache(REFRESH_QUIET);
1349 if (allow_trivial && !fast_forward_only) {
1350 /* See if it is really trivial. */
1351 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1352 printf(_("Trying really trivial in-index merge...\n"));
1353 if (!read_tree_trivial(common->item->object.sha1,
1354 head_commit->object.sha1, remoteheads->item->object.sha1))
1355 return merge_trivial(head_commit);
1356 printf(_("Nope.\n"));
1360 * An octopus. If we can reach all the remote we are up
1364 struct commit_list *j;
1366 for (j = remoteheads; j; j = j->next) {
1367 struct commit_list *common_one;
1370 * Here we *have* to calculate the individual
1371 * merge_bases again, otherwise "git merge HEAD^
1372 * HEAD^^" would be missed.
1374 common_one = get_merge_bases(head_commit, j->item, 1);
1375 if (hashcmp(common_one->item->object.sha1,
1376 j->item->object.sha1)) {
1382 finish_up_to_date("Already up-to-date. Yeeah!");
1387 if (fast_forward_only)
1388 die(_("Not possible to fast-forward, aborting."));
1390 /* We are going to make a new commit. */
1391 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1394 * At this point, we need a real merge. No matter what strategy
1395 * we use, it would operate on the index, possibly affecting the
1396 * working tree, and when resolved cleanly, have the desired
1397 * tree in the index -- this means that the index must be in
1398 * sync with the head commit. The strategies are responsible
1401 if (use_strategies_nr == 1 ||
1403 * Stash away the local changes so that we can try more than one.
1406 hashcpy(stash, null_sha1);
1408 for (i = 0; i < use_strategies_nr; i++) {
1411 printf(_("Rewinding the tree to pristine...\n"));
1412 restore_state(head_commit->object.sha1, stash);
1414 if (use_strategies_nr != 1)
1415 printf(_("Trying merge strategy %s...\n"),
1416 use_strategies[i]->name);
1418 * Remember which strategy left the state in the working
1421 wt_strategy = use_strategies[i]->name;
1423 ret = try_merge_strategy(use_strategies[i]->name,
1424 common, head_commit, head_arg);
1425 if (!option_commit && !ret) {
1428 * This is necessary here just to avoid writing
1429 * the tree, but later we will *not* exit with
1430 * status code 1 because merge_was_ok is set.
1437 * The backend exits with 1 when conflicts are
1438 * left to be resolved, with 2 when it does not
1439 * handle the given merge at all.
1442 int cnt = evaluate_result();
1444 if (best_cnt <= 0 || cnt <= best_cnt) {
1445 best_strategy = use_strategies[i]->name;
1455 /* Automerge succeeded. */
1456 write_tree_trivial(result_tree);
1457 automerge_was_ok = 1;
1462 * If we have a resulting tree, that means the strategy module
1463 * auto resolved the merge cleanly.
1465 if (automerge_was_ok)
1466 return finish_automerge(head_commit, common, result_tree,
1470 * Pick the result from the best strategy and have the user fix
1473 if (!best_strategy) {
1474 restore_state(head_commit->object.sha1, stash);
1475 if (use_strategies_nr > 1)
1477 _("No merge strategy handled the merge.\n"));
1479 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1480 use_strategies[0]->name);
1482 } else if (best_strategy == wt_strategy)
1483 ; /* We already have its result in the working tree. */
1485 printf(_("Rewinding the tree to pristine...\n"));
1486 restore_state(head_commit->object.sha1, stash);
1487 printf(_("Using the %s to prepare resolving by hand.\n"),
1489 try_merge_strategy(best_strategy, common, head_commit, head_arg);
1493 finish(head_commit, NULL, NULL);
1495 write_merge_state();
1498 fprintf(stderr, _("Automatic merge went well; "
1499 "stopped before committing as requested\n"));
1502 return suggest_conflicts(option_renormalize);