Teach 'git merge' that some merge strategies no longer exist
[git/spearce.git] / builtin-merge.c
blob06b9970306396ca8ef2b64d95a411280796f4017
1 /*
2 * Builtin "git merge"
4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
7 */
9 #include "cache.h"
10 #include "parse-options.h"
11 #include "builtin.h"
12 #include "run-command.h"
13 #include "diff.h"
14 #include "refs.h"
15 #include "commit.h"
16 #include "diffcore.h"
17 #include "revision.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
20 #include "dir.h"
21 #include "utf8.h"
22 #include "log-tree.h"
23 #include "color.h"
24 #include "rerere.h"
26 #define DEFAULT_TWOHEAD (1<<0)
27 #define DEFAULT_OCTOPUS (1<<1)
28 #define NO_FAST_FORWARD (1<<2)
29 #define NO_TRIVIAL (1<<3)
31 struct strategy {
32 const char *name;
33 unsigned attr;
36 static const char * const builtin_merge_usage[] = {
37 "git-merge [options] <remote>...",
38 "git-merge [options] <msg> HEAD <remote>",
39 NULL
42 static int show_diffstat = 1, option_log, squash;
43 static int option_commit = 1, allow_fast_forward = 1;
44 static int allow_trivial = 1, have_message;
45 static struct strbuf merge_msg;
46 static struct commit_list *remoteheads;
47 static unsigned char head[20], stash[20];
48 static struct strategy **use_strategies;
49 static size_t use_strategies_nr, use_strategies_alloc;
50 static const char *branch;
52 static struct strategy all_strategy[] = {
53 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
54 { "octopus", DEFAULT_OCTOPUS },
55 { "resolve", 0 },
56 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
57 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
60 static const char *pull_twohead, *pull_octopus;
62 static int option_parse_message(const struct option *opt,
63 const char *arg, int unset)
65 struct strbuf *buf = opt->value;
67 if (unset)
68 strbuf_setlen(buf, 0);
69 else {
70 strbuf_addf(buf, "%s\n\n", arg);
71 have_message = 1;
73 return 0;
76 static struct strategy *get_strategy(const char *name)
78 int i;
80 if (!name)
81 return NULL;
83 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
84 if (!strcmp(name, all_strategy[i].name))
85 return &all_strategy[i];
86 return NULL;
89 static void append_strategy(struct strategy *s)
91 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
92 use_strategies[use_strategies_nr++] = s;
95 static int option_parse_strategy(const struct option *opt,
96 const char *name, int unset)
98 int i;
99 struct strategy *s;
101 if (unset)
102 return 0;
104 s = get_strategy(name);
106 if (s)
107 append_strategy(s);
108 else {
109 struct strbuf err;
110 strbuf_init(&err, 0);
111 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
112 strbuf_addf(&err, " %s", all_strategy[i].name);
113 fprintf(stderr, "Could not find merge strategy '%s'.\n", name);
114 fprintf(stderr, "Available strategies are:%s.\n", err.buf);
115 exit(1);
117 return 0;
120 static int option_parse_n(const struct option *opt,
121 const char *arg, int unset)
123 show_diffstat = unset;
124 return 0;
127 static struct option builtin_merge_options[] = {
128 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
129 "do not show a diffstat at the end of the merge",
130 PARSE_OPT_NOARG, option_parse_n },
131 OPT_BOOLEAN(0, "stat", &show_diffstat,
132 "show a diffstat at the end of the merge"),
133 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
134 OPT_BOOLEAN(0, "log", &option_log,
135 "add list of one-line log to merge commit message"),
136 OPT_BOOLEAN(0, "squash", &squash,
137 "create a single commit instead of doing a merge"),
138 OPT_BOOLEAN(0, "commit", &option_commit,
139 "perform a commit if the merge succeeds (default)"),
140 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
141 "allow fast forward (default)"),
142 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
143 "merge strategy to use", option_parse_strategy),
144 OPT_CALLBACK('m', "message", &merge_msg, "message",
145 "message to be used for the merge commit (if any)",
146 option_parse_message),
147 OPT_END()
150 /* Cleans up metadata that is uninteresting after a succeeded merge. */
151 static void drop_save(void)
153 unlink(git_path("MERGE_HEAD"));
154 unlink(git_path("MERGE_MSG"));
157 static void save_state(void)
159 int len;
160 struct child_process cp;
161 struct strbuf buffer = STRBUF_INIT;
162 const char *argv[] = {"stash", "create", NULL};
164 memset(&cp, 0, sizeof(cp));
165 cp.argv = argv;
166 cp.out = -1;
167 cp.git_cmd = 1;
169 if (start_command(&cp))
170 die("could not run stash.");
171 len = strbuf_read(&buffer, cp.out, 1024);
172 close(cp.out);
174 if (finish_command(&cp) || len < 0)
175 die("stash failed");
176 else if (!len)
177 return;
178 strbuf_setlen(&buffer, buffer.len-1);
179 if (get_sha1(buffer.buf, stash))
180 die("not a valid object: %s", buffer.buf);
183 static void reset_hard(unsigned const char *sha1, int verbose)
185 int i = 0;
186 const char *args[6];
188 args[i++] = "read-tree";
189 if (verbose)
190 args[i++] = "-v";
191 args[i++] = "--reset";
192 args[i++] = "-u";
193 args[i++] = sha1_to_hex(sha1);
194 args[i] = NULL;
196 if (run_command_v_opt(args, RUN_GIT_CMD))
197 die("read-tree failed");
200 static void restore_state(void)
202 struct strbuf sb;
203 const char *args[] = { "stash", "apply", NULL, NULL };
205 if (is_null_sha1(stash))
206 return;
208 reset_hard(head, 1);
210 strbuf_init(&sb, 0);
211 args[2] = sha1_to_hex(stash);
214 * It is OK to ignore error here, for example when there was
215 * nothing to restore.
217 run_command_v_opt(args, RUN_GIT_CMD);
219 strbuf_release(&sb);
220 refresh_cache(REFRESH_QUIET);
223 /* This is called when no merge was necessary. */
224 static void finish_up_to_date(const char *msg)
226 printf("%s%s\n", squash ? " (nothing to squash)" : "", msg);
227 drop_save();
230 static void squash_message(void)
232 struct rev_info rev;
233 struct commit *commit;
234 struct strbuf out;
235 struct commit_list *j;
236 int fd;
238 printf("Squash commit -- not updating HEAD\n");
239 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
240 if (fd < 0)
241 die("Could not write to %s", git_path("SQUASH_MSG"));
243 init_revisions(&rev, NULL);
244 rev.ignore_merges = 1;
245 rev.commit_format = CMIT_FMT_MEDIUM;
247 commit = lookup_commit(head);
248 commit->object.flags |= UNINTERESTING;
249 add_pending_object(&rev, &commit->object, NULL);
251 for (j = remoteheads; j; j = j->next)
252 add_pending_object(&rev, &j->item->object, NULL);
254 setup_revisions(0, NULL, &rev, NULL);
255 if (prepare_revision_walk(&rev))
256 die("revision walk setup failed");
258 strbuf_init(&out, 0);
259 strbuf_addstr(&out, "Squashed commit of the following:\n");
260 while ((commit = get_revision(&rev)) != NULL) {
261 strbuf_addch(&out, '\n');
262 strbuf_addf(&out, "commit %s\n",
263 sha1_to_hex(commit->object.sha1));
264 pretty_print_commit(rev.commit_format, commit, &out, rev.abbrev,
265 NULL, NULL, rev.date_mode, 0);
267 write(fd, out.buf, out.len);
268 close(fd);
269 strbuf_release(&out);
272 static int run_hook(const char *name)
274 struct child_process hook;
275 const char *argv[3], *env[2];
276 char index[PATH_MAX];
278 argv[0] = git_path("hooks/%s", name);
279 if (access(argv[0], X_OK) < 0)
280 return 0;
282 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", get_index_file());
283 env[0] = index;
284 env[1] = NULL;
286 if (squash)
287 argv[1] = "1";
288 else
289 argv[1] = "0";
290 argv[2] = NULL;
292 memset(&hook, 0, sizeof(hook));
293 hook.argv = argv;
294 hook.no_stdin = 1;
295 hook.stdout_to_stderr = 1;
296 hook.env = env;
298 return run_command(&hook);
301 static void finish(const unsigned char *new_head, const char *msg)
303 struct strbuf reflog_message;
305 strbuf_init(&reflog_message, 0);
306 if (!msg)
307 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
308 else {
309 printf("%s\n", msg);
310 strbuf_addf(&reflog_message, "%s: %s",
311 getenv("GIT_REFLOG_ACTION"), msg);
313 if (squash) {
314 squash_message();
315 } else {
316 if (!merge_msg.len)
317 printf("No merge message -- not updating HEAD\n");
318 else {
319 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
320 update_ref(reflog_message.buf, "HEAD",
321 new_head, head, 0,
322 DIE_ON_ERR);
324 * We ignore errors in 'gc --auto', since the
325 * user should see them.
327 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
330 if (new_head && show_diffstat) {
331 struct diff_options opts;
332 diff_setup(&opts);
333 opts.output_format |=
334 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
335 opts.detect_rename = DIFF_DETECT_RENAME;
336 if (diff_use_color_default > 0)
337 DIFF_OPT_SET(&opts, COLOR_DIFF);
338 if (diff_setup_done(&opts) < 0)
339 die("diff_setup_done failed");
340 diff_tree_sha1(head, new_head, "", &opts);
341 diffcore_std(&opts);
342 diff_flush(&opts);
345 /* Run a post-merge hook */
346 run_hook("post-merge");
348 strbuf_release(&reflog_message);
351 /* Get the name for the merge commit's message. */
352 static void merge_name(const char *remote, struct strbuf *msg)
354 struct object *remote_head;
355 unsigned char branch_head[20], buf_sha[20];
356 struct strbuf buf;
357 const char *ptr;
358 int len, early;
360 memset(branch_head, 0, sizeof(branch_head));
361 remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
362 if (!remote_head)
363 die("'%s' does not point to a commit", remote);
365 strbuf_init(&buf, 0);
366 strbuf_addstr(&buf, "refs/heads/");
367 strbuf_addstr(&buf, remote);
368 resolve_ref(buf.buf, branch_head, 0, 0);
370 if (!hashcmp(remote_head->sha1, branch_head)) {
371 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
372 sha1_to_hex(branch_head), remote);
373 return;
376 /* See if remote matches <name>^^^.. or <name>~<number> */
377 for (len = 0, ptr = remote + strlen(remote);
378 remote < ptr && ptr[-1] == '^';
379 ptr--)
380 len++;
381 if (len)
382 early = 1;
383 else {
384 early = 0;
385 ptr = strrchr(remote, '~');
386 if (ptr) {
387 int seen_nonzero = 0;
389 len++; /* count ~ */
390 while (*++ptr && isdigit(*ptr)) {
391 seen_nonzero |= (*ptr != '0');
392 len++;
394 if (*ptr)
395 len = 0; /* not ...~<number> */
396 else if (seen_nonzero)
397 early = 1;
398 else if (len == 1)
399 early = 1; /* "name~" is "name~1"! */
402 if (len) {
403 struct strbuf truname = STRBUF_INIT;
404 strbuf_addstr(&truname, "refs/heads/");
405 strbuf_addstr(&truname, remote);
406 strbuf_setlen(&truname, len+11);
407 if (resolve_ref(truname.buf, buf_sha, 0, 0)) {
408 strbuf_addf(msg,
409 "%s\t\tbranch '%s'%s of .\n",
410 sha1_to_hex(remote_head->sha1),
411 truname.buf,
412 (early ? " (early part)" : ""));
413 return;
417 if (!strcmp(remote, "FETCH_HEAD") &&
418 !access(git_path("FETCH_HEAD"), R_OK)) {
419 FILE *fp;
420 struct strbuf line;
421 char *ptr;
423 strbuf_init(&line, 0);
424 fp = fopen(git_path("FETCH_HEAD"), "r");
425 if (!fp)
426 die("could not open %s for reading: %s",
427 git_path("FETCH_HEAD"), strerror(errno));
428 strbuf_getline(&line, fp, '\n');
429 fclose(fp);
430 ptr = strstr(line.buf, "\tnot-for-merge\t");
431 if (ptr)
432 strbuf_remove(&line, ptr-line.buf+1, 13);
433 strbuf_addbuf(msg, &line);
434 strbuf_release(&line);
435 return;
437 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
438 sha1_to_hex(remote_head->sha1), remote);
441 int git_merge_config(const char *k, const char *v, void *cb)
443 if (branch && !prefixcmp(k, "branch.") &&
444 !prefixcmp(k + 7, branch) &&
445 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
446 const char **argv;
447 int argc;
448 char *buf;
450 buf = xstrdup(v);
451 argc = split_cmdline(buf, &argv);
452 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
453 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
454 argc++;
455 parse_options(argc, argv, builtin_merge_options,
456 builtin_merge_usage, 0);
457 free(buf);
460 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
461 show_diffstat = git_config_bool(k, v);
462 else if (!strcmp(k, "pull.twohead"))
463 return git_config_string(&pull_twohead, k, v);
464 else if (!strcmp(k, "pull.octopus"))
465 return git_config_string(&pull_octopus, k, v);
466 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary"))
467 option_log = git_config_bool(k, v);
468 return git_diff_ui_config(k, v, cb);
471 static int read_tree_trivial(unsigned char *common, unsigned char *head,
472 unsigned char *one)
474 int i, nr_trees = 0;
475 struct tree *trees[MAX_UNPACK_TREES];
476 struct tree_desc t[MAX_UNPACK_TREES];
477 struct unpack_trees_options opts;
479 memset(&opts, 0, sizeof(opts));
480 opts.head_idx = 2;
481 opts.src_index = &the_index;
482 opts.dst_index = &the_index;
483 opts.update = 1;
484 opts.verbose_update = 1;
485 opts.trivial_merges_only = 1;
486 opts.merge = 1;
487 trees[nr_trees] = parse_tree_indirect(common);
488 if (!trees[nr_trees++])
489 return -1;
490 trees[nr_trees] = parse_tree_indirect(head);
491 if (!trees[nr_trees++])
492 return -1;
493 trees[nr_trees] = parse_tree_indirect(one);
494 if (!trees[nr_trees++])
495 return -1;
496 opts.fn = threeway_merge;
497 cache_tree_free(&active_cache_tree);
498 for (i = 0; i < nr_trees; i++) {
499 parse_tree(trees[i]);
500 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
502 if (unpack_trees(nr_trees, t, &opts))
503 return -1;
504 return 0;
507 static void write_tree_trivial(unsigned char *sha1)
509 if (write_cache_as_tree(sha1, 0, NULL))
510 die("git write-tree failed to write a tree");
513 static int try_merge_strategy(const char *strategy, struct commit_list *common,
514 const char *head_arg)
516 const char **args;
517 int i = 0, ret;
518 struct commit_list *j;
519 struct strbuf buf;
521 args = xmalloc((4 + commit_list_count(common) +
522 commit_list_count(remoteheads)) * sizeof(char *));
523 strbuf_init(&buf, 0);
524 strbuf_addf(&buf, "merge-%s", strategy);
525 args[i++] = buf.buf;
526 for (j = common; j; j = j->next)
527 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
528 args[i++] = "--";
529 args[i++] = head_arg;
530 for (j = remoteheads; j; j = j->next)
531 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
532 args[i] = NULL;
533 ret = run_command_v_opt(args, RUN_GIT_CMD);
534 strbuf_release(&buf);
535 i = 1;
536 for (j = common; j; j = j->next)
537 free((void *)args[i++]);
538 i += 2;
539 for (j = remoteheads; j; j = j->next)
540 free((void *)args[i++]);
541 free(args);
542 return -ret;
545 static void count_diff_files(struct diff_queue_struct *q,
546 struct diff_options *opt, void *data)
548 int *count = data;
550 (*count) += q->nr;
553 static int count_unmerged_entries(void)
555 const struct index_state *state = &the_index;
556 int i, ret = 0;
558 for (i = 0; i < state->cache_nr; i++)
559 if (ce_stage(state->cache[i]))
560 ret++;
562 return ret;
565 static int checkout_fast_forward(unsigned char *head, unsigned char *remote)
567 struct tree *trees[MAX_UNPACK_TREES];
568 struct unpack_trees_options opts;
569 struct tree_desc t[MAX_UNPACK_TREES];
570 int i, fd, nr_trees = 0;
571 struct dir_struct dir;
572 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
574 if (read_cache_unmerged())
575 die("you need to resolve your current index first");
577 fd = hold_locked_index(lock_file, 1);
579 memset(&trees, 0, sizeof(trees));
580 memset(&opts, 0, sizeof(opts));
581 memset(&t, 0, sizeof(t));
582 dir.show_ignored = 1;
583 dir.exclude_per_dir = ".gitignore";
584 opts.dir = &dir;
586 opts.head_idx = 1;
587 opts.src_index = &the_index;
588 opts.dst_index = &the_index;
589 opts.update = 1;
590 opts.verbose_update = 1;
591 opts.merge = 1;
592 opts.fn = twoway_merge;
594 trees[nr_trees] = parse_tree_indirect(head);
595 if (!trees[nr_trees++])
596 return -1;
597 trees[nr_trees] = parse_tree_indirect(remote);
598 if (!trees[nr_trees++])
599 return -1;
600 for (i = 0; i < nr_trees; i++) {
601 parse_tree(trees[i]);
602 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
604 if (unpack_trees(nr_trees, t, &opts))
605 return -1;
606 if (write_cache(fd, active_cache, active_nr) ||
607 commit_locked_index(lock_file))
608 die("unable to write new index file");
609 return 0;
612 static void split_merge_strategies(const char *string, struct strategy **list,
613 int *nr, int *alloc)
615 char *p, *q, *buf;
617 if (!string)
618 return;
620 buf = xstrdup(string);
621 q = buf;
622 for (;;) {
623 p = strchr(q, ' ');
624 if (!p) {
625 ALLOC_GROW(*list, *nr + 1, *alloc);
626 (*list)[(*nr)++].name = xstrdup(q);
627 free(buf);
628 return;
629 } else {
630 *p = '\0';
631 ALLOC_GROW(*list, *nr + 1, *alloc);
632 (*list)[(*nr)++].name = xstrdup(q);
633 q = ++p;
638 static void add_strategies(const char *string, unsigned attr)
640 struct strategy *list = NULL;
641 int list_alloc = 0, list_nr = 0, i;
643 memset(&list, 0, sizeof(list));
644 split_merge_strategies(string, &list, &list_nr, &list_alloc);
645 if (list != NULL) {
646 for (i = 0; i < list_nr; i++) {
647 struct strategy *s;
649 s = get_strategy(list[i].name);
650 if (s)
651 append_strategy(s);
653 return;
655 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
656 if (all_strategy[i].attr & attr)
657 append_strategy(&all_strategy[i]);
661 static int merge_trivial(void)
663 unsigned char result_tree[20], result_commit[20];
664 struct commit_list parent;
666 write_tree_trivial(result_tree);
667 printf("Wonderful.\n");
668 parent.item = remoteheads->item;
669 parent.next = NULL;
670 commit_tree(merge_msg.buf, result_tree, &parent, result_commit);
671 finish(result_commit, "In-index merge");
672 drop_save();
673 return 0;
676 static int finish_automerge(struct commit_list *common,
677 unsigned char *result_tree,
678 const char *wt_strategy)
680 struct commit_list *parents = NULL, *j;
681 struct strbuf buf = STRBUF_INIT;
682 unsigned char result_commit[20];
684 free_commit_list(common);
685 if (allow_fast_forward) {
686 parents = remoteheads;
687 commit_list_insert(lookup_commit(head), &parents);
688 parents = reduce_heads(parents);
689 } else {
690 struct commit_list **pptr = &parents;
692 pptr = &commit_list_insert(lookup_commit(head),
693 pptr)->next;
694 for (j = remoteheads; j; j = j->next)
695 pptr = &commit_list_insert(j->item, pptr)->next;
697 free_commit_list(remoteheads);
698 strbuf_addch(&merge_msg, '\n');
699 commit_tree(merge_msg.buf, result_tree, parents, result_commit);
700 strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
701 finish(result_commit, buf.buf);
702 strbuf_release(&buf);
703 drop_save();
704 return 0;
707 static int suggest_conflicts(void)
709 FILE *fp;
710 int pos;
712 fp = fopen(git_path("MERGE_MSG"), "a");
713 if (!fp)
714 die("Could open %s for writing", git_path("MERGE_MSG"));
715 fprintf(fp, "\nConflicts:\n");
716 for (pos = 0; pos < active_nr; pos++) {
717 struct cache_entry *ce = active_cache[pos];
719 if (ce_stage(ce)) {
720 fprintf(fp, "\t%s\n", ce->name);
721 while (pos + 1 < active_nr &&
722 !strcmp(ce->name,
723 active_cache[pos + 1]->name))
724 pos++;
727 fclose(fp);
728 rerere();
729 printf("Automatic merge failed; "
730 "fix conflicts and then commit the result.\n");
731 return 1;
734 static struct commit *is_old_style_invocation(int argc, const char **argv)
736 struct commit *second_token = NULL;
737 if (argc > 1) {
738 unsigned char second_sha1[20];
740 if (get_sha1(argv[1], second_sha1))
741 return NULL;
742 second_token = lookup_commit_reference_gently(second_sha1, 0);
743 if (!second_token)
744 die("'%s' is not a commit", argv[1]);
745 if (hashcmp(second_token->object.sha1, head))
746 return NULL;
748 return second_token;
751 static int evaluate_result(void)
753 int cnt = 0;
754 struct rev_info rev;
756 if (read_cache() < 0)
757 die("failed to read the cache");
759 /* Check how many files differ. */
760 init_revisions(&rev, "");
761 setup_revisions(0, NULL, &rev, NULL);
762 rev.diffopt.output_format |=
763 DIFF_FORMAT_CALLBACK;
764 rev.diffopt.format_callback = count_diff_files;
765 rev.diffopt.format_callback_data = &cnt;
766 run_diff_files(&rev, 0);
769 * Check how many unmerged entries are
770 * there.
772 cnt += count_unmerged_entries();
774 return cnt;
777 int cmd_merge(int argc, const char **argv, const char *prefix)
779 unsigned char result_tree[20];
780 struct strbuf buf;
781 const char *head_arg;
782 int flag, head_invalid = 0, i;
783 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
784 struct commit_list *common = NULL;
785 const char *best_strategy = NULL, *wt_strategy = NULL;
786 struct commit_list **remotes = &remoteheads;
788 setup_work_tree();
789 if (unmerged_cache())
790 die("You are in the middle of a conflicted merge.");
793 * Check if we are _not_ on a detached HEAD, i.e. if there is a
794 * current branch.
796 branch = resolve_ref("HEAD", head, 0, &flag);
797 if (branch && !prefixcmp(branch, "refs/heads/"))
798 branch += 11;
799 if (is_null_sha1(head))
800 head_invalid = 1;
802 git_config(git_merge_config, NULL);
804 /* for color.ui */
805 if (diff_use_color_default == -1)
806 diff_use_color_default = git_use_color_default;
808 argc = parse_options(argc, argv, builtin_merge_options,
809 builtin_merge_usage, 0);
811 if (squash) {
812 if (!allow_fast_forward)
813 die("You cannot combine --squash with --no-ff.");
814 option_commit = 0;
817 if (!argc)
818 usage_with_options(builtin_merge_usage,
819 builtin_merge_options);
822 * This could be traditional "merge <msg> HEAD <commit>..." and
823 * the way we can tell it is to see if the second token is HEAD,
824 * but some people might have misused the interface and used a
825 * committish that is the same as HEAD there instead.
826 * Traditional format never would have "-m" so it is an
827 * additional safety measure to check for it.
829 strbuf_init(&buf, 0);
831 if (!have_message && is_old_style_invocation(argc, argv)) {
832 strbuf_addstr(&merge_msg, argv[0]);
833 head_arg = argv[1];
834 argv += 2;
835 argc -= 2;
836 } else if (head_invalid) {
837 struct object *remote_head;
839 * If the merged head is a valid one there is no reason
840 * to forbid "git merge" into a branch yet to be born.
841 * We do the same for "git pull".
843 if (argc != 1)
844 die("Can merge only exactly one commit into "
845 "empty head");
846 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
847 if (!remote_head)
848 die("%s - not something we can merge", argv[0]);
849 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
850 DIE_ON_ERR);
851 reset_hard(remote_head->sha1, 0);
852 return 0;
853 } else {
854 struct strbuf msg;
856 /* We are invoked directly as the first-class UI. */
857 head_arg = "HEAD";
860 * All the rest are the commits being merged;
861 * prepare the standard merge summary message to
862 * be appended to the given message. If remote
863 * is invalid we will die later in the common
864 * codepath so we discard the error in this
865 * loop.
867 strbuf_init(&msg, 0);
868 for (i = 0; i < argc; i++)
869 merge_name(argv[i], &msg);
870 fmt_merge_msg(option_log, &msg, &merge_msg);
871 if (merge_msg.len)
872 strbuf_setlen(&merge_msg, merge_msg.len-1);
875 if (head_invalid || !argc)
876 usage_with_options(builtin_merge_usage,
877 builtin_merge_options);
879 strbuf_addstr(&buf, "merge");
880 for (i = 0; i < argc; i++)
881 strbuf_addf(&buf, " %s", argv[i]);
882 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
883 strbuf_reset(&buf);
885 for (i = 0; i < argc; i++) {
886 struct object *o;
888 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
889 if (!o)
890 die("%s - not something we can merge", argv[i]);
891 remotes = &commit_list_insert(lookup_commit(o->sha1),
892 remotes)->next;
894 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
895 setenv(buf.buf, argv[i], 1);
896 strbuf_reset(&buf);
899 if (!use_strategies) {
900 if (!remoteheads->next)
901 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
902 else
903 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
906 for (i = 0; i < use_strategies_nr; i++) {
907 if (use_strategies[i]->attr & NO_FAST_FORWARD)
908 allow_fast_forward = 0;
909 if (use_strategies[i]->attr & NO_TRIVIAL)
910 allow_trivial = 0;
913 if (!remoteheads->next)
914 common = get_merge_bases(lookup_commit(head),
915 remoteheads->item, 1);
916 else {
917 struct commit_list *list = remoteheads;
918 commit_list_insert(lookup_commit(head), &list);
919 common = get_octopus_merge_bases(list);
920 free(list);
923 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
924 DIE_ON_ERR);
926 if (!common)
927 ; /* No common ancestors found. We need a real merge. */
928 else if (!remoteheads->next && !common->next &&
929 common->item == remoteheads->item) {
931 * If head can reach all the merge then we are up to date.
932 * but first the most common case of merging one remote.
934 finish_up_to_date("Already up-to-date.");
935 return 0;
936 } else if (allow_fast_forward && !remoteheads->next &&
937 !common->next &&
938 !hashcmp(common->item->object.sha1, head)) {
939 /* Again the most common case of merging one remote. */
940 struct strbuf msg;
941 struct object *o;
942 char hex[41];
944 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
946 printf("Updating %s..%s\n",
947 hex,
948 find_unique_abbrev(remoteheads->item->object.sha1,
949 DEFAULT_ABBREV));
950 refresh_cache(REFRESH_QUIET);
951 strbuf_init(&msg, 0);
952 strbuf_addstr(&msg, "Fast forward");
953 if (have_message)
954 strbuf_addstr(&msg,
955 " (no commit created; -m option ignored)");
956 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
957 0, NULL, OBJ_COMMIT);
958 if (!o)
959 return 1;
961 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
962 return 1;
964 finish(o->sha1, msg.buf);
965 drop_save();
966 return 0;
967 } else if (!remoteheads->next && common->next)
970 * We are not doing octopus and not fast forward. Need
971 * a real merge.
973 else if (!remoteheads->next && !common->next && option_commit) {
975 * We are not doing octopus, not fast forward, and have
976 * only one common.
978 refresh_cache(REFRESH_QUIET);
979 if (allow_trivial) {
980 /* See if it is really trivial. */
981 git_committer_info(IDENT_ERROR_ON_NO_NAME);
982 printf("Trying really trivial in-index merge...\n");
983 if (!read_tree_trivial(common->item->object.sha1,
984 head, remoteheads->item->object.sha1))
985 return merge_trivial();
986 printf("Nope.\n");
988 } else {
990 * An octopus. If we can reach all the remote we are up
991 * to date.
993 int up_to_date = 1;
994 struct commit_list *j;
996 for (j = remoteheads; j; j = j->next) {
997 struct commit_list *common_one;
1000 * Here we *have* to calculate the individual
1001 * merge_bases again, otherwise "git merge HEAD^
1002 * HEAD^^" would be missed.
1004 common_one = get_merge_bases(lookup_commit(head),
1005 j->item, 1);
1006 if (hashcmp(common_one->item->object.sha1,
1007 j->item->object.sha1)) {
1008 up_to_date = 0;
1009 break;
1012 if (up_to_date) {
1013 finish_up_to_date("Already up-to-date. Yeeah!");
1014 return 0;
1018 /* We are going to make a new commit. */
1019 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1022 * At this point, we need a real merge. No matter what strategy
1023 * we use, it would operate on the index, possibly affecting the
1024 * working tree, and when resolved cleanly, have the desired
1025 * tree in the index -- this means that the index must be in
1026 * sync with the head commit. The strategies are responsible
1027 * to ensure this.
1029 if (use_strategies_nr != 1) {
1031 * Stash away the local changes so that we can try more
1032 * than one.
1034 save_state();
1035 } else {
1036 memcpy(stash, null_sha1, 20);
1039 for (i = 0; i < use_strategies_nr; i++) {
1040 int ret;
1041 if (i) {
1042 printf("Rewinding the tree to pristine...\n");
1043 restore_state();
1045 if (use_strategies_nr != 1)
1046 printf("Trying merge strategy %s...\n",
1047 use_strategies[i]->name);
1049 * Remember which strategy left the state in the working
1050 * tree.
1052 wt_strategy = use_strategies[i]->name;
1054 ret = try_merge_strategy(use_strategies[i]->name,
1055 common, head_arg);
1056 if (!option_commit && !ret) {
1057 merge_was_ok = 1;
1059 * This is necessary here just to avoid writing
1060 * the tree, but later we will *not* exit with
1061 * status code 1 because merge_was_ok is set.
1063 ret = 1;
1066 if (ret) {
1068 * The backend exits with 1 when conflicts are
1069 * left to be resolved, with 2 when it does not
1070 * handle the given merge at all.
1072 if (ret == 1) {
1073 int cnt = evaluate_result();
1075 if (best_cnt <= 0 || cnt <= best_cnt) {
1076 best_strategy = use_strategies[i]->name;
1077 best_cnt = cnt;
1080 if (merge_was_ok)
1081 break;
1082 else
1083 continue;
1086 /* Automerge succeeded. */
1087 write_tree_trivial(result_tree);
1088 automerge_was_ok = 1;
1089 break;
1093 * If we have a resulting tree, that means the strategy module
1094 * auto resolved the merge cleanly.
1096 if (automerge_was_ok)
1097 return finish_automerge(common, result_tree, wt_strategy);
1100 * Pick the result from the best strategy and have the user fix
1101 * it up.
1103 if (!best_strategy) {
1104 restore_state();
1105 if (use_strategies_nr > 1)
1106 fprintf(stderr,
1107 "No merge strategy handled the merge.\n");
1108 else
1109 fprintf(stderr, "Merge with strategy %s failed.\n",
1110 use_strategies[0]->name);
1111 return 2;
1112 } else if (best_strategy == wt_strategy)
1113 ; /* We already have its result in the working tree. */
1114 else {
1115 printf("Rewinding the tree to pristine...\n");
1116 restore_state();
1117 printf("Using the %s to prepare resolving by hand.\n",
1118 best_strategy);
1119 try_merge_strategy(best_strategy, common, head_arg);
1122 if (squash)
1123 finish(NULL, NULL);
1124 else {
1125 int fd;
1126 struct commit_list *j;
1128 for (j = remoteheads; j; j = j->next)
1129 strbuf_addf(&buf, "%s\n",
1130 sha1_to_hex(j->item->object.sha1));
1131 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1132 if (fd < 0)
1133 die("Could open %s for writing",
1134 git_path("MERGE_HEAD"));
1135 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1136 die("Could not write to %s", git_path("MERGE_HEAD"));
1137 close(fd);
1138 strbuf_addch(&merge_msg, '\n');
1139 fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1140 if (fd < 0)
1141 die("Could open %s for writing", git_path("MERGE_MSG"));
1142 if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1143 merge_msg.len)
1144 die("Could not write to %s", git_path("MERGE_MSG"));
1145 close(fd);
1148 if (merge_was_ok) {
1149 fprintf(stderr, "Automatic merge went well; "
1150 "stopped before committing as requested\n");
1151 return 0;
1152 } else
1153 return suggest_conflicts();