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