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