documentation: fix apostrophe usage
[git.git] / builtin / merge.c
blobfd21c0d4f4b88ee2c26b7ba4b1206c20357c17ea
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 "builtin.h"
11 #include "abspath.h"
12 #include "advice.h"
13 #include "config.h"
14 #include "editor.h"
15 #include "environment.h"
16 #include "gettext.h"
17 #include "hex.h"
18 #include "object-name.h"
19 #include "parse-options.h"
20 #include "lockfile.h"
21 #include "run-command.h"
22 #include "hook.h"
23 #include "diff.h"
24 #include "diff-merges.h"
25 #include "refs.h"
26 #include "refspec.h"
27 #include "commit.h"
28 #include "diffcore.h"
29 #include "path.h"
30 #include "revision.h"
31 #include "unpack-trees.h"
32 #include "cache-tree.h"
33 #include "dir.h"
34 #include "utf8.h"
35 #include "log-tree.h"
36 #include "color.h"
37 #include "rerere.h"
38 #include "help.h"
39 #include "merge.h"
40 #include "merge-recursive.h"
41 #include "merge-ort-wrappers.h"
42 #include "resolve-undo.h"
43 #include "remote.h"
44 #include "fmt-merge-msg.h"
45 #include "gpg-interface.h"
46 #include "sequencer.h"
47 #include "string-list.h"
48 #include "packfile.h"
49 #include "tag.h"
50 #include "alias.h"
51 #include "branch.h"
52 #include "commit-reach.h"
53 #include "wt-status.h"
54 #include "commit-graph.h"
56 #define DEFAULT_TWOHEAD (1<<0)
57 #define DEFAULT_OCTOPUS (1<<1)
58 #define NO_FAST_FORWARD (1<<2)
59 #define NO_TRIVIAL (1<<3)
61 struct strategy {
62 const char *name;
63 unsigned attr;
66 static const char * const builtin_merge_usage[] = {
67 N_("git merge [<options>] [<commit>...]"),
68 "git merge --abort",
69 "git merge --continue",
70 NULL
73 static int show_diffstat = 1, shortlog_len = -1, squash;
74 static int option_commit = -1;
75 static int option_edit = -1;
76 static int allow_trivial = 1, have_message, verify_signatures;
77 static int check_trust_level = 1;
78 static int overwrite_ignore = 1;
79 static struct strbuf merge_msg = STRBUF_INIT;
80 static struct strategy **use_strategies;
81 static size_t use_strategies_nr, use_strategies_alloc;
82 static struct strvec xopts = STRVEC_INIT;
83 static const char *branch;
84 static char *branch_mergeoptions;
85 static int verbosity;
86 static int allow_rerere_auto;
87 static int abort_current_merge;
88 static int quit_current_merge;
89 static int continue_current_merge;
90 static int allow_unrelated_histories;
91 static int show_progress = -1;
92 static int default_to_upstream = 1;
93 static int signoff;
94 static const char *sign_commit;
95 static int autostash;
96 static int no_verify;
97 static char *into_name;
99 static struct strategy all_strategy[] = {
100 { "recursive", NO_TRIVIAL },
101 { "octopus", DEFAULT_OCTOPUS },
102 { "ort", DEFAULT_TWOHEAD | NO_TRIVIAL },
103 { "resolve", 0 },
104 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
105 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
108 static const char *pull_twohead, *pull_octopus;
110 enum ff_type {
111 FF_NO,
112 FF_ALLOW,
113 FF_ONLY
116 static enum ff_type fast_forward = FF_ALLOW;
118 static const char *cleanup_arg;
119 static enum commit_msg_cleanup_mode cleanup_mode;
121 static int option_parse_message(const struct option *opt,
122 const char *arg, int unset)
124 struct strbuf *buf = opt->value;
126 if (unset)
127 strbuf_setlen(buf, 0);
128 else if (arg) {
129 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
130 have_message = 1;
131 } else
132 return error(_("switch `m' requires a value"));
133 return 0;
136 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
137 const struct option *opt,
138 const char *arg_not_used,
139 int unset)
141 struct strbuf *buf = opt->value;
142 const char *arg;
144 BUG_ON_OPT_ARG(arg_not_used);
145 if (unset)
146 BUG("-F cannot be negated");
148 if (ctx->opt) {
149 arg = ctx->opt;
150 ctx->opt = NULL;
151 } else if (ctx->argc > 1) {
152 ctx->argc--;
153 arg = *++ctx->argv;
154 } else
155 return error(_("option `%s' requires a value"), opt->long_name);
157 if (buf->len)
158 strbuf_addch(buf, '\n');
159 if (ctx->prefix && !is_absolute_path(arg))
160 arg = prefix_filename(ctx->prefix, arg);
161 if (strbuf_read_file(buf, arg, 0) < 0)
162 return error(_("could not read file '%s'"), arg);
163 have_message = 1;
165 return 0;
168 static struct strategy *get_strategy(const char *name)
170 int i;
171 struct strategy *ret;
172 static struct cmdnames main_cmds, other_cmds;
173 static int loaded;
174 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
176 if (!name)
177 return NULL;
179 if (default_strategy &&
180 !strcmp(default_strategy, "ort") &&
181 !strcmp(name, "recursive")) {
182 name = "ort";
185 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
186 if (!strcmp(name, all_strategy[i].name))
187 return &all_strategy[i];
189 if (!loaded) {
190 struct cmdnames not_strategies;
191 loaded = 1;
193 memset(&not_strategies, 0, sizeof(struct cmdnames));
194 load_command_list("git-merge-", &main_cmds, &other_cmds);
195 for (i = 0; i < main_cmds.cnt; i++) {
196 int j, found = 0;
197 struct cmdname *ent = main_cmds.names[i];
198 for (j = 0; !found && j < ARRAY_SIZE(all_strategy); j++)
199 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
200 && !all_strategy[j].name[ent->len])
201 found = 1;
202 if (!found)
203 add_cmdname(&not_strategies, ent->name, ent->len);
205 exclude_cmds(&main_cmds, &not_strategies);
207 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
208 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
209 fprintf(stderr, _("Available strategies are:"));
210 for (i = 0; i < main_cmds.cnt; i++)
211 fprintf(stderr, " %s", main_cmds.names[i]->name);
212 fprintf(stderr, ".\n");
213 if (other_cmds.cnt) {
214 fprintf(stderr, _("Available custom strategies are:"));
215 for (i = 0; i < other_cmds.cnt; i++)
216 fprintf(stderr, " %s", other_cmds.names[i]->name);
217 fprintf(stderr, ".\n");
219 exit(1);
222 CALLOC_ARRAY(ret, 1);
223 ret->name = xstrdup(name);
224 ret->attr = NO_TRIVIAL;
225 return ret;
228 static void append_strategy(struct strategy *s)
230 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
231 use_strategies[use_strategies_nr++] = s;
234 static int option_parse_strategy(const struct option *opt UNUSED,
235 const char *name, int unset)
237 if (unset)
238 return 0;
240 append_strategy(get_strategy(name));
241 return 0;
244 static struct option builtin_merge_options[] = {
245 OPT_SET_INT('n', NULL, &show_diffstat,
246 N_("do not show a diffstat at the end of the merge"), 0),
247 OPT_BOOL(0, "stat", &show_diffstat,
248 N_("show a diffstat at the end of the merge")),
249 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
250 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
251 N_("add (at most <n>) entries from shortlog to merge commit message"),
252 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
253 OPT_BOOL(0, "squash", &squash,
254 N_("create a single commit instead of doing a merge")),
255 OPT_BOOL(0, "commit", &option_commit,
256 N_("perform a commit if the merge succeeds (default)")),
257 OPT_BOOL('e', "edit", &option_edit,
258 N_("edit message before committing")),
259 OPT_CLEANUP(&cleanup_arg),
260 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
261 OPT_SET_INT_F(0, "ff-only", &fast_forward,
262 N_("abort if fast-forward is not possible"),
263 FF_ONLY, PARSE_OPT_NONEG),
264 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
265 OPT_BOOL(0, "verify-signatures", &verify_signatures,
266 N_("verify that the named commit has a valid GPG signature")),
267 OPT_CALLBACK('s', "strategy", NULL, N_("strategy"),
268 N_("merge strategy to use"), option_parse_strategy),
269 OPT_STRVEC('X', "strategy-option", &xopts, N_("option=value"),
270 N_("option for selected merge strategy")),
271 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
272 N_("merge commit message (for a non-fast-forward merge)"),
273 option_parse_message),
274 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
275 N_("read message from file"), PARSE_OPT_NONEG,
276 NULL, 0, option_read_message },
277 OPT_STRING(0, "into-name", &into_name, N_("name"),
278 N_("use <name> instead of the real target")),
279 OPT__VERBOSITY(&verbosity),
280 OPT_BOOL(0, "abort", &abort_current_merge,
281 N_("abort the current in-progress merge")),
282 OPT_BOOL(0, "quit", &quit_current_merge,
283 N_("--abort but leave index and working tree alone")),
284 OPT_BOOL(0, "continue", &continue_current_merge,
285 N_("continue the current in-progress merge")),
286 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
287 N_("allow merging unrelated histories")),
288 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
289 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
290 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
291 OPT_AUTOSTASH(&autostash),
292 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
293 OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
294 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
295 OPT_END()
298 static int save_state(struct object_id *stash)
300 int len;
301 struct child_process cp = CHILD_PROCESS_INIT;
302 struct strbuf buffer = STRBUF_INIT;
303 struct lock_file lock_file = LOCK_INIT;
304 int fd;
305 int rc = -1;
307 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
308 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
309 if (0 <= fd)
310 repo_update_index_if_able(the_repository, &lock_file);
311 rollback_lock_file(&lock_file);
313 strvec_pushl(&cp.args, "stash", "create", NULL);
314 cp.out = -1;
315 cp.git_cmd = 1;
317 if (start_command(&cp))
318 die(_("could not run stash."));
319 len = strbuf_read(&buffer, cp.out, 1024);
320 close(cp.out);
322 if (finish_command(&cp) || len < 0)
323 die(_("stash failed"));
324 else if (!len) /* no changes */
325 goto out;
326 strbuf_setlen(&buffer, buffer.len-1);
327 if (repo_get_oid(the_repository, buffer.buf, stash))
328 die(_("not a valid object: %s"), buffer.buf);
329 rc = 0;
330 out:
331 strbuf_release(&buffer);
332 return rc;
335 static void read_empty(const struct object_id *oid)
337 struct child_process cmd = CHILD_PROCESS_INIT;
339 strvec_pushl(&cmd.args, "read-tree", "-m", "-u", empty_tree_oid_hex(),
340 oid_to_hex(oid), NULL);
341 cmd.git_cmd = 1;
343 if (run_command(&cmd))
344 die(_("read-tree failed"));
347 static void reset_hard(const struct object_id *oid)
349 struct child_process cmd = CHILD_PROCESS_INIT;
351 strvec_pushl(&cmd.args, "read-tree", "-v", "--reset", "-u",
352 oid_to_hex(oid), NULL);
353 cmd.git_cmd = 1;
355 if (run_command(&cmd))
356 die(_("read-tree failed"));
359 static void restore_state(const struct object_id *head,
360 const struct object_id *stash)
362 struct child_process cmd = CHILD_PROCESS_INIT;
364 reset_hard(head);
366 if (is_null_oid(stash))
367 goto refresh_cache;
369 strvec_pushl(&cmd.args, "stash", "apply", "--index", "--quiet", NULL);
370 strvec_push(&cmd.args, oid_to_hex(stash));
373 * It is OK to ignore error here, for example when there was
374 * nothing to restore.
376 cmd.git_cmd = 1;
377 run_command(&cmd);
379 refresh_cache:
380 discard_index(&the_index);
381 if (repo_read_index(the_repository) < 0)
382 die(_("could not read index"));
385 /* This is called when no merge was necessary. */
386 static void finish_up_to_date(void)
388 if (verbosity >= 0) {
389 if (squash)
390 puts(_("Already up to date. (nothing to squash)"));
391 else
392 puts(_("Already up to date."));
394 remove_merge_branch_state(the_repository);
397 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
399 struct rev_info rev;
400 struct strbuf out = STRBUF_INIT;
401 struct commit_list *j;
402 struct pretty_print_context ctx = {0};
404 printf(_("Squash commit -- not updating HEAD\n"));
406 repo_init_revisions(the_repository, &rev, NULL);
407 diff_merges_suppress(&rev);
408 rev.commit_format = CMIT_FMT_MEDIUM;
410 commit->object.flags |= UNINTERESTING;
411 add_pending_object(&rev, &commit->object, NULL);
413 for (j = remoteheads; j; j = j->next)
414 add_pending_object(&rev, &j->item->object, NULL);
416 setup_revisions(0, NULL, &rev, NULL);
417 if (prepare_revision_walk(&rev))
418 die(_("revision walk setup failed"));
420 ctx.abbrev = rev.abbrev;
421 ctx.date_mode = rev.date_mode;
422 ctx.fmt = rev.commit_format;
424 strbuf_addstr(&out, "Squashed commit of the following:\n");
425 while ((commit = get_revision(&rev)) != NULL) {
426 strbuf_addch(&out, '\n');
427 strbuf_addf(&out, "commit %s\n",
428 oid_to_hex(&commit->object.oid));
429 pretty_print_commit(&ctx, commit, &out);
431 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
432 strbuf_release(&out);
433 release_revisions(&rev);
436 static void finish(struct commit *head_commit,
437 struct commit_list *remoteheads,
438 const struct object_id *new_head, const char *msg)
440 struct strbuf reflog_message = STRBUF_INIT;
441 const struct object_id *head = &head_commit->object.oid;
443 if (!msg)
444 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
445 else {
446 if (verbosity >= 0)
447 printf("%s\n", msg);
448 strbuf_addf(&reflog_message, "%s: %s",
449 getenv("GIT_REFLOG_ACTION"), msg);
451 if (squash) {
452 squash_message(head_commit, remoteheads);
453 } else {
454 if (verbosity >= 0 && !merge_msg.len)
455 printf(_("No merge message -- not updating HEAD\n"));
456 else {
457 update_ref(reflog_message.buf, "HEAD", new_head, head,
458 0, UPDATE_REFS_DIE_ON_ERR);
460 * We ignore errors in 'gc --auto', since the
461 * user should see them.
463 run_auto_maintenance(verbosity < 0);
466 if (new_head && show_diffstat) {
467 struct diff_options opts;
468 repo_diff_setup(the_repository, &opts);
469 opts.stat_width = -1; /* use full terminal width */
470 opts.stat_name_width = -1; /* respect statNameWidth config */
471 opts.stat_graph_width = -1; /* respect statGraphWidth config */
472 opts.output_format |=
473 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
474 opts.detect_rename = DIFF_DETECT_RENAME;
475 diff_setup_done(&opts);
476 diff_tree_oid(head, new_head, "", &opts);
477 diffcore_std(&opts);
478 diff_flush(&opts);
481 /* Run a post-merge hook */
482 run_hooks_l("post-merge", squash ? "1" : "0", NULL);
484 if (new_head)
485 apply_autostash(git_path_merge_autostash(the_repository));
486 strbuf_release(&reflog_message);
489 /* Get the name for the merge commit's message. */
490 static void merge_name(const char *remote, struct strbuf *msg)
492 struct commit *remote_head;
493 struct object_id branch_head;
494 struct strbuf bname = STRBUF_INIT;
495 struct merge_remote_desc *desc;
496 const char *ptr;
497 char *found_ref = NULL;
498 int len, early;
500 strbuf_branchname(&bname, remote, 0);
501 remote = bname.buf;
503 oidclr(&branch_head);
504 remote_head = get_merge_parent(remote);
505 if (!remote_head)
506 die(_("'%s' does not point to a commit"), remote);
508 if (repo_dwim_ref(the_repository, remote, strlen(remote), &branch_head,
509 &found_ref, 0) > 0) {
510 if (starts_with(found_ref, "refs/heads/")) {
511 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
512 oid_to_hex(&branch_head), remote);
513 goto cleanup;
515 if (starts_with(found_ref, "refs/tags/")) {
516 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
517 oid_to_hex(&branch_head), remote);
518 goto cleanup;
520 if (starts_with(found_ref, "refs/remotes/")) {
521 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
522 oid_to_hex(&branch_head), remote);
523 goto cleanup;
527 /* See if remote matches <name>^^^.. or <name>~<number> */
528 for (len = 0, ptr = remote + strlen(remote);
529 remote < ptr && ptr[-1] == '^';
530 ptr--)
531 len++;
532 if (len)
533 early = 1;
534 else {
535 early = 0;
536 ptr = strrchr(remote, '~');
537 if (ptr) {
538 int seen_nonzero = 0;
540 len++; /* count ~ */
541 while (*++ptr && isdigit(*ptr)) {
542 seen_nonzero |= (*ptr != '0');
543 len++;
545 if (*ptr)
546 len = 0; /* not ...~<number> */
547 else if (seen_nonzero)
548 early = 1;
549 else if (len == 1)
550 early = 1; /* "name~" is "name~1"! */
553 if (len) {
554 struct strbuf truname = STRBUF_INIT;
555 strbuf_addf(&truname, "refs/heads/%s", remote);
556 strbuf_setlen(&truname, truname.len - len);
557 if (ref_exists(truname.buf)) {
558 strbuf_addf(msg,
559 "%s\t\tbranch '%s'%s of .\n",
560 oid_to_hex(&remote_head->object.oid),
561 truname.buf + 11,
562 (early ? " (early part)" : ""));
563 strbuf_release(&truname);
564 goto cleanup;
566 strbuf_release(&truname);
569 desc = merge_remote_util(remote_head);
570 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
571 strbuf_addf(msg, "%s\t\t%s '%s'\n",
572 oid_to_hex(&desc->obj->oid),
573 type_name(desc->obj->type),
574 remote);
575 goto cleanup;
578 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
579 oid_to_hex(&remote_head->object.oid), remote);
580 cleanup:
581 free(found_ref);
582 strbuf_release(&bname);
585 static void parse_branch_merge_options(char *bmo)
587 const char **argv;
588 int argc;
590 if (!bmo)
591 return;
592 argc = split_cmdline(bmo, &argv);
593 if (argc < 0)
594 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
595 _(split_cmdline_strerror(argc)));
596 REALLOC_ARRAY(argv, argc + 2);
597 MOVE_ARRAY(argv + 1, argv, argc + 1);
598 argc++;
599 argv[0] = "branch.*.mergeoptions";
600 parse_options(argc, argv, NULL, builtin_merge_options,
601 builtin_merge_usage, 0);
602 free(argv);
605 static int git_merge_config(const char *k, const char *v,
606 const struct config_context *ctx, void *cb)
608 int status;
609 const char *str;
611 if (branch &&
612 skip_prefix(k, "branch.", &str) &&
613 skip_prefix(str, branch, &str) &&
614 !strcmp(str, ".mergeoptions")) {
615 free(branch_mergeoptions);
616 branch_mergeoptions = xstrdup(v);
617 return 0;
620 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
621 show_diffstat = git_config_bool(k, v);
622 else if (!strcmp(k, "merge.verifysignatures"))
623 verify_signatures = git_config_bool(k, v);
624 else if (!strcmp(k, "pull.twohead"))
625 return git_config_string(&pull_twohead, k, v);
626 else if (!strcmp(k, "pull.octopus"))
627 return git_config_string(&pull_octopus, k, v);
628 else if (!strcmp(k, "commit.cleanup"))
629 return git_config_string(&cleanup_arg, k, v);
630 else if (!strcmp(k, "merge.ff")) {
631 int boolval = git_parse_maybe_bool(v);
632 if (0 <= boolval) {
633 fast_forward = boolval ? FF_ALLOW : FF_NO;
634 } else if (v && !strcmp(v, "only")) {
635 fast_forward = FF_ONLY;
636 } /* do not barf on values from future versions of git */
637 return 0;
638 } else if (!strcmp(k, "merge.defaulttoupstream")) {
639 default_to_upstream = git_config_bool(k, v);
640 return 0;
641 } else if (!strcmp(k, "commit.gpgsign")) {
642 sign_commit = git_config_bool(k, v) ? "" : NULL;
643 return 0;
644 } else if (!strcmp(k, "gpg.mintrustlevel")) {
645 check_trust_level = 0;
646 } else if (!strcmp(k, "merge.autostash")) {
647 autostash = git_config_bool(k, v);
648 return 0;
651 status = fmt_merge_msg_config(k, v, ctx, cb);
652 if (status)
653 return status;
654 return git_diff_ui_config(k, v, ctx, cb);
657 static int read_tree_trivial(struct object_id *common, struct object_id *head,
658 struct object_id *one)
660 int i, nr_trees = 0;
661 struct tree *trees[MAX_UNPACK_TREES];
662 struct tree_desc t[MAX_UNPACK_TREES];
663 struct unpack_trees_options opts;
665 memset(&opts, 0, sizeof(opts));
666 opts.head_idx = 2;
667 opts.src_index = &the_index;
668 opts.dst_index = &the_index;
669 opts.update = 1;
670 opts.verbose_update = 1;
671 opts.trivial_merges_only = 1;
672 opts.merge = 1;
673 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
674 trees[nr_trees] = parse_tree_indirect(common);
675 if (!trees[nr_trees++])
676 return -1;
677 trees[nr_trees] = parse_tree_indirect(head);
678 if (!trees[nr_trees++])
679 return -1;
680 trees[nr_trees] = parse_tree_indirect(one);
681 if (!trees[nr_trees++])
682 return -1;
683 opts.fn = threeway_merge;
684 cache_tree_free(&the_index.cache_tree);
685 for (i = 0; i < nr_trees; i++) {
686 parse_tree(trees[i]);
687 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
689 if (unpack_trees(nr_trees, t, &opts))
690 return -1;
691 return 0;
694 static void write_tree_trivial(struct object_id *oid)
696 if (write_index_as_tree(oid, &the_index, get_index_file(), 0, NULL))
697 die(_("git write-tree failed to write a tree"));
700 static int try_merge_strategy(const char *strategy, struct commit_list *common,
701 struct commit_list *remoteheads,
702 struct commit *head)
704 const char *head_arg = "HEAD";
706 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
707 SKIP_IF_UNCHANGED, 0, NULL, NULL,
708 NULL) < 0)
709 return error(_("Unable to write index."));
711 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
712 !strcmp(strategy, "ort")) {
713 struct lock_file lock = LOCK_INIT;
714 int clean, x;
715 struct commit *result;
716 struct commit_list *reversed = NULL;
717 struct merge_options o;
718 struct commit_list *j;
720 if (remoteheads->next) {
721 error(_("Not handling anything other than two heads merge."));
722 return 2;
725 init_merge_options(&o, the_repository);
726 if (!strcmp(strategy, "subtree"))
727 o.subtree_shift = "";
729 o.show_rename_progress =
730 show_progress == -1 ? isatty(2) : show_progress;
732 for (x = 0; x < xopts.nr; x++)
733 if (parse_merge_opt(&o, xopts.v[x]))
734 die(_("unknown strategy option: -X%s"), xopts.v[x]);
736 o.branch1 = head_arg;
737 o.branch2 = merge_remote_util(remoteheads->item)->name;
739 for (j = common; j; j = j->next)
740 commit_list_insert(j->item, &reversed);
742 repo_hold_locked_index(the_repository, &lock,
743 LOCK_DIE_ON_ERROR);
744 if (!strcmp(strategy, "ort"))
745 clean = merge_ort_recursive(&o, head, remoteheads->item,
746 reversed, &result);
747 else
748 clean = merge_recursive(&o, head, remoteheads->item,
749 reversed, &result);
750 if (clean < 0) {
751 rollback_lock_file(&lock);
752 return 2;
754 if (write_locked_index(&the_index, &lock,
755 COMMIT_LOCK | SKIP_IF_UNCHANGED))
756 die(_("unable to write %s"), get_index_file());
757 return clean ? 0 : 1;
758 } else {
759 return try_merge_command(the_repository,
760 strategy, xopts.nr, xopts.v,
761 common, head_arg, remoteheads);
765 static void count_diff_files(struct diff_queue_struct *q,
766 struct diff_options *opt UNUSED, void *data)
768 int *count = data;
770 (*count) += q->nr;
773 static int count_unmerged_entries(void)
775 int i, ret = 0;
777 for (i = 0; i < the_index.cache_nr; i++)
778 if (ce_stage(the_index.cache[i]))
779 ret++;
781 return ret;
784 static void add_strategies(const char *string, unsigned attr)
786 int i;
788 if (string) {
789 struct string_list list = STRING_LIST_INIT_DUP;
790 struct string_list_item *item;
791 string_list_split(&list, string, ' ', -1);
792 for_each_string_list_item(item, &list)
793 append_strategy(get_strategy(item->string));
794 string_list_clear(&list, 0);
795 return;
797 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
798 if (all_strategy[i].attr & attr)
799 append_strategy(&all_strategy[i]);
803 static void read_merge_msg(struct strbuf *msg)
805 const char *filename = git_path_merge_msg(the_repository);
806 strbuf_reset(msg);
807 if (strbuf_read_file(msg, filename, 0) < 0)
808 die_errno(_("Could not read from '%s'"), filename);
811 static void write_merge_state(struct commit_list *);
812 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
814 if (err_msg)
815 error("%s", err_msg);
816 fprintf(stderr,
817 _("Not committing merge; use 'git commit' to complete the merge.\n"));
818 write_merge_state(remoteheads);
819 exit(1);
822 static const char merge_editor_comment[] =
823 N_("Please enter a commit message to explain why this merge is necessary,\n"
824 "especially if it merges an updated upstream into a topic branch.\n"
825 "\n");
827 static const char scissors_editor_comment[] =
828 N_("An empty message aborts the commit.\n");
830 static const char no_scissors_editor_comment[] =
831 N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
832 "the commit.\n");
834 static void write_merge_heads(struct commit_list *);
835 static void prepare_to_commit(struct commit_list *remoteheads)
837 struct strbuf msg = STRBUF_INIT;
838 const char *index_file = get_index_file();
840 if (!no_verify) {
841 int invoked_hook;
843 if (run_commit_hook(0 < option_edit, index_file, &invoked_hook,
844 "pre-merge-commit", NULL))
845 abort_commit(remoteheads, NULL);
847 * Re-read the index as pre-merge-commit hook could have updated it,
848 * and write it out as a tree. We must do this before we invoke
849 * the editor and after we invoke run_status above.
851 if (invoked_hook)
852 discard_index(&the_index);
854 read_index_from(&the_index, index_file, get_git_dir());
855 strbuf_addbuf(&msg, &merge_msg);
856 if (squash)
857 BUG("the control must not reach here under --squash");
858 if (0 < option_edit) {
859 strbuf_addch(&msg, '\n');
860 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
861 wt_status_append_cut_line(&msg);
862 strbuf_commented_addf(&msg, comment_line_char, "\n");
864 strbuf_commented_addf(&msg, comment_line_char,
865 _(merge_editor_comment));
866 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
867 strbuf_commented_addf(&msg, comment_line_char,
868 _(scissors_editor_comment));
869 else
870 strbuf_commented_addf(&msg, comment_line_char,
871 _(no_scissors_editor_comment), comment_line_char);
873 if (signoff)
874 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
875 write_merge_heads(remoteheads);
876 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
877 if (run_commit_hook(0 < option_edit, get_index_file(), NULL,
878 "prepare-commit-msg",
879 git_path_merge_msg(the_repository), "merge", NULL))
880 abort_commit(remoteheads, NULL);
881 if (0 < option_edit) {
882 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
883 abort_commit(remoteheads, NULL);
886 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
887 NULL, "commit-msg",
888 git_path_merge_msg(the_repository), NULL))
889 abort_commit(remoteheads, NULL);
891 read_merge_msg(&msg);
892 cleanup_message(&msg, cleanup_mode, 0);
893 if (!msg.len)
894 abort_commit(remoteheads, _("Empty commit message."));
895 strbuf_release(&merge_msg);
896 strbuf_addbuf(&merge_msg, &msg);
897 strbuf_release(&msg);
900 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
902 struct object_id result_tree, result_commit;
903 struct commit_list *parents, **pptr = &parents;
905 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
906 SKIP_IF_UNCHANGED, 0, NULL, NULL,
907 NULL) < 0)
908 return error(_("Unable to write index."));
910 write_tree_trivial(&result_tree);
911 printf(_("Wonderful.\n"));
912 pptr = commit_list_append(head, pptr);
913 pptr = commit_list_append(remoteheads->item, pptr);
914 prepare_to_commit(remoteheads);
915 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
916 &result_commit, NULL, sign_commit))
917 die(_("failed to write commit object"));
918 finish(head, remoteheads, &result_commit, "In-index merge");
919 remove_merge_branch_state(the_repository);
920 return 0;
923 static int finish_automerge(struct commit *head,
924 int head_subsumed,
925 struct commit_list *common,
926 struct commit_list *remoteheads,
927 struct object_id *result_tree,
928 const char *wt_strategy)
930 struct commit_list *parents = NULL;
931 struct strbuf buf = STRBUF_INIT;
932 struct object_id result_commit;
934 write_tree_trivial(result_tree);
935 free_commit_list(common);
936 parents = remoteheads;
937 if (!head_subsumed || fast_forward == FF_NO)
938 commit_list_insert(head, &parents);
939 prepare_to_commit(remoteheads);
940 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
941 &result_commit, NULL, sign_commit))
942 die(_("failed to write commit object"));
943 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
944 finish(head, remoteheads, &result_commit, buf.buf);
945 strbuf_release(&buf);
946 remove_merge_branch_state(the_repository);
947 return 0;
950 static int suggest_conflicts(void)
952 const char *filename;
953 FILE *fp;
954 struct strbuf msgbuf = STRBUF_INIT;
956 filename = git_path_merge_msg(the_repository);
957 fp = xfopen(filename, "a");
960 * We can't use cleanup_mode because if we're not using the editor,
961 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
962 * though the message is meant to be processed later by git-commit.
963 * Thus, we will get the cleanup mode which is returned when we _are_
964 * using an editor.
966 append_conflicts_hint(&the_index, &msgbuf,
967 get_cleanup_mode(cleanup_arg, 1));
968 fputs(msgbuf.buf, fp);
969 strbuf_release(&msgbuf);
970 fclose(fp);
971 repo_rerere(the_repository, allow_rerere_auto);
972 printf(_("Automatic merge failed; "
973 "fix conflicts and then commit the result.\n"));
974 return 1;
977 static int evaluate_result(void)
979 int cnt = 0;
980 struct rev_info rev;
982 /* Check how many files differ. */
983 repo_init_revisions(the_repository, &rev, "");
984 setup_revisions(0, NULL, &rev, NULL);
985 rev.diffopt.output_format |=
986 DIFF_FORMAT_CALLBACK;
987 rev.diffopt.format_callback = count_diff_files;
988 rev.diffopt.format_callback_data = &cnt;
989 run_diff_files(&rev, 0);
992 * Check how many unmerged entries are
993 * there.
995 cnt += count_unmerged_entries();
997 release_revisions(&rev);
998 return cnt;
1002 * Pretend as if the user told us to merge with the remote-tracking
1003 * branch we have for the upstream of the current branch
1005 static int setup_with_upstream(const char ***argv)
1007 struct branch *branch = branch_get(NULL);
1008 int i;
1009 const char **args;
1011 if (!branch)
1012 die(_("No current branch."));
1013 if (!branch->remote_name)
1014 die(_("No remote for the current branch."));
1015 if (!branch->merge_nr)
1016 die(_("No default upstream defined for the current branch."));
1018 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1019 for (i = 0; i < branch->merge_nr; i++) {
1020 if (!branch->merge[i]->dst)
1021 die(_("No remote-tracking branch for %s from %s"),
1022 branch->merge[i]->src, branch->remote_name);
1023 args[i] = branch->merge[i]->dst;
1025 args[i] = NULL;
1026 *argv = args;
1027 return i;
1030 static void write_merge_heads(struct commit_list *remoteheads)
1032 struct commit_list *j;
1033 struct strbuf buf = STRBUF_INIT;
1035 for (j = remoteheads; j; j = j->next) {
1036 struct object_id *oid;
1037 struct commit *c = j->item;
1038 struct merge_remote_desc *desc;
1040 desc = merge_remote_util(c);
1041 if (desc && desc->obj) {
1042 oid = &desc->obj->oid;
1043 } else {
1044 oid = &c->object.oid;
1046 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1048 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1050 strbuf_reset(&buf);
1051 if (fast_forward == FF_NO)
1052 strbuf_addstr(&buf, "no-ff");
1053 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1054 strbuf_release(&buf);
1057 static void write_merge_state(struct commit_list *remoteheads)
1059 write_merge_heads(remoteheads);
1060 strbuf_addch(&merge_msg, '\n');
1061 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1062 merge_msg.len);
1065 static int default_edit_option(void)
1067 static const char name[] = "GIT_MERGE_AUTOEDIT";
1068 const char *e = getenv(name);
1069 struct stat st_stdin, st_stdout;
1071 if (have_message)
1072 /* an explicit -m msg without --[no-]edit */
1073 return 0;
1075 if (e) {
1076 int v = git_parse_maybe_bool(e);
1077 if (v < 0)
1078 die(_("Bad value '%s' in environment '%s'"), e, name);
1079 return v;
1082 /* Use editor if stdin and stdout are the same and is a tty */
1083 return (!fstat(0, &st_stdin) &&
1084 !fstat(1, &st_stdout) &&
1085 isatty(0) && isatty(1) &&
1086 st_stdin.st_dev == st_stdout.st_dev &&
1087 st_stdin.st_ino == st_stdout.st_ino &&
1088 st_stdin.st_mode == st_stdout.st_mode);
1091 static struct commit_list *reduce_parents(struct commit *head_commit,
1092 int *head_subsumed,
1093 struct commit_list *remoteheads)
1095 struct commit_list *parents, **remotes;
1098 * Is the current HEAD reachable from another commit being
1099 * merged? If so we do not want to record it as a parent of
1100 * the resulting merge, unless --no-ff is given. We will flip
1101 * this variable to 0 when we find HEAD among the independent
1102 * tips being merged.
1104 *head_subsumed = 1;
1106 /* Find what parents to record by checking independent ones. */
1107 parents = reduce_heads(remoteheads);
1108 free_commit_list(remoteheads);
1110 remoteheads = NULL;
1111 remotes = &remoteheads;
1112 while (parents) {
1113 struct commit *commit = pop_commit(&parents);
1114 if (commit == head_commit)
1115 *head_subsumed = 0;
1116 else
1117 remotes = &commit_list_insert(commit, remotes)->next;
1119 return remoteheads;
1122 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1124 struct fmt_merge_msg_opts opts;
1126 memset(&opts, 0, sizeof(opts));
1127 opts.add_title = !have_message;
1128 opts.shortlog_len = shortlog_len;
1129 opts.credit_people = (0 < option_edit);
1130 opts.into_name = into_name;
1132 fmt_merge_msg(merge_names, merge_msg, &opts);
1133 if (merge_msg->len)
1134 strbuf_setlen(merge_msg, merge_msg->len - 1);
1137 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1139 const char *filename;
1140 int fd, pos, npos;
1141 struct strbuf fetch_head_file = STRBUF_INIT;
1142 const unsigned hexsz = the_hash_algo->hexsz;
1144 if (!merge_names)
1145 merge_names = &fetch_head_file;
1147 filename = git_path_fetch_head(the_repository);
1148 fd = xopen(filename, O_RDONLY);
1150 if (strbuf_read(merge_names, fd, 0) < 0)
1151 die_errno(_("could not read '%s'"), filename);
1152 if (close(fd) < 0)
1153 die_errno(_("could not close '%s'"), filename);
1155 for (pos = 0; pos < merge_names->len; pos = npos) {
1156 struct object_id oid;
1157 char *ptr;
1158 struct commit *commit;
1160 ptr = strchr(merge_names->buf + pos, '\n');
1161 if (ptr)
1162 npos = ptr - merge_names->buf + 1;
1163 else
1164 npos = merge_names->len;
1166 if (npos - pos < hexsz + 2 ||
1167 get_oid_hex(merge_names->buf + pos, &oid))
1168 commit = NULL; /* bad */
1169 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1170 continue; /* not-for-merge */
1171 else {
1172 char saved = merge_names->buf[pos + hexsz];
1173 merge_names->buf[pos + hexsz] = '\0';
1174 commit = get_merge_parent(merge_names->buf + pos);
1175 merge_names->buf[pos + hexsz] = saved;
1177 if (!commit) {
1178 if (ptr)
1179 *ptr = '\0';
1180 die(_("not something we can merge in %s: %s"),
1181 filename, merge_names->buf + pos);
1183 remotes = &commit_list_insert(commit, remotes)->next;
1186 if (merge_names == &fetch_head_file)
1187 strbuf_release(&fetch_head_file);
1190 static struct commit_list *collect_parents(struct commit *head_commit,
1191 int *head_subsumed,
1192 int argc, const char **argv,
1193 struct strbuf *merge_msg)
1195 int i;
1196 struct commit_list *remoteheads = NULL;
1197 struct commit_list **remotes = &remoteheads;
1198 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1200 if (merge_msg && (!have_message || shortlog_len))
1201 autogen = &merge_names;
1203 if (head_commit)
1204 remotes = &commit_list_insert(head_commit, remotes)->next;
1206 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1207 handle_fetch_head(remotes, autogen);
1208 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1209 } else {
1210 for (i = 0; i < argc; i++) {
1211 struct commit *commit = get_merge_parent(argv[i]);
1212 if (!commit)
1213 help_unknown_ref(argv[i], "merge",
1214 _("not something we can merge"));
1215 remotes = &commit_list_insert(commit, remotes)->next;
1217 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1218 if (autogen) {
1219 struct commit_list *p;
1220 for (p = remoteheads; p; p = p->next)
1221 merge_name(merge_remote_util(p->item)->name, autogen);
1225 if (autogen) {
1226 prepare_merge_message(autogen, merge_msg);
1227 strbuf_release(autogen);
1230 return remoteheads;
1233 static int merging_a_throwaway_tag(struct commit *commit)
1235 char *tag_ref;
1236 struct object_id oid;
1237 int is_throwaway_tag = 0;
1239 /* Are we merging a tag? */
1240 if (!merge_remote_util(commit) ||
1241 !merge_remote_util(commit)->obj ||
1242 merge_remote_util(commit)->obj->type != OBJ_TAG)
1243 return is_throwaway_tag;
1246 * Now we know we are merging a tag object. Are we downstream
1247 * and following the tags from upstream? If so, we must have
1248 * the tag object pointed at by "refs/tags/$T" where $T is the
1249 * tagname recorded in the tag object. We want to allow such
1250 * a "just to catch up" merge to fast-forward.
1252 * Otherwise, we are playing an integrator's role, making a
1253 * merge with a throw-away tag from a contributor with
1254 * something like "git pull $contributor $signed_tag".
1255 * We want to forbid such a merge from fast-forwarding
1256 * by default; otherwise we would not keep the signature
1257 * anywhere.
1259 tag_ref = xstrfmt("refs/tags/%s",
1260 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1261 if (!read_ref(tag_ref, &oid) &&
1262 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1263 is_throwaway_tag = 0;
1264 else
1265 is_throwaway_tag = 1;
1266 free(tag_ref);
1267 return is_throwaway_tag;
1270 int cmd_merge(int argc, const char **argv, const char *prefix)
1272 struct object_id result_tree, stash, head_oid;
1273 struct commit *head_commit;
1274 struct strbuf buf = STRBUF_INIT;
1275 int i, ret = 0, head_subsumed;
1276 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1277 struct commit_list *common = NULL;
1278 const char *best_strategy = NULL, *wt_strategy = NULL;
1279 struct commit_list *remoteheads = NULL, *p;
1280 void *branch_to_free;
1281 int orig_argc = argc;
1283 if (argc == 2 && !strcmp(argv[1], "-h"))
1284 usage_with_options(builtin_merge_usage, builtin_merge_options);
1286 prepare_repo_settings(the_repository);
1287 the_repository->settings.command_requires_full_index = 0;
1290 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1291 * current branch.
1293 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1294 if (branch)
1295 skip_prefix(branch, "refs/heads/", &branch);
1297 if (!pull_twohead) {
1298 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1299 if (default_strategy && !strcmp(default_strategy, "ort"))
1300 pull_twohead = "ort";
1303 init_diff_ui_defaults();
1304 git_config(git_merge_config, NULL);
1306 if (!branch || is_null_oid(&head_oid))
1307 head_commit = NULL;
1308 else
1309 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1311 if (branch_mergeoptions)
1312 parse_branch_merge_options(branch_mergeoptions);
1313 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1314 builtin_merge_usage, 0);
1315 if (shortlog_len < 0)
1316 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1318 if (verbosity < 0 && show_progress == -1)
1319 show_progress = 0;
1321 if (abort_current_merge) {
1322 int nargc = 2;
1323 const char *nargv[] = {"reset", "--merge", NULL};
1324 struct strbuf stash_oid = STRBUF_INIT;
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 (read_oneliner(&stash_oid, git_path_merge_autostash(the_repository),
1334 READ_ONELINER_SKIP_IF_EMPTY))
1335 unlink(git_path_merge_autostash(the_repository));
1337 /* Invoke 'git reset --merge' */
1338 ret = cmd_reset(nargc, nargv, prefix);
1340 if (stash_oid.len)
1341 apply_autostash_oid(stash_oid.buf);
1343 strbuf_release(&stash_oid);
1344 goto done;
1347 if (quit_current_merge) {
1348 if (orig_argc != 2)
1349 usage_msg_opt(_("--quit expects no arguments"),
1350 builtin_merge_usage,
1351 builtin_merge_options);
1353 remove_merge_branch_state(the_repository);
1354 goto done;
1357 if (continue_current_merge) {
1358 int nargc = 1;
1359 const char *nargv[] = {"commit", NULL};
1361 if (orig_argc != 2)
1362 usage_msg_opt(_("--continue expects no arguments"),
1363 builtin_merge_usage, builtin_merge_options);
1365 if (!file_exists(git_path_merge_head(the_repository)))
1366 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1368 /* Invoke 'git commit' */
1369 ret = cmd_commit(nargc, nargv, prefix);
1370 goto done;
1373 if (repo_read_index_unmerged(the_repository))
1374 die_resolve_conflict("merge");
1376 if (file_exists(git_path_merge_head(the_repository))) {
1378 * There is no unmerged entry, don't advise 'git
1379 * add/rm <file>', just 'git commit'.
1381 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1382 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1383 "Please, commit your changes before you merge."));
1384 else
1385 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1387 if (ref_exists("CHERRY_PICK_HEAD")) {
1388 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1389 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1390 "Please, commit your changes before you merge."));
1391 else
1392 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1394 resolve_undo_clear_index(&the_index);
1396 if (option_edit < 0)
1397 option_edit = default_edit_option();
1399 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1401 if (verbosity < 0)
1402 show_diffstat = 0;
1404 if (squash) {
1405 if (fast_forward == FF_NO)
1406 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1407 if (option_commit > 0)
1408 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1410 * squash can now silently disable option_commit - this is not
1411 * a problem as it is only overriding the default, not a user
1412 * supplied option.
1414 option_commit = 0;
1417 if (option_commit < 0)
1418 option_commit = 1;
1420 if (!argc) {
1421 if (default_to_upstream)
1422 argc = setup_with_upstream(&argv);
1423 else
1424 die(_("No commit specified and merge.defaultToUpstream not set."));
1425 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1426 argv[0] = "@{-1}";
1429 if (!argc)
1430 usage_with_options(builtin_merge_usage,
1431 builtin_merge_options);
1433 if (!head_commit) {
1435 * If the merged head is a valid one there is no reason
1436 * to forbid "git merge" into a branch yet to be born.
1437 * We do the same for "git pull".
1439 struct object_id *remote_head_oid;
1440 if (squash)
1441 die(_("Squash commit into empty head not supported yet"));
1442 if (fast_forward == FF_NO)
1443 die(_("Non-fast-forward commit does not make sense into "
1444 "an empty head"));
1445 remoteheads = collect_parents(head_commit, &head_subsumed,
1446 argc, argv, NULL);
1447 if (!remoteheads)
1448 die(_("%s - not something we can merge"), argv[0]);
1449 if (remoteheads->next)
1450 die(_("Can merge only exactly one commit into empty head"));
1452 if (verify_signatures)
1453 verify_merge_signature(remoteheads->item, verbosity,
1454 check_trust_level);
1456 remote_head_oid = &remoteheads->item->object.oid;
1457 read_empty(remote_head_oid);
1458 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1459 UPDATE_REFS_DIE_ON_ERR);
1460 goto done;
1464 * All the rest are the commits being merged; prepare
1465 * the standard merge summary message to be appended
1466 * to the given message.
1468 remoteheads = collect_parents(head_commit, &head_subsumed,
1469 argc, argv, &merge_msg);
1471 if (!head_commit || !argc)
1472 usage_with_options(builtin_merge_usage,
1473 builtin_merge_options);
1475 if (verify_signatures) {
1476 for (p = remoteheads; p; p = p->next) {
1477 verify_merge_signature(p->item, verbosity,
1478 check_trust_level);
1482 strbuf_addstr(&buf, "merge");
1483 for (p = remoteheads; p; p = p->next)
1484 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1485 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1486 strbuf_reset(&buf);
1488 for (p = remoteheads; p; p = p->next) {
1489 struct commit *commit = p->item;
1490 strbuf_addf(&buf, "GITHEAD_%s",
1491 oid_to_hex(&commit->object.oid));
1492 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1493 strbuf_reset(&buf);
1494 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1495 fast_forward = FF_NO;
1498 if (!use_strategies && !pull_twohead &&
1499 remoteheads && !remoteheads->next) {
1500 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1501 if (default_strategy)
1502 append_strategy(get_strategy(default_strategy));
1504 if (!use_strategies) {
1505 if (!remoteheads)
1506 ; /* already up-to-date */
1507 else if (!remoteheads->next)
1508 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1509 else
1510 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1513 for (i = 0; i < use_strategies_nr; i++) {
1514 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1515 fast_forward = FF_NO;
1516 if (use_strategies[i]->attr & NO_TRIVIAL)
1517 allow_trivial = 0;
1520 if (!remoteheads)
1521 ; /* already up-to-date */
1522 else if (!remoteheads->next)
1523 common = repo_get_merge_bases(the_repository, head_commit,
1524 remoteheads->item);
1525 else {
1526 struct commit_list *list = remoteheads;
1527 commit_list_insert(head_commit, &list);
1528 common = get_octopus_merge_bases(list);
1529 free(list);
1532 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1533 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1535 if (remoteheads && !common) {
1536 /* No common ancestors found. */
1537 if (!allow_unrelated_histories)
1538 die(_("refusing to merge unrelated histories"));
1539 /* otherwise, we need a real merge. */
1540 } else if (!remoteheads ||
1541 (!remoteheads->next && !common->next &&
1542 common->item == remoteheads->item)) {
1544 * If head can reach all the merge then we are up to date.
1545 * but first the most common case of merging one remote.
1547 finish_up_to_date();
1548 goto done;
1549 } else if (fast_forward != FF_NO && !remoteheads->next &&
1550 !common->next &&
1551 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1552 /* Again the most common case of merging one remote. */
1553 const char *msg = have_message ?
1554 "Fast-forward (no commit created; -m option ignored)" :
1555 "Fast-forward";
1556 struct commit *commit;
1558 if (verbosity >= 0) {
1559 printf(_("Updating %s..%s\n"),
1560 repo_find_unique_abbrev(the_repository, &head_commit->object.oid,
1561 DEFAULT_ABBREV),
1562 repo_find_unique_abbrev(the_repository, &remoteheads->item->object.oid,
1563 DEFAULT_ABBREV));
1565 commit = remoteheads->item;
1566 if (!commit) {
1567 ret = 1;
1568 goto done;
1571 if (autostash)
1572 create_autostash(the_repository,
1573 git_path_merge_autostash(the_repository));
1574 if (checkout_fast_forward(the_repository,
1575 &head_commit->object.oid,
1576 &commit->object.oid,
1577 overwrite_ignore)) {
1578 apply_autostash(git_path_merge_autostash(the_repository));
1579 ret = 1;
1580 goto done;
1583 finish(head_commit, remoteheads, &commit->object.oid, msg);
1584 remove_merge_branch_state(the_repository);
1585 goto done;
1586 } else if (!remoteheads->next && common->next)
1589 * We are not doing octopus and not fast-forward. Need
1590 * a real merge.
1592 else if (!remoteheads->next && !common->next && option_commit) {
1594 * We are not doing octopus, not fast-forward, and have
1595 * only one common.
1597 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
1598 if (allow_trivial && fast_forward != FF_ONLY) {
1600 * Must first ensure that index matches HEAD before
1601 * attempting a trivial merge.
1603 struct tree *head_tree = repo_get_commit_tree(the_repository,
1604 head_commit);
1605 struct strbuf sb = STRBUF_INIT;
1607 if (repo_index_has_changes(the_repository, head_tree,
1608 &sb)) {
1609 error(_("Your local changes to the following files would be overwritten by merge:\n %s"),
1610 sb.buf);
1611 strbuf_release(&sb);
1612 ret = 2;
1613 goto done;
1616 /* See if it is really trivial. */
1617 git_committer_info(IDENT_STRICT);
1618 printf(_("Trying really trivial in-index merge...\n"));
1619 if (!read_tree_trivial(&common->item->object.oid,
1620 &head_commit->object.oid,
1621 &remoteheads->item->object.oid)) {
1622 ret = merge_trivial(head_commit, remoteheads);
1623 goto done;
1625 printf(_("Nope.\n"));
1627 } else {
1629 * An octopus. If we can reach all the remote we are up
1630 * to date.
1632 int up_to_date = 1;
1633 struct commit_list *j;
1635 for (j = remoteheads; j; j = j->next) {
1636 struct commit_list *common_one;
1639 * Here we *have* to calculate the individual
1640 * merge_bases again, otherwise "git merge HEAD^
1641 * HEAD^^" would be missed.
1643 common_one = repo_get_merge_bases(the_repository,
1644 head_commit,
1645 j->item);
1646 if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1647 up_to_date = 0;
1648 break;
1651 if (up_to_date) {
1652 finish_up_to_date();
1653 goto done;
1657 if (fast_forward == FF_ONLY)
1658 die_ff_impossible();
1660 if (autostash)
1661 create_autostash(the_repository,
1662 git_path_merge_autostash(the_repository));
1664 /* We are going to make a new commit. */
1665 git_committer_info(IDENT_STRICT);
1668 * At this point, we need a real merge. No matter what strategy
1669 * we use, it would operate on the index, possibly affecting the
1670 * working tree, and when resolved cleanly, have the desired
1671 * tree in the index -- this means that the index must be in
1672 * sync with the head commit. The strategies are responsible
1673 * to ensure this.
1675 * Stash away the local changes so that we can try more than one
1676 * and/or recover from merge strategies bailing while leaving the
1677 * index and working tree polluted.
1679 if (save_state(&stash))
1680 oidclr(&stash);
1682 for (i = 0; i < use_strategies_nr; i++) {
1683 int ret, cnt;
1684 if (i) {
1685 printf(_("Rewinding the tree to pristine...\n"));
1686 restore_state(&head_commit->object.oid, &stash);
1688 if (use_strategies_nr != 1)
1689 printf(_("Trying merge strategy %s...\n"),
1690 use_strategies[i]->name);
1692 * Remember which strategy left the state in the working
1693 * tree.
1695 wt_strategy = use_strategies[i]->name;
1697 ret = try_merge_strategy(wt_strategy,
1698 common, remoteheads,
1699 head_commit);
1701 * The backend exits with 1 when conflicts are
1702 * left to be resolved, with 2 when it does not
1703 * handle the given merge at all.
1705 if (ret < 2) {
1706 if (!ret) {
1708 * This strategy worked; no point in trying
1709 * another.
1711 merge_was_ok = 1;
1712 best_strategy = wt_strategy;
1713 break;
1715 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1716 if (best_cnt <= 0 || cnt <= best_cnt) {
1717 best_strategy = wt_strategy;
1718 best_cnt = cnt;
1724 * If we have a resulting tree, that means the strategy module
1725 * auto resolved the merge cleanly.
1727 if (merge_was_ok && option_commit) {
1728 automerge_was_ok = 1;
1729 ret = finish_automerge(head_commit, head_subsumed,
1730 common, remoteheads,
1731 &result_tree, wt_strategy);
1732 goto done;
1736 * Pick the result from the best strategy and have the user fix
1737 * it up.
1739 if (!best_strategy) {
1740 restore_state(&head_commit->object.oid, &stash);
1741 if (use_strategies_nr > 1)
1742 fprintf(stderr,
1743 _("No merge strategy handled the merge.\n"));
1744 else
1745 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1746 use_strategies[0]->name);
1747 apply_autostash(git_path_merge_autostash(the_repository));
1748 ret = 2;
1749 goto done;
1750 } else if (best_strategy == wt_strategy)
1751 ; /* We already have its result in the working tree. */
1752 else {
1753 printf(_("Rewinding the tree to pristine...\n"));
1754 restore_state(&head_commit->object.oid, &stash);
1755 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1756 best_strategy);
1757 try_merge_strategy(best_strategy, common, remoteheads,
1758 head_commit);
1761 if (squash) {
1762 finish(head_commit, remoteheads, NULL, NULL);
1764 git_test_write_commit_graph_or_die();
1765 } else
1766 write_merge_state(remoteheads);
1768 if (merge_was_ok)
1769 fprintf(stderr, _("Automatic merge went well; "
1770 "stopped before committing as requested\n"));
1771 else
1772 ret = suggest_conflicts();
1773 if (autostash)
1774 printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1776 done:
1777 if (!automerge_was_ok) {
1778 free_commit_list(common);
1779 free_commit_list(remoteheads);
1781 strbuf_release(&buf);
1782 free(branch_to_free);
1783 discard_index(&the_index);
1784 return ret;