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