merge: use return value of resolve_ref() to determine if HEAD is invalid
[git/jrn.git] / builtin / merge.c
blobc371484ab6b779d183534a04a57cdb3c190fc9a9
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"
28 #include "remote.h"
30 #define DEFAULT_TWOHEAD (1<<0)
31 #define DEFAULT_OCTOPUS (1<<1)
32 #define NO_FAST_FORWARD (1<<2)
33 #define NO_TRIVIAL (1<<3)
35 struct strategy {
36 const char *name;
37 unsigned attr;
40 static const char * const builtin_merge_usage[] = {
41 "git merge [options] [<commit>...]",
42 "git merge [options] <msg> HEAD <commit>",
43 "git merge --abort",
44 NULL
47 static int show_diffstat = 1, shortlog_len, squash;
48 static int option_commit = 1, allow_fast_forward = 1;
49 static int fast_forward_only;
50 static int allow_trivial = 1, have_message;
51 static struct strbuf merge_msg;
52 static struct commit_list *remoteheads;
53 static unsigned char head[20];
54 static struct strategy **use_strategies;
55 static size_t use_strategies_nr, use_strategies_alloc;
56 static const char **xopts;
57 static size_t xopts_nr, xopts_alloc;
58 static const char *branch;
59 static char *branch_mergeoptions;
60 static int option_renormalize;
61 static int verbosity;
62 static int allow_rerere_auto;
63 static int abort_current_merge;
64 static int show_progress = -1;
65 static int default_to_upstream;
67 static struct strategy all_strategy[] = {
68 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
69 { "octopus", DEFAULT_OCTOPUS },
70 { "resolve", 0 },
71 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
72 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
75 static const char *pull_twohead, *pull_octopus;
77 static int option_parse_message(const struct option *opt,
78 const char *arg, int unset)
80 struct strbuf *buf = opt->value;
82 if (unset)
83 strbuf_setlen(buf, 0);
84 else if (arg) {
85 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
86 have_message = 1;
87 } else
88 return error(_("switch `m' requires a value"));
89 return 0;
92 static struct strategy *get_strategy(const char *name)
94 int i;
95 struct strategy *ret;
96 static struct cmdnames main_cmds, other_cmds;
97 static int loaded;
99 if (!name)
100 return NULL;
102 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
103 if (!strcmp(name, all_strategy[i].name))
104 return &all_strategy[i];
106 if (!loaded) {
107 struct cmdnames not_strategies;
108 loaded = 1;
110 memset(&not_strategies, 0, sizeof(struct cmdnames));
111 load_command_list("git-merge-", &main_cmds, &other_cmds);
112 for (i = 0; i < main_cmds.cnt; i++) {
113 int j, found = 0;
114 struct cmdname *ent = main_cmds.names[i];
115 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
116 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
117 && !all_strategy[j].name[ent->len])
118 found = 1;
119 if (!found)
120 add_cmdname(&not_strategies, ent->name, ent->len);
122 exclude_cmds(&main_cmds, &not_strategies);
124 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
125 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
126 fprintf(stderr, _("Available strategies are:"));
127 for (i = 0; i < main_cmds.cnt; i++)
128 fprintf(stderr, " %s", main_cmds.names[i]->name);
129 fprintf(stderr, ".\n");
130 if (other_cmds.cnt) {
131 fprintf(stderr, _("Available custom strategies are:"));
132 for (i = 0; i < other_cmds.cnt; i++)
133 fprintf(stderr, " %s", other_cmds.names[i]->name);
134 fprintf(stderr, ".\n");
136 exit(1);
139 ret = xcalloc(1, sizeof(struct strategy));
140 ret->name = xstrdup(name);
141 ret->attr = NO_TRIVIAL;
142 return ret;
145 static void append_strategy(struct strategy *s)
147 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
148 use_strategies[use_strategies_nr++] = s;
151 static int option_parse_strategy(const struct option *opt,
152 const char *name, int unset)
154 if (unset)
155 return 0;
157 append_strategy(get_strategy(name));
158 return 0;
161 static int option_parse_x(const struct option *opt,
162 const char *arg, int unset)
164 if (unset)
165 return 0;
167 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
168 xopts[xopts_nr++] = xstrdup(arg);
169 return 0;
172 static int option_parse_n(const struct option *opt,
173 const char *arg, int unset)
175 show_diffstat = unset;
176 return 0;
179 static struct option builtin_merge_options[] = {
180 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
181 "do not show a diffstat at the end of the merge",
182 PARSE_OPT_NOARG, option_parse_n },
183 OPT_BOOLEAN(0, "stat", &show_diffstat,
184 "show a diffstat at the end of the merge"),
185 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
186 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
187 "add (at most <n>) entries from shortlog to merge commit message",
188 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
189 OPT_BOOLEAN(0, "squash", &squash,
190 "create a single commit instead of doing a merge"),
191 OPT_BOOLEAN(0, "commit", &option_commit,
192 "perform a commit if the merge succeeds (default)"),
193 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
194 "allow fast-forward (default)"),
195 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
196 "abort if fast-forward is not possible"),
197 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
198 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
199 "merge strategy to use", option_parse_strategy),
200 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
201 "option for selected merge strategy", option_parse_x),
202 OPT_CALLBACK('m', "message", &merge_msg, "message",
203 "merge commit message (for a non-fast-forward merge)",
204 option_parse_message),
205 OPT__VERBOSITY(&verbosity),
206 OPT_BOOLEAN(0, "abort", &abort_current_merge,
207 "abort the current in-progress merge"),
208 OPT_SET_INT(0, "progress", &show_progress, "force progress reporting", 1),
209 OPT_END()
212 /* Cleans up metadata that is uninteresting after a succeeded merge. */
213 static void drop_save(void)
215 unlink(git_path("MERGE_HEAD"));
216 unlink(git_path("MERGE_MSG"));
217 unlink(git_path("MERGE_MODE"));
220 static int save_state(unsigned char *stash)
222 int len;
223 struct child_process cp;
224 struct strbuf buffer = STRBUF_INIT;
225 const char *argv[] = {"stash", "create", NULL};
227 memset(&cp, 0, sizeof(cp));
228 cp.argv = argv;
229 cp.out = -1;
230 cp.git_cmd = 1;
232 if (start_command(&cp))
233 die(_("could not run stash."));
234 len = strbuf_read(&buffer, cp.out, 1024);
235 close(cp.out);
237 if (finish_command(&cp) || len < 0)
238 die(_("stash failed"));
239 else if (!len) /* no changes */
240 return -1;
241 strbuf_setlen(&buffer, buffer.len-1);
242 if (get_sha1(buffer.buf, stash))
243 die(_("not a valid object: %s"), buffer.buf);
244 return 0;
247 static void read_empty(unsigned const char *sha1, int verbose)
249 int i = 0;
250 const char *args[7];
252 args[i++] = "read-tree";
253 if (verbose)
254 args[i++] = "-v";
255 args[i++] = "-m";
256 args[i++] = "-u";
257 args[i++] = EMPTY_TREE_SHA1_HEX;
258 args[i++] = sha1_to_hex(sha1);
259 args[i] = NULL;
261 if (run_command_v_opt(args, RUN_GIT_CMD))
262 die(_("read-tree failed"));
265 static void reset_hard(unsigned const char *sha1, int verbose)
267 int i = 0;
268 const char *args[6];
270 args[i++] = "read-tree";
271 if (verbose)
272 args[i++] = "-v";
273 args[i++] = "--reset";
274 args[i++] = "-u";
275 args[i++] = sha1_to_hex(sha1);
276 args[i] = NULL;
278 if (run_command_v_opt(args, RUN_GIT_CMD))
279 die(_("read-tree failed"));
282 static void restore_state(const unsigned char *stash)
284 struct strbuf sb = STRBUF_INIT;
285 const char *args[] = { "stash", "apply", NULL, NULL };
287 if (is_null_sha1(stash))
288 return;
290 reset_hard(head, 1);
292 args[2] = sha1_to_hex(stash);
295 * It is OK to ignore error here, for example when there was
296 * nothing to restore.
298 run_command_v_opt(args, RUN_GIT_CMD);
300 strbuf_release(&sb);
301 refresh_cache(REFRESH_QUIET);
304 /* This is called when no merge was necessary. */
305 static void finish_up_to_date(const char *msg)
307 if (verbosity >= 0)
308 printf("%s%s\n", squash ? _(" (nothing to squash)") : "", msg);
309 drop_save();
312 static void squash_message(void)
314 struct rev_info rev;
315 struct commit *commit;
316 struct strbuf out = STRBUF_INIT;
317 struct commit_list *j;
318 int fd;
319 struct pretty_print_context ctx = {0};
321 printf(_("Squash commit -- not updating HEAD\n"));
322 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
323 if (fd < 0)
324 die_errno(_("Could not write to '%s'"), git_path("SQUASH_MSG"));
326 init_revisions(&rev, NULL);
327 rev.ignore_merges = 1;
328 rev.commit_format = CMIT_FMT_MEDIUM;
330 commit = lookup_commit(head);
331 commit->object.flags |= UNINTERESTING;
332 add_pending_object(&rev, &commit->object, NULL);
334 for (j = remoteheads; j; j = j->next)
335 add_pending_object(&rev, &j->item->object, NULL);
337 setup_revisions(0, NULL, &rev, NULL);
338 if (prepare_revision_walk(&rev))
339 die(_("revision walk setup failed"));
341 ctx.abbrev = rev.abbrev;
342 ctx.date_mode = rev.date_mode;
343 ctx.fmt = rev.commit_format;
345 strbuf_addstr(&out, "Squashed commit of the following:\n");
346 while ((commit = get_revision(&rev)) != NULL) {
347 strbuf_addch(&out, '\n');
348 strbuf_addf(&out, "commit %s\n",
349 sha1_to_hex(commit->object.sha1));
350 pretty_print_commit(&ctx, commit, &out);
352 if (write(fd, out.buf, out.len) < 0)
353 die_errno(_("Writing SQUASH_MSG"));
354 if (close(fd))
355 die_errno(_("Finishing SQUASH_MSG"));
356 strbuf_release(&out);
359 static void finish(const unsigned char *new_head, const char *msg)
361 struct strbuf reflog_message = STRBUF_INIT;
363 if (!msg)
364 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
365 else {
366 if (verbosity >= 0)
367 printf("%s\n", msg);
368 strbuf_addf(&reflog_message, "%s: %s",
369 getenv("GIT_REFLOG_ACTION"), msg);
371 if (squash) {
372 squash_message();
373 } else {
374 if (verbosity >= 0 && !merge_msg.len)
375 printf(_("No merge message -- not updating HEAD\n"));
376 else {
377 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
378 update_ref(reflog_message.buf, "HEAD",
379 new_head, head, 0,
380 DIE_ON_ERR);
382 * We ignore errors in 'gc --auto', since the
383 * user should see them.
385 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
388 if (new_head && show_diffstat) {
389 struct diff_options opts;
390 diff_setup(&opts);
391 opts.output_format |=
392 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
393 opts.detect_rename = DIFF_DETECT_RENAME;
394 if (diff_use_color_default > 0)
395 DIFF_OPT_SET(&opts, COLOR_DIFF);
396 if (diff_setup_done(&opts) < 0)
397 die(_("diff_setup_done failed"));
398 diff_tree_sha1(head, new_head, "", &opts);
399 diffcore_std(&opts);
400 diff_flush(&opts);
403 /* Run a post-merge hook */
404 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
406 strbuf_release(&reflog_message);
409 /* Get the name for the merge commit's message. */
410 static void merge_name(const char *remote, struct strbuf *msg)
412 struct object *remote_head;
413 unsigned char branch_head[20], buf_sha[20];
414 struct strbuf buf = STRBUF_INIT;
415 struct strbuf bname = STRBUF_INIT;
416 const char *ptr;
417 char *found_ref;
418 int len, early;
420 strbuf_branchname(&bname, remote);
421 remote = bname.buf;
423 memset(branch_head, 0, sizeof(branch_head));
424 remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
425 if (!remote_head)
426 die(_("'%s' does not point to a commit"), remote);
428 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
429 if (!prefixcmp(found_ref, "refs/heads/")) {
430 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
431 sha1_to_hex(branch_head), remote);
432 goto cleanup;
434 if (!prefixcmp(found_ref, "refs/remotes/")) {
435 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
436 sha1_to_hex(branch_head), remote);
437 goto cleanup;
441 /* See if remote matches <name>^^^.. or <name>~<number> */
442 for (len = 0, ptr = remote + strlen(remote);
443 remote < ptr && ptr[-1] == '^';
444 ptr--)
445 len++;
446 if (len)
447 early = 1;
448 else {
449 early = 0;
450 ptr = strrchr(remote, '~');
451 if (ptr) {
452 int seen_nonzero = 0;
454 len++; /* count ~ */
455 while (*++ptr && isdigit(*ptr)) {
456 seen_nonzero |= (*ptr != '0');
457 len++;
459 if (*ptr)
460 len = 0; /* not ...~<number> */
461 else if (seen_nonzero)
462 early = 1;
463 else if (len == 1)
464 early = 1; /* "name~" is "name~1"! */
467 if (len) {
468 struct strbuf truname = STRBUF_INIT;
469 strbuf_addstr(&truname, "refs/heads/");
470 strbuf_addstr(&truname, remote);
471 strbuf_setlen(&truname, truname.len - len);
472 if (resolve_ref(truname.buf, buf_sha, 1, NULL)) {
473 strbuf_addf(msg,
474 "%s\t\tbranch '%s'%s of .\n",
475 sha1_to_hex(remote_head->sha1),
476 truname.buf + 11,
477 (early ? " (early part)" : ""));
478 strbuf_release(&truname);
479 goto cleanup;
483 if (!strcmp(remote, "FETCH_HEAD") &&
484 !access(git_path("FETCH_HEAD"), R_OK)) {
485 FILE *fp;
486 struct strbuf line = STRBUF_INIT;
487 char *ptr;
489 fp = fopen(git_path("FETCH_HEAD"), "r");
490 if (!fp)
491 die_errno(_("could not open '%s' for reading"),
492 git_path("FETCH_HEAD"));
493 strbuf_getline(&line, fp, '\n');
494 fclose(fp);
495 ptr = strstr(line.buf, "\tnot-for-merge\t");
496 if (ptr)
497 strbuf_remove(&line, ptr-line.buf+1, 13);
498 strbuf_addbuf(msg, &line);
499 strbuf_release(&line);
500 goto cleanup;
502 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
503 sha1_to_hex(remote_head->sha1), remote);
504 cleanup:
505 strbuf_release(&buf);
506 strbuf_release(&bname);
509 static void parse_branch_merge_options(char *bmo)
511 const char **argv;
512 int argc;
514 if (!bmo)
515 return;
516 argc = split_cmdline(bmo, &argv);
517 if (argc < 0)
518 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
519 split_cmdline_strerror(argc));
520 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
521 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
522 argc++;
523 argv[0] = "branch.*.mergeoptions";
524 parse_options(argc, argv, NULL, builtin_merge_options,
525 builtin_merge_usage, 0);
526 free(argv);
529 static int git_merge_config(const char *k, const char *v, void *cb)
531 if (branch && !prefixcmp(k, "branch.") &&
532 !prefixcmp(k + 7, branch) &&
533 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
534 free(branch_mergeoptions);
535 branch_mergeoptions = xstrdup(v);
536 return 0;
539 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
540 show_diffstat = git_config_bool(k, v);
541 else if (!strcmp(k, "pull.twohead"))
542 return git_config_string(&pull_twohead, k, v);
543 else if (!strcmp(k, "pull.octopus"))
544 return git_config_string(&pull_octopus, k, v);
545 else if (!strcmp(k, "merge.renormalize"))
546 option_renormalize = git_config_bool(k, v);
547 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary")) {
548 int is_bool;
549 shortlog_len = git_config_bool_or_int(k, v, &is_bool);
550 if (!is_bool && shortlog_len < 0)
551 return error(_("%s: negative length %s"), k, v);
552 if (is_bool && shortlog_len)
553 shortlog_len = DEFAULT_MERGE_LOG_LEN;
554 return 0;
555 } else if (!strcmp(k, "merge.ff")) {
556 int boolval = git_config_maybe_bool(k, v);
557 if (0 <= boolval) {
558 allow_fast_forward = boolval;
559 } else if (v && !strcmp(v, "only")) {
560 allow_fast_forward = 1;
561 fast_forward_only = 1;
562 } /* do not barf on values from future versions of git */
563 return 0;
564 } else if (!strcmp(k, "merge.defaulttoupstream")) {
565 default_to_upstream = git_config_bool(k, v);
566 return 0;
568 return git_diff_ui_config(k, v, cb);
571 static int read_tree_trivial(unsigned char *common, unsigned char *head,
572 unsigned char *one)
574 int i, nr_trees = 0;
575 struct tree *trees[MAX_UNPACK_TREES];
576 struct tree_desc t[MAX_UNPACK_TREES];
577 struct unpack_trees_options opts;
579 memset(&opts, 0, sizeof(opts));
580 opts.head_idx = 2;
581 opts.src_index = &the_index;
582 opts.dst_index = &the_index;
583 opts.update = 1;
584 opts.verbose_update = 1;
585 opts.trivial_merges_only = 1;
586 opts.merge = 1;
587 trees[nr_trees] = parse_tree_indirect(common);
588 if (!trees[nr_trees++])
589 return -1;
590 trees[nr_trees] = parse_tree_indirect(head);
591 if (!trees[nr_trees++])
592 return -1;
593 trees[nr_trees] = parse_tree_indirect(one);
594 if (!trees[nr_trees++])
595 return -1;
596 opts.fn = threeway_merge;
597 cache_tree_free(&active_cache_tree);
598 for (i = 0; i < nr_trees; i++) {
599 parse_tree(trees[i]);
600 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
602 if (unpack_trees(nr_trees, t, &opts))
603 return -1;
604 return 0;
607 static void write_tree_trivial(unsigned char *sha1)
609 if (write_cache_as_tree(sha1, 0, NULL))
610 die(_("git write-tree failed to write a tree"));
613 static const char *merge_argument(struct commit *commit)
615 if (commit)
616 return sha1_to_hex(commit->object.sha1);
617 else
618 return EMPTY_TREE_SHA1_HEX;
621 int try_merge_command(const char *strategy, size_t xopts_nr,
622 const char **xopts, struct commit_list *common,
623 const char *head_arg, struct commit_list *remotes)
625 const char **args;
626 int i = 0, x = 0, ret;
627 struct commit_list *j;
628 struct strbuf buf = STRBUF_INIT;
630 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
631 commit_list_count(remotes)) * sizeof(char *));
632 strbuf_addf(&buf, "merge-%s", strategy);
633 args[i++] = buf.buf;
634 for (x = 0; x < xopts_nr; x++) {
635 char *s = xmalloc(strlen(xopts[x])+2+1);
636 strcpy(s, "--");
637 strcpy(s+2, xopts[x]);
638 args[i++] = s;
640 for (j = common; j; j = j->next)
641 args[i++] = xstrdup(merge_argument(j->item));
642 args[i++] = "--";
643 args[i++] = head_arg;
644 for (j = remotes; j; j = j->next)
645 args[i++] = xstrdup(merge_argument(j->item));
646 args[i] = NULL;
647 ret = run_command_v_opt(args, RUN_GIT_CMD);
648 strbuf_release(&buf);
649 i = 1;
650 for (x = 0; x < xopts_nr; x++)
651 free((void *)args[i++]);
652 for (j = common; j; j = j->next)
653 free((void *)args[i++]);
654 i += 2;
655 for (j = remotes; j; j = j->next)
656 free((void *)args[i++]);
657 free(args);
658 discard_cache();
659 if (read_cache() < 0)
660 die(_("failed to read the cache"));
661 resolve_undo_clear();
663 return ret;
666 static int try_merge_strategy(const char *strategy, struct commit_list *common,
667 const char *head_arg)
669 int index_fd;
670 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
672 index_fd = hold_locked_index(lock, 1);
673 refresh_cache(REFRESH_QUIET);
674 if (active_cache_changed &&
675 (write_cache(index_fd, active_cache, active_nr) ||
676 commit_locked_index(lock)))
677 return error(_("Unable to write index."));
678 rollback_lock_file(lock);
680 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
681 int clean, x;
682 struct commit *result;
683 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
684 int index_fd;
685 struct commit_list *reversed = NULL;
686 struct merge_options o;
687 struct commit_list *j;
689 if (remoteheads->next) {
690 error(_("Not handling anything other than two heads merge."));
691 return 2;
694 init_merge_options(&o);
695 if (!strcmp(strategy, "subtree"))
696 o.subtree_shift = "";
698 o.renormalize = option_renormalize;
699 o.show_rename_progress =
700 show_progress == -1 ? isatty(2) : show_progress;
702 for (x = 0; x < xopts_nr; x++)
703 if (parse_merge_opt(&o, xopts[x]))
704 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
706 o.branch1 = head_arg;
707 o.branch2 = remoteheads->item->util;
709 for (j = common; j; j = j->next)
710 commit_list_insert(j->item, &reversed);
712 index_fd = hold_locked_index(lock, 1);
713 clean = merge_recursive(&o, lookup_commit(head),
714 remoteheads->item, reversed, &result);
715 if (active_cache_changed &&
716 (write_cache(index_fd, active_cache, active_nr) ||
717 commit_locked_index(lock)))
718 die (_("unable to write %s"), get_index_file());
719 rollback_lock_file(lock);
720 return clean ? 0 : 1;
721 } else {
722 return try_merge_command(strategy, xopts_nr, xopts,
723 common, head_arg, remoteheads);
727 static void count_diff_files(struct diff_queue_struct *q,
728 struct diff_options *opt, void *data)
730 int *count = data;
732 (*count) += q->nr;
735 static int count_unmerged_entries(void)
737 int i, ret = 0;
739 for (i = 0; i < active_nr; i++)
740 if (ce_stage(active_cache[i]))
741 ret++;
743 return ret;
746 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
748 struct tree *trees[MAX_UNPACK_TREES];
749 struct unpack_trees_options opts;
750 struct tree_desc t[MAX_UNPACK_TREES];
751 int i, fd, nr_trees = 0;
752 struct dir_struct dir;
753 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
755 refresh_cache(REFRESH_QUIET);
757 fd = hold_locked_index(lock_file, 1);
759 memset(&trees, 0, sizeof(trees));
760 memset(&opts, 0, sizeof(opts));
761 memset(&t, 0, sizeof(t));
762 memset(&dir, 0, sizeof(dir));
763 dir.flags |= DIR_SHOW_IGNORED;
764 dir.exclude_per_dir = ".gitignore";
765 opts.dir = &dir;
767 opts.head_idx = 1;
768 opts.src_index = &the_index;
769 opts.dst_index = &the_index;
770 opts.update = 1;
771 opts.verbose_update = 1;
772 opts.merge = 1;
773 opts.fn = twoway_merge;
774 setup_unpack_trees_porcelain(&opts, "merge");
776 trees[nr_trees] = parse_tree_indirect(head);
777 if (!trees[nr_trees++])
778 return -1;
779 trees[nr_trees] = parse_tree_indirect(remote);
780 if (!trees[nr_trees++])
781 return -1;
782 for (i = 0; i < nr_trees; i++) {
783 parse_tree(trees[i]);
784 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
786 if (unpack_trees(nr_trees, t, &opts))
787 return -1;
788 if (write_cache(fd, active_cache, active_nr) ||
789 commit_locked_index(lock_file))
790 die(_("unable to write new index file"));
791 return 0;
794 static void split_merge_strategies(const char *string, struct strategy **list,
795 int *nr, int *alloc)
797 char *p, *q, *buf;
799 if (!string)
800 return;
802 buf = xstrdup(string);
803 q = buf;
804 for (;;) {
805 p = strchr(q, ' ');
806 if (!p) {
807 ALLOC_GROW(*list, *nr + 1, *alloc);
808 (*list)[(*nr)++].name = xstrdup(q);
809 free(buf);
810 return;
811 } else {
812 *p = '\0';
813 ALLOC_GROW(*list, *nr + 1, *alloc);
814 (*list)[(*nr)++].name = xstrdup(q);
815 q = ++p;
820 static void add_strategies(const char *string, unsigned attr)
822 struct strategy *list = NULL;
823 int list_alloc = 0, list_nr = 0, i;
825 memset(&list, 0, sizeof(list));
826 split_merge_strategies(string, &list, &list_nr, &list_alloc);
827 if (list) {
828 for (i = 0; i < list_nr; i++)
829 append_strategy(get_strategy(list[i].name));
830 return;
832 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
833 if (all_strategy[i].attr & attr)
834 append_strategy(&all_strategy[i]);
838 static void write_merge_msg(void)
840 int fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
841 if (fd < 0)
842 die_errno(_("Could not open '%s' for writing"),
843 git_path("MERGE_MSG"));
844 if (write_in_full(fd, merge_msg.buf, merge_msg.len) != merge_msg.len)
845 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
846 close(fd);
849 static void read_merge_msg(void)
851 strbuf_reset(&merge_msg);
852 if (strbuf_read_file(&merge_msg, git_path("MERGE_MSG"), 0) < 0)
853 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
856 static void run_prepare_commit_msg(void)
858 write_merge_msg();
859 run_hook(get_index_file(), "prepare-commit-msg",
860 git_path("MERGE_MSG"), "merge", NULL, NULL);
861 read_merge_msg();
864 static int merge_trivial(void)
866 unsigned char result_tree[20], result_commit[20];
867 struct commit_list *parent = xmalloc(sizeof(*parent));
869 write_tree_trivial(result_tree);
870 printf(_("Wonderful.\n"));
871 parent->item = lookup_commit(head);
872 parent->next = xmalloc(sizeof(*parent->next));
873 parent->next->item = remoteheads->item;
874 parent->next->next = NULL;
875 run_prepare_commit_msg();
876 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
877 finish(result_commit, "In-index merge");
878 drop_save();
879 return 0;
882 static int finish_automerge(struct commit_list *common,
883 unsigned char *result_tree,
884 const char *wt_strategy)
886 struct commit_list *parents = NULL, *j;
887 struct strbuf buf = STRBUF_INIT;
888 unsigned char result_commit[20];
890 free_commit_list(common);
891 if (allow_fast_forward) {
892 parents = remoteheads;
893 commit_list_insert(lookup_commit(head), &parents);
894 parents = reduce_heads(parents);
895 } else {
896 struct commit_list **pptr = &parents;
898 pptr = &commit_list_insert(lookup_commit(head),
899 pptr)->next;
900 for (j = remoteheads; j; j = j->next)
901 pptr = &commit_list_insert(j->item, pptr)->next;
903 free_commit_list(remoteheads);
904 strbuf_addch(&merge_msg, '\n');
905 run_prepare_commit_msg();
906 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
907 strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
908 finish(result_commit, buf.buf);
909 strbuf_release(&buf);
910 drop_save();
911 return 0;
914 static int suggest_conflicts(int renormalizing)
916 FILE *fp;
917 int pos;
919 fp = fopen(git_path("MERGE_MSG"), "a");
920 if (!fp)
921 die_errno(_("Could not open '%s' for writing"),
922 git_path("MERGE_MSG"));
923 fprintf(fp, "\nConflicts:\n");
924 for (pos = 0; pos < active_nr; pos++) {
925 struct cache_entry *ce = active_cache[pos];
927 if (ce_stage(ce)) {
928 fprintf(fp, "\t%s\n", ce->name);
929 while (pos + 1 < active_nr &&
930 !strcmp(ce->name,
931 active_cache[pos + 1]->name))
932 pos++;
935 fclose(fp);
936 rerere(allow_rerere_auto);
937 printf(_("Automatic merge failed; "
938 "fix conflicts and then commit the result.\n"));
939 return 1;
942 static struct commit *is_old_style_invocation(int argc, const char **argv)
944 struct commit *second_token = NULL;
945 if (argc > 2) {
946 unsigned char second_sha1[20];
948 if (get_sha1(argv[1], second_sha1))
949 return NULL;
950 second_token = lookup_commit_reference_gently(second_sha1, 0);
951 if (!second_token)
952 die(_("'%s' is not a commit"), argv[1]);
953 if (hashcmp(second_token->object.sha1, head))
954 return NULL;
956 return second_token;
959 static int evaluate_result(void)
961 int cnt = 0;
962 struct rev_info rev;
964 /* Check how many files differ. */
965 init_revisions(&rev, "");
966 setup_revisions(0, NULL, &rev, NULL);
967 rev.diffopt.output_format |=
968 DIFF_FORMAT_CALLBACK;
969 rev.diffopt.format_callback = count_diff_files;
970 rev.diffopt.format_callback_data = &cnt;
971 run_diff_files(&rev, 0);
974 * Check how many unmerged entries are
975 * there.
977 cnt += count_unmerged_entries();
979 return cnt;
983 * Pretend as if the user told us to merge with the tracking
984 * branch we have for the upstream of the current branch
986 static int setup_with_upstream(const char ***argv)
988 struct branch *branch = branch_get(NULL);
989 int i;
990 const char **args;
992 if (!branch)
993 die(_("No current branch."));
994 if (!branch->remote)
995 die(_("No remote for the current branch."));
996 if (!branch->merge_nr)
997 die(_("No default upstream defined for the current branch."));
999 args = xcalloc(branch->merge_nr + 1, sizeof(char *));
1000 for (i = 0; i < branch->merge_nr; i++) {
1001 if (!branch->merge[i]->dst)
1002 die(_("No remote tracking branch for %s from %s"),
1003 branch->merge[i]->src, branch->remote_name);
1004 args[i] = branch->merge[i]->dst;
1006 args[i] = NULL;
1007 *argv = args;
1008 return i;
1011 int cmd_merge(int argc, const char **argv, const char *prefix)
1013 unsigned char result_tree[20];
1014 unsigned char stash[20];
1015 struct strbuf buf = STRBUF_INIT;
1016 const char *head_arg;
1017 int flag, head_invalid = 0, i;
1018 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1019 struct commit_list *common = NULL;
1020 const char *best_strategy = NULL, *wt_strategy = NULL;
1021 struct commit_list **remotes = &remoteheads;
1023 if (argc == 2 && !strcmp(argv[1], "-h"))
1024 usage_with_options(builtin_merge_usage, builtin_merge_options);
1027 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1028 * current branch.
1030 branch = resolve_ref("HEAD", head, 0, &flag);
1031 if (branch && !prefixcmp(branch, "refs/heads/"))
1032 branch += 11;
1033 if (!branch || is_null_sha1(head))
1034 head_invalid = 1;
1036 git_config(git_merge_config, NULL);
1038 /* for color.ui */
1039 if (diff_use_color_default == -1)
1040 diff_use_color_default = git_use_color_default;
1042 if (branch_mergeoptions)
1043 parse_branch_merge_options(branch_mergeoptions);
1044 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1045 builtin_merge_usage, 0);
1047 if (verbosity < 0 && show_progress == -1)
1048 show_progress = 0;
1050 if (abort_current_merge) {
1051 int nargc = 2;
1052 const char *nargv[] = {"reset", "--merge", NULL};
1054 if (!file_exists(git_path("MERGE_HEAD")))
1055 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1057 /* Invoke 'git reset --merge' */
1058 return cmd_reset(nargc, nargv, prefix);
1061 if (read_cache_unmerged())
1062 die_resolve_conflict("merge");
1064 if (file_exists(git_path("MERGE_HEAD"))) {
1066 * There is no unmerged entry, don't advise 'git
1067 * add/rm <file>', just 'git commit'.
1069 if (advice_resolve_conflict)
1070 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1071 "Please, commit your changes before you can merge."));
1072 else
1073 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1075 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1076 if (advice_resolve_conflict)
1077 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1078 "Please, commit your changes before you can merge."));
1079 else
1080 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1082 resolve_undo_clear();
1084 if (verbosity < 0)
1085 show_diffstat = 0;
1087 if (squash) {
1088 if (!allow_fast_forward)
1089 die(_("You cannot combine --squash with --no-ff."));
1090 option_commit = 0;
1093 if (!allow_fast_forward && fast_forward_only)
1094 die(_("You cannot combine --no-ff with --ff-only."));
1096 if (!abort_current_merge) {
1097 if (!argc && default_to_upstream)
1098 argc = setup_with_upstream(&argv);
1099 else if (argc == 1 && !strcmp(argv[0], "-"))
1100 argv[0] = "@{-1}";
1102 if (!argc)
1103 usage_with_options(builtin_merge_usage,
1104 builtin_merge_options);
1107 * This could be traditional "merge <msg> HEAD <commit>..." and
1108 * the way we can tell it is to see if the second token is HEAD,
1109 * but some people might have misused the interface and used a
1110 * committish that is the same as HEAD there instead.
1111 * Traditional format never would have "-m" so it is an
1112 * additional safety measure to check for it.
1115 if (!have_message && is_old_style_invocation(argc, argv)) {
1116 strbuf_addstr(&merge_msg, argv[0]);
1117 head_arg = argv[1];
1118 argv += 2;
1119 argc -= 2;
1120 } else if (head_invalid) {
1121 struct object *remote_head;
1123 * If the merged head is a valid one there is no reason
1124 * to forbid "git merge" into a branch yet to be born.
1125 * We do the same for "git pull".
1127 if (argc != 1)
1128 die(_("Can merge only exactly one commit into "
1129 "empty head"));
1130 if (squash)
1131 die(_("Squash commit into empty head not supported yet"));
1132 if (!allow_fast_forward)
1133 die(_("Non-fast-forward commit does not make sense into "
1134 "an empty head"));
1135 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
1136 if (!remote_head)
1137 die(_("%s - not something we can merge"), argv[0]);
1138 read_empty(remote_head->sha1, 0);
1139 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
1140 DIE_ON_ERR);
1141 return 0;
1142 } else {
1143 struct strbuf merge_names = STRBUF_INIT;
1145 /* We are invoked directly as the first-class UI. */
1146 head_arg = "HEAD";
1149 * All the rest are the commits being merged;
1150 * prepare the standard merge summary message to
1151 * be appended to the given message. If remote
1152 * is invalid we will die later in the common
1153 * codepath so we discard the error in this
1154 * loop.
1156 for (i = 0; i < argc; i++)
1157 merge_name(argv[i], &merge_names);
1159 if (!have_message || shortlog_len) {
1160 fmt_merge_msg(&merge_names, &merge_msg, !have_message,
1161 shortlog_len);
1162 if (merge_msg.len)
1163 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1167 if (head_invalid || !argc)
1168 usage_with_options(builtin_merge_usage,
1169 builtin_merge_options);
1171 strbuf_addstr(&buf, "merge");
1172 for (i = 0; i < argc; i++)
1173 strbuf_addf(&buf, " %s", argv[i]);
1174 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1175 strbuf_reset(&buf);
1177 for (i = 0; i < argc; i++) {
1178 struct object *o;
1179 struct commit *commit;
1181 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
1182 if (!o)
1183 die(_("%s - not something we can merge"), argv[i]);
1184 commit = lookup_commit(o->sha1);
1185 commit->util = (void *)argv[i];
1186 remotes = &commit_list_insert(commit, remotes)->next;
1188 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1189 setenv(buf.buf, argv[i], 1);
1190 strbuf_reset(&buf);
1193 if (!use_strategies) {
1194 if (!remoteheads->next)
1195 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1196 else
1197 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1200 for (i = 0; i < use_strategies_nr; i++) {
1201 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1202 allow_fast_forward = 0;
1203 if (use_strategies[i]->attr & NO_TRIVIAL)
1204 allow_trivial = 0;
1207 if (!remoteheads->next)
1208 common = get_merge_bases(lookup_commit(head),
1209 remoteheads->item, 1);
1210 else {
1211 struct commit_list *list = remoteheads;
1212 commit_list_insert(lookup_commit(head), &list);
1213 common = get_octopus_merge_bases(list);
1214 free(list);
1217 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1218 DIE_ON_ERR);
1220 if (!common)
1221 ; /* No common ancestors found. We need a real merge. */
1222 else if (!remoteheads->next && !common->next &&
1223 common->item == remoteheads->item) {
1225 * If head can reach all the merge then we are up to date.
1226 * but first the most common case of merging one remote.
1228 finish_up_to_date("Already up-to-date.");
1229 return 0;
1230 } else if (allow_fast_forward && !remoteheads->next &&
1231 !common->next &&
1232 !hashcmp(common->item->object.sha1, head)) {
1233 /* Again the most common case of merging one remote. */
1234 struct strbuf msg = STRBUF_INIT;
1235 struct object *o;
1236 char hex[41];
1238 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1240 if (verbosity >= 0)
1241 printf(_("Updating %s..%s\n"),
1242 hex,
1243 find_unique_abbrev(remoteheads->item->object.sha1,
1244 DEFAULT_ABBREV));
1245 strbuf_addstr(&msg, "Fast-forward");
1246 if (have_message)
1247 strbuf_addstr(&msg,
1248 " (no commit created; -m option ignored)");
1249 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1250 0, NULL, OBJ_COMMIT);
1251 if (!o)
1252 return 1;
1254 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1255 return 1;
1257 finish(o->sha1, msg.buf);
1258 drop_save();
1259 return 0;
1260 } else if (!remoteheads->next && common->next)
1263 * We are not doing octopus and not fast-forward. Need
1264 * a real merge.
1266 else if (!remoteheads->next && !common->next && option_commit) {
1268 * We are not doing octopus, not fast-forward, and have
1269 * only one common.
1271 refresh_cache(REFRESH_QUIET);
1272 if (allow_trivial && !fast_forward_only) {
1273 /* See if it is really trivial. */
1274 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1275 printf(_("Trying really trivial in-index merge...\n"));
1276 if (!read_tree_trivial(common->item->object.sha1,
1277 head, remoteheads->item->object.sha1))
1278 return merge_trivial();
1279 printf(_("Nope.\n"));
1281 } else {
1283 * An octopus. If we can reach all the remote we are up
1284 * to date.
1286 int up_to_date = 1;
1287 struct commit_list *j;
1289 for (j = remoteheads; j; j = j->next) {
1290 struct commit_list *common_one;
1293 * Here we *have* to calculate the individual
1294 * merge_bases again, otherwise "git merge HEAD^
1295 * HEAD^^" would be missed.
1297 common_one = get_merge_bases(lookup_commit(head),
1298 j->item, 1);
1299 if (hashcmp(common_one->item->object.sha1,
1300 j->item->object.sha1)) {
1301 up_to_date = 0;
1302 break;
1305 if (up_to_date) {
1306 finish_up_to_date("Already up-to-date. Yeeah!");
1307 return 0;
1311 if (fast_forward_only)
1312 die(_("Not possible to fast-forward, aborting."));
1314 /* We are going to make a new commit. */
1315 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1318 * At this point, we need a real merge. No matter what strategy
1319 * we use, it would operate on the index, possibly affecting the
1320 * working tree, and when resolved cleanly, have the desired
1321 * tree in the index -- this means that the index must be in
1322 * sync with the head commit. The strategies are responsible
1323 * to ensure this.
1325 if (use_strategies_nr == 1 ||
1327 * Stash away the local changes so that we can try more than one.
1329 save_state(stash))
1330 hashcpy(stash, null_sha1);
1332 for (i = 0; i < use_strategies_nr; i++) {
1333 int ret;
1334 if (i) {
1335 printf(_("Rewinding the tree to pristine...\n"));
1336 restore_state(stash);
1338 if (use_strategies_nr != 1)
1339 printf(_("Trying merge strategy %s...\n"),
1340 use_strategies[i]->name);
1342 * Remember which strategy left the state in the working
1343 * tree.
1345 wt_strategy = use_strategies[i]->name;
1347 ret = try_merge_strategy(use_strategies[i]->name,
1348 common, head_arg);
1349 if (!option_commit && !ret) {
1350 merge_was_ok = 1;
1352 * This is necessary here just to avoid writing
1353 * the tree, but later we will *not* exit with
1354 * status code 1 because merge_was_ok is set.
1356 ret = 1;
1359 if (ret) {
1361 * The backend exits with 1 when conflicts are
1362 * left to be resolved, with 2 when it does not
1363 * handle the given merge at all.
1365 if (ret == 1) {
1366 int cnt = evaluate_result();
1368 if (best_cnt <= 0 || cnt <= best_cnt) {
1369 best_strategy = use_strategies[i]->name;
1370 best_cnt = cnt;
1373 if (merge_was_ok)
1374 break;
1375 else
1376 continue;
1379 /* Automerge succeeded. */
1380 write_tree_trivial(result_tree);
1381 automerge_was_ok = 1;
1382 break;
1386 * If we have a resulting tree, that means the strategy module
1387 * auto resolved the merge cleanly.
1389 if (automerge_was_ok)
1390 return finish_automerge(common, result_tree, wt_strategy);
1393 * Pick the result from the best strategy and have the user fix
1394 * it up.
1396 if (!best_strategy) {
1397 restore_state(stash);
1398 if (use_strategies_nr > 1)
1399 fprintf(stderr,
1400 _("No merge strategy handled the merge.\n"));
1401 else
1402 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1403 use_strategies[0]->name);
1404 return 2;
1405 } else if (best_strategy == wt_strategy)
1406 ; /* We already have its result in the working tree. */
1407 else {
1408 printf(_("Rewinding the tree to pristine...\n"));
1409 restore_state(stash);
1410 printf(_("Using the %s to prepare resolving by hand.\n"),
1411 best_strategy);
1412 try_merge_strategy(best_strategy, common, head_arg);
1415 if (squash)
1416 finish(NULL, NULL);
1417 else {
1418 int fd;
1419 struct commit_list *j;
1421 for (j = remoteheads; j; j = j->next)
1422 strbuf_addf(&buf, "%s\n",
1423 sha1_to_hex(j->item->object.sha1));
1424 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1425 if (fd < 0)
1426 die_errno(_("Could not open '%s' for writing"),
1427 git_path("MERGE_HEAD"));
1428 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1429 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1430 close(fd);
1431 strbuf_addch(&merge_msg, '\n');
1432 write_merge_msg();
1433 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1434 if (fd < 0)
1435 die_errno(_("Could not open '%s' for writing"),
1436 git_path("MERGE_MODE"));
1437 strbuf_reset(&buf);
1438 if (!allow_fast_forward)
1439 strbuf_addf(&buf, "no-ff");
1440 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1441 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1442 close(fd);
1445 if (merge_was_ok) {
1446 fprintf(stderr, _("Automatic merge went well; "
1447 "stopped before committing as requested\n"));
1448 return 0;
1449 } else
1450 return suggest_conflicts(option_renormalize);