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