Code

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