commit: do not lose mergetag header when not amending
[git/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
9#include "cache.h"
10#include "parse-options.h"
11#include "builtin.h"
12#include "run-command.h"
13#include "diff.h"
14#include "refs.h"
15#include "commit.h"
16#include "diffcore.h"
17#include "revision.h"
18#include "unpack-trees.h"
19#include "cache-tree.h"
20#include "dir.h"
21#include "utf8.h"
22#include "log-tree.h"
23#include "color.h"
fcab40a3 24#include "rerere.h"
87091b49 25#include "help.h"
18668f53 26#include "merge-recursive.h"
cfc5789a 27#include "resolve-undo.h"
93e535a5 28#include "remote.h"
1c7b76be
MV
29
30#define DEFAULT_TWOHEAD (1<<0)
31#define DEFAULT_OCTOPUS (1<<1)
32#define NO_FAST_FORWARD (1<<2)
33#define NO_TRIVIAL (1<<3)
34
35struct strategy {
36 const char *name;
37 unsigned attr;
38};
39
40static const char * const builtin_merge_usage[] = {
93e535a5 41 "git merge [options] [<commit>...]",
c395c25b
JH
42 "git merge [options] <msg> HEAD <commit>",
43 "git merge --abort",
1c7b76be
MV
44 NULL
45};
46
96e9420c 47static int show_diffstat = 1, shortlog_len, squash;
1c7b76be 48static int option_commit = 1, allow_fast_forward = 1;
66f4b98a 49static int fast_forward_only, option_edit;
1c7b76be
MV
50static int allow_trivial = 1, have_message;
51static struct strbuf merge_msg;
52static struct commit_list *remoteheads;
1c7b76be
MV
53static struct strategy **use_strategies;
54static size_t use_strategies_nr, use_strategies_alloc;
8cc5b290
AP
55static const char **xopts;
56static size_t xopts_nr, xopts_alloc;
1c7b76be 57static const char *branch;
0d8fc3ef 58static char *branch_mergeoptions;
7610fa57 59static int option_renormalize;
7f87aff2 60static int verbosity;
cb6020bb 61static int allow_rerere_auto;
35d2fffd 62static int abort_current_merge;
99bfc669 63static int show_progress = -1;
93e535a5 64static int default_to_upstream;
1c7b76be
MV
65
66static struct strategy all_strategy[] = {
1c7b76be
MV
67 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
68 { "octopus", DEFAULT_OCTOPUS },
69 { "resolve", 0 },
1c7b76be
MV
70 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
71 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
72};
73
74static const char *pull_twohead, *pull_octopus;
75
76static int option_parse_message(const struct option *opt,
77 const char *arg, int unset)
78{
79 struct strbuf *buf = opt->value;
80
81 if (unset)
82 strbuf_setlen(buf, 0);
74f5b7fb 83 else if (arg) {
ce9d823b 84 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
1c7b76be 85 have_message = 1;
74f5b7fb 86 } else
bacec478 87 return error(_("switch `m' requires a value"));
1c7b76be
MV
88 return 0;
89}
90
91static struct strategy *get_strategy(const char *name)
92{
93 int i;
87091b49
MV
94 struct strategy *ret;
95 static struct cmdnames main_cmds, other_cmds;
e321180e 96 static int loaded;
1c7b76be
MV
97
98 if (!name)
99 return NULL;
100
101 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
102 if (!strcmp(name, all_strategy[i].name))
103 return &all_strategy[i];
1719b5e4 104
e321180e 105 if (!loaded) {
87091b49 106 struct cmdnames not_strategies;
e321180e 107 loaded = 1;
87091b49 108
87091b49 109 memset(&not_strategies, 0, sizeof(struct cmdnames));
e321180e 110 load_command_list("git-merge-", &main_cmds, &other_cmds);
87091b49
MV
111 for (i = 0; i < main_cmds.cnt; i++) {
112 int j, found = 0;
113 struct cmdname *ent = main_cmds.names[i];
114 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
115 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
116 && !all_strategy[j].name[ent->len])
117 found = 1;
118 if (!found)
119 add_cmdname(&not_strategies, ent->name, ent->len);
87091b49 120 }
ed874656 121 exclude_cmds(&main_cmds, &not_strategies);
87091b49
MV
122 }
123 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
bacec478
ÆAB
124 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
125 fprintf(stderr, _("Available strategies are:"));
131f9a10
JH
126 for (i = 0; i < main_cmds.cnt; i++)
127 fprintf(stderr, " %s", main_cmds.names[i]->name);
128 fprintf(stderr, ".\n");
129 if (other_cmds.cnt) {
bacec478 130 fprintf(stderr, _("Available custom strategies are:"));
131f9a10
JH
131 for (i = 0; i < other_cmds.cnt; i++)
132 fprintf(stderr, " %s", other_cmds.names[i]->name);
133 fprintf(stderr, ".\n");
134 }
87091b49
MV
135 exit(1);
136 }
137
19d4b416 138 ret = xcalloc(1, sizeof(struct strategy));
87091b49 139 ret->name = xstrdup(name);
52b48ef1 140 ret->attr = NO_TRIVIAL;
87091b49 141 return ret;
1c7b76be
MV
142}
143
144static void append_strategy(struct strategy *s)
145{
146 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
147 use_strategies[use_strategies_nr++] = s;
148}
149
150static int option_parse_strategy(const struct option *opt,
151 const char *name, int unset)
152{
1c7b76be
MV
153 if (unset)
154 return 0;
155
1719b5e4 156 append_strategy(get_strategy(name));
1c7b76be
MV
157 return 0;
158}
159
8cc5b290
AP
160static int option_parse_x(const struct option *opt,
161 const char *arg, int unset)
162{
163 if (unset)
164 return 0;
165
166 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
167 xopts[xopts_nr++] = xstrdup(arg);
168 return 0;
169}
170
1c7b76be
MV
171static int option_parse_n(const struct option *opt,
172 const char *arg, int unset)
173{
174 show_diffstat = unset;
175 return 0;
176}
177
178static struct option builtin_merge_options[] = {
179 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
180 "do not show a diffstat at the end of the merge",
181 PARSE_OPT_NOARG, option_parse_n },
182 OPT_BOOLEAN(0, "stat", &show_diffstat,
183 "show a diffstat at the end of the merge"),
184 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
96e9420c
RR
185 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
186 "add (at most <n>) entries from shortlog to merge commit message",
187 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
1c7b76be
MV
188 OPT_BOOLEAN(0, "squash", &squash,
189 "create a single commit instead of doing a merge"),
190 OPT_BOOLEAN(0, "commit", &option_commit,
191 "perform a commit if the merge succeeds (default)"),
66f4b98a
JS
192 OPT_BOOLEAN('e', "edit", &option_edit,
193 "edit message before committing"),
1c7b76be 194 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
a75d7b54 195 "allow fast-forward (default)"),
13474835 196 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
4d8c3258 197 "abort if fast-forward is not possible"),
cb6020bb 198 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
1c7b76be
MV
199 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
200 "merge strategy to use", option_parse_strategy),
8cc5b290
AP
201 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
202 "option for selected merge strategy", option_parse_x),
23c6a803 203 OPT_CALLBACK('m', "message", &merge_msg, "message",
3f406175 204 "merge commit message (for a non-fast-forward merge)",
1c7b76be 205 option_parse_message),
7f87aff2 206 OPT__VERBOSITY(&verbosity),
35d2fffd
JH
207 OPT_BOOLEAN(0, "abort", &abort_current_merge,
208 "abort the current in-progress merge"),
99bfc669 209 OPT_SET_INT(0, "progress", &show_progress, "force progress reporting", 1),
1c7b76be
MV
210 OPT_END()
211};
212
213/* Cleans up metadata that is uninteresting after a succeeded merge. */
214static void drop_save(void)
215{
216 unlink(git_path("MERGE_HEAD"));
217 unlink(git_path("MERGE_MSG"));
cf10f9fd 218 unlink(git_path("MERGE_MODE"));
1c7b76be
MV
219}
220
b4fd9406 221static int save_state(unsigned char *stash)
1c7b76be
MV
222{
223 int len;
224 struct child_process cp;
225 struct strbuf buffer = STRBUF_INIT;
226 const char *argv[] = {"stash", "create", NULL};
227
228 memset(&cp, 0, sizeof(cp));
229 cp.argv = argv;
230 cp.out = -1;
231 cp.git_cmd = 1;
232
233 if (start_command(&cp))
bacec478 234 die(_("could not run stash."));
1c7b76be
MV
235 len = strbuf_read(&buffer, cp.out, 1024);
236 close(cp.out);
237
238 if (finish_command(&cp) || len < 0)
bacec478 239 die(_("stash failed"));
b4fd9406
NTND
240 else if (!len) /* no changes */
241 return -1;
1c7b76be
MV
242 strbuf_setlen(&buffer, buffer.len-1);
243 if (get_sha1(buffer.buf, stash))
bacec478 244 die(_("not a valid object: %s"), buffer.buf);
b4fd9406 245 return 0;
1c7b76be
MV
246}
247
172b6428
CB
248static void read_empty(unsigned const char *sha1, int verbose)
249{
250 int i = 0;
251 const char *args[7];
252
253 args[i++] = "read-tree";
254 if (verbose)
255 args[i++] = "-v";
256 args[i++] = "-m";
257 args[i++] = "-u";
258 args[i++] = EMPTY_TREE_SHA1_HEX;
259 args[i++] = sha1_to_hex(sha1);
260 args[i] = NULL;
261
262 if (run_command_v_opt(args, RUN_GIT_CMD))
bacec478 263 die(_("read-tree failed"));
172b6428
CB
264}
265
1c7b76be
MV
266static void reset_hard(unsigned const char *sha1, int verbose)
267{
268 int i = 0;
269 const char *args[6];
270
271 args[i++] = "read-tree";
272 if (verbose)
273 args[i++] = "-v";
274 args[i++] = "--reset";
275 args[i++] = "-u";
276 args[i++] = sha1_to_hex(sha1);
277 args[i] = NULL;
278
279 if (run_command_v_opt(args, RUN_GIT_CMD))
bacec478 280 die(_("read-tree failed"));
1c7b76be
MV
281}
282
894642f6
NTND
283static void restore_state(const unsigned char *head,
284 const unsigned char *stash)
1c7b76be 285{
f285a2d7 286 struct strbuf sb = STRBUF_INIT;
1c7b76be
MV
287 const char *args[] = { "stash", "apply", NULL, NULL };
288
289 if (is_null_sha1(stash))
290 return;
291
292 reset_hard(head, 1);
293
1c7b76be
MV
294 args[2] = sha1_to_hex(stash);
295
296 /*
297 * It is OK to ignore error here, for example when there was
298 * nothing to restore.
299 */
300 run_command_v_opt(args, RUN_GIT_CMD);
301
302 strbuf_release(&sb);
303 refresh_cache(REFRESH_QUIET);
304}
305
306/* This is called when no merge was necessary. */
307static void finish_up_to_date(const char *msg)
308{
7f87aff2 309 if (verbosity >= 0)
bacec478 310 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
1c7b76be
MV
311 drop_save();
312}
313
894642f6 314static void squash_message(struct commit *commit)
1c7b76be
MV
315{
316 struct rev_info rev;
f285a2d7 317 struct strbuf out = STRBUF_INIT;
1c7b76be
MV
318 struct commit_list *j;
319 int fd;
dd2e794a 320 struct pretty_print_context ctx = {0};
1c7b76be 321
bacec478 322 printf(_("Squash commit -- not updating HEAD\n"));
1c7b76be
MV
323 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
324 if (fd < 0)
bacec478 325 die_errno(_("Could not write to '%s'"), git_path("SQUASH_MSG"));
1c7b76be
MV
326
327 init_revisions(&rev, NULL);
328 rev.ignore_merges = 1;
329 rev.commit_format = CMIT_FMT_MEDIUM;
330
1c7b76be
MV
331 commit->object.flags |= UNINTERESTING;
332 add_pending_object(&rev, &commit->object, NULL);
333
334 for (j = remoteheads; j; j = j->next)
335 add_pending_object(&rev, &j->item->object, NULL);
336
337 setup_revisions(0, NULL, &rev, NULL);
338 if (prepare_revision_walk(&rev))
bacec478 339 die(_("revision walk setup failed"));
1c7b76be 340
dd2e794a
TR
341 ctx.abbrev = rev.abbrev;
342 ctx.date_mode = rev.date_mode;
6bf13944 343 ctx.fmt = rev.commit_format;
dd2e794a 344
1c7b76be
MV
345 strbuf_addstr(&out, "Squashed commit of the following:\n");
346 while ((commit = get_revision(&rev)) != NULL) {
347 strbuf_addch(&out, '\n');
348 strbuf_addf(&out, "commit %s\n",
349 sha1_to_hex(commit->object.sha1));
6bf13944 350 pretty_print_commit(&ctx, commit, &out);
1c7b76be 351 }
47d32af2 352 if (write(fd, out.buf, out.len) < 0)
bacec478 353 die_errno(_("Writing SQUASH_MSG"));
47d32af2 354 if (close(fd))
bacec478 355 die_errno(_("Finishing SQUASH_MSG"));
1c7b76be
MV
356 strbuf_release(&out);
357}
358
894642f6
NTND
359static void finish(struct commit *head_commit,
360 const unsigned char *new_head, const char *msg)
1c7b76be 361{
f285a2d7 362 struct strbuf reflog_message = STRBUF_INIT;
894642f6 363 const unsigned char *head = head_commit->object.sha1;
1c7b76be 364
1c7b76be
MV
365 if (!msg)
366 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
367 else {
7f87aff2
TA
368 if (verbosity >= 0)
369 printf("%s\n", msg);
1c7b76be
MV
370 strbuf_addf(&reflog_message, "%s: %s",
371 getenv("GIT_REFLOG_ACTION"), msg);
372 }
373 if (squash) {
894642f6 374 squash_message(head_commit);
1c7b76be 375 } else {
7f87aff2 376 if (verbosity >= 0 && !merge_msg.len)
bacec478 377 printf(_("No merge message -- not updating HEAD\n"));
1c7b76be
MV
378 else {
379 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
380 update_ref(reflog_message.buf, "HEAD",
381 new_head, head, 0,
382 DIE_ON_ERR);
383 /*
384 * We ignore errors in 'gc --auto', since the
385 * user should see them.
386 */
387 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
388 }
389 }
390 if (new_head && show_diffstat) {
391 struct diff_options opts;
392 diff_setup(&opts);
393 opts.output_format |=
394 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
395 opts.detect_rename = DIFF_DETECT_RENAME;
1c7b76be 396 if (diff_setup_done(&opts) < 0)
bacec478 397 die(_("diff_setup_done failed"));
1c7b76be
MV
398 diff_tree_sha1(head, new_head, "", &opts);
399 diffcore_std(&opts);
400 diff_flush(&opts);
401 }
402
403 /* Run a post-merge hook */
ae98a008 404 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
1c7b76be
MV
405
406 strbuf_release(&reflog_message);
407}
408
409/* Get the name for the merge commit's message. */
410static void merge_name(const char *remote, struct strbuf *msg)
411{
ae8e4c9c 412 struct commit *remote_head;
1c7b76be 413 unsigned char branch_head[20], buf_sha[20];
f285a2d7 414 struct strbuf buf = STRBUF_INIT;
c9717ee9 415 struct strbuf bname = STRBUF_INIT;
1c7b76be 416 const char *ptr;
751c5974 417 char *found_ref;
1c7b76be
MV
418 int len, early;
419
a552de75
JH
420 strbuf_branchname(&bname, remote);
421 remote = bname.buf;
c9717ee9 422
1c7b76be 423 memset(branch_head, 0, sizeof(branch_head));
ae8e4c9c 424 remote_head = get_merge_parent(remote);
1c7b76be 425 if (!remote_head)
bacec478 426 die(_("'%s' does not point to a commit"), remote);
1c7b76be 427
751c5974
JK
428 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
429 if (!prefixcmp(found_ref, "refs/heads/")) {
430 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
431 sha1_to_hex(branch_head), remote);
432 goto cleanup;
433 }
57b58db7
JH
434 if (!prefixcmp(found_ref, "refs/tags/")) {
435 strbuf_addf(msg, "%s\t\ttag '%s' of .\n",
436 sha1_to_hex(branch_head), remote);
437 goto cleanup;
438 }
69a8b7c7 439 if (!prefixcmp(found_ref, "refs/remotes/")) {
13931236 440 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
69a8b7c7
JK
441 sha1_to_hex(branch_head), remote);
442 goto cleanup;
443 }
1c7b76be
MV
444 }
445
446 /* See if remote matches <name>^^^.. or <name>~<number> */
447 for (len = 0, ptr = remote + strlen(remote);
448 remote < ptr && ptr[-1] == '^';
449 ptr--)
450 len++;
451 if (len)
452 early = 1;
453 else {
454 early = 0;
455 ptr = strrchr(remote, '~');
456 if (ptr) {
457 int seen_nonzero = 0;
458
459 len++; /* count ~ */
460 while (*++ptr && isdigit(*ptr)) {
461 seen_nonzero |= (*ptr != '0');
462 len++;
463 }
464 if (*ptr)
465 len = 0; /* not ...~<number> */
466 else if (seen_nonzero)
467 early = 1;
468 else if (len == 1)
469 early = 1; /* "name~" is "name~1"! */
470 }
471 }
472 if (len) {
473 struct strbuf truname = STRBUF_INIT;
474 strbuf_addstr(&truname, "refs/heads/");
475 strbuf_addstr(&truname, remote);
9b6bf4d5 476 strbuf_setlen(&truname, truname.len - len);
b81f925f 477 if (resolve_ref(truname.buf, buf_sha, 1, NULL)) {
1c7b76be
MV
478 strbuf_addf(msg,
479 "%s\t\tbranch '%s'%s of .\n",
ae8e4c9c 480 sha1_to_hex(remote_head->object.sha1),
9b6bf4d5 481 truname.buf + 11,
1c7b76be 482 (early ? " (early part)" : ""));
c9717ee9
JH
483 strbuf_release(&truname);
484 goto cleanup;
1c7b76be
MV
485 }
486 }
487
488 if (!strcmp(remote, "FETCH_HEAD") &&
489 !access(git_path("FETCH_HEAD"), R_OK)) {
490 FILE *fp;
f285a2d7 491 struct strbuf line = STRBUF_INIT;
1c7b76be
MV
492 char *ptr;
493
1c7b76be
MV
494 fp = fopen(git_path("FETCH_HEAD"), "r");
495 if (!fp)
bacec478 496 die_errno(_("could not open '%s' for reading"),
d824cbba 497 git_path("FETCH_HEAD"));
1c7b76be
MV
498 strbuf_getline(&line, fp, '\n');
499 fclose(fp);
500 ptr = strstr(line.buf, "\tnot-for-merge\t");
501 if (ptr)
502 strbuf_remove(&line, ptr-line.buf+1, 13);
503 strbuf_addbuf(msg, &line);
504 strbuf_release(&line);
c9717ee9 505 goto cleanup;
1c7b76be
MV
506 }
507 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
ae8e4c9c 508 sha1_to_hex(remote_head->object.sha1), remote);
c9717ee9
JH
509cleanup:
510 strbuf_release(&buf);
511 strbuf_release(&bname);
1c7b76be
MV
512}
513
0d8fc3ef
JH
514static void parse_branch_merge_options(char *bmo)
515{
516 const char **argv;
517 int argc;
518
519 if (!bmo)
520 return;
521 argc = split_cmdline(bmo, &argv);
522 if (argc < 0)
c7fe5b61
JH
523 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
524 split_cmdline_strerror(argc));
0d8fc3ef
JH
525 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
526 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
527 argc++;
528 argv[0] = "branch.*.mergeoptions";
529 parse_options(argc, argv, NULL, builtin_merge_options,
530 builtin_merge_usage, 0);
531 free(argv);
532}
533
186458b1 534static int git_merge_config(const char *k, const char *v, void *cb)
1c7b76be
MV
535{
536 if (branch && !prefixcmp(k, "branch.") &&
537 !prefixcmp(k + 7, branch) &&
538 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
0d8fc3ef
JH
539 free(branch_mergeoptions);
540 branch_mergeoptions = xstrdup(v);
541 return 0;
1c7b76be
MV
542 }
543
544 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
545 show_diffstat = git_config_bool(k, v);
546 else if (!strcmp(k, "pull.twohead"))
547 return git_config_string(&pull_twohead, k, v);
548 else if (!strcmp(k, "pull.octopus"))
549 return git_config_string(&pull_octopus, k, v);
7610fa57
JN
550 else if (!strcmp(k, "merge.renormalize"))
551 option_renormalize = git_config_bool(k, v);
96e9420c 552 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary")) {
bda3b8ff
RR
553 int is_bool;
554 shortlog_len = git_config_bool_or_int(k, v, &is_bool);
555 if (!is_bool && shortlog_len < 0)
bacec478 556 return error(_("%s: negative length %s"), k, v);
bda3b8ff
RR
557 if (is_bool && shortlog_len)
558 shortlog_len = DEFAULT_MERGE_LOG_LEN;
96e9420c 559 return 0;
f23e8dec
JH
560 } else if (!strcmp(k, "merge.ff")) {
561 int boolval = git_config_maybe_bool(k, v);
562 if (0 <= boolval) {
563 allow_fast_forward = boolval;
564 } else if (v && !strcmp(v, "only")) {
565 allow_fast_forward = 1;
566 fast_forward_only = 1;
567 } /* do not barf on values from future versions of git */
568 return 0;
93e535a5
JH
569 } else if (!strcmp(k, "merge.defaulttoupstream")) {
570 default_to_upstream = git_config_bool(k, v);
571 return 0;
96e9420c 572 }
1c7b76be
MV
573 return git_diff_ui_config(k, v, cb);
574}
575
576static int read_tree_trivial(unsigned char *common, unsigned char *head,
577 unsigned char *one)
578{
579 int i, nr_trees = 0;
580 struct tree *trees[MAX_UNPACK_TREES];
581 struct tree_desc t[MAX_UNPACK_TREES];
582 struct unpack_trees_options opts;
583
584 memset(&opts, 0, sizeof(opts));
585 opts.head_idx = 2;
586 opts.src_index = &the_index;
587 opts.dst_index = &the_index;
588 opts.update = 1;
589 opts.verbose_update = 1;
590 opts.trivial_merges_only = 1;
591 opts.merge = 1;
592 trees[nr_trees] = parse_tree_indirect(common);
593 if (!trees[nr_trees++])
594 return -1;
595 trees[nr_trees] = parse_tree_indirect(head);
596 if (!trees[nr_trees++])
597 return -1;
598 trees[nr_trees] = parse_tree_indirect(one);
599 if (!trees[nr_trees++])
600 return -1;
601 opts.fn = threeway_merge;
602 cache_tree_free(&active_cache_tree);
603 for (i = 0; i < nr_trees; i++) {
604 parse_tree(trees[i]);
605 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
606 }
607 if (unpack_trees(nr_trees, t, &opts))
608 return -1;
609 return 0;
610}
611
612static void write_tree_trivial(unsigned char *sha1)
613{
614 if (write_cache_as_tree(sha1, 0, NULL))
bacec478 615 die(_("git write-tree failed to write a tree"));
1c7b76be
MV
616}
617
16180734
JK
618static const char *merge_argument(struct commit *commit)
619{
620 if (commit)
621 return sha1_to_hex(commit->object.sha1);
622 else
623 return EMPTY_TREE_SHA1_HEX;
624}
625
67ac1e1d
JN
626int try_merge_command(const char *strategy, size_t xopts_nr,
627 const char **xopts, struct commit_list *common,
c674d052 628 const char *head_arg, struct commit_list *remotes)
1c7b76be
MV
629{
630 const char **args;
8cc5b290 631 int i = 0, x = 0, ret;
1c7b76be 632 struct commit_list *j;
f285a2d7 633 struct strbuf buf = STRBUF_INIT;
3f9083cd
CC
634
635 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
636 commit_list_count(remotes)) * sizeof(char *));
637 strbuf_addf(&buf, "merge-%s", strategy);
638 args[i++] = buf.buf;
639 for (x = 0; x < xopts_nr; x++) {
640 char *s = xmalloc(strlen(xopts[x])+2+1);
641 strcpy(s, "--");
642 strcpy(s+2, xopts[x]);
643 args[i++] = s;
644 }
645 for (j = common; j; j = j->next)
16180734 646 args[i++] = xstrdup(merge_argument(j->item));
3f9083cd
CC
647 args[i++] = "--";
648 args[i++] = head_arg;
649 for (j = remotes; j; j = j->next)
16180734 650 args[i++] = xstrdup(merge_argument(j->item));
3f9083cd
CC
651 args[i] = NULL;
652 ret = run_command_v_opt(args, RUN_GIT_CMD);
653 strbuf_release(&buf);
654 i = 1;
655 for (x = 0; x < xopts_nr; x++)
656 free((void *)args[i++]);
657 for (j = common; j; j = j->next)
658 free((void *)args[i++]);
659 i += 2;
660 for (j = remotes; j; j = j->next)
661 free((void *)args[i++]);
662 free(args);
663 discard_cache();
664 if (read_cache() < 0)
bacec478 665 die(_("failed to read the cache"));
3f9083cd
CC
666 resolve_undo_clear();
667
668 return ret;
669}
670
671static int try_merge_strategy(const char *strategy, struct commit_list *common,
894642f6 672 struct commit *head, const char *head_arg)
3f9083cd 673{
668f26ff
MV
674 int index_fd;
675 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
676
677 index_fd = hold_locked_index(lock, 1);
678 refresh_cache(REFRESH_QUIET);
679 if (active_cache_changed &&
680 (write_cache(index_fd, active_cache, active_nr) ||
681 commit_locked_index(lock)))
bacec478 682 return error(_("Unable to write index."));
668f26ff 683 rollback_lock_file(lock);
1c7b76be 684
18668f53 685 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
3f9083cd 686 int clean, x;
18668f53
MV
687 struct commit *result;
688 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
689 int index_fd;
690 struct commit_list *reversed = NULL;
691 struct merge_options o;
3f9083cd 692 struct commit_list *j;
18668f53
MV
693
694 if (remoteheads->next) {
bacec478 695 error(_("Not handling anything other than two heads merge."));
18668f53
MV
696 return 2;
697 }
698
699 init_merge_options(&o);
700 if (!strcmp(strategy, "subtree"))
85e51b78 701 o.subtree_shift = "";
8cc5b290 702
7610fa57 703 o.renormalize = option_renormalize;
99bfc669
JK
704 o.show_rename_progress =
705 show_progress == -1 ? isatty(2) : show_progress;
7610fa57 706
635a7bb1
JN
707 for (x = 0; x < xopts_nr; x++)
708 if (parse_merge_opt(&o, xopts[x]))
bacec478 709 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
18668f53
MV
710
711 o.branch1 = head_arg;
ae8e4c9c 712 o.branch2 = merge_remote_util(remoteheads->item)->name;
18668f53
MV
713
714 for (j = common; j; j = j->next)
715 commit_list_insert(j->item, &reversed);
716
717 index_fd = hold_locked_index(lock, 1);
894642f6 718 clean = merge_recursive(&o, head,
18668f53
MV
719 remoteheads->item, reversed, &result);
720 if (active_cache_changed &&
721 (write_cache(index_fd, active_cache, active_nr) ||
722 commit_locked_index(lock)))
bacec478 723 die (_("unable to write %s"), get_index_file());
42716660 724 rollback_lock_file(lock);
18668f53
MV
725 return clean ? 0 : 1;
726 } else {
67ac1e1d
JN
727 return try_merge_command(strategy, xopts_nr, xopts,
728 common, head_arg, remoteheads);
18668f53 729 }
1c7b76be
MV
730}
731
732static void count_diff_files(struct diff_queue_struct *q,
733 struct diff_options *opt, void *data)
734{
735 int *count = data;
736
737 (*count) += q->nr;
738}
739
740static int count_unmerged_entries(void)
741{
1c7b76be
MV
742 int i, ret = 0;
743
be6ff819
JH
744 for (i = 0; i < active_nr; i++)
745 if (ce_stage(active_cache[i]))
1c7b76be
MV
746 ret++;
747
748 return ret;
749}
750
cac42b26 751int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
1c7b76be
MV
752{
753 struct tree *trees[MAX_UNPACK_TREES];
754 struct unpack_trees_options opts;
755 struct tree_desc t[MAX_UNPACK_TREES];
756 int i, fd, nr_trees = 0;
757 struct dir_struct dir;
758 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
759
9ca8f607 760 refresh_cache(REFRESH_QUIET);
1c7b76be
MV
761
762 fd = hold_locked_index(lock_file, 1);
763
764 memset(&trees, 0, sizeof(trees));
765 memset(&opts, 0, sizeof(opts));
766 memset(&t, 0, sizeof(t));
5d2299de 767 memset(&dir, 0, sizeof(dir));
7c4c97c0 768 dir.flags |= DIR_SHOW_IGNORED;
1c7b76be
MV
769 dir.exclude_per_dir = ".gitignore";
770 opts.dir = &dir;
771
772 opts.head_idx = 1;
773 opts.src_index = &the_index;
774 opts.dst_index = &the_index;
775 opts.update = 1;
776 opts.verbose_update = 1;
777 opts.merge = 1;
778 opts.fn = twoway_merge;
e294030f 779 setup_unpack_trees_porcelain(&opts, "merge");
1c7b76be
MV
780
781 trees[nr_trees] = parse_tree_indirect(head);
782 if (!trees[nr_trees++])
783 return -1;
784 trees[nr_trees] = parse_tree_indirect(remote);
785 if (!trees[nr_trees++])
786 return -1;
787 for (i = 0; i < nr_trees; i++) {
788 parse_tree(trees[i]);
789 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
790 }
791 if (unpack_trees(nr_trees, t, &opts))
792 return -1;
793 if (write_cache(fd, active_cache, active_nr) ||
794 commit_locked_index(lock_file))
bacec478 795 die(_("unable to write new index file"));
1c7b76be
MV
796 return 0;
797}
798
799static void split_merge_strategies(const char *string, struct strategy **list,
800 int *nr, int *alloc)
801{
802 char *p, *q, *buf;
803
804 if (!string)
805 return;
806
807 buf = xstrdup(string);
808 q = buf;
809 for (;;) {
810 p = strchr(q, ' ');
811 if (!p) {
812 ALLOC_GROW(*list, *nr + 1, *alloc);
813 (*list)[(*nr)++].name = xstrdup(q);
814 free(buf);
815 return;
816 } else {
817 *p = '\0';
818 ALLOC_GROW(*list, *nr + 1, *alloc);
819 (*list)[(*nr)++].name = xstrdup(q);
820 q = ++p;
821 }
822 }
823}
824
825static void add_strategies(const char *string, unsigned attr)
826{
827 struct strategy *list = NULL;
828 int list_alloc = 0, list_nr = 0, i;
829
830 memset(&list, 0, sizeof(list));
831 split_merge_strategies(string, &list, &list_nr, &list_alloc);
1719b5e4
MV
832 if (list) {
833 for (i = 0; i < list_nr; i++)
834 append_strategy(get_strategy(list[i].name));
1c7b76be
MV
835 return;
836 }
837 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
838 if (all_strategy[i].attr & attr)
839 append_strategy(&all_strategy[i]);
840
841}
842
66f4b98a 843static void write_merge_msg(struct strbuf *msg)
65969d43
JS
844{
845 int fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
846 if (fd < 0)
6c80cd29 847 die_errno(_("Could not open '%s' for writing"),
65969d43 848 git_path("MERGE_MSG"));
66f4b98a 849 if (write_in_full(fd, msg->buf, msg->len) != msg->len)
6c80cd29 850 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
65969d43
JS
851 close(fd);
852}
853
66f4b98a 854static void read_merge_msg(struct strbuf *msg)
65969d43 855{
66f4b98a
JS
856 strbuf_reset(msg);
857 if (strbuf_read_file(msg, git_path("MERGE_MSG"), 0) < 0)
650ed9db 858 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
65969d43
JS
859}
860
66f4b98a
JS
861static void write_merge_state(void);
862static void abort_commit(const char *err_msg)
65969d43 863{
66f4b98a
JS
864 if (err_msg)
865 error("%s", err_msg);
866 fprintf(stderr,
867 _("Not committing merge; use 'git commit' to complete the merge.\n"));
868 write_merge_state();
869 exit(1);
870}
871
872static void prepare_to_commit(void)
873{
874 struct strbuf msg = STRBUF_INIT;
875 strbuf_addbuf(&msg, &merge_msg);
876 strbuf_addch(&msg, '\n');
877 write_merge_msg(&msg);
65969d43
JS
878 run_hook(get_index_file(), "prepare-commit-msg",
879 git_path("MERGE_MSG"), "merge", NULL, NULL);
66f4b98a
JS
880 if (option_edit) {
881 if (launch_editor(git_path("MERGE_MSG"), NULL, NULL))
882 abort_commit(NULL);
883 }
884 read_merge_msg(&msg);
885 stripspace(&msg, option_edit);
886 if (!msg.len)
887 abort_commit(_("Empty commit message."));
888 strbuf_release(&merge_msg);
889 strbuf_addbuf(&merge_msg, &msg);
890 strbuf_release(&msg);
65969d43
JS
891}
892
894642f6 893static int merge_trivial(struct commit *head)
1c7b76be
MV
894{
895 unsigned char result_tree[20], result_commit[20];
36e40535 896 struct commit_list *parent = xmalloc(sizeof(*parent));
1c7b76be
MV
897
898 write_tree_trivial(result_tree);
157efde1 899 printf(_("Wonderful.\n"));
894642f6 900 parent->item = head;
36e40535 901 parent->next = xmalloc(sizeof(*parent->next));
446247db
JH
902 parent->next->item = remoteheads->item;
903 parent->next->next = NULL;
66f4b98a 904 prepare_to_commit();
ee20a129 905 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
894642f6 906 finish(head, result_commit, "In-index merge");
1c7b76be
MV
907 drop_save();
908 return 0;
909}
910
894642f6
NTND
911static int finish_automerge(struct commit *head,
912 struct commit_list *common,
1c7b76be
MV
913 unsigned char *result_tree,
914 const char *wt_strategy)
915{
916 struct commit_list *parents = NULL, *j;
917 struct strbuf buf = STRBUF_INIT;
918 unsigned char result_commit[20];
919
920 free_commit_list(common);
921 if (allow_fast_forward) {
922 parents = remoteheads;
894642f6 923 commit_list_insert(head, &parents);
1c7b76be
MV
924 parents = reduce_heads(parents);
925 } else {
926 struct commit_list **pptr = &parents;
927
894642f6 928 pptr = &commit_list_insert(head,
1c7b76be
MV
929 pptr)->next;
930 for (j = remoteheads; j; j = j->next)
931 pptr = &commit_list_insert(j->item, pptr)->next;
932 }
1c7b76be 933 strbuf_addch(&merge_msg, '\n');
66f4b98a
JS
934 prepare_to_commit();
935 free_commit_list(remoteheads);
ee20a129 936 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
f23101bf 937 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
894642f6 938 finish(head, result_commit, buf.buf);
1c7b76be
MV
939 strbuf_release(&buf);
940 drop_save();
941 return 0;
942}
943
7610fa57 944static int suggest_conflicts(int renormalizing)
1c7b76be
MV
945{
946 FILE *fp;
947 int pos;
948
949 fp = fopen(git_path("MERGE_MSG"), "a");
950 if (!fp)
bacec478 951 die_errno(_("Could not open '%s' for writing"),
0721c314 952 git_path("MERGE_MSG"));
1c7b76be
MV
953 fprintf(fp, "\nConflicts:\n");
954 for (pos = 0; pos < active_nr; pos++) {
955 struct cache_entry *ce = active_cache[pos];
956
957 if (ce_stage(ce)) {
958 fprintf(fp, "\t%s\n", ce->name);
959 while (pos + 1 < active_nr &&
960 !strcmp(ce->name,
961 active_cache[pos + 1]->name))
962 pos++;
963 }
964 }
965 fclose(fp);
cb6020bb 966 rerere(allow_rerere_auto);
bacec478
ÆAB
967 printf(_("Automatic merge failed; "
968 "fix conflicts and then commit the result.\n"));
1c7b76be
MV
969 return 1;
970}
971
894642f6
NTND
972static struct commit *is_old_style_invocation(int argc, const char **argv,
973 const unsigned char *head)
1c7b76be
MV
974{
975 struct commit *second_token = NULL;
76bf488e 976 if (argc > 2) {
1c7b76be
MV
977 unsigned char second_sha1[20];
978
979 if (get_sha1(argv[1], second_sha1))
980 return NULL;
981 second_token = lookup_commit_reference_gently(second_sha1, 0);
982 if (!second_token)
bacec478 983 die(_("'%s' is not a commit"), argv[1]);
1c7b76be
MV
984 if (hashcmp(second_token->object.sha1, head))
985 return NULL;
986 }
987 return second_token;
988}
989
990static int evaluate_result(void)
991{
992 int cnt = 0;
993 struct rev_info rev;
994
1c7b76be
MV
995 /* Check how many files differ. */
996 init_revisions(&rev, "");
997 setup_revisions(0, NULL, &rev, NULL);
998 rev.diffopt.output_format |=
999 DIFF_FORMAT_CALLBACK;
1000 rev.diffopt.format_callback = count_diff_files;
1001 rev.diffopt.format_callback_data = &cnt;
1002 run_diff_files(&rev, 0);
1003
1004 /*
1005 * Check how many unmerged entries are
1006 * there.
1007 */
1008 cnt += count_unmerged_entries();
1009
1010 return cnt;
1011}
1012
93e535a5
JH
1013/*
1014 * Pretend as if the user told us to merge with the tracking
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."));
93e535a5 1025 if (!branch->remote)
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
JH
1029
1030 args = xcalloc(branch->merge_nr + 1, sizeof(char *));
1031 for (i = 0; i < branch->merge_nr; i++) {
1032 if (!branch->merge[i]->dst)
c7f426d4 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
66f4b98a
JS
1042static void write_merge_state(void)
1043{
1044 int fd;
1045 struct commit_list *j;
1046 struct strbuf buf = STRBUF_INIT;
1047
274a5c06
JH
1048 for (j = remoteheads; j; j = j->next) {
1049 unsigned const char *sha1;
1050 struct commit *c = j->item;
1051 if (c->util && merge_remote_util(c)->obj) {
1052 sha1 = merge_remote_util(c)->obj->sha1;
1053 } else {
1054 sha1 = c->object.sha1;
1055 }
1056 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
1057 }
66f4b98a
JS
1058 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1059 if (fd < 0)
1060 die_errno(_("Could not open '%s' for writing"),
1061 git_path("MERGE_HEAD"));
1062 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1063 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1064 close(fd);
1065 strbuf_addch(&merge_msg, '\n');
1066 write_merge_msg(&merge_msg);
1067 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1068 if (fd < 0)
1069 die_errno(_("Could not open '%s' for writing"),
1070 git_path("MERGE_MODE"));
1071 strbuf_reset(&buf);
1072 if (!allow_fast_forward)
1073 strbuf_addf(&buf, "no-ff");
1074 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1075 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1076 close(fd);
1077}
1078
1c7b76be
MV
1079int cmd_merge(int argc, const char **argv, const char *prefix)
1080{
1081 unsigned char result_tree[20];
b4fd9406 1082 unsigned char stash[20];
894642f6
NTND
1083 unsigned char head_sha1[20];
1084 struct commit *head_commit;
f285a2d7 1085 struct strbuf buf = STRBUF_INIT;
1c7b76be 1086 const char *head_arg;
894642f6 1087 int flag, i;
1c7b76be
MV
1088 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1089 struct commit_list *common = NULL;
1090 const char *best_strategy = NULL, *wt_strategy = NULL;
1091 struct commit_list **remotes = &remoteheads;
1092
da53eec6
NTND
1093 if (argc == 2 && !strcmp(argv[1], "-h"))
1094 usage_with_options(builtin_merge_usage, builtin_merge_options);
1c7b76be
MV
1095
1096 /*
1097 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1098 * current branch.
1099 */
894642f6 1100 branch = resolve_ref("HEAD", head_sha1, 0, &flag);
1c7b76be
MV
1101 if (branch && !prefixcmp(branch, "refs/heads/"))
1102 branch += 11;
894642f6
NTND
1103 if (!branch || is_null_sha1(head_sha1))
1104 head_commit = NULL;
baf18fc2
NTND
1105 else
1106 head_commit = lookup_commit_or_die(head_sha1, "HEAD");
1c7b76be
MV
1107
1108 git_config(git_merge_config, NULL);
1109
0d8fc3ef
JH
1110 if (branch_mergeoptions)
1111 parse_branch_merge_options(branch_mergeoptions);
37782920 1112 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1c7b76be 1113 builtin_merge_usage, 0);
2a22c1b3 1114
99bfc669
JK
1115 if (verbosity < 0 && show_progress == -1)
1116 show_progress = 0;
1117
35d2fffd
JH
1118 if (abort_current_merge) {
1119 int nargc = 2;
1120 const char *nargv[] = {"reset", "--merge", NULL};
1121
1122 if (!file_exists(git_path("MERGE_HEAD")))
bacec478 1123 die(_("There is no merge to abort (MERGE_HEAD missing)."));
35d2fffd
JH
1124
1125 /* Invoke 'git reset --merge' */
1126 return cmd_reset(nargc, nargv, prefix);
1127 }
1128
2a22c1b3
JH
1129 if (read_cache_unmerged())
1130 die_resolve_conflict("merge");
1131
1132 if (file_exists(git_path("MERGE_HEAD"))) {
1133 /*
1134 * There is no unmerged entry, don't advise 'git
1135 * add/rm <file>', just 'git commit'.
1136 */
1137 if (advice_resolve_conflict)
bacec478
ÆAB
1138 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1139 "Please, commit your changes before you can merge."));
2a22c1b3 1140 else
bacec478 1141 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
2a22c1b3 1142 }
d7e5c0cb
JS
1143 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1144 if (advice_resolve_conflict)
f68f1801
ÆAB
1145 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1146 "Please, commit your changes before you can merge."));
d7e5c0cb 1147 else
f68f1801 1148 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
2a22c1b3
JH
1149 }
1150 resolve_undo_clear();
1151
7f87aff2
TA
1152 if (verbosity < 0)
1153 show_diffstat = 0;
1c7b76be
MV
1154
1155 if (squash) {
1156 if (!allow_fast_forward)
bacec478 1157 die(_("You cannot combine --squash with --no-ff."));
1c7b76be
MV
1158 option_commit = 0;
1159 }
1160
13474835 1161 if (!allow_fast_forward && fast_forward_only)
bacec478 1162 die(_("You cannot combine --no-ff with --ff-only."));
13474835 1163
4e8115ff
JH
1164 if (!abort_current_merge) {
1165 if (!argc && default_to_upstream)
1166 argc = setup_with_upstream(&argv);
1167 else if (argc == 1 && !strcmp(argv[0], "-"))
1168 argv[0] = "@{-1}";
1169 }
1c7b76be
MV
1170 if (!argc)
1171 usage_with_options(builtin_merge_usage,
1172 builtin_merge_options);
1173
1174 /*
1175 * This could be traditional "merge <msg> HEAD <commit>..." and
1176 * the way we can tell it is to see if the second token is HEAD,
1177 * but some people might have misused the interface and used a
1178 * committish that is the same as HEAD there instead.
1179 * Traditional format never would have "-m" so it is an
1180 * additional safety measure to check for it.
1181 */
1c7b76be 1182
894642f6
NTND
1183 if (!have_message && head_commit &&
1184 is_old_style_invocation(argc, argv, head_commit->object.sha1)) {
1c7b76be
MV
1185 strbuf_addstr(&merge_msg, argv[0]);
1186 head_arg = argv[1];
1187 argv += 2;
1188 argc -= 2;
894642f6 1189 } else if (!head_commit) {
ae8e4c9c 1190 struct commit *remote_head;
1c7b76be
MV
1191 /*
1192 * If the merged head is a valid one there is no reason
1193 * to forbid "git merge" into a branch yet to be born.
1194 * We do the same for "git pull".
1195 */
1196 if (argc != 1)
bacec478
ÆAB
1197 die(_("Can merge only exactly one commit into "
1198 "empty head"));
4be636f4 1199 if (squash)
bacec478 1200 die(_("Squash commit into empty head not supported yet"));
4be636f4 1201 if (!allow_fast_forward)
bacec478
ÆAB
1202 die(_("Non-fast-forward commit does not make sense into "
1203 "an empty head"));
ae8e4c9c 1204 remote_head = get_merge_parent(argv[0]);
1c7b76be 1205 if (!remote_head)
bacec478 1206 die(_("%s - not something we can merge"), argv[0]);
ae8e4c9c
JH
1207 read_empty(remote_head->object.sha1, 0);
1208 update_ref("initial pull", "HEAD", remote_head->object.sha1,
1209 NULL, 0, DIE_ON_ERR);
1c7b76be
MV
1210 return 0;
1211 } else {
97d45bcb 1212 struct strbuf merge_names = STRBUF_INIT;
1c7b76be
MV
1213
1214 /* We are invoked directly as the first-class UI. */
1215 head_arg = "HEAD";
1216
1217 /*
ae8e4c9c
JH
1218 * All the rest are the commits being merged; prepare
1219 * the standard merge summary message to be appended
1220 * to the given message.
1c7b76be 1221 */
f0ecac2b
TRC
1222 for (i = 0; i < argc; i++)
1223 merge_name(argv[i], &merge_names);
1224
96e9420c 1225 if (!have_message || shortlog_len) {
cbda121c
JH
1226 struct fmt_merge_msg_opts opts;
1227 memset(&opts, 0, sizeof(opts));
1228 opts.add_title = !have_message;
1229 opts.shortlog_len = shortlog_len;
1230
1231 fmt_merge_msg(&merge_names, &merge_msg, &opts);
1876166a
RR
1232 if (merge_msg.len)
1233 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1234 }
1c7b76be
MV
1235 }
1236
894642f6 1237 if (!head_commit || !argc)
1c7b76be
MV
1238 usage_with_options(builtin_merge_usage,
1239 builtin_merge_options);
1240
1241 strbuf_addstr(&buf, "merge");
1242 for (i = 0; i < argc; i++)
1243 strbuf_addf(&buf, " %s", argv[i]);
1244 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1245 strbuf_reset(&buf);
1246
1247 for (i = 0; i < argc; i++) {
ae8e4c9c
JH
1248 struct commit *commit = get_merge_parent(argv[i]);
1249 if (!commit)
bacec478 1250 die(_("%s - not something we can merge"), argv[i]);
18668f53 1251 remotes = &commit_list_insert(commit, remotes)->next;
ae8e4c9c
JH
1252 strbuf_addf(&buf, "GITHEAD_%s",
1253 sha1_to_hex(commit->object.sha1));
1c7b76be
MV
1254 setenv(buf.buf, argv[i], 1);
1255 strbuf_reset(&buf);
fab47d05
JH
1256 if (merge_remote_util(commit) &&
1257 merge_remote_util(commit)->obj &&
1258 merge_remote_util(commit)->obj->type == OBJ_TAG) {
1259 option_edit = 1;
1260 allow_fast_forward = 0;
1261 }
1c7b76be
MV
1262 }
1263
1264 if (!use_strategies) {
1265 if (!remoteheads->next)
1266 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1267 else
1268 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1269 }
1270
1271 for (i = 0; i < use_strategies_nr; i++) {
1272 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1273 allow_fast_forward = 0;
1274 if (use_strategies[i]->attr & NO_TRIVIAL)
1275 allow_trivial = 0;
1276 }
1277
1278 if (!remoteheads->next)
894642f6 1279 common = get_merge_bases(head_commit, remoteheads->item, 1);
1c7b76be
MV
1280 else {
1281 struct commit_list *list = remoteheads;
894642f6 1282 commit_list_insert(head_commit, &list);
1c7b76be
MV
1283 common = get_octopus_merge_bases(list);
1284 free(list);
1285 }
1286
894642f6
NTND
1287 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.sha1,
1288 NULL, 0, DIE_ON_ERR);
1c7b76be
MV
1289
1290 if (!common)
1291 ; /* No common ancestors found. We need a real merge. */
1292 else if (!remoteheads->next && !common->next &&
1293 common->item == remoteheads->item) {
1294 /*
1295 * If head can reach all the merge then we are up to date.
1296 * but first the most common case of merging one remote.
1297 */
1298 finish_up_to_date("Already up-to-date.");
1299 return 0;
1300 } else if (allow_fast_forward && !remoteheads->next &&
1301 !common->next &&
894642f6 1302 !hashcmp(common->item->object.sha1, head_commit->object.sha1)) {
1c7b76be 1303 /* Again the most common case of merging one remote. */
f285a2d7 1304 struct strbuf msg = STRBUF_INIT;
ae8e4c9c 1305 struct commit *commit;
1c7b76be
MV
1306 char hex[41];
1307
894642f6 1308 strcpy(hex, find_unique_abbrev(head_commit->object.sha1, DEFAULT_ABBREV));
1c7b76be 1309
7f87aff2 1310 if (verbosity >= 0)
2ceb61e0 1311 printf(_("Updating %s..%s\n"),
7f87aff2
TA
1312 hex,
1313 find_unique_abbrev(remoteheads->item->object.sha1,
1314 DEFAULT_ABBREV));
a75d7b54 1315 strbuf_addstr(&msg, "Fast-forward");
1c7b76be
MV
1316 if (have_message)
1317 strbuf_addstr(&msg,
1318 " (no commit created; -m option ignored)");
ae8e4c9c
JH
1319 commit = remoteheads->item;
1320 if (!commit)
1c7b76be
MV
1321 return 1;
1322
ae8e4c9c
JH
1323 if (checkout_fast_forward(head_commit->object.sha1,
1324 commit->object.sha1))
1c7b76be
MV
1325 return 1;
1326
ae8e4c9c 1327 finish(head_commit, commit->object.sha1, msg.buf);
1c7b76be
MV
1328 drop_save();
1329 return 0;
1330 } else if (!remoteheads->next && common->next)
1331 ;
1332 /*
a75d7b54 1333 * We are not doing octopus and not fast-forward. Need
1c7b76be
MV
1334 * a real merge.
1335 */
1336 else if (!remoteheads->next && !common->next && option_commit) {
1337 /*
a75d7b54 1338 * We are not doing octopus, not fast-forward, and have
1c7b76be
MV
1339 * only one common.
1340 */
1341 refresh_cache(REFRESH_QUIET);
13474835 1342 if (allow_trivial && !fast_forward_only) {
1c7b76be
MV
1343 /* See if it is really trivial. */
1344 git_committer_info(IDENT_ERROR_ON_NO_NAME);
bacec478 1345 printf(_("Trying really trivial in-index merge...\n"));
1c7b76be 1346 if (!read_tree_trivial(common->item->object.sha1,
894642f6
NTND
1347 head_commit->object.sha1, remoteheads->item->object.sha1))
1348 return merge_trivial(head_commit);
bacec478 1349 printf(_("Nope.\n"));
1c7b76be
MV
1350 }
1351 } else {
1352 /*
1353 * An octopus. If we can reach all the remote we are up
1354 * to date.
1355 */
1356 int up_to_date = 1;
1357 struct commit_list *j;
1358
1359 for (j = remoteheads; j; j = j->next) {
1360 struct commit_list *common_one;
1361
1362 /*
1363 * Here we *have* to calculate the individual
1364 * merge_bases again, otherwise "git merge HEAD^
1365 * HEAD^^" would be missed.
1366 */
894642f6 1367 common_one = get_merge_bases(head_commit, j->item, 1);
1c7b76be
MV
1368 if (hashcmp(common_one->item->object.sha1,
1369 j->item->object.sha1)) {
1370 up_to_date = 0;
1371 break;
1372 }
1373 }
1374 if (up_to_date) {
1375 finish_up_to_date("Already up-to-date. Yeeah!");
1376 return 0;
1377 }
1378 }
1379
13474835 1380 if (fast_forward_only)
bacec478 1381 die(_("Not possible to fast-forward, aborting."));
13474835 1382
1c7b76be
MV
1383 /* We are going to make a new commit. */
1384 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1385
1386 /*
1387 * At this point, we need a real merge. No matter what strategy
1388 * we use, it would operate on the index, possibly affecting the
1389 * working tree, and when resolved cleanly, have the desired
1390 * tree in the index -- this means that the index must be in
1391 * sync with the head commit. The strategies are responsible
1392 * to ensure this.
1393 */
b4fd9406
NTND
1394 if (use_strategies_nr == 1 ||
1395 /*
1396 * Stash away the local changes so that we can try more than one.
1397 */
1398 save_state(stash))
1399 hashcpy(stash, null_sha1);
1c7b76be
MV
1400
1401 for (i = 0; i < use_strategies_nr; i++) {
1402 int ret;
1403 if (i) {
bacec478 1404 printf(_("Rewinding the tree to pristine...\n"));
894642f6 1405 restore_state(head_commit->object.sha1, stash);
1c7b76be
MV
1406 }
1407 if (use_strategies_nr != 1)
bacec478 1408 printf(_("Trying merge strategy %s...\n"),
1c7b76be
MV
1409 use_strategies[i]->name);
1410 /*
1411 * Remember which strategy left the state in the working
1412 * tree.
1413 */
1414 wt_strategy = use_strategies[i]->name;
1415
1416 ret = try_merge_strategy(use_strategies[i]->name,
894642f6 1417 common, head_commit, head_arg);
1c7b76be
MV
1418 if (!option_commit && !ret) {
1419 merge_was_ok = 1;
1420 /*
1421 * This is necessary here just to avoid writing
1422 * the tree, but later we will *not* exit with
1423 * status code 1 because merge_was_ok is set.
1424 */
1425 ret = 1;
1426 }
1427
1428 if (ret) {
1429 /*
1430 * The backend exits with 1 when conflicts are
1431 * left to be resolved, with 2 when it does not
1432 * handle the given merge at all.
1433 */
1434 if (ret == 1) {
1435 int cnt = evaluate_result();
1436
1437 if (best_cnt <= 0 || cnt <= best_cnt) {
1438 best_strategy = use_strategies[i]->name;
1439 best_cnt = cnt;
1440 }
1441 }
1442 if (merge_was_ok)
1443 break;
1444 else
1445 continue;
1446 }
1447
1448 /* Automerge succeeded. */
1449 write_tree_trivial(result_tree);
1450 automerge_was_ok = 1;
1451 break;
1452 }
1453
1454 /*
1455 * If we have a resulting tree, that means the strategy module
1456 * auto resolved the merge cleanly.
1457 */
1458 if (automerge_was_ok)
894642f6
NTND
1459 return finish_automerge(head_commit, common, result_tree,
1460 wt_strategy);
1c7b76be
MV
1461
1462 /*
1463 * Pick the result from the best strategy and have the user fix
1464 * it up.
1465 */
1466 if (!best_strategy) {
894642f6 1467 restore_state(head_commit->object.sha1, stash);
1c7b76be
MV
1468 if (use_strategies_nr > 1)
1469 fprintf(stderr,
bacec478 1470 _("No merge strategy handled the merge.\n"));
1c7b76be 1471 else
bacec478 1472 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1c7b76be
MV
1473 use_strategies[0]->name);
1474 return 2;
1475 } else if (best_strategy == wt_strategy)
1476 ; /* We already have its result in the working tree. */
1477 else {
bacec478 1478 printf(_("Rewinding the tree to pristine...\n"));
894642f6 1479 restore_state(head_commit->object.sha1, stash);
bacec478 1480 printf(_("Using the %s to prepare resolving by hand.\n"),
1c7b76be 1481 best_strategy);
894642f6 1482 try_merge_strategy(best_strategy, common, head_commit, head_arg);
1c7b76be
MV
1483 }
1484
1485 if (squash)
894642f6 1486 finish(head_commit, NULL, NULL);
66f4b98a
JS
1487 else
1488 write_merge_state();
1c7b76be
MV
1489
1490 if (merge_was_ok) {
bacec478
ÆAB
1491 fprintf(stderr, _("Automatic merge went well; "
1492 "stopped before committing as requested\n"));
1c7b76be
MV
1493 return 0;
1494 } else
7610fa57 1495 return suggest_conflicts(option_renormalize);
1c7b76be 1496}