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