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