Code

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