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