Merge branch 'ab/t7610-timeout'
[alt-git.git] / builtin / merge.c
blobb3f75f55c8a82db92f31b7f32a503eb70357e9c8
1 /*
2 * Builtin "git merge"
4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
7 */
9 #define USE_THE_INDEX_COMPATIBILITY_MACROS
10 #include "cache.h"
11 #include "config.h"
12 #include "parse-options.h"
13 #include "builtin.h"
14 #include "lockfile.h"
15 #include "run-command.h"
16 #include "hook.h"
17 #include "diff.h"
18 #include "diff-merges.h"
19 #include "refs.h"
20 #include "refspec.h"
21 #include "commit.h"
22 #include "diffcore.h"
23 #include "revision.h"
24 #include "unpack-trees.h"
25 #include "cache-tree.h"
26 #include "dir.h"
27 #include "utf8.h"
28 #include "log-tree.h"
29 #include "color.h"
30 #include "rerere.h"
31 #include "help.h"
32 #include "merge-recursive.h"
33 #include "merge-ort-wrappers.h"
34 #include "resolve-undo.h"
35 #include "remote.h"
36 #include "fmt-merge-msg.h"
37 #include "gpg-interface.h"
38 #include "sequencer.h"
39 #include "string-list.h"
40 #include "packfile.h"
41 #include "tag.h"
42 #include "alias.h"
43 #include "branch.h"
44 #include "commit-reach.h"
45 #include "wt-status.h"
46 #include "commit-graph.h"
48 #define DEFAULT_TWOHEAD (1<<0)
49 #define DEFAULT_OCTOPUS (1<<1)
50 #define NO_FAST_FORWARD (1<<2)
51 #define NO_TRIVIAL (1<<3)
53 struct strategy {
54 const char *name;
55 unsigned attr;
58 static const char * const builtin_merge_usage[] = {
59 N_("git merge [<options>] [<commit>...]"),
60 "git merge --abort",
61 "git merge --continue",
62 NULL
65 static int show_diffstat = 1, shortlog_len = -1, squash;
66 static int option_commit = -1;
67 static int option_edit = -1;
68 static int allow_trivial = 1, have_message, verify_signatures;
69 static int check_trust_level = 1;
70 static int overwrite_ignore = 1;
71 static struct strbuf merge_msg = STRBUF_INIT;
72 static struct strategy **use_strategies;
73 static size_t use_strategies_nr, use_strategies_alloc;
74 static const char **xopts;
75 static size_t xopts_nr, xopts_alloc;
76 static const char *branch;
77 static char *branch_mergeoptions;
78 static int verbosity;
79 static int allow_rerere_auto;
80 static int abort_current_merge;
81 static int quit_current_merge;
82 static int continue_current_merge;
83 static int allow_unrelated_histories;
84 static int show_progress = -1;
85 static int default_to_upstream = 1;
86 static int signoff;
87 static const char *sign_commit;
88 static int autostash;
89 static int no_verify;
90 static char *into_name;
92 static struct strategy all_strategy[] = {
93 { "recursive", NO_TRIVIAL },
94 { "octopus", DEFAULT_OCTOPUS },
95 { "ort", DEFAULT_TWOHEAD | NO_TRIVIAL },
96 { "resolve", 0 },
97 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
98 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
101 static const char *pull_twohead, *pull_octopus;
103 enum ff_type {
104 FF_NO,
105 FF_ALLOW,
106 FF_ONLY
109 static enum ff_type fast_forward = FF_ALLOW;
111 static const char *cleanup_arg;
112 static enum commit_msg_cleanup_mode cleanup_mode;
114 static int option_parse_message(const struct option *opt,
115 const char *arg, int unset)
117 struct strbuf *buf = opt->value;
119 if (unset)
120 strbuf_setlen(buf, 0);
121 else if (arg) {
122 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
123 have_message = 1;
124 } else
125 return error(_("switch `m' requires a value"));
126 return 0;
129 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
130 const struct option *opt,
131 const char *arg_not_used,
132 int unset)
134 struct strbuf *buf = opt->value;
135 const char *arg;
137 BUG_ON_OPT_ARG(arg_not_used);
138 if (unset)
139 BUG("-F cannot be negated");
141 if (ctx->opt) {
142 arg = ctx->opt;
143 ctx->opt = NULL;
144 } else if (ctx->argc > 1) {
145 ctx->argc--;
146 arg = *++ctx->argv;
147 } else
148 return error(_("option `%s' requires a value"), opt->long_name);
150 if (buf->len)
151 strbuf_addch(buf, '\n');
152 if (ctx->prefix && !is_absolute_path(arg))
153 arg = prefix_filename(ctx->prefix, arg);
154 if (strbuf_read_file(buf, arg, 0) < 0)
155 return error(_("could not read file '%s'"), arg);
156 have_message = 1;
158 return 0;
161 static struct strategy *get_strategy(const char *name)
163 int i;
164 struct strategy *ret;
165 static struct cmdnames main_cmds, other_cmds;
166 static int loaded;
167 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
169 if (!name)
170 return NULL;
172 if (default_strategy &&
173 !strcmp(default_strategy, "ort") &&
174 !strcmp(name, "recursive")) {
175 name = "ort";
178 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
179 if (!strcmp(name, all_strategy[i].name))
180 return &all_strategy[i];
182 if (!loaded) {
183 struct cmdnames not_strategies;
184 loaded = 1;
186 memset(&not_strategies, 0, sizeof(struct cmdnames));
187 load_command_list("git-merge-", &main_cmds, &other_cmds);
188 for (i = 0; i < main_cmds.cnt; i++) {
189 int j, found = 0;
190 struct cmdname *ent = main_cmds.names[i];
191 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
192 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
193 && !all_strategy[j].name[ent->len])
194 found = 1;
195 if (!found)
196 add_cmdname(&not_strategies, ent->name, ent->len);
198 exclude_cmds(&main_cmds, &not_strategies);
200 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
201 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
202 fprintf(stderr, _("Available strategies are:"));
203 for (i = 0; i < main_cmds.cnt; i++)
204 fprintf(stderr, " %s", main_cmds.names[i]->name);
205 fprintf(stderr, ".\n");
206 if (other_cmds.cnt) {
207 fprintf(stderr, _("Available custom strategies are:"));
208 for (i = 0; i < other_cmds.cnt; i++)
209 fprintf(stderr, " %s", other_cmds.names[i]->name);
210 fprintf(stderr, ".\n");
212 exit(1);
215 CALLOC_ARRAY(ret, 1);
216 ret->name = xstrdup(name);
217 ret->attr = NO_TRIVIAL;
218 return ret;
221 static void append_strategy(struct strategy *s)
223 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
224 use_strategies[use_strategies_nr++] = s;
227 static int option_parse_strategy(const struct option *opt,
228 const char *name, int unset)
230 if (unset)
231 return 0;
233 append_strategy(get_strategy(name));
234 return 0;
237 static int option_parse_x(const struct option *opt,
238 const char *arg, int unset)
240 if (unset)
241 return 0;
243 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
244 xopts[xopts_nr++] = xstrdup(arg);
245 return 0;
248 static int option_parse_n(const struct option *opt,
249 const char *arg, int unset)
251 BUG_ON_OPT_ARG(arg);
252 show_diffstat = unset;
253 return 0;
256 static struct option builtin_merge_options[] = {
257 OPT_CALLBACK_F('n', NULL, NULL, NULL,
258 N_("do not show a diffstat at the end of the merge"),
259 PARSE_OPT_NOARG, option_parse_n),
260 OPT_BOOL(0, "stat", &show_diffstat,
261 N_("show a diffstat at the end of the merge")),
262 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
263 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
264 N_("add (at most <n>) entries from shortlog to merge commit message"),
265 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
266 OPT_BOOL(0, "squash", &squash,
267 N_("create a single commit instead of doing a merge")),
268 OPT_BOOL(0, "commit", &option_commit,
269 N_("perform a commit if the merge succeeds (default)")),
270 OPT_BOOL('e', "edit", &option_edit,
271 N_("edit message before committing")),
272 OPT_CLEANUP(&cleanup_arg),
273 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
274 OPT_SET_INT_F(0, "ff-only", &fast_forward,
275 N_("abort if fast-forward is not possible"),
276 FF_ONLY, PARSE_OPT_NONEG),
277 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
278 OPT_BOOL(0, "verify-signatures", &verify_signatures,
279 N_("verify that the named commit has a valid GPG signature")),
280 OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
281 N_("merge strategy to use"), option_parse_strategy),
282 OPT_CALLBACK('X', "strategy-option", &xopts, N_("option=value"),
283 N_("option for selected merge strategy"), option_parse_x),
284 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
285 N_("merge commit message (for a non-fast-forward merge)"),
286 option_parse_message),
287 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
288 N_("read message from file"), PARSE_OPT_NONEG,
289 NULL, 0, option_read_message },
290 OPT_STRING(0, "into-name", &into_name, N_("name"),
291 N_("use <name> instead of the real target")),
292 OPT__VERBOSITY(&verbosity),
293 OPT_BOOL(0, "abort", &abort_current_merge,
294 N_("abort the current in-progress merge")),
295 OPT_BOOL(0, "quit", &quit_current_merge,
296 N_("--abort but leave index and working tree alone")),
297 OPT_BOOL(0, "continue", &continue_current_merge,
298 N_("continue the current in-progress merge")),
299 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
300 N_("allow merging unrelated histories")),
301 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
302 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
303 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
304 OPT_AUTOSTASH(&autostash),
305 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
306 OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
307 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
308 OPT_END()
311 static int save_state(struct object_id *stash)
313 int len;
314 struct child_process cp = CHILD_PROCESS_INIT;
315 struct strbuf buffer = STRBUF_INIT;
316 struct lock_file lock_file = LOCK_INIT;
317 int fd;
318 int rc = -1;
320 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
321 refresh_cache(REFRESH_QUIET);
322 if (0 <= fd)
323 repo_update_index_if_able(the_repository, &lock_file);
324 rollback_lock_file(&lock_file);
326 strvec_pushl(&cp.args, "stash", "create", NULL);
327 cp.out = -1;
328 cp.git_cmd = 1;
330 if (start_command(&cp))
331 die(_("could not run stash."));
332 len = strbuf_read(&buffer, cp.out, 1024);
333 close(cp.out);
335 if (finish_command(&cp) || len < 0)
336 die(_("stash failed"));
337 else if (!len) /* no changes */
338 goto out;
339 strbuf_setlen(&buffer, buffer.len-1);
340 if (get_oid(buffer.buf, stash))
341 die(_("not a valid object: %s"), buffer.buf);
342 rc = 0;
343 out:
344 strbuf_release(&buffer);
345 return rc;
348 static void read_empty(const struct object_id *oid)
350 struct child_process cmd = CHILD_PROCESS_INIT;
352 strvec_pushl(&cmd.args, "read-tree", "-m", "-u", empty_tree_oid_hex(),
353 oid_to_hex(oid), NULL);
354 cmd.git_cmd = 1;
356 if (run_command(&cmd))
357 die(_("read-tree failed"));
360 static void reset_hard(const struct object_id *oid)
362 struct child_process cmd = CHILD_PROCESS_INIT;
364 strvec_pushl(&cmd.args, "read-tree", "-v", "--reset", "-u",
365 oid_to_hex(oid), NULL);
366 cmd.git_cmd = 1;
368 if (run_command(&cmd))
369 die(_("read-tree failed"));
372 static void restore_state(const struct object_id *head,
373 const struct object_id *stash)
375 struct child_process cmd = CHILD_PROCESS_INIT;
377 reset_hard(head);
379 if (is_null_oid(stash))
380 goto refresh_cache;
382 strvec_pushl(&cmd.args, "stash", "apply", "--index", "--quiet", NULL);
383 strvec_push(&cmd.args, oid_to_hex(stash));
386 * It is OK to ignore error here, for example when there was
387 * nothing to restore.
389 cmd.git_cmd = 1;
390 run_command(&cmd);
392 refresh_cache:
393 if (discard_cache() < 0 || read_cache() < 0)
394 die(_("could not read index"));
397 /* This is called when no merge was necessary. */
398 static void finish_up_to_date(void)
400 if (verbosity >= 0) {
401 if (squash)
402 puts(_("Already up to date. (nothing to squash)"));
403 else
404 puts(_("Already up to date."));
406 remove_merge_branch_state(the_repository);
409 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
411 struct rev_info rev;
412 struct strbuf out = STRBUF_INIT;
413 struct commit_list *j;
414 struct pretty_print_context ctx = {0};
416 printf(_("Squash commit -- not updating HEAD\n"));
418 repo_init_revisions(the_repository, &rev, NULL);
419 diff_merges_suppress(&rev);
420 rev.commit_format = CMIT_FMT_MEDIUM;
422 commit->object.flags |= UNINTERESTING;
423 add_pending_object(&rev, &commit->object, NULL);
425 for (j = remoteheads; j; j = j->next)
426 add_pending_object(&rev, &j->item->object, NULL);
428 setup_revisions(0, NULL, &rev, NULL);
429 if (prepare_revision_walk(&rev))
430 die(_("revision walk setup failed"));
432 ctx.abbrev = rev.abbrev;
433 ctx.date_mode = rev.date_mode;
434 ctx.fmt = rev.commit_format;
436 strbuf_addstr(&out, "Squashed commit of the following:\n");
437 while ((commit = get_revision(&rev)) != NULL) {
438 strbuf_addch(&out, '\n');
439 strbuf_addf(&out, "commit %s\n",
440 oid_to_hex(&commit->object.oid));
441 pretty_print_commit(&ctx, commit, &out);
443 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
444 strbuf_release(&out);
445 release_revisions(&rev);
448 static void finish(struct commit *head_commit,
449 struct commit_list *remoteheads,
450 const struct object_id *new_head, const char *msg)
452 struct strbuf reflog_message = STRBUF_INIT;
453 const struct object_id *head = &head_commit->object.oid;
455 if (!msg)
456 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
457 else {
458 if (verbosity >= 0)
459 printf("%s\n", msg);
460 strbuf_addf(&reflog_message, "%s: %s",
461 getenv("GIT_REFLOG_ACTION"), msg);
463 if (squash) {
464 squash_message(head_commit, remoteheads);
465 } else {
466 if (verbosity >= 0 && !merge_msg.len)
467 printf(_("No merge message -- not updating HEAD\n"));
468 else {
469 update_ref(reflog_message.buf, "HEAD", new_head, head,
470 0, UPDATE_REFS_DIE_ON_ERR);
472 * We ignore errors in 'gc --auto', since the
473 * user should see them.
475 run_auto_maintenance(verbosity < 0);
478 if (new_head && show_diffstat) {
479 struct diff_options opts;
480 repo_diff_setup(the_repository, &opts);
481 opts.stat_width = -1; /* use full terminal width */
482 opts.stat_graph_width = -1; /* respect statGraphWidth config */
483 opts.output_format |=
484 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
485 opts.detect_rename = DIFF_DETECT_RENAME;
486 diff_setup_done(&opts);
487 diff_tree_oid(head, new_head, "", &opts);
488 diffcore_std(&opts);
489 diff_flush(&opts);
492 /* Run a post-merge hook */
493 run_hooks_l("post-merge", squash ? "1" : "0", NULL);
495 if (new_head)
496 apply_autostash(git_path_merge_autostash(the_repository));
497 strbuf_release(&reflog_message);
500 /* Get the name for the merge commit's message. */
501 static void merge_name(const char *remote, struct strbuf *msg)
503 struct commit *remote_head;
504 struct object_id branch_head;
505 struct strbuf bname = STRBUF_INIT;
506 struct merge_remote_desc *desc;
507 const char *ptr;
508 char *found_ref = NULL;
509 int len, early;
511 strbuf_branchname(&bname, remote, 0);
512 remote = bname.buf;
514 oidclr(&branch_head);
515 remote_head = get_merge_parent(remote);
516 if (!remote_head)
517 die(_("'%s' does not point to a commit"), remote);
519 if (dwim_ref(remote, strlen(remote), &branch_head, &found_ref, 0) > 0) {
520 if (starts_with(found_ref, "refs/heads/")) {
521 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
522 oid_to_hex(&branch_head), remote);
523 goto cleanup;
525 if (starts_with(found_ref, "refs/tags/")) {
526 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
527 oid_to_hex(&branch_head), remote);
528 goto cleanup;
530 if (starts_with(found_ref, "refs/remotes/")) {
531 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
532 oid_to_hex(&branch_head), remote);
533 goto cleanup;
537 /* See if remote matches <name>^^^.. or <name>~<number> */
538 for (len = 0, ptr = remote + strlen(remote);
539 remote < ptr && ptr[-1] == '^';
540 ptr--)
541 len++;
542 if (len)
543 early = 1;
544 else {
545 early = 0;
546 ptr = strrchr(remote, '~');
547 if (ptr) {
548 int seen_nonzero = 0;
550 len++; /* count ~ */
551 while (*++ptr && isdigit(*ptr)) {
552 seen_nonzero |= (*ptr != '0');
553 len++;
555 if (*ptr)
556 len = 0; /* not ...~<number> */
557 else if (seen_nonzero)
558 early = 1;
559 else if (len == 1)
560 early = 1; /* "name~" is "name~1"! */
563 if (len) {
564 struct strbuf truname = STRBUF_INIT;
565 strbuf_addf(&truname, "refs/heads/%s", remote);
566 strbuf_setlen(&truname, truname.len - len);
567 if (ref_exists(truname.buf)) {
568 strbuf_addf(msg,
569 "%s\t\tbranch '%s'%s of .\n",
570 oid_to_hex(&remote_head->object.oid),
571 truname.buf + 11,
572 (early ? " (early part)" : ""));
573 strbuf_release(&truname);
574 goto cleanup;
576 strbuf_release(&truname);
579 desc = merge_remote_util(remote_head);
580 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
581 strbuf_addf(msg, "%s\t\t%s '%s'\n",
582 oid_to_hex(&desc->obj->oid),
583 type_name(desc->obj->type),
584 remote);
585 goto cleanup;
588 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
589 oid_to_hex(&remote_head->object.oid), remote);
590 cleanup:
591 free(found_ref);
592 strbuf_release(&bname);
595 static void parse_branch_merge_options(char *bmo)
597 const char **argv;
598 int argc;
600 if (!bmo)
601 return;
602 argc = split_cmdline(bmo, &argv);
603 if (argc < 0)
604 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
605 _(split_cmdline_strerror(argc)));
606 REALLOC_ARRAY(argv, argc + 2);
607 MOVE_ARRAY(argv + 1, argv, argc + 1);
608 argc++;
609 argv[0] = "branch.*.mergeoptions";
610 parse_options(argc, argv, NULL, builtin_merge_options,
611 builtin_merge_usage, 0);
612 free(argv);
615 static int git_merge_config(const char *k, const char *v, void *cb)
617 int status;
618 const char *str;
620 if (branch &&
621 skip_prefix(k, "branch.", &str) &&
622 skip_prefix(str, branch, &str) &&
623 !strcmp(str, ".mergeoptions")) {
624 free(branch_mergeoptions);
625 branch_mergeoptions = xstrdup(v);
626 return 0;
629 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
630 show_diffstat = git_config_bool(k, v);
631 else if (!strcmp(k, "merge.verifysignatures"))
632 verify_signatures = git_config_bool(k, v);
633 else if (!strcmp(k, "pull.twohead"))
634 return git_config_string(&pull_twohead, k, v);
635 else if (!strcmp(k, "pull.octopus"))
636 return git_config_string(&pull_octopus, k, v);
637 else if (!strcmp(k, "commit.cleanup"))
638 return git_config_string(&cleanup_arg, k, v);
639 else if (!strcmp(k, "merge.ff")) {
640 int boolval = git_parse_maybe_bool(v);
641 if (0 <= boolval) {
642 fast_forward = boolval ? FF_ALLOW : FF_NO;
643 } else if (v && !strcmp(v, "only")) {
644 fast_forward = FF_ONLY;
645 } /* do not barf on values from future versions of git */
646 return 0;
647 } else if (!strcmp(k, "merge.defaulttoupstream")) {
648 default_to_upstream = git_config_bool(k, v);
649 return 0;
650 } else if (!strcmp(k, "commit.gpgsign")) {
651 sign_commit = git_config_bool(k, v) ? "" : NULL;
652 return 0;
653 } else if (!strcmp(k, "gpg.mintrustlevel")) {
654 check_trust_level = 0;
655 } else if (!strcmp(k, "merge.autostash")) {
656 autostash = git_config_bool(k, v);
657 return 0;
660 status = fmt_merge_msg_config(k, v, cb);
661 if (status)
662 return status;
663 status = git_gpg_config(k, v, NULL);
664 if (status)
665 return status;
666 return git_diff_ui_config(k, v, cb);
669 static int read_tree_trivial(struct object_id *common, struct object_id *head,
670 struct object_id *one)
672 int i, nr_trees = 0;
673 struct tree *trees[MAX_UNPACK_TREES];
674 struct tree_desc t[MAX_UNPACK_TREES];
675 struct unpack_trees_options opts;
677 memset(&opts, 0, sizeof(opts));
678 opts.head_idx = 2;
679 opts.src_index = &the_index;
680 opts.dst_index = &the_index;
681 opts.update = 1;
682 opts.verbose_update = 1;
683 opts.trivial_merges_only = 1;
684 opts.merge = 1;
685 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
686 trees[nr_trees] = parse_tree_indirect(common);
687 if (!trees[nr_trees++])
688 return -1;
689 trees[nr_trees] = parse_tree_indirect(head);
690 if (!trees[nr_trees++])
691 return -1;
692 trees[nr_trees] = parse_tree_indirect(one);
693 if (!trees[nr_trees++])
694 return -1;
695 opts.fn = threeway_merge;
696 cache_tree_free(&active_cache_tree);
697 for (i = 0; i < nr_trees; i++) {
698 parse_tree(trees[i]);
699 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
701 if (unpack_trees(nr_trees, t, &opts))
702 return -1;
703 return 0;
706 static void write_tree_trivial(struct object_id *oid)
708 if (write_cache_as_tree(oid, 0, NULL))
709 die(_("git write-tree failed to write a tree"));
712 static int try_merge_strategy(const char *strategy, struct commit_list *common,
713 struct commit_list *remoteheads,
714 struct commit *head)
716 const char *head_arg = "HEAD";
718 if (refresh_and_write_cache(REFRESH_QUIET, SKIP_IF_UNCHANGED, 0) < 0)
719 return error(_("Unable to write index."));
721 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
722 !strcmp(strategy, "ort")) {
723 struct lock_file lock = LOCK_INIT;
724 int clean, x;
725 struct commit *result;
726 struct commit_list *reversed = NULL;
727 struct merge_options o;
728 struct commit_list *j;
730 if (remoteheads->next) {
731 error(_("Not handling anything other than two heads merge."));
732 return 2;
735 init_merge_options(&o, the_repository);
736 if (!strcmp(strategy, "subtree"))
737 o.subtree_shift = "";
739 o.show_rename_progress =
740 show_progress == -1 ? isatty(2) : show_progress;
742 for (x = 0; x < xopts_nr; x++)
743 if (parse_merge_opt(&o, xopts[x]))
744 die(_("unknown strategy option: -X%s"), xopts[x]);
746 o.branch1 = head_arg;
747 o.branch2 = merge_remote_util(remoteheads->item)->name;
749 for (j = common; j; j = j->next)
750 commit_list_insert(j->item, &reversed);
752 hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
753 if (!strcmp(strategy, "ort"))
754 clean = merge_ort_recursive(&o, head, remoteheads->item,
755 reversed, &result);
756 else
757 clean = merge_recursive(&o, head, remoteheads->item,
758 reversed, &result);
759 if (clean < 0) {
760 rollback_lock_file(&lock);
761 return 2;
763 if (write_locked_index(&the_index, &lock,
764 COMMIT_LOCK | SKIP_IF_UNCHANGED))
765 die(_("unable to write %s"), get_index_file());
766 return clean ? 0 : 1;
767 } else {
768 return try_merge_command(the_repository,
769 strategy, xopts_nr, xopts,
770 common, head_arg, remoteheads);
774 static void count_diff_files(struct diff_queue_struct *q,
775 struct diff_options *opt, void *data)
777 int *count = data;
779 (*count) += q->nr;
782 static int count_unmerged_entries(void)
784 int i, ret = 0;
786 for (i = 0; i < active_nr; i++)
787 if (ce_stage(active_cache[i]))
788 ret++;
790 return ret;
793 static void add_strategies(const char *string, unsigned attr)
795 int i;
797 if (string) {
798 struct string_list list = STRING_LIST_INIT_DUP;
799 struct string_list_item *item;
800 string_list_split(&list, string, ' ', -1);
801 for_each_string_list_item(item, &list)
802 append_strategy(get_strategy(item->string));
803 string_list_clear(&list, 0);
804 return;
806 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
807 if (all_strategy[i].attr & attr)
808 append_strategy(&all_strategy[i]);
812 static void read_merge_msg(struct strbuf *msg)
814 const char *filename = git_path_merge_msg(the_repository);
815 strbuf_reset(msg);
816 if (strbuf_read_file(msg, filename, 0) < 0)
817 die_errno(_("Could not read from '%s'"), filename);
820 static void write_merge_state(struct commit_list *);
821 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
823 if (err_msg)
824 error("%s", err_msg);
825 fprintf(stderr,
826 _("Not committing merge; use 'git commit' to complete the merge.\n"));
827 write_merge_state(remoteheads);
828 exit(1);
831 static const char merge_editor_comment[] =
832 N_("Please enter a commit message to explain why this merge is necessary,\n"
833 "especially if it merges an updated upstream into a topic branch.\n"
834 "\n");
836 static const char scissors_editor_comment[] =
837 N_("An empty message aborts the commit.\n");
839 static const char no_scissors_editor_comment[] =
840 N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
841 "the commit.\n");
843 static void write_merge_heads(struct commit_list *);
844 static void prepare_to_commit(struct commit_list *remoteheads)
846 struct strbuf msg = STRBUF_INIT;
847 const char *index_file = get_index_file();
849 if (!no_verify) {
850 int invoked_hook;
852 if (run_commit_hook(0 < option_edit, index_file, &invoked_hook,
853 "pre-merge-commit", NULL))
854 abort_commit(remoteheads, NULL);
856 * Re-read the index as pre-merge-commit hook could have updated it,
857 * and write it out as a tree. We must do this before we invoke
858 * the editor and after we invoke run_status above.
860 if (invoked_hook)
861 discard_cache();
863 read_cache_from(index_file);
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, "\n");
873 strbuf_commented_addf(&msg, _(merge_editor_comment));
874 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
875 strbuf_commented_addf(&msg, _(scissors_editor_comment));
876 else
877 strbuf_commented_addf(&msg,
878 _(no_scissors_editor_comment), comment_line_char);
880 if (signoff)
881 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
882 write_merge_heads(remoteheads);
883 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
884 if (run_commit_hook(0 < option_edit, get_index_file(), NULL,
885 "prepare-commit-msg",
886 git_path_merge_msg(the_repository), "merge", NULL))
887 abort_commit(remoteheads, NULL);
888 if (0 < option_edit) {
889 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
890 abort_commit(remoteheads, NULL);
893 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
894 NULL, "commit-msg",
895 git_path_merge_msg(the_repository), NULL))
896 abort_commit(remoteheads, NULL);
898 read_merge_msg(&msg);
899 cleanup_message(&msg, cleanup_mode, 0);
900 if (!msg.len)
901 abort_commit(remoteheads, _("Empty commit message."));
902 strbuf_release(&merge_msg);
903 strbuf_addbuf(&merge_msg, &msg);
904 strbuf_release(&msg);
907 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
909 struct object_id result_tree, result_commit;
910 struct commit_list *parents, **pptr = &parents;
912 if (refresh_and_write_cache(REFRESH_QUIET, SKIP_IF_UNCHANGED, 0) < 0)
913 return error(_("Unable to write index."));
915 write_tree_trivial(&result_tree);
916 printf(_("Wonderful.\n"));
917 pptr = commit_list_append(head, pptr);
918 pptr = commit_list_append(remoteheads->item, pptr);
919 prepare_to_commit(remoteheads);
920 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
921 &result_commit, NULL, sign_commit))
922 die(_("failed to write commit object"));
923 finish(head, remoteheads, &result_commit, "In-index merge");
924 remove_merge_branch_state(the_repository);
925 return 0;
928 static int finish_automerge(struct commit *head,
929 int head_subsumed,
930 struct commit_list *common,
931 struct commit_list *remoteheads,
932 struct object_id *result_tree,
933 const char *wt_strategy)
935 struct commit_list *parents = NULL;
936 struct strbuf buf = STRBUF_INIT;
937 struct object_id result_commit;
939 write_tree_trivial(result_tree);
940 free_commit_list(common);
941 parents = remoteheads;
942 if (!head_subsumed || fast_forward == FF_NO)
943 commit_list_insert(head, &parents);
944 prepare_to_commit(remoteheads);
945 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
946 &result_commit, NULL, sign_commit))
947 die(_("failed to write commit object"));
948 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
949 finish(head, remoteheads, &result_commit, buf.buf);
950 strbuf_release(&buf);
951 remove_merge_branch_state(the_repository);
952 return 0;
955 static int suggest_conflicts(void)
957 const char *filename;
958 FILE *fp;
959 struct strbuf msgbuf = STRBUF_INIT;
961 filename = git_path_merge_msg(the_repository);
962 fp = xfopen(filename, "a");
965 * We can't use cleanup_mode because if we're not using the editor,
966 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
967 * though the message is meant to be processed later by git-commit.
968 * Thus, we will get the cleanup mode which is returned when we _are_
969 * using an editor.
971 append_conflicts_hint(&the_index, &msgbuf,
972 get_cleanup_mode(cleanup_arg, 1));
973 fputs(msgbuf.buf, fp);
974 strbuf_release(&msgbuf);
975 fclose(fp);
976 repo_rerere(the_repository, allow_rerere_auto);
977 printf(_("Automatic merge failed; "
978 "fix conflicts and then commit the result.\n"));
979 return 1;
982 static int evaluate_result(void)
984 int cnt = 0;
985 struct rev_info rev;
987 /* Check how many files differ. */
988 repo_init_revisions(the_repository, &rev, "");
989 setup_revisions(0, NULL, &rev, NULL);
990 rev.diffopt.output_format |=
991 DIFF_FORMAT_CALLBACK;
992 rev.diffopt.format_callback = count_diff_files;
993 rev.diffopt.format_callback_data = &cnt;
994 run_diff_files(&rev, 0);
997 * Check how many unmerged entries are
998 * there.
1000 cnt += count_unmerged_entries();
1002 release_revisions(&rev);
1003 return cnt;
1007 * Pretend as if the user told us to merge with the remote-tracking
1008 * branch we have for the upstream of the current branch
1010 static int setup_with_upstream(const char ***argv)
1012 struct branch *branch = branch_get(NULL);
1013 int i;
1014 const char **args;
1016 if (!branch)
1017 die(_("No current branch."));
1018 if (!branch->remote_name)
1019 die(_("No remote for the current branch."));
1020 if (!branch->merge_nr)
1021 die(_("No default upstream defined for the current branch."));
1023 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1024 for (i = 0; i < branch->merge_nr; i++) {
1025 if (!branch->merge[i]->dst)
1026 die(_("No remote-tracking branch for %s from %s"),
1027 branch->merge[i]->src, branch->remote_name);
1028 args[i] = branch->merge[i]->dst;
1030 args[i] = NULL;
1031 *argv = args;
1032 return i;
1035 static void write_merge_heads(struct commit_list *remoteheads)
1037 struct commit_list *j;
1038 struct strbuf buf = STRBUF_INIT;
1040 for (j = remoteheads; j; j = j->next) {
1041 struct object_id *oid;
1042 struct commit *c = j->item;
1043 struct merge_remote_desc *desc;
1045 desc = merge_remote_util(c);
1046 if (desc && desc->obj) {
1047 oid = &desc->obj->oid;
1048 } else {
1049 oid = &c->object.oid;
1051 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1053 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1055 strbuf_reset(&buf);
1056 if (fast_forward == FF_NO)
1057 strbuf_addstr(&buf, "no-ff");
1058 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1059 strbuf_release(&buf);
1062 static void write_merge_state(struct commit_list *remoteheads)
1064 write_merge_heads(remoteheads);
1065 strbuf_addch(&merge_msg, '\n');
1066 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1067 merge_msg.len);
1070 static int default_edit_option(void)
1072 static const char name[] = "GIT_MERGE_AUTOEDIT";
1073 const char *e = getenv(name);
1074 struct stat st_stdin, st_stdout;
1076 if (have_message)
1077 /* an explicit -m msg without --[no-]edit */
1078 return 0;
1080 if (e) {
1081 int v = git_parse_maybe_bool(e);
1082 if (v < 0)
1083 die(_("Bad value '%s' in environment '%s'"), e, name);
1084 return v;
1087 /* Use editor if stdin and stdout are the same and is a tty */
1088 return (!fstat(0, &st_stdin) &&
1089 !fstat(1, &st_stdout) &&
1090 isatty(0) && isatty(1) &&
1091 st_stdin.st_dev == st_stdout.st_dev &&
1092 st_stdin.st_ino == st_stdout.st_ino &&
1093 st_stdin.st_mode == st_stdout.st_mode);
1096 static struct commit_list *reduce_parents(struct commit *head_commit,
1097 int *head_subsumed,
1098 struct commit_list *remoteheads)
1100 struct commit_list *parents, **remotes;
1103 * Is the current HEAD reachable from another commit being
1104 * merged? If so we do not want to record it as a parent of
1105 * the resulting merge, unless --no-ff is given. We will flip
1106 * this variable to 0 when we find HEAD among the independent
1107 * tips being merged.
1109 *head_subsumed = 1;
1111 /* Find what parents to record by checking independent ones. */
1112 parents = reduce_heads(remoteheads);
1113 free_commit_list(remoteheads);
1115 remoteheads = NULL;
1116 remotes = &remoteheads;
1117 while (parents) {
1118 struct commit *commit = pop_commit(&parents);
1119 if (commit == head_commit)
1120 *head_subsumed = 0;
1121 else
1122 remotes = &commit_list_insert(commit, remotes)->next;
1124 return remoteheads;
1127 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1129 struct fmt_merge_msg_opts opts;
1131 memset(&opts, 0, sizeof(opts));
1132 opts.add_title = !have_message;
1133 opts.shortlog_len = shortlog_len;
1134 opts.credit_people = (0 < option_edit);
1135 opts.into_name = into_name;
1137 fmt_merge_msg(merge_names, merge_msg, &opts);
1138 if (merge_msg->len)
1139 strbuf_setlen(merge_msg, merge_msg->len - 1);
1142 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1144 const char *filename;
1145 int fd, pos, npos;
1146 struct strbuf fetch_head_file = STRBUF_INIT;
1147 const unsigned hexsz = the_hash_algo->hexsz;
1149 if (!merge_names)
1150 merge_names = &fetch_head_file;
1152 filename = git_path_fetch_head(the_repository);
1153 fd = xopen(filename, O_RDONLY);
1155 if (strbuf_read(merge_names, fd, 0) < 0)
1156 die_errno(_("could not read '%s'"), filename);
1157 if (close(fd) < 0)
1158 die_errno(_("could not close '%s'"), filename);
1160 for (pos = 0; pos < merge_names->len; pos = npos) {
1161 struct object_id oid;
1162 char *ptr;
1163 struct commit *commit;
1165 ptr = strchr(merge_names->buf + pos, '\n');
1166 if (ptr)
1167 npos = ptr - merge_names->buf + 1;
1168 else
1169 npos = merge_names->len;
1171 if (npos - pos < hexsz + 2 ||
1172 get_oid_hex(merge_names->buf + pos, &oid))
1173 commit = NULL; /* bad */
1174 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1175 continue; /* not-for-merge */
1176 else {
1177 char saved = merge_names->buf[pos + hexsz];
1178 merge_names->buf[pos + hexsz] = '\0';
1179 commit = get_merge_parent(merge_names->buf + pos);
1180 merge_names->buf[pos + hexsz] = saved;
1182 if (!commit) {
1183 if (ptr)
1184 *ptr = '\0';
1185 die(_("not something we can merge in %s: %s"),
1186 filename, merge_names->buf + pos);
1188 remotes = &commit_list_insert(commit, remotes)->next;
1191 if (merge_names == &fetch_head_file)
1192 strbuf_release(&fetch_head_file);
1195 static struct commit_list *collect_parents(struct commit *head_commit,
1196 int *head_subsumed,
1197 int argc, const char **argv,
1198 struct strbuf *merge_msg)
1200 int i;
1201 struct commit_list *remoteheads = NULL;
1202 struct commit_list **remotes = &remoteheads;
1203 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1205 if (merge_msg && (!have_message || shortlog_len))
1206 autogen = &merge_names;
1208 if (head_commit)
1209 remotes = &commit_list_insert(head_commit, remotes)->next;
1211 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1212 handle_fetch_head(remotes, autogen);
1213 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1214 } else {
1215 for (i = 0; i < argc; i++) {
1216 struct commit *commit = get_merge_parent(argv[i]);
1217 if (!commit)
1218 help_unknown_ref(argv[i], "merge",
1219 _("not something we can merge"));
1220 remotes = &commit_list_insert(commit, remotes)->next;
1222 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1223 if (autogen) {
1224 struct commit_list *p;
1225 for (p = remoteheads; p; p = p->next)
1226 merge_name(merge_remote_util(p->item)->name, autogen);
1230 if (autogen) {
1231 prepare_merge_message(autogen, merge_msg);
1232 strbuf_release(autogen);
1235 return remoteheads;
1238 static int merging_a_throwaway_tag(struct commit *commit)
1240 char *tag_ref;
1241 struct object_id oid;
1242 int is_throwaway_tag = 0;
1244 /* Are we merging a tag? */
1245 if (!merge_remote_util(commit) ||
1246 !merge_remote_util(commit)->obj ||
1247 merge_remote_util(commit)->obj->type != OBJ_TAG)
1248 return is_throwaway_tag;
1251 * Now we know we are merging a tag object. Are we downstream
1252 * and following the tags from upstream? If so, we must have
1253 * the tag object pointed at by "refs/tags/$T" where $T is the
1254 * tagname recorded in the tag object. We want to allow such
1255 * a "just to catch up" merge to fast-forward.
1257 * Otherwise, we are playing an integrator's role, making a
1258 * merge with a throw-away tag from a contributor with
1259 * something like "git pull $contributor $signed_tag".
1260 * We want to forbid such a merge from fast-forwarding
1261 * by default; otherwise we would not keep the signature
1262 * anywhere.
1264 tag_ref = xstrfmt("refs/tags/%s",
1265 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1266 if (!read_ref(tag_ref, &oid) &&
1267 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1268 is_throwaway_tag = 0;
1269 else
1270 is_throwaway_tag = 1;
1271 free(tag_ref);
1272 return is_throwaway_tag;
1275 int cmd_merge(int argc, const char **argv, const char *prefix)
1277 struct object_id result_tree, stash, head_oid;
1278 struct commit *head_commit;
1279 struct strbuf buf = STRBUF_INIT;
1280 int i, ret = 0, head_subsumed;
1281 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1282 struct commit_list *common = NULL;
1283 const char *best_strategy = NULL, *wt_strategy = NULL;
1284 struct commit_list *remoteheads = NULL, *p;
1285 void *branch_to_free;
1286 int orig_argc = argc;
1288 if (argc == 2 && !strcmp(argv[1], "-h"))
1289 usage_with_options(builtin_merge_usage, builtin_merge_options);
1291 prepare_repo_settings(the_repository);
1292 the_repository->settings.command_requires_full_index = 0;
1295 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1296 * current branch.
1298 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1299 if (branch)
1300 skip_prefix(branch, "refs/heads/", &branch);
1302 if (!pull_twohead) {
1303 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1304 if (default_strategy && !strcmp(default_strategy, "ort"))
1305 pull_twohead = "ort";
1308 init_diff_ui_defaults();
1309 git_config(git_merge_config, NULL);
1311 if (!branch || is_null_oid(&head_oid))
1312 head_commit = NULL;
1313 else
1314 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1316 if (branch_mergeoptions)
1317 parse_branch_merge_options(branch_mergeoptions);
1318 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1319 builtin_merge_usage, 0);
1320 if (shortlog_len < 0)
1321 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1323 if (verbosity < 0 && show_progress == -1)
1324 show_progress = 0;
1326 if (abort_current_merge) {
1327 int nargc = 2;
1328 const char *nargv[] = {"reset", "--merge", NULL};
1329 struct strbuf stash_oid = STRBUF_INIT;
1331 if (orig_argc != 2)
1332 usage_msg_opt(_("--abort expects no arguments"),
1333 builtin_merge_usage, builtin_merge_options);
1335 if (!file_exists(git_path_merge_head(the_repository)))
1336 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1338 if (read_oneliner(&stash_oid, git_path_merge_autostash(the_repository),
1339 READ_ONELINER_SKIP_IF_EMPTY))
1340 unlink(git_path_merge_autostash(the_repository));
1342 /* Invoke 'git reset --merge' */
1343 ret = cmd_reset(nargc, nargv, prefix);
1345 if (stash_oid.len)
1346 apply_autostash_oid(stash_oid.buf);
1348 strbuf_release(&stash_oid);
1349 goto done;
1352 if (quit_current_merge) {
1353 if (orig_argc != 2)
1354 usage_msg_opt(_("--quit expects no arguments"),
1355 builtin_merge_usage,
1356 builtin_merge_options);
1358 remove_merge_branch_state(the_repository);
1359 goto done;
1362 if (continue_current_merge) {
1363 int nargc = 1;
1364 const char *nargv[] = {"commit", NULL};
1366 if (orig_argc != 2)
1367 usage_msg_opt(_("--continue expects no arguments"),
1368 builtin_merge_usage, builtin_merge_options);
1370 if (!file_exists(git_path_merge_head(the_repository)))
1371 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1373 /* Invoke 'git commit' */
1374 ret = cmd_commit(nargc, nargv, prefix);
1375 goto done;
1378 if (read_cache_unmerged())
1379 die_resolve_conflict("merge");
1381 if (file_exists(git_path_merge_head(the_repository))) {
1383 * There is no unmerged entry, don't advise 'git
1384 * add/rm <file>', just 'git commit'.
1386 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1387 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1388 "Please, commit your changes before you merge."));
1389 else
1390 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1392 if (ref_exists("CHERRY_PICK_HEAD")) {
1393 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1394 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1395 "Please, commit your changes before you merge."));
1396 else
1397 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1399 resolve_undo_clear();
1401 if (option_edit < 0)
1402 option_edit = default_edit_option();
1404 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1406 if (verbosity < 0)
1407 show_diffstat = 0;
1409 if (squash) {
1410 if (fast_forward == FF_NO)
1411 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1412 if (option_commit > 0)
1413 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1415 * squash can now silently disable option_commit - this is not
1416 * a problem as it is only overriding the default, not a user
1417 * supplied option.
1419 option_commit = 0;
1422 if (option_commit < 0)
1423 option_commit = 1;
1425 if (!argc) {
1426 if (default_to_upstream)
1427 argc = setup_with_upstream(&argv);
1428 else
1429 die(_("No commit specified and merge.defaultToUpstream not set."));
1430 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1431 argv[0] = "@{-1}";
1434 if (!argc)
1435 usage_with_options(builtin_merge_usage,
1436 builtin_merge_options);
1438 if (!head_commit) {
1440 * If the merged head is a valid one there is no reason
1441 * to forbid "git merge" into a branch yet to be born.
1442 * We do the same for "git pull".
1444 struct object_id *remote_head_oid;
1445 if (squash)
1446 die(_("Squash commit into empty head not supported yet"));
1447 if (fast_forward == FF_NO)
1448 die(_("Non-fast-forward commit does not make sense into "
1449 "an empty head"));
1450 remoteheads = collect_parents(head_commit, &head_subsumed,
1451 argc, argv, NULL);
1452 if (!remoteheads)
1453 die(_("%s - not something we can merge"), argv[0]);
1454 if (remoteheads->next)
1455 die(_("Can merge only exactly one commit into empty head"));
1457 if (verify_signatures)
1458 verify_merge_signature(remoteheads->item, verbosity,
1459 check_trust_level);
1461 remote_head_oid = &remoteheads->item->object.oid;
1462 read_empty(remote_head_oid);
1463 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1464 UPDATE_REFS_DIE_ON_ERR);
1465 goto done;
1469 * All the rest are the commits being merged; prepare
1470 * the standard merge summary message to be appended
1471 * to the given message.
1473 remoteheads = collect_parents(head_commit, &head_subsumed,
1474 argc, argv, &merge_msg);
1476 if (!head_commit || !argc)
1477 usage_with_options(builtin_merge_usage,
1478 builtin_merge_options);
1480 if (verify_signatures) {
1481 for (p = remoteheads; p; p = p->next) {
1482 verify_merge_signature(p->item, verbosity,
1483 check_trust_level);
1487 strbuf_addstr(&buf, "merge");
1488 for (p = remoteheads; p; p = p->next)
1489 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1490 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1491 strbuf_reset(&buf);
1493 for (p = remoteheads; p; p = p->next) {
1494 struct commit *commit = p->item;
1495 strbuf_addf(&buf, "GITHEAD_%s",
1496 oid_to_hex(&commit->object.oid));
1497 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1498 strbuf_reset(&buf);
1499 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1500 fast_forward = FF_NO;
1503 if (!use_strategies && !pull_twohead &&
1504 remoteheads && !remoteheads->next) {
1505 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1506 if (default_strategy)
1507 append_strategy(get_strategy(default_strategy));
1509 if (!use_strategies) {
1510 if (!remoteheads)
1511 ; /* already up-to-date */
1512 else if (!remoteheads->next)
1513 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1514 else
1515 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1518 for (i = 0; i < use_strategies_nr; i++) {
1519 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1520 fast_forward = FF_NO;
1521 if (use_strategies[i]->attr & NO_TRIVIAL)
1522 allow_trivial = 0;
1525 if (!remoteheads)
1526 ; /* already up-to-date */
1527 else if (!remoteheads->next)
1528 common = get_merge_bases(head_commit, remoteheads->item);
1529 else {
1530 struct commit_list *list = remoteheads;
1531 commit_list_insert(head_commit, &list);
1532 common = get_octopus_merge_bases(list);
1533 free(list);
1536 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1537 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1539 if (remoteheads && !common) {
1540 /* No common ancestors found. */
1541 if (!allow_unrelated_histories)
1542 die(_("refusing to merge unrelated histories"));
1543 /* otherwise, we need a real merge. */
1544 } else if (!remoteheads ||
1545 (!remoteheads->next && !common->next &&
1546 common->item == remoteheads->item)) {
1548 * If head can reach all the merge then we are up to date.
1549 * but first the most common case of merging one remote.
1551 finish_up_to_date();
1552 goto done;
1553 } else if (fast_forward != FF_NO && !remoteheads->next &&
1554 !common->next &&
1555 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1556 /* Again the most common case of merging one remote. */
1557 struct strbuf msg = STRBUF_INIT;
1558 struct commit *commit;
1560 if (verbosity >= 0) {
1561 printf(_("Updating %s..%s\n"),
1562 find_unique_abbrev(&head_commit->object.oid,
1563 DEFAULT_ABBREV),
1564 find_unique_abbrev(&remoteheads->item->object.oid,
1565 DEFAULT_ABBREV));
1567 strbuf_addstr(&msg, "Fast-forward");
1568 if (have_message)
1569 strbuf_addstr(&msg,
1570 " (no commit created; -m option ignored)");
1571 commit = remoteheads->item;
1572 if (!commit) {
1573 ret = 1;
1574 goto done;
1577 if (autostash)
1578 create_autostash(the_repository,
1579 git_path_merge_autostash(the_repository));
1580 if (checkout_fast_forward(the_repository,
1581 &head_commit->object.oid,
1582 &commit->object.oid,
1583 overwrite_ignore)) {
1584 apply_autostash(git_path_merge_autostash(the_repository));
1585 ret = 1;
1586 goto done;
1589 finish(head_commit, remoteheads, &commit->object.oid, msg.buf);
1590 remove_merge_branch_state(the_repository);
1591 strbuf_release(&msg);
1592 goto done;
1593 } else if (!remoteheads->next && common->next)
1596 * We are not doing octopus and not fast-forward. Need
1597 * a real merge.
1599 else if (!remoteheads->next && !common->next && option_commit) {
1601 * We are not doing octopus, not fast-forward, and have
1602 * only one common.
1604 refresh_cache(REFRESH_QUIET);
1605 if (allow_trivial && fast_forward != FF_ONLY) {
1607 * Must first ensure that index matches HEAD before
1608 * attempting a trivial merge.
1610 struct tree *head_tree = get_commit_tree(head_commit);
1611 struct strbuf sb = STRBUF_INIT;
1613 if (repo_index_has_changes(the_repository, head_tree,
1614 &sb)) {
1615 error(_("Your local changes to the following files would be overwritten by merge:\n %s"),
1616 sb.buf);
1617 strbuf_release(&sb);
1618 return 2;
1621 /* See if it is really trivial. */
1622 git_committer_info(IDENT_STRICT);
1623 printf(_("Trying really trivial in-index merge...\n"));
1624 if (!read_tree_trivial(&common->item->object.oid,
1625 &head_commit->object.oid,
1626 &remoteheads->item->object.oid)) {
1627 ret = merge_trivial(head_commit, remoteheads);
1628 goto done;
1630 printf(_("Nope.\n"));
1632 } else {
1634 * An octopus. If we can reach all the remote we are up
1635 * to date.
1637 int up_to_date = 1;
1638 struct commit_list *j;
1640 for (j = remoteheads; j; j = j->next) {
1641 struct commit_list *common_one;
1644 * Here we *have* to calculate the individual
1645 * merge_bases again, otherwise "git merge HEAD^
1646 * HEAD^^" would be missed.
1648 common_one = get_merge_bases(head_commit, j->item);
1649 if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1650 up_to_date = 0;
1651 break;
1654 if (up_to_date) {
1655 finish_up_to_date();
1656 goto done;
1660 if (fast_forward == FF_ONLY)
1661 die_ff_impossible();
1663 if (autostash)
1664 create_autostash(the_repository,
1665 git_path_merge_autostash(the_repository));
1667 /* We are going to make a new commit. */
1668 git_committer_info(IDENT_STRICT);
1671 * At this point, we need a real merge. No matter what strategy
1672 * we use, it would operate on the index, possibly affecting the
1673 * working tree, and when resolved cleanly, have the desired
1674 * tree in the index -- this means that the index must be in
1675 * sync with the head commit. The strategies are responsible
1676 * to ensure this.
1678 * Stash away the local changes so that we can try more than one
1679 * and/or recover from merge strategies bailing while leaving the
1680 * index and working tree polluted.
1682 if (save_state(&stash))
1683 oidclr(&stash);
1685 for (i = 0; i < use_strategies_nr; i++) {
1686 int ret, cnt;
1687 if (i) {
1688 printf(_("Rewinding the tree to pristine...\n"));
1689 restore_state(&head_commit->object.oid, &stash);
1691 if (use_strategies_nr != 1)
1692 printf(_("Trying merge strategy %s...\n"),
1693 use_strategies[i]->name);
1695 * Remember which strategy left the state in the working
1696 * tree.
1698 wt_strategy = use_strategies[i]->name;
1700 ret = try_merge_strategy(wt_strategy,
1701 common, remoteheads,
1702 head_commit);
1704 * The backend exits with 1 when conflicts are
1705 * left to be resolved, with 2 when it does not
1706 * handle the given merge at all.
1708 if (ret < 2) {
1709 if (!ret) {
1711 * This strategy worked; no point in trying
1712 * another.
1714 merge_was_ok = 1;
1715 best_strategy = wt_strategy;
1716 break;
1718 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1719 if (best_cnt <= 0 || cnt <= best_cnt) {
1720 best_strategy = wt_strategy;
1721 best_cnt = cnt;
1727 * If we have a resulting tree, that means the strategy module
1728 * auto resolved the merge cleanly.
1730 if (merge_was_ok && option_commit) {
1731 automerge_was_ok = 1;
1732 ret = finish_automerge(head_commit, head_subsumed,
1733 common, remoteheads,
1734 &result_tree, wt_strategy);
1735 goto done;
1739 * Pick the result from the best strategy and have the user fix
1740 * it up.
1742 if (!best_strategy) {
1743 restore_state(&head_commit->object.oid, &stash);
1744 if (use_strategies_nr > 1)
1745 fprintf(stderr,
1746 _("No merge strategy handled the merge.\n"));
1747 else
1748 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1749 use_strategies[0]->name);
1750 apply_autostash(git_path_merge_autostash(the_repository));
1751 ret = 2;
1752 goto done;
1753 } else if (best_strategy == wt_strategy)
1754 ; /* We already have its result in the working tree. */
1755 else {
1756 printf(_("Rewinding the tree to pristine...\n"));
1757 restore_state(&head_commit->object.oid, &stash);
1758 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1759 best_strategy);
1760 try_merge_strategy(best_strategy, common, remoteheads,
1761 head_commit);
1764 if (squash) {
1765 finish(head_commit, remoteheads, NULL, NULL);
1767 git_test_write_commit_graph_or_die();
1768 } else
1769 write_merge_state(remoteheads);
1771 if (merge_was_ok)
1772 fprintf(stderr, _("Automatic merge went well; "
1773 "stopped before committing as requested\n"));
1774 else
1775 ret = suggest_conflicts();
1776 if (autostash)
1777 printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1779 done:
1780 if (!automerge_was_ok) {
1781 free_commit_list(common);
1782 free_commit_list(remoteheads);
1784 strbuf_release(&buf);
1785 free(branch_to_free);
1786 return ret;