]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/merge.c
18b22c0a26d6337a7c68075326c2367f5cfe5986
[thirdparty/git.git] / builtin / merge.c
1 /*
2 * Builtin "git merge"
3 *
4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
5 *
6 * Based on git-merge.sh by Junio C Hamano.
7 */
8
9 #define USE_THE_REPOSITORY_VARIABLE
10 #define DISABLE_SIGN_COMPARE_WARNINGS
11
12 #include "builtin.h"
13
14 #include "abspath.h"
15 #include "advice.h"
16 #include "config.h"
17 #include "editor.h"
18 #include "environment.h"
19 #include "gettext.h"
20 #include "hex.h"
21 #include "object-name.h"
22 #include "parse-options.h"
23 #include "lockfile.h"
24 #include "repository.h"
25 #include "run-command.h"
26 #include "hook.h"
27 #include "diff.h"
28 #include "diff-merges.h"
29 #include "refs.h"
30 #include "refspec.h"
31 #include "commit.h"
32 #include "diffcore.h"
33 #include "path.h"
34 #include "revision.h"
35 #include "unpack-trees.h"
36 #include "cache-tree.h"
37 #include "dir.h"
38 #include "color.h"
39 #include "rerere.h"
40 #include "help.h"
41 #include "merge.h"
42 #include "merge-ort-wrappers.h"
43 #include "resolve-undo.h"
44 #include "remote.h"
45 #include "fmt-merge-msg.h"
46 #include "sequencer.h"
47 #include "string-list.h"
48 #include "tag.h"
49 #include "alias.h"
50 #include "branch.h"
51 #include "commit-reach.h"
52 #include "wt-status.h"
53 #include "commit-graph.h"
54
55 #define DEFAULT_TWOHEAD (1<<0)
56 #define DEFAULT_OCTOPUS (1<<1)
57 #define NO_FAST_FORWARD (1<<2)
58 #define NO_TRIVIAL (1<<3)
59
60 struct strategy {
61 const char *name;
62 unsigned attr;
63 };
64
65 static const char * const builtin_merge_usage[] = {
66 N_("git merge [<options>] [<commit>...]"),
67 "git merge --abort",
68 "git merge --continue",
69 NULL
70 };
71
72 #define MERGE_SHOW_DIFFSTAT 1
73 #define MERGE_SHOW_COMPACTSUMMARY 2
74
75 static int show_diffstat = MERGE_SHOW_DIFFSTAT, shortlog_len = -1, squash;
76 static int option_commit = -1;
77 static int option_edit = -1;
78 static int allow_trivial = 1, have_message, verify_signatures;
79 static int check_trust_level = 1;
80 static int overwrite_ignore = 1;
81 static struct strbuf merge_msg = STRBUF_INIT;
82 static struct strategy **use_strategies;
83 static size_t use_strategies_nr, use_strategies_alloc;
84 static struct strvec xopts = STRVEC_INIT;
85 static const char *branch;
86 static char *branch_mergeoptions;
87 static int verbosity;
88 static int allow_rerere_auto;
89 static int abort_current_merge;
90 static int quit_current_merge;
91 static int continue_current_merge;
92 static int allow_unrelated_histories;
93 static int show_progress = -1;
94 static int default_to_upstream = 1;
95 static int signoff;
96 static const char *sign_commit;
97 static int autostash;
98 static int no_verify;
99 static char *into_name;
100
101 static struct strategy all_strategy[] = {
102 { "recursive", NO_TRIVIAL },
103 { "octopus", DEFAULT_OCTOPUS },
104 { "ort", DEFAULT_TWOHEAD | NO_TRIVIAL },
105 { "resolve", 0 },
106 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
107 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
108 };
109
110 static char *pull_twohead, *pull_octopus;
111
112 enum ff_type {
113 FF_NO,
114 FF_ALLOW,
115 FF_ONLY
116 };
117
118 static enum ff_type fast_forward = FF_ALLOW;
119
120 static char *cleanup_arg;
121 static enum commit_msg_cleanup_mode cleanup_mode;
122
123 static int option_parse_message(const struct option *opt,
124 const char *arg, int unset)
125 {
126 struct strbuf *buf = opt->value;
127
128 if (unset)
129 strbuf_setlen(buf, 0);
130 else if (arg) {
131 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
132 have_message = 1;
133 } else
134 return error(_("switch `m' requires a value"));
135 return 0;
136 }
137
138 static enum parse_opt_result option_read_message(struct parse_opt_ctx_t *ctx,
139 const struct option *opt,
140 const char *arg_not_used,
141 int unset)
142 {
143 struct strbuf *buf = opt->value;
144 const char *arg;
145
146 BUG_ON_OPT_ARG(arg_not_used);
147 if (unset)
148 BUG("-F cannot be negated");
149
150 if (ctx->opt) {
151 arg = ctx->opt;
152 ctx->opt = NULL;
153 } else if (ctx->argc > 1) {
154 ctx->argc--;
155 arg = *++ctx->argv;
156 } else
157 return error(_("option `%s' requires a value"), opt->long_name);
158
159 if (buf->len)
160 strbuf_addch(buf, '\n');
161 if (ctx->prefix && !is_absolute_path(arg))
162 arg = prefix_filename(ctx->prefix, arg);
163 if (strbuf_read_file(buf, arg, 0) < 0)
164 return error(_("could not read file '%s'"), arg);
165 have_message = 1;
166
167 return 0;
168 }
169
170 static struct strategy *get_strategy(const char *name)
171 {
172 int i;
173 struct strategy *ret;
174 static struct cmdnames main_cmds = {0}, other_cmds = {0};
175 static int loaded;
176 char *default_strategy = NULL;
177
178 if (!name)
179 return NULL;
180
181 if (default_strategy &&
182 !strcmp(default_strategy, "ort") &&
183 !strcmp(name, "recursive")) {
184 name = "ort";
185 }
186
187 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
188 if (!strcmp(name, all_strategy[i].name))
189 return &all_strategy[i];
190
191 if (!loaded) {
192 struct cmdnames not_strategies = {0};
193 loaded = 1;
194
195 load_command_list("git-merge-", &main_cmds, &other_cmds);
196 for (i = 0; i < main_cmds.cnt; i++) {
197 int j, found = 0;
198 struct cmdname *ent = main_cmds.names[i];
199 for (j = 0; !found && j < ARRAY_SIZE(all_strategy); j++)
200 if (!xstrncmpz(all_strategy[j].name, ent->name, ent->len))
201 found = 1;
202 if (!found)
203 add_cmdname(&not_strategies, ent->name, ent->len);
204 }
205 exclude_cmds(&main_cmds, &not_strategies);
206
207 cmdnames_release(&not_strategies);
208 }
209 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
210 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
211 fprintf(stderr, _("Available strategies are:"));
212 for (i = 0; i < main_cmds.cnt; i++)
213 fprintf(stderr, " %s", main_cmds.names[i]->name);
214 fprintf(stderr, ".\n");
215 if (other_cmds.cnt) {
216 fprintf(stderr, _("Available custom strategies are:"));
217 for (i = 0; i < other_cmds.cnt; i++)
218 fprintf(stderr, " %s", other_cmds.names[i]->name);
219 fprintf(stderr, ".\n");
220 }
221 exit(1);
222 }
223
224 CALLOC_ARRAY(ret, 1);
225 ret->name = xstrdup(name);
226 ret->attr = NO_TRIVIAL;
227
228 cmdnames_release(&main_cmds);
229 cmdnames_release(&other_cmds);
230 return ret;
231 }
232
233 static void append_strategy(struct strategy *s)
234 {
235 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
236 use_strategies[use_strategies_nr++] = s;
237 }
238
239 static int option_parse_strategy(const struct option *opt UNUSED,
240 const char *name, int unset)
241 {
242 if (unset)
243 return 0;
244
245 append_strategy(get_strategy(name));
246 return 0;
247 }
248
249 static int option_parse_compact_summary(const struct option *opt,
250 const char *name UNUSED, int unset)
251 {
252 int *setting = opt->value;
253
254 if (unset)
255 *setting = 0;
256 else
257 *setting = MERGE_SHOW_COMPACTSUMMARY;
258 return 0;
259 }
260
261 static struct option builtin_merge_options[] = {
262 OPT_SET_INT('n', NULL, &show_diffstat,
263 N_("do not show a diffstat at the end of the merge"), 0),
264 OPT_BOOL(0, "stat", &show_diffstat,
265 N_("show a diffstat at the end of the merge")),
266 OPT_BOOL(0, "summary", &show_diffstat, N_("(synonym to --stat)")),
267 OPT_CALLBACK_F(0, "compact-summary", &show_diffstat, N_("compact-summary"),
268 N_("show a compact-summary at the end of the merge"),
269 PARSE_OPT_NOARG,
270 option_parse_compact_summary),
271 {
272 .type = OPTION_INTEGER,
273 .long_name = "log",
274 .value = &shortlog_len,
275 .precision = sizeof(shortlog_len),
276 .argh = N_("n"),
277 .help = N_("add (at most <n>) entries from shortlog to merge commit message"),
278 .flags = PARSE_OPT_OPTARG,
279 .defval = DEFAULT_MERGE_LOG_LEN,
280 },
281 OPT_BOOL(0, "squash", &squash,
282 N_("create a single commit instead of doing a merge")),
283 OPT_BOOL(0, "commit", &option_commit,
284 N_("perform a commit if the merge succeeds (default)")),
285 OPT_BOOL('e', "edit", &option_edit,
286 N_("edit message before committing")),
287 OPT_CLEANUP(&cleanup_arg),
288 OPT_SET_INT(0, "ff", &fast_forward, N_("allow fast-forward (default)"), FF_ALLOW),
289 OPT_SET_INT_F(0, "ff-only", &fast_forward,
290 N_("abort if fast-forward is not possible"),
291 FF_ONLY, PARSE_OPT_NONEG),
292 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
293 OPT_BOOL(0, "verify-signatures", &verify_signatures,
294 N_("verify that the named commit has a valid GPG signature")),
295 OPT_CALLBACK('s', "strategy", NULL, N_("strategy"),
296 N_("merge strategy to use"), option_parse_strategy),
297 OPT_STRVEC('X', "strategy-option", &xopts, N_("option=value"),
298 N_("option for selected merge strategy")),
299 OPT_CALLBACK('m', "message", &merge_msg, N_("message"),
300 N_("merge commit message (for a non-fast-forward merge)"),
301 option_parse_message),
302 {
303 .type = OPTION_LOWLEVEL_CALLBACK,
304 .short_name = 'F',
305 .long_name = "file",
306 .value = &merge_msg,
307 .argh = N_("path"),
308 .help = N_("read message from file"),
309 .flags = PARSE_OPT_NONEG,
310 .ll_callback = option_read_message,
311 },
312 OPT_STRING(0, "into-name", &into_name, N_("name"),
313 N_("use <name> instead of the real target")),
314 OPT__VERBOSITY(&verbosity),
315 OPT_BOOL(0, "abort", &abort_current_merge,
316 N_("abort the current in-progress merge")),
317 OPT_BOOL(0, "quit", &quit_current_merge,
318 N_("--abort but leave index and working tree alone")),
319 OPT_BOOL(0, "continue", &continue_current_merge,
320 N_("continue the current in-progress merge")),
321 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories,
322 N_("allow merging unrelated histories")),
323 OPT_SET_INT(0, "progress", &show_progress, N_("force progress reporting"), 1),
324 {
325 .type = OPTION_STRING,
326 .short_name = 'S',
327 .long_name = "gpg-sign",
328 .value = &sign_commit,
329 .argh = N_("key-id"),
330 .help = N_("GPG sign commit"),
331 .flags = PARSE_OPT_OPTARG,
332 .defval = (intptr_t) "",
333 },
334 OPT_AUTOSTASH(&autostash),
335 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore, N_("update ignored files (default)")),
336 OPT_BOOL(0, "signoff", &signoff, N_("add a Signed-off-by trailer")),
337 OPT_BOOL(0, "no-verify", &no_verify, N_("bypass pre-merge-commit and commit-msg hooks")),
338 OPT_END()
339 };
340
341 static int save_state(struct object_id *stash)
342 {
343 int len;
344 struct child_process cp = CHILD_PROCESS_INIT;
345 struct strbuf buffer = STRBUF_INIT;
346 struct lock_file lock_file = LOCK_INIT;
347 int fd;
348 int rc = -1;
349
350 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
351 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
352 if (0 <= fd)
353 repo_update_index_if_able(the_repository, &lock_file);
354 rollback_lock_file(&lock_file);
355
356 strvec_pushl(&cp.args, "stash", "create", NULL);
357 cp.out = -1;
358 cp.git_cmd = 1;
359
360 if (start_command(&cp))
361 die(_("could not run stash."));
362 len = strbuf_read(&buffer, cp.out, 1024);
363 close(cp.out);
364
365 if (finish_command(&cp) || len < 0)
366 die(_("stash failed"));
367 else if (!len) /* no changes */
368 goto out;
369 strbuf_setlen(&buffer, buffer.len-1);
370 if (repo_get_oid(the_repository, buffer.buf, stash))
371 die(_("not a valid object: %s"), buffer.buf);
372 rc = 0;
373 out:
374 strbuf_release(&buffer);
375 return rc;
376 }
377
378 static void read_empty(const struct object_id *oid)
379 {
380 struct child_process cmd = CHILD_PROCESS_INIT;
381
382 strvec_pushl(&cmd.args, "read-tree", "-m", "-u",
383 empty_tree_oid_hex(the_repository->hash_algo),
384 oid_to_hex(oid), NULL);
385 cmd.git_cmd = 1;
386
387 if (run_command(&cmd))
388 die(_("read-tree failed"));
389 }
390
391 static void reset_hard(const struct object_id *oid)
392 {
393 struct child_process cmd = CHILD_PROCESS_INIT;
394
395 strvec_pushl(&cmd.args, "read-tree", "-v", "--reset", "-u",
396 oid_to_hex(oid), NULL);
397 cmd.git_cmd = 1;
398
399 if (run_command(&cmd))
400 die(_("read-tree failed"));
401 }
402
403 static void restore_state(const struct object_id *head,
404 const struct object_id *stash)
405 {
406 struct child_process cmd = CHILD_PROCESS_INIT;
407
408 reset_hard(head);
409
410 if (is_null_oid(stash))
411 goto refresh_cache;
412
413 strvec_pushl(&cmd.args, "stash", "apply", "--index", "--quiet", NULL);
414 strvec_push(&cmd.args, oid_to_hex(stash));
415
416 /*
417 * It is OK to ignore error here, for example when there was
418 * nothing to restore.
419 */
420 cmd.git_cmd = 1;
421 run_command(&cmd);
422
423 refresh_cache:
424 discard_index(the_repository->index);
425 if (repo_read_index(the_repository) < 0)
426 die(_("could not read index"));
427 }
428
429 /* This is called when no merge was necessary. */
430 static void finish_up_to_date(void)
431 {
432 if (verbosity >= 0) {
433 if (squash)
434 puts(_("Already up to date. (nothing to squash)"));
435 else
436 puts(_("Already up to date."));
437 }
438 remove_merge_branch_state(the_repository);
439 }
440
441 static void squash_message(struct commit *commit, struct commit_list *remoteheads)
442 {
443 struct rev_info rev;
444 struct strbuf out = STRBUF_INIT;
445 struct commit_list *j;
446 struct pretty_print_context ctx = {0};
447
448 printf(_("Squash commit -- not updating HEAD\n"));
449
450 repo_init_revisions(the_repository, &rev, NULL);
451 diff_merges_suppress(&rev);
452 rev.commit_format = CMIT_FMT_MEDIUM;
453
454 commit->object.flags |= UNINTERESTING;
455 add_pending_object(&rev, &commit->object, NULL);
456
457 for (j = remoteheads; j; j = j->next)
458 add_pending_object(&rev, &j->item->object, NULL);
459
460 setup_revisions(0, NULL, &rev, NULL);
461 if (prepare_revision_walk(&rev))
462 die(_("revision walk setup failed"));
463
464 ctx.abbrev = rev.abbrev;
465 ctx.date_mode = rev.date_mode;
466 ctx.fmt = rev.commit_format;
467
468 strbuf_addstr(&out, "Squashed commit of the following:\n");
469 while ((commit = get_revision(&rev)) != NULL) {
470 strbuf_addch(&out, '\n');
471 strbuf_addf(&out, "commit %s\n",
472 oid_to_hex(&commit->object.oid));
473 pretty_print_commit(&ctx, commit, &out);
474 }
475 write_file_buf(git_path_squash_msg(the_repository), out.buf, out.len);
476 strbuf_release(&out);
477 release_revisions(&rev);
478 }
479
480 static void finish(struct commit *head_commit,
481 struct commit_list *remoteheads,
482 const struct object_id *new_head, const char *msg)
483 {
484 struct strbuf reflog_message = STRBUF_INIT;
485 const struct object_id *head = &head_commit->object.oid;
486
487 if (!msg)
488 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
489 else {
490 if (verbosity >= 0)
491 printf("%s\n", msg);
492 strbuf_addf(&reflog_message, "%s: %s",
493 getenv("GIT_REFLOG_ACTION"), msg);
494 }
495 if (squash) {
496 squash_message(head_commit, remoteheads);
497 } else {
498 if (verbosity >= 0 && !merge_msg.len)
499 printf(_("No merge message -- not updating HEAD\n"));
500 else {
501 refs_update_ref(get_main_ref_store(the_repository),
502 reflog_message.buf, "HEAD", new_head,
503 head,
504 0, UPDATE_REFS_DIE_ON_ERR);
505 /*
506 * We ignore errors in 'gc --auto', since the
507 * user should see them.
508 */
509 run_auto_maintenance(verbosity < 0);
510 }
511 }
512 if (new_head && show_diffstat) {
513 struct diff_options opts;
514 repo_diff_setup(the_repository, &opts);
515 init_diffstat_widths(&opts);
516
517 switch (show_diffstat) {
518 case MERGE_SHOW_DIFFSTAT: /* 1 */
519 opts.output_format |=
520 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
521 break;
522 case MERGE_SHOW_COMPACTSUMMARY: /* 2 */
523 opts.output_format |= DIFF_FORMAT_DIFFSTAT;
524 opts.flags.stat_with_summary = 1;
525 break;
526 default:
527 break;
528 }
529 opts.detect_rename = DIFF_DETECT_RENAME;
530 diff_setup_done(&opts);
531 diff_tree_oid(head, new_head, "", &opts);
532 diffcore_std(&opts);
533 diff_flush(&opts);
534 }
535
536 /* Run a post-merge hook */
537 run_hooks_l(the_repository, "post-merge", squash ? "1" : "0", NULL);
538
539 if (new_head)
540 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
541 strbuf_release(&reflog_message);
542 }
543
544 /* Get the name for the merge commit's message. */
545 static void merge_name(const char *remote, struct strbuf *msg)
546 {
547 struct commit *remote_head;
548 struct object_id branch_head;
549 struct strbuf bname = STRBUF_INIT;
550 struct merge_remote_desc *desc;
551 const char *ptr;
552 char *found_ref = NULL;
553 int len, early;
554
555 copy_branchname(&bname, remote, 0);
556 remote = bname.buf;
557
558 oidclr(&branch_head, the_repository->hash_algo);
559 remote_head = get_merge_parent(remote);
560 if (!remote_head)
561 die(_("'%s' does not point to a commit"), remote);
562
563 if (repo_dwim_ref(the_repository, remote, strlen(remote), &branch_head,
564 &found_ref, 0) > 0) {
565 if (starts_with(found_ref, "refs/heads/")) {
566 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
567 oid_to_hex(&branch_head), remote);
568 goto cleanup;
569 }
570 if (starts_with(found_ref, "refs/tags/")) {
571 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
572 oid_to_hex(&branch_head), remote);
573 goto cleanup;
574 }
575 if (starts_with(found_ref, "refs/remotes/")) {
576 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
577 oid_to_hex(&branch_head), remote);
578 goto cleanup;
579 }
580 }
581
582 /* See if remote matches <name>^^^.. or <name>~<number> */
583 for (len = 0, ptr = remote + strlen(remote);
584 remote < ptr && ptr[-1] == '^';
585 ptr--)
586 len++;
587 if (len)
588 early = 1;
589 else {
590 early = 0;
591 ptr = strrchr(remote, '~');
592 if (ptr) {
593 int seen_nonzero = 0;
594
595 len++; /* count ~ */
596 while (*++ptr && isdigit(*ptr)) {
597 seen_nonzero |= (*ptr != '0');
598 len++;
599 }
600 if (*ptr)
601 len = 0; /* not ...~<number> */
602 else if (seen_nonzero)
603 early = 1;
604 else if (len == 1)
605 early = 1; /* "name~" is "name~1"! */
606 }
607 }
608 if (len) {
609 struct strbuf truname = STRBUF_INIT;
610 strbuf_addf(&truname, "refs/heads/%s", remote);
611 strbuf_setlen(&truname, truname.len - len);
612 if (refs_ref_exists(get_main_ref_store(the_repository), truname.buf)) {
613 strbuf_addf(msg,
614 "%s\t\tbranch '%s'%s of .\n",
615 oid_to_hex(&remote_head->object.oid),
616 truname.buf + 11,
617 (early ? " (early part)" : ""));
618 strbuf_release(&truname);
619 goto cleanup;
620 }
621 strbuf_release(&truname);
622 }
623
624 desc = merge_remote_util(remote_head);
625 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
626 strbuf_addf(msg, "%s\t\t%s '%s'\n",
627 oid_to_hex(&desc->obj->oid),
628 type_name(desc->obj->type),
629 remote);
630 goto cleanup;
631 }
632
633 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
634 oid_to_hex(&remote_head->object.oid), remote);
635 cleanup:
636 free(found_ref);
637 strbuf_release(&bname);
638 }
639
640 static void parse_branch_merge_options(char *bmo)
641 {
642 const char **argv;
643 int argc;
644
645 if (!bmo)
646 return;
647 argc = split_cmdline(bmo, &argv);
648 if (argc < 0)
649 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
650 _(split_cmdline_strerror(argc)));
651 REALLOC_ARRAY(argv, argc + 2);
652 MOVE_ARRAY(argv + 1, argv, argc + 1);
653 argc++;
654 argv[0] = "branch.*.mergeoptions";
655 parse_options(argc, argv, NULL, builtin_merge_options,
656 builtin_merge_usage, 0);
657 free(argv);
658 }
659
660 static int git_merge_config(const char *k, const char *v,
661 const struct config_context *ctx, void *cb)
662 {
663 int status;
664 const char *str;
665
666 if (branch &&
667 skip_prefix(k, "branch.", &str) &&
668 skip_prefix(str, branch, &str) &&
669 !strcmp(str, ".mergeoptions")) {
670 free(branch_mergeoptions);
671 branch_mergeoptions = xstrdup(v);
672 return 0;
673 }
674
675 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat")) {
676 int val = git_parse_maybe_bool_text(v);
677 switch (val) {
678 case 0:
679 show_diffstat = 0;
680 break;
681 case 1:
682 show_diffstat = MERGE_SHOW_DIFFSTAT;
683 break;
684 default:
685 if (!strcmp(v, "compact"))
686 show_diffstat = MERGE_SHOW_COMPACTSUMMARY;
687 /*
688 * We do not need to have an explicit
689 *
690 * else if (!strcmp(v, "diffstat"))
691 * show_diffstat = MERGE_SHOW_DIFFSTAT;
692 *
693 * here, because the catch-all uses the
694 * diffstat style anyway.
695 */
696 else
697 /*
698 * A setting from a future? It is not an
699 * error grave enough to fail the command.
700 * proceed using the default one.
701 */
702 show_diffstat = MERGE_SHOW_DIFFSTAT;
703 break;
704 }
705 } else if (!strcmp(k, "merge.verifysignatures")) {
706 verify_signatures = git_config_bool(k, v);
707 } else if (!strcmp(k, "pull.twohead")) {
708 FREE_AND_NULL(pull_twohead);
709 return git_config_string(&pull_twohead, k, v);
710 } else if (!strcmp(k, "pull.octopus")) {
711 FREE_AND_NULL(pull_octopus);
712 return git_config_string(&pull_octopus, k, v);
713 } else if (!strcmp(k, "commit.cleanup")) {
714 return git_config_string(&cleanup_arg, k, v);
715 } else if (!strcmp(k, "merge.ff")) {
716 int boolval = git_parse_maybe_bool(v);
717 if (0 <= boolval) {
718 fast_forward = boolval ? FF_ALLOW : FF_NO;
719 } else if (v && !strcmp(v, "only")) {
720 fast_forward = FF_ONLY;
721 } /* do not barf on values from future versions of git */
722 return 0;
723 } else if (!strcmp(k, "merge.defaulttoupstream")) {
724 default_to_upstream = git_config_bool(k, v);
725 return 0;
726 } else if (!strcmp(k, "commit.gpgsign")) {
727 sign_commit = git_config_bool(k, v) ? "" : NULL;
728 return 0;
729 } else if (!strcmp(k, "gpg.mintrustlevel")) {
730 check_trust_level = 0;
731 } else if (!strcmp(k, "merge.autostash")) {
732 autostash = git_config_bool(k, v);
733 return 0;
734 }
735
736 status = fmt_merge_msg_config(k, v, ctx, cb);
737 if (status)
738 return status;
739 return git_diff_ui_config(k, v, ctx, cb);
740 }
741
742 static int read_tree_trivial(struct object_id *common, struct object_id *head,
743 struct object_id *one)
744 {
745 int i, nr_trees = 0;
746 struct tree *trees[MAX_UNPACK_TREES];
747 struct tree_desc t[MAX_UNPACK_TREES];
748 struct unpack_trees_options opts;
749
750 memset(&opts, 0, sizeof(opts));
751 opts.head_idx = 2;
752 opts.src_index = the_repository->index;
753 opts.dst_index = the_repository->index;
754 opts.update = 1;
755 opts.verbose_update = 1;
756 opts.trivial_merges_only = 1;
757 opts.merge = 1;
758 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
759 trees[nr_trees] = parse_tree_indirect(common);
760 if (!trees[nr_trees++])
761 return -1;
762 trees[nr_trees] = parse_tree_indirect(head);
763 if (!trees[nr_trees++])
764 return -1;
765 trees[nr_trees] = parse_tree_indirect(one);
766 if (!trees[nr_trees++])
767 return -1;
768 opts.fn = threeway_merge;
769 cache_tree_free(&the_repository->index->cache_tree);
770 for (i = 0; i < nr_trees; i++) {
771 parse_tree(trees[i]);
772 init_tree_desc(t+i, &trees[i]->object.oid,
773 trees[i]->buffer, trees[i]->size);
774 }
775 if (unpack_trees(nr_trees, t, &opts))
776 return -1;
777 return 0;
778 }
779
780 static void write_tree_trivial(struct object_id *oid)
781 {
782 if (write_index_as_tree(oid, the_repository->index,
783 repo_get_index_file(the_repository),
784 0, NULL))
785 die(_("git write-tree failed to write a tree"));
786 }
787
788 static int try_merge_strategy(const char *strategy, struct commit_list *common,
789 struct commit_list *remoteheads,
790 struct commit *head)
791 {
792 const char *head_arg = "HEAD";
793
794 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
795 SKIP_IF_UNCHANGED, 0, NULL, NULL,
796 NULL) < 0)
797 die(_("Unable to write index."));
798
799 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
800 !strcmp(strategy, "ort")) {
801 struct lock_file lock = LOCK_INIT;
802 int clean, x;
803 struct commit *result;
804 struct commit_list *reversed = NULL;
805 struct merge_options o;
806 struct commit_list *j;
807
808 if (remoteheads->next) {
809 error(_("Not handling anything other than two heads merge."));
810 return 2;
811 }
812
813 init_ui_merge_options(&o, the_repository);
814 if (!strcmp(strategy, "subtree"))
815 o.subtree_shift = "";
816
817 o.show_rename_progress =
818 show_progress == -1 ? isatty(2) : show_progress;
819
820 for (x = 0; x < xopts.nr; x++)
821 if (parse_merge_opt(&o, xopts.v[x]))
822 die(_("unknown strategy option: -X%s"), xopts.v[x]);
823
824 o.branch1 = head_arg;
825 o.branch2 = merge_remote_util(remoteheads->item)->name;
826
827 for (j = common; j; j = j->next)
828 commit_list_insert(j->item, &reversed);
829
830 repo_hold_locked_index(the_repository, &lock,
831 LOCK_DIE_ON_ERROR);
832 clean = merge_ort_recursive(&o, head, remoteheads->item,
833 reversed, &result);
834 free_commit_list(reversed);
835 strbuf_release(&o.obuf);
836
837 if (clean < 0) {
838 rollback_lock_file(&lock);
839 return 2;
840 }
841 if (write_locked_index(the_repository->index, &lock,
842 COMMIT_LOCK | SKIP_IF_UNCHANGED))
843 die(_("unable to write %s"), repo_get_index_file(the_repository));
844 return clean ? 0 : 1;
845 } else {
846 return try_merge_command(the_repository,
847 strategy, xopts.nr, xopts.v,
848 common, head_arg, remoteheads);
849 }
850 }
851
852 static void count_diff_files(struct diff_queue_struct *q,
853 struct diff_options *opt UNUSED, void *data)
854 {
855 int *count = data;
856
857 (*count) += q->nr;
858 }
859
860 static int count_unmerged_entries(void)
861 {
862 int i, ret = 0;
863
864 for (i = 0; i < the_repository->index->cache_nr; i++)
865 if (ce_stage(the_repository->index->cache[i]))
866 ret++;
867
868 return ret;
869 }
870
871 static void add_strategies(const char *string, unsigned attr)
872 {
873 int i;
874
875 if (string) {
876 struct string_list list = STRING_LIST_INIT_DUP;
877 struct string_list_item *item;
878 string_list_split(&list, string, ' ', -1);
879 for_each_string_list_item(item, &list)
880 append_strategy(get_strategy(item->string));
881 string_list_clear(&list, 0);
882 return;
883 }
884 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
885 if (all_strategy[i].attr & attr)
886 append_strategy(&all_strategy[i]);
887
888 }
889
890 static void read_merge_msg(struct strbuf *msg)
891 {
892 const char *filename = git_path_merge_msg(the_repository);
893 strbuf_reset(msg);
894 if (strbuf_read_file(msg, filename, 0) < 0)
895 die_errno(_("Could not read from '%s'"), filename);
896 }
897
898 static void write_merge_state(struct commit_list *);
899 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
900 {
901 if (err_msg)
902 error("%s", err_msg);
903 fprintf(stderr,
904 _("Not committing merge; use 'git commit' to complete the merge.\n"));
905 write_merge_state(remoteheads);
906 exit(1);
907 }
908
909 static const char merge_editor_comment[] =
910 N_("Please enter a commit message to explain why this merge is necessary,\n"
911 "especially if it merges an updated upstream into a topic branch.\n"
912 "\n");
913
914 static const char scissors_editor_comment[] =
915 N_("An empty message aborts the commit.\n");
916
917 static const char no_scissors_editor_comment[] =
918 N_("Lines starting with '%s' will be ignored, and an empty message aborts\n"
919 "the commit.\n");
920
921 static void write_merge_heads(struct commit_list *);
922 static void prepare_to_commit(struct commit_list *remoteheads)
923 {
924 struct strbuf msg = STRBUF_INIT;
925 const char *index_file = repo_get_index_file(the_repository);
926
927 if (!no_verify) {
928 int invoked_hook;
929
930 if (run_commit_hook(0 < option_edit, index_file, &invoked_hook,
931 "pre-merge-commit", NULL))
932 abort_commit(remoteheads, NULL);
933 /*
934 * Re-read the index as pre-merge-commit hook could have updated it,
935 * and write it out as a tree. We must do this before we invoke
936 * the editor and after we invoke run_status above.
937 */
938 if (invoked_hook)
939 discard_index(the_repository->index);
940 }
941 read_index_from(the_repository->index, index_file,
942 repo_get_git_dir(the_repository));
943 strbuf_addbuf(&msg, &merge_msg);
944 if (squash)
945 BUG("the control must not reach here under --squash");
946 if (0 < option_edit) {
947 strbuf_addch(&msg, '\n');
948 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
949 wt_status_append_cut_line(&msg);
950 strbuf_commented_addf(&msg, comment_line_str, "\n");
951 }
952 strbuf_commented_addf(&msg, comment_line_str,
953 _(merge_editor_comment));
954 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
955 strbuf_commented_addf(&msg, comment_line_str,
956 _(scissors_editor_comment));
957 else
958 strbuf_commented_addf(&msg, comment_line_str,
959 _(no_scissors_editor_comment), comment_line_str);
960 }
961 if (signoff)
962 append_signoff(&msg, ignored_log_message_bytes(msg.buf, msg.len), 0);
963 write_merge_heads(remoteheads);
964 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
965 if (run_commit_hook(0 < option_edit, repo_get_index_file(the_repository),
966 NULL, "prepare-commit-msg",
967 git_path_merge_msg(the_repository), "merge", NULL))
968 abort_commit(remoteheads, NULL);
969 if (0 < option_edit) {
970 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
971 abort_commit(remoteheads, NULL);
972 }
973
974 if (!no_verify && run_commit_hook(0 < option_edit, repo_get_index_file(the_repository),
975 NULL, "commit-msg",
976 git_path_merge_msg(the_repository), NULL))
977 abort_commit(remoteheads, NULL);
978
979 read_merge_msg(&msg);
980 cleanup_message(&msg, cleanup_mode, 0);
981 if (!msg.len)
982 abort_commit(remoteheads, _("Empty commit message."));
983 strbuf_release(&merge_msg);
984 strbuf_addbuf(&merge_msg, &msg);
985 strbuf_release(&msg);
986 }
987
988 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
989 {
990 struct object_id result_tree, result_commit;
991 struct commit_list *parents = NULL, **pptr = &parents;
992
993 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
994 SKIP_IF_UNCHANGED, 0, NULL, NULL,
995 NULL) < 0)
996 return error(_("Unable to write index."));
997
998 write_tree_trivial(&result_tree);
999 printf(_("Wonderful.\n"));
1000 pptr = commit_list_append(head, pptr);
1001 pptr = commit_list_append(remoteheads->item, pptr);
1002 prepare_to_commit(remoteheads);
1003 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
1004 &result_commit, NULL, sign_commit))
1005 die(_("failed to write commit object"));
1006 finish(head, remoteheads, &result_commit, "In-index merge");
1007
1008 remove_merge_branch_state(the_repository);
1009 free_commit_list(parents);
1010 return 0;
1011 }
1012
1013 static int finish_automerge(struct commit *head,
1014 int head_subsumed,
1015 struct commit_list *common,
1016 struct commit_list *remoteheads,
1017 struct object_id *result_tree,
1018 const char *wt_strategy)
1019 {
1020 struct commit_list *parents = NULL;
1021 struct strbuf buf = STRBUF_INIT;
1022 struct object_id result_commit;
1023
1024 write_tree_trivial(result_tree);
1025 free_commit_list(common);
1026 parents = remoteheads;
1027 if (!head_subsumed || fast_forward == FF_NO)
1028 commit_list_insert(head, &parents);
1029 prepare_to_commit(remoteheads);
1030 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
1031 &result_commit, NULL, sign_commit))
1032 die(_("failed to write commit object"));
1033 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
1034 finish(head, remoteheads, &result_commit, buf.buf);
1035
1036 strbuf_release(&buf);
1037 remove_merge_branch_state(the_repository);
1038 free_commit_list(parents);
1039 return 0;
1040 }
1041
1042 static int suggest_conflicts(void)
1043 {
1044 const char *filename;
1045 FILE *fp;
1046 struct strbuf msgbuf = STRBUF_INIT;
1047
1048 filename = git_path_merge_msg(the_repository);
1049 fp = xfopen(filename, "a");
1050
1051 /*
1052 * We can't use cleanup_mode because if we're not using the editor,
1053 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
1054 * though the message is meant to be processed later by git-commit.
1055 * Thus, we will get the cleanup mode which is returned when we _are_
1056 * using an editor.
1057 */
1058 append_conflicts_hint(the_repository->index, &msgbuf,
1059 get_cleanup_mode(cleanup_arg, 1));
1060 fputs(msgbuf.buf, fp);
1061 strbuf_release(&msgbuf);
1062 fclose(fp);
1063 repo_rerere(the_repository, allow_rerere_auto);
1064 printf(_("Automatic merge failed; "
1065 "fix conflicts and then commit the result.\n"));
1066 return 1;
1067 }
1068
1069 static int evaluate_result(void)
1070 {
1071 int cnt = 0;
1072 struct rev_info rev;
1073
1074 /* Check how many files differ. */
1075 repo_init_revisions(the_repository, &rev, "");
1076 setup_revisions(0, NULL, &rev, NULL);
1077 rev.diffopt.output_format |=
1078 DIFF_FORMAT_CALLBACK;
1079 rev.diffopt.format_callback = count_diff_files;
1080 rev.diffopt.format_callback_data = &cnt;
1081 run_diff_files(&rev, 0);
1082
1083 /*
1084 * Check how many unmerged entries are
1085 * there.
1086 */
1087 cnt += count_unmerged_entries();
1088
1089 release_revisions(&rev);
1090 return cnt;
1091 }
1092
1093 /*
1094 * Pretend as if the user told us to merge with the remote-tracking
1095 * branch we have for the upstream of the current branch
1096 */
1097 static int setup_with_upstream(const char ***argv)
1098 {
1099 struct branch *branch = branch_get(NULL);
1100 int i;
1101 const char **args;
1102
1103 if (!branch)
1104 die(_("No current branch."));
1105 if (!branch->remote_name)
1106 die(_("No remote for the current branch."));
1107 if (!branch->merge_nr)
1108 die(_("No default upstream defined for the current branch."));
1109
1110 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1111 for (i = 0; i < branch->merge_nr; i++) {
1112 if (!branch->merge[i]->dst)
1113 die(_("No remote-tracking branch for %s from %s"),
1114 branch->merge[i]->src, branch->remote_name);
1115 args[i] = branch->merge[i]->dst;
1116 }
1117 args[i] = NULL;
1118 *argv = args;
1119 return i;
1120 }
1121
1122 static void write_merge_heads(struct commit_list *remoteheads)
1123 {
1124 struct commit_list *j;
1125 struct strbuf buf = STRBUF_INIT;
1126
1127 for (j = remoteheads; j; j = j->next) {
1128 struct object_id *oid;
1129 struct commit *c = j->item;
1130 struct merge_remote_desc *desc;
1131
1132 desc = merge_remote_util(c);
1133 if (desc && desc->obj) {
1134 oid = &desc->obj->oid;
1135 } else {
1136 oid = &c->object.oid;
1137 }
1138 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1139 }
1140 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1141
1142 strbuf_reset(&buf);
1143 if (fast_forward == FF_NO)
1144 strbuf_addstr(&buf, "no-ff");
1145 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1146 strbuf_release(&buf);
1147 }
1148
1149 static void write_merge_state(struct commit_list *remoteheads)
1150 {
1151 write_merge_heads(remoteheads);
1152 strbuf_addch(&merge_msg, '\n');
1153 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1154 merge_msg.len);
1155 }
1156
1157 static int default_edit_option(void)
1158 {
1159 static const char name[] = "GIT_MERGE_AUTOEDIT";
1160 const char *e = getenv(name);
1161 struct stat st_stdin, st_stdout;
1162
1163 if (have_message)
1164 /* an explicit -m msg without --[no-]edit */
1165 return 0;
1166
1167 if (e) {
1168 int v = git_parse_maybe_bool(e);
1169 if (v < 0)
1170 die(_("Bad value '%s' in environment '%s'"), e, name);
1171 return v;
1172 }
1173
1174 /* Use editor if stdin and stdout are the same and is a tty */
1175 return (!fstat(0, &st_stdin) &&
1176 !fstat(1, &st_stdout) &&
1177 isatty(0) && isatty(1) &&
1178 st_stdin.st_dev == st_stdout.st_dev &&
1179 st_stdin.st_ino == st_stdout.st_ino &&
1180 st_stdin.st_mode == st_stdout.st_mode);
1181 }
1182
1183 static struct commit_list *reduce_parents(struct commit *head_commit,
1184 int *head_subsumed,
1185 struct commit_list *remoteheads)
1186 {
1187 struct commit_list *parents, **remotes;
1188
1189 /*
1190 * Is the current HEAD reachable from another commit being
1191 * merged? If so we do not want to record it as a parent of
1192 * the resulting merge, unless --no-ff is given. We will flip
1193 * this variable to 0 when we find HEAD among the independent
1194 * tips being merged.
1195 */
1196 *head_subsumed = 1;
1197
1198 /* Find what parents to record by checking independent ones. */
1199 parents = reduce_heads(remoteheads);
1200 free_commit_list(remoteheads);
1201
1202 remoteheads = NULL;
1203 remotes = &remoteheads;
1204 while (parents) {
1205 struct commit *commit = pop_commit(&parents);
1206 if (commit == head_commit)
1207 *head_subsumed = 0;
1208 else
1209 remotes = &commit_list_insert(commit, remotes)->next;
1210 }
1211 return remoteheads;
1212 }
1213
1214 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1215 {
1216 struct fmt_merge_msg_opts opts;
1217
1218 memset(&opts, 0, sizeof(opts));
1219 opts.add_title = !have_message;
1220 opts.shortlog_len = shortlog_len;
1221 opts.credit_people = (0 < option_edit);
1222 opts.into_name = into_name;
1223
1224 fmt_merge_msg(merge_names, merge_msg, &opts);
1225 if (merge_msg->len)
1226 strbuf_setlen(merge_msg, merge_msg->len - 1);
1227 }
1228
1229 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1230 {
1231 const char *filename;
1232 int fd, pos, npos;
1233 struct strbuf fetch_head_file = STRBUF_INIT;
1234 const unsigned hexsz = the_hash_algo->hexsz;
1235
1236 if (!merge_names)
1237 merge_names = &fetch_head_file;
1238
1239 filename = git_path_fetch_head(the_repository);
1240 fd = xopen(filename, O_RDONLY);
1241
1242 if (strbuf_read(merge_names, fd, 0) < 0)
1243 die_errno(_("could not read '%s'"), filename);
1244 if (close(fd) < 0)
1245 die_errno(_("could not close '%s'"), filename);
1246
1247 for (pos = 0; pos < merge_names->len; pos = npos) {
1248 struct object_id oid;
1249 char *ptr;
1250 struct commit *commit;
1251
1252 ptr = strchr(merge_names->buf + pos, '\n');
1253 if (ptr)
1254 npos = ptr - merge_names->buf + 1;
1255 else
1256 npos = merge_names->len;
1257
1258 if (npos - pos < hexsz + 2 ||
1259 get_oid_hex(merge_names->buf + pos, &oid))
1260 commit = NULL; /* bad */
1261 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1262 continue; /* not-for-merge */
1263 else {
1264 char saved = merge_names->buf[pos + hexsz];
1265 merge_names->buf[pos + hexsz] = '\0';
1266 commit = get_merge_parent(merge_names->buf + pos);
1267 merge_names->buf[pos + hexsz] = saved;
1268 }
1269 if (!commit) {
1270 if (ptr)
1271 *ptr = '\0';
1272 die(_("not something we can merge in %s: %s"),
1273 filename, merge_names->buf + pos);
1274 }
1275 remotes = &commit_list_insert(commit, remotes)->next;
1276 }
1277
1278 if (merge_names == &fetch_head_file)
1279 strbuf_release(&fetch_head_file);
1280 }
1281
1282 static struct commit_list *collect_parents(struct commit *head_commit,
1283 int *head_subsumed,
1284 int argc, const char **argv,
1285 struct strbuf *merge_msg)
1286 {
1287 int i;
1288 struct commit_list *remoteheads = NULL;
1289 struct commit_list **remotes = &remoteheads;
1290 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1291
1292 if (merge_msg && (!have_message || shortlog_len))
1293 autogen = &merge_names;
1294
1295 if (head_commit)
1296 remotes = &commit_list_insert(head_commit, remotes)->next;
1297
1298 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1299 handle_fetch_head(remotes, autogen);
1300 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1301 } else {
1302 for (i = 0; i < argc; i++) {
1303 struct commit *commit = get_merge_parent(argv[i]);
1304 if (!commit)
1305 help_unknown_ref(argv[i], "merge",
1306 _("not something we can merge"));
1307 remotes = &commit_list_insert(commit, remotes)->next;
1308 }
1309 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1310 if (autogen) {
1311 struct commit_list *p;
1312 for (p = remoteheads; p; p = p->next)
1313 merge_name(merge_remote_util(p->item)->name, autogen);
1314 }
1315 }
1316
1317 if (autogen) {
1318 prepare_merge_message(autogen, merge_msg);
1319 strbuf_release(autogen);
1320 }
1321
1322 return remoteheads;
1323 }
1324
1325 static int merging_a_throwaway_tag(struct commit *commit)
1326 {
1327 char *tag_ref;
1328 struct object_id oid;
1329 int is_throwaway_tag = 0;
1330
1331 /* Are we merging a tag? */
1332 if (!merge_remote_util(commit) ||
1333 !merge_remote_util(commit)->obj ||
1334 merge_remote_util(commit)->obj->type != OBJ_TAG)
1335 return is_throwaway_tag;
1336
1337 /*
1338 * Now we know we are merging a tag object. Are we downstream
1339 * and following the tags from upstream? If so, we must have
1340 * the tag object pointed at by "refs/tags/$T" where $T is the
1341 * tagname recorded in the tag object. We want to allow such
1342 * a "just to catch up" merge to fast-forward.
1343 *
1344 * Otherwise, we are playing an integrator's role, making a
1345 * merge with a throw-away tag from a contributor with
1346 * something like "git pull $contributor $signed_tag".
1347 * We want to forbid such a merge from fast-forwarding
1348 * by default; otherwise we would not keep the signature
1349 * anywhere.
1350 */
1351 tag_ref = xstrfmt("refs/tags/%s",
1352 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1353 if (!refs_read_ref(get_main_ref_store(the_repository), tag_ref, &oid) &&
1354 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1355 is_throwaway_tag = 0;
1356 else
1357 is_throwaway_tag = 1;
1358 free(tag_ref);
1359 return is_throwaway_tag;
1360 }
1361
1362 int cmd_merge(int argc,
1363 const char **argv,
1364 const char *prefix,
1365 struct repository *repo UNUSED)
1366 {
1367 struct object_id result_tree, stash, head_oid;
1368 struct commit *head_commit;
1369 struct strbuf buf = STRBUF_INIT;
1370 int i, ret = 0, head_subsumed;
1371 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1372 struct commit_list *common = NULL;
1373 const char *best_strategy = NULL, *wt_strategy = NULL;
1374 struct commit_list *remoteheads = NULL, *p;
1375 void *branch_to_free;
1376 int orig_argc = argc;
1377
1378 show_usage_with_options_if_asked(argc, argv,
1379 builtin_merge_usage, builtin_merge_options);
1380
1381 prepare_repo_settings(the_repository);
1382 the_repository->settings.command_requires_full_index = 0;
1383
1384 /*
1385 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1386 * current branch.
1387 */
1388 branch = branch_to_free = refs_resolve_refdup(get_main_ref_store(the_repository),
1389 "HEAD", 0, &head_oid,
1390 NULL);
1391 if (branch)
1392 skip_prefix(branch, "refs/heads/", &branch);
1393
1394 init_diff_ui_defaults();
1395 git_config(git_merge_config, NULL);
1396
1397 if (!branch || is_null_oid(&head_oid))
1398 head_commit = NULL;
1399 else
1400 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1401
1402 if (branch_mergeoptions)
1403 parse_branch_merge_options(branch_mergeoptions);
1404 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1405 builtin_merge_usage, 0);
1406 if (shortlog_len < 0)
1407 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1408
1409 if (verbosity < 0 && show_progress == -1)
1410 show_progress = 0;
1411
1412 if (abort_current_merge) {
1413 int nargc = 2;
1414 const char *nargv[] = {"reset", "--merge", NULL};
1415 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
1416 struct object_id stash_oid = {0};
1417
1418 if (orig_argc != 2)
1419 usage_msg_opt(_("--abort expects no arguments"),
1420 builtin_merge_usage, builtin_merge_options);
1421
1422 if (!file_exists(git_path_merge_head(the_repository)))
1423 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1424
1425 if (!refs_read_ref(get_main_ref_store(the_repository), "MERGE_AUTOSTASH", &stash_oid))
1426 refs_delete_ref(get_main_ref_store(the_repository),
1427 "", "MERGE_AUTOSTASH", &stash_oid,
1428 REF_NO_DEREF);
1429
1430 /* Invoke 'git reset --merge' */
1431 ret = cmd_reset(nargc, nargv, prefix, the_repository);
1432
1433 if (!is_null_oid(&stash_oid)) {
1434 oid_to_hex_r(stash_oid_hex, &stash_oid);
1435 apply_autostash_oid(stash_oid_hex);
1436 }
1437
1438 goto done;
1439 }
1440
1441 if (quit_current_merge) {
1442 if (orig_argc != 2)
1443 usage_msg_opt(_("--quit expects no arguments"),
1444 builtin_merge_usage,
1445 builtin_merge_options);
1446
1447 remove_merge_branch_state(the_repository);
1448 goto done;
1449 }
1450
1451 if (continue_current_merge) {
1452 int nargc = 1;
1453 const char *nargv[] = {"commit", NULL};
1454
1455 if (orig_argc != 2)
1456 usage_msg_opt(_("--continue expects no arguments"),
1457 builtin_merge_usage, builtin_merge_options);
1458
1459 if (!file_exists(git_path_merge_head(the_repository)))
1460 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1461
1462 /* Invoke 'git commit' */
1463 ret = cmd_commit(nargc, nargv, prefix, the_repository);
1464 goto done;
1465 }
1466
1467 if (repo_read_index_unmerged(the_repository))
1468 die_resolve_conflict("merge");
1469
1470 if (file_exists(git_path_merge_head(the_repository))) {
1471 /*
1472 * There is no unmerged entry, don't advise 'git
1473 * add/rm <file>', just 'git commit'.
1474 */
1475 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1476 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1477 "Please, commit your changes before you merge."));
1478 else
1479 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1480 }
1481 if (refs_ref_exists(get_main_ref_store(the_repository), "CHERRY_PICK_HEAD")) {
1482 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1483 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1484 "Please, commit your changes before you merge."));
1485 else
1486 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1487 }
1488 resolve_undo_clear_index(the_repository->index);
1489
1490 if (option_edit < 0)
1491 option_edit = default_edit_option();
1492
1493 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1494
1495 if (verbosity < 0)
1496 show_diffstat = 0;
1497
1498 if (squash) {
1499 if (fast_forward == FF_NO)
1500 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1501 if (option_commit > 0)
1502 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1503 /*
1504 * squash can now silently disable option_commit - this is not
1505 * a problem as it is only overriding the default, not a user
1506 * supplied option.
1507 */
1508 option_commit = 0;
1509 }
1510
1511 if (option_commit < 0)
1512 option_commit = 1;
1513
1514 if (!argc) {
1515 if (default_to_upstream)
1516 argc = setup_with_upstream(&argv);
1517 else
1518 die(_("No commit specified and merge.defaultToUpstream not set."));
1519 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1520 argv[0] = "@{-1}";
1521 }
1522
1523 if (!argc)
1524 usage_with_options(builtin_merge_usage,
1525 builtin_merge_options);
1526
1527 if (!head_commit) {
1528 /*
1529 * If the merged head is a valid one there is no reason
1530 * to forbid "git merge" into a branch yet to be born.
1531 * We do the same for "git pull".
1532 */
1533 struct object_id *remote_head_oid;
1534 if (squash)
1535 die(_("Squash commit into empty head not supported yet"));
1536 if (fast_forward == FF_NO)
1537 die(_("Non-fast-forward commit does not make sense into "
1538 "an empty head"));
1539 remoteheads = collect_parents(head_commit, &head_subsumed,
1540 argc, argv, NULL);
1541 if (!remoteheads)
1542 die(_("%s - not something we can merge"), argv[0]);
1543 if (remoteheads->next)
1544 die(_("Can merge only exactly one commit into empty head"));
1545
1546 if (verify_signatures)
1547 verify_merge_signature(remoteheads->item, verbosity,
1548 check_trust_level);
1549
1550 remote_head_oid = &remoteheads->item->object.oid;
1551 read_empty(remote_head_oid);
1552 refs_update_ref(get_main_ref_store(the_repository),
1553 "initial pull", "HEAD", remote_head_oid, NULL,
1554 0,
1555 UPDATE_REFS_DIE_ON_ERR);
1556 goto done;
1557 }
1558
1559 /*
1560 * All the rest are the commits being merged; prepare
1561 * the standard merge summary message to be appended
1562 * to the given message.
1563 */
1564 remoteheads = collect_parents(head_commit, &head_subsumed,
1565 argc, argv, &merge_msg);
1566
1567 if (!head_commit || !argc)
1568 usage_with_options(builtin_merge_usage,
1569 builtin_merge_options);
1570
1571 if (verify_signatures) {
1572 for (p = remoteheads; p; p = p->next) {
1573 verify_merge_signature(p->item, verbosity,
1574 check_trust_level);
1575 }
1576 }
1577
1578 strbuf_addstr(&buf, "merge");
1579 for (p = remoteheads; p; p = p->next)
1580 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1581 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1582 strbuf_reset(&buf);
1583
1584 for (p = remoteheads; p; p = p->next) {
1585 struct commit *commit = p->item;
1586 strbuf_addf(&buf, "GITHEAD_%s",
1587 oid_to_hex(&commit->object.oid));
1588 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1589 strbuf_reset(&buf);
1590 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1591 fast_forward = FF_NO;
1592 }
1593
1594 if (!use_strategies) {
1595 if (!remoteheads)
1596 ; /* already up-to-date */
1597 else if (!remoteheads->next)
1598 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1599 else
1600 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1601 }
1602
1603 for (i = 0; i < use_strategies_nr; i++) {
1604 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1605 fast_forward = FF_NO;
1606 if (use_strategies[i]->attr & NO_TRIVIAL)
1607 allow_trivial = 0;
1608 }
1609
1610 if (!remoteheads)
1611 ; /* already up-to-date */
1612 else if (!remoteheads->next) {
1613 if (repo_get_merge_bases(the_repository, head_commit,
1614 remoteheads->item, &common) < 0) {
1615 ret = 2;
1616 goto done;
1617 }
1618 } else {
1619 struct commit_list *list = remoteheads;
1620 commit_list_insert(head_commit, &list);
1621 if (get_octopus_merge_bases(list, &common) < 0) {
1622 free(list);
1623 ret = 2;
1624 goto done;
1625 }
1626 free(list);
1627 }
1628
1629 refs_update_ref(get_main_ref_store(the_repository),
1630 "updating ORIG_HEAD", "ORIG_HEAD",
1631 &head_commit->object.oid, NULL, 0,
1632 UPDATE_REFS_DIE_ON_ERR);
1633
1634 if (remoteheads && !common) {
1635 /* No common ancestors found. */
1636 if (!allow_unrelated_histories)
1637 die(_("refusing to merge unrelated histories"));
1638 /* otherwise, we need a real merge. */
1639 } else if (!remoteheads ||
1640 (!remoteheads->next && !common->next &&
1641 common->item == remoteheads->item)) {
1642 /*
1643 * If head can reach all the merge then we are up to date.
1644 * but first the most common case of merging one remote.
1645 */
1646 finish_up_to_date();
1647 goto done;
1648 } else if (fast_forward != FF_NO && !remoteheads->next &&
1649 !common->next &&
1650 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1651 /* Again the most common case of merging one remote. */
1652 const char *msg = have_message ?
1653 "Fast-forward (no commit created; -m option ignored)" :
1654 "Fast-forward";
1655 struct commit *commit;
1656
1657 if (verbosity >= 0) {
1658 printf(_("Updating %s..%s\n"),
1659 repo_find_unique_abbrev(the_repository, &head_commit->object.oid,
1660 DEFAULT_ABBREV),
1661 repo_find_unique_abbrev(the_repository, &remoteheads->item->object.oid,
1662 DEFAULT_ABBREV));
1663 }
1664 commit = remoteheads->item;
1665 if (!commit) {
1666 ret = 1;
1667 goto done;
1668 }
1669
1670 if (autostash)
1671 create_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1672 if (checkout_fast_forward(the_repository,
1673 &head_commit->object.oid,
1674 &commit->object.oid,
1675 overwrite_ignore)) {
1676 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1677 ret = 1;
1678 goto done;
1679 }
1680
1681 finish(head_commit, remoteheads, &commit->object.oid, msg);
1682 remove_merge_branch_state(the_repository);
1683 goto done;
1684 } else if (!remoteheads->next && common->next)
1685 ;
1686 /*
1687 * We are not doing octopus and not fast-forward. Need
1688 * a real merge.
1689 */
1690 else if (!remoteheads->next && !common->next && option_commit) {
1691 /*
1692 * We are not doing octopus, not fast-forward, and have
1693 * only one common.
1694 */
1695 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
1696 if (allow_trivial && fast_forward != FF_ONLY) {
1697 /*
1698 * Must first ensure that index matches HEAD before
1699 * attempting a trivial merge.
1700 */
1701 struct tree *head_tree = repo_get_commit_tree(the_repository,
1702 head_commit);
1703 struct strbuf sb = STRBUF_INIT;
1704
1705 if (repo_index_has_changes(the_repository, head_tree,
1706 &sb)) {
1707 error(_("Your local changes to the following files would be overwritten by merge:\n %s"),
1708 sb.buf);
1709 strbuf_release(&sb);
1710 ret = 2;
1711 goto done;
1712 }
1713
1714 /* See if it is really trivial. */
1715 git_committer_info(IDENT_STRICT);
1716 printf(_("Trying really trivial in-index merge...\n"));
1717 if (!read_tree_trivial(&common->item->object.oid,
1718 &head_commit->object.oid,
1719 &remoteheads->item->object.oid)) {
1720 ret = merge_trivial(head_commit, remoteheads);
1721 goto done;
1722 }
1723 printf(_("Nope.\n"));
1724 }
1725 } else {
1726 /*
1727 * An octopus. If we can reach all the remote we are up
1728 * to date.
1729 */
1730 int up_to_date = 1;
1731 struct commit_list *j;
1732
1733 for (j = remoteheads; j; j = j->next) {
1734 struct commit_list *common_one = NULL;
1735 struct commit *common_item;
1736
1737 /*
1738 * Here we *have* to calculate the individual
1739 * merge_bases again, otherwise "git merge HEAD^
1740 * HEAD^^" would be missed.
1741 */
1742 if (repo_get_merge_bases(the_repository, head_commit,
1743 j->item, &common_one) < 0)
1744 exit(128);
1745
1746 common_item = common_one->item;
1747 free_commit_list(common_one);
1748 if (!oideq(&common_item->object.oid, &j->item->object.oid)) {
1749 up_to_date = 0;
1750 break;
1751 }
1752 }
1753 if (up_to_date) {
1754 finish_up_to_date();
1755 goto done;
1756 }
1757 }
1758
1759 if (fast_forward == FF_ONLY)
1760 die_ff_impossible();
1761
1762 if (autostash)
1763 create_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1764
1765 /* We are going to make a new commit. */
1766 git_committer_info(IDENT_STRICT);
1767
1768 /*
1769 * At this point, we need a real merge. No matter what strategy
1770 * we use, it would operate on the index, possibly affecting the
1771 * working tree, and when resolved cleanly, have the desired
1772 * tree in the index -- this means that the index must be in
1773 * sync with the head commit. The strategies are responsible
1774 * to ensure this.
1775 *
1776 * Stash away the local changes so that we can try more than one
1777 * and/or recover from merge strategies bailing while leaving the
1778 * index and working tree polluted.
1779 */
1780 if (save_state(&stash))
1781 oidclr(&stash, the_repository->hash_algo);
1782
1783 for (i = 0; i < use_strategies_nr; i++) {
1784 int ret, cnt;
1785 if (i) {
1786 printf(_("Rewinding the tree to pristine...\n"));
1787 restore_state(&head_commit->object.oid, &stash);
1788 }
1789 if (use_strategies_nr != 1)
1790 printf(_("Trying merge strategy %s...\n"),
1791 use_strategies[i]->name);
1792 /*
1793 * Remember which strategy left the state in the working
1794 * tree.
1795 */
1796 wt_strategy = use_strategies[i]->name;
1797
1798 ret = try_merge_strategy(wt_strategy,
1799 common, remoteheads,
1800 head_commit);
1801 /*
1802 * The backend exits with 1 when conflicts are
1803 * left to be resolved, with 2 when it does not
1804 * handle the given merge at all.
1805 */
1806 if (ret < 2) {
1807 if (!ret) {
1808 /*
1809 * This strategy worked; no point in trying
1810 * another.
1811 */
1812 merge_was_ok = 1;
1813 best_strategy = wt_strategy;
1814 break;
1815 }
1816 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1817 if (best_cnt <= 0 || cnt <= best_cnt) {
1818 best_strategy = wt_strategy;
1819 best_cnt = cnt;
1820 }
1821 }
1822 }
1823
1824 /*
1825 * If we have a resulting tree, that means the strategy module
1826 * auto resolved the merge cleanly.
1827 */
1828 if (merge_was_ok && option_commit) {
1829 automerge_was_ok = 1;
1830 ret = finish_automerge(head_commit, head_subsumed,
1831 common, remoteheads,
1832 &result_tree, wt_strategy);
1833 goto done;
1834 }
1835
1836 /*
1837 * Pick the result from the best strategy and have the user fix
1838 * it up.
1839 */
1840 if (!best_strategy) {
1841 restore_state(&head_commit->object.oid, &stash);
1842 if (use_strategies_nr > 1)
1843 fprintf(stderr,
1844 _("No merge strategy handled the merge.\n"));
1845 else
1846 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1847 use_strategies[0]->name);
1848 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1849 ret = 2;
1850 goto done;
1851 } else if (best_strategy == wt_strategy)
1852 ; /* We already have its result in the working tree. */
1853 else {
1854 printf(_("Rewinding the tree to pristine...\n"));
1855 restore_state(&head_commit->object.oid, &stash);
1856 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1857 best_strategy);
1858 try_merge_strategy(best_strategy, common, remoteheads,
1859 head_commit);
1860 }
1861
1862 if (squash) {
1863 finish(head_commit, remoteheads, NULL, NULL);
1864
1865 git_test_write_commit_graph_or_die();
1866 } else
1867 write_merge_state(remoteheads);
1868
1869 if (merge_was_ok)
1870 fprintf(stderr, _("Automatic merge went well; "
1871 "stopped before committing as requested\n"));
1872 else
1873 ret = suggest_conflicts();
1874 if (autostash)
1875 printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1876
1877 done:
1878 if (!automerge_was_ok) {
1879 free_commit_list(common);
1880 free_commit_list(remoteheads);
1881 }
1882 strbuf_release(&buf);
1883 free(branch_to_free);
1884 free(pull_twohead);
1885 free(pull_octopus);
1886 discard_index(the_repository->index);
1887 return ret;
1888 }