Merge branch 'mm/phrase-remote-tracking' into next
[git/mingw/4msysgit.git] / builtin / merge.c
blobc24a7be020d10540581b41c21a2ecf83df5563d9
1 /*
2 * Builtin "git merge"
4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
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;
39 static const char * const builtin_merge_usage[] = {
40 "git merge [options] <remote>...",
41 "git merge [options] <msg> HEAD <remote>",
42 NULL
45 static int show_diffstat = 1, shortlog_len, squash;
46 static int option_commit = 1, allow_fast_forward = 1;
47 static int fast_forward_only;
48 static int allow_trivial = 1, have_message;
49 static struct strbuf merge_msg;
50 static struct commit_list *remoteheads;
51 static unsigned char head[20], stash[20];
52 static struct strategy **use_strategies;
53 static size_t use_strategies_nr, use_strategies_alloc;
54 static const char **xopts;
55 static size_t xopts_nr, xopts_alloc;
56 static const char *branch;
57 static int option_renormalize;
58 static int verbosity;
59 static int allow_rerere_auto;
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 },
69 static const char *pull_twohead, *pull_octopus;
71 static int option_parse_message(const struct option *opt,
72 const char *arg, int unset)
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;
86 static struct strategy *get_strategy(const char *name)
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);
116 exclude_cmds(&main_cmds, &not_strategies);
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");
130 exit(1);
133 ret = xcalloc(1, sizeof(struct strategy));
134 ret->name = xstrdup(name);
135 ret->attr = NO_TRIVIAL;
136 return ret;
139 static void append_strategy(struct strategy *s)
141 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
142 use_strategies[use_strategies_nr++] = s;
145 static int option_parse_strategy(const struct option *opt,
146 const char *name, int unset)
148 if (unset)
149 return 0;
151 append_strategy(get_strategy(name));
152 return 0;
155 static int option_parse_x(const struct option *opt,
156 const char *arg, int unset)
158 if (unset)
159 return 0;
161 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
162 xopts[xopts_nr++] = xstrdup(arg);
163 return 0;
166 static int option_parse_n(const struct option *opt,
167 const char *arg, int unset)
169 show_diffstat = unset;
170 return 0;
173 static struct option builtin_merge_options[] = {
174 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
175 "do not show a diffstat at the end of the merge",
176 PARSE_OPT_NOARG, option_parse_n },
177 OPT_BOOLEAN(0, "stat", &show_diffstat,
178 "show a diffstat at the end of the merge"),
179 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
180 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
181 "add (at most <n>) entries from shortlog to merge commit message",
182 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
183 OPT_BOOLEAN(0, "squash", &squash,
184 "create a single commit instead of doing a merge"),
185 OPT_BOOLEAN(0, "commit", &option_commit,
186 "perform a commit if the merge succeeds (default)"),
187 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
188 "allow fast-forward (default)"),
189 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
190 "abort if fast-forward is not possible"),
191 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
192 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
193 "merge strategy to use", option_parse_strategy),
194 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
195 "option for selected merge strategy", option_parse_x),
196 OPT_CALLBACK('m', "message", &merge_msg, "message",
197 "message to be used for the merge commit (if any)",
198 option_parse_message),
199 OPT__VERBOSITY(&verbosity),
200 OPT_END()
203 /* Cleans up metadata that is uninteresting after a succeeded merge. */
204 static void drop_save(void)
206 unlink(git_path("MERGE_HEAD"));
207 unlink(git_path("MERGE_MSG"));
208 unlink(git_path("MERGE_MODE"));
211 static void save_state(void)
213 int len;
214 struct child_process cp;
215 struct strbuf buffer = STRBUF_INIT;
216 const char *argv[] = {"stash", "create", NULL};
218 memset(&cp, 0, sizeof(cp));
219 cp.argv = argv;
220 cp.out = -1;
221 cp.git_cmd = 1;
223 if (start_command(&cp))
224 die("could not run stash.");
225 len = strbuf_read(&buffer, cp.out, 1024);
226 close(cp.out);
228 if (finish_command(&cp) || len < 0)
229 die("stash failed");
230 else if (!len)
231 return;
232 strbuf_setlen(&buffer, buffer.len-1);
233 if (get_sha1(buffer.buf, stash))
234 die("not a valid object: %s", buffer.buf);
237 static void read_empty(unsigned const char *sha1, int verbose)
239 int i = 0;
240 const char *args[7];
242 args[i++] = "read-tree";
243 if (verbose)
244 args[i++] = "-v";
245 args[i++] = "-m";
246 args[i++] = "-u";
247 args[i++] = EMPTY_TREE_SHA1_HEX;
248 args[i++] = sha1_to_hex(sha1);
249 args[i] = NULL;
251 if (run_command_v_opt(args, RUN_GIT_CMD))
252 die("read-tree failed");
255 static void reset_hard(unsigned const char *sha1, int verbose)
257 int i = 0;
258 const char *args[6];
260 args[i++] = "read-tree";
261 if (verbose)
262 args[i++] = "-v";
263 args[i++] = "--reset";
264 args[i++] = "-u";
265 args[i++] = sha1_to_hex(sha1);
266 args[i] = NULL;
268 if (run_command_v_opt(args, RUN_GIT_CMD))
269 die("read-tree failed");
272 static void restore_state(void)
274 struct strbuf sb = STRBUF_INIT;
275 const char *args[] = { "stash", "apply", NULL, NULL };
277 if (is_null_sha1(stash))
278 return;
280 reset_hard(head, 1);
282 args[2] = sha1_to_hex(stash);
285 * It is OK to ignore error here, for example when there was
286 * nothing to restore.
288 run_command_v_opt(args, RUN_GIT_CMD);
290 strbuf_release(&sb);
291 refresh_cache(REFRESH_QUIET);
294 /* This is called when no merge was necessary. */
295 static void finish_up_to_date(const char *msg)
297 if (verbosity >= 0)
298 printf("%s%s\n", squash ? " (nothing to squash)" : "", msg);
299 drop_save();
302 static void squash_message(void)
304 struct rev_info rev;
305 struct commit *commit;
306 struct strbuf out = STRBUF_INIT;
307 struct commit_list *j;
308 int fd;
309 struct pretty_print_context ctx = {0};
311 printf("Squash commit -- not updating HEAD\n");
312 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
313 if (fd < 0)
314 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
316 init_revisions(&rev, NULL);
317 rev.ignore_merges = 1;
318 rev.commit_format = CMIT_FMT_MEDIUM;
320 commit = lookup_commit(head);
321 commit->object.flags |= UNINTERESTING;
322 add_pending_object(&rev, &commit->object, NULL);
324 for (j = remoteheads; j; j = j->next)
325 add_pending_object(&rev, &j->item->object, NULL);
327 setup_revisions(0, NULL, &rev, NULL);
328 if (prepare_revision_walk(&rev))
329 die("revision walk setup failed");
331 ctx.abbrev = rev.abbrev;
332 ctx.date_mode = rev.date_mode;
334 strbuf_addstr(&out, "Squashed commit of the following:\n");
335 while ((commit = get_revision(&rev)) != NULL) {
336 strbuf_addch(&out, '\n');
337 strbuf_addf(&out, "commit %s\n",
338 sha1_to_hex(commit->object.sha1));
339 pretty_print_commit(rev.commit_format, commit, &out, &ctx);
341 if (write(fd, out.buf, out.len) < 0)
342 die_errno("Writing SQUASH_MSG");
343 if (close(fd))
344 die_errno("Finishing SQUASH_MSG");
345 strbuf_release(&out);
348 static void finish(const unsigned char *new_head, const char *msg)
350 struct strbuf reflog_message = STRBUF_INIT;
352 if (!msg)
353 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
354 else {
355 if (verbosity >= 0)
356 printf("%s\n", msg);
357 strbuf_addf(&reflog_message, "%s: %s",
358 getenv("GIT_REFLOG_ACTION"), msg);
360 if (squash) {
361 squash_message();
362 } else {
363 if (verbosity >= 0 && !merge_msg.len)
364 printf("No merge message -- not updating HEAD\n");
365 else {
366 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
367 update_ref(reflog_message.buf, "HEAD",
368 new_head, head, 0,
369 DIE_ON_ERR);
371 * We ignore errors in 'gc --auto', since the
372 * user should see them.
374 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
377 if (new_head && show_diffstat) {
378 struct diff_options opts;
379 diff_setup(&opts);
380 opts.output_format |=
381 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
382 opts.detect_rename = DIFF_DETECT_RENAME;
383 if (diff_use_color_default > 0)
384 DIFF_OPT_SET(&opts, COLOR_DIFF);
385 if (diff_setup_done(&opts) < 0)
386 die("diff_setup_done failed");
387 diff_tree_sha1(head, new_head, "", &opts);
388 diffcore_std(&opts);
389 diff_flush(&opts);
392 /* Run a post-merge hook */
393 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
395 strbuf_release(&reflog_message);
398 /* Get the name for the merge commit's message. */
399 static void merge_name(const char *remote, struct strbuf *msg)
401 struct object *remote_head;
402 unsigned char branch_head[20], buf_sha[20];
403 struct strbuf buf = STRBUF_INIT;
404 struct strbuf bname = STRBUF_INIT;
405 const char *ptr;
406 char *found_ref;
407 int len, early;
409 strbuf_branchname(&bname, remote);
410 remote = bname.buf;
412 memset(branch_head, 0, sizeof(branch_head));
413 remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
414 if (!remote_head)
415 die("'%s' does not point to a commit", remote);
417 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
418 if (!prefixcmp(found_ref, "refs/heads/")) {
419 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
420 sha1_to_hex(branch_head), remote);
421 goto cleanup;
423 if (!prefixcmp(found_ref, "refs/remotes/")) {
424 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
425 sha1_to_hex(branch_head), remote);
426 goto cleanup;
430 /* See if remote matches <name>^^^.. or <name>~<number> */
431 for (len = 0, ptr = remote + strlen(remote);
432 remote < ptr && ptr[-1] == '^';
433 ptr--)
434 len++;
435 if (len)
436 early = 1;
437 else {
438 early = 0;
439 ptr = strrchr(remote, '~');
440 if (ptr) {
441 int seen_nonzero = 0;
443 len++; /* count ~ */
444 while (*++ptr && isdigit(*ptr)) {
445 seen_nonzero |= (*ptr != '0');
446 len++;
448 if (*ptr)
449 len = 0; /* not ...~<number> */
450 else if (seen_nonzero)
451 early = 1;
452 else if (len == 1)
453 early = 1; /* "name~" is "name~1"! */
456 if (len) {
457 struct strbuf truname = STRBUF_INIT;
458 strbuf_addstr(&truname, "refs/heads/");
459 strbuf_addstr(&truname, remote);
460 strbuf_setlen(&truname, truname.len - len);
461 if (resolve_ref(truname.buf, buf_sha, 1, NULL)) {
462 strbuf_addf(msg,
463 "%s\t\tbranch '%s'%s of .\n",
464 sha1_to_hex(remote_head->sha1),
465 truname.buf + 11,
466 (early ? " (early part)" : ""));
467 strbuf_release(&truname);
468 goto cleanup;
472 if (!strcmp(remote, "FETCH_HEAD") &&
473 !access(git_path("FETCH_HEAD"), R_OK)) {
474 FILE *fp;
475 struct strbuf line = STRBUF_INIT;
476 char *ptr;
478 fp = fopen(git_path("FETCH_HEAD"), "r");
479 if (!fp)
480 die_errno("could not open '%s' for reading",
481 git_path("FETCH_HEAD"));
482 strbuf_getline(&line, fp, '\n');
483 fclose(fp);
484 ptr = strstr(line.buf, "\tnot-for-merge\t");
485 if (ptr)
486 strbuf_remove(&line, ptr-line.buf+1, 13);
487 strbuf_addbuf(msg, &line);
488 strbuf_release(&line);
489 goto cleanup;
491 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
492 sha1_to_hex(remote_head->sha1), remote);
493 cleanup:
494 strbuf_release(&buf);
495 strbuf_release(&bname);
498 static int git_merge_config(const char *k, const char *v, void *cb)
500 if (branch && !prefixcmp(k, "branch.") &&
501 !prefixcmp(k + 7, branch) &&
502 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
503 const char **argv;
504 int argc;
505 char *buf;
507 buf = xstrdup(v);
508 argc = split_cmdline(buf, &argv);
509 if (argc < 0)
510 die("Bad branch.%s.mergeoptions string: %s", branch,
511 split_cmdline_strerror(argc));
512 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
513 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
514 argc++;
515 parse_options(argc, argv, NULL, builtin_merge_options,
516 builtin_merge_usage, 0);
517 free(buf);
520 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
521 show_diffstat = git_config_bool(k, v);
522 else if (!strcmp(k, "pull.twohead"))
523 return git_config_string(&pull_twohead, k, v);
524 else if (!strcmp(k, "pull.octopus"))
525 return git_config_string(&pull_octopus, k, v);
526 else if (!strcmp(k, "merge.renormalize"))
527 option_renormalize = git_config_bool(k, v);
528 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary")) {
529 int is_bool;
530 shortlog_len = git_config_bool_or_int(k, v, &is_bool);
531 if (!is_bool && shortlog_len < 0)
532 return error("%s: negative length %s", k, v);
533 if (is_bool && shortlog_len)
534 shortlog_len = DEFAULT_MERGE_LOG_LEN;
535 return 0;
537 return git_diff_ui_config(k, v, cb);
540 static int read_tree_trivial(unsigned char *common, unsigned char *head,
541 unsigned char *one)
543 int i, nr_trees = 0;
544 struct tree *trees[MAX_UNPACK_TREES];
545 struct tree_desc t[MAX_UNPACK_TREES];
546 struct unpack_trees_options opts;
548 memset(&opts, 0, sizeof(opts));
549 opts.head_idx = 2;
550 opts.src_index = &the_index;
551 opts.dst_index = &the_index;
552 opts.update = 1;
553 opts.verbose_update = 1;
554 opts.trivial_merges_only = 1;
555 opts.merge = 1;
556 trees[nr_trees] = parse_tree_indirect(common);
557 if (!trees[nr_trees++])
558 return -1;
559 trees[nr_trees] = parse_tree_indirect(head);
560 if (!trees[nr_trees++])
561 return -1;
562 trees[nr_trees] = parse_tree_indirect(one);
563 if (!trees[nr_trees++])
564 return -1;
565 opts.fn = threeway_merge;
566 cache_tree_free(&active_cache_tree);
567 for (i = 0; i < nr_trees; i++) {
568 parse_tree(trees[i]);
569 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
571 if (unpack_trees(nr_trees, t, &opts))
572 return -1;
573 return 0;
576 static void write_tree_trivial(unsigned char *sha1)
578 if (write_cache_as_tree(sha1, 0, NULL))
579 die("git write-tree failed to write a tree");
582 int try_merge_command(const char *strategy, struct commit_list *common,
583 const char *head_arg, struct commit_list *remotes)
585 const char **args;
586 int i = 0, x = 0, ret;
587 struct commit_list *j;
588 struct strbuf buf = STRBUF_INIT;
590 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
591 commit_list_count(remotes)) * sizeof(char *));
592 strbuf_addf(&buf, "merge-%s", strategy);
593 args[i++] = buf.buf;
594 for (x = 0; x < xopts_nr; x++) {
595 char *s = xmalloc(strlen(xopts[x])+2+1);
596 strcpy(s, "--");
597 strcpy(s+2, xopts[x]);
598 args[i++] = s;
600 for (j = common; j; j = j->next)
601 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
602 args[i++] = "--";
603 args[i++] = head_arg;
604 for (j = remotes; j; j = j->next)
605 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
606 args[i] = NULL;
607 ret = run_command_v_opt(args, RUN_GIT_CMD);
608 strbuf_release(&buf);
609 i = 1;
610 for (x = 0; x < xopts_nr; x++)
611 free((void *)args[i++]);
612 for (j = common; j; j = j->next)
613 free((void *)args[i++]);
614 i += 2;
615 for (j = remotes; j; j = j->next)
616 free((void *)args[i++]);
617 free(args);
618 discard_cache();
619 if (read_cache() < 0)
620 die("failed to read the cache");
621 resolve_undo_clear();
623 return ret;
626 static int try_merge_strategy(const char *strategy, struct commit_list *common,
627 const char *head_arg)
629 int index_fd;
630 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
632 index_fd = hold_locked_index(lock, 1);
633 refresh_cache(REFRESH_QUIET);
634 if (active_cache_changed &&
635 (write_cache(index_fd, active_cache, active_nr) ||
636 commit_locked_index(lock)))
637 return error("Unable to write index.");
638 rollback_lock_file(lock);
640 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
641 int clean, x;
642 struct commit *result;
643 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
644 int index_fd;
645 struct commit_list *reversed = NULL;
646 struct merge_options o;
647 struct commit_list *j;
649 if (remoteheads->next) {
650 error("Not handling anything other than two heads merge.");
651 return 2;
654 init_merge_options(&o);
655 if (!strcmp(strategy, "subtree"))
656 o.subtree_shift = "";
658 o.renormalize = option_renormalize;
660 for (x = 0; x < xopts_nr; x++)
661 if (parse_merge_opt(&o, xopts[x]))
662 die("Unknown option for merge-recursive: -X%s", xopts[x]);
664 o.branch1 = head_arg;
665 o.branch2 = remoteheads->item->util;
667 for (j = common; j; j = j->next)
668 commit_list_insert(j->item, &reversed);
670 index_fd = hold_locked_index(lock, 1);
671 clean = merge_recursive(&o, lookup_commit(head),
672 remoteheads->item, reversed, &result);
673 if (active_cache_changed &&
674 (write_cache(index_fd, active_cache, active_nr) ||
675 commit_locked_index(lock)))
676 die ("unable to write %s", get_index_file());
677 rollback_lock_file(lock);
678 return clean ? 0 : 1;
679 } else {
680 return try_merge_command(strategy, common, head_arg, remoteheads);
684 static void count_diff_files(struct diff_queue_struct *q,
685 struct diff_options *opt, void *data)
687 int *count = data;
689 (*count) += q->nr;
692 static int count_unmerged_entries(void)
694 int i, ret = 0;
696 for (i = 0; i < active_nr; i++)
697 if (ce_stage(active_cache[i]))
698 ret++;
700 return ret;
703 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
705 struct tree *trees[MAX_UNPACK_TREES];
706 struct unpack_trees_options opts;
707 struct tree_desc t[MAX_UNPACK_TREES];
708 int i, fd, nr_trees = 0;
709 struct dir_struct dir;
710 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
712 refresh_cache(REFRESH_QUIET);
714 fd = hold_locked_index(lock_file, 1);
716 memset(&trees, 0, sizeof(trees));
717 memset(&opts, 0, sizeof(opts));
718 memset(&t, 0, sizeof(t));
719 memset(&dir, 0, sizeof(dir));
720 dir.flags |= DIR_SHOW_IGNORED;
721 dir.exclude_per_dir = ".gitignore";
722 opts.dir = &dir;
724 opts.head_idx = 1;
725 opts.src_index = &the_index;
726 opts.dst_index = &the_index;
727 opts.update = 1;
728 opts.verbose_update = 1;
729 opts.merge = 1;
730 opts.fn = twoway_merge;
731 setup_unpack_trees_porcelain(&opts, "merge");
733 trees[nr_trees] = parse_tree_indirect(head);
734 if (!trees[nr_trees++])
735 return -1;
736 trees[nr_trees] = parse_tree_indirect(remote);
737 if (!trees[nr_trees++])
738 return -1;
739 for (i = 0; i < nr_trees; i++) {
740 parse_tree(trees[i]);
741 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
743 if (unpack_trees(nr_trees, t, &opts))
744 return -1;
745 if (write_cache(fd, active_cache, active_nr) ||
746 commit_locked_index(lock_file))
747 die("unable to write new index file");
748 return 0;
751 static void split_merge_strategies(const char *string, struct strategy **list,
752 int *nr, int *alloc)
754 char *p, *q, *buf;
756 if (!string)
757 return;
759 buf = xstrdup(string);
760 q = buf;
761 for (;;) {
762 p = strchr(q, ' ');
763 if (!p) {
764 ALLOC_GROW(*list, *nr + 1, *alloc);
765 (*list)[(*nr)++].name = xstrdup(q);
766 free(buf);
767 return;
768 } else {
769 *p = '\0';
770 ALLOC_GROW(*list, *nr + 1, *alloc);
771 (*list)[(*nr)++].name = xstrdup(q);
772 q = ++p;
777 static void add_strategies(const char *string, unsigned attr)
779 struct strategy *list = NULL;
780 int list_alloc = 0, list_nr = 0, i;
782 memset(&list, 0, sizeof(list));
783 split_merge_strategies(string, &list, &list_nr, &list_alloc);
784 if (list) {
785 for (i = 0; i < list_nr; i++)
786 append_strategy(get_strategy(list[i].name));
787 return;
789 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
790 if (all_strategy[i].attr & attr)
791 append_strategy(&all_strategy[i]);
795 static int merge_trivial(void)
797 unsigned char result_tree[20], result_commit[20];
798 struct commit_list *parent = xmalloc(sizeof(*parent));
800 write_tree_trivial(result_tree);
801 printf("Wonderful.\n");
802 parent->item = lookup_commit(head);
803 parent->next = xmalloc(sizeof(*parent->next));
804 parent->next->item = remoteheads->item;
805 parent->next->next = NULL;
806 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
807 finish(result_commit, "In-index merge");
808 drop_save();
809 return 0;
812 static int finish_automerge(struct commit_list *common,
813 unsigned char *result_tree,
814 const char *wt_strategy)
816 struct commit_list *parents = NULL, *j;
817 struct strbuf buf = STRBUF_INIT;
818 unsigned char result_commit[20];
820 free_commit_list(common);
821 if (allow_fast_forward) {
822 parents = remoteheads;
823 commit_list_insert(lookup_commit(head), &parents);
824 parents = reduce_heads(parents);
825 } else {
826 struct commit_list **pptr = &parents;
828 pptr = &commit_list_insert(lookup_commit(head),
829 pptr)->next;
830 for (j = remoteheads; j; j = j->next)
831 pptr = &commit_list_insert(j->item, pptr)->next;
833 free_commit_list(remoteheads);
834 strbuf_addch(&merge_msg, '\n');
835 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
836 strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
837 finish(result_commit, buf.buf);
838 strbuf_release(&buf);
839 drop_save();
840 return 0;
843 static int suggest_conflicts(int renormalizing)
845 FILE *fp;
846 int pos;
848 fp = fopen(git_path("MERGE_MSG"), "a");
849 if (!fp)
850 die_errno("Could not open '%s' for writing",
851 git_path("MERGE_MSG"));
852 fprintf(fp, "\nConflicts:\n");
853 for (pos = 0; pos < active_nr; pos++) {
854 struct cache_entry *ce = active_cache[pos];
856 if (ce_stage(ce)) {
857 fprintf(fp, "\t%s\n", ce->name);
858 while (pos + 1 < active_nr &&
859 !strcmp(ce->name,
860 active_cache[pos + 1]->name))
861 pos++;
864 fclose(fp);
865 rerere(allow_rerere_auto);
866 printf("Automatic merge failed; "
867 "fix conflicts and then commit the result.\n");
868 return 1;
871 static struct commit *is_old_style_invocation(int argc, const char **argv)
873 struct commit *second_token = NULL;
874 if (argc > 2) {
875 unsigned char second_sha1[20];
877 if (get_sha1(argv[1], second_sha1))
878 return NULL;
879 second_token = lookup_commit_reference_gently(second_sha1, 0);
880 if (!second_token)
881 die("'%s' is not a commit", argv[1]);
882 if (hashcmp(second_token->object.sha1, head))
883 return NULL;
885 return second_token;
888 static int evaluate_result(void)
890 int cnt = 0;
891 struct rev_info rev;
893 /* Check how many files differ. */
894 init_revisions(&rev, "");
895 setup_revisions(0, NULL, &rev, NULL);
896 rev.diffopt.output_format |=
897 DIFF_FORMAT_CALLBACK;
898 rev.diffopt.format_callback = count_diff_files;
899 rev.diffopt.format_callback_data = &cnt;
900 run_diff_files(&rev, 0);
903 * Check how many unmerged entries are
904 * there.
906 cnt += count_unmerged_entries();
908 return cnt;
911 int cmd_merge(int argc, const char **argv, const char *prefix)
913 unsigned char result_tree[20];
914 struct strbuf buf = STRBUF_INIT;
915 const char *head_arg;
916 int flag, head_invalid = 0, i;
917 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
918 struct commit_list *common = NULL;
919 const char *best_strategy = NULL, *wt_strategy = NULL;
920 struct commit_list **remotes = &remoteheads;
922 if (read_cache_unmerged()) {
923 die_resolve_conflict("merge");
925 if (file_exists(git_path("MERGE_HEAD"))) {
927 * There is no unmerged entry, don't advise 'git
928 * add/rm <file>', just 'git commit'.
930 if (advice_resolve_conflict)
931 die("You have not concluded your merge (MERGE_HEAD exists).\n"
932 "Please, commit your changes before you can merge.");
933 else
934 die("You have not concluded your merge (MERGE_HEAD exists).");
937 resolve_undo_clear();
939 * Check if we are _not_ on a detached HEAD, i.e. if there is a
940 * current branch.
942 branch = resolve_ref("HEAD", head, 0, &flag);
943 if (branch && !prefixcmp(branch, "refs/heads/"))
944 branch += 11;
945 if (is_null_sha1(head))
946 head_invalid = 1;
948 git_config(git_merge_config, NULL);
950 /* for color.ui */
951 if (diff_use_color_default == -1)
952 diff_use_color_default = git_use_color_default;
954 argc = parse_options(argc, argv, prefix, builtin_merge_options,
955 builtin_merge_usage, 0);
956 if (verbosity < 0)
957 show_diffstat = 0;
959 if (squash) {
960 if (!allow_fast_forward)
961 die("You cannot combine --squash with --no-ff.");
962 option_commit = 0;
965 if (!allow_fast_forward && fast_forward_only)
966 die("You cannot combine --no-ff with --ff-only.");
968 if (!argc)
969 usage_with_options(builtin_merge_usage,
970 builtin_merge_options);
973 * This could be traditional "merge <msg> HEAD <commit>..." and
974 * the way we can tell it is to see if the second token is HEAD,
975 * but some people might have misused the interface and used a
976 * committish that is the same as HEAD there instead.
977 * Traditional format never would have "-m" so it is an
978 * additional safety measure to check for it.
981 if (!have_message && is_old_style_invocation(argc, argv)) {
982 strbuf_addstr(&merge_msg, argv[0]);
983 head_arg = argv[1];
984 argv += 2;
985 argc -= 2;
986 } else if (head_invalid) {
987 struct object *remote_head;
989 * If the merged head is a valid one there is no reason
990 * to forbid "git merge" into a branch yet to be born.
991 * We do the same for "git pull".
993 if (argc != 1)
994 die("Can merge only exactly one commit into "
995 "empty head");
996 if (squash)
997 die("Squash commit into empty head not supported yet");
998 if (!allow_fast_forward)
999 die("Non-fast-forward commit does not make sense into "
1000 "an empty head");
1001 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
1002 if (!remote_head)
1003 die("%s - not something we can merge", argv[0]);
1004 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
1005 DIE_ON_ERR);
1006 read_empty(remote_head->sha1, 0);
1007 return 0;
1008 } else {
1009 struct strbuf merge_names = STRBUF_INIT;
1011 /* We are invoked directly as the first-class UI. */
1012 head_arg = "HEAD";
1015 * All the rest are the commits being merged;
1016 * prepare the standard merge summary message to
1017 * be appended to the given message. If remote
1018 * is invalid we will die later in the common
1019 * codepath so we discard the error in this
1020 * loop.
1022 for (i = 0; i < argc; i++)
1023 merge_name(argv[i], &merge_names);
1025 if (!have_message || shortlog_len) {
1026 fmt_merge_msg(&merge_names, &merge_msg, !have_message,
1027 shortlog_len);
1028 if (merge_msg.len)
1029 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1033 if (head_invalid || !argc)
1034 usage_with_options(builtin_merge_usage,
1035 builtin_merge_options);
1037 strbuf_addstr(&buf, "merge");
1038 for (i = 0; i < argc; i++)
1039 strbuf_addf(&buf, " %s", argv[i]);
1040 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1041 strbuf_reset(&buf);
1043 for (i = 0; i < argc; i++) {
1044 struct object *o;
1045 struct commit *commit;
1047 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
1048 if (!o)
1049 die("%s - not something we can merge", argv[i]);
1050 commit = lookup_commit(o->sha1);
1051 commit->util = (void *)argv[i];
1052 remotes = &commit_list_insert(commit, remotes)->next;
1054 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1055 setenv(buf.buf, argv[i], 1);
1056 strbuf_reset(&buf);
1059 if (!use_strategies) {
1060 if (!remoteheads->next)
1061 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1062 else
1063 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1066 for (i = 0; i < use_strategies_nr; i++) {
1067 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1068 allow_fast_forward = 0;
1069 if (use_strategies[i]->attr & NO_TRIVIAL)
1070 allow_trivial = 0;
1073 if (!remoteheads->next)
1074 common = get_merge_bases(lookup_commit(head),
1075 remoteheads->item, 1);
1076 else {
1077 struct commit_list *list = remoteheads;
1078 commit_list_insert(lookup_commit(head), &list);
1079 common = get_octopus_merge_bases(list);
1080 free(list);
1083 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1084 DIE_ON_ERR);
1086 if (!common)
1087 ; /* No common ancestors found. We need a real merge. */
1088 else if (!remoteheads->next && !common->next &&
1089 common->item == remoteheads->item) {
1091 * If head can reach all the merge then we are up to date.
1092 * but first the most common case of merging one remote.
1094 finish_up_to_date("Already up-to-date.");
1095 return 0;
1096 } else if (allow_fast_forward && !remoteheads->next &&
1097 !common->next &&
1098 !hashcmp(common->item->object.sha1, head)) {
1099 /* Again the most common case of merging one remote. */
1100 struct strbuf msg = STRBUF_INIT;
1101 struct object *o;
1102 char hex[41];
1104 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1106 if (verbosity >= 0)
1107 printf("Updating %s..%s\n",
1108 hex,
1109 find_unique_abbrev(remoteheads->item->object.sha1,
1110 DEFAULT_ABBREV));
1111 strbuf_addstr(&msg, "Fast-forward");
1112 if (have_message)
1113 strbuf_addstr(&msg,
1114 " (no commit created; -m option ignored)");
1115 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1116 0, NULL, OBJ_COMMIT);
1117 if (!o)
1118 return 1;
1120 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1121 return 1;
1123 finish(o->sha1, msg.buf);
1124 drop_save();
1125 return 0;
1126 } else if (!remoteheads->next && common->next)
1129 * We are not doing octopus and not fast-forward. Need
1130 * a real merge.
1132 else if (!remoteheads->next && !common->next && option_commit) {
1134 * We are not doing octopus, not fast-forward, and have
1135 * only one common.
1137 refresh_cache(REFRESH_QUIET);
1138 if (allow_trivial && !fast_forward_only) {
1139 /* See if it is really trivial. */
1140 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1141 printf("Trying really trivial in-index merge...\n");
1142 if (!read_tree_trivial(common->item->object.sha1,
1143 head, remoteheads->item->object.sha1))
1144 return merge_trivial();
1145 printf("Nope.\n");
1147 } else {
1149 * An octopus. If we can reach all the remote we are up
1150 * to date.
1152 int up_to_date = 1;
1153 struct commit_list *j;
1155 for (j = remoteheads; j; j = j->next) {
1156 struct commit_list *common_one;
1159 * Here we *have* to calculate the individual
1160 * merge_bases again, otherwise "git merge HEAD^
1161 * HEAD^^" would be missed.
1163 common_one = get_merge_bases(lookup_commit(head),
1164 j->item, 1);
1165 if (hashcmp(common_one->item->object.sha1,
1166 j->item->object.sha1)) {
1167 up_to_date = 0;
1168 break;
1171 if (up_to_date) {
1172 finish_up_to_date("Already up-to-date. Yeeah!");
1173 return 0;
1177 if (fast_forward_only)
1178 die("Not possible to fast-forward, aborting.");
1180 /* We are going to make a new commit. */
1181 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1184 * At this point, we need a real merge. No matter what strategy
1185 * we use, it would operate on the index, possibly affecting the
1186 * working tree, and when resolved cleanly, have the desired
1187 * tree in the index -- this means that the index must be in
1188 * sync with the head commit. The strategies are responsible
1189 * to ensure this.
1191 if (use_strategies_nr != 1) {
1193 * Stash away the local changes so that we can try more
1194 * than one.
1196 save_state();
1197 } else {
1198 memcpy(stash, null_sha1, 20);
1201 for (i = 0; i < use_strategies_nr; i++) {
1202 int ret;
1203 if (i) {
1204 printf("Rewinding the tree to pristine...\n");
1205 restore_state();
1207 if (use_strategies_nr != 1)
1208 printf("Trying merge strategy %s...\n",
1209 use_strategies[i]->name);
1211 * Remember which strategy left the state in the working
1212 * tree.
1214 wt_strategy = use_strategies[i]->name;
1216 ret = try_merge_strategy(use_strategies[i]->name,
1217 common, head_arg);
1218 if (!option_commit && !ret) {
1219 merge_was_ok = 1;
1221 * This is necessary here just to avoid writing
1222 * the tree, but later we will *not* exit with
1223 * status code 1 because merge_was_ok is set.
1225 ret = 1;
1228 if (ret) {
1230 * The backend exits with 1 when conflicts are
1231 * left to be resolved, with 2 when it does not
1232 * handle the given merge at all.
1234 if (ret == 1) {
1235 int cnt = evaluate_result();
1237 if (best_cnt <= 0 || cnt <= best_cnt) {
1238 best_strategy = use_strategies[i]->name;
1239 best_cnt = cnt;
1242 if (merge_was_ok)
1243 break;
1244 else
1245 continue;
1248 /* Automerge succeeded. */
1249 write_tree_trivial(result_tree);
1250 automerge_was_ok = 1;
1251 break;
1255 * If we have a resulting tree, that means the strategy module
1256 * auto resolved the merge cleanly.
1258 if (automerge_was_ok)
1259 return finish_automerge(common, result_tree, wt_strategy);
1262 * Pick the result from the best strategy and have the user fix
1263 * it up.
1265 if (!best_strategy) {
1266 restore_state();
1267 if (use_strategies_nr > 1)
1268 fprintf(stderr,
1269 "No merge strategy handled the merge.\n");
1270 else
1271 fprintf(stderr, "Merge with strategy %s failed.\n",
1272 use_strategies[0]->name);
1273 return 2;
1274 } else if (best_strategy == wt_strategy)
1275 ; /* We already have its result in the working tree. */
1276 else {
1277 printf("Rewinding the tree to pristine...\n");
1278 restore_state();
1279 printf("Using the %s to prepare resolving by hand.\n",
1280 best_strategy);
1281 try_merge_strategy(best_strategy, common, head_arg);
1284 if (squash)
1285 finish(NULL, NULL);
1286 else {
1287 int fd;
1288 struct commit_list *j;
1290 for (j = remoteheads; j; j = j->next)
1291 strbuf_addf(&buf, "%s\n",
1292 sha1_to_hex(j->item->object.sha1));
1293 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1294 if (fd < 0)
1295 die_errno("Could not open '%s' for writing",
1296 git_path("MERGE_HEAD"));
1297 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1298 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1299 close(fd);
1300 strbuf_addch(&merge_msg, '\n');
1301 fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1302 if (fd < 0)
1303 die_errno("Could not open '%s' for writing",
1304 git_path("MERGE_MSG"));
1305 if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1306 merge_msg.len)
1307 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1308 close(fd);
1309 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1310 if (fd < 0)
1311 die_errno("Could not open '%s' for writing",
1312 git_path("MERGE_MODE"));
1313 strbuf_reset(&buf);
1314 if (!allow_fast_forward)
1315 strbuf_addf(&buf, "no-ff");
1316 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1317 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1318 close(fd);
1321 if (merge_was_ok) {
1322 fprintf(stderr, "Automatic merge went well; "
1323 "stopped before committing as requested\n");
1324 return 0;
1325 } else
1326 return suggest_conflicts(option_renormalize);