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