Merge branch 'mt/grep-sparse-checkout'
[alt-git.git] / builtin / merge.c
blobeb00b273e668e2725447a2d6a0edc5ad2d67ed67
1 /*
2 * Builtin "git merge"
4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
7 */
9 #define USE_THE_INDEX_COMPATIBILITY_MACROS
10 #include "cache.h"
11 #include "config.h"
12 #include "parse-options.h"
13 #include "builtin.h"
14 #include "lockfile.h"
15 #include "run-command.h"
16 #include "diff.h"
17 #include "diff-merges.h"
18 #include "refs.h"
19 #include "refspec.h"
20 #include "commit.h"
21 #include "diffcore.h"
22 #include "revision.h"
23 #include "unpack-trees.h"
24 #include "cache-tree.h"
25 #include "dir.h"
26 #include "utf8.h"
27 #include "log-tree.h"
28 #include "color.h"
29 #include "rerere.h"
30 #include "help.h"
31 #include "merge-recursive.h"
32 #include "merge-ort-wrappers.h"
33 #include "resolve-undo.h"
34 #include "remote.h"
35 #include "fmt-merge-msg.h"
36 #include "gpg-interface.h"
37 #include "sequencer.h"
38 #include "string-list.h"
39 #include "packfile.h"
40 #include "tag.h"
41 #include "alias.h"
42 #include "branch.h"
43 #include "commit-reach.h"
44 #include "wt-status.h"
45 #include "commit-graph.h"
47 #define DEFAULT_TWOHEAD (1<<0)
48 #define DEFAULT_OCTOPUS (1<<1)
49 #define NO_FAST_FORWARD (1<<2)
50 #define NO_TRIVIAL (1<<3)
52 struct strategy {
53 const char *name;
54 unsigned attr;
57 static const char * const builtin_merge_usage[] = {
58 N_("git merge [<options>] [<commit>...]"),
59 N_("git merge --abort"),
60 N_("git merge --continue"),
61 NULL
64 static int show_diffstat = 1, shortlog_len = -1, squash;
65 static int option_commit = -1;
66 static int option_edit = -1;
67 static int allow_trivial = 1, have_message, verify_signatures;
68 static int check_trust_level = 1;
69 static int overwrite_ignore = 1;
70 static struct strbuf merge_msg = STRBUF_INIT;
71 static struct strategy **use_strategies;
72 static size_t use_strategies_nr, use_strategies_alloc;
73 static const char **xopts;
74 static size_t xopts_nr, xopts_alloc;
75 static const char *branch;
76 static char *branch_mergeoptions;
77 static int verbosity;
78 static int allow_rerere_auto;
79 static int abort_current_merge;
80 static int quit_current_merge;
81 static int continue_current_merge;
82 static int allow_unrelated_histories;
83 static int show_progress = -1;
84 static int default_to_upstream = 1;
85 static int signoff;
86 static const char *sign_commit;
87 static int autostash;
88 static int no_verify;
90 static struct strategy all_strategy[] = {
91 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
92 { "octopus", DEFAULT_OCTOPUS },
93 { "ort", NO_TRIVIAL },
94 { "resolve", 0 },
95 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
96 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
99 static const char *pull_twohead, *pull_octopus;
101 enum ff_type {
102 FF_NO,
103 FF_ALLOW,
104 FF_ONLY
107 static enum ff_type fast_forward = FF_ALLOW;
109 static const char *cleanup_arg;
110 static enum commit_msg_cleanup_mode cleanup_mode;
112 static int option_parse_message(const struct option *opt,
113 const char *arg, int unset)
115 struct strbuf *buf = opt->value;
117 if (unset)
118 strbuf_setlen(buf, 0);
119 else if (arg) {
120 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
121 have_message = 1;
122 } else
123 return error(_("switch `m' requires a value"));
124 return 0;
127 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
128 const struct option *opt,
129 const char *arg_not_used,
130 int unset)
132 struct strbuf *buf = opt->value;
133 const char *arg;
135 BUG_ON_OPT_ARG(arg_not_used);
136 if (unset)
137 BUG("-F cannot be negated");
139 if (ctx->opt) {
140 arg = ctx->opt;
141 ctx->opt = NULL;
142 } else if (ctx->argc > 1) {
143 ctx->argc--;
144 arg = *++ctx->argv;
145 } else
146 return error(_("option `%s' requires a value"), opt->long_name);
148 if (buf->len)
149 strbuf_addch(buf, '\n');
150 if (ctx->prefix && !is_absolute_path(arg))
151 arg = prefix_filename(ctx->prefix, arg);
152 if (strbuf_read_file(buf, arg, 0) < 0)
153 return error(_("could not read file '%s'"), arg);
154 have_message = 1;
156 return 0;
159 static struct strategy *get_strategy(const char *name)
161 int i;
162 struct strategy *ret;
163 static struct cmdnames main_cmds, other_cmds;
164 static int loaded;
165 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
167 if (!name)
168 return NULL;
170 if (default_strategy &&
171 !strcmp(default_strategy, "ort") &&
172 !strcmp(name, "recursive")) {
173 name = "ort";
176 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
177 if (!strcmp(name, all_strategy[i].name))
178 return &all_strategy[i];
180 if (!loaded) {
181 struct cmdnames not_strategies;
182 loaded = 1;
184 memset(&not_strategies, 0, sizeof(struct cmdnames));
185 load_command_list("git-merge-", &main_cmds, &other_cmds);
186 for (i = 0; i < main_cmds.cnt; i++) {
187 int j, found = 0;
188 struct cmdname *ent = main_cmds.names[i];
189 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
190 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
191 && !all_strategy[j].name[ent->len])
192 found = 1;
193 if (!found)
194 add_cmdname(&not_strategies, ent->name, ent->len);
196 exclude_cmds(&main_cmds, &not_strategies);
198 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
199 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
200 fprintf(stderr, _("Available strategies are:"));
201 for (i = 0; i < main_cmds.cnt; i++)
202 fprintf(stderr, " %s", main_cmds.names[i]->name);
203 fprintf(stderr, ".\n");
204 if (other_cmds.cnt) {
205 fprintf(stderr, _("Available custom strategies are:"));
206 for (i = 0; i < other_cmds.cnt; i++)
207 fprintf(stderr, " %s", other_cmds.names[i]->name);
208 fprintf(stderr, ".\n");
210 exit(1);
213 ret = xcalloc(1, sizeof(struct strategy));
214 ret->name = xstrdup(name);
215 ret->attr = NO_TRIVIAL;
216 return ret;
219 static void append_strategy(struct strategy *s)
221 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
222 use_strategies[use_strategies_nr++] = s;
225 static int option_parse_strategy(const struct option *opt,
226 const char *name, int unset)
228 if (unset)
229 return 0;
231 append_strategy(get_strategy(name));
232 return 0;
235 static int option_parse_x(const struct option *opt,
236 const char *arg, int unset)
238 if (unset)
239 return 0;
241 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
242 xopts[xopts_nr++] = xstrdup(arg);
243 return 0;
246 static int option_parse_n(const struct option *opt,
247 const char *arg, int unset)
249 BUG_ON_OPT_ARG(arg);
250 show_diffstat = unset;
251 return 0;
254 static struct option builtin_merge_options[] = {
255 OPT_CALLBACK_F('n', NULL, NULL, NULL,
256 N_("do not show a diffstat at the end of the merge"),
257 PARSE_OPT_NOARG, option_parse_n),
258 OPT_BOOL(0, "stat", &show_diffstat,
259 N_("show a diffstat at the end of the merge")),
260 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
261 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
262 N_("add (at most <n>) entries from shortlog to merge commit message"),
263 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
264 OPT_BOOL(0, "squash", &squash,
265 N_("create a single commit instead of doing a merge")),
266 OPT_BOOL(0, "commit", &option_commit,
267 N_("perform a commit if the merge succeeds (default)")),
268 OPT_BOOL('e', "edit", &option_edit,
269 N_("edit message before committing")),
270 OPT_CLEANUP(&cleanup_arg),
271 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
272 OPT_SET_INT_F(0, "ff-only", &fast_forward,
273 N_("abort if fast-forward is not possible"),
274 FF_ONLY, PARSE_OPT_NONEG),
275 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
276 OPT_BOOL(0, "verify-signatures", &verify_signatures,
277 N_("verify that the named commit has a valid GPG signature")),
278 OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
279 N_("merge strategy to use"), option_parse_strategy),
280 OPT_CALLBACK('X', "strategy-option", &xopts, N_("option=value"),
281 N_("option for selected merge strategy"), option_parse_x),
282 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
283 N_("merge commit message (for a non-fast-forward merge)"),
284 option_parse_message),
285 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
286 N_("read message from file"), PARSE_OPT_NONEG,
287 NULL, 0, option_read_message },
288 OPT__VERBOSITY(&verbosity),
289 OPT_BOOL(0, "abort", &abort_current_merge,
290 N_("abort the current in-progress merge")),
291 OPT_BOOL(0, "quit", &quit_current_merge,
292 N_("--abort but leave index and working tree alone")),
293 OPT_BOOL(0, "continue", &continue_current_merge,
294 N_("continue the current in-progress merge")),
295 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
296 N_("allow merging unrelated histories")),
297 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
298 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
299 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
300 OPT_AUTOSTASH(&autostash),
301 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
302 OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
303 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
304 OPT_END()
307 static int save_state(struct object_id *stash)
309 int len;
310 struct child_process cp = CHILD_PROCESS_INIT;
311 struct strbuf buffer = STRBUF_INIT;
312 const char *argv[] = {"stash", "create", NULL};
313 int rc = -1;
315 cp.argv = argv;
316 cp.out = -1;
317 cp.git_cmd = 1;
319 if (start_command(&cp))
320 die(_("could not run stash."));
321 len = strbuf_read(&buffer, cp.out, 1024);
322 close(cp.out);
324 if (finish_command(&cp) || len < 0)
325 die(_("stash failed"));
326 else if (!len) /* no changes */
327 goto out;
328 strbuf_setlen(&buffer, buffer.len-1);
329 if (get_oid(buffer.buf, stash))
330 die(_("not a valid object: %s"), buffer.buf);
331 rc = 0;
332 out:
333 strbuf_release(&buffer);
334 return rc;
337 static void read_empty(const struct object_id *oid, int verbose)
339 int i = 0;
340 const char *args[7];
342 args[i++] = "read-tree";
343 if (verbose)
344 args[i++] = "-v";
345 args[i++] = "-m";
346 args[i++] = "-u";
347 args[i++] = empty_tree_oid_hex();
348 args[i++] = oid_to_hex(oid);
349 args[i] = NULL;
351 if (run_command_v_opt(args, RUN_GIT_CMD))
352 die(_("read-tree failed"));
355 static void reset_hard(const struct object_id *oid, int verbose)
357 int i = 0;
358 const char *args[6];
360 args[i++] = "read-tree";
361 if (verbose)
362 args[i++] = "-v";
363 args[i++] = "--reset";
364 args[i++] = "-u";
365 args[i++] = oid_to_hex(oid);
366 args[i] = NULL;
368 if (run_command_v_opt(args, RUN_GIT_CMD))
369 die(_("read-tree failed"));
372 static void restore_state(const struct object_id *head,
373 const struct object_id *stash)
375 struct strbuf sb = STRBUF_INIT;
376 const char *args[] = { "stash", "apply", NULL, NULL };
378 if (is_null_oid(stash))
379 return;
381 reset_hard(head, 1);
383 args[2] = oid_to_hex(stash);
386 * It is OK to ignore error here, for example when there was
387 * nothing to restore.
389 run_command_v_opt(args, RUN_GIT_CMD);
391 strbuf_release(&sb);
392 refresh_cache(REFRESH_QUIET);
395 /* This is called when no merge was necessary. */
396 static void finish_up_to_date(const char *msg)
398 if (verbosity >= 0)
399 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
400 remove_merge_branch_state(the_repository);
403 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
405 struct rev_info rev;
406 struct strbuf out = STRBUF_INIT;
407 struct commit_list *j;
408 struct pretty_print_context ctx = {0};
410 printf(_("Squash commit -- not updating HEAD\n"));
412 repo_init_revisions(the_repository, &rev, NULL);
413 diff_merges_suppress(&rev);
414 rev.commit_format = CMIT_FMT_MEDIUM;
416 commit->object.flags |= UNINTERESTING;
417 add_pending_object(&rev, &commit->object, NULL);
419 for (j = remoteheads; j; j = j->next)
420 add_pending_object(&rev, &j->item->object, NULL);
422 setup_revisions(0, NULL, &rev, NULL);
423 if (prepare_revision_walk(&rev))
424 die(_("revision walk setup failed"));
426 ctx.abbrev = rev.abbrev;
427 ctx.date_mode = rev.date_mode;
428 ctx.fmt = rev.commit_format;
430 strbuf_addstr(&out, "Squashed commit of the following:\n");
431 while ((commit = get_revision(&rev)) != NULL) {
432 strbuf_addch(&out, '\n');
433 strbuf_addf(&out, "commit %s\n",
434 oid_to_hex(&commit->object.oid));
435 pretty_print_commit(&ctx, commit, &out);
437 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
438 strbuf_release(&out);
441 static void finish(struct commit *head_commit,
442 struct commit_list *remoteheads,
443 const struct object_id *new_head, const char *msg)
445 struct strbuf reflog_message = STRBUF_INIT;
446 const struct object_id *head = &head_commit->object.oid;
448 if (!msg)
449 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
450 else {
451 if (verbosity >= 0)
452 printf("%s\n", msg);
453 strbuf_addf(&reflog_message, "%s: %s",
454 getenv("GIT_REFLOG_ACTION"), msg);
456 if (squash) {
457 squash_message(head_commit, remoteheads);
458 } else {
459 if (verbosity >= 0 && !merge_msg.len)
460 printf(_("No merge message -- not updating HEAD\n"));
461 else {
462 update_ref(reflog_message.buf, "HEAD", new_head, head,
463 0, UPDATE_REFS_DIE_ON_ERR);
465 * We ignore errors in 'gc --auto', since the
466 * user should see them.
468 close_object_store(the_repository->objects);
469 run_auto_maintenance(verbosity < 0);
472 if (new_head && show_diffstat) {
473 struct diff_options opts;
474 repo_diff_setup(the_repository, &opts);
475 opts.stat_width = -1; /* use full terminal width */
476 opts.stat_graph_width = -1; /* respect statGraphWidth config */
477 opts.output_format |=
478 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
479 opts.detect_rename = DIFF_DETECT_RENAME;
480 diff_setup_done(&opts);
481 diff_tree_oid(head, new_head, "", &opts);
482 diffcore_std(&opts);
483 diff_flush(&opts);
486 /* Run a post-merge hook */
487 run_hook_le(NULL, "post-merge", squash ? "1" : "0", NULL);
489 apply_autostash(git_path_merge_autostash(the_repository));
490 strbuf_release(&reflog_message);
493 /* Get the name for the merge commit's message. */
494 static void merge_name(const char *remote, struct strbuf *msg)
496 struct commit *remote_head;
497 struct object_id branch_head;
498 struct strbuf buf = STRBUF_INIT;
499 struct strbuf bname = STRBUF_INIT;
500 struct merge_remote_desc *desc;
501 const char *ptr;
502 char *found_ref;
503 int len, early;
505 strbuf_branchname(&bname, remote, 0);
506 remote = bname.buf;
508 oidclr(&branch_head);
509 remote_head = get_merge_parent(remote);
510 if (!remote_head)
511 die(_("'%s' does not point to a commit"), remote);
513 if (dwim_ref(remote, strlen(remote), &branch_head, &found_ref, 0) > 0) {
514 if (starts_with(found_ref, "refs/heads/")) {
515 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
516 oid_to_hex(&branch_head), remote);
517 goto cleanup;
519 if (starts_with(found_ref, "refs/tags/")) {
520 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
521 oid_to_hex(&branch_head), remote);
522 goto cleanup;
524 if (starts_with(found_ref, "refs/remotes/")) {
525 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
526 oid_to_hex(&branch_head), remote);
527 goto cleanup;
531 /* See if remote matches <name>^^^.. or <name>~<number> */
532 for (len = 0, ptr = remote + strlen(remote);
533 remote < ptr && ptr[-1] == '^';
534 ptr--)
535 len++;
536 if (len)
537 early = 1;
538 else {
539 early = 0;
540 ptr = strrchr(remote, '~');
541 if (ptr) {
542 int seen_nonzero = 0;
544 len++; /* count ~ */
545 while (*++ptr && isdigit(*ptr)) {
546 seen_nonzero |= (*ptr != '0');
547 len++;
549 if (*ptr)
550 len = 0; /* not ...~<number> */
551 else if (seen_nonzero)
552 early = 1;
553 else if (len == 1)
554 early = 1; /* "name~" is "name~1"! */
557 if (len) {
558 struct strbuf truname = STRBUF_INIT;
559 strbuf_addf(&truname, "refs/heads/%s", remote);
560 strbuf_setlen(&truname, truname.len - len);
561 if (ref_exists(truname.buf)) {
562 strbuf_addf(msg,
563 "%s\t\tbranch '%s'%s of .\n",
564 oid_to_hex(&remote_head->object.oid),
565 truname.buf + 11,
566 (early ? " (early part)" : ""));
567 strbuf_release(&truname);
568 goto cleanup;
570 strbuf_release(&truname);
573 desc = merge_remote_util(remote_head);
574 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
575 strbuf_addf(msg, "%s\t\t%s '%s'\n",
576 oid_to_hex(&desc->obj->oid),
577 type_name(desc->obj->type),
578 remote);
579 goto cleanup;
582 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
583 oid_to_hex(&remote_head->object.oid), remote);
584 cleanup:
585 strbuf_release(&buf);
586 strbuf_release(&bname);
589 static void parse_branch_merge_options(char *bmo)
591 const char **argv;
592 int argc;
594 if (!bmo)
595 return;
596 argc = split_cmdline(bmo, &argv);
597 if (argc < 0)
598 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
599 _(split_cmdline_strerror(argc)));
600 REALLOC_ARRAY(argv, argc + 2);
601 MOVE_ARRAY(argv + 1, argv, argc + 1);
602 argc++;
603 argv[0] = "branch.*.mergeoptions";
604 parse_options(argc, argv, NULL, builtin_merge_options,
605 builtin_merge_usage, 0);
606 free(argv);
609 static int git_merge_config(const char *k, const char *v, void *cb)
611 int status;
612 const char *str;
614 if (branch &&
615 skip_prefix(k, "branch.", &str) &&
616 skip_prefix(str, branch, &str) &&
617 !strcmp(str, ".mergeoptions")) {
618 free(branch_mergeoptions);
619 branch_mergeoptions = xstrdup(v);
620 return 0;
623 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
624 show_diffstat = git_config_bool(k, v);
625 else if (!strcmp(k, "merge.verifysignatures"))
626 verify_signatures = git_config_bool(k, v);
627 else if (!strcmp(k, "pull.twohead"))
628 return git_config_string(&pull_twohead, k, v);
629 else if (!strcmp(k, "pull.octopus"))
630 return git_config_string(&pull_octopus, k, v);
631 else if (!strcmp(k, "commit.cleanup"))
632 return git_config_string(&cleanup_arg, k, v);
633 else if (!strcmp(k, "merge.ff")) {
634 int boolval = git_parse_maybe_bool(v);
635 if (0 <= boolval) {
636 fast_forward = boolval ? FF_ALLOW : FF_NO;
637 } else if (v && !strcmp(v, "only")) {
638 fast_forward = FF_ONLY;
639 } /* do not barf on values from future versions of git */
640 return 0;
641 } else if (!strcmp(k, "merge.defaulttoupstream")) {
642 default_to_upstream = git_config_bool(k, v);
643 return 0;
644 } else if (!strcmp(k, "commit.gpgsign")) {
645 sign_commit = git_config_bool(k, v) ? "" : NULL;
646 return 0;
647 } else if (!strcmp(k, "gpg.mintrustlevel")) {
648 check_trust_level = 0;
649 } else if (!strcmp(k, "merge.autostash")) {
650 autostash = git_config_bool(k, v);
651 return 0;
654 status = fmt_merge_msg_config(k, v, cb);
655 if (status)
656 return status;
657 status = git_gpg_config(k, v, NULL);
658 if (status)
659 return status;
660 return git_diff_ui_config(k, v, cb);
663 static int read_tree_trivial(struct object_id *common, struct object_id *head,
664 struct object_id *one)
666 int i, nr_trees = 0;
667 struct tree *trees[MAX_UNPACK_TREES];
668 struct tree_desc t[MAX_UNPACK_TREES];
669 struct unpack_trees_options opts;
671 memset(&opts, 0, sizeof(opts));
672 opts.head_idx = 2;
673 opts.src_index = &the_index;
674 opts.dst_index = &the_index;
675 opts.update = 1;
676 opts.verbose_update = 1;
677 opts.trivial_merges_only = 1;
678 opts.merge = 1;
679 trees[nr_trees] = parse_tree_indirect(common);
680 if (!trees[nr_trees++])
681 return -1;
682 trees[nr_trees] = parse_tree_indirect(head);
683 if (!trees[nr_trees++])
684 return -1;
685 trees[nr_trees] = parse_tree_indirect(one);
686 if (!trees[nr_trees++])
687 return -1;
688 opts.fn = threeway_merge;
689 cache_tree_free(&active_cache_tree);
690 for (i = 0; i < nr_trees; i++) {
691 parse_tree(trees[i]);
692 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
694 if (unpack_trees(nr_trees, t, &opts))
695 return -1;
696 return 0;
699 static void write_tree_trivial(struct object_id *oid)
701 if (write_cache_as_tree(oid, 0, NULL))
702 die(_("git write-tree failed to write a tree"));
705 static int try_merge_strategy(const char *strategy, struct commit_list *common,
706 struct commit_list *remoteheads,
707 struct commit *head)
709 const char *head_arg = "HEAD";
711 if (refresh_and_write_cache(REFRESH_QUIET, SKIP_IF_UNCHANGED, 0) < 0)
712 return error(_("Unable to write index."));
714 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
715 !strcmp(strategy, "ort")) {
716 struct lock_file lock = LOCK_INIT;
717 int clean, x;
718 struct commit *result;
719 struct commit_list *reversed = NULL;
720 struct merge_options o;
721 struct commit_list *j;
723 if (remoteheads->next) {
724 error(_("Not handling anything other than two heads merge."));
725 return 2;
728 init_merge_options(&o, the_repository);
729 if (!strcmp(strategy, "subtree"))
730 o.subtree_shift = "";
732 o.show_rename_progress =
733 show_progress == -1 ? isatty(2) : show_progress;
735 for (x = 0; x < xopts_nr; x++)
736 if (parse_merge_opt(&o, xopts[x]))
737 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
739 o.branch1 = head_arg;
740 o.branch2 = merge_remote_util(remoteheads->item)->name;
742 for (j = common; j; j = j->next)
743 commit_list_insert(j->item, &reversed);
745 hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
746 if (!strcmp(strategy, "ort"))
747 clean = merge_ort_recursive(&o, head, remoteheads->item,
748 reversed, &result);
749 else
750 clean = merge_recursive(&o, head, remoteheads->item,
751 reversed, &result);
752 if (clean < 0)
753 exit(128);
754 if (write_locked_index(&the_index, &lock,
755 COMMIT_LOCK | SKIP_IF_UNCHANGED))
756 die(_("unable to write %s"), get_index_file());
757 return clean ? 0 : 1;
758 } else {
759 return try_merge_command(the_repository,
760 strategy, xopts_nr, xopts,
761 common, head_arg, remoteheads);
765 static void count_diff_files(struct diff_queue_struct *q,
766 struct diff_options *opt, void *data)
768 int *count = data;
770 (*count) += q->nr;
773 static int count_unmerged_entries(void)
775 int i, ret = 0;
777 for (i = 0; i < active_nr; i++)
778 if (ce_stage(active_cache[i]))
779 ret++;
781 return ret;
784 static void add_strategies(const char *string, unsigned attr)
786 int i;
788 if (string) {
789 struct string_list list = STRING_LIST_INIT_DUP;
790 struct string_list_item *item;
791 string_list_split(&list, string, ' ', -1);
792 for_each_string_list_item(item, &list)
793 append_strategy(get_strategy(item->string));
794 string_list_clear(&list, 0);
795 return;
797 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
798 if (all_strategy[i].attr & attr)
799 append_strategy(&all_strategy[i]);
803 static void read_merge_msg(struct strbuf *msg)
805 const char *filename = git_path_merge_msg(the_repository);
806 strbuf_reset(msg);
807 if (strbuf_read_file(msg, filename, 0) < 0)
808 die_errno(_("Could not read from '%s'"), filename);
811 static void write_merge_state(struct commit_list *);
812 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
814 if (err_msg)
815 error("%s", err_msg);
816 fprintf(stderr,
817 _("Not committing merge; use 'git commit' to complete the merge.\n"));
818 write_merge_state(remoteheads);
819 exit(1);
822 static const char merge_editor_comment[] =
823 N_("Please enter a commit message to explain why this merge is necessary,\n"
824 "especially if it merges an updated upstream into a topic branch.\n"
825 "\n");
827 static const char scissors_editor_comment[] =
828 N_("An empty message aborts the commit.\n");
830 static const char no_scissors_editor_comment[] =
831 N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
832 "the commit.\n");
834 static void write_merge_heads(struct commit_list *);
835 static void prepare_to_commit(struct commit_list *remoteheads)
837 struct strbuf msg = STRBUF_INIT;
838 const char *index_file = get_index_file();
840 if (!no_verify && run_commit_hook(0 < option_edit, index_file, "pre-merge-commit", NULL))
841 abort_commit(remoteheads, NULL);
843 * Re-read the index as pre-merge-commit hook could have updated it,
844 * and write it out as a tree. We must do this before we invoke
845 * the editor and after we invoke run_status above.
847 if (find_hook("pre-merge-commit"))
848 discard_cache();
849 read_cache_from(index_file);
850 strbuf_addbuf(&msg, &merge_msg);
851 if (squash)
852 BUG("the control must not reach here under --squash");
853 if (0 < option_edit) {
854 strbuf_addch(&msg, '\n');
855 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
856 wt_status_append_cut_line(&msg);
857 strbuf_commented_addf(&msg, "\n");
859 strbuf_commented_addf(&msg, _(merge_editor_comment));
860 strbuf_commented_addf(&msg, _(cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS ?
861 scissors_editor_comment :
862 no_scissors_editor_comment), comment_line_char);
864 if (signoff)
865 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
866 write_merge_heads(remoteheads);
867 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
868 if (run_commit_hook(0 < option_edit, get_index_file(), "prepare-commit-msg",
869 git_path_merge_msg(the_repository), "merge", NULL))
870 abort_commit(remoteheads, NULL);
871 if (0 < option_edit) {
872 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
873 abort_commit(remoteheads, NULL);
876 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
877 "commit-msg",
878 git_path_merge_msg(the_repository), NULL))
879 abort_commit(remoteheads, NULL);
881 read_merge_msg(&msg);
882 cleanup_message(&msg, cleanup_mode, 0);
883 if (!msg.len)
884 abort_commit(remoteheads, _("Empty commit message."));
885 strbuf_release(&merge_msg);
886 strbuf_addbuf(&merge_msg, &msg);
887 strbuf_release(&msg);
890 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
892 struct object_id result_tree, result_commit;
893 struct commit_list *parents, **pptr = &parents;
895 if (refresh_and_write_cache(REFRESH_QUIET, SKIP_IF_UNCHANGED, 0) < 0)
896 return error(_("Unable to write index."));
898 write_tree_trivial(&result_tree);
899 printf(_("Wonderful.\n"));
900 pptr = commit_list_append(head, pptr);
901 pptr = commit_list_append(remoteheads->item, pptr);
902 prepare_to_commit(remoteheads);
903 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
904 &result_commit, NULL, sign_commit))
905 die(_("failed to write commit object"));
906 finish(head, remoteheads, &result_commit, "In-index merge");
907 remove_merge_branch_state(the_repository);
908 return 0;
911 static int finish_automerge(struct commit *head,
912 int head_subsumed,
913 struct commit_list *common,
914 struct commit_list *remoteheads,
915 struct object_id *result_tree,
916 const char *wt_strategy)
918 struct commit_list *parents = NULL;
919 struct strbuf buf = STRBUF_INIT;
920 struct object_id result_commit;
922 write_tree_trivial(result_tree);
923 free_commit_list(common);
924 parents = remoteheads;
925 if (!head_subsumed || fast_forward == FF_NO)
926 commit_list_insert(head, &parents);
927 prepare_to_commit(remoteheads);
928 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
929 &result_commit, NULL, sign_commit))
930 die(_("failed to write commit object"));
931 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
932 finish(head, remoteheads, &result_commit, buf.buf);
933 strbuf_release(&buf);
934 remove_merge_branch_state(the_repository);
935 return 0;
938 static int suggest_conflicts(void)
940 const char *filename;
941 FILE *fp;
942 struct strbuf msgbuf = STRBUF_INIT;
944 filename = git_path_merge_msg(the_repository);
945 fp = xfopen(filename, "a");
948 * We can't use cleanup_mode because if we're not using the editor,
949 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
950 * though the message is meant to be processed later by git-commit.
951 * Thus, we will get the cleanup mode which is returned when we _are_
952 * using an editor.
954 append_conflicts_hint(&the_index, &msgbuf,
955 get_cleanup_mode(cleanup_arg, 1));
956 fputs(msgbuf.buf, fp);
957 strbuf_release(&msgbuf);
958 fclose(fp);
959 repo_rerere(the_repository, allow_rerere_auto);
960 printf(_("Automatic merge failed; "
961 "fix conflicts and then commit the result.\n"));
962 return 1;
965 static int evaluate_result(void)
967 int cnt = 0;
968 struct rev_info rev;
970 /* Check how many files differ. */
971 repo_init_revisions(the_repository, &rev, "");
972 setup_revisions(0, NULL, &rev, NULL);
973 rev.diffopt.output_format |=
974 DIFF_FORMAT_CALLBACK;
975 rev.diffopt.format_callback = count_diff_files;
976 rev.diffopt.format_callback_data = &cnt;
977 run_diff_files(&rev, 0);
980 * Check how many unmerged entries are
981 * there.
983 cnt += count_unmerged_entries();
985 return cnt;
989 * Pretend as if the user told us to merge with the remote-tracking
990 * branch we have for the upstream of the current branch
992 static int setup_with_upstream(const char ***argv)
994 struct branch *branch = branch_get(NULL);
995 int i;
996 const char **args;
998 if (!branch)
999 die(_("No current branch."));
1000 if (!branch->remote_name)
1001 die(_("No remote for the current branch."));
1002 if (!branch->merge_nr)
1003 die(_("No default upstream defined for the current branch."));
1005 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1006 for (i = 0; i < branch->merge_nr; i++) {
1007 if (!branch->merge[i]->dst)
1008 die(_("No remote-tracking branch for %s from %s"),
1009 branch->merge[i]->src, branch->remote_name);
1010 args[i] = branch->merge[i]->dst;
1012 args[i] = NULL;
1013 *argv = args;
1014 return i;
1017 static void write_merge_heads(struct commit_list *remoteheads)
1019 struct commit_list *j;
1020 struct strbuf buf = STRBUF_INIT;
1022 for (j = remoteheads; j; j = j->next) {
1023 struct object_id *oid;
1024 struct commit *c = j->item;
1025 struct merge_remote_desc *desc;
1027 desc = merge_remote_util(c);
1028 if (desc && desc->obj) {
1029 oid = &desc->obj->oid;
1030 } else {
1031 oid = &c->object.oid;
1033 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1035 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1037 strbuf_reset(&buf);
1038 if (fast_forward == FF_NO)
1039 strbuf_addstr(&buf, "no-ff");
1040 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1041 strbuf_release(&buf);
1044 static void write_merge_state(struct commit_list *remoteheads)
1046 write_merge_heads(remoteheads);
1047 strbuf_addch(&merge_msg, '\n');
1048 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1049 merge_msg.len);
1052 static int default_edit_option(void)
1054 static const char name[] = "GIT_MERGE_AUTOEDIT";
1055 const char *e = getenv(name);
1056 struct stat st_stdin, st_stdout;
1058 if (have_message)
1059 /* an explicit -m msg without --[no-]edit */
1060 return 0;
1062 if (e) {
1063 int v = git_parse_maybe_bool(e);
1064 if (v < 0)
1065 die(_("Bad value '%s' in environment '%s'"), e, name);
1066 return v;
1069 /* Use editor if stdin and stdout are the same and is a tty */
1070 return (!fstat(0, &st_stdin) &&
1071 !fstat(1, &st_stdout) &&
1072 isatty(0) && isatty(1) &&
1073 st_stdin.st_dev == st_stdout.st_dev &&
1074 st_stdin.st_ino == st_stdout.st_ino &&
1075 st_stdin.st_mode == st_stdout.st_mode);
1078 static struct commit_list *reduce_parents(struct commit *head_commit,
1079 int *head_subsumed,
1080 struct commit_list *remoteheads)
1082 struct commit_list *parents, **remotes;
1085 * Is the current HEAD reachable from another commit being
1086 * merged? If so we do not want to record it as a parent of
1087 * the resulting merge, unless --no-ff is given. We will flip
1088 * this variable to 0 when we find HEAD among the independent
1089 * tips being merged.
1091 *head_subsumed = 1;
1093 /* Find what parents to record by checking independent ones. */
1094 parents = reduce_heads(remoteheads);
1095 free_commit_list(remoteheads);
1097 remoteheads = NULL;
1098 remotes = &remoteheads;
1099 while (parents) {
1100 struct commit *commit = pop_commit(&parents);
1101 if (commit == head_commit)
1102 *head_subsumed = 0;
1103 else
1104 remotes = &commit_list_insert(commit, remotes)->next;
1106 return remoteheads;
1109 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1111 struct fmt_merge_msg_opts opts;
1113 memset(&opts, 0, sizeof(opts));
1114 opts.add_title = !have_message;
1115 opts.shortlog_len = shortlog_len;
1116 opts.credit_people = (0 < option_edit);
1118 fmt_merge_msg(merge_names, merge_msg, &opts);
1119 if (merge_msg->len)
1120 strbuf_setlen(merge_msg, merge_msg->len - 1);
1123 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1125 const char *filename;
1126 int fd, pos, npos;
1127 struct strbuf fetch_head_file = STRBUF_INIT;
1128 const unsigned hexsz = the_hash_algo->hexsz;
1130 if (!merge_names)
1131 merge_names = &fetch_head_file;
1133 filename = git_path_fetch_head(the_repository);
1134 fd = open(filename, O_RDONLY);
1135 if (fd < 0)
1136 die_errno(_("could not open '%s' for reading"), filename);
1138 if (strbuf_read(merge_names, fd, 0) < 0)
1139 die_errno(_("could not read '%s'"), filename);
1140 if (close(fd) < 0)
1141 die_errno(_("could not close '%s'"), filename);
1143 for (pos = 0; pos < merge_names->len; pos = npos) {
1144 struct object_id oid;
1145 char *ptr;
1146 struct commit *commit;
1148 ptr = strchr(merge_names->buf + pos, '\n');
1149 if (ptr)
1150 npos = ptr - merge_names->buf + 1;
1151 else
1152 npos = merge_names->len;
1154 if (npos - pos < hexsz + 2 ||
1155 get_oid_hex(merge_names->buf + pos, &oid))
1156 commit = NULL; /* bad */
1157 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1158 continue; /* not-for-merge */
1159 else {
1160 char saved = merge_names->buf[pos + hexsz];
1161 merge_names->buf[pos + hexsz] = '\0';
1162 commit = get_merge_parent(merge_names->buf + pos);
1163 merge_names->buf[pos + hexsz] = saved;
1165 if (!commit) {
1166 if (ptr)
1167 *ptr = '\0';
1168 die(_("not something we can merge in %s: %s"),
1169 filename, merge_names->buf + pos);
1171 remotes = &commit_list_insert(commit, remotes)->next;
1174 if (merge_names == &fetch_head_file)
1175 strbuf_release(&fetch_head_file);
1178 static struct commit_list *collect_parents(struct commit *head_commit,
1179 int *head_subsumed,
1180 int argc, const char **argv,
1181 struct strbuf *merge_msg)
1183 int i;
1184 struct commit_list *remoteheads = NULL;
1185 struct commit_list **remotes = &remoteheads;
1186 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1188 if (merge_msg && (!have_message || shortlog_len))
1189 autogen = &merge_names;
1191 if (head_commit)
1192 remotes = &commit_list_insert(head_commit, remotes)->next;
1194 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1195 handle_fetch_head(remotes, autogen);
1196 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1197 } else {
1198 for (i = 0; i < argc; i++) {
1199 struct commit *commit = get_merge_parent(argv[i]);
1200 if (!commit)
1201 help_unknown_ref(argv[i], "merge",
1202 _("not something we can merge"));
1203 remotes = &commit_list_insert(commit, remotes)->next;
1205 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1206 if (autogen) {
1207 struct commit_list *p;
1208 for (p = remoteheads; p; p = p->next)
1209 merge_name(merge_remote_util(p->item)->name, autogen);
1213 if (autogen) {
1214 prepare_merge_message(autogen, merge_msg);
1215 strbuf_release(autogen);
1218 return remoteheads;
1221 static int merging_a_throwaway_tag(struct commit *commit)
1223 char *tag_ref;
1224 struct object_id oid;
1225 int is_throwaway_tag = 0;
1227 /* Are we merging a tag? */
1228 if (!merge_remote_util(commit) ||
1229 !merge_remote_util(commit)->obj ||
1230 merge_remote_util(commit)->obj->type != OBJ_TAG)
1231 return is_throwaway_tag;
1234 * Now we know we are merging a tag object. Are we downstream
1235 * and following the tags from upstream? If so, we must have
1236 * the tag object pointed at by "refs/tags/$T" where $T is the
1237 * tagname recorded in the tag object. We want to allow such
1238 * a "just to catch up" merge to fast-forward.
1240 * Otherwise, we are playing an integrator's role, making a
1241 * merge with a throw-away tag from a contributor with
1242 * something like "git pull $contributor $signed_tag".
1243 * We want to forbid such a merge from fast-forwarding
1244 * by default; otherwise we would not keep the signature
1245 * anywhere.
1247 tag_ref = xstrfmt("refs/tags/%s",
1248 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1249 if (!read_ref(tag_ref, &oid) &&
1250 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1251 is_throwaway_tag = 0;
1252 else
1253 is_throwaway_tag = 1;
1254 free(tag_ref);
1255 return is_throwaway_tag;
1258 int cmd_merge(int argc, const char **argv, const char *prefix)
1260 struct object_id result_tree, stash, head_oid;
1261 struct commit *head_commit;
1262 struct strbuf buf = STRBUF_INIT;
1263 int i, ret = 0, head_subsumed;
1264 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1265 struct commit_list *common = NULL;
1266 const char *best_strategy = NULL, *wt_strategy = NULL;
1267 struct commit_list *remoteheads, *p;
1268 void *branch_to_free;
1269 int orig_argc = argc;
1271 if (argc == 2 && !strcmp(argv[1], "-h"))
1272 usage_with_options(builtin_merge_usage, builtin_merge_options);
1275 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1276 * current branch.
1278 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1279 if (branch)
1280 skip_prefix(branch, "refs/heads/", &branch);
1282 if (!pull_twohead) {
1283 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1284 if (default_strategy && !strcmp(default_strategy, "ort"))
1285 pull_twohead = "ort";
1288 init_diff_ui_defaults();
1289 git_config(git_merge_config, NULL);
1291 if (!branch || is_null_oid(&head_oid))
1292 head_commit = NULL;
1293 else
1294 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1296 if (branch_mergeoptions)
1297 parse_branch_merge_options(branch_mergeoptions);
1298 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1299 builtin_merge_usage, 0);
1300 if (shortlog_len < 0)
1301 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1303 if (verbosity < 0 && show_progress == -1)
1304 show_progress = 0;
1306 if (abort_current_merge) {
1307 int nargc = 2;
1308 const char *nargv[] = {"reset", "--merge", NULL};
1309 struct strbuf stash_oid = STRBUF_INIT;
1311 if (orig_argc != 2)
1312 usage_msg_opt(_("--abort expects no arguments"),
1313 builtin_merge_usage, builtin_merge_options);
1315 if (!file_exists(git_path_merge_head(the_repository)))
1316 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1318 if (read_oneliner(&stash_oid, git_path_merge_autostash(the_repository),
1319 READ_ONELINER_SKIP_IF_EMPTY))
1320 unlink(git_path_merge_autostash(the_repository));
1322 /* Invoke 'git reset --merge' */
1323 ret = cmd_reset(nargc, nargv, prefix);
1325 if (stash_oid.len)
1326 apply_autostash_oid(stash_oid.buf);
1328 strbuf_release(&stash_oid);
1329 goto done;
1332 if (quit_current_merge) {
1333 if (orig_argc != 2)
1334 usage_msg_opt(_("--quit expects no arguments"),
1335 builtin_merge_usage,
1336 builtin_merge_options);
1338 remove_merge_branch_state(the_repository);
1339 goto done;
1342 if (continue_current_merge) {
1343 int nargc = 1;
1344 const char *nargv[] = {"commit", NULL};
1346 if (orig_argc != 2)
1347 usage_msg_opt(_("--continue expects no arguments"),
1348 builtin_merge_usage, builtin_merge_options);
1350 if (!file_exists(git_path_merge_head(the_repository)))
1351 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1353 /* Invoke 'git commit' */
1354 ret = cmd_commit(nargc, nargv, prefix);
1355 goto done;
1358 if (read_cache_unmerged())
1359 die_resolve_conflict("merge");
1361 if (file_exists(git_path_merge_head(the_repository))) {
1363 * There is no unmerged entry, don't advise 'git
1364 * add/rm <file>', just 'git commit'.
1366 if (advice_resolve_conflict)
1367 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1368 "Please, commit your changes before you merge."));
1369 else
1370 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1372 if (ref_exists("CHERRY_PICK_HEAD")) {
1373 if (advice_resolve_conflict)
1374 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1375 "Please, commit your changes before you merge."));
1376 else
1377 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1379 resolve_undo_clear();
1381 if (option_edit < 0)
1382 option_edit = default_edit_option();
1384 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1386 if (verbosity < 0)
1387 show_diffstat = 0;
1389 if (squash) {
1390 if (fast_forward == FF_NO)
1391 die(_("You cannot combine --squash with --no-ff."));
1392 if (option_commit > 0)
1393 die(_("You cannot combine --squash with --commit."));
1395 * squash can now silently disable option_commit - this is not
1396 * a problem as it is only overriding the default, not a user
1397 * supplied option.
1399 option_commit = 0;
1402 if (option_commit < 0)
1403 option_commit = 1;
1405 if (!argc) {
1406 if (default_to_upstream)
1407 argc = setup_with_upstream(&argv);
1408 else
1409 die(_("No commit specified and merge.defaultToUpstream not set."));
1410 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1411 argv[0] = "@{-1}";
1414 if (!argc)
1415 usage_with_options(builtin_merge_usage,
1416 builtin_merge_options);
1418 if (!head_commit) {
1420 * If the merged head is a valid one there is no reason
1421 * to forbid "git merge" into a branch yet to be born.
1422 * We do the same for "git pull".
1424 struct object_id *remote_head_oid;
1425 if (squash)
1426 die(_("Squash commit into empty head not supported yet"));
1427 if (fast_forward == FF_NO)
1428 die(_("Non-fast-forward commit does not make sense into "
1429 "an empty head"));
1430 remoteheads = collect_parents(head_commit, &head_subsumed,
1431 argc, argv, NULL);
1432 if (!remoteheads)
1433 die(_("%s - not something we can merge"), argv[0]);
1434 if (remoteheads->next)
1435 die(_("Can merge only exactly one commit into empty head"));
1437 if (verify_signatures)
1438 verify_merge_signature(remoteheads->item, verbosity,
1439 check_trust_level);
1441 remote_head_oid = &remoteheads->item->object.oid;
1442 read_empty(remote_head_oid, 0);
1443 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1444 UPDATE_REFS_DIE_ON_ERR);
1445 goto done;
1449 * All the rest are the commits being merged; prepare
1450 * the standard merge summary message to be appended
1451 * to the given message.
1453 remoteheads = collect_parents(head_commit, &head_subsumed,
1454 argc, argv, &merge_msg);
1456 if (!head_commit || !argc)
1457 usage_with_options(builtin_merge_usage,
1458 builtin_merge_options);
1460 if (verify_signatures) {
1461 for (p = remoteheads; p; p = p->next) {
1462 verify_merge_signature(p->item, verbosity,
1463 check_trust_level);
1467 strbuf_addstr(&buf, "merge");
1468 for (p = remoteheads; p; p = p->next)
1469 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1470 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1471 strbuf_reset(&buf);
1473 for (p = remoteheads; p; p = p->next) {
1474 struct commit *commit = p->item;
1475 strbuf_addf(&buf, "GITHEAD_%s",
1476 oid_to_hex(&commit->object.oid));
1477 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1478 strbuf_reset(&buf);
1479 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1480 fast_forward = FF_NO;
1483 if (!use_strategies) {
1484 if (!remoteheads)
1485 ; /* already up-to-date */
1486 else if (!remoteheads->next)
1487 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1488 else
1489 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1492 for (i = 0; i < use_strategies_nr; i++) {
1493 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1494 fast_forward = FF_NO;
1495 if (use_strategies[i]->attr & NO_TRIVIAL)
1496 allow_trivial = 0;
1499 if (!remoteheads)
1500 ; /* already up-to-date */
1501 else if (!remoteheads->next)
1502 common = get_merge_bases(head_commit, remoteheads->item);
1503 else {
1504 struct commit_list *list = remoteheads;
1505 commit_list_insert(head_commit, &list);
1506 common = get_octopus_merge_bases(list);
1507 free(list);
1510 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1511 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1513 if (remoteheads && !common) {
1514 /* No common ancestors found. */
1515 if (!allow_unrelated_histories)
1516 die(_("refusing to merge unrelated histories"));
1517 /* otherwise, we need a real merge. */
1518 } else if (!remoteheads ||
1519 (!remoteheads->next && !common->next &&
1520 common->item == remoteheads->item)) {
1522 * If head can reach all the merge then we are up to date.
1523 * but first the most common case of merging one remote.
1525 finish_up_to_date(_("Already up to date."));
1526 goto done;
1527 } else if (fast_forward != FF_NO && !remoteheads->next &&
1528 !common->next &&
1529 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1530 /* Again the most common case of merging one remote. */
1531 struct strbuf msg = STRBUF_INIT;
1532 struct commit *commit;
1534 if (verbosity >= 0) {
1535 printf(_("Updating %s..%s\n"),
1536 find_unique_abbrev(&head_commit->object.oid,
1537 DEFAULT_ABBREV),
1538 find_unique_abbrev(&remoteheads->item->object.oid,
1539 DEFAULT_ABBREV));
1541 strbuf_addstr(&msg, "Fast-forward");
1542 if (have_message)
1543 strbuf_addstr(&msg,
1544 " (no commit created; -m option ignored)");
1545 commit = remoteheads->item;
1546 if (!commit) {
1547 ret = 1;
1548 goto done;
1551 if (autostash)
1552 create_autostash(the_repository,
1553 git_path_merge_autostash(the_repository),
1554 "merge");
1555 if (checkout_fast_forward(the_repository,
1556 &head_commit->object.oid,
1557 &commit->object.oid,
1558 overwrite_ignore)) {
1559 ret = 1;
1560 goto done;
1563 finish(head_commit, remoteheads, &commit->object.oid, msg.buf);
1564 remove_merge_branch_state(the_repository);
1565 goto done;
1566 } else if (!remoteheads->next && common->next)
1569 * We are not doing octopus and not fast-forward. Need
1570 * a real merge.
1572 else if (!remoteheads->next && !common->next && option_commit) {
1574 * We are not doing octopus, not fast-forward, and have
1575 * only one common.
1577 refresh_cache(REFRESH_QUIET);
1578 if (allow_trivial && fast_forward != FF_ONLY) {
1579 /* See if it is really trivial. */
1580 git_committer_info(IDENT_STRICT);
1581 printf(_("Trying really trivial in-index merge...\n"));
1582 if (!read_tree_trivial(&common->item->object.oid,
1583 &head_commit->object.oid,
1584 &remoteheads->item->object.oid)) {
1585 ret = merge_trivial(head_commit, remoteheads);
1586 goto done;
1588 printf(_("Nope.\n"));
1590 } else {
1592 * An octopus. If we can reach all the remote we are up
1593 * to date.
1595 int up_to_date = 1;
1596 struct commit_list *j;
1598 for (j = remoteheads; j; j = j->next) {
1599 struct commit_list *common_one;
1602 * Here we *have* to calculate the individual
1603 * merge_bases again, otherwise "git merge HEAD^
1604 * HEAD^^" would be missed.
1606 common_one = get_merge_bases(head_commit, j->item);
1607 if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1608 up_to_date = 0;
1609 break;
1612 if (up_to_date) {
1613 finish_up_to_date(_("Already up to date. Yeeah!"));
1614 goto done;
1618 if (fast_forward == FF_ONLY)
1619 die(_("Not possible to fast-forward, aborting."));
1621 if (autostash)
1622 create_autostash(the_repository,
1623 git_path_merge_autostash(the_repository),
1624 "merge");
1626 /* We are going to make a new commit. */
1627 git_committer_info(IDENT_STRICT);
1630 * At this point, we need a real merge. No matter what strategy
1631 * we use, it would operate on the index, possibly affecting the
1632 * working tree, and when resolved cleanly, have the desired
1633 * tree in the index -- this means that the index must be in
1634 * sync with the head commit. The strategies are responsible
1635 * to ensure this.
1637 if (use_strategies_nr == 1 ||
1639 * Stash away the local changes so that we can try more than one.
1641 save_state(&stash))
1642 oidclr(&stash);
1644 for (i = 0; !merge_was_ok && i < use_strategies_nr; i++) {
1645 int ret, cnt;
1646 if (i) {
1647 printf(_("Rewinding the tree to pristine...\n"));
1648 restore_state(&head_commit->object.oid, &stash);
1650 if (use_strategies_nr != 1)
1651 printf(_("Trying merge strategy %s...\n"),
1652 use_strategies[i]->name);
1654 * Remember which strategy left the state in the working
1655 * tree.
1657 wt_strategy = use_strategies[i]->name;
1659 ret = try_merge_strategy(use_strategies[i]->name,
1660 common, remoteheads,
1661 head_commit);
1663 * The backend exits with 1 when conflicts are
1664 * left to be resolved, with 2 when it does not
1665 * handle the given merge at all.
1667 if (ret < 2) {
1668 if (!ret) {
1669 if (option_commit) {
1670 /* Automerge succeeded. */
1671 automerge_was_ok = 1;
1672 break;
1674 merge_was_ok = 1;
1676 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1677 if (best_cnt <= 0 || cnt <= best_cnt) {
1678 best_strategy = use_strategies[i]->name;
1679 best_cnt = cnt;
1685 * If we have a resulting tree, that means the strategy module
1686 * auto resolved the merge cleanly.
1688 if (automerge_was_ok) {
1689 ret = finish_automerge(head_commit, head_subsumed,
1690 common, remoteheads,
1691 &result_tree, wt_strategy);
1692 goto done;
1696 * Pick the result from the best strategy and have the user fix
1697 * it up.
1699 if (!best_strategy) {
1700 restore_state(&head_commit->object.oid, &stash);
1701 if (use_strategies_nr > 1)
1702 fprintf(stderr,
1703 _("No merge strategy handled the merge.\n"));
1704 else
1705 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1706 use_strategies[0]->name);
1707 ret = 2;
1708 goto done;
1709 } else if (best_strategy == wt_strategy)
1710 ; /* We already have its result in the working tree. */
1711 else {
1712 printf(_("Rewinding the tree to pristine...\n"));
1713 restore_state(&head_commit->object.oid, &stash);
1714 printf(_("Using the %s to prepare resolving by hand.\n"),
1715 best_strategy);
1716 try_merge_strategy(best_strategy, common, remoteheads,
1717 head_commit);
1720 if (squash) {
1721 finish(head_commit, remoteheads, NULL, NULL);
1723 git_test_write_commit_graph_or_die();
1724 } else
1725 write_merge_state(remoteheads);
1727 if (merge_was_ok)
1728 fprintf(stderr, _("Automatic merge went well; "
1729 "stopped before committing as requested\n"));
1730 else
1731 ret = suggest_conflicts();
1733 done:
1734 free(branch_to_free);
1735 return ret;