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