resolve-undo: record resolved conflicts in a new index extension section
[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
29 #define DEFAULT_TWOHEAD (1<<0)
30 #define DEFAULT_OCTOPUS (1<<1)
31 #define NO_FAST_FORWARD (1<<2)
32 #define NO_TRIVIAL      (1<<3)
33
34 struct strategy {
35         const char *name;
36         unsigned attr;
37 };
38
39 static const char * const builtin_merge_usage[] = {
40         "git merge [options] <remote>...",
41         "git merge [options] <msg> HEAD <remote>",
42         NULL
43 };
44
45 static int show_diffstat = 1, option_log, squash;
46 static int option_commit = 1, allow_fast_forward = 1;
47 static int fast_forward_only;
48 static int allow_trivial = 1, have_message;
49 static struct strbuf merge_msg;
50 static struct commit_list *remoteheads;
51 static unsigned char head[20], stash[20];
52 static struct strategy **use_strategies;
53 static size_t use_strategies_nr, use_strategies_alloc;
54 static const char *branch;
55 static int verbosity;
56
57 static struct strategy all_strategy[] = {
58         { "recursive",  DEFAULT_TWOHEAD | NO_TRIVIAL },
59         { "octopus",    DEFAULT_OCTOPUS },
60         { "resolve",    0 },
61         { "ours",       NO_FAST_FORWARD | NO_TRIVIAL },
62         { "subtree",    NO_FAST_FORWARD | NO_TRIVIAL },
63 };
64
65 static const char *pull_twohead, *pull_octopus;
66
67 static int option_parse_message(const struct option *opt,
68                                 const char *arg, int unset)
69 {
70         struct strbuf *buf = opt->value;
71
72         if (unset)
73                 strbuf_setlen(buf, 0);
74         else if (arg) {
75                 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
76                 have_message = 1;
77         } else
78                 return error("switch `m' requires a value");
79         return 0;
80 }
81
82 static struct strategy *get_strategy(const char *name)
83 {
84         int i;
85         struct strategy *ret;
86         static struct cmdnames main_cmds, other_cmds;
87         static int loaded;
88
89         if (!name)
90                 return NULL;
91
92         for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
93                 if (!strcmp(name, all_strategy[i].name))
94                         return &all_strategy[i];
95
96         if (!loaded) {
97                 struct cmdnames not_strategies;
98                 loaded = 1;
99
100                 memset(&not_strategies, 0, sizeof(struct cmdnames));
101                 load_command_list("git-merge-", &main_cmds, &other_cmds);
102                 for (i = 0; i < main_cmds.cnt; i++) {
103                         int j, found = 0;
104                         struct cmdname *ent = main_cmds.names[i];
105                         for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
106                                 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
107                                                 && !all_strategy[j].name[ent->len])
108                                         found = 1;
109                         if (!found)
110                                 add_cmdname(&not_strategies, ent->name, ent->len);
111                 }
112                 exclude_cmds(&main_cmds, &not_strategies);
113         }
114         if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
115                 fprintf(stderr, "Could not find merge strategy '%s'.\n", name);
116                 fprintf(stderr, "Available strategies are:");
117                 for (i = 0; i < main_cmds.cnt; i++)
118                         fprintf(stderr, " %s", main_cmds.names[i]->name);
119                 fprintf(stderr, ".\n");
120                 if (other_cmds.cnt) {
121                         fprintf(stderr, "Available custom strategies are:");
122                         for (i = 0; i < other_cmds.cnt; i++)
123                                 fprintf(stderr, " %s", other_cmds.names[i]->name);
124                         fprintf(stderr, ".\n");
125                 }
126                 exit(1);
127         }
128
129         ret = xcalloc(1, sizeof(struct strategy));
130         ret->name = xstrdup(name);
131         return ret;
132 }
133
134 static void append_strategy(struct strategy *s)
135 {
136         ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
137         use_strategies[use_strategies_nr++] = s;
138 }
139
140 static int option_parse_strategy(const struct option *opt,
141                                  const char *name, int unset)
142 {
143         if (unset)
144                 return 0;
145
146         append_strategy(get_strategy(name));
147         return 0;
148 }
149
150 static int option_parse_n(const struct option *opt,
151                           const char *arg, int unset)
152 {
153         show_diffstat = unset;
154         return 0;
155 }
156
157 static struct option builtin_merge_options[] = {
158         { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
159                 "do not show a diffstat at the end of the merge",
160                 PARSE_OPT_NOARG, option_parse_n },
161         OPT_BOOLEAN(0, "stat", &show_diffstat,
162                 "show a diffstat at the end of the merge"),
163         OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
164         OPT_BOOLEAN(0, "log", &option_log,
165                 "add list of one-line log to merge commit message"),
166         OPT_BOOLEAN(0, "squash", &squash,
167                 "create a single commit instead of doing a merge"),
168         OPT_BOOLEAN(0, "commit", &option_commit,
169                 "perform a commit if the merge succeeds (default)"),
170         OPT_BOOLEAN(0, "ff", &allow_fast_forward,
171                 "allow fast-forward (default)"),
172         OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
173                 "abort if fast-forward is not possible"),
174         OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
175                 "merge strategy to use", option_parse_strategy),
176         OPT_CALLBACK('m', "message", &merge_msg, "message",
177                 "message to be used for the merge commit (if any)",
178                 option_parse_message),
179         OPT__VERBOSITY(&verbosity),
180         OPT_END()
181 };
182
183 /* Cleans up metadata that is uninteresting after a succeeded merge. */
184 static void drop_save(void)
185 {
186         unlink(git_path("MERGE_HEAD"));
187         unlink(git_path("MERGE_MSG"));
188         unlink(git_path("MERGE_MODE"));
189 }
190
191 static void save_state(void)
192 {
193         int len;
194         struct child_process cp;
195         struct strbuf buffer = STRBUF_INIT;
196         const char *argv[] = {"stash", "create", NULL};
197
198         memset(&cp, 0, sizeof(cp));
199         cp.argv = argv;
200         cp.out = -1;
201         cp.git_cmd = 1;
202
203         if (start_command(&cp))
204                 die("could not run stash.");
205         len = strbuf_read(&buffer, cp.out, 1024);
206         close(cp.out);
207
208         if (finish_command(&cp) || len < 0)
209                 die("stash failed");
210         else if (!len)
211                 return;
212         strbuf_setlen(&buffer, buffer.len-1);
213         if (get_sha1(buffer.buf, stash))
214                 die("not a valid object: %s", buffer.buf);
215 }
216
217 static void reset_hard(unsigned const char *sha1, int verbose)
218 {
219         int i = 0;
220         const char *args[6];
221
222         args[i++] = "read-tree";
223         if (verbose)
224                 args[i++] = "-v";
225         args[i++] = "--reset";
226         args[i++] = "-u";
227         args[i++] = sha1_to_hex(sha1);
228         args[i] = NULL;
229
230         if (run_command_v_opt(args, RUN_GIT_CMD))
231                 die("read-tree failed");
232 }
233
234 static void restore_state(void)
235 {
236         struct strbuf sb = STRBUF_INIT;
237         const char *args[] = { "stash", "apply", NULL, NULL };
238
239         if (is_null_sha1(stash))
240                 return;
241
242         reset_hard(head, 1);
243
244         args[2] = sha1_to_hex(stash);
245
246         /*
247          * It is OK to ignore error here, for example when there was
248          * nothing to restore.
249          */
250         run_command_v_opt(args, RUN_GIT_CMD);
251
252         strbuf_release(&sb);
253         refresh_cache(REFRESH_QUIET);
254 }
255
256 /* This is called when no merge was necessary. */
257 static void finish_up_to_date(const char *msg)
258 {
259         if (verbosity >= 0)
260                 printf("%s%s\n", squash ? " (nothing to squash)" : "", msg);
261         drop_save();
262 }
263
264 static void squash_message(void)
265 {
266         struct rev_info rev;
267         struct commit *commit;
268         struct strbuf out = STRBUF_INIT;
269         struct commit_list *j;
270         int fd;
271         struct pretty_print_context ctx = {0};
272
273         printf("Squash commit -- not updating HEAD\n");
274         fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
275         if (fd < 0)
276                 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
277
278         init_revisions(&rev, NULL);
279         rev.ignore_merges = 1;
280         rev.commit_format = CMIT_FMT_MEDIUM;
281
282         commit = lookup_commit(head);
283         commit->object.flags |= UNINTERESTING;
284         add_pending_object(&rev, &commit->object, NULL);
285
286         for (j = remoteheads; j; j = j->next)
287                 add_pending_object(&rev, &j->item->object, NULL);
288
289         setup_revisions(0, NULL, &rev, NULL);
290         if (prepare_revision_walk(&rev))
291                 die("revision walk setup failed");
292
293         ctx.abbrev = rev.abbrev;
294         ctx.date_mode = rev.date_mode;
295
296         strbuf_addstr(&out, "Squashed commit of the following:\n");
297         while ((commit = get_revision(&rev)) != NULL) {
298                 strbuf_addch(&out, '\n');
299                 strbuf_addf(&out, "commit %s\n",
300                         sha1_to_hex(commit->object.sha1));
301                 pretty_print_commit(rev.commit_format, commit, &out, &ctx);
302         }
303         if (write(fd, out.buf, out.len) < 0)
304                 die_errno("Writing SQUASH_MSG");
305         if (close(fd))
306                 die_errno("Finishing SQUASH_MSG");
307         strbuf_release(&out);
308 }
309
310 static void finish(const unsigned char *new_head, const char *msg)
311 {
312         struct strbuf reflog_message = STRBUF_INIT;
313
314         if (!msg)
315                 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
316         else {
317                 if (verbosity >= 0)
318                         printf("%s\n", msg);
319                 strbuf_addf(&reflog_message, "%s: %s",
320                         getenv("GIT_REFLOG_ACTION"), msg);
321         }
322         if (squash) {
323                 squash_message();
324         } else {
325                 if (verbosity >= 0 && !merge_msg.len)
326                         printf("No merge message -- not updating HEAD\n");
327                 else {
328                         const char *argv_gc_auto[] = { "gc", "--auto", NULL };
329                         update_ref(reflog_message.buf, "HEAD",
330                                 new_head, head, 0,
331                                 DIE_ON_ERR);
332                         /*
333                          * We ignore errors in 'gc --auto', since the
334                          * user should see them.
335                          */
336                         run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
337                 }
338         }
339         if (new_head && show_diffstat) {
340                 struct diff_options opts;
341                 diff_setup(&opts);
342                 opts.output_format |=
343                         DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
344                 opts.detect_rename = DIFF_DETECT_RENAME;
345                 if (diff_use_color_default > 0)
346                         DIFF_OPT_SET(&opts, COLOR_DIFF);
347                 if (diff_setup_done(&opts) < 0)
348                         die("diff_setup_done failed");
349                 diff_tree_sha1(head, new_head, "", &opts);
350                 diffcore_std(&opts);
351                 diff_flush(&opts);
352         }
353
354         /* Run a post-merge hook */
355         run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
356
357         strbuf_release(&reflog_message);
358 }
359
360 /* Get the name for the merge commit's message. */
361 static void merge_name(const char *remote, struct strbuf *msg)
362 {
363         struct object *remote_head;
364         unsigned char branch_head[20], buf_sha[20];
365         struct strbuf buf = STRBUF_INIT;
366         struct strbuf bname = STRBUF_INIT;
367         const char *ptr;
368         char *found_ref;
369         int len, early;
370
371         strbuf_branchname(&bname, remote);
372         remote = bname.buf;
373
374         memset(branch_head, 0, sizeof(branch_head));
375         remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
376         if (!remote_head)
377                 die("'%s' does not point to a commit", remote);
378
379         if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
380                 if (!prefixcmp(found_ref, "refs/heads/")) {
381                         strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
382                                     sha1_to_hex(branch_head), remote);
383                         goto cleanup;
384                 }
385                 if (!prefixcmp(found_ref, "refs/remotes/")) {
386                         strbuf_addf(msg, "%s\t\tremote branch '%s' of .\n",
387                                     sha1_to_hex(branch_head), remote);
388                         goto cleanup;
389                 }
390         }
391
392         /* See if remote matches <name>^^^.. or <name>~<number> */
393         for (len = 0, ptr = remote + strlen(remote);
394              remote < ptr && ptr[-1] == '^';
395              ptr--)
396                 len++;
397         if (len)
398                 early = 1;
399         else {
400                 early = 0;
401                 ptr = strrchr(remote, '~');
402                 if (ptr) {
403                         int seen_nonzero = 0;
404
405                         len++; /* count ~ */
406                         while (*++ptr && isdigit(*ptr)) {
407                                 seen_nonzero |= (*ptr != '0');
408                                 len++;
409                         }
410                         if (*ptr)
411                                 len = 0; /* not ...~<number> */
412                         else if (seen_nonzero)
413                                 early = 1;
414                         else if (len == 1)
415                                 early = 1; /* "name~" is "name~1"! */
416                 }
417         }
418         if (len) {
419                 struct strbuf truname = STRBUF_INIT;
420                 strbuf_addstr(&truname, "refs/heads/");
421                 strbuf_addstr(&truname, remote);
422                 strbuf_setlen(&truname, truname.len - len);
423                 if (resolve_ref(truname.buf, buf_sha, 0, NULL)) {
424                         strbuf_addf(msg,
425                                     "%s\t\tbranch '%s'%s of .\n",
426                                     sha1_to_hex(remote_head->sha1),
427                                     truname.buf + 11,
428                                     (early ? " (early part)" : ""));
429                         strbuf_release(&truname);
430                         goto cleanup;
431                 }
432         }
433
434         if (!strcmp(remote, "FETCH_HEAD") &&
435                         !access(git_path("FETCH_HEAD"), R_OK)) {
436                 FILE *fp;
437                 struct strbuf line = STRBUF_INIT;
438                 char *ptr;
439
440                 fp = fopen(git_path("FETCH_HEAD"), "r");
441                 if (!fp)
442                         die_errno("could not open '%s' for reading",
443                                   git_path("FETCH_HEAD"));
444                 strbuf_getline(&line, fp, '\n');
445                 fclose(fp);
446                 ptr = strstr(line.buf, "\tnot-for-merge\t");
447                 if (ptr)
448                         strbuf_remove(&line, ptr-line.buf+1, 13);
449                 strbuf_addbuf(msg, &line);
450                 strbuf_release(&line);
451                 goto cleanup;
452         }
453         strbuf_addf(msg, "%s\t\tcommit '%s'\n",
454                 sha1_to_hex(remote_head->sha1), remote);
455 cleanup:
456         strbuf_release(&buf);
457         strbuf_release(&bname);
458 }
459
460 static int git_merge_config(const char *k, const char *v, void *cb)
461 {
462         if (branch && !prefixcmp(k, "branch.") &&
463                 !prefixcmp(k + 7, branch) &&
464                 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
465                 const char **argv;
466                 int argc;
467                 char *buf;
468
469                 buf = xstrdup(v);
470                 argc = split_cmdline(buf, &argv);
471                 if (argc < 0)
472                         die("Bad branch.%s.mergeoptions string", branch);
473                 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
474                 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
475                 argc++;
476                 parse_options(argc, argv, NULL, builtin_merge_options,
477                               builtin_merge_usage, 0);
478                 free(buf);
479         }
480
481         if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
482                 show_diffstat = git_config_bool(k, v);
483         else if (!strcmp(k, "pull.twohead"))
484                 return git_config_string(&pull_twohead, k, v);
485         else if (!strcmp(k, "pull.octopus"))
486                 return git_config_string(&pull_octopus, k, v);
487         else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary"))
488                 option_log = git_config_bool(k, v);
489         return git_diff_ui_config(k, v, cb);
490 }
491
492 static int read_tree_trivial(unsigned char *common, unsigned char *head,
493                              unsigned char *one)
494 {
495         int i, nr_trees = 0;
496         struct tree *trees[MAX_UNPACK_TREES];
497         struct tree_desc t[MAX_UNPACK_TREES];
498         struct unpack_trees_options opts;
499
500         memset(&opts, 0, sizeof(opts));
501         opts.head_idx = 2;
502         opts.src_index = &the_index;
503         opts.dst_index = &the_index;
504         opts.update = 1;
505         opts.verbose_update = 1;
506         opts.trivial_merges_only = 1;
507         opts.merge = 1;
508         trees[nr_trees] = parse_tree_indirect(common);
509         if (!trees[nr_trees++])
510                 return -1;
511         trees[nr_trees] = parse_tree_indirect(head);
512         if (!trees[nr_trees++])
513                 return -1;
514         trees[nr_trees] = parse_tree_indirect(one);
515         if (!trees[nr_trees++])
516                 return -1;
517         opts.fn = threeway_merge;
518         cache_tree_free(&active_cache_tree);
519         for (i = 0; i < nr_trees; i++) {
520                 parse_tree(trees[i]);
521                 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
522         }
523         if (unpack_trees(nr_trees, t, &opts))
524                 return -1;
525         return 0;
526 }
527
528 static void write_tree_trivial(unsigned char *sha1)
529 {
530         if (write_cache_as_tree(sha1, 0, NULL))
531                 die("git write-tree failed to write a tree");
532 }
533
534 static int try_merge_strategy(const char *strategy, struct commit_list *common,
535                               const char *head_arg)
536 {
537         const char **args;
538         int i = 0, ret;
539         struct commit_list *j;
540         struct strbuf buf = STRBUF_INIT;
541         int index_fd;
542         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
543
544         index_fd = hold_locked_index(lock, 1);
545         refresh_cache(REFRESH_QUIET);
546         if (active_cache_changed &&
547                         (write_cache(index_fd, active_cache, active_nr) ||
548                          commit_locked_index(lock)))
549                 return error("Unable to write index.");
550         rollback_lock_file(lock);
551
552         if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
553                 int clean;
554                 struct commit *result;
555                 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
556                 int index_fd;
557                 struct commit_list *reversed = NULL;
558                 struct merge_options o;
559
560                 if (remoteheads->next) {
561                         error("Not handling anything other than two heads merge.");
562                         return 2;
563                 }
564
565                 init_merge_options(&o);
566                 if (!strcmp(strategy, "subtree"))
567                         o.subtree_merge = 1;
568
569                 o.branch1 = head_arg;
570                 o.branch2 = remoteheads->item->util;
571
572                 for (j = common; j; j = j->next)
573                         commit_list_insert(j->item, &reversed);
574
575                 index_fd = hold_locked_index(lock, 1);
576                 clean = merge_recursive(&o, lookup_commit(head),
577                                 remoteheads->item, reversed, &result);
578                 if (active_cache_changed &&
579                                 (write_cache(index_fd, active_cache, active_nr) ||
580                                  commit_locked_index(lock)))
581                         die ("unable to write %s", get_index_file());
582                 rollback_lock_file(lock);
583                 return clean ? 0 : 1;
584         } else {
585                 args = xmalloc((4 + commit_list_count(common) +
586                                         commit_list_count(remoteheads)) * sizeof(char *));
587                 strbuf_addf(&buf, "merge-%s", strategy);
588                 args[i++] = buf.buf;
589                 for (j = common; j; j = j->next)
590                         args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
591                 args[i++] = "--";
592                 args[i++] = head_arg;
593                 for (j = remoteheads; j; j = j->next)
594                         args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
595                 args[i] = NULL;
596                 ret = run_command_v_opt(args, RUN_GIT_CMD);
597                 strbuf_release(&buf);
598                 i = 1;
599                 for (j = common; j; j = j->next)
600                         free((void *)args[i++]);
601                 i += 2;
602                 for (j = remoteheads; j; j = j->next)
603                         free((void *)args[i++]);
604                 free(args);
605                 discard_cache();
606                 if (read_cache() < 0)
607                         die("failed to read the cache");
608                 resolve_undo_clear();
609                 return ret;
610         }
611 }
612
613 static void count_diff_files(struct diff_queue_struct *q,
614                              struct diff_options *opt, void *data)
615 {
616         int *count = data;
617
618         (*count) += q->nr;
619 }
620
621 static int count_unmerged_entries(void)
622 {
623         int i, ret = 0;
624
625         for (i = 0; i < active_nr; i++)
626                 if (ce_stage(active_cache[i]))
627                         ret++;
628
629         return ret;
630 }
631
632 static int checkout_fast_forward(unsigned char *head, unsigned char *remote)
633 {
634         struct tree *trees[MAX_UNPACK_TREES];
635         struct unpack_trees_options opts;
636         struct tree_desc t[MAX_UNPACK_TREES];
637         int i, fd, nr_trees = 0;
638         struct dir_struct dir;
639         struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
640
641         refresh_cache(REFRESH_QUIET);
642
643         fd = hold_locked_index(lock_file, 1);
644
645         memset(&trees, 0, sizeof(trees));
646         memset(&opts, 0, sizeof(opts));
647         memset(&t, 0, sizeof(t));
648         memset(&dir, 0, sizeof(dir));
649         dir.flags |= DIR_SHOW_IGNORED;
650         dir.exclude_per_dir = ".gitignore";
651         opts.dir = &dir;
652
653         opts.head_idx = 1;
654         opts.src_index = &the_index;
655         opts.dst_index = &the_index;
656         opts.update = 1;
657         opts.verbose_update = 1;
658         opts.merge = 1;
659         opts.fn = twoway_merge;
660         opts.msgs = get_porcelain_error_msgs();
661
662         trees[nr_trees] = parse_tree_indirect(head);
663         if (!trees[nr_trees++])
664                 return -1;
665         trees[nr_trees] = parse_tree_indirect(remote);
666         if (!trees[nr_trees++])
667                 return -1;
668         for (i = 0; i < nr_trees; i++) {
669                 parse_tree(trees[i]);
670                 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
671         }
672         if (unpack_trees(nr_trees, t, &opts))
673                 return -1;
674         if (write_cache(fd, active_cache, active_nr) ||
675                 commit_locked_index(lock_file))
676                 die("unable to write new index file");
677         return 0;
678 }
679
680 static void split_merge_strategies(const char *string, struct strategy **list,
681                                    int *nr, int *alloc)
682 {
683         char *p, *q, *buf;
684
685         if (!string)
686                 return;
687
688         buf = xstrdup(string);
689         q = buf;
690         for (;;) {
691                 p = strchr(q, ' ');
692                 if (!p) {
693                         ALLOC_GROW(*list, *nr + 1, *alloc);
694                         (*list)[(*nr)++].name = xstrdup(q);
695                         free(buf);
696                         return;
697                 } else {
698                         *p = '\0';
699                         ALLOC_GROW(*list, *nr + 1, *alloc);
700                         (*list)[(*nr)++].name = xstrdup(q);
701                         q = ++p;
702                 }
703         }
704 }
705
706 static void add_strategies(const char *string, unsigned attr)
707 {
708         struct strategy *list = NULL;
709         int list_alloc = 0, list_nr = 0, i;
710
711         memset(&list, 0, sizeof(list));
712         split_merge_strategies(string, &list, &list_nr, &list_alloc);
713         if (list) {
714                 for (i = 0; i < list_nr; i++)
715                         append_strategy(get_strategy(list[i].name));
716                 return;
717         }
718         for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
719                 if (all_strategy[i].attr & attr)
720                         append_strategy(&all_strategy[i]);
721
722 }
723
724 static int merge_trivial(void)
725 {
726         unsigned char result_tree[20], result_commit[20];
727         struct commit_list *parent = xmalloc(sizeof(*parent));
728
729         write_tree_trivial(result_tree);
730         printf("Wonderful.\n");
731         parent->item = lookup_commit(head);
732         parent->next = xmalloc(sizeof(*parent->next));
733         parent->next->item = remoteheads->item;
734         parent->next->next = NULL;
735         commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
736         finish(result_commit, "In-index merge");
737         drop_save();
738         return 0;
739 }
740
741 static int finish_automerge(struct commit_list *common,
742                             unsigned char *result_tree,
743                             const char *wt_strategy)
744 {
745         struct commit_list *parents = NULL, *j;
746         struct strbuf buf = STRBUF_INIT;
747         unsigned char result_commit[20];
748
749         free_commit_list(common);
750         if (allow_fast_forward) {
751                 parents = remoteheads;
752                 commit_list_insert(lookup_commit(head), &parents);
753                 parents = reduce_heads(parents);
754         } else {
755                 struct commit_list **pptr = &parents;
756
757                 pptr = &commit_list_insert(lookup_commit(head),
758                                 pptr)->next;
759                 for (j = remoteheads; j; j = j->next)
760                         pptr = &commit_list_insert(j->item, pptr)->next;
761         }
762         free_commit_list(remoteheads);
763         strbuf_addch(&merge_msg, '\n');
764         commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
765         strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
766         finish(result_commit, buf.buf);
767         strbuf_release(&buf);
768         drop_save();
769         return 0;
770 }
771
772 static int suggest_conflicts(void)
773 {
774         FILE *fp;
775         int pos;
776
777         fp = fopen(git_path("MERGE_MSG"), "a");
778         if (!fp)
779                 die_errno("Could not open '%s' for writing",
780                           git_path("MERGE_MSG"));
781         fprintf(fp, "\nConflicts:\n");
782         for (pos = 0; pos < active_nr; pos++) {
783                 struct cache_entry *ce = active_cache[pos];
784
785                 if (ce_stage(ce)) {
786                         fprintf(fp, "\t%s\n", ce->name);
787                         while (pos + 1 < active_nr &&
788                                         !strcmp(ce->name,
789                                                 active_cache[pos + 1]->name))
790                                 pos++;
791                 }
792         }
793         fclose(fp);
794         rerere();
795         printf("Automatic merge failed; "
796                         "fix conflicts and then commit the result.\n");
797         return 1;
798 }
799
800 static struct commit *is_old_style_invocation(int argc, const char **argv)
801 {
802         struct commit *second_token = NULL;
803         if (argc > 2) {
804                 unsigned char second_sha1[20];
805
806                 if (get_sha1(argv[1], second_sha1))
807                         return NULL;
808                 second_token = lookup_commit_reference_gently(second_sha1, 0);
809                 if (!second_token)
810                         die("'%s' is not a commit", argv[1]);
811                 if (hashcmp(second_token->object.sha1, head))
812                         return NULL;
813         }
814         return second_token;
815 }
816
817 static int evaluate_result(void)
818 {
819         int cnt = 0;
820         struct rev_info rev;
821
822         /* Check how many files differ. */
823         init_revisions(&rev, "");
824         setup_revisions(0, NULL, &rev, NULL);
825         rev.diffopt.output_format |=
826                 DIFF_FORMAT_CALLBACK;
827         rev.diffopt.format_callback = count_diff_files;
828         rev.diffopt.format_callback_data = &cnt;
829         run_diff_files(&rev, 0);
830
831         /*
832          * Check how many unmerged entries are
833          * there.
834          */
835         cnt += count_unmerged_entries();
836
837         return cnt;
838 }
839
840 int cmd_merge(int argc, const char **argv, const char *prefix)
841 {
842         unsigned char result_tree[20];
843         struct strbuf buf = STRBUF_INIT;
844         const char *head_arg;
845         int flag, head_invalid = 0, i;
846         int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
847         struct commit_list *common = NULL;
848         const char *best_strategy = NULL, *wt_strategy = NULL;
849         struct commit_list **remotes = &remoteheads;
850
851         if (file_exists(git_path("MERGE_HEAD")))
852                 die("You have not concluded your merge. (MERGE_HEAD exists)");
853         if (read_cache_unmerged())
854                 die("You are in the middle of a conflicted merge."
855                                 " (index unmerged)");
856         resolve_undo_clear();
857         /*
858          * Check if we are _not_ on a detached HEAD, i.e. if there is a
859          * current branch.
860          */
861         branch = resolve_ref("HEAD", head, 0, &flag);
862         if (branch && !prefixcmp(branch, "refs/heads/"))
863                 branch += 11;
864         if (is_null_sha1(head))
865                 head_invalid = 1;
866
867         git_config(git_merge_config, NULL);
868
869         /* for color.ui */
870         if (diff_use_color_default == -1)
871                 diff_use_color_default = git_use_color_default;
872
873         argc = parse_options(argc, argv, prefix, builtin_merge_options,
874                         builtin_merge_usage, 0);
875         if (verbosity < 0)
876                 show_diffstat = 0;
877
878         if (squash) {
879                 if (!allow_fast_forward)
880                         die("You cannot combine --squash with --no-ff.");
881                 option_commit = 0;
882         }
883
884         if (!allow_fast_forward && fast_forward_only)
885                 die("You cannot combine --no-ff with --ff-only.");
886
887         if (!argc)
888                 usage_with_options(builtin_merge_usage,
889                         builtin_merge_options);
890
891         /*
892          * This could be traditional "merge <msg> HEAD <commit>..."  and
893          * the way we can tell it is to see if the second token is HEAD,
894          * but some people might have misused the interface and used a
895          * committish that is the same as HEAD there instead.
896          * Traditional format never would have "-m" so it is an
897          * additional safety measure to check for it.
898          */
899
900         if (!have_message && is_old_style_invocation(argc, argv)) {
901                 strbuf_addstr(&merge_msg, argv[0]);
902                 head_arg = argv[1];
903                 argv += 2;
904                 argc -= 2;
905         } else if (head_invalid) {
906                 struct object *remote_head;
907                 /*
908                  * If the merged head is a valid one there is no reason
909                  * to forbid "git merge" into a branch yet to be born.
910                  * We do the same for "git pull".
911                  */
912                 if (argc != 1)
913                         die("Can merge only exactly one commit into "
914                                 "empty head");
915                 if (squash)
916                         die("Squash commit into empty head not supported yet");
917                 if (!allow_fast_forward)
918                         die("Non-fast-forward commit does not make sense into "
919                             "an empty head");
920                 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
921                 if (!remote_head)
922                         die("%s - not something we can merge", argv[0]);
923                 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
924                                 DIE_ON_ERR);
925                 reset_hard(remote_head->sha1, 0);
926                 return 0;
927         } else {
928                 struct strbuf msg = STRBUF_INIT;
929
930                 /* We are invoked directly as the first-class UI. */
931                 head_arg = "HEAD";
932
933                 /*
934                  * All the rest are the commits being merged;
935                  * prepare the standard merge summary message to
936                  * be appended to the given message.  If remote
937                  * is invalid we will die later in the common
938                  * codepath so we discard the error in this
939                  * loop.
940                  */
941                 if (!have_message) {
942                         for (i = 0; i < argc; i++)
943                                 merge_name(argv[i], &msg);
944                         fmt_merge_msg(option_log, &msg, &merge_msg);
945                         if (merge_msg.len)
946                                 strbuf_setlen(&merge_msg, merge_msg.len-1);
947                 }
948         }
949
950         if (head_invalid || !argc)
951                 usage_with_options(builtin_merge_usage,
952                         builtin_merge_options);
953
954         strbuf_addstr(&buf, "merge");
955         for (i = 0; i < argc; i++)
956                 strbuf_addf(&buf, " %s", argv[i]);
957         setenv("GIT_REFLOG_ACTION", buf.buf, 0);
958         strbuf_reset(&buf);
959
960         for (i = 0; i < argc; i++) {
961                 struct object *o;
962                 struct commit *commit;
963
964                 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
965                 if (!o)
966                         die("%s - not something we can merge", argv[i]);
967                 commit = lookup_commit(o->sha1);
968                 commit->util = (void *)argv[i];
969                 remotes = &commit_list_insert(commit, remotes)->next;
970
971                 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
972                 setenv(buf.buf, argv[i], 1);
973                 strbuf_reset(&buf);
974         }
975
976         if (!use_strategies) {
977                 if (!remoteheads->next)
978                         add_strategies(pull_twohead, DEFAULT_TWOHEAD);
979                 else
980                         add_strategies(pull_octopus, DEFAULT_OCTOPUS);
981         }
982
983         for (i = 0; i < use_strategies_nr; i++) {
984                 if (use_strategies[i]->attr & NO_FAST_FORWARD)
985                         allow_fast_forward = 0;
986                 if (use_strategies[i]->attr & NO_TRIVIAL)
987                         allow_trivial = 0;
988         }
989
990         if (!remoteheads->next)
991                 common = get_merge_bases(lookup_commit(head),
992                                 remoteheads->item, 1);
993         else {
994                 struct commit_list *list = remoteheads;
995                 commit_list_insert(lookup_commit(head), &list);
996                 common = get_octopus_merge_bases(list);
997                 free(list);
998         }
999
1000         update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1001                 DIE_ON_ERR);
1002
1003         if (!common)
1004                 ; /* No common ancestors found. We need a real merge. */
1005         else if (!remoteheads->next && !common->next &&
1006                         common->item == remoteheads->item) {
1007                 /*
1008                  * If head can reach all the merge then we are up to date.
1009                  * but first the most common case of merging one remote.
1010                  */
1011                 finish_up_to_date("Already up-to-date.");
1012                 return 0;
1013         } else if (allow_fast_forward && !remoteheads->next &&
1014                         !common->next &&
1015                         !hashcmp(common->item->object.sha1, head)) {
1016                 /* Again the most common case of merging one remote. */
1017                 struct strbuf msg = STRBUF_INIT;
1018                 struct object *o;
1019                 char hex[41];
1020
1021                 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1022
1023                 if (verbosity >= 0)
1024                         printf("Updating %s..%s\n",
1025                                 hex,
1026                                 find_unique_abbrev(remoteheads->item->object.sha1,
1027                                 DEFAULT_ABBREV));
1028                 strbuf_addstr(&msg, "Fast-forward");
1029                 if (have_message)
1030                         strbuf_addstr(&msg,
1031                                 " (no commit created; -m option ignored)");
1032                 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1033                         0, NULL, OBJ_COMMIT);
1034                 if (!o)
1035                         return 1;
1036
1037                 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1038                         return 1;
1039
1040                 finish(o->sha1, msg.buf);
1041                 drop_save();
1042                 return 0;
1043         } else if (!remoteheads->next && common->next)
1044                 ;
1045                 /*
1046                  * We are not doing octopus and not fast-forward.  Need
1047                  * a real merge.
1048                  */
1049         else if (!remoteheads->next && !common->next && option_commit) {
1050                 /*
1051                  * We are not doing octopus, not fast-forward, and have
1052                  * only one common.
1053                  */
1054                 refresh_cache(REFRESH_QUIET);
1055                 if (allow_trivial && !fast_forward_only) {
1056                         /* See if it is really trivial. */
1057                         git_committer_info(IDENT_ERROR_ON_NO_NAME);
1058                         printf("Trying really trivial in-index merge...\n");
1059                         if (!read_tree_trivial(common->item->object.sha1,
1060                                         head, remoteheads->item->object.sha1))
1061                                 return merge_trivial();
1062                         printf("Nope.\n");
1063                 }
1064         } else {
1065                 /*
1066                  * An octopus.  If we can reach all the remote we are up
1067                  * to date.
1068                  */
1069                 int up_to_date = 1;
1070                 struct commit_list *j;
1071
1072                 for (j = remoteheads; j; j = j->next) {
1073                         struct commit_list *common_one;
1074
1075                         /*
1076                          * Here we *have* to calculate the individual
1077                          * merge_bases again, otherwise "git merge HEAD^
1078                          * HEAD^^" would be missed.
1079                          */
1080                         common_one = get_merge_bases(lookup_commit(head),
1081                                 j->item, 1);
1082                         if (hashcmp(common_one->item->object.sha1,
1083                                 j->item->object.sha1)) {
1084                                 up_to_date = 0;
1085                                 break;
1086                         }
1087                 }
1088                 if (up_to_date) {
1089                         finish_up_to_date("Already up-to-date. Yeeah!");
1090                         return 0;
1091                 }
1092         }
1093
1094         if (fast_forward_only)
1095                 die("Not possible to fast-forward, aborting.");
1096
1097         /* We are going to make a new commit. */
1098         git_committer_info(IDENT_ERROR_ON_NO_NAME);
1099
1100         /*
1101          * At this point, we need a real merge.  No matter what strategy
1102          * we use, it would operate on the index, possibly affecting the
1103          * working tree, and when resolved cleanly, have the desired
1104          * tree in the index -- this means that the index must be in
1105          * sync with the head commit.  The strategies are responsible
1106          * to ensure this.
1107          */
1108         if (use_strategies_nr != 1) {
1109                 /*
1110                  * Stash away the local changes so that we can try more
1111                  * than one.
1112                  */
1113                 save_state();
1114         } else {
1115                 memcpy(stash, null_sha1, 20);
1116         }
1117
1118         for (i = 0; i < use_strategies_nr; i++) {
1119                 int ret;
1120                 if (i) {
1121                         printf("Rewinding the tree to pristine...\n");
1122                         restore_state();
1123                 }
1124                 if (use_strategies_nr != 1)
1125                         printf("Trying merge strategy %s...\n",
1126                                 use_strategies[i]->name);
1127                 /*
1128                  * Remember which strategy left the state in the working
1129                  * tree.
1130                  */
1131                 wt_strategy = use_strategies[i]->name;
1132
1133                 ret = try_merge_strategy(use_strategies[i]->name,
1134                         common, head_arg);
1135                 if (!option_commit && !ret) {
1136                         merge_was_ok = 1;
1137                         /*
1138                          * This is necessary here just to avoid writing
1139                          * the tree, but later we will *not* exit with
1140                          * status code 1 because merge_was_ok is set.
1141                          */
1142                         ret = 1;
1143                 }
1144
1145                 if (ret) {
1146                         /*
1147                          * The backend exits with 1 when conflicts are
1148                          * left to be resolved, with 2 when it does not
1149                          * handle the given merge at all.
1150                          */
1151                         if (ret == 1) {
1152                                 int cnt = evaluate_result();
1153
1154                                 if (best_cnt <= 0 || cnt <= best_cnt) {
1155                                         best_strategy = use_strategies[i]->name;
1156                                         best_cnt = cnt;
1157                                 }
1158                         }
1159                         if (merge_was_ok)
1160                                 break;
1161                         else
1162                                 continue;
1163                 }
1164
1165                 /* Automerge succeeded. */
1166                 write_tree_trivial(result_tree);
1167                 automerge_was_ok = 1;
1168                 break;
1169         }
1170
1171         /*
1172          * If we have a resulting tree, that means the strategy module
1173          * auto resolved the merge cleanly.
1174          */
1175         if (automerge_was_ok)
1176                 return finish_automerge(common, result_tree, wt_strategy);
1177
1178         /*
1179          * Pick the result from the best strategy and have the user fix
1180          * it up.
1181          */
1182         if (!best_strategy) {
1183                 restore_state();
1184                 if (use_strategies_nr > 1)
1185                         fprintf(stderr,
1186                                 "No merge strategy handled the merge.\n");
1187                 else
1188                         fprintf(stderr, "Merge with strategy %s failed.\n",
1189                                 use_strategies[0]->name);
1190                 return 2;
1191         } else if (best_strategy == wt_strategy)
1192                 ; /* We already have its result in the working tree. */
1193         else {
1194                 printf("Rewinding the tree to pristine...\n");
1195                 restore_state();
1196                 printf("Using the %s to prepare resolving by hand.\n",
1197                         best_strategy);
1198                 try_merge_strategy(best_strategy, common, head_arg);
1199         }
1200
1201         if (squash)
1202                 finish(NULL, NULL);
1203         else {
1204                 int fd;
1205                 struct commit_list *j;
1206
1207                 for (j = remoteheads; j; j = j->next)
1208                         strbuf_addf(&buf, "%s\n",
1209                                 sha1_to_hex(j->item->object.sha1));
1210                 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1211                 if (fd < 0)
1212                         die_errno("Could not open '%s' for writing",
1213                                   git_path("MERGE_HEAD"));
1214                 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1215                         die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1216                 close(fd);
1217                 strbuf_addch(&merge_msg, '\n');
1218                 fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1219                 if (fd < 0)
1220                         die_errno("Could not open '%s' for writing",
1221                                   git_path("MERGE_MSG"));
1222                 if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1223                         merge_msg.len)
1224                         die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1225                 close(fd);
1226                 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1227                 if (fd < 0)
1228                         die_errno("Could not open '%s' for writing",
1229                                   git_path("MERGE_MODE"));
1230                 strbuf_reset(&buf);
1231                 if (!allow_fast_forward)
1232                         strbuf_addf(&buf, "no-ff");
1233                 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1234                         die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1235                 close(fd);
1236         }
1237
1238         if (merge_was_ok) {
1239                 fprintf(stderr, "Automatic merge went well; "
1240                         "stopped before committing as requested\n");
1241                 return 0;
1242         } else
1243                 return suggest_conflicts();
1244 }