builtin/merge.c: reduce parents early
[git/dscho.git] / builtin / merge.c
blob20aeca0b3c29f3c1c0e037b25f630eb0d9bbf34e
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"
25 #include "help.h"
26 #include "merge-recursive.h"
27 #include "resolve-undo.h"
28 #include "remote.h"
29 #include "fmt-merge-msg.h"
30 #include "gpg-interface.h"
32 #define DEFAULT_TWOHEAD (1<<0)
33 #define DEFAULT_OCTOPUS (1<<1)
34 #define NO_FAST_FORWARD (1<<2)
35 #define NO_TRIVIAL (1<<3)
37 struct strategy {
38 const char *name;
39 unsigned attr;
42 static const char * const builtin_merge_usage[] = {
43 "git merge [options] [<commit>...]",
44 "git merge [options] <msg> HEAD <commit>",
45 "git merge --abort",
46 NULL
49 static int show_diffstat = 1, shortlog_len = -1, squash;
50 static int option_commit = 1, allow_fast_forward = 1;
51 static int fast_forward_only, option_edit = -1;
52 static int allow_trivial = 1, have_message;
53 static int overwrite_ignore = 1;
54 static struct strbuf merge_msg = STRBUF_INIT;
55 static struct strategy **use_strategies;
56 static size_t use_strategies_nr, use_strategies_alloc;
57 static const char **xopts;
58 static size_t xopts_nr, xopts_alloc;
59 static const char *branch;
60 static char *branch_mergeoptions;
61 static int option_renormalize;
62 static int verbosity;
63 static int allow_rerere_auto;
64 static int abort_current_merge;
65 static int show_progress = -1;
66 static int default_to_upstream;
67 static const char *sign_commit;
69 static struct strategy all_strategy[] = {
70 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
71 { "octopus", DEFAULT_OCTOPUS },
72 { "resolve", 0 },
73 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
74 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
77 static const char *pull_twohead, *pull_octopus;
79 static int option_parse_message(const struct option *opt,
80 const char *arg, int unset)
82 struct strbuf *buf = opt->value;
84 if (unset)
85 strbuf_setlen(buf, 0);
86 else if (arg) {
87 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
88 have_message = 1;
89 } else
90 return error(_("switch `m' requires a value"));
91 return 0;
94 static struct strategy *get_strategy(const char *name)
96 int i;
97 struct strategy *ret;
98 static struct cmdnames main_cmds, other_cmds;
99 static int loaded;
101 if (!name)
102 return NULL;
104 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
105 if (!strcmp(name, all_strategy[i].name))
106 return &all_strategy[i];
108 if (!loaded) {
109 struct cmdnames not_strategies;
110 loaded = 1;
112 memset(&not_strategies, 0, sizeof(struct cmdnames));
113 load_command_list("git-merge-", &main_cmds, &other_cmds);
114 for (i = 0; i < main_cmds.cnt; i++) {
115 int j, found = 0;
116 struct cmdname *ent = main_cmds.names[i];
117 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
118 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
119 && !all_strategy[j].name[ent->len])
120 found = 1;
121 if (!found)
122 add_cmdname(&not_strategies, ent->name, ent->len);
124 exclude_cmds(&main_cmds, &not_strategies);
126 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
127 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
128 fprintf(stderr, _("Available strategies are:"));
129 for (i = 0; i < main_cmds.cnt; i++)
130 fprintf(stderr, " %s", main_cmds.names[i]->name);
131 fprintf(stderr, ".\n");
132 if (other_cmds.cnt) {
133 fprintf(stderr, _("Available custom strategies are:"));
134 for (i = 0; i < other_cmds.cnt; i++)
135 fprintf(stderr, " %s", other_cmds.names[i]->name);
136 fprintf(stderr, ".\n");
138 exit(1);
141 ret = xcalloc(1, sizeof(struct strategy));
142 ret->name = xstrdup(name);
143 ret->attr = NO_TRIVIAL;
144 return ret;
147 static void append_strategy(struct strategy *s)
149 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
150 use_strategies[use_strategies_nr++] = s;
153 static int option_parse_strategy(const struct option *opt,
154 const char *name, int unset)
156 if (unset)
157 return 0;
159 append_strategy(get_strategy(name));
160 return 0;
163 static int option_parse_x(const struct option *opt,
164 const char *arg, int unset)
166 if (unset)
167 return 0;
169 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
170 xopts[xopts_nr++] = xstrdup(arg);
171 return 0;
174 static int option_parse_n(const struct option *opt,
175 const char *arg, int unset)
177 show_diffstat = unset;
178 return 0;
181 static struct option builtin_merge_options[] = {
182 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
183 "do not show a diffstat at the end of the merge",
184 PARSE_OPT_NOARG, option_parse_n },
185 OPT_BOOLEAN(0, "stat", &show_diffstat,
186 "show a diffstat at the end of the merge"),
187 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
188 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
189 "add (at most <n>) entries from shortlog to merge commit message",
190 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
191 OPT_BOOLEAN(0, "squash", &squash,
192 "create a single commit instead of doing a merge"),
193 OPT_BOOLEAN(0, "commit", &option_commit,
194 "perform a commit if the merge succeeds (default)"),
195 OPT_BOOL('e', "edit", &option_edit,
196 "edit message before committing"),
197 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
198 "allow fast-forward (default)"),
199 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
200 "abort if fast-forward is not possible"),
201 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
202 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
203 "merge strategy to use", option_parse_strategy),
204 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
205 "option for selected merge strategy", option_parse_x),
206 OPT_CALLBACK('m', "message", &merge_msg, "message",
207 "merge commit message (for a non-fast-forward merge)",
208 option_parse_message),
209 OPT__VERBOSITY(&verbosity),
210 OPT_BOOLEAN(0, "abort", &abort_current_merge,
211 "abort the current in-progress merge"),
212 OPT_SET_INT(0, "progress", &show_progress, "force progress reporting", 1),
213 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, "key id",
214 "GPG sign commit", PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
215 OPT_BOOLEAN(0, "overwrite-ignore", &overwrite_ignore, "update ignored files (default)"),
216 OPT_END()
219 /* Cleans up metadata that is uninteresting after a succeeded merge. */
220 static void drop_save(void)
222 unlink(git_path("MERGE_HEAD"));
223 unlink(git_path("MERGE_MSG"));
224 unlink(git_path("MERGE_MODE"));
227 static int save_state(unsigned char *stash)
229 int len;
230 struct child_process cp;
231 struct strbuf buffer = STRBUF_INIT;
232 const char *argv[] = {"stash", "create", NULL};
234 memset(&cp, 0, sizeof(cp));
235 cp.argv = argv;
236 cp.out = -1;
237 cp.git_cmd = 1;
239 if (start_command(&cp))
240 die(_("could not run stash."));
241 len = strbuf_read(&buffer, cp.out, 1024);
242 close(cp.out);
244 if (finish_command(&cp) || len < 0)
245 die(_("stash failed"));
246 else if (!len) /* no changes */
247 return -1;
248 strbuf_setlen(&buffer, buffer.len-1);
249 if (get_sha1(buffer.buf, stash))
250 die(_("not a valid object: %s"), buffer.buf);
251 return 0;
254 static void read_empty(unsigned const char *sha1, int verbose)
256 int i = 0;
257 const char *args[7];
259 args[i++] = "read-tree";
260 if (verbose)
261 args[i++] = "-v";
262 args[i++] = "-m";
263 args[i++] = "-u";
264 args[i++] = EMPTY_TREE_SHA1_HEX;
265 args[i++] = sha1_to_hex(sha1);
266 args[i] = NULL;
268 if (run_command_v_opt(args, RUN_GIT_CMD))
269 die(_("read-tree failed"));
272 static void reset_hard(unsigned const char *sha1, int verbose)
274 int i = 0;
275 const char *args[6];
277 args[i++] = "read-tree";
278 if (verbose)
279 args[i++] = "-v";
280 args[i++] = "--reset";
281 args[i++] = "-u";
282 args[i++] = sha1_to_hex(sha1);
283 args[i] = NULL;
285 if (run_command_v_opt(args, RUN_GIT_CMD))
286 die(_("read-tree failed"));
289 static void restore_state(const unsigned char *head,
290 const unsigned char *stash)
292 struct strbuf sb = STRBUF_INIT;
293 const char *args[] = { "stash", "apply", NULL, NULL };
295 if (is_null_sha1(stash))
296 return;
298 reset_hard(head, 1);
300 args[2] = sha1_to_hex(stash);
303 * It is OK to ignore error here, for example when there was
304 * nothing to restore.
306 run_command_v_opt(args, RUN_GIT_CMD);
308 strbuf_release(&sb);
309 refresh_cache(REFRESH_QUIET);
312 /* This is called when no merge was necessary. */
313 static void finish_up_to_date(const char *msg)
315 if (verbosity >= 0)
316 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
317 drop_save();
320 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
322 struct rev_info rev;
323 struct strbuf out = STRBUF_INIT;
324 struct commit_list *j;
325 const char *filename;
326 int fd;
327 struct pretty_print_context ctx = {0};
329 printf(_("Squash commit -- not updating HEAD\n"));
330 filename = git_path("SQUASH_MSG");
331 fd = open(filename, O_WRONLY | O_CREAT, 0666);
332 if (fd < 0)
333 die_errno(_("Could not write to '%s'"), filename);
335 init_revisions(&rev, NULL);
336 rev.ignore_merges = 1;
337 rev.commit_format = CMIT_FMT_MEDIUM;
339 commit->object.flags |= UNINTERESTING;
340 add_pending_object(&rev, &commit->object, NULL);
342 for (j = remoteheads; j; j = j->next)
343 add_pending_object(&rev, &j->item->object, NULL);
345 setup_revisions(0, NULL, &rev, NULL);
346 if (prepare_revision_walk(&rev))
347 die(_("revision walk setup failed"));
349 ctx.abbrev = rev.abbrev;
350 ctx.date_mode = rev.date_mode;
351 ctx.fmt = rev.commit_format;
353 strbuf_addstr(&out, "Squashed commit of the following:\n");
354 while ((commit = get_revision(&rev)) != NULL) {
355 strbuf_addch(&out, '\n');
356 strbuf_addf(&out, "commit %s\n",
357 sha1_to_hex(commit->object.sha1));
358 pretty_print_commit(&ctx, commit, &out);
360 if (write(fd, out.buf, out.len) < 0)
361 die_errno(_("Writing SQUASH_MSG"));
362 if (close(fd))
363 die_errno(_("Finishing SQUASH_MSG"));
364 strbuf_release(&out);
367 static void finish(struct commit *head_commit,
368 struct commit_list *remoteheads,
369 const unsigned char *new_head, const char *msg)
371 struct strbuf reflog_message = STRBUF_INIT;
372 const unsigned char *head = head_commit->object.sha1;
374 if (!msg)
375 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
376 else {
377 if (verbosity >= 0)
378 printf("%s\n", msg);
379 strbuf_addf(&reflog_message, "%s: %s",
380 getenv("GIT_REFLOG_ACTION"), msg);
382 if (squash) {
383 squash_message(head_commit, remoteheads);
384 } else {
385 if (verbosity >= 0 && !merge_msg.len)
386 printf(_("No merge message -- not updating HEAD\n"));
387 else {
388 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
389 update_ref(reflog_message.buf, "HEAD",
390 new_head, head, 0,
391 DIE_ON_ERR);
393 * We ignore errors in 'gc --auto', since the
394 * user should see them.
396 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
399 if (new_head && show_diffstat) {
400 struct diff_options opts;
401 diff_setup(&opts);
402 opts.output_format |=
403 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
404 opts.detect_rename = DIFF_DETECT_RENAME;
405 if (diff_setup_done(&opts) < 0)
406 die(_("diff_setup_done failed"));
407 diff_tree_sha1(head, new_head, "", &opts);
408 diffcore_std(&opts);
409 diff_flush(&opts);
412 /* Run a post-merge hook */
413 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
415 strbuf_release(&reflog_message);
418 /* Get the name for the merge commit's message. */
419 static void merge_name(const char *remote, struct strbuf *msg)
421 struct commit *remote_head;
422 unsigned char branch_head[20];
423 struct strbuf buf = STRBUF_INIT;
424 struct strbuf bname = STRBUF_INIT;
425 const char *ptr;
426 char *found_ref;
427 int len, early;
429 strbuf_branchname(&bname, remote);
430 remote = bname.buf;
432 memset(branch_head, 0, sizeof(branch_head));
433 remote_head = get_merge_parent(remote);
434 if (!remote_head)
435 die(_("'%s' does not point to a commit"), remote);
437 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
438 if (!prefixcmp(found_ref, "refs/heads/")) {
439 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
440 sha1_to_hex(branch_head), remote);
441 goto cleanup;
443 if (!prefixcmp(found_ref, "refs/tags/")) {
444 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
445 sha1_to_hex(branch_head), remote);
446 goto cleanup;
448 if (!prefixcmp(found_ref, "refs/remotes/")) {
449 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
450 sha1_to_hex(branch_head), remote);
451 goto cleanup;
455 /* See if remote matches <name>^^^.. or <name>~<number> */
456 for (len = 0, ptr = remote + strlen(remote);
457 remote < ptr && ptr[-1] == '^';
458 ptr--)
459 len++;
460 if (len)
461 early = 1;
462 else {
463 early = 0;
464 ptr = strrchr(remote, '~');
465 if (ptr) {
466 int seen_nonzero = 0;
468 len++; /* count ~ */
469 while (*++ptr && isdigit(*ptr)) {
470 seen_nonzero |= (*ptr != '0');
471 len++;
473 if (*ptr)
474 len = 0; /* not ...~<number> */
475 else if (seen_nonzero)
476 early = 1;
477 else if (len == 1)
478 early = 1; /* "name~" is "name~1"! */
481 if (len) {
482 struct strbuf truname = STRBUF_INIT;
483 strbuf_addstr(&truname, "refs/heads/");
484 strbuf_addstr(&truname, remote);
485 strbuf_setlen(&truname, truname.len - len);
486 if (ref_exists(truname.buf)) {
487 strbuf_addf(msg,
488 "%s\t\tbranch '%s'%s of .\n",
489 sha1_to_hex(remote_head->object.sha1),
490 truname.buf + 11,
491 (early ? " (early part)" : ""));
492 strbuf_release(&truname);
493 goto cleanup;
497 if (!strcmp(remote, "FETCH_HEAD") &&
498 !access(git_path("FETCH_HEAD"), R_OK)) {
499 const char *filename;
500 FILE *fp;
501 struct strbuf line = STRBUF_INIT;
502 char *ptr;
504 filename = git_path("FETCH_HEAD");
505 fp = fopen(filename, "r");
506 if (!fp)
507 die_errno(_("could not open '%s' for reading"),
508 filename);
509 strbuf_getline(&line, fp, '\n');
510 fclose(fp);
511 ptr = strstr(line.buf, "\tnot-for-merge\t");
512 if (ptr)
513 strbuf_remove(&line, ptr-line.buf+1, 13);
514 strbuf_addbuf(msg, &line);
515 strbuf_release(&line);
516 goto cleanup;
518 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
519 sha1_to_hex(remote_head->object.sha1), remote);
520 cleanup:
521 strbuf_release(&buf);
522 strbuf_release(&bname);
525 static void parse_branch_merge_options(char *bmo)
527 const char **argv;
528 int argc;
530 if (!bmo)
531 return;
532 argc = split_cmdline(bmo, &argv);
533 if (argc < 0)
534 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
535 split_cmdline_strerror(argc));
536 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
537 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
538 argc++;
539 argv[0] = "branch.*.mergeoptions";
540 parse_options(argc, argv, NULL, builtin_merge_options,
541 builtin_merge_usage, 0);
542 free(argv);
545 static int git_merge_config(const char *k, const char *v, void *cb)
547 int status;
549 if (branch && !prefixcmp(k, "branch.") &&
550 !prefixcmp(k + 7, branch) &&
551 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
552 free(branch_mergeoptions);
553 branch_mergeoptions = xstrdup(v);
554 return 0;
557 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
558 show_diffstat = git_config_bool(k, v);
559 else if (!strcmp(k, "pull.twohead"))
560 return git_config_string(&pull_twohead, k, v);
561 else if (!strcmp(k, "pull.octopus"))
562 return git_config_string(&pull_octopus, k, v);
563 else if (!strcmp(k, "merge.renormalize"))
564 option_renormalize = git_config_bool(k, v);
565 else if (!strcmp(k, "merge.ff")) {
566 int boolval = git_config_maybe_bool(k, v);
567 if (0 <= boolval) {
568 allow_fast_forward = boolval;
569 } else if (v && !strcmp(v, "only")) {
570 allow_fast_forward = 1;
571 fast_forward_only = 1;
572 } /* do not barf on values from future versions of git */
573 return 0;
574 } else if (!strcmp(k, "merge.defaulttoupstream")) {
575 default_to_upstream = git_config_bool(k, v);
576 return 0;
579 status = fmt_merge_msg_config(k, v, cb);
580 if (status)
581 return status;
582 status = git_gpg_config(k, v, NULL);
583 if (status)
584 return status;
585 return git_diff_ui_config(k, v, cb);
588 static int read_tree_trivial(unsigned char *common, unsigned char *head,
589 unsigned char *one)
591 int i, nr_trees = 0;
592 struct tree *trees[MAX_UNPACK_TREES];
593 struct tree_desc t[MAX_UNPACK_TREES];
594 struct unpack_trees_options opts;
596 memset(&opts, 0, sizeof(opts));
597 opts.head_idx = 2;
598 opts.src_index = &the_index;
599 opts.dst_index = &the_index;
600 opts.update = 1;
601 opts.verbose_update = 1;
602 opts.trivial_merges_only = 1;
603 opts.merge = 1;
604 trees[nr_trees] = parse_tree_indirect(common);
605 if (!trees[nr_trees++])
606 return -1;
607 trees[nr_trees] = parse_tree_indirect(head);
608 if (!trees[nr_trees++])
609 return -1;
610 trees[nr_trees] = parse_tree_indirect(one);
611 if (!trees[nr_trees++])
612 return -1;
613 opts.fn = threeway_merge;
614 cache_tree_free(&active_cache_tree);
615 for (i = 0; i < nr_trees; i++) {
616 parse_tree(trees[i]);
617 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
619 if (unpack_trees(nr_trees, t, &opts))
620 return -1;
621 return 0;
624 static void write_tree_trivial(unsigned char *sha1)
626 if (write_cache_as_tree(sha1, 0, NULL))
627 die(_("git write-tree failed to write a tree"));
630 static const char *merge_argument(struct commit *commit)
632 if (commit)
633 return sha1_to_hex(commit->object.sha1);
634 else
635 return EMPTY_TREE_SHA1_HEX;
638 int try_merge_command(const char *strategy, size_t xopts_nr,
639 const char **xopts, struct commit_list *common,
640 const char *head_arg, struct commit_list *remotes)
642 const char **args;
643 int i = 0, x = 0, ret;
644 struct commit_list *j;
645 struct strbuf buf = STRBUF_INIT;
647 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
648 commit_list_count(remotes)) * sizeof(char *));
649 strbuf_addf(&buf, "merge-%s", strategy);
650 args[i++] = buf.buf;
651 for (x = 0; x < xopts_nr; x++) {
652 char *s = xmalloc(strlen(xopts[x])+2+1);
653 strcpy(s, "--");
654 strcpy(s+2, xopts[x]);
655 args[i++] = s;
657 for (j = common; j; j = j->next)
658 args[i++] = xstrdup(merge_argument(j->item));
659 args[i++] = "--";
660 args[i++] = head_arg;
661 for (j = remotes; j; j = j->next)
662 args[i++] = xstrdup(merge_argument(j->item));
663 args[i] = NULL;
664 ret = run_command_v_opt(args, RUN_GIT_CMD);
665 strbuf_release(&buf);
666 i = 1;
667 for (x = 0; x < xopts_nr; x++)
668 free((void *)args[i++]);
669 for (j = common; j; j = j->next)
670 free((void *)args[i++]);
671 i += 2;
672 for (j = remotes; j; j = j->next)
673 free((void *)args[i++]);
674 free(args);
675 discard_cache();
676 if (read_cache() < 0)
677 die(_("failed to read the cache"));
678 resolve_undo_clear();
680 return ret;
683 static int try_merge_strategy(const char *strategy, struct commit_list *common,
684 struct commit_list *remoteheads,
685 struct commit *head, const char *head_arg)
687 int index_fd;
688 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
690 index_fd = hold_locked_index(lock, 1);
691 refresh_cache(REFRESH_QUIET);
692 if (active_cache_changed &&
693 (write_cache(index_fd, active_cache, active_nr) ||
694 commit_locked_index(lock)))
695 return error(_("Unable to write index."));
696 rollback_lock_file(lock);
698 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
699 int clean, x;
700 struct commit *result;
701 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
702 int index_fd;
703 struct commit_list *reversed = NULL;
704 struct merge_options o;
705 struct commit_list *j;
707 if (remoteheads->next) {
708 error(_("Not handling anything other than two heads merge."));
709 return 2;
712 init_merge_options(&o);
713 if (!strcmp(strategy, "subtree"))
714 o.subtree_shift = "";
716 o.renormalize = option_renormalize;
717 o.show_rename_progress =
718 show_progress == -1 ? isatty(2) : show_progress;
720 for (x = 0; x < xopts_nr; x++)
721 if (parse_merge_opt(&o, xopts[x]))
722 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
724 o.branch1 = head_arg;
725 o.branch2 = merge_remote_util(remoteheads->item)->name;
727 for (j = common; j; j = j->next)
728 commit_list_insert(j->item, &reversed);
730 index_fd = hold_locked_index(lock, 1);
731 clean = merge_recursive(&o, head,
732 remoteheads->item, reversed, &result);
733 if (active_cache_changed &&
734 (write_cache(index_fd, active_cache, active_nr) ||
735 commit_locked_index(lock)))
736 die (_("unable to write %s"), get_index_file());
737 rollback_lock_file(lock);
738 return clean ? 0 : 1;
739 } else {
740 return try_merge_command(strategy, xopts_nr, xopts,
741 common, head_arg, remoteheads);
745 static void count_diff_files(struct diff_queue_struct *q,
746 struct diff_options *opt, void *data)
748 int *count = data;
750 (*count) += q->nr;
753 static int count_unmerged_entries(void)
755 int i, ret = 0;
757 for (i = 0; i < active_nr; i++)
758 if (ce_stage(active_cache[i]))
759 ret++;
761 return ret;
764 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
766 struct tree *trees[MAX_UNPACK_TREES];
767 struct unpack_trees_options opts;
768 struct tree_desc t[MAX_UNPACK_TREES];
769 int i, fd, nr_trees = 0;
770 struct dir_struct dir;
771 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
773 refresh_cache(REFRESH_QUIET);
775 fd = hold_locked_index(lock_file, 1);
777 memset(&trees, 0, sizeof(trees));
778 memset(&opts, 0, sizeof(opts));
779 memset(&t, 0, sizeof(t));
780 if (overwrite_ignore) {
781 memset(&dir, 0, sizeof(dir));
782 dir.flags |= DIR_SHOW_IGNORED;
783 setup_standard_excludes(&dir);
784 opts.dir = &dir;
787 opts.head_idx = 1;
788 opts.src_index = &the_index;
789 opts.dst_index = &the_index;
790 opts.update = 1;
791 opts.verbose_update = 1;
792 opts.merge = 1;
793 opts.fn = twoway_merge;
794 setup_unpack_trees_porcelain(&opts, "merge");
796 trees[nr_trees] = parse_tree_indirect(head);
797 if (!trees[nr_trees++])
798 return -1;
799 trees[nr_trees] = parse_tree_indirect(remote);
800 if (!trees[nr_trees++])
801 return -1;
802 for (i = 0; i < nr_trees; i++) {
803 parse_tree(trees[i]);
804 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
806 if (unpack_trees(nr_trees, t, &opts))
807 return -1;
808 if (write_cache(fd, active_cache, active_nr) ||
809 commit_locked_index(lock_file))
810 die(_("unable to write new index file"));
811 return 0;
814 static void split_merge_strategies(const char *string, struct strategy **list,
815 int *nr, int *alloc)
817 char *p, *q, *buf;
819 if (!string)
820 return;
822 buf = xstrdup(string);
823 q = buf;
824 for (;;) {
825 p = strchr(q, ' ');
826 if (!p) {
827 ALLOC_GROW(*list, *nr + 1, *alloc);
828 (*list)[(*nr)++].name = xstrdup(q);
829 free(buf);
830 return;
831 } else {
832 *p = '\0';
833 ALLOC_GROW(*list, *nr + 1, *alloc);
834 (*list)[(*nr)++].name = xstrdup(q);
835 q = ++p;
840 static void add_strategies(const char *string, unsigned attr)
842 struct strategy *list = NULL;
843 int list_alloc = 0, list_nr = 0, i;
845 memset(&list, 0, sizeof(list));
846 split_merge_strategies(string, &list, &list_nr, &list_alloc);
847 if (list) {
848 for (i = 0; i < list_nr; i++)
849 append_strategy(get_strategy(list[i].name));
850 return;
852 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
853 if (all_strategy[i].attr & attr)
854 append_strategy(&all_strategy[i]);
858 static void write_merge_msg(struct strbuf *msg)
860 const char *filename = git_path("MERGE_MSG");
861 int fd = open(filename, O_WRONLY | O_CREAT, 0666);
862 if (fd < 0)
863 die_errno(_("Could not open '%s' for writing"),
864 filename);
865 if (write_in_full(fd, msg->buf, msg->len) != msg->len)
866 die_errno(_("Could not write to '%s'"), filename);
867 close(fd);
870 static void read_merge_msg(struct strbuf *msg)
872 const char *filename = git_path("MERGE_MSG");
873 strbuf_reset(msg);
874 if (strbuf_read_file(msg, filename, 0) < 0)
875 die_errno(_("Could not read from '%s'"), filename);
878 static void write_merge_state(struct commit_list *);
879 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
881 if (err_msg)
882 error("%s", err_msg);
883 fprintf(stderr,
884 _("Not committing merge; use 'git commit' to complete the merge.\n"));
885 write_merge_state(remoteheads);
886 exit(1);
889 static const char merge_editor_comment[] =
890 N_("Please enter a commit message to explain why this merge is necessary,\n"
891 "especially if it merges an updated upstream into a topic branch.\n"
892 "\n"
893 "Lines starting with '#' will be ignored, and an empty message aborts\n"
894 "the commit.\n");
896 static void prepare_to_commit(struct commit_list *remoteheads)
898 struct strbuf msg = STRBUF_INIT;
899 const char *comment = _(merge_editor_comment);
900 strbuf_addbuf(&msg, &merge_msg);
901 strbuf_addch(&msg, '\n');
902 if (0 < option_edit)
903 strbuf_add_lines(&msg, "# ", comment, strlen(comment));
904 write_merge_msg(&msg);
905 run_hook(get_index_file(), "prepare-commit-msg",
906 git_path("MERGE_MSG"), "merge", NULL, NULL);
907 if (option_edit) {
908 if (launch_editor(git_path("MERGE_MSG"), NULL, NULL))
909 abort_commit(remoteheads, NULL);
911 read_merge_msg(&msg);
912 stripspace(&msg, option_edit);
913 if (!msg.len)
914 abort_commit(remoteheads, _("Empty commit message."));
915 strbuf_release(&merge_msg);
916 strbuf_addbuf(&merge_msg, &msg);
917 strbuf_release(&msg);
920 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
922 unsigned char result_tree[20], result_commit[20];
923 struct commit_list *parent = xmalloc(sizeof(*parent));
925 write_tree_trivial(result_tree);
926 printf(_("Wonderful.\n"));
927 parent->item = head;
928 parent->next = xmalloc(sizeof(*parent->next));
929 parent->next->item = remoteheads->item;
930 parent->next->next = NULL;
931 prepare_to_commit(remoteheads);
932 if (commit_tree(&merge_msg, result_tree, parent, result_commit, NULL,
933 sign_commit))
934 die(_("failed to write commit object"));
935 finish(head, remoteheads, result_commit, "In-index merge");
936 drop_save();
937 return 0;
940 static int finish_automerge(struct commit *head,
941 int head_subsumed,
942 struct commit_list *common,
943 struct commit_list *remoteheads,
944 unsigned char *result_tree,
945 const char *wt_strategy)
947 struct commit_list *parents = NULL;
948 struct strbuf buf = STRBUF_INIT;
949 unsigned char result_commit[20];
951 free_commit_list(common);
952 parents = remoteheads;
953 if (!head_subsumed || !allow_fast_forward)
954 commit_list_insert(head, &parents);
955 strbuf_addch(&merge_msg, '\n');
956 prepare_to_commit(remoteheads);
957 if (commit_tree(&merge_msg, result_tree, parents, result_commit,
958 NULL, sign_commit))
959 die(_("failed to write commit object"));
960 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
961 finish(head, remoteheads, result_commit, buf.buf);
962 strbuf_release(&buf);
963 drop_save();
964 return 0;
967 static int suggest_conflicts(int renormalizing)
969 const char *filename;
970 FILE *fp;
971 int pos;
973 filename = git_path("MERGE_MSG");
974 fp = fopen(filename, "a");
975 if (!fp)
976 die_errno(_("Could not open '%s' for writing"), filename);
977 fprintf(fp, "\nConflicts:\n");
978 for (pos = 0; pos < active_nr; pos++) {
979 struct cache_entry *ce = active_cache[pos];
981 if (ce_stage(ce)) {
982 fprintf(fp, "\t%s\n", ce->name);
983 while (pos + 1 < active_nr &&
984 !strcmp(ce->name,
985 active_cache[pos + 1]->name))
986 pos++;
989 fclose(fp);
990 rerere(allow_rerere_auto);
991 printf(_("Automatic merge failed; "
992 "fix conflicts and then commit the result.\n"));
993 return 1;
996 static struct commit *is_old_style_invocation(int argc, const char **argv,
997 const unsigned char *head)
999 struct commit *second_token = NULL;
1000 if (argc > 2) {
1001 unsigned char second_sha1[20];
1003 if (get_sha1(argv[1], second_sha1))
1004 return NULL;
1005 second_token = lookup_commit_reference_gently(second_sha1, 0);
1006 if (!second_token)
1007 die(_("'%s' is not a commit"), argv[1]);
1008 if (hashcmp(second_token->object.sha1, head))
1009 return NULL;
1011 return second_token;
1014 static int evaluate_result(void)
1016 int cnt = 0;
1017 struct rev_info rev;
1019 /* Check how many files differ. */
1020 init_revisions(&rev, "");
1021 setup_revisions(0, NULL, &rev, NULL);
1022 rev.diffopt.output_format |=
1023 DIFF_FORMAT_CALLBACK;
1024 rev.diffopt.format_callback = count_diff_files;
1025 rev.diffopt.format_callback_data = &cnt;
1026 run_diff_files(&rev, 0);
1029 * Check how many unmerged entries are
1030 * there.
1032 cnt += count_unmerged_entries();
1034 return cnt;
1038 * Pretend as if the user told us to merge with the tracking
1039 * branch we have for the upstream of the current branch
1041 static int setup_with_upstream(const char ***argv)
1043 struct branch *branch = branch_get(NULL);
1044 int i;
1045 const char **args;
1047 if (!branch)
1048 die(_("No current branch."));
1049 if (!branch->remote)
1050 die(_("No remote for the current branch."));
1051 if (!branch->merge_nr)
1052 die(_("No default upstream defined for the current branch."));
1054 args = xcalloc(branch->merge_nr + 1, sizeof(char *));
1055 for (i = 0; i < branch->merge_nr; i++) {
1056 if (!branch->merge[i]->dst)
1057 die(_("No remote tracking branch for %s from %s"),
1058 branch->merge[i]->src, branch->remote_name);
1059 args[i] = branch->merge[i]->dst;
1061 args[i] = NULL;
1062 *argv = args;
1063 return i;
1066 static void write_merge_state(struct commit_list *remoteheads)
1068 const char *filename;
1069 int fd;
1070 struct commit_list *j;
1071 struct strbuf buf = STRBUF_INIT;
1073 for (j = remoteheads; j; j = j->next) {
1074 unsigned const char *sha1;
1075 struct commit *c = j->item;
1076 if (c->util && merge_remote_util(c)->obj) {
1077 sha1 = merge_remote_util(c)->obj->sha1;
1078 } else {
1079 sha1 = c->object.sha1;
1081 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
1083 filename = git_path("MERGE_HEAD");
1084 fd = open(filename, O_WRONLY | O_CREAT, 0666);
1085 if (fd < 0)
1086 die_errno(_("Could not open '%s' for writing"), filename);
1087 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1088 die_errno(_("Could not write to '%s'"), filename);
1089 close(fd);
1090 strbuf_addch(&merge_msg, '\n');
1091 write_merge_msg(&merge_msg);
1093 filename = git_path("MERGE_MODE");
1094 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
1095 if (fd < 0)
1096 die_errno(_("Could not open '%s' for writing"), filename);
1097 strbuf_reset(&buf);
1098 if (!allow_fast_forward)
1099 strbuf_addf(&buf, "no-ff");
1100 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1101 die_errno(_("Could not write to '%s'"), filename);
1102 close(fd);
1105 static int default_edit_option(void)
1107 static const char name[] = "GIT_MERGE_AUTOEDIT";
1108 const char *e = getenv(name);
1109 struct stat st_stdin, st_stdout;
1111 if (have_message)
1112 /* an explicit -m msg without --[no-]edit */
1113 return 0;
1115 if (e) {
1116 int v = git_config_maybe_bool(name, e);
1117 if (v < 0)
1118 die("Bad value '%s' in environment '%s'", e, name);
1119 return v;
1122 /* Use editor if stdin and stdout are the same and is a tty */
1123 return (!fstat(0, &st_stdin) &&
1124 !fstat(1, &st_stdout) &&
1125 isatty(0) && isatty(1) &&
1126 st_stdin.st_dev == st_stdout.st_dev &&
1127 st_stdin.st_ino == st_stdout.st_ino &&
1128 st_stdin.st_mode == st_stdout.st_mode);
1131 static struct commit_list *collect_parents(struct commit *head_commit,
1132 int *head_subsumed,
1133 int argc, const char **argv)
1135 int i;
1136 struct commit_list *remoteheads = NULL, *parents, *next;
1137 struct commit_list **remotes = &remoteheads;
1139 if (head_commit)
1140 remotes = &commit_list_insert(head_commit, remotes)->next;
1141 for (i = 0; i < argc; i++) {
1142 struct commit *commit = get_merge_parent(argv[i]);
1143 if (!commit)
1144 die(_("%s - not something we can merge"), argv[i]);
1145 remotes = &commit_list_insert(commit, remotes)->next;
1147 *remotes = NULL;
1149 parents = reduce_heads(remoteheads);
1151 *head_subsumed = 1; /* we will flip this to 0 when we find it */
1152 for (remoteheads = NULL, remotes = &remoteheads;
1153 parents;
1154 parents = next) {
1155 struct commit *commit = parents->item;
1156 next = parents->next;
1157 if (commit == head_commit)
1158 *head_subsumed = 0;
1159 else
1160 remotes = &commit_list_insert(commit, remotes)->next;
1162 return remoteheads;
1165 int cmd_merge(int argc, const char **argv, const char *prefix)
1167 unsigned char result_tree[20];
1168 unsigned char stash[20];
1169 unsigned char head_sha1[20];
1170 struct commit *head_commit;
1171 struct strbuf buf = STRBUF_INIT;
1172 const char *head_arg;
1173 int flag, i, ret = 0, head_subsumed;
1174 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1175 struct commit_list *common = NULL;
1176 const char *best_strategy = NULL, *wt_strategy = NULL;
1177 struct commit_list *remoteheads, *p;
1178 void *branch_to_free;
1180 if (argc == 2 && !strcmp(argv[1], "-h"))
1181 usage_with_options(builtin_merge_usage, builtin_merge_options);
1184 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1185 * current branch.
1187 branch = branch_to_free = resolve_refdup("HEAD", head_sha1, 0, &flag);
1188 if (branch && !prefixcmp(branch, "refs/heads/"))
1189 branch += 11;
1190 if (!branch || is_null_sha1(head_sha1))
1191 head_commit = NULL;
1192 else
1193 head_commit = lookup_commit_or_die(head_sha1, "HEAD");
1195 git_config(git_merge_config, NULL);
1197 if (branch_mergeoptions)
1198 parse_branch_merge_options(branch_mergeoptions);
1199 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1200 builtin_merge_usage, 0);
1201 if (shortlog_len < 0)
1202 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1204 if (verbosity < 0 && show_progress == -1)
1205 show_progress = 0;
1207 if (abort_current_merge) {
1208 int nargc = 2;
1209 const char *nargv[] = {"reset", "--merge", NULL};
1211 if (!file_exists(git_path("MERGE_HEAD")))
1212 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1214 /* Invoke 'git reset --merge' */
1215 ret = cmd_reset(nargc, nargv, prefix);
1216 goto done;
1219 if (read_cache_unmerged())
1220 die_resolve_conflict("merge");
1222 if (file_exists(git_path("MERGE_HEAD"))) {
1224 * There is no unmerged entry, don't advise 'git
1225 * add/rm <file>', just 'git commit'.
1227 if (advice_resolve_conflict)
1228 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1229 "Please, commit your changes before you can merge."));
1230 else
1231 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1233 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1234 if (advice_resolve_conflict)
1235 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1236 "Please, commit your changes before you can merge."));
1237 else
1238 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1240 resolve_undo_clear();
1242 if (verbosity < 0)
1243 show_diffstat = 0;
1245 if (squash) {
1246 if (!allow_fast_forward)
1247 die(_("You cannot combine --squash with --no-ff."));
1248 option_commit = 0;
1251 if (!allow_fast_forward && fast_forward_only)
1252 die(_("You cannot combine --no-ff with --ff-only."));
1254 if (!abort_current_merge) {
1255 if (!argc) {
1256 if (default_to_upstream)
1257 argc = setup_with_upstream(&argv);
1258 else
1259 die(_("No commit specified and merge.defaultToUpstream not set."));
1260 } else if (argc == 1 && !strcmp(argv[0], "-"))
1261 argv[0] = "@{-1}";
1263 if (!argc)
1264 usage_with_options(builtin_merge_usage,
1265 builtin_merge_options);
1268 * This could be traditional "merge <msg> HEAD <commit>..." and
1269 * the way we can tell it is to see if the second token is HEAD,
1270 * but some people might have misused the interface and used a
1271 * committish that is the same as HEAD there instead.
1272 * Traditional format never would have "-m" so it is an
1273 * additional safety measure to check for it.
1276 if (!have_message && head_commit &&
1277 is_old_style_invocation(argc, argv, head_commit->object.sha1)) {
1278 strbuf_addstr(&merge_msg, argv[0]);
1279 head_arg = argv[1];
1280 argv += 2;
1281 argc -= 2;
1282 remoteheads = collect_parents(head_commit, &head_subsumed, argc, argv);
1283 } else if (!head_commit) {
1284 struct commit *remote_head;
1286 * If the merged head is a valid one there is no reason
1287 * to forbid "git merge" into a branch yet to be born.
1288 * We do the same for "git pull".
1290 if (argc != 1)
1291 die(_("Can merge only exactly one commit into "
1292 "empty head"));
1293 if (squash)
1294 die(_("Squash commit into empty head not supported yet"));
1295 if (!allow_fast_forward)
1296 die(_("Non-fast-forward commit does not make sense into "
1297 "an empty head"));
1298 remoteheads = collect_parents(head_commit, &head_subsumed, argc, argv);
1299 remote_head = remoteheads->item;
1300 if (!remote_head)
1301 die(_("%s - not something we can merge"), argv[0]);
1302 read_empty(remote_head->object.sha1, 0);
1303 update_ref("initial pull", "HEAD", remote_head->object.sha1,
1304 NULL, 0, DIE_ON_ERR);
1305 goto done;
1306 } else {
1307 struct strbuf merge_names = STRBUF_INIT;
1309 /* We are invoked directly as the first-class UI. */
1310 head_arg = "HEAD";
1313 * All the rest are the commits being merged; prepare
1314 * the standard merge summary message to be appended
1315 * to the given message.
1317 remoteheads = collect_parents(head_commit, &head_subsumed, argc, argv);
1318 for (p = remoteheads; p; p = p->next)
1319 merge_name(merge_remote_util(p->item)->name, &merge_names);
1321 if (!have_message || shortlog_len) {
1322 struct fmt_merge_msg_opts opts;
1323 memset(&opts, 0, sizeof(opts));
1324 opts.add_title = !have_message;
1325 opts.shortlog_len = shortlog_len;
1327 fmt_merge_msg(&merge_names, &merge_msg, &opts);
1328 if (merge_msg.len)
1329 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1333 if (!head_commit || !argc)
1334 usage_with_options(builtin_merge_usage,
1335 builtin_merge_options);
1337 strbuf_addstr(&buf, "merge");
1338 for (p = remoteheads; p; p = p->next)
1339 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1340 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1341 strbuf_reset(&buf);
1343 for (p = remoteheads; p; p = p->next) {
1344 struct commit *commit = p->item;
1345 strbuf_addf(&buf, "GITHEAD_%s",
1346 sha1_to_hex(commit->object.sha1));
1347 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1348 strbuf_reset(&buf);
1349 if (!fast_forward_only &&
1350 merge_remote_util(commit) &&
1351 merge_remote_util(commit)->obj &&
1352 merge_remote_util(commit)->obj->type == OBJ_TAG) {
1353 if (option_edit < 0)
1354 option_edit = default_edit_option();
1355 allow_fast_forward = 0;
1359 if (option_edit < 0)
1360 option_edit = 0;
1362 if (!use_strategies) {
1363 if (!remoteheads)
1364 ; /* already up-to-date */
1365 else if (!remoteheads->next)
1366 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1367 else
1368 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1371 for (i = 0; i < use_strategies_nr; i++) {
1372 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1373 allow_fast_forward = 0;
1374 if (use_strategies[i]->attr & NO_TRIVIAL)
1375 allow_trivial = 0;
1378 if (!remoteheads)
1379 ; /* already up-to-date */
1380 else if (!remoteheads->next)
1381 common = get_merge_bases(head_commit, remoteheads->item, 1);
1382 else {
1383 struct commit_list *list = remoteheads;
1384 commit_list_insert(head_commit, &list);
1385 common = get_octopus_merge_bases(list);
1386 free(list);
1389 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.sha1,
1390 NULL, 0, DIE_ON_ERR);
1392 if (remoteheads && !common)
1393 ; /* No common ancestors found. We need a real merge. */
1394 else if (!remoteheads ||
1395 (!remoteheads->next && !common->next &&
1396 common->item == remoteheads->item)) {
1398 * If head can reach all the merge then we are up to date.
1399 * but first the most common case of merging one remote.
1401 finish_up_to_date("Already up-to-date.");
1402 goto done;
1403 } else if (allow_fast_forward && !remoteheads->next &&
1404 !common->next &&
1405 !hashcmp(common->item->object.sha1, head_commit->object.sha1)) {
1406 /* Again the most common case of merging one remote. */
1407 struct strbuf msg = STRBUF_INIT;
1408 struct commit *commit;
1409 char hex[41];
1411 strcpy(hex, find_unique_abbrev(head_commit->object.sha1, DEFAULT_ABBREV));
1413 if (verbosity >= 0)
1414 printf(_("Updating %s..%s\n"),
1415 hex,
1416 find_unique_abbrev(remoteheads->item->object.sha1,
1417 DEFAULT_ABBREV));
1418 strbuf_addstr(&msg, "Fast-forward");
1419 if (have_message)
1420 strbuf_addstr(&msg,
1421 " (no commit created; -m option ignored)");
1422 commit = remoteheads->item;
1423 if (!commit) {
1424 ret = 1;
1425 goto done;
1428 if (checkout_fast_forward(head_commit->object.sha1,
1429 commit->object.sha1)) {
1430 ret = 1;
1431 goto done;
1434 finish(head_commit, remoteheads, commit->object.sha1, msg.buf);
1435 drop_save();
1436 goto done;
1437 } else if (!remoteheads->next && common->next)
1440 * We are not doing octopus and not fast-forward. Need
1441 * a real merge.
1443 else if (!remoteheads->next && !common->next && option_commit) {
1445 * We are not doing octopus, not fast-forward, and have
1446 * only one common.
1448 refresh_cache(REFRESH_QUIET);
1449 if (allow_trivial && !fast_forward_only) {
1450 /* See if it is really trivial. */
1451 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1452 printf(_("Trying really trivial in-index merge...\n"));
1453 if (!read_tree_trivial(common->item->object.sha1,
1454 head_commit->object.sha1,
1455 remoteheads->item->object.sha1)) {
1456 ret = merge_trivial(head_commit, remoteheads);
1457 goto done;
1459 printf(_("Nope.\n"));
1461 } else {
1463 * An octopus. If we can reach all the remote we are up
1464 * to date.
1466 int up_to_date = 1;
1467 struct commit_list *j;
1469 for (j = remoteheads; j; j = j->next) {
1470 struct commit_list *common_one;
1473 * Here we *have* to calculate the individual
1474 * merge_bases again, otherwise "git merge HEAD^
1475 * HEAD^^" would be missed.
1477 common_one = get_merge_bases(head_commit, j->item, 1);
1478 if (hashcmp(common_one->item->object.sha1,
1479 j->item->object.sha1)) {
1480 up_to_date = 0;
1481 break;
1484 if (up_to_date) {
1485 finish_up_to_date("Already up-to-date. Yeeah!");
1486 goto done;
1490 if (fast_forward_only)
1491 die(_("Not possible to fast-forward, aborting."));
1493 /* We are going to make a new commit. */
1494 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1497 * At this point, we need a real merge. No matter what strategy
1498 * we use, it would operate on the index, possibly affecting the
1499 * working tree, and when resolved cleanly, have the desired
1500 * tree in the index -- this means that the index must be in
1501 * sync with the head commit. The strategies are responsible
1502 * to ensure this.
1504 if (use_strategies_nr == 1 ||
1506 * Stash away the local changes so that we can try more than one.
1508 save_state(stash))
1509 hashcpy(stash, null_sha1);
1511 for (i = 0; i < use_strategies_nr; i++) {
1512 int ret;
1513 if (i) {
1514 printf(_("Rewinding the tree to pristine...\n"));
1515 restore_state(head_commit->object.sha1, stash);
1517 if (use_strategies_nr != 1)
1518 printf(_("Trying merge strategy %s...\n"),
1519 use_strategies[i]->name);
1521 * Remember which strategy left the state in the working
1522 * tree.
1524 wt_strategy = use_strategies[i]->name;
1526 ret = try_merge_strategy(use_strategies[i]->name,
1527 common, remoteheads,
1528 head_commit, head_arg);
1529 if (!option_commit && !ret) {
1530 merge_was_ok = 1;
1532 * This is necessary here just to avoid writing
1533 * the tree, but later we will *not* exit with
1534 * status code 1 because merge_was_ok is set.
1536 ret = 1;
1539 if (ret) {
1541 * The backend exits with 1 when conflicts are
1542 * left to be resolved, with 2 when it does not
1543 * handle the given merge at all.
1545 if (ret == 1) {
1546 int cnt = evaluate_result();
1548 if (best_cnt <= 0 || cnt <= best_cnt) {
1549 best_strategy = use_strategies[i]->name;
1550 best_cnt = cnt;
1553 if (merge_was_ok)
1554 break;
1555 else
1556 continue;
1559 /* Automerge succeeded. */
1560 write_tree_trivial(result_tree);
1561 automerge_was_ok = 1;
1562 break;
1566 * If we have a resulting tree, that means the strategy module
1567 * auto resolved the merge cleanly.
1569 if (automerge_was_ok) {
1570 ret = finish_automerge(head_commit, head_subsumed,
1571 common, remoteheads,
1572 result_tree, wt_strategy);
1573 goto done;
1577 * Pick the result from the best strategy and have the user fix
1578 * it up.
1580 if (!best_strategy) {
1581 restore_state(head_commit->object.sha1, stash);
1582 if (use_strategies_nr > 1)
1583 fprintf(stderr,
1584 _("No merge strategy handled the merge.\n"));
1585 else
1586 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1587 use_strategies[0]->name);
1588 ret = 2;
1589 goto done;
1590 } else if (best_strategy == wt_strategy)
1591 ; /* We already have its result in the working tree. */
1592 else {
1593 printf(_("Rewinding the tree to pristine...\n"));
1594 restore_state(head_commit->object.sha1, stash);
1595 printf(_("Using the %s to prepare resolving by hand.\n"),
1596 best_strategy);
1597 try_merge_strategy(best_strategy, common, remoteheads,
1598 head_commit, head_arg);
1601 if (squash)
1602 finish(head_commit, remoteheads, NULL, NULL);
1603 else
1604 write_merge_state(remoteheads);
1606 if (merge_was_ok)
1607 fprintf(stderr, _("Automatic merge went well; "
1608 "stopped before committing as requested\n"));
1609 else
1610 ret = suggest_conflicts(option_renormalize);
1612 done:
1613 free(branch_to_free);
1614 return ret;