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