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