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