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"
30 #define DEFAULT_TWOHEAD (1<<0)
31 #define DEFAULT_OCTOPUS (1<<1)
32 #define NO_FAST_FORWARD (1<<2)
33 #define NO_TRIVIAL (1<<3)
40 static const char * const builtin_merge_usage[] = {
41 "git merge [options] [<commit>...]",
42 "git merge [options] <msg> HEAD <commit>",
47 static int show_diffstat = 1, shortlog_len, squash;
48 static int option_commit = 1, allow_fast_forward = 1;
49 static int fast_forward_only, option_edit;
50 static int allow_trivial = 1, have_message;
51 static struct strbuf merge_msg;
52 static struct commit_list *remoteheads;
53 static struct strategy **use_strategies;
54 static size_t use_strategies_nr, use_strategies_alloc;
55 static const char **xopts;
56 static size_t xopts_nr, xopts_alloc;
57 static const char *branch;
58 static char *branch_mergeoptions;
59 static int option_renormalize;
61 static int allow_rerere_auto;
62 static int abort_current_merge;
63 static int show_progress = -1;
64 static int default_to_upstream;
66 static struct strategy all_strategy[] = {
67 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
68 { "octopus", DEFAULT_OCTOPUS },
70 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
71 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
74 static const char *pull_twohead, *pull_octopus;
76 static int option_parse_message(const struct option *opt,
77 const char *arg, int unset)
79 struct strbuf *buf = opt->value;
82 strbuf_setlen(buf, 0);
84 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
87 return error(_("switch `m' requires a value"));
91 static struct strategy *get_strategy(const char *name)
95 static struct cmdnames main_cmds, other_cmds;
101 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
102 if (!strcmp(name, all_strategy[i].name))
103 return &all_strategy[i];
106 struct cmdnames not_strategies;
109 memset(¬_strategies, 0, sizeof(struct cmdnames));
110 load_command_list("git-merge-", &main_cmds, &other_cmds);
111 for (i = 0; i < main_cmds.cnt; i++) {
113 struct cmdname *ent = main_cmds.names[i];
114 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
115 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
116 && !all_strategy[j].name[ent->len])
119 add_cmdname(¬_strategies, ent->name, ent->len);
121 exclude_cmds(&main_cmds, ¬_strategies);
123 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
124 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
125 fprintf(stderr, _("Available strategies are:"));
126 for (i = 0; i < main_cmds.cnt; i++)
127 fprintf(stderr, " %s", main_cmds.names[i]->name);
128 fprintf(stderr, ".\n");
129 if (other_cmds.cnt) {
130 fprintf(stderr, _("Available custom strategies are:"));
131 for (i = 0; i < other_cmds.cnt; i++)
132 fprintf(stderr, " %s", other_cmds.names[i]->name);
133 fprintf(stderr, ".\n");
138 ret = xcalloc(1, sizeof(struct strategy));
139 ret->name = xstrdup(name);
140 ret->attr = NO_TRIVIAL;
144 static void append_strategy(struct strategy *s)
146 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
147 use_strategies[use_strategies_nr++] = s;
150 static int option_parse_strategy(const struct option *opt,
151 const char *name, int unset)
156 append_strategy(get_strategy(name));
160 static int option_parse_x(const struct option *opt,
161 const char *arg, int unset)
166 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
167 xopts[xopts_nr++] = xstrdup(arg);
171 static int option_parse_n(const struct option *opt,
172 const char *arg, int unset)
174 show_diffstat = unset;
178 static struct option builtin_merge_options[] = {
179 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
180 "do not show a diffstat at the end of the merge",
181 PARSE_OPT_NOARG, option_parse_n },
182 OPT_BOOLEAN(0, "stat", &show_diffstat,
183 "show a diffstat at the end of the merge"),
184 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
185 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
186 "add (at most <n>) entries from shortlog to merge commit message",
187 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
188 OPT_BOOLEAN(0, "squash", &squash,
189 "create a single commit instead of doing a merge"),
190 OPT_BOOLEAN(0, "commit", &option_commit,
191 "perform a commit if the merge succeeds (default)"),
192 OPT_BOOLEAN('e', "edit", &option_edit,
193 "edit message before committing"),
194 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
195 "allow fast-forward (default)"),
196 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
197 "abort if fast-forward is not possible"),
198 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
199 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
200 "merge strategy to use", option_parse_strategy),
201 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
202 "option for selected merge strategy", option_parse_x),
203 OPT_CALLBACK('m', "message", &merge_msg, "message",
204 "merge commit message (for a non-fast-forward merge)",
205 option_parse_message),
206 OPT__VERBOSITY(&verbosity),
207 OPT_BOOLEAN(0, "abort", &abort_current_merge,
208 "abort the current in-progress merge"),
209 OPT_SET_INT(0, "progress", &show_progress, "force progress reporting", 1),
213 /* Cleans up metadata that is uninteresting after a succeeded merge. */
214 static void drop_save(void)
216 unlink(git_path("MERGE_HEAD"));
217 unlink(git_path("MERGE_MSG"));
218 unlink(git_path("MERGE_MODE"));
221 static int save_state(unsigned char *stash)
224 struct child_process cp;
225 struct strbuf buffer = STRBUF_INIT;
226 const char *argv[] = {"stash", "create", NULL};
228 memset(&cp, 0, sizeof(cp));
233 if (start_command(&cp))
234 die(_("could not run stash."));
235 len = strbuf_read(&buffer, cp.out, 1024);
238 if (finish_command(&cp) || len < 0)
239 die(_("stash failed"));
240 else if (!len) /* no changes */
242 strbuf_setlen(&buffer, buffer.len-1);
243 if (get_sha1(buffer.buf, stash))
244 die(_("not a valid object: %s"), buffer.buf);
248 static void read_empty(unsigned const char *sha1, int verbose)
253 args[i++] = "read-tree";
258 args[i++] = EMPTY_TREE_SHA1_HEX;
259 args[i++] = sha1_to_hex(sha1);
262 if (run_command_v_opt(args, RUN_GIT_CMD))
263 die(_("read-tree failed"));
266 static void reset_hard(unsigned const char *sha1, int verbose)
271 args[i++] = "read-tree";
274 args[i++] = "--reset";
276 args[i++] = sha1_to_hex(sha1);
279 if (run_command_v_opt(args, RUN_GIT_CMD))
280 die(_("read-tree failed"));
283 static void restore_state(const unsigned char *head,
284 const unsigned char *stash)
286 struct strbuf sb = STRBUF_INIT;
287 const char *args[] = { "stash", "apply", NULL, NULL };
289 if (is_null_sha1(stash))
294 args[2] = sha1_to_hex(stash);
297 * It is OK to ignore error here, for example when there was
298 * nothing to restore.
300 run_command_v_opt(args, RUN_GIT_CMD);
303 refresh_cache(REFRESH_QUIET);
306 /* This is called when no merge was necessary. */
307 static void finish_up_to_date(const char *msg)
310 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
314 static void squash_message(struct commit *commit)
317 struct strbuf out = STRBUF_INIT;
318 struct commit_list *j;
320 struct pretty_print_context ctx = {0};
322 printf(_("Squash commit -- not updating HEAD\n"));
323 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
325 die_errno(_("Could not write to '%s'"), git_path("SQUASH_MSG"));
327 init_revisions(&rev, NULL);
328 rev.ignore_merges = 1;
329 rev.commit_format = CMIT_FMT_MEDIUM;
331 commit->object.flags |= UNINTERESTING;
332 add_pending_object(&rev, &commit->object, NULL);
334 for (j = remoteheads; j; j = j->next)
335 add_pending_object(&rev, &j->item->object, NULL);
337 setup_revisions(0, NULL, &rev, NULL);
338 if (prepare_revision_walk(&rev))
339 die(_("revision walk setup failed"));
341 ctx.abbrev = rev.abbrev;
342 ctx.date_mode = rev.date_mode;
343 ctx.fmt = rev.commit_format;
345 strbuf_addstr(&out, "Squashed commit of the following:\n");
346 while ((commit = get_revision(&rev)) != NULL) {
347 strbuf_addch(&out, '\n');
348 strbuf_addf(&out, "commit %s\n",
349 sha1_to_hex(commit->object.sha1));
350 pretty_print_commit(&ctx, commit, &out);
352 if (write(fd, out.buf, out.len) < 0)
353 die_errno(_("Writing SQUASH_MSG"));
355 die_errno(_("Finishing SQUASH_MSG"));
356 strbuf_release(&out);
359 static void finish(struct commit *head_commit,
360 const unsigned char *new_head, const char *msg)
362 struct strbuf reflog_message = STRBUF_INIT;
363 const unsigned char *head = head_commit->object.sha1;
366 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
370 strbuf_addf(&reflog_message, "%s: %s",
371 getenv("GIT_REFLOG_ACTION"), msg);
374 squash_message(head_commit);
376 if (verbosity >= 0 && !merge_msg.len)
377 printf(_("No merge message -- not updating HEAD\n"));
379 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
380 update_ref(reflog_message.buf, "HEAD",
384 * We ignore errors in 'gc --auto', since the
385 * user should see them.
387 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
390 if (new_head && show_diffstat) {
391 struct diff_options opts;
393 opts.output_format |=
394 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
395 opts.detect_rename = DIFF_DETECT_RENAME;
396 if (diff_setup_done(&opts) < 0)
397 die(_("diff_setup_done failed"));
398 diff_tree_sha1(head, new_head, "", &opts);
403 /* Run a post-merge hook */
404 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
406 strbuf_release(&reflog_message);
409 static struct object *want_commit(const char *name)
412 unsigned char sha1[20];
413 if (get_sha1(name, sha1))
415 obj = parse_object(sha1);
416 return peel_to_type(name, 0, obj, OBJ_COMMIT);
419 /* Get the name for the merge commit's message. */
420 static void merge_name(const char *remote, struct strbuf *msg)
422 struct object *remote_head;
423 unsigned char branch_head[20], buf_sha[20];
424 struct strbuf buf = STRBUF_INIT;
425 struct strbuf bname = STRBUF_INIT;
430 strbuf_branchname(&bname, remote);
433 memset(branch_head, 0, sizeof(branch_head));
434 remote_head = want_commit(remote);
436 die(_("'%s' does not point to a commit"), remote);
438 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
439 if (!prefixcmp(found_ref, "refs/heads/")) {
440 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
441 sha1_to_hex(branch_head), remote);
444 if (!prefixcmp(found_ref, "refs/tags/")) {
445 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
446 sha1_to_hex(branch_head), remote);
449 if (!prefixcmp(found_ref, "refs/remotes/")) {
450 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
451 sha1_to_hex(branch_head), remote);
456 /* See if remote matches <name>^^^.. or <name>~<number> */
457 for (len = 0, ptr = remote + strlen(remote);
458 remote < ptr && ptr[-1] == '^';
465 ptr = strrchr(remote, '~');
467 int seen_nonzero = 0;
470 while (*++ptr && isdigit(*ptr)) {
471 seen_nonzero |= (*ptr != '0');
475 len = 0; /* not ...~<number> */
476 else if (seen_nonzero)
479 early = 1; /* "name~" is "name~1"! */
483 struct strbuf truname = STRBUF_INIT;
484 strbuf_addstr(&truname, "refs/heads/");
485 strbuf_addstr(&truname, remote);
486 strbuf_setlen(&truname, truname.len - len);
487 if (resolve_ref(truname.buf, buf_sha, 1, NULL)) {
489 "%s\t\tbranch '%s'%s of .\n",
490 sha1_to_hex(remote_head->sha1),
492 (early ? " (early part)" : ""));
493 strbuf_release(&truname);
498 if (!strcmp(remote, "FETCH_HEAD") &&
499 !access(git_path("FETCH_HEAD"), R_OK)) {
501 struct strbuf line = STRBUF_INIT;
504 fp = fopen(git_path("FETCH_HEAD"), "r");
506 die_errno(_("could not open '%s' for reading"),
507 git_path("FETCH_HEAD"));
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)
546 if (branch && !prefixcmp(k, "branch.") &&
547 !prefixcmp(k + 7, branch) &&
548 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
549 free(branch_mergeoptions);
550 branch_mergeoptions = xstrdup(v);
554 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
555 show_diffstat = git_config_bool(k, v);
556 else if (!strcmp(k, "pull.twohead"))
557 return git_config_string(&pull_twohead, k, v);
558 else if (!strcmp(k, "pull.octopus"))
559 return git_config_string(&pull_octopus, k, v);
560 else if (!strcmp(k, "merge.renormalize"))
561 option_renormalize = git_config_bool(k, v);
562 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary")) {
564 shortlog_len = git_config_bool_or_int(k, v, &is_bool);
565 if (!is_bool && shortlog_len < 0)
566 return error(_("%s: negative length %s"), k, v);
567 if (is_bool && shortlog_len)
568 shortlog_len = DEFAULT_MERGE_LOG_LEN;
570 } else if (!strcmp(k, "merge.ff")) {
571 int boolval = git_config_maybe_bool(k, v);
573 allow_fast_forward = boolval;
574 } else if (v && !strcmp(v, "only")) {
575 allow_fast_forward = 1;
576 fast_forward_only = 1;
577 } /* do not barf on values from future versions of git */
579 } else if (!strcmp(k, "merge.defaulttoupstream")) {
580 default_to_upstream = git_config_bool(k, v);
583 return git_diff_ui_config(k, v, cb);
586 static int read_tree_trivial(unsigned char *common, unsigned char *head,
590 struct tree *trees[MAX_UNPACK_TREES];
591 struct tree_desc t[MAX_UNPACK_TREES];
592 struct unpack_trees_options opts;
594 memset(&opts, 0, sizeof(opts));
596 opts.src_index = &the_index;
597 opts.dst_index = &the_index;
599 opts.verbose_update = 1;
600 opts.trivial_merges_only = 1;
602 trees[nr_trees] = parse_tree_indirect(common);
603 if (!trees[nr_trees++])
605 trees[nr_trees] = parse_tree_indirect(head);
606 if (!trees[nr_trees++])
608 trees[nr_trees] = parse_tree_indirect(one);
609 if (!trees[nr_trees++])
611 opts.fn = threeway_merge;
612 cache_tree_free(&active_cache_tree);
613 for (i = 0; i < nr_trees; i++) {
614 parse_tree(trees[i]);
615 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
617 if (unpack_trees(nr_trees, t, &opts))
622 static void write_tree_trivial(unsigned char *sha1)
624 if (write_cache_as_tree(sha1, 0, NULL))
625 die(_("git write-tree failed to write a tree"));
628 static const char *merge_argument(struct commit *commit)
631 return sha1_to_hex(commit->object.sha1);
633 return EMPTY_TREE_SHA1_HEX;
636 int try_merge_command(const char *strategy, size_t xopts_nr,
637 const char **xopts, struct commit_list *common,
638 const char *head_arg, struct commit_list *remotes)
641 int i = 0, x = 0, ret;
642 struct commit_list *j;
643 struct strbuf buf = STRBUF_INIT;
645 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
646 commit_list_count(remotes)) * sizeof(char *));
647 strbuf_addf(&buf, "merge-%s", strategy);
649 for (x = 0; x < xopts_nr; x++) {
650 char *s = xmalloc(strlen(xopts[x])+2+1);
652 strcpy(s+2, xopts[x]);
655 for (j = common; j; j = j->next)
656 args[i++] = xstrdup(merge_argument(j->item));
658 args[i++] = head_arg;
659 for (j = remotes; j; j = j->next)
660 args[i++] = xstrdup(merge_argument(j->item));
662 ret = run_command_v_opt(args, RUN_GIT_CMD);
663 strbuf_release(&buf);
665 for (x = 0; x < xopts_nr; x++)
666 free((void *)args[i++]);
667 for (j = common; j; j = j->next)
668 free((void *)args[i++]);
670 for (j = remotes; j; j = j->next)
671 free((void *)args[i++]);
674 if (read_cache() < 0)
675 die(_("failed to read the cache"));
676 resolve_undo_clear();
681 static int try_merge_strategy(const char *strategy, struct commit_list *common,
682 struct commit *head, const char *head_arg)
685 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
687 index_fd = hold_locked_index(lock, 1);
688 refresh_cache(REFRESH_QUIET);
689 if (active_cache_changed &&
690 (write_cache(index_fd, active_cache, active_nr) ||
691 commit_locked_index(lock)))
692 return error(_("Unable to write index."));
693 rollback_lock_file(lock);
695 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
697 struct commit *result;
698 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
700 struct commit_list *reversed = NULL;
701 struct merge_options o;
702 struct commit_list *j;
704 if (remoteheads->next) {
705 error(_("Not handling anything other than two heads merge."));
709 init_merge_options(&o);
710 if (!strcmp(strategy, "subtree"))
711 o.subtree_shift = "";
713 o.renormalize = option_renormalize;
714 o.show_rename_progress =
715 show_progress == -1 ? isatty(2) : show_progress;
717 for (x = 0; x < xopts_nr; x++)
718 if (parse_merge_opt(&o, xopts[x]))
719 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
721 o.branch1 = head_arg;
722 o.branch2 = remoteheads->item->util;
724 for (j = common; j; j = j->next)
725 commit_list_insert(j->item, &reversed);
727 index_fd = hold_locked_index(lock, 1);
728 clean = merge_recursive(&o, head,
729 remoteheads->item, reversed, &result);
730 if (active_cache_changed &&
731 (write_cache(index_fd, active_cache, active_nr) ||
732 commit_locked_index(lock)))
733 die (_("unable to write %s"), get_index_file());
734 rollback_lock_file(lock);
735 return clean ? 0 : 1;
737 return try_merge_command(strategy, xopts_nr, xopts,
738 common, head_arg, remoteheads);
742 static void count_diff_files(struct diff_queue_struct *q,
743 struct diff_options *opt, void *data)
750 static int count_unmerged_entries(void)
754 for (i = 0; i < active_nr; i++)
755 if (ce_stage(active_cache[i]))
761 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
763 struct tree *trees[MAX_UNPACK_TREES];
764 struct unpack_trees_options opts;
765 struct tree_desc t[MAX_UNPACK_TREES];
766 int i, fd, nr_trees = 0;
767 struct dir_struct dir;
768 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
770 refresh_cache(REFRESH_QUIET);
772 fd = hold_locked_index(lock_file, 1);
774 memset(&trees, 0, sizeof(trees));
775 memset(&opts, 0, sizeof(opts));
776 memset(&t, 0, sizeof(t));
777 memset(&dir, 0, sizeof(dir));
778 dir.flags |= DIR_SHOW_IGNORED;
779 dir.exclude_per_dir = ".gitignore";
783 opts.src_index = &the_index;
784 opts.dst_index = &the_index;
786 opts.verbose_update = 1;
788 opts.fn = twoway_merge;
789 setup_unpack_trees_porcelain(&opts, "merge");
791 trees[nr_trees] = parse_tree_indirect(head);
792 if (!trees[nr_trees++])
794 trees[nr_trees] = parse_tree_indirect(remote);
795 if (!trees[nr_trees++])
797 for (i = 0; i < nr_trees; i++) {
798 parse_tree(trees[i]);
799 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
801 if (unpack_trees(nr_trees, t, &opts))
803 if (write_cache(fd, active_cache, active_nr) ||
804 commit_locked_index(lock_file))
805 die(_("unable to write new index file"));
809 static void split_merge_strategies(const char *string, struct strategy **list,
817 buf = xstrdup(string);
822 ALLOC_GROW(*list, *nr + 1, *alloc);
823 (*list)[(*nr)++].name = xstrdup(q);
828 ALLOC_GROW(*list, *nr + 1, *alloc);
829 (*list)[(*nr)++].name = xstrdup(q);
835 static void add_strategies(const char *string, unsigned attr)
837 struct strategy *list = NULL;
838 int list_alloc = 0, list_nr = 0, i;
840 memset(&list, 0, sizeof(list));
841 split_merge_strategies(string, &list, &list_nr, &list_alloc);
843 for (i = 0; i < list_nr; i++)
844 append_strategy(get_strategy(list[i].name));
847 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
848 if (all_strategy[i].attr & attr)
849 append_strategy(&all_strategy[i]);
853 static void write_merge_msg(struct strbuf *msg)
855 int fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
857 die_errno(_("Could not open '%s' for writing"),
858 git_path("MERGE_MSG"));
859 if (write_in_full(fd, msg->buf, msg->len) != msg->len)
860 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
864 static void read_merge_msg(struct strbuf *msg)
867 if (strbuf_read_file(msg, git_path("MERGE_MSG"), 0) < 0)
868 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
871 static void write_merge_state(void);
872 static void abort_commit(const char *err_msg)
875 error("%s", err_msg);
877 _("Not committing merge; use 'git commit' to complete the merge.\n"));
882 static void prepare_to_commit(void)
884 struct strbuf msg = STRBUF_INIT;
885 strbuf_addbuf(&msg, &merge_msg);
886 strbuf_addch(&msg, '\n');
887 write_merge_msg(&msg);
888 run_hook(get_index_file(), "prepare-commit-msg",
889 git_path("MERGE_MSG"), "merge", NULL, NULL);
891 if (launch_editor(git_path("MERGE_MSG"), NULL, NULL))
894 read_merge_msg(&msg);
895 stripspace(&msg, option_edit);
897 abort_commit(_("Empty commit message."));
898 strbuf_release(&merge_msg);
899 strbuf_addbuf(&merge_msg, &msg);
900 strbuf_release(&msg);
903 static int merge_trivial(struct commit *head)
905 unsigned char result_tree[20], result_commit[20];
906 struct commit_list *parent = xmalloc(sizeof(*parent));
908 write_tree_trivial(result_tree);
909 printf(_("Wonderful.\n"));
911 parent->next = xmalloc(sizeof(*parent->next));
912 parent->next->item = remoteheads->item;
913 parent->next->next = NULL;
915 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
916 finish(head, result_commit, "In-index merge");
921 static int finish_automerge(struct commit *head,
922 struct commit_list *common,
923 unsigned char *result_tree,
924 const char *wt_strategy)
926 struct commit_list *parents = NULL, *j;
927 struct strbuf buf = STRBUF_INIT;
928 unsigned char result_commit[20];
930 free_commit_list(common);
931 if (allow_fast_forward) {
932 parents = remoteheads;
933 commit_list_insert(head, &parents);
934 parents = reduce_heads(parents);
936 struct commit_list **pptr = &parents;
938 pptr = &commit_list_insert(head,
940 for (j = remoteheads; j; j = j->next)
941 pptr = &commit_list_insert(j->item, pptr)->next;
943 strbuf_addch(&merge_msg, '\n');
945 free_commit_list(remoteheads);
946 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
947 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
948 finish(head, result_commit, buf.buf);
949 strbuf_release(&buf);
954 static int suggest_conflicts(int renormalizing)
959 fp = fopen(git_path("MERGE_MSG"), "a");
961 die_errno(_("Could not open '%s' for writing"),
962 git_path("MERGE_MSG"));
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)
1055 struct commit_list *j;
1056 struct strbuf buf = STRBUF_INIT;
1058 for (j = remoteheads; j; j = j->next)
1059 strbuf_addf(&buf, "%s\n",
1060 sha1_to_hex(j->item->object.sha1));
1061 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1063 die_errno(_("Could not open '%s' for writing"),
1064 git_path("MERGE_HEAD"));
1065 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1066 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1068 strbuf_addch(&merge_msg, '\n');
1069 write_merge_msg(&merge_msg);
1070 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1072 die_errno(_("Could not open '%s' for writing"),
1073 git_path("MERGE_MODE"));
1075 if (!allow_fast_forward)
1076 strbuf_addf(&buf, "no-ff");
1077 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1078 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1082 int cmd_merge(int argc, const char **argv, const char *prefix)
1084 unsigned char result_tree[20];
1085 unsigned char stash[20];
1086 unsigned char head_sha1[20];
1087 struct commit *head_commit;
1088 struct strbuf buf = STRBUF_INIT;
1089 const char *head_arg;
1091 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1092 struct commit_list *common = NULL;
1093 const char *best_strategy = NULL, *wt_strategy = NULL;
1094 struct commit_list **remotes = &remoteheads;
1096 if (argc == 2 && !strcmp(argv[1], "-h"))
1097 usage_with_options(builtin_merge_usage, builtin_merge_options);
1100 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1103 branch = resolve_ref("HEAD", head_sha1, 0, &flag);
1104 if (branch && !prefixcmp(branch, "refs/heads/"))
1106 if (!branch || is_null_sha1(head_sha1))
1109 head_commit = lookup_commit_or_die(head_sha1, "HEAD");
1111 git_config(git_merge_config, NULL);
1113 if (branch_mergeoptions)
1114 parse_branch_merge_options(branch_mergeoptions);
1115 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1116 builtin_merge_usage, 0);
1118 if (verbosity < 0 && show_progress == -1)
1121 if (abort_current_merge) {
1123 const char *nargv[] = {"reset", "--merge", NULL};
1125 if (!file_exists(git_path("MERGE_HEAD")))
1126 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1128 /* Invoke 'git reset --merge' */
1129 return cmd_reset(nargc, nargv, prefix);
1132 if (read_cache_unmerged())
1133 die_resolve_conflict("merge");
1135 if (file_exists(git_path("MERGE_HEAD"))) {
1137 * There is no unmerged entry, don't advise 'git
1138 * add/rm <file>', just 'git commit'.
1140 if (advice_resolve_conflict)
1141 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1142 "Please, commit your changes before you can merge."));
1144 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1146 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1147 if (advice_resolve_conflict)
1148 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1149 "Please, commit your changes before you can merge."));
1151 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1153 resolve_undo_clear();
1159 if (!allow_fast_forward)
1160 die(_("You cannot combine --squash with --no-ff."));
1164 if (!allow_fast_forward && fast_forward_only)
1165 die(_("You cannot combine --no-ff with --ff-only."));
1167 if (!abort_current_merge) {
1168 if (!argc && default_to_upstream)
1169 argc = setup_with_upstream(&argv);
1170 else if (argc == 1 && !strcmp(argv[0], "-"))
1174 usage_with_options(builtin_merge_usage,
1175 builtin_merge_options);
1178 * This could be traditional "merge <msg> HEAD <commit>..." and
1179 * the way we can tell it is to see if the second token is HEAD,
1180 * but some people might have misused the interface and used a
1181 * committish that is the same as HEAD there instead.
1182 * Traditional format never would have "-m" so it is an
1183 * additional safety measure to check for it.
1186 if (!have_message && head_commit &&
1187 is_old_style_invocation(argc, argv, head_commit->object.sha1)) {
1188 strbuf_addstr(&merge_msg, argv[0]);
1192 } else if (!head_commit) {
1193 struct object *remote_head;
1195 * If the merged head is a valid one there is no reason
1196 * to forbid "git merge" into a branch yet to be born.
1197 * We do the same for "git pull".
1200 die(_("Can merge only exactly one commit into "
1203 die(_("Squash commit into empty head not supported yet"));
1204 if (!allow_fast_forward)
1205 die(_("Non-fast-forward commit does not make sense into "
1207 remote_head = want_commit(argv[0]);
1209 die(_("%s - not something we can merge"), argv[0]);
1210 read_empty(remote_head->sha1, 0);
1211 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
1215 struct strbuf merge_names = STRBUF_INIT;
1217 /* We are invoked directly as the first-class UI. */
1221 * All the rest are the commits being merged;
1222 * prepare the standard merge summary message to
1223 * be appended to the given message. If remote
1224 * is invalid we will die later in the common
1225 * codepath so we discard the error in this
1228 for (i = 0; i < argc; i++)
1229 merge_name(argv[i], &merge_names);
1231 if (!have_message || shortlog_len) {
1232 fmt_merge_msg(&merge_names, &merge_msg, !have_message,
1235 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1239 if (!head_commit || !argc)
1240 usage_with_options(builtin_merge_usage,
1241 builtin_merge_options);
1243 strbuf_addstr(&buf, "merge");
1244 for (i = 0; i < argc; i++)
1245 strbuf_addf(&buf, " %s", argv[i]);
1246 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1249 for (i = 0; i < argc; i++) {
1251 struct commit *commit;
1253 o = want_commit(argv[i]);
1255 die(_("%s - not something we can merge"), argv[i]);
1256 commit = lookup_commit(o->sha1);
1257 commit->util = (void *)argv[i];
1258 remotes = &commit_list_insert(commit, remotes)->next;
1260 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1261 setenv(buf.buf, argv[i], 1);
1265 if (!use_strategies) {
1266 if (!remoteheads->next)
1267 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1269 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1272 for (i = 0; i < use_strategies_nr; i++) {
1273 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1274 allow_fast_forward = 0;
1275 if (use_strategies[i]->attr & NO_TRIVIAL)
1279 if (!remoteheads->next)
1280 common = get_merge_bases(head_commit, remoteheads->item, 1);
1282 struct commit_list *list = remoteheads;
1283 commit_list_insert(head_commit, &list);
1284 common = get_octopus_merge_bases(list);
1288 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.sha1,
1289 NULL, 0, DIE_ON_ERR);
1292 ; /* No common ancestors found. We need a real merge. */
1293 else if (!remoteheads->next && !common->next &&
1294 common->item == remoteheads->item) {
1296 * If head can reach all the merge then we are up to date.
1297 * but first the most common case of merging one remote.
1299 finish_up_to_date("Already up-to-date.");
1301 } else if (allow_fast_forward && !remoteheads->next &&
1303 !hashcmp(common->item->object.sha1, head_commit->object.sha1)) {
1304 /* Again the most common case of merging one remote. */
1305 struct strbuf msg = STRBUF_INIT;
1309 strcpy(hex, find_unique_abbrev(head_commit->object.sha1, DEFAULT_ABBREV));
1312 printf(_("Updating %s..%s\n"),
1314 find_unique_abbrev(remoteheads->item->object.sha1,
1316 strbuf_addstr(&msg, "Fast-forward");
1319 " (no commit created; -m option ignored)");
1320 o = want_commit(sha1_to_hex(remoteheads->item->object.sha1));
1324 if (checkout_fast_forward(head_commit->object.sha1, remoteheads->item->object.sha1))
1327 finish(head_commit, o->sha1, msg.buf);
1330 } else if (!remoteheads->next && common->next)
1333 * We are not doing octopus and not fast-forward. Need
1336 else if (!remoteheads->next && !common->next && option_commit) {
1338 * We are not doing octopus, not fast-forward, and have
1341 refresh_cache(REFRESH_QUIET);
1342 if (allow_trivial && !fast_forward_only) {
1343 /* See if it is really trivial. */
1344 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1345 printf(_("Trying really trivial in-index merge...\n"));
1346 if (!read_tree_trivial(common->item->object.sha1,
1347 head_commit->object.sha1, remoteheads->item->object.sha1))
1348 return merge_trivial(head_commit);
1349 printf(_("Nope.\n"));
1353 * An octopus. If we can reach all the remote we are up
1357 struct commit_list *j;
1359 for (j = remoteheads; j; j = j->next) {
1360 struct commit_list *common_one;
1363 * Here we *have* to calculate the individual
1364 * merge_bases again, otherwise "git merge HEAD^
1365 * HEAD^^" would be missed.
1367 common_one = get_merge_bases(head_commit, j->item, 1);
1368 if (hashcmp(common_one->item->object.sha1,
1369 j->item->object.sha1)) {
1375 finish_up_to_date("Already up-to-date. Yeeah!");
1380 if (fast_forward_only)
1381 die(_("Not possible to fast-forward, aborting."));
1383 /* We are going to make a new commit. */
1384 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1387 * At this point, we need a real merge. No matter what strategy
1388 * we use, it would operate on the index, possibly affecting the
1389 * working tree, and when resolved cleanly, have the desired
1390 * tree in the index -- this means that the index must be in
1391 * sync with the head commit. The strategies are responsible
1394 if (use_strategies_nr == 1 ||
1396 * Stash away the local changes so that we can try more than one.
1399 hashcpy(stash, null_sha1);
1401 for (i = 0; i < use_strategies_nr; i++) {
1404 printf(_("Rewinding the tree to pristine...\n"));
1405 restore_state(head_commit->object.sha1, stash);
1407 if (use_strategies_nr != 1)
1408 printf(_("Trying merge strategy %s...\n"),
1409 use_strategies[i]->name);
1411 * Remember which strategy left the state in the working
1414 wt_strategy = use_strategies[i]->name;
1416 ret = try_merge_strategy(use_strategies[i]->name,
1417 common, head_commit, head_arg);
1418 if (!option_commit && !ret) {
1421 * This is necessary here just to avoid writing
1422 * the tree, but later we will *not* exit with
1423 * status code 1 because merge_was_ok is set.
1430 * The backend exits with 1 when conflicts are
1431 * left to be resolved, with 2 when it does not
1432 * handle the given merge at all.
1435 int cnt = evaluate_result();
1437 if (best_cnt <= 0 || cnt <= best_cnt) {
1438 best_strategy = use_strategies[i]->name;
1448 /* Automerge succeeded. */
1449 write_tree_trivial(result_tree);
1450 automerge_was_ok = 1;
1455 * If we have a resulting tree, that means the strategy module
1456 * auto resolved the merge cleanly.
1458 if (automerge_was_ok)
1459 return finish_automerge(head_commit, common, result_tree,
1463 * Pick the result from the best strategy and have the user fix
1466 if (!best_strategy) {
1467 restore_state(head_commit->object.sha1, stash);
1468 if (use_strategies_nr > 1)
1470 _("No merge strategy handled the merge.\n"));
1472 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1473 use_strategies[0]->name);
1475 } else if (best_strategy == wt_strategy)
1476 ; /* We already have its result in the working tree. */
1478 printf(_("Rewinding the tree to pristine...\n"));
1479 restore_state(head_commit->object.sha1, stash);
1480 printf(_("Using the %s to prepare resolving by hand.\n"),
1482 try_merge_strategy(best_strategy, common, head_commit, head_arg);
1486 finish(head_commit, NULL, NULL);
1488 write_merge_state();
1491 fprintf(stderr, _("Automatic merge went well; "
1492 "stopped before committing as requested\n"));
1495 return suggest_conflicts(option_renormalize);