]> asedeno.scripts.mit.edu Git - git.git/blob - builtin/merge.c
t6200-fmt-merge-msg: Exercise '--log' to configure shortlog length
[git.git] / builtin / merge.c
1 /*
2  * Builtin "git merge"
3  *
4  * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
5  *
6  * Based on git-merge.sh by Junio C Hamano.
7  */
8
9 #include "cache.h"
10 #include "parse-options.h"
11 #include "builtin.h"
12 #include "run-command.h"
13 #include "diff.h"
14 #include "refs.h"
15 #include "commit.h"
16 #include "diffcore.h"
17 #include "revision.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
20 #include "dir.h"
21 #include "utf8.h"
22 #include "log-tree.h"
23 #include "color.h"
24 #include "rerere.h"
25 #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 verbosity;
58 static int allow_rerere_auto;
59
60 static struct strategy all_strategy[] = {
61         { "recursive",  DEFAULT_TWOHEAD | NO_TRIVIAL },
62         { "octopus",    DEFAULT_OCTOPUS },
63         { "resolve",    0 },
64         { "ours",       NO_FAST_FORWARD | NO_TRIVIAL },
65         { "subtree",    NO_FAST_FORWARD | NO_TRIVIAL },
66 };
67
68 static const char *pull_twohead, *pull_octopus;
69
70 static int option_parse_message(const struct option *opt,
71                                 const char *arg, int unset)
72 {
73         struct strbuf *buf = opt->value;
74
75         if (unset)
76                 strbuf_setlen(buf, 0);
77         else if (arg) {
78                 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
79                 have_message = 1;
80         } else
81                 return error("switch `m' requires a value");
82         return 0;
83 }
84
85 static struct strategy *get_strategy(const char *name)
86 {
87         int i;
88         struct strategy *ret;
89         static struct cmdnames main_cmds, other_cmds;
90         static int loaded;
91
92         if (!name)
93                 return NULL;
94
95         for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
96                 if (!strcmp(name, all_strategy[i].name))
97                         return &all_strategy[i];
98
99         if (!loaded) {
100                 struct cmdnames not_strategies;
101                 loaded = 1;
102
103                 memset(&not_strategies, 0, sizeof(struct cmdnames));
104                 load_command_list("git-merge-", &main_cmds, &other_cmds);
105                 for (i = 0; i < main_cmds.cnt; i++) {
106                         int j, found = 0;
107                         struct cmdname *ent = main_cmds.names[i];
108                         for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
109                                 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
110                                                 && !all_strategy[j].name[ent->len])
111                                         found = 1;
112                         if (!found)
113                                 add_cmdname(&not_strategies, ent->name, ent->len);
114                 }
115                 exclude_cmds(&main_cmds, &not_strategies);
116         }
117         if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
118                 fprintf(stderr, "Could not find merge strategy '%s'.\n", name);
119                 fprintf(stderr, "Available strategies are:");
120                 for (i = 0; i < main_cmds.cnt; i++)
121                         fprintf(stderr, " %s", main_cmds.names[i]->name);
122                 fprintf(stderr, ".\n");
123                 if (other_cmds.cnt) {
124                         fprintf(stderr, "Available custom strategies are:");
125                         for (i = 0; i < other_cmds.cnt; i++)
126                                 fprintf(stderr, " %s", other_cmds.names[i]->name);
127                         fprintf(stderr, ".\n");
128                 }
129                 exit(1);
130         }
131
132         ret = xcalloc(1, sizeof(struct strategy));
133         ret->name = xstrdup(name);
134         return ret;
135 }
136
137 static void append_strategy(struct strategy *s)
138 {
139         ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
140         use_strategies[use_strategies_nr++] = s;
141 }
142
143 static int option_parse_strategy(const struct option *opt,
144                                  const char *name, int unset)
145 {
146         if (unset)
147                 return 0;
148
149         append_strategy(get_strategy(name));
150         return 0;
151 }
152
153 static int option_parse_x(const struct option *opt,
154                           const char *arg, int unset)
155 {
156         if (unset)
157                 return 0;
158
159         ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
160         xopts[xopts_nr++] = xstrdup(arg);
161         return 0;
162 }
163
164 static int option_parse_n(const struct option *opt,
165                           const char *arg, int unset)
166 {
167         show_diffstat = unset;
168         return 0;
169 }
170
171 static struct option builtin_merge_options[] = {
172         { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
173                 "do not show a diffstat at the end of the merge",
174                 PARSE_OPT_NOARG, option_parse_n },
175         OPT_BOOLEAN(0, "stat", &show_diffstat,
176                 "show a diffstat at the end of the merge"),
177         OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
178         { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
179           "add (at most <n>) entries from shortlog to merge commit message",
180           PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
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, 1, 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                 int is_bool;
507                 shortlog_len = git_config_bool_or_int(k, v, &is_bool);
508                 if (!is_bool && shortlog_len < 0)
509                         return error("%s: negative length %s", k, v);
510                 if (is_bool && shortlog_len)
511                         shortlog_len = DEFAULT_MERGE_LOG_LEN;
512                 return 0;
513         }
514         return git_diff_ui_config(k, v, cb);
515 }
516
517 static int read_tree_trivial(unsigned char *common, unsigned char *head,
518                              unsigned char *one)
519 {
520         int i, nr_trees = 0;
521         struct tree *trees[MAX_UNPACK_TREES];
522         struct tree_desc t[MAX_UNPACK_TREES];
523         struct unpack_trees_options opts;
524
525         memset(&opts, 0, sizeof(opts));
526         opts.head_idx = 2;
527         opts.src_index = &the_index;
528         opts.dst_index = &the_index;
529         opts.update = 1;
530         opts.verbose_update = 1;
531         opts.trivial_merges_only = 1;
532         opts.merge = 1;
533         trees[nr_trees] = parse_tree_indirect(common);
534         if (!trees[nr_trees++])
535                 return -1;
536         trees[nr_trees] = parse_tree_indirect(head);
537         if (!trees[nr_trees++])
538                 return -1;
539         trees[nr_trees] = parse_tree_indirect(one);
540         if (!trees[nr_trees++])
541                 return -1;
542         opts.fn = threeway_merge;
543         cache_tree_free(&active_cache_tree);
544         for (i = 0; i < nr_trees; i++) {
545                 parse_tree(trees[i]);
546                 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
547         }
548         if (unpack_trees(nr_trees, t, &opts))
549                 return -1;
550         return 0;
551 }
552
553 static void write_tree_trivial(unsigned char *sha1)
554 {
555         if (write_cache_as_tree(sha1, 0, NULL))
556                 die("git write-tree failed to write a tree");
557 }
558
559 int try_merge_command(const char *strategy, struct commit_list *common,
560                       const char *head_arg, struct commit_list *remotes)
561 {
562         const char **args;
563         int i = 0, x = 0, ret;
564         struct commit_list *j;
565         struct strbuf buf = STRBUF_INIT;
566
567         args = xmalloc((4 + xopts_nr + commit_list_count(common) +
568                         commit_list_count(remotes)) * sizeof(char *));
569         strbuf_addf(&buf, "merge-%s", strategy);
570         args[i++] = buf.buf;
571         for (x = 0; x < xopts_nr; x++) {
572                 char *s = xmalloc(strlen(xopts[x])+2+1);
573                 strcpy(s, "--");
574                 strcpy(s+2, xopts[x]);
575                 args[i++] = s;
576         }
577         for (j = common; j; j = j->next)
578                 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
579         args[i++] = "--";
580         args[i++] = head_arg;
581         for (j = remotes; j; j = j->next)
582                 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
583         args[i] = NULL;
584         ret = run_command_v_opt(args, RUN_GIT_CMD);
585         strbuf_release(&buf);
586         i = 1;
587         for (x = 0; x < xopts_nr; x++)
588                 free((void *)args[i++]);
589         for (j = common; j; j = j->next)
590                 free((void *)args[i++]);
591         i += 2;
592         for (j = remotes; j; j = j->next)
593                 free((void *)args[i++]);
594         free(args);
595         discard_cache();
596         if (read_cache() < 0)
597                 die("failed to read the cache");
598         resolve_undo_clear();
599
600         return ret;
601 }
602
603 static int try_merge_strategy(const char *strategy, struct commit_list *common,
604                               const char *head_arg)
605 {
606         int index_fd;
607         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
608
609         index_fd = hold_locked_index(lock, 1);
610         refresh_cache(REFRESH_QUIET);
611         if (active_cache_changed &&
612                         (write_cache(index_fd, active_cache, active_nr) ||
613                          commit_locked_index(lock)))
614                 return error("Unable to write index.");
615         rollback_lock_file(lock);
616
617         if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
618                 int clean, x;
619                 struct commit *result;
620                 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
621                 int index_fd;
622                 struct commit_list *reversed = NULL;
623                 struct merge_options o;
624                 struct commit_list *j;
625
626                 if (remoteheads->next) {
627                         error("Not handling anything other than two heads merge.");
628                         return 2;
629                 }
630
631                 init_merge_options(&o);
632                 if (!strcmp(strategy, "subtree"))
633                         o.subtree_shift = "";
634
635                 for (x = 0; x < xopts_nr; x++) {
636                         if (!strcmp(xopts[x], "ours"))
637                                 o.recursive_variant = MERGE_RECURSIVE_OURS;
638                         else if (!strcmp(xopts[x], "theirs"))
639                                 o.recursive_variant = MERGE_RECURSIVE_THEIRS;
640                         else if (!strcmp(xopts[x], "subtree"))
641                                 o.subtree_shift = "";
642                         else if (!prefixcmp(xopts[x], "subtree="))
643                                 o.subtree_shift = xopts[x]+8;
644                         else
645                                 die("Unknown option for merge-recursive: -X%s", xopts[x]);
646                 }
647
648                 o.branch1 = head_arg;
649                 o.branch2 = remoteheads->item->util;
650
651                 for (j = common; j; j = j->next)
652                         commit_list_insert(j->item, &reversed);
653
654                 index_fd = hold_locked_index(lock, 1);
655                 clean = merge_recursive(&o, lookup_commit(head),
656                                 remoteheads->item, reversed, &result);
657                 if (active_cache_changed &&
658                                 (write_cache(index_fd, active_cache, active_nr) ||
659                                  commit_locked_index(lock)))
660                         die ("unable to write %s", get_index_file());
661                 rollback_lock_file(lock);
662                 return clean ? 0 : 1;
663         } else {
664                 return try_merge_command(strategy, common, head_arg, remoteheads);
665         }
666 }
667
668 static void count_diff_files(struct diff_queue_struct *q,
669                              struct diff_options *opt, void *data)
670 {
671         int *count = data;
672
673         (*count) += q->nr;
674 }
675
676 static int count_unmerged_entries(void)
677 {
678         int i, ret = 0;
679
680         for (i = 0; i < active_nr; i++)
681                 if (ce_stage(active_cache[i]))
682                         ret++;
683
684         return ret;
685 }
686
687 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
688 {
689         struct tree *trees[MAX_UNPACK_TREES];
690         struct unpack_trees_options opts;
691         struct tree_desc t[MAX_UNPACK_TREES];
692         int i, fd, nr_trees = 0;
693         struct dir_struct dir;
694         struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
695
696         refresh_cache(REFRESH_QUIET);
697
698         fd = hold_locked_index(lock_file, 1);
699
700         memset(&trees, 0, sizeof(trees));
701         memset(&opts, 0, sizeof(opts));
702         memset(&t, 0, sizeof(t));
703         memset(&dir, 0, sizeof(dir));
704         dir.flags |= DIR_SHOW_IGNORED;
705         dir.exclude_per_dir = ".gitignore";
706         opts.dir = &dir;
707
708         opts.head_idx = 1;
709         opts.src_index = &the_index;
710         opts.dst_index = &the_index;
711         opts.update = 1;
712         opts.verbose_update = 1;
713         opts.merge = 1;
714         opts.fn = twoway_merge;
715         opts.msgs = get_porcelain_error_msgs();
716
717         trees[nr_trees] = parse_tree_indirect(head);
718         if (!trees[nr_trees++])
719                 return -1;
720         trees[nr_trees] = parse_tree_indirect(remote);
721         if (!trees[nr_trees++])
722                 return -1;
723         for (i = 0; i < nr_trees; i++) {
724                 parse_tree(trees[i]);
725                 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
726         }
727         if (unpack_trees(nr_trees, t, &opts))
728                 return -1;
729         if (write_cache(fd, active_cache, active_nr) ||
730                 commit_locked_index(lock_file))
731                 die("unable to write new index file");
732         return 0;
733 }
734
735 static void split_merge_strategies(const char *string, struct strategy **list,
736                                    int *nr, int *alloc)
737 {
738         char *p, *q, *buf;
739
740         if (!string)
741                 return;
742
743         buf = xstrdup(string);
744         q = buf;
745         for (;;) {
746                 p = strchr(q, ' ');
747                 if (!p) {
748                         ALLOC_GROW(*list, *nr + 1, *alloc);
749                         (*list)[(*nr)++].name = xstrdup(q);
750                         free(buf);
751                         return;
752                 } else {
753                         *p = '\0';
754                         ALLOC_GROW(*list, *nr + 1, *alloc);
755                         (*list)[(*nr)++].name = xstrdup(q);
756                         q = ++p;
757                 }
758         }
759 }
760
761 static void add_strategies(const char *string, unsigned attr)
762 {
763         struct strategy *list = NULL;
764         int list_alloc = 0, list_nr = 0, i;
765
766         memset(&list, 0, sizeof(list));
767         split_merge_strategies(string, &list, &list_nr, &list_alloc);
768         if (list) {
769                 for (i = 0; i < list_nr; i++)
770                         append_strategy(get_strategy(list[i].name));
771                 return;
772         }
773         for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
774                 if (all_strategy[i].attr & attr)
775                         append_strategy(&all_strategy[i]);
776
777 }
778
779 static int merge_trivial(void)
780 {
781         unsigned char result_tree[20], result_commit[20];
782         struct commit_list *parent = xmalloc(sizeof(*parent));
783
784         write_tree_trivial(result_tree);
785         printf("Wonderful.\n");
786         parent->item = lookup_commit(head);
787         parent->next = xmalloc(sizeof(*parent->next));
788         parent->next->item = remoteheads->item;
789         parent->next->next = NULL;
790         commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
791         finish(result_commit, "In-index merge");
792         drop_save();
793         return 0;
794 }
795
796 static int finish_automerge(struct commit_list *common,
797                             unsigned char *result_tree,
798                             const char *wt_strategy)
799 {
800         struct commit_list *parents = NULL, *j;
801         struct strbuf buf = STRBUF_INIT;
802         unsigned char result_commit[20];
803
804         free_commit_list(common);
805         if (allow_fast_forward) {
806                 parents = remoteheads;
807                 commit_list_insert(lookup_commit(head), &parents);
808                 parents = reduce_heads(parents);
809         } else {
810                 struct commit_list **pptr = &parents;
811
812                 pptr = &commit_list_insert(lookup_commit(head),
813                                 pptr)->next;
814                 for (j = remoteheads; j; j = j->next)
815                         pptr = &commit_list_insert(j->item, pptr)->next;
816         }
817         free_commit_list(remoteheads);
818         strbuf_addch(&merge_msg, '\n');
819         commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
820         strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
821         finish(result_commit, buf.buf);
822         strbuf_release(&buf);
823         drop_save();
824         return 0;
825 }
826
827 static int suggest_conflicts(void)
828 {
829         FILE *fp;
830         int pos;
831
832         fp = fopen(git_path("MERGE_MSG"), "a");
833         if (!fp)
834                 die_errno("Could not open '%s' for writing",
835                           git_path("MERGE_MSG"));
836         fprintf(fp, "\nConflicts:\n");
837         for (pos = 0; pos < active_nr; pos++) {
838                 struct cache_entry *ce = active_cache[pos];
839
840                 if (ce_stage(ce)) {
841                         fprintf(fp, "\t%s\n", ce->name);
842                         while (pos + 1 < active_nr &&
843                                         !strcmp(ce->name,
844                                                 active_cache[pos + 1]->name))
845                                 pos++;
846                 }
847         }
848         fclose(fp);
849         rerere(allow_rerere_auto);
850         printf("Automatic merge failed; "
851                         "fix conflicts and then commit the result.\n");
852         return 1;
853 }
854
855 static struct commit *is_old_style_invocation(int argc, const char **argv)
856 {
857         struct commit *second_token = NULL;
858         if (argc > 2) {
859                 unsigned char second_sha1[20];
860
861                 if (get_sha1(argv[1], second_sha1))
862                         return NULL;
863                 second_token = lookup_commit_reference_gently(second_sha1, 0);
864                 if (!second_token)
865                         die("'%s' is not a commit", argv[1]);
866                 if (hashcmp(second_token->object.sha1, head))
867                         return NULL;
868         }
869         return second_token;
870 }
871
872 static int evaluate_result(void)
873 {
874         int cnt = 0;
875         struct rev_info rev;
876
877         /* Check how many files differ. */
878         init_revisions(&rev, "");
879         setup_revisions(0, NULL, &rev, NULL);
880         rev.diffopt.output_format |=
881                 DIFF_FORMAT_CALLBACK;
882         rev.diffopt.format_callback = count_diff_files;
883         rev.diffopt.format_callback_data = &cnt;
884         run_diff_files(&rev, 0);
885
886         /*
887          * Check how many unmerged entries are
888          * there.
889          */
890         cnt += count_unmerged_entries();
891
892         return cnt;
893 }
894
895 int cmd_merge(int argc, const char **argv, const char *prefix)
896 {
897         unsigned char result_tree[20];
898         struct strbuf buf = STRBUF_INIT;
899         const char *head_arg;
900         int flag, head_invalid = 0, i;
901         int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
902         struct commit_list *common = NULL;
903         const char *best_strategy = NULL, *wt_strategy = NULL;
904         struct commit_list **remotes = &remoteheads;
905
906         if (read_cache_unmerged()) {
907                 die_resolve_conflict("merge");
908         }
909         if (file_exists(git_path("MERGE_HEAD"))) {
910                 /*
911                  * There is no unmerged entry, don't advise 'git
912                  * add/rm <file>', just 'git commit'.
913                  */
914                 if (advice_resolve_conflict)
915                         die("You have not concluded your merge (MERGE_HEAD exists).\n"
916                             "Please, commit your changes before you can merge.");
917                 else
918                         die("You have not concluded your merge (MERGE_HEAD exists).");
919         }
920
921         resolve_undo_clear();
922         /*
923          * Check if we are _not_ on a detached HEAD, i.e. if there is a
924          * current branch.
925          */
926         branch = resolve_ref("HEAD", head, 0, &flag);
927         if (branch && !prefixcmp(branch, "refs/heads/"))
928                 branch += 11;
929         if (is_null_sha1(head))
930                 head_invalid = 1;
931
932         git_config(git_merge_config, NULL);
933
934         /* for color.ui */
935         if (diff_use_color_default == -1)
936                 diff_use_color_default = git_use_color_default;
937
938         argc = parse_options(argc, argv, prefix, builtin_merge_options,
939                         builtin_merge_usage, 0);
940         if (verbosity < 0)
941                 show_diffstat = 0;
942
943         if (squash) {
944                 if (!allow_fast_forward)
945                         die("You cannot combine --squash with --no-ff.");
946                 option_commit = 0;
947         }
948
949         if (!allow_fast_forward && fast_forward_only)
950                 die("You cannot combine --no-ff with --ff-only.");
951
952         if (!argc)
953                 usage_with_options(builtin_merge_usage,
954                         builtin_merge_options);
955
956         /*
957          * This could be traditional "merge <msg> HEAD <commit>..."  and
958          * the way we can tell it is to see if the second token is HEAD,
959          * but some people might have misused the interface and used a
960          * committish that is the same as HEAD there instead.
961          * Traditional format never would have "-m" so it is an
962          * additional safety measure to check for it.
963          */
964
965         if (!have_message && is_old_style_invocation(argc, argv)) {
966                 strbuf_addstr(&merge_msg, argv[0]);
967                 head_arg = argv[1];
968                 argv += 2;
969                 argc -= 2;
970         } else if (head_invalid) {
971                 struct object *remote_head;
972                 /*
973                  * If the merged head is a valid one there is no reason
974                  * to forbid "git merge" into a branch yet to be born.
975                  * We do the same for "git pull".
976                  */
977                 if (argc != 1)
978                         die("Can merge only exactly one commit into "
979                                 "empty head");
980                 if (squash)
981                         die("Squash commit into empty head not supported yet");
982                 if (!allow_fast_forward)
983                         die("Non-fast-forward commit does not make sense into "
984                             "an empty head");
985                 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
986                 if (!remote_head)
987                         die("%s - not something we can merge", argv[0]);
988                 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
989                                 DIE_ON_ERR);
990                 reset_hard(remote_head->sha1, 0);
991                 return 0;
992         } else {
993                 struct strbuf merge_names = STRBUF_INIT;
994
995                 /* We are invoked directly as the first-class UI. */
996                 head_arg = "HEAD";
997
998                 /*
999                  * All the rest are the commits being merged;
1000                  * prepare the standard merge summary message to
1001                  * be appended to the given message.  If remote
1002                  * is invalid we will die later in the common
1003                  * codepath so we discard the error in this
1004                  * loop.
1005                  */
1006                 for (i = 0; i < argc; i++)
1007                         merge_name(argv[i], &merge_names);
1008
1009                 if (!have_message || shortlog_len) {
1010                         fmt_merge_msg(&merge_names, &merge_msg, !have_message,
1011                                       shortlog_len);
1012                         if (merge_msg.len)
1013                                 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1014                 }
1015         }
1016
1017         if (head_invalid || !argc)
1018                 usage_with_options(builtin_merge_usage,
1019                         builtin_merge_options);
1020
1021         strbuf_addstr(&buf, "merge");
1022         for (i = 0; i < argc; i++)
1023                 strbuf_addf(&buf, " %s", argv[i]);
1024         setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1025         strbuf_reset(&buf);
1026
1027         for (i = 0; i < argc; i++) {
1028                 struct object *o;
1029                 struct commit *commit;
1030
1031                 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
1032                 if (!o)
1033                         die("%s - not something we can merge", argv[i]);
1034                 commit = lookup_commit(o->sha1);
1035                 commit->util = (void *)argv[i];
1036                 remotes = &commit_list_insert(commit, remotes)->next;
1037
1038                 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1039                 setenv(buf.buf, argv[i], 1);
1040                 strbuf_reset(&buf);
1041         }
1042
1043         if (!use_strategies) {
1044                 if (!remoteheads->next)
1045                         add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1046                 else
1047                         add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1048         }
1049
1050         for (i = 0; i < use_strategies_nr; i++) {
1051                 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1052                         allow_fast_forward = 0;
1053                 if (use_strategies[i]->attr & NO_TRIVIAL)
1054                         allow_trivial = 0;
1055         }
1056
1057         if (!remoteheads->next)
1058                 common = get_merge_bases(lookup_commit(head),
1059                                 remoteheads->item, 1);
1060         else {
1061                 struct commit_list *list = remoteheads;
1062                 commit_list_insert(lookup_commit(head), &list);
1063                 common = get_octopus_merge_bases(list);
1064                 free(list);
1065         }
1066
1067         update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1068                 DIE_ON_ERR);
1069
1070         if (!common)
1071                 ; /* No common ancestors found. We need a real merge. */
1072         else if (!remoteheads->next && !common->next &&
1073                         common->item == remoteheads->item) {
1074                 /*
1075                  * If head can reach all the merge then we are up to date.
1076                  * but first the most common case of merging one remote.
1077                  */
1078                 finish_up_to_date("Already up-to-date.");
1079                 return 0;
1080         } else if (allow_fast_forward && !remoteheads->next &&
1081                         !common->next &&
1082                         !hashcmp(common->item->object.sha1, head)) {
1083                 /* Again the most common case of merging one remote. */
1084                 struct strbuf msg = STRBUF_INIT;
1085                 struct object *o;
1086                 char hex[41];
1087
1088                 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1089
1090                 if (verbosity >= 0)
1091                         printf("Updating %s..%s\n",
1092                                 hex,
1093                                 find_unique_abbrev(remoteheads->item->object.sha1,
1094                                 DEFAULT_ABBREV));
1095                 strbuf_addstr(&msg, "Fast-forward");
1096                 if (have_message)
1097                         strbuf_addstr(&msg,
1098                                 " (no commit created; -m option ignored)");
1099                 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1100                         0, NULL, OBJ_COMMIT);
1101                 if (!o)
1102                         return 1;
1103
1104                 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1105                         return 1;
1106
1107                 finish(o->sha1, msg.buf);
1108                 drop_save();
1109                 return 0;
1110         } else if (!remoteheads->next && common->next)
1111                 ;
1112                 /*
1113                  * We are not doing octopus and not fast-forward.  Need
1114                  * a real merge.
1115                  */
1116         else if (!remoteheads->next && !common->next && option_commit) {
1117                 /*
1118                  * We are not doing octopus, not fast-forward, and have
1119                  * only one common.
1120                  */
1121                 refresh_cache(REFRESH_QUIET);
1122                 if (allow_trivial && !fast_forward_only) {
1123                         /* See if it is really trivial. */
1124                         git_committer_info(IDENT_ERROR_ON_NO_NAME);
1125                         printf("Trying really trivial in-index merge...\n");
1126                         if (!read_tree_trivial(common->item->object.sha1,
1127                                         head, remoteheads->item->object.sha1))
1128                                 return merge_trivial();
1129                         printf("Nope.\n");
1130                 }
1131         } else {
1132                 /*
1133                  * An octopus.  If we can reach all the remote we are up
1134                  * to date.
1135                  */
1136                 int up_to_date = 1;
1137                 struct commit_list *j;
1138
1139                 for (j = remoteheads; j; j = j->next) {
1140                         struct commit_list *common_one;
1141
1142                         /*
1143                          * Here we *have* to calculate the individual
1144                          * merge_bases again, otherwise "git merge HEAD^
1145                          * HEAD^^" would be missed.
1146                          */
1147                         common_one = get_merge_bases(lookup_commit(head),
1148                                 j->item, 1);
1149                         if (hashcmp(common_one->item->object.sha1,
1150                                 j->item->object.sha1)) {
1151                                 up_to_date = 0;
1152                                 break;
1153                         }
1154                 }
1155                 if (up_to_date) {
1156                         finish_up_to_date("Already up-to-date. Yeeah!");
1157                         return 0;
1158                 }
1159         }
1160
1161         if (fast_forward_only)
1162                 die("Not possible to fast-forward, aborting.");
1163
1164         /* We are going to make a new commit. */
1165         git_committer_info(IDENT_ERROR_ON_NO_NAME);
1166
1167         /*
1168          * At this point, we need a real merge.  No matter what strategy
1169          * we use, it would operate on the index, possibly affecting the
1170          * working tree, and when resolved cleanly, have the desired
1171          * tree in the index -- this means that the index must be in
1172          * sync with the head commit.  The strategies are responsible
1173          * to ensure this.
1174          */
1175         if (use_strategies_nr != 1) {
1176                 /*
1177                  * Stash away the local changes so that we can try more
1178                  * than one.
1179                  */
1180                 save_state();
1181         } else {
1182                 memcpy(stash, null_sha1, 20);
1183         }
1184
1185         for (i = 0; i < use_strategies_nr; i++) {
1186                 int ret;
1187                 if (i) {
1188                         printf("Rewinding the tree to pristine...\n");
1189                         restore_state();
1190                 }
1191                 if (use_strategies_nr != 1)
1192                         printf("Trying merge strategy %s...\n",
1193                                 use_strategies[i]->name);
1194                 /*
1195                  * Remember which strategy left the state in the working
1196                  * tree.
1197                  */
1198                 wt_strategy = use_strategies[i]->name;
1199
1200                 ret = try_merge_strategy(use_strategies[i]->name,
1201                         common, head_arg);
1202                 if (!option_commit && !ret) {
1203                         merge_was_ok = 1;
1204                         /*
1205                          * This is necessary here just to avoid writing
1206                          * the tree, but later we will *not* exit with
1207                          * status code 1 because merge_was_ok is set.
1208                          */
1209                         ret = 1;
1210                 }
1211
1212                 if (ret) {
1213                         /*
1214                          * The backend exits with 1 when conflicts are
1215                          * left to be resolved, with 2 when it does not
1216                          * handle the given merge at all.
1217                          */
1218                         if (ret == 1) {
1219                                 int cnt = evaluate_result();
1220
1221                                 if (best_cnt <= 0 || cnt <= best_cnt) {
1222                                         best_strategy = use_strategies[i]->name;
1223                                         best_cnt = cnt;
1224                                 }
1225                         }
1226                         if (merge_was_ok)
1227                                 break;
1228                         else
1229                                 continue;
1230                 }
1231
1232                 /* Automerge succeeded. */
1233                 write_tree_trivial(result_tree);
1234                 automerge_was_ok = 1;
1235                 break;
1236         }
1237
1238         /*
1239          * If we have a resulting tree, that means the strategy module
1240          * auto resolved the merge cleanly.
1241          */
1242         if (automerge_was_ok)
1243                 return finish_automerge(common, result_tree, wt_strategy);
1244
1245         /*
1246          * Pick the result from the best strategy and have the user fix
1247          * it up.
1248          */
1249         if (!best_strategy) {
1250                 restore_state();
1251                 if (use_strategies_nr > 1)
1252                         fprintf(stderr,
1253                                 "No merge strategy handled the merge.\n");
1254                 else
1255                         fprintf(stderr, "Merge with strategy %s failed.\n",
1256                                 use_strategies[0]->name);
1257                 return 2;
1258         } else if (best_strategy == wt_strategy)
1259                 ; /* We already have its result in the working tree. */
1260         else {
1261                 printf("Rewinding the tree to pristine...\n");
1262                 restore_state();
1263                 printf("Using the %s to prepare resolving by hand.\n",
1264                         best_strategy);
1265                 try_merge_strategy(best_strategy, common, head_arg);
1266         }
1267
1268         if (squash)
1269                 finish(NULL, NULL);
1270         else {
1271                 int fd;
1272                 struct commit_list *j;
1273
1274                 for (j = remoteheads; j; j = j->next)
1275                         strbuf_addf(&buf, "%s\n",
1276                                 sha1_to_hex(j->item->object.sha1));
1277                 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1278                 if (fd < 0)
1279                         die_errno("Could not open '%s' for writing",
1280                                   git_path("MERGE_HEAD"));
1281                 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1282                         die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1283                 close(fd);
1284                 strbuf_addch(&merge_msg, '\n');
1285                 fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1286                 if (fd < 0)
1287                         die_errno("Could not open '%s' for writing",
1288                                   git_path("MERGE_MSG"));
1289                 if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1290                         merge_msg.len)
1291                         die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1292                 close(fd);
1293                 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1294                 if (fd < 0)
1295                         die_errno("Could not open '%s' for writing",
1296                                   git_path("MERGE_MODE"));
1297                 strbuf_reset(&buf);
1298                 if (!allow_fast_forward)
1299                         strbuf_addf(&buf, "no-ff");
1300                 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1301                         die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1302                 close(fd);
1303         }
1304
1305         if (merge_was_ok) {
1306                 fprintf(stderr, "Automatic merge went well; "
1307                         "stopped before committing as requested\n");
1308                 return 0;
1309         } else
1310                 return suggest_conflicts();
1311 }