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