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