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