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