Sync with 1.7.2.3
[git/gitweb.git] / builtin / merge.c
blob47e705ba9b6bb043b28183422d518b65cf513478
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, 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 },
68 static const char *pull_twohead, *pull_octopus;
70 static int option_parse_message(const struct option *opt,
71 const char *arg, int unset)
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;
85 static struct strategy *get_strategy(const char *name)
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);
115 exclude_cmds(&main_cmds, &not_strategies);
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");
129 exit(1);
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()
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 reset_hard(unsigned const char *sha1, int verbose)
236 int i = 0;
237 const char *args[6];
239 args[i++] = "read-tree";
240 if (verbose)
241 args[i++] = "-v";
242 args[i++] = "--reset";
243 args[i++] = "-u";
244 args[i++] = sha1_to_hex(sha1);
245 args[i] = NULL;
247 if (run_command_v_opt(args, RUN_GIT_CMD))
248 die("read-tree failed");
251 static void restore_state(void)
253 struct strbuf sb = STRBUF_INIT;
254 const char *args[] = { "stash", "apply", NULL, NULL };
256 if (is_null_sha1(stash))
257 return;
259 reset_hard(head, 1);
261 args[2] = sha1_to_hex(stash);
264 * It is OK to ignore error here, for example when there was
265 * nothing to restore.
267 run_command_v_opt(args, RUN_GIT_CMD);
269 strbuf_release(&sb);
270 refresh_cache(REFRESH_QUIET);
273 /* This is called when no merge was necessary. */
274 static void finish_up_to_date(const char *msg)
276 if (verbosity >= 0)
277 printf("%s%s\n", squash ? " (nothing to squash)" : "", msg);
278 drop_save();
281 static void squash_message(void)
283 struct rev_info rev;
284 struct commit *commit;
285 struct strbuf out = STRBUF_INIT;
286 struct commit_list *j;
287 int fd;
288 struct pretty_print_context ctx = {0};
290 printf("Squash commit -- not updating HEAD\n");
291 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
292 if (fd < 0)
293 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
295 init_revisions(&rev, NULL);
296 rev.ignore_merges = 1;
297 rev.commit_format = CMIT_FMT_MEDIUM;
299 commit = lookup_commit(head);
300 commit->object.flags |= UNINTERESTING;
301 add_pending_object(&rev, &commit->object, NULL);
303 for (j = remoteheads; j; j = j->next)
304 add_pending_object(&rev, &j->item->object, NULL);
306 setup_revisions(0, NULL, &rev, NULL);
307 if (prepare_revision_walk(&rev))
308 die("revision walk setup failed");
310 ctx.abbrev = rev.abbrev;
311 ctx.date_mode = rev.date_mode;
313 strbuf_addstr(&out, "Squashed commit of the following:\n");
314 while ((commit = get_revision(&rev)) != NULL) {
315 strbuf_addch(&out, '\n');
316 strbuf_addf(&out, "commit %s\n",
317 sha1_to_hex(commit->object.sha1));
318 pretty_print_commit(rev.commit_format, commit, &out, &ctx);
320 if (write(fd, out.buf, out.len) < 0)
321 die_errno("Writing SQUASH_MSG");
322 if (close(fd))
323 die_errno("Finishing SQUASH_MSG");
324 strbuf_release(&out);
327 static void finish(const unsigned char *new_head, const char *msg)
329 struct strbuf reflog_message = STRBUF_INIT;
331 if (!msg)
332 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
333 else {
334 if (verbosity >= 0)
335 printf("%s\n", msg);
336 strbuf_addf(&reflog_message, "%s: %s",
337 getenv("GIT_REFLOG_ACTION"), msg);
339 if (squash) {
340 squash_message();
341 } else {
342 if (verbosity >= 0 && !merge_msg.len)
343 printf("No merge message -- not updating HEAD\n");
344 else {
345 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
346 update_ref(reflog_message.buf, "HEAD",
347 new_head, head, 0,
348 DIE_ON_ERR);
350 * We ignore errors in 'gc --auto', since the
351 * user should see them.
353 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
356 if (new_head && show_diffstat) {
357 struct diff_options opts;
358 diff_setup(&opts);
359 opts.output_format |=
360 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
361 opts.detect_rename = DIFF_DETECT_RENAME;
362 if (diff_use_color_default > 0)
363 DIFF_OPT_SET(&opts, COLOR_DIFF);
364 if (diff_setup_done(&opts) < 0)
365 die("diff_setup_done failed");
366 diff_tree_sha1(head, new_head, "", &opts);
367 diffcore_std(&opts);
368 diff_flush(&opts);
371 /* Run a post-merge hook */
372 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
374 strbuf_release(&reflog_message);
377 /* Get the name for the merge commit's message. */
378 static void merge_name(const char *remote, struct strbuf *msg)
380 struct object *remote_head;
381 unsigned char branch_head[20], buf_sha[20];
382 struct strbuf buf = STRBUF_INIT;
383 struct strbuf bname = STRBUF_INIT;
384 const char *ptr;
385 char *found_ref;
386 int len, early;
388 strbuf_branchname(&bname, remote);
389 remote = bname.buf;
391 memset(branch_head, 0, sizeof(branch_head));
392 remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
393 if (!remote_head)
394 die("'%s' does not point to a commit", remote);
396 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
397 if (!prefixcmp(found_ref, "refs/heads/")) {
398 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
399 sha1_to_hex(branch_head), remote);
400 goto cleanup;
402 if (!prefixcmp(found_ref, "refs/remotes/")) {
403 strbuf_addf(msg, "%s\t\tremote branch '%s' of .\n",
404 sha1_to_hex(branch_head), remote);
405 goto cleanup;
409 /* See if remote matches <name>^^^.. or <name>~<number> */
410 for (len = 0, ptr = remote + strlen(remote);
411 remote < ptr && ptr[-1] == '^';
412 ptr--)
413 len++;
414 if (len)
415 early = 1;
416 else {
417 early = 0;
418 ptr = strrchr(remote, '~');
419 if (ptr) {
420 int seen_nonzero = 0;
422 len++; /* count ~ */
423 while (*++ptr && isdigit(*ptr)) {
424 seen_nonzero |= (*ptr != '0');
425 len++;
427 if (*ptr)
428 len = 0; /* not ...~<number> */
429 else if (seen_nonzero)
430 early = 1;
431 else if (len == 1)
432 early = 1; /* "name~" is "name~1"! */
435 if (len) {
436 struct strbuf truname = STRBUF_INIT;
437 strbuf_addstr(&truname, "refs/heads/");
438 strbuf_addstr(&truname, remote);
439 strbuf_setlen(&truname, truname.len - len);
440 if (resolve_ref(truname.buf, buf_sha, 0, NULL)) {
441 strbuf_addf(msg,
442 "%s\t\tbranch '%s'%s of .\n",
443 sha1_to_hex(remote_head->sha1),
444 truname.buf + 11,
445 (early ? " (early part)" : ""));
446 strbuf_release(&truname);
447 goto cleanup;
451 if (!strcmp(remote, "FETCH_HEAD") &&
452 !access(git_path("FETCH_HEAD"), R_OK)) {
453 FILE *fp;
454 struct strbuf line = STRBUF_INIT;
455 char *ptr;
457 fp = fopen(git_path("FETCH_HEAD"), "r");
458 if (!fp)
459 die_errno("could not open '%s' for reading",
460 git_path("FETCH_HEAD"));
461 strbuf_getline(&line, fp, '\n');
462 fclose(fp);
463 ptr = strstr(line.buf, "\tnot-for-merge\t");
464 if (ptr)
465 strbuf_remove(&line, ptr-line.buf+1, 13);
466 strbuf_addbuf(msg, &line);
467 strbuf_release(&line);
468 goto cleanup;
470 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
471 sha1_to_hex(remote_head->sha1), remote);
472 cleanup:
473 strbuf_release(&buf);
474 strbuf_release(&bname);
477 static int git_merge_config(const char *k, const char *v, void *cb)
479 if (branch && !prefixcmp(k, "branch.") &&
480 !prefixcmp(k + 7, branch) &&
481 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
482 const char **argv;
483 int argc;
484 char *buf;
486 buf = xstrdup(v);
487 argc = split_cmdline(buf, &argv);
488 if (argc < 0)
489 die("Bad branch.%s.mergeoptions string: %s", branch,
490 split_cmdline_strerror(argc));
491 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
492 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
493 argc++;
494 parse_options(argc, argv, NULL, builtin_merge_options,
495 builtin_merge_usage, 0);
496 free(buf);
499 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
500 show_diffstat = git_config_bool(k, v);
501 else if (!strcmp(k, "pull.twohead"))
502 return git_config_string(&pull_twohead, k, v);
503 else if (!strcmp(k, "pull.octopus"))
504 return git_config_string(&pull_octopus, k, v);
505 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary"))
506 option_log = git_config_bool(k, v);
507 return git_diff_ui_config(k, v, cb);
510 static int read_tree_trivial(unsigned char *common, unsigned char *head,
511 unsigned char *one)
513 int i, nr_trees = 0;
514 struct tree *trees[MAX_UNPACK_TREES];
515 struct tree_desc t[MAX_UNPACK_TREES];
516 struct unpack_trees_options opts;
518 memset(&opts, 0, sizeof(opts));
519 opts.head_idx = 2;
520 opts.src_index = &the_index;
521 opts.dst_index = &the_index;
522 opts.update = 1;
523 opts.verbose_update = 1;
524 opts.trivial_merges_only = 1;
525 opts.merge = 1;
526 trees[nr_trees] = parse_tree_indirect(common);
527 if (!trees[nr_trees++])
528 return -1;
529 trees[nr_trees] = parse_tree_indirect(head);
530 if (!trees[nr_trees++])
531 return -1;
532 trees[nr_trees] = parse_tree_indirect(one);
533 if (!trees[nr_trees++])
534 return -1;
535 opts.fn = threeway_merge;
536 cache_tree_free(&active_cache_tree);
537 for (i = 0; i < nr_trees; i++) {
538 parse_tree(trees[i]);
539 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
541 if (unpack_trees(nr_trees, t, &opts))
542 return -1;
543 return 0;
546 static void write_tree_trivial(unsigned char *sha1)
548 if (write_cache_as_tree(sha1, 0, NULL))
549 die("git write-tree failed to write a tree");
552 int try_merge_command(const char *strategy, struct commit_list *common,
553 const char *head_arg, struct commit_list *remotes)
555 const char **args;
556 int i = 0, x = 0, ret;
557 struct commit_list *j;
558 struct strbuf buf = STRBUF_INIT;
560 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
561 commit_list_count(remotes)) * sizeof(char *));
562 strbuf_addf(&buf, "merge-%s", strategy);
563 args[i++] = buf.buf;
564 for (x = 0; x < xopts_nr; x++) {
565 char *s = xmalloc(strlen(xopts[x])+2+1);
566 strcpy(s, "--");
567 strcpy(s+2, xopts[x]);
568 args[i++] = s;
570 for (j = common; j; j = j->next)
571 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
572 args[i++] = "--";
573 args[i++] = head_arg;
574 for (j = remotes; j; j = j->next)
575 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
576 args[i] = NULL;
577 ret = run_command_v_opt(args, RUN_GIT_CMD);
578 strbuf_release(&buf);
579 i = 1;
580 for (x = 0; x < xopts_nr; x++)
581 free((void *)args[i++]);
582 for (j = common; j; j = j->next)
583 free((void *)args[i++]);
584 i += 2;
585 for (j = remotes; j; j = j->next)
586 free((void *)args[i++]);
587 free(args);
588 discard_cache();
589 if (read_cache() < 0)
590 die("failed to read the cache");
591 resolve_undo_clear();
593 return ret;
596 static int try_merge_strategy(const char *strategy, struct commit_list *common,
597 const char *head_arg)
599 int index_fd;
600 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
602 index_fd = hold_locked_index(lock, 1);
603 refresh_cache(REFRESH_QUIET);
604 if (active_cache_changed &&
605 (write_cache(index_fd, active_cache, active_nr) ||
606 commit_locked_index(lock)))
607 return error("Unable to write index.");
608 rollback_lock_file(lock);
610 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
611 int clean, x;
612 struct commit *result;
613 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
614 int index_fd;
615 struct commit_list *reversed = NULL;
616 struct merge_options o;
617 struct commit_list *j;
619 if (remoteheads->next) {
620 error("Not handling anything other than two heads merge.");
621 return 2;
624 init_merge_options(&o);
625 if (!strcmp(strategy, "subtree"))
626 o.subtree_shift = "";
628 for (x = 0; x < xopts_nr; x++) {
629 if (!strcmp(xopts[x], "ours"))
630 o.recursive_variant = MERGE_RECURSIVE_OURS;
631 else if (!strcmp(xopts[x], "theirs"))
632 o.recursive_variant = MERGE_RECURSIVE_THEIRS;
633 else if (!strcmp(xopts[x], "subtree"))
634 o.subtree_shift = "";
635 else if (!prefixcmp(xopts[x], "subtree="))
636 o.subtree_shift = xopts[x]+8;
637 else
638 die("Unknown option for merge-recursive: -X%s", xopts[x]);
641 o.branch1 = head_arg;
642 o.branch2 = remoteheads->item->util;
644 for (j = common; j; j = j->next)
645 commit_list_insert(j->item, &reversed);
647 index_fd = hold_locked_index(lock, 1);
648 clean = merge_recursive(&o, lookup_commit(head),
649 remoteheads->item, reversed, &result);
650 if (active_cache_changed &&
651 (write_cache(index_fd, active_cache, active_nr) ||
652 commit_locked_index(lock)))
653 die ("unable to write %s", get_index_file());
654 rollback_lock_file(lock);
655 return clean ? 0 : 1;
656 } else {
657 return try_merge_command(strategy, common, head_arg, remoteheads);
661 static void count_diff_files(struct diff_queue_struct *q,
662 struct diff_options *opt, void *data)
664 int *count = data;
666 (*count) += q->nr;
669 static int count_unmerged_entries(void)
671 int i, ret = 0;
673 for (i = 0; i < active_nr; i++)
674 if (ce_stage(active_cache[i]))
675 ret++;
677 return ret;
680 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
682 struct tree *trees[MAX_UNPACK_TREES];
683 struct unpack_trees_options opts;
684 struct tree_desc t[MAX_UNPACK_TREES];
685 int i, fd, nr_trees = 0;
686 struct dir_struct dir;
687 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
689 refresh_cache(REFRESH_QUIET);
691 fd = hold_locked_index(lock_file, 1);
693 memset(&trees, 0, sizeof(trees));
694 memset(&opts, 0, sizeof(opts));
695 memset(&t, 0, sizeof(t));
696 memset(&dir, 0, sizeof(dir));
697 dir.flags |= DIR_SHOW_IGNORED;
698 dir.exclude_per_dir = ".gitignore";
699 opts.dir = &dir;
701 opts.head_idx = 1;
702 opts.src_index = &the_index;
703 opts.dst_index = &the_index;
704 opts.update = 1;
705 opts.verbose_update = 1;
706 opts.merge = 1;
707 opts.fn = twoway_merge;
708 opts.show_all_errors = 1;
709 set_porcelain_error_msgs(opts.msgs, "merge");
711 trees[nr_trees] = parse_tree_indirect(head);
712 if (!trees[nr_trees++])
713 return -1;
714 trees[nr_trees] = parse_tree_indirect(remote);
715 if (!trees[nr_trees++])
716 return -1;
717 for (i = 0; i < nr_trees; i++) {
718 parse_tree(trees[i]);
719 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
721 if (unpack_trees(nr_trees, t, &opts))
722 return -1;
723 if (write_cache(fd, active_cache, active_nr) ||
724 commit_locked_index(lock_file))
725 die("unable to write new index file");
726 return 0;
729 static void split_merge_strategies(const char *string, struct strategy **list,
730 int *nr, int *alloc)
732 char *p, *q, *buf;
734 if (!string)
735 return;
737 buf = xstrdup(string);
738 q = buf;
739 for (;;) {
740 p = strchr(q, ' ');
741 if (!p) {
742 ALLOC_GROW(*list, *nr + 1, *alloc);
743 (*list)[(*nr)++].name = xstrdup(q);
744 free(buf);
745 return;
746 } else {
747 *p = '\0';
748 ALLOC_GROW(*list, *nr + 1, *alloc);
749 (*list)[(*nr)++].name = xstrdup(q);
750 q = ++p;
755 static void add_strategies(const char *string, unsigned attr)
757 struct strategy *list = NULL;
758 int list_alloc = 0, list_nr = 0, i;
760 memset(&list, 0, sizeof(list));
761 split_merge_strategies(string, &list, &list_nr, &list_alloc);
762 if (list) {
763 for (i = 0; i < list_nr; i++)
764 append_strategy(get_strategy(list[i].name));
765 return;
767 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
768 if (all_strategy[i].attr & attr)
769 append_strategy(&all_strategy[i]);
773 static int merge_trivial(void)
775 unsigned char result_tree[20], result_commit[20];
776 struct commit_list *parent = xmalloc(sizeof(*parent));
778 write_tree_trivial(result_tree);
779 printf("Wonderful.\n");
780 parent->item = lookup_commit(head);
781 parent->next = xmalloc(sizeof(*parent->next));
782 parent->next->item = remoteheads->item;
783 parent->next->next = NULL;
784 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
785 finish(result_commit, "In-index merge");
786 drop_save();
787 return 0;
790 static int finish_automerge(struct commit_list *common,
791 unsigned char *result_tree,
792 const char *wt_strategy)
794 struct commit_list *parents = NULL, *j;
795 struct strbuf buf = STRBUF_INIT;
796 unsigned char result_commit[20];
798 free_commit_list(common);
799 if (allow_fast_forward) {
800 parents = remoteheads;
801 commit_list_insert(lookup_commit(head), &parents);
802 parents = reduce_heads(parents);
803 } else {
804 struct commit_list **pptr = &parents;
806 pptr = &commit_list_insert(lookup_commit(head),
807 pptr)->next;
808 for (j = remoteheads; j; j = j->next)
809 pptr = &commit_list_insert(j->item, pptr)->next;
811 free_commit_list(remoteheads);
812 strbuf_addch(&merge_msg, '\n');
813 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
814 strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
815 finish(result_commit, buf.buf);
816 strbuf_release(&buf);
817 drop_save();
818 return 0;
821 static int suggest_conflicts(void)
823 FILE *fp;
824 int pos;
826 fp = fopen(git_path("MERGE_MSG"), "a");
827 if (!fp)
828 die_errno("Could not open '%s' for writing",
829 git_path("MERGE_MSG"));
830 fprintf(fp, "\nConflicts:\n");
831 for (pos = 0; pos < active_nr; pos++) {
832 struct cache_entry *ce = active_cache[pos];
834 if (ce_stage(ce)) {
835 fprintf(fp, "\t%s\n", ce->name);
836 while (pos + 1 < active_nr &&
837 !strcmp(ce->name,
838 active_cache[pos + 1]->name))
839 pos++;
842 fclose(fp);
843 rerere(allow_rerere_auto);
844 printf("Automatic merge failed; "
845 "fix conflicts and then commit the result.\n");
846 return 1;
849 static struct commit *is_old_style_invocation(int argc, const char **argv)
851 struct commit *second_token = NULL;
852 if (argc > 2) {
853 unsigned char second_sha1[20];
855 if (get_sha1(argv[1], second_sha1))
856 return NULL;
857 second_token = lookup_commit_reference_gently(second_sha1, 0);
858 if (!second_token)
859 die("'%s' is not a commit", argv[1]);
860 if (hashcmp(second_token->object.sha1, head))
861 return NULL;
863 return second_token;
866 static int evaluate_result(void)
868 int cnt = 0;
869 struct rev_info rev;
871 /* Check how many files differ. */
872 init_revisions(&rev, "");
873 setup_revisions(0, NULL, &rev, NULL);
874 rev.diffopt.output_format |=
875 DIFF_FORMAT_CALLBACK;
876 rev.diffopt.format_callback = count_diff_files;
877 rev.diffopt.format_callback_data = &cnt;
878 run_diff_files(&rev, 0);
881 * Check how many unmerged entries are
882 * there.
884 cnt += count_unmerged_entries();
886 return cnt;
889 int cmd_merge(int argc, const char **argv, const char *prefix)
891 unsigned char result_tree[20];
892 struct strbuf buf = STRBUF_INIT;
893 const char *head_arg;
894 int flag, head_invalid = 0, i;
895 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
896 struct commit_list *common = NULL;
897 const char *best_strategy = NULL, *wt_strategy = NULL;
898 struct commit_list **remotes = &remoteheads;
900 if (read_cache_unmerged()) {
901 die_resolve_conflict("merge");
903 if (file_exists(git_path("MERGE_HEAD"))) {
905 * There is no unmerged entry, don't advise 'git
906 * add/rm <file>', just 'git commit'.
908 if (advice_resolve_conflict)
909 die("You have not concluded your merge (MERGE_HEAD exists).\n"
910 "Please, commit your changes before you can merge.");
911 else
912 die("You have not concluded your merge (MERGE_HEAD exists).");
915 resolve_undo_clear();
917 * Check if we are _not_ on a detached HEAD, i.e. if there is a
918 * current branch.
920 branch = resolve_ref("HEAD", head, 0, &flag);
921 if (branch && !prefixcmp(branch, "refs/heads/"))
922 branch += 11;
923 if (is_null_sha1(head))
924 head_invalid = 1;
926 git_config(git_merge_config, NULL);
928 /* for color.ui */
929 if (diff_use_color_default == -1)
930 diff_use_color_default = git_use_color_default;
932 argc = parse_options(argc, argv, prefix, builtin_merge_options,
933 builtin_merge_usage, 0);
934 if (verbosity < 0)
935 show_diffstat = 0;
937 if (squash) {
938 if (!allow_fast_forward)
939 die("You cannot combine --squash with --no-ff.");
940 option_commit = 0;
943 if (!allow_fast_forward && fast_forward_only)
944 die("You cannot combine --no-ff with --ff-only.");
946 if (!argc)
947 usage_with_options(builtin_merge_usage,
948 builtin_merge_options);
951 * This could be traditional "merge <msg> HEAD <commit>..." and
952 * the way we can tell it is to see if the second token is HEAD,
953 * but some people might have misused the interface and used a
954 * committish that is the same as HEAD there instead.
955 * Traditional format never would have "-m" so it is an
956 * additional safety measure to check for it.
959 if (!have_message && is_old_style_invocation(argc, argv)) {
960 strbuf_addstr(&merge_msg, argv[0]);
961 head_arg = argv[1];
962 argv += 2;
963 argc -= 2;
964 } else if (head_invalid) {
965 struct object *remote_head;
967 * If the merged head is a valid one there is no reason
968 * to forbid "git merge" into a branch yet to be born.
969 * We do the same for "git pull".
971 if (argc != 1)
972 die("Can merge only exactly one commit into "
973 "empty head");
974 if (squash)
975 die("Squash commit into empty head not supported yet");
976 if (!allow_fast_forward)
977 die("Non-fast-forward commit does not make sense into "
978 "an empty head");
979 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
980 if (!remote_head)
981 die("%s - not something we can merge", argv[0]);
982 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
983 DIE_ON_ERR);
984 reset_hard(remote_head->sha1, 0);
985 return 0;
986 } else {
987 struct strbuf merge_names = STRBUF_INIT;
989 /* We are invoked directly as the first-class UI. */
990 head_arg = "HEAD";
993 * All the rest are the commits being merged;
994 * prepare the standard merge summary message to
995 * be appended to the given message. If remote
996 * is invalid we will die later in the common
997 * codepath so we discard the error in this
998 * loop.
1000 for (i = 0; i < argc; i++)
1001 merge_name(argv[i], &merge_names);
1003 if (have_message && option_log)
1004 fmt_merge_msg_shortlog(&merge_names, &merge_msg);
1005 else if (!have_message)
1006 fmt_merge_msg(option_log, &merge_names, &merge_msg);
1009 if (!(have_message && !option_log) && merge_msg.len)
1010 strbuf_setlen(&merge_msg, merge_msg.len-1);
1013 if (head_invalid || !argc)
1014 usage_with_options(builtin_merge_usage,
1015 builtin_merge_options);
1017 strbuf_addstr(&buf, "merge");
1018 for (i = 0; i < argc; i++)
1019 strbuf_addf(&buf, " %s", argv[i]);
1020 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1021 strbuf_reset(&buf);
1023 for (i = 0; i < argc; i++) {
1024 struct object *o;
1025 struct commit *commit;
1027 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
1028 if (!o)
1029 die("%s - not something we can merge", argv[i]);
1030 commit = lookup_commit(o->sha1);
1031 commit->util = (void *)argv[i];
1032 remotes = &commit_list_insert(commit, remotes)->next;
1034 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1035 setenv(buf.buf, argv[i], 1);
1036 strbuf_reset(&buf);
1039 if (!use_strategies) {
1040 if (!remoteheads->next)
1041 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1042 else
1043 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1046 for (i = 0; i < use_strategies_nr; i++) {
1047 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1048 allow_fast_forward = 0;
1049 if (use_strategies[i]->attr & NO_TRIVIAL)
1050 allow_trivial = 0;
1053 if (!remoteheads->next)
1054 common = get_merge_bases(lookup_commit(head),
1055 remoteheads->item, 1);
1056 else {
1057 struct commit_list *list = remoteheads;
1058 commit_list_insert(lookup_commit(head), &list);
1059 common = get_octopus_merge_bases(list);
1060 free(list);
1063 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1064 DIE_ON_ERR);
1066 if (!common)
1067 ; /* No common ancestors found. We need a real merge. */
1068 else if (!remoteheads->next && !common->next &&
1069 common->item == remoteheads->item) {
1071 * If head can reach all the merge then we are up to date.
1072 * but first the most common case of merging one remote.
1074 finish_up_to_date("Already up-to-date.");
1075 return 0;
1076 } else if (allow_fast_forward && !remoteheads->next &&
1077 !common->next &&
1078 !hashcmp(common->item->object.sha1, head)) {
1079 /* Again the most common case of merging one remote. */
1080 struct strbuf msg = STRBUF_INIT;
1081 struct object *o;
1082 char hex[41];
1084 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1086 if (verbosity >= 0)
1087 printf("Updating %s..%s\n",
1088 hex,
1089 find_unique_abbrev(remoteheads->item->object.sha1,
1090 DEFAULT_ABBREV));
1091 strbuf_addstr(&msg, "Fast-forward");
1092 if (have_message)
1093 strbuf_addstr(&msg,
1094 " (no commit created; -m option ignored)");
1095 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1096 0, NULL, OBJ_COMMIT);
1097 if (!o)
1098 return 1;
1100 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1101 return 1;
1103 finish(o->sha1, msg.buf);
1104 drop_save();
1105 return 0;
1106 } else if (!remoteheads->next && common->next)
1109 * We are not doing octopus and not fast-forward. Need
1110 * a real merge.
1112 else if (!remoteheads->next && !common->next && option_commit) {
1114 * We are not doing octopus, not fast-forward, and have
1115 * only one common.
1117 refresh_cache(REFRESH_QUIET);
1118 if (allow_trivial && !fast_forward_only) {
1119 /* See if it is really trivial. */
1120 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1121 printf("Trying really trivial in-index merge...\n");
1122 if (!read_tree_trivial(common->item->object.sha1,
1123 head, remoteheads->item->object.sha1))
1124 return merge_trivial();
1125 printf("Nope.\n");
1127 } else {
1129 * An octopus. If we can reach all the remote we are up
1130 * to date.
1132 int up_to_date = 1;
1133 struct commit_list *j;
1135 for (j = remoteheads; j; j = j->next) {
1136 struct commit_list *common_one;
1139 * Here we *have* to calculate the individual
1140 * merge_bases again, otherwise "git merge HEAD^
1141 * HEAD^^" would be missed.
1143 common_one = get_merge_bases(lookup_commit(head),
1144 j->item, 1);
1145 if (hashcmp(common_one->item->object.sha1,
1146 j->item->object.sha1)) {
1147 up_to_date = 0;
1148 break;
1151 if (up_to_date) {
1152 finish_up_to_date("Already up-to-date. Yeeah!");
1153 return 0;
1157 if (fast_forward_only)
1158 die("Not possible to fast-forward, aborting.");
1160 /* We are going to make a new commit. */
1161 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1164 * At this point, we need a real merge. No matter what strategy
1165 * we use, it would operate on the index, possibly affecting the
1166 * working tree, and when resolved cleanly, have the desired
1167 * tree in the index -- this means that the index must be in
1168 * sync with the head commit. The strategies are responsible
1169 * to ensure this.
1171 if (use_strategies_nr != 1) {
1173 * Stash away the local changes so that we can try more
1174 * than one.
1176 save_state();
1177 } else {
1178 memcpy(stash, null_sha1, 20);
1181 for (i = 0; i < use_strategies_nr; i++) {
1182 int ret;
1183 if (i) {
1184 printf("Rewinding the tree to pristine...\n");
1185 restore_state();
1187 if (use_strategies_nr != 1)
1188 printf("Trying merge strategy %s...\n",
1189 use_strategies[i]->name);
1191 * Remember which strategy left the state in the working
1192 * tree.
1194 wt_strategy = use_strategies[i]->name;
1196 ret = try_merge_strategy(use_strategies[i]->name,
1197 common, head_arg);
1198 if (!option_commit && !ret) {
1199 merge_was_ok = 1;
1201 * This is necessary here just to avoid writing
1202 * the tree, but later we will *not* exit with
1203 * status code 1 because merge_was_ok is set.
1205 ret = 1;
1208 if (ret) {
1210 * The backend exits with 1 when conflicts are
1211 * left to be resolved, with 2 when it does not
1212 * handle the given merge at all.
1214 if (ret == 1) {
1215 int cnt = evaluate_result();
1217 if (best_cnt <= 0 || cnt <= best_cnt) {
1218 best_strategy = use_strategies[i]->name;
1219 best_cnt = cnt;
1222 if (merge_was_ok)
1223 break;
1224 else
1225 continue;
1228 /* Automerge succeeded. */
1229 write_tree_trivial(result_tree);
1230 automerge_was_ok = 1;
1231 break;
1235 * If we have a resulting tree, that means the strategy module
1236 * auto resolved the merge cleanly.
1238 if (automerge_was_ok)
1239 return finish_automerge(common, result_tree, wt_strategy);
1242 * Pick the result from the best strategy and have the user fix
1243 * it up.
1245 if (!best_strategy) {
1246 restore_state();
1247 if (use_strategies_nr > 1)
1248 fprintf(stderr,
1249 "No merge strategy handled the merge.\n");
1250 else
1251 fprintf(stderr, "Merge with strategy %s failed.\n",
1252 use_strategies[0]->name);
1253 return 2;
1254 } else if (best_strategy == wt_strategy)
1255 ; /* We already have its result in the working tree. */
1256 else {
1257 printf("Rewinding the tree to pristine...\n");
1258 restore_state();
1259 printf("Using the %s to prepare resolving by hand.\n",
1260 best_strategy);
1261 try_merge_strategy(best_strategy, common, head_arg);
1264 if (squash)
1265 finish(NULL, NULL);
1266 else {
1267 int fd;
1268 struct commit_list *j;
1270 for (j = remoteheads; j; j = j->next)
1271 strbuf_addf(&buf, "%s\n",
1272 sha1_to_hex(j->item->object.sha1));
1273 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1274 if (fd < 0)
1275 die_errno("Could not open '%s' for writing",
1276 git_path("MERGE_HEAD"));
1277 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1278 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1279 close(fd);
1280 strbuf_addch(&merge_msg, '\n');
1281 fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1282 if (fd < 0)
1283 die_errno("Could not open '%s' for writing",
1284 git_path("MERGE_MSG"));
1285 if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1286 merge_msg.len)
1287 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1288 close(fd);
1289 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1290 if (fd < 0)
1291 die_errno("Could not open '%s' for writing",
1292 git_path("MERGE_MODE"));
1293 strbuf_reset(&buf);
1294 if (!allow_fast_forward)
1295 strbuf_addf(&buf, "no-ff");
1296 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1297 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1298 close(fd);
1301 if (merge_was_ok) {
1302 fprintf(stderr, "Automatic merge went well; "
1303 "stopped before committing as requested\n");
1304 return 0;
1305 } else
1306 return suggest_conflicts();