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