notes.c: use designated initializers for clarity
[git/debian.git] / builtin / merge.c
bloba99be9610e9bc1950deb0afd9c47395ccc6a3ab1
1 /*
2 * Builtin "git merge"
4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
7 */
9 #define USE_THE_INDEX_VARIABLE
10 #include "cache.h"
11 #include "abspath.h"
12 #include "alloc.h"
13 #include "config.h"
14 #include "environment.h"
15 #include "gettext.h"
16 #include "hex.h"
17 #include "parse-options.h"
18 #include "builtin.h"
19 #include "lockfile.h"
20 #include "run-command.h"
21 #include "hook.h"
22 #include "diff.h"
23 #include "diff-merges.h"
24 #include "refs.h"
25 #include "refspec.h"
26 #include "commit.h"
27 #include "diffcore.h"
28 #include "revision.h"
29 #include "unpack-trees.h"
30 #include "cache-tree.h"
31 #include "dir.h"
32 #include "utf8.h"
33 #include "log-tree.h"
34 #include "color.h"
35 #include "rerere.h"
36 #include "help.h"
37 #include "merge-recursive.h"
38 #include "merge-ort-wrappers.h"
39 #include "resolve-undo.h"
40 #include "remote.h"
41 #include "fmt-merge-msg.h"
42 #include "gpg-interface.h"
43 #include "sequencer.h"
44 #include "string-list.h"
45 #include "packfile.h"
46 #include "tag.h"
47 #include "alias.h"
48 #include "branch.h"
49 #include "commit-reach.h"
50 #include "wt-status.h"
51 #include "commit-graph.h"
52 #include "wrapper.h"
54 #define DEFAULT_TWOHEAD (1<<0)
55 #define DEFAULT_OCTOPUS (1<<1)
56 #define NO_FAST_FORWARD (1<<2)
57 #define NO_TRIVIAL (1<<3)
59 struct strategy {
60 const char *name;
61 unsigned attr;
64 static const char * const builtin_merge_usage[] = {
65 N_("git merge [<options>] [<commit>...]"),
66 "git merge --abort",
67 "git merge --continue",
68 NULL
71 static int show_diffstat = 1, shortlog_len = -1, squash;
72 static int option_commit = -1;
73 static int option_edit = -1;
74 static int allow_trivial = 1, have_message, verify_signatures;
75 static int check_trust_level = 1;
76 static int overwrite_ignore = 1;
77 static struct strbuf merge_msg = STRBUF_INIT;
78 static struct strategy **use_strategies;
79 static size_t use_strategies_nr, use_strategies_alloc;
80 static const char **xopts;
81 static size_t xopts_nr, xopts_alloc;
82 static const char *branch;
83 static char *branch_mergeoptions;
84 static int verbosity;
85 static int allow_rerere_auto;
86 static int abort_current_merge;
87 static int quit_current_merge;
88 static int continue_current_merge;
89 static int allow_unrelated_histories;
90 static int show_progress = -1;
91 static int default_to_upstream = 1;
92 static int signoff;
93 static const char *sign_commit;
94 static int autostash;
95 static int no_verify;
96 static char *into_name;
98 static struct strategy all_strategy[] = {
99 { "recursive", NO_TRIVIAL },
100 { "octopus", DEFAULT_OCTOPUS },
101 { "ort", DEFAULT_TWOHEAD | NO_TRIVIAL },
102 { "resolve", 0 },
103 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
104 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
107 static const char *pull_twohead, *pull_octopus;
109 enum ff_type {
110 FF_NO,
111 FF_ALLOW,
112 FF_ONLY
115 static enum ff_type fast_forward = FF_ALLOW;
117 static const char *cleanup_arg;
118 static enum commit_msg_cleanup_mode cleanup_mode;
120 static int option_parse_message(const struct option *opt,
121 const char *arg, int unset)
123 struct strbuf *buf = opt->value;
125 if (unset)
126 strbuf_setlen(buf, 0);
127 else if (arg) {
128 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
129 have_message = 1;
130 } else
131 return error(_("switch `m' requires a value"));
132 return 0;
135 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
136 const struct option *opt,
137 const char *arg_not_used,
138 int unset)
140 struct strbuf *buf = opt->value;
141 const char *arg;
143 BUG_ON_OPT_ARG(arg_not_used);
144 if (unset)
145 BUG("-F cannot be negated");
147 if (ctx->opt) {
148 arg = ctx->opt;
149 ctx->opt = NULL;
150 } else if (ctx->argc > 1) {
151 ctx->argc--;
152 arg = *++ctx->argv;
153 } else
154 return error(_("option `%s' requires a value"), opt->long_name);
156 if (buf->len)
157 strbuf_addch(buf, '\n');
158 if (ctx->prefix && !is_absolute_path(arg))
159 arg = prefix_filename(ctx->prefix, arg);
160 if (strbuf_read_file(buf, arg, 0) < 0)
161 return error(_("could not read file '%s'"), arg);
162 have_message = 1;
164 return 0;
167 static struct strategy *get_strategy(const char *name)
169 int i;
170 struct strategy *ret;
171 static struct cmdnames main_cmds, other_cmds;
172 static int loaded;
173 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
175 if (!name)
176 return NULL;
178 if (default_strategy &&
179 !strcmp(default_strategy, "ort") &&
180 !strcmp(name, "recursive")) {
181 name = "ort";
184 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
185 if (!strcmp(name, all_strategy[i].name))
186 return &all_strategy[i];
188 if (!loaded) {
189 struct cmdnames not_strategies;
190 loaded = 1;
192 memset(&not_strategies, 0, sizeof(struct cmdnames));
193 load_command_list("git-merge-", &main_cmds, &other_cmds);
194 for (i = 0; i < main_cmds.cnt; i++) {
195 int j, found = 0;
196 struct cmdname *ent = main_cmds.names[i];
197 for (j = 0; !found && j < ARRAY_SIZE(all_strategy); j++)
198 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
199 && !all_strategy[j].name[ent->len])
200 found = 1;
201 if (!found)
202 add_cmdname(&not_strategies, ent->name, ent->len);
204 exclude_cmds(&main_cmds, &not_strategies);
206 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
207 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
208 fprintf(stderr, _("Available strategies are:"));
209 for (i = 0; i < main_cmds.cnt; i++)
210 fprintf(stderr, " %s", main_cmds.names[i]->name);
211 fprintf(stderr, ".\n");
212 if (other_cmds.cnt) {
213 fprintf(stderr, _("Available custom strategies are:"));
214 for (i = 0; i < other_cmds.cnt; i++)
215 fprintf(stderr, " %s", other_cmds.names[i]->name);
216 fprintf(stderr, ".\n");
218 exit(1);
221 CALLOC_ARRAY(ret, 1);
222 ret->name = xstrdup(name);
223 ret->attr = NO_TRIVIAL;
224 return ret;
227 static void append_strategy(struct strategy *s)
229 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
230 use_strategies[use_strategies_nr++] = s;
233 static int option_parse_strategy(const struct option *opt,
234 const char *name, int unset)
236 if (unset)
237 return 0;
239 append_strategy(get_strategy(name));
240 return 0;
243 static int option_parse_x(const struct option *opt,
244 const char *arg, int unset)
246 if (unset)
247 return 0;
249 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
250 xopts[xopts_nr++] = xstrdup(arg);
251 return 0;
254 static int option_parse_n(const struct option *opt,
255 const char *arg, int unset)
257 BUG_ON_OPT_ARG(arg);
258 show_diffstat = unset;
259 return 0;
262 static struct option builtin_merge_options[] = {
263 OPT_CALLBACK_F('n', NULL, NULL, NULL,
264 N_("do not show a diffstat at the end of the merge"),
265 PARSE_OPT_NOARG, option_parse_n),
266 OPT_BOOL(0, "stat", &show_diffstat,
267 N_("show a diffstat at the end of the merge")),
268 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
269 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
270 N_("add (at most <n>) entries from shortlog to merge commit message"),
271 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
272 OPT_BOOL(0, "squash", &squash,
273 N_("create a single commit instead of doing a merge")),
274 OPT_BOOL(0, "commit", &option_commit,
275 N_("perform a commit if the merge succeeds (default)")),
276 OPT_BOOL('e', "edit", &option_edit,
277 N_("edit message before committing")),
278 OPT_CLEANUP(&cleanup_arg),
279 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
280 OPT_SET_INT_F(0, "ff-only", &fast_forward,
281 N_("abort if fast-forward is not possible"),
282 FF_ONLY, PARSE_OPT_NONEG),
283 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
284 OPT_BOOL(0, "verify-signatures", &verify_signatures,
285 N_("verify that the named commit has a valid GPG signature")),
286 OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
287 N_("merge strategy to use"), option_parse_strategy),
288 OPT_CALLBACK('X', "strategy-option", &xopts, N_("option=value"),
289 N_("option for selected merge strategy"), option_parse_x),
290 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
291 N_("merge commit message (for a non-fast-forward merge)"),
292 option_parse_message),
293 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
294 N_("read message from file"), PARSE_OPT_NONEG,
295 NULL, 0, option_read_message },
296 OPT_STRING(0, "into-name", &into_name, N_("name"),
297 N_("use <name> instead of the real target")),
298 OPT__VERBOSITY(&verbosity),
299 OPT_BOOL(0, "abort", &abort_current_merge,
300 N_("abort the current in-progress merge")),
301 OPT_BOOL(0, "quit", &quit_current_merge,
302 N_("--abort but leave index and working tree alone")),
303 OPT_BOOL(0, "continue", &continue_current_merge,
304 N_("continue the current in-progress merge")),
305 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
306 N_("allow merging unrelated histories")),
307 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
308 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
309 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
310 OPT_AUTOSTASH(&autostash),
311 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
312 OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
313 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
314 OPT_END()
317 static int save_state(struct object_id *stash)
319 int len;
320 struct child_process cp = CHILD_PROCESS_INIT;
321 struct strbuf buffer = STRBUF_INIT;
322 struct lock_file lock_file = LOCK_INIT;
323 int fd;
324 int rc = -1;
326 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
327 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
328 if (0 <= fd)
329 repo_update_index_if_able(the_repository, &lock_file);
330 rollback_lock_file(&lock_file);
332 strvec_pushl(&cp.args, "stash", "create", NULL);
333 cp.out = -1;
334 cp.git_cmd = 1;
336 if (start_command(&cp))
337 die(_("could not run stash."));
338 len = strbuf_read(&buffer, cp.out, 1024);
339 close(cp.out);
341 if (finish_command(&cp) || len < 0)
342 die(_("stash failed"));
343 else if (!len) /* no changes */
344 goto out;
345 strbuf_setlen(&buffer, buffer.len-1);
346 if (repo_get_oid(the_repository, buffer.buf, stash))
347 die(_("not a valid object: %s"), buffer.buf);
348 rc = 0;
349 out:
350 strbuf_release(&buffer);
351 return rc;
354 static void read_empty(const struct object_id *oid)
356 struct child_process cmd = CHILD_PROCESS_INIT;
358 strvec_pushl(&cmd.args, "read-tree", "-m", "-u", empty_tree_oid_hex(),
359 oid_to_hex(oid), NULL);
360 cmd.git_cmd = 1;
362 if (run_command(&cmd))
363 die(_("read-tree failed"));
366 static void reset_hard(const struct object_id *oid)
368 struct child_process cmd = CHILD_PROCESS_INIT;
370 strvec_pushl(&cmd.args, "read-tree", "-v", "--reset", "-u",
371 oid_to_hex(oid), NULL);
372 cmd.git_cmd = 1;
374 if (run_command(&cmd))
375 die(_("read-tree failed"));
378 static void restore_state(const struct object_id *head,
379 const struct object_id *stash)
381 struct child_process cmd = CHILD_PROCESS_INIT;
383 reset_hard(head);
385 if (is_null_oid(stash))
386 goto refresh_cache;
388 strvec_pushl(&cmd.args, "stash", "apply", "--index", "--quiet", NULL);
389 strvec_push(&cmd.args, oid_to_hex(stash));
392 * It is OK to ignore error here, for example when there was
393 * nothing to restore.
395 cmd.git_cmd = 1;
396 run_command(&cmd);
398 refresh_cache:
399 discard_index(&the_index);
400 if (repo_read_index(the_repository) < 0)
401 die(_("could not read index"));
404 /* This is called when no merge was necessary. */
405 static void finish_up_to_date(void)
407 if (verbosity >= 0) {
408 if (squash)
409 puts(_("Already up to date. (nothing to squash)"));
410 else
411 puts(_("Already up to date."));
413 remove_merge_branch_state(the_repository);
416 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
418 struct rev_info rev;
419 struct strbuf out = STRBUF_INIT;
420 struct commit_list *j;
421 struct pretty_print_context ctx = {0};
423 printf(_("Squash commit -- not updating HEAD\n"));
425 repo_init_revisions(the_repository, &rev, NULL);
426 diff_merges_suppress(&rev);
427 rev.commit_format = CMIT_FMT_MEDIUM;
429 commit->object.flags |= UNINTERESTING;
430 add_pending_object(&rev, &commit->object, NULL);
432 for (j = remoteheads; j; j = j->next)
433 add_pending_object(&rev, &j->item->object, NULL);
435 setup_revisions(0, NULL, &rev, NULL);
436 if (prepare_revision_walk(&rev))
437 die(_("revision walk setup failed"));
439 ctx.abbrev = rev.abbrev;
440 ctx.date_mode = rev.date_mode;
441 ctx.fmt = rev.commit_format;
443 strbuf_addstr(&out, "Squashed commit of the following:\n");
444 while ((commit = get_revision(&rev)) != NULL) {
445 strbuf_addch(&out, '\n');
446 strbuf_addf(&out, "commit %s\n",
447 oid_to_hex(&commit->object.oid));
448 pretty_print_commit(&ctx, commit, &out);
450 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
451 strbuf_release(&out);
452 release_revisions(&rev);
455 static void finish(struct commit *head_commit,
456 struct commit_list *remoteheads,
457 const struct object_id *new_head, const char *msg)
459 struct strbuf reflog_message = STRBUF_INIT;
460 const struct object_id *head = &head_commit->object.oid;
462 if (!msg)
463 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
464 else {
465 if (verbosity >= 0)
466 printf("%s\n", msg);
467 strbuf_addf(&reflog_message, "%s: %s",
468 getenv("GIT_REFLOG_ACTION"), msg);
470 if (squash) {
471 squash_message(head_commit, remoteheads);
472 } else {
473 if (verbosity >= 0 && !merge_msg.len)
474 printf(_("No merge message -- not updating HEAD\n"));
475 else {
476 update_ref(reflog_message.buf, "HEAD", new_head, head,
477 0, UPDATE_REFS_DIE_ON_ERR);
479 * We ignore errors in 'gc --auto', since the
480 * user should see them.
482 run_auto_maintenance(verbosity < 0);
485 if (new_head && show_diffstat) {
486 struct diff_options opts;
487 repo_diff_setup(the_repository, &opts);
488 opts.stat_width = -1; /* use full terminal width */
489 opts.stat_graph_width = -1; /* respect statGraphWidth config */
490 opts.output_format |=
491 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
492 opts.detect_rename = DIFF_DETECT_RENAME;
493 diff_setup_done(&opts);
494 diff_tree_oid(head, new_head, "", &opts);
495 diffcore_std(&opts);
496 diff_flush(&opts);
499 /* Run a post-merge hook */
500 run_hooks_l("post-merge", squash ? "1" : "0", NULL);
502 if (new_head)
503 apply_autostash(git_path_merge_autostash(the_repository));
504 strbuf_release(&reflog_message);
507 /* Get the name for the merge commit's message. */
508 static void merge_name(const char *remote, struct strbuf *msg)
510 struct commit *remote_head;
511 struct object_id branch_head;
512 struct strbuf bname = STRBUF_INIT;
513 struct merge_remote_desc *desc;
514 const char *ptr;
515 char *found_ref = NULL;
516 int len, early;
518 strbuf_branchname(&bname, remote, 0);
519 remote = bname.buf;
521 oidclr(&branch_head);
522 remote_head = get_merge_parent(remote);
523 if (!remote_head)
524 die(_("'%s' does not point to a commit"), remote);
526 if (repo_dwim_ref(the_repository, remote, strlen(remote), &branch_head,
527 &found_ref, 0) > 0) {
528 if (starts_with(found_ref, "refs/heads/")) {
529 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
530 oid_to_hex(&branch_head), remote);
531 goto cleanup;
533 if (starts_with(found_ref, "refs/tags/")) {
534 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
535 oid_to_hex(&branch_head), remote);
536 goto cleanup;
538 if (starts_with(found_ref, "refs/remotes/")) {
539 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
540 oid_to_hex(&branch_head), remote);
541 goto cleanup;
545 /* See if remote matches <name>^^^.. or <name>~<number> */
546 for (len = 0, ptr = remote + strlen(remote);
547 remote < ptr && ptr[-1] == '^';
548 ptr--)
549 len++;
550 if (len)
551 early = 1;
552 else {
553 early = 0;
554 ptr = strrchr(remote, '~');
555 if (ptr) {
556 int seen_nonzero = 0;
558 len++; /* count ~ */
559 while (*++ptr && isdigit(*ptr)) {
560 seen_nonzero |= (*ptr != '0');
561 len++;
563 if (*ptr)
564 len = 0; /* not ...~<number> */
565 else if (seen_nonzero)
566 early = 1;
567 else if (len == 1)
568 early = 1; /* "name~" is "name~1"! */
571 if (len) {
572 struct strbuf truname = STRBUF_INIT;
573 strbuf_addf(&truname, "refs/heads/%s", remote);
574 strbuf_setlen(&truname, truname.len - len);
575 if (ref_exists(truname.buf)) {
576 strbuf_addf(msg,
577 "%s\t\tbranch '%s'%s of .\n",
578 oid_to_hex(&remote_head->object.oid),
579 truname.buf + 11,
580 (early ? " (early part)" : ""));
581 strbuf_release(&truname);
582 goto cleanup;
584 strbuf_release(&truname);
587 desc = merge_remote_util(remote_head);
588 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
589 strbuf_addf(msg, "%s\t\t%s '%s'\n",
590 oid_to_hex(&desc->obj->oid),
591 type_name(desc->obj->type),
592 remote);
593 goto cleanup;
596 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
597 oid_to_hex(&remote_head->object.oid), remote);
598 cleanup:
599 free(found_ref);
600 strbuf_release(&bname);
603 static void parse_branch_merge_options(char *bmo)
605 const char **argv;
606 int argc;
608 if (!bmo)
609 return;
610 argc = split_cmdline(bmo, &argv);
611 if (argc < 0)
612 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
613 _(split_cmdline_strerror(argc)));
614 REALLOC_ARRAY(argv, argc + 2);
615 MOVE_ARRAY(argv + 1, argv, argc + 1);
616 argc++;
617 argv[0] = "branch.*.mergeoptions";
618 parse_options(argc, argv, NULL, builtin_merge_options,
619 builtin_merge_usage, 0);
620 free(argv);
623 static int git_merge_config(const char *k, const char *v, void *cb)
625 int status;
626 const char *str;
628 if (branch &&
629 skip_prefix(k, "branch.", &str) &&
630 skip_prefix(str, branch, &str) &&
631 !strcmp(str, ".mergeoptions")) {
632 free(branch_mergeoptions);
633 branch_mergeoptions = xstrdup(v);
634 return 0;
637 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
638 show_diffstat = git_config_bool(k, v);
639 else if (!strcmp(k, "merge.verifysignatures"))
640 verify_signatures = git_config_bool(k, v);
641 else if (!strcmp(k, "pull.twohead"))
642 return git_config_string(&pull_twohead, k, v);
643 else if (!strcmp(k, "pull.octopus"))
644 return git_config_string(&pull_octopus, k, v);
645 else if (!strcmp(k, "commit.cleanup"))
646 return git_config_string(&cleanup_arg, k, v);
647 else if (!strcmp(k, "merge.ff")) {
648 int boolval = git_parse_maybe_bool(v);
649 if (0 <= boolval) {
650 fast_forward = boolval ? FF_ALLOW : FF_NO;
651 } else if (v && !strcmp(v, "only")) {
652 fast_forward = FF_ONLY;
653 } /* do not barf on values from future versions of git */
654 return 0;
655 } else if (!strcmp(k, "merge.defaulttoupstream")) {
656 default_to_upstream = git_config_bool(k, v);
657 return 0;
658 } else if (!strcmp(k, "commit.gpgsign")) {
659 sign_commit = git_config_bool(k, v) ? "" : NULL;
660 return 0;
661 } else if (!strcmp(k, "gpg.mintrustlevel")) {
662 check_trust_level = 0;
663 } else if (!strcmp(k, "merge.autostash")) {
664 autostash = git_config_bool(k, v);
665 return 0;
668 status = fmt_merge_msg_config(k, v, cb);
669 if (status)
670 return status;
671 return git_diff_ui_config(k, v, cb);
674 static int read_tree_trivial(struct object_id *common, struct object_id *head,
675 struct object_id *one)
677 int i, nr_trees = 0;
678 struct tree *trees[MAX_UNPACK_TREES];
679 struct tree_desc t[MAX_UNPACK_TREES];
680 struct unpack_trees_options opts;
682 memset(&opts, 0, sizeof(opts));
683 opts.head_idx = 2;
684 opts.src_index = &the_index;
685 opts.dst_index = &the_index;
686 opts.update = 1;
687 opts.verbose_update = 1;
688 opts.trivial_merges_only = 1;
689 opts.merge = 1;
690 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
691 trees[nr_trees] = parse_tree_indirect(common);
692 if (!trees[nr_trees++])
693 return -1;
694 trees[nr_trees] = parse_tree_indirect(head);
695 if (!trees[nr_trees++])
696 return -1;
697 trees[nr_trees] = parse_tree_indirect(one);
698 if (!trees[nr_trees++])
699 return -1;
700 opts.fn = threeway_merge;
701 cache_tree_free(&the_index.cache_tree);
702 for (i = 0; i < nr_trees; i++) {
703 parse_tree(trees[i]);
704 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
706 if (unpack_trees(nr_trees, t, &opts))
707 return -1;
708 return 0;
711 static void write_tree_trivial(struct object_id *oid)
713 if (write_index_as_tree(oid, &the_index, get_index_file(), 0, NULL))
714 die(_("git write-tree failed to write a tree"));
717 static int try_merge_strategy(const char *strategy, struct commit_list *common,
718 struct commit_list *remoteheads,
719 struct commit *head)
721 const char *head_arg = "HEAD";
723 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
724 SKIP_IF_UNCHANGED, 0, NULL, NULL,
725 NULL) < 0)
726 return error(_("Unable to write index."));
728 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
729 !strcmp(strategy, "ort")) {
730 struct lock_file lock = LOCK_INIT;
731 int clean, x;
732 struct commit *result;
733 struct commit_list *reversed = NULL;
734 struct merge_options o;
735 struct commit_list *j;
737 if (remoteheads->next) {
738 error(_("Not handling anything other than two heads merge."));
739 return 2;
742 init_merge_options(&o, the_repository);
743 if (!strcmp(strategy, "subtree"))
744 o.subtree_shift = "";
746 o.show_rename_progress =
747 show_progress == -1 ? isatty(2) : show_progress;
749 for (x = 0; x < xopts_nr; x++)
750 if (parse_merge_opt(&o, xopts[x]))
751 die(_("unknown strategy option: -X%s"), xopts[x]);
753 o.branch1 = head_arg;
754 o.branch2 = merge_remote_util(remoteheads->item)->name;
756 for (j = common; j; j = j->next)
757 commit_list_insert(j->item, &reversed);
759 repo_hold_locked_index(the_repository, &lock,
760 LOCK_DIE_ON_ERROR);
761 if (!strcmp(strategy, "ort"))
762 clean = merge_ort_recursive(&o, head, remoteheads->item,
763 reversed, &result);
764 else
765 clean = merge_recursive(&o, head, remoteheads->item,
766 reversed, &result);
767 if (clean < 0) {
768 rollback_lock_file(&lock);
769 return 2;
771 if (write_locked_index(&the_index, &lock,
772 COMMIT_LOCK | SKIP_IF_UNCHANGED))
773 die(_("unable to write %s"), get_index_file());
774 return clean ? 0 : 1;
775 } else {
776 return try_merge_command(the_repository,
777 strategy, xopts_nr, xopts,
778 common, head_arg, remoteheads);
782 static void count_diff_files(struct diff_queue_struct *q,
783 struct diff_options *opt UNUSED, void *data)
785 int *count = data;
787 (*count) += q->nr;
790 static int count_unmerged_entries(void)
792 int i, ret = 0;
794 for (i = 0; i < the_index.cache_nr; i++)
795 if (ce_stage(the_index.cache[i]))
796 ret++;
798 return ret;
801 static void add_strategies(const char *string, unsigned attr)
803 int i;
805 if (string) {
806 struct string_list list = STRING_LIST_INIT_DUP;
807 struct string_list_item *item;
808 string_list_split(&list, string, ' ', -1);
809 for_each_string_list_item(item, &list)
810 append_strategy(get_strategy(item->string));
811 string_list_clear(&list, 0);
812 return;
814 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
815 if (all_strategy[i].attr & attr)
816 append_strategy(&all_strategy[i]);
820 static void read_merge_msg(struct strbuf *msg)
822 const char *filename = git_path_merge_msg(the_repository);
823 strbuf_reset(msg);
824 if (strbuf_read_file(msg, filename, 0) < 0)
825 die_errno(_("Could not read from '%s'"), filename);
828 static void write_merge_state(struct commit_list *);
829 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
831 if (err_msg)
832 error("%s", err_msg);
833 fprintf(stderr,
834 _("Not committing merge; use 'git commit' to complete the merge.\n"));
835 write_merge_state(remoteheads);
836 exit(1);
839 static const char merge_editor_comment[] =
840 N_("Please enter a commit message to explain why this merge is necessary,\n"
841 "especially if it merges an updated upstream into a topic branch.\n"
842 "\n");
844 static const char scissors_editor_comment[] =
845 N_("An empty message aborts the commit.\n");
847 static const char no_scissors_editor_comment[] =
848 N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
849 "the commit.\n");
851 static void write_merge_heads(struct commit_list *);
852 static void prepare_to_commit(struct commit_list *remoteheads)
854 struct strbuf msg = STRBUF_INIT;
855 const char *index_file = get_index_file();
857 if (!no_verify) {
858 int invoked_hook;
860 if (run_commit_hook(0 < option_edit, index_file, &invoked_hook,
861 "pre-merge-commit", NULL))
862 abort_commit(remoteheads, NULL);
864 * Re-read the index as pre-merge-commit hook could have updated it,
865 * and write it out as a tree. We must do this before we invoke
866 * the editor and after we invoke run_status above.
868 if (invoked_hook)
869 discard_index(&the_index);
871 read_index_from(&the_index, index_file, get_git_dir());
872 strbuf_addbuf(&msg, &merge_msg);
873 if (squash)
874 BUG("the control must not reach here under --squash");
875 if (0 < option_edit) {
876 strbuf_addch(&msg, '\n');
877 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
878 wt_status_append_cut_line(&msg);
879 strbuf_commented_addf(&msg, "\n");
881 strbuf_commented_addf(&msg, _(merge_editor_comment));
882 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
883 strbuf_commented_addf(&msg, _(scissors_editor_comment));
884 else
885 strbuf_commented_addf(&msg,
886 _(no_scissors_editor_comment), comment_line_char);
888 if (signoff)
889 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
890 write_merge_heads(remoteheads);
891 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
892 if (run_commit_hook(0 < option_edit, get_index_file(), NULL,
893 "prepare-commit-msg",
894 git_path_merge_msg(the_repository), "merge", NULL))
895 abort_commit(remoteheads, NULL);
896 if (0 < option_edit) {
897 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
898 abort_commit(remoteheads, NULL);
901 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
902 NULL, "commit-msg",
903 git_path_merge_msg(the_repository), NULL))
904 abort_commit(remoteheads, NULL);
906 read_merge_msg(&msg);
907 cleanup_message(&msg, cleanup_mode, 0);
908 if (!msg.len)
909 abort_commit(remoteheads, _("Empty commit message."));
910 strbuf_release(&merge_msg);
911 strbuf_addbuf(&merge_msg, &msg);
912 strbuf_release(&msg);
915 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
917 struct object_id result_tree, result_commit;
918 struct commit_list *parents, **pptr = &parents;
920 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
921 SKIP_IF_UNCHANGED, 0, NULL, NULL,
922 NULL) < 0)
923 return error(_("Unable to write index."));
925 write_tree_trivial(&result_tree);
926 printf(_("Wonderful.\n"));
927 pptr = commit_list_append(head, pptr);
928 pptr = commit_list_append(remoteheads->item, pptr);
929 prepare_to_commit(remoteheads);
930 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
931 &result_commit, NULL, sign_commit))
932 die(_("failed to write commit object"));
933 finish(head, remoteheads, &result_commit, "In-index merge");
934 remove_merge_branch_state(the_repository);
935 return 0;
938 static int finish_automerge(struct commit *head,
939 int head_subsumed,
940 struct commit_list *common,
941 struct commit_list *remoteheads,
942 struct object_id *result_tree,
943 const char *wt_strategy)
945 struct commit_list *parents = NULL;
946 struct strbuf buf = STRBUF_INIT;
947 struct object_id result_commit;
949 write_tree_trivial(result_tree);
950 free_commit_list(common);
951 parents = remoteheads;
952 if (!head_subsumed || fast_forward == FF_NO)
953 commit_list_insert(head, &parents);
954 prepare_to_commit(remoteheads);
955 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
956 &result_commit, NULL, sign_commit))
957 die(_("failed to write commit object"));
958 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
959 finish(head, remoteheads, &result_commit, buf.buf);
960 strbuf_release(&buf);
961 remove_merge_branch_state(the_repository);
962 return 0;
965 static int suggest_conflicts(void)
967 const char *filename;
968 FILE *fp;
969 struct strbuf msgbuf = STRBUF_INIT;
971 filename = git_path_merge_msg(the_repository);
972 fp = xfopen(filename, "a");
975 * We can't use cleanup_mode because if we're not using the editor,
976 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
977 * though the message is meant to be processed later by git-commit.
978 * Thus, we will get the cleanup mode which is returned when we _are_
979 * using an editor.
981 append_conflicts_hint(&the_index, &msgbuf,
982 get_cleanup_mode(cleanup_arg, 1));
983 fputs(msgbuf.buf, fp);
984 strbuf_release(&msgbuf);
985 fclose(fp);
986 repo_rerere(the_repository, allow_rerere_auto);
987 printf(_("Automatic merge failed; "
988 "fix conflicts and then commit the result.\n"));
989 return 1;
992 static int evaluate_result(void)
994 int cnt = 0;
995 struct rev_info rev;
997 /* Check how many files differ. */
998 repo_init_revisions(the_repository, &rev, "");
999 setup_revisions(0, NULL, &rev, NULL);
1000 rev.diffopt.output_format |=
1001 DIFF_FORMAT_CALLBACK;
1002 rev.diffopt.format_callback = count_diff_files;
1003 rev.diffopt.format_callback_data = &cnt;
1004 run_diff_files(&rev, 0);
1007 * Check how many unmerged entries are
1008 * there.
1010 cnt += count_unmerged_entries();
1012 release_revisions(&rev);
1013 return cnt;
1017 * Pretend as if the user told us to merge with the remote-tracking
1018 * branch we have for the upstream of the current branch
1020 static int setup_with_upstream(const char ***argv)
1022 struct branch *branch = branch_get(NULL);
1023 int i;
1024 const char **args;
1026 if (!branch)
1027 die(_("No current branch."));
1028 if (!branch->remote_name)
1029 die(_("No remote for the current branch."));
1030 if (!branch->merge_nr)
1031 die(_("No default upstream defined for the current branch."));
1033 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1034 for (i = 0; i < branch->merge_nr; i++) {
1035 if (!branch->merge[i]->dst)
1036 die(_("No remote-tracking branch for %s from %s"),
1037 branch->merge[i]->src, branch->remote_name);
1038 args[i] = branch->merge[i]->dst;
1040 args[i] = NULL;
1041 *argv = args;
1042 return i;
1045 static void write_merge_heads(struct commit_list *remoteheads)
1047 struct commit_list *j;
1048 struct strbuf buf = STRBUF_INIT;
1050 for (j = remoteheads; j; j = j->next) {
1051 struct object_id *oid;
1052 struct commit *c = j->item;
1053 struct merge_remote_desc *desc;
1055 desc = merge_remote_util(c);
1056 if (desc && desc->obj) {
1057 oid = &desc->obj->oid;
1058 } else {
1059 oid = &c->object.oid;
1061 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1063 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1065 strbuf_reset(&buf);
1066 if (fast_forward == FF_NO)
1067 strbuf_addstr(&buf, "no-ff");
1068 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1069 strbuf_release(&buf);
1072 static void write_merge_state(struct commit_list *remoteheads)
1074 write_merge_heads(remoteheads);
1075 strbuf_addch(&merge_msg, '\n');
1076 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1077 merge_msg.len);
1080 static int default_edit_option(void)
1082 static const char name[] = "GIT_MERGE_AUTOEDIT";
1083 const char *e = getenv(name);
1084 struct stat st_stdin, st_stdout;
1086 if (have_message)
1087 /* an explicit -m msg without --[no-]edit */
1088 return 0;
1090 if (e) {
1091 int v = git_parse_maybe_bool(e);
1092 if (v < 0)
1093 die(_("Bad value '%s' in environment '%s'"), e, name);
1094 return v;
1097 /* Use editor if stdin and stdout are the same and is a tty */
1098 return (!fstat(0, &st_stdin) &&
1099 !fstat(1, &st_stdout) &&
1100 isatty(0) && isatty(1) &&
1101 st_stdin.st_dev == st_stdout.st_dev &&
1102 st_stdin.st_ino == st_stdout.st_ino &&
1103 st_stdin.st_mode == st_stdout.st_mode);
1106 static struct commit_list *reduce_parents(struct commit *head_commit,
1107 int *head_subsumed,
1108 struct commit_list *remoteheads)
1110 struct commit_list *parents, **remotes;
1113 * Is the current HEAD reachable from another commit being
1114 * merged? If so we do not want to record it as a parent of
1115 * the resulting merge, unless --no-ff is given. We will flip
1116 * this variable to 0 when we find HEAD among the independent
1117 * tips being merged.
1119 *head_subsumed = 1;
1121 /* Find what parents to record by checking independent ones. */
1122 parents = reduce_heads(remoteheads);
1123 free_commit_list(remoteheads);
1125 remoteheads = NULL;
1126 remotes = &remoteheads;
1127 while (parents) {
1128 struct commit *commit = pop_commit(&parents);
1129 if (commit == head_commit)
1130 *head_subsumed = 0;
1131 else
1132 remotes = &commit_list_insert(commit, remotes)->next;
1134 return remoteheads;
1137 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1139 struct fmt_merge_msg_opts opts;
1141 memset(&opts, 0, sizeof(opts));
1142 opts.add_title = !have_message;
1143 opts.shortlog_len = shortlog_len;
1144 opts.credit_people = (0 < option_edit);
1145 opts.into_name = into_name;
1147 fmt_merge_msg(merge_names, merge_msg, &opts);
1148 if (merge_msg->len)
1149 strbuf_setlen(merge_msg, merge_msg->len - 1);
1152 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1154 const char *filename;
1155 int fd, pos, npos;
1156 struct strbuf fetch_head_file = STRBUF_INIT;
1157 const unsigned hexsz = the_hash_algo->hexsz;
1159 if (!merge_names)
1160 merge_names = &fetch_head_file;
1162 filename = git_path_fetch_head(the_repository);
1163 fd = xopen(filename, O_RDONLY);
1165 if (strbuf_read(merge_names, fd, 0) < 0)
1166 die_errno(_("could not read '%s'"), filename);
1167 if (close(fd) < 0)
1168 die_errno(_("could not close '%s'"), filename);
1170 for (pos = 0; pos < merge_names->len; pos = npos) {
1171 struct object_id oid;
1172 char *ptr;
1173 struct commit *commit;
1175 ptr = strchr(merge_names->buf + pos, '\n');
1176 if (ptr)
1177 npos = ptr - merge_names->buf + 1;
1178 else
1179 npos = merge_names->len;
1181 if (npos - pos < hexsz + 2 ||
1182 get_oid_hex(merge_names->buf + pos, &oid))
1183 commit = NULL; /* bad */
1184 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1185 continue; /* not-for-merge */
1186 else {
1187 char saved = merge_names->buf[pos + hexsz];
1188 merge_names->buf[pos + hexsz] = '\0';
1189 commit = get_merge_parent(merge_names->buf + pos);
1190 merge_names->buf[pos + hexsz] = saved;
1192 if (!commit) {
1193 if (ptr)
1194 *ptr = '\0';
1195 die(_("not something we can merge in %s: %s"),
1196 filename, merge_names->buf + pos);
1198 remotes = &commit_list_insert(commit, remotes)->next;
1201 if (merge_names == &fetch_head_file)
1202 strbuf_release(&fetch_head_file);
1205 static struct commit_list *collect_parents(struct commit *head_commit,
1206 int *head_subsumed,
1207 int argc, const char **argv,
1208 struct strbuf *merge_msg)
1210 int i;
1211 struct commit_list *remoteheads = NULL;
1212 struct commit_list **remotes = &remoteheads;
1213 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1215 if (merge_msg && (!have_message || shortlog_len))
1216 autogen = &merge_names;
1218 if (head_commit)
1219 remotes = &commit_list_insert(head_commit, remotes)->next;
1221 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1222 handle_fetch_head(remotes, autogen);
1223 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1224 } else {
1225 for (i = 0; i < argc; i++) {
1226 struct commit *commit = get_merge_parent(argv[i]);
1227 if (!commit)
1228 help_unknown_ref(argv[i], "merge",
1229 _("not something we can merge"));
1230 remotes = &commit_list_insert(commit, remotes)->next;
1232 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1233 if (autogen) {
1234 struct commit_list *p;
1235 for (p = remoteheads; p; p = p->next)
1236 merge_name(merge_remote_util(p->item)->name, autogen);
1240 if (autogen) {
1241 prepare_merge_message(autogen, merge_msg);
1242 strbuf_release(autogen);
1245 return remoteheads;
1248 static int merging_a_throwaway_tag(struct commit *commit)
1250 char *tag_ref;
1251 struct object_id oid;
1252 int is_throwaway_tag = 0;
1254 /* Are we merging a tag? */
1255 if (!merge_remote_util(commit) ||
1256 !merge_remote_util(commit)->obj ||
1257 merge_remote_util(commit)->obj->type != OBJ_TAG)
1258 return is_throwaway_tag;
1261 * Now we know we are merging a tag object. Are we downstream
1262 * and following the tags from upstream? If so, we must have
1263 * the tag object pointed at by "refs/tags/$T" where $T is the
1264 * tagname recorded in the tag object. We want to allow such
1265 * a "just to catch up" merge to fast-forward.
1267 * Otherwise, we are playing an integrator's role, making a
1268 * merge with a throw-away tag from a contributor with
1269 * something like "git pull $contributor $signed_tag".
1270 * We want to forbid such a merge from fast-forwarding
1271 * by default; otherwise we would not keep the signature
1272 * anywhere.
1274 tag_ref = xstrfmt("refs/tags/%s",
1275 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1276 if (!read_ref(tag_ref, &oid) &&
1277 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1278 is_throwaway_tag = 0;
1279 else
1280 is_throwaway_tag = 1;
1281 free(tag_ref);
1282 return is_throwaway_tag;
1285 int cmd_merge(int argc, const char **argv, const char *prefix)
1287 struct object_id result_tree, stash, head_oid;
1288 struct commit *head_commit;
1289 struct strbuf buf = STRBUF_INIT;
1290 int i, ret = 0, head_subsumed;
1291 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1292 struct commit_list *common = NULL;
1293 const char *best_strategy = NULL, *wt_strategy = NULL;
1294 struct commit_list *remoteheads = NULL, *p;
1295 void *branch_to_free;
1296 int orig_argc = argc;
1298 if (argc == 2 && !strcmp(argv[1], "-h"))
1299 usage_with_options(builtin_merge_usage, builtin_merge_options);
1301 prepare_repo_settings(the_repository);
1302 the_repository->settings.command_requires_full_index = 0;
1305 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1306 * current branch.
1308 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1309 if (branch)
1310 skip_prefix(branch, "refs/heads/", &branch);
1312 if (!pull_twohead) {
1313 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1314 if (default_strategy && !strcmp(default_strategy, "ort"))
1315 pull_twohead = "ort";
1318 init_diff_ui_defaults();
1319 git_config(git_merge_config, NULL);
1321 if (!branch || is_null_oid(&head_oid))
1322 head_commit = NULL;
1323 else
1324 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1326 if (branch_mergeoptions)
1327 parse_branch_merge_options(branch_mergeoptions);
1328 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1329 builtin_merge_usage, 0);
1330 if (shortlog_len < 0)
1331 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1333 if (verbosity < 0 && show_progress == -1)
1334 show_progress = 0;
1336 if (abort_current_merge) {
1337 int nargc = 2;
1338 const char *nargv[] = {"reset", "--merge", NULL};
1339 struct strbuf stash_oid = STRBUF_INIT;
1341 if (orig_argc != 2)
1342 usage_msg_opt(_("--abort expects no arguments"),
1343 builtin_merge_usage, builtin_merge_options);
1345 if (!file_exists(git_path_merge_head(the_repository)))
1346 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1348 if (read_oneliner(&stash_oid, git_path_merge_autostash(the_repository),
1349 READ_ONELINER_SKIP_IF_EMPTY))
1350 unlink(git_path_merge_autostash(the_repository));
1352 /* Invoke 'git reset --merge' */
1353 ret = cmd_reset(nargc, nargv, prefix);
1355 if (stash_oid.len)
1356 apply_autostash_oid(stash_oid.buf);
1358 strbuf_release(&stash_oid);
1359 goto done;
1362 if (quit_current_merge) {
1363 if (orig_argc != 2)
1364 usage_msg_opt(_("--quit expects no arguments"),
1365 builtin_merge_usage,
1366 builtin_merge_options);
1368 remove_merge_branch_state(the_repository);
1369 goto done;
1372 if (continue_current_merge) {
1373 int nargc = 1;
1374 const char *nargv[] = {"commit", NULL};
1376 if (orig_argc != 2)
1377 usage_msg_opt(_("--continue expects no arguments"),
1378 builtin_merge_usage, builtin_merge_options);
1380 if (!file_exists(git_path_merge_head(the_repository)))
1381 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1383 /* Invoke 'git commit' */
1384 ret = cmd_commit(nargc, nargv, prefix);
1385 goto done;
1388 if (repo_read_index_unmerged(the_repository))
1389 die_resolve_conflict("merge");
1391 if (file_exists(git_path_merge_head(the_repository))) {
1393 * There is no unmerged entry, don't advise 'git
1394 * add/rm <file>', just 'git commit'.
1396 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1397 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1398 "Please, commit your changes before you merge."));
1399 else
1400 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1402 if (ref_exists("CHERRY_PICK_HEAD")) {
1403 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1404 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1405 "Please, commit your changes before you merge."));
1406 else
1407 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1409 resolve_undo_clear_index(&the_index);
1411 if (option_edit < 0)
1412 option_edit = default_edit_option();
1414 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1416 if (verbosity < 0)
1417 show_diffstat = 0;
1419 if (squash) {
1420 if (fast_forward == FF_NO)
1421 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1422 if (option_commit > 0)
1423 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1425 * squash can now silently disable option_commit - this is not
1426 * a problem as it is only overriding the default, not a user
1427 * supplied option.
1429 option_commit = 0;
1432 if (option_commit < 0)
1433 option_commit = 1;
1435 if (!argc) {
1436 if (default_to_upstream)
1437 argc = setup_with_upstream(&argv);
1438 else
1439 die(_("No commit specified and merge.defaultToUpstream not set."));
1440 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1441 argv[0] = "@{-1}";
1444 if (!argc)
1445 usage_with_options(builtin_merge_usage,
1446 builtin_merge_options);
1448 if (!head_commit) {
1450 * If the merged head is a valid one there is no reason
1451 * to forbid "git merge" into a branch yet to be born.
1452 * We do the same for "git pull".
1454 struct object_id *remote_head_oid;
1455 if (squash)
1456 die(_("Squash commit into empty head not supported yet"));
1457 if (fast_forward == FF_NO)
1458 die(_("Non-fast-forward commit does not make sense into "
1459 "an empty head"));
1460 remoteheads = collect_parents(head_commit, &head_subsumed,
1461 argc, argv, NULL);
1462 if (!remoteheads)
1463 die(_("%s - not something we can merge"), argv[0]);
1464 if (remoteheads->next)
1465 die(_("Can merge only exactly one commit into empty head"));
1467 if (verify_signatures)
1468 verify_merge_signature(remoteheads->item, verbosity,
1469 check_trust_level);
1471 remote_head_oid = &remoteheads->item->object.oid;
1472 read_empty(remote_head_oid);
1473 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1474 UPDATE_REFS_DIE_ON_ERR);
1475 goto done;
1479 * All the rest are the commits being merged; prepare
1480 * the standard merge summary message to be appended
1481 * to the given message.
1483 remoteheads = collect_parents(head_commit, &head_subsumed,
1484 argc, argv, &merge_msg);
1486 if (!head_commit || !argc)
1487 usage_with_options(builtin_merge_usage,
1488 builtin_merge_options);
1490 if (verify_signatures) {
1491 for (p = remoteheads; p; p = p->next) {
1492 verify_merge_signature(p->item, verbosity,
1493 check_trust_level);
1497 strbuf_addstr(&buf, "merge");
1498 for (p = remoteheads; p; p = p->next)
1499 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1500 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1501 strbuf_reset(&buf);
1503 for (p = remoteheads; p; p = p->next) {
1504 struct commit *commit = p->item;
1505 strbuf_addf(&buf, "GITHEAD_%s",
1506 oid_to_hex(&commit->object.oid));
1507 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1508 strbuf_reset(&buf);
1509 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1510 fast_forward = FF_NO;
1513 if (!use_strategies && !pull_twohead &&
1514 remoteheads && !remoteheads->next) {
1515 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1516 if (default_strategy)
1517 append_strategy(get_strategy(default_strategy));
1519 if (!use_strategies) {
1520 if (!remoteheads)
1521 ; /* already up-to-date */
1522 else if (!remoteheads->next)
1523 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1524 else
1525 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1528 for (i = 0; i < use_strategies_nr; i++) {
1529 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1530 fast_forward = FF_NO;
1531 if (use_strategies[i]->attr & NO_TRIVIAL)
1532 allow_trivial = 0;
1535 if (!remoteheads)
1536 ; /* already up-to-date */
1537 else if (!remoteheads->next)
1538 common = repo_get_merge_bases(the_repository, head_commit,
1539 remoteheads->item);
1540 else {
1541 struct commit_list *list = remoteheads;
1542 commit_list_insert(head_commit, &list);
1543 common = get_octopus_merge_bases(list);
1544 free(list);
1547 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1548 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1550 if (remoteheads && !common) {
1551 /* No common ancestors found. */
1552 if (!allow_unrelated_histories)
1553 die(_("refusing to merge unrelated histories"));
1554 /* otherwise, we need a real merge. */
1555 } else if (!remoteheads ||
1556 (!remoteheads->next && !common->next &&
1557 common->item == remoteheads->item)) {
1559 * If head can reach all the merge then we are up to date.
1560 * but first the most common case of merging one remote.
1562 finish_up_to_date();
1563 goto done;
1564 } else if (fast_forward != FF_NO && !remoteheads->next &&
1565 !common->next &&
1566 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1567 /* Again the most common case of merging one remote. */
1568 const char *msg = have_message ?
1569 "Fast-forward (no commit created; -m option ignored)" :
1570 "Fast-forward";
1571 struct commit *commit;
1573 if (verbosity >= 0) {
1574 printf(_("Updating %s..%s\n"),
1575 repo_find_unique_abbrev(the_repository, &head_commit->object.oid,
1576 DEFAULT_ABBREV),
1577 repo_find_unique_abbrev(the_repository, &remoteheads->item->object.oid,
1578 DEFAULT_ABBREV));
1580 commit = remoteheads->item;
1581 if (!commit) {
1582 ret = 1;
1583 goto done;
1586 if (autostash)
1587 create_autostash(the_repository,
1588 git_path_merge_autostash(the_repository));
1589 if (checkout_fast_forward(the_repository,
1590 &head_commit->object.oid,
1591 &commit->object.oid,
1592 overwrite_ignore)) {
1593 apply_autostash(git_path_merge_autostash(the_repository));
1594 ret = 1;
1595 goto done;
1598 finish(head_commit, remoteheads, &commit->object.oid, msg);
1599 remove_merge_branch_state(the_repository);
1600 goto done;
1601 } else if (!remoteheads->next && common->next)
1604 * We are not doing octopus and not fast-forward. Need
1605 * a real merge.
1607 else if (!remoteheads->next && !common->next && option_commit) {
1609 * We are not doing octopus, not fast-forward, and have
1610 * only one common.
1612 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
1613 if (allow_trivial && fast_forward != FF_ONLY) {
1615 * Must first ensure that index matches HEAD before
1616 * attempting a trivial merge.
1618 struct tree *head_tree = repo_get_commit_tree(the_repository,
1619 head_commit);
1620 struct strbuf sb = STRBUF_INIT;
1622 if (repo_index_has_changes(the_repository, head_tree,
1623 &sb)) {
1624 error(_("Your local changes to the following files would be overwritten by merge:\n %s"),
1625 sb.buf);
1626 strbuf_release(&sb);
1627 ret = 2;
1628 goto done;
1631 /* See if it is really trivial. */
1632 git_committer_info(IDENT_STRICT);
1633 printf(_("Trying really trivial in-index merge...\n"));
1634 if (!read_tree_trivial(&common->item->object.oid,
1635 &head_commit->object.oid,
1636 &remoteheads->item->object.oid)) {
1637 ret = merge_trivial(head_commit, remoteheads);
1638 goto done;
1640 printf(_("Nope.\n"));
1642 } else {
1644 * An octopus. If we can reach all the remote we are up
1645 * to date.
1647 int up_to_date = 1;
1648 struct commit_list *j;
1650 for (j = remoteheads; j; j = j->next) {
1651 struct commit_list *common_one;
1654 * Here we *have* to calculate the individual
1655 * merge_bases again, otherwise "git merge HEAD^
1656 * HEAD^^" would be missed.
1658 common_one = repo_get_merge_bases(the_repository,
1659 head_commit,
1660 j->item);
1661 if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1662 up_to_date = 0;
1663 break;
1666 if (up_to_date) {
1667 finish_up_to_date();
1668 goto done;
1672 if (fast_forward == FF_ONLY)
1673 die_ff_impossible();
1675 if (autostash)
1676 create_autostash(the_repository,
1677 git_path_merge_autostash(the_repository));
1679 /* We are going to make a new commit. */
1680 git_committer_info(IDENT_STRICT);
1683 * At this point, we need a real merge. No matter what strategy
1684 * we use, it would operate on the index, possibly affecting the
1685 * working tree, and when resolved cleanly, have the desired
1686 * tree in the index -- this means that the index must be in
1687 * sync with the head commit. The strategies are responsible
1688 * to ensure this.
1690 * Stash away the local changes so that we can try more than one
1691 * and/or recover from merge strategies bailing while leaving the
1692 * index and working tree polluted.
1694 if (save_state(&stash))
1695 oidclr(&stash);
1697 for (i = 0; i < use_strategies_nr; i++) {
1698 int ret, cnt;
1699 if (i) {
1700 printf(_("Rewinding the tree to pristine...\n"));
1701 restore_state(&head_commit->object.oid, &stash);
1703 if (use_strategies_nr != 1)
1704 printf(_("Trying merge strategy %s...\n"),
1705 use_strategies[i]->name);
1707 * Remember which strategy left the state in the working
1708 * tree.
1710 wt_strategy = use_strategies[i]->name;
1712 ret = try_merge_strategy(wt_strategy,
1713 common, remoteheads,
1714 head_commit);
1716 * The backend exits with 1 when conflicts are
1717 * left to be resolved, with 2 when it does not
1718 * handle the given merge at all.
1720 if (ret < 2) {
1721 if (!ret) {
1723 * This strategy worked; no point in trying
1724 * another.
1726 merge_was_ok = 1;
1727 best_strategy = wt_strategy;
1728 break;
1730 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1731 if (best_cnt <= 0 || cnt <= best_cnt) {
1732 best_strategy = wt_strategy;
1733 best_cnt = cnt;
1739 * If we have a resulting tree, that means the strategy module
1740 * auto resolved the merge cleanly.
1742 if (merge_was_ok && option_commit) {
1743 automerge_was_ok = 1;
1744 ret = finish_automerge(head_commit, head_subsumed,
1745 common, remoteheads,
1746 &result_tree, wt_strategy);
1747 goto done;
1751 * Pick the result from the best strategy and have the user fix
1752 * it up.
1754 if (!best_strategy) {
1755 restore_state(&head_commit->object.oid, &stash);
1756 if (use_strategies_nr > 1)
1757 fprintf(stderr,
1758 _("No merge strategy handled the merge.\n"));
1759 else
1760 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1761 use_strategies[0]->name);
1762 apply_autostash(git_path_merge_autostash(the_repository));
1763 ret = 2;
1764 goto done;
1765 } else if (best_strategy == wt_strategy)
1766 ; /* We already have its result in the working tree. */
1767 else {
1768 printf(_("Rewinding the tree to pristine...\n"));
1769 restore_state(&head_commit->object.oid, &stash);
1770 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1771 best_strategy);
1772 try_merge_strategy(best_strategy, common, remoteheads,
1773 head_commit);
1776 if (squash) {
1777 finish(head_commit, remoteheads, NULL, NULL);
1779 git_test_write_commit_graph_or_die();
1780 } else
1781 write_merge_state(remoteheads);
1783 if (merge_was_ok)
1784 fprintf(stderr, _("Automatic merge went well; "
1785 "stopped before committing as requested\n"));
1786 else
1787 ret = suggest_conflicts();
1788 if (autostash)
1789 printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1791 done:
1792 if (!automerge_was_ok) {
1793 free_commit_list(common);
1794 free_commit_list(remoteheads);
1796 strbuf_release(&buf);
1797 free(branch_to_free);
1798 discard_index(&the_index);
1799 return ret;