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