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