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