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