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