]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/merge.c
Merge branch 'ds/bundle-uri-5'
[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; !found && 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 struct lock_file lock_file = LOCK_INIT;
317 int fd;
318 int rc = -1;
319
320 fd = repo_hold_locked_index(the_repository, &lock_file, 0);
321 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
322 if (0 <= fd)
323 repo_update_index_if_able(the_repository, &lock_file);
324 rollback_lock_file(&lock_file);
325
326 strvec_pushl(&cp.args, "stash", "create", NULL);
327 cp.out = -1;
328 cp.git_cmd = 1;
329
330 if (start_command(&cp))
331 die(_("could not run stash."));
332 len = strbuf_read(&buffer, cp.out, 1024);
333 close(cp.out);
334
335 if (finish_command(&cp) || len < 0)
336 die(_("stash failed"));
337 else if (!len) /* no changes */
338 goto out;
339 strbuf_setlen(&buffer, buffer.len-1);
340 if (get_oid(buffer.buf, stash))
341 die(_("not a valid object: %s"), buffer.buf);
342 rc = 0;
343 out:
344 strbuf_release(&buffer);
345 return rc;
346 }
347
348 static void read_empty(const struct object_id *oid)
349 {
350 struct child_process cmd = CHILD_PROCESS_INIT;
351
352 strvec_pushl(&cmd.args, "read-tree", "-m", "-u", empty_tree_oid_hex(),
353 oid_to_hex(oid), NULL);
354 cmd.git_cmd = 1;
355
356 if (run_command(&cmd))
357 die(_("read-tree failed"));
358 }
359
360 static void reset_hard(const struct object_id *oid)
361 {
362 struct child_process cmd = CHILD_PROCESS_INIT;
363
364 strvec_pushl(&cmd.args, "read-tree", "-v", "--reset", "-u",
365 oid_to_hex(oid), NULL);
366 cmd.git_cmd = 1;
367
368 if (run_command(&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 child_process cmd = CHILD_PROCESS_INIT;
376
377 reset_hard(head);
378
379 if (is_null_oid(stash))
380 goto refresh_cache;
381
382 strvec_pushl(&cmd.args, "stash", "apply", "--index", "--quiet", NULL);
383 strvec_push(&cmd.args, 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 cmd.git_cmd = 1;
390 run_command(&cmd);
391
392 refresh_cache:
393 discard_cache();
394 if (read_cache() < 0)
395 die(_("could not read index"));
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 bname = STRBUF_INIT;
507 struct merge_remote_desc *desc;
508 const char *ptr;
509 char *found_ref = NULL;
510 int len, early;
511
512 strbuf_branchname(&bname, remote, 0);
513 remote = bname.buf;
514
515 oidclr(&branch_head);
516 remote_head = get_merge_parent(remote);
517 if (!remote_head)
518 die(_("'%s' does not point to a commit"), remote);
519
520 if (dwim_ref(remote, strlen(remote), &branch_head, &found_ref, 0) > 0) {
521 if (starts_with(found_ref, "refs/heads/")) {
522 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
523 oid_to_hex(&branch_head), remote);
524 goto cleanup;
525 }
526 if (starts_with(found_ref, "refs/tags/")) {
527 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
528 oid_to_hex(&branch_head), remote);
529 goto cleanup;
530 }
531 if (starts_with(found_ref, "refs/remotes/")) {
532 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
533 oid_to_hex(&branch_head), remote);
534 goto cleanup;
535 }
536 }
537
538 /* See if remote matches <name>^^^.. or <name>~<number> */
539 for (len = 0, ptr = remote + strlen(remote);
540 remote < ptr && ptr[-1] == '^';
541 ptr--)
542 len++;
543 if (len)
544 early = 1;
545 else {
546 early = 0;
547 ptr = strrchr(remote, '~');
548 if (ptr) {
549 int seen_nonzero = 0;
550
551 len++; /* count ~ */
552 while (*++ptr && isdigit(*ptr)) {
553 seen_nonzero |= (*ptr != '0');
554 len++;
555 }
556 if (*ptr)
557 len = 0; /* not ...~<number> */
558 else if (seen_nonzero)
559 early = 1;
560 else if (len == 1)
561 early = 1; /* "name~" is "name~1"! */
562 }
563 }
564 if (len) {
565 struct strbuf truname = STRBUF_INIT;
566 strbuf_addf(&truname, "refs/heads/%s", remote);
567 strbuf_setlen(&truname, truname.len - len);
568 if (ref_exists(truname.buf)) {
569 strbuf_addf(msg,
570 "%s\t\tbranch '%s'%s of .\n",
571 oid_to_hex(&remote_head->object.oid),
572 truname.buf + 11,
573 (early ? " (early part)" : ""));
574 strbuf_release(&truname);
575 goto cleanup;
576 }
577 strbuf_release(&truname);
578 }
579
580 desc = merge_remote_util(remote_head);
581 if (desc && desc->obj && desc->obj->type == OBJ_TAG) {
582 strbuf_addf(msg, "%s\t\t%s '%s'\n",
583 oid_to_hex(&desc->obj->oid),
584 type_name(desc->obj->type),
585 remote);
586 goto cleanup;
587 }
588
589 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
590 oid_to_hex(&remote_head->object.oid), remote);
591 cleanup:
592 free(found_ref);
593 strbuf_release(&bname);
594 }
595
596 static void parse_branch_merge_options(char *bmo)
597 {
598 const char **argv;
599 int argc;
600
601 if (!bmo)
602 return;
603 argc = split_cmdline(bmo, &argv);
604 if (argc < 0)
605 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
606 _(split_cmdline_strerror(argc)));
607 REALLOC_ARRAY(argv, argc + 2);
608 MOVE_ARRAY(argv + 1, argv, argc + 1);
609 argc++;
610 argv[0] = "branch.*.mergeoptions";
611 parse_options(argc, argv, NULL, builtin_merge_options,
612 builtin_merge_usage, 0);
613 free(argv);
614 }
615
616 static int git_merge_config(const char *k, const char *v, void *cb)
617 {
618 int status;
619 const char *str;
620
621 if (branch &&
622 skip_prefix(k, "branch.", &str) &&
623 skip_prefix(str, branch, &str) &&
624 !strcmp(str, ".mergeoptions")) {
625 free(branch_mergeoptions);
626 branch_mergeoptions = xstrdup(v);
627 return 0;
628 }
629
630 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
631 show_diffstat = git_config_bool(k, v);
632 else if (!strcmp(k, "merge.verifysignatures"))
633 verify_signatures = git_config_bool(k, v);
634 else if (!strcmp(k, "pull.twohead"))
635 return git_config_string(&pull_twohead, k, v);
636 else if (!strcmp(k, "pull.octopus"))
637 return git_config_string(&pull_octopus, k, v);
638 else if (!strcmp(k, "commit.cleanup"))
639 return git_config_string(&cleanup_arg, k, v);
640 else if (!strcmp(k, "merge.ff")) {
641 int boolval = git_parse_maybe_bool(v);
642 if (0 <= boolval) {
643 fast_forward = boolval ? FF_ALLOW : FF_NO;
644 } else if (v && !strcmp(v, "only")) {
645 fast_forward = FF_ONLY;
646 } /* do not barf on values from future versions of git */
647 return 0;
648 } else if (!strcmp(k, "merge.defaulttoupstream")) {
649 default_to_upstream = git_config_bool(k, v);
650 return 0;
651 } else if (!strcmp(k, "commit.gpgsign")) {
652 sign_commit = git_config_bool(k, v) ? "" : NULL;
653 return 0;
654 } else if (!strcmp(k, "gpg.mintrustlevel")) {
655 check_trust_level = 0;
656 } else if (!strcmp(k, "merge.autostash")) {
657 autostash = git_config_bool(k, v);
658 return 0;
659 }
660
661 status = fmt_merge_msg_config(k, v, cb);
662 if (status)
663 return status;
664 status = git_gpg_config(k, v, NULL);
665 if (status)
666 return status;
667 return git_diff_ui_config(k, v, cb);
668 }
669
670 static int read_tree_trivial(struct object_id *common, struct object_id *head,
671 struct object_id *one)
672 {
673 int i, nr_trees = 0;
674 struct tree *trees[MAX_UNPACK_TREES];
675 struct tree_desc t[MAX_UNPACK_TREES];
676 struct unpack_trees_options opts;
677
678 memset(&opts, 0, sizeof(opts));
679 opts.head_idx = 2;
680 opts.src_index = &the_index;
681 opts.dst_index = &the_index;
682 opts.update = 1;
683 opts.verbose_update = 1;
684 opts.trivial_merges_only = 1;
685 opts.merge = 1;
686 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
687 trees[nr_trees] = parse_tree_indirect(common);
688 if (!trees[nr_trees++])
689 return -1;
690 trees[nr_trees] = parse_tree_indirect(head);
691 if (!trees[nr_trees++])
692 return -1;
693 trees[nr_trees] = parse_tree_indirect(one);
694 if (!trees[nr_trees++])
695 return -1;
696 opts.fn = threeway_merge;
697 cache_tree_free(&the_index.cache_tree);
698 for (i = 0; i < nr_trees; i++) {
699 parse_tree(trees[i]);
700 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
701 }
702 if (unpack_trees(nr_trees, t, &opts))
703 return -1;
704 return 0;
705 }
706
707 static void write_tree_trivial(struct object_id *oid)
708 {
709 if (write_cache_as_tree(oid, 0, NULL))
710 die(_("git write-tree failed to write a tree"));
711 }
712
713 static int try_merge_strategy(const char *strategy, struct commit_list *common,
714 struct commit_list *remoteheads,
715 struct commit *head)
716 {
717 const char *head_arg = "HEAD";
718
719 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
720 SKIP_IF_UNCHANGED, 0, NULL, NULL,
721 NULL) < 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 repo_hold_locked_index(the_repository, &lock,
756 LOCK_DIE_ON_ERROR);
757 if (!strcmp(strategy, "ort"))
758 clean = merge_ort_recursive(&o, head, remoteheads->item,
759 reversed, &result);
760 else
761 clean = merge_recursive(&o, head, remoteheads->item,
762 reversed, &result);
763 if (clean < 0) {
764 rollback_lock_file(&lock);
765 return 2;
766 }
767 if (write_locked_index(&the_index, &lock,
768 COMMIT_LOCK | SKIP_IF_UNCHANGED))
769 die(_("unable to write %s"), get_index_file());
770 return clean ? 0 : 1;
771 } else {
772 return try_merge_command(the_repository,
773 strategy, xopts_nr, xopts,
774 common, head_arg, remoteheads);
775 }
776 }
777
778 static void count_diff_files(struct diff_queue_struct *q,
779 struct diff_options *opt UNUSED, void *data)
780 {
781 int *count = data;
782
783 (*count) += q->nr;
784 }
785
786 static int count_unmerged_entries(void)
787 {
788 int i, ret = 0;
789
790 for (i = 0; i < the_index.cache_nr; i++)
791 if (ce_stage(the_index.cache[i]))
792 ret++;
793
794 return ret;
795 }
796
797 static void add_strategies(const char *string, unsigned attr)
798 {
799 int i;
800
801 if (string) {
802 struct string_list list = STRING_LIST_INIT_DUP;
803 struct string_list_item *item;
804 string_list_split(&list, string, ' ', -1);
805 for_each_string_list_item(item, &list)
806 append_strategy(get_strategy(item->string));
807 string_list_clear(&list, 0);
808 return;
809 }
810 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
811 if (all_strategy[i].attr & attr)
812 append_strategy(&all_strategy[i]);
813
814 }
815
816 static void read_merge_msg(struct strbuf *msg)
817 {
818 const char *filename = git_path_merge_msg(the_repository);
819 strbuf_reset(msg);
820 if (strbuf_read_file(msg, filename, 0) < 0)
821 die_errno(_("Could not read from '%s'"), filename);
822 }
823
824 static void write_merge_state(struct commit_list *);
825 static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
826 {
827 if (err_msg)
828 error("%s", err_msg);
829 fprintf(stderr,
830 _("Not committing merge; use 'git commit' to complete the merge.\n"));
831 write_merge_state(remoteheads);
832 exit(1);
833 }
834
835 static const char merge_editor_comment[] =
836 N_("Please enter a commit message to explain why this merge is necessary,\n"
837 "especially if it merges an updated upstream into a topic branch.\n"
838 "\n");
839
840 static const char scissors_editor_comment[] =
841 N_("An empty message aborts the commit.\n");
842
843 static const char no_scissors_editor_comment[] =
844 N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
845 "the commit.\n");
846
847 static void write_merge_heads(struct commit_list *);
848 static void prepare_to_commit(struct commit_list *remoteheads)
849 {
850 struct strbuf msg = STRBUF_INIT;
851 const char *index_file = get_index_file();
852
853 if (!no_verify) {
854 int invoked_hook;
855
856 if (run_commit_hook(0 < option_edit, index_file, &invoked_hook,
857 "pre-merge-commit", NULL))
858 abort_commit(remoteheads, NULL);
859 /*
860 * Re-read the index as pre-merge-commit hook could have updated it,
861 * and write it out as a tree. We must do this before we invoke
862 * the editor and after we invoke run_status above.
863 */
864 if (invoked_hook)
865 discard_index(&the_index);
866 }
867 read_index_from(&the_index, index_file, get_git_dir());
868 strbuf_addbuf(&msg, &merge_msg);
869 if (squash)
870 BUG("the control must not reach here under --squash");
871 if (0 < option_edit) {
872 strbuf_addch(&msg, '\n');
873 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
874 wt_status_append_cut_line(&msg);
875 strbuf_commented_addf(&msg, "\n");
876 }
877 strbuf_commented_addf(&msg, _(merge_editor_comment));
878 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
879 strbuf_commented_addf(&msg, _(scissors_editor_comment));
880 else
881 strbuf_commented_addf(&msg,
882 _(no_scissors_editor_comment), comment_line_char);
883 }
884 if (signoff)
885 append_signoff(&msg, ignore_non_trailer(msg.buf, msg.len), 0);
886 write_merge_heads(remoteheads);
887 write_file_buf(git_path_merge_msg(the_repository), msg.buf, msg.len);
888 if (run_commit_hook(0 < option_edit, get_index_file(), NULL,
889 "prepare-commit-msg",
890 git_path_merge_msg(the_repository), "merge", NULL))
891 abort_commit(remoteheads, NULL);
892 if (0 < option_edit) {
893 if (launch_editor(git_path_merge_msg(the_repository), NULL, NULL))
894 abort_commit(remoteheads, NULL);
895 }
896
897 if (!no_verify && run_commit_hook(0 < option_edit, get_index_file(),
898 NULL, "commit-msg",
899 git_path_merge_msg(the_repository), NULL))
900 abort_commit(remoteheads, NULL);
901
902 read_merge_msg(&msg);
903 cleanup_message(&msg, cleanup_mode, 0);
904 if (!msg.len)
905 abort_commit(remoteheads, _("Empty commit message."));
906 strbuf_release(&merge_msg);
907 strbuf_addbuf(&merge_msg, &msg);
908 strbuf_release(&msg);
909 }
910
911 static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
912 {
913 struct object_id result_tree, result_commit;
914 struct commit_list *parents, **pptr = &parents;
915
916 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
917 SKIP_IF_UNCHANGED, 0, NULL, NULL,
918 NULL) < 0)
919 return error(_("Unable to write index."));
920
921 write_tree_trivial(&result_tree);
922 printf(_("Wonderful.\n"));
923 pptr = commit_list_append(head, pptr);
924 pptr = commit_list_append(remoteheads->item, pptr);
925 prepare_to_commit(remoteheads);
926 if (commit_tree(merge_msg.buf, merge_msg.len, &result_tree, parents,
927 &result_commit, NULL, sign_commit))
928 die(_("failed to write commit object"));
929 finish(head, remoteheads, &result_commit, "In-index merge");
930 remove_merge_branch_state(the_repository);
931 return 0;
932 }
933
934 static int finish_automerge(struct commit *head,
935 int head_subsumed,
936 struct commit_list *common,
937 struct commit_list *remoteheads,
938 struct object_id *result_tree,
939 const char *wt_strategy)
940 {
941 struct commit_list *parents = NULL;
942 struct strbuf buf = STRBUF_INIT;
943 struct object_id result_commit;
944
945 write_tree_trivial(result_tree);
946 free_commit_list(common);
947 parents = remoteheads;
948 if (!head_subsumed || fast_forward == FF_NO)
949 commit_list_insert(head, &parents);
950 prepare_to_commit(remoteheads);
951 if (commit_tree(merge_msg.buf, merge_msg.len, result_tree, parents,
952 &result_commit, NULL, sign_commit))
953 die(_("failed to write commit object"));
954 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
955 finish(head, remoteheads, &result_commit, buf.buf);
956 strbuf_release(&buf);
957 remove_merge_branch_state(the_repository);
958 return 0;
959 }
960
961 static int suggest_conflicts(void)
962 {
963 const char *filename;
964 FILE *fp;
965 struct strbuf msgbuf = STRBUF_INIT;
966
967 filename = git_path_merge_msg(the_repository);
968 fp = xfopen(filename, "a");
969
970 /*
971 * We can't use cleanup_mode because if we're not using the editor,
972 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
973 * though the message is meant to be processed later by git-commit.
974 * Thus, we will get the cleanup mode which is returned when we _are_
975 * using an editor.
976 */
977 append_conflicts_hint(&the_index, &msgbuf,
978 get_cleanup_mode(cleanup_arg, 1));
979 fputs(msgbuf.buf, fp);
980 strbuf_release(&msgbuf);
981 fclose(fp);
982 repo_rerere(the_repository, allow_rerere_auto);
983 printf(_("Automatic merge failed; "
984 "fix conflicts and then commit the result.\n"));
985 return 1;
986 }
987
988 static int evaluate_result(void)
989 {
990 int cnt = 0;
991 struct rev_info rev;
992
993 /* Check how many files differ. */
994 repo_init_revisions(the_repository, &rev, "");
995 setup_revisions(0, NULL, &rev, NULL);
996 rev.diffopt.output_format |=
997 DIFF_FORMAT_CALLBACK;
998 rev.diffopt.format_callback = count_diff_files;
999 rev.diffopt.format_callback_data = &cnt;
1000 run_diff_files(&rev, 0);
1001
1002 /*
1003 * Check how many unmerged entries are
1004 * there.
1005 */
1006 cnt += count_unmerged_entries();
1007
1008 release_revisions(&rev);
1009 return cnt;
1010 }
1011
1012 /*
1013 * Pretend as if the user told us to merge with the remote-tracking
1014 * branch we have for the upstream of the current branch
1015 */
1016 static int setup_with_upstream(const char ***argv)
1017 {
1018 struct branch *branch = branch_get(NULL);
1019 int i;
1020 const char **args;
1021
1022 if (!branch)
1023 die(_("No current branch."));
1024 if (!branch->remote_name)
1025 die(_("No remote for the current branch."));
1026 if (!branch->merge_nr)
1027 die(_("No default upstream defined for the current branch."));
1028
1029 args = xcalloc(st_add(branch->merge_nr, 1), sizeof(char *));
1030 for (i = 0; i < branch->merge_nr; i++) {
1031 if (!branch->merge[i]->dst)
1032 die(_("No remote-tracking branch for %s from %s"),
1033 branch->merge[i]->src, branch->remote_name);
1034 args[i] = branch->merge[i]->dst;
1035 }
1036 args[i] = NULL;
1037 *argv = args;
1038 return i;
1039 }
1040
1041 static void write_merge_heads(struct commit_list *remoteheads)
1042 {
1043 struct commit_list *j;
1044 struct strbuf buf = STRBUF_INIT;
1045
1046 for (j = remoteheads; j; j = j->next) {
1047 struct object_id *oid;
1048 struct commit *c = j->item;
1049 struct merge_remote_desc *desc;
1050
1051 desc = merge_remote_util(c);
1052 if (desc && desc->obj) {
1053 oid = &desc->obj->oid;
1054 } else {
1055 oid = &c->object.oid;
1056 }
1057 strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
1058 }
1059 write_file_buf(git_path_merge_head(the_repository), buf.buf, buf.len);
1060
1061 strbuf_reset(&buf);
1062 if (fast_forward == FF_NO)
1063 strbuf_addstr(&buf, "no-ff");
1064 write_file_buf(git_path_merge_mode(the_repository), buf.buf, buf.len);
1065 strbuf_release(&buf);
1066 }
1067
1068 static void write_merge_state(struct commit_list *remoteheads)
1069 {
1070 write_merge_heads(remoteheads);
1071 strbuf_addch(&merge_msg, '\n');
1072 write_file_buf(git_path_merge_msg(the_repository), merge_msg.buf,
1073 merge_msg.len);
1074 }
1075
1076 static int default_edit_option(void)
1077 {
1078 static const char name[] = "GIT_MERGE_AUTOEDIT";
1079 const char *e = getenv(name);
1080 struct stat st_stdin, st_stdout;
1081
1082 if (have_message)
1083 /* an explicit -m msg without --[no-]edit */
1084 return 0;
1085
1086 if (e) {
1087 int v = git_parse_maybe_bool(e);
1088 if (v < 0)
1089 die(_("Bad value '%s' in environment '%s'"), e, name);
1090 return v;
1091 }
1092
1093 /* Use editor if stdin and stdout are the same and is a tty */
1094 return (!fstat(0, &st_stdin) &&
1095 !fstat(1, &st_stdout) &&
1096 isatty(0) && isatty(1) &&
1097 st_stdin.st_dev == st_stdout.st_dev &&
1098 st_stdin.st_ino == st_stdout.st_ino &&
1099 st_stdin.st_mode == st_stdout.st_mode);
1100 }
1101
1102 static struct commit_list *reduce_parents(struct commit *head_commit,
1103 int *head_subsumed,
1104 struct commit_list *remoteheads)
1105 {
1106 struct commit_list *parents, **remotes;
1107
1108 /*
1109 * Is the current HEAD reachable from another commit being
1110 * merged? If so we do not want to record it as a parent of
1111 * the resulting merge, unless --no-ff is given. We will flip
1112 * this variable to 0 when we find HEAD among the independent
1113 * tips being merged.
1114 */
1115 *head_subsumed = 1;
1116
1117 /* Find what parents to record by checking independent ones. */
1118 parents = reduce_heads(remoteheads);
1119 free_commit_list(remoteheads);
1120
1121 remoteheads = NULL;
1122 remotes = &remoteheads;
1123 while (parents) {
1124 struct commit *commit = pop_commit(&parents);
1125 if (commit == head_commit)
1126 *head_subsumed = 0;
1127 else
1128 remotes = &commit_list_insert(commit, remotes)->next;
1129 }
1130 return remoteheads;
1131 }
1132
1133 static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *merge_msg)
1134 {
1135 struct fmt_merge_msg_opts opts;
1136
1137 memset(&opts, 0, sizeof(opts));
1138 opts.add_title = !have_message;
1139 opts.shortlog_len = shortlog_len;
1140 opts.credit_people = (0 < option_edit);
1141 opts.into_name = into_name;
1142
1143 fmt_merge_msg(merge_names, merge_msg, &opts);
1144 if (merge_msg->len)
1145 strbuf_setlen(merge_msg, merge_msg->len - 1);
1146 }
1147
1148 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
1149 {
1150 const char *filename;
1151 int fd, pos, npos;
1152 struct strbuf fetch_head_file = STRBUF_INIT;
1153 const unsigned hexsz = the_hash_algo->hexsz;
1154
1155 if (!merge_names)
1156 merge_names = &fetch_head_file;
1157
1158 filename = git_path_fetch_head(the_repository);
1159 fd = xopen(filename, O_RDONLY);
1160
1161 if (strbuf_read(merge_names, fd, 0) < 0)
1162 die_errno(_("could not read '%s'"), filename);
1163 if (close(fd) < 0)
1164 die_errno(_("could not close '%s'"), filename);
1165
1166 for (pos = 0; pos < merge_names->len; pos = npos) {
1167 struct object_id oid;
1168 char *ptr;
1169 struct commit *commit;
1170
1171 ptr = strchr(merge_names->buf + pos, '\n');
1172 if (ptr)
1173 npos = ptr - merge_names->buf + 1;
1174 else
1175 npos = merge_names->len;
1176
1177 if (npos - pos < hexsz + 2 ||
1178 get_oid_hex(merge_names->buf + pos, &oid))
1179 commit = NULL; /* bad */
1180 else if (memcmp(merge_names->buf + pos + hexsz, "\t\t", 2))
1181 continue; /* not-for-merge */
1182 else {
1183 char saved = merge_names->buf[pos + hexsz];
1184 merge_names->buf[pos + hexsz] = '\0';
1185 commit = get_merge_parent(merge_names->buf + pos);
1186 merge_names->buf[pos + hexsz] = saved;
1187 }
1188 if (!commit) {
1189 if (ptr)
1190 *ptr = '\0';
1191 die(_("not something we can merge in %s: %s"),
1192 filename, merge_names->buf + pos);
1193 }
1194 remotes = &commit_list_insert(commit, remotes)->next;
1195 }
1196
1197 if (merge_names == &fetch_head_file)
1198 strbuf_release(&fetch_head_file);
1199 }
1200
1201 static struct commit_list *collect_parents(struct commit *head_commit,
1202 int *head_subsumed,
1203 int argc, const char **argv,
1204 struct strbuf *merge_msg)
1205 {
1206 int i;
1207 struct commit_list *remoteheads = NULL;
1208 struct commit_list **remotes = &remoteheads;
1209 struct strbuf merge_names = STRBUF_INIT, *autogen = NULL;
1210
1211 if (merge_msg && (!have_message || shortlog_len))
1212 autogen = &merge_names;
1213
1214 if (head_commit)
1215 remotes = &commit_list_insert(head_commit, remotes)->next;
1216
1217 if (argc == 1 && !strcmp(argv[0], "FETCH_HEAD")) {
1218 handle_fetch_head(remotes, autogen);
1219 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1220 } else {
1221 for (i = 0; i < argc; i++) {
1222 struct commit *commit = get_merge_parent(argv[i]);
1223 if (!commit)
1224 help_unknown_ref(argv[i], "merge",
1225 _("not something we can merge"));
1226 remotes = &commit_list_insert(commit, remotes)->next;
1227 }
1228 remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
1229 if (autogen) {
1230 struct commit_list *p;
1231 for (p = remoteheads; p; p = p->next)
1232 merge_name(merge_remote_util(p->item)->name, autogen);
1233 }
1234 }
1235
1236 if (autogen) {
1237 prepare_merge_message(autogen, merge_msg);
1238 strbuf_release(autogen);
1239 }
1240
1241 return remoteheads;
1242 }
1243
1244 static int merging_a_throwaway_tag(struct commit *commit)
1245 {
1246 char *tag_ref;
1247 struct object_id oid;
1248 int is_throwaway_tag = 0;
1249
1250 /* Are we merging a tag? */
1251 if (!merge_remote_util(commit) ||
1252 !merge_remote_util(commit)->obj ||
1253 merge_remote_util(commit)->obj->type != OBJ_TAG)
1254 return is_throwaway_tag;
1255
1256 /*
1257 * Now we know we are merging a tag object. Are we downstream
1258 * and following the tags from upstream? If so, we must have
1259 * the tag object pointed at by "refs/tags/$T" where $T is the
1260 * tagname recorded in the tag object. We want to allow such
1261 * a "just to catch up" merge to fast-forward.
1262 *
1263 * Otherwise, we are playing an integrator's role, making a
1264 * merge with a throw-away tag from a contributor with
1265 * something like "git pull $contributor $signed_tag".
1266 * We want to forbid such a merge from fast-forwarding
1267 * by default; otherwise we would not keep the signature
1268 * anywhere.
1269 */
1270 tag_ref = xstrfmt("refs/tags/%s",
1271 ((struct tag *)merge_remote_util(commit)->obj)->tag);
1272 if (!read_ref(tag_ref, &oid) &&
1273 oideq(&oid, &merge_remote_util(commit)->obj->oid))
1274 is_throwaway_tag = 0;
1275 else
1276 is_throwaway_tag = 1;
1277 free(tag_ref);
1278 return is_throwaway_tag;
1279 }
1280
1281 int cmd_merge(int argc, const char **argv, const char *prefix)
1282 {
1283 struct object_id result_tree, stash, head_oid;
1284 struct commit *head_commit;
1285 struct strbuf buf = STRBUF_INIT;
1286 int i, ret = 0, head_subsumed;
1287 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1288 struct commit_list *common = NULL;
1289 const char *best_strategy = NULL, *wt_strategy = NULL;
1290 struct commit_list *remoteheads = NULL, *p;
1291 void *branch_to_free;
1292 int orig_argc = argc;
1293
1294 if (argc == 2 && !strcmp(argv[1], "-h"))
1295 usage_with_options(builtin_merge_usage, builtin_merge_options);
1296
1297 prepare_repo_settings(the_repository);
1298 the_repository->settings.command_requires_full_index = 0;
1299
1300 /*
1301 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1302 * current branch.
1303 */
1304 branch = branch_to_free = resolve_refdup("HEAD", 0, &head_oid, NULL);
1305 if (branch)
1306 skip_prefix(branch, "refs/heads/", &branch);
1307
1308 if (!pull_twohead) {
1309 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1310 if (default_strategy && !strcmp(default_strategy, "ort"))
1311 pull_twohead = "ort";
1312 }
1313
1314 init_diff_ui_defaults();
1315 git_config(git_merge_config, NULL);
1316
1317 if (!branch || is_null_oid(&head_oid))
1318 head_commit = NULL;
1319 else
1320 head_commit = lookup_commit_or_die(&head_oid, "HEAD");
1321
1322 if (branch_mergeoptions)
1323 parse_branch_merge_options(branch_mergeoptions);
1324 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1325 builtin_merge_usage, 0);
1326 if (shortlog_len < 0)
1327 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1328
1329 if (verbosity < 0 && show_progress == -1)
1330 show_progress = 0;
1331
1332 if (abort_current_merge) {
1333 int nargc = 2;
1334 const char *nargv[] = {"reset", "--merge", NULL};
1335 struct strbuf stash_oid = STRBUF_INIT;
1336
1337 if (orig_argc != 2)
1338 usage_msg_opt(_("--abort expects no arguments"),
1339 builtin_merge_usage, builtin_merge_options);
1340
1341 if (!file_exists(git_path_merge_head(the_repository)))
1342 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1343
1344 if (read_oneliner(&stash_oid, git_path_merge_autostash(the_repository),
1345 READ_ONELINER_SKIP_IF_EMPTY))
1346 unlink(git_path_merge_autostash(the_repository));
1347
1348 /* Invoke 'git reset --merge' */
1349 ret = cmd_reset(nargc, nargv, prefix);
1350
1351 if (stash_oid.len)
1352 apply_autostash_oid(stash_oid.buf);
1353
1354 strbuf_release(&stash_oid);
1355 goto done;
1356 }
1357
1358 if (quit_current_merge) {
1359 if (orig_argc != 2)
1360 usage_msg_opt(_("--quit expects no arguments"),
1361 builtin_merge_usage,
1362 builtin_merge_options);
1363
1364 remove_merge_branch_state(the_repository);
1365 goto done;
1366 }
1367
1368 if (continue_current_merge) {
1369 int nargc = 1;
1370 const char *nargv[] = {"commit", NULL};
1371
1372 if (orig_argc != 2)
1373 usage_msg_opt(_("--continue expects no arguments"),
1374 builtin_merge_usage, builtin_merge_options);
1375
1376 if (!file_exists(git_path_merge_head(the_repository)))
1377 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1378
1379 /* Invoke 'git commit' */
1380 ret = cmd_commit(nargc, nargv, prefix);
1381 goto done;
1382 }
1383
1384 if (repo_read_index_unmerged(the_repository))
1385 die_resolve_conflict("merge");
1386
1387 if (file_exists(git_path_merge_head(the_repository))) {
1388 /*
1389 * There is no unmerged entry, don't advise 'git
1390 * add/rm <file>', just 'git commit'.
1391 */
1392 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1393 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1394 "Please, commit your changes before you merge."));
1395 else
1396 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1397 }
1398 if (ref_exists("CHERRY_PICK_HEAD")) {
1399 if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
1400 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1401 "Please, commit your changes before you merge."));
1402 else
1403 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1404 }
1405 resolve_undo_clear_index(&the_index);
1406
1407 if (option_edit < 0)
1408 option_edit = default_edit_option();
1409
1410 cleanup_mode = get_cleanup_mode(cleanup_arg, 0 < option_edit);
1411
1412 if (verbosity < 0)
1413 show_diffstat = 0;
1414
1415 if (squash) {
1416 if (fast_forward == FF_NO)
1417 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1418 if (option_commit > 0)
1419 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1420 /*
1421 * squash can now silently disable option_commit - this is not
1422 * a problem as it is only overriding the default, not a user
1423 * supplied option.
1424 */
1425 option_commit = 0;
1426 }
1427
1428 if (option_commit < 0)
1429 option_commit = 1;
1430
1431 if (!argc) {
1432 if (default_to_upstream)
1433 argc = setup_with_upstream(&argv);
1434 else
1435 die(_("No commit specified and merge.defaultToUpstream not set."));
1436 } else if (argc == 1 && !strcmp(argv[0], "-")) {
1437 argv[0] = "@{-1}";
1438 }
1439
1440 if (!argc)
1441 usage_with_options(builtin_merge_usage,
1442 builtin_merge_options);
1443
1444 if (!head_commit) {
1445 /*
1446 * If the merged head is a valid one there is no reason
1447 * to forbid "git merge" into a branch yet to be born.
1448 * We do the same for "git pull".
1449 */
1450 struct object_id *remote_head_oid;
1451 if (squash)
1452 die(_("Squash commit into empty head not supported yet"));
1453 if (fast_forward == FF_NO)
1454 die(_("Non-fast-forward commit does not make sense into "
1455 "an empty head"));
1456 remoteheads = collect_parents(head_commit, &head_subsumed,
1457 argc, argv, NULL);
1458 if (!remoteheads)
1459 die(_("%s - not something we can merge"), argv[0]);
1460 if (remoteheads->next)
1461 die(_("Can merge only exactly one commit into empty head"));
1462
1463 if (verify_signatures)
1464 verify_merge_signature(remoteheads->item, verbosity,
1465 check_trust_level);
1466
1467 remote_head_oid = &remoteheads->item->object.oid;
1468 read_empty(remote_head_oid);
1469 update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
1470 UPDATE_REFS_DIE_ON_ERR);
1471 goto done;
1472 }
1473
1474 /*
1475 * All the rest are the commits being merged; prepare
1476 * the standard merge summary message to be appended
1477 * to the given message.
1478 */
1479 remoteheads = collect_parents(head_commit, &head_subsumed,
1480 argc, argv, &merge_msg);
1481
1482 if (!head_commit || !argc)
1483 usage_with_options(builtin_merge_usage,
1484 builtin_merge_options);
1485
1486 if (verify_signatures) {
1487 for (p = remoteheads; p; p = p->next) {
1488 verify_merge_signature(p->item, verbosity,
1489 check_trust_level);
1490 }
1491 }
1492
1493 strbuf_addstr(&buf, "merge");
1494 for (p = remoteheads; p; p = p->next)
1495 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1496 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1497 strbuf_reset(&buf);
1498
1499 for (p = remoteheads; p; p = p->next) {
1500 struct commit *commit = p->item;
1501 strbuf_addf(&buf, "GITHEAD_%s",
1502 oid_to_hex(&commit->object.oid));
1503 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1504 strbuf_reset(&buf);
1505 if (fast_forward != FF_ONLY && merging_a_throwaway_tag(commit))
1506 fast_forward = FF_NO;
1507 }
1508
1509 if (!use_strategies && !pull_twohead &&
1510 remoteheads && !remoteheads->next) {
1511 char *default_strategy = getenv("GIT_TEST_MERGE_ALGORITHM");
1512 if (default_strategy)
1513 append_strategy(get_strategy(default_strategy));
1514 }
1515 if (!use_strategies) {
1516 if (!remoteheads)
1517 ; /* already up-to-date */
1518 else if (!remoteheads->next)
1519 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1520 else
1521 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1522 }
1523
1524 for (i = 0; i < use_strategies_nr; i++) {
1525 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1526 fast_forward = FF_NO;
1527 if (use_strategies[i]->attr & NO_TRIVIAL)
1528 allow_trivial = 0;
1529 }
1530
1531 if (!remoteheads)
1532 ; /* already up-to-date */
1533 else if (!remoteheads->next)
1534 common = get_merge_bases(head_commit, remoteheads->item);
1535 else {
1536 struct commit_list *list = remoteheads;
1537 commit_list_insert(head_commit, &list);
1538 common = get_octopus_merge_bases(list);
1539 free(list);
1540 }
1541
1542 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1543 &head_commit->object.oid, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1544
1545 if (remoteheads && !common) {
1546 /* No common ancestors found. */
1547 if (!allow_unrelated_histories)
1548 die(_("refusing to merge unrelated histories"));
1549 /* otherwise, we need a real merge. */
1550 } else if (!remoteheads ||
1551 (!remoteheads->next && !common->next &&
1552 common->item == remoteheads->item)) {
1553 /*
1554 * If head can reach all the merge then we are up to date.
1555 * but first the most common case of merging one remote.
1556 */
1557 finish_up_to_date();
1558 goto done;
1559 } else if (fast_forward != FF_NO && !remoteheads->next &&
1560 !common->next &&
1561 oideq(&common->item->object.oid, &head_commit->object.oid)) {
1562 /* Again the most common case of merging one remote. */
1563 struct strbuf msg = STRBUF_INIT;
1564 struct commit *commit;
1565
1566 if (verbosity >= 0) {
1567 printf(_("Updating %s..%s\n"),
1568 find_unique_abbrev(&head_commit->object.oid,
1569 DEFAULT_ABBREV),
1570 find_unique_abbrev(&remoteheads->item->object.oid,
1571 DEFAULT_ABBREV));
1572 }
1573 strbuf_addstr(&msg, "Fast-forward");
1574 if (have_message)
1575 strbuf_addstr(&msg,
1576 " (no commit created; -m option ignored)");
1577 commit = remoteheads->item;
1578 if (!commit) {
1579 ret = 1;
1580 goto done;
1581 }
1582
1583 if (autostash)
1584 create_autostash(the_repository,
1585 git_path_merge_autostash(the_repository));
1586 if (checkout_fast_forward(the_repository,
1587 &head_commit->object.oid,
1588 &commit->object.oid,
1589 overwrite_ignore)) {
1590 apply_autostash(git_path_merge_autostash(the_repository));
1591 ret = 1;
1592 goto done;
1593 }
1594
1595 finish(head_commit, remoteheads, &commit->object.oid, msg.buf);
1596 remove_merge_branch_state(the_repository);
1597 strbuf_release(&msg);
1598 goto done;
1599 } else if (!remoteheads->next && common->next)
1600 ;
1601 /*
1602 * We are not doing octopus and not fast-forward. Need
1603 * a real merge.
1604 */
1605 else if (!remoteheads->next && !common->next && option_commit) {
1606 /*
1607 * We are not doing octopus, not fast-forward, and have
1608 * only one common.
1609 */
1610 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
1611 if (allow_trivial && fast_forward != FF_ONLY) {
1612 /*
1613 * Must first ensure that index matches HEAD before
1614 * attempting a trivial merge.
1615 */
1616 struct tree *head_tree = get_commit_tree(head_commit);
1617 struct strbuf sb = STRBUF_INIT;
1618
1619 if (repo_index_has_changes(the_repository, head_tree,
1620 &sb)) {
1621 error(_("Your local changes to the following files would be overwritten by merge:\n %s"),
1622 sb.buf);
1623 strbuf_release(&sb);
1624 return 2;
1625 }
1626
1627 /* See if it is really trivial. */
1628 git_committer_info(IDENT_STRICT);
1629 printf(_("Trying really trivial in-index merge...\n"));
1630 if (!read_tree_trivial(&common->item->object.oid,
1631 &head_commit->object.oid,
1632 &remoteheads->item->object.oid)) {
1633 ret = merge_trivial(head_commit, remoteheads);
1634 goto done;
1635 }
1636 printf(_("Nope.\n"));
1637 }
1638 } else {
1639 /*
1640 * An octopus. If we can reach all the remote we are up
1641 * to date.
1642 */
1643 int up_to_date = 1;
1644 struct commit_list *j;
1645
1646 for (j = remoteheads; j; j = j->next) {
1647 struct commit_list *common_one;
1648
1649 /*
1650 * Here we *have* to calculate the individual
1651 * merge_bases again, otherwise "git merge HEAD^
1652 * HEAD^^" would be missed.
1653 */
1654 common_one = get_merge_bases(head_commit, j->item);
1655 if (!oideq(&common_one->item->object.oid, &j->item->object.oid)) {
1656 up_to_date = 0;
1657 break;
1658 }
1659 }
1660 if (up_to_date) {
1661 finish_up_to_date();
1662 goto done;
1663 }
1664 }
1665
1666 if (fast_forward == FF_ONLY)
1667 die_ff_impossible();
1668
1669 if (autostash)
1670 create_autostash(the_repository,
1671 git_path_merge_autostash(the_repository));
1672
1673 /* We are going to make a new commit. */
1674 git_committer_info(IDENT_STRICT);
1675
1676 /*
1677 * At this point, we need a real merge. No matter what strategy
1678 * we use, it would operate on the index, possibly affecting the
1679 * working tree, and when resolved cleanly, have the desired
1680 * tree in the index -- this means that the index must be in
1681 * sync with the head commit. The strategies are responsible
1682 * to ensure this.
1683 *
1684 * Stash away the local changes so that we can try more than one
1685 * and/or recover from merge strategies bailing while leaving the
1686 * index and working tree polluted.
1687 */
1688 if (save_state(&stash))
1689 oidclr(&stash);
1690
1691 for (i = 0; i < use_strategies_nr; i++) {
1692 int ret, cnt;
1693 if (i) {
1694 printf(_("Rewinding the tree to pristine...\n"));
1695 restore_state(&head_commit->object.oid, &stash);
1696 }
1697 if (use_strategies_nr != 1)
1698 printf(_("Trying merge strategy %s...\n"),
1699 use_strategies[i]->name);
1700 /*
1701 * Remember which strategy left the state in the working
1702 * tree.
1703 */
1704 wt_strategy = use_strategies[i]->name;
1705
1706 ret = try_merge_strategy(wt_strategy,
1707 common, remoteheads,
1708 head_commit);
1709 /*
1710 * The backend exits with 1 when conflicts are
1711 * left to be resolved, with 2 when it does not
1712 * handle the given merge at all.
1713 */
1714 if (ret < 2) {
1715 if (!ret) {
1716 /*
1717 * This strategy worked; no point in trying
1718 * another.
1719 */
1720 merge_was_ok = 1;
1721 best_strategy = wt_strategy;
1722 break;
1723 }
1724 cnt = (use_strategies_nr > 1) ? evaluate_result() : 0;
1725 if (best_cnt <= 0 || cnt <= best_cnt) {
1726 best_strategy = wt_strategy;
1727 best_cnt = cnt;
1728 }
1729 }
1730 }
1731
1732 /*
1733 * If we have a resulting tree, that means the strategy module
1734 * auto resolved the merge cleanly.
1735 */
1736 if (merge_was_ok && option_commit) {
1737 automerge_was_ok = 1;
1738 ret = finish_automerge(head_commit, head_subsumed,
1739 common, remoteheads,
1740 &result_tree, wt_strategy);
1741 goto done;
1742 }
1743
1744 /*
1745 * Pick the result from the best strategy and have the user fix
1746 * it up.
1747 */
1748 if (!best_strategy) {
1749 restore_state(&head_commit->object.oid, &stash);
1750 if (use_strategies_nr > 1)
1751 fprintf(stderr,
1752 _("No merge strategy handled the merge.\n"));
1753 else
1754 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1755 use_strategies[0]->name);
1756 apply_autostash(git_path_merge_autostash(the_repository));
1757 ret = 2;
1758 goto done;
1759 } else if (best_strategy == wt_strategy)
1760 ; /* We already have its result in the working tree. */
1761 else {
1762 printf(_("Rewinding the tree to pristine...\n"));
1763 restore_state(&head_commit->object.oid, &stash);
1764 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1765 best_strategy);
1766 try_merge_strategy(best_strategy, common, remoteheads,
1767 head_commit);
1768 }
1769
1770 if (squash) {
1771 finish(head_commit, remoteheads, NULL, NULL);
1772
1773 git_test_write_commit_graph_or_die();
1774 } else
1775 write_merge_state(remoteheads);
1776
1777 if (merge_was_ok)
1778 fprintf(stderr, _("Automatic merge went well; "
1779 "stopped before committing as requested\n"));
1780 else
1781 ret = suggest_conflicts();
1782 if (autostash)
1783 printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1784
1785 done:
1786 if (!automerge_was_ok) {
1787 free_commit_list(common);
1788 free_commit_list(remoteheads);
1789 }
1790 strbuf_release(&buf);
1791 free(branch_to_free);
1792 discard_index(&the_index);
1793 return ret;
1794 }