]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/merge.c
Copy resolve_ref() return value for longer use
[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
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
6099835c
JH
409static struct object *want_commit(const char *name)
410{
411 struct object *obj;
412 unsigned char sha1[20];
413 if (get_sha1(name, sha1))
414 return NULL;
415 obj = parse_object(sha1);
416 return peel_to_type(name, 0, obj, OBJ_COMMIT);
417}
418
1c7b76be
MV
419/* Get the name for the merge commit's message. */
420static void merge_name(const char *remote, struct strbuf *msg)
421{
422 struct object *remote_head;
c6893323 423 unsigned char branch_head[20];
f285a2d7 424 struct strbuf buf = STRBUF_INIT;
c9717ee9 425 struct strbuf bname = STRBUF_INIT;
1c7b76be 426 const char *ptr;
751c5974 427 char *found_ref;
1c7b76be
MV
428 int len, early;
429
a552de75
JH
430 strbuf_branchname(&bname, remote);
431 remote = bname.buf;
c9717ee9 432
1c7b76be 433 memset(branch_head, 0, sizeof(branch_head));
6099835c 434 remote_head = want_commit(remote);
1c7b76be 435 if (!remote_head)
bacec478 436 die(_("'%s' does not point to a commit"), remote);
1c7b76be 437
751c5974
JK
438 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
439 if (!prefixcmp(found_ref, "refs/heads/")) {
440 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
441 sha1_to_hex(branch_head), remote);
442 goto cleanup;
443 }
69a8b7c7 444 if (!prefixcmp(found_ref, "refs/remotes/")) {
13931236 445 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
69a8b7c7
JK
446 sha1_to_hex(branch_head), remote);
447 goto cleanup;
448 }
1c7b76be
MV
449 }
450
451 /* See if remote matches <name>^^^.. or <name>~<number> */
452 for (len = 0, ptr = remote + strlen(remote);
453 remote < ptr && ptr[-1] == '^';
454 ptr--)
455 len++;
456 if (len)
457 early = 1;
458 else {
459 early = 0;
460 ptr = strrchr(remote, '~');
461 if (ptr) {
462 int seen_nonzero = 0;
463
464 len++; /* count ~ */
465 while (*++ptr && isdigit(*ptr)) {
466 seen_nonzero |= (*ptr != '0');
467 len++;
468 }
469 if (*ptr)
470 len = 0; /* not ...~<number> */
471 else if (seen_nonzero)
472 early = 1;
473 else if (len == 1)
474 early = 1; /* "name~" is "name~1"! */
475 }
476 }
477 if (len) {
478 struct strbuf truname = STRBUF_INIT;
479 strbuf_addstr(&truname, "refs/heads/");
480 strbuf_addstr(&truname, remote);
9b6bf4d5 481 strbuf_setlen(&truname, truname.len - len);
c6893323 482 if (ref_exists(truname.buf)) {
1c7b76be
MV
483 strbuf_addf(msg,
484 "%s\t\tbranch '%s'%s of .\n",
485 sha1_to_hex(remote_head->sha1),
9b6bf4d5 486 truname.buf + 11,
1c7b76be 487 (early ? " (early part)" : ""));
c9717ee9
JH
488 strbuf_release(&truname);
489 goto cleanup;
1c7b76be
MV
490 }
491 }
492
493 if (!strcmp(remote, "FETCH_HEAD") &&
494 !access(git_path("FETCH_HEAD"), R_OK)) {
495 FILE *fp;
f285a2d7 496 struct strbuf line = STRBUF_INIT;
1c7b76be
MV
497 char *ptr;
498
1c7b76be
MV
499 fp = fopen(git_path("FETCH_HEAD"), "r");
500 if (!fp)
bacec478 501 die_errno(_("could not open '%s' for reading"),
d824cbba 502 git_path("FETCH_HEAD"));
1c7b76be
MV
503 strbuf_getline(&line, fp, '\n');
504 fclose(fp);
505 ptr = strstr(line.buf, "\tnot-for-merge\t");
506 if (ptr)
507 strbuf_remove(&line, ptr-line.buf+1, 13);
508 strbuf_addbuf(msg, &line);
509 strbuf_release(&line);
c9717ee9 510 goto cleanup;
1c7b76be
MV
511 }
512 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
513 sha1_to_hex(remote_head->sha1), remote);
c9717ee9
JH
514cleanup:
515 strbuf_release(&buf);
516 strbuf_release(&bname);
1c7b76be
MV
517}
518
0d8fc3ef
JH
519static void parse_branch_merge_options(char *bmo)
520{
521 const char **argv;
522 int argc;
523
524 if (!bmo)
525 return;
526 argc = split_cmdline(bmo, &argv);
527 if (argc < 0)
c7fe5b61
JH
528 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
529 split_cmdline_strerror(argc));
0d8fc3ef
JH
530 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
531 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
532 argc++;
533 argv[0] = "branch.*.mergeoptions";
534 parse_options(argc, argv, NULL, builtin_merge_options,
535 builtin_merge_usage, 0);
536 free(argv);
537}
538
186458b1 539static int git_merge_config(const char *k, const char *v, void *cb)
1c7b76be
MV
540{
541 if (branch && !prefixcmp(k, "branch.") &&
542 !prefixcmp(k + 7, branch) &&
543 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
0d8fc3ef
JH
544 free(branch_mergeoptions);
545 branch_mergeoptions = xstrdup(v);
546 return 0;
1c7b76be
MV
547 }
548
549 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
550 show_diffstat = git_config_bool(k, v);
551 else if (!strcmp(k, "pull.twohead"))
552 return git_config_string(&pull_twohead, k, v);
553 else if (!strcmp(k, "pull.octopus"))
554 return git_config_string(&pull_octopus, k, v);
7610fa57
JN
555 else if (!strcmp(k, "merge.renormalize"))
556 option_renormalize = git_config_bool(k, v);
96e9420c 557 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary")) {
bda3b8ff
RR
558 int is_bool;
559 shortlog_len = git_config_bool_or_int(k, v, &is_bool);
560 if (!is_bool && shortlog_len < 0)
bacec478 561 return error(_("%s: negative length %s"), k, v);
bda3b8ff
RR
562 if (is_bool && shortlog_len)
563 shortlog_len = DEFAULT_MERGE_LOG_LEN;
96e9420c 564 return 0;
f23e8dec
JH
565 } else if (!strcmp(k, "merge.ff")) {
566 int boolval = git_config_maybe_bool(k, v);
567 if (0 <= boolval) {
568 allow_fast_forward = boolval;
569 } else if (v && !strcmp(v, "only")) {
570 allow_fast_forward = 1;
571 fast_forward_only = 1;
572 } /* do not barf on values from future versions of git */
573 return 0;
93e535a5
JH
574 } else if (!strcmp(k, "merge.defaulttoupstream")) {
575 default_to_upstream = git_config_bool(k, v);
576 return 0;
96e9420c 577 }
1c7b76be
MV
578 return git_diff_ui_config(k, v, cb);
579}
580
581static int read_tree_trivial(unsigned char *common, unsigned char *head,
582 unsigned char *one)
583{
584 int i, nr_trees = 0;
585 struct tree *trees[MAX_UNPACK_TREES];
586 struct tree_desc t[MAX_UNPACK_TREES];
587 struct unpack_trees_options opts;
588
589 memset(&opts, 0, sizeof(opts));
590 opts.head_idx = 2;
591 opts.src_index = &the_index;
592 opts.dst_index = &the_index;
593 opts.update = 1;
594 opts.verbose_update = 1;
595 opts.trivial_merges_only = 1;
596 opts.merge = 1;
597 trees[nr_trees] = parse_tree_indirect(common);
598 if (!trees[nr_trees++])
599 return -1;
600 trees[nr_trees] = parse_tree_indirect(head);
601 if (!trees[nr_trees++])
602 return -1;
603 trees[nr_trees] = parse_tree_indirect(one);
604 if (!trees[nr_trees++])
605 return -1;
606 opts.fn = threeway_merge;
607 cache_tree_free(&active_cache_tree);
608 for (i = 0; i < nr_trees; i++) {
609 parse_tree(trees[i]);
610 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
611 }
612 if (unpack_trees(nr_trees, t, &opts))
613 return -1;
614 return 0;
615}
616
617static void write_tree_trivial(unsigned char *sha1)
618{
619 if (write_cache_as_tree(sha1, 0, NULL))
bacec478 620 die(_("git write-tree failed to write a tree"));
1c7b76be
MV
621}
622
16180734
JK
623static const char *merge_argument(struct commit *commit)
624{
625 if (commit)
626 return sha1_to_hex(commit->object.sha1);
627 else
628 return EMPTY_TREE_SHA1_HEX;
629}
630
67ac1e1d
JN
631int try_merge_command(const char *strategy, size_t xopts_nr,
632 const char **xopts, struct commit_list *common,
c674d052 633 const char *head_arg, struct commit_list *remotes)
1c7b76be
MV
634{
635 const char **args;
8cc5b290 636 int i = 0, x = 0, ret;
1c7b76be 637 struct commit_list *j;
f285a2d7 638 struct strbuf buf = STRBUF_INIT;
3f9083cd
CC
639
640 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
641 commit_list_count(remotes)) * sizeof(char *));
642 strbuf_addf(&buf, "merge-%s", strategy);
643 args[i++] = buf.buf;
644 for (x = 0; x < xopts_nr; x++) {
645 char *s = xmalloc(strlen(xopts[x])+2+1);
646 strcpy(s, "--");
647 strcpy(s+2, xopts[x]);
648 args[i++] = s;
649 }
650 for (j = common; j; j = j->next)
16180734 651 args[i++] = xstrdup(merge_argument(j->item));
3f9083cd
CC
652 args[i++] = "--";
653 args[i++] = head_arg;
654 for (j = remotes; j; j = j->next)
16180734 655 args[i++] = xstrdup(merge_argument(j->item));
3f9083cd
CC
656 args[i] = NULL;
657 ret = run_command_v_opt(args, RUN_GIT_CMD);
658 strbuf_release(&buf);
659 i = 1;
660 for (x = 0; x < xopts_nr; x++)
661 free((void *)args[i++]);
662 for (j = common; j; j = j->next)
663 free((void *)args[i++]);
664 i += 2;
665 for (j = remotes; j; j = j->next)
666 free((void *)args[i++]);
667 free(args);
668 discard_cache();
669 if (read_cache() < 0)
bacec478 670 die(_("failed to read the cache"));
3f9083cd
CC
671 resolve_undo_clear();
672
673 return ret;
674}
675
676static int try_merge_strategy(const char *strategy, struct commit_list *common,
894642f6 677 struct commit *head, const char *head_arg)
3f9083cd 678{
668f26ff
MV
679 int index_fd;
680 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
681
682 index_fd = hold_locked_index(lock, 1);
683 refresh_cache(REFRESH_QUIET);
684 if (active_cache_changed &&
685 (write_cache(index_fd, active_cache, active_nr) ||
686 commit_locked_index(lock)))
bacec478 687 return error(_("Unable to write index."));
668f26ff 688 rollback_lock_file(lock);
1c7b76be 689
18668f53 690 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
3f9083cd 691 int clean, x;
18668f53
MV
692 struct commit *result;
693 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
694 int index_fd;
695 struct commit_list *reversed = NULL;
696 struct merge_options o;
3f9083cd 697 struct commit_list *j;
18668f53
MV
698
699 if (remoteheads->next) {
bacec478 700 error(_("Not handling anything other than two heads merge."));
18668f53
MV
701 return 2;
702 }
703
704 init_merge_options(&o);
705 if (!strcmp(strategy, "subtree"))
85e51b78 706 o.subtree_shift = "";
8cc5b290 707
7610fa57 708 o.renormalize = option_renormalize;
99bfc669
JK
709 o.show_rename_progress =
710 show_progress == -1 ? isatty(2) : show_progress;
7610fa57 711
635a7bb1
JN
712 for (x = 0; x < xopts_nr; x++)
713 if (parse_merge_opt(&o, xopts[x]))
bacec478 714 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
18668f53
MV
715
716 o.branch1 = head_arg;
717 o.branch2 = remoteheads->item->util;
718
719 for (j = common; j; j = j->next)
720 commit_list_insert(j->item, &reversed);
721
722 index_fd = hold_locked_index(lock, 1);
894642f6 723 clean = merge_recursive(&o, head,
18668f53
MV
724 remoteheads->item, reversed, &result);
725 if (active_cache_changed &&
726 (write_cache(index_fd, active_cache, active_nr) ||
727 commit_locked_index(lock)))
bacec478 728 die (_("unable to write %s"), get_index_file());
42716660 729 rollback_lock_file(lock);
18668f53
MV
730 return clean ? 0 : 1;
731 } else {
67ac1e1d
JN
732 return try_merge_command(strategy, xopts_nr, xopts,
733 common, head_arg, remoteheads);
18668f53 734 }
1c7b76be
MV
735}
736
737static void count_diff_files(struct diff_queue_struct *q,
738 struct diff_options *opt, void *data)
739{
740 int *count = data;
741
742 (*count) += q->nr;
743}
744
745static int count_unmerged_entries(void)
746{
1c7b76be
MV
747 int i, ret = 0;
748
be6ff819
JH
749 for (i = 0; i < active_nr; i++)
750 if (ce_stage(active_cache[i]))
1c7b76be
MV
751 ret++;
752
753 return ret;
754}
755
cac42b26 756int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
1c7b76be
MV
757{
758 struct tree *trees[MAX_UNPACK_TREES];
759 struct unpack_trees_options opts;
760 struct tree_desc t[MAX_UNPACK_TREES];
761 int i, fd, nr_trees = 0;
762 struct dir_struct dir;
763 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
764
9ca8f607 765 refresh_cache(REFRESH_QUIET);
1c7b76be
MV
766
767 fd = hold_locked_index(lock_file, 1);
768
769 memset(&trees, 0, sizeof(trees));
770 memset(&opts, 0, sizeof(opts));
771 memset(&t, 0, sizeof(t));
5d2299de 772 memset(&dir, 0, sizeof(dir));
7c4c97c0 773 dir.flags |= DIR_SHOW_IGNORED;
1c7b76be
MV
774 dir.exclude_per_dir = ".gitignore";
775 opts.dir = &dir;
776
777 opts.head_idx = 1;
778 opts.src_index = &the_index;
779 opts.dst_index = &the_index;
780 opts.update = 1;
781 opts.verbose_update = 1;
782 opts.merge = 1;
783 opts.fn = twoway_merge;
e294030f 784 setup_unpack_trees_porcelain(&opts, "merge");
1c7b76be
MV
785
786 trees[nr_trees] = parse_tree_indirect(head);
787 if (!trees[nr_trees++])
788 return -1;
789 trees[nr_trees] = parse_tree_indirect(remote);
790 if (!trees[nr_trees++])
791 return -1;
792 for (i = 0; i < nr_trees; i++) {
793 parse_tree(trees[i]);
794 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
795 }
796 if (unpack_trees(nr_trees, t, &opts))
797 return -1;
798 if (write_cache(fd, active_cache, active_nr) ||
799 commit_locked_index(lock_file))
bacec478 800 die(_("unable to write new index file"));
1c7b76be
MV
801 return 0;
802}
803
804static void split_merge_strategies(const char *string, struct strategy **list,
805 int *nr, int *alloc)
806{
807 char *p, *q, *buf;
808
809 if (!string)
810 return;
811
812 buf = xstrdup(string);
813 q = buf;
814 for (;;) {
815 p = strchr(q, ' ');
816 if (!p) {
817 ALLOC_GROW(*list, *nr + 1, *alloc);
818 (*list)[(*nr)++].name = xstrdup(q);
819 free(buf);
820 return;
821 } else {
822 *p = '\0';
823 ALLOC_GROW(*list, *nr + 1, *alloc);
824 (*list)[(*nr)++].name = xstrdup(q);
825 q = ++p;
826 }
827 }
828}
829
830static void add_strategies(const char *string, unsigned attr)
831{
832 struct strategy *list = NULL;
833 int list_alloc = 0, list_nr = 0, i;
834
835 memset(&list, 0, sizeof(list));
836 split_merge_strategies(string, &list, &list_nr, &list_alloc);
1719b5e4
MV
837 if (list) {
838 for (i = 0; i < list_nr; i++)
839 append_strategy(get_strategy(list[i].name));
1c7b76be
MV
840 return;
841 }
842 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
843 if (all_strategy[i].attr & attr)
844 append_strategy(&all_strategy[i]);
845
846}
847
66f4b98a 848static void write_merge_msg(struct strbuf *msg)
65969d43
JS
849{
850 int fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
851 if (fd < 0)
6c80cd29 852 die_errno(_("Could not open '%s' for writing"),
65969d43 853 git_path("MERGE_MSG"));
66f4b98a 854 if (write_in_full(fd, msg->buf, msg->len) != msg->len)
6c80cd29 855 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
65969d43
JS
856 close(fd);
857}
858
66f4b98a 859static void read_merge_msg(struct strbuf *msg)
65969d43 860{
66f4b98a
JS
861 strbuf_reset(msg);
862 if (strbuf_read_file(msg, git_path("MERGE_MSG"), 0) < 0)
650ed9db 863 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
65969d43
JS
864}
865
66f4b98a
JS
866static void write_merge_state(void);
867static void abort_commit(const char *err_msg)
65969d43 868{
66f4b98a
JS
869 if (err_msg)
870 error("%s", err_msg);
871 fprintf(stderr,
872 _("Not committing merge; use 'git commit' to complete the merge.\n"));
873 write_merge_state();
874 exit(1);
875}
876
877static void prepare_to_commit(void)
878{
879 struct strbuf msg = STRBUF_INIT;
880 strbuf_addbuf(&msg, &merge_msg);
881 strbuf_addch(&msg, '\n');
882 write_merge_msg(&msg);
65969d43
JS
883 run_hook(get_index_file(), "prepare-commit-msg",
884 git_path("MERGE_MSG"), "merge", NULL, NULL);
66f4b98a
JS
885 if (option_edit) {
886 if (launch_editor(git_path("MERGE_MSG"), NULL, NULL))
887 abort_commit(NULL);
888 }
889 read_merge_msg(&msg);
890 stripspace(&msg, option_edit);
891 if (!msg.len)
892 abort_commit(_("Empty commit message."));
893 strbuf_release(&merge_msg);
894 strbuf_addbuf(&merge_msg, &msg);
895 strbuf_release(&msg);
65969d43
JS
896}
897
894642f6 898static int merge_trivial(struct commit *head)
1c7b76be
MV
899{
900 unsigned char result_tree[20], result_commit[20];
36e40535 901 struct commit_list *parent = xmalloc(sizeof(*parent));
1c7b76be
MV
902
903 write_tree_trivial(result_tree);
157efde1 904 printf(_("Wonderful.\n"));
894642f6 905 parent->item = head;
36e40535 906 parent->next = xmalloc(sizeof(*parent->next));
446247db
JH
907 parent->next->item = remoteheads->item;
908 parent->next->next = NULL;
66f4b98a 909 prepare_to_commit();
ee20a129 910 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
894642f6 911 finish(head, result_commit, "In-index merge");
1c7b76be
MV
912 drop_save();
913 return 0;
914}
915
894642f6
NTND
916static int finish_automerge(struct commit *head,
917 struct commit_list *common,
1c7b76be
MV
918 unsigned char *result_tree,
919 const char *wt_strategy)
920{
921 struct commit_list *parents = NULL, *j;
922 struct strbuf buf = STRBUF_INIT;
923 unsigned char result_commit[20];
924
925 free_commit_list(common);
926 if (allow_fast_forward) {
927 parents = remoteheads;
894642f6 928 commit_list_insert(head, &parents);
1c7b76be
MV
929 parents = reduce_heads(parents);
930 } else {
931 struct commit_list **pptr = &parents;
932
894642f6 933 pptr = &commit_list_insert(head,
1c7b76be
MV
934 pptr)->next;
935 for (j = remoteheads; j; j = j->next)
936 pptr = &commit_list_insert(j->item, pptr)->next;
937 }
1c7b76be 938 strbuf_addch(&merge_msg, '\n');
66f4b98a
JS
939 prepare_to_commit();
940 free_commit_list(remoteheads);
ee20a129 941 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
f23101bf 942 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
894642f6 943 finish(head, result_commit, buf.buf);
1c7b76be
MV
944 strbuf_release(&buf);
945 drop_save();
946 return 0;
947}
948
7610fa57 949static int suggest_conflicts(int renormalizing)
1c7b76be
MV
950{
951 FILE *fp;
952 int pos;
953
954 fp = fopen(git_path("MERGE_MSG"), "a");
955 if (!fp)
bacec478 956 die_errno(_("Could not open '%s' for writing"),
0721c314 957 git_path("MERGE_MSG"));
1c7b76be
MV
958 fprintf(fp, "\nConflicts:\n");
959 for (pos = 0; pos < active_nr; pos++) {
960 struct cache_entry *ce = active_cache[pos];
961
962 if (ce_stage(ce)) {
963 fprintf(fp, "\t%s\n", ce->name);
964 while (pos + 1 < active_nr &&
965 !strcmp(ce->name,
966 active_cache[pos + 1]->name))
967 pos++;
968 }
969 }
970 fclose(fp);
cb6020bb 971 rerere(allow_rerere_auto);
bacec478
ÆAB
972 printf(_("Automatic merge failed; "
973 "fix conflicts and then commit the result.\n"));
1c7b76be
MV
974 return 1;
975}
976
894642f6
NTND
977static struct commit *is_old_style_invocation(int argc, const char **argv,
978 const unsigned char *head)
1c7b76be
MV
979{
980 struct commit *second_token = NULL;
76bf488e 981 if (argc > 2) {
1c7b76be
MV
982 unsigned char second_sha1[20];
983
984 if (get_sha1(argv[1], second_sha1))
985 return NULL;
986 second_token = lookup_commit_reference_gently(second_sha1, 0);
987 if (!second_token)
bacec478 988 die(_("'%s' is not a commit"), argv[1]);
1c7b76be
MV
989 if (hashcmp(second_token->object.sha1, head))
990 return NULL;
991 }
992 return second_token;
993}
994
995static int evaluate_result(void)
996{
997 int cnt = 0;
998 struct rev_info rev;
999
1c7b76be
MV
1000 /* Check how many files differ. */
1001 init_revisions(&rev, "");
1002 setup_revisions(0, NULL, &rev, NULL);
1003 rev.diffopt.output_format |=
1004 DIFF_FORMAT_CALLBACK;
1005 rev.diffopt.format_callback = count_diff_files;
1006 rev.diffopt.format_callback_data = &cnt;
1007 run_diff_files(&rev, 0);
1008
1009 /*
1010 * Check how many unmerged entries are
1011 * there.
1012 */
1013 cnt += count_unmerged_entries();
1014
1015 return cnt;
1016}
1017
93e535a5
JH
1018/*
1019 * Pretend as if the user told us to merge with the tracking
1020 * branch we have for the upstream of the current branch
1021 */
1022static int setup_with_upstream(const char ***argv)
1023{
1024 struct branch *branch = branch_get(NULL);
1025 int i;
1026 const char **args;
1027
1028 if (!branch)
c7f426d4 1029 die(_("No current branch."));
93e535a5 1030 if (!branch->remote)
c7f426d4 1031 die(_("No remote for the current branch."));
93e535a5 1032 if (!branch->merge_nr)
c7f426d4 1033 die(_("No default upstream defined for the current branch."));
93e535a5
JH
1034
1035 args = xcalloc(branch->merge_nr + 1, sizeof(char *));
1036 for (i = 0; i < branch->merge_nr; i++) {
1037 if (!branch->merge[i]->dst)
c7f426d4 1038 die(_("No remote tracking branch for %s from %s"),
93e535a5
JH
1039 branch->merge[i]->src, branch->remote_name);
1040 args[i] = branch->merge[i]->dst;
1041 }
1042 args[i] = NULL;
1043 *argv = args;
1044 return i;
1045}
1046
66f4b98a
JS
1047static void write_merge_state(void)
1048{
1049 int fd;
1050 struct commit_list *j;
1051 struct strbuf buf = STRBUF_INIT;
1052
1053 for (j = remoteheads; j; j = j->next)
1054 strbuf_addf(&buf, "%s\n",
1055 sha1_to_hex(j->item->object.sha1));
1056 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1057 if (fd < 0)
1058 die_errno(_("Could not open '%s' for writing"),
1059 git_path("MERGE_HEAD"));
1060 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1061 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1062 close(fd);
1063 strbuf_addch(&merge_msg, '\n');
1064 write_merge_msg(&merge_msg);
1065 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1066 if (fd < 0)
1067 die_errno(_("Could not open '%s' for writing"),
1068 git_path("MERGE_MODE"));
1069 strbuf_reset(&buf);
1070 if (!allow_fast_forward)
1071 strbuf_addf(&buf, "no-ff");
1072 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1073 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1074 close(fd);
1075}
1076
1c7b76be
MV
1077int cmd_merge(int argc, const char **argv, const char *prefix)
1078{
1079 unsigned char result_tree[20];
b4fd9406 1080 unsigned char stash[20];
894642f6
NTND
1081 unsigned char head_sha1[20];
1082 struct commit *head_commit;
f285a2d7 1083 struct strbuf buf = STRBUF_INIT;
1c7b76be 1084 const char *head_arg;
d5a35c11 1085 int flag, i, ret = 0;
1c7b76be
MV
1086 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1087 struct commit_list *common = NULL;
1088 const char *best_strategy = NULL, *wt_strategy = NULL;
1089 struct commit_list **remotes = &remoteheads;
1090
da53eec6
NTND
1091 if (argc == 2 && !strcmp(argv[1], "-h"))
1092 usage_with_options(builtin_merge_usage, builtin_merge_options);
1c7b76be
MV
1093
1094 /*
1095 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1096 * current branch.
1097 */
894642f6 1098 branch = resolve_ref("HEAD", head_sha1, 0, &flag);
d5a35c11
NTND
1099 if (branch) {
1100 if (!prefixcmp(branch, "refs/heads/"))
1101 branch += 11;
1102 branch = xstrdup(branch);
1103 }
894642f6
NTND
1104 if (!branch || is_null_sha1(head_sha1))
1105 head_commit = NULL;
baf18fc2
NTND
1106 else
1107 head_commit = lookup_commit_or_die(head_sha1, "HEAD");
1c7b76be
MV
1108
1109 git_config(git_merge_config, NULL);
1110
0d8fc3ef
JH
1111 if (branch_mergeoptions)
1112 parse_branch_merge_options(branch_mergeoptions);
37782920 1113 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1c7b76be 1114 builtin_merge_usage, 0);
2a22c1b3 1115
99bfc669
JK
1116 if (verbosity < 0 && show_progress == -1)
1117 show_progress = 0;
1118
35d2fffd
JH
1119 if (abort_current_merge) {
1120 int nargc = 2;
1121 const char *nargv[] = {"reset", "--merge", NULL};
1122
1123 if (!file_exists(git_path("MERGE_HEAD")))
bacec478 1124 die(_("There is no merge to abort (MERGE_HEAD missing)."));
35d2fffd
JH
1125
1126 /* Invoke 'git reset --merge' */
d5a35c11
NTND
1127 ret = cmd_reset(nargc, nargv, prefix);
1128 goto done;
35d2fffd
JH
1129 }
1130
2a22c1b3
JH
1131 if (read_cache_unmerged())
1132 die_resolve_conflict("merge");
1133
1134 if (file_exists(git_path("MERGE_HEAD"))) {
1135 /*
1136 * There is no unmerged entry, don't advise 'git
1137 * add/rm <file>', just 'git commit'.
1138 */
1139 if (advice_resolve_conflict)
bacec478
ÆAB
1140 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1141 "Please, commit your changes before you can merge."));
2a22c1b3 1142 else
bacec478 1143 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
2a22c1b3 1144 }
d7e5c0cb
JS
1145 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1146 if (advice_resolve_conflict)
f68f1801
ÆAB
1147 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1148 "Please, commit your changes before you can merge."));
d7e5c0cb 1149 else
f68f1801 1150 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
2a22c1b3
JH
1151 }
1152 resolve_undo_clear();
1153
7f87aff2
TA
1154 if (verbosity < 0)
1155 show_diffstat = 0;
1c7b76be
MV
1156
1157 if (squash) {
1158 if (!allow_fast_forward)
bacec478 1159 die(_("You cannot combine --squash with --no-ff."));
1c7b76be
MV
1160 option_commit = 0;
1161 }
1162
13474835 1163 if (!allow_fast_forward && fast_forward_only)
bacec478 1164 die(_("You cannot combine --no-ff with --ff-only."));
13474835 1165
4e8115ff
JH
1166 if (!abort_current_merge) {
1167 if (!argc && default_to_upstream)
1168 argc = setup_with_upstream(&argv);
1169 else if (argc == 1 && !strcmp(argv[0], "-"))
1170 argv[0] = "@{-1}";
1171 }
1c7b76be
MV
1172 if (!argc)
1173 usage_with_options(builtin_merge_usage,
1174 builtin_merge_options);
1175
1176 /*
1177 * This could be traditional "merge <msg> HEAD <commit>..." and
1178 * the way we can tell it is to see if the second token is HEAD,
1179 * but some people might have misused the interface and used a
1180 * committish that is the same as HEAD there instead.
1181 * Traditional format never would have "-m" so it is an
1182 * additional safety measure to check for it.
1183 */
1c7b76be 1184
894642f6
NTND
1185 if (!have_message && head_commit &&
1186 is_old_style_invocation(argc, argv, head_commit->object.sha1)) {
1c7b76be
MV
1187 strbuf_addstr(&merge_msg, argv[0]);
1188 head_arg = argv[1];
1189 argv += 2;
1190 argc -= 2;
894642f6 1191 } else if (!head_commit) {
1c7b76be
MV
1192 struct object *remote_head;
1193 /*
1194 * If the merged head is a valid one there is no reason
1195 * to forbid "git merge" into a branch yet to be born.
1196 * We do the same for "git pull".
1197 */
1198 if (argc != 1)
bacec478
ÆAB
1199 die(_("Can merge only exactly one commit into "
1200 "empty head"));
4be636f4 1201 if (squash)
bacec478 1202 die(_("Squash commit into empty head not supported yet"));
4be636f4 1203 if (!allow_fast_forward)
bacec478
ÆAB
1204 die(_("Non-fast-forward commit does not make sense into "
1205 "an empty head"));
6099835c 1206 remote_head = want_commit(argv[0]);
1c7b76be 1207 if (!remote_head)
bacec478 1208 die(_("%s - not something we can merge"), argv[0]);
97b1b4f3 1209 read_empty(remote_head->sha1, 0);
1c7b76be
MV
1210 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
1211 DIE_ON_ERR);
d5a35c11 1212 goto done;
1c7b76be 1213 } else {
97d45bcb 1214 struct strbuf merge_names = STRBUF_INIT;
1c7b76be
MV
1215
1216 /* We are invoked directly as the first-class UI. */
1217 head_arg = "HEAD";
1218
1219 /*
1220 * All the rest are the commits being merged;
1221 * prepare the standard merge summary message to
1222 * be appended to the given message. If remote
1223 * is invalid we will die later in the common
1224 * codepath so we discard the error in this
1225 * loop.
1226 */
f0ecac2b
TRC
1227 for (i = 0; i < argc; i++)
1228 merge_name(argv[i], &merge_names);
1229
96e9420c 1230 if (!have_message || shortlog_len) {
1876166a 1231 fmt_merge_msg(&merge_names, &merge_msg, !have_message,
96e9420c 1232 shortlog_len);
1876166a
RR
1233 if (merge_msg.len)
1234 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1235 }
1c7b76be
MV
1236 }
1237
894642f6 1238 if (!head_commit || !argc)
1c7b76be
MV
1239 usage_with_options(builtin_merge_usage,
1240 builtin_merge_options);
1241
1242 strbuf_addstr(&buf, "merge");
1243 for (i = 0; i < argc; i++)
1244 strbuf_addf(&buf, " %s", argv[i]);
1245 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1246 strbuf_reset(&buf);
1247
1248 for (i = 0; i < argc; i++) {
1249 struct object *o;
18668f53 1250 struct commit *commit;
1c7b76be 1251
6099835c 1252 o = want_commit(argv[i]);
1c7b76be 1253 if (!o)
bacec478 1254 die(_("%s - not something we can merge"), argv[i]);
18668f53
MV
1255 commit = lookup_commit(o->sha1);
1256 commit->util = (void *)argv[i];
1257 remotes = &commit_list_insert(commit, remotes)->next;
1c7b76be
MV
1258
1259 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1260 setenv(buf.buf, argv[i], 1);
1261 strbuf_reset(&buf);
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.");
d5a35c11 1299 goto done;
1c7b76be
MV
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;
1c7b76be
MV
1305 struct object *o;
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)");
6099835c 1319 o = want_commit(sha1_to_hex(remoteheads->item->object.sha1));
d5a35c11
NTND
1320 if (!o) {
1321 ret = 1;
1322 goto done;
1323 }
1c7b76be 1324
d5a35c11
NTND
1325 if (checkout_fast_forward(head_commit->object.sha1,
1326 remoteheads->item->object.sha1)) {
1327 ret = 1;
1328 goto done;
1329 }
1c7b76be 1330
894642f6 1331 finish(head_commit, o->sha1, msg.buf);
1c7b76be 1332 drop_save();
d5a35c11 1333 goto done;
1c7b76be
MV
1334 } else if (!remoteheads->next && common->next)
1335 ;
1336 /*
a75d7b54 1337 * We are not doing octopus and not fast-forward. Need
1c7b76be
MV
1338 * a real merge.
1339 */
1340 else if (!remoteheads->next && !common->next && option_commit) {
1341 /*
a75d7b54 1342 * We are not doing octopus, not fast-forward, and have
1c7b76be
MV
1343 * only one common.
1344 */
1345 refresh_cache(REFRESH_QUIET);
13474835 1346 if (allow_trivial && !fast_forward_only) {
1c7b76be
MV
1347 /* See if it is really trivial. */
1348 git_committer_info(IDENT_ERROR_ON_NO_NAME);
bacec478 1349 printf(_("Trying really trivial in-index merge...\n"));
1c7b76be 1350 if (!read_tree_trivial(common->item->object.sha1,
d5a35c11
NTND
1351 head_commit->object.sha1,
1352 remoteheads->item->object.sha1)) {
1353 ret = merge_trivial(head_commit);
1354 goto done;
1355 }
bacec478 1356 printf(_("Nope.\n"));
1c7b76be
MV
1357 }
1358 } else {
1359 /*
1360 * An octopus. If we can reach all the remote we are up
1361 * to date.
1362 */
1363 int up_to_date = 1;
1364 struct commit_list *j;
1365
1366 for (j = remoteheads; j; j = j->next) {
1367 struct commit_list *common_one;
1368
1369 /*
1370 * Here we *have* to calculate the individual
1371 * merge_bases again, otherwise "git merge HEAD^
1372 * HEAD^^" would be missed.
1373 */
894642f6 1374 common_one = get_merge_bases(head_commit, j->item, 1);
1c7b76be
MV
1375 if (hashcmp(common_one->item->object.sha1,
1376 j->item->object.sha1)) {
1377 up_to_date = 0;
1378 break;
1379 }
1380 }
1381 if (up_to_date) {
1382 finish_up_to_date("Already up-to-date. Yeeah!");
d5a35c11 1383 goto done;
1c7b76be
MV
1384 }
1385 }
1386
13474835 1387 if (fast_forward_only)
bacec478 1388 die(_("Not possible to fast-forward, aborting."));
13474835 1389
1c7b76be
MV
1390 /* We are going to make a new commit. */
1391 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1392
1393 /*
1394 * At this point, we need a real merge. No matter what strategy
1395 * we use, it would operate on the index, possibly affecting the
1396 * working tree, and when resolved cleanly, have the desired
1397 * tree in the index -- this means that the index must be in
1398 * sync with the head commit. The strategies are responsible
1399 * to ensure this.
1400 */
b4fd9406
NTND
1401 if (use_strategies_nr == 1 ||
1402 /*
1403 * Stash away the local changes so that we can try more than one.
1404 */
1405 save_state(stash))
1406 hashcpy(stash, null_sha1);
1c7b76be
MV
1407
1408 for (i = 0; i < use_strategies_nr; i++) {
1409 int ret;
1410 if (i) {
bacec478 1411 printf(_("Rewinding the tree to pristine...\n"));
894642f6 1412 restore_state(head_commit->object.sha1, stash);
1c7b76be
MV
1413 }
1414 if (use_strategies_nr != 1)
bacec478 1415 printf(_("Trying merge strategy %s...\n"),
1c7b76be
MV
1416 use_strategies[i]->name);
1417 /*
1418 * Remember which strategy left the state in the working
1419 * tree.
1420 */
1421 wt_strategy = use_strategies[i]->name;
1422
1423 ret = try_merge_strategy(use_strategies[i]->name,
894642f6 1424 common, head_commit, head_arg);
1c7b76be
MV
1425 if (!option_commit && !ret) {
1426 merge_was_ok = 1;
1427 /*
1428 * This is necessary here just to avoid writing
1429 * the tree, but later we will *not* exit with
1430 * status code 1 because merge_was_ok is set.
1431 */
1432 ret = 1;
1433 }
1434
1435 if (ret) {
1436 /*
1437 * The backend exits with 1 when conflicts are
1438 * left to be resolved, with 2 when it does not
1439 * handle the given merge at all.
1440 */
1441 if (ret == 1) {
1442 int cnt = evaluate_result();
1443
1444 if (best_cnt <= 0 || cnt <= best_cnt) {
1445 best_strategy = use_strategies[i]->name;
1446 best_cnt = cnt;
1447 }
1448 }
1449 if (merge_was_ok)
1450 break;
1451 else
1452 continue;
1453 }
1454
1455 /* Automerge succeeded. */
1456 write_tree_trivial(result_tree);
1457 automerge_was_ok = 1;
1458 break;
1459 }
1460
1461 /*
1462 * If we have a resulting tree, that means the strategy module
1463 * auto resolved the merge cleanly.
1464 */
d5a35c11
NTND
1465 if (automerge_was_ok) {
1466 ret = finish_automerge(head_commit, common, result_tree,
1467 wt_strategy);
1468 goto done;
1469 }
1c7b76be
MV
1470
1471 /*
1472 * Pick the result from the best strategy and have the user fix
1473 * it up.
1474 */
1475 if (!best_strategy) {
894642f6 1476 restore_state(head_commit->object.sha1, stash);
1c7b76be
MV
1477 if (use_strategies_nr > 1)
1478 fprintf(stderr,
bacec478 1479 _("No merge strategy handled the merge.\n"));
1c7b76be 1480 else
bacec478 1481 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1c7b76be 1482 use_strategies[0]->name);
d5a35c11
NTND
1483 ret = 2;
1484 goto done;
1c7b76be
MV
1485 } else if (best_strategy == wt_strategy)
1486 ; /* We already have its result in the working tree. */
1487 else {
bacec478 1488 printf(_("Rewinding the tree to pristine...\n"));
894642f6 1489 restore_state(head_commit->object.sha1, stash);
bacec478 1490 printf(_("Using the %s to prepare resolving by hand.\n"),
1c7b76be 1491 best_strategy);
894642f6 1492 try_merge_strategy(best_strategy, common, head_commit, head_arg);
1c7b76be
MV
1493 }
1494
1495 if (squash)
894642f6 1496 finish(head_commit, NULL, NULL);
66f4b98a
JS
1497 else
1498 write_merge_state();
1c7b76be 1499
d5a35c11 1500 if (merge_was_ok)
bacec478
ÆAB
1501 fprintf(stderr, _("Automatic merge went well; "
1502 "stopped before committing as requested\n"));
d5a35c11
NTND
1503 else
1504 ret = suggest_conflicts(option_renormalize);
1505
1506done:
1507 free((char *)branch);
1508 return ret;
1c7b76be 1509}