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