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