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