builtin/merge.c: collect other parents early
[git/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[] = {
93e535a5 43 "git merge [options] [<commit>...]",
c395c25b
JH
44 "git merge [options] <msg> HEAD <commit>",
45 "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;
3adab6f3 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,
183 "do not show a diffstat at the end of the merge",
184 PARSE_OPT_NOARG, option_parse_n },
185 OPT_BOOLEAN(0, "stat", &show_diffstat,
186 "show a diffstat at the end of the merge"),
187 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
96e9420c
RR
188 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
189 "add (at most <n>) entries from shortlog to merge commit message",
190 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
1c7b76be
MV
191 OPT_BOOLEAN(0, "squash", &squash,
192 "create a single commit instead of doing a merge"),
193 OPT_BOOLEAN(0, "commit", &option_commit,
194 "perform a commit if the merge succeeds (default)"),
3adab6f3 195 OPT_BOOL('e', "edit", &option_edit,
66f4b98a 196 "edit message before committing"),
1c7b76be 197 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
a75d7b54 198 "allow fast-forward (default)"),
13474835 199 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
4d8c3258 200 "abort if fast-forward is not possible"),
cb6020bb 201 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
1c7b76be
MV
202 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
203 "merge strategy to use", option_parse_strategy),
8cc5b290
AP
204 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
205 "option for selected merge strategy", option_parse_x),
23c6a803 206 OPT_CALLBACK('m', "message", &merge_msg, "message",
3f406175 207 "merge commit message (for a non-fast-forward merge)",
1c7b76be 208 option_parse_message),
7f87aff2 209 OPT__VERBOSITY(&verbosity),
35d2fffd
JH
210 OPT_BOOLEAN(0, "abort", &abort_current_merge,
211 "abort the current in-progress merge"),
99bfc669 212 OPT_SET_INT(0, "progress", &show_progress, "force progress reporting", 1),
ba3c69a9
JH
213 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, "key id",
214 "GPG sign commit", PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
c1d7036b 215 OPT_BOOLEAN(0, "overwrite-ignore", &overwrite_ignore, "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);
402 opts.output_format |=
403 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
404 opts.detect_rename = DIFF_DETECT_RENAME;
1c7b76be 405 if (diff_setup_done(&opts) < 0)
bacec478 406 die(_("diff_setup_done failed"));
1c7b76be
MV
407 diff_tree_sha1(head, new_head, "", &opts);
408 diffcore_std(&opts);
409 diff_flush(&opts);
410 }
411
412 /* Run a post-merge hook */
ae98a008 413 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
1c7b76be
MV
414
415 strbuf_release(&reflog_message);
416}
417
418/* Get the name for the merge commit's message. */
419static void merge_name(const char *remote, struct strbuf *msg)
420{
ae8e4c9c 421 struct commit *remote_head;
c6893323 422 unsigned char branch_head[20];
f285a2d7 423 struct strbuf buf = STRBUF_INIT;
c9717ee9 424 struct strbuf bname = STRBUF_INIT;
1c7b76be 425 const char *ptr;
751c5974 426 char *found_ref;
1c7b76be
MV
427 int len, early;
428
a552de75
JH
429 strbuf_branchname(&bname, remote);
430 remote = bname.buf;
c9717ee9 431
1c7b76be 432 memset(branch_head, 0, sizeof(branch_head));
ae8e4c9c 433 remote_head = get_merge_parent(remote);
1c7b76be 434 if (!remote_head)
bacec478 435 die(_("'%s' does not point to a commit"), remote);
1c7b76be 436
751c5974
JK
437 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
438 if (!prefixcmp(found_ref, "refs/heads/")) {
439 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
440 sha1_to_hex(branch_head), remote);
441 goto cleanup;
442 }
57b58db7
JH
443 if (!prefixcmp(found_ref, "refs/tags/")) {
444 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
445 sha1_to_hex(branch_head), remote);
446 goto cleanup;
447 }
69a8b7c7 448 if (!prefixcmp(found_ref, "refs/remotes/")) {
13931236 449 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
69a8b7c7
JK
450 sha1_to_hex(branch_head), remote);
451 goto cleanup;
452 }
1c7b76be
MV
453 }
454
455 /* See if remote matches <name>^^^.. or <name>~<number> */
456 for (len = 0, ptr = remote + strlen(remote);
457 remote < ptr && ptr[-1] == '^';
458 ptr--)
459 len++;
460 if (len)
461 early = 1;
462 else {
463 early = 0;
464 ptr = strrchr(remote, '~');
465 if (ptr) {
466 int seen_nonzero = 0;
467
468 len++; /* count ~ */
469 while (*++ptr && isdigit(*ptr)) {
470 seen_nonzero |= (*ptr != '0');
471 len++;
472 }
473 if (*ptr)
474 len = 0; /* not ...~<number> */
475 else if (seen_nonzero)
476 early = 1;
477 else if (len == 1)
478 early = 1; /* "name~" is "name~1"! */
479 }
480 }
481 if (len) {
482 struct strbuf truname = STRBUF_INIT;
483 strbuf_addstr(&truname, "refs/heads/");
484 strbuf_addstr(&truname, remote);
9b6bf4d5 485 strbuf_setlen(&truname, truname.len - len);
c6893323 486 if (ref_exists(truname.buf)) {
1c7b76be
MV
487 strbuf_addf(msg,
488 "%s\t\tbranch '%s'%s of .\n",
ae8e4c9c 489 sha1_to_hex(remote_head->object.sha1),
9b6bf4d5 490 truname.buf + 11,
1c7b76be 491 (early ? " (early part)" : ""));
c9717ee9
JH
492 strbuf_release(&truname);
493 goto cleanup;
1c7b76be
MV
494 }
495 }
496
497 if (!strcmp(remote, "FETCH_HEAD") &&
498 !access(git_path("FETCH_HEAD"), R_OK)) {
418c9b17 499 const char *filename;
1c7b76be 500 FILE *fp;
f285a2d7 501 struct strbuf line = STRBUF_INIT;
1c7b76be
MV
502 char *ptr;
503
418c9b17
JN
504 filename = git_path("FETCH_HEAD");
505 fp = fopen(filename, "r");
1c7b76be 506 if (!fp)
bacec478 507 die_errno(_("could not open '%s' for reading"),
418c9b17 508 filename);
1c7b76be
MV
509 strbuf_getline(&line, fp, '\n');
510 fclose(fp);
511 ptr = strstr(line.buf, "\tnot-for-merge\t");
512 if (ptr)
513 strbuf_remove(&line, ptr-line.buf+1, 13);
514 strbuf_addbuf(msg, &line);
515 strbuf_release(&line);
c9717ee9 516 goto cleanup;
1c7b76be
MV
517 }
518 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
ae8e4c9c 519 sha1_to_hex(remote_head->object.sha1), remote);
c9717ee9
JH
520cleanup:
521 strbuf_release(&buf);
522 strbuf_release(&bname);
1c7b76be
MV
523}
524
0d8fc3ef
JH
525static void parse_branch_merge_options(char *bmo)
526{
527 const char **argv;
528 int argc;
529
530 if (!bmo)
531 return;
532 argc = split_cmdline(bmo, &argv);
533 if (argc < 0)
c7fe5b61
JH
534 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
535 split_cmdline_strerror(argc));
0d8fc3ef
JH
536 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
537 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
538 argc++;
539 argv[0] = "branch.*.mergeoptions";
540 parse_options(argc, argv, NULL, builtin_merge_options,
541 builtin_merge_usage, 0);
542 free(argv);
543}
544
186458b1 545static int git_merge_config(const char *k, const char *v, void *cb)
1c7b76be 546{
898eacd8
JH
547 int status;
548
1c7b76be
MV
549 if (branch && !prefixcmp(k, "branch.") &&
550 !prefixcmp(k + 7, branch) &&
551 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
0d8fc3ef
JH
552 free(branch_mergeoptions);
553 branch_mergeoptions = xstrdup(v);
554 return 0;
1c7b76be
MV
555 }
556
557 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
558 show_diffstat = git_config_bool(k, v);
559 else if (!strcmp(k, "pull.twohead"))
560 return git_config_string(&pull_twohead, k, v);
561 else if (!strcmp(k, "pull.octopus"))
562 return git_config_string(&pull_octopus, k, v);
7610fa57
JN
563 else if (!strcmp(k, "merge.renormalize"))
564 option_renormalize = git_config_bool(k, v);
898eacd8 565 else if (!strcmp(k, "merge.ff")) {
f23e8dec
JH
566 int boolval = git_config_maybe_bool(k, v);
567 if (0 <= boolval) {
568 allow_fast_forward = boolval;
569 } else if (v && !strcmp(v, "only")) {
570 allow_fast_forward = 1;
571 fast_forward_only = 1;
572 } /* do not barf on values from future versions of git */
573 return 0;
93e535a5
JH
574 } else if (!strcmp(k, "merge.defaulttoupstream")) {
575 default_to_upstream = git_config_bool(k, v);
576 return 0;
96e9420c 577 }
ba3c69a9 578
898eacd8 579 status = fmt_merge_msg_config(k, v, cb);
5de89d3a
JH
580 if (status)
581 return status;
ba3c69a9 582 status = git_gpg_config(k, v, NULL);
898eacd8
JH
583 if (status)
584 return status;
1c7b76be
MV
585 return git_diff_ui_config(k, v, cb);
586}
587
588static int read_tree_trivial(unsigned char *common, unsigned char *head,
589 unsigned char *one)
590{
591 int i, nr_trees = 0;
592 struct tree *trees[MAX_UNPACK_TREES];
593 struct tree_desc t[MAX_UNPACK_TREES];
594 struct unpack_trees_options opts;
595
596 memset(&opts, 0, sizeof(opts));
597 opts.head_idx = 2;
598 opts.src_index = &the_index;
599 opts.dst_index = &the_index;
600 opts.update = 1;
601 opts.verbose_update = 1;
602 opts.trivial_merges_only = 1;
603 opts.merge = 1;
604 trees[nr_trees] = parse_tree_indirect(common);
605 if (!trees[nr_trees++])
606 return -1;
607 trees[nr_trees] = parse_tree_indirect(head);
608 if (!trees[nr_trees++])
609 return -1;
610 trees[nr_trees] = parse_tree_indirect(one);
611 if (!trees[nr_trees++])
612 return -1;
613 opts.fn = threeway_merge;
614 cache_tree_free(&active_cache_tree);
615 for (i = 0; i < nr_trees; i++) {
616 parse_tree(trees[i]);
617 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
618 }
619 if (unpack_trees(nr_trees, t, &opts))
620 return -1;
621 return 0;
622}
623
624static void write_tree_trivial(unsigned char *sha1)
625{
626 if (write_cache_as_tree(sha1, 0, NULL))
bacec478 627 die(_("git write-tree failed to write a tree"));
1c7b76be
MV
628}
629
16180734
JK
630static const char *merge_argument(struct commit *commit)
631{
632 if (commit)
633 return sha1_to_hex(commit->object.sha1);
634 else
635 return EMPTY_TREE_SHA1_HEX;
636}
637
67ac1e1d
JN
638int try_merge_command(const char *strategy, size_t xopts_nr,
639 const char **xopts, struct commit_list *common,
c674d052 640 const char *head_arg, struct commit_list *remotes)
1c7b76be
MV
641{
642 const char **args;
8cc5b290 643 int i = 0, x = 0, ret;
1c7b76be 644 struct commit_list *j;
f285a2d7 645 struct strbuf buf = STRBUF_INIT;
3f9083cd
CC
646
647 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
648 commit_list_count(remotes)) * sizeof(char *));
649 strbuf_addf(&buf, "merge-%s", strategy);
650 args[i++] = buf.buf;
651 for (x = 0; x < xopts_nr; x++) {
652 char *s = xmalloc(strlen(xopts[x])+2+1);
653 strcpy(s, "--");
654 strcpy(s+2, xopts[x]);
655 args[i++] = s;
656 }
657 for (j = common; j; j = j->next)
16180734 658 args[i++] = xstrdup(merge_argument(j->item));
3f9083cd
CC
659 args[i++] = "--";
660 args[i++] = head_arg;
661 for (j = remotes; j; j = j->next)
16180734 662 args[i++] = xstrdup(merge_argument(j->item));
3f9083cd
CC
663 args[i] = NULL;
664 ret = run_command_v_opt(args, RUN_GIT_CMD);
665 strbuf_release(&buf);
666 i = 1;
667 for (x = 0; x < xopts_nr; x++)
668 free((void *)args[i++]);
669 for (j = common; j; j = j->next)
670 free((void *)args[i++]);
671 i += 2;
672 for (j = remotes; j; j = j->next)
673 free((void *)args[i++]);
674 free(args);
675 discard_cache();
676 if (read_cache() < 0)
bacec478 677 die(_("failed to read the cache"));
3f9083cd
CC
678 resolve_undo_clear();
679
680 return ret;
681}
682
683static int try_merge_strategy(const char *strategy, struct commit_list *common,
4c57bd27 684 struct commit_list *remoteheads,
894642f6 685 struct commit *head, const char *head_arg)
3f9083cd 686{
668f26ff
MV
687 int index_fd;
688 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
689
690 index_fd = hold_locked_index(lock, 1);
691 refresh_cache(REFRESH_QUIET);
692 if (active_cache_changed &&
693 (write_cache(index_fd, active_cache, active_nr) ||
694 commit_locked_index(lock)))
bacec478 695 return error(_("Unable to write index."));
668f26ff 696 rollback_lock_file(lock);
1c7b76be 697
18668f53 698 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
3f9083cd 699 int clean, x;
18668f53
MV
700 struct commit *result;
701 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
702 int index_fd;
703 struct commit_list *reversed = NULL;
704 struct merge_options o;
3f9083cd 705 struct commit_list *j;
18668f53
MV
706
707 if (remoteheads->next) {
bacec478 708 error(_("Not handling anything other than two heads merge."));
18668f53
MV
709 return 2;
710 }
711
712 init_merge_options(&o);
713 if (!strcmp(strategy, "subtree"))
85e51b78 714 o.subtree_shift = "";
8cc5b290 715
7610fa57 716 o.renormalize = option_renormalize;
99bfc669
JK
717 o.show_rename_progress =
718 show_progress == -1 ? isatty(2) : show_progress;
7610fa57 719
635a7bb1
JN
720 for (x = 0; x < xopts_nr; x++)
721 if (parse_merge_opt(&o, xopts[x]))
bacec478 722 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
18668f53
MV
723
724 o.branch1 = head_arg;
ae8e4c9c 725 o.branch2 = merge_remote_util(remoteheads->item)->name;
18668f53
MV
726
727 for (j = common; j; j = j->next)
728 commit_list_insert(j->item, &reversed);
729
730 index_fd = hold_locked_index(lock, 1);
894642f6 731 clean = merge_recursive(&o, head,
18668f53
MV
732 remoteheads->item, reversed, &result);
733 if (active_cache_changed &&
734 (write_cache(index_fd, active_cache, active_nr) ||
735 commit_locked_index(lock)))
bacec478 736 die (_("unable to write %s"), get_index_file());
42716660 737 rollback_lock_file(lock);
18668f53
MV
738 return clean ? 0 : 1;
739 } else {
67ac1e1d
JN
740 return try_merge_command(strategy, xopts_nr, xopts,
741 common, head_arg, remoteheads);
18668f53 742 }
1c7b76be
MV
743}
744
745static void count_diff_files(struct diff_queue_struct *q,
746 struct diff_options *opt, void *data)
747{
748 int *count = data;
749
750 (*count) += q->nr;
751}
752
753static int count_unmerged_entries(void)
754{
1c7b76be
MV
755 int i, ret = 0;
756
be6ff819
JH
757 for (i = 0; i < active_nr; i++)
758 if (ce_stage(active_cache[i]))
1c7b76be
MV
759 ret++;
760
761 return ret;
762}
763
cac42b26 764int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
1c7b76be
MV
765{
766 struct tree *trees[MAX_UNPACK_TREES];
767 struct unpack_trees_options opts;
768 struct tree_desc t[MAX_UNPACK_TREES];
769 int i, fd, nr_trees = 0;
770 struct dir_struct dir;
771 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
772
9ca8f607 773 refresh_cache(REFRESH_QUIET);
1c7b76be
MV
774
775 fd = hold_locked_index(lock_file, 1);
776
777 memset(&trees, 0, sizeof(trees));
778 memset(&opts, 0, sizeof(opts));
779 memset(&t, 0, sizeof(t));
c1d7036b
NTND
780 if (overwrite_ignore) {
781 memset(&dir, 0, sizeof(dir));
782 dir.flags |= DIR_SHOW_IGNORED;
783 setup_standard_excludes(&dir);
784 opts.dir = &dir;
785 }
1c7b76be
MV
786
787 opts.head_idx = 1;
788 opts.src_index = &the_index;
789 opts.dst_index = &the_index;
790 opts.update = 1;
791 opts.verbose_update = 1;
792 opts.merge = 1;
793 opts.fn = twoway_merge;
e294030f 794 setup_unpack_trees_porcelain(&opts, "merge");
1c7b76be
MV
795
796 trees[nr_trees] = parse_tree_indirect(head);
797 if (!trees[nr_trees++])
798 return -1;
799 trees[nr_trees] = parse_tree_indirect(remote);
800 if (!trees[nr_trees++])
801 return -1;
802 for (i = 0; i < nr_trees; i++) {
803 parse_tree(trees[i]);
804 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
805 }
806 if (unpack_trees(nr_trees, t, &opts))
807 return -1;
808 if (write_cache(fd, active_cache, active_nr) ||
809 commit_locked_index(lock_file))
bacec478 810 die(_("unable to write new index file"));
1c7b76be
MV
811 return 0;
812}
813
814static void split_merge_strategies(const char *string, struct strategy **list,
815 int *nr, int *alloc)
816{
817 char *p, *q, *buf;
818
819 if (!string)
820 return;
821
822 buf = xstrdup(string);
823 q = buf;
824 for (;;) {
825 p = strchr(q, ' ');
826 if (!p) {
827 ALLOC_GROW(*list, *nr + 1, *alloc);
828 (*list)[(*nr)++].name = xstrdup(q);
829 free(buf);
830 return;
831 } else {
832 *p = '\0';
833 ALLOC_GROW(*list, *nr + 1, *alloc);
834 (*list)[(*nr)++].name = xstrdup(q);
835 q = ++p;
836 }
837 }
838}
839
840static void add_strategies(const char *string, unsigned attr)
841{
842 struct strategy *list = NULL;
843 int list_alloc = 0, list_nr = 0, i;
844
845 memset(&list, 0, sizeof(list));
846 split_merge_strategies(string, &list, &list_nr, &list_alloc);
1719b5e4
MV
847 if (list) {
848 for (i = 0; i < list_nr; i++)
849 append_strategy(get_strategy(list[i].name));
1c7b76be
MV
850 return;
851 }
852 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
853 if (all_strategy[i].attr & attr)
854 append_strategy(&all_strategy[i]);
855
856}
857
66f4b98a 858static void write_merge_msg(struct strbuf *msg)
65969d43 859{
418c9b17
JN
860 const char *filename = git_path("MERGE_MSG");
861 int fd = open(filename, O_WRONLY | O_CREAT, 0666);
65969d43 862 if (fd < 0)
6c80cd29 863 die_errno(_("Could not open '%s' for writing"),
418c9b17 864 filename);
66f4b98a 865 if (write_in_full(fd, msg->buf, msg->len) != msg->len)
418c9b17 866 die_errno(_("Could not write to '%s'"), filename);
65969d43
JS
867 close(fd);
868}
869
66f4b98a 870static void read_merge_msg(struct strbuf *msg)
65969d43 871{
418c9b17 872 const char *filename = git_path("MERGE_MSG");
66f4b98a 873 strbuf_reset(msg);
418c9b17
JN
874 if (strbuf_read_file(msg, filename, 0) < 0)
875 die_errno(_("Could not read from '%s'"), filename);
65969d43
JS
876}
877
4c57bd27
JH
878static void write_merge_state(struct commit_list *);
879static void abort_commit(struct commit_list *remoteheads, const char *err_msg)
65969d43 880{
66f4b98a
JS
881 if (err_msg)
882 error("%s", err_msg);
883 fprintf(stderr,
884 _("Not committing merge; use 'git commit' to complete the merge.\n"));
4c57bd27 885 write_merge_state(remoteheads);
66f4b98a
JS
886 exit(1);
887}
888
f26af3fc
TR
889static const char merge_editor_comment[] =
890N_("Please enter a commit message to explain why this merge is necessary,\n"
891 "especially if it merges an updated upstream into a topic branch.\n"
892 "\n"
893 "Lines starting with '#' will be ignored, and an empty message aborts\n"
894 "the commit.\n");
895
4c57bd27 896static void prepare_to_commit(struct commit_list *remoteheads)
66f4b98a
JS
897{
898 struct strbuf msg = STRBUF_INIT;
f26af3fc 899 const char *comment = _(merge_editor_comment);
66f4b98a
JS
900 strbuf_addbuf(&msg, &merge_msg);
901 strbuf_addch(&msg, '\n');
f26af3fc
TR
902 if (0 < option_edit)
903 strbuf_add_lines(&msg, "# ", comment, strlen(comment));
66f4b98a 904 write_merge_msg(&msg);
65969d43
JS
905 run_hook(get_index_file(), "prepare-commit-msg",
906 git_path("MERGE_MSG"), "merge", NULL, NULL);
66f4b98a
JS
907 if (option_edit) {
908 if (launch_editor(git_path("MERGE_MSG"), NULL, NULL))
4c57bd27 909 abort_commit(remoteheads, NULL);
66f4b98a
JS
910 }
911 read_merge_msg(&msg);
912 stripspace(&msg, option_edit);
913 if (!msg.len)
4c57bd27 914 abort_commit(remoteheads, _("Empty commit message."));
66f4b98a
JS
915 strbuf_release(&merge_msg);
916 strbuf_addbuf(&merge_msg, &msg);
917 strbuf_release(&msg);
65969d43
JS
918}
919
4c57bd27 920static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
1c7b76be
MV
921{
922 unsigned char result_tree[20], result_commit[20];
36e40535 923 struct commit_list *parent = xmalloc(sizeof(*parent));
1c7b76be
MV
924
925 write_tree_trivial(result_tree);
157efde1 926 printf(_("Wonderful.\n"));
894642f6 927 parent->item = head;
36e40535 928 parent->next = xmalloc(sizeof(*parent->next));
446247db
JH
929 parent->next->item = remoteheads->item;
930 parent->next->next = NULL;
4c57bd27 931 prepare_to_commit(remoteheads);
5de89d3a
JH
932 if (commit_tree(&merge_msg, result_tree, parent, result_commit, NULL,
933 sign_commit))
6b3c4c05 934 die(_("failed to write commit object"));
4c57bd27 935 finish(head, remoteheads, result_commit, "In-index merge");
1c7b76be
MV
936 drop_save();
937 return 0;
938}
939
894642f6
NTND
940static int finish_automerge(struct commit *head,
941 struct commit_list *common,
4c57bd27 942 struct commit_list *remoteheads,
1c7b76be
MV
943 unsigned char *result_tree,
944 const char *wt_strategy)
945{
946 struct commit_list *parents = NULL, *j;
947 struct strbuf buf = STRBUF_INIT;
948 unsigned char result_commit[20];
949
950 free_commit_list(common);
951 if (allow_fast_forward) {
952 parents = remoteheads;
894642f6 953 commit_list_insert(head, &parents);
1c7b76be
MV
954 parents = reduce_heads(parents);
955 } else {
956 struct commit_list **pptr = &parents;
957
894642f6 958 pptr = &commit_list_insert(head,
1c7b76be
MV
959 pptr)->next;
960 for (j = remoteheads; j; j = j->next)
961 pptr = &commit_list_insert(j->item, pptr)->next;
962 }
1c7b76be 963 strbuf_addch(&merge_msg, '\n');
4c57bd27 964 prepare_to_commit(remoteheads);
66f4b98a 965 free_commit_list(remoteheads);
5de89d3a
JH
966 if (commit_tree(&merge_msg, result_tree, parents, result_commit,
967 NULL, sign_commit))
6b3c4c05 968 die(_("failed to write commit object"));
f23101bf 969 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
4c57bd27 970 finish(head, remoteheads, result_commit, buf.buf);
1c7b76be
MV
971 strbuf_release(&buf);
972 drop_save();
973 return 0;
974}
975
7610fa57 976static int suggest_conflicts(int renormalizing)
1c7b76be 977{
418c9b17 978 const char *filename;
1c7b76be
MV
979 FILE *fp;
980 int pos;
981
418c9b17
JN
982 filename = git_path("MERGE_MSG");
983 fp = fopen(filename, "a");
1c7b76be 984 if (!fp)
418c9b17 985 die_errno(_("Could not open '%s' for writing"), filename);
1c7b76be
MV
986 fprintf(fp, "\nConflicts:\n");
987 for (pos = 0; pos < active_nr; pos++) {
988 struct cache_entry *ce = active_cache[pos];
989
990 if (ce_stage(ce)) {
991 fprintf(fp, "\t%s\n", ce->name);
992 while (pos + 1 < active_nr &&
993 !strcmp(ce->name,
994 active_cache[pos + 1]->name))
995 pos++;
996 }
997 }
998 fclose(fp);
cb6020bb 999 rerere(allow_rerere_auto);
bacec478
ÆAB
1000 printf(_("Automatic merge failed; "
1001 "fix conflicts and then commit the result.\n"));
1c7b76be
MV
1002 return 1;
1003}
1004
894642f6
NTND
1005static struct commit *is_old_style_invocation(int argc, const char **argv,
1006 const unsigned char *head)
1c7b76be
MV
1007{
1008 struct commit *second_token = NULL;
76bf488e 1009 if (argc > 2) {
1c7b76be
MV
1010 unsigned char second_sha1[20];
1011
1012 if (get_sha1(argv[1], second_sha1))
1013 return NULL;
1014 second_token = lookup_commit_reference_gently(second_sha1, 0);
1015 if (!second_token)
bacec478 1016 die(_("'%s' is not a commit"), argv[1]);
1c7b76be
MV
1017 if (hashcmp(second_token->object.sha1, head))
1018 return NULL;
1019 }
1020 return second_token;
1021}
1022
1023static int evaluate_result(void)
1024{
1025 int cnt = 0;
1026 struct rev_info rev;
1027
1c7b76be
MV
1028 /* Check how many files differ. */
1029 init_revisions(&rev, "");
1030 setup_revisions(0, NULL, &rev, NULL);
1031 rev.diffopt.output_format |=
1032 DIFF_FORMAT_CALLBACK;
1033 rev.diffopt.format_callback = count_diff_files;
1034 rev.diffopt.format_callback_data = &cnt;
1035 run_diff_files(&rev, 0);
1036
1037 /*
1038 * Check how many unmerged entries are
1039 * there.
1040 */
1041 cnt += count_unmerged_entries();
1042
1043 return cnt;
1044}
1045
93e535a5
JH
1046/*
1047 * Pretend as if the user told us to merge with the tracking
1048 * branch we have for the upstream of the current branch
1049 */
1050static int setup_with_upstream(const char ***argv)
1051{
1052 struct branch *branch = branch_get(NULL);
1053 int i;
1054 const char **args;
1055
1056 if (!branch)
c7f426d4 1057 die(_("No current branch."));
93e535a5 1058 if (!branch->remote)
c7f426d4 1059 die(_("No remote for the current branch."));
93e535a5 1060 if (!branch->merge_nr)
c7f426d4 1061 die(_("No default upstream defined for the current branch."));
93e535a5
JH
1062
1063 args = xcalloc(branch->merge_nr + 1, sizeof(char *));
1064 for (i = 0; i < branch->merge_nr; i++) {
1065 if (!branch->merge[i]->dst)
c7f426d4 1066 die(_("No remote tracking branch for %s from %s"),
93e535a5
JH
1067 branch->merge[i]->src, branch->remote_name);
1068 args[i] = branch->merge[i]->dst;
1069 }
1070 args[i] = NULL;
1071 *argv = args;
1072 return i;
1073}
1074
4c57bd27 1075static void write_merge_state(struct commit_list *remoteheads)
66f4b98a 1076{
418c9b17 1077 const char *filename;
66f4b98a
JS
1078 int fd;
1079 struct commit_list *j;
1080 struct strbuf buf = STRBUF_INIT;
1081
274a5c06
JH
1082 for (j = remoteheads; j; j = j->next) {
1083 unsigned const char *sha1;
1084 struct commit *c = j->item;
1085 if (c->util && merge_remote_util(c)->obj) {
1086 sha1 = merge_remote_util(c)->obj->sha1;
1087 } else {
1088 sha1 = c->object.sha1;
1089 }
1090 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
1091 }
418c9b17
JN
1092 filename = git_path("MERGE_HEAD");
1093 fd = open(filename, O_WRONLY | O_CREAT, 0666);
66f4b98a 1094 if (fd < 0)
418c9b17 1095 die_errno(_("Could not open '%s' for writing"), filename);
66f4b98a 1096 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
418c9b17 1097 die_errno(_("Could not write to '%s'"), filename);
66f4b98a
JS
1098 close(fd);
1099 strbuf_addch(&merge_msg, '\n');
1100 write_merge_msg(&merge_msg);
418c9b17
JN
1101
1102 filename = git_path("MERGE_MODE");
1103 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
66f4b98a 1104 if (fd < 0)
418c9b17 1105 die_errno(_("Could not open '%s' for writing"), filename);
66f4b98a
JS
1106 strbuf_reset(&buf);
1107 if (!allow_fast_forward)
1108 strbuf_addf(&buf, "no-ff");
1109 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
418c9b17 1110 die_errno(_("Could not write to '%s'"), filename);
66f4b98a
JS
1111 close(fd);
1112}
1113
d387868a
JH
1114static int default_edit_option(void)
1115{
1116 static const char name[] = "GIT_MERGE_AUTOEDIT";
1117 const char *e = getenv(name);
1118 struct stat st_stdin, st_stdout;
1119
1120 if (have_message)
1121 /* an explicit -m msg without --[no-]edit */
1122 return 0;
1123
1124 if (e) {
1125 int v = git_config_maybe_bool(name, e);
1126 if (v < 0)
1127 die("Bad value '%s' in environment '%s'", e, name);
1128 return v;
1129 }
1130
1131 /* Use editor if stdin and stdout are the same and is a tty */
1132 return (!fstat(0, &st_stdin) &&
1133 !fstat(1, &st_stdout) &&
1134 isatty(0) && isatty(1) &&
1135 st_stdin.st_dev == st_stdout.st_dev &&
1136 st_stdin.st_ino == st_stdout.st_ino &&
1137 st_stdin.st_mode == st_stdout.st_mode);
1138}
1139
b5d887f9
JH
1140static struct commit_list *collect_parents(int argc, const char **argv)
1141{
1142 int i;
1143 struct commit_list *remoteheads = NULL;
1144 struct commit_list **remotes = &remoteheads;
1145
1146 for (i = 0; i < argc; i++) {
1147 struct commit *commit = get_merge_parent(argv[i]);
1148 if (!commit)
1149 die(_("%s - not something we can merge"), argv[i]);
1150 remotes = &commit_list_insert(commit, remotes)->next;
1151 }
1152 *remotes = NULL;
1153 return remoteheads;
1154}
d387868a 1155
1c7b76be
MV
1156int cmd_merge(int argc, const char **argv, const char *prefix)
1157{
1158 unsigned char result_tree[20];
b4fd9406 1159 unsigned char stash[20];
894642f6
NTND
1160 unsigned char head_sha1[20];
1161 struct commit *head_commit;
f285a2d7 1162 struct strbuf buf = STRBUF_INIT;
1c7b76be 1163 const char *head_arg;
d5a35c11 1164 int flag, i, ret = 0;
1c7b76be
MV
1165 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1166 struct commit_list *common = NULL;
1167 const char *best_strategy = NULL, *wt_strategy = NULL;
b5d887f9 1168 struct commit_list *remoteheads, *p;
96ec7b1e 1169 void *branch_to_free;
1c7b76be 1170
da53eec6
NTND
1171 if (argc == 2 && !strcmp(argv[1], "-h"))
1172 usage_with_options(builtin_merge_usage, builtin_merge_options);
1c7b76be
MV
1173
1174 /*
1175 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1176 * current branch.
1177 */
96ec7b1e
NTND
1178 branch = branch_to_free = resolve_refdup("HEAD", head_sha1, 0, &flag);
1179 if (branch && !prefixcmp(branch, "refs/heads/"))
1180 branch += 11;
894642f6
NTND
1181 if (!branch || is_null_sha1(head_sha1))
1182 head_commit = NULL;
baf18fc2
NTND
1183 else
1184 head_commit = lookup_commit_or_die(head_sha1, "HEAD");
1c7b76be
MV
1185
1186 git_config(git_merge_config, NULL);
1187
0d8fc3ef
JH
1188 if (branch_mergeoptions)
1189 parse_branch_merge_options(branch_mergeoptions);
37782920 1190 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1c7b76be 1191 builtin_merge_usage, 0);
898eacd8
JH
1192 if (shortlog_len < 0)
1193 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
2a22c1b3 1194
99bfc669
JK
1195 if (verbosity < 0 && show_progress == -1)
1196 show_progress = 0;
1197
35d2fffd
JH
1198 if (abort_current_merge) {
1199 int nargc = 2;
1200 const char *nargv[] = {"reset", "--merge", NULL};
1201
1202 if (!file_exists(git_path("MERGE_HEAD")))
bacec478 1203 die(_("There is no merge to abort (MERGE_HEAD missing)."));
35d2fffd
JH
1204
1205 /* Invoke 'git reset --merge' */
d5a35c11
NTND
1206 ret = cmd_reset(nargc, nargv, prefix);
1207 goto done;
35d2fffd
JH
1208 }
1209
2a22c1b3
JH
1210 if (read_cache_unmerged())
1211 die_resolve_conflict("merge");
1212
1213 if (file_exists(git_path("MERGE_HEAD"))) {
1214 /*
1215 * There is no unmerged entry, don't advise 'git
1216 * add/rm <file>', just 'git commit'.
1217 */
1218 if (advice_resolve_conflict)
bacec478
ÆAB
1219 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1220 "Please, commit your changes before you can merge."));
2a22c1b3 1221 else
bacec478 1222 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
2a22c1b3 1223 }
d7e5c0cb
JS
1224 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1225 if (advice_resolve_conflict)
f68f1801
ÆAB
1226 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1227 "Please, commit your changes before you can merge."));
d7e5c0cb 1228 else
f68f1801 1229 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
2a22c1b3
JH
1230 }
1231 resolve_undo_clear();
1232
7f87aff2
TA
1233 if (verbosity < 0)
1234 show_diffstat = 0;
1c7b76be
MV
1235
1236 if (squash) {
1237 if (!allow_fast_forward)
bacec478 1238 die(_("You cannot combine --squash with --no-ff."));
1c7b76be
MV
1239 option_commit = 0;
1240 }
1241
13474835 1242 if (!allow_fast_forward && fast_forward_only)
bacec478 1243 die(_("You cannot combine --no-ff with --ff-only."));
13474835 1244
4e8115ff 1245 if (!abort_current_merge) {
5480207c
VR
1246 if (!argc) {
1247 if (default_to_upstream)
1248 argc = setup_with_upstream(&argv);
1249 else
1250 die(_("No commit specified and merge.defaultToUpstream not set."));
1251 } else if (argc == 1 && !strcmp(argv[0], "-"))
4e8115ff
JH
1252 argv[0] = "@{-1}";
1253 }
1c7b76be
MV
1254 if (!argc)
1255 usage_with_options(builtin_merge_usage,
1256 builtin_merge_options);
1257
1258 /*
1259 * This could be traditional "merge <msg> HEAD <commit>..." and
1260 * the way we can tell it is to see if the second token is HEAD,
1261 * but some people might have misused the interface and used a
1262 * committish that is the same as HEAD there instead.
1263 * Traditional format never would have "-m" so it is an
1264 * additional safety measure to check for it.
1265 */
1c7b76be 1266
894642f6
NTND
1267 if (!have_message && head_commit &&
1268 is_old_style_invocation(argc, argv, head_commit->object.sha1)) {
1c7b76be
MV
1269 strbuf_addstr(&merge_msg, argv[0]);
1270 head_arg = argv[1];
1271 argv += 2;
1272 argc -= 2;
b5d887f9 1273 remoteheads = collect_parents(argc, argv);
894642f6 1274 } else if (!head_commit) {
ae8e4c9c 1275 struct commit *remote_head;
1c7b76be
MV
1276 /*
1277 * If the merged head is a valid one there is no reason
1278 * to forbid "git merge" into a branch yet to be born.
1279 * We do the same for "git pull".
1280 */
1281 if (argc != 1)
bacec478
ÆAB
1282 die(_("Can merge only exactly one commit into "
1283 "empty head"));
4be636f4 1284 if (squash)
bacec478 1285 die(_("Squash commit into empty head not supported yet"));
4be636f4 1286 if (!allow_fast_forward)
bacec478
ÆAB
1287 die(_("Non-fast-forward commit does not make sense into "
1288 "an empty head"));
b5d887f9
JH
1289 remoteheads = collect_parents(argc, argv);
1290 remote_head = remoteheads->item;
1c7b76be 1291 if (!remote_head)
bacec478 1292 die(_("%s - not something we can merge"), argv[0]);
ae8e4c9c
JH
1293 read_empty(remote_head->object.sha1, 0);
1294 update_ref("initial pull", "HEAD", remote_head->object.sha1,
1295 NULL, 0, DIE_ON_ERR);
d5a35c11 1296 goto done;
1c7b76be 1297 } else {
97d45bcb 1298 struct strbuf merge_names = STRBUF_INIT;
1c7b76be
MV
1299
1300 /* We are invoked directly as the first-class UI. */
1301 head_arg = "HEAD";
1302
1303 /*
ae8e4c9c
JH
1304 * All the rest are the commits being merged; prepare
1305 * the standard merge summary message to be appended
1306 * to the given message.
1c7b76be 1307 */
b5d887f9
JH
1308 remoteheads = collect_parents(argc, argv);
1309 for (p = remoteheads; p; p = p->next)
1310 merge_name(merge_remote_util(p->item)->name, &merge_names);
f0ecac2b 1311
96e9420c 1312 if (!have_message || shortlog_len) {
cbda121c
JH
1313 struct fmt_merge_msg_opts opts;
1314 memset(&opts, 0, sizeof(opts));
1315 opts.add_title = !have_message;
1316 opts.shortlog_len = shortlog_len;
1317
1318 fmt_merge_msg(&merge_names, &merge_msg, &opts);
1876166a
RR
1319 if (merge_msg.len)
1320 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1321 }
1c7b76be
MV
1322 }
1323
894642f6 1324 if (!head_commit || !argc)
1c7b76be
MV
1325 usage_with_options(builtin_merge_usage,
1326 builtin_merge_options);
1327
1328 strbuf_addstr(&buf, "merge");
b5d887f9
JH
1329 for (p = remoteheads; p; p = p->next)
1330 strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
1c7b76be
MV
1331 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1332 strbuf_reset(&buf);
1333
b5d887f9
JH
1334 for (p = remoteheads; p; p = p->next) {
1335 struct commit *commit = p->item;
ae8e4c9c
JH
1336 strbuf_addf(&buf, "GITHEAD_%s",
1337 sha1_to_hex(commit->object.sha1));
b5d887f9 1338 setenv(buf.buf, merge_remote_util(commit)->name, 1);
1c7b76be 1339 strbuf_reset(&buf);
b5c9f1c1
JH
1340 if (!fast_forward_only &&
1341 merge_remote_util(commit) &&
fab47d05
JH
1342 merge_remote_util(commit)->obj &&
1343 merge_remote_util(commit)->obj->type == OBJ_TAG) {
3adab6f3 1344 if (option_edit < 0)
d387868a 1345 option_edit = default_edit_option();
fab47d05
JH
1346 allow_fast_forward = 0;
1347 }
1c7b76be
MV
1348 }
1349
3adab6f3
JH
1350 if (option_edit < 0)
1351 option_edit = 0;
1352
1c7b76be
MV
1353 if (!use_strategies) {
1354 if (!remoteheads->next)
1355 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1356 else
1357 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1358 }
1359
1360 for (i = 0; i < use_strategies_nr; i++) {
1361 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1362 allow_fast_forward = 0;
1363 if (use_strategies[i]->attr & NO_TRIVIAL)
1364 allow_trivial = 0;
1365 }
1366
1367 if (!remoteheads->next)
894642f6 1368 common = get_merge_bases(head_commit, remoteheads->item, 1);
1c7b76be
MV
1369 else {
1370 struct commit_list *list = remoteheads;
894642f6 1371 commit_list_insert(head_commit, &list);
1c7b76be
MV
1372 common = get_octopus_merge_bases(list);
1373 free(list);
1374 }
1375
894642f6
NTND
1376 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.sha1,
1377 NULL, 0, DIE_ON_ERR);
1c7b76be
MV
1378
1379 if (!common)
1380 ; /* No common ancestors found. We need a real merge. */
1381 else if (!remoteheads->next && !common->next &&
1382 common->item == remoteheads->item) {
1383 /*
1384 * If head can reach all the merge then we are up to date.
1385 * but first the most common case of merging one remote.
1386 */
1387 finish_up_to_date("Already up-to-date.");
d5a35c11 1388 goto done;
1c7b76be
MV
1389 } else if (allow_fast_forward && !remoteheads->next &&
1390 !common->next &&
894642f6 1391 !hashcmp(common->item->object.sha1, head_commit->object.sha1)) {
1c7b76be 1392 /* Again the most common case of merging one remote. */
f285a2d7 1393 struct strbuf msg = STRBUF_INIT;
ae8e4c9c 1394 struct commit *commit;
1c7b76be
MV
1395 char hex[41];
1396
894642f6 1397 strcpy(hex, find_unique_abbrev(head_commit->object.sha1, DEFAULT_ABBREV));
1c7b76be 1398
7f87aff2 1399 if (verbosity >= 0)
2ceb61e0 1400 printf(_("Updating %s..%s\n"),
7f87aff2
TA
1401 hex,
1402 find_unique_abbrev(remoteheads->item->object.sha1,
1403 DEFAULT_ABBREV));
a75d7b54 1404 strbuf_addstr(&msg, "Fast-forward");
1c7b76be
MV
1405 if (have_message)
1406 strbuf_addstr(&msg,
1407 " (no commit created; -m option ignored)");
ae8e4c9c 1408 commit = remoteheads->item;
b7f7c079 1409 if (!commit) {
d5a35c11
NTND
1410 ret = 1;
1411 goto done;
1412 }
1c7b76be 1413
ae8e4c9c 1414 if (checkout_fast_forward(head_commit->object.sha1,
b7f7c079 1415 commit->object.sha1)) {
d5a35c11
NTND
1416 ret = 1;
1417 goto done;
1418 }
1c7b76be 1419
4c57bd27 1420 finish(head_commit, remoteheads, commit->object.sha1, msg.buf);
1c7b76be 1421 drop_save();
d5a35c11 1422 goto done;
1c7b76be
MV
1423 } else if (!remoteheads->next && common->next)
1424 ;
1425 /*
a75d7b54 1426 * We are not doing octopus and not fast-forward. Need
1c7b76be
MV
1427 * a real merge.
1428 */
1429 else if (!remoteheads->next && !common->next && option_commit) {
1430 /*
a75d7b54 1431 * We are not doing octopus, not fast-forward, and have
1c7b76be
MV
1432 * only one common.
1433 */
1434 refresh_cache(REFRESH_QUIET);
13474835 1435 if (allow_trivial && !fast_forward_only) {
1c7b76be
MV
1436 /* See if it is really trivial. */
1437 git_committer_info(IDENT_ERROR_ON_NO_NAME);
bacec478 1438 printf(_("Trying really trivial in-index merge...\n"));
1c7b76be 1439 if (!read_tree_trivial(common->item->object.sha1,
d5a35c11
NTND
1440 head_commit->object.sha1,
1441 remoteheads->item->object.sha1)) {
4c57bd27 1442 ret = merge_trivial(head_commit, remoteheads);
d5a35c11
NTND
1443 goto done;
1444 }
bacec478 1445 printf(_("Nope.\n"));
1c7b76be
MV
1446 }
1447 } else {
1448 /*
1449 * An octopus. If we can reach all the remote we are up
1450 * to date.
1451 */
1452 int up_to_date = 1;
1453 struct commit_list *j;
1454
1455 for (j = remoteheads; j; j = j->next) {
1456 struct commit_list *common_one;
1457
1458 /*
1459 * Here we *have* to calculate the individual
1460 * merge_bases again, otherwise "git merge HEAD^
1461 * HEAD^^" would be missed.
1462 */
894642f6 1463 common_one = get_merge_bases(head_commit, j->item, 1);
1c7b76be
MV
1464 if (hashcmp(common_one->item->object.sha1,
1465 j->item->object.sha1)) {
1466 up_to_date = 0;
1467 break;
1468 }
1469 }
1470 if (up_to_date) {
1471 finish_up_to_date("Already up-to-date. Yeeah!");
d5a35c11 1472 goto done;
1c7b76be
MV
1473 }
1474 }
1475
13474835 1476 if (fast_forward_only)
bacec478 1477 die(_("Not possible to fast-forward, aborting."));
13474835 1478
1c7b76be
MV
1479 /* We are going to make a new commit. */
1480 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1481
1482 /*
1483 * At this point, we need a real merge. No matter what strategy
1484 * we use, it would operate on the index, possibly affecting the
1485 * working tree, and when resolved cleanly, have the desired
1486 * tree in the index -- this means that the index must be in
1487 * sync with the head commit. The strategies are responsible
1488 * to ensure this.
1489 */
b4fd9406
NTND
1490 if (use_strategies_nr == 1 ||
1491 /*
1492 * Stash away the local changes so that we can try more than one.
1493 */
1494 save_state(stash))
1495 hashcpy(stash, null_sha1);
1c7b76be
MV
1496
1497 for (i = 0; i < use_strategies_nr; i++) {
1498 int ret;
1499 if (i) {
bacec478 1500 printf(_("Rewinding the tree to pristine...\n"));
894642f6 1501 restore_state(head_commit->object.sha1, stash);
1c7b76be
MV
1502 }
1503 if (use_strategies_nr != 1)
bacec478 1504 printf(_("Trying merge strategy %s...\n"),
1c7b76be
MV
1505 use_strategies[i]->name);
1506 /*
1507 * Remember which strategy left the state in the working
1508 * tree.
1509 */
1510 wt_strategy = use_strategies[i]->name;
1511
1512 ret = try_merge_strategy(use_strategies[i]->name,
4c57bd27
JH
1513 common, remoteheads,
1514 head_commit, head_arg);
1c7b76be
MV
1515 if (!option_commit && !ret) {
1516 merge_was_ok = 1;
1517 /*
1518 * This is necessary here just to avoid writing
1519 * the tree, but later we will *not* exit with
1520 * status code 1 because merge_was_ok is set.
1521 */
1522 ret = 1;
1523 }
1524
1525 if (ret) {
1526 /*
1527 * The backend exits with 1 when conflicts are
1528 * left to be resolved, with 2 when it does not
1529 * handle the given merge at all.
1530 */
1531 if (ret == 1) {
1532 int cnt = evaluate_result();
1533
1534 if (best_cnt <= 0 || cnt <= best_cnt) {
1535 best_strategy = use_strategies[i]->name;
1536 best_cnt = cnt;
1537 }
1538 }
1539 if (merge_was_ok)
1540 break;
1541 else
1542 continue;
1543 }
1544
1545 /* Automerge succeeded. */
1546 write_tree_trivial(result_tree);
1547 automerge_was_ok = 1;
1548 break;
1549 }
1550
1551 /*
1552 * If we have a resulting tree, that means the strategy module
1553 * auto resolved the merge cleanly.
1554 */
d5a35c11 1555 if (automerge_was_ok) {
4c57bd27
JH
1556 ret = finish_automerge(head_commit, common, remoteheads,
1557 result_tree, wt_strategy);
d5a35c11
NTND
1558 goto done;
1559 }
1c7b76be
MV
1560
1561 /*
1562 * Pick the result from the best strategy and have the user fix
1563 * it up.
1564 */
1565 if (!best_strategy) {
894642f6 1566 restore_state(head_commit->object.sha1, stash);
1c7b76be
MV
1567 if (use_strategies_nr > 1)
1568 fprintf(stderr,
bacec478 1569 _("No merge strategy handled the merge.\n"));
1c7b76be 1570 else
bacec478 1571 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1c7b76be 1572 use_strategies[0]->name);
d5a35c11
NTND
1573 ret = 2;
1574 goto done;
1c7b76be
MV
1575 } else if (best_strategy == wt_strategy)
1576 ; /* We already have its result in the working tree. */
1577 else {
bacec478 1578 printf(_("Rewinding the tree to pristine...\n"));
894642f6 1579 restore_state(head_commit->object.sha1, stash);
bacec478 1580 printf(_("Using the %s to prepare resolving by hand.\n"),
1c7b76be 1581 best_strategy);
4c57bd27
JH
1582 try_merge_strategy(best_strategy, common, remoteheads,
1583 head_commit, head_arg);
1c7b76be
MV
1584 }
1585
1586 if (squash)
4c57bd27 1587 finish(head_commit, remoteheads, NULL, NULL);
66f4b98a 1588 else
4c57bd27 1589 write_merge_state(remoteheads);
1c7b76be 1590
d5a35c11 1591 if (merge_was_ok)
bacec478
ÆAB
1592 fprintf(stderr, _("Automatic merge went well; "
1593 "stopped before committing as requested\n"));
d5a35c11
NTND
1594 else
1595 ret = suggest_conflicts(option_renormalize);
1596
1597done:
96ec7b1e 1598 free(branch_to_free);
d5a35c11 1599 return ret;
1c7b76be 1600}