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 #define DEFAULT_TWOHEAD (1<<0)
30 #define DEFAULT_OCTOPUS (1<<1)
31 #define NO_FAST_FORWARD (1<<2)
32 #define NO_TRIVIAL (1<<3)
39 static const char * const builtin_merge_usage[] = {
40 "git merge [options] <remote>...",
41 "git merge [options] <msg> HEAD <remote>",
45 static int show_diffstat = 1, shortlog_len, squash;
46 static int option_commit = 1, allow_fast_forward = 1;
47 static int fast_forward_only;
48 static int allow_trivial = 1, have_message;
49 static struct strbuf merge_msg;
50 static struct commit_list *remoteheads;
51 static unsigned char head[20], stash[20];
52 static struct strategy **use_strategies;
53 static size_t use_strategies_nr, use_strategies_alloc;
54 static const char **xopts;
55 static size_t xopts_nr, xopts_alloc;
56 static const char *branch;
57 static int option_renormalize;
59 static int allow_rerere_auto;
61 static struct strategy all_strategy[] = {
62 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
63 { "octopus", DEFAULT_OCTOPUS },
65 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
66 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
69 static const char *pull_twohead, *pull_octopus;
71 static int option_parse_message(const struct option *opt,
72 const char *arg, int unset)
74 struct strbuf *buf = opt->value;
77 strbuf_setlen(buf, 0);
79 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
82 return error("switch `m' requires a value");
86 static struct strategy *get_strategy(const char *name)
90 static struct cmdnames main_cmds, other_cmds;
96 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
97 if (!strcmp(name, all_strategy[i].name))
98 return &all_strategy[i];
101 struct cmdnames not_strategies;
104 memset(¬_strategies, 0, sizeof(struct cmdnames));
105 load_command_list("git-merge-", &main_cmds, &other_cmds);
106 for (i = 0; i < main_cmds.cnt; i++) {
108 struct cmdname *ent = main_cmds.names[i];
109 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
110 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
111 && !all_strategy[j].name[ent->len])
114 add_cmdname(¬_strategies, ent->name, ent->len);
116 exclude_cmds(&main_cmds, ¬_strategies);
118 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
119 fprintf(stderr, "Could not find merge strategy '%s'.\n", name);
120 fprintf(stderr, "Available strategies are:");
121 for (i = 0; i < main_cmds.cnt; i++)
122 fprintf(stderr, " %s", main_cmds.names[i]->name);
123 fprintf(stderr, ".\n");
124 if (other_cmds.cnt) {
125 fprintf(stderr, "Available custom strategies are:");
126 for (i = 0; i < other_cmds.cnt; i++)
127 fprintf(stderr, " %s", other_cmds.names[i]->name);
128 fprintf(stderr, ".\n");
133 ret = xcalloc(1, sizeof(struct strategy));
134 ret->name = xstrdup(name);
135 ret->attr = NO_TRIVIAL;
139 static void append_strategy(struct strategy *s)
141 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
142 use_strategies[use_strategies_nr++] = s;
145 static int option_parse_strategy(const struct option *opt,
146 const char *name, int unset)
151 append_strategy(get_strategy(name));
155 static int option_parse_x(const struct option *opt,
156 const char *arg, int unset)
161 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
162 xopts[xopts_nr++] = xstrdup(arg);
166 static int option_parse_n(const struct option *opt,
167 const char *arg, int unset)
169 show_diffstat = unset;
173 static struct option builtin_merge_options[] = {
174 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
175 "do not show a diffstat at the end of the merge",
176 PARSE_OPT_NOARG, option_parse_n },
177 OPT_BOOLEAN(0, "stat", &show_diffstat,
178 "show a diffstat at the end of the merge"),
179 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
180 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
181 "add (at most <n>) entries from shortlog to merge commit message",
182 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
183 OPT_BOOLEAN(0, "squash", &squash,
184 "create a single commit instead of doing a merge"),
185 OPT_BOOLEAN(0, "commit", &option_commit,
186 "perform a commit if the merge succeeds (default)"),
187 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
188 "allow fast-forward (default)"),
189 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
190 "abort if fast-forward is not possible"),
191 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
192 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
193 "merge strategy to use", option_parse_strategy),
194 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
195 "option for selected merge strategy", option_parse_x),
196 OPT_CALLBACK('m', "message", &merge_msg, "message",
197 "message to be used for the merge commit (if any)",
198 option_parse_message),
199 OPT__VERBOSITY(&verbosity),
203 /* Cleans up metadata that is uninteresting after a succeeded merge. */
204 static void drop_save(void)
206 unlink(git_path("MERGE_HEAD"));
207 unlink(git_path("MERGE_MSG"));
208 unlink(git_path("MERGE_MODE"));
211 static void save_state(void)
214 struct child_process cp;
215 struct strbuf buffer = STRBUF_INIT;
216 const char *argv[] = {"stash", "create", NULL};
218 memset(&cp, 0, sizeof(cp));
223 if (start_command(&cp))
224 die("could not run stash.");
225 len = strbuf_read(&buffer, cp.out, 1024);
228 if (finish_command(&cp) || len < 0)
232 strbuf_setlen(&buffer, buffer.len-1);
233 if (get_sha1(buffer.buf, stash))
234 die("not a valid object: %s", buffer.buf);
237 static void read_empty(unsigned const char *sha1, int verbose)
242 args[i++] = "read-tree";
247 args[i++] = EMPTY_TREE_SHA1_HEX;
248 args[i++] = sha1_to_hex(sha1);
251 if (run_command_v_opt(args, RUN_GIT_CMD))
252 die("read-tree failed");
255 static void reset_hard(unsigned const char *sha1, int verbose)
260 args[i++] = "read-tree";
263 args[i++] = "--reset";
265 args[i++] = sha1_to_hex(sha1);
268 if (run_command_v_opt(args, RUN_GIT_CMD))
269 die("read-tree failed");
272 static void restore_state(void)
274 struct strbuf sb = STRBUF_INIT;
275 const char *args[] = { "stash", "apply", NULL, NULL };
277 if (is_null_sha1(stash))
282 args[2] = sha1_to_hex(stash);
285 * It is OK to ignore error here, for example when there was
286 * nothing to restore.
288 run_command_v_opt(args, RUN_GIT_CMD);
291 refresh_cache(REFRESH_QUIET);
294 /* This is called when no merge was necessary. */
295 static void finish_up_to_date(const char *msg)
298 printf("%s%s\n", squash ? " (nothing to squash)" : "", msg);
302 static void squash_message(void)
305 struct commit *commit;
306 struct strbuf out = STRBUF_INIT;
307 struct commit_list *j;
309 struct pretty_print_context ctx = {0};
311 printf("Squash commit -- not updating HEAD\n");
312 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
314 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
316 init_revisions(&rev, NULL);
317 rev.ignore_merges = 1;
318 rev.commit_format = CMIT_FMT_MEDIUM;
320 commit = lookup_commit(head);
321 commit->object.flags |= UNINTERESTING;
322 add_pending_object(&rev, &commit->object, NULL);
324 for (j = remoteheads; j; j = j->next)
325 add_pending_object(&rev, &j->item->object, NULL);
327 setup_revisions(0, NULL, &rev, NULL);
328 if (prepare_revision_walk(&rev))
329 die("revision walk setup failed");
331 ctx.abbrev = rev.abbrev;
332 ctx.date_mode = rev.date_mode;
334 strbuf_addstr(&out, "Squashed commit of the following:\n");
335 while ((commit = get_revision(&rev)) != NULL) {
336 strbuf_addch(&out, '\n');
337 strbuf_addf(&out, "commit %s\n",
338 sha1_to_hex(commit->object.sha1));
339 pretty_print_commit(rev.commit_format, commit, &out, &ctx);
341 if (write(fd, out.buf, out.len) < 0)
342 die_errno("Writing SQUASH_MSG");
344 die_errno("Finishing SQUASH_MSG");
345 strbuf_release(&out);
348 static void finish(const unsigned char *new_head, const char *msg)
350 struct strbuf reflog_message = STRBUF_INIT;
353 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
357 strbuf_addf(&reflog_message, "%s: %s",
358 getenv("GIT_REFLOG_ACTION"), msg);
363 if (verbosity >= 0 && !merge_msg.len)
364 printf("No merge message -- not updating HEAD\n");
366 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
367 update_ref(reflog_message.buf, "HEAD",
371 * We ignore errors in 'gc --auto', since the
372 * user should see them.
374 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
377 if (new_head && show_diffstat) {
378 struct diff_options opts;
380 opts.output_format |=
381 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
382 opts.detect_rename = DIFF_DETECT_RENAME;
383 if (diff_use_color_default > 0)
384 DIFF_OPT_SET(&opts, COLOR_DIFF);
385 if (diff_setup_done(&opts) < 0)
386 die("diff_setup_done failed");
387 diff_tree_sha1(head, new_head, "", &opts);
392 /* Run a post-merge hook */
393 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
395 strbuf_release(&reflog_message);
398 /* Get the name for the merge commit's message. */
399 static void merge_name(const char *remote, struct strbuf *msg)
401 struct object *remote_head;
402 unsigned char branch_head[20], buf_sha[20];
403 struct strbuf buf = STRBUF_INIT;
404 struct strbuf bname = STRBUF_INIT;
409 strbuf_branchname(&bname, remote);
412 memset(branch_head, 0, sizeof(branch_head));
413 remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
415 die("'%s' does not point to a commit", remote);
417 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
418 if (!prefixcmp(found_ref, "refs/heads/")) {
419 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
420 sha1_to_hex(branch_head), remote);
423 if (!prefixcmp(found_ref, "refs/remotes/")) {
424 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
425 sha1_to_hex(branch_head), remote);
430 /* See if remote matches <name>^^^.. or <name>~<number> */
431 for (len = 0, ptr = remote + strlen(remote);
432 remote < ptr && ptr[-1] == '^';
439 ptr = strrchr(remote, '~');
441 int seen_nonzero = 0;
444 while (*++ptr && isdigit(*ptr)) {
445 seen_nonzero |= (*ptr != '0');
449 len = 0; /* not ...~<number> */
450 else if (seen_nonzero)
453 early = 1; /* "name~" is "name~1"! */
457 struct strbuf truname = STRBUF_INIT;
458 strbuf_addstr(&truname, "refs/heads/");
459 strbuf_addstr(&truname, remote);
460 strbuf_setlen(&truname, truname.len - len);
461 if (resolve_ref(truname.buf, buf_sha, 1, NULL)) {
463 "%s\t\tbranch '%s'%s of .\n",
464 sha1_to_hex(remote_head->sha1),
466 (early ? " (early part)" : ""));
467 strbuf_release(&truname);
472 if (!strcmp(remote, "FETCH_HEAD") &&
473 !access(git_path("FETCH_HEAD"), R_OK)) {
475 struct strbuf line = STRBUF_INIT;
478 fp = fopen(git_path("FETCH_HEAD"), "r");
480 die_errno("could not open '%s' for reading",
481 git_path("FETCH_HEAD"));
482 strbuf_getline(&line, fp, '\n');
484 ptr = strstr(line.buf, "\tnot-for-merge\t");
486 strbuf_remove(&line, ptr-line.buf+1, 13);
487 strbuf_addbuf(msg, &line);
488 strbuf_release(&line);
491 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
492 sha1_to_hex(remote_head->sha1), remote);
494 strbuf_release(&buf);
495 strbuf_release(&bname);
498 static int git_merge_config(const char *k, const char *v, void *cb)
500 if (branch && !prefixcmp(k, "branch.") &&
501 !prefixcmp(k + 7, branch) &&
502 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
508 argc = split_cmdline(buf, &argv);
510 die("Bad branch.%s.mergeoptions string: %s", branch,
511 split_cmdline_strerror(argc));
512 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
513 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
515 parse_options(argc, argv, NULL, builtin_merge_options,
516 builtin_merge_usage, 0);
520 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
521 show_diffstat = git_config_bool(k, v);
522 else if (!strcmp(k, "pull.twohead"))
523 return git_config_string(&pull_twohead, k, v);
524 else if (!strcmp(k, "pull.octopus"))
525 return git_config_string(&pull_octopus, k, v);
526 else if (!strcmp(k, "merge.renormalize"))
527 option_renormalize = git_config_bool(k, v);
528 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary")) {
530 shortlog_len = git_config_bool_or_int(k, v, &is_bool);
531 if (!is_bool && shortlog_len < 0)
532 return error("%s: negative length %s", k, v);
533 if (is_bool && shortlog_len)
534 shortlog_len = DEFAULT_MERGE_LOG_LEN;
537 return git_diff_ui_config(k, v, cb);
540 static int read_tree_trivial(unsigned char *common, unsigned char *head,
544 struct tree *trees[MAX_UNPACK_TREES];
545 struct tree_desc t[MAX_UNPACK_TREES];
546 struct unpack_trees_options opts;
548 memset(&opts, 0, sizeof(opts));
550 opts.src_index = &the_index;
551 opts.dst_index = &the_index;
553 opts.verbose_update = 1;
554 opts.trivial_merges_only = 1;
556 trees[nr_trees] = parse_tree_indirect(common);
557 if (!trees[nr_trees++])
559 trees[nr_trees] = parse_tree_indirect(head);
560 if (!trees[nr_trees++])
562 trees[nr_trees] = parse_tree_indirect(one);
563 if (!trees[nr_trees++])
565 opts.fn = threeway_merge;
566 cache_tree_free(&active_cache_tree);
567 for (i = 0; i < nr_trees; i++) {
568 parse_tree(trees[i]);
569 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
571 if (unpack_trees(nr_trees, t, &opts))
576 static void write_tree_trivial(unsigned char *sha1)
578 if (write_cache_as_tree(sha1, 0, NULL))
579 die("git write-tree failed to write a tree");
582 int try_merge_command(const char *strategy, struct commit_list *common,
583 const char *head_arg, struct commit_list *remotes)
586 int i = 0, x = 0, ret;
587 struct commit_list *j;
588 struct strbuf buf = STRBUF_INIT;
590 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
591 commit_list_count(remotes)) * sizeof(char *));
592 strbuf_addf(&buf, "merge-%s", strategy);
594 for (x = 0; x < xopts_nr; x++) {
595 char *s = xmalloc(strlen(xopts[x])+2+1);
597 strcpy(s+2, xopts[x]);
600 for (j = common; j; j = j->next)
601 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
603 args[i++] = head_arg;
604 for (j = remotes; j; j = j->next)
605 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
607 ret = run_command_v_opt(args, RUN_GIT_CMD);
608 strbuf_release(&buf);
610 for (x = 0; x < xopts_nr; x++)
611 free((void *)args[i++]);
612 for (j = common; j; j = j->next)
613 free((void *)args[i++]);
615 for (j = remotes; j; j = j->next)
616 free((void *)args[i++]);
619 if (read_cache() < 0)
620 die("failed to read the cache");
621 resolve_undo_clear();
626 static int try_merge_strategy(const char *strategy, struct commit_list *common,
627 const char *head_arg)
630 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
632 index_fd = hold_locked_index(lock, 1);
633 refresh_cache(REFRESH_QUIET);
634 if (active_cache_changed &&
635 (write_cache(index_fd, active_cache, active_nr) ||
636 commit_locked_index(lock)))
637 return error("Unable to write index.");
638 rollback_lock_file(lock);
640 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
642 struct commit *result;
643 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
645 struct commit_list *reversed = NULL;
646 struct merge_options o;
647 struct commit_list *j;
649 if (remoteheads->next) {
650 error("Not handling anything other than two heads merge.");
654 init_merge_options(&o);
655 if (!strcmp(strategy, "subtree"))
656 o.subtree_shift = "";
658 o.renormalize = option_renormalize;
660 for (x = 0; x < xopts_nr; x++)
661 if (parse_merge_opt(&o, xopts[x]))
662 die("Unknown option for merge-recursive: -X%s", xopts[x]);
664 o.branch1 = head_arg;
665 o.branch2 = remoteheads->item->util;
667 for (j = common; j; j = j->next)
668 commit_list_insert(j->item, &reversed);
670 index_fd = hold_locked_index(lock, 1);
671 clean = merge_recursive(&o, lookup_commit(head),
672 remoteheads->item, reversed, &result);
673 if (active_cache_changed &&
674 (write_cache(index_fd, active_cache, active_nr) ||
675 commit_locked_index(lock)))
676 die ("unable to write %s", get_index_file());
677 rollback_lock_file(lock);
678 return clean ? 0 : 1;
680 return try_merge_command(strategy, common, head_arg, remoteheads);
684 static void count_diff_files(struct diff_queue_struct *q,
685 struct diff_options *opt, void *data)
692 static int count_unmerged_entries(void)
696 for (i = 0; i < active_nr; i++)
697 if (ce_stage(active_cache[i]))
703 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
705 struct tree *trees[MAX_UNPACK_TREES];
706 struct unpack_trees_options opts;
707 struct tree_desc t[MAX_UNPACK_TREES];
708 int i, fd, nr_trees = 0;
709 struct dir_struct dir;
710 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
712 refresh_cache(REFRESH_QUIET);
714 fd = hold_locked_index(lock_file, 1);
716 memset(&trees, 0, sizeof(trees));
717 memset(&opts, 0, sizeof(opts));
718 memset(&t, 0, sizeof(t));
719 memset(&dir, 0, sizeof(dir));
720 dir.flags |= DIR_SHOW_IGNORED;
721 dir.exclude_per_dir = ".gitignore";
725 opts.src_index = &the_index;
726 opts.dst_index = &the_index;
728 opts.verbose_update = 1;
730 opts.fn = twoway_merge;
731 setup_unpack_trees_porcelain(&opts, "merge");
733 trees[nr_trees] = parse_tree_indirect(head);
734 if (!trees[nr_trees++])
736 trees[nr_trees] = parse_tree_indirect(remote);
737 if (!trees[nr_trees++])
739 for (i = 0; i < nr_trees; i++) {
740 parse_tree(trees[i]);
741 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
743 if (unpack_trees(nr_trees, t, &opts))
745 if (write_cache(fd, active_cache, active_nr) ||
746 commit_locked_index(lock_file))
747 die("unable to write new index file");
751 static void split_merge_strategies(const char *string, struct strategy **list,
759 buf = xstrdup(string);
764 ALLOC_GROW(*list, *nr + 1, *alloc);
765 (*list)[(*nr)++].name = xstrdup(q);
770 ALLOC_GROW(*list, *nr + 1, *alloc);
771 (*list)[(*nr)++].name = xstrdup(q);
777 static void add_strategies(const char *string, unsigned attr)
779 struct strategy *list = NULL;
780 int list_alloc = 0, list_nr = 0, i;
782 memset(&list, 0, sizeof(list));
783 split_merge_strategies(string, &list, &list_nr, &list_alloc);
785 for (i = 0; i < list_nr; i++)
786 append_strategy(get_strategy(list[i].name));
789 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
790 if (all_strategy[i].attr & attr)
791 append_strategy(&all_strategy[i]);
795 static int merge_trivial(void)
797 unsigned char result_tree[20], result_commit[20];
798 struct commit_list *parent = xmalloc(sizeof(*parent));
800 write_tree_trivial(result_tree);
801 printf("Wonderful.\n");
802 parent->item = lookup_commit(head);
803 parent->next = xmalloc(sizeof(*parent->next));
804 parent->next->item = remoteheads->item;
805 parent->next->next = NULL;
806 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
807 finish(result_commit, "In-index merge");
812 static int finish_automerge(struct commit_list *common,
813 unsigned char *result_tree,
814 const char *wt_strategy)
816 struct commit_list *parents = NULL, *j;
817 struct strbuf buf = STRBUF_INIT;
818 unsigned char result_commit[20];
820 free_commit_list(common);
821 if (allow_fast_forward) {
822 parents = remoteheads;
823 commit_list_insert(lookup_commit(head), &parents);
824 parents = reduce_heads(parents);
826 struct commit_list **pptr = &parents;
828 pptr = &commit_list_insert(lookup_commit(head),
830 for (j = remoteheads; j; j = j->next)
831 pptr = &commit_list_insert(j->item, pptr)->next;
833 free_commit_list(remoteheads);
834 strbuf_addch(&merge_msg, '\n');
835 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
836 strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
837 finish(result_commit, buf.buf);
838 strbuf_release(&buf);
843 static int suggest_conflicts(int renormalizing)
848 fp = fopen(git_path("MERGE_MSG"), "a");
850 die_errno("Could not open '%s' for writing",
851 git_path("MERGE_MSG"));
852 fprintf(fp, "\nConflicts:\n");
853 for (pos = 0; pos < active_nr; pos++) {
854 struct cache_entry *ce = active_cache[pos];
857 fprintf(fp, "\t%s\n", ce->name);
858 while (pos + 1 < active_nr &&
860 active_cache[pos + 1]->name))
865 rerere(allow_rerere_auto);
866 printf("Automatic merge failed; "
867 "fix conflicts and then commit the result.\n");
871 static struct commit *is_old_style_invocation(int argc, const char **argv)
873 struct commit *second_token = NULL;
875 unsigned char second_sha1[20];
877 if (get_sha1(argv[1], second_sha1))
879 second_token = lookup_commit_reference_gently(second_sha1, 0);
881 die("'%s' is not a commit", argv[1]);
882 if (hashcmp(second_token->object.sha1, head))
888 static int evaluate_result(void)
893 /* Check how many files differ. */
894 init_revisions(&rev, "");
895 setup_revisions(0, NULL, &rev, NULL);
896 rev.diffopt.output_format |=
897 DIFF_FORMAT_CALLBACK;
898 rev.diffopt.format_callback = count_diff_files;
899 rev.diffopt.format_callback_data = &cnt;
900 run_diff_files(&rev, 0);
903 * Check how many unmerged entries are
906 cnt += count_unmerged_entries();
911 int cmd_merge(int argc, const char **argv, const char *prefix)
913 unsigned char result_tree[20];
914 struct strbuf buf = STRBUF_INIT;
915 const char *head_arg;
916 int flag, head_invalid = 0, i;
917 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
918 struct commit_list *common = NULL;
919 const char *best_strategy = NULL, *wt_strategy = NULL;
920 struct commit_list **remotes = &remoteheads;
922 if (read_cache_unmerged()) {
923 die_resolve_conflict("merge");
925 if (file_exists(git_path("MERGE_HEAD"))) {
927 * There is no unmerged entry, don't advise 'git
928 * add/rm <file>', just 'git commit'.
930 if (advice_resolve_conflict)
931 die("You have not concluded your merge (MERGE_HEAD exists).\n"
932 "Please, commit your changes before you can merge.");
934 die("You have not concluded your merge (MERGE_HEAD exists).");
937 resolve_undo_clear();
939 * Check if we are _not_ on a detached HEAD, i.e. if there is a
942 branch = resolve_ref("HEAD", head, 0, &flag);
943 if (branch && !prefixcmp(branch, "refs/heads/"))
945 if (is_null_sha1(head))
948 git_config(git_merge_config, NULL);
951 if (diff_use_color_default == -1)
952 diff_use_color_default = git_use_color_default;
954 argc = parse_options(argc, argv, prefix, builtin_merge_options,
955 builtin_merge_usage, 0);
960 if (!allow_fast_forward)
961 die("You cannot combine --squash with --no-ff.");
965 if (!allow_fast_forward && fast_forward_only)
966 die("You cannot combine --no-ff with --ff-only.");
969 usage_with_options(builtin_merge_usage,
970 builtin_merge_options);
973 * This could be traditional "merge <msg> HEAD <commit>..." and
974 * the way we can tell it is to see if the second token is HEAD,
975 * but some people might have misused the interface and used a
976 * committish that is the same as HEAD there instead.
977 * Traditional format never would have "-m" so it is an
978 * additional safety measure to check for it.
981 if (!have_message && is_old_style_invocation(argc, argv)) {
982 strbuf_addstr(&merge_msg, argv[0]);
986 } else if (head_invalid) {
987 struct object *remote_head;
989 * If the merged head is a valid one there is no reason
990 * to forbid "git merge" into a branch yet to be born.
991 * We do the same for "git pull".
994 die("Can merge only exactly one commit into "
997 die("Squash commit into empty head not supported yet");
998 if (!allow_fast_forward)
999 die("Non-fast-forward commit does not make sense into "
1001 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
1003 die("%s - not something we can merge", argv[0]);
1004 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
1006 read_empty(remote_head->sha1, 0);
1009 struct strbuf merge_names = STRBUF_INIT;
1011 /* We are invoked directly as the first-class UI. */
1015 * All the rest are the commits being merged;
1016 * prepare the standard merge summary message to
1017 * be appended to the given message. If remote
1018 * is invalid we will die later in the common
1019 * codepath so we discard the error in this
1022 for (i = 0; i < argc; i++)
1023 merge_name(argv[i], &merge_names);
1025 if (!have_message || shortlog_len) {
1026 fmt_merge_msg(&merge_names, &merge_msg, !have_message,
1029 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1033 if (head_invalid || !argc)
1034 usage_with_options(builtin_merge_usage,
1035 builtin_merge_options);
1037 strbuf_addstr(&buf, "merge");
1038 for (i = 0; i < argc; i++)
1039 strbuf_addf(&buf, " %s", argv[i]);
1040 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1043 for (i = 0; i < argc; i++) {
1045 struct commit *commit;
1047 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
1049 die("%s - not something we can merge", argv[i]);
1050 commit = lookup_commit(o->sha1);
1051 commit->util = (void *)argv[i];
1052 remotes = &commit_list_insert(commit, remotes)->next;
1054 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1055 setenv(buf.buf, argv[i], 1);
1059 if (!use_strategies) {
1060 if (!remoteheads->next)
1061 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1063 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1066 for (i = 0; i < use_strategies_nr; i++) {
1067 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1068 allow_fast_forward = 0;
1069 if (use_strategies[i]->attr & NO_TRIVIAL)
1073 if (!remoteheads->next)
1074 common = get_merge_bases(lookup_commit(head),
1075 remoteheads->item, 1);
1077 struct commit_list *list = remoteheads;
1078 commit_list_insert(lookup_commit(head), &list);
1079 common = get_octopus_merge_bases(list);
1083 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1087 ; /* No common ancestors found. We need a real merge. */
1088 else if (!remoteheads->next && !common->next &&
1089 common->item == remoteheads->item) {
1091 * If head can reach all the merge then we are up to date.
1092 * but first the most common case of merging one remote.
1094 finish_up_to_date("Already up-to-date.");
1096 } else if (allow_fast_forward && !remoteheads->next &&
1098 !hashcmp(common->item->object.sha1, head)) {
1099 /* Again the most common case of merging one remote. */
1100 struct strbuf msg = STRBUF_INIT;
1104 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1107 printf("Updating %s..%s\n",
1109 find_unique_abbrev(remoteheads->item->object.sha1,
1111 strbuf_addstr(&msg, "Fast-forward");
1114 " (no commit created; -m option ignored)");
1115 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1116 0, NULL, OBJ_COMMIT);
1120 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1123 finish(o->sha1, msg.buf);
1126 } else if (!remoteheads->next && common->next)
1129 * We are not doing octopus and not fast-forward. Need
1132 else if (!remoteheads->next && !common->next && option_commit) {
1134 * We are not doing octopus, not fast-forward, and have
1137 refresh_cache(REFRESH_QUIET);
1138 if (allow_trivial && !fast_forward_only) {
1139 /* See if it is really trivial. */
1140 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1141 printf("Trying really trivial in-index merge...\n");
1142 if (!read_tree_trivial(common->item->object.sha1,
1143 head, remoteheads->item->object.sha1))
1144 return merge_trivial();
1149 * An octopus. If we can reach all the remote we are up
1153 struct commit_list *j;
1155 for (j = remoteheads; j; j = j->next) {
1156 struct commit_list *common_one;
1159 * Here we *have* to calculate the individual
1160 * merge_bases again, otherwise "git merge HEAD^
1161 * HEAD^^" would be missed.
1163 common_one = get_merge_bases(lookup_commit(head),
1165 if (hashcmp(common_one->item->object.sha1,
1166 j->item->object.sha1)) {
1172 finish_up_to_date("Already up-to-date. Yeeah!");
1177 if (fast_forward_only)
1178 die("Not possible to fast-forward, aborting.");
1180 /* We are going to make a new commit. */
1181 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1184 * At this point, we need a real merge. No matter what strategy
1185 * we use, it would operate on the index, possibly affecting the
1186 * working tree, and when resolved cleanly, have the desired
1187 * tree in the index -- this means that the index must be in
1188 * sync with the head commit. The strategies are responsible
1191 if (use_strategies_nr != 1) {
1193 * Stash away the local changes so that we can try more
1198 memcpy(stash, null_sha1, 20);
1201 for (i = 0; i < use_strategies_nr; i++) {
1204 printf("Rewinding the tree to pristine...\n");
1207 if (use_strategies_nr != 1)
1208 printf("Trying merge strategy %s...\n",
1209 use_strategies[i]->name);
1211 * Remember which strategy left the state in the working
1214 wt_strategy = use_strategies[i]->name;
1216 ret = try_merge_strategy(use_strategies[i]->name,
1218 if (!option_commit && !ret) {
1221 * This is necessary here just to avoid writing
1222 * the tree, but later we will *not* exit with
1223 * status code 1 because merge_was_ok is set.
1230 * The backend exits with 1 when conflicts are
1231 * left to be resolved, with 2 when it does not
1232 * handle the given merge at all.
1235 int cnt = evaluate_result();
1237 if (best_cnt <= 0 || cnt <= best_cnt) {
1238 best_strategy = use_strategies[i]->name;
1248 /* Automerge succeeded. */
1249 write_tree_trivial(result_tree);
1250 automerge_was_ok = 1;
1255 * If we have a resulting tree, that means the strategy module
1256 * auto resolved the merge cleanly.
1258 if (automerge_was_ok)
1259 return finish_automerge(common, result_tree, wt_strategy);
1262 * Pick the result from the best strategy and have the user fix
1265 if (!best_strategy) {
1267 if (use_strategies_nr > 1)
1269 "No merge strategy handled the merge.\n");
1271 fprintf(stderr, "Merge with strategy %s failed.\n",
1272 use_strategies[0]->name);
1274 } else if (best_strategy == wt_strategy)
1275 ; /* We already have its result in the working tree. */
1277 printf("Rewinding the tree to pristine...\n");
1279 printf("Using the %s to prepare resolving by hand.\n",
1281 try_merge_strategy(best_strategy, common, head_arg);
1288 struct commit_list *j;
1290 for (j = remoteheads; j; j = j->next)
1291 strbuf_addf(&buf, "%s\n",
1292 sha1_to_hex(j->item->object.sha1));
1293 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1295 die_errno("Could not open '%s' for writing",
1296 git_path("MERGE_HEAD"));
1297 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1298 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1300 strbuf_addch(&merge_msg, '\n');
1301 fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1303 die_errno("Could not open '%s' for writing",
1304 git_path("MERGE_MSG"));
1305 if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1307 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1309 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1311 die_errno("Could not open '%s' for writing",
1312 git_path("MERGE_MODE"));
1314 if (!allow_fast_forward)
1315 strbuf_addf(&buf, "no-ff");
1316 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1317 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1322 fprintf(stderr, "Automatic merge went well; "
1323 "stopped before committing as requested\n");
1326 return suggest_conflicts(option_renormalize);