trace2: fix incorrect function pointer check
[git.git] / builtin / merge.c
blobe47d77baeebe888cfb67f8e03804ffc3ee3715c0
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 #define USE_THE_INDEX_COMPATIBILITY_MACROS
10 #include "cache.h"
11 #include "config.h"
12 #include "parse-options.h"
13 #include "builtin.h"
14 #include "lockfile.h"
15 #include "run-command.h"
16 #include "diff.h"
17 #include "refs.h"
18 #include "refspec.h"
19 #include "commit.h"
20 #include "diffcore.h"
21 #include "revision.h"
22 #include "unpack-trees.h"
23 #include "cache-tree.h"
24 #include "dir.h"
25 #include "utf8.h"
26 #include "log-tree.h"
27 #include "color.h"
28 #include "rerere.h"
29 #include "help.h"
30 #include "merge-recursive.h"
31 #include "resolve-undo.h"
32 #include "remote.h"
33 #include "fmt-merge-msg.h"
34 #include "gpg-interface.h"
35 #include "sequencer.h"
36 #include "string-list.h"
37 #include "packfile.h"
38 #include "tag.h"
39 #include "alias.h"
40 #include "commit-reach.h"
42 #define DEFAULT_TWOHEAD (1<<0)
43 #define DEFAULT_OCTOPUS (1<<1)
44 #define NO_FAST_FORWARD (1<<2)
45 #define NO_TRIVIAL (1<<3)
47 struct strategy {
48 const char *name;
49 unsigned attr;
52 static const char * const builtin_merge_usage[] = {
53 N_("git merge [<options>] [<commit>...]"),
54 N_("git merge --abort"),
55 N_("git merge --continue"),
56 NULL
59 static int show_diffstat = 1, shortlog_len = -1, squash;
60 static int option_commit = 1;
61 static int option_edit = -1;
62 static int allow_trivial = 1, have_message, verify_signatures;
63 static int overwrite_ignore = 1;
64 static struct strbuf merge_msg = STRBUF_INIT;
65 static struct strategy **use_strategies;
66 static size_t use_strategies_nr, use_strategies_alloc;
67 static const char **xopts;
68 static size_t xopts_nr, xopts_alloc;
69 static const char *branch;
70 static char *branch_mergeoptions;
71 static int option_renormalize;
72 static int verbosity;
73 static int allow_rerere_auto;
74 static int abort_current_merge;
75 static int continue_current_merge;
76 static int allow_unrelated_histories;
77 static int show_progress = -1;
78 static int default_to_upstream = 1;
79 static int signoff;
80 static const char *sign_commit;
81 static int verify_msg = 1;
83 static struct strategy all_strategy[] = {
84 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
85 { "octopus", DEFAULT_OCTOPUS },
86 { "resolve", 0 },
87 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
88 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
91 static const char *pull_twohead, *pull_octopus;
93 enum ff_type {
94 FF_NO,
95 FF_ALLOW,
96 FF_ONLY
99 static enum ff_type fast_forward = FF_ALLOW;
101 static int option_parse_message(const struct option *opt,
102 const char *arg, int unset)
104 struct strbuf *buf = opt->value;
106 if (unset)
107 strbuf_setlen(buf, 0);
108 else if (arg) {
109 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
110 have_message = 1;
111 } else
112 return error(_("switch `m' requires a value"));
113 return 0;
116 static int option_read_message(struct parse_opt_ctx_t *ctx,
117 const struct option *opt, int unset)
119 struct strbuf *buf = opt->value;
120 const char *arg;
122 if (unset)
123 BUG("-F cannot be negated");
125 if (ctx->opt) {
126 arg = ctx->opt;
127 ctx->opt = NULL;
128 } else if (ctx->argc > 1) {
129 ctx->argc--;
130 arg = *++ctx->argv;
131 } else
132 return error(_("option `%s' requires a value"), opt->long_name);
134 if (buf->len)
135 strbuf_addch(buf, '\n');
136 if (ctx->prefix && !is_absolute_path(arg))
137 arg = prefix_filename(ctx->prefix, arg);
138 if (strbuf_read_file(buf, arg, 0) < 0)
139 return error(_("could not read file '%s'"), arg);
140 have_message = 1;
142 return 0;
145 static struct strategy *get_strategy(const char *name)
147 int i;
148 struct strategy *ret;
149 static struct cmdnames main_cmds, other_cmds;
150 static int loaded;
152 if (!name)
153 return NULL;
155 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
156 if (!strcmp(name, all_strategy[i].name))
157 return &all_strategy[i];
159 if (!loaded) {
160 struct cmdnames not_strategies;
161 loaded = 1;
163 memset(&not_strategies, 0, sizeof(struct cmdnames));
164 load_command_list("git-merge-", &main_cmds, &other_cmds);
165 for (i = 0; i < main_cmds.cnt; i++) {
166 int j, found = 0;
167 struct cmdname *ent = main_cmds.names[i];
168 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
169 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
170 && !all_strategy[j].name[ent->len])
171 found = 1;
172 if (!found)
173 add_cmdname(&not_strategies, ent->name, ent->len);
175 exclude_cmds(&main_cmds, &not_strategies);
177 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
178 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
179 fprintf(stderr, _("Available strategies are:"));
180 for (i = 0; i < main_cmds.cnt; i++)
181 fprintf(stderr, " %s", main_cmds.names[i]->name);
182 fprintf(stderr, ".\n");
183 if (other_cmds.cnt) {
184 fprintf(stderr, _("Available custom strategies are:"));
185 for (i = 0; i < other_cmds.cnt; i++)
186 fprintf(stderr, " %s", other_cmds.names[i]->name);
187 fprintf(stderr, ".\n");
189 exit(1);
192 ret = xcalloc(1, sizeof(struct strategy));
193 ret->name = xstrdup(name);
194 ret->attr = NO_TRIVIAL;
195 return ret;
198 static void append_strategy(struct strategy *s)
200 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
201 use_strategies[use_strategies_nr++] = s;
204 static int option_parse_strategy(const struct option *opt,
205 const char *name, int unset)
207 if (unset)
208 return 0;
210 append_strategy(get_strategy(name));
211 return 0;
214 static int option_parse_x(const struct option *opt,
215 const char *arg, int unset)
217 if (unset)
218 return 0;
220 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
221 xopts[xopts_nr++] = xstrdup(arg);
222 return 0;
225 static int option_parse_n(const struct option *opt,
226 const char *arg, int unset)
228 BUG_ON_OPT_ARG(arg);
229 show_diffstat = unset;
230 return 0;
233 static struct option builtin_merge_options[] = {
234 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
235 N_("do not show a diffstat at the end of the merge"),
236 PARSE_OPT_NOARG, option_parse_n },
237 OPT_BOOL(0, "stat", &show_diffstat,
238 N_("show a diffstat at the end of the merge")),
239 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
240 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
241 N_("add (at most <n>) entries from shortlog to merge commit message"),
242 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
243 OPT_BOOL(0, "squash", &squash,
244 N_("create a single commit instead of doing a merge")),
245 OPT_BOOL(0, "commit", &option_commit,
246 N_("perform a commit if the merge succeeds (default)")),
247 OPT_BOOL('e', "edit", &option_edit,
248 N_("edit message before committing")),
249 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
250 OPT_SET_INT_F(0, "ff-only", &fast_forward,
251 N_("abort if fast-forward is not possible"),
252 FF_ONLY, PARSE_OPT_NONEG),
253 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
254 OPT_BOOL(0, "verify-signatures", &verify_signatures,
255 N_("verify that the named commit has a valid GPG signature")),
256 OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
257 N_("merge strategy to use"), option_parse_strategy),
258 OPT_CALLBACK('X', "strategy-option", &xopts, N_("option=value"),
259 N_("option for selected merge strategy"), option_parse_x),
260 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
261 N_("merge commit message (for a non-fast-forward merge)"),
262 option_parse_message),
263 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
264 N_("read message from file"), PARSE_OPT_NONEG,
265 (parse_opt_cb *) option_read_message },
266 OPT__VERBOSITY(&verbosity),
267 OPT_BOOL(0, "abort", &abort_current_merge,
268 N_("abort the current in-progress merge")),
269 OPT_BOOL(0, "continue", &continue_current_merge,
270 N_("continue the current in-progress merge")),
271 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
272 N_("allow merging unrelated histories")),
273 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
274 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
275 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
276 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
277 OPT_BOOL(0, "signoff", &signoff, N_("add Signed-off-by:")),
278 OPT_BOOL(0, "verify", &verify_msg, N_("verify commit-msg hook")),
279 OPT_END()
282 /* Cleans up metadata that is uninteresting after a succeeded merge. */
283 static void drop_save(void)
285 unlink(git_path_merge_head(the_repository));
286 unlink(git_path_merge_msg(the_repository));
287 unlink(git_path_merge_mode(the_repository));
290 static int save_state(struct object_id *stash)
292 int len;
293 struct child_process cp = CHILD_PROCESS_INIT;
294 struct strbuf buffer = STRBUF_INIT;
295 const char *argv[] = {"stash", "create", NULL};
296 int rc = -1;
298 cp.argv = argv;
299 cp.out = -1;
300 cp.git_cmd = 1;
302 if (start_command(&cp))
303 die(_("could not run stash."));
304 len = strbuf_read(&buffer, cp.out, 1024);
305 close(cp.out);
307 if (finish_command(&cp) || len < 0)
308 die(_("stash failed"));
309 else if (!len) /* no changes */
310 goto out;
311 strbuf_setlen(&buffer, buffer.len-1);
312 if (get_oid(buffer.buf, stash))
313 die(_("not a valid object: %s"), buffer.buf);
314 rc = 0;
315 out:
316 strbuf_release(&buffer);
317 return rc;
320 static void read_empty(const struct object_id *oid, int verbose)
322 int i = 0;
323 const char *args[7];
325 args[i++] = "read-tree";
326 if (verbose)
327 args[i++] = "-v";
328 args[i++] = "-m";
329 args[i++] = "-u";
330 args[i++] = empty_tree_oid_hex();
331 args[i++] = oid_to_hex(oid);
332 args[i] = NULL;
334 if (run_command_v_opt(args, RUN_GIT_CMD))
335 die(_("read-tree failed"));
338 static void reset_hard(const struct object_id *oid, int verbose)
340 int i = 0;
341 const char *args[6];
343 args[i++] = "read-tree";
344 if (verbose)
345 args[i++] = "-v";
346 args[i++] = "--reset";
347 args[i++] = "-u";
348 args[i++] = oid_to_hex(oid);
349 args[i] = NULL;
351 if (run_command_v_opt(args, RUN_GIT_CMD))
352 die(_("read-tree failed"));
355 static void restore_state(const struct object_id *head,
356 const struct object_id *stash)
358 struct strbuf sb = STRBUF_INIT;
359 const char *args[] = { "stash", "apply", NULL, NULL };
361 if (is_null_oid(stash))
362 return;
364 reset_hard(head, 1);
366 args[2] = oid_to_hex(stash);
369 * It is OK to ignore error here, for example when there was
370 * nothing to restore.
372 run_command_v_opt(args, RUN_GIT_CMD);
374 strbuf_release(&sb);
375 refresh_cache(REFRESH_QUIET);
378 /* This is called when no merge was necessary. */
379 static void finish_up_to_date(const char *msg)
381 if (verbosity >= 0)
382 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
383 drop_save();
386 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
388 struct rev_info rev;
389 struct strbuf out = STRBUF_INIT;
390 struct commit_list *j;
391 struct pretty_print_context ctx = {0};
393 printf(_("Squash commit -- not updating HEAD\n"));
395 repo_init_revisions(the_repository, &rev, NULL);
396 rev.ignore_merges = 1;
397 rev.commit_format = CMIT_FMT_MEDIUM;
399 commit->object.flags |= UNINTERESTING;
400 add_pending_object(&rev, &commit->object, NULL);
402 for (j = remoteheads; j; j = j->next)
403 add_pending_object(&rev, &j->item->object, NULL);
405 setup_revisions(0, NULL, &rev, NULL);
406 if (prepare_revision_walk(&rev))
407 die(_("revision walk setup failed"));
409 ctx.abbrev = rev.abbrev;
410 ctx.date_mode = rev.date_mode;
411 ctx.fmt = rev.commit_format;
413 strbuf_addstr(&out, "Squashed commit of the following:\n");
414 while ((commit = get_revision(&rev)) != NULL) {
415 strbuf_addch(&out, '\n');
416 strbuf_addf(&out, "commit %s\n",
417 oid_to_hex(&commit->object.oid));
418 pretty_print_commit(&ctx, commit, &out);
420 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
421 strbuf_release(&out);
424 static void finish(struct commit *head_commit,
425 struct commit_list *remoteheads,
426 const struct object_id *new_head, const char *msg)
428 struct strbuf reflog_message = STRBUF_INIT;
429 const struct object_id *head = &head_commit->object.oid;
431 if (!msg)
432 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
433 else {
434 if (verbosity >= 0)
435 printf("%s\n", msg);
436 strbuf_addf(&reflog_message, "%s: %s",
437 getenv("GIT_REFLOG_ACTION"), msg);
439 if (squash) {
440 squash_message(head_commit, remoteheads);
441 } else {
442 if (verbosity >= 0 && !merge_msg.len)
443 printf(_("No merge message -- not updating HEAD\n"));
444 else {
445 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
446 update_ref(reflog_message.buf, "HEAD", new_head, head,
447 0, UPDATE_REFS_DIE_ON_ERR);
449 * We ignore errors in 'gc --auto', since the
450 * user should see them.
452 close_all_packs(the_repository->objects);
453 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
456 if (new_head && show_diffstat) {
457 struct diff_options opts;
458 repo_diff_setup(the_repository, &opts);
459 opts.stat_width = -1; /* use full terminal width */
460 opts.stat_graph_width = -1; /* respect statGraphWidth config */
461 opts.output_format |=
462 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
463 opts.detect_rename = DIFF_DETECT_RENAME;
464 diff_setup_done(&opts);
465 diff_tree_oid(head, new_head, "", &opts);
466 diffcore_std(&opts);
467 diff_flush(&opts);
470 /* Run a post-merge hook */
471 run_hook_le(NULL, "post-merge", squash ? "1" : "0", NULL);
473 strbuf_release(&reflog_message);
476 /* Get the name for the merge commit's message. */
477 static void merge_name(const char *remote, struct strbuf *msg)
479 struct commit *remote_head;
480 struct object_id branch_head;
481 struct strbuf buf = STRBUF_INIT;
482 struct strbuf bname = STRBUF_INIT;
483 struct merge_remote_desc *desc;
484 const char *ptr;
485 char *found_ref;
486 int len, early;
488 strbuf_branchname(&bname, remote, 0);
489 remote = bname.buf;
491 oidclr(&branch_head);
492 remote_head = get_merge_parent(remote);
493 if (!remote_head)
494 die(_("'%s' does not point to a commit"), remote);
496 if (dwim_ref(remote, strlen(remote), &branch_head, &found_ref) > 0) {
497 if (starts_with(found_ref, "refs/heads/")) {
498 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
499 oid_to_hex(&branch_head), remote);
500 goto cleanup;
502 if (starts_with(found_ref, "refs/tags/")) {
503 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
504 oid_to_hex(&branch_head), remote);
505 goto cleanup;
507 if (starts_with(found_ref, "refs/remotes/")) {
508 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
509 oid_to_hex(&branch_head), remote);
510 goto cleanup;
514 /* See if remote matches <name>^^^.. or <name>~<number> */
515 for (len = 0, ptr = remote + strlen(remote);
516 remote < ptr && ptr[-1] == '^';
517 ptr--)
518 len++;
519 if (len)
520 early = 1;
521 else {
522 early = 0;
523 ptr = strrchr(remote, '~');
524 if (ptr) {
525 int seen_nonzero = 0;
527 len++; /* count ~ */
528 while (*++ptr && isdigit(*ptr)) {
529 seen_nonzero |= (*ptr != '0');
530 len++;
532 if (*ptr)
533 len = 0; /* not ...~<number> */
534 else if (seen_nonzero)
535 early = 1;
536 else if (len == 1)
537 early = 1; /* "name~" is "name~1"! */
540 if (len) {
541 struct strbuf truname = STRBUF_INIT;
542 strbuf_addf(&truname, "refs/heads/%s", remote);
543 strbuf_setlen(&truname, truname.len - len);
544 if (ref_exists(truname.buf)) {
545 strbuf_addf(msg,
546 "%s\t\tbranch '%s'%s of .\n",
547 oid_to_hex(&remote_head->object.oid),
548 truname.buf + 11,
549 (early ? " (early part)" : ""));
550 strbuf_release(&truname);
551 goto cleanup;
553 strbuf_release(&truname);
556 desc = merge_remote_util(remote_head);
557 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
558 strbuf_addf(msg, "%s\t\t%s '%s'\n",
559 oid_to_hex(&desc->obj->oid),
560 type_name(desc->obj->type),
561 remote);
562 goto cleanup;
565 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
566 oid_to_hex(&remote_head->object.oid), remote);
567 cleanup:
568 strbuf_release(&buf);
569 strbuf_release(&bname);
572 static void parse_branch_merge_options(char *bmo)
574 const char **argv;
575 int argc;
577 if (!bmo)
578 return;
579 argc = split_cmdline(bmo, &argv);
580 if (argc < 0)
581 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
582 _(split_cmdline_strerror(argc)));
583 REALLOC_ARRAY(argv, argc + 2);
584 MOVE_ARRAY(argv + 1, argv, argc + 1);
585 argc++;
586 argv[0] = "branch.*.mergeoptions";
587 parse_options(argc, argv, NULL, builtin_merge_options,
588 builtin_merge_usage, 0);
589 free(argv);
592 static int git_merge_config(const char *k, const char *v, void *cb)
594 int status;
596 if (branch && starts_with(k, "branch.") &&
597 starts_with(k + 7, branch) &&
598 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
599 free(branch_mergeoptions);
600 branch_mergeoptions = xstrdup(v);
601 return 0;
604 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
605 show_diffstat = git_config_bool(k, v);
606 else if (!strcmp(k, "merge.verifysignatures"))
607 verify_signatures = git_config_bool(k, v);
608 else if (!strcmp(k, "pull.twohead"))
609 return git_config_string(&pull_twohead, k, v);
610 else if (!strcmp(k, "pull.octopus"))
611 return git_config_string(&pull_octopus, k, v);
612 else if (!strcmp(k, "merge.renormalize"))
613 option_renormalize = git_config_bool(k, v);
614 else if (!strcmp(k, "merge.ff")) {
615 int boolval = git_parse_maybe_bool(v);
616 if (0 <= boolval) {
617 fast_forward = boolval ? FF_ALLOW : FF_NO;
618 } else if (v && !strcmp(v, "only")) {
619 fast_forward = FF_ONLY;
620 } /* do not barf on values from future versions of git */
621 return 0;
622 } else if (!strcmp(k, "merge.defaulttoupstream")) {
623 default_to_upstream = git_config_bool(k, v);
624 return 0;
625 } else if (!strcmp(k, "commit.gpgsign")) {
626 sign_commit = git_config_bool(k, v) ? "" : NULL;
627 return 0;
630 status = fmt_merge_msg_config(k, v, cb);
631 if (status)
632 return status;
633 status = git_gpg_config(k, v, NULL);
634 if (status)
635 return status;
636 return git_diff_ui_config(k, v, cb);
639 static int read_tree_trivial(struct object_id *common, struct object_id *head,
640 struct object_id *one)
642 int i, nr_trees = 0;
643 struct tree *trees[MAX_UNPACK_TREES];
644 struct tree_desc t[MAX_UNPACK_TREES];
645 struct unpack_trees_options opts;
647 memset(&opts, 0, sizeof(opts));
648 opts.head_idx = 2;
649 opts.src_index = &the_index;
650 opts.dst_index = &the_index;
651 opts.update = 1;
652 opts.verbose_update = 1;
653 opts.trivial_merges_only = 1;
654 opts.merge = 1;
655 trees[nr_trees] = parse_tree_indirect(common);
656 if (!trees[nr_trees++])
657 return -1;
658 trees[nr_trees] = parse_tree_indirect(head);
659 if (!trees[nr_trees++])
660 return -1;
661 trees[nr_trees] = parse_tree_indirect(one);
662 if (!trees[nr_trees++])
663 return -1;
664 opts.fn = threeway_merge;
665 cache_tree_free(&active_cache_tree);
666 for (i = 0; i < nr_trees; i++) {
667 parse_tree(trees[i]);
668 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
670 if (unpack_trees(nr_trees, t, &opts))
671 return -1;
672 return 0;
675 static void write_tree_trivial(struct object_id *oid)
677 if (write_cache_as_tree(oid, 0, NULL))
678 die(_("git write-tree failed to write a tree"));
681 static int try_merge_strategy(const char *strategy, struct commit_list *common,
682 struct commit_list *remoteheads,
683 struct commit *head)
685 struct lock_file lock = LOCK_INIT;
686 const char *head_arg = "HEAD";
688 hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
689 refresh_cache(REFRESH_QUIET);
690 if (write_locked_index(&the_index, &lock,
691 COMMIT_LOCK | SKIP_IF_UNCHANGED))
692 return error(_("Unable to write index."));
694 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
695 int clean, x;
696 struct commit *result;
697 struct commit_list *reversed = NULL;
698 struct merge_options o;
699 struct commit_list *j;
701 if (remoteheads->next) {
702 error(_("Not handling anything other than two heads merge."));
703 return 2;
706 init_merge_options(&o, the_repository);
707 if (!strcmp(strategy, "subtree"))
708 o.subtree_shift = "";
710 o.renormalize = option_renormalize;
711 o.show_rename_progress =
712 show_progress == -1 ? isatty(2) : show_progress;
714 for (x = 0; x < xopts_nr; x++)
715 if (parse_merge_opt(&o, xopts[x]))
716 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
718 o.branch1 = head_arg;
719 o.branch2 = merge_remote_util(remoteheads->item)->name;
721 for (j = common; j; j = j->next)
722 commit_list_insert(j->item, &reversed);
724 hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
725 clean = merge_recursive(&o, head,
726 remoteheads->item, reversed, &result);
727 if (clean < 0)
728 exit(128);
729 if (write_locked_index(&the_index, &lock,
730 COMMIT_LOCK | SKIP_IF_UNCHANGED))
731 die(_("unable to write %s"), get_index_file());
732 return clean ? 0 : 1;
733 } else {
734 return try_merge_command(the_repository,
735 strategy, xopts_nr, xopts,
736 common, head_arg, remoteheads);
740 static void count_diff_files(struct diff_queue_struct *q,
741 struct diff_options *opt, void *data)
743 int *count = data;
745 (*count) += q->nr;
748 static int count_unmerged_entries(void)
750 int i, ret = 0;
752 for (i = 0; i < active_nr; i++)
753 if (ce_stage(active_cache[i]))
754 ret++;
756 return ret;
759 static void add_strategies(const char *string, unsigned attr)
761 int i;
763 if (string) {
764 struct string_list list = STRING_LIST_INIT_DUP;
765 struct string_list_item *item;
766 string_list_split(&list, string, ' ', -1);
767 for_each_string_list_item(item, &list)
768 append_strategy(get_strategy(item->string));
769 string_list_clear(&list, 0);
770 return;
772 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
773 if (all_strategy[i].attr & attr)
774 append_strategy(&all_strategy[i]);
778 static void read_merge_msg(struct strbuf *msg)
780 const char *filename = git_path_merge_msg(the_repository);
781 strbuf_reset(msg);
782 if (strbuf_read_file(msg, filename, 0) < 0)
783 die_errno(_("Could not read from '%s'"), filename);
786 static void write_merge_state(struct commit_list *);
787 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
789 if (err_msg)
790 error("%s", err_msg);
791 fprintf(stderr,
792 _("Not committing merge; use 'git commit' to complete the merge.\n"));
793 write_merge_state(remoteheads);
794 exit(1);
797 static const char merge_editor_comment[] =
798 N_("Please enter a commit message to explain why this merge is necessary,\n"
799 "especially if it merges an updated upstream into a topic branch.\n"
800 "\n"
801 "Lines starting with '%c' will be ignored, and an empty message aborts\n"
802 "the commit.\n");
804 static void write_merge_heads(struct commit_list *);
805 static void prepare_to_commit(struct commit_list *remoteheads)
807 struct strbuf msg = STRBUF_INIT;
808 strbuf_addbuf(&msg, &merge_msg);
809 strbuf_addch(&msg, '\n');
810 if (squash)
811 BUG("the control must not reach here under --squash");
812 if (0 < option_edit)
813 strbuf_commented_addf(&msg, _(merge_editor_comment), comment_line_char);
814 if (signoff)
815 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
816 write_merge_heads(remoteheads);
817 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
818 if (run_commit_hook(0 < option_edit, get_index_file(), "prepare-commit-msg",
819 git_path_merge_msg(the_repository), "merge", NULL))
820 abort_commit(remoteheads, NULL);
821 if (0 < option_edit) {
822 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
823 abort_commit(remoteheads, NULL);
826 if (verify_msg && run_commit_hook(0 < option_edit, get_index_file(),
827 "commit-msg",
828 git_path_merge_msg(the_repository), NULL))
829 abort_commit(remoteheads, NULL);
831 read_merge_msg(&msg);
832 strbuf_stripspace(&msg, 0 < option_edit);
833 if (!msg.len)
834 abort_commit(remoteheads, _("Empty commit message."));
835 strbuf_release(&merge_msg);
836 strbuf_addbuf(&merge_msg, &msg);
837 strbuf_release(&msg);
840 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
842 struct object_id result_tree, result_commit;
843 struct commit_list *parents, **pptr = &parents;
844 struct lock_file lock = LOCK_INIT;
846 hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
847 refresh_cache(REFRESH_QUIET);
848 if (write_locked_index(&the_index, &lock,
849 COMMIT_LOCK | SKIP_IF_UNCHANGED))
850 return error(_("Unable to write index."));
852 write_tree_trivial(&result_tree);
853 printf(_("Wonderful.\n"));
854 pptr = commit_list_append(head, pptr);
855 pptr = commit_list_append(remoteheads->item, pptr);
856 prepare_to_commit(remoteheads);
857 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
858 &result_commit, NULL, sign_commit))
859 die(_("failed to write commit object"));
860 finish(head, remoteheads, &result_commit, "In-index merge");
861 drop_save();
862 return 0;
865 static int finish_automerge(struct commit *head,
866 int head_subsumed,
867 struct commit_list *common,
868 struct commit_list *remoteheads,
869 struct object_id *result_tree,
870 const char *wt_strategy)
872 struct commit_list *parents = NULL;
873 struct strbuf buf = STRBUF_INIT;
874 struct object_id result_commit;
876 free_commit_list(common);
877 parents = remoteheads;
878 if (!head_subsumed || fast_forward == FF_NO)
879 commit_list_insert(head, &parents);
880 strbuf_addch(&merge_msg, '\n');
881 prepare_to_commit(remoteheads);
882 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
883 &result_commit, NULL, sign_commit))
884 die(_("failed to write commit object"));
885 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
886 finish(head, remoteheads, &result_commit, buf.buf);
887 strbuf_release(&buf);
888 drop_save();
889 return 0;
892 static int suggest_conflicts(void)
894 const char *filename;
895 FILE *fp;
896 struct strbuf msgbuf = STRBUF_INIT;
898 filename = git_path_merge_msg(the_repository);
899 fp = xfopen(filename, "a");
901 append_conflicts_hint(&the_index, &msgbuf);
902 fputs(msgbuf.buf, fp);
903 strbuf_release(&msgbuf);
904 fclose(fp);
905 repo_rerere(the_repository, allow_rerere_auto);
906 printf(_("Automatic merge failed; "
907 "fix conflicts and then commit the result.\n"));
908 return 1;
911 static int evaluate_result(void)
913 int cnt = 0;
914 struct rev_info rev;
916 /* Check how many files differ. */
917 repo_init_revisions(the_repository, &rev, "");
918 setup_revisions(0, NULL, &rev, NULL);
919 rev.diffopt.output_format |=
920 DIFF_FORMAT_CALLBACK;
921 rev.diffopt.format_callback = count_diff_files;
922 rev.diffopt.format_callback_data = &cnt;
923 run_diff_files(&rev, 0);
926 * Check how many unmerged entries are
927 * there.
929 cnt += count_unmerged_entries();
931 return cnt;
935 * Pretend as if the user told us to merge with the remote-tracking
936 * branch we have for the upstream of the current branch
938 static int setup_with_upstream(const char ***argv)
940 struct branch *branch = branch_get(NULL);
941 int i;
942 const char **args;
944 if (!branch)
945 die(_("No current branch."));
946 if (!branch->remote_name)
947 die(_("No remote for the current branch."));
948 if (!branch->merge_nr)
949 die(_("No default upstream defined for the current branch."));
951 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
952 for (i = 0; i < branch->merge_nr; i++) {
953 if (!branch->merge[i]->dst)
954 die(_("No remote-tracking branch for %s from %s"),
955 branch->merge[i]->src, branch->remote_name);
956 args[i] = branch->merge[i]->dst;
958 args[i] = NULL;
959 *argv = args;
960 return i;
963 static void write_merge_heads(struct commit_list *remoteheads)
965 struct commit_list *j;
966 struct strbuf buf = STRBUF_INIT;
968 for (j = remoteheads; j; j = j->next) {
969 struct object_id *oid;
970 struct commit *c = j->item;
971 struct merge_remote_desc *desc;
973 desc = merge_remote_util(c);
974 if (desc && desc->obj) {
975 oid = &desc->obj->oid;
976 } else {
977 oid = &c->object.oid;
979 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
981 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
983 strbuf_reset(&buf);
984 if (fast_forward == FF_NO)
985 strbuf_addstr(&buf, "no-ff");
986 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
987 strbuf_release(&buf);
990 static void write_merge_state(struct commit_list *remoteheads)
992 write_merge_heads(remoteheads);
993 strbuf_addch(&merge_msg, '\n');
994 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
995 merge_msg.len);
998 static int default_edit_option(void)
1000 static const char name[] = "GIT_MERGE_AUTOEDIT";
1001 const char *e = getenv(name);
1002 struct stat st_stdin, st_stdout;
1004 if (have_message)
1005 /* an explicit -m msg without --[no-]edit */
1006 return 0;
1008 if (e) {
1009 int v = git_parse_maybe_bool(e);
1010 if (v < 0)
1011 die(_("Bad value '%s' in environment '%s'"), e, name);
1012 return v;
1015 /* Use editor if stdin and stdout are the same and is a tty */
1016 return (!fstat(0, &st_stdin) &&
1017 !fstat(1, &st_stdout) &&
1018 isatty(0) && isatty(1) &&
1019 st_stdin.st_dev == st_stdout.st_dev &&
1020 st_stdin.st_ino == st_stdout.st_ino &&
1021 st_stdin.st_mode == st_stdout.st_mode);
1024 static struct commit_list *reduce_parents(struct commit *head_commit,
1025 int *head_subsumed,
1026 struct commit_list *remoteheads)
1028 struct commit_list *parents, **remotes;
1031 * Is the current HEAD reachable from another commit being
1032 * merged? If so we do not want to record it as a parent of
1033 * the resulting merge, unless --no-ff is given. We will flip
1034 * this variable to 0 when we find HEAD among the independent
1035 * tips being merged.
1037 *head_subsumed = 1;
1039 /* Find what parents to record by checking independent ones. */
1040 parents = reduce_heads(remoteheads);
1041 free_commit_list(remoteheads);
1043 remoteheads = NULL;
1044 remotes = &remoteheads;
1045 while (parents) {
1046 struct commit *commit = pop_commit(&parents);
1047 if (commit == head_commit)
1048 *head_subsumed = 0;
1049 else
1050 remotes = &commit_list_insert(commit, remotes)->next;
1052 return remoteheads;
1055 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1057 struct fmt_merge_msg_opts opts;
1059 memset(&opts, 0, sizeof(opts));
1060 opts.add_title = !have_message;
1061 opts.shortlog_len = shortlog_len;
1062 opts.credit_people = (0 < option_edit);
1064 fmt_merge_msg(merge_names, merge_msg, &opts);
1065 if (merge_msg->len)
1066 strbuf_setlen(merge_msg, merge_msg->len - 1);
1069 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1071 const char *filename;
1072 int fd, pos, npos;
1073 struct strbuf fetch_head_file = STRBUF_INIT;
1074 const unsigned hexsz = the_hash_algo->hexsz;
1076 if (!merge_names)
1077 merge_names = &fetch_head_file;
1079 filename = git_path_fetch_head(the_repository);
1080 fd = open(filename, O_RDONLY);
1081 if (fd < 0)
1082 die_errno(_("could not open '%s' for reading"), filename);
1084 if (strbuf_read(merge_names, fd, 0) < 0)
1085 die_errno(_("could not read '%s'"), filename);
1086 if (close(fd) < 0)
1087 die_errno(_("could not close '%s'"), filename);
1089 for (pos = 0; pos < merge_names->len; pos = npos) {
1090 struct object_id oid;
1091 char *ptr;
1092 struct commit *commit;
1094 ptr = strchr(merge_names->buf + pos, '\n');
1095 if (ptr)
1096 npos = ptr - merge_names->buf + 1;
1097 else
1098 npos = merge_names->len;
1100 if (npos - pos < hexsz + 2 ||
1101 get_oid_hex(merge_names->buf + pos, &oid))
1102 commit = NULL; /* bad */
1103 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1104 continue; /* not-for-merge */
1105 else {
1106 char saved = merge_names->buf[pos + hexsz];
1107 merge_names->buf[pos + hexsz] = '\0';
1108 commit = get_merge_parent(merge_names->buf + pos);
1109 merge_names->buf[pos + hexsz] = saved;
1111 if (!commit) {
1112 if (ptr)
1113 *ptr = '\0';
1114 die(_("not something we can merge in %s: %s"),
1115 filename, merge_names->buf + pos);
1117 remotes = &commit_list_insert(commit, remotes)->next;
1120 if (merge_names == &fetch_head_file)
1121 strbuf_release(&fetch_head_file);
1124 static struct commit_list *collect_parents(struct commit *head_commit,
1125 int *head_subsumed,
1126 int argc, const char **argv,
1127 struct strbuf *merge_msg)
1129 int i;
1130 struct commit_list *remoteheads = NULL;
1131 struct commit_list **remotes = &remoteheads;
1132 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1134 if (merge_msg && (!have_message || shortlog_len))
1135 autogen = &merge_names;
1137 if (head_commit)
1138 remotes = &commit_list_insert(head_commit, remotes)->next;
1140 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1141 handle_fetch_head(remotes, autogen);
1142 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1143 } else {
1144 for (i = 0; i < argc; i++) {
1145 struct commit *commit = get_merge_parent(argv[i]);
1146 if (!commit)
1147 help_unknown_ref(argv[i], "merge",
1148 _("not something we can merge"));
1149 remotes = &commit_list_insert(commit, remotes)->next;
1151 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1152 if (autogen) {
1153 struct commit_list *p;
1154 for (p = remoteheads; p; p = p->next)
1155 merge_name(merge_remote_util(p->item)->name, autogen);
1159 if (autogen) {
1160 prepare_merge_message(autogen, merge_msg);
1161 strbuf_release(autogen);
1164 return remoteheads;
1167 static int merging_a_throwaway_tag(struct commit *commit)
1169 char *tag_ref;
1170 struct object_id oid;
1171 int is_throwaway_tag = 0;
1173 /* Are we merging a tag? */
1174 if (!merge_remote_util(commit) ||
1175 !merge_remote_util(commit)->obj ||
1176 merge_remote_util(commit)->obj->type != OBJ_TAG)
1177 return is_throwaway_tag;
1180 * Now we know we are merging a tag object. Are we downstream
1181 * and following the tags from upstream? If so, we must have
1182 * the tag object pointed at by "refs/tags/$T" where $T is the
1183 * tagname recorded in the tag object. We want to allow such
1184 * a "just to catch up" merge to fast-forward.
1186 * Otherwise, we are playing an integrator's role, making a
1187 * merge with a throw-away tag from a contributor with
1188 * something like "git pull $contributor $signed_tag".
1189 * We want to forbid such a merge from fast-forwarding
1190 * by default; otherwise we would not keep the signature
1191 * anywhere.
1193 tag_ref = xstrfmt("refs/tags/%s",
1194 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1195 if (!read_ref(tag_ref, &oid) &&
1196 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1197 is_throwaway_tag = 0;
1198 else
1199 is_throwaway_tag = 1;
1200 free(tag_ref);
1201 return is_throwaway_tag;
1204 int cmd_merge(int argc, const char **argv, const char *prefix)
1206 struct object_id result_tree, stash, head_oid;
1207 struct commit *head_commit;
1208 struct strbuf buf = STRBUF_INIT;
1209 int i, ret = 0, head_subsumed;
1210 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1211 struct commit_list *common = NULL;
1212 const char *best_strategy = NULL, *wt_strategy = NULL;
1213 struct commit_list *remoteheads, *p;
1214 void *branch_to_free;
1215 int orig_argc = argc;
1217 if (argc == 2 && !strcmp(argv[1], "-h"))
1218 usage_with_options(builtin_merge_usage, builtin_merge_options);
1221 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1222 * current branch.
1224 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1225 if (branch)
1226 skip_prefix(branch, "refs/heads/", &branch);
1228 init_diff_ui_defaults();
1229 git_config(git_merge_config, NULL);
1231 if (!branch || is_null_oid(&head_oid))
1232 head_commit = NULL;
1233 else
1234 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1236 if (branch_mergeoptions)
1237 parse_branch_merge_options(branch_mergeoptions);
1238 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1239 builtin_merge_usage, 0);
1240 if (shortlog_len < 0)
1241 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1243 if (verbosity < 0 && show_progress == -1)
1244 show_progress = 0;
1246 if (abort_current_merge) {
1247 int nargc = 2;
1248 const char *nargv[] = {"reset", "--merge", NULL};
1250 if (orig_argc != 2)
1251 usage_msg_opt(_("--abort expects no arguments"),
1252 builtin_merge_usage, builtin_merge_options);
1254 if (!file_exists(git_path_merge_head(the_repository)))
1255 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1257 /* Invoke 'git reset --merge' */
1258 ret = cmd_reset(nargc, nargv, prefix);
1259 goto done;
1262 if (continue_current_merge) {
1263 int nargc = 1;
1264 const char *nargv[] = {"commit", NULL};
1266 if (orig_argc != 2)
1267 usage_msg_opt(_("--continue expects no arguments"),
1268 builtin_merge_usage, builtin_merge_options);
1270 if (!file_exists(git_path_merge_head(the_repository)))
1271 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1273 /* Invoke 'git commit' */
1274 ret = cmd_commit(nargc, nargv, prefix);
1275 goto done;
1278 if (read_cache_unmerged())
1279 die_resolve_conflict("merge");
1281 if (file_exists(git_path_merge_head(the_repository))) {
1283 * There is no unmerged entry, don't advise 'git
1284 * add/rm <file>', just 'git commit'.
1286 if (advice_resolve_conflict)
1287 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1288 "Please, commit your changes before you merge."));
1289 else
1290 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1292 if (file_exists(git_path_cherry_pick_head(the_repository))) {
1293 if (advice_resolve_conflict)
1294 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1295 "Please, commit your changes before you merge."));
1296 else
1297 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1299 resolve_undo_clear();
1301 if (verbosity < 0)
1302 show_diffstat = 0;
1304 if (squash) {
1305 if (fast_forward == FF_NO)
1306 die(_("You cannot combine --squash with --no-ff."));
1307 option_commit = 0;
1310 if (!argc) {
1311 if (default_to_upstream)
1312 argc = setup_with_upstream(&argv);
1313 else
1314 die(_("No commit specified and merge.defaultToUpstream not set."));
1315 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1316 argv[0] = "@{-1}";
1319 if (!argc)
1320 usage_with_options(builtin_merge_usage,
1321 builtin_merge_options);
1323 if (!head_commit) {
1325 * If the merged head is a valid one there is no reason
1326 * to forbid "git merge" into a branch yet to be born.
1327 * We do the same for "git pull".
1329 struct object_id *remote_head_oid;
1330 if (squash)
1331 die(_("Squash commit into empty head not supported yet"));
1332 if (fast_forward == FF_NO)
1333 die(_("Non-fast-forward commit does not make sense into "
1334 "an empty head"));
1335 remoteheads = collect_parents(head_commit, &head_subsumed,
1336 argc, argv, NULL);
1337 if (!remoteheads)
1338 die(_("%s - not something we can merge"), argv[0]);
1339 if (remoteheads->next)
1340 die(_("Can merge only exactly one commit into empty head"));
1342 if (verify_signatures)
1343 verify_merge_signature(remoteheads->item, verbosity);
1345 remote_head_oid = &remoteheads->item->object.oid;
1346 read_empty(remote_head_oid, 0);
1347 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1348 UPDATE_REFS_DIE_ON_ERR);
1349 goto done;
1353 * All the rest are the commits being merged; prepare
1354 * the standard merge summary message to be appended
1355 * to the given message.
1357 remoteheads = collect_parents(head_commit, &head_subsumed,
1358 argc, argv, &merge_msg);
1360 if (!head_commit || !argc)
1361 usage_with_options(builtin_merge_usage,
1362 builtin_merge_options);
1364 if (verify_signatures) {
1365 for (p = remoteheads; p; p = p->next) {
1366 verify_merge_signature(p->item, verbosity);
1370 strbuf_addstr(&buf, "merge");
1371 for (p = remoteheads; p; p = p->next)
1372 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1373 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1374 strbuf_reset(&buf);
1376 for (p = remoteheads; p; p = p->next) {
1377 struct commit *commit = p->item;
1378 strbuf_addf(&buf, "GITHEAD_%s",
1379 oid_to_hex(&commit->object.oid));
1380 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1381 strbuf_reset(&buf);
1382 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1383 fast_forward = FF_NO;
1386 if (option_edit < 0)
1387 option_edit = default_edit_option();
1389 if (!use_strategies) {
1390 if (!remoteheads)
1391 ; /* already up-to-date */
1392 else if (!remoteheads->next)
1393 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1394 else
1395 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1398 for (i = 0; i < use_strategies_nr; i++) {
1399 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1400 fast_forward = FF_NO;
1401 if (use_strategies[i]->attr & NO_TRIVIAL)
1402 allow_trivial = 0;
1405 if (!remoteheads)
1406 ; /* already up-to-date */
1407 else if (!remoteheads->next)
1408 common = get_merge_bases(head_commit, remoteheads->item);
1409 else {
1410 struct commit_list *list = remoteheads;
1411 commit_list_insert(head_commit, &list);
1412 common = get_octopus_merge_bases(list);
1413 free(list);
1416 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1417 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1419 if (remoteheads && !common) {
1420 /* No common ancestors found. */
1421 if (!allow_unrelated_histories)
1422 die(_("refusing to merge unrelated histories"));
1423 /* otherwise, we need a real merge. */
1424 } else if (!remoteheads ||
1425 (!remoteheads->next && !common->next &&
1426 common->item == remoteheads->item)) {
1428 * If head can reach all the merge then we are up to date.
1429 * but first the most common case of merging one remote.
1431 finish_up_to_date(_("Already up to date."));
1432 goto done;
1433 } else if (fast_forward != FF_NO && !remoteheads->next &&
1434 !common->next &&
1435 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1436 /* Again the most common case of merging one remote. */
1437 struct strbuf msg = STRBUF_INIT;
1438 struct commit *commit;
1440 if (verbosity >= 0) {
1441 printf(_("Updating %s..%s\n"),
1442 find_unique_abbrev(&head_commit->object.oid,
1443 DEFAULT_ABBREV),
1444 find_unique_abbrev(&remoteheads->item->object.oid,
1445 DEFAULT_ABBREV));
1447 strbuf_addstr(&msg, "Fast-forward");
1448 if (have_message)
1449 strbuf_addstr(&msg,
1450 " (no commit created; -m option ignored)");
1451 commit = remoteheads->item;
1452 if (!commit) {
1453 ret = 1;
1454 goto done;
1457 if (checkout_fast_forward(the_repository,
1458 &head_commit->object.oid,
1459 &commit->object.oid,
1460 overwrite_ignore)) {
1461 ret = 1;
1462 goto done;
1465 finish(head_commit, remoteheads, &commit->object.oid, msg.buf);
1466 drop_save();
1467 goto done;
1468 } else if (!remoteheads->next && common->next)
1471 * We are not doing octopus and not fast-forward. Need
1472 * a real merge.
1474 else if (!remoteheads->next && !common->next && option_commit) {
1476 * We are not doing octopus, not fast-forward, and have
1477 * only one common.
1479 refresh_cache(REFRESH_QUIET);
1480 if (allow_trivial && fast_forward != FF_ONLY) {
1481 /* See if it is really trivial. */
1482 git_committer_info(IDENT_STRICT);
1483 printf(_("Trying really trivial in-index merge...\n"));
1484 if (!read_tree_trivial(&common->item->object.oid,
1485 &head_commit->object.oid,
1486 &remoteheads->item->object.oid)) {
1487 ret = merge_trivial(head_commit, remoteheads);
1488 goto done;
1490 printf(_("Nope.\n"));
1492 } else {
1494 * An octopus. If we can reach all the remote we are up
1495 * to date.
1497 int up_to_date = 1;
1498 struct commit_list *j;
1500 for (j = remoteheads; j; j = j->next) {
1501 struct commit_list *common_one;
1504 * Here we *have* to calculate the individual
1505 * merge_bases again, otherwise "git merge HEAD^
1506 * HEAD^^" would be missed.
1508 common_one = get_merge_bases(head_commit, j->item);
1509 if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1510 up_to_date = 0;
1511 break;
1514 if (up_to_date) {
1515 finish_up_to_date(_("Already up to date. Yeeah!"));
1516 goto done;
1520 if (fast_forward == FF_ONLY)
1521 die(_("Not possible to fast-forward, aborting."));
1523 /* We are going to make a new commit. */
1524 git_committer_info(IDENT_STRICT);
1527 * At this point, we need a real merge. No matter what strategy
1528 * we use, it would operate on the index, possibly affecting the
1529 * working tree, and when resolved cleanly, have the desired
1530 * tree in the index -- this means that the index must be in
1531 * sync with the head commit. The strategies are responsible
1532 * to ensure this.
1534 if (use_strategies_nr == 1 ||
1536 * Stash away the local changes so that we can try more than one.
1538 save_state(&stash))
1539 oidclr(&stash);
1541 for (i = 0; i < use_strategies_nr; i++) {
1542 int ret;
1543 if (i) {
1544 printf(_("Rewinding the tree to pristine...\n"));
1545 restore_state(&head_commit->object.oid, &stash);
1547 if (use_strategies_nr != 1)
1548 printf(_("Trying merge strategy %s...\n"),
1549 use_strategies[i]->name);
1551 * Remember which strategy left the state in the working
1552 * tree.
1554 wt_strategy = use_strategies[i]->name;
1556 ret = try_merge_strategy(use_strategies[i]->name,
1557 common, remoteheads,
1558 head_commit);
1559 if (!option_commit && !ret) {
1560 merge_was_ok = 1;
1562 * This is necessary here just to avoid writing
1563 * the tree, but later we will *not* exit with
1564 * status code 1 because merge_was_ok is set.
1566 ret = 1;
1569 if (ret) {
1571 * The backend exits with 1 when conflicts are
1572 * left to be resolved, with 2 when it does not
1573 * handle the given merge at all.
1575 if (ret == 1) {
1576 int cnt = evaluate_result();
1578 if (best_cnt <= 0 || cnt <= best_cnt) {
1579 best_strategy = use_strategies[i]->name;
1580 best_cnt = cnt;
1583 if (merge_was_ok)
1584 break;
1585 else
1586 continue;
1589 /* Automerge succeeded. */
1590 write_tree_trivial(&result_tree);
1591 automerge_was_ok = 1;
1592 break;
1596 * If we have a resulting tree, that means the strategy module
1597 * auto resolved the merge cleanly.
1599 if (automerge_was_ok) {
1600 ret = finish_automerge(head_commit, head_subsumed,
1601 common, remoteheads,
1602 &result_tree, wt_strategy);
1603 goto done;
1607 * Pick the result from the best strategy and have the user fix
1608 * it up.
1610 if (!best_strategy) {
1611 restore_state(&head_commit->object.oid, &stash);
1612 if (use_strategies_nr > 1)
1613 fprintf(stderr,
1614 _("No merge strategy handled the merge.\n"));
1615 else
1616 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1617 use_strategies[0]->name);
1618 ret = 2;
1619 goto done;
1620 } else if (best_strategy == wt_strategy)
1621 ; /* We already have its result in the working tree. */
1622 else {
1623 printf(_("Rewinding the tree to pristine...\n"));
1624 restore_state(&head_commit->object.oid, &stash);
1625 printf(_("Using the %s to prepare resolving by hand.\n"),
1626 best_strategy);
1627 try_merge_strategy(best_strategy, common, remoteheads,
1628 head_commit);
1631 if (squash)
1632 finish(head_commit, remoteheads, NULL, NULL);
1633 else
1634 write_merge_state(remoteheads);
1636 if (merge_was_ok)
1637 fprintf(stderr, _("Automatic merge went well; "
1638 "stopped before committing as requested\n"));
1639 else
1640 ret = suggest_conflicts();
1642 done:
1643 free(branch_to_free);
1644 return ret;