Code

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