Code

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