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, option_log, 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);
138 static void append_strategy(struct strategy *s)
140 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
141 use_strategies[use_strategies_nr++] = s;
144 static int option_parse_strategy(const struct option *opt,
145 const char *name, int unset)
150 append_strategy(get_strategy(name));
154 static int option_parse_x(const struct option *opt,
155 const char *arg, int unset)
160 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
161 xopts[xopts_nr++] = xstrdup(arg);
165 static int option_parse_n(const struct option *opt,
166 const char *arg, int unset)
168 show_diffstat = unset;
172 static struct option builtin_merge_options[] = {
173 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
174 "do not show a diffstat at the end of the merge",
175 PARSE_OPT_NOARG, option_parse_n },
176 OPT_BOOLEAN(0, "stat", &show_diffstat,
177 "show a diffstat at the end of the merge"),
178 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
179 OPT_BOOLEAN(0, "log", &option_log,
180 "add list of one-line log to merge commit message"),
181 OPT_BOOLEAN(0, "squash", &squash,
182 "create a single commit instead of doing a merge"),
183 OPT_BOOLEAN(0, "commit", &option_commit,
184 "perform a commit if the merge succeeds (default)"),
185 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
186 "allow fast-forward (default)"),
187 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
188 "abort if fast-forward is not possible"),
189 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
190 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
191 "merge strategy to use", option_parse_strategy),
192 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
193 "option for selected merge strategy", option_parse_x),
194 OPT_CALLBACK('m', "message", &merge_msg, "message",
195 "message to be used for the merge commit (if any)",
196 option_parse_message),
197 OPT__VERBOSITY(&verbosity),
201 /* Cleans up metadata that is uninteresting after a succeeded merge. */
202 static void drop_save(void)
204 unlink(git_path("MERGE_HEAD"));
205 unlink(git_path("MERGE_MSG"));
206 unlink(git_path("MERGE_MODE"));
209 static void save_state(void)
212 struct child_process cp;
213 struct strbuf buffer = STRBUF_INIT;
214 const char *argv[] = {"stash", "create", NULL};
216 memset(&cp, 0, sizeof(cp));
221 if (start_command(&cp))
222 die("could not run stash.");
223 len = strbuf_read(&buffer, cp.out, 1024);
226 if (finish_command(&cp) || len < 0)
230 strbuf_setlen(&buffer, buffer.len-1);
231 if (get_sha1(buffer.buf, stash))
232 die("not a valid object: %s", buffer.buf);
235 static void reset_hard(unsigned const char *sha1, int verbose)
240 args[i++] = "read-tree";
243 args[i++] = "--reset";
245 args[i++] = sha1_to_hex(sha1);
248 if (run_command_v_opt(args, RUN_GIT_CMD))
249 die("read-tree failed");
252 static void restore_state(void)
254 struct strbuf sb = STRBUF_INIT;
255 const char *args[] = { "stash", "apply", NULL, NULL };
257 if (is_null_sha1(stash))
262 args[2] = sha1_to_hex(stash);
265 * It is OK to ignore error here, for example when there was
266 * nothing to restore.
268 run_command_v_opt(args, RUN_GIT_CMD);
271 refresh_cache(REFRESH_QUIET);
274 /* This is called when no merge was necessary. */
275 static void finish_up_to_date(const char *msg)
278 printf("%s%s\n", squash ? " (nothing to squash)" : "", msg);
282 static void squash_message(void)
285 struct commit *commit;
286 struct strbuf out = STRBUF_INIT;
287 struct commit_list *j;
289 struct pretty_print_context ctx = {0};
291 printf("Squash commit -- not updating HEAD\n");
292 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
294 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
296 init_revisions(&rev, NULL);
297 rev.ignore_merges = 1;
298 rev.commit_format = CMIT_FMT_MEDIUM;
300 commit = lookup_commit(head);
301 commit->object.flags |= UNINTERESTING;
302 add_pending_object(&rev, &commit->object, NULL);
304 for (j = remoteheads; j; j = j->next)
305 add_pending_object(&rev, &j->item->object, NULL);
307 setup_revisions(0, NULL, &rev, NULL);
308 if (prepare_revision_walk(&rev))
309 die("revision walk setup failed");
311 ctx.abbrev = rev.abbrev;
312 ctx.date_mode = rev.date_mode;
314 strbuf_addstr(&out, "Squashed commit of the following:\n");
315 while ((commit = get_revision(&rev)) != NULL) {
316 strbuf_addch(&out, '\n');
317 strbuf_addf(&out, "commit %s\n",
318 sha1_to_hex(commit->object.sha1));
319 pretty_print_commit(rev.commit_format, commit, &out, &ctx);
321 if (write(fd, out.buf, out.len) < 0)
322 die_errno("Writing SQUASH_MSG");
324 die_errno("Finishing SQUASH_MSG");
325 strbuf_release(&out);
328 static void finish(const unsigned char *new_head, const char *msg)
330 struct strbuf reflog_message = STRBUF_INIT;
333 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
337 strbuf_addf(&reflog_message, "%s: %s",
338 getenv("GIT_REFLOG_ACTION"), msg);
343 if (verbosity >= 0 && !merge_msg.len)
344 printf("No merge message -- not updating HEAD\n");
346 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
347 update_ref(reflog_message.buf, "HEAD",
351 * We ignore errors in 'gc --auto', since the
352 * user should see them.
354 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
357 if (new_head && show_diffstat) {
358 struct diff_options opts;
360 opts.output_format |=
361 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
362 opts.detect_rename = DIFF_DETECT_RENAME;
363 if (diff_use_color_default > 0)
364 DIFF_OPT_SET(&opts, COLOR_DIFF);
365 if (diff_setup_done(&opts) < 0)
366 die("diff_setup_done failed");
367 diff_tree_sha1(head, new_head, "", &opts);
372 /* Run a post-merge hook */
373 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
375 strbuf_release(&reflog_message);
378 /* Get the name for the merge commit's message. */
379 static void merge_name(const char *remote, struct strbuf *msg)
381 struct object *remote_head;
382 unsigned char branch_head[20], buf_sha[20];
383 struct strbuf buf = STRBUF_INIT;
384 struct strbuf bname = STRBUF_INIT;
389 strbuf_branchname(&bname, remote);
392 memset(branch_head, 0, sizeof(branch_head));
393 remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
395 die("'%s' does not point to a commit", remote);
397 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
398 if (!prefixcmp(found_ref, "refs/heads/")) {
399 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
400 sha1_to_hex(branch_head), remote);
403 if (!prefixcmp(found_ref, "refs/remotes/")) {
404 strbuf_addf(msg, "%s\t\tremote branch '%s' of .\n",
405 sha1_to_hex(branch_head), remote);
410 /* See if remote matches <name>^^^.. or <name>~<number> */
411 for (len = 0, ptr = remote + strlen(remote);
412 remote < ptr && ptr[-1] == '^';
419 ptr = strrchr(remote, '~');
421 int seen_nonzero = 0;
424 while (*++ptr && isdigit(*ptr)) {
425 seen_nonzero |= (*ptr != '0');
429 len = 0; /* not ...~<number> */
430 else if (seen_nonzero)
433 early = 1; /* "name~" is "name~1"! */
437 struct strbuf truname = STRBUF_INIT;
438 strbuf_addstr(&truname, "refs/heads/");
439 strbuf_addstr(&truname, remote);
440 strbuf_setlen(&truname, truname.len - len);
441 if (resolve_ref(truname.buf, buf_sha, 0, NULL)) {
443 "%s\t\tbranch '%s'%s of .\n",
444 sha1_to_hex(remote_head->sha1),
446 (early ? " (early part)" : ""));
447 strbuf_release(&truname);
452 if (!strcmp(remote, "FETCH_HEAD") &&
453 !access(git_path("FETCH_HEAD"), R_OK)) {
455 struct strbuf line = STRBUF_INIT;
458 fp = fopen(git_path("FETCH_HEAD"), "r");
460 die_errno("could not open '%s' for reading",
461 git_path("FETCH_HEAD"));
462 strbuf_getline(&line, fp, '\n');
464 ptr = strstr(line.buf, "\tnot-for-merge\t");
466 strbuf_remove(&line, ptr-line.buf+1, 13);
467 strbuf_addbuf(msg, &line);
468 strbuf_release(&line);
471 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
472 sha1_to_hex(remote_head->sha1), remote);
474 strbuf_release(&buf);
475 strbuf_release(&bname);
478 static int git_merge_config(const char *k, const char *v, void *cb)
480 if (branch && !prefixcmp(k, "branch.") &&
481 !prefixcmp(k + 7, branch) &&
482 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
488 argc = split_cmdline(buf, &argv);
490 die("Bad branch.%s.mergeoptions string", branch);
491 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
492 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
494 parse_options(argc, argv, NULL, builtin_merge_options,
495 builtin_merge_usage, 0);
499 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
500 show_diffstat = git_config_bool(k, v);
501 else if (!strcmp(k, "pull.twohead"))
502 return git_config_string(&pull_twohead, k, v);
503 else if (!strcmp(k, "pull.octopus"))
504 return git_config_string(&pull_octopus, k, v);
505 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary"))
506 option_log = git_config_bool(k, v);
507 else if (!strcmp(k, "merge.renormalize"))
508 option_renormalize = git_config_bool(k, v);
509 return git_diff_ui_config(k, v, cb);
512 static int read_tree_trivial(unsigned char *common, unsigned char *head,
516 struct tree *trees[MAX_UNPACK_TREES];
517 struct tree_desc t[MAX_UNPACK_TREES];
518 struct unpack_trees_options opts;
520 memset(&opts, 0, sizeof(opts));
522 opts.src_index = &the_index;
523 opts.dst_index = &the_index;
525 opts.verbose_update = 1;
526 opts.trivial_merges_only = 1;
528 trees[nr_trees] = parse_tree_indirect(common);
529 if (!trees[nr_trees++])
531 trees[nr_trees] = parse_tree_indirect(head);
532 if (!trees[nr_trees++])
534 trees[nr_trees] = parse_tree_indirect(one);
535 if (!trees[nr_trees++])
537 opts.fn = threeway_merge;
538 cache_tree_free(&active_cache_tree);
539 for (i = 0; i < nr_trees; i++) {
540 parse_tree(trees[i]);
541 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
543 if (unpack_trees(nr_trees, t, &opts))
548 static void write_tree_trivial(unsigned char *sha1)
550 if (write_cache_as_tree(sha1, 0, NULL))
551 die("git write-tree failed to write a tree");
554 int try_merge_command(const char *strategy, struct commit_list *common,
555 const char *head_arg, struct commit_list *remotes)
558 int i = 0, x = 0, ret;
559 struct commit_list *j;
560 struct strbuf buf = STRBUF_INIT;
562 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
563 commit_list_count(remotes)) * sizeof(char *));
564 strbuf_addf(&buf, "merge-%s", strategy);
566 for (x = 0; x < xopts_nr; x++) {
567 char *s = xmalloc(strlen(xopts[x])+2+1);
569 strcpy(s+2, xopts[x]);
572 for (j = common; j; j = j->next)
573 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
575 args[i++] = head_arg;
576 for (j = remotes; j; j = j->next)
577 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
579 ret = run_command_v_opt(args, RUN_GIT_CMD);
580 strbuf_release(&buf);
582 for (x = 0; x < xopts_nr; x++)
583 free((void *)args[i++]);
584 for (j = common; j; j = j->next)
585 free((void *)args[i++]);
587 for (j = remotes; j; j = j->next)
588 free((void *)args[i++]);
591 if (read_cache() < 0)
592 die("failed to read the cache");
593 resolve_undo_clear();
598 static int try_merge_strategy(const char *strategy, struct commit_list *common,
599 const char *head_arg)
602 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
604 index_fd = hold_locked_index(lock, 1);
605 refresh_cache(REFRESH_QUIET);
606 if (active_cache_changed &&
607 (write_cache(index_fd, active_cache, active_nr) ||
608 commit_locked_index(lock)))
609 return error("Unable to write index.");
610 rollback_lock_file(lock);
612 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
614 struct commit *result;
615 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
617 struct commit_list *reversed = NULL;
618 struct merge_options o;
619 struct commit_list *j;
621 if (remoteheads->next) {
622 error("Not handling anything other than two heads merge.");
626 init_merge_options(&o);
627 if (!strcmp(strategy, "subtree"))
628 o.subtree_shift = "";
630 o.renormalize = option_renormalize;
633 * NEEDSWORK: merge with table in builtin/merge-recursive
635 for (x = 0; x < xopts_nr; x++) {
636 if (!strcmp(xopts[x], "ours"))
637 o.recursive_variant = MERGE_RECURSIVE_OURS;
638 else if (!strcmp(xopts[x], "theirs"))
639 o.recursive_variant = MERGE_RECURSIVE_THEIRS;
640 else if (!strcmp(xopts[x], "subtree"))
641 o.subtree_shift = "";
642 else if (!prefixcmp(xopts[x], "subtree="))
643 o.subtree_shift = xopts[x]+8;
644 else if (!strcmp(xopts[x], "renormalize"))
646 else if (!strcmp(xopts[x], "no-renormalize"))
649 die("Unknown option for merge-recursive: -X%s", xopts[x]);
652 o.branch1 = head_arg;
653 o.branch2 = remoteheads->item->util;
655 for (j = common; j; j = j->next)
656 commit_list_insert(j->item, &reversed);
658 index_fd = hold_locked_index(lock, 1);
659 clean = merge_recursive(&o, lookup_commit(head),
660 remoteheads->item, reversed, &result);
661 if (active_cache_changed &&
662 (write_cache(index_fd, active_cache, active_nr) ||
663 commit_locked_index(lock)))
664 die ("unable to write %s", get_index_file());
665 rollback_lock_file(lock);
666 return clean ? 0 : 1;
668 return try_merge_command(strategy, common, head_arg, remoteheads);
672 static void count_diff_files(struct diff_queue_struct *q,
673 struct diff_options *opt, void *data)
680 static int count_unmerged_entries(void)
684 for (i = 0; i < active_nr; i++)
685 if (ce_stage(active_cache[i]))
691 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
693 struct tree *trees[MAX_UNPACK_TREES];
694 struct unpack_trees_options opts;
695 struct tree_desc t[MAX_UNPACK_TREES];
696 int i, fd, nr_trees = 0;
697 struct dir_struct dir;
698 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
700 refresh_cache(REFRESH_QUIET);
702 fd = hold_locked_index(lock_file, 1);
704 memset(&trees, 0, sizeof(trees));
705 memset(&opts, 0, sizeof(opts));
706 memset(&t, 0, sizeof(t));
707 memset(&dir, 0, sizeof(dir));
708 dir.flags |= DIR_SHOW_IGNORED;
709 dir.exclude_per_dir = ".gitignore";
713 opts.src_index = &the_index;
714 opts.dst_index = &the_index;
716 opts.verbose_update = 1;
718 opts.fn = twoway_merge;
719 opts.msgs = get_porcelain_error_msgs();
721 trees[nr_trees] = parse_tree_indirect(head);
722 if (!trees[nr_trees++])
724 trees[nr_trees] = parse_tree_indirect(remote);
725 if (!trees[nr_trees++])
727 for (i = 0; i < nr_trees; i++) {
728 parse_tree(trees[i]);
729 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
731 if (unpack_trees(nr_trees, t, &opts))
733 if (write_cache(fd, active_cache, active_nr) ||
734 commit_locked_index(lock_file))
735 die("unable to write new index file");
739 static void split_merge_strategies(const char *string, struct strategy **list,
747 buf = xstrdup(string);
752 ALLOC_GROW(*list, *nr + 1, *alloc);
753 (*list)[(*nr)++].name = xstrdup(q);
758 ALLOC_GROW(*list, *nr + 1, *alloc);
759 (*list)[(*nr)++].name = xstrdup(q);
765 static void add_strategies(const char *string, unsigned attr)
767 struct strategy *list = NULL;
768 int list_alloc = 0, list_nr = 0, i;
770 memset(&list, 0, sizeof(list));
771 split_merge_strategies(string, &list, &list_nr, &list_alloc);
773 for (i = 0; i < list_nr; i++)
774 append_strategy(get_strategy(list[i].name));
777 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
778 if (all_strategy[i].attr & attr)
779 append_strategy(&all_strategy[i]);
783 static int merge_trivial(void)
785 unsigned char result_tree[20], result_commit[20];
786 struct commit_list *parent = xmalloc(sizeof(*parent));
788 write_tree_trivial(result_tree);
789 printf("Wonderful.\n");
790 parent->item = lookup_commit(head);
791 parent->next = xmalloc(sizeof(*parent->next));
792 parent->next->item = remoteheads->item;
793 parent->next->next = NULL;
794 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
795 finish(result_commit, "In-index merge");
800 static int finish_automerge(struct commit_list *common,
801 unsigned char *result_tree,
802 const char *wt_strategy)
804 struct commit_list *parents = NULL, *j;
805 struct strbuf buf = STRBUF_INIT;
806 unsigned char result_commit[20];
808 free_commit_list(common);
809 if (allow_fast_forward) {
810 parents = remoteheads;
811 commit_list_insert(lookup_commit(head), &parents);
812 parents = reduce_heads(parents);
814 struct commit_list **pptr = &parents;
816 pptr = &commit_list_insert(lookup_commit(head),
818 for (j = remoteheads; j; j = j->next)
819 pptr = &commit_list_insert(j->item, pptr)->next;
821 free_commit_list(remoteheads);
822 strbuf_addch(&merge_msg, '\n');
823 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
824 strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
825 finish(result_commit, buf.buf);
826 strbuf_release(&buf);
831 static int suggest_conflicts(int renormalizing)
836 fp = fopen(git_path("MERGE_MSG"), "a");
838 die_errno("Could not open '%s' for writing",
839 git_path("MERGE_MSG"));
840 fprintf(fp, "\nConflicts:\n");
841 for (pos = 0; pos < active_nr; pos++) {
842 struct cache_entry *ce = active_cache[pos];
845 fprintf(fp, "\t%s\n", ce->name);
846 while (pos + 1 < active_nr &&
848 active_cache[pos + 1]->name))
853 rerere(allow_rerere_auto);
854 printf("Automatic merge failed; "
855 "fix conflicts and then commit the result.\n");
859 static struct commit *is_old_style_invocation(int argc, const char **argv)
861 struct commit *second_token = NULL;
863 unsigned char second_sha1[20];
865 if (get_sha1(argv[1], second_sha1))
867 second_token = lookup_commit_reference_gently(second_sha1, 0);
869 die("'%s' is not a commit", argv[1]);
870 if (hashcmp(second_token->object.sha1, head))
876 static int evaluate_result(void)
881 /* Check how many files differ. */
882 init_revisions(&rev, "");
883 setup_revisions(0, NULL, &rev, NULL);
884 rev.diffopt.output_format |=
885 DIFF_FORMAT_CALLBACK;
886 rev.diffopt.format_callback = count_diff_files;
887 rev.diffopt.format_callback_data = &cnt;
888 run_diff_files(&rev, 0);
891 * Check how many unmerged entries are
894 cnt += count_unmerged_entries();
899 int cmd_merge(int argc, const char **argv, const char *prefix)
901 unsigned char result_tree[20];
902 struct strbuf buf = STRBUF_INIT;
903 const char *head_arg;
904 int flag, head_invalid = 0, i;
905 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
906 struct commit_list *common = NULL;
907 const char *best_strategy = NULL, *wt_strategy = NULL;
908 struct commit_list **remotes = &remoteheads;
910 if (read_cache_unmerged()) {
911 die_resolve_conflict("merge");
913 if (file_exists(git_path("MERGE_HEAD"))) {
915 * There is no unmerged entry, don't advise 'git
916 * add/rm <file>', just 'git commit'.
918 if (advice_resolve_conflict)
919 die("You have not concluded your merge (MERGE_HEAD exists).\n"
920 "Please, commit your changes before you can merge.");
922 die("You have not concluded your merge (MERGE_HEAD exists).");
925 resolve_undo_clear();
927 * Check if we are _not_ on a detached HEAD, i.e. if there is a
930 branch = resolve_ref("HEAD", head, 0, &flag);
931 if (branch && !prefixcmp(branch, "refs/heads/"))
933 if (is_null_sha1(head))
936 git_config(git_merge_config, NULL);
939 if (diff_use_color_default == -1)
940 diff_use_color_default = git_use_color_default;
942 argc = parse_options(argc, argv, prefix, builtin_merge_options,
943 builtin_merge_usage, 0);
948 if (!allow_fast_forward)
949 die("You cannot combine --squash with --no-ff.");
953 if (!allow_fast_forward && fast_forward_only)
954 die("You cannot combine --no-ff with --ff-only.");
957 usage_with_options(builtin_merge_usage,
958 builtin_merge_options);
961 * This could be traditional "merge <msg> HEAD <commit>..." and
962 * the way we can tell it is to see if the second token is HEAD,
963 * but some people might have misused the interface and used a
964 * committish that is the same as HEAD there instead.
965 * Traditional format never would have "-m" so it is an
966 * additional safety measure to check for it.
969 if (!have_message && is_old_style_invocation(argc, argv)) {
970 strbuf_addstr(&merge_msg, argv[0]);
974 } else if (head_invalid) {
975 struct object *remote_head;
977 * If the merged head is a valid one there is no reason
978 * to forbid "git merge" into a branch yet to be born.
979 * We do the same for "git pull".
982 die("Can merge only exactly one commit into "
985 die("Squash commit into empty head not supported yet");
986 if (!allow_fast_forward)
987 die("Non-fast-forward commit does not make sense into "
989 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
991 die("%s - not something we can merge", argv[0]);
992 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
994 reset_hard(remote_head->sha1, 0);
997 struct strbuf merge_names = STRBUF_INIT;
999 /* We are invoked directly as the first-class UI. */
1003 * All the rest are the commits being merged;
1004 * prepare the standard merge summary message to
1005 * be appended to the given message. If remote
1006 * is invalid we will die later in the common
1007 * codepath so we discard the error in this
1010 for (i = 0; i < argc; i++)
1011 merge_name(argv[i], &merge_names);
1013 if (have_message && option_log)
1014 fmt_merge_msg_shortlog(&merge_names, &merge_msg);
1015 else if (!have_message)
1016 fmt_merge_msg(option_log, &merge_names, &merge_msg);
1019 if (!(have_message && !option_log) && merge_msg.len)
1020 strbuf_setlen(&merge_msg, merge_msg.len-1);
1023 if (head_invalid || !argc)
1024 usage_with_options(builtin_merge_usage,
1025 builtin_merge_options);
1027 strbuf_addstr(&buf, "merge");
1028 for (i = 0; i < argc; i++)
1029 strbuf_addf(&buf, " %s", argv[i]);
1030 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1033 for (i = 0; i < argc; i++) {
1035 struct commit *commit;
1037 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
1039 die("%s - not something we can merge", argv[i]);
1040 commit = lookup_commit(o->sha1);
1041 commit->util = (void *)argv[i];
1042 remotes = &commit_list_insert(commit, remotes)->next;
1044 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1045 setenv(buf.buf, argv[i], 1);
1049 if (!use_strategies) {
1050 if (!remoteheads->next)
1051 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1053 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1056 for (i = 0; i < use_strategies_nr; i++) {
1057 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1058 allow_fast_forward = 0;
1059 if (use_strategies[i]->attr & NO_TRIVIAL)
1063 if (!remoteheads->next)
1064 common = get_merge_bases(lookup_commit(head),
1065 remoteheads->item, 1);
1067 struct commit_list *list = remoteheads;
1068 commit_list_insert(lookup_commit(head), &list);
1069 common = get_octopus_merge_bases(list);
1073 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1077 ; /* No common ancestors found. We need a real merge. */
1078 else if (!remoteheads->next && !common->next &&
1079 common->item == remoteheads->item) {
1081 * If head can reach all the merge then we are up to date.
1082 * but first the most common case of merging one remote.
1084 finish_up_to_date("Already up-to-date.");
1086 } else if (allow_fast_forward && !remoteheads->next &&
1088 !hashcmp(common->item->object.sha1, head)) {
1089 /* Again the most common case of merging one remote. */
1090 struct strbuf msg = STRBUF_INIT;
1094 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1097 printf("Updating %s..%s\n",
1099 find_unique_abbrev(remoteheads->item->object.sha1,
1101 strbuf_addstr(&msg, "Fast-forward");
1104 " (no commit created; -m option ignored)");
1105 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1106 0, NULL, OBJ_COMMIT);
1110 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1113 finish(o->sha1, msg.buf);
1116 } else if (!remoteheads->next && common->next)
1119 * We are not doing octopus and not fast-forward. Need
1122 else if (!remoteheads->next && !common->next && option_commit) {
1124 * We are not doing octopus, not fast-forward, and have
1127 refresh_cache(REFRESH_QUIET);
1128 if (allow_trivial && !fast_forward_only) {
1129 /* See if it is really trivial. */
1130 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1131 printf("Trying really trivial in-index merge...\n");
1132 if (!read_tree_trivial(common->item->object.sha1,
1133 head, remoteheads->item->object.sha1))
1134 return merge_trivial();
1139 * An octopus. If we can reach all the remote we are up
1143 struct commit_list *j;
1145 for (j = remoteheads; j; j = j->next) {
1146 struct commit_list *common_one;
1149 * Here we *have* to calculate the individual
1150 * merge_bases again, otherwise "git merge HEAD^
1151 * HEAD^^" would be missed.
1153 common_one = get_merge_bases(lookup_commit(head),
1155 if (hashcmp(common_one->item->object.sha1,
1156 j->item->object.sha1)) {
1162 finish_up_to_date("Already up-to-date. Yeeah!");
1167 if (fast_forward_only)
1168 die("Not possible to fast-forward, aborting.");
1170 /* We are going to make a new commit. */
1171 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1174 * At this point, we need a real merge. No matter what strategy
1175 * we use, it would operate on the index, possibly affecting the
1176 * working tree, and when resolved cleanly, have the desired
1177 * tree in the index -- this means that the index must be in
1178 * sync with the head commit. The strategies are responsible
1181 if (use_strategies_nr != 1) {
1183 * Stash away the local changes so that we can try more
1188 memcpy(stash, null_sha1, 20);
1191 for (i = 0; i < use_strategies_nr; i++) {
1194 printf("Rewinding the tree to pristine...\n");
1197 if (use_strategies_nr != 1)
1198 printf("Trying merge strategy %s...\n",
1199 use_strategies[i]->name);
1201 * Remember which strategy left the state in the working
1204 wt_strategy = use_strategies[i]->name;
1206 ret = try_merge_strategy(use_strategies[i]->name,
1208 if (!option_commit && !ret) {
1211 * This is necessary here just to avoid writing
1212 * the tree, but later we will *not* exit with
1213 * status code 1 because merge_was_ok is set.
1220 * The backend exits with 1 when conflicts are
1221 * left to be resolved, with 2 when it does not
1222 * handle the given merge at all.
1225 int cnt = evaluate_result();
1227 if (best_cnt <= 0 || cnt <= best_cnt) {
1228 best_strategy = use_strategies[i]->name;
1238 /* Automerge succeeded. */
1239 write_tree_trivial(result_tree);
1240 automerge_was_ok = 1;
1245 * If we have a resulting tree, that means the strategy module
1246 * auto resolved the merge cleanly.
1248 if (automerge_was_ok)
1249 return finish_automerge(common, result_tree, wt_strategy);
1252 * Pick the result from the best strategy and have the user fix
1255 if (!best_strategy) {
1257 if (use_strategies_nr > 1)
1259 "No merge strategy handled the merge.\n");
1261 fprintf(stderr, "Merge with strategy %s failed.\n",
1262 use_strategies[0]->name);
1264 } else if (best_strategy == wt_strategy)
1265 ; /* We already have its result in the working tree. */
1267 printf("Rewinding the tree to pristine...\n");
1269 printf("Using the %s to prepare resolving by hand.\n",
1271 try_merge_strategy(best_strategy, common, head_arg);
1278 struct commit_list *j;
1280 for (j = remoteheads; j; j = j->next)
1281 strbuf_addf(&buf, "%s\n",
1282 sha1_to_hex(j->item->object.sha1));
1283 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1285 die_errno("Could not open '%s' for writing",
1286 git_path("MERGE_HEAD"));
1287 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1288 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1290 strbuf_addch(&merge_msg, '\n');
1291 fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1293 die_errno("Could not open '%s' for writing",
1294 git_path("MERGE_MSG"));
1295 if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1297 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1299 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1301 die_errno("Could not open '%s' for writing",
1302 git_path("MERGE_MODE"));
1304 if (!allow_fast_forward)
1305 strbuf_addf(&buf, "no-ff");
1306 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1307 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1312 fprintf(stderr, "Automatic merge went well; "
1313 "stopped before committing as requested\n");
1316 return suggest_conflicts(option_renormalize);