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