t/unit-tests: fix typos
[git/gitster.git] / builtin / merge.c
blob84d0f3604bc36c77f98a68377d1f078b7d241824
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 */
8 #define USE_THE_REPOSITORY_VARIABLE
9 #include "builtin.h"
11 #include "abspath.h"
12 #include "advice.h"
13 #include "config.h"
14 #include "editor.h"
15 #include "environment.h"
16 #include "gettext.h"
17 #include "hex.h"
18 #include "object-name.h"
19 #include "parse-options.h"
20 #include "lockfile.h"
21 #include "repository.h"
22 #include "run-command.h"
23 #include "hook.h"
24 #include "diff.h"
25 #include "diff-merges.h"
26 #include "refs.h"
27 #include "refspec.h"
28 #include "commit.h"
29 #include "diffcore.h"
30 #include "path.h"
31 #include "revision.h"
32 #include "unpack-trees.h"
33 #include "cache-tree.h"
34 #include "dir.h"
35 #include "color.h"
36 #include "rerere.h"
37 #include "help.h"
38 #include "merge.h"
39 #include "merge-recursive.h"
40 #include "merge-ort-wrappers.h"
41 #include "resolve-undo.h"
42 #include "remote.h"
43 #include "fmt-merge-msg.h"
44 #include "sequencer.h"
45 #include "string-list.h"
46 #include "tag.h"
47 #include "alias.h"
48 #include "branch.h"
49 #include "commit-reach.h"
50 #include "wt-status.h"
51 #include "commit-graph.h"
53 #define DEFAULT_TWOHEAD (1<<0)
54 #define DEFAULT_OCTOPUS (1<<1)
55 #define NO_FAST_FORWARD (1<<2)
56 #define NO_TRIVIAL (1<<3)
58 struct strategy {
59 const char *name;
60 unsigned attr;
63 static const char * const builtin_merge_usage[] = {
64 N_("git merge [<options>] [<commit>...]"),
65 "git merge --abort",
66 "git merge --continue",
67 NULL
70 static int show_diffstat = 1, shortlog_len = -1, squash;
71 static int option_commit = -1;
72 static int option_edit = -1;
73 static int allow_trivial = 1, have_message, verify_signatures;
74 static int check_trust_level = 1;
75 static int overwrite_ignore = 1;
76 static struct strbuf merge_msg = STRBUF_INIT;
77 static struct strategy **use_strategies;
78 static size_t use_strategies_nr, use_strategies_alloc;
79 static struct strvec xopts = STRVEC_INIT;
80 static const char *branch;
81 static char *branch_mergeoptions;
82 static int verbosity;
83 static int allow_rerere_auto;
84 static int abort_current_merge;
85 static int quit_current_merge;
86 static int continue_current_merge;
87 static int allow_unrelated_histories;
88 static int show_progress = -1;
89 static int default_to_upstream = 1;
90 static int signoff;
91 static const char *sign_commit;
92 static int autostash;
93 static int no_verify;
94 static char *into_name;
96 static struct strategy all_strategy[] = {
97 { "recursive", NO_TRIVIAL },
98 { "octopus", DEFAULT_OCTOPUS },
99 { "ort", DEFAULT_TWOHEAD | NO_TRIVIAL },
100 { "resolve", 0 },
101 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
102 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
105 static char *pull_twohead, *pull_octopus;
107 enum ff_type {
108 FF_NO,
109 FF_ALLOW,
110 FF_ONLY
113 static enum ff_type fast_forward = FF_ALLOW;
115 static char *cleanup_arg;
116 static enum commit_msg_cleanup_mode cleanup_mode;
118 static int option_parse_message(const struct option *opt,
119 const char *arg, int unset)
121 struct strbuf *buf = opt->value;
123 if (unset)
124 strbuf_setlen(buf, 0);
125 else if (arg) {
126 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
127 have_message = 1;
128 } else
129 return error(_("switch `m' requires a value"));
130 return 0;
133 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
134 const struct option *opt,
135 const char *arg_not_used,
136 int unset)
138 struct strbuf *buf = opt->value;
139 const char *arg;
141 BUG_ON_OPT_ARG(arg_not_used);
142 if (unset)
143 BUG("-F cannot be negated");
145 if (ctx->opt) {
146 arg = ctx->opt;
147 ctx->opt = NULL;
148 } else if (ctx->argc > 1) {
149 ctx->argc--;
150 arg = *++ctx->argv;
151 } else
152 return error(_("option `%s' requires a value"), opt->long_name);
154 if (buf->len)
155 strbuf_addch(buf, '\n');
156 if (ctx->prefix && !is_absolute_path(arg))
157 arg = prefix_filename(ctx->prefix, arg);
158 if (strbuf_read_file(buf, arg, 0) < 0)
159 return error(_("could not read file '%s'"), arg);
160 have_message = 1;
162 return 0;
165 static struct strategy *get_strategy(const char *name)
167 int i;
168 struct strategy *ret;
169 static struct cmdnames main_cmds = {0}, other_cmds = {0};
170 static int loaded;
171 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
173 if (!name)
174 return NULL;
176 if (default_strategy &&
177 !strcmp(default_strategy, "ort") &&
178 !strcmp(name, "recursive")) {
179 name = "ort";
182 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
183 if (!strcmp(name, all_strategy[i].name))
184 return &all_strategy[i];
186 if (!loaded) {
187 struct cmdnames not_strategies = {0};
188 loaded = 1;
190 load_command_list("git-merge-", &main_cmds, &other_cmds);
191 for (i = 0; i < main_cmds.cnt; i++) {
192 int j, found = 0;
193 struct cmdname *ent = main_cmds.names[i];
194 for (j = 0; !found && j < ARRAY_SIZE(all_strategy); j++)
195 if (!xstrncmpz(all_strategy[j].name, ent->name, ent->len))
196 found = 1;
197 if (!found)
198 add_cmdname(&not_strategies, ent->name, ent->len);
200 exclude_cmds(&main_cmds, &not_strategies);
202 cmdnames_release(&not_strategies);
204 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
205 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
206 fprintf(stderr, _("Available strategies are:"));
207 for (i = 0; i < main_cmds.cnt; i++)
208 fprintf(stderr, " %s", main_cmds.names[i]->name);
209 fprintf(stderr, ".\n");
210 if (other_cmds.cnt) {
211 fprintf(stderr, _("Available custom strategies are:"));
212 for (i = 0; i < other_cmds.cnt; i++)
213 fprintf(stderr, " %s", other_cmds.names[i]->name);
214 fprintf(stderr, ".\n");
216 exit(1);
219 CALLOC_ARRAY(ret, 1);
220 ret->name = xstrdup(name);
221 ret->attr = NO_TRIVIAL;
223 cmdnames_release(&main_cmds);
224 cmdnames_release(&other_cmds);
225 return ret;
228 static void append_strategy(struct strategy *s)
230 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
231 use_strategies[use_strategies_nr++] = s;
234 static int option_parse_strategy(const struct option *opt UNUSED,
235 const char *name, int unset)
237 if (unset)
238 return 0;
240 append_strategy(get_strategy(name));
241 return 0;
244 static struct option builtin_merge_options[] = {
245 OPT_SET_INT('n', NULL, &show_diffstat,
246 N_("do not show a diffstat at the end of the merge"), 0),
247 OPT_BOOL(0, "stat", &show_diffstat,
248 N_("show a diffstat at the end of the merge")),
249 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
250 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
251 N_("add (at most <n>) entries from shortlog to merge commit message"),
252 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
253 OPT_BOOL(0, "squash", &squash,
254 N_("create a single commit instead of doing a merge")),
255 OPT_BOOL(0, "commit", &option_commit,
256 N_("perform a commit if the merge succeeds (default)")),
257 OPT_BOOL('e', "edit", &option_edit,
258 N_("edit message before committing")),
259 OPT_CLEANUP(&cleanup_arg),
260 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
261 OPT_SET_INT_F(0, "ff-only", &fast_forward,
262 N_("abort if fast-forward is not possible"),
263 FF_ONLY, PARSE_OPT_NONEG),
264 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
265 OPT_BOOL(0, "verify-signatures", &verify_signatures,
266 N_("verify that the named commit has a valid GPG signature")),
267 OPT_CALLBACK('s', "strategy", NULL, N_("strategy"),
268 N_("merge strategy to use"), option_parse_strategy),
269 OPT_STRVEC('X', "strategy-option", &xopts, N_("option=value"),
270 N_("option for selected merge strategy")),
271 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
272 N_("merge commit message (for a non-fast-forward merge)"),
273 option_parse_message),
274 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
275 N_("read message from file"), PARSE_OPT_NONEG,
276 NULL, 0, option_read_message },
277 OPT_STRING(0, "into-name", &into_name, N_("name"),
278 N_("use <name> instead of the real target")),
279 OPT__VERBOSITY(&verbosity),
280 OPT_BOOL(0, "abort", &abort_current_merge,
281 N_("abort the current in-progress merge")),
282 OPT_BOOL(0, "quit", &quit_current_merge,
283 N_("--abort but leave index and working tree alone")),
284 OPT_BOOL(0, "continue", &continue_current_merge,
285 N_("continue the current in-progress merge")),
286 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
287 N_("allow merging unrelated histories")),
288 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
289 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
290 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
291 OPT_AUTOSTASH(&autostash),
292 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
293 OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
294 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
295 OPT_END()
298 static int save_state(struct object_id *stash)
300 int len;
301 struct child_process cp = CHILD_PROCESS_INIT;
302 struct strbuf buffer = STRBUF_INIT;
303 struct lock_file lock_file = LOCK_INIT;
304 int fd;
305 int rc = -1;
307 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
308 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
309 if (0 <= fd)
310 repo_update_index_if_able(the_repository, &lock_file);
311 rollback_lock_file(&lock_file);
313 strvec_pushl(&cp.args, "stash", "create", NULL);
314 cp.out = -1;
315 cp.git_cmd = 1;
317 if (start_command(&cp))
318 die(_("could not run stash."));
319 len = strbuf_read(&buffer, cp.out, 1024);
320 close(cp.out);
322 if (finish_command(&cp) || len < 0)
323 die(_("stash failed"));
324 else if (!len) /* no changes */
325 goto out;
326 strbuf_setlen(&buffer, buffer.len-1);
327 if (repo_get_oid(the_repository, buffer.buf, stash))
328 die(_("not a valid object: %s"), buffer.buf);
329 rc = 0;
330 out:
331 strbuf_release(&buffer);
332 return rc;
335 static void read_empty(const struct object_id *oid)
337 struct child_process cmd = CHILD_PROCESS_INIT;
339 strvec_pushl(&cmd.args, "read-tree", "-m", "-u",
340 empty_tree_oid_hex(the_repository->hash_algo),
341 oid_to_hex(oid), NULL);
342 cmd.git_cmd = 1;
344 if (run_command(&cmd))
345 die(_("read-tree failed"));
348 static void reset_hard(const struct object_id *oid)
350 struct child_process cmd = CHILD_PROCESS_INIT;
352 strvec_pushl(&cmd.args, "read-tree", "-v", "--reset", "-u",
353 oid_to_hex(oid), NULL);
354 cmd.git_cmd = 1;
356 if (run_command(&cmd))
357 die(_("read-tree failed"));
360 static void restore_state(const struct object_id *head,
361 const struct object_id *stash)
363 struct child_process cmd = CHILD_PROCESS_INIT;
365 reset_hard(head);
367 if (is_null_oid(stash))
368 goto refresh_cache;
370 strvec_pushl(&cmd.args, "stash", "apply", "--index", "--quiet", NULL);
371 strvec_push(&cmd.args, oid_to_hex(stash));
374 * It is OK to ignore error here, for example when there was
375 * nothing to restore.
377 cmd.git_cmd = 1;
378 run_command(&cmd);
380 refresh_cache:
381 discard_index(the_repository->index);
382 if (repo_read_index(the_repository) < 0)
383 die(_("could not read index"));
386 /* This is called when no merge was necessary. */
387 static void finish_up_to_date(void)
389 if (verbosity >= 0) {
390 if (squash)
391 puts(_("Already up to date. (nothing to squash)"));
392 else
393 puts(_("Already up to date."));
395 remove_merge_branch_state(the_repository);
398 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
400 struct rev_info rev;
401 struct strbuf out = STRBUF_INIT;
402 struct commit_list *j;
403 struct pretty_print_context ctx = {0};
405 printf(_("Squash commit -- not updating HEAD\n"));
407 repo_init_revisions(the_repository, &rev, NULL);
408 diff_merges_suppress(&rev);
409 rev.commit_format = CMIT_FMT_MEDIUM;
411 commit->object.flags |= UNINTERESTING;
412 add_pending_object(&rev, &commit->object, NULL);
414 for (j = remoteheads; j; j = j->next)
415 add_pending_object(&rev, &j->item->object, NULL);
417 setup_revisions(0, NULL, &rev, NULL);
418 if (prepare_revision_walk(&rev))
419 die(_("revision walk setup failed"));
421 ctx.abbrev = rev.abbrev;
422 ctx.date_mode = rev.date_mode;
423 ctx.fmt = rev.commit_format;
425 strbuf_addstr(&out, "Squashed commit of the following:\n");
426 while ((commit = get_revision(&rev)) != NULL) {
427 strbuf_addch(&out, '\n');
428 strbuf_addf(&out, "commit %s\n",
429 oid_to_hex(&commit->object.oid));
430 pretty_print_commit(&ctx, commit, &out);
432 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
433 strbuf_release(&out);
434 release_revisions(&rev);
437 static void finish(struct commit *head_commit,
438 struct commit_list *remoteheads,
439 const struct object_id *new_head, const char *msg)
441 struct strbuf reflog_message = STRBUF_INIT;
442 const struct object_id *head = &head_commit->object.oid;
444 if (!msg)
445 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
446 else {
447 if (verbosity >= 0)
448 printf("%s\n", msg);
449 strbuf_addf(&reflog_message, "%s: %s",
450 getenv("GIT_REFLOG_ACTION"), msg);
452 if (squash) {
453 squash_message(head_commit, remoteheads);
454 } else {
455 if (verbosity >= 0 && !merge_msg.len)
456 printf(_("No merge message -- not updating HEAD\n"));
457 else {
458 refs_update_ref(get_main_ref_store(the_repository),
459 reflog_message.buf, "HEAD", new_head,
460 head,
461 0, UPDATE_REFS_DIE_ON_ERR);
463 * We ignore errors in 'gc --auto', since the
464 * user should see them.
466 run_auto_maintenance(verbosity < 0);
469 if (new_head && show_diffstat) {
470 struct diff_options opts;
471 repo_diff_setup(the_repository, &opts);
472 init_diffstat_widths(&opts);
473 opts.output_format |=
474 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
475 opts.detect_rename = DIFF_DETECT_RENAME;
476 diff_setup_done(&opts);
477 diff_tree_oid(head, new_head, "", &opts);
478 diffcore_std(&opts);
479 diff_flush(&opts);
482 /* Run a post-merge hook */
483 run_hooks_l(the_repository, "post-merge", squash ? "1" : "0", NULL);
485 if (new_head)
486 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
487 strbuf_release(&reflog_message);
490 /* Get the name for the merge commit's message. */
491 static void merge_name(const char *remote, struct strbuf *msg)
493 struct commit *remote_head;
494 struct object_id branch_head;
495 struct strbuf bname = STRBUF_INIT;
496 struct merge_remote_desc *desc;
497 const char *ptr;
498 char *found_ref = NULL;
499 int len, early;
501 strbuf_branchname(&bname, remote, 0);
502 remote = bname.buf;
504 oidclr(&branch_head, the_repository->hash_algo);
505 remote_head = get_merge_parent(remote);
506 if (!remote_head)
507 die(_("'%s' does not point to a commit"), remote);
509 if (repo_dwim_ref(the_repository, remote, strlen(remote), &branch_head,
510 &found_ref, 0) > 0) {
511 if (starts_with(found_ref, "refs/heads/")) {
512 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
513 oid_to_hex(&branch_head), remote);
514 goto cleanup;
516 if (starts_with(found_ref, "refs/tags/")) {
517 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
518 oid_to_hex(&branch_head), remote);
519 goto cleanup;
521 if (starts_with(found_ref, "refs/remotes/")) {
522 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
523 oid_to_hex(&branch_head), remote);
524 goto cleanup;
528 /* See if remote matches <name>^^^.. or <name>~<number> */
529 for (len = 0, ptr = remote + strlen(remote);
530 remote < ptr && ptr[-1] == '^';
531 ptr--)
532 len++;
533 if (len)
534 early = 1;
535 else {
536 early = 0;
537 ptr = strrchr(remote, '~');
538 if (ptr) {
539 int seen_nonzero = 0;
541 len++; /* count ~ */
542 while (*++ptr && isdigit(*ptr)) {
543 seen_nonzero |= (*ptr != '0');
544 len++;
546 if (*ptr)
547 len = 0; /* not ...~<number> */
548 else if (seen_nonzero)
549 early = 1;
550 else if (len == 1)
551 early = 1; /* "name~" is "name~1"! */
554 if (len) {
555 struct strbuf truname = STRBUF_INIT;
556 strbuf_addf(&truname, "refs/heads/%s", remote);
557 strbuf_setlen(&truname, truname.len - len);
558 if (refs_ref_exists(get_main_ref_store(the_repository), truname.buf)) {
559 strbuf_addf(msg,
560 "%s\t\tbranch '%s'%s of .\n",
561 oid_to_hex(&remote_head->object.oid),
562 truname.buf + 11,
563 (early ? " (early part)" : ""));
564 strbuf_release(&truname);
565 goto cleanup;
567 strbuf_release(&truname);
570 desc = merge_remote_util(remote_head);
571 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
572 strbuf_addf(msg, "%s\t\t%s '%s'\n",
573 oid_to_hex(&desc->obj->oid),
574 type_name(desc->obj->type),
575 remote);
576 goto cleanup;
579 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
580 oid_to_hex(&remote_head->object.oid), remote);
581 cleanup:
582 free(found_ref);
583 strbuf_release(&bname);
586 static void parse_branch_merge_options(char *bmo)
588 const char **argv;
589 int argc;
591 if (!bmo)
592 return;
593 argc = split_cmdline(bmo, &argv);
594 if (argc < 0)
595 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
596 _(split_cmdline_strerror(argc)));
597 REALLOC_ARRAY(argv, argc + 2);
598 MOVE_ARRAY(argv + 1, argv, argc + 1);
599 argc++;
600 argv[0] = "branch.*.mergeoptions";
601 parse_options(argc, argv, NULL, builtin_merge_options,
602 builtin_merge_usage, 0);
603 free(argv);
606 static int git_merge_config(const char *k, const char *v,
607 const struct config_context *ctx, void *cb)
609 int status;
610 const char *str;
612 if (branch &&
613 skip_prefix(k, "branch.", &str) &&
614 skip_prefix(str, branch, &str) &&
615 !strcmp(str, ".mergeoptions")) {
616 free(branch_mergeoptions);
617 branch_mergeoptions = xstrdup(v);
618 return 0;
621 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat")) {
622 show_diffstat = git_config_bool(k, v);
623 } else if (!strcmp(k, "merge.verifysignatures")) {
624 verify_signatures = git_config_bool(k, v);
625 } else if (!strcmp(k, "pull.twohead")) {
626 FREE_AND_NULL(pull_twohead);
627 return git_config_string(&pull_twohead, k, v);
628 } else if (!strcmp(k, "pull.octopus")) {
629 FREE_AND_NULL(pull_octopus);
630 return git_config_string(&pull_octopus, k, v);
631 } else if (!strcmp(k, "commit.cleanup")) {
632 return git_config_string(&cleanup_arg, k, v);
633 } else if (!strcmp(k, "merge.ff")) {
634 int boolval = git_parse_maybe_bool(v);
635 if (0 <= boolval) {
636 fast_forward = boolval ? FF_ALLOW : FF_NO;
637 } else if (v && !strcmp(v, "only")) {
638 fast_forward = FF_ONLY;
639 } /* do not barf on values from future versions of git */
640 return 0;
641 } else if (!strcmp(k, "merge.defaulttoupstream")) {
642 default_to_upstream = git_config_bool(k, v);
643 return 0;
644 } else if (!strcmp(k, "commit.gpgsign")) {
645 sign_commit = git_config_bool(k, v) ? "" : NULL;
646 return 0;
647 } else if (!strcmp(k, "gpg.mintrustlevel")) {
648 check_trust_level = 0;
649 } else if (!strcmp(k, "merge.autostash")) {
650 autostash = git_config_bool(k, v);
651 return 0;
654 status = fmt_merge_msg_config(k, v, ctx, cb);
655 if (status)
656 return status;
657 return git_diff_ui_config(k, v, ctx, cb);
660 static int read_tree_trivial(struct object_id *common, struct object_id *head,
661 struct object_id *one)
663 int i, nr_trees = 0;
664 struct tree *trees[MAX_UNPACK_TREES];
665 struct tree_desc t[MAX_UNPACK_TREES];
666 struct unpack_trees_options opts;
668 memset(&opts, 0, sizeof(opts));
669 opts.head_idx = 2;
670 opts.src_index = the_repository->index;
671 opts.dst_index = the_repository->index;
672 opts.update = 1;
673 opts.verbose_update = 1;
674 opts.trivial_merges_only = 1;
675 opts.merge = 1;
676 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
677 trees[nr_trees] = parse_tree_indirect(common);
678 if (!trees[nr_trees++])
679 return -1;
680 trees[nr_trees] = parse_tree_indirect(head);
681 if (!trees[nr_trees++])
682 return -1;
683 trees[nr_trees] = parse_tree_indirect(one);
684 if (!trees[nr_trees++])
685 return -1;
686 opts.fn = threeway_merge;
687 cache_tree_free(&the_repository->index->cache_tree);
688 for (i = 0; i < nr_trees; i++) {
689 parse_tree(trees[i]);
690 init_tree_desc(t+i, &trees[i]->object.oid,
691 trees[i]->buffer, trees[i]->size);
693 if (unpack_trees(nr_trees, t, &opts))
694 return -1;
695 return 0;
698 static void write_tree_trivial(struct object_id *oid)
700 if (write_index_as_tree(oid, the_repository->index,
701 repo_get_index_file(the_repository),
702 0, NULL))
703 die(_("git write-tree failed to write a tree"));
706 static int try_merge_strategy(const char *strategy, struct commit_list *common,
707 struct commit_list *remoteheads,
708 struct commit *head)
710 const char *head_arg = "HEAD";
712 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
713 SKIP_IF_UNCHANGED, 0, NULL, NULL,
714 NULL) < 0)
715 die(_("Unable to write index."));
717 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
718 !strcmp(strategy, "ort")) {
719 struct lock_file lock = LOCK_INIT;
720 int clean, x;
721 struct commit *result;
722 struct commit_list *reversed = NULL;
723 struct merge_options o;
724 struct commit_list *j;
726 if (remoteheads->next) {
727 error(_("Not handling anything other than two heads merge."));
728 return 2;
731 init_ui_merge_options(&o, the_repository);
732 if (!strcmp(strategy, "subtree"))
733 o.subtree_shift = "";
735 o.show_rename_progress =
736 show_progress == -1 ? isatty(2) : show_progress;
738 for (x = 0; x < xopts.nr; x++)
739 if (parse_merge_opt(&o, xopts.v[x]))
740 die(_("unknown strategy option: -X%s"), xopts.v[x]);
742 o.branch1 = head_arg;
743 o.branch2 = merge_remote_util(remoteheads->item)->name;
745 for (j = common; j; j = j->next)
746 commit_list_insert(j->item, &reversed);
748 repo_hold_locked_index(the_repository, &lock,
749 LOCK_DIE_ON_ERROR);
750 if (!strcmp(strategy, "ort"))
751 clean = merge_ort_recursive(&o, head, remoteheads->item,
752 reversed, &result);
753 else
754 clean = merge_recursive(&o, head, remoteheads->item,
755 reversed, &result);
756 free_commit_list(reversed);
758 if (clean < 0) {
759 rollback_lock_file(&lock);
760 return 2;
762 if (write_locked_index(the_repository->index, &lock,
763 COMMIT_LOCK | SKIP_IF_UNCHANGED))
764 die(_("unable to write %s"), repo_get_index_file(the_repository));
765 return clean ? 0 : 1;
766 } else {
767 return try_merge_command(the_repository,
768 strategy, xopts.nr, xopts.v,
769 common, head_arg, remoteheads);
773 static void count_diff_files(struct diff_queue_struct *q,
774 struct diff_options *opt UNUSED, void *data)
776 int *count = data;
778 (*count) += q->nr;
781 static int count_unmerged_entries(void)
783 int i, ret = 0;
785 for (i = 0; i < the_repository->index->cache_nr; i++)
786 if (ce_stage(the_repository->index->cache[i]))
787 ret++;
789 return ret;
792 static void add_strategies(const char *string, unsigned attr)
794 int i;
796 if (string) {
797 struct string_list list = STRING_LIST_INIT_DUP;
798 struct string_list_item *item;
799 string_list_split(&list, string, ' ', -1);
800 for_each_string_list_item(item, &list)
801 append_strategy(get_strategy(item->string));
802 string_list_clear(&list, 0);
803 return;
805 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
806 if (all_strategy[i].attr & attr)
807 append_strategy(&all_strategy[i]);
811 static void read_merge_msg(struct strbuf *msg)
813 const char *filename = git_path_merge_msg(the_repository);
814 strbuf_reset(msg);
815 if (strbuf_read_file(msg, filename, 0) < 0)
816 die_errno(_("Could not read from '%s'"), filename);
819 static void write_merge_state(struct commit_list *);
820 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
822 if (err_msg)
823 error("%s", err_msg);
824 fprintf(stderr,
825 _("Not committing merge; use 'git commit' to complete the merge.\n"));
826 write_merge_state(remoteheads);
827 exit(1);
830 static const char merge_editor_comment[] =
831 N_("Please enter a commit message to explain why this merge is necessary,\n"
832 "especially if it merges an updated upstream into a topic branch.\n"
833 "\n");
835 static const char scissors_editor_comment[] =
836 N_("An empty message aborts the commit.\n");
838 static const char no_scissors_editor_comment[] =
839 N_("Lines starting with '%s' will be ignored, and an empty message aborts\n"
840 "the commit.\n");
842 static void write_merge_heads(struct commit_list *);
843 static void prepare_to_commit(struct commit_list *remoteheads)
845 struct strbuf msg = STRBUF_INIT;
846 const char *index_file = repo_get_index_file(the_repository);
848 if (!no_verify) {
849 int invoked_hook;
851 if (run_commit_hook(0 < option_edit, index_file, &invoked_hook,
852 "pre-merge-commit", NULL))
853 abort_commit(remoteheads, NULL);
855 * Re-read the index as pre-merge-commit hook could have updated it,
856 * and write it out as a tree. We must do this before we invoke
857 * the editor and after we invoke run_status above.
859 if (invoked_hook)
860 discard_index(the_repository->index);
862 read_index_from(the_repository->index, index_file,
863 repo_get_git_dir(the_repository));
864 strbuf_addbuf(&msg, &merge_msg);
865 if (squash)
866 BUG("the control must not reach here under --squash");
867 if (0 < option_edit) {
868 strbuf_addch(&msg, '\n');
869 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
870 wt_status_append_cut_line(&msg);
871 strbuf_commented_addf(&msg, comment_line_str, "\n");
873 strbuf_commented_addf(&msg, comment_line_str,
874 _(merge_editor_comment));
875 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
876 strbuf_commented_addf(&msg, comment_line_str,
877 _(scissors_editor_comment));
878 else
879 strbuf_commented_addf(&msg, comment_line_str,
880 _(no_scissors_editor_comment), comment_line_str);
882 if (signoff)
883 append_signoff(&msg, ignored_log_message_bytes(msg.buf, msg.len), 0);
884 write_merge_heads(remoteheads);
885 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
886 if (run_commit_hook(0 < option_edit, repo_get_index_file(the_repository),
887 NULL, "prepare-commit-msg",
888 git_path_merge_msg(the_repository), "merge", NULL))
889 abort_commit(remoteheads, NULL);
890 if (0 < option_edit) {
891 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
892 abort_commit(remoteheads, NULL);
895 if (!no_verify && run_commit_hook(0 < option_edit, repo_get_index_file(the_repository),
896 NULL, "commit-msg",
897 git_path_merge_msg(the_repository), NULL))
898 abort_commit(remoteheads, NULL);
900 read_merge_msg(&msg);
901 cleanup_message(&msg, cleanup_mode, 0);
902 if (!msg.len)
903 abort_commit(remoteheads, _("Empty commit message."));
904 strbuf_release(&merge_msg);
905 strbuf_addbuf(&merge_msg, &msg);
906 strbuf_release(&msg);
909 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
911 struct object_id result_tree, result_commit;
912 struct commit_list *parents = NULL, **pptr = &parents;
914 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
915 SKIP_IF_UNCHANGED, 0, NULL, NULL,
916 NULL) < 0)
917 return error(_("Unable to write index."));
919 write_tree_trivial(&result_tree);
920 printf(_("Wonderful.\n"));
921 pptr = commit_list_append(head, pptr);
922 pptr = commit_list_append(remoteheads->item, pptr);
923 prepare_to_commit(remoteheads);
924 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
925 &result_commit, NULL, sign_commit))
926 die(_("failed to write commit object"));
927 finish(head, remoteheads, &result_commit, "In-index merge");
929 remove_merge_branch_state(the_repository);
930 free_commit_list(parents);
931 return 0;
934 static int finish_automerge(struct commit *head,
935 int head_subsumed,
936 struct commit_list *common,
937 struct commit_list *remoteheads,
938 struct object_id *result_tree,
939 const char *wt_strategy)
941 struct commit_list *parents = NULL;
942 struct strbuf buf = STRBUF_INIT;
943 struct object_id result_commit;
945 write_tree_trivial(result_tree);
946 free_commit_list(common);
947 parents = remoteheads;
948 if (!head_subsumed || fast_forward == FF_NO)
949 commit_list_insert(head, &parents);
950 prepare_to_commit(remoteheads);
951 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
952 &result_commit, NULL, sign_commit))
953 die(_("failed to write commit object"));
954 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
955 finish(head, remoteheads, &result_commit, buf.buf);
957 strbuf_release(&buf);
958 remove_merge_branch_state(the_repository);
959 free_commit_list(parents);
960 return 0;
963 static int suggest_conflicts(void)
965 const char *filename;
966 FILE *fp;
967 struct strbuf msgbuf = STRBUF_INIT;
969 filename = git_path_merge_msg(the_repository);
970 fp = xfopen(filename, "a");
973 * We can't use cleanup_mode because if we're not using the editor,
974 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
975 * though the message is meant to be processed later by git-commit.
976 * Thus, we will get the cleanup mode which is returned when we _are_
977 * using an editor.
979 append_conflicts_hint(the_repository->index, &msgbuf,
980 get_cleanup_mode(cleanup_arg, 1));
981 fputs(msgbuf.buf, fp);
982 strbuf_release(&msgbuf);
983 fclose(fp);
984 repo_rerere(the_repository, allow_rerere_auto);
985 printf(_("Automatic merge failed; "
986 "fix conflicts and then commit the result.\n"));
987 return 1;
990 static int evaluate_result(void)
992 int cnt = 0;
993 struct rev_info rev;
995 /* Check how many files differ. */
996 repo_init_revisions(the_repository, &rev, "");
997 setup_revisions(0, NULL, &rev, NULL);
998 rev.diffopt.output_format |=
999 DIFF_FORMAT_CALLBACK;
1000 rev.diffopt.format_callback = count_diff_files;
1001 rev.diffopt.format_callback_data = &cnt;
1002 run_diff_files(&rev, 0);
1005 * Check how many unmerged entries are
1006 * there.
1008 cnt += count_unmerged_entries();
1010 release_revisions(&rev);
1011 return cnt;
1015 * Pretend as if the user told us to merge with the remote-tracking
1016 * branch we have for the upstream of the current branch
1018 static int setup_with_upstream(const char ***argv)
1020 struct branch *branch = branch_get(NULL);
1021 int i;
1022 const char **args;
1024 if (!branch)
1025 die(_("No current branch."));
1026 if (!branch->remote_name)
1027 die(_("No remote for the current branch."));
1028 if (!branch->merge_nr)
1029 die(_("No default upstream defined for the current branch."));
1031 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1032 for (i = 0; i < branch->merge_nr; i++) {
1033 if (!branch->merge[i]->dst)
1034 die(_("No remote-tracking branch for %s from %s"),
1035 branch->merge[i]->src, branch->remote_name);
1036 args[i] = branch->merge[i]->dst;
1038 args[i] = NULL;
1039 *argv = args;
1040 return i;
1043 static void write_merge_heads(struct commit_list *remoteheads)
1045 struct commit_list *j;
1046 struct strbuf buf = STRBUF_INIT;
1048 for (j = remoteheads; j; j = j->next) {
1049 struct object_id *oid;
1050 struct commit *c = j->item;
1051 struct merge_remote_desc *desc;
1053 desc = merge_remote_util(c);
1054 if (desc && desc->obj) {
1055 oid = &desc->obj->oid;
1056 } else {
1057 oid = &c->object.oid;
1059 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1061 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1063 strbuf_reset(&buf);
1064 if (fast_forward == FF_NO)
1065 strbuf_addstr(&buf, "no-ff");
1066 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1067 strbuf_release(&buf);
1070 static void write_merge_state(struct commit_list *remoteheads)
1072 write_merge_heads(remoteheads);
1073 strbuf_addch(&merge_msg, '\n');
1074 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1075 merge_msg.len);
1078 static int default_edit_option(void)
1080 static const char name[] = "GIT_MERGE_AUTOEDIT";
1081 const char *e = getenv(name);
1082 struct stat st_stdin, st_stdout;
1084 if (have_message)
1085 /* an explicit -m msg without --[no-]edit */
1086 return 0;
1088 if (e) {
1089 int v = git_parse_maybe_bool(e);
1090 if (v < 0)
1091 die(_("Bad value '%s' in environment '%s'"), e, name);
1092 return v;
1095 /* Use editor if stdin and stdout are the same and is a tty */
1096 return (!fstat(0, &st_stdin) &&
1097 !fstat(1, &st_stdout) &&
1098 isatty(0) && isatty(1) &&
1099 st_stdin.st_dev == st_stdout.st_dev &&
1100 st_stdin.st_ino == st_stdout.st_ino &&
1101 st_stdin.st_mode == st_stdout.st_mode);
1104 static struct commit_list *reduce_parents(struct commit *head_commit,
1105 int *head_subsumed,
1106 struct commit_list *remoteheads)
1108 struct commit_list *parents, **remotes;
1111 * Is the current HEAD reachable from another commit being
1112 * merged? If so we do not want to record it as a parent of
1113 * the resulting merge, unless --no-ff is given. We will flip
1114 * this variable to 0 when we find HEAD among the independent
1115 * tips being merged.
1117 *head_subsumed = 1;
1119 /* Find what parents to record by checking independent ones. */
1120 parents = reduce_heads(remoteheads);
1121 free_commit_list(remoteheads);
1123 remoteheads = NULL;
1124 remotes = &remoteheads;
1125 while (parents) {
1126 struct commit *commit = pop_commit(&parents);
1127 if (commit == head_commit)
1128 *head_subsumed = 0;
1129 else
1130 remotes = &commit_list_insert(commit, remotes)->next;
1132 return remoteheads;
1135 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1137 struct fmt_merge_msg_opts opts;
1139 memset(&opts, 0, sizeof(opts));
1140 opts.add_title = !have_message;
1141 opts.shortlog_len = shortlog_len;
1142 opts.credit_people = (0 < option_edit);
1143 opts.into_name = into_name;
1145 fmt_merge_msg(merge_names, merge_msg, &opts);
1146 if (merge_msg->len)
1147 strbuf_setlen(merge_msg, merge_msg->len - 1);
1150 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1152 const char *filename;
1153 int fd, pos, npos;
1154 struct strbuf fetch_head_file = STRBUF_INIT;
1155 const unsigned hexsz = the_hash_algo->hexsz;
1157 if (!merge_names)
1158 merge_names = &fetch_head_file;
1160 filename = git_path_fetch_head(the_repository);
1161 fd = xopen(filename, O_RDONLY);
1163 if (strbuf_read(merge_names, fd, 0) < 0)
1164 die_errno(_("could not read '%s'"), filename);
1165 if (close(fd) < 0)
1166 die_errno(_("could not close '%s'"), filename);
1168 for (pos = 0; pos < merge_names->len; pos = npos) {
1169 struct object_id oid;
1170 char *ptr;
1171 struct commit *commit;
1173 ptr = strchr(merge_names->buf + pos, '\n');
1174 if (ptr)
1175 npos = ptr - merge_names->buf + 1;
1176 else
1177 npos = merge_names->len;
1179 if (npos - pos < hexsz + 2 ||
1180 get_oid_hex(merge_names->buf + pos, &oid))
1181 commit = NULL; /* bad */
1182 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1183 continue; /* not-for-merge */
1184 else {
1185 char saved = merge_names->buf[pos + hexsz];
1186 merge_names->buf[pos + hexsz] = '\0';
1187 commit = get_merge_parent(merge_names->buf + pos);
1188 merge_names->buf[pos + hexsz] = saved;
1190 if (!commit) {
1191 if (ptr)
1192 *ptr = '\0';
1193 die(_("not something we can merge in %s: %s"),
1194 filename, merge_names->buf + pos);
1196 remotes = &commit_list_insert(commit, remotes)->next;
1199 if (merge_names == &fetch_head_file)
1200 strbuf_release(&fetch_head_file);
1203 static struct commit_list *collect_parents(struct commit *head_commit,
1204 int *head_subsumed,
1205 int argc, const char **argv,
1206 struct strbuf *merge_msg)
1208 int i;
1209 struct commit_list *remoteheads = NULL;
1210 struct commit_list **remotes = &remoteheads;
1211 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1213 if (merge_msg && (!have_message || shortlog_len))
1214 autogen = &merge_names;
1216 if (head_commit)
1217 remotes = &commit_list_insert(head_commit, remotes)->next;
1219 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1220 handle_fetch_head(remotes, autogen);
1221 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1222 } else {
1223 for (i = 0; i < argc; i++) {
1224 struct commit *commit = get_merge_parent(argv[i]);
1225 if (!commit)
1226 help_unknown_ref(argv[i], "merge",
1227 _("not something we can merge"));
1228 remotes = &commit_list_insert(commit, remotes)->next;
1230 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1231 if (autogen) {
1232 struct commit_list *p;
1233 for (p = remoteheads; p; p = p->next)
1234 merge_name(merge_remote_util(p->item)->name, autogen);
1238 if (autogen) {
1239 prepare_merge_message(autogen, merge_msg);
1240 strbuf_release(autogen);
1243 return remoteheads;
1246 static int merging_a_throwaway_tag(struct commit *commit)
1248 char *tag_ref;
1249 struct object_id oid;
1250 int is_throwaway_tag = 0;
1252 /* Are we merging a tag? */
1253 if (!merge_remote_util(commit) ||
1254 !merge_remote_util(commit)->obj ||
1255 merge_remote_util(commit)->obj->type != OBJ_TAG)
1256 return is_throwaway_tag;
1259 * Now we know we are merging a tag object. Are we downstream
1260 * and following the tags from upstream? If so, we must have
1261 * the tag object pointed at by "refs/tags/$T" where $T is the
1262 * tagname recorded in the tag object. We want to allow such
1263 * a "just to catch up" merge to fast-forward.
1265 * Otherwise, we are playing an integrator's role, making a
1266 * merge with a throw-away tag from a contributor with
1267 * something like "git pull $contributor $signed_tag".
1268 * We want to forbid such a merge from fast-forwarding
1269 * by default; otherwise we would not keep the signature
1270 * anywhere.
1272 tag_ref = xstrfmt("refs/tags/%s",
1273 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1274 if (!refs_read_ref(get_main_ref_store(the_repository), tag_ref, &oid) &&
1275 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1276 is_throwaway_tag = 0;
1277 else
1278 is_throwaway_tag = 1;
1279 free(tag_ref);
1280 return is_throwaway_tag;
1283 int cmd_merge(int argc,
1284 const char **argv,
1285 const char *prefix,
1286 struct repository *repo UNUSED)
1288 struct object_id result_tree, stash, head_oid;
1289 struct commit *head_commit;
1290 struct strbuf buf = STRBUF_INIT;
1291 int i, ret = 0, head_subsumed;
1292 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1293 struct commit_list *common = NULL;
1294 const char *best_strategy = NULL, *wt_strategy = NULL;
1295 struct commit_list *remoteheads = NULL, *p;
1296 void *branch_to_free;
1297 int orig_argc = argc;
1299 if (argc == 2 && !strcmp(argv[1], "-h"))
1300 usage_with_options(builtin_merge_usage, builtin_merge_options);
1302 prepare_repo_settings(the_repository);
1303 the_repository->settings.command_requires_full_index = 0;
1306 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1307 * current branch.
1309 branch = branch_to_free = refs_resolve_refdup(get_main_ref_store(the_repository),
1310 "HEAD", 0, &head_oid,
1311 NULL);
1312 if (branch)
1313 skip_prefix(branch, "refs/heads/", &branch);
1315 if (!pull_twohead) {
1316 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1317 if (default_strategy && !strcmp(default_strategy, "ort"))
1318 pull_twohead = xstrdup("ort");
1321 init_diff_ui_defaults();
1322 git_config(git_merge_config, NULL);
1324 if (!branch || is_null_oid(&head_oid))
1325 head_commit = NULL;
1326 else
1327 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1329 if (branch_mergeoptions)
1330 parse_branch_merge_options(branch_mergeoptions);
1331 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1332 builtin_merge_usage, 0);
1333 if (shortlog_len < 0)
1334 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1336 if (verbosity < 0 && show_progress == -1)
1337 show_progress = 0;
1339 if (abort_current_merge) {
1340 int nargc = 2;
1341 const char *nargv[] = {"reset", "--merge", NULL};
1342 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
1343 struct object_id stash_oid = {0};
1345 if (orig_argc != 2)
1346 usage_msg_opt(_("--abort expects no arguments"),
1347 builtin_merge_usage, builtin_merge_options);
1349 if (!file_exists(git_path_merge_head(the_repository)))
1350 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1352 if (!refs_read_ref(get_main_ref_store(the_repository), "MERGE_AUTOSTASH", &stash_oid))
1353 refs_delete_ref(get_main_ref_store(the_repository),
1354 "", "MERGE_AUTOSTASH", &stash_oid,
1355 REF_NO_DEREF);
1357 /* Invoke 'git reset --merge' */
1358 ret = cmd_reset(nargc, nargv, prefix, the_repository);
1360 if (!is_null_oid(&stash_oid)) {
1361 oid_to_hex_r(stash_oid_hex, &stash_oid);
1362 apply_autostash_oid(stash_oid_hex);
1365 goto done;
1368 if (quit_current_merge) {
1369 if (orig_argc != 2)
1370 usage_msg_opt(_("--quit expects no arguments"),
1371 builtin_merge_usage,
1372 builtin_merge_options);
1374 remove_merge_branch_state(the_repository);
1375 goto done;
1378 if (continue_current_merge) {
1379 int nargc = 1;
1380 const char *nargv[] = {"commit", NULL};
1382 if (orig_argc != 2)
1383 usage_msg_opt(_("--continue expects no arguments"),
1384 builtin_merge_usage, builtin_merge_options);
1386 if (!file_exists(git_path_merge_head(the_repository)))
1387 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1389 /* Invoke 'git commit' */
1390 ret = cmd_commit(nargc, nargv, prefix, the_repository);
1391 goto done;
1394 if (repo_read_index_unmerged(the_repository))
1395 die_resolve_conflict("merge");
1397 if (file_exists(git_path_merge_head(the_repository))) {
1399 * There is no unmerged entry, don't advise 'git
1400 * add/rm <file>', just 'git commit'.
1402 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1403 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1404 "Please, commit your changes before you merge."));
1405 else
1406 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1408 if (refs_ref_exists(get_main_ref_store(the_repository), "CHERRY_PICK_HEAD")) {
1409 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1410 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1411 "Please, commit your changes before you merge."));
1412 else
1413 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1415 resolve_undo_clear_index(the_repository->index);
1417 if (option_edit < 0)
1418 option_edit = default_edit_option();
1420 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1422 if (verbosity < 0)
1423 show_diffstat = 0;
1425 if (squash) {
1426 if (fast_forward == FF_NO)
1427 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1428 if (option_commit > 0)
1429 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1431 * squash can now silently disable option_commit - this is not
1432 * a problem as it is only overriding the default, not a user
1433 * supplied option.
1435 option_commit = 0;
1438 if (option_commit < 0)
1439 option_commit = 1;
1441 if (!argc) {
1442 if (default_to_upstream)
1443 argc = setup_with_upstream(&argv);
1444 else
1445 die(_("No commit specified and merge.defaultToUpstream not set."));
1446 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1447 argv[0] = "@{-1}";
1450 if (!argc)
1451 usage_with_options(builtin_merge_usage,
1452 builtin_merge_options);
1454 if (!head_commit) {
1456 * If the merged head is a valid one there is no reason
1457 * to forbid "git merge" into a branch yet to be born.
1458 * We do the same for "git pull".
1460 struct object_id *remote_head_oid;
1461 if (squash)
1462 die(_("Squash commit into empty head not supported yet"));
1463 if (fast_forward == FF_NO)
1464 die(_("Non-fast-forward commit does not make sense into "
1465 "an empty head"));
1466 remoteheads = collect_parents(head_commit, &head_subsumed,
1467 argc, argv, NULL);
1468 if (!remoteheads)
1469 die(_("%s - not something we can merge"), argv[0]);
1470 if (remoteheads->next)
1471 die(_("Can merge only exactly one commit into empty head"));
1473 if (verify_signatures)
1474 verify_merge_signature(remoteheads->item, verbosity,
1475 check_trust_level);
1477 remote_head_oid = &remoteheads->item->object.oid;
1478 read_empty(remote_head_oid);
1479 refs_update_ref(get_main_ref_store(the_repository),
1480 "initial pull", "HEAD", remote_head_oid, NULL,
1482 UPDATE_REFS_DIE_ON_ERR);
1483 goto done;
1487 * All the rest are the commits being merged; prepare
1488 * the standard merge summary message to be appended
1489 * to the given message.
1491 remoteheads = collect_parents(head_commit, &head_subsumed,
1492 argc, argv, &merge_msg);
1494 if (!head_commit || !argc)
1495 usage_with_options(builtin_merge_usage,
1496 builtin_merge_options);
1498 if (verify_signatures) {
1499 for (p = remoteheads; p; p = p->next) {
1500 verify_merge_signature(p->item, verbosity,
1501 check_trust_level);
1505 strbuf_addstr(&buf, "merge");
1506 for (p = remoteheads; p; p = p->next)
1507 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1508 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1509 strbuf_reset(&buf);
1511 for (p = remoteheads; p; p = p->next) {
1512 struct commit *commit = p->item;
1513 strbuf_addf(&buf, "GITHEAD_%s",
1514 oid_to_hex(&commit->object.oid));
1515 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1516 strbuf_reset(&buf);
1517 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1518 fast_forward = FF_NO;
1521 if (!use_strategies && !pull_twohead &&
1522 remoteheads && !remoteheads->next) {
1523 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1524 if (default_strategy)
1525 append_strategy(get_strategy(default_strategy));
1527 if (!use_strategies) {
1528 if (!remoteheads)
1529 ; /* already up-to-date */
1530 else if (!remoteheads->next)
1531 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1532 else
1533 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1536 for (i = 0; i < use_strategies_nr; i++) {
1537 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1538 fast_forward = FF_NO;
1539 if (use_strategies[i]->attr & NO_TRIVIAL)
1540 allow_trivial = 0;
1543 if (!remoteheads)
1544 ; /* already up-to-date */
1545 else if (!remoteheads->next) {
1546 if (repo_get_merge_bases(the_repository, head_commit,
1547 remoteheads->item, &common) < 0) {
1548 ret = 2;
1549 goto done;
1551 } else {
1552 struct commit_list *list = remoteheads;
1553 commit_list_insert(head_commit, &list);
1554 if (get_octopus_merge_bases(list, &common) < 0) {
1555 free(list);
1556 ret = 2;
1557 goto done;
1559 free(list);
1562 refs_update_ref(get_main_ref_store(the_repository),
1563 "updating ORIG_HEAD", "ORIG_HEAD",
1564 &head_commit->object.oid, NULL, 0,
1565 UPDATE_REFS_DIE_ON_ERR);
1567 if (remoteheads && !common) {
1568 /* No common ancestors found. */
1569 if (!allow_unrelated_histories)
1570 die(_("refusing to merge unrelated histories"));
1571 /* otherwise, we need a real merge. */
1572 } else if (!remoteheads ||
1573 (!remoteheads->next && !common->next &&
1574 common->item == remoteheads->item)) {
1576 * If head can reach all the merge then we are up to date.
1577 * but first the most common case of merging one remote.
1579 finish_up_to_date();
1580 goto done;
1581 } else if (fast_forward != FF_NO && !remoteheads->next &&
1582 !common->next &&
1583 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1584 /* Again the most common case of merging one remote. */
1585 const char *msg = have_message ?
1586 "Fast-forward (no commit created; -m option ignored)" :
1587 "Fast-forward";
1588 struct commit *commit;
1590 if (verbosity >= 0) {
1591 printf(_("Updating %s..%s\n"),
1592 repo_find_unique_abbrev(the_repository, &head_commit->object.oid,
1593 DEFAULT_ABBREV),
1594 repo_find_unique_abbrev(the_repository, &remoteheads->item->object.oid,
1595 DEFAULT_ABBREV));
1597 commit = remoteheads->item;
1598 if (!commit) {
1599 ret = 1;
1600 goto done;
1603 if (autostash)
1604 create_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1605 if (checkout_fast_forward(the_repository,
1606 &head_commit->object.oid,
1607 &commit->object.oid,
1608 overwrite_ignore)) {
1609 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1610 ret = 1;
1611 goto done;
1614 finish(head_commit, remoteheads, &commit->object.oid, msg);
1615 remove_merge_branch_state(the_repository);
1616 goto done;
1617 } else if (!remoteheads->next && common->next)
1620 * We are not doing octopus and not fast-forward. Need
1621 * a real merge.
1623 else if (!remoteheads->next && !common->next && option_commit) {
1625 * We are not doing octopus, not fast-forward, and have
1626 * only one common.
1628 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
1629 if (allow_trivial && fast_forward != FF_ONLY) {
1631 * Must first ensure that index matches HEAD before
1632 * attempting a trivial merge.
1634 struct tree *head_tree = repo_get_commit_tree(the_repository,
1635 head_commit);
1636 struct strbuf sb = STRBUF_INIT;
1638 if (repo_index_has_changes(the_repository, head_tree,
1639 &sb)) {
1640 error(_("Your local changes to the following files would be overwritten by merge:\n %s"),
1641 sb.buf);
1642 strbuf_release(&sb);
1643 ret = 2;
1644 goto done;
1647 /* See if it is really trivial. */
1648 git_committer_info(IDENT_STRICT);
1649 printf(_("Trying really trivial in-index merge...\n"));
1650 if (!read_tree_trivial(&common->item->object.oid,
1651 &head_commit->object.oid,
1652 &remoteheads->item->object.oid)) {
1653 ret = merge_trivial(head_commit, remoteheads);
1654 goto done;
1656 printf(_("Nope.\n"));
1658 } else {
1660 * An octopus. If we can reach all the remote we are up
1661 * to date.
1663 int up_to_date = 1;
1664 struct commit_list *j;
1666 for (j = remoteheads; j; j = j->next) {
1667 struct commit_list *common_one = NULL;
1668 struct commit *common_item;
1671 * Here we *have* to calculate the individual
1672 * merge_bases again, otherwise "git merge HEAD^
1673 * HEAD^^" would be missed.
1675 if (repo_get_merge_bases(the_repository, head_commit,
1676 j->item, &common_one) < 0)
1677 exit(128);
1679 common_item = common_one->item;
1680 free_commit_list(common_one);
1681 if (!oideq(&common_item->object.oid, &j->item->object.oid)) {
1682 up_to_date = 0;
1683 break;
1686 if (up_to_date) {
1687 finish_up_to_date();
1688 goto done;
1692 if (fast_forward == FF_ONLY)
1693 die_ff_impossible();
1695 if (autostash)
1696 create_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1698 /* We are going to make a new commit. */
1699 git_committer_info(IDENT_STRICT);
1702 * At this point, we need a real merge. No matter what strategy
1703 * we use, it would operate on the index, possibly affecting the
1704 * working tree, and when resolved cleanly, have the desired
1705 * tree in the index -- this means that the index must be in
1706 * sync with the head commit. The strategies are responsible
1707 * to ensure this.
1709 * Stash away the local changes so that we can try more than one
1710 * and/or recover from merge strategies bailing while leaving the
1711 * index and working tree polluted.
1713 if (save_state(&stash))
1714 oidclr(&stash, the_repository->hash_algo);
1716 for (i = 0; i < use_strategies_nr; i++) {
1717 int ret, cnt;
1718 if (i) {
1719 printf(_("Rewinding the tree to pristine...\n"));
1720 restore_state(&head_commit->object.oid, &stash);
1722 if (use_strategies_nr != 1)
1723 printf(_("Trying merge strategy %s...\n"),
1724 use_strategies[i]->name);
1726 * Remember which strategy left the state in the working
1727 * tree.
1729 wt_strategy = use_strategies[i]->name;
1731 ret = try_merge_strategy(wt_strategy,
1732 common, remoteheads,
1733 head_commit);
1735 * The backend exits with 1 when conflicts are
1736 * left to be resolved, with 2 when it does not
1737 * handle the given merge at all.
1739 if (ret < 2) {
1740 if (!ret) {
1742 * This strategy worked; no point in trying
1743 * another.
1745 merge_was_ok = 1;
1746 best_strategy = wt_strategy;
1747 break;
1749 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1750 if (best_cnt <= 0 || cnt <= best_cnt) {
1751 best_strategy = wt_strategy;
1752 best_cnt = cnt;
1758 * If we have a resulting tree, that means the strategy module
1759 * auto resolved the merge cleanly.
1761 if (merge_was_ok && option_commit) {
1762 automerge_was_ok = 1;
1763 ret = finish_automerge(head_commit, head_subsumed,
1764 common, remoteheads,
1765 &result_tree, wt_strategy);
1766 goto done;
1770 * Pick the result from the best strategy and have the user fix
1771 * it up.
1773 if (!best_strategy) {
1774 restore_state(&head_commit->object.oid, &stash);
1775 if (use_strategies_nr > 1)
1776 fprintf(stderr,
1777 _("No merge strategy handled the merge.\n"));
1778 else
1779 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1780 use_strategies[0]->name);
1781 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1782 ret = 2;
1783 goto done;
1784 } else if (best_strategy == wt_strategy)
1785 ; /* We already have its result in the working tree. */
1786 else {
1787 printf(_("Rewinding the tree to pristine...\n"));
1788 restore_state(&head_commit->object.oid, &stash);
1789 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1790 best_strategy);
1791 try_merge_strategy(best_strategy, common, remoteheads,
1792 head_commit);
1795 if (squash) {
1796 finish(head_commit, remoteheads, NULL, NULL);
1798 git_test_write_commit_graph_or_die();
1799 } else
1800 write_merge_state(remoteheads);
1802 if (merge_was_ok)
1803 fprintf(stderr, _("Automatic merge went well; "
1804 "stopped before committing as requested\n"));
1805 else
1806 ret = suggest_conflicts();
1807 if (autostash)
1808 printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1810 done:
1811 if (!automerge_was_ok) {
1812 free_commit_list(common);
1813 free_commit_list(remoteheads);
1815 strbuf_release(&buf);
1816 free(branch_to_free);
1817 free(pull_twohead);
1818 free(pull_octopus);
1819 discard_index(the_repository->index);
1820 return ret;