gc: add `gc.repackFilter` config option
[git.git] / builtin / merge.c
blob545da0c8a1106f76b44b363ee4feefc2f5a573eb
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_graph_width = -1; /* respect statGraphWidth config */
471 opts.output_format |=
472 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
473 opts.detect_rename = DIFF_DETECT_RENAME;
474 diff_setup_done(&opts);
475 diff_tree_oid(head, new_head, "", &opts);
476 diffcore_std(&opts);
477 diff_flush(&opts);
480 /* Run a post-merge hook */
481 run_hooks_l("post-merge", squash ? "1" : "0", NULL);
483 if (new_head)
484 apply_autostash(git_path_merge_autostash(the_repository));
485 strbuf_release(&reflog_message);
488 /* Get the name for the merge commit's message. */
489 static void merge_name(const char *remote, struct strbuf *msg)
491 struct commit *remote_head;
492 struct object_id branch_head;
493 struct strbuf bname = STRBUF_INIT;
494 struct merge_remote_desc *desc;
495 const char *ptr;
496 char *found_ref = NULL;
497 int len, early;
499 strbuf_branchname(&bname, remote, 0);
500 remote = bname.buf;
502 oidclr(&branch_head);
503 remote_head = get_merge_parent(remote);
504 if (!remote_head)
505 die(_("'%s' does not point to a commit"), remote);
507 if (repo_dwim_ref(the_repository, remote, strlen(remote), &branch_head,
508 &found_ref, 0) > 0) {
509 if (starts_with(found_ref, "refs/heads/")) {
510 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
511 oid_to_hex(&branch_head), remote);
512 goto cleanup;
514 if (starts_with(found_ref, "refs/tags/")) {
515 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
516 oid_to_hex(&branch_head), remote);
517 goto cleanup;
519 if (starts_with(found_ref, "refs/remotes/")) {
520 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
521 oid_to_hex(&branch_head), remote);
522 goto cleanup;
526 /* See if remote matches <name>^^^.. or <name>~<number> */
527 for (len = 0, ptr = remote + strlen(remote);
528 remote < ptr && ptr[-1] == '^';
529 ptr--)
530 len++;
531 if (len)
532 early = 1;
533 else {
534 early = 0;
535 ptr = strrchr(remote, '~');
536 if (ptr) {
537 int seen_nonzero = 0;
539 len++; /* count ~ */
540 while (*++ptr && isdigit(*ptr)) {
541 seen_nonzero |= (*ptr != '0');
542 len++;
544 if (*ptr)
545 len = 0; /* not ...~<number> */
546 else if (seen_nonzero)
547 early = 1;
548 else if (len == 1)
549 early = 1; /* "name~" is "name~1"! */
552 if (len) {
553 struct strbuf truname = STRBUF_INIT;
554 strbuf_addf(&truname, "refs/heads/%s", remote);
555 strbuf_setlen(&truname, truname.len - len);
556 if (ref_exists(truname.buf)) {
557 strbuf_addf(msg,
558 "%s\t\tbranch '%s'%s of .\n",
559 oid_to_hex(&remote_head->object.oid),
560 truname.buf + 11,
561 (early ? " (early part)" : ""));
562 strbuf_release(&truname);
563 goto cleanup;
565 strbuf_release(&truname);
568 desc = merge_remote_util(remote_head);
569 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
570 strbuf_addf(msg, "%s\t\t%s '%s'\n",
571 oid_to_hex(&desc->obj->oid),
572 type_name(desc->obj->type),
573 remote);
574 goto cleanup;
577 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
578 oid_to_hex(&remote_head->object.oid), remote);
579 cleanup:
580 free(found_ref);
581 strbuf_release(&bname);
584 static void parse_branch_merge_options(char *bmo)
586 const char **argv;
587 int argc;
589 if (!bmo)
590 return;
591 argc = split_cmdline(bmo, &argv);
592 if (argc < 0)
593 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
594 _(split_cmdline_strerror(argc)));
595 REALLOC_ARRAY(argv, argc + 2);
596 MOVE_ARRAY(argv + 1, argv, argc + 1);
597 argc++;
598 argv[0] = "branch.*.mergeoptions";
599 parse_options(argc, argv, NULL, builtin_merge_options,
600 builtin_merge_usage, 0);
601 free(argv);
604 static int git_merge_config(const char *k, const char *v,
605 const struct config_context *ctx, void *cb)
607 int status;
608 const char *str;
610 if (branch &&
611 skip_prefix(k, "branch.", &str) &&
612 skip_prefix(str, branch, &str) &&
613 !strcmp(str, ".mergeoptions")) {
614 free(branch_mergeoptions);
615 branch_mergeoptions = xstrdup(v);
616 return 0;
619 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
620 show_diffstat = git_config_bool(k, v);
621 else if (!strcmp(k, "merge.verifysignatures"))
622 verify_signatures = git_config_bool(k, v);
623 else if (!strcmp(k, "pull.twohead"))
624 return git_config_string(&pull_twohead, k, v);
625 else if (!strcmp(k, "pull.octopus"))
626 return git_config_string(&pull_octopus, k, v);
627 else if (!strcmp(k, "commit.cleanup"))
628 return git_config_string(&cleanup_arg, k, v);
629 else if (!strcmp(k, "merge.ff")) {
630 int boolval = git_parse_maybe_bool(v);
631 if (0 <= boolval) {
632 fast_forward = boolval ? FF_ALLOW : FF_NO;
633 } else if (v && !strcmp(v, "only")) {
634 fast_forward = FF_ONLY;
635 } /* do not barf on values from future versions of git */
636 return 0;
637 } else if (!strcmp(k, "merge.defaulttoupstream")) {
638 default_to_upstream = git_config_bool(k, v);
639 return 0;
640 } else if (!strcmp(k, "commit.gpgsign")) {
641 sign_commit = git_config_bool(k, v) ? "" : NULL;
642 return 0;
643 } else if (!strcmp(k, "gpg.mintrustlevel")) {
644 check_trust_level = 0;
645 } else if (!strcmp(k, "merge.autostash")) {
646 autostash = git_config_bool(k, v);
647 return 0;
650 status = fmt_merge_msg_config(k, v, ctx, cb);
651 if (status)
652 return status;
653 return git_diff_ui_config(k, v, ctx, cb);
656 static int read_tree_trivial(struct object_id *common, struct object_id *head,
657 struct object_id *one)
659 int i, nr_trees = 0;
660 struct tree *trees[MAX_UNPACK_TREES];
661 struct tree_desc t[MAX_UNPACK_TREES];
662 struct unpack_trees_options opts;
664 memset(&opts, 0, sizeof(opts));
665 opts.head_idx = 2;
666 opts.src_index = &the_index;
667 opts.dst_index = &the_index;
668 opts.update = 1;
669 opts.verbose_update = 1;
670 opts.trivial_merges_only = 1;
671 opts.merge = 1;
672 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
673 trees[nr_trees] = parse_tree_indirect(common);
674 if (!trees[nr_trees++])
675 return -1;
676 trees[nr_trees] = parse_tree_indirect(head);
677 if (!trees[nr_trees++])
678 return -1;
679 trees[nr_trees] = parse_tree_indirect(one);
680 if (!trees[nr_trees++])
681 return -1;
682 opts.fn = threeway_merge;
683 cache_tree_free(&the_index.cache_tree);
684 for (i = 0; i < nr_trees; i++) {
685 parse_tree(trees[i]);
686 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
688 if (unpack_trees(nr_trees, t, &opts))
689 return -1;
690 return 0;
693 static void write_tree_trivial(struct object_id *oid)
695 if (write_index_as_tree(oid, &the_index, get_index_file(), 0, NULL))
696 die(_("git write-tree failed to write a tree"));
699 static int try_merge_strategy(const char *strategy, struct commit_list *common,
700 struct commit_list *remoteheads,
701 struct commit *head)
703 const char *head_arg = "HEAD";
705 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
706 SKIP_IF_UNCHANGED, 0, NULL, NULL,
707 NULL) < 0)
708 return error(_("Unable to write index."));
710 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
711 !strcmp(strategy, "ort")) {
712 struct lock_file lock = LOCK_INIT;
713 int clean, x;
714 struct commit *result;
715 struct commit_list *reversed = NULL;
716 struct merge_options o;
717 struct commit_list *j;
719 if (remoteheads->next) {
720 error(_("Not handling anything other than two heads merge."));
721 return 2;
724 init_merge_options(&o, the_repository);
725 if (!strcmp(strategy, "subtree"))
726 o.subtree_shift = "";
728 o.show_rename_progress =
729 show_progress == -1 ? isatty(2) : show_progress;
731 for (x = 0; x < xopts.nr; x++)
732 if (parse_merge_opt(&o, xopts.v[x]))
733 die(_("unknown strategy option: -X%s"), xopts.v[x]);
735 o.branch1 = head_arg;
736 o.branch2 = merge_remote_util(remoteheads->item)->name;
738 for (j = common; j; j = j->next)
739 commit_list_insert(j->item, &reversed);
741 repo_hold_locked_index(the_repository, &lock,
742 LOCK_DIE_ON_ERROR);
743 if (!strcmp(strategy, "ort"))
744 clean = merge_ort_recursive(&o, head, remoteheads->item,
745 reversed, &result);
746 else
747 clean = merge_recursive(&o, head, remoteheads->item,
748 reversed, &result);
749 if (clean < 0) {
750 rollback_lock_file(&lock);
751 return 2;
753 if (write_locked_index(&the_index, &lock,
754 COMMIT_LOCK | SKIP_IF_UNCHANGED))
755 die(_("unable to write %s"), get_index_file());
756 return clean ? 0 : 1;
757 } else {
758 return try_merge_command(the_repository,
759 strategy, xopts.nr, xopts.v,
760 common, head_arg, remoteheads);
764 static void count_diff_files(struct diff_queue_struct *q,
765 struct diff_options *opt UNUSED, void *data)
767 int *count = data;
769 (*count) += q->nr;
772 static int count_unmerged_entries(void)
774 int i, ret = 0;
776 for (i = 0; i < the_index.cache_nr; i++)
777 if (ce_stage(the_index.cache[i]))
778 ret++;
780 return ret;
783 static void add_strategies(const char *string, unsigned attr)
785 int i;
787 if (string) {
788 struct string_list list = STRING_LIST_INIT_DUP;
789 struct string_list_item *item;
790 string_list_split(&list, string, ' ', -1);
791 for_each_string_list_item(item, &list)
792 append_strategy(get_strategy(item->string));
793 string_list_clear(&list, 0);
794 return;
796 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
797 if (all_strategy[i].attr & attr)
798 append_strategy(&all_strategy[i]);
802 static void read_merge_msg(struct strbuf *msg)
804 const char *filename = git_path_merge_msg(the_repository);
805 strbuf_reset(msg);
806 if (strbuf_read_file(msg, filename, 0) < 0)
807 die_errno(_("Could not read from '%s'"), filename);
810 static void write_merge_state(struct commit_list *);
811 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
813 if (err_msg)
814 error("%s", err_msg);
815 fprintf(stderr,
816 _("Not committing merge; use 'git commit' to complete the merge.\n"));
817 write_merge_state(remoteheads);
818 exit(1);
821 static const char merge_editor_comment[] =
822 N_("Please enter a commit message to explain why this merge is necessary,\n"
823 "especially if it merges an updated upstream into a topic branch.\n"
824 "\n");
826 static const char scissors_editor_comment[] =
827 N_("An empty message aborts the commit.\n");
829 static const char no_scissors_editor_comment[] =
830 N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
831 "the commit.\n");
833 static void write_merge_heads(struct commit_list *);
834 static void prepare_to_commit(struct commit_list *remoteheads)
836 struct strbuf msg = STRBUF_INIT;
837 const char *index_file = get_index_file();
839 if (!no_verify) {
840 int invoked_hook;
842 if (run_commit_hook(0 < option_edit, index_file, &invoked_hook,
843 "pre-merge-commit", NULL))
844 abort_commit(remoteheads, NULL);
846 * Re-read the index as pre-merge-commit hook could have updated it,
847 * and write it out as a tree. We must do this before we invoke
848 * the editor and after we invoke run_status above.
850 if (invoked_hook)
851 discard_index(&the_index);
853 read_index_from(&the_index, index_file, get_git_dir());
854 strbuf_addbuf(&msg, &merge_msg);
855 if (squash)
856 BUG("the control must not reach here under --squash");
857 if (0 < option_edit) {
858 strbuf_addch(&msg, '\n');
859 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
860 wt_status_append_cut_line(&msg);
861 strbuf_commented_addf(&msg, comment_line_char, "\n");
863 strbuf_commented_addf(&msg, comment_line_char,
864 _(merge_editor_comment));
865 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
866 strbuf_commented_addf(&msg, comment_line_char,
867 _(scissors_editor_comment));
868 else
869 strbuf_commented_addf(&msg, comment_line_char,
870 _(no_scissors_editor_comment), comment_line_char);
872 if (signoff)
873 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
874 write_merge_heads(remoteheads);
875 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
876 if (run_commit_hook(0 < option_edit, get_index_file(), NULL,
877 "prepare-commit-msg",
878 git_path_merge_msg(the_repository), "merge", NULL))
879 abort_commit(remoteheads, NULL);
880 if (0 < option_edit) {
881 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
882 abort_commit(remoteheads, NULL);
885 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
886 NULL, "commit-msg",
887 git_path_merge_msg(the_repository), NULL))
888 abort_commit(remoteheads, NULL);
890 read_merge_msg(&msg);
891 cleanup_message(&msg, cleanup_mode, 0);
892 if (!msg.len)
893 abort_commit(remoteheads, _("Empty commit message."));
894 strbuf_release(&merge_msg);
895 strbuf_addbuf(&merge_msg, &msg);
896 strbuf_release(&msg);
899 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
901 struct object_id result_tree, result_commit;
902 struct commit_list *parents, **pptr = &parents;
904 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
905 SKIP_IF_UNCHANGED, 0, NULL, NULL,
906 NULL) < 0)
907 return error(_("Unable to write index."));
909 write_tree_trivial(&result_tree);
910 printf(_("Wonderful.\n"));
911 pptr = commit_list_append(head, pptr);
912 pptr = commit_list_append(remoteheads->item, pptr);
913 prepare_to_commit(remoteheads);
914 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
915 &result_commit, NULL, sign_commit))
916 die(_("failed to write commit object"));
917 finish(head, remoteheads, &result_commit, "In-index merge");
918 remove_merge_branch_state(the_repository);
919 return 0;
922 static int finish_automerge(struct commit *head,
923 int head_subsumed,
924 struct commit_list *common,
925 struct commit_list *remoteheads,
926 struct object_id *result_tree,
927 const char *wt_strategy)
929 struct commit_list *parents = NULL;
930 struct strbuf buf = STRBUF_INIT;
931 struct object_id result_commit;
933 write_tree_trivial(result_tree);
934 free_commit_list(common);
935 parents = remoteheads;
936 if (!head_subsumed || fast_forward == FF_NO)
937 commit_list_insert(head, &parents);
938 prepare_to_commit(remoteheads);
939 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
940 &result_commit, NULL, sign_commit))
941 die(_("failed to write commit object"));
942 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
943 finish(head, remoteheads, &result_commit, buf.buf);
944 strbuf_release(&buf);
945 remove_merge_branch_state(the_repository);
946 return 0;
949 static int suggest_conflicts(void)
951 const char *filename;
952 FILE *fp;
953 struct strbuf msgbuf = STRBUF_INIT;
955 filename = git_path_merge_msg(the_repository);
956 fp = xfopen(filename, "a");
959 * We can't use cleanup_mode because if we're not using the editor,
960 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
961 * though the message is meant to be processed later by git-commit.
962 * Thus, we will get the cleanup mode which is returned when we _are_
963 * using an editor.
965 append_conflicts_hint(&the_index, &msgbuf,
966 get_cleanup_mode(cleanup_arg, 1));
967 fputs(msgbuf.buf, fp);
968 strbuf_release(&msgbuf);
969 fclose(fp);
970 repo_rerere(the_repository, allow_rerere_auto);
971 printf(_("Automatic merge failed; "
972 "fix conflicts and then commit the result.\n"));
973 return 1;
976 static int evaluate_result(void)
978 int cnt = 0;
979 struct rev_info rev;
981 /* Check how many files differ. */
982 repo_init_revisions(the_repository, &rev, "");
983 setup_revisions(0, NULL, &rev, NULL);
984 rev.diffopt.output_format |=
985 DIFF_FORMAT_CALLBACK;
986 rev.diffopt.format_callback = count_diff_files;
987 rev.diffopt.format_callback_data = &cnt;
988 run_diff_files(&rev, 0);
991 * Check how many unmerged entries are
992 * there.
994 cnt += count_unmerged_entries();
996 release_revisions(&rev);
997 return cnt;
1001 * Pretend as if the user told us to merge with the remote-tracking
1002 * branch we have for the upstream of the current branch
1004 static int setup_with_upstream(const char ***argv)
1006 struct branch *branch = branch_get(NULL);
1007 int i;
1008 const char **args;
1010 if (!branch)
1011 die(_("No current branch."));
1012 if (!branch->remote_name)
1013 die(_("No remote for the current branch."));
1014 if (!branch->merge_nr)
1015 die(_("No default upstream defined for the current branch."));
1017 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1018 for (i = 0; i < branch->merge_nr; i++) {
1019 if (!branch->merge[i]->dst)
1020 die(_("No remote-tracking branch for %s from %s"),
1021 branch->merge[i]->src, branch->remote_name);
1022 args[i] = branch->merge[i]->dst;
1024 args[i] = NULL;
1025 *argv = args;
1026 return i;
1029 static void write_merge_heads(struct commit_list *remoteheads)
1031 struct commit_list *j;
1032 struct strbuf buf = STRBUF_INIT;
1034 for (j = remoteheads; j; j = j->next) {
1035 struct object_id *oid;
1036 struct commit *c = j->item;
1037 struct merge_remote_desc *desc;
1039 desc = merge_remote_util(c);
1040 if (desc && desc->obj) {
1041 oid = &desc->obj->oid;
1042 } else {
1043 oid = &c->object.oid;
1045 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1047 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1049 strbuf_reset(&buf);
1050 if (fast_forward == FF_NO)
1051 strbuf_addstr(&buf, "no-ff");
1052 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1053 strbuf_release(&buf);
1056 static void write_merge_state(struct commit_list *remoteheads)
1058 write_merge_heads(remoteheads);
1059 strbuf_addch(&merge_msg, '\n');
1060 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1061 merge_msg.len);
1064 static int default_edit_option(void)
1066 static const char name[] = "GIT_MERGE_AUTOEDIT";
1067 const char *e = getenv(name);
1068 struct stat st_stdin, st_stdout;
1070 if (have_message)
1071 /* an explicit -m msg without --[no-]edit */
1072 return 0;
1074 if (e) {
1075 int v = git_parse_maybe_bool(e);
1076 if (v < 0)
1077 die(_("Bad value '%s' in environment '%s'"), e, name);
1078 return v;
1081 /* Use editor if stdin and stdout are the same and is a tty */
1082 return (!fstat(0, &st_stdin) &&
1083 !fstat(1, &st_stdout) &&
1084 isatty(0) && isatty(1) &&
1085 st_stdin.st_dev == st_stdout.st_dev &&
1086 st_stdin.st_ino == st_stdout.st_ino &&
1087 st_stdin.st_mode == st_stdout.st_mode);
1090 static struct commit_list *reduce_parents(struct commit *head_commit,
1091 int *head_subsumed,
1092 struct commit_list *remoteheads)
1094 struct commit_list *parents, **remotes;
1097 * Is the current HEAD reachable from another commit being
1098 * merged? If so we do not want to record it as a parent of
1099 * the resulting merge, unless --no-ff is given. We will flip
1100 * this variable to 0 when we find HEAD among the independent
1101 * tips being merged.
1103 *head_subsumed = 1;
1105 /* Find what parents to record by checking independent ones. */
1106 parents = reduce_heads(remoteheads);
1107 free_commit_list(remoteheads);
1109 remoteheads = NULL;
1110 remotes = &remoteheads;
1111 while (parents) {
1112 struct commit *commit = pop_commit(&parents);
1113 if (commit == head_commit)
1114 *head_subsumed = 0;
1115 else
1116 remotes = &commit_list_insert(commit, remotes)->next;
1118 return remoteheads;
1121 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1123 struct fmt_merge_msg_opts opts;
1125 memset(&opts, 0, sizeof(opts));
1126 opts.add_title = !have_message;
1127 opts.shortlog_len = shortlog_len;
1128 opts.credit_people = (0 < option_edit);
1129 opts.into_name = into_name;
1131 fmt_merge_msg(merge_names, merge_msg, &opts);
1132 if (merge_msg->len)
1133 strbuf_setlen(merge_msg, merge_msg->len - 1);
1136 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1138 const char *filename;
1139 int fd, pos, npos;
1140 struct strbuf fetch_head_file = STRBUF_INIT;
1141 const unsigned hexsz = the_hash_algo->hexsz;
1143 if (!merge_names)
1144 merge_names = &fetch_head_file;
1146 filename = git_path_fetch_head(the_repository);
1147 fd = xopen(filename, O_RDONLY);
1149 if (strbuf_read(merge_names, fd, 0) < 0)
1150 die_errno(_("could not read '%s'"), filename);
1151 if (close(fd) < 0)
1152 die_errno(_("could not close '%s'"), filename);
1154 for (pos = 0; pos < merge_names->len; pos = npos) {
1155 struct object_id oid;
1156 char *ptr;
1157 struct commit *commit;
1159 ptr = strchr(merge_names->buf + pos, '\n');
1160 if (ptr)
1161 npos = ptr - merge_names->buf + 1;
1162 else
1163 npos = merge_names->len;
1165 if (npos - pos < hexsz + 2 ||
1166 get_oid_hex(merge_names->buf + pos, &oid))
1167 commit = NULL; /* bad */
1168 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1169 continue; /* not-for-merge */
1170 else {
1171 char saved = merge_names->buf[pos + hexsz];
1172 merge_names->buf[pos + hexsz] = '\0';
1173 commit = get_merge_parent(merge_names->buf + pos);
1174 merge_names->buf[pos + hexsz] = saved;
1176 if (!commit) {
1177 if (ptr)
1178 *ptr = '\0';
1179 die(_("not something we can merge in %s: %s"),
1180 filename, merge_names->buf + pos);
1182 remotes = &commit_list_insert(commit, remotes)->next;
1185 if (merge_names == &fetch_head_file)
1186 strbuf_release(&fetch_head_file);
1189 static struct commit_list *collect_parents(struct commit *head_commit,
1190 int *head_subsumed,
1191 int argc, const char **argv,
1192 struct strbuf *merge_msg)
1194 int i;
1195 struct commit_list *remoteheads = NULL;
1196 struct commit_list **remotes = &remoteheads;
1197 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1199 if (merge_msg && (!have_message || shortlog_len))
1200 autogen = &merge_names;
1202 if (head_commit)
1203 remotes = &commit_list_insert(head_commit, remotes)->next;
1205 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1206 handle_fetch_head(remotes, autogen);
1207 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1208 } else {
1209 for (i = 0; i < argc; i++) {
1210 struct commit *commit = get_merge_parent(argv[i]);
1211 if (!commit)
1212 help_unknown_ref(argv[i], "merge",
1213 _("not something we can merge"));
1214 remotes = &commit_list_insert(commit, remotes)->next;
1216 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1217 if (autogen) {
1218 struct commit_list *p;
1219 for (p = remoteheads; p; p = p->next)
1220 merge_name(merge_remote_util(p->item)->name, autogen);
1224 if (autogen) {
1225 prepare_merge_message(autogen, merge_msg);
1226 strbuf_release(autogen);
1229 return remoteheads;
1232 static int merging_a_throwaway_tag(struct commit *commit)
1234 char *tag_ref;
1235 struct object_id oid;
1236 int is_throwaway_tag = 0;
1238 /* Are we merging a tag? */
1239 if (!merge_remote_util(commit) ||
1240 !merge_remote_util(commit)->obj ||
1241 merge_remote_util(commit)->obj->type != OBJ_TAG)
1242 return is_throwaway_tag;
1245 * Now we know we are merging a tag object. Are we downstream
1246 * and following the tags from upstream? If so, we must have
1247 * the tag object pointed at by "refs/tags/$T" where $T is the
1248 * tagname recorded in the tag object. We want to allow such
1249 * a "just to catch up" merge to fast-forward.
1251 * Otherwise, we are playing an integrator's role, making a
1252 * merge with a throw-away tag from a contributor with
1253 * something like "git pull $contributor $signed_tag".
1254 * We want to forbid such a merge from fast-forwarding
1255 * by default; otherwise we would not keep the signature
1256 * anywhere.
1258 tag_ref = xstrfmt("refs/tags/%s",
1259 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1260 if (!read_ref(tag_ref, &oid) &&
1261 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1262 is_throwaway_tag = 0;
1263 else
1264 is_throwaway_tag = 1;
1265 free(tag_ref);
1266 return is_throwaway_tag;
1269 int cmd_merge(int argc, const char **argv, const char *prefix)
1271 struct object_id result_tree, stash, head_oid;
1272 struct commit *head_commit;
1273 struct strbuf buf = STRBUF_INIT;
1274 int i, ret = 0, head_subsumed;
1275 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1276 struct commit_list *common = NULL;
1277 const char *best_strategy = NULL, *wt_strategy = NULL;
1278 struct commit_list *remoteheads = NULL, *p;
1279 void *branch_to_free;
1280 int orig_argc = argc;
1282 if (argc == 2 && !strcmp(argv[1], "-h"))
1283 usage_with_options(builtin_merge_usage, builtin_merge_options);
1285 prepare_repo_settings(the_repository);
1286 the_repository->settings.command_requires_full_index = 0;
1289 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1290 * current branch.
1292 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, 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 = "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 struct strbuf stash_oid = STRBUF_INIT;
1325 if (orig_argc != 2)
1326 usage_msg_opt(_("--abort expects no arguments"),
1327 builtin_merge_usage, builtin_merge_options);
1329 if (!file_exists(git_path_merge_head(the_repository)))
1330 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1332 if (read_oneliner(&stash_oid, git_path_merge_autostash(the_repository),
1333 READ_ONELINER_SKIP_IF_EMPTY))
1334 unlink(git_path_merge_autostash(the_repository));
1336 /* Invoke 'git reset --merge' */
1337 ret = cmd_reset(nargc, nargv, prefix);
1339 if (stash_oid.len)
1340 apply_autostash_oid(stash_oid.buf);
1342 strbuf_release(&stash_oid);
1343 goto done;
1346 if (quit_current_merge) {
1347 if (orig_argc != 2)
1348 usage_msg_opt(_("--quit expects no arguments"),
1349 builtin_merge_usage,
1350 builtin_merge_options);
1352 remove_merge_branch_state(the_repository);
1353 goto done;
1356 if (continue_current_merge) {
1357 int nargc = 1;
1358 const char *nargv[] = {"commit", NULL};
1360 if (orig_argc != 2)
1361 usage_msg_opt(_("--continue expects no arguments"),
1362 builtin_merge_usage, builtin_merge_options);
1364 if (!file_exists(git_path_merge_head(the_repository)))
1365 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1367 /* Invoke 'git commit' */
1368 ret = cmd_commit(nargc, nargv, prefix);
1369 goto done;
1372 if (repo_read_index_unmerged(the_repository))
1373 die_resolve_conflict("merge");
1375 if (file_exists(git_path_merge_head(the_repository))) {
1377 * There is no unmerged entry, don't advise 'git
1378 * add/rm <file>', just 'git commit'.
1380 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1381 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1382 "Please, commit your changes before you merge."));
1383 else
1384 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1386 if (ref_exists("CHERRY_PICK_HEAD")) {
1387 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1388 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1389 "Please, commit your changes before you merge."));
1390 else
1391 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1393 resolve_undo_clear_index(&the_index);
1395 if (option_edit < 0)
1396 option_edit = default_edit_option();
1398 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1400 if (verbosity < 0)
1401 show_diffstat = 0;
1403 if (squash) {
1404 if (fast_forward == FF_NO)
1405 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1406 if (option_commit > 0)
1407 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1409 * squash can now silently disable option_commit - this is not
1410 * a problem as it is only overriding the default, not a user
1411 * supplied option.
1413 option_commit = 0;
1416 if (option_commit < 0)
1417 option_commit = 1;
1419 if (!argc) {
1420 if (default_to_upstream)
1421 argc = setup_with_upstream(&argv);
1422 else
1423 die(_("No commit specified and merge.defaultToUpstream not set."));
1424 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1425 argv[0] = "@{-1}";
1428 if (!argc)
1429 usage_with_options(builtin_merge_usage,
1430 builtin_merge_options);
1432 if (!head_commit) {
1434 * If the merged head is a valid one there is no reason
1435 * to forbid "git merge" into a branch yet to be born.
1436 * We do the same for "git pull".
1438 struct object_id *remote_head_oid;
1439 if (squash)
1440 die(_("Squash commit into empty head not supported yet"));
1441 if (fast_forward == FF_NO)
1442 die(_("Non-fast-forward commit does not make sense into "
1443 "an empty head"));
1444 remoteheads = collect_parents(head_commit, &head_subsumed,
1445 argc, argv, NULL);
1446 if (!remoteheads)
1447 die(_("%s - not something we can merge"), argv[0]);
1448 if (remoteheads->next)
1449 die(_("Can merge only exactly one commit into empty head"));
1451 if (verify_signatures)
1452 verify_merge_signature(remoteheads->item, verbosity,
1453 check_trust_level);
1455 remote_head_oid = &remoteheads->item->object.oid;
1456 read_empty(remote_head_oid);
1457 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1458 UPDATE_REFS_DIE_ON_ERR);
1459 goto done;
1463 * All the rest are the commits being merged; prepare
1464 * the standard merge summary message to be appended
1465 * to the given message.
1467 remoteheads = collect_parents(head_commit, &head_subsumed,
1468 argc, argv, &merge_msg);
1470 if (!head_commit || !argc)
1471 usage_with_options(builtin_merge_usage,
1472 builtin_merge_options);
1474 if (verify_signatures) {
1475 for (p = remoteheads; p; p = p->next) {
1476 verify_merge_signature(p->item, verbosity,
1477 check_trust_level);
1481 strbuf_addstr(&buf, "merge");
1482 for (p = remoteheads; p; p = p->next)
1483 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1484 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1485 strbuf_reset(&buf);
1487 for (p = remoteheads; p; p = p->next) {
1488 struct commit *commit = p->item;
1489 strbuf_addf(&buf, "GITHEAD_%s",
1490 oid_to_hex(&commit->object.oid));
1491 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1492 strbuf_reset(&buf);
1493 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1494 fast_forward = FF_NO;
1497 if (!use_strategies && !pull_twohead &&
1498 remoteheads && !remoteheads->next) {
1499 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1500 if (default_strategy)
1501 append_strategy(get_strategy(default_strategy));
1503 if (!use_strategies) {
1504 if (!remoteheads)
1505 ; /* already up-to-date */
1506 else if (!remoteheads->next)
1507 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1508 else
1509 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1512 for (i = 0; i < use_strategies_nr; i++) {
1513 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1514 fast_forward = FF_NO;
1515 if (use_strategies[i]->attr & NO_TRIVIAL)
1516 allow_trivial = 0;
1519 if (!remoteheads)
1520 ; /* already up-to-date */
1521 else if (!remoteheads->next)
1522 common = repo_get_merge_bases(the_repository, head_commit,
1523 remoteheads->item);
1524 else {
1525 struct commit_list *list = remoteheads;
1526 commit_list_insert(head_commit, &list);
1527 common = get_octopus_merge_bases(list);
1528 free(list);
1531 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1532 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1534 if (remoteheads && !common) {
1535 /* No common ancestors found. */
1536 if (!allow_unrelated_histories)
1537 die(_("refusing to merge unrelated histories"));
1538 /* otherwise, we need a real merge. */
1539 } else if (!remoteheads ||
1540 (!remoteheads->next && !common->next &&
1541 common->item == remoteheads->item)) {
1543 * If head can reach all the merge then we are up to date.
1544 * but first the most common case of merging one remote.
1546 finish_up_to_date();
1547 goto done;
1548 } else if (fast_forward != FF_NO && !remoteheads->next &&
1549 !common->next &&
1550 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1551 /* Again the most common case of merging one remote. */
1552 const char *msg = have_message ?
1553 "Fast-forward (no commit created; -m option ignored)" :
1554 "Fast-forward";
1555 struct commit *commit;
1557 if (verbosity >= 0) {
1558 printf(_("Updating %s..%s\n"),
1559 repo_find_unique_abbrev(the_repository, &head_commit->object.oid,
1560 DEFAULT_ABBREV),
1561 repo_find_unique_abbrev(the_repository, &remoteheads->item->object.oid,
1562 DEFAULT_ABBREV));
1564 commit = remoteheads->item;
1565 if (!commit) {
1566 ret = 1;
1567 goto done;
1570 if (autostash)
1571 create_autostash(the_repository,
1572 git_path_merge_autostash(the_repository));
1573 if (checkout_fast_forward(the_repository,
1574 &head_commit->object.oid,
1575 &commit->object.oid,
1576 overwrite_ignore)) {
1577 apply_autostash(git_path_merge_autostash(the_repository));
1578 ret = 1;
1579 goto done;
1582 finish(head_commit, remoteheads, &commit->object.oid, msg);
1583 remove_merge_branch_state(the_repository);
1584 goto done;
1585 } else if (!remoteheads->next && common->next)
1588 * We are not doing octopus and not fast-forward. Need
1589 * a real merge.
1591 else if (!remoteheads->next && !common->next && option_commit) {
1593 * We are not doing octopus, not fast-forward, and have
1594 * only one common.
1596 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
1597 if (allow_trivial && fast_forward != FF_ONLY) {
1599 * Must first ensure that index matches HEAD before
1600 * attempting a trivial merge.
1602 struct tree *head_tree = repo_get_commit_tree(the_repository,
1603 head_commit);
1604 struct strbuf sb = STRBUF_INIT;
1606 if (repo_index_has_changes(the_repository, head_tree,
1607 &sb)) {
1608 error(_("Your local changes to the following files would be overwritten by merge:\n %s"),
1609 sb.buf);
1610 strbuf_release(&sb);
1611 ret = 2;
1612 goto done;
1615 /* See if it is really trivial. */
1616 git_committer_info(IDENT_STRICT);
1617 printf(_("Trying really trivial in-index merge...\n"));
1618 if (!read_tree_trivial(&common->item->object.oid,
1619 &head_commit->object.oid,
1620 &remoteheads->item->object.oid)) {
1621 ret = merge_trivial(head_commit, remoteheads);
1622 goto done;
1624 printf(_("Nope.\n"));
1626 } else {
1628 * An octopus. If we can reach all the remote we are up
1629 * to date.
1631 int up_to_date = 1;
1632 struct commit_list *j;
1634 for (j = remoteheads; j; j = j->next) {
1635 struct commit_list *common_one;
1638 * Here we *have* to calculate the individual
1639 * merge_bases again, otherwise "git merge HEAD^
1640 * HEAD^^" would be missed.
1642 common_one = repo_get_merge_bases(the_repository,
1643 head_commit,
1644 j->item);
1645 if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1646 up_to_date = 0;
1647 break;
1650 if (up_to_date) {
1651 finish_up_to_date();
1652 goto done;
1656 if (fast_forward == FF_ONLY)
1657 die_ff_impossible();
1659 if (autostash)
1660 create_autostash(the_repository,
1661 git_path_merge_autostash(the_repository));
1663 /* We are going to make a new commit. */
1664 git_committer_info(IDENT_STRICT);
1667 * At this point, we need a real merge. No matter what strategy
1668 * we use, it would operate on the index, possibly affecting the
1669 * working tree, and when resolved cleanly, have the desired
1670 * tree in the index -- this means that the index must be in
1671 * sync with the head commit. The strategies are responsible
1672 * to ensure this.
1674 * Stash away the local changes so that we can try more than one
1675 * and/or recover from merge strategies bailing while leaving the
1676 * index and working tree polluted.
1678 if (save_state(&stash))
1679 oidclr(&stash);
1681 for (i = 0; i < use_strategies_nr; i++) {
1682 int ret, cnt;
1683 if (i) {
1684 printf(_("Rewinding the tree to pristine...\n"));
1685 restore_state(&head_commit->object.oid, &stash);
1687 if (use_strategies_nr != 1)
1688 printf(_("Trying merge strategy %s...\n"),
1689 use_strategies[i]->name);
1691 * Remember which strategy left the state in the working
1692 * tree.
1694 wt_strategy = use_strategies[i]->name;
1696 ret = try_merge_strategy(wt_strategy,
1697 common, remoteheads,
1698 head_commit);
1700 * The backend exits with 1 when conflicts are
1701 * left to be resolved, with 2 when it does not
1702 * handle the given merge at all.
1704 if (ret < 2) {
1705 if (!ret) {
1707 * This strategy worked; no point in trying
1708 * another.
1710 merge_was_ok = 1;
1711 best_strategy = wt_strategy;
1712 break;
1714 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1715 if (best_cnt <= 0 || cnt <= best_cnt) {
1716 best_strategy = wt_strategy;
1717 best_cnt = cnt;
1723 * If we have a resulting tree, that means the strategy module
1724 * auto resolved the merge cleanly.
1726 if (merge_was_ok && option_commit) {
1727 automerge_was_ok = 1;
1728 ret = finish_automerge(head_commit, head_subsumed,
1729 common, remoteheads,
1730 &result_tree, wt_strategy);
1731 goto done;
1735 * Pick the result from the best strategy and have the user fix
1736 * it up.
1738 if (!best_strategy) {
1739 restore_state(&head_commit->object.oid, &stash);
1740 if (use_strategies_nr > 1)
1741 fprintf(stderr,
1742 _("No merge strategy handled the merge.\n"));
1743 else
1744 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1745 use_strategies[0]->name);
1746 apply_autostash(git_path_merge_autostash(the_repository));
1747 ret = 2;
1748 goto done;
1749 } else if (best_strategy == wt_strategy)
1750 ; /* We already have its result in the working tree. */
1751 else {
1752 printf(_("Rewinding the tree to pristine...\n"));
1753 restore_state(&head_commit->object.oid, &stash);
1754 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1755 best_strategy);
1756 try_merge_strategy(best_strategy, common, remoteheads,
1757 head_commit);
1760 if (squash) {
1761 finish(head_commit, remoteheads, NULL, NULL);
1763 git_test_write_commit_graph_or_die();
1764 } else
1765 write_merge_state(remoteheads);
1767 if (merge_was_ok)
1768 fprintf(stderr, _("Automatic merge went well; "
1769 "stopped before committing as requested\n"));
1770 else
1771 ret = suggest_conflicts();
1772 if (autostash)
1773 printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1775 done:
1776 if (!automerge_was_ok) {
1777 free_commit_list(common);
1778 free_commit_list(remoteheads);
1780 strbuf_release(&buf);
1781 free(branch_to_free);
1782 discard_index(&the_index);
1783 return ret;