Code

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