Git 2.34.8
[git.git] / builtin / merge.c
blobea3112e0c0b3acc9f4439430fb19e596a9fc9093
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;
91 static struct strategy all_strategy[] = {
92 { "recursive", NO_TRIVIAL },
93 { "octopus", DEFAULT_OCTOPUS },
94 { "ort", DEFAULT_TWOHEAD | NO_TRIVIAL },
95 { "resolve", 0 },
96 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
97 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
100 static const char *pull_twohead, *pull_octopus;
102 enum ff_type {
103 FF_NO,
104 FF_ALLOW,
105 FF_ONLY
108 static enum ff_type fast_forward = FF_ALLOW;
110 static const char *cleanup_arg;
111 static enum commit_msg_cleanup_mode cleanup_mode;
113 static int option_parse_message(const struct option *opt,
114 const char *arg, int unset)
116 struct strbuf *buf = opt->value;
118 if (unset)
119 strbuf_setlen(buf, 0);
120 else if (arg) {
121 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
122 have_message = 1;
123 } else
124 return error(_("switch `m' requires a value"));
125 return 0;
128 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
129 const struct option *opt,
130 const char *arg_not_used,
131 int unset)
133 struct strbuf *buf = opt->value;
134 const char *arg;
136 BUG_ON_OPT_ARG(arg_not_used);
137 if (unset)
138 BUG("-F cannot be negated");
140 if (ctx->opt) {
141 arg = ctx->opt;
142 ctx->opt = NULL;
143 } else if (ctx->argc > 1) {
144 ctx->argc--;
145 arg = *++ctx->argv;
146 } else
147 return error(_("option `%s' requires a value"), opt->long_name);
149 if (buf->len)
150 strbuf_addch(buf, '\n');
151 if (ctx->prefix && !is_absolute_path(arg))
152 arg = prefix_filename(ctx->prefix, arg);
153 if (strbuf_read_file(buf, arg, 0) < 0)
154 return error(_("could not read file '%s'"), arg);
155 have_message = 1;
157 return 0;
160 static struct strategy *get_strategy(const char *name)
162 int i;
163 struct strategy *ret;
164 static struct cmdnames main_cmds, other_cmds;
165 static int loaded;
166 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
168 if (!name)
169 return NULL;
171 if (default_strategy &&
172 !strcmp(default_strategy, "ort") &&
173 !strcmp(name, "recursive")) {
174 name = "ort";
177 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
178 if (!strcmp(name, all_strategy[i].name))
179 return &all_strategy[i];
181 if (!loaded) {
182 struct cmdnames not_strategies;
183 loaded = 1;
185 memset(&not_strategies, 0, sizeof(struct cmdnames));
186 load_command_list("git-merge-", &main_cmds, &other_cmds);
187 for (i = 0; i < main_cmds.cnt; i++) {
188 int j, found = 0;
189 struct cmdname *ent = main_cmds.names[i];
190 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
191 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
192 && !all_strategy[j].name[ent->len])
193 found = 1;
194 if (!found)
195 add_cmdname(&not_strategies, ent->name, ent->len);
197 exclude_cmds(&main_cmds, &not_strategies);
199 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
200 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
201 fprintf(stderr, _("Available strategies are:"));
202 for (i = 0; i < main_cmds.cnt; i++)
203 fprintf(stderr, " %s", main_cmds.names[i]->name);
204 fprintf(stderr, ".\n");
205 if (other_cmds.cnt) {
206 fprintf(stderr, _("Available custom strategies are:"));
207 for (i = 0; i < other_cmds.cnt; i++)
208 fprintf(stderr, " %s", other_cmds.names[i]->name);
209 fprintf(stderr, ".\n");
211 exit(1);
214 CALLOC_ARRAY(ret, 1);
215 ret->name = xstrdup(name);
216 ret->attr = NO_TRIVIAL;
217 return ret;
220 static void append_strategy(struct strategy *s)
222 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
223 use_strategies[use_strategies_nr++] = s;
226 static int option_parse_strategy(const struct option *opt,
227 const char *name, int unset)
229 if (unset)
230 return 0;
232 append_strategy(get_strategy(name));
233 return 0;
236 static int option_parse_x(const struct option *opt,
237 const char *arg, int unset)
239 if (unset)
240 return 0;
242 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
243 xopts[xopts_nr++] = xstrdup(arg);
244 return 0;
247 static int option_parse_n(const struct option *opt,
248 const char *arg, int unset)
250 BUG_ON_OPT_ARG(arg);
251 show_diffstat = unset;
252 return 0;
255 static struct option builtin_merge_options[] = {
256 OPT_CALLBACK_F('n', NULL, NULL, NULL,
257 N_("do not show a diffstat at the end of the merge"),
258 PARSE_OPT_NOARG, option_parse_n),
259 OPT_BOOL(0, "stat", &show_diffstat,
260 N_("show a diffstat at the end of the merge")),
261 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
262 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
263 N_("add (at most <n>) entries from shortlog to merge commit message"),
264 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
265 OPT_BOOL(0, "squash", &squash,
266 N_("create a single commit instead of doing a merge")),
267 OPT_BOOL(0, "commit", &option_commit,
268 N_("perform a commit if the merge succeeds (default)")),
269 OPT_BOOL('e', "edit", &option_edit,
270 N_("edit message before committing")),
271 OPT_CLEANUP(&cleanup_arg),
272 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
273 OPT_SET_INT_F(0, "ff-only", &fast_forward,
274 N_("abort if fast-forward is not possible"),
275 FF_ONLY, PARSE_OPT_NONEG),
276 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
277 OPT_BOOL(0, "verify-signatures", &verify_signatures,
278 N_("verify that the named commit has a valid GPG signature")),
279 OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
280 N_("merge strategy to use"), option_parse_strategy),
281 OPT_CALLBACK('X', "strategy-option", &xopts, N_("option=value"),
282 N_("option for selected merge strategy"), option_parse_x),
283 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
284 N_("merge commit message (for a non-fast-forward merge)"),
285 option_parse_message),
286 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
287 N_("read message from file"), PARSE_OPT_NONEG,
288 NULL, 0, option_read_message },
289 OPT__VERBOSITY(&verbosity),
290 OPT_BOOL(0, "abort", &abort_current_merge,
291 N_("abort the current in-progress merge")),
292 OPT_BOOL(0, "quit", &quit_current_merge,
293 N_("--abort but leave index and working tree alone")),
294 OPT_BOOL(0, "continue", &continue_current_merge,
295 N_("continue the current in-progress merge")),
296 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
297 N_("allow merging unrelated histories")),
298 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
299 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
300 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
301 OPT_AUTOSTASH(&autostash),
302 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
303 OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
304 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
305 OPT_END()
308 static int save_state(struct object_id *stash)
310 int len;
311 struct child_process cp = CHILD_PROCESS_INIT;
312 struct strbuf buffer = STRBUF_INIT;
313 const char *argv[] = {"stash", "create", NULL};
314 int rc = -1;
316 cp.argv = argv;
317 cp.out = -1;
318 cp.git_cmd = 1;
320 if (start_command(&cp))
321 die(_("could not run stash."));
322 len = strbuf_read(&buffer, cp.out, 1024);
323 close(cp.out);
325 if (finish_command(&cp) || len < 0)
326 die(_("stash failed"));
327 else if (!len) /* no changes */
328 goto out;
329 strbuf_setlen(&buffer, buffer.len-1);
330 if (get_oid(buffer.buf, stash))
331 die(_("not a valid object: %s"), buffer.buf);
332 rc = 0;
333 out:
334 strbuf_release(&buffer);
335 return rc;
338 static void read_empty(const struct object_id *oid, int verbose)
340 int i = 0;
341 const char *args[7];
343 args[i++] = "read-tree";
344 if (verbose)
345 args[i++] = "-v";
346 args[i++] = "-m";
347 args[i++] = "-u";
348 args[i++] = empty_tree_oid_hex();
349 args[i++] = oid_to_hex(oid);
350 args[i] = NULL;
352 if (run_command_v_opt(args, RUN_GIT_CMD))
353 die(_("read-tree failed"));
356 static void reset_hard(const struct object_id *oid, int verbose)
358 int i = 0;
359 const char *args[6];
361 args[i++] = "read-tree";
362 if (verbose)
363 args[i++] = "-v";
364 args[i++] = "--reset";
365 args[i++] = "-u";
366 args[i++] = oid_to_hex(oid);
367 args[i] = NULL;
369 if (run_command_v_opt(args, RUN_GIT_CMD))
370 die(_("read-tree failed"));
373 static void restore_state(const struct object_id *head,
374 const struct object_id *stash)
376 struct strbuf sb = STRBUF_INIT;
377 const char *args[] = { "stash", "apply", NULL, NULL };
379 if (is_null_oid(stash))
380 return;
382 reset_hard(head, 1);
384 args[2] = oid_to_hex(stash);
387 * It is OK to ignore error here, for example when there was
388 * nothing to restore.
390 run_command_v_opt(args, RUN_GIT_CMD);
392 strbuf_release(&sb);
393 refresh_cache(REFRESH_QUIET);
396 /* This is called when no merge was necessary. */
397 static void finish_up_to_date(void)
399 if (verbosity >= 0) {
400 if (squash)
401 puts(_("Already up to date. (nothing to squash)"));
402 else
403 puts(_("Already up to date."));
405 remove_merge_branch_state(the_repository);
408 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
410 struct rev_info rev;
411 struct strbuf out = STRBUF_INIT;
412 struct commit_list *j;
413 struct pretty_print_context ctx = {0};
415 printf(_("Squash commit -- not updating HEAD\n"));
417 repo_init_revisions(the_repository, &rev, NULL);
418 diff_merges_suppress(&rev);
419 rev.commit_format = CMIT_FMT_MEDIUM;
421 commit->object.flags |= UNINTERESTING;
422 add_pending_object(&rev, &commit->object, NULL);
424 for (j = remoteheads; j; j = j->next)
425 add_pending_object(&rev, &j->item->object, NULL);
427 setup_revisions(0, NULL, &rev, NULL);
428 if (prepare_revision_walk(&rev))
429 die(_("revision walk setup failed"));
431 ctx.abbrev = rev.abbrev;
432 ctx.date_mode = rev.date_mode;
433 ctx.fmt = rev.commit_format;
435 strbuf_addstr(&out, "Squashed commit of the following:\n");
436 while ((commit = get_revision(&rev)) != NULL) {
437 strbuf_addch(&out, '\n');
438 strbuf_addf(&out, "commit %s\n",
439 oid_to_hex(&commit->object.oid));
440 pretty_print_commit(&ctx, commit, &out);
442 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
443 strbuf_release(&out);
446 static void finish(struct commit *head_commit,
447 struct commit_list *remoteheads,
448 const struct object_id *new_head, const char *msg)
450 struct strbuf reflog_message = STRBUF_INIT;
451 const struct object_id *head = &head_commit->object.oid;
453 if (!msg)
454 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
455 else {
456 if (verbosity >= 0)
457 printf("%s\n", msg);
458 strbuf_addf(&reflog_message, "%s: %s",
459 getenv("GIT_REFLOG_ACTION"), msg);
461 if (squash) {
462 squash_message(head_commit, remoteheads);
463 } else {
464 if (verbosity >= 0 && !merge_msg.len)
465 printf(_("No merge message -- not updating HEAD\n"));
466 else {
467 update_ref(reflog_message.buf, "HEAD", new_head, head,
468 0, UPDATE_REFS_DIE_ON_ERR);
470 * We ignore errors in 'gc --auto', since the
471 * user should see them.
473 run_auto_maintenance(verbosity < 0);
476 if (new_head && show_diffstat) {
477 struct diff_options opts;
478 repo_diff_setup(the_repository, &opts);
479 opts.stat_width = -1; /* use full terminal width */
480 opts.stat_graph_width = -1; /* respect statGraphWidth config */
481 opts.output_format |=
482 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
483 opts.detect_rename = DIFF_DETECT_RENAME;
484 diff_setup_done(&opts);
485 diff_tree_oid(head, new_head, "", &opts);
486 diffcore_std(&opts);
487 diff_flush(&opts);
490 /* Run a post-merge hook */
491 run_hook_le(NULL, "post-merge", squash ? "1" : "0", NULL);
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 buf = STRBUF_INIT;
503 struct strbuf bname = STRBUF_INIT;
504 struct merge_remote_desc *desc;
505 const char *ptr;
506 char *found_ref = NULL;
507 int len, early;
509 strbuf_branchname(&bname, remote, 0);
510 remote = bname.buf;
512 oidclr(&branch_head);
513 remote_head = get_merge_parent(remote);
514 if (!remote_head)
515 die(_("'%s' does not point to a commit"), remote);
517 if (dwim_ref(remote, strlen(remote), &branch_head, &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(&buf);
591 strbuf_release(&bname);
594 static void parse_branch_merge_options(char *bmo)
596 const char **argv;
597 int argc;
599 if (!bmo)
600 return;
601 argc = split_cmdline(bmo, &argv);
602 if (argc < 0)
603 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
604 _(split_cmdline_strerror(argc)));
605 REALLOC_ARRAY(argv, argc + 2);
606 MOVE_ARRAY(argv + 1, argv, argc + 1);
607 argc++;
608 argv[0] = "branch.*.mergeoptions";
609 parse_options(argc, argv, NULL, builtin_merge_options,
610 builtin_merge_usage, 0);
611 free(argv);
614 static int git_merge_config(const char *k, const char *v, 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, cb);
660 if (status)
661 return status;
662 status = git_gpg_config(k, v, NULL);
663 if (status)
664 return status;
665 return git_diff_ui_config(k, v, cb);
668 static int read_tree_trivial(struct object_id *common, struct object_id *head,
669 struct object_id *one)
671 int i, nr_trees = 0;
672 struct tree *trees[MAX_UNPACK_TREES];
673 struct tree_desc t[MAX_UNPACK_TREES];
674 struct unpack_trees_options opts;
676 memset(&opts, 0, sizeof(opts));
677 opts.head_idx = 2;
678 opts.src_index = &the_index;
679 opts.dst_index = &the_index;
680 opts.update = 1;
681 opts.verbose_update = 1;
682 opts.trivial_merges_only = 1;
683 opts.merge = 1;
684 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
685 trees[nr_trees] = parse_tree_indirect(common);
686 if (!trees[nr_trees++])
687 return -1;
688 trees[nr_trees] = parse_tree_indirect(head);
689 if (!trees[nr_trees++])
690 return -1;
691 trees[nr_trees] = parse_tree_indirect(one);
692 if (!trees[nr_trees++])
693 return -1;
694 opts.fn = threeway_merge;
695 cache_tree_free(&active_cache_tree);
696 for (i = 0; i < nr_trees; i++) {
697 parse_tree(trees[i]);
698 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
700 if (unpack_trees(nr_trees, t, &opts))
701 return -1;
702 return 0;
705 static void write_tree_trivial(struct object_id *oid)
707 if (write_cache_as_tree(oid, 0, NULL))
708 die(_("git write-tree failed to write a tree"));
711 static int try_merge_strategy(const char *strategy, struct commit_list *common,
712 struct commit_list *remoteheads,
713 struct commit *head)
715 const char *head_arg = "HEAD";
717 if (refresh_and_write_cache(REFRESH_QUIET, SKIP_IF_UNCHANGED, 0) < 0)
718 return error(_("Unable to write index."));
720 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
721 !strcmp(strategy, "ort")) {
722 struct lock_file lock = LOCK_INIT;
723 int clean, x;
724 struct commit *result;
725 struct commit_list *reversed = NULL;
726 struct merge_options o;
727 struct commit_list *j;
729 if (remoteheads->next) {
730 error(_("Not handling anything other than two heads merge."));
731 return 2;
734 init_merge_options(&o, the_repository);
735 if (!strcmp(strategy, "subtree"))
736 o.subtree_shift = "";
738 o.show_rename_progress =
739 show_progress == -1 ? isatty(2) : show_progress;
741 for (x = 0; x < xopts_nr; x++)
742 if (parse_merge_opt(&o, xopts[x]))
743 die(_("unknown strategy option: -X%s"), xopts[x]);
745 o.branch1 = head_arg;
746 o.branch2 = merge_remote_util(remoteheads->item)->name;
748 for (j = common; j; j = j->next)
749 commit_list_insert(j->item, &reversed);
751 hold_locked_index(&lock, 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 exit(128);
760 if (write_locked_index(&the_index, &lock,
761 COMMIT_LOCK | SKIP_IF_UNCHANGED))
762 die(_("unable to write %s"), get_index_file());
763 return clean ? 0 : 1;
764 } else {
765 return try_merge_command(the_repository,
766 strategy, xopts_nr, xopts,
767 common, head_arg, remoteheads);
771 static void count_diff_files(struct diff_queue_struct *q,
772 struct diff_options *opt, void *data)
774 int *count = data;
776 (*count) += q->nr;
779 static int count_unmerged_entries(void)
781 int i, ret = 0;
783 for (i = 0; i < active_nr; i++)
784 if (ce_stage(active_cache[i]))
785 ret++;
787 return ret;
790 static void add_strategies(const char *string, unsigned attr)
792 int i;
794 if (string) {
795 struct string_list list = STRING_LIST_INIT_DUP;
796 struct string_list_item *item;
797 string_list_split(&list, string, ' ', -1);
798 for_each_string_list_item(item, &list)
799 append_strategy(get_strategy(item->string));
800 string_list_clear(&list, 0);
801 return;
803 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
804 if (all_strategy[i].attr & attr)
805 append_strategy(&all_strategy[i]);
809 static void read_merge_msg(struct strbuf *msg)
811 const char *filename = git_path_merge_msg(the_repository);
812 strbuf_reset(msg);
813 if (strbuf_read_file(msg, filename, 0) < 0)
814 die_errno(_("Could not read from '%s'"), filename);
817 static void write_merge_state(struct commit_list *);
818 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
820 if (err_msg)
821 error("%s", err_msg);
822 fprintf(stderr,
823 _("Not committing merge; use 'git commit' to complete the merge.\n"));
824 write_merge_state(remoteheads);
825 exit(1);
828 static const char merge_editor_comment[] =
829 N_("Please enter a commit message to explain why this merge is necessary,\n"
830 "especially if it merges an updated upstream into a topic branch.\n"
831 "\n");
833 static const char scissors_editor_comment[] =
834 N_("An empty message aborts the commit.\n");
836 static const char no_scissors_editor_comment[] =
837 N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
838 "the commit.\n");
840 static void write_merge_heads(struct commit_list *);
841 static void prepare_to_commit(struct commit_list *remoteheads)
843 struct strbuf msg = STRBUF_INIT;
844 const char *index_file = get_index_file();
846 if (!no_verify && run_commit_hook(0 < option_edit, index_file, "pre-merge-commit", NULL))
847 abort_commit(remoteheads, NULL);
849 * Re-read the index as pre-merge-commit hook could have updated it,
850 * and write it out as a tree. We must do this before we invoke
851 * the editor and after we invoke run_status above.
853 if (hook_exists("pre-merge-commit"))
854 discard_cache();
855 read_cache_from(index_file);
856 strbuf_addbuf(&msg, &merge_msg);
857 if (squash)
858 BUG("the control must not reach here under --squash");
859 if (0 < option_edit) {
860 strbuf_addch(&msg, '\n');
861 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
862 wt_status_append_cut_line(&msg);
863 strbuf_commented_addf(&msg, "\n");
865 strbuf_commented_addf(&msg, _(merge_editor_comment));
866 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
867 strbuf_commented_addf(&msg, _(scissors_editor_comment));
868 else
869 strbuf_commented_addf(&msg,
870 _(no_scissors_editor_comment), comment_line_char);
872 if (signoff)
873 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
874 write_merge_heads(remoteheads);
875 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
876 if (run_commit_hook(0 < option_edit, get_index_file(), "prepare-commit-msg",
877 git_path_merge_msg(the_repository), "merge", NULL))
878 abort_commit(remoteheads, NULL);
879 if (0 < option_edit) {
880 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
881 abort_commit(remoteheads, NULL);
884 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
885 "commit-msg",
886 git_path_merge_msg(the_repository), NULL))
887 abort_commit(remoteheads, NULL);
889 read_merge_msg(&msg);
890 cleanup_message(&msg, cleanup_mode, 0);
891 if (!msg.len)
892 abort_commit(remoteheads, _("Empty commit message."));
893 strbuf_release(&merge_msg);
894 strbuf_addbuf(&merge_msg, &msg);
895 strbuf_release(&msg);
898 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
900 struct object_id result_tree, result_commit;
901 struct commit_list *parents, **pptr = &parents;
903 if (refresh_and_write_cache(REFRESH_QUIET, SKIP_IF_UNCHANGED, 0) < 0)
904 return error(_("Unable to write index."));
906 write_tree_trivial(&result_tree);
907 printf(_("Wonderful.\n"));
908 pptr = commit_list_append(head, pptr);
909 pptr = commit_list_append(remoteheads->item, pptr);
910 prepare_to_commit(remoteheads);
911 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
912 &result_commit, NULL, sign_commit))
913 die(_("failed to write commit object"));
914 finish(head, remoteheads, &result_commit, "In-index merge");
915 remove_merge_branch_state(the_repository);
916 return 0;
919 static int finish_automerge(struct commit *head,
920 int head_subsumed,
921 struct commit_list *common,
922 struct commit_list *remoteheads,
923 struct object_id *result_tree,
924 const char *wt_strategy)
926 struct commit_list *parents = NULL;
927 struct strbuf buf = STRBUF_INIT;
928 struct object_id result_commit;
930 write_tree_trivial(result_tree);
931 free_commit_list(common);
932 parents = remoteheads;
933 if (!head_subsumed || fast_forward == FF_NO)
934 commit_list_insert(head, &parents);
935 prepare_to_commit(remoteheads);
936 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
937 &result_commit, NULL, sign_commit))
938 die(_("failed to write commit object"));
939 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
940 finish(head, remoteheads, &result_commit, buf.buf);
941 strbuf_release(&buf);
942 remove_merge_branch_state(the_repository);
943 return 0;
946 static int suggest_conflicts(void)
948 const char *filename;
949 FILE *fp;
950 struct strbuf msgbuf = STRBUF_INIT;
952 filename = git_path_merge_msg(the_repository);
953 fp = xfopen(filename, "a");
956 * We can't use cleanup_mode because if we're not using the editor,
957 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
958 * though the message is meant to be processed later by git-commit.
959 * Thus, we will get the cleanup mode which is returned when we _are_
960 * using an editor.
962 append_conflicts_hint(&the_index, &msgbuf,
963 get_cleanup_mode(cleanup_arg, 1));
964 fputs(msgbuf.buf, fp);
965 strbuf_release(&msgbuf);
966 fclose(fp);
967 repo_rerere(the_repository, allow_rerere_auto);
968 printf(_("Automatic merge failed; "
969 "fix conflicts and then commit the result.\n"));
970 return 1;
973 static int evaluate_result(void)
975 int cnt = 0;
976 struct rev_info rev;
978 /* Check how many files differ. */
979 repo_init_revisions(the_repository, &rev, "");
980 setup_revisions(0, NULL, &rev, NULL);
981 rev.diffopt.output_format |=
982 DIFF_FORMAT_CALLBACK;
983 rev.diffopt.format_callback = count_diff_files;
984 rev.diffopt.format_callback_data = &cnt;
985 run_diff_files(&rev, 0);
988 * Check how many unmerged entries are
989 * there.
991 cnt += count_unmerged_entries();
993 return cnt;
997 * Pretend as if the user told us to merge with the remote-tracking
998 * branch we have for the upstream of the current branch
1000 static int setup_with_upstream(const char ***argv)
1002 struct branch *branch = branch_get(NULL);
1003 int i;
1004 const char **args;
1006 if (!branch)
1007 die(_("No current branch."));
1008 if (!branch->remote_name)
1009 die(_("No remote for the current branch."));
1010 if (!branch->merge_nr)
1011 die(_("No default upstream defined for the current branch."));
1013 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1014 for (i = 0; i < branch->merge_nr; i++) {
1015 if (!branch->merge[i]->dst)
1016 die(_("No remote-tracking branch for %s from %s"),
1017 branch->merge[i]->src, branch->remote_name);
1018 args[i] = branch->merge[i]->dst;
1020 args[i] = NULL;
1021 *argv = args;
1022 return i;
1025 static void write_merge_heads(struct commit_list *remoteheads)
1027 struct commit_list *j;
1028 struct strbuf buf = STRBUF_INIT;
1030 for (j = remoteheads; j; j = j->next) {
1031 struct object_id *oid;
1032 struct commit *c = j->item;
1033 struct merge_remote_desc *desc;
1035 desc = merge_remote_util(c);
1036 if (desc && desc->obj) {
1037 oid = &desc->obj->oid;
1038 } else {
1039 oid = &c->object.oid;
1041 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1043 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1045 strbuf_reset(&buf);
1046 if (fast_forward == FF_NO)
1047 strbuf_addstr(&buf, "no-ff");
1048 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1049 strbuf_release(&buf);
1052 static void write_merge_state(struct commit_list *remoteheads)
1054 write_merge_heads(remoteheads);
1055 strbuf_addch(&merge_msg, '\n');
1056 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1057 merge_msg.len);
1060 static int default_edit_option(void)
1062 static const char name[] = "GIT_MERGE_AUTOEDIT";
1063 const char *e = getenv(name);
1064 struct stat st_stdin, st_stdout;
1066 if (have_message)
1067 /* an explicit -m msg without --[no-]edit */
1068 return 0;
1070 if (e) {
1071 int v = git_parse_maybe_bool(e);
1072 if (v < 0)
1073 die(_("Bad value '%s' in environment '%s'"), e, name);
1074 return v;
1077 /* Use editor if stdin and stdout are the same and is a tty */
1078 return (!fstat(0, &st_stdin) &&
1079 !fstat(1, &st_stdout) &&
1080 isatty(0) && isatty(1) &&
1081 st_stdin.st_dev == st_stdout.st_dev &&
1082 st_stdin.st_ino == st_stdout.st_ino &&
1083 st_stdin.st_mode == st_stdout.st_mode);
1086 static struct commit_list *reduce_parents(struct commit *head_commit,
1087 int *head_subsumed,
1088 struct commit_list *remoteheads)
1090 struct commit_list *parents, **remotes;
1093 * Is the current HEAD reachable from another commit being
1094 * merged? If so we do not want to record it as a parent of
1095 * the resulting merge, unless --no-ff is given. We will flip
1096 * this variable to 0 when we find HEAD among the independent
1097 * tips being merged.
1099 *head_subsumed = 1;
1101 /* Find what parents to record by checking independent ones. */
1102 parents = reduce_heads(remoteheads);
1103 free_commit_list(remoteheads);
1105 remoteheads = NULL;
1106 remotes = &remoteheads;
1107 while (parents) {
1108 struct commit *commit = pop_commit(&parents);
1109 if (commit == head_commit)
1110 *head_subsumed = 0;
1111 else
1112 remotes = &commit_list_insert(commit, remotes)->next;
1114 return remoteheads;
1117 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1119 struct fmt_merge_msg_opts opts;
1121 memset(&opts, 0, sizeof(opts));
1122 opts.add_title = !have_message;
1123 opts.shortlog_len = shortlog_len;
1124 opts.credit_people = (0 < option_edit);
1126 fmt_merge_msg(merge_names, merge_msg, &opts);
1127 if (merge_msg->len)
1128 strbuf_setlen(merge_msg, merge_msg->len - 1);
1131 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1133 const char *filename;
1134 int fd, pos, npos;
1135 struct strbuf fetch_head_file = STRBUF_INIT;
1136 const unsigned hexsz = the_hash_algo->hexsz;
1138 if (!merge_names)
1139 merge_names = &fetch_head_file;
1141 filename = git_path_fetch_head(the_repository);
1142 fd = xopen(filename, O_RDONLY);
1144 if (strbuf_read(merge_names, fd, 0) < 0)
1145 die_errno(_("could not read '%s'"), filename);
1146 if (close(fd) < 0)
1147 die_errno(_("could not close '%s'"), filename);
1149 for (pos = 0; pos < merge_names->len; pos = npos) {
1150 struct object_id oid;
1151 char *ptr;
1152 struct commit *commit;
1154 ptr = strchr(merge_names->buf + pos, '\n');
1155 if (ptr)
1156 npos = ptr - merge_names->buf + 1;
1157 else
1158 npos = merge_names->len;
1160 if (npos - pos < hexsz + 2 ||
1161 get_oid_hex(merge_names->buf + pos, &oid))
1162 commit = NULL; /* bad */
1163 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1164 continue; /* not-for-merge */
1165 else {
1166 char saved = merge_names->buf[pos + hexsz];
1167 merge_names->buf[pos + hexsz] = '\0';
1168 commit = get_merge_parent(merge_names->buf + pos);
1169 merge_names->buf[pos + hexsz] = saved;
1171 if (!commit) {
1172 if (ptr)
1173 *ptr = '\0';
1174 die(_("not something we can merge in %s: %s"),
1175 filename, merge_names->buf + pos);
1177 remotes = &commit_list_insert(commit, remotes)->next;
1180 if (merge_names == &fetch_head_file)
1181 strbuf_release(&fetch_head_file);
1184 static struct commit_list *collect_parents(struct commit *head_commit,
1185 int *head_subsumed,
1186 int argc, const char **argv,
1187 struct strbuf *merge_msg)
1189 int i;
1190 struct commit_list *remoteheads = NULL;
1191 struct commit_list **remotes = &remoteheads;
1192 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1194 if (merge_msg && (!have_message || shortlog_len))
1195 autogen = &merge_names;
1197 if (head_commit)
1198 remotes = &commit_list_insert(head_commit, remotes)->next;
1200 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1201 handle_fetch_head(remotes, autogen);
1202 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1203 } else {
1204 for (i = 0; i < argc; i++) {
1205 struct commit *commit = get_merge_parent(argv[i]);
1206 if (!commit)
1207 help_unknown_ref(argv[i], "merge",
1208 _("not something we can merge"));
1209 remotes = &commit_list_insert(commit, remotes)->next;
1211 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1212 if (autogen) {
1213 struct commit_list *p;
1214 for (p = remoteheads; p; p = p->next)
1215 merge_name(merge_remote_util(p->item)->name, autogen);
1219 if (autogen) {
1220 prepare_merge_message(autogen, merge_msg);
1221 strbuf_release(autogen);
1224 return remoteheads;
1227 static int merging_a_throwaway_tag(struct commit *commit)
1229 char *tag_ref;
1230 struct object_id oid;
1231 int is_throwaway_tag = 0;
1233 /* Are we merging a tag? */
1234 if (!merge_remote_util(commit) ||
1235 !merge_remote_util(commit)->obj ||
1236 merge_remote_util(commit)->obj->type != OBJ_TAG)
1237 return is_throwaway_tag;
1240 * Now we know we are merging a tag object. Are we downstream
1241 * and following the tags from upstream? If so, we must have
1242 * the tag object pointed at by "refs/tags/$T" where $T is the
1243 * tagname recorded in the tag object. We want to allow such
1244 * a "just to catch up" merge to fast-forward.
1246 * Otherwise, we are playing an integrator's role, making a
1247 * merge with a throw-away tag from a contributor with
1248 * something like "git pull $contributor $signed_tag".
1249 * We want to forbid such a merge from fast-forwarding
1250 * by default; otherwise we would not keep the signature
1251 * anywhere.
1253 tag_ref = xstrfmt("refs/tags/%s",
1254 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1255 if (!read_ref(tag_ref, &oid) &&
1256 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1257 is_throwaway_tag = 0;
1258 else
1259 is_throwaway_tag = 1;
1260 free(tag_ref);
1261 return is_throwaway_tag;
1264 int cmd_merge(int argc, const char **argv, const char *prefix)
1266 struct object_id result_tree, stash, head_oid;
1267 struct commit *head_commit;
1268 struct strbuf buf = STRBUF_INIT;
1269 int i, ret = 0, head_subsumed;
1270 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1271 struct commit_list *common = NULL;
1272 const char *best_strategy = NULL, *wt_strategy = NULL;
1273 struct commit_list *remoteheads, *p;
1274 void *branch_to_free;
1275 int orig_argc = argc;
1277 if (argc == 2 && !strcmp(argv[1], "-h"))
1278 usage_with_options(builtin_merge_usage, builtin_merge_options);
1280 prepare_repo_settings(the_repository);
1281 the_repository->settings.command_requires_full_index = 0;
1284 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1285 * current branch.
1287 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1288 if (branch)
1289 skip_prefix(branch, "refs/heads/", &branch);
1291 if (!pull_twohead) {
1292 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1293 if (default_strategy && !strcmp(default_strategy, "ort"))
1294 pull_twohead = "ort";
1297 init_diff_ui_defaults();
1298 git_config(git_merge_config, NULL);
1300 if (!branch || is_null_oid(&head_oid))
1301 head_commit = NULL;
1302 else
1303 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1305 if (branch_mergeoptions)
1306 parse_branch_merge_options(branch_mergeoptions);
1307 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1308 builtin_merge_usage, 0);
1309 if (shortlog_len < 0)
1310 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1312 if (verbosity < 0 && show_progress == -1)
1313 show_progress = 0;
1315 if (abort_current_merge) {
1316 int nargc = 2;
1317 const char *nargv[] = {"reset", "--merge", NULL};
1318 struct strbuf stash_oid = STRBUF_INIT;
1320 if (orig_argc != 2)
1321 usage_msg_opt(_("--abort expects no arguments"),
1322 builtin_merge_usage, builtin_merge_options);
1324 if (!file_exists(git_path_merge_head(the_repository)))
1325 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1327 if (read_oneliner(&stash_oid, git_path_merge_autostash(the_repository),
1328 READ_ONELINER_SKIP_IF_EMPTY))
1329 unlink(git_path_merge_autostash(the_repository));
1331 /* Invoke 'git reset --merge' */
1332 ret = cmd_reset(nargc, nargv, prefix);
1334 if (stash_oid.len)
1335 apply_autostash_oid(stash_oid.buf);
1337 strbuf_release(&stash_oid);
1338 goto done;
1341 if (quit_current_merge) {
1342 if (orig_argc != 2)
1343 usage_msg_opt(_("--quit expects no arguments"),
1344 builtin_merge_usage,
1345 builtin_merge_options);
1347 remove_merge_branch_state(the_repository);
1348 goto done;
1351 if (continue_current_merge) {
1352 int nargc = 1;
1353 const char *nargv[] = {"commit", NULL};
1355 if (orig_argc != 2)
1356 usage_msg_opt(_("--continue expects no arguments"),
1357 builtin_merge_usage, builtin_merge_options);
1359 if (!file_exists(git_path_merge_head(the_repository)))
1360 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1362 /* Invoke 'git commit' */
1363 ret = cmd_commit(nargc, nargv, prefix);
1364 goto done;
1367 if (read_cache_unmerged())
1368 die_resolve_conflict("merge");
1370 if (file_exists(git_path_merge_head(the_repository))) {
1372 * There is no unmerged entry, don't advise 'git
1373 * add/rm <file>', just 'git commit'.
1375 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1376 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1377 "Please, commit your changes before you merge."));
1378 else
1379 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1381 if (ref_exists("CHERRY_PICK_HEAD")) {
1382 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1383 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1384 "Please, commit your changes before you merge."));
1385 else
1386 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1388 resolve_undo_clear();
1390 if (option_edit < 0)
1391 option_edit = default_edit_option();
1393 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1395 if (verbosity < 0)
1396 show_diffstat = 0;
1398 if (squash) {
1399 if (fast_forward == FF_NO)
1400 die(_("You cannot combine --squash with --no-ff."));
1401 if (option_commit > 0)
1402 die(_("You cannot combine --squash with --commit."));
1404 * squash can now silently disable option_commit - this is not
1405 * a problem as it is only overriding the default, not a user
1406 * supplied option.
1408 option_commit = 0;
1411 if (option_commit < 0)
1412 option_commit = 1;
1414 if (!argc) {
1415 if (default_to_upstream)
1416 argc = setup_with_upstream(&argv);
1417 else
1418 die(_("No commit specified and merge.defaultToUpstream not set."));
1419 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1420 argv[0] = "@{-1}";
1423 if (!argc)
1424 usage_with_options(builtin_merge_usage,
1425 builtin_merge_options);
1427 if (!head_commit) {
1429 * If the merged head is a valid one there is no reason
1430 * to forbid "git merge" into a branch yet to be born.
1431 * We do the same for "git pull".
1433 struct object_id *remote_head_oid;
1434 if (squash)
1435 die(_("Squash commit into empty head not supported yet"));
1436 if (fast_forward == FF_NO)
1437 die(_("Non-fast-forward commit does not make sense into "
1438 "an empty head"));
1439 remoteheads = collect_parents(head_commit, &head_subsumed,
1440 argc, argv, NULL);
1441 if (!remoteheads)
1442 die(_("%s - not something we can merge"), argv[0]);
1443 if (remoteheads->next)
1444 die(_("Can merge only exactly one commit into empty head"));
1446 if (verify_signatures)
1447 verify_merge_signature(remoteheads->item, verbosity,
1448 check_trust_level);
1450 remote_head_oid = &remoteheads->item->object.oid;
1451 read_empty(remote_head_oid, 0);
1452 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1453 UPDATE_REFS_DIE_ON_ERR);
1454 goto done;
1458 * All the rest are the commits being merged; prepare
1459 * the standard merge summary message to be appended
1460 * to the given message.
1462 remoteheads = collect_parents(head_commit, &head_subsumed,
1463 argc, argv, &merge_msg);
1465 if (!head_commit || !argc)
1466 usage_with_options(builtin_merge_usage,
1467 builtin_merge_options);
1469 if (verify_signatures) {
1470 for (p = remoteheads; p; p = p->next) {
1471 verify_merge_signature(p->item, verbosity,
1472 check_trust_level);
1476 strbuf_addstr(&buf, "merge");
1477 for (p = remoteheads; p; p = p->next)
1478 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1479 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1480 strbuf_reset(&buf);
1482 for (p = remoteheads; p; p = p->next) {
1483 struct commit *commit = p->item;
1484 strbuf_addf(&buf, "GITHEAD_%s",
1485 oid_to_hex(&commit->object.oid));
1486 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1487 strbuf_reset(&buf);
1488 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1489 fast_forward = FF_NO;
1492 if (!use_strategies && !pull_twohead &&
1493 remoteheads && !remoteheads->next) {
1494 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1495 if (default_strategy)
1496 append_strategy(get_strategy(default_strategy));
1498 if (!use_strategies) {
1499 if (!remoteheads)
1500 ; /* already up-to-date */
1501 else if (!remoteheads->next)
1502 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1503 else
1504 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1507 for (i = 0; i < use_strategies_nr; i++) {
1508 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1509 fast_forward = FF_NO;
1510 if (use_strategies[i]->attr & NO_TRIVIAL)
1511 allow_trivial = 0;
1514 if (!remoteheads)
1515 ; /* already up-to-date */
1516 else if (!remoteheads->next)
1517 common = get_merge_bases(head_commit, remoteheads->item);
1518 else {
1519 struct commit_list *list = remoteheads;
1520 commit_list_insert(head_commit, &list);
1521 common = get_octopus_merge_bases(list);
1522 free(list);
1525 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1526 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1528 if (remoteheads && !common) {
1529 /* No common ancestors found. */
1530 if (!allow_unrelated_histories)
1531 die(_("refusing to merge unrelated histories"));
1532 /* otherwise, we need a real merge. */
1533 } else if (!remoteheads ||
1534 (!remoteheads->next && !common->next &&
1535 common->item == remoteheads->item)) {
1537 * If head can reach all the merge then we are up to date.
1538 * but first the most common case of merging one remote.
1540 finish_up_to_date();
1541 goto done;
1542 } else if (fast_forward != FF_NO && !remoteheads->next &&
1543 !common->next &&
1544 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1545 /* Again the most common case of merging one remote. */
1546 struct strbuf msg = STRBUF_INIT;
1547 struct commit *commit;
1549 if (verbosity >= 0) {
1550 printf(_("Updating %s..%s\n"),
1551 find_unique_abbrev(&head_commit->object.oid,
1552 DEFAULT_ABBREV),
1553 find_unique_abbrev(&remoteheads->item->object.oid,
1554 DEFAULT_ABBREV));
1556 strbuf_addstr(&msg, "Fast-forward");
1557 if (have_message)
1558 strbuf_addstr(&msg,
1559 " (no commit created; -m option ignored)");
1560 commit = remoteheads->item;
1561 if (!commit) {
1562 ret = 1;
1563 goto done;
1566 if (autostash)
1567 create_autostash(the_repository,
1568 git_path_merge_autostash(the_repository),
1569 "merge");
1570 if (checkout_fast_forward(the_repository,
1571 &head_commit->object.oid,
1572 &commit->object.oid,
1573 overwrite_ignore)) {
1574 apply_autostash(git_path_merge_autostash(the_repository));
1575 ret = 1;
1576 goto done;
1579 finish(head_commit, remoteheads, &commit->object.oid, msg.buf);
1580 remove_merge_branch_state(the_repository);
1581 strbuf_release(&msg);
1582 goto done;
1583 } else if (!remoteheads->next && common->next)
1586 * We are not doing octopus and not fast-forward. Need
1587 * a real merge.
1589 else if (!remoteheads->next && !common->next && option_commit) {
1591 * We are not doing octopus, not fast-forward, and have
1592 * only one common.
1594 refresh_cache(REFRESH_QUIET);
1595 if (allow_trivial && fast_forward != FF_ONLY) {
1596 /* See if it is really trivial. */
1597 git_committer_info(IDENT_STRICT);
1598 printf(_("Trying really trivial in-index merge...\n"));
1599 if (!read_tree_trivial(&common->item->object.oid,
1600 &head_commit->object.oid,
1601 &remoteheads->item->object.oid)) {
1602 ret = merge_trivial(head_commit, remoteheads);
1603 goto done;
1605 printf(_("Nope.\n"));
1607 } else {
1609 * An octopus. If we can reach all the remote we are up
1610 * to date.
1612 int up_to_date = 1;
1613 struct commit_list *j;
1615 for (j = remoteheads; j; j = j->next) {
1616 struct commit_list *common_one;
1619 * Here we *have* to calculate the individual
1620 * merge_bases again, otherwise "git merge HEAD^
1621 * HEAD^^" would be missed.
1623 common_one = get_merge_bases(head_commit, j->item);
1624 if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1625 up_to_date = 0;
1626 break;
1629 if (up_to_date) {
1630 finish_up_to_date();
1631 goto done;
1635 if (fast_forward == FF_ONLY)
1636 die_ff_impossible();
1638 if (autostash)
1639 create_autostash(the_repository,
1640 git_path_merge_autostash(the_repository),
1641 "merge");
1643 /* We are going to make a new commit. */
1644 git_committer_info(IDENT_STRICT);
1647 * At this point, we need a real merge. No matter what strategy
1648 * we use, it would operate on the index, possibly affecting the
1649 * working tree, and when resolved cleanly, have the desired
1650 * tree in the index -- this means that the index must be in
1651 * sync with the head commit. The strategies are responsible
1652 * to ensure this.
1654 if (use_strategies_nr == 1 ||
1656 * Stash away the local changes so that we can try more than one.
1658 save_state(&stash))
1659 oidclr(&stash);
1661 for (i = 0; !merge_was_ok && i < use_strategies_nr; i++) {
1662 int ret, cnt;
1663 if (i) {
1664 printf(_("Rewinding the tree to pristine...\n"));
1665 restore_state(&head_commit->object.oid, &stash);
1667 if (use_strategies_nr != 1)
1668 printf(_("Trying merge strategy %s...\n"),
1669 use_strategies[i]->name);
1671 * Remember which strategy left the state in the working
1672 * tree.
1674 wt_strategy = use_strategies[i]->name;
1676 ret = try_merge_strategy(use_strategies[i]->name,
1677 common, remoteheads,
1678 head_commit);
1680 * The backend exits with 1 when conflicts are
1681 * left to be resolved, with 2 when it does not
1682 * handle the given merge at all.
1684 if (ret < 2) {
1685 if (!ret) {
1686 if (option_commit) {
1687 /* Automerge succeeded. */
1688 automerge_was_ok = 1;
1689 break;
1691 merge_was_ok = 1;
1693 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1694 if (best_cnt <= 0 || cnt <= best_cnt) {
1695 best_strategy = use_strategies[i]->name;
1696 best_cnt = cnt;
1702 * If we have a resulting tree, that means the strategy module
1703 * auto resolved the merge cleanly.
1705 if (automerge_was_ok) {
1706 ret = finish_automerge(head_commit, head_subsumed,
1707 common, remoteheads,
1708 &result_tree, wt_strategy);
1709 goto done;
1713 * Pick the result from the best strategy and have the user fix
1714 * it up.
1716 if (!best_strategy) {
1717 restore_state(&head_commit->object.oid, &stash);
1718 if (use_strategies_nr > 1)
1719 fprintf(stderr,
1720 _("No merge strategy handled the merge.\n"));
1721 else
1722 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1723 use_strategies[0]->name);
1724 apply_autostash(git_path_merge_autostash(the_repository));
1725 ret = 2;
1726 goto done;
1727 } else if (best_strategy == wt_strategy)
1728 ; /* We already have its result in the working tree. */
1729 else {
1730 printf(_("Rewinding the tree to pristine...\n"));
1731 restore_state(&head_commit->object.oid, &stash);
1732 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1733 best_strategy);
1734 try_merge_strategy(best_strategy, common, remoteheads,
1735 head_commit);
1738 if (squash) {
1739 finish(head_commit, remoteheads, NULL, NULL);
1741 git_test_write_commit_graph_or_die();
1742 } else
1743 write_merge_state(remoteheads);
1745 if (merge_was_ok)
1746 fprintf(stderr, _("Automatic merge went well; "
1747 "stopped before committing as requested\n"));
1748 else
1749 ret = suggest_conflicts();
1751 done:
1752 strbuf_release(&buf);
1753 free(branch_to_free);
1754 return ret;