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