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