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