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