ci: use upload-artifacts v1 for dockerized jobs
[git/debian.git] / builtin / merge.c
blob22f23990b37b6af8756daa5bcf7a1a7bbef2049c
1 /*
2 * Builtin "git merge"
4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
7 */
9 #define USE_THE_INDEX_COMPATIBILITY_MACROS
10 #include "cache.h"
11 #include "config.h"
12 #include "parse-options.h"
13 #include "builtin.h"
14 #include "lockfile.h"
15 #include "run-command.h"
16 #include "diff.h"
17 #include "diff-merges.h"
18 #include "refs.h"
19 #include "refspec.h"
20 #include "commit.h"
21 #include "diffcore.h"
22 #include "revision.h"
23 #include "unpack-trees.h"
24 #include "cache-tree.h"
25 #include "dir.h"
26 #include "utf8.h"
27 #include "log-tree.h"
28 #include "color.h"
29 #include "rerere.h"
30 #include "help.h"
31 #include "merge-recursive.h"
32 #include "merge-ort-wrappers.h"
33 #include "resolve-undo.h"
34 #include "remote.h"
35 #include "fmt-merge-msg.h"
36 #include "gpg-interface.h"
37 #include "sequencer.h"
38 #include "string-list.h"
39 #include "packfile.h"
40 #include "tag.h"
41 #include "alias.h"
42 #include "branch.h"
43 #include "commit-reach.h"
44 #include "wt-status.h"
45 #include "commit-graph.h"
47 #define DEFAULT_TWOHEAD (1<<0)
48 #define DEFAULT_OCTOPUS (1<<1)
49 #define NO_FAST_FORWARD (1<<2)
50 #define NO_TRIVIAL (1<<3)
52 struct strategy {
53 const char *name;
54 unsigned attr;
57 static const char * const builtin_merge_usage[] = {
58 N_("git merge [<options>] [<commit>...]"),
59 "git merge --abort",
60 "git merge --continue",
61 NULL
64 static int show_diffstat = 1, shortlog_len = -1, squash;
65 static int option_commit = -1;
66 static int option_edit = -1;
67 static int allow_trivial = 1, have_message, verify_signatures;
68 static int check_trust_level = 1;
69 static int overwrite_ignore = 1;
70 static struct strbuf merge_msg = STRBUF_INIT;
71 static struct strategy **use_strategies;
72 static size_t use_strategies_nr, use_strategies_alloc;
73 static const char **xopts;
74 static size_t xopts_nr, xopts_alloc;
75 static const char *branch;
76 static char *branch_mergeoptions;
77 static int verbosity;
78 static int allow_rerere_auto;
79 static int abort_current_merge;
80 static int quit_current_merge;
81 static int continue_current_merge;
82 static int allow_unrelated_histories;
83 static int show_progress = -1;
84 static int default_to_upstream = 1;
85 static int signoff;
86 static const char *sign_commit;
87 static int autostash;
88 static int no_verify;
90 static struct strategy all_strategy[] = {
91 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
92 { "octopus", DEFAULT_OCTOPUS },
93 { "ort", NO_TRIVIAL },
94 { "resolve", 0 },
95 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
96 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
99 static const char *pull_twohead, *pull_octopus;
101 enum ff_type {
102 FF_NO,
103 FF_ALLOW,
104 FF_ONLY
107 static enum ff_type fast_forward = FF_ALLOW;
109 static const char *cleanup_arg;
110 static enum commit_msg_cleanup_mode cleanup_mode;
112 static int option_parse_message(const struct option *opt,
113 const char *arg, int unset)
115 struct strbuf *buf = opt->value;
117 if (unset)
118 strbuf_setlen(buf, 0);
119 else if (arg) {
120 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
121 have_message = 1;
122 } else
123 return error(_("switch `m' requires a value"));
124 return 0;
127 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
128 const struct option *opt,
129 const char *arg_not_used,
130 int unset)
132 struct strbuf *buf = opt->value;
133 const char *arg;
135 BUG_ON_OPT_ARG(arg_not_used);
136 if (unset)
137 BUG("-F cannot be negated");
139 if (ctx->opt) {
140 arg = ctx->opt;
141 ctx->opt = NULL;
142 } else if (ctx->argc > 1) {
143 ctx->argc--;
144 arg = *++ctx->argv;
145 } else
146 return error(_("option `%s' requires a value"), opt->long_name);
148 if (buf->len)
149 strbuf_addch(buf, '\n');
150 if (ctx->prefix && !is_absolute_path(arg))
151 arg = prefix_filename(ctx->prefix, arg);
152 if (strbuf_read_file(buf, arg, 0) < 0)
153 return error(_("could not read file '%s'"), arg);
154 have_message = 1;
156 return 0;
159 static struct strategy *get_strategy(const char *name)
161 int i;
162 struct strategy *ret;
163 static struct cmdnames main_cmds, other_cmds;
164 static int loaded;
165 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
167 if (!name)
168 return NULL;
170 if (default_strategy &&
171 !strcmp(default_strategy, "ort") &&
172 !strcmp(name, "recursive")) {
173 name = "ort";
176 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
177 if (!strcmp(name, all_strategy[i].name))
178 return &all_strategy[i];
180 if (!loaded) {
181 struct cmdnames not_strategies;
182 loaded = 1;
184 memset(&not_strategies, 0, sizeof(struct cmdnames));
185 load_command_list("git-merge-", &main_cmds, &other_cmds);
186 for (i = 0; i < main_cmds.cnt; i++) {
187 int j, found = 0;
188 struct cmdname *ent = main_cmds.names[i];
189 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
190 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
191 && !all_strategy[j].name[ent->len])
192 found = 1;
193 if (!found)
194 add_cmdname(&not_strategies, ent->name, ent->len);
196 exclude_cmds(&main_cmds, &not_strategies);
198 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
199 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
200 fprintf(stderr, _("Available strategies are:"));
201 for (i = 0; i < main_cmds.cnt; i++)
202 fprintf(stderr, " %s", main_cmds.names[i]->name);
203 fprintf(stderr, ".\n");
204 if (other_cmds.cnt) {
205 fprintf(stderr, _("Available custom strategies are:"));
206 for (i = 0; i < other_cmds.cnt; i++)
207 fprintf(stderr, " %s", other_cmds.names[i]->name);
208 fprintf(stderr, ".\n");
210 exit(1);
213 CALLOC_ARRAY(ret, 1);
214 ret->name = xstrdup(name);
215 ret->attr = NO_TRIVIAL;
216 return ret;
219 static void append_strategy(struct strategy *s)
221 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
222 use_strategies[use_strategies_nr++] = s;
225 static int option_parse_strategy(const struct option *opt,
226 const char *name, int unset)
228 if (unset)
229 return 0;
231 append_strategy(get_strategy(name));
232 return 0;
235 static int option_parse_x(const struct option *opt,
236 const char *arg, int unset)
238 if (unset)
239 return 0;
241 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
242 xopts[xopts_nr++] = xstrdup(arg);
243 return 0;
246 static int option_parse_n(const struct option *opt,
247 const char *arg, int unset)
249 BUG_ON_OPT_ARG(arg);
250 show_diffstat = unset;
251 return 0;
254 static struct option builtin_merge_options[] = {
255 OPT_CALLBACK_F('n', NULL, NULL, NULL,
256 N_("do not show a diffstat at the end of the merge"),
257 PARSE_OPT_NOARG, option_parse_n),
258 OPT_BOOL(0, "stat", &show_diffstat,
259 N_("show a diffstat at the end of the merge")),
260 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
261 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
262 N_("add (at most <n>) entries from shortlog to merge commit message"),
263 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
264 OPT_BOOL(0, "squash", &squash,
265 N_("create a single commit instead of doing a merge")),
266 OPT_BOOL(0, "commit", &option_commit,
267 N_("perform a commit if the merge succeeds (default)")),
268 OPT_BOOL('e', "edit", &option_edit,
269 N_("edit message before committing")),
270 OPT_CLEANUP(&cleanup_arg),
271 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
272 OPT_SET_INT_F(0, "ff-only", &fast_forward,
273 N_("abort if fast-forward is not possible"),
274 FF_ONLY, PARSE_OPT_NONEG),
275 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
276 OPT_BOOL(0, "verify-signatures", &verify_signatures,
277 N_("verify that the named commit has a valid GPG signature")),
278 OPT_CALLBACK('s', "strategy", &use_strategies, N_("strategy"),
279 N_("merge strategy to use"), option_parse_strategy),
280 OPT_CALLBACK('X', "strategy-option", &xopts, N_("option=value"),
281 N_("option for selected merge strategy"), option_parse_x),
282 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
283 N_("merge commit message (for a non-fast-forward merge)"),
284 option_parse_message),
285 { OPTION_LOWLEVEL_CALLBACK, 'F', "file", &merge_msg, N_("path"),
286 N_("read message from file"), PARSE_OPT_NONEG,
287 NULL, 0, option_read_message },
288 OPT__VERBOSITY(&verbosity),
289 OPT_BOOL(0, "abort", &abort_current_merge,
290 N_("abort the current in-progress merge")),
291 OPT_BOOL(0, "quit", &quit_current_merge,
292 N_("--abort but leave index and working tree alone")),
293 OPT_BOOL(0, "continue", &continue_current_merge,
294 N_("continue the current in-progress merge")),
295 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
296 N_("allow merging unrelated histories")),
297 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
298 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
299 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
300 OPT_AUTOSTASH(&autostash),
301 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
302 OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
303 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
304 OPT_END()
307 static int save_state(struct object_id *stash)
309 int len;
310 struct child_process cp = CHILD_PROCESS_INIT;
311 struct strbuf buffer = STRBUF_INIT;
312 const char *argv[] = {"stash", "create", NULL};
313 int rc = -1;
315 cp.argv = argv;
316 cp.out = -1;
317 cp.git_cmd = 1;
319 if (start_command(&cp))
320 die(_("could not run stash."));
321 len = strbuf_read(&buffer, cp.out, 1024);
322 close(cp.out);
324 if (finish_command(&cp) || len < 0)
325 die(_("stash failed"));
326 else if (!len) /* no changes */
327 goto out;
328 strbuf_setlen(&buffer, buffer.len-1);
329 if (get_oid(buffer.buf, stash))
330 die(_("not a valid object: %s"), buffer.buf);
331 rc = 0;
332 out:
333 strbuf_release(&buffer);
334 return rc;
337 static void read_empty(const struct object_id *oid, int verbose)
339 int i = 0;
340 const char *args[7];
342 args[i++] = "read-tree";
343 if (verbose)
344 args[i++] = "-v";
345 args[i++] = "-m";
346 args[i++] = "-u";
347 args[i++] = empty_tree_oid_hex();
348 args[i++] = oid_to_hex(oid);
349 args[i] = NULL;
351 if (run_command_v_opt(args, RUN_GIT_CMD))
352 die(_("read-tree failed"));
355 static void reset_hard(const struct object_id *oid, int verbose)
357 int i = 0;
358 const char *args[6];
360 args[i++] = "read-tree";
361 if (verbose)
362 args[i++] = "-v";
363 args[i++] = "--reset";
364 args[i++] = "-u";
365 args[i++] = oid_to_hex(oid);
366 args[i] = NULL;
368 if (run_command_v_opt(args, RUN_GIT_CMD))
369 die(_("read-tree failed"));
372 static void restore_state(const struct object_id *head,
373 const struct object_id *stash)
375 struct strbuf sb = STRBUF_INIT;
376 const char *args[] = { "stash", "apply", NULL, NULL };
378 if (is_null_oid(stash))
379 return;
381 reset_hard(head, 1);
383 args[2] = oid_to_hex(stash);
386 * It is OK to ignore error here, for example when there was
387 * nothing to restore.
389 run_command_v_opt(args, RUN_GIT_CMD);
391 strbuf_release(&sb);
392 refresh_cache(REFRESH_QUIET);
395 /* This is called when no merge was necessary. */
396 static void finish_up_to_date(void)
398 if (verbosity >= 0) {
399 if (squash)
400 puts(_("Already up to date. (nothing to squash)"));
401 else
402 puts(_("Already up to date."));
404 remove_merge_branch_state(the_repository);
407 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
409 struct rev_info rev;
410 struct strbuf out = STRBUF_INIT;
411 struct commit_list *j;
412 struct pretty_print_context ctx = {0};
414 printf(_("Squash commit -- not updating HEAD\n"));
416 repo_init_revisions(the_repository, &rev, NULL);
417 diff_merges_suppress(&rev);
418 rev.commit_format = CMIT_FMT_MEDIUM;
420 commit->object.flags |= UNINTERESTING;
421 add_pending_object(&rev, &commit->object, NULL);
423 for (j = remoteheads; j; j = j->next)
424 add_pending_object(&rev, &j->item->object, NULL);
426 setup_revisions(0, NULL, &rev, NULL);
427 if (prepare_revision_walk(&rev))
428 die(_("revision walk setup failed"));
430 ctx.abbrev = rev.abbrev;
431 ctx.date_mode = rev.date_mode;
432 ctx.fmt = rev.commit_format;
434 strbuf_addstr(&out, "Squashed commit of the following:\n");
435 while ((commit = get_revision(&rev)) != NULL) {
436 strbuf_addch(&out, '\n');
437 strbuf_addf(&out, "commit %s\n",
438 oid_to_hex(&commit->object.oid));
439 pretty_print_commit(&ctx, commit, &out);
441 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
442 strbuf_release(&out);
445 static void finish(struct commit *head_commit,
446 struct commit_list *remoteheads,
447 const struct object_id *new_head, const char *msg)
449 struct strbuf reflog_message = STRBUF_INIT;
450 const struct object_id *head = &head_commit->object.oid;
452 if (!msg)
453 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
454 else {
455 if (verbosity >= 0)
456 printf("%s\n", msg);
457 strbuf_addf(&reflog_message, "%s: %s",
458 getenv("GIT_REFLOG_ACTION"), msg);
460 if (squash) {
461 squash_message(head_commit, remoteheads);
462 } else {
463 if (verbosity >= 0 && !merge_msg.len)
464 printf(_("No merge message -- not updating HEAD\n"));
465 else {
466 update_ref(reflog_message.buf, "HEAD", new_head, head,
467 0, UPDATE_REFS_DIE_ON_ERR);
469 * We ignore errors in 'gc --auto', since the
470 * user should see them.
472 close_object_store(the_repository->objects);
473 run_auto_maintenance(verbosity < 0);
476 if (new_head && show_diffstat) {
477 struct diff_options opts;
478 repo_diff_setup(the_repository, &opts);
479 opts.stat_width = -1; /* use full terminal width */
480 opts.stat_graph_width = -1; /* respect statGraphWidth config */
481 opts.output_format |=
482 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
483 opts.detect_rename = DIFF_DETECT_RENAME;
484 diff_setup_done(&opts);
485 diff_tree_oid(head, new_head, "", &opts);
486 diffcore_std(&opts);
487 diff_flush(&opts);
490 /* Run a post-merge hook */
491 run_hook_le(NULL, "post-merge", squash ? "1" : "0", NULL);
493 apply_autostash(git_path_merge_autostash(the_repository));
494 strbuf_release(&reflog_message);
497 /* Get the name for the merge commit's message. */
498 static void merge_name(const char *remote, struct strbuf *msg)
500 struct commit *remote_head;
501 struct object_id branch_head;
502 struct strbuf buf = STRBUF_INIT;
503 struct strbuf bname = STRBUF_INIT;
504 struct merge_remote_desc *desc;
505 const char *ptr;
506 char *found_ref = NULL;
507 int len, early;
509 strbuf_branchname(&bname, remote, 0);
510 remote = bname.buf;
512 oidclr(&branch_head);
513 remote_head = get_merge_parent(remote);
514 if (!remote_head)
515 die(_("'%s' does not point to a commit"), remote);
517 if (dwim_ref(remote, strlen(remote), &branch_head, &found_ref, 0) > 0) {
518 if (starts_with(found_ref, "refs/heads/")) {
519 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
520 oid_to_hex(&branch_head), remote);
521 goto cleanup;
523 if (starts_with(found_ref, "refs/tags/")) {
524 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
525 oid_to_hex(&branch_head), remote);
526 goto cleanup;
528 if (starts_with(found_ref, "refs/remotes/")) {
529 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
530 oid_to_hex(&branch_head), remote);
531 goto cleanup;
535 /* See if remote matches <name>^^^.. or <name>~<number> */
536 for (len = 0, ptr = remote + strlen(remote);
537 remote < ptr && ptr[-1] == '^';
538 ptr--)
539 len++;
540 if (len)
541 early = 1;
542 else {
543 early = 0;
544 ptr = strrchr(remote, '~');
545 if (ptr) {
546 int seen_nonzero = 0;
548 len++; /* count ~ */
549 while (*++ptr && isdigit(*ptr)) {
550 seen_nonzero |= (*ptr != '0');
551 len++;
553 if (*ptr)
554 len = 0; /* not ...~<number> */
555 else if (seen_nonzero)
556 early = 1;
557 else if (len == 1)
558 early = 1; /* "name~" is "name~1"! */
561 if (len) {
562 struct strbuf truname = STRBUF_INIT;
563 strbuf_addf(&truname, "refs/heads/%s", remote);
564 strbuf_setlen(&truname, truname.len - len);
565 if (ref_exists(truname.buf)) {
566 strbuf_addf(msg,
567 "%s\t\tbranch '%s'%s of .\n",
568 oid_to_hex(&remote_head->object.oid),
569 truname.buf + 11,
570 (early ? " (early part)" : ""));
571 strbuf_release(&truname);
572 goto cleanup;
574 strbuf_release(&truname);
577 desc = merge_remote_util(remote_head);
578 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
579 strbuf_addf(msg, "%s\t\t%s '%s'\n",
580 oid_to_hex(&desc->obj->oid),
581 type_name(desc->obj->type),
582 remote);
583 goto cleanup;
586 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
587 oid_to_hex(&remote_head->object.oid), remote);
588 cleanup:
589 free(found_ref);
590 strbuf_release(&buf);
591 strbuf_release(&bname);
594 static void parse_branch_merge_options(char *bmo)
596 const char **argv;
597 int argc;
599 if (!bmo)
600 return;
601 argc = split_cmdline(bmo, &argv);
602 if (argc < 0)
603 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
604 _(split_cmdline_strerror(argc)));
605 REALLOC_ARRAY(argv, argc + 2);
606 MOVE_ARRAY(argv + 1, argv, argc + 1);
607 argc++;
608 argv[0] = "branch.*.mergeoptions";
609 parse_options(argc, argv, NULL, builtin_merge_options,
610 builtin_merge_usage, 0);
611 free(argv);
614 static int git_merge_config(const char *k, const char *v, void *cb)
616 int status;
617 const char *str;
619 if (branch &&
620 skip_prefix(k, "branch.", &str) &&
621 skip_prefix(str, branch, &str) &&
622 !strcmp(str, ".mergeoptions")) {
623 free(branch_mergeoptions);
624 branch_mergeoptions = xstrdup(v);
625 return 0;
628 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
629 show_diffstat = git_config_bool(k, v);
630 else if (!strcmp(k, "merge.verifysignatures"))
631 verify_signatures = git_config_bool(k, v);
632 else if (!strcmp(k, "pull.twohead"))
633 return git_config_string(&pull_twohead, k, v);
634 else if (!strcmp(k, "pull.octopus"))
635 return git_config_string(&pull_octopus, k, v);
636 else if (!strcmp(k, "commit.cleanup"))
637 return git_config_string(&cleanup_arg, k, v);
638 else if (!strcmp(k, "merge.ff")) {
639 int boolval = git_parse_maybe_bool(v);
640 if (0 <= boolval) {
641 fast_forward = boolval ? FF_ALLOW : FF_NO;
642 } else if (v && !strcmp(v, "only")) {
643 fast_forward = FF_ONLY;
644 } /* do not barf on values from future versions of git */
645 return 0;
646 } else if (!strcmp(k, "merge.defaulttoupstream")) {
647 default_to_upstream = git_config_bool(k, v);
648 return 0;
649 } else if (!strcmp(k, "commit.gpgsign")) {
650 sign_commit = git_config_bool(k, v) ? "" : NULL;
651 return 0;
652 } else if (!strcmp(k, "gpg.mintrustlevel")) {
653 check_trust_level = 0;
654 } else if (!strcmp(k, "merge.autostash")) {
655 autostash = git_config_bool(k, v);
656 return 0;
659 status = fmt_merge_msg_config(k, v, cb);
660 if (status)
661 return status;
662 status = git_gpg_config(k, v, NULL);
663 if (status)
664 return status;
665 return git_diff_ui_config(k, v, cb);
668 static int read_tree_trivial(struct object_id *common, struct object_id *head,
669 struct object_id *one)
671 int i, nr_trees = 0;
672 struct tree *trees[MAX_UNPACK_TREES];
673 struct tree_desc t[MAX_UNPACK_TREES];
674 struct unpack_trees_options opts;
676 memset(&opts, 0, sizeof(opts));
677 opts.head_idx = 2;
678 opts.src_index = &the_index;
679 opts.dst_index = &the_index;
680 opts.update = 1;
681 opts.verbose_update = 1;
682 opts.trivial_merges_only = 1;
683 opts.merge = 1;
684 trees[nr_trees] = parse_tree_indirect(common);
685 if (!trees[nr_trees++])
686 return -1;
687 trees[nr_trees] = parse_tree_indirect(head);
688 if (!trees[nr_trees++])
689 return -1;
690 trees[nr_trees] = parse_tree_indirect(one);
691 if (!trees[nr_trees++])
692 return -1;
693 opts.fn = threeway_merge;
694 cache_tree_free(&active_cache_tree);
695 for (i = 0; i < nr_trees; i++) {
696 parse_tree(trees[i]);
697 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
699 if (unpack_trees(nr_trees, t, &opts))
700 return -1;
701 return 0;
704 static void write_tree_trivial(struct object_id *oid)
706 if (write_cache_as_tree(oid, 0, NULL))
707 die(_("git write-tree failed to write a tree"));
710 static int try_merge_strategy(const char *strategy, struct commit_list *common,
711 struct commit_list *remoteheads,
712 struct commit *head)
714 const char *head_arg = "HEAD";
716 if (refresh_and_write_cache(REFRESH_QUIET, SKIP_IF_UNCHANGED, 0) < 0)
717 return error(_("Unable to write index."));
719 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
720 !strcmp(strategy, "ort")) {
721 struct lock_file lock = LOCK_INIT;
722 int clean, x;
723 struct commit *result;
724 struct commit_list *reversed = NULL;
725 struct merge_options o;
726 struct commit_list *j;
728 if (remoteheads->next) {
729 error(_("Not handling anything other than two heads merge."));
730 return 2;
733 init_merge_options(&o, the_repository);
734 if (!strcmp(strategy, "subtree"))
735 o.subtree_shift = "";
737 o.show_rename_progress =
738 show_progress == -1 ? isatty(2) : show_progress;
740 for (x = 0; x < xopts_nr; x++)
741 if (parse_merge_opt(&o, xopts[x]))
742 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
744 o.branch1 = head_arg;
745 o.branch2 = merge_remote_util(remoteheads->item)->name;
747 for (j = common; j; j = j->next)
748 commit_list_insert(j->item, &reversed);
750 hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
751 if (!strcmp(strategy, "ort"))
752 clean = merge_ort_recursive(&o, head, remoteheads->item,
753 reversed, &result);
754 else
755 clean = merge_recursive(&o, head, remoteheads->item,
756 reversed, &result);
757 if (clean < 0)
758 exit(128);
759 if (write_locked_index(&the_index, &lock,
760 COMMIT_LOCK | SKIP_IF_UNCHANGED))
761 die(_("unable to write %s"), get_index_file());
762 return clean ? 0 : 1;
763 } else {
764 return try_merge_command(the_repository,
765 strategy, xopts_nr, xopts,
766 common, head_arg, remoteheads);
770 static void count_diff_files(struct diff_queue_struct *q,
771 struct diff_options *opt, void *data)
773 int *count = data;
775 (*count) += q->nr;
778 static int count_unmerged_entries(void)
780 int i, ret = 0;
782 for (i = 0; i < active_nr; i++)
783 if (ce_stage(active_cache[i]))
784 ret++;
786 return ret;
789 static void add_strategies(const char *string, unsigned attr)
791 int i;
793 if (string) {
794 struct string_list list = STRING_LIST_INIT_DUP;
795 struct string_list_item *item;
796 string_list_split(&list, string, ' ', -1);
797 for_each_string_list_item(item, &list)
798 append_strategy(get_strategy(item->string));
799 string_list_clear(&list, 0);
800 return;
802 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
803 if (all_strategy[i].attr & attr)
804 append_strategy(&all_strategy[i]);
808 static void read_merge_msg(struct strbuf *msg)
810 const char *filename = git_path_merge_msg(the_repository);
811 strbuf_reset(msg);
812 if (strbuf_read_file(msg, filename, 0) < 0)
813 die_errno(_("Could not read from '%s'"), filename);
816 static void write_merge_state(struct commit_list *);
817 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
819 if (err_msg)
820 error("%s", err_msg);
821 fprintf(stderr,
822 _("Not committing merge; use 'git commit' to complete the merge.\n"));
823 write_merge_state(remoteheads);
824 exit(1);
827 static const char merge_editor_comment[] =
828 N_("Please enter a commit message to explain why this merge is necessary,\n"
829 "especially if it merges an updated upstream into a topic branch.\n"
830 "\n");
832 static const char scissors_editor_comment[] =
833 N_("An empty message aborts the commit.\n");
835 static const char no_scissors_editor_comment[] =
836 N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
837 "the commit.\n");
839 static void write_merge_heads(struct commit_list *);
840 static void prepare_to_commit(struct commit_list *remoteheads)
842 struct strbuf msg = STRBUF_INIT;
843 const char *index_file = get_index_file();
845 if (!no_verify && run_commit_hook(0 < option_edit, index_file, "pre-merge-commit", NULL))
846 abort_commit(remoteheads, NULL);
848 * Re-read the index as pre-merge-commit hook could have updated it,
849 * and write it out as a tree. We must do this before we invoke
850 * the editor and after we invoke run_status above.
852 if (find_hook("pre-merge-commit"))
853 discard_cache();
854 read_cache_from(index_file);
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, "\n");
864 strbuf_commented_addf(&msg, _(merge_editor_comment));
865 strbuf_commented_addf(&msg, _(cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS ?
866 scissors_editor_comment :
867 no_scissors_editor_comment), comment_line_char);
869 if (signoff)
870 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
871 write_merge_heads(remoteheads);
872 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
873 if (run_commit_hook(0 < option_edit, get_index_file(), "prepare-commit-msg",
874 git_path_merge_msg(the_repository), "merge", NULL))
875 abort_commit(remoteheads, NULL);
876 if (0 < option_edit) {
877 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
878 abort_commit(remoteheads, NULL);
881 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
882 "commit-msg",
883 git_path_merge_msg(the_repository), NULL))
884 abort_commit(remoteheads, NULL);
886 read_merge_msg(&msg);
887 cleanup_message(&msg, cleanup_mode, 0);
888 if (!msg.len)
889 abort_commit(remoteheads, _("Empty commit message."));
890 strbuf_release(&merge_msg);
891 strbuf_addbuf(&merge_msg, &msg);
892 strbuf_release(&msg);
895 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
897 struct object_id result_tree, result_commit;
898 struct commit_list *parents, **pptr = &parents;
900 if (refresh_and_write_cache(REFRESH_QUIET, SKIP_IF_UNCHANGED, 0) < 0)
901 return error(_("Unable to write index."));
903 write_tree_trivial(&result_tree);
904 printf(_("Wonderful.\n"));
905 pptr = commit_list_append(head, pptr);
906 pptr = commit_list_append(remoteheads->item, pptr);
907 prepare_to_commit(remoteheads);
908 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
909 &result_commit, NULL, sign_commit))
910 die(_("failed to write commit object"));
911 finish(head, remoteheads, &result_commit, "In-index merge");
912 remove_merge_branch_state(the_repository);
913 return 0;
916 static int finish_automerge(struct commit *head,
917 int head_subsumed,
918 struct commit_list *common,
919 struct commit_list *remoteheads,
920 struct object_id *result_tree,
921 const char *wt_strategy)
923 struct commit_list *parents = NULL;
924 struct strbuf buf = STRBUF_INIT;
925 struct object_id result_commit;
927 write_tree_trivial(result_tree);
928 free_commit_list(common);
929 parents = remoteheads;
930 if (!head_subsumed || fast_forward == FF_NO)
931 commit_list_insert(head, &parents);
932 prepare_to_commit(remoteheads);
933 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
934 &result_commit, NULL, sign_commit))
935 die(_("failed to write commit object"));
936 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
937 finish(head, remoteheads, &result_commit, buf.buf);
938 strbuf_release(&buf);
939 remove_merge_branch_state(the_repository);
940 return 0;
943 static int suggest_conflicts(void)
945 const char *filename;
946 FILE *fp;
947 struct strbuf msgbuf = STRBUF_INIT;
949 filename = git_path_merge_msg(the_repository);
950 fp = xfopen(filename, "a");
953 * We can't use cleanup_mode because if we're not using the editor,
954 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
955 * though the message is meant to be processed later by git-commit.
956 * Thus, we will get the cleanup mode which is returned when we _are_
957 * using an editor.
959 append_conflicts_hint(&the_index, &msgbuf,
960 get_cleanup_mode(cleanup_arg, 1));
961 fputs(msgbuf.buf, fp);
962 strbuf_release(&msgbuf);
963 fclose(fp);
964 repo_rerere(the_repository, allow_rerere_auto);
965 printf(_("Automatic merge failed; "
966 "fix conflicts and then commit the result.\n"));
967 return 1;
970 static int evaluate_result(void)
972 int cnt = 0;
973 struct rev_info rev;
975 /* Check how many files differ. */
976 repo_init_revisions(the_repository, &rev, "");
977 setup_revisions(0, NULL, &rev, NULL);
978 rev.diffopt.output_format |=
979 DIFF_FORMAT_CALLBACK;
980 rev.diffopt.format_callback = count_diff_files;
981 rev.diffopt.format_callback_data = &cnt;
982 run_diff_files(&rev, 0);
985 * Check how many unmerged entries are
986 * there.
988 cnt += count_unmerged_entries();
990 return cnt;
994 * Pretend as if the user told us to merge with the remote-tracking
995 * branch we have for the upstream of the current branch
997 static int setup_with_upstream(const char ***argv)
999 struct branch *branch = branch_get(NULL);
1000 int i;
1001 const char **args;
1003 if (!branch)
1004 die(_("No current branch."));
1005 if (!branch->remote_name)
1006 die(_("No remote for the current branch."));
1007 if (!branch->merge_nr)
1008 die(_("No default upstream defined for the current branch."));
1010 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1011 for (i = 0; i < branch->merge_nr; i++) {
1012 if (!branch->merge[i]->dst)
1013 die(_("No remote-tracking branch for %s from %s"),
1014 branch->merge[i]->src, branch->remote_name);
1015 args[i] = branch->merge[i]->dst;
1017 args[i] = NULL;
1018 *argv = args;
1019 return i;
1022 static void write_merge_heads(struct commit_list *remoteheads)
1024 struct commit_list *j;
1025 struct strbuf buf = STRBUF_INIT;
1027 for (j = remoteheads; j; j = j->next) {
1028 struct object_id *oid;
1029 struct commit *c = j->item;
1030 struct merge_remote_desc *desc;
1032 desc = merge_remote_util(c);
1033 if (desc && desc->obj) {
1034 oid = &desc->obj->oid;
1035 } else {
1036 oid = &c->object.oid;
1038 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1040 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1042 strbuf_reset(&buf);
1043 if (fast_forward == FF_NO)
1044 strbuf_addstr(&buf, "no-ff");
1045 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1046 strbuf_release(&buf);
1049 static void write_merge_state(struct commit_list *remoteheads)
1051 write_merge_heads(remoteheads);
1052 strbuf_addch(&merge_msg, '\n');
1053 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1054 merge_msg.len);
1057 static int default_edit_option(void)
1059 static const char name[] = "GIT_MERGE_AUTOEDIT";
1060 const char *e = getenv(name);
1061 struct stat st_stdin, st_stdout;
1063 if (have_message)
1064 /* an explicit -m msg without --[no-]edit */
1065 return 0;
1067 if (e) {
1068 int v = git_parse_maybe_bool(e);
1069 if (v < 0)
1070 die(_("Bad value '%s' in environment '%s'"), e, name);
1071 return v;
1074 /* Use editor if stdin and stdout are the same and is a tty */
1075 return (!fstat(0, &st_stdin) &&
1076 !fstat(1, &st_stdout) &&
1077 isatty(0) && isatty(1) &&
1078 st_stdin.st_dev == st_stdout.st_dev &&
1079 st_stdin.st_ino == st_stdout.st_ino &&
1080 st_stdin.st_mode == st_stdout.st_mode);
1083 static struct commit_list *reduce_parents(struct commit *head_commit,
1084 int *head_subsumed,
1085 struct commit_list *remoteheads)
1087 struct commit_list *parents, **remotes;
1090 * Is the current HEAD reachable from another commit being
1091 * merged? If so we do not want to record it as a parent of
1092 * the resulting merge, unless --no-ff is given. We will flip
1093 * this variable to 0 when we find HEAD among the independent
1094 * tips being merged.
1096 *head_subsumed = 1;
1098 /* Find what parents to record by checking independent ones. */
1099 parents = reduce_heads(remoteheads);
1100 free_commit_list(remoteheads);
1102 remoteheads = NULL;
1103 remotes = &remoteheads;
1104 while (parents) {
1105 struct commit *commit = pop_commit(&parents);
1106 if (commit == head_commit)
1107 *head_subsumed = 0;
1108 else
1109 remotes = &commit_list_insert(commit, remotes)->next;
1111 return remoteheads;
1114 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1116 struct fmt_merge_msg_opts opts;
1118 memset(&opts, 0, sizeof(opts));
1119 opts.add_title = !have_message;
1120 opts.shortlog_len = shortlog_len;
1121 opts.credit_people = (0 < option_edit);
1123 fmt_merge_msg(merge_names, merge_msg, &opts);
1124 if (merge_msg->len)
1125 strbuf_setlen(merge_msg, merge_msg->len - 1);
1128 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1130 const char *filename;
1131 int fd, pos, npos;
1132 struct strbuf fetch_head_file = STRBUF_INIT;
1133 const unsigned hexsz = the_hash_algo->hexsz;
1135 if (!merge_names)
1136 merge_names = &fetch_head_file;
1138 filename = git_path_fetch_head(the_repository);
1139 fd = open(filename, O_RDONLY);
1140 if (fd < 0)
1141 die_errno(_("could not open '%s' for reading"), filename);
1143 if (strbuf_read(merge_names, fd, 0) < 0)
1144 die_errno(_("could not read '%s'"), filename);
1145 if (close(fd) < 0)
1146 die_errno(_("could not close '%s'"), filename);
1148 for (pos = 0; pos < merge_names->len; pos = npos) {
1149 struct object_id oid;
1150 char *ptr;
1151 struct commit *commit;
1153 ptr = strchr(merge_names->buf + pos, '\n');
1154 if (ptr)
1155 npos = ptr - merge_names->buf + 1;
1156 else
1157 npos = merge_names->len;
1159 if (npos - pos < hexsz + 2 ||
1160 get_oid_hex(merge_names->buf + pos, &oid))
1161 commit = NULL; /* bad */
1162 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1163 continue; /* not-for-merge */
1164 else {
1165 char saved = merge_names->buf[pos + hexsz];
1166 merge_names->buf[pos + hexsz] = '\0';
1167 commit = get_merge_parent(merge_names->buf + pos);
1168 merge_names->buf[pos + hexsz] = saved;
1170 if (!commit) {
1171 if (ptr)
1172 *ptr = '\0';
1173 die(_("not something we can merge in %s: %s"),
1174 filename, merge_names->buf + pos);
1176 remotes = &commit_list_insert(commit, remotes)->next;
1179 if (merge_names == &fetch_head_file)
1180 strbuf_release(&fetch_head_file);
1183 static struct commit_list *collect_parents(struct commit *head_commit,
1184 int *head_subsumed,
1185 int argc, const char **argv,
1186 struct strbuf *merge_msg)
1188 int i;
1189 struct commit_list *remoteheads = NULL;
1190 struct commit_list **remotes = &remoteheads;
1191 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1193 if (merge_msg && (!have_message || shortlog_len))
1194 autogen = &merge_names;
1196 if (head_commit)
1197 remotes = &commit_list_insert(head_commit, remotes)->next;
1199 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1200 handle_fetch_head(remotes, autogen);
1201 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1202 } else {
1203 for (i = 0; i < argc; i++) {
1204 struct commit *commit = get_merge_parent(argv[i]);
1205 if (!commit)
1206 help_unknown_ref(argv[i], "merge",
1207 _("not something we can merge"));
1208 remotes = &commit_list_insert(commit, remotes)->next;
1210 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1211 if (autogen) {
1212 struct commit_list *p;
1213 for (p = remoteheads; p; p = p->next)
1214 merge_name(merge_remote_util(p->item)->name, autogen);
1218 if (autogen) {
1219 prepare_merge_message(autogen, merge_msg);
1220 strbuf_release(autogen);
1223 return remoteheads;
1226 static int merging_a_throwaway_tag(struct commit *commit)
1228 char *tag_ref;
1229 struct object_id oid;
1230 int is_throwaway_tag = 0;
1232 /* Are we merging a tag? */
1233 if (!merge_remote_util(commit) ||
1234 !merge_remote_util(commit)->obj ||
1235 merge_remote_util(commit)->obj->type != OBJ_TAG)
1236 return is_throwaway_tag;
1239 * Now we know we are merging a tag object. Are we downstream
1240 * and following the tags from upstream? If so, we must have
1241 * the tag object pointed at by "refs/tags/$T" where $T is the
1242 * tagname recorded in the tag object. We want to allow such
1243 * a "just to catch up" merge to fast-forward.
1245 * Otherwise, we are playing an integrator's role, making a
1246 * merge with a throw-away tag from a contributor with
1247 * something like "git pull $contributor $signed_tag".
1248 * We want to forbid such a merge from fast-forwarding
1249 * by default; otherwise we would not keep the signature
1250 * anywhere.
1252 tag_ref = xstrfmt("refs/tags/%s",
1253 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1254 if (!read_ref(tag_ref, &oid) &&
1255 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1256 is_throwaway_tag = 0;
1257 else
1258 is_throwaway_tag = 1;
1259 free(tag_ref);
1260 return is_throwaway_tag;
1263 int cmd_merge(int argc, const char **argv, const char *prefix)
1265 struct object_id result_tree, stash, head_oid;
1266 struct commit *head_commit;
1267 struct strbuf buf = STRBUF_INIT;
1268 int i, ret = 0, head_subsumed;
1269 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1270 struct commit_list *common = NULL;
1271 const char *best_strategy = NULL, *wt_strategy = NULL;
1272 struct commit_list *remoteheads, *p;
1273 void *branch_to_free;
1274 int orig_argc = argc;
1276 if (argc == 2 && !strcmp(argv[1], "-h"))
1277 usage_with_options(builtin_merge_usage, builtin_merge_options);
1280 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1281 * current branch.
1283 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1284 if (branch)
1285 skip_prefix(branch, "refs/heads/", &branch);
1287 if (!pull_twohead) {
1288 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1289 if (default_strategy && !strcmp(default_strategy, "ort"))
1290 pull_twohead = "ort";
1293 init_diff_ui_defaults();
1294 git_config(git_merge_config, NULL);
1296 if (!branch || is_null_oid(&head_oid))
1297 head_commit = NULL;
1298 else
1299 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1301 if (branch_mergeoptions)
1302 parse_branch_merge_options(branch_mergeoptions);
1303 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1304 builtin_merge_usage, 0);
1305 if (shortlog_len < 0)
1306 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1308 if (verbosity < 0 && show_progress == -1)
1309 show_progress = 0;
1311 if (abort_current_merge) {
1312 int nargc = 2;
1313 const char *nargv[] = {"reset", "--merge", NULL};
1314 struct strbuf stash_oid = STRBUF_INIT;
1316 if (orig_argc != 2)
1317 usage_msg_opt(_("--abort expects no arguments"),
1318 builtin_merge_usage, builtin_merge_options);
1320 if (!file_exists(git_path_merge_head(the_repository)))
1321 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1323 if (read_oneliner(&stash_oid, git_path_merge_autostash(the_repository),
1324 READ_ONELINER_SKIP_IF_EMPTY))
1325 unlink(git_path_merge_autostash(the_repository));
1327 /* Invoke 'git reset --merge' */
1328 ret = cmd_reset(nargc, nargv, prefix);
1330 if (stash_oid.len)
1331 apply_autostash_oid(stash_oid.buf);
1333 strbuf_release(&stash_oid);
1334 goto done;
1337 if (quit_current_merge) {
1338 if (orig_argc != 2)
1339 usage_msg_opt(_("--quit expects no arguments"),
1340 builtin_merge_usage,
1341 builtin_merge_options);
1343 remove_merge_branch_state(the_repository);
1344 goto done;
1347 if (continue_current_merge) {
1348 int nargc = 1;
1349 const char *nargv[] = {"commit", NULL};
1351 if (orig_argc != 2)
1352 usage_msg_opt(_("--continue expects no arguments"),
1353 builtin_merge_usage, builtin_merge_options);
1355 if (!file_exists(git_path_merge_head(the_repository)))
1356 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1358 /* Invoke 'git commit' */
1359 ret = cmd_commit(nargc, nargv, prefix);
1360 goto done;
1363 if (read_cache_unmerged())
1364 die_resolve_conflict("merge");
1366 if (file_exists(git_path_merge_head(the_repository))) {
1368 * There is no unmerged entry, don't advise 'git
1369 * add/rm <file>', just 'git commit'.
1371 if (advice_resolve_conflict)
1372 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1373 "Please, commit your changes before you merge."));
1374 else
1375 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1377 if (ref_exists("CHERRY_PICK_HEAD")) {
1378 if (advice_resolve_conflict)
1379 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1380 "Please, commit your changes before you merge."));
1381 else
1382 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1384 resolve_undo_clear();
1386 if (option_edit < 0)
1387 option_edit = default_edit_option();
1389 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1391 if (verbosity < 0)
1392 show_diffstat = 0;
1394 if (squash) {
1395 if (fast_forward == FF_NO)
1396 die(_("You cannot combine --squash with --no-ff."));
1397 if (option_commit > 0)
1398 die(_("You cannot combine --squash with --commit."));
1400 * squash can now silently disable option_commit - this is not
1401 * a problem as it is only overriding the default, not a user
1402 * supplied option.
1404 option_commit = 0;
1407 if (option_commit < 0)
1408 option_commit = 1;
1410 if (!argc) {
1411 if (default_to_upstream)
1412 argc = setup_with_upstream(&argv);
1413 else
1414 die(_("No commit specified and merge.defaultToUpstream not set."));
1415 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1416 argv[0] = "@{-1}";
1419 if (!argc)
1420 usage_with_options(builtin_merge_usage,
1421 builtin_merge_options);
1423 if (!head_commit) {
1425 * If the merged head is a valid one there is no reason
1426 * to forbid "git merge" into a branch yet to be born.
1427 * We do the same for "git pull".
1429 struct object_id *remote_head_oid;
1430 if (squash)
1431 die(_("Squash commit into empty head not supported yet"));
1432 if (fast_forward == FF_NO)
1433 die(_("Non-fast-forward commit does not make sense into "
1434 "an empty head"));
1435 remoteheads = collect_parents(head_commit, &head_subsumed,
1436 argc, argv, NULL);
1437 if (!remoteheads)
1438 die(_("%s - not something we can merge"), argv[0]);
1439 if (remoteheads->next)
1440 die(_("Can merge only exactly one commit into empty head"));
1442 if (verify_signatures)
1443 verify_merge_signature(remoteheads->item, verbosity,
1444 check_trust_level);
1446 remote_head_oid = &remoteheads->item->object.oid;
1447 read_empty(remote_head_oid, 0);
1448 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1449 UPDATE_REFS_DIE_ON_ERR);
1450 goto done;
1454 * All the rest are the commits being merged; prepare
1455 * the standard merge summary message to be appended
1456 * to the given message.
1458 remoteheads = collect_parents(head_commit, &head_subsumed,
1459 argc, argv, &merge_msg);
1461 if (!head_commit || !argc)
1462 usage_with_options(builtin_merge_usage,
1463 builtin_merge_options);
1465 if (verify_signatures) {
1466 for (p = remoteheads; p; p = p->next) {
1467 verify_merge_signature(p->item, verbosity,
1468 check_trust_level);
1472 strbuf_addstr(&buf, "merge");
1473 for (p = remoteheads; p; p = p->next)
1474 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1475 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1476 strbuf_reset(&buf);
1478 for (p = remoteheads; p; p = p->next) {
1479 struct commit *commit = p->item;
1480 strbuf_addf(&buf, "GITHEAD_%s",
1481 oid_to_hex(&commit->object.oid));
1482 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1483 strbuf_reset(&buf);
1484 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1485 fast_forward = FF_NO;
1488 if (!use_strategies) {
1489 if (!remoteheads)
1490 ; /* already up-to-date */
1491 else if (!remoteheads->next)
1492 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1493 else
1494 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1497 for (i = 0; i < use_strategies_nr; i++) {
1498 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1499 fast_forward = FF_NO;
1500 if (use_strategies[i]->attr & NO_TRIVIAL)
1501 allow_trivial = 0;
1504 if (!remoteheads)
1505 ; /* already up-to-date */
1506 else if (!remoteheads->next)
1507 common = get_merge_bases(head_commit, remoteheads->item);
1508 else {
1509 struct commit_list *list = remoteheads;
1510 commit_list_insert(head_commit, &list);
1511 common = get_octopus_merge_bases(list);
1512 free(list);
1515 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1516 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1518 if (remoteheads && !common) {
1519 /* No common ancestors found. */
1520 if (!allow_unrelated_histories)
1521 die(_("refusing to merge unrelated histories"));
1522 /* otherwise, we need a real merge. */
1523 } else if (!remoteheads ||
1524 (!remoteheads->next && !common->next &&
1525 common->item == remoteheads->item)) {
1527 * If head can reach all the merge then we are up to date.
1528 * but first the most common case of merging one remote.
1530 finish_up_to_date();
1531 goto done;
1532 } else if (fast_forward != FF_NO && !remoteheads->next &&
1533 !common->next &&
1534 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1535 /* Again the most common case of merging one remote. */
1536 struct strbuf msg = STRBUF_INIT;
1537 struct commit *commit;
1539 if (verbosity >= 0) {
1540 printf(_("Updating %s..%s\n"),
1541 find_unique_abbrev(&head_commit->object.oid,
1542 DEFAULT_ABBREV),
1543 find_unique_abbrev(&remoteheads->item->object.oid,
1544 DEFAULT_ABBREV));
1546 strbuf_addstr(&msg, "Fast-forward");
1547 if (have_message)
1548 strbuf_addstr(&msg,
1549 " (no commit created; -m option ignored)");
1550 commit = remoteheads->item;
1551 if (!commit) {
1552 ret = 1;
1553 goto done;
1556 if (autostash)
1557 create_autostash(the_repository,
1558 git_path_merge_autostash(the_repository),
1559 "merge");
1560 if (checkout_fast_forward(the_repository,
1561 &head_commit->object.oid,
1562 &commit->object.oid,
1563 overwrite_ignore)) {
1564 apply_autostash(git_path_merge_autostash(the_repository));
1565 ret = 1;
1566 goto done;
1569 finish(head_commit, remoteheads, &commit->object.oid, msg.buf);
1570 remove_merge_branch_state(the_repository);
1571 goto done;
1572 } else if (!remoteheads->next && common->next)
1575 * We are not doing octopus and not fast-forward. Need
1576 * a real merge.
1578 else if (!remoteheads->next && !common->next && option_commit) {
1580 * We are not doing octopus, not fast-forward, and have
1581 * only one common.
1583 refresh_cache(REFRESH_QUIET);
1584 if (allow_trivial && fast_forward != FF_ONLY) {
1585 /* See if it is really trivial. */
1586 git_committer_info(IDENT_STRICT);
1587 printf(_("Trying really trivial in-index merge...\n"));
1588 if (!read_tree_trivial(&common->item->object.oid,
1589 &head_commit->object.oid,
1590 &remoteheads->item->object.oid)) {
1591 ret = merge_trivial(head_commit, remoteheads);
1592 goto done;
1594 printf(_("Nope.\n"));
1596 } else {
1598 * An octopus. If we can reach all the remote we are up
1599 * to date.
1601 int up_to_date = 1;
1602 struct commit_list *j;
1604 for (j = remoteheads; j; j = j->next) {
1605 struct commit_list *common_one;
1608 * Here we *have* to calculate the individual
1609 * merge_bases again, otherwise "git merge HEAD^
1610 * HEAD^^" would be missed.
1612 common_one = get_merge_bases(head_commit, j->item);
1613 if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1614 up_to_date = 0;
1615 break;
1618 if (up_to_date) {
1619 finish_up_to_date();
1620 goto done;
1624 if (fast_forward == FF_ONLY)
1625 die(_("Not possible to fast-forward, aborting."));
1627 if (autostash)
1628 create_autostash(the_repository,
1629 git_path_merge_autostash(the_repository),
1630 "merge");
1632 /* We are going to make a new commit. */
1633 git_committer_info(IDENT_STRICT);
1636 * At this point, we need a real merge. No matter what strategy
1637 * we use, it would operate on the index, possibly affecting the
1638 * working tree, and when resolved cleanly, have the desired
1639 * tree in the index -- this means that the index must be in
1640 * sync with the head commit. The strategies are responsible
1641 * to ensure this.
1643 if (use_strategies_nr == 1 ||
1645 * Stash away the local changes so that we can try more than one.
1647 save_state(&stash))
1648 oidclr(&stash);
1650 for (i = 0; !merge_was_ok && i < use_strategies_nr; i++) {
1651 int ret, cnt;
1652 if (i) {
1653 printf(_("Rewinding the tree to pristine...\n"));
1654 restore_state(&head_commit->object.oid, &stash);
1656 if (use_strategies_nr != 1)
1657 printf(_("Trying merge strategy %s...\n"),
1658 use_strategies[i]->name);
1660 * Remember which strategy left the state in the working
1661 * tree.
1663 wt_strategy = use_strategies[i]->name;
1665 ret = try_merge_strategy(use_strategies[i]->name,
1666 common, remoteheads,
1667 head_commit);
1669 * The backend exits with 1 when conflicts are
1670 * left to be resolved, with 2 when it does not
1671 * handle the given merge at all.
1673 if (ret < 2) {
1674 if (!ret) {
1675 if (option_commit) {
1676 /* Automerge succeeded. */
1677 automerge_was_ok = 1;
1678 break;
1680 merge_was_ok = 1;
1682 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1683 if (best_cnt <= 0 || cnt <= best_cnt) {
1684 best_strategy = use_strategies[i]->name;
1685 best_cnt = cnt;
1691 * If we have a resulting tree, that means the strategy module
1692 * auto resolved the merge cleanly.
1694 if (automerge_was_ok) {
1695 ret = finish_automerge(head_commit, head_subsumed,
1696 common, remoteheads,
1697 &result_tree, wt_strategy);
1698 goto done;
1702 * Pick the result from the best strategy and have the user fix
1703 * it up.
1705 if (!best_strategy) {
1706 restore_state(&head_commit->object.oid, &stash);
1707 if (use_strategies_nr > 1)
1708 fprintf(stderr,
1709 _("No merge strategy handled the merge.\n"));
1710 else
1711 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1712 use_strategies[0]->name);
1713 apply_autostash(git_path_merge_autostash(the_repository));
1714 ret = 2;
1715 goto done;
1716 } else if (best_strategy == wt_strategy)
1717 ; /* We already have its result in the working tree. */
1718 else {
1719 printf(_("Rewinding the tree to pristine...\n"));
1720 restore_state(&head_commit->object.oid, &stash);
1721 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1722 best_strategy);
1723 try_merge_strategy(best_strategy, common, remoteheads,
1724 head_commit);
1727 if (squash) {
1728 finish(head_commit, remoteheads, NULL, NULL);
1730 git_test_write_commit_graph_or_die();
1731 } else
1732 write_merge_state(remoteheads);
1734 if (merge_was_ok)
1735 fprintf(stderr, _("Automatic merge went well; "
1736 "stopped before committing as requested\n"));
1737 else
1738 ret = suggest_conflicts();
1740 done:
1741 free(branch_to_free);
1742 return ret;