commit: teach --gpg-sign option
[git/jrn.git] / builtin / merge.c
blobe5afe64cefba88cd435a89c9d4d87f459488853d
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 "gpg-interface.h"
31 #define DEFAULT_TWOHEAD (1<<0)
32 #define DEFAULT_OCTOPUS (1<<1)
33 #define NO_FAST_FORWARD (1<<2)
34 #define NO_TRIVIAL (1<<3)
36 struct strategy {
37 const char *name;
38 unsigned attr;
41 static const char * const builtin_merge_usage[] = {
42 "git merge [options] [<commit>...]",
43 "git merge [options] <msg> HEAD <commit>",
44 "git merge --abort",
45 NULL
48 static int show_diffstat = 1, shortlog_len, squash;
49 static int option_commit = 1, allow_fast_forward = 1;
50 static int fast_forward_only, option_edit;
51 static int allow_trivial = 1, have_message;
52 static struct strbuf merge_msg;
53 static struct commit_list *remoteheads;
54 static struct strategy **use_strategies;
55 static size_t use_strategies_nr, use_strategies_alloc;
56 static const char **xopts;
57 static size_t xopts_nr, xopts_alloc;
58 static const char *branch;
59 static char *branch_mergeoptions;
60 static int option_renormalize;
61 static int verbosity;
62 static int allow_rerere_auto;
63 static int abort_current_merge;
64 static int show_progress = -1;
65 static int default_to_upstream;
66 static const char *sign_commit;
68 static struct strategy all_strategy[] = {
69 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
70 { "octopus", DEFAULT_OCTOPUS },
71 { "resolve", 0 },
72 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
73 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
76 static const char *pull_twohead, *pull_octopus;
78 static int option_parse_message(const struct option *opt,
79 const char *arg, int unset)
81 struct strbuf *buf = opt->value;
83 if (unset)
84 strbuf_setlen(buf, 0);
85 else if (arg) {
86 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
87 have_message = 1;
88 } else
89 return error(_("switch `m' requires a value"));
90 return 0;
93 static struct strategy *get_strategy(const char *name)
95 int i;
96 struct strategy *ret;
97 static struct cmdnames main_cmds, other_cmds;
98 static int loaded;
100 if (!name)
101 return NULL;
103 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
104 if (!strcmp(name, all_strategy[i].name))
105 return &all_strategy[i];
107 if (!loaded) {
108 struct cmdnames not_strategies;
109 loaded = 1;
111 memset(&not_strategies, 0, sizeof(struct cmdnames));
112 load_command_list("git-merge-", &main_cmds, &other_cmds);
113 for (i = 0; i < main_cmds.cnt; i++) {
114 int j, found = 0;
115 struct cmdname *ent = main_cmds.names[i];
116 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
117 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
118 && !all_strategy[j].name[ent->len])
119 found = 1;
120 if (!found)
121 add_cmdname(&not_strategies, ent->name, ent->len);
123 exclude_cmds(&main_cmds, &not_strategies);
125 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
126 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
127 fprintf(stderr, _("Available strategies are:"));
128 for (i = 0; i < main_cmds.cnt; i++)
129 fprintf(stderr, " %s", main_cmds.names[i]->name);
130 fprintf(stderr, ".\n");
131 if (other_cmds.cnt) {
132 fprintf(stderr, _("Available custom strategies are:"));
133 for (i = 0; i < other_cmds.cnt; i++)
134 fprintf(stderr, " %s", other_cmds.names[i]->name);
135 fprintf(stderr, ".\n");
137 exit(1);
140 ret = xcalloc(1, sizeof(struct strategy));
141 ret->name = xstrdup(name);
142 ret->attr = NO_TRIVIAL;
143 return ret;
146 static void append_strategy(struct strategy *s)
148 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
149 use_strategies[use_strategies_nr++] = s;
152 static int option_parse_strategy(const struct option *opt,
153 const char *name, int unset)
155 if (unset)
156 return 0;
158 append_strategy(get_strategy(name));
159 return 0;
162 static int option_parse_x(const struct option *opt,
163 const char *arg, int unset)
165 if (unset)
166 return 0;
168 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
169 xopts[xopts_nr++] = xstrdup(arg);
170 return 0;
173 static int option_parse_n(const struct option *opt,
174 const char *arg, int unset)
176 show_diffstat = unset;
177 return 0;
180 static struct option builtin_merge_options[] = {
181 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
182 "do not show a diffstat at the end of the merge",
183 PARSE_OPT_NOARG, option_parse_n },
184 OPT_BOOLEAN(0, "stat", &show_diffstat,
185 "show a diffstat at the end of the merge"),
186 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
187 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
188 "add (at most <n>) entries from shortlog to merge commit message",
189 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
190 OPT_BOOLEAN(0, "squash", &squash,
191 "create a single commit instead of doing a merge"),
192 OPT_BOOLEAN(0, "commit", &option_commit,
193 "perform a commit if the merge succeeds (default)"),
194 OPT_BOOLEAN('e', "edit", &option_edit,
195 "edit message before committing"),
196 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
197 "allow fast-forward (default)"),
198 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
199 "abort if fast-forward is not possible"),
200 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
201 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
202 "merge strategy to use", option_parse_strategy),
203 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
204 "option for selected merge strategy", option_parse_x),
205 OPT_CALLBACK('m', "message", &merge_msg, "message",
206 "merge commit message (for a non-fast-forward merge)",
207 option_parse_message),
208 OPT__VERBOSITY(&verbosity),
209 OPT_BOOLEAN(0, "abort", &abort_current_merge,
210 "abort the current in-progress merge"),
211 OPT_SET_INT(0, "progress", &show_progress, "force progress reporting", 1),
212 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, "key id",
213 "GPG sign commit", PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
214 OPT_END()
217 /* Cleans up metadata that is uninteresting after a succeeded merge. */
218 static void drop_save(void)
220 unlink(git_path("MERGE_HEAD"));
221 unlink(git_path("MERGE_MSG"));
222 unlink(git_path("MERGE_MODE"));
225 static int save_state(unsigned char *stash)
227 int len;
228 struct child_process cp;
229 struct strbuf buffer = STRBUF_INIT;
230 const char *argv[] = {"stash", "create", NULL};
232 memset(&cp, 0, sizeof(cp));
233 cp.argv = argv;
234 cp.out = -1;
235 cp.git_cmd = 1;
237 if (start_command(&cp))
238 die(_("could not run stash."));
239 len = strbuf_read(&buffer, cp.out, 1024);
240 close(cp.out);
242 if (finish_command(&cp) || len < 0)
243 die(_("stash failed"));
244 else if (!len) /* no changes */
245 return -1;
246 strbuf_setlen(&buffer, buffer.len-1);
247 if (get_sha1(buffer.buf, stash))
248 die(_("not a valid object: %s"), buffer.buf);
249 return 0;
252 static void read_empty(unsigned const char *sha1, int verbose)
254 int i = 0;
255 const char *args[7];
257 args[i++] = "read-tree";
258 if (verbose)
259 args[i++] = "-v";
260 args[i++] = "-m";
261 args[i++] = "-u";
262 args[i++] = EMPTY_TREE_SHA1_HEX;
263 args[i++] = sha1_to_hex(sha1);
264 args[i] = NULL;
266 if (run_command_v_opt(args, RUN_GIT_CMD))
267 die(_("read-tree failed"));
270 static void reset_hard(unsigned const char *sha1, int verbose)
272 int i = 0;
273 const char *args[6];
275 args[i++] = "read-tree";
276 if (verbose)
277 args[i++] = "-v";
278 args[i++] = "--reset";
279 args[i++] = "-u";
280 args[i++] = sha1_to_hex(sha1);
281 args[i] = NULL;
283 if (run_command_v_opt(args, RUN_GIT_CMD))
284 die(_("read-tree failed"));
287 static void restore_state(const unsigned char *head,
288 const unsigned char *stash)
290 struct strbuf sb = STRBUF_INIT;
291 const char *args[] = { "stash", "apply", NULL, NULL };
293 if (is_null_sha1(stash))
294 return;
296 reset_hard(head, 1);
298 args[2] = sha1_to_hex(stash);
301 * It is OK to ignore error here, for example when there was
302 * nothing to restore.
304 run_command_v_opt(args, RUN_GIT_CMD);
306 strbuf_release(&sb);
307 refresh_cache(REFRESH_QUIET);
310 /* This is called when no merge was necessary. */
311 static void finish_up_to_date(const char *msg)
313 if (verbosity >= 0)
314 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
315 drop_save();
318 static void squash_message(struct commit *commit)
320 struct rev_info rev;
321 struct strbuf out = STRBUF_INIT;
322 struct commit_list *j;
323 int fd;
324 struct pretty_print_context ctx = {0};
326 printf(_("Squash commit -- not updating HEAD\n"));
327 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
328 if (fd < 0)
329 die_errno(_("Could not write to '%s'"), git_path("SQUASH_MSG"));
331 init_revisions(&rev, NULL);
332 rev.ignore_merges = 1;
333 rev.commit_format = CMIT_FMT_MEDIUM;
335 commit->object.flags |= UNINTERESTING;
336 add_pending_object(&rev, &commit->object, NULL);
338 for (j = remoteheads; j; j = j->next)
339 add_pending_object(&rev, &j->item->object, NULL);
341 setup_revisions(0, NULL, &rev, NULL);
342 if (prepare_revision_walk(&rev))
343 die(_("revision walk setup failed"));
345 ctx.abbrev = rev.abbrev;
346 ctx.date_mode = rev.date_mode;
347 ctx.fmt = rev.commit_format;
349 strbuf_addstr(&out, "Squashed commit of the following:\n");
350 while ((commit = get_revision(&rev)) != NULL) {
351 strbuf_addch(&out, '\n');
352 strbuf_addf(&out, "commit %s\n",
353 sha1_to_hex(commit->object.sha1));
354 pretty_print_commit(&ctx, commit, &out);
356 if (write(fd, out.buf, out.len) < 0)
357 die_errno(_("Writing SQUASH_MSG"));
358 if (close(fd))
359 die_errno(_("Finishing SQUASH_MSG"));
360 strbuf_release(&out);
363 static void finish(struct commit *head_commit,
364 const unsigned char *new_head, const char *msg)
366 struct strbuf reflog_message = STRBUF_INIT;
367 const unsigned char *head = head_commit->object.sha1;
369 if (!msg)
370 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
371 else {
372 if (verbosity >= 0)
373 printf("%s\n", msg);
374 strbuf_addf(&reflog_message, "%s: %s",
375 getenv("GIT_REFLOG_ACTION"), msg);
377 if (squash) {
378 squash_message(head_commit);
379 } else {
380 if (verbosity >= 0 && !merge_msg.len)
381 printf(_("No merge message -- not updating HEAD\n"));
382 else {
383 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
384 update_ref(reflog_message.buf, "HEAD",
385 new_head, head, 0,
386 DIE_ON_ERR);
388 * We ignore errors in 'gc --auto', since the
389 * user should see them.
391 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
394 if (new_head && show_diffstat) {
395 struct diff_options opts;
396 diff_setup(&opts);
397 opts.output_format |=
398 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
399 opts.detect_rename = DIFF_DETECT_RENAME;
400 if (diff_setup_done(&opts) < 0)
401 die(_("diff_setup_done failed"));
402 diff_tree_sha1(head, new_head, "", &opts);
403 diffcore_std(&opts);
404 diff_flush(&opts);
407 /* Run a post-merge hook */
408 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
410 strbuf_release(&reflog_message);
413 /* Get the name for the merge commit's message. */
414 static void merge_name(const char *remote, struct strbuf *msg)
416 struct commit *remote_head;
417 unsigned char branch_head[20], buf_sha[20];
418 struct strbuf buf = STRBUF_INIT;
419 struct strbuf bname = STRBUF_INIT;
420 const char *ptr;
421 char *found_ref;
422 int len, early;
424 strbuf_branchname(&bname, remote);
425 remote = bname.buf;
427 memset(branch_head, 0, sizeof(branch_head));
428 remote_head = get_merge_parent(remote);
429 if (!remote_head)
430 die(_("'%s' does not point to a commit"), remote);
432 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
433 if (!prefixcmp(found_ref, "refs/heads/")) {
434 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
435 sha1_to_hex(branch_head), remote);
436 goto cleanup;
438 if (!prefixcmp(found_ref, "refs/tags/")) {
439 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
440 sha1_to_hex(branch_head), remote);
441 goto cleanup;
443 if (!prefixcmp(found_ref, "refs/remotes/")) {
444 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
445 sha1_to_hex(branch_head), remote);
446 goto cleanup;
450 /* See if remote matches <name>^^^.. or <name>~<number> */
451 for (len = 0, ptr = remote + strlen(remote);
452 remote < ptr && ptr[-1] == '^';
453 ptr--)
454 len++;
455 if (len)
456 early = 1;
457 else {
458 early = 0;
459 ptr = strrchr(remote, '~');
460 if (ptr) {
461 int seen_nonzero = 0;
463 len++; /* count ~ */
464 while (*++ptr && isdigit(*ptr)) {
465 seen_nonzero |= (*ptr != '0');
466 len++;
468 if (*ptr)
469 len = 0; /* not ...~<number> */
470 else if (seen_nonzero)
471 early = 1;
472 else if (len == 1)
473 early = 1; /* "name~" is "name~1"! */
476 if (len) {
477 struct strbuf truname = STRBUF_INIT;
478 strbuf_addstr(&truname, "refs/heads/");
479 strbuf_addstr(&truname, remote);
480 strbuf_setlen(&truname, truname.len - len);
481 if (resolve_ref(truname.buf, buf_sha, 1, NULL)) {
482 strbuf_addf(msg,
483 "%s\t\tbranch '%s'%s of .\n",
484 sha1_to_hex(remote_head->object.sha1),
485 truname.buf + 11,
486 (early ? " (early part)" : ""));
487 strbuf_release(&truname);
488 goto cleanup;
492 if (!strcmp(remote, "FETCH_HEAD") &&
493 !access(git_path("FETCH_HEAD"), R_OK)) {
494 FILE *fp;
495 struct strbuf line = STRBUF_INIT;
496 char *ptr;
498 fp = fopen(git_path("FETCH_HEAD"), "r");
499 if (!fp)
500 die_errno(_("could not open '%s' for reading"),
501 git_path("FETCH_HEAD"));
502 strbuf_getline(&line, fp, '\n');
503 fclose(fp);
504 ptr = strstr(line.buf, "\tnot-for-merge\t");
505 if (ptr)
506 strbuf_remove(&line, ptr-line.buf+1, 13);
507 strbuf_addbuf(msg, &line);
508 strbuf_release(&line);
509 goto cleanup;
511 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
512 sha1_to_hex(remote_head->object.sha1), remote);
513 cleanup:
514 strbuf_release(&buf);
515 strbuf_release(&bname);
518 static void parse_branch_merge_options(char *bmo)
520 const char **argv;
521 int argc;
523 if (!bmo)
524 return;
525 argc = split_cmdline(bmo, &argv);
526 if (argc < 0)
527 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
528 split_cmdline_strerror(argc));
529 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
530 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
531 argc++;
532 argv[0] = "branch.*.mergeoptions";
533 parse_options(argc, argv, NULL, builtin_merge_options,
534 builtin_merge_usage, 0);
535 free(argv);
538 static int git_merge_config(const char *k, const char *v, void *cb)
540 int status;
542 if (branch && !prefixcmp(k, "branch.") &&
543 !prefixcmp(k + 7, branch) &&
544 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
545 free(branch_mergeoptions);
546 branch_mergeoptions = xstrdup(v);
547 return 0;
550 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
551 show_diffstat = git_config_bool(k, v);
552 else if (!strcmp(k, "pull.twohead"))
553 return git_config_string(&pull_twohead, k, v);
554 else if (!strcmp(k, "pull.octopus"))
555 return git_config_string(&pull_octopus, k, v);
556 else if (!strcmp(k, "merge.renormalize"))
557 option_renormalize = git_config_bool(k, v);
558 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary")) {
559 int is_bool;
560 shortlog_len = git_config_bool_or_int(k, v, &is_bool);
561 if (!is_bool && shortlog_len < 0)
562 return error(_("%s: negative length %s"), k, v);
563 if (is_bool && shortlog_len)
564 shortlog_len = DEFAULT_MERGE_LOG_LEN;
565 return 0;
566 } else if (!strcmp(k, "merge.ff")) {
567 int boolval = git_config_maybe_bool(k, v);
568 if (0 <= boolval) {
569 allow_fast_forward = boolval;
570 } else if (v && !strcmp(v, "only")) {
571 allow_fast_forward = 1;
572 fast_forward_only = 1;
573 } /* do not barf on values from future versions of git */
574 return 0;
575 } else if (!strcmp(k, "merge.defaulttoupstream")) {
576 default_to_upstream = git_config_bool(k, v);
577 return 0;
580 status = git_gpg_config(k, v, NULL);
581 if (status)
582 return status;
583 return git_diff_ui_config(k, v, cb);
586 static int read_tree_trivial(unsigned char *common, unsigned char *head,
587 unsigned char *one)
589 int i, nr_trees = 0;
590 struct tree *trees[MAX_UNPACK_TREES];
591 struct tree_desc t[MAX_UNPACK_TREES];
592 struct unpack_trees_options opts;
594 memset(&opts, 0, sizeof(opts));
595 opts.head_idx = 2;
596 opts.src_index = &the_index;
597 opts.dst_index = &the_index;
598 opts.update = 1;
599 opts.verbose_update = 1;
600 opts.trivial_merges_only = 1;
601 opts.merge = 1;
602 trees[nr_trees] = parse_tree_indirect(common);
603 if (!trees[nr_trees++])
604 return -1;
605 trees[nr_trees] = parse_tree_indirect(head);
606 if (!trees[nr_trees++])
607 return -1;
608 trees[nr_trees] = parse_tree_indirect(one);
609 if (!trees[nr_trees++])
610 return -1;
611 opts.fn = threeway_merge;
612 cache_tree_free(&active_cache_tree);
613 for (i = 0; i < nr_trees; i++) {
614 parse_tree(trees[i]);
615 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
617 if (unpack_trees(nr_trees, t, &opts))
618 return -1;
619 return 0;
622 static void write_tree_trivial(unsigned char *sha1)
624 if (write_cache_as_tree(sha1, 0, NULL))
625 die(_("git write-tree failed to write a tree"));
628 static const char *merge_argument(struct commit *commit)
630 if (commit)
631 return sha1_to_hex(commit->object.sha1);
632 else
633 return EMPTY_TREE_SHA1_HEX;
636 int try_merge_command(const char *strategy, size_t xopts_nr,
637 const char **xopts, struct commit_list *common,
638 const char *head_arg, struct commit_list *remotes)
640 const char **args;
641 int i = 0, x = 0, ret;
642 struct commit_list *j;
643 struct strbuf buf = STRBUF_INIT;
645 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
646 commit_list_count(remotes)) * sizeof(char *));
647 strbuf_addf(&buf, "merge-%s", strategy);
648 args[i++] = buf.buf;
649 for (x = 0; x < xopts_nr; x++) {
650 char *s = xmalloc(strlen(xopts[x])+2+1);
651 strcpy(s, "--");
652 strcpy(s+2, xopts[x]);
653 args[i++] = s;
655 for (j = common; j; j = j->next)
656 args[i++] = xstrdup(merge_argument(j->item));
657 args[i++] = "--";
658 args[i++] = head_arg;
659 for (j = remotes; j; j = j->next)
660 args[i++] = xstrdup(merge_argument(j->item));
661 args[i] = NULL;
662 ret = run_command_v_opt(args, RUN_GIT_CMD);
663 strbuf_release(&buf);
664 i = 1;
665 for (x = 0; x < xopts_nr; x++)
666 free((void *)args[i++]);
667 for (j = common; j; j = j->next)
668 free((void *)args[i++]);
669 i += 2;
670 for (j = remotes; j; j = j->next)
671 free((void *)args[i++]);
672 free(args);
673 discard_cache();
674 if (read_cache() < 0)
675 die(_("failed to read the cache"));
676 resolve_undo_clear();
678 return ret;
681 static int try_merge_strategy(const char *strategy, struct commit_list *common,
682 struct commit *head, const char *head_arg)
684 int index_fd;
685 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
687 index_fd = hold_locked_index(lock, 1);
688 refresh_cache(REFRESH_QUIET);
689 if (active_cache_changed &&
690 (write_cache(index_fd, active_cache, active_nr) ||
691 commit_locked_index(lock)))
692 return error(_("Unable to write index."));
693 rollback_lock_file(lock);
695 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
696 int clean, x;
697 struct commit *result;
698 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
699 int index_fd;
700 struct commit_list *reversed = NULL;
701 struct merge_options o;
702 struct commit_list *j;
704 if (remoteheads->next) {
705 error(_("Not handling anything other than two heads merge."));
706 return 2;
709 init_merge_options(&o);
710 if (!strcmp(strategy, "subtree"))
711 o.subtree_shift = "";
713 o.renormalize = option_renormalize;
714 o.show_rename_progress =
715 show_progress == -1 ? isatty(2) : show_progress;
717 for (x = 0; x < xopts_nr; x++)
718 if (parse_merge_opt(&o, xopts[x]))
719 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
721 o.branch1 = head_arg;
722 o.branch2 = merge_remote_util(remoteheads->item)->name;
724 for (j = common; j; j = j->next)
725 commit_list_insert(j->item, &reversed);
727 index_fd = hold_locked_index(lock, 1);
728 clean = merge_recursive(&o, head,
729 remoteheads->item, reversed, &result);
730 if (active_cache_changed &&
731 (write_cache(index_fd, active_cache, active_nr) ||
732 commit_locked_index(lock)))
733 die (_("unable to write %s"), get_index_file());
734 rollback_lock_file(lock);
735 return clean ? 0 : 1;
736 } else {
737 return try_merge_command(strategy, xopts_nr, xopts,
738 common, head_arg, remoteheads);
742 static void count_diff_files(struct diff_queue_struct *q,
743 struct diff_options *opt, void *data)
745 int *count = data;
747 (*count) += q->nr;
750 static int count_unmerged_entries(void)
752 int i, ret = 0;
754 for (i = 0; i < active_nr; i++)
755 if (ce_stage(active_cache[i]))
756 ret++;
758 return ret;
761 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
763 struct tree *trees[MAX_UNPACK_TREES];
764 struct unpack_trees_options opts;
765 struct tree_desc t[MAX_UNPACK_TREES];
766 int i, fd, nr_trees = 0;
767 struct dir_struct dir;
768 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
770 refresh_cache(REFRESH_QUIET);
772 fd = hold_locked_index(lock_file, 1);
774 memset(&trees, 0, sizeof(trees));
775 memset(&opts, 0, sizeof(opts));
776 memset(&t, 0, sizeof(t));
777 memset(&dir, 0, sizeof(dir));
778 dir.flags |= DIR_SHOW_IGNORED;
779 dir.exclude_per_dir = ".gitignore";
780 opts.dir = &dir;
782 opts.head_idx = 1;
783 opts.src_index = &the_index;
784 opts.dst_index = &the_index;
785 opts.update = 1;
786 opts.verbose_update = 1;
787 opts.merge = 1;
788 opts.fn = twoway_merge;
789 setup_unpack_trees_porcelain(&opts, "merge");
791 trees[nr_trees] = parse_tree_indirect(head);
792 if (!trees[nr_trees++])
793 return -1;
794 trees[nr_trees] = parse_tree_indirect(remote);
795 if (!trees[nr_trees++])
796 return -1;
797 for (i = 0; i < nr_trees; i++) {
798 parse_tree(trees[i]);
799 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
801 if (unpack_trees(nr_trees, t, &opts))
802 return -1;
803 if (write_cache(fd, active_cache, active_nr) ||
804 commit_locked_index(lock_file))
805 die(_("unable to write new index file"));
806 return 0;
809 static void split_merge_strategies(const char *string, struct strategy **list,
810 int *nr, int *alloc)
812 char *p, *q, *buf;
814 if (!string)
815 return;
817 buf = xstrdup(string);
818 q = buf;
819 for (;;) {
820 p = strchr(q, ' ');
821 if (!p) {
822 ALLOC_GROW(*list, *nr + 1, *alloc);
823 (*list)[(*nr)++].name = xstrdup(q);
824 free(buf);
825 return;
826 } else {
827 *p = '\0';
828 ALLOC_GROW(*list, *nr + 1, *alloc);
829 (*list)[(*nr)++].name = xstrdup(q);
830 q = ++p;
835 static void add_strategies(const char *string, unsigned attr)
837 struct strategy *list = NULL;
838 int list_alloc = 0, list_nr = 0, i;
840 memset(&list, 0, sizeof(list));
841 split_merge_strategies(string, &list, &list_nr, &list_alloc);
842 if (list) {
843 for (i = 0; i < list_nr; i++)
844 append_strategy(get_strategy(list[i].name));
845 return;
847 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
848 if (all_strategy[i].attr & attr)
849 append_strategy(&all_strategy[i]);
853 static void write_merge_msg(struct strbuf *msg)
855 int fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
856 if (fd < 0)
857 die_errno(_("Could not open '%s' for writing"),
858 git_path("MERGE_MSG"));
859 if (write_in_full(fd, msg->buf, msg->len) != msg->len)
860 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
861 close(fd);
864 static void read_merge_msg(struct strbuf *msg)
866 strbuf_reset(msg);
867 if (strbuf_read_file(msg, git_path("MERGE_MSG"), 0) < 0)
868 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
871 static void write_merge_state(void);
872 static void abort_commit(const char *err_msg)
874 if (err_msg)
875 error("%s", err_msg);
876 fprintf(stderr,
877 _("Not committing merge; use 'git commit' to complete the merge.\n"));
878 write_merge_state();
879 exit(1);
882 static void prepare_to_commit(void)
884 struct strbuf msg = STRBUF_INIT;
885 strbuf_addbuf(&msg, &merge_msg);
886 strbuf_addch(&msg, '\n');
887 write_merge_msg(&msg);
888 run_hook(get_index_file(), "prepare-commit-msg",
889 git_path("MERGE_MSG"), "merge", NULL, NULL);
890 if (option_edit) {
891 if (launch_editor(git_path("MERGE_MSG"), NULL, NULL))
892 abort_commit(NULL);
894 read_merge_msg(&msg);
895 stripspace(&msg, option_edit);
896 if (!msg.len)
897 abort_commit(_("Empty commit message."));
898 strbuf_release(&merge_msg);
899 strbuf_addbuf(&merge_msg, &msg);
900 strbuf_release(&msg);
903 static int merge_trivial(struct commit *head)
905 unsigned char result_tree[20], result_commit[20];
906 struct commit_list *parent = xmalloc(sizeof(*parent));
908 write_tree_trivial(result_tree);
909 printf(_("Wonderful.\n"));
910 parent->item = head;
911 parent->next = xmalloc(sizeof(*parent->next));
912 parent->next->item = remoteheads->item;
913 parent->next->next = NULL;
914 prepare_to_commit();
915 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL,
916 sign_commit);
917 finish(head, result_commit, "In-index merge");
918 drop_save();
919 return 0;
922 static int finish_automerge(struct commit *head,
923 struct commit_list *common,
924 unsigned char *result_tree,
925 const char *wt_strategy)
927 struct commit_list *parents = NULL, *j;
928 struct strbuf buf = STRBUF_INIT;
929 unsigned char result_commit[20];
931 free_commit_list(common);
932 if (allow_fast_forward) {
933 parents = remoteheads;
934 commit_list_insert(head, &parents);
935 parents = reduce_heads(parents);
936 } else {
937 struct commit_list **pptr = &parents;
939 pptr = &commit_list_insert(head,
940 pptr)->next;
941 for (j = remoteheads; j; j = j->next)
942 pptr = &commit_list_insert(j->item, pptr)->next;
944 strbuf_addch(&merge_msg, '\n');
945 prepare_to_commit();
946 free_commit_list(remoteheads);
947 commit_tree(merge_msg.buf, result_tree, parents, result_commit,
948 NULL, sign_commit);
949 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
950 finish(head, result_commit, buf.buf);
951 strbuf_release(&buf);
952 drop_save();
953 return 0;
956 static int suggest_conflicts(int renormalizing)
958 FILE *fp;
959 int pos;
961 fp = fopen(git_path("MERGE_MSG"), "a");
962 if (!fp)
963 die_errno(_("Could not open '%s' for writing"),
964 git_path("MERGE_MSG"));
965 fprintf(fp, "\nConflicts:\n");
966 for (pos = 0; pos < active_nr; pos++) {
967 struct cache_entry *ce = active_cache[pos];
969 if (ce_stage(ce)) {
970 fprintf(fp, "\t%s\n", ce->name);
971 while (pos + 1 < active_nr &&
972 !strcmp(ce->name,
973 active_cache[pos + 1]->name))
974 pos++;
977 fclose(fp);
978 rerere(allow_rerere_auto);
979 printf(_("Automatic merge failed; "
980 "fix conflicts and then commit the result.\n"));
981 return 1;
984 static struct commit *is_old_style_invocation(int argc, const char **argv,
985 const unsigned char *head)
987 struct commit *second_token = NULL;
988 if (argc > 2) {
989 unsigned char second_sha1[20];
991 if (get_sha1(argv[1], second_sha1))
992 return NULL;
993 second_token = lookup_commit_reference_gently(second_sha1, 0);
994 if (!second_token)
995 die(_("'%s' is not a commit"), argv[1]);
996 if (hashcmp(second_token->object.sha1, head))
997 return NULL;
999 return second_token;
1002 static int evaluate_result(void)
1004 int cnt = 0;
1005 struct rev_info rev;
1007 /* Check how many files differ. */
1008 init_revisions(&rev, "");
1009 setup_revisions(0, NULL, &rev, NULL);
1010 rev.diffopt.output_format |=
1011 DIFF_FORMAT_CALLBACK;
1012 rev.diffopt.format_callback = count_diff_files;
1013 rev.diffopt.format_callback_data = &cnt;
1014 run_diff_files(&rev, 0);
1017 * Check how many unmerged entries are
1018 * there.
1020 cnt += count_unmerged_entries();
1022 return cnt;
1026 * Pretend as if the user told us to merge with the tracking
1027 * branch we have for the upstream of the current branch
1029 static int setup_with_upstream(const char ***argv)
1031 struct branch *branch = branch_get(NULL);
1032 int i;
1033 const char **args;
1035 if (!branch)
1036 die(_("No current branch."));
1037 if (!branch->remote)
1038 die(_("No remote for the current branch."));
1039 if (!branch->merge_nr)
1040 die(_("No default upstream defined for the current branch."));
1042 args = xcalloc(branch->merge_nr + 1, sizeof(char *));
1043 for (i = 0; i < branch->merge_nr; i++) {
1044 if (!branch->merge[i]->dst)
1045 die(_("No remote tracking branch for %s from %s"),
1046 branch->merge[i]->src, branch->remote_name);
1047 args[i] = branch->merge[i]->dst;
1049 args[i] = NULL;
1050 *argv = args;
1051 return i;
1054 static void write_merge_state(void)
1056 int fd;
1057 struct commit_list *j;
1058 struct strbuf buf = STRBUF_INIT;
1060 for (j = remoteheads; j; j = j->next) {
1061 unsigned const char *sha1;
1062 struct commit *c = j->item;
1063 if (c->util && merge_remote_util(c)->obj) {
1064 sha1 = merge_remote_util(c)->obj->sha1;
1065 } else {
1066 sha1 = c->object.sha1;
1068 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
1070 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1071 if (fd < 0)
1072 die_errno(_("Could not open '%s' for writing"),
1073 git_path("MERGE_HEAD"));
1074 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1075 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1076 close(fd);
1077 strbuf_addch(&merge_msg, '\n');
1078 write_merge_msg(&merge_msg);
1079 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1080 if (fd < 0)
1081 die_errno(_("Could not open '%s' for writing"),
1082 git_path("MERGE_MODE"));
1083 strbuf_reset(&buf);
1084 if (!allow_fast_forward)
1085 strbuf_addf(&buf, "no-ff");
1086 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1087 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1088 close(fd);
1091 int cmd_merge(int argc, const char **argv, const char *prefix)
1093 unsigned char result_tree[20];
1094 unsigned char stash[20];
1095 unsigned char head_sha1[20];
1096 struct commit *head_commit;
1097 struct strbuf buf = STRBUF_INIT;
1098 const char *head_arg;
1099 int flag, i;
1100 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1101 struct commit_list *common = NULL;
1102 const char *best_strategy = NULL, *wt_strategy = NULL;
1103 struct commit_list **remotes = &remoteheads;
1105 if (argc == 2 && !strcmp(argv[1], "-h"))
1106 usage_with_options(builtin_merge_usage, builtin_merge_options);
1109 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1110 * current branch.
1112 branch = resolve_ref("HEAD", head_sha1, 0, &flag);
1113 if (branch && !prefixcmp(branch, "refs/heads/"))
1114 branch += 11;
1115 if (!branch || is_null_sha1(head_sha1))
1116 head_commit = NULL;
1117 else
1118 head_commit = lookup_commit_or_die(head_sha1, "HEAD");
1120 git_config(git_merge_config, NULL);
1122 if (branch_mergeoptions)
1123 parse_branch_merge_options(branch_mergeoptions);
1124 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1125 builtin_merge_usage, 0);
1127 if (verbosity < 0 && show_progress == -1)
1128 show_progress = 0;
1130 if (abort_current_merge) {
1131 int nargc = 2;
1132 const char *nargv[] = {"reset", "--merge", NULL};
1134 if (!file_exists(git_path("MERGE_HEAD")))
1135 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1137 /* Invoke 'git reset --merge' */
1138 return cmd_reset(nargc, nargv, prefix);
1141 if (read_cache_unmerged())
1142 die_resolve_conflict("merge");
1144 if (file_exists(git_path("MERGE_HEAD"))) {
1146 * There is no unmerged entry, don't advise 'git
1147 * add/rm <file>', just 'git commit'.
1149 if (advice_resolve_conflict)
1150 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1151 "Please, commit your changes before you can merge."));
1152 else
1153 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1155 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1156 if (advice_resolve_conflict)
1157 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1158 "Please, commit your changes before you can merge."));
1159 else
1160 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1162 resolve_undo_clear();
1164 if (verbosity < 0)
1165 show_diffstat = 0;
1167 if (squash) {
1168 if (!allow_fast_forward)
1169 die(_("You cannot combine --squash with --no-ff."));
1170 option_commit = 0;
1173 if (!allow_fast_forward && fast_forward_only)
1174 die(_("You cannot combine --no-ff with --ff-only."));
1176 if (!abort_current_merge) {
1177 if (!argc && default_to_upstream)
1178 argc = setup_with_upstream(&argv);
1179 else if (argc == 1 && !strcmp(argv[0], "-"))
1180 argv[0] = "@{-1}";
1182 if (!argc)
1183 usage_with_options(builtin_merge_usage,
1184 builtin_merge_options);
1187 * This could be traditional "merge <msg> HEAD <commit>..." and
1188 * the way we can tell it is to see if the second token is HEAD,
1189 * but some people might have misused the interface and used a
1190 * committish that is the same as HEAD there instead.
1191 * Traditional format never would have "-m" so it is an
1192 * additional safety measure to check for it.
1195 if (!have_message && head_commit &&
1196 is_old_style_invocation(argc, argv, head_commit->object.sha1)) {
1197 strbuf_addstr(&merge_msg, argv[0]);
1198 head_arg = argv[1];
1199 argv += 2;
1200 argc -= 2;
1201 } else if (!head_commit) {
1202 struct commit *remote_head;
1204 * If the merged head is a valid one there is no reason
1205 * to forbid "git merge" into a branch yet to be born.
1206 * We do the same for "git pull".
1208 if (argc != 1)
1209 die(_("Can merge only exactly one commit into "
1210 "empty head"));
1211 if (squash)
1212 die(_("Squash commit into empty head not supported yet"));
1213 if (!allow_fast_forward)
1214 die(_("Non-fast-forward commit does not make sense into "
1215 "an empty head"));
1216 remote_head = get_merge_parent(argv[0]);
1217 if (!remote_head)
1218 die(_("%s - not something we can merge"), argv[0]);
1219 read_empty(remote_head->object.sha1, 0);
1220 update_ref("initial pull", "HEAD", remote_head->object.sha1,
1221 NULL, 0, DIE_ON_ERR);
1222 return 0;
1223 } else {
1224 struct strbuf merge_names = STRBUF_INIT;
1226 /* We are invoked directly as the first-class UI. */
1227 head_arg = "HEAD";
1230 * All the rest are the commits being merged; prepare
1231 * the standard merge summary message to be appended
1232 * to the given message.
1234 for (i = 0; i < argc; i++)
1235 merge_name(argv[i], &merge_names);
1237 if (!have_message || shortlog_len) {
1238 struct fmt_merge_msg_opts opts;
1239 memset(&opts, 0, sizeof(opts));
1240 opts.add_title = !have_message;
1241 opts.shortlog_len = shortlog_len;
1243 fmt_merge_msg(&merge_names, &merge_msg, &opts);
1244 if (merge_msg.len)
1245 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1249 if (!head_commit || !argc)
1250 usage_with_options(builtin_merge_usage,
1251 builtin_merge_options);
1253 strbuf_addstr(&buf, "merge");
1254 for (i = 0; i < argc; i++)
1255 strbuf_addf(&buf, " %s", argv[i]);
1256 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1257 strbuf_reset(&buf);
1259 for (i = 0; i < argc; i++) {
1260 struct commit *commit = get_merge_parent(argv[i]);
1261 if (!commit)
1262 die(_("%s - not something we can merge"), argv[i]);
1263 remotes = &commit_list_insert(commit, remotes)->next;
1264 strbuf_addf(&buf, "GITHEAD_%s",
1265 sha1_to_hex(commit->object.sha1));
1266 setenv(buf.buf, argv[i], 1);
1267 strbuf_reset(&buf);
1268 if (merge_remote_util(commit) &&
1269 merge_remote_util(commit)->obj &&
1270 merge_remote_util(commit)->obj->type == OBJ_TAG) {
1271 option_edit = 1;
1272 allow_fast_forward = 0;
1276 if (!use_strategies) {
1277 if (!remoteheads->next)
1278 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1279 else
1280 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1283 for (i = 0; i < use_strategies_nr; i++) {
1284 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1285 allow_fast_forward = 0;
1286 if (use_strategies[i]->attr & NO_TRIVIAL)
1287 allow_trivial = 0;
1290 if (!remoteheads->next)
1291 common = get_merge_bases(head_commit, remoteheads->item, 1);
1292 else {
1293 struct commit_list *list = remoteheads;
1294 commit_list_insert(head_commit, &list);
1295 common = get_octopus_merge_bases(list);
1296 free(list);
1299 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.sha1,
1300 NULL, 0, DIE_ON_ERR);
1302 if (!common)
1303 ; /* No common ancestors found. We need a real merge. */
1304 else if (!remoteheads->next && !common->next &&
1305 common->item == remoteheads->item) {
1307 * If head can reach all the merge then we are up to date.
1308 * but first the most common case of merging one remote.
1310 finish_up_to_date("Already up-to-date.");
1311 return 0;
1312 } else if (allow_fast_forward && !remoteheads->next &&
1313 !common->next &&
1314 !hashcmp(common->item->object.sha1, head_commit->object.sha1)) {
1315 /* Again the most common case of merging one remote. */
1316 struct strbuf msg = STRBUF_INIT;
1317 struct commit *commit;
1318 char hex[41];
1320 strcpy(hex, find_unique_abbrev(head_commit->object.sha1, DEFAULT_ABBREV));
1322 if (verbosity >= 0)
1323 printf(_("Updating %s..%s\n"),
1324 hex,
1325 find_unique_abbrev(remoteheads->item->object.sha1,
1326 DEFAULT_ABBREV));
1327 strbuf_addstr(&msg, "Fast-forward");
1328 if (have_message)
1329 strbuf_addstr(&msg,
1330 " (no commit created; -m option ignored)");
1331 commit = remoteheads->item;
1332 if (!commit)
1333 return 1;
1335 if (checkout_fast_forward(head_commit->object.sha1,
1336 commit->object.sha1))
1337 return 1;
1339 finish(head_commit, commit->object.sha1, msg.buf);
1340 drop_save();
1341 return 0;
1342 } else if (!remoteheads->next && common->next)
1345 * We are not doing octopus and not fast-forward. Need
1346 * a real merge.
1348 else if (!remoteheads->next && !common->next && option_commit) {
1350 * We are not doing octopus, not fast-forward, and have
1351 * only one common.
1353 refresh_cache(REFRESH_QUIET);
1354 if (allow_trivial && !fast_forward_only) {
1355 /* See if it is really trivial. */
1356 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1357 printf(_("Trying really trivial in-index merge...\n"));
1358 if (!read_tree_trivial(common->item->object.sha1,
1359 head_commit->object.sha1, remoteheads->item->object.sha1))
1360 return merge_trivial(head_commit);
1361 printf(_("Nope.\n"));
1363 } else {
1365 * An octopus. If we can reach all the remote we are up
1366 * to date.
1368 int up_to_date = 1;
1369 struct commit_list *j;
1371 for (j = remoteheads; j; j = j->next) {
1372 struct commit_list *common_one;
1375 * Here we *have* to calculate the individual
1376 * merge_bases again, otherwise "git merge HEAD^
1377 * HEAD^^" would be missed.
1379 common_one = get_merge_bases(head_commit, j->item, 1);
1380 if (hashcmp(common_one->item->object.sha1,
1381 j->item->object.sha1)) {
1382 up_to_date = 0;
1383 break;
1386 if (up_to_date) {
1387 finish_up_to_date("Already up-to-date. Yeeah!");
1388 return 0;
1392 if (fast_forward_only)
1393 die(_("Not possible to fast-forward, aborting."));
1395 /* We are going to make a new commit. */
1396 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1399 * At this point, we need a real merge. No matter what strategy
1400 * we use, it would operate on the index, possibly affecting the
1401 * working tree, and when resolved cleanly, have the desired
1402 * tree in the index -- this means that the index must be in
1403 * sync with the head commit. The strategies are responsible
1404 * to ensure this.
1406 if (use_strategies_nr == 1 ||
1408 * Stash away the local changes so that we can try more than one.
1410 save_state(stash))
1411 hashcpy(stash, null_sha1);
1413 for (i = 0; i < use_strategies_nr; i++) {
1414 int ret;
1415 if (i) {
1416 printf(_("Rewinding the tree to pristine...\n"));
1417 restore_state(head_commit->object.sha1, stash);
1419 if (use_strategies_nr != 1)
1420 printf(_("Trying merge strategy %s...\n"),
1421 use_strategies[i]->name);
1423 * Remember which strategy left the state in the working
1424 * tree.
1426 wt_strategy = use_strategies[i]->name;
1428 ret = try_merge_strategy(use_strategies[i]->name,
1429 common, head_commit, head_arg);
1430 if (!option_commit && !ret) {
1431 merge_was_ok = 1;
1433 * This is necessary here just to avoid writing
1434 * the tree, but later we will *not* exit with
1435 * status code 1 because merge_was_ok is set.
1437 ret = 1;
1440 if (ret) {
1442 * The backend exits with 1 when conflicts are
1443 * left to be resolved, with 2 when it does not
1444 * handle the given merge at all.
1446 if (ret == 1) {
1447 int cnt = evaluate_result();
1449 if (best_cnt <= 0 || cnt <= best_cnt) {
1450 best_strategy = use_strategies[i]->name;
1451 best_cnt = cnt;
1454 if (merge_was_ok)
1455 break;
1456 else
1457 continue;
1460 /* Automerge succeeded. */
1461 write_tree_trivial(result_tree);
1462 automerge_was_ok = 1;
1463 break;
1467 * If we have a resulting tree, that means the strategy module
1468 * auto resolved the merge cleanly.
1470 if (automerge_was_ok)
1471 return finish_automerge(head_commit, common, result_tree,
1472 wt_strategy);
1475 * Pick the result from the best strategy and have the user fix
1476 * it up.
1478 if (!best_strategy) {
1479 restore_state(head_commit->object.sha1, stash);
1480 if (use_strategies_nr > 1)
1481 fprintf(stderr,
1482 _("No merge strategy handled the merge.\n"));
1483 else
1484 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1485 use_strategies[0]->name);
1486 return 2;
1487 } else if (best_strategy == wt_strategy)
1488 ; /* We already have its result in the working tree. */
1489 else {
1490 printf(_("Rewinding the tree to pristine...\n"));
1491 restore_state(head_commit->object.sha1, stash);
1492 printf(_("Using the %s to prepare resolving by hand.\n"),
1493 best_strategy);
1494 try_merge_strategy(best_strategy, common, head_commit, head_arg);
1497 if (squash)
1498 finish(head_commit, NULL, NULL);
1499 else
1500 write_merge_state();
1502 if (merge_was_ok) {
1503 fprintf(stderr, _("Automatic merge went well; "
1504 "stopped before committing as requested\n"));
1505 return 0;
1506 } else
1507 return suggest_conflicts(option_renormalize);