merge: make xopts a strvec
[git.git] / builtin / merge.c
blob53e9fe70d9daf002513965c8368ba8029a2dd485
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_VARIABLE
10 #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 "run-command.h"
22 #include "hook.h"
23 #include "diff.h"
24 #include "diff-merges.h"
25 #include "refs.h"
26 #include "refspec.h"
27 #include "commit.h"
28 #include "diffcore.h"
29 #include "path.h"
30 #include "revision.h"
31 #include "unpack-trees.h"
32 #include "cache-tree.h"
33 #include "dir.h"
34 #include "utf8.h"
35 #include "log-tree.h"
36 #include "color.h"
37 #include "rerere.h"
38 #include "help.h"
39 #include "merge.h"
40 #include "merge-recursive.h"
41 #include "merge-ort-wrappers.h"
42 #include "resolve-undo.h"
43 #include "remote.h"
44 #include "fmt-merge-msg.h"
45 #include "gpg-interface.h"
46 #include "sequencer.h"
47 #include "string-list.h"
48 #include "packfile.h"
49 #include "tag.h"
50 #include "alias.h"
51 #include "branch.h"
52 #include "commit-reach.h"
53 #include "wt-status.h"
54 #include "commit-graph.h"
56 #define DEFAULT_TWOHEAD (1<<0)
57 #define DEFAULT_OCTOPUS (1<<1)
58 #define NO_FAST_FORWARD (1<<2)
59 #define NO_TRIVIAL (1<<3)
61 struct strategy {
62 const char *name;
63 unsigned attr;
66 static const char * const builtin_merge_usage[] = {
67 N_("git merge [<options>] [<commit>...]"),
68 "git merge --abort",
69 "git merge --continue",
70 NULL
73 static int show_diffstat = 1, shortlog_len = -1, squash;
74 static int option_commit = -1;
75 static int option_edit = -1;
76 static int allow_trivial = 1, have_message, verify_signatures;
77 static int check_trust_level = 1;
78 static int overwrite_ignore = 1;
79 static struct strbuf merge_msg = STRBUF_INIT;
80 static struct strategy **use_strategies;
81 static size_t use_strategies_nr, use_strategies_alloc;
82 static struct strvec xopts = STRVEC_INIT;
83 static const char *branch;
84 static char *branch_mergeoptions;
85 static int verbosity;
86 static int allow_rerere_auto;
87 static int abort_current_merge;
88 static int quit_current_merge;
89 static int continue_current_merge;
90 static int allow_unrelated_histories;
91 static int show_progress = -1;
92 static int default_to_upstream = 1;
93 static int signoff;
94 static const char *sign_commit;
95 static int autostash;
96 static int no_verify;
97 static char *into_name;
99 static struct strategy all_strategy[] = {
100 { "recursive", NO_TRIVIAL },
101 { "octopus", DEFAULT_OCTOPUS },
102 { "ort", DEFAULT_TWOHEAD | NO_TRIVIAL },
103 { "resolve", 0 },
104 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
105 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
108 static const char *pull_twohead, *pull_octopus;
110 enum ff_type {
111 FF_NO,
112 FF_ALLOW,
113 FF_ONLY
116 static enum ff_type fast_forward = FF_ALLOW;
118 static const char *cleanup_arg;
119 static enum commit_msg_cleanup_mode cleanup_mode;
121 static int option_parse_message(const struct option *opt,
122 const char *arg, int unset)
124 struct strbuf *buf = opt->value;
126 if (unset)
127 strbuf_setlen(buf, 0);
128 else if (arg) {
129 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
130 have_message = 1;
131 } else
132 return error(_("switch `m' requires a value"));
133 return 0;
136 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
137 const struct option *opt,
138 const char *arg_not_used,
139 int unset)
141 struct strbuf *buf = opt->value;
142 const char *arg;
144 BUG_ON_OPT_ARG(arg_not_used);
145 if (unset)
146 BUG("-F cannot be negated");
148 if (ctx->opt) {
149 arg = ctx->opt;
150 ctx->opt = NULL;
151 } else if (ctx->argc > 1) {
152 ctx->argc--;
153 arg = *++ctx->argv;
154 } else
155 return error(_("option `%s' requires a value"), opt->long_name);
157 if (buf->len)
158 strbuf_addch(buf, '\n');
159 if (ctx->prefix && !is_absolute_path(arg))
160 arg = prefix_filename(ctx->prefix, arg);
161 if (strbuf_read_file(buf, arg, 0) < 0)
162 return error(_("could not read file '%s'"), arg);
163 have_message = 1;
165 return 0;
168 static struct strategy *get_strategy(const char *name)
170 int i;
171 struct strategy *ret;
172 static struct cmdnames main_cmds, other_cmds;
173 static int loaded;
174 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
176 if (!name)
177 return NULL;
179 if (default_strategy &&
180 !strcmp(default_strategy, "ort") &&
181 !strcmp(name, "recursive")) {
182 name = "ort";
185 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
186 if (!strcmp(name, all_strategy[i].name))
187 return &all_strategy[i];
189 if (!loaded) {
190 struct cmdnames not_strategies;
191 loaded = 1;
193 memset(&not_strategies, 0, sizeof(struct cmdnames));
194 load_command_list("git-merge-", &main_cmds, &other_cmds);
195 for (i = 0; i < main_cmds.cnt; i++) {
196 int j, found = 0;
197 struct cmdname *ent = main_cmds.names[i];
198 for (j = 0; !found && j < ARRAY_SIZE(all_strategy); j++)
199 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
200 && !all_strategy[j].name[ent->len])
201 found = 1;
202 if (!found)
203 add_cmdname(&not_strategies, ent->name, ent->len);
205 exclude_cmds(&main_cmds, &not_strategies);
207 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
208 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
209 fprintf(stderr, _("Available strategies are:"));
210 for (i = 0; i < main_cmds.cnt; i++)
211 fprintf(stderr, " %s", main_cmds.names[i]->name);
212 fprintf(stderr, ".\n");
213 if (other_cmds.cnt) {
214 fprintf(stderr, _("Available custom strategies are:"));
215 for (i = 0; i < other_cmds.cnt; i++)
216 fprintf(stderr, " %s", other_cmds.names[i]->name);
217 fprintf(stderr, ".\n");
219 exit(1);
222 CALLOC_ARRAY(ret, 1);
223 ret->name = xstrdup(name);
224 ret->attr = NO_TRIVIAL;
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,
235 const char *name, int unset)
237 if (unset)
238 return 0;
240 append_strategy(get_strategy(name));
241 return 0;
244 static int option_parse_n(const struct option *opt,
245 const char *arg, int unset)
247 BUG_ON_OPT_ARG(arg);
248 show_diffstat = unset;
249 return 0;
252 static struct option builtin_merge_options[] = {
253 OPT_CALLBACK_F('n', NULL, NULL, NULL,
254 N_("do not show a diffstat at the end of the merge"),
255 PARSE_OPT_NOARG, option_parse_n),
256 OPT_BOOL(0, "stat", &show_diffstat,
257 N_("show a diffstat at the end of the merge")),
258 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
259 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
260 N_("add (at most <n>) entries from shortlog to merge commit message"),
261 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
262 OPT_BOOL(0, "squash", &squash,
263 N_("create a single commit instead of doing a merge")),
264 OPT_BOOL(0, "commit", &option_commit,
265 N_("perform a commit if the merge succeeds (default)")),
266 OPT_BOOL('e', "edit", &option_edit,
267 N_("edit message before committing")),
268 OPT_CLEANUP(&cleanup_arg),
269 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
270 OPT_SET_INT_F(0, "ff-only", &fast_forward,
271 N_("abort if fast-forward is not possible"),
272 FF_ONLY, PARSE_OPT_NONEG),
273 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
274 OPT_BOOL(0, "verify-signatures", &verify_signatures,
275 N_("verify that the named commit has a valid GPG signature")),
276 OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
277 N_("merge strategy to use"), option_parse_strategy),
278 OPT_STRVEC('X', "strategy-option", &xopts, N_("option=value"),
279 N_("option for selected merge strategy")),
280 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
281 N_("merge commit message (for a non-fast-forward merge)"),
282 option_parse_message),
283 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
284 N_("read message from file"), PARSE_OPT_NONEG,
285 NULL, 0, option_read_message },
286 OPT_STRING(0, "into-name", &into_name, N_("name"),
287 N_("use <name> instead of the real target")),
288 OPT__VERBOSITY(&verbosity),
289 OPT_BOOL(0, "abort", &abort_current_merge,
290 N_("abort the current in-progress merge")),
291 OPT_BOOL(0, "quit", &quit_current_merge,
292 N_("--abort but leave index and working tree alone")),
293 OPT_BOOL(0, "continue", &continue_current_merge,
294 N_("continue the current in-progress merge")),
295 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
296 N_("allow merging unrelated histories")),
297 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
298 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
299 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
300 OPT_AUTOSTASH(&autostash),
301 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
302 OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
303 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
304 OPT_END()
307 static int save_state(struct object_id *stash)
309 int len;
310 struct child_process cp = CHILD_PROCESS_INIT;
311 struct strbuf buffer = STRBUF_INIT;
312 struct lock_file lock_file = LOCK_INIT;
313 int fd;
314 int rc = -1;
316 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
317 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
318 if (0 <= fd)
319 repo_update_index_if_able(the_repository, &lock_file);
320 rollback_lock_file(&lock_file);
322 strvec_pushl(&cp.args, "stash", "create", NULL);
323 cp.out = -1;
324 cp.git_cmd = 1;
326 if (start_command(&cp))
327 die(_("could not run stash."));
328 len = strbuf_read(&buffer, cp.out, 1024);
329 close(cp.out);
331 if (finish_command(&cp) || len < 0)
332 die(_("stash failed"));
333 else if (!len) /* no changes */
334 goto out;
335 strbuf_setlen(&buffer, buffer.len-1);
336 if (repo_get_oid(the_repository, buffer.buf, stash))
337 die(_("not a valid object: %s"), buffer.buf);
338 rc = 0;
339 out:
340 strbuf_release(&buffer);
341 return rc;
344 static void read_empty(const struct object_id *oid)
346 struct child_process cmd = CHILD_PROCESS_INIT;
348 strvec_pushl(&cmd.args, "read-tree", "-m", "-u", empty_tree_oid_hex(),
349 oid_to_hex(oid), NULL);
350 cmd.git_cmd = 1;
352 if (run_command(&cmd))
353 die(_("read-tree failed"));
356 static void reset_hard(const struct object_id *oid)
358 struct child_process cmd = CHILD_PROCESS_INIT;
360 strvec_pushl(&cmd.args, "read-tree", "-v", "--reset", "-u",
361 oid_to_hex(oid), NULL);
362 cmd.git_cmd = 1;
364 if (run_command(&cmd))
365 die(_("read-tree failed"));
368 static void restore_state(const struct object_id *head,
369 const struct object_id *stash)
371 struct child_process cmd = CHILD_PROCESS_INIT;
373 reset_hard(head);
375 if (is_null_oid(stash))
376 goto refresh_cache;
378 strvec_pushl(&cmd.args, "stash", "apply", "--index", "--quiet", NULL);
379 strvec_push(&cmd.args, oid_to_hex(stash));
382 * It is OK to ignore error here, for example when there was
383 * nothing to restore.
385 cmd.git_cmd = 1;
386 run_command(&cmd);
388 refresh_cache:
389 discard_index(&the_index);
390 if (repo_read_index(the_repository) < 0)
391 die(_("could not read index"));
394 /* This is called when no merge was necessary. */
395 static void finish_up_to_date(void)
397 if (verbosity >= 0) {
398 if (squash)
399 puts(_("Already up to date. (nothing to squash)"));
400 else
401 puts(_("Already up to date."));
403 remove_merge_branch_state(the_repository);
406 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
408 struct rev_info rev;
409 struct strbuf out = STRBUF_INIT;
410 struct commit_list *j;
411 struct pretty_print_context ctx = {0};
413 printf(_("Squash commit -- not updating HEAD\n"));
415 repo_init_revisions(the_repository, &rev, NULL);
416 diff_merges_suppress(&rev);
417 rev.commit_format = CMIT_FMT_MEDIUM;
419 commit->object.flags |= UNINTERESTING;
420 add_pending_object(&rev, &commit->object, NULL);
422 for (j = remoteheads; j; j = j->next)
423 add_pending_object(&rev, &j->item->object, NULL);
425 setup_revisions(0, NULL, &rev, NULL);
426 if (prepare_revision_walk(&rev))
427 die(_("revision walk setup failed"));
429 ctx.abbrev = rev.abbrev;
430 ctx.date_mode = rev.date_mode;
431 ctx.fmt = rev.commit_format;
433 strbuf_addstr(&out, "Squashed commit of the following:\n");
434 while ((commit = get_revision(&rev)) != NULL) {
435 strbuf_addch(&out, '\n');
436 strbuf_addf(&out, "commit %s\n",
437 oid_to_hex(&commit->object.oid));
438 pretty_print_commit(&ctx, commit, &out);
440 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
441 strbuf_release(&out);
442 release_revisions(&rev);
445 static void finish(struct commit *head_commit,
446 struct commit_list *remoteheads,
447 const struct object_id *new_head, const char *msg)
449 struct strbuf reflog_message = STRBUF_INIT;
450 const struct object_id *head = &head_commit->object.oid;
452 if (!msg)
453 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
454 else {
455 if (verbosity >= 0)
456 printf("%s\n", msg);
457 strbuf_addf(&reflog_message, "%s: %s",
458 getenv("GIT_REFLOG_ACTION"), msg);
460 if (squash) {
461 squash_message(head_commit, remoteheads);
462 } else {
463 if (verbosity >= 0 && !merge_msg.len)
464 printf(_("No merge message -- not updating HEAD\n"));
465 else {
466 update_ref(reflog_message.buf, "HEAD", new_head, head,
467 0, UPDATE_REFS_DIE_ON_ERR);
469 * We ignore errors in 'gc --auto', since the
470 * user should see them.
472 run_auto_maintenance(verbosity < 0);
475 if (new_head && show_diffstat) {
476 struct diff_options opts;
477 repo_diff_setup(the_repository, &opts);
478 opts.stat_width = -1; /* use full terminal width */
479 opts.stat_graph_width = -1; /* respect statGraphWidth config */
480 opts.output_format |=
481 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
482 opts.detect_rename = DIFF_DETECT_RENAME;
483 diff_setup_done(&opts);
484 diff_tree_oid(head, new_head, "", &opts);
485 diffcore_std(&opts);
486 diff_flush(&opts);
489 /* Run a post-merge hook */
490 run_hooks_l("post-merge", squash ? "1" : "0", NULL);
492 if (new_head)
493 apply_autostash(git_path_merge_autostash(the_repository));
494 strbuf_release(&reflog_message);
497 /* Get the name for the merge commit's message. */
498 static void merge_name(const char *remote, struct strbuf *msg)
500 struct commit *remote_head;
501 struct object_id branch_head;
502 struct strbuf bname = STRBUF_INIT;
503 struct merge_remote_desc *desc;
504 const char *ptr;
505 char *found_ref = NULL;
506 int len, early;
508 strbuf_branchname(&bname, remote, 0);
509 remote = bname.buf;
511 oidclr(&branch_head);
512 remote_head = get_merge_parent(remote);
513 if (!remote_head)
514 die(_("'%s' does not point to a commit"), remote);
516 if (repo_dwim_ref(the_repository, remote, strlen(remote), &branch_head,
517 &found_ref, 0) > 0) {
518 if (starts_with(found_ref, "refs/heads/")) {
519 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
520 oid_to_hex(&branch_head), remote);
521 goto cleanup;
523 if (starts_with(found_ref, "refs/tags/")) {
524 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
525 oid_to_hex(&branch_head), remote);
526 goto cleanup;
528 if (starts_with(found_ref, "refs/remotes/")) {
529 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
530 oid_to_hex(&branch_head), remote);
531 goto cleanup;
535 /* See if remote matches <name>^^^.. or <name>~<number> */
536 for (len = 0, ptr = remote + strlen(remote);
537 remote < ptr && ptr[-1] == '^';
538 ptr--)
539 len++;
540 if (len)
541 early = 1;
542 else {
543 early = 0;
544 ptr = strrchr(remote, '~');
545 if (ptr) {
546 int seen_nonzero = 0;
548 len++; /* count ~ */
549 while (*++ptr && isdigit(*ptr)) {
550 seen_nonzero |= (*ptr != '0');
551 len++;
553 if (*ptr)
554 len = 0; /* not ...~<number> */
555 else if (seen_nonzero)
556 early = 1;
557 else if (len == 1)
558 early = 1; /* "name~" is "name~1"! */
561 if (len) {
562 struct strbuf truname = STRBUF_INIT;
563 strbuf_addf(&truname, "refs/heads/%s", remote);
564 strbuf_setlen(&truname, truname.len - len);
565 if (ref_exists(truname.buf)) {
566 strbuf_addf(msg,
567 "%s\t\tbranch '%s'%s of .\n",
568 oid_to_hex(&remote_head->object.oid),
569 truname.buf + 11,
570 (early ? " (early part)" : ""));
571 strbuf_release(&truname);
572 goto cleanup;
574 strbuf_release(&truname);
577 desc = merge_remote_util(remote_head);
578 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
579 strbuf_addf(msg, "%s\t\t%s '%s'\n",
580 oid_to_hex(&desc->obj->oid),
581 type_name(desc->obj->type),
582 remote);
583 goto cleanup;
586 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
587 oid_to_hex(&remote_head->object.oid), remote);
588 cleanup:
589 free(found_ref);
590 strbuf_release(&bname);
593 static void parse_branch_merge_options(char *bmo)
595 const char **argv;
596 int argc;
598 if (!bmo)
599 return;
600 argc = split_cmdline(bmo, &argv);
601 if (argc < 0)
602 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
603 _(split_cmdline_strerror(argc)));
604 REALLOC_ARRAY(argv, argc + 2);
605 MOVE_ARRAY(argv + 1, argv, argc + 1);
606 argc++;
607 argv[0] = "branch.*.mergeoptions";
608 parse_options(argc, argv, NULL, builtin_merge_options,
609 builtin_merge_usage, 0);
610 free(argv);
613 static int git_merge_config(const char *k, const char *v,
614 const struct config_context *ctx, void *cb)
616 int status;
617 const char *str;
619 if (branch &&
620 skip_prefix(k, "branch.", &str) &&
621 skip_prefix(str, branch, &str) &&
622 !strcmp(str, ".mergeoptions")) {
623 free(branch_mergeoptions);
624 branch_mergeoptions = xstrdup(v);
625 return 0;
628 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
629 show_diffstat = git_config_bool(k, v);
630 else if (!strcmp(k, "merge.verifysignatures"))
631 verify_signatures = git_config_bool(k, v);
632 else if (!strcmp(k, "pull.twohead"))
633 return git_config_string(&pull_twohead, k, v);
634 else if (!strcmp(k, "pull.octopus"))
635 return git_config_string(&pull_octopus, k, v);
636 else if (!strcmp(k, "commit.cleanup"))
637 return git_config_string(&cleanup_arg, k, v);
638 else if (!strcmp(k, "merge.ff")) {
639 int boolval = git_parse_maybe_bool(v);
640 if (0 <= boolval) {
641 fast_forward = boolval ? FF_ALLOW : FF_NO;
642 } else if (v && !strcmp(v, "only")) {
643 fast_forward = FF_ONLY;
644 } /* do not barf on values from future versions of git */
645 return 0;
646 } else if (!strcmp(k, "merge.defaulttoupstream")) {
647 default_to_upstream = git_config_bool(k, v);
648 return 0;
649 } else if (!strcmp(k, "commit.gpgsign")) {
650 sign_commit = git_config_bool(k, v) ? "" : NULL;
651 return 0;
652 } else if (!strcmp(k, "gpg.mintrustlevel")) {
653 check_trust_level = 0;
654 } else if (!strcmp(k, "merge.autostash")) {
655 autostash = git_config_bool(k, v);
656 return 0;
659 status = fmt_merge_msg_config(k, v, ctx, cb);
660 if (status)
661 return status;
662 return git_diff_ui_config(k, v, ctx, cb);
665 static int read_tree_trivial(struct object_id *common, struct object_id *head,
666 struct object_id *one)
668 int i, nr_trees = 0;
669 struct tree *trees[MAX_UNPACK_TREES];
670 struct tree_desc t[MAX_UNPACK_TREES];
671 struct unpack_trees_options opts;
673 memset(&opts, 0, sizeof(opts));
674 opts.head_idx = 2;
675 opts.src_index = &the_index;
676 opts.dst_index = &the_index;
677 opts.update = 1;
678 opts.verbose_update = 1;
679 opts.trivial_merges_only = 1;
680 opts.merge = 1;
681 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
682 trees[nr_trees] = parse_tree_indirect(common);
683 if (!trees[nr_trees++])
684 return -1;
685 trees[nr_trees] = parse_tree_indirect(head);
686 if (!trees[nr_trees++])
687 return -1;
688 trees[nr_trees] = parse_tree_indirect(one);
689 if (!trees[nr_trees++])
690 return -1;
691 opts.fn = threeway_merge;
692 cache_tree_free(&the_index.cache_tree);
693 for (i = 0; i < nr_trees; i++) {
694 parse_tree(trees[i]);
695 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
697 if (unpack_trees(nr_trees, t, &opts))
698 return -1;
699 return 0;
702 static void write_tree_trivial(struct object_id *oid)
704 if (write_index_as_tree(oid, &the_index, get_index_file(), 0, NULL))
705 die(_("git write-tree failed to write a tree"));
708 static int try_merge_strategy(const char *strategy, struct commit_list *common,
709 struct commit_list *remoteheads,
710 struct commit *head)
712 const char *head_arg = "HEAD";
714 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
715 SKIP_IF_UNCHANGED, 0, NULL, NULL,
716 NULL) < 0)
717 return error(_("Unable to write index."));
719 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
720 !strcmp(strategy, "ort")) {
721 struct lock_file lock = LOCK_INIT;
722 int clean, x;
723 struct commit *result;
724 struct commit_list *reversed = NULL;
725 struct merge_options o;
726 struct commit_list *j;
728 if (remoteheads->next) {
729 error(_("Not handling anything other than two heads merge."));
730 return 2;
733 init_merge_options(&o, the_repository);
734 if (!strcmp(strategy, "subtree"))
735 o.subtree_shift = "";
737 o.show_rename_progress =
738 show_progress == -1 ? isatty(2) : show_progress;
740 for (x = 0; x < xopts.nr; x++)
741 if (parse_merge_opt(&o, xopts.v[x]))
742 die(_("unknown strategy option: -X%s"), xopts.v[x]);
744 o.branch1 = head_arg;
745 o.branch2 = merge_remote_util(remoteheads->item)->name;
747 for (j = common; j; j = j->next)
748 commit_list_insert(j->item, &reversed);
750 repo_hold_locked_index(the_repository, &lock,
751 LOCK_DIE_ON_ERROR);
752 if (!strcmp(strategy, "ort"))
753 clean = merge_ort_recursive(&o, head, remoteheads->item,
754 reversed, &result);
755 else
756 clean = merge_recursive(&o, head, remoteheads->item,
757 reversed, &result);
758 if (clean < 0) {
759 rollback_lock_file(&lock);
760 return 2;
762 if (write_locked_index(&the_index, &lock,
763 COMMIT_LOCK | SKIP_IF_UNCHANGED))
764 die(_("unable to write %s"), get_index_file());
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_index.cache_nr; i++)
786 if (ce_stage(the_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 '%c' 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 = get_index_file();
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_index);
862 read_index_from(&the_index, index_file, get_git_dir());
863 strbuf_addbuf(&msg, &merge_msg);
864 if (squash)
865 BUG("the control must not reach here under --squash");
866 if (0 < option_edit) {
867 strbuf_addch(&msg, '\n');
868 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
869 wt_status_append_cut_line(&msg);
870 strbuf_commented_addf(&msg, comment_line_char, "\n");
872 strbuf_commented_addf(&msg, comment_line_char,
873 _(merge_editor_comment));
874 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
875 strbuf_commented_addf(&msg, comment_line_char,
876 _(scissors_editor_comment));
877 else
878 strbuf_commented_addf(&msg, comment_line_char,
879 _(no_scissors_editor_comment), comment_line_char);
881 if (signoff)
882 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
883 write_merge_heads(remoteheads);
884 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
885 if (run_commit_hook(0 < option_edit, get_index_file(), NULL,
886 "prepare-commit-msg",
887 git_path_merge_msg(the_repository), "merge", NULL))
888 abort_commit(remoteheads, NULL);
889 if (0 < option_edit) {
890 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
891 abort_commit(remoteheads, NULL);
894 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
895 NULL, "commit-msg",
896 git_path_merge_msg(the_repository), NULL))
897 abort_commit(remoteheads, NULL);
899 read_merge_msg(&msg);
900 cleanup_message(&msg, cleanup_mode, 0);
901 if (!msg.len)
902 abort_commit(remoteheads, _("Empty commit message."));
903 strbuf_release(&merge_msg);
904 strbuf_addbuf(&merge_msg, &msg);
905 strbuf_release(&msg);
908 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
910 struct object_id result_tree, result_commit;
911 struct commit_list *parents, **pptr = &parents;
913 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
914 SKIP_IF_UNCHANGED, 0, NULL, NULL,
915 NULL) < 0)
916 return error(_("Unable to write index."));
918 write_tree_trivial(&result_tree);
919 printf(_("Wonderful.\n"));
920 pptr = commit_list_append(head, pptr);
921 pptr = commit_list_append(remoteheads->item, pptr);
922 prepare_to_commit(remoteheads);
923 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
924 &result_commit, NULL, sign_commit))
925 die(_("failed to write commit object"));
926 finish(head, remoteheads, &result_commit, "In-index merge");
927 remove_merge_branch_state(the_repository);
928 return 0;
931 static int finish_automerge(struct commit *head,
932 int head_subsumed,
933 struct commit_list *common,
934 struct commit_list *remoteheads,
935 struct object_id *result_tree,
936 const char *wt_strategy)
938 struct commit_list *parents = NULL;
939 struct strbuf buf = STRBUF_INIT;
940 struct object_id result_commit;
942 write_tree_trivial(result_tree);
943 free_commit_list(common);
944 parents = remoteheads;
945 if (!head_subsumed || fast_forward == FF_NO)
946 commit_list_insert(head, &parents);
947 prepare_to_commit(remoteheads);
948 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
949 &result_commit, NULL, sign_commit))
950 die(_("failed to write commit object"));
951 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
952 finish(head, remoteheads, &result_commit, buf.buf);
953 strbuf_release(&buf);
954 remove_merge_branch_state(the_repository);
955 return 0;
958 static int suggest_conflicts(void)
960 const char *filename;
961 FILE *fp;
962 struct strbuf msgbuf = STRBUF_INIT;
964 filename = git_path_merge_msg(the_repository);
965 fp = xfopen(filename, "a");
968 * We can't use cleanup_mode because if we're not using the editor,
969 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
970 * though the message is meant to be processed later by git-commit.
971 * Thus, we will get the cleanup mode which is returned when we _are_
972 * using an editor.
974 append_conflicts_hint(&the_index, &msgbuf,
975 get_cleanup_mode(cleanup_arg, 1));
976 fputs(msgbuf.buf, fp);
977 strbuf_release(&msgbuf);
978 fclose(fp);
979 repo_rerere(the_repository, allow_rerere_auto);
980 printf(_("Automatic merge failed; "
981 "fix conflicts and then commit the result.\n"));
982 return 1;
985 static int evaluate_result(void)
987 int cnt = 0;
988 struct rev_info rev;
990 /* Check how many files differ. */
991 repo_init_revisions(the_repository, &rev, "");
992 setup_revisions(0, NULL, &rev, NULL);
993 rev.diffopt.output_format |=
994 DIFF_FORMAT_CALLBACK;
995 rev.diffopt.format_callback = count_diff_files;
996 rev.diffopt.format_callback_data = &cnt;
997 run_diff_files(&rev, 0);
1000 * Check how many unmerged entries are
1001 * there.
1003 cnt += count_unmerged_entries();
1005 release_revisions(&rev);
1006 return cnt;
1010 * Pretend as if the user told us to merge with the remote-tracking
1011 * branch we have for the upstream of the current branch
1013 static int setup_with_upstream(const char ***argv)
1015 struct branch *branch = branch_get(NULL);
1016 int i;
1017 const char **args;
1019 if (!branch)
1020 die(_("No current branch."));
1021 if (!branch->remote_name)
1022 die(_("No remote for the current branch."));
1023 if (!branch->merge_nr)
1024 die(_("No default upstream defined for the current branch."));
1026 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1027 for (i = 0; i < branch->merge_nr; i++) {
1028 if (!branch->merge[i]->dst)
1029 die(_("No remote-tracking branch for %s from %s"),
1030 branch->merge[i]->src, branch->remote_name);
1031 args[i] = branch->merge[i]->dst;
1033 args[i] = NULL;
1034 *argv = args;
1035 return i;
1038 static void write_merge_heads(struct commit_list *remoteheads)
1040 struct commit_list *j;
1041 struct strbuf buf = STRBUF_INIT;
1043 for (j = remoteheads; j; j = j->next) {
1044 struct object_id *oid;
1045 struct commit *c = j->item;
1046 struct merge_remote_desc *desc;
1048 desc = merge_remote_util(c);
1049 if (desc && desc->obj) {
1050 oid = &desc->obj->oid;
1051 } else {
1052 oid = &c->object.oid;
1054 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1056 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1058 strbuf_reset(&buf);
1059 if (fast_forward == FF_NO)
1060 strbuf_addstr(&buf, "no-ff");
1061 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1062 strbuf_release(&buf);
1065 static void write_merge_state(struct commit_list *remoteheads)
1067 write_merge_heads(remoteheads);
1068 strbuf_addch(&merge_msg, '\n');
1069 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1070 merge_msg.len);
1073 static int default_edit_option(void)
1075 static const char name[] = "GIT_MERGE_AUTOEDIT";
1076 const char *e = getenv(name);
1077 struct stat st_stdin, st_stdout;
1079 if (have_message)
1080 /* an explicit -m msg without --[no-]edit */
1081 return 0;
1083 if (e) {
1084 int v = git_parse_maybe_bool(e);
1085 if (v < 0)
1086 die(_("Bad value '%s' in environment '%s'"), e, name);
1087 return v;
1090 /* Use editor if stdin and stdout are the same and is a tty */
1091 return (!fstat(0, &st_stdin) &&
1092 !fstat(1, &st_stdout) &&
1093 isatty(0) && isatty(1) &&
1094 st_stdin.st_dev == st_stdout.st_dev &&
1095 st_stdin.st_ino == st_stdout.st_ino &&
1096 st_stdin.st_mode == st_stdout.st_mode);
1099 static struct commit_list *reduce_parents(struct commit *head_commit,
1100 int *head_subsumed,
1101 struct commit_list *remoteheads)
1103 struct commit_list *parents, **remotes;
1106 * Is the current HEAD reachable from another commit being
1107 * merged? If so we do not want to record it as a parent of
1108 * the resulting merge, unless --no-ff is given. We will flip
1109 * this variable to 0 when we find HEAD among the independent
1110 * tips being merged.
1112 *head_subsumed = 1;
1114 /* Find what parents to record by checking independent ones. */
1115 parents = reduce_heads(remoteheads);
1116 free_commit_list(remoteheads);
1118 remoteheads = NULL;
1119 remotes = &remoteheads;
1120 while (parents) {
1121 struct commit *commit = pop_commit(&parents);
1122 if (commit == head_commit)
1123 *head_subsumed = 0;
1124 else
1125 remotes = &commit_list_insert(commit, remotes)->next;
1127 return remoteheads;
1130 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1132 struct fmt_merge_msg_opts opts;
1134 memset(&opts, 0, sizeof(opts));
1135 opts.add_title = !have_message;
1136 opts.shortlog_len = shortlog_len;
1137 opts.credit_people = (0 < option_edit);
1138 opts.into_name = into_name;
1140 fmt_merge_msg(merge_names, merge_msg, &opts);
1141 if (merge_msg->len)
1142 strbuf_setlen(merge_msg, merge_msg->len - 1);
1145 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1147 const char *filename;
1148 int fd, pos, npos;
1149 struct strbuf fetch_head_file = STRBUF_INIT;
1150 const unsigned hexsz = the_hash_algo->hexsz;
1152 if (!merge_names)
1153 merge_names = &fetch_head_file;
1155 filename = git_path_fetch_head(the_repository);
1156 fd = xopen(filename, O_RDONLY);
1158 if (strbuf_read(merge_names, fd, 0) < 0)
1159 die_errno(_("could not read '%s'"), filename);
1160 if (close(fd) < 0)
1161 die_errno(_("could not close '%s'"), filename);
1163 for (pos = 0; pos < merge_names->len; pos = npos) {
1164 struct object_id oid;
1165 char *ptr;
1166 struct commit *commit;
1168 ptr = strchr(merge_names->buf + pos, '\n');
1169 if (ptr)
1170 npos = ptr - merge_names->buf + 1;
1171 else
1172 npos = merge_names->len;
1174 if (npos - pos < hexsz + 2 ||
1175 get_oid_hex(merge_names->buf + pos, &oid))
1176 commit = NULL; /* bad */
1177 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1178 continue; /* not-for-merge */
1179 else {
1180 char saved = merge_names->buf[pos + hexsz];
1181 merge_names->buf[pos + hexsz] = '\0';
1182 commit = get_merge_parent(merge_names->buf + pos);
1183 merge_names->buf[pos + hexsz] = saved;
1185 if (!commit) {
1186 if (ptr)
1187 *ptr = '\0';
1188 die(_("not something we can merge in %s: %s"),
1189 filename, merge_names->buf + pos);
1191 remotes = &commit_list_insert(commit, remotes)->next;
1194 if (merge_names == &fetch_head_file)
1195 strbuf_release(&fetch_head_file);
1198 static struct commit_list *collect_parents(struct commit *head_commit,
1199 int *head_subsumed,
1200 int argc, const char **argv,
1201 struct strbuf *merge_msg)
1203 int i;
1204 struct commit_list *remoteheads = NULL;
1205 struct commit_list **remotes = &remoteheads;
1206 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1208 if (merge_msg && (!have_message || shortlog_len))
1209 autogen = &merge_names;
1211 if (head_commit)
1212 remotes = &commit_list_insert(head_commit, remotes)->next;
1214 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1215 handle_fetch_head(remotes, autogen);
1216 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1217 } else {
1218 for (i = 0; i < argc; i++) {
1219 struct commit *commit = get_merge_parent(argv[i]);
1220 if (!commit)
1221 help_unknown_ref(argv[i], "merge",
1222 _("not something we can merge"));
1223 remotes = &commit_list_insert(commit, remotes)->next;
1225 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1226 if (autogen) {
1227 struct commit_list *p;
1228 for (p = remoteheads; p; p = p->next)
1229 merge_name(merge_remote_util(p->item)->name, autogen);
1233 if (autogen) {
1234 prepare_merge_message(autogen, merge_msg);
1235 strbuf_release(autogen);
1238 return remoteheads;
1241 static int merging_a_throwaway_tag(struct commit *commit)
1243 char *tag_ref;
1244 struct object_id oid;
1245 int is_throwaway_tag = 0;
1247 /* Are we merging a tag? */
1248 if (!merge_remote_util(commit) ||
1249 !merge_remote_util(commit)->obj ||
1250 merge_remote_util(commit)->obj->type != OBJ_TAG)
1251 return is_throwaway_tag;
1254 * Now we know we are merging a tag object. Are we downstream
1255 * and following the tags from upstream? If so, we must have
1256 * the tag object pointed at by "refs/tags/$T" where $T is the
1257 * tagname recorded in the tag object. We want to allow such
1258 * a "just to catch up" merge to fast-forward.
1260 * Otherwise, we are playing an integrator's role, making a
1261 * merge with a throw-away tag from a contributor with
1262 * something like "git pull $contributor $signed_tag".
1263 * We want to forbid such a merge from fast-forwarding
1264 * by default; otherwise we would not keep the signature
1265 * anywhere.
1267 tag_ref = xstrfmt("refs/tags/%s",
1268 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1269 if (!read_ref(tag_ref, &oid) &&
1270 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1271 is_throwaway_tag = 0;
1272 else
1273 is_throwaway_tag = 1;
1274 free(tag_ref);
1275 return is_throwaway_tag;
1278 int cmd_merge(int argc, const char **argv, const char *prefix)
1280 struct object_id result_tree, stash, head_oid;
1281 struct commit *head_commit;
1282 struct strbuf buf = STRBUF_INIT;
1283 int i, ret = 0, head_subsumed;
1284 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1285 struct commit_list *common = NULL;
1286 const char *best_strategy = NULL, *wt_strategy = NULL;
1287 struct commit_list *remoteheads = NULL, *p;
1288 void *branch_to_free;
1289 int orig_argc = argc;
1291 if (argc == 2 && !strcmp(argv[1], "-h"))
1292 usage_with_options(builtin_merge_usage, builtin_merge_options);
1294 prepare_repo_settings(the_repository);
1295 the_repository->settings.command_requires_full_index = 0;
1298 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1299 * current branch.
1301 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1302 if (branch)
1303 skip_prefix(branch, "refs/heads/", &branch);
1305 if (!pull_twohead) {
1306 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1307 if (default_strategy && !strcmp(default_strategy, "ort"))
1308 pull_twohead = "ort";
1311 init_diff_ui_defaults();
1312 git_config(git_merge_config, NULL);
1314 if (!branch || is_null_oid(&head_oid))
1315 head_commit = NULL;
1316 else
1317 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1319 if (branch_mergeoptions)
1320 parse_branch_merge_options(branch_mergeoptions);
1321 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1322 builtin_merge_usage, 0);
1323 if (shortlog_len < 0)
1324 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1326 if (verbosity < 0 && show_progress == -1)
1327 show_progress = 0;
1329 if (abort_current_merge) {
1330 int nargc = 2;
1331 const char *nargv[] = {"reset", "--merge", NULL};
1332 struct strbuf stash_oid = STRBUF_INIT;
1334 if (orig_argc != 2)
1335 usage_msg_opt(_("--abort expects no arguments"),
1336 builtin_merge_usage, builtin_merge_options);
1338 if (!file_exists(git_path_merge_head(the_repository)))
1339 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1341 if (read_oneliner(&stash_oid, git_path_merge_autostash(the_repository),
1342 READ_ONELINER_SKIP_IF_EMPTY))
1343 unlink(git_path_merge_autostash(the_repository));
1345 /* Invoke 'git reset --merge' */
1346 ret = cmd_reset(nargc, nargv, prefix);
1348 if (stash_oid.len)
1349 apply_autostash_oid(stash_oid.buf);
1351 strbuf_release(&stash_oid);
1352 goto done;
1355 if (quit_current_merge) {
1356 if (orig_argc != 2)
1357 usage_msg_opt(_("--quit expects no arguments"),
1358 builtin_merge_usage,
1359 builtin_merge_options);
1361 remove_merge_branch_state(the_repository);
1362 goto done;
1365 if (continue_current_merge) {
1366 int nargc = 1;
1367 const char *nargv[] = {"commit", NULL};
1369 if (orig_argc != 2)
1370 usage_msg_opt(_("--continue expects no arguments"),
1371 builtin_merge_usage, builtin_merge_options);
1373 if (!file_exists(git_path_merge_head(the_repository)))
1374 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1376 /* Invoke 'git commit' */
1377 ret = cmd_commit(nargc, nargv, prefix);
1378 goto done;
1381 if (repo_read_index_unmerged(the_repository))
1382 die_resolve_conflict("merge");
1384 if (file_exists(git_path_merge_head(the_repository))) {
1386 * There is no unmerged entry, don't advise 'git
1387 * add/rm <file>', just 'git commit'.
1389 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1390 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1391 "Please, commit your changes before you merge."));
1392 else
1393 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1395 if (ref_exists("CHERRY_PICK_HEAD")) {
1396 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1397 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1398 "Please, commit your changes before you merge."));
1399 else
1400 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1402 resolve_undo_clear_index(&the_index);
1404 if (option_edit < 0)
1405 option_edit = default_edit_option();
1407 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1409 if (verbosity < 0)
1410 show_diffstat = 0;
1412 if (squash) {
1413 if (fast_forward == FF_NO)
1414 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1415 if (option_commit > 0)
1416 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1418 * squash can now silently disable option_commit - this is not
1419 * a problem as it is only overriding the default, not a user
1420 * supplied option.
1422 option_commit = 0;
1425 if (option_commit < 0)
1426 option_commit = 1;
1428 if (!argc) {
1429 if (default_to_upstream)
1430 argc = setup_with_upstream(&argv);
1431 else
1432 die(_("No commit specified and merge.defaultToUpstream not set."));
1433 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1434 argv[0] = "@{-1}";
1437 if (!argc)
1438 usage_with_options(builtin_merge_usage,
1439 builtin_merge_options);
1441 if (!head_commit) {
1443 * If the merged head is a valid one there is no reason
1444 * to forbid "git merge" into a branch yet to be born.
1445 * We do the same for "git pull".
1447 struct object_id *remote_head_oid;
1448 if (squash)
1449 die(_("Squash commit into empty head not supported yet"));
1450 if (fast_forward == FF_NO)
1451 die(_("Non-fast-forward commit does not make sense into "
1452 "an empty head"));
1453 remoteheads = collect_parents(head_commit, &head_subsumed,
1454 argc, argv, NULL);
1455 if (!remoteheads)
1456 die(_("%s - not something we can merge"), argv[0]);
1457 if (remoteheads->next)
1458 die(_("Can merge only exactly one commit into empty head"));
1460 if (verify_signatures)
1461 verify_merge_signature(remoteheads->item, verbosity,
1462 check_trust_level);
1464 remote_head_oid = &remoteheads->item->object.oid;
1465 read_empty(remote_head_oid);
1466 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1467 UPDATE_REFS_DIE_ON_ERR);
1468 goto done;
1472 * All the rest are the commits being merged; prepare
1473 * the standard merge summary message to be appended
1474 * to the given message.
1476 remoteheads = collect_parents(head_commit, &head_subsumed,
1477 argc, argv, &merge_msg);
1479 if (!head_commit || !argc)
1480 usage_with_options(builtin_merge_usage,
1481 builtin_merge_options);
1483 if (verify_signatures) {
1484 for (p = remoteheads; p; p = p->next) {
1485 verify_merge_signature(p->item, verbosity,
1486 check_trust_level);
1490 strbuf_addstr(&buf, "merge");
1491 for (p = remoteheads; p; p = p->next)
1492 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1493 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1494 strbuf_reset(&buf);
1496 for (p = remoteheads; p; p = p->next) {
1497 struct commit *commit = p->item;
1498 strbuf_addf(&buf, "GITHEAD_%s",
1499 oid_to_hex(&commit->object.oid));
1500 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1501 strbuf_reset(&buf);
1502 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1503 fast_forward = FF_NO;
1506 if (!use_strategies && !pull_twohead &&
1507 remoteheads && !remoteheads->next) {
1508 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1509 if (default_strategy)
1510 append_strategy(get_strategy(default_strategy));
1512 if (!use_strategies) {
1513 if (!remoteheads)
1514 ; /* already up-to-date */
1515 else if (!remoteheads->next)
1516 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1517 else
1518 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1521 for (i = 0; i < use_strategies_nr; i++) {
1522 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1523 fast_forward = FF_NO;
1524 if (use_strategies[i]->attr & NO_TRIVIAL)
1525 allow_trivial = 0;
1528 if (!remoteheads)
1529 ; /* already up-to-date */
1530 else if (!remoteheads->next)
1531 common = repo_get_merge_bases(the_repository, head_commit,
1532 remoteheads->item);
1533 else {
1534 struct commit_list *list = remoteheads;
1535 commit_list_insert(head_commit, &list);
1536 common = get_octopus_merge_bases(list);
1537 free(list);
1540 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1541 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1543 if (remoteheads && !common) {
1544 /* No common ancestors found. */
1545 if (!allow_unrelated_histories)
1546 die(_("refusing to merge unrelated histories"));
1547 /* otherwise, we need a real merge. */
1548 } else if (!remoteheads ||
1549 (!remoteheads->next && !common->next &&
1550 common->item == remoteheads->item)) {
1552 * If head can reach all the merge then we are up to date.
1553 * but first the most common case of merging one remote.
1555 finish_up_to_date();
1556 goto done;
1557 } else if (fast_forward != FF_NO && !remoteheads->next &&
1558 !common->next &&
1559 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1560 /* Again the most common case of merging one remote. */
1561 const char *msg = have_message ?
1562 "Fast-forward (no commit created; -m option ignored)" :
1563 "Fast-forward";
1564 struct commit *commit;
1566 if (verbosity >= 0) {
1567 printf(_("Updating %s..%s\n"),
1568 repo_find_unique_abbrev(the_repository, &head_commit->object.oid,
1569 DEFAULT_ABBREV),
1570 repo_find_unique_abbrev(the_repository, &remoteheads->item->object.oid,
1571 DEFAULT_ABBREV));
1573 commit = remoteheads->item;
1574 if (!commit) {
1575 ret = 1;
1576 goto done;
1579 if (autostash)
1580 create_autostash(the_repository,
1581 git_path_merge_autostash(the_repository));
1582 if (checkout_fast_forward(the_repository,
1583 &head_commit->object.oid,
1584 &commit->object.oid,
1585 overwrite_ignore)) {
1586 apply_autostash(git_path_merge_autostash(the_repository));
1587 ret = 1;
1588 goto done;
1591 finish(head_commit, remoteheads, &commit->object.oid, msg);
1592 remove_merge_branch_state(the_repository);
1593 goto done;
1594 } else if (!remoteheads->next && common->next)
1597 * We are not doing octopus and not fast-forward. Need
1598 * a real merge.
1600 else if (!remoteheads->next && !common->next && option_commit) {
1602 * We are not doing octopus, not fast-forward, and have
1603 * only one common.
1605 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
1606 if (allow_trivial && fast_forward != FF_ONLY) {
1608 * Must first ensure that index matches HEAD before
1609 * attempting a trivial merge.
1611 struct tree *head_tree = repo_get_commit_tree(the_repository,
1612 head_commit);
1613 struct strbuf sb = STRBUF_INIT;
1615 if (repo_index_has_changes(the_repository, head_tree,
1616 &sb)) {
1617 error(_("Your local changes to the following files would be overwritten by merge:\n %s"),
1618 sb.buf);
1619 strbuf_release(&sb);
1620 ret = 2;
1621 goto done;
1624 /* See if it is really trivial. */
1625 git_committer_info(IDENT_STRICT);
1626 printf(_("Trying really trivial in-index merge...\n"));
1627 if (!read_tree_trivial(&common->item->object.oid,
1628 &head_commit->object.oid,
1629 &remoteheads->item->object.oid)) {
1630 ret = merge_trivial(head_commit, remoteheads);
1631 goto done;
1633 printf(_("Nope.\n"));
1635 } else {
1637 * An octopus. If we can reach all the remote we are up
1638 * to date.
1640 int up_to_date = 1;
1641 struct commit_list *j;
1643 for (j = remoteheads; j; j = j->next) {
1644 struct commit_list *common_one;
1647 * Here we *have* to calculate the individual
1648 * merge_bases again, otherwise "git merge HEAD^
1649 * HEAD^^" would be missed.
1651 common_one = repo_get_merge_bases(the_repository,
1652 head_commit,
1653 j->item);
1654 if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1655 up_to_date = 0;
1656 break;
1659 if (up_to_date) {
1660 finish_up_to_date();
1661 goto done;
1665 if (fast_forward == FF_ONLY)
1666 die_ff_impossible();
1668 if (autostash)
1669 create_autostash(the_repository,
1670 git_path_merge_autostash(the_repository));
1672 /* We are going to make a new commit. */
1673 git_committer_info(IDENT_STRICT);
1676 * At this point, we need a real merge. No matter what strategy
1677 * we use, it would operate on the index, possibly affecting the
1678 * working tree, and when resolved cleanly, have the desired
1679 * tree in the index -- this means that the index must be in
1680 * sync with the head commit. The strategies are responsible
1681 * to ensure this.
1683 * Stash away the local changes so that we can try more than one
1684 * and/or recover from merge strategies bailing while leaving the
1685 * index and working tree polluted.
1687 if (save_state(&stash))
1688 oidclr(&stash);
1690 for (i = 0; i < use_strategies_nr; i++) {
1691 int ret, cnt;
1692 if (i) {
1693 printf(_("Rewinding the tree to pristine...\n"));
1694 restore_state(&head_commit->object.oid, &stash);
1696 if (use_strategies_nr != 1)
1697 printf(_("Trying merge strategy %s...\n"),
1698 use_strategies[i]->name);
1700 * Remember which strategy left the state in the working
1701 * tree.
1703 wt_strategy = use_strategies[i]->name;
1705 ret = try_merge_strategy(wt_strategy,
1706 common, remoteheads,
1707 head_commit);
1709 * The backend exits with 1 when conflicts are
1710 * left to be resolved, with 2 when it does not
1711 * handle the given merge at all.
1713 if (ret < 2) {
1714 if (!ret) {
1716 * This strategy worked; no point in trying
1717 * another.
1719 merge_was_ok = 1;
1720 best_strategy = wt_strategy;
1721 break;
1723 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1724 if (best_cnt <= 0 || cnt <= best_cnt) {
1725 best_strategy = wt_strategy;
1726 best_cnt = cnt;
1732 * If we have a resulting tree, that means the strategy module
1733 * auto resolved the merge cleanly.
1735 if (merge_was_ok && option_commit) {
1736 automerge_was_ok = 1;
1737 ret = finish_automerge(head_commit, head_subsumed,
1738 common, remoteheads,
1739 &result_tree, wt_strategy);
1740 goto done;
1744 * Pick the result from the best strategy and have the user fix
1745 * it up.
1747 if (!best_strategy) {
1748 restore_state(&head_commit->object.oid, &stash);
1749 if (use_strategies_nr > 1)
1750 fprintf(stderr,
1751 _("No merge strategy handled the merge.\n"));
1752 else
1753 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1754 use_strategies[0]->name);
1755 apply_autostash(git_path_merge_autostash(the_repository));
1756 ret = 2;
1757 goto done;
1758 } else if (best_strategy == wt_strategy)
1759 ; /* We already have its result in the working tree. */
1760 else {
1761 printf(_("Rewinding the tree to pristine...\n"));
1762 restore_state(&head_commit->object.oid, &stash);
1763 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1764 best_strategy);
1765 try_merge_strategy(best_strategy, common, remoteheads,
1766 head_commit);
1769 if (squash) {
1770 finish(head_commit, remoteheads, NULL, NULL);
1772 git_test_write_commit_graph_or_die();
1773 } else
1774 write_merge_state(remoteheads);
1776 if (merge_was_ok)
1777 fprintf(stderr, _("Automatic merge went well; "
1778 "stopped before committing as requested\n"));
1779 else
1780 ret = suggest_conflicts();
1781 if (autostash)
1782 printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1784 done:
1785 if (!automerge_was_ok) {
1786 free_commit_list(common);
1787 free_commit_list(remoteheads);
1789 strbuf_release(&buf);
1790 free(branch_to_free);
1791 discard_index(&the_index);
1792 return ret;