The fifteenth batch
[alt-git.git] / builtin / merge.c
blobfb3eb15b8955661586eeb76bc59d4532354739a9
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 #include "builtin.h"
10 #include "abspath.h"
11 #include "advice.h"
12 #include "config.h"
13 #include "editor.h"
14 #include "environment.h"
15 #include "gettext.h"
16 #include "hex.h"
17 #include "object-name.h"
18 #include "parse-options.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 "path.h"
29 #include "revision.h"
30 #include "unpack-trees.h"
31 #include "cache-tree.h"
32 #include "dir.h"
33 #include "color.h"
34 #include "rerere.h"
35 #include "help.h"
36 #include "merge.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 "sequencer.h"
43 #include "string-list.h"
44 #include "tag.h"
45 #include "alias.h"
46 #include "branch.h"
47 #include "commit-reach.h"
48 #include "wt-status.h"
49 #include "commit-graph.h"
51 #define DEFAULT_TWOHEAD (1<<0)
52 #define DEFAULT_OCTOPUS (1<<1)
53 #define NO_FAST_FORWARD (1<<2)
54 #define NO_TRIVIAL (1<<3)
56 struct strategy {
57 const char *name;
58 unsigned attr;
61 static const char * const builtin_merge_usage[] = {
62 N_("git merge [<options>] [<commit>...]"),
63 "git merge --abort",
64 "git merge --continue",
65 NULL
68 static int show_diffstat = 1, shortlog_len = -1, squash;
69 static int option_commit = -1;
70 static int option_edit = -1;
71 static int allow_trivial = 1, have_message, verify_signatures;
72 static int check_trust_level = 1;
73 static int overwrite_ignore = 1;
74 static struct strbuf merge_msg = STRBUF_INIT;
75 static struct strategy **use_strategies;
76 static size_t use_strategies_nr, use_strategies_alloc;
77 static struct strvec xopts = STRVEC_INIT;
78 static const char *branch;
79 static char *branch_mergeoptions;
80 static int verbosity;
81 static int allow_rerere_auto;
82 static int abort_current_merge;
83 static int quit_current_merge;
84 static int continue_current_merge;
85 static int allow_unrelated_histories;
86 static int show_progress = -1;
87 static int default_to_upstream = 1;
88 static int signoff;
89 static const char *sign_commit;
90 static int autostash;
91 static int no_verify;
92 static char *into_name;
94 static struct strategy all_strategy[] = {
95 { "recursive", NO_TRIVIAL },
96 { "octopus", DEFAULT_OCTOPUS },
97 { "ort", DEFAULT_TWOHEAD | NO_TRIVIAL },
98 { "resolve", 0 },
99 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
100 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
103 static char *pull_twohead, *pull_octopus;
105 enum ff_type {
106 FF_NO,
107 FF_ALLOW,
108 FF_ONLY
111 static enum ff_type fast_forward = FF_ALLOW;
113 static char *cleanup_arg;
114 static enum commit_msg_cleanup_mode cleanup_mode;
116 static int option_parse_message(const struct option *opt,
117 const char *arg, int unset)
119 struct strbuf *buf = opt->value;
121 if (unset)
122 strbuf_setlen(buf, 0);
123 else if (arg) {
124 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
125 have_message = 1;
126 } else
127 return error(_("switch `m' requires a value"));
128 return 0;
131 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
132 const struct option *opt,
133 const char *arg_not_used,
134 int unset)
136 struct strbuf *buf = opt->value;
137 const char *arg;
139 BUG_ON_OPT_ARG(arg_not_used);
140 if (unset)
141 BUG("-F cannot be negated");
143 if (ctx->opt) {
144 arg = ctx->opt;
145 ctx->opt = NULL;
146 } else if (ctx->argc > 1) {
147 ctx->argc--;
148 arg = *++ctx->argv;
149 } else
150 return error(_("option `%s' requires a value"), opt->long_name);
152 if (buf->len)
153 strbuf_addch(buf, '\n');
154 if (ctx->prefix && !is_absolute_path(arg))
155 arg = prefix_filename(ctx->prefix, arg);
156 if (strbuf_read_file(buf, arg, 0) < 0)
157 return error(_("could not read file '%s'"), arg);
158 have_message = 1;
160 return 0;
163 static struct strategy *get_strategy(const char *name)
165 int i;
166 struct strategy *ret;
167 static struct cmdnames main_cmds, other_cmds;
168 static int loaded;
169 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
171 if (!name)
172 return NULL;
174 if (default_strategy &&
175 !strcmp(default_strategy, "ort") &&
176 !strcmp(name, "recursive")) {
177 name = "ort";
180 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
181 if (!strcmp(name, all_strategy[i].name))
182 return &all_strategy[i];
184 if (!loaded) {
185 struct cmdnames not_strategies;
186 loaded = 1;
188 memset(&not_strategies, 0, sizeof(struct cmdnames));
189 load_command_list("git-merge-", &main_cmds, &other_cmds);
190 for (i = 0; i < main_cmds.cnt; i++) {
191 int j, found = 0;
192 struct cmdname *ent = main_cmds.names[i];
193 for (j = 0; !found && j < ARRAY_SIZE(all_strategy); j++)
194 if (!xstrncmpz(all_strategy[j].name, ent->name, ent->len))
195 found = 1;
196 if (!found)
197 add_cmdname(&not_strategies, ent->name, ent->len);
199 exclude_cmds(&main_cmds, &not_strategies);
201 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
202 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
203 fprintf(stderr, _("Available strategies are:"));
204 for (i = 0; i < main_cmds.cnt; i++)
205 fprintf(stderr, " %s", main_cmds.names[i]->name);
206 fprintf(stderr, ".\n");
207 if (other_cmds.cnt) {
208 fprintf(stderr, _("Available custom strategies are:"));
209 for (i = 0; i < other_cmds.cnt; i++)
210 fprintf(stderr, " %s", other_cmds.names[i]->name);
211 fprintf(stderr, ".\n");
213 exit(1);
216 CALLOC_ARRAY(ret, 1);
217 ret->name = xstrdup(name);
218 ret->attr = NO_TRIVIAL;
219 return ret;
222 static void append_strategy(struct strategy *s)
224 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
225 use_strategies[use_strategies_nr++] = s;
228 static int option_parse_strategy(const struct option *opt UNUSED,
229 const char *name, int unset)
231 if (unset)
232 return 0;
234 append_strategy(get_strategy(name));
235 return 0;
238 static struct option builtin_merge_options[] = {
239 OPT_SET_INT('n', NULL, &show_diffstat,
240 N_("do not show a diffstat at the end of the merge"), 0),
241 OPT_BOOL(0, "stat", &show_diffstat,
242 N_("show a diffstat at the end of the merge")),
243 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
244 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
245 N_("add (at most <n>) entries from shortlog to merge commit message"),
246 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
247 OPT_BOOL(0, "squash", &squash,
248 N_("create a single commit instead of doing a merge")),
249 OPT_BOOL(0, "commit", &option_commit,
250 N_("perform a commit if the merge succeeds (default)")),
251 OPT_BOOL('e', "edit", &option_edit,
252 N_("edit message before committing")),
253 OPT_CLEANUP(&cleanup_arg),
254 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
255 OPT_SET_INT_F(0, "ff-only", &fast_forward,
256 N_("abort if fast-forward is not possible"),
257 FF_ONLY, PARSE_OPT_NONEG),
258 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
259 OPT_BOOL(0, "verify-signatures", &verify_signatures,
260 N_("verify that the named commit has a valid GPG signature")),
261 OPT_CALLBACK('s', "strategy", NULL, N_("strategy"),
262 N_("merge strategy to use"), option_parse_strategy),
263 OPT_STRVEC('X', "strategy-option", &xopts, N_("option=value"),
264 N_("option for selected merge strategy")),
265 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
266 N_("merge commit message (for a non-fast-forward merge)"),
267 option_parse_message),
268 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
269 N_("read message from file"), PARSE_OPT_NONEG,
270 NULL, 0, option_read_message },
271 OPT_STRING(0, "into-name", &into_name, N_("name"),
272 N_("use <name> instead of the real target")),
273 OPT__VERBOSITY(&verbosity),
274 OPT_BOOL(0, "abort", &abort_current_merge,
275 N_("abort the current in-progress merge")),
276 OPT_BOOL(0, "quit", &quit_current_merge,
277 N_("--abort but leave index and working tree alone")),
278 OPT_BOOL(0, "continue", &continue_current_merge,
279 N_("continue the current in-progress merge")),
280 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
281 N_("allow merging unrelated histories")),
282 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
283 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
284 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
285 OPT_AUTOSTASH(&autostash),
286 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
287 OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
288 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
289 OPT_END()
292 static int save_state(struct object_id *stash)
294 int len;
295 struct child_process cp = CHILD_PROCESS_INIT;
296 struct strbuf buffer = STRBUF_INIT;
297 struct lock_file lock_file = LOCK_INIT;
298 int fd;
299 int rc = -1;
301 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
302 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
303 if (0 <= fd)
304 repo_update_index_if_able(the_repository, &lock_file);
305 rollback_lock_file(&lock_file);
307 strvec_pushl(&cp.args, "stash", "create", NULL);
308 cp.out = -1;
309 cp.git_cmd = 1;
311 if (start_command(&cp))
312 die(_("could not run stash."));
313 len = strbuf_read(&buffer, cp.out, 1024);
314 close(cp.out);
316 if (finish_command(&cp) || len < 0)
317 die(_("stash failed"));
318 else if (!len) /* no changes */
319 goto out;
320 strbuf_setlen(&buffer, buffer.len-1);
321 if (repo_get_oid(the_repository, buffer.buf, stash))
322 die(_("not a valid object: %s"), buffer.buf);
323 rc = 0;
324 out:
325 strbuf_release(&buffer);
326 return rc;
329 static void read_empty(const struct object_id *oid)
331 struct child_process cmd = CHILD_PROCESS_INIT;
333 strvec_pushl(&cmd.args, "read-tree", "-m", "-u", empty_tree_oid_hex(),
334 oid_to_hex(oid), NULL);
335 cmd.git_cmd = 1;
337 if (run_command(&cmd))
338 die(_("read-tree failed"));
341 static void reset_hard(const struct object_id *oid)
343 struct child_process cmd = CHILD_PROCESS_INIT;
345 strvec_pushl(&cmd.args, "read-tree", "-v", "--reset", "-u",
346 oid_to_hex(oid), NULL);
347 cmd.git_cmd = 1;
349 if (run_command(&cmd))
350 die(_("read-tree failed"));
353 static void restore_state(const struct object_id *head,
354 const struct object_id *stash)
356 struct child_process cmd = CHILD_PROCESS_INIT;
358 reset_hard(head);
360 if (is_null_oid(stash))
361 goto refresh_cache;
363 strvec_pushl(&cmd.args, "stash", "apply", "--index", "--quiet", NULL);
364 strvec_push(&cmd.args, oid_to_hex(stash));
367 * It is OK to ignore error here, for example when there was
368 * nothing to restore.
370 cmd.git_cmd = 1;
371 run_command(&cmd);
373 refresh_cache:
374 discard_index(the_repository->index);
375 if (repo_read_index(the_repository) < 0)
376 die(_("could not read index"));
379 /* This is called when no merge was necessary. */
380 static void finish_up_to_date(void)
382 if (verbosity >= 0) {
383 if (squash)
384 puts(_("Already up to date. (nothing to squash)"));
385 else
386 puts(_("Already up to date."));
388 remove_merge_branch_state(the_repository);
391 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
393 struct rev_info rev;
394 struct strbuf out = STRBUF_INIT;
395 struct commit_list *j;
396 struct pretty_print_context ctx = {0};
398 printf(_("Squash commit -- not updating HEAD\n"));
400 repo_init_revisions(the_repository, &rev, NULL);
401 diff_merges_suppress(&rev);
402 rev.commit_format = CMIT_FMT_MEDIUM;
404 commit->object.flags |= UNINTERESTING;
405 add_pending_object(&rev, &commit->object, NULL);
407 for (j = remoteheads; j; j = j->next)
408 add_pending_object(&rev, &j->item->object, NULL);
410 setup_revisions(0, NULL, &rev, NULL);
411 if (prepare_revision_walk(&rev))
412 die(_("revision walk setup failed"));
414 ctx.abbrev = rev.abbrev;
415 ctx.date_mode = rev.date_mode;
416 ctx.fmt = rev.commit_format;
418 strbuf_addstr(&out, "Squashed commit of the following:\n");
419 while ((commit = get_revision(&rev)) != NULL) {
420 strbuf_addch(&out, '\n');
421 strbuf_addf(&out, "commit %s\n",
422 oid_to_hex(&commit->object.oid));
423 pretty_print_commit(&ctx, commit, &out);
425 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
426 strbuf_release(&out);
427 release_revisions(&rev);
430 static void finish(struct commit *head_commit,
431 struct commit_list *remoteheads,
432 const struct object_id *new_head, const char *msg)
434 struct strbuf reflog_message = STRBUF_INIT;
435 const struct object_id *head = &head_commit->object.oid;
437 if (!msg)
438 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
439 else {
440 if (verbosity >= 0)
441 printf("%s\n", msg);
442 strbuf_addf(&reflog_message, "%s: %s",
443 getenv("GIT_REFLOG_ACTION"), msg);
445 if (squash) {
446 squash_message(head_commit, remoteheads);
447 } else {
448 if (verbosity >= 0 && !merge_msg.len)
449 printf(_("No merge message -- not updating HEAD\n"));
450 else {
451 refs_update_ref(get_main_ref_store(the_repository),
452 reflog_message.buf, "HEAD", new_head,
453 head,
454 0, UPDATE_REFS_DIE_ON_ERR);
456 * We ignore errors in 'gc --auto', since the
457 * user should see them.
459 run_auto_maintenance(verbosity < 0);
462 if (new_head && show_diffstat) {
463 struct diff_options opts;
464 repo_diff_setup(the_repository, &opts);
465 init_diffstat_widths(&opts);
466 opts.output_format |=
467 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
468 opts.detect_rename = DIFF_DETECT_RENAME;
469 diff_setup_done(&opts);
470 diff_tree_oid(head, new_head, "", &opts);
471 diffcore_std(&opts);
472 diff_flush(&opts);
475 /* Run a post-merge hook */
476 run_hooks_l("post-merge", squash ? "1" : "0", NULL);
478 if (new_head)
479 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
480 strbuf_release(&reflog_message);
483 /* Get the name for the merge commit's message. */
484 static void merge_name(const char *remote, struct strbuf *msg)
486 struct commit *remote_head;
487 struct object_id branch_head;
488 struct strbuf bname = STRBUF_INIT;
489 struct merge_remote_desc *desc;
490 const char *ptr;
491 char *found_ref = NULL;
492 int len, early;
494 strbuf_branchname(&bname, remote, 0);
495 remote = bname.buf;
497 oidclr(&branch_head);
498 remote_head = get_merge_parent(remote);
499 if (!remote_head)
500 die(_("'%s' does not point to a commit"), remote);
502 if (repo_dwim_ref(the_repository, remote, strlen(remote), &branch_head,
503 &found_ref, 0) > 0) {
504 if (starts_with(found_ref, "refs/heads/")) {
505 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
506 oid_to_hex(&branch_head), remote);
507 goto cleanup;
509 if (starts_with(found_ref, "refs/tags/")) {
510 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
511 oid_to_hex(&branch_head), remote);
512 goto cleanup;
514 if (starts_with(found_ref, "refs/remotes/")) {
515 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
516 oid_to_hex(&branch_head), remote);
517 goto cleanup;
521 /* See if remote matches <name>^^^.. or <name>~<number> */
522 for (len = 0, ptr = remote + strlen(remote);
523 remote < ptr && ptr[-1] == '^';
524 ptr--)
525 len++;
526 if (len)
527 early = 1;
528 else {
529 early = 0;
530 ptr = strrchr(remote, '~');
531 if (ptr) {
532 int seen_nonzero = 0;
534 len++; /* count ~ */
535 while (*++ptr && isdigit(*ptr)) {
536 seen_nonzero |= (*ptr != '0');
537 len++;
539 if (*ptr)
540 len = 0; /* not ...~<number> */
541 else if (seen_nonzero)
542 early = 1;
543 else if (len == 1)
544 early = 1; /* "name~" is "name~1"! */
547 if (len) {
548 struct strbuf truname = STRBUF_INIT;
549 strbuf_addf(&truname, "refs/heads/%s", remote);
550 strbuf_setlen(&truname, truname.len - len);
551 if (refs_ref_exists(get_main_ref_store(the_repository), truname.buf)) {
552 strbuf_addf(msg,
553 "%s\t\tbranch '%s'%s of .\n",
554 oid_to_hex(&remote_head->object.oid),
555 truname.buf + 11,
556 (early ? " (early part)" : ""));
557 strbuf_release(&truname);
558 goto cleanup;
560 strbuf_release(&truname);
563 desc = merge_remote_util(remote_head);
564 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
565 strbuf_addf(msg, "%s\t\t%s '%s'\n",
566 oid_to_hex(&desc->obj->oid),
567 type_name(desc->obj->type),
568 remote);
569 goto cleanup;
572 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
573 oid_to_hex(&remote_head->object.oid), remote);
574 cleanup:
575 free(found_ref);
576 strbuf_release(&bname);
579 static void parse_branch_merge_options(char *bmo)
581 const char **argv;
582 int argc;
584 if (!bmo)
585 return;
586 argc = split_cmdline(bmo, &argv);
587 if (argc < 0)
588 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
589 _(split_cmdline_strerror(argc)));
590 REALLOC_ARRAY(argv, argc + 2);
591 MOVE_ARRAY(argv + 1, argv, argc + 1);
592 argc++;
593 argv[0] = "branch.*.mergeoptions";
594 parse_options(argc, argv, NULL, builtin_merge_options,
595 builtin_merge_usage, 0);
596 free(argv);
599 static int git_merge_config(const char *k, const char *v,
600 const struct config_context *ctx, void *cb)
602 int status;
603 const char *str;
605 if (branch &&
606 skip_prefix(k, "branch.", &str) &&
607 skip_prefix(str, branch, &str) &&
608 !strcmp(str, ".mergeoptions")) {
609 free(branch_mergeoptions);
610 branch_mergeoptions = xstrdup(v);
611 return 0;
614 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat")) {
615 show_diffstat = git_config_bool(k, v);
616 } else if (!strcmp(k, "merge.verifysignatures")) {
617 verify_signatures = git_config_bool(k, v);
618 } else if (!strcmp(k, "pull.twohead")) {
619 FREE_AND_NULL(pull_twohead);
620 return git_config_string(&pull_twohead, k, v);
621 } else if (!strcmp(k, "pull.octopus")) {
622 FREE_AND_NULL(pull_octopus);
623 return git_config_string(&pull_octopus, k, v);
624 } else if (!strcmp(k, "commit.cleanup")) {
625 return git_config_string(&cleanup_arg, k, v);
626 } else if (!strcmp(k, "merge.ff")) {
627 int boolval = git_parse_maybe_bool(v);
628 if (0 <= boolval) {
629 fast_forward = boolval ? FF_ALLOW : FF_NO;
630 } else if (v && !strcmp(v, "only")) {
631 fast_forward = FF_ONLY;
632 } /* do not barf on values from future versions of git */
633 return 0;
634 } else if (!strcmp(k, "merge.defaulttoupstream")) {
635 default_to_upstream = git_config_bool(k, v);
636 return 0;
637 } else if (!strcmp(k, "commit.gpgsign")) {
638 sign_commit = git_config_bool(k, v) ? "" : NULL;
639 return 0;
640 } else if (!strcmp(k, "gpg.mintrustlevel")) {
641 check_trust_level = 0;
642 } else if (!strcmp(k, "merge.autostash")) {
643 autostash = git_config_bool(k, v);
644 return 0;
647 status = fmt_merge_msg_config(k, v, ctx, cb);
648 if (status)
649 return status;
650 return git_diff_ui_config(k, v, ctx, cb);
653 static int read_tree_trivial(struct object_id *common, struct object_id *head,
654 struct object_id *one)
656 int i, nr_trees = 0;
657 struct tree *trees[MAX_UNPACK_TREES];
658 struct tree_desc t[MAX_UNPACK_TREES];
659 struct unpack_trees_options opts;
661 memset(&opts, 0, sizeof(opts));
662 opts.head_idx = 2;
663 opts.src_index = the_repository->index;
664 opts.dst_index = the_repository->index;
665 opts.update = 1;
666 opts.verbose_update = 1;
667 opts.trivial_merges_only = 1;
668 opts.merge = 1;
669 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
670 trees[nr_trees] = parse_tree_indirect(common);
671 if (!trees[nr_trees++])
672 return -1;
673 trees[nr_trees] = parse_tree_indirect(head);
674 if (!trees[nr_trees++])
675 return -1;
676 trees[nr_trees] = parse_tree_indirect(one);
677 if (!trees[nr_trees++])
678 return -1;
679 opts.fn = threeway_merge;
680 cache_tree_free(&the_repository->index->cache_tree);
681 for (i = 0; i < nr_trees; i++) {
682 parse_tree(trees[i]);
683 init_tree_desc(t+i, &trees[i]->object.oid,
684 trees[i]->buffer, trees[i]->size);
686 if (unpack_trees(nr_trees, t, &opts))
687 return -1;
688 return 0;
691 static void write_tree_trivial(struct object_id *oid)
693 if (write_index_as_tree(oid, the_repository->index, get_index_file(), 0, NULL))
694 die(_("git write-tree failed to write a tree"));
697 static int try_merge_strategy(const char *strategy, struct commit_list *common,
698 struct commit_list *remoteheads,
699 struct commit *head)
701 const char *head_arg = "HEAD";
703 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
704 SKIP_IF_UNCHANGED, 0, NULL, NULL,
705 NULL) < 0)
706 return error(_("Unable to write index."));
708 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
709 !strcmp(strategy, "ort")) {
710 struct lock_file lock = LOCK_INIT;
711 int clean, x;
712 struct commit *result;
713 struct commit_list *reversed = NULL;
714 struct merge_options o;
715 struct commit_list *j;
717 if (remoteheads->next) {
718 error(_("Not handling anything other than two heads merge."));
719 return 2;
722 init_merge_options(&o, the_repository);
723 if (!strcmp(strategy, "subtree"))
724 o.subtree_shift = "";
726 o.show_rename_progress =
727 show_progress == -1 ? isatty(2) : show_progress;
729 for (x = 0; x < xopts.nr; x++)
730 if (parse_merge_opt(&o, xopts.v[x]))
731 die(_("unknown strategy option: -X%s"), xopts.v[x]);
733 o.branch1 = head_arg;
734 o.branch2 = merge_remote_util(remoteheads->item)->name;
736 for (j = common; j; j = j->next)
737 commit_list_insert(j->item, &reversed);
739 repo_hold_locked_index(the_repository, &lock,
740 LOCK_DIE_ON_ERROR);
741 if (!strcmp(strategy, "ort"))
742 clean = merge_ort_recursive(&o, head, remoteheads->item,
743 reversed, &result);
744 else
745 clean = merge_recursive(&o, head, remoteheads->item,
746 reversed, &result);
747 if (clean < 0) {
748 rollback_lock_file(&lock);
749 return 2;
751 if (write_locked_index(the_repository->index, &lock,
752 COMMIT_LOCK | SKIP_IF_UNCHANGED))
753 die(_("unable to write %s"), get_index_file());
754 return clean ? 0 : 1;
755 } else {
756 return try_merge_command(the_repository,
757 strategy, xopts.nr, xopts.v,
758 common, head_arg, remoteheads);
762 static void count_diff_files(struct diff_queue_struct *q,
763 struct diff_options *opt UNUSED, void *data)
765 int *count = data;
767 (*count) += q->nr;
770 static int count_unmerged_entries(void)
772 int i, ret = 0;
774 for (i = 0; i < the_repository->index->cache_nr; i++)
775 if (ce_stage(the_repository->index->cache[i]))
776 ret++;
778 return ret;
781 static void add_strategies(const char *string, unsigned attr)
783 int i;
785 if (string) {
786 struct string_list list = STRING_LIST_INIT_DUP;
787 struct string_list_item *item;
788 string_list_split(&list, string, ' ', -1);
789 for_each_string_list_item(item, &list)
790 append_strategy(get_strategy(item->string));
791 string_list_clear(&list, 0);
792 return;
794 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
795 if (all_strategy[i].attr & attr)
796 append_strategy(&all_strategy[i]);
800 static void read_merge_msg(struct strbuf *msg)
802 const char *filename = git_path_merge_msg(the_repository);
803 strbuf_reset(msg);
804 if (strbuf_read_file(msg, filename, 0) < 0)
805 die_errno(_("Could not read from '%s'"), filename);
808 static void write_merge_state(struct commit_list *);
809 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
811 if (err_msg)
812 error("%s", err_msg);
813 fprintf(stderr,
814 _("Not committing merge; use 'git commit' to complete the merge.\n"));
815 write_merge_state(remoteheads);
816 exit(1);
819 static const char merge_editor_comment[] =
820 N_("Please enter a commit message to explain why this merge is necessary,\n"
821 "especially if it merges an updated upstream into a topic branch.\n"
822 "\n");
824 static const char scissors_editor_comment[] =
825 N_("An empty message aborts the commit.\n");
827 static const char no_scissors_editor_comment[] =
828 N_("Lines starting with '%s' will be ignored, and an empty message aborts\n"
829 "the commit.\n");
831 static void write_merge_heads(struct commit_list *);
832 static void prepare_to_commit(struct commit_list *remoteheads)
834 struct strbuf msg = STRBUF_INIT;
835 const char *index_file = get_index_file();
837 if (!no_verify) {
838 int invoked_hook;
840 if (run_commit_hook(0 < option_edit, index_file, &invoked_hook,
841 "pre-merge-commit", NULL))
842 abort_commit(remoteheads, NULL);
844 * Re-read the index as pre-merge-commit hook could have updated it,
845 * and write it out as a tree. We must do this before we invoke
846 * the editor and after we invoke run_status above.
848 if (invoked_hook)
849 discard_index(the_repository->index);
851 read_index_from(the_repository->index, index_file, get_git_dir());
852 strbuf_addbuf(&msg, &merge_msg);
853 if (squash)
854 BUG("the control must not reach here under --squash");
855 if (0 < option_edit) {
856 strbuf_addch(&msg, '\n');
857 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
858 wt_status_append_cut_line(&msg);
859 strbuf_commented_addf(&msg, comment_line_str, "\n");
861 strbuf_commented_addf(&msg, comment_line_str,
862 _(merge_editor_comment));
863 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
864 strbuf_commented_addf(&msg, comment_line_str,
865 _(scissors_editor_comment));
866 else
867 strbuf_commented_addf(&msg, comment_line_str,
868 _(no_scissors_editor_comment), comment_line_str);
870 if (signoff)
871 append_signoff(&msg, ignored_log_message_bytes(msg.buf, msg.len), 0);
872 write_merge_heads(remoteheads);
873 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
874 if (run_commit_hook(0 < option_edit, get_index_file(), NULL,
875 "prepare-commit-msg",
876 git_path_merge_msg(the_repository), "merge", NULL))
877 abort_commit(remoteheads, NULL);
878 if (0 < option_edit) {
879 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
880 abort_commit(remoteheads, NULL);
883 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
884 NULL, "commit-msg",
885 git_path_merge_msg(the_repository), NULL))
886 abort_commit(remoteheads, NULL);
888 read_merge_msg(&msg);
889 cleanup_message(&msg, cleanup_mode, 0);
890 if (!msg.len)
891 abort_commit(remoteheads, _("Empty commit message."));
892 strbuf_release(&merge_msg);
893 strbuf_addbuf(&merge_msg, &msg);
894 strbuf_release(&msg);
897 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
899 struct object_id result_tree, result_commit;
900 struct commit_list *parents, **pptr = &parents;
902 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
903 SKIP_IF_UNCHANGED, 0, NULL, NULL,
904 NULL) < 0)
905 return error(_("Unable to write index."));
907 write_tree_trivial(&result_tree);
908 printf(_("Wonderful.\n"));
909 pptr = commit_list_append(head, pptr);
910 pptr = commit_list_append(remoteheads->item, pptr);
911 prepare_to_commit(remoteheads);
912 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
913 &result_commit, NULL, sign_commit))
914 die(_("failed to write commit object"));
915 finish(head, remoteheads, &result_commit, "In-index merge");
916 remove_merge_branch_state(the_repository);
917 return 0;
920 static int finish_automerge(struct commit *head,
921 int head_subsumed,
922 struct commit_list *common,
923 struct commit_list *remoteheads,
924 struct object_id *result_tree,
925 const char *wt_strategy)
927 struct commit_list *parents = NULL;
928 struct strbuf buf = STRBUF_INIT;
929 struct object_id result_commit;
931 write_tree_trivial(result_tree);
932 free_commit_list(common);
933 parents = remoteheads;
934 if (!head_subsumed || fast_forward == FF_NO)
935 commit_list_insert(head, &parents);
936 prepare_to_commit(remoteheads);
937 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
938 &result_commit, NULL, sign_commit))
939 die(_("failed to write commit object"));
940 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
941 finish(head, remoteheads, &result_commit, buf.buf);
942 strbuf_release(&buf);
943 remove_merge_branch_state(the_repository);
944 return 0;
947 static int suggest_conflicts(void)
949 const char *filename;
950 FILE *fp;
951 struct strbuf msgbuf = STRBUF_INIT;
953 filename = git_path_merge_msg(the_repository);
954 fp = xfopen(filename, "a");
957 * We can't use cleanup_mode because if we're not using the editor,
958 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
959 * though the message is meant to be processed later by git-commit.
960 * Thus, we will get the cleanup mode which is returned when we _are_
961 * using an editor.
963 append_conflicts_hint(the_repository->index, &msgbuf,
964 get_cleanup_mode(cleanup_arg, 1));
965 fputs(msgbuf.buf, fp);
966 strbuf_release(&msgbuf);
967 fclose(fp);
968 repo_rerere(the_repository, allow_rerere_auto);
969 printf(_("Automatic merge failed; "
970 "fix conflicts and then commit the result.\n"));
971 return 1;
974 static int evaluate_result(void)
976 int cnt = 0;
977 struct rev_info rev;
979 /* Check how many files differ. */
980 repo_init_revisions(the_repository, &rev, "");
981 setup_revisions(0, NULL, &rev, NULL);
982 rev.diffopt.output_format |=
983 DIFF_FORMAT_CALLBACK;
984 rev.diffopt.format_callback = count_diff_files;
985 rev.diffopt.format_callback_data = &cnt;
986 run_diff_files(&rev, 0);
989 * Check how many unmerged entries are
990 * there.
992 cnt += count_unmerged_entries();
994 release_revisions(&rev);
995 return cnt;
999 * Pretend as if the user told us to merge with the remote-tracking
1000 * branch we have for the upstream of the current branch
1002 static int setup_with_upstream(const char ***argv)
1004 struct branch *branch = branch_get(NULL);
1005 int i;
1006 const char **args;
1008 if (!branch)
1009 die(_("No current branch."));
1010 if (!branch->remote_name)
1011 die(_("No remote for the current branch."));
1012 if (!branch->merge_nr)
1013 die(_("No default upstream defined for the current branch."));
1015 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1016 for (i = 0; i < branch->merge_nr; i++) {
1017 if (!branch->merge[i]->dst)
1018 die(_("No remote-tracking branch for %s from %s"),
1019 branch->merge[i]->src, branch->remote_name);
1020 args[i] = branch->merge[i]->dst;
1022 args[i] = NULL;
1023 *argv = args;
1024 return i;
1027 static void write_merge_heads(struct commit_list *remoteheads)
1029 struct commit_list *j;
1030 struct strbuf buf = STRBUF_INIT;
1032 for (j = remoteheads; j; j = j->next) {
1033 struct object_id *oid;
1034 struct commit *c = j->item;
1035 struct merge_remote_desc *desc;
1037 desc = merge_remote_util(c);
1038 if (desc && desc->obj) {
1039 oid = &desc->obj->oid;
1040 } else {
1041 oid = &c->object.oid;
1043 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1045 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1047 strbuf_reset(&buf);
1048 if (fast_forward == FF_NO)
1049 strbuf_addstr(&buf, "no-ff");
1050 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1051 strbuf_release(&buf);
1054 static void write_merge_state(struct commit_list *remoteheads)
1056 write_merge_heads(remoteheads);
1057 strbuf_addch(&merge_msg, '\n');
1058 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1059 merge_msg.len);
1062 static int default_edit_option(void)
1064 static const char name[] = "GIT_MERGE_AUTOEDIT";
1065 const char *e = getenv(name);
1066 struct stat st_stdin, st_stdout;
1068 if (have_message)
1069 /* an explicit -m msg without --[no-]edit */
1070 return 0;
1072 if (e) {
1073 int v = git_parse_maybe_bool(e);
1074 if (v < 0)
1075 die(_("Bad value '%s' in environment '%s'"), e, name);
1076 return v;
1079 /* Use editor if stdin and stdout are the same and is a tty */
1080 return (!fstat(0, &st_stdin) &&
1081 !fstat(1, &st_stdout) &&
1082 isatty(0) && isatty(1) &&
1083 st_stdin.st_dev == st_stdout.st_dev &&
1084 st_stdin.st_ino == st_stdout.st_ino &&
1085 st_stdin.st_mode == st_stdout.st_mode);
1088 static struct commit_list *reduce_parents(struct commit *head_commit,
1089 int *head_subsumed,
1090 struct commit_list *remoteheads)
1092 struct commit_list *parents, **remotes;
1095 * Is the current HEAD reachable from another commit being
1096 * merged? If so we do not want to record it as a parent of
1097 * the resulting merge, unless --no-ff is given. We will flip
1098 * this variable to 0 when we find HEAD among the independent
1099 * tips being merged.
1101 *head_subsumed = 1;
1103 /* Find what parents to record by checking independent ones. */
1104 parents = reduce_heads(remoteheads);
1105 free_commit_list(remoteheads);
1107 remoteheads = NULL;
1108 remotes = &remoteheads;
1109 while (parents) {
1110 struct commit *commit = pop_commit(&parents);
1111 if (commit == head_commit)
1112 *head_subsumed = 0;
1113 else
1114 remotes = &commit_list_insert(commit, remotes)->next;
1116 return remoteheads;
1119 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1121 struct fmt_merge_msg_opts opts;
1123 memset(&opts, 0, sizeof(opts));
1124 opts.add_title = !have_message;
1125 opts.shortlog_len = shortlog_len;
1126 opts.credit_people = (0 < option_edit);
1127 opts.into_name = into_name;
1129 fmt_merge_msg(merge_names, merge_msg, &opts);
1130 if (merge_msg->len)
1131 strbuf_setlen(merge_msg, merge_msg->len - 1);
1134 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1136 const char *filename;
1137 int fd, pos, npos;
1138 struct strbuf fetch_head_file = STRBUF_INIT;
1139 const unsigned hexsz = the_hash_algo->hexsz;
1141 if (!merge_names)
1142 merge_names = &fetch_head_file;
1144 filename = git_path_fetch_head(the_repository);
1145 fd = xopen(filename, O_RDONLY);
1147 if (strbuf_read(merge_names, fd, 0) < 0)
1148 die_errno(_("could not read '%s'"), filename);
1149 if (close(fd) < 0)
1150 die_errno(_("could not close '%s'"), filename);
1152 for (pos = 0; pos < merge_names->len; pos = npos) {
1153 struct object_id oid;
1154 char *ptr;
1155 struct commit *commit;
1157 ptr = strchr(merge_names->buf + pos, '\n');
1158 if (ptr)
1159 npos = ptr - merge_names->buf + 1;
1160 else
1161 npos = merge_names->len;
1163 if (npos - pos < hexsz + 2 ||
1164 get_oid_hex(merge_names->buf + pos, &oid))
1165 commit = NULL; /* bad */
1166 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1167 continue; /* not-for-merge */
1168 else {
1169 char saved = merge_names->buf[pos + hexsz];
1170 merge_names->buf[pos + hexsz] = '\0';
1171 commit = get_merge_parent(merge_names->buf + pos);
1172 merge_names->buf[pos + hexsz] = saved;
1174 if (!commit) {
1175 if (ptr)
1176 *ptr = '\0';
1177 die(_("not something we can merge in %s: %s"),
1178 filename, merge_names->buf + pos);
1180 remotes = &commit_list_insert(commit, remotes)->next;
1183 if (merge_names == &fetch_head_file)
1184 strbuf_release(&fetch_head_file);
1187 static struct commit_list *collect_parents(struct commit *head_commit,
1188 int *head_subsumed,
1189 int argc, const char **argv,
1190 struct strbuf *merge_msg)
1192 int i;
1193 struct commit_list *remoteheads = NULL;
1194 struct commit_list **remotes = &remoteheads;
1195 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1197 if (merge_msg && (!have_message || shortlog_len))
1198 autogen = &merge_names;
1200 if (head_commit)
1201 remotes = &commit_list_insert(head_commit, remotes)->next;
1203 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1204 handle_fetch_head(remotes, autogen);
1205 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1206 } else {
1207 for (i = 0; i < argc; i++) {
1208 struct commit *commit = get_merge_parent(argv[i]);
1209 if (!commit)
1210 help_unknown_ref(argv[i], "merge",
1211 _("not something we can merge"));
1212 remotes = &commit_list_insert(commit, remotes)->next;
1214 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1215 if (autogen) {
1216 struct commit_list *p;
1217 for (p = remoteheads; p; p = p->next)
1218 merge_name(merge_remote_util(p->item)->name, autogen);
1222 if (autogen) {
1223 prepare_merge_message(autogen, merge_msg);
1224 strbuf_release(autogen);
1227 return remoteheads;
1230 static int merging_a_throwaway_tag(struct commit *commit)
1232 char *tag_ref;
1233 struct object_id oid;
1234 int is_throwaway_tag = 0;
1236 /* Are we merging a tag? */
1237 if (!merge_remote_util(commit) ||
1238 !merge_remote_util(commit)->obj ||
1239 merge_remote_util(commit)->obj->type != OBJ_TAG)
1240 return is_throwaway_tag;
1243 * Now we know we are merging a tag object. Are we downstream
1244 * and following the tags from upstream? If so, we must have
1245 * the tag object pointed at by "refs/tags/$T" where $T is the
1246 * tagname recorded in the tag object. We want to allow such
1247 * a "just to catch up" merge to fast-forward.
1249 * Otherwise, we are playing an integrator's role, making a
1250 * merge with a throw-away tag from a contributor with
1251 * something like "git pull $contributor $signed_tag".
1252 * We want to forbid such a merge from fast-forwarding
1253 * by default; otherwise we would not keep the signature
1254 * anywhere.
1256 tag_ref = xstrfmt("refs/tags/%s",
1257 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1258 if (!refs_read_ref(get_main_ref_store(the_repository), tag_ref, &oid) &&
1259 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1260 is_throwaway_tag = 0;
1261 else
1262 is_throwaway_tag = 1;
1263 free(tag_ref);
1264 return is_throwaway_tag;
1267 int cmd_merge(int argc, const char **argv, const char *prefix)
1269 struct object_id result_tree, stash, head_oid;
1270 struct commit *head_commit;
1271 struct strbuf buf = STRBUF_INIT;
1272 int i, ret = 0, head_subsumed;
1273 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1274 struct commit_list *common = NULL;
1275 const char *best_strategy = NULL, *wt_strategy = NULL;
1276 struct commit_list *remoteheads = NULL, *p;
1277 void *branch_to_free;
1278 int orig_argc = argc;
1280 if (argc == 2 && !strcmp(argv[1], "-h"))
1281 usage_with_options(builtin_merge_usage, builtin_merge_options);
1283 prepare_repo_settings(the_repository);
1284 the_repository->settings.command_requires_full_index = 0;
1287 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1288 * current branch.
1290 branch = branch_to_free = refs_resolve_refdup(get_main_ref_store(the_repository),
1291 "HEAD", 0, &head_oid,
1292 NULL);
1293 if (branch)
1294 skip_prefix(branch, "refs/heads/", &branch);
1296 if (!pull_twohead) {
1297 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1298 if (default_strategy && !strcmp(default_strategy, "ort"))
1299 pull_twohead = xstrdup("ort");
1302 init_diff_ui_defaults();
1303 git_config(git_merge_config, NULL);
1305 if (!branch || is_null_oid(&head_oid))
1306 head_commit = NULL;
1307 else
1308 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1310 if (branch_mergeoptions)
1311 parse_branch_merge_options(branch_mergeoptions);
1312 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1313 builtin_merge_usage, 0);
1314 if (shortlog_len < 0)
1315 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1317 if (verbosity < 0 && show_progress == -1)
1318 show_progress = 0;
1320 if (abort_current_merge) {
1321 int nargc = 2;
1322 const char *nargv[] = {"reset", "--merge", NULL};
1323 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
1324 struct object_id stash_oid = {0};
1326 if (orig_argc != 2)
1327 usage_msg_opt(_("--abort expects no arguments"),
1328 builtin_merge_usage, builtin_merge_options);
1330 if (!file_exists(git_path_merge_head(the_repository)))
1331 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1333 if (!refs_read_ref(get_main_ref_store(the_repository), "MERGE_AUTOSTASH", &stash_oid))
1334 refs_delete_ref(get_main_ref_store(the_repository),
1335 "", "MERGE_AUTOSTASH", &stash_oid,
1336 REF_NO_DEREF);
1338 /* Invoke 'git reset --merge' */
1339 ret = cmd_reset(nargc, nargv, prefix);
1341 if (!is_null_oid(&stash_oid)) {
1342 oid_to_hex_r(stash_oid_hex, &stash_oid);
1343 apply_autostash_oid(stash_oid_hex);
1346 goto done;
1349 if (quit_current_merge) {
1350 if (orig_argc != 2)
1351 usage_msg_opt(_("--quit expects no arguments"),
1352 builtin_merge_usage,
1353 builtin_merge_options);
1355 remove_merge_branch_state(the_repository);
1356 goto done;
1359 if (continue_current_merge) {
1360 int nargc = 1;
1361 const char *nargv[] = {"commit", NULL};
1363 if (orig_argc != 2)
1364 usage_msg_opt(_("--continue expects no arguments"),
1365 builtin_merge_usage, builtin_merge_options);
1367 if (!file_exists(git_path_merge_head(the_repository)))
1368 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1370 /* Invoke 'git commit' */
1371 ret = cmd_commit(nargc, nargv, prefix);
1372 goto done;
1375 if (repo_read_index_unmerged(the_repository))
1376 die_resolve_conflict("merge");
1378 if (file_exists(git_path_merge_head(the_repository))) {
1380 * There is no unmerged entry, don't advise 'git
1381 * add/rm <file>', just 'git commit'.
1383 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1384 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1385 "Please, commit your changes before you merge."));
1386 else
1387 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1389 if (refs_ref_exists(get_main_ref_store(the_repository), "CHERRY_PICK_HEAD")) {
1390 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1391 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1392 "Please, commit your changes before you merge."));
1393 else
1394 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1396 resolve_undo_clear_index(the_repository->index);
1398 if (option_edit < 0)
1399 option_edit = default_edit_option();
1401 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1403 if (verbosity < 0)
1404 show_diffstat = 0;
1406 if (squash) {
1407 if (fast_forward == FF_NO)
1408 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1409 if (option_commit > 0)
1410 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1412 * squash can now silently disable option_commit - this is not
1413 * a problem as it is only overriding the default, not a user
1414 * supplied option.
1416 option_commit = 0;
1419 if (option_commit < 0)
1420 option_commit = 1;
1422 if (!argc) {
1423 if (default_to_upstream)
1424 argc = setup_with_upstream(&argv);
1425 else
1426 die(_("No commit specified and merge.defaultToUpstream not set."));
1427 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1428 argv[0] = "@{-1}";
1431 if (!argc)
1432 usage_with_options(builtin_merge_usage,
1433 builtin_merge_options);
1435 if (!head_commit) {
1437 * If the merged head is a valid one there is no reason
1438 * to forbid "git merge" into a branch yet to be born.
1439 * We do the same for "git pull".
1441 struct object_id *remote_head_oid;
1442 if (squash)
1443 die(_("Squash commit into empty head not supported yet"));
1444 if (fast_forward == FF_NO)
1445 die(_("Non-fast-forward commit does not make sense into "
1446 "an empty head"));
1447 remoteheads = collect_parents(head_commit, &head_subsumed,
1448 argc, argv, NULL);
1449 if (!remoteheads)
1450 die(_("%s - not something we can merge"), argv[0]);
1451 if (remoteheads->next)
1452 die(_("Can merge only exactly one commit into empty head"));
1454 if (verify_signatures)
1455 verify_merge_signature(remoteheads->item, verbosity,
1456 check_trust_level);
1458 remote_head_oid = &remoteheads->item->object.oid;
1459 read_empty(remote_head_oid);
1460 refs_update_ref(get_main_ref_store(the_repository),
1461 "initial pull", "HEAD", remote_head_oid, NULL,
1463 UPDATE_REFS_DIE_ON_ERR);
1464 goto done;
1468 * All the rest are the commits being merged; prepare
1469 * the standard merge summary message to be appended
1470 * to the given message.
1472 remoteheads = collect_parents(head_commit, &head_subsumed,
1473 argc, argv, &merge_msg);
1475 if (!head_commit || !argc)
1476 usage_with_options(builtin_merge_usage,
1477 builtin_merge_options);
1479 if (verify_signatures) {
1480 for (p = remoteheads; p; p = p->next) {
1481 verify_merge_signature(p->item, verbosity,
1482 check_trust_level);
1486 strbuf_addstr(&buf, "merge");
1487 for (p = remoteheads; p; p = p->next)
1488 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1489 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1490 strbuf_reset(&buf);
1492 for (p = remoteheads; p; p = p->next) {
1493 struct commit *commit = p->item;
1494 strbuf_addf(&buf, "GITHEAD_%s",
1495 oid_to_hex(&commit->object.oid));
1496 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1497 strbuf_reset(&buf);
1498 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1499 fast_forward = FF_NO;
1502 if (!use_strategies && !pull_twohead &&
1503 remoteheads && !remoteheads->next) {
1504 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1505 if (default_strategy)
1506 append_strategy(get_strategy(default_strategy));
1508 if (!use_strategies) {
1509 if (!remoteheads)
1510 ; /* already up-to-date */
1511 else if (!remoteheads->next)
1512 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1513 else
1514 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1517 for (i = 0; i < use_strategies_nr; i++) {
1518 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1519 fast_forward = FF_NO;
1520 if (use_strategies[i]->attr & NO_TRIVIAL)
1521 allow_trivial = 0;
1524 if (!remoteheads)
1525 ; /* already up-to-date */
1526 else if (!remoteheads->next) {
1527 if (repo_get_merge_bases(the_repository, head_commit,
1528 remoteheads->item, &common) < 0) {
1529 ret = 2;
1530 goto done;
1532 } else {
1533 struct commit_list *list = remoteheads;
1534 commit_list_insert(head_commit, &list);
1535 if (get_octopus_merge_bases(list, &common) < 0) {
1536 free(list);
1537 ret = 2;
1538 goto done;
1540 free(list);
1543 refs_update_ref(get_main_ref_store(the_repository),
1544 "updating ORIG_HEAD", "ORIG_HEAD",
1545 &head_commit->object.oid, NULL, 0,
1546 UPDATE_REFS_DIE_ON_ERR);
1548 if (remoteheads && !common) {
1549 /* No common ancestors found. */
1550 if (!allow_unrelated_histories)
1551 die(_("refusing to merge unrelated histories"));
1552 /* otherwise, we need a real merge. */
1553 } else if (!remoteheads ||
1554 (!remoteheads->next && !common->next &&
1555 common->item == remoteheads->item)) {
1557 * If head can reach all the merge then we are up to date.
1558 * but first the most common case of merging one remote.
1560 finish_up_to_date();
1561 goto done;
1562 } else if (fast_forward != FF_NO && !remoteheads->next &&
1563 !common->next &&
1564 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1565 /* Again the most common case of merging one remote. */
1566 const char *msg = have_message ?
1567 "Fast-forward (no commit created; -m option ignored)" :
1568 "Fast-forward";
1569 struct commit *commit;
1571 if (verbosity >= 0) {
1572 printf(_("Updating %s..%s\n"),
1573 repo_find_unique_abbrev(the_repository, &head_commit->object.oid,
1574 DEFAULT_ABBREV),
1575 repo_find_unique_abbrev(the_repository, &remoteheads->item->object.oid,
1576 DEFAULT_ABBREV));
1578 commit = remoteheads->item;
1579 if (!commit) {
1580 ret = 1;
1581 goto done;
1584 if (autostash)
1585 create_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1586 if (checkout_fast_forward(the_repository,
1587 &head_commit->object.oid,
1588 &commit->object.oid,
1589 overwrite_ignore)) {
1590 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1591 ret = 1;
1592 goto done;
1595 finish(head_commit, remoteheads, &commit->object.oid, msg);
1596 remove_merge_branch_state(the_repository);
1597 goto done;
1598 } else if (!remoteheads->next && common->next)
1601 * We are not doing octopus and not fast-forward. Need
1602 * a real merge.
1604 else if (!remoteheads->next && !common->next && option_commit) {
1606 * We are not doing octopus, not fast-forward, and have
1607 * only one common.
1609 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
1610 if (allow_trivial && fast_forward != FF_ONLY) {
1612 * Must first ensure that index matches HEAD before
1613 * attempting a trivial merge.
1615 struct tree *head_tree = repo_get_commit_tree(the_repository,
1616 head_commit);
1617 struct strbuf sb = STRBUF_INIT;
1619 if (repo_index_has_changes(the_repository, head_tree,
1620 &sb)) {
1621 error(_("Your local changes to the following files would be overwritten by merge:\n %s"),
1622 sb.buf);
1623 strbuf_release(&sb);
1624 ret = 2;
1625 goto done;
1628 /* See if it is really trivial. */
1629 git_committer_info(IDENT_STRICT);
1630 printf(_("Trying really trivial in-index merge...\n"));
1631 if (!read_tree_trivial(&common->item->object.oid,
1632 &head_commit->object.oid,
1633 &remoteheads->item->object.oid)) {
1634 ret = merge_trivial(head_commit, remoteheads);
1635 goto done;
1637 printf(_("Nope.\n"));
1639 } else {
1641 * An octopus. If we can reach all the remote we are up
1642 * to date.
1644 int up_to_date = 1;
1645 struct commit_list *j;
1647 for (j = remoteheads; j; j = j->next) {
1648 struct commit_list *common_one = NULL;
1649 struct commit *common_item;
1652 * Here we *have* to calculate the individual
1653 * merge_bases again, otherwise "git merge HEAD^
1654 * HEAD^^" would be missed.
1656 if (repo_get_merge_bases(the_repository, head_commit,
1657 j->item, &common_one) < 0)
1658 exit(128);
1660 common_item = common_one->item;
1661 free_commit_list(common_one);
1662 if (!oideq(&common_item->object.oid, &j->item->object.oid)) {
1663 up_to_date = 0;
1664 break;
1667 if (up_to_date) {
1668 finish_up_to_date();
1669 goto done;
1673 if (fast_forward == FF_ONLY)
1674 die_ff_impossible();
1676 if (autostash)
1677 create_autostash_ref(the_repository, "MERGE_AUTOSTASH");
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_ref(the_repository, "MERGE_AUTOSTASH");
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 free(pull_twohead);
1799 free(pull_octopus);
1800 discard_index(the_repository->index);
1801 return ret;