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