submodule_init: die cleanly on submodules without url defined
[git/raj.git] / builtin / merge.c
blob6ec3126db1fe717dc089d84922557d91b3956886
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 "lockfile.h"
13 #include "run-command.h"
14 #include "diff.h"
15 #include "refs.h"
16 #include "commit.h"
17 #include "diffcore.h"
18 #include "revision.h"
19 #include "unpack-trees.h"
20 #include "cache-tree.h"
21 #include "dir.h"
22 #include "utf8.h"
23 #include "log-tree.h"
24 #include "color.h"
25 #include "rerere.h"
26 #include "help.h"
27 #include "merge-recursive.h"
28 #include "resolve-undo.h"
29 #include "remote.h"
30 #include "fmt-merge-msg.h"
31 #include "gpg-interface.h"
32 #include "sequencer.h"
33 #include "string-list.h"
35 #define DEFAULT_TWOHEAD (1<<0)
36 #define DEFAULT_OCTOPUS (1<<1)
37 #define NO_FAST_FORWARD (1<<2)
38 #define NO_TRIVIAL (1<<3)
40 struct strategy {
41 const char *name;
42 unsigned attr;
45 static const char * const builtin_merge_usage[] = {
46 N_("git merge [<options>] [<commit>...]"),
47 N_("git merge [<options>] <msg> HEAD <commit>"),
48 N_("git merge --abort"),
49 NULL
52 static int show_diffstat = 1, shortlog_len = -1, squash;
53 static int option_commit = 1;
54 static int option_edit = -1;
55 static int allow_trivial = 1, have_message, verify_signatures;
56 static int overwrite_ignore = 1;
57 static struct strbuf merge_msg = STRBUF_INIT;
58 static struct strategy **use_strategies;
59 static size_t use_strategies_nr, use_strategies_alloc;
60 static const char **xopts;
61 static size_t xopts_nr, xopts_alloc;
62 static const char *branch;
63 static char *branch_mergeoptions;
64 static int option_renormalize;
65 static int verbosity;
66 static int allow_rerere_auto;
67 static int abort_current_merge;
68 static int allow_unrelated_histories;
69 static int show_progress = -1;
70 static int default_to_upstream = 1;
71 static const char *sign_commit;
73 static struct strategy all_strategy[] = {
74 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
75 { "octopus", DEFAULT_OCTOPUS },
76 { "resolve", 0 },
77 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
78 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
81 static const char *pull_twohead, *pull_octopus;
83 enum ff_type {
84 FF_NO,
85 FF_ALLOW,
86 FF_ONLY
89 static enum ff_type fast_forward = FF_ALLOW;
91 static int option_parse_message(const struct option *opt,
92 const char *arg, int unset)
94 struct strbuf *buf = opt->value;
96 if (unset)
97 strbuf_setlen(buf, 0);
98 else if (arg) {
99 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
100 have_message = 1;
101 } else
102 return error(_("switch `m' requires a value"));
103 return 0;
106 static struct strategy *get_strategy(const char *name)
108 int i;
109 struct strategy *ret;
110 static struct cmdnames main_cmds, other_cmds;
111 static int loaded;
113 if (!name)
114 return NULL;
116 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
117 if (!strcmp(name, all_strategy[i].name))
118 return &all_strategy[i];
120 if (!loaded) {
121 struct cmdnames not_strategies;
122 loaded = 1;
124 memset(&not_strategies, 0, sizeof(struct cmdnames));
125 load_command_list("git-merge-", &main_cmds, &other_cmds);
126 for (i = 0; i < main_cmds.cnt; i++) {
127 int j, found = 0;
128 struct cmdname *ent = main_cmds.names[i];
129 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
130 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
131 && !all_strategy[j].name[ent->len])
132 found = 1;
133 if (!found)
134 add_cmdname(&not_strategies, ent->name, ent->len);
136 exclude_cmds(&main_cmds, &not_strategies);
138 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
139 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
140 fprintf(stderr, _("Available strategies are:"));
141 for (i = 0; i < main_cmds.cnt; i++)
142 fprintf(stderr, " %s", main_cmds.names[i]->name);
143 fprintf(stderr, ".\n");
144 if (other_cmds.cnt) {
145 fprintf(stderr, _("Available custom strategies are:"));
146 for (i = 0; i < other_cmds.cnt; i++)
147 fprintf(stderr, " %s", other_cmds.names[i]->name);
148 fprintf(stderr, ".\n");
150 exit(1);
153 ret = xcalloc(1, sizeof(struct strategy));
154 ret->name = xstrdup(name);
155 ret->attr = NO_TRIVIAL;
156 return ret;
159 static void append_strategy(struct strategy *s)
161 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
162 use_strategies[use_strategies_nr++] = s;
165 static int option_parse_strategy(const struct option *opt,
166 const char *name, int unset)
168 if (unset)
169 return 0;
171 append_strategy(get_strategy(name));
172 return 0;
175 static int option_parse_x(const struct option *opt,
176 const char *arg, int unset)
178 if (unset)
179 return 0;
181 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
182 xopts[xopts_nr++] = xstrdup(arg);
183 return 0;
186 static int option_parse_n(const struct option *opt,
187 const char *arg, int unset)
189 show_diffstat = unset;
190 return 0;
193 static struct option builtin_merge_options[] = {
194 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
195 N_("do not show a diffstat at the end of the merge"),
196 PARSE_OPT_NOARG, option_parse_n },
197 OPT_BOOL(0, "stat", &show_diffstat,
198 N_("show a diffstat at the end of the merge")),
199 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
200 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
201 N_("add (at most <n>) entries from shortlog to merge commit message"),
202 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
203 OPT_BOOL(0, "squash", &squash,
204 N_("create a single commit instead of doing a merge")),
205 OPT_BOOL(0, "commit", &option_commit,
206 N_("perform a commit if the merge succeeds (default)")),
207 OPT_BOOL('e', "edit", &option_edit,
208 N_("edit message before committing")),
209 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
210 { OPTION_SET_INT, 0, "ff-only", &fast_forward, NULL,
211 N_("abort if fast-forward is not possible"),
212 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, FF_ONLY },
213 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
214 OPT_BOOL(0, "verify-signatures", &verify_signatures,
215 N_("Verify that the named commit has a valid GPG signature")),
216 OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
217 N_("merge strategy to use"), option_parse_strategy),
218 OPT_CALLBACK('X', "strategy-option", &xopts, N_("option=value"),
219 N_("option for selected merge strategy"), option_parse_x),
220 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
221 N_("merge commit message (for a non-fast-forward merge)"),
222 option_parse_message),
223 OPT__VERBOSITY(&verbosity),
224 OPT_BOOL(0, "abort", &abort_current_merge,
225 N_("abort the current in-progress merge")),
226 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
227 N_("allow merging unrelated histories")),
228 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
229 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
230 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
231 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
232 OPT_END()
235 /* Cleans up metadata that is uninteresting after a succeeded merge. */
236 static void drop_save(void)
238 unlink(git_path_merge_head());
239 unlink(git_path_merge_msg());
240 unlink(git_path_merge_mode());
243 static int save_state(unsigned char *stash)
245 int len;
246 struct child_process cp = CHILD_PROCESS_INIT;
247 struct strbuf buffer = STRBUF_INIT;
248 const char *argv[] = {"stash", "create", NULL};
250 cp.argv = argv;
251 cp.out = -1;
252 cp.git_cmd = 1;
254 if (start_command(&cp))
255 die(_("could not run stash."));
256 len = strbuf_read(&buffer, cp.out, 1024);
257 close(cp.out);
259 if (finish_command(&cp) || len < 0)
260 die(_("stash failed"));
261 else if (!len) /* no changes */
262 return -1;
263 strbuf_setlen(&buffer, buffer.len-1);
264 if (get_sha1(buffer.buf, stash))
265 die(_("not a valid object: %s"), buffer.buf);
266 return 0;
269 static void read_empty(unsigned const char *sha1, int verbose)
271 int i = 0;
272 const char *args[7];
274 args[i++] = "read-tree";
275 if (verbose)
276 args[i++] = "-v";
277 args[i++] = "-m";
278 args[i++] = "-u";
279 args[i++] = EMPTY_TREE_SHA1_HEX;
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 reset_hard(unsigned const char *sha1, int verbose)
289 int i = 0;
290 const char *args[6];
292 args[i++] = "read-tree";
293 if (verbose)
294 args[i++] = "-v";
295 args[i++] = "--reset";
296 args[i++] = "-u";
297 args[i++] = sha1_to_hex(sha1);
298 args[i] = NULL;
300 if (run_command_v_opt(args, RUN_GIT_CMD))
301 die(_("read-tree failed"));
304 static void restore_state(const unsigned char *head,
305 const unsigned char *stash)
307 struct strbuf sb = STRBUF_INIT;
308 const char *args[] = { "stash", "apply", NULL, NULL };
310 if (is_null_sha1(stash))
311 return;
313 reset_hard(head, 1);
315 args[2] = sha1_to_hex(stash);
318 * It is OK to ignore error here, for example when there was
319 * nothing to restore.
321 run_command_v_opt(args, RUN_GIT_CMD);
323 strbuf_release(&sb);
324 refresh_cache(REFRESH_QUIET);
327 /* This is called when no merge was necessary. */
328 static void finish_up_to_date(const char *msg)
330 if (verbosity >= 0)
331 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
332 drop_save();
335 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
337 struct rev_info rev;
338 struct strbuf out = STRBUF_INIT;
339 struct commit_list *j;
340 const char *filename;
341 int fd;
342 struct pretty_print_context ctx = {0};
344 printf(_("Squash commit -- not updating HEAD\n"));
345 filename = git_path_squash_msg();
346 fd = open(filename, O_WRONLY | O_CREAT, 0666);
347 if (fd < 0)
348 die_errno(_("Could not write to '%s'"), filename);
350 init_revisions(&rev, NULL);
351 rev.ignore_merges = 1;
352 rev.commit_format = CMIT_FMT_MEDIUM;
354 commit->object.flags |= UNINTERESTING;
355 add_pending_object(&rev, &commit->object, NULL);
357 for (j = remoteheads; j; j = j->next)
358 add_pending_object(&rev, &j->item->object, NULL);
360 setup_revisions(0, NULL, &rev, NULL);
361 if (prepare_revision_walk(&rev))
362 die(_("revision walk setup failed"));
364 ctx.abbrev = rev.abbrev;
365 ctx.date_mode = rev.date_mode;
366 ctx.fmt = rev.commit_format;
368 strbuf_addstr(&out, "Squashed commit of the following:\n");
369 while ((commit = get_revision(&rev)) != NULL) {
370 strbuf_addch(&out, '\n');
371 strbuf_addf(&out, "commit %s\n",
372 oid_to_hex(&commit->object.oid));
373 pretty_print_commit(&ctx, commit, &out);
375 if (write_in_full(fd, out.buf, out.len) != out.len)
376 die_errno(_("Writing SQUASH_MSG"));
377 if (close(fd))
378 die_errno(_("Finishing SQUASH_MSG"));
379 strbuf_release(&out);
382 static void finish(struct commit *head_commit,
383 struct commit_list *remoteheads,
384 const unsigned char *new_head, const char *msg)
386 struct strbuf reflog_message = STRBUF_INIT;
387 const unsigned char *head = head_commit->object.oid.hash;
389 if (!msg)
390 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
391 else {
392 if (verbosity >= 0)
393 printf("%s\n", msg);
394 strbuf_addf(&reflog_message, "%s: %s",
395 getenv("GIT_REFLOG_ACTION"), msg);
397 if (squash) {
398 squash_message(head_commit, remoteheads);
399 } else {
400 if (verbosity >= 0 && !merge_msg.len)
401 printf(_("No merge message -- not updating HEAD\n"));
402 else {
403 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
404 update_ref(reflog_message.buf, "HEAD",
405 new_head, head, 0,
406 UPDATE_REFS_DIE_ON_ERR);
408 * We ignore errors in 'gc --auto', since the
409 * user should see them.
411 close_all_packs();
412 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
415 if (new_head && show_diffstat) {
416 struct diff_options opts;
417 diff_setup(&opts);
418 opts.stat_width = -1; /* use full terminal width */
419 opts.stat_graph_width = -1; /* respect statGraphWidth config */
420 opts.output_format |=
421 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
422 opts.detect_rename = DIFF_DETECT_RENAME;
423 diff_setup_done(&opts);
424 diff_tree_sha1(head, new_head, "", &opts);
425 diffcore_std(&opts);
426 diff_flush(&opts);
429 /* Run a post-merge hook */
430 run_hook_le(NULL, "post-merge", squash ? "1" : "0", NULL);
432 strbuf_release(&reflog_message);
435 /* Get the name for the merge commit's message. */
436 static void merge_name(const char *remote, struct strbuf *msg)
438 struct commit *remote_head;
439 unsigned char branch_head[20];
440 struct strbuf buf = STRBUF_INIT;
441 struct strbuf bname = STRBUF_INIT;
442 const char *ptr;
443 char *found_ref;
444 int len, early;
446 strbuf_branchname(&bname, remote);
447 remote = bname.buf;
449 memset(branch_head, 0, sizeof(branch_head));
450 remote_head = get_merge_parent(remote);
451 if (!remote_head)
452 die(_("'%s' does not point to a commit"), remote);
454 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
455 if (starts_with(found_ref, "refs/heads/")) {
456 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
457 sha1_to_hex(branch_head), remote);
458 goto cleanup;
460 if (starts_with(found_ref, "refs/tags/")) {
461 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
462 sha1_to_hex(branch_head), remote);
463 goto cleanup;
465 if (starts_with(found_ref, "refs/remotes/")) {
466 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
467 sha1_to_hex(branch_head), remote);
468 goto cleanup;
472 /* See if remote matches <name>^^^.. or <name>~<number> */
473 for (len = 0, ptr = remote + strlen(remote);
474 remote < ptr && ptr[-1] == '^';
475 ptr--)
476 len++;
477 if (len)
478 early = 1;
479 else {
480 early = 0;
481 ptr = strrchr(remote, '~');
482 if (ptr) {
483 int seen_nonzero = 0;
485 len++; /* count ~ */
486 while (*++ptr && isdigit(*ptr)) {
487 seen_nonzero |= (*ptr != '0');
488 len++;
490 if (*ptr)
491 len = 0; /* not ...~<number> */
492 else if (seen_nonzero)
493 early = 1;
494 else if (len == 1)
495 early = 1; /* "name~" is "name~1"! */
498 if (len) {
499 struct strbuf truname = STRBUF_INIT;
500 strbuf_addf(&truname, "refs/heads/%s", remote);
501 strbuf_setlen(&truname, truname.len - len);
502 if (ref_exists(truname.buf)) {
503 strbuf_addf(msg,
504 "%s\t\tbranch '%s'%s of .\n",
505 sha1_to_hex(remote_head->object.oid.hash),
506 truname.buf + 11,
507 (early ? " (early part)" : ""));
508 strbuf_release(&truname);
509 goto cleanup;
511 strbuf_release(&truname);
514 if (remote_head->util) {
515 struct merge_remote_desc *desc;
516 desc = merge_remote_util(remote_head);
517 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
518 strbuf_addf(msg, "%s\t\t%s '%s'\n",
519 sha1_to_hex(desc->obj->oid.hash),
520 typename(desc->obj->type),
521 remote);
522 goto cleanup;
526 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
527 sha1_to_hex(remote_head->object.oid.hash), remote);
528 cleanup:
529 strbuf_release(&buf);
530 strbuf_release(&bname);
533 static void parse_branch_merge_options(char *bmo)
535 const char **argv;
536 int argc;
538 if (!bmo)
539 return;
540 argc = split_cmdline(bmo, &argv);
541 if (argc < 0)
542 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
543 split_cmdline_strerror(argc));
544 REALLOC_ARRAY(argv, argc + 2);
545 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
546 argc++;
547 argv[0] = "branch.*.mergeoptions";
548 parse_options(argc, argv, NULL, builtin_merge_options,
549 builtin_merge_usage, 0);
550 free(argv);
553 static int git_merge_config(const char *k, const char *v, void *cb)
555 int status;
557 if (branch && starts_with(k, "branch.") &&
558 starts_with(k + 7, branch) &&
559 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
560 free(branch_mergeoptions);
561 branch_mergeoptions = xstrdup(v);
562 return 0;
565 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
566 show_diffstat = git_config_bool(k, v);
567 else if (!strcmp(k, "pull.twohead"))
568 return git_config_string(&pull_twohead, k, v);
569 else if (!strcmp(k, "pull.octopus"))
570 return git_config_string(&pull_octopus, k, v);
571 else if (!strcmp(k, "merge.renormalize"))
572 option_renormalize = git_config_bool(k, v);
573 else if (!strcmp(k, "merge.ff")) {
574 int boolval = git_config_maybe_bool(k, v);
575 if (0 <= boolval) {
576 fast_forward = boolval ? FF_ALLOW : FF_NO;
577 } else if (v && !strcmp(v, "only")) {
578 fast_forward = FF_ONLY;
579 } /* do not barf on values from future versions of git */
580 return 0;
581 } else if (!strcmp(k, "merge.defaulttoupstream")) {
582 default_to_upstream = git_config_bool(k, v);
583 return 0;
584 } else if (!strcmp(k, "commit.gpgsign")) {
585 sign_commit = git_config_bool(k, v) ? "" : NULL;
586 return 0;
589 status = fmt_merge_msg_config(k, v, cb);
590 if (status)
591 return status;
592 status = git_gpg_config(k, v, NULL);
593 if (status)
594 return status;
595 return git_diff_ui_config(k, v, cb);
598 static int read_tree_trivial(unsigned char *common, unsigned char *head,
599 unsigned char *one)
601 int i, nr_trees = 0;
602 struct tree *trees[MAX_UNPACK_TREES];
603 struct tree_desc t[MAX_UNPACK_TREES];
604 struct unpack_trees_options opts;
606 memset(&opts, 0, sizeof(opts));
607 opts.head_idx = 2;
608 opts.src_index = &the_index;
609 opts.dst_index = &the_index;
610 opts.update = 1;
611 opts.verbose_update = 1;
612 opts.trivial_merges_only = 1;
613 opts.merge = 1;
614 trees[nr_trees] = parse_tree_indirect(common);
615 if (!trees[nr_trees++])
616 return -1;
617 trees[nr_trees] = parse_tree_indirect(head);
618 if (!trees[nr_trees++])
619 return -1;
620 trees[nr_trees] = parse_tree_indirect(one);
621 if (!trees[nr_trees++])
622 return -1;
623 opts.fn = threeway_merge;
624 cache_tree_free(&active_cache_tree);
625 for (i = 0; i < nr_trees; i++) {
626 parse_tree(trees[i]);
627 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
629 if (unpack_trees(nr_trees, t, &opts))
630 return -1;
631 return 0;
634 static void write_tree_trivial(unsigned char *sha1)
636 if (write_cache_as_tree(sha1, 0, NULL))
637 die(_("git write-tree failed to write a tree"));
640 static int try_merge_strategy(const char *strategy, struct commit_list *common,
641 struct commit_list *remoteheads,
642 struct commit *head, const char *head_arg)
644 static struct lock_file lock;
646 hold_locked_index(&lock, 1);
647 refresh_cache(REFRESH_QUIET);
648 if (active_cache_changed &&
649 write_locked_index(&the_index, &lock, COMMIT_LOCK))
650 return error(_("Unable to write index."));
651 rollback_lock_file(&lock);
653 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
654 int clean, x;
655 struct commit *result;
656 struct commit_list *reversed = NULL;
657 struct merge_options o;
658 struct commit_list *j;
660 if (remoteheads->next) {
661 error(_("Not handling anything other than two heads merge."));
662 return 2;
665 init_merge_options(&o);
666 if (!strcmp(strategy, "subtree"))
667 o.subtree_shift = "";
669 o.renormalize = option_renormalize;
670 o.show_rename_progress =
671 show_progress == -1 ? isatty(2) : show_progress;
673 for (x = 0; x < xopts_nr; x++)
674 if (parse_merge_opt(&o, xopts[x]))
675 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
677 o.branch1 = head_arg;
678 o.branch2 = merge_remote_util(remoteheads->item)->name;
680 for (j = common; j; j = j->next)
681 commit_list_insert(j->item, &reversed);
683 hold_locked_index(&lock, 1);
684 clean = merge_recursive(&o, head,
685 remoteheads->item, reversed, &result);
686 if (active_cache_changed &&
687 write_locked_index(&the_index, &lock, COMMIT_LOCK))
688 die (_("unable to write %s"), get_index_file());
689 rollback_lock_file(&lock);
690 return clean ? 0 : 1;
691 } else {
692 return try_merge_command(strategy, xopts_nr, xopts,
693 common, head_arg, remoteheads);
697 static void count_diff_files(struct diff_queue_struct *q,
698 struct diff_options *opt, void *data)
700 int *count = data;
702 (*count) += q->nr;
705 static int count_unmerged_entries(void)
707 int i, ret = 0;
709 for (i = 0; i < active_nr; i++)
710 if (ce_stage(active_cache[i]))
711 ret++;
713 return ret;
716 static void add_strategies(const char *string, unsigned attr)
718 int i;
720 if (string) {
721 struct string_list list = STRING_LIST_INIT_DUP;
722 struct string_list_item *item;
723 string_list_split(&list, string, ' ', -1);
724 for_each_string_list_item(item, &list)
725 append_strategy(get_strategy(item->string));
726 string_list_clear(&list, 0);
727 return;
729 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
730 if (all_strategy[i].attr & attr)
731 append_strategy(&all_strategy[i]);
735 static void write_merge_msg(struct strbuf *msg)
737 const char *filename = git_path_merge_msg();
738 int fd = open(filename, O_WRONLY | O_CREAT, 0666);
739 if (fd < 0)
740 die_errno(_("Could not open '%s' for writing"),
741 filename);
742 if (write_in_full(fd, msg->buf, msg->len) != msg->len)
743 die_errno(_("Could not write to '%s'"), filename);
744 close(fd);
747 static void read_merge_msg(struct strbuf *msg)
749 const char *filename = git_path_merge_msg();
750 strbuf_reset(msg);
751 if (strbuf_read_file(msg, filename, 0) < 0)
752 die_errno(_("Could not read from '%s'"), filename);
755 static void write_merge_state(struct commit_list *);
756 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
758 if (err_msg)
759 error("%s", err_msg);
760 fprintf(stderr,
761 _("Not committing merge; use 'git commit' to complete the merge.\n"));
762 write_merge_state(remoteheads);
763 exit(1);
766 static const char merge_editor_comment[] =
767 N_("Please enter a commit message to explain why this merge is necessary,\n"
768 "especially if it merges an updated upstream into a topic branch.\n"
769 "\n"
770 "Lines starting with '%c' will be ignored, and an empty message aborts\n"
771 "the commit.\n");
773 static void prepare_to_commit(struct commit_list *remoteheads)
775 struct strbuf msg = STRBUF_INIT;
776 strbuf_addbuf(&msg, &merge_msg);
777 strbuf_addch(&msg, '\n');
778 if (0 < option_edit)
779 strbuf_commented_addf(&msg, _(merge_editor_comment), comment_line_char);
780 write_merge_msg(&msg);
781 if (run_commit_hook(0 < option_edit, get_index_file(), "prepare-commit-msg",
782 git_path_merge_msg(), "merge", NULL))
783 abort_commit(remoteheads, NULL);
784 if (0 < option_edit) {
785 if (launch_editor(git_path_merge_msg(), NULL, NULL))
786 abort_commit(remoteheads, NULL);
788 read_merge_msg(&msg);
789 strbuf_stripspace(&msg, 0 < option_edit);
790 if (!msg.len)
791 abort_commit(remoteheads, _("Empty commit message."));
792 strbuf_release(&merge_msg);
793 strbuf_addbuf(&merge_msg, &msg);
794 strbuf_release(&msg);
797 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
799 unsigned char result_tree[20], result_commit[20];
800 struct commit_list *parents, **pptr = &parents;
801 static struct lock_file lock;
803 hold_locked_index(&lock, 1);
804 refresh_cache(REFRESH_QUIET);
805 if (active_cache_changed &&
806 write_locked_index(&the_index, &lock, COMMIT_LOCK))
807 return error(_("Unable to write index."));
808 rollback_lock_file(&lock);
810 write_tree_trivial(result_tree);
811 printf(_("Wonderful.\n"));
812 pptr = commit_list_append(head, pptr);
813 pptr = commit_list_append(remoteheads->item, pptr);
814 prepare_to_commit(remoteheads);
815 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
816 result_commit, NULL, sign_commit))
817 die(_("failed to write commit object"));
818 finish(head, remoteheads, result_commit, "In-index merge");
819 drop_save();
820 return 0;
823 static int finish_automerge(struct commit *head,
824 int head_subsumed,
825 struct commit_list *common,
826 struct commit_list *remoteheads,
827 unsigned char *result_tree,
828 const char *wt_strategy)
830 struct commit_list *parents = NULL;
831 struct strbuf buf = STRBUF_INIT;
832 unsigned char result_commit[20];
834 free_commit_list(common);
835 parents = remoteheads;
836 if (!head_subsumed || fast_forward == FF_NO)
837 commit_list_insert(head, &parents);
838 strbuf_addch(&merge_msg, '\n');
839 prepare_to_commit(remoteheads);
840 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
841 result_commit, NULL, sign_commit))
842 die(_("failed to write commit object"));
843 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
844 finish(head, remoteheads, result_commit, buf.buf);
845 strbuf_release(&buf);
846 drop_save();
847 return 0;
850 static int suggest_conflicts(void)
852 const char *filename;
853 FILE *fp;
854 struct strbuf msgbuf = STRBUF_INIT;
856 filename = git_path_merge_msg();
857 fp = fopen(filename, "a");
858 if (!fp)
859 die_errno(_("Could not open '%s' for writing"), filename);
861 append_conflicts_hint(&msgbuf);
862 fputs(msgbuf.buf, fp);
863 strbuf_release(&msgbuf);
864 fclose(fp);
865 rerere(allow_rerere_auto);
866 printf(_("Automatic merge failed; "
867 "fix conflicts and then commit the result.\n"));
868 return 1;
871 static struct commit *is_old_style_invocation(int argc, const char **argv,
872 const unsigned char *head)
874 struct commit *second_token = NULL;
875 if (argc > 2) {
876 unsigned char second_sha1[20];
878 if (get_sha1(argv[1], second_sha1))
879 return NULL;
880 second_token = lookup_commit_reference_gently(second_sha1, 0);
881 if (!second_token)
882 die(_("'%s' is not a commit"), argv[1]);
883 if (hashcmp(second_token->object.oid.hash, head))
884 return NULL;
886 return second_token;
889 static int evaluate_result(void)
891 int cnt = 0;
892 struct rev_info rev;
894 /* Check how many files differ. */
895 init_revisions(&rev, "");
896 setup_revisions(0, NULL, &rev, NULL);
897 rev.diffopt.output_format |=
898 DIFF_FORMAT_CALLBACK;
899 rev.diffopt.format_callback = count_diff_files;
900 rev.diffopt.format_callback_data = &cnt;
901 run_diff_files(&rev, 0);
904 * Check how many unmerged entries are
905 * there.
907 cnt += count_unmerged_entries();
909 return cnt;
913 * Pretend as if the user told us to merge with the remote-tracking
914 * branch we have for the upstream of the current branch
916 static int setup_with_upstream(const char ***argv)
918 struct branch *branch = branch_get(NULL);
919 int i;
920 const char **args;
922 if (!branch)
923 die(_("No current branch."));
924 if (!branch->remote_name)
925 die(_("No remote for the current branch."));
926 if (!branch->merge_nr)
927 die(_("No default upstream defined for the current branch."));
929 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
930 for (i = 0; i < branch->merge_nr; i++) {
931 if (!branch->merge[i]->dst)
932 die(_("No remote-tracking branch for %s from %s"),
933 branch->merge[i]->src, branch->remote_name);
934 args[i] = branch->merge[i]->dst;
936 args[i] = NULL;
937 *argv = args;
938 return i;
941 static void write_merge_state(struct commit_list *remoteheads)
943 const char *filename;
944 int fd;
945 struct commit_list *j;
946 struct strbuf buf = STRBUF_INIT;
948 for (j = remoteheads; j; j = j->next) {
949 struct object_id *oid;
950 struct commit *c = j->item;
951 if (c->util && merge_remote_util(c)->obj) {
952 oid = &merge_remote_util(c)->obj->oid;
953 } else {
954 oid = &c->object.oid;
956 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
958 filename = git_path_merge_head();
959 fd = open(filename, O_WRONLY | O_CREAT, 0666);
960 if (fd < 0)
961 die_errno(_("Could not open '%s' for writing"), filename);
962 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
963 die_errno(_("Could not write to '%s'"), filename);
964 close(fd);
965 strbuf_addch(&merge_msg, '\n');
966 write_merge_msg(&merge_msg);
968 filename = git_path_merge_mode();
969 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
970 if (fd < 0)
971 die_errno(_("Could not open '%s' for writing"), filename);
972 strbuf_reset(&buf);
973 if (fast_forward == FF_NO)
974 strbuf_addf(&buf, "no-ff");
975 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
976 die_errno(_("Could not write to '%s'"), filename);
977 close(fd);
980 static int default_edit_option(void)
982 static const char name[] = "GIT_MERGE_AUTOEDIT";
983 const char *e = getenv(name);
984 struct stat st_stdin, st_stdout;
986 if (have_message)
987 /* an explicit -m msg without --[no-]edit */
988 return 0;
990 if (e) {
991 int v = git_config_maybe_bool(name, e);
992 if (v < 0)
993 die("Bad value '%s' in environment '%s'", e, name);
994 return v;
997 /* Use editor if stdin and stdout are the same and is a tty */
998 return (!fstat(0, &st_stdin) &&
999 !fstat(1, &st_stdout) &&
1000 isatty(0) && isatty(1) &&
1001 st_stdin.st_dev == st_stdout.st_dev &&
1002 st_stdin.st_ino == st_stdout.st_ino &&
1003 st_stdin.st_mode == st_stdout.st_mode);
1006 static struct commit_list *reduce_parents(struct commit *head_commit,
1007 int *head_subsumed,
1008 struct commit_list *remoteheads)
1010 struct commit_list *parents, **remotes;
1013 * Is the current HEAD reachable from another commit being
1014 * merged? If so we do not want to record it as a parent of
1015 * the resulting merge, unless --no-ff is given. We will flip
1016 * this variable to 0 when we find HEAD among the independent
1017 * tips being merged.
1019 *head_subsumed = 1;
1021 /* Find what parents to record by checking independent ones. */
1022 parents = reduce_heads(remoteheads);
1024 remoteheads = NULL;
1025 remotes = &remoteheads;
1026 while (parents) {
1027 struct commit *commit = pop_commit(&parents);
1028 if (commit == head_commit)
1029 *head_subsumed = 0;
1030 else
1031 remotes = &commit_list_insert(commit, remotes)->next;
1033 return remoteheads;
1036 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1038 struct fmt_merge_msg_opts opts;
1040 memset(&opts, 0, sizeof(opts));
1041 opts.add_title = !have_message;
1042 opts.shortlog_len = shortlog_len;
1043 opts.credit_people = (0 < option_edit);
1045 fmt_merge_msg(merge_names, merge_msg, &opts);
1046 if (merge_msg->len)
1047 strbuf_setlen(merge_msg, merge_msg->len - 1);
1050 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1052 const char *filename;
1053 int fd, pos, npos;
1054 struct strbuf fetch_head_file = STRBUF_INIT;
1056 if (!merge_names)
1057 merge_names = &fetch_head_file;
1059 filename = git_path_fetch_head();
1060 fd = open(filename, O_RDONLY);
1061 if (fd < 0)
1062 die_errno(_("could not open '%s' for reading"), filename);
1064 if (strbuf_read(merge_names, fd, 0) < 0)
1065 die_errno(_("could not read '%s'"), filename);
1066 if (close(fd) < 0)
1067 die_errno(_("could not close '%s'"), filename);
1069 for (pos = 0; pos < merge_names->len; pos = npos) {
1070 unsigned char sha1[20];
1071 char *ptr;
1072 struct commit *commit;
1074 ptr = strchr(merge_names->buf + pos, '\n');
1075 if (ptr)
1076 npos = ptr - merge_names->buf + 1;
1077 else
1078 npos = merge_names->len;
1080 if (npos - pos < 40 + 2 ||
1081 get_sha1_hex(merge_names->buf + pos, sha1))
1082 commit = NULL; /* bad */
1083 else if (memcmp(merge_names->buf + pos + 40, "\t\t", 2))
1084 continue; /* not-for-merge */
1085 else {
1086 char saved = merge_names->buf[pos + 40];
1087 merge_names->buf[pos + 40] = '\0';
1088 commit = get_merge_parent(merge_names->buf + pos);
1089 merge_names->buf[pos + 40] = saved;
1091 if (!commit) {
1092 if (ptr)
1093 *ptr = '\0';
1094 die("not something we can merge in %s: %s",
1095 filename, merge_names->buf + pos);
1097 remotes = &commit_list_insert(commit, remotes)->next;
1100 if (merge_names == &fetch_head_file)
1101 strbuf_release(&fetch_head_file);
1104 static struct commit_list *collect_parents(struct commit *head_commit,
1105 int *head_subsumed,
1106 int argc, const char **argv,
1107 struct strbuf *merge_msg)
1109 int i;
1110 struct commit_list *remoteheads = NULL;
1111 struct commit_list **remotes = &remoteheads;
1112 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1114 if (merge_msg && (!have_message || shortlog_len))
1115 autogen = &merge_names;
1117 if (head_commit)
1118 remotes = &commit_list_insert(head_commit, remotes)->next;
1120 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1121 handle_fetch_head(remotes, autogen);
1122 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1123 } else {
1124 for (i = 0; i < argc; i++) {
1125 struct commit *commit = get_merge_parent(argv[i]);
1126 if (!commit)
1127 help_unknown_ref(argv[i], "merge",
1128 "not something we can merge");
1129 remotes = &commit_list_insert(commit, remotes)->next;
1131 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1132 if (autogen) {
1133 struct commit_list *p;
1134 for (p = remoteheads; p; p = p->next)
1135 merge_name(merge_remote_util(p->item)->name, autogen);
1139 if (autogen) {
1140 prepare_merge_message(autogen, merge_msg);
1141 strbuf_release(autogen);
1144 return remoteheads;
1147 int cmd_merge(int argc, const char **argv, const char *prefix)
1149 unsigned char result_tree[20];
1150 unsigned char stash[20];
1151 unsigned char head_sha1[20];
1152 struct commit *head_commit;
1153 struct strbuf buf = STRBUF_INIT;
1154 const char *head_arg;
1155 int i, ret = 0, head_subsumed;
1156 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1157 struct commit_list *common = NULL;
1158 const char *best_strategy = NULL, *wt_strategy = NULL;
1159 struct commit_list *remoteheads, *p;
1160 void *branch_to_free;
1162 if (argc == 2 && !strcmp(argv[1], "-h"))
1163 usage_with_options(builtin_merge_usage, builtin_merge_options);
1166 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1167 * current branch.
1169 branch = branch_to_free = resolve_refdup("HEAD", 0, head_sha1, NULL);
1170 if (branch && starts_with(branch, "refs/heads/"))
1171 branch += 11;
1172 if (!branch || is_null_sha1(head_sha1))
1173 head_commit = NULL;
1174 else
1175 head_commit = lookup_commit_or_die(head_sha1, "HEAD");
1177 init_diff_ui_defaults();
1178 git_config(git_merge_config, NULL);
1180 if (branch_mergeoptions)
1181 parse_branch_merge_options(branch_mergeoptions);
1182 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1183 builtin_merge_usage, 0);
1184 if (shortlog_len < 0)
1185 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1187 if (verbosity < 0 && show_progress == -1)
1188 show_progress = 0;
1190 if (abort_current_merge) {
1191 int nargc = 2;
1192 const char *nargv[] = {"reset", "--merge", NULL};
1194 if (!file_exists(git_path_merge_head()))
1195 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1197 /* Invoke 'git reset --merge' */
1198 ret = cmd_reset(nargc, nargv, prefix);
1199 goto done;
1202 if (read_cache_unmerged())
1203 die_resolve_conflict("merge");
1205 if (file_exists(git_path_merge_head())) {
1207 * There is no unmerged entry, don't advise 'git
1208 * add/rm <file>', just 'git commit'.
1210 if (advice_resolve_conflict)
1211 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1212 "Please, commit your changes before you merge."));
1213 else
1214 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1216 if (file_exists(git_path_cherry_pick_head())) {
1217 if (advice_resolve_conflict)
1218 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1219 "Please, commit your changes before you merge."));
1220 else
1221 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1223 resolve_undo_clear();
1225 if (verbosity < 0)
1226 show_diffstat = 0;
1228 if (squash) {
1229 if (fast_forward == FF_NO)
1230 die(_("You cannot combine --squash with --no-ff."));
1231 option_commit = 0;
1234 if (!argc) {
1235 if (default_to_upstream)
1236 argc = setup_with_upstream(&argv);
1237 else
1238 die(_("No commit specified and merge.defaultToUpstream not set."));
1239 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1240 argv[0] = "@{-1}";
1243 if (!argc)
1244 usage_with_options(builtin_merge_usage,
1245 builtin_merge_options);
1247 if (!head_commit) {
1249 * If the merged head is a valid one there is no reason
1250 * to forbid "git merge" into a branch yet to be born.
1251 * We do the same for "git pull".
1253 unsigned char *remote_head_sha1;
1254 if (squash)
1255 die(_("Squash commit into empty head not supported yet"));
1256 if (fast_forward == FF_NO)
1257 die(_("Non-fast-forward commit does not make sense into "
1258 "an empty head"));
1259 remoteheads = collect_parents(head_commit, &head_subsumed,
1260 argc, argv, NULL);
1261 if (!remoteheads)
1262 die(_("%s - not something we can merge"), argv[0]);
1263 if (remoteheads->next)
1264 die(_("Can merge only exactly one commit into empty head"));
1265 remote_head_sha1 = remoteheads->item->object.oid.hash;
1266 read_empty(remote_head_sha1, 0);
1267 update_ref("initial pull", "HEAD", remote_head_sha1,
1268 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1269 goto done;
1273 * This could be traditional "merge <msg> HEAD <commit>..." and
1274 * the way we can tell it is to see if the second token is HEAD,
1275 * but some people might have misused the interface and used a
1276 * commit-ish that is the same as HEAD there instead.
1277 * Traditional format never would have "-m" so it is an
1278 * additional safety measure to check for it.
1280 if (!have_message &&
1281 is_old_style_invocation(argc, argv, head_commit->object.oid.hash)) {
1282 warning("old-style 'git merge <msg> HEAD <commit>' is deprecated.");
1283 strbuf_addstr(&merge_msg, argv[0]);
1284 head_arg = argv[1];
1285 argv += 2;
1286 argc -= 2;
1287 remoteheads = collect_parents(head_commit, &head_subsumed,
1288 argc, argv, NULL);
1289 } else {
1290 /* We are invoked directly as the first-class UI. */
1291 head_arg = "HEAD";
1294 * All the rest are the commits being merged; prepare
1295 * the standard merge summary message to be appended
1296 * to the given message.
1298 remoteheads = collect_parents(head_commit, &head_subsumed,
1299 argc, argv, &merge_msg);
1302 if (!head_commit || !argc)
1303 usage_with_options(builtin_merge_usage,
1304 builtin_merge_options);
1306 if (verify_signatures) {
1307 for (p = remoteheads; p; p = p->next) {
1308 struct commit *commit = p->item;
1309 char hex[GIT_SHA1_HEXSZ + 1];
1310 struct signature_check signature_check;
1311 memset(&signature_check, 0, sizeof(signature_check));
1313 check_commit_signature(commit, &signature_check);
1315 find_unique_abbrev_r(hex, commit->object.oid.hash, DEFAULT_ABBREV);
1316 switch (signature_check.result) {
1317 case 'G':
1318 break;
1319 case 'U':
1320 die(_("Commit %s has an untrusted GPG signature, "
1321 "allegedly by %s."), hex, signature_check.signer);
1322 case 'B':
1323 die(_("Commit %s has a bad GPG signature "
1324 "allegedly by %s."), hex, signature_check.signer);
1325 default: /* 'N' */
1326 die(_("Commit %s does not have a GPG signature."), hex);
1328 if (verbosity >= 0 && signature_check.result == 'G')
1329 printf(_("Commit %s has a good GPG signature by %s\n"),
1330 hex, signature_check.signer);
1332 signature_check_clear(&signature_check);
1336 strbuf_addstr(&buf, "merge");
1337 for (p = remoteheads; p; p = p->next)
1338 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1339 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1340 strbuf_reset(&buf);
1342 for (p = remoteheads; p; p = p->next) {
1343 struct commit *commit = p->item;
1344 strbuf_addf(&buf, "GITHEAD_%s",
1345 sha1_to_hex(commit->object.oid.hash));
1346 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1347 strbuf_reset(&buf);
1348 if (fast_forward != FF_ONLY &&
1349 merge_remote_util(commit) &&
1350 merge_remote_util(commit)->obj &&
1351 merge_remote_util(commit)->obj->type == OBJ_TAG)
1352 fast_forward = FF_NO;
1355 if (option_edit < 0)
1356 option_edit = default_edit_option();
1358 if (!use_strategies) {
1359 if (!remoteheads)
1360 ; /* already up-to-date */
1361 else if (!remoteheads->next)
1362 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1363 else
1364 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1367 for (i = 0; i < use_strategies_nr; i++) {
1368 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1369 fast_forward = FF_NO;
1370 if (use_strategies[i]->attr & NO_TRIVIAL)
1371 allow_trivial = 0;
1374 if (!remoteheads)
1375 ; /* already up-to-date */
1376 else if (!remoteheads->next)
1377 common = get_merge_bases(head_commit, remoteheads->item);
1378 else {
1379 struct commit_list *list = remoteheads;
1380 commit_list_insert(head_commit, &list);
1381 common = get_octopus_merge_bases(list);
1382 free(list);
1385 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.oid.hash,
1386 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1388 if (remoteheads && !common) {
1389 /* No common ancestors found. */
1390 if (!allow_unrelated_histories)
1391 die(_("refusing to merge unrelated histories"));
1392 /* otherwise, we need a real merge. */
1393 } else if (!remoteheads ||
1394 (!remoteheads->next && !common->next &&
1395 common->item == remoteheads->item)) {
1397 * If head can reach all the merge then we are up to date.
1398 * but first the most common case of merging one remote.
1400 finish_up_to_date("Already up-to-date.");
1401 goto done;
1402 } else if (fast_forward != FF_NO && !remoteheads->next &&
1403 !common->next &&
1404 !hashcmp(common->item->object.oid.hash, head_commit->object.oid.hash)) {
1405 /* Again the most common case of merging one remote. */
1406 struct strbuf msg = STRBUF_INIT;
1407 struct commit *commit;
1409 if (verbosity >= 0) {
1410 char from[GIT_SHA1_HEXSZ + 1], to[GIT_SHA1_HEXSZ + 1];
1411 find_unique_abbrev_r(from, head_commit->object.oid.hash,
1412 DEFAULT_ABBREV);
1413 find_unique_abbrev_r(to, remoteheads->item->object.oid.hash,
1414 DEFAULT_ABBREV);
1415 printf(_("Updating %s..%s\n"), from, to);
1417 strbuf_addstr(&msg, "Fast-forward");
1418 if (have_message)
1419 strbuf_addstr(&msg,
1420 " (no commit created; -m option ignored)");
1421 commit = remoteheads->item;
1422 if (!commit) {
1423 ret = 1;
1424 goto done;
1427 if (checkout_fast_forward(head_commit->object.oid.hash,
1428 commit->object.oid.hash,
1429 overwrite_ignore)) {
1430 ret = 1;
1431 goto done;
1434 finish(head_commit, remoteheads, commit->object.oid.hash, 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 != FF_ONLY) {
1450 /* See if it is really trivial. */
1451 git_committer_info(IDENT_STRICT);
1452 printf(_("Trying really trivial in-index merge...\n"));
1453 if (!read_tree_trivial(common->item->object.oid.hash,
1454 head_commit->object.oid.hash,
1455 remoteheads->item->object.oid.hash)) {
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);
1478 if (hashcmp(common_one->item->object.oid.hash,
1479 j->item->object.oid.hash)) {
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 == FF_ONLY)
1491 die(_("Not possible to fast-forward, aborting."));
1493 /* We are going to make a new commit. */
1494 git_committer_info(IDENT_STRICT);
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.oid.hash, 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.oid.hash, 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.oid.hash, 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();
1612 done:
1613 free(branch_to_free);
1614 return ret;