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