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