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