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