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