fmt-merge-msg.c: Fix an "dubious one-bit signed bitfield" sparse error
[git/jrn.git] / builtin / merge.c
blobb8f25dd44e2d85fc607dd18c540db443036f08f9
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"
29 #include "fmt-merge-msg.h"
31 #define DEFAULT_TWOHEAD (1<<0)
32 #define DEFAULT_OCTOPUS (1<<1)
33 #define NO_FAST_FORWARD (1<<2)
34 #define NO_TRIVIAL (1<<3)
36 struct strategy {
37 const char *name;
38 unsigned attr;
41 static const char * const builtin_merge_usage[] = {
42 "git merge [options] [<commit>...]",
43 "git merge [options] <msg> HEAD <commit>",
44 "git merge --abort",
45 NULL
48 static int show_diffstat = 1, shortlog_len = -1, squash;
49 static int option_commit = 1, allow_fast_forward = 1;
50 static int fast_forward_only;
51 static int allow_trivial = 1, have_message;
52 static struct strbuf merge_msg;
53 static struct commit_list *remoteheads;
54 static unsigned char head[20], stash[20];
55 static struct strategy **use_strategies;
56 static size_t use_strategies_nr, use_strategies_alloc;
57 static const char **xopts;
58 static size_t xopts_nr, xopts_alloc;
59 static const char *branch;
60 static char *branch_mergeoptions;
61 static int option_renormalize;
62 static int verbosity;
63 static int allow_rerere_auto;
64 static int abort_current_merge;
65 static int show_progress = -1;
66 static int default_to_upstream;
68 static struct strategy all_strategy[] = {
69 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
70 { "octopus", DEFAULT_OCTOPUS },
71 { "resolve", 0 },
72 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
73 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
76 static const char *pull_twohead, *pull_octopus;
78 static int option_parse_message(const struct option *opt,
79 const char *arg, int unset)
81 struct strbuf *buf = opt->value;
83 if (unset)
84 strbuf_setlen(buf, 0);
85 else if (arg) {
86 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
87 have_message = 1;
88 } else
89 return error(_("switch `m' requires a value"));
90 return 0;
93 static struct strategy *get_strategy(const char *name)
95 int i;
96 struct strategy *ret;
97 static struct cmdnames main_cmds, other_cmds;
98 static int loaded;
100 if (!name)
101 return NULL;
103 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
104 if (!strcmp(name, all_strategy[i].name))
105 return &all_strategy[i];
107 if (!loaded) {
108 struct cmdnames not_strategies;
109 loaded = 1;
111 memset(&not_strategies, 0, sizeof(struct cmdnames));
112 load_command_list("git-merge-", &main_cmds, &other_cmds);
113 for (i = 0; i < main_cmds.cnt; i++) {
114 int j, found = 0;
115 struct cmdname *ent = main_cmds.names[i];
116 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
117 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
118 && !all_strategy[j].name[ent->len])
119 found = 1;
120 if (!found)
121 add_cmdname(&not_strategies, ent->name, ent->len);
123 exclude_cmds(&main_cmds, &not_strategies);
125 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
126 fprintf(stderr, _("Could not find merge strategy '%s'.\n"), name);
127 fprintf(stderr, _("Available strategies are:"));
128 for (i = 0; i < main_cmds.cnt; i++)
129 fprintf(stderr, " %s", main_cmds.names[i]->name);
130 fprintf(stderr, ".\n");
131 if (other_cmds.cnt) {
132 fprintf(stderr, _("Available custom strategies are:"));
133 for (i = 0; i < other_cmds.cnt; i++)
134 fprintf(stderr, " %s", other_cmds.names[i]->name);
135 fprintf(stderr, ".\n");
137 exit(1);
140 ret = xcalloc(1, sizeof(struct strategy));
141 ret->name = xstrdup(name);
142 ret->attr = NO_TRIVIAL;
143 return ret;
146 static void append_strategy(struct strategy *s)
148 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
149 use_strategies[use_strategies_nr++] = s;
152 static int option_parse_strategy(const struct option *opt,
153 const char *name, int unset)
155 if (unset)
156 return 0;
158 append_strategy(get_strategy(name));
159 return 0;
162 static int option_parse_x(const struct option *opt,
163 const char *arg, int unset)
165 if (unset)
166 return 0;
168 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
169 xopts[xopts_nr++] = xstrdup(arg);
170 return 0;
173 static int option_parse_n(const struct option *opt,
174 const char *arg, int unset)
176 show_diffstat = unset;
177 return 0;
180 static struct option builtin_merge_options[] = {
181 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
182 "do not show a diffstat at the end of the merge",
183 PARSE_OPT_NOARG, option_parse_n },
184 OPT_BOOLEAN(0, "stat", &show_diffstat,
185 "show a diffstat at the end of the merge"),
186 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
187 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
188 "add (at most <n>) entries from shortlog to merge commit message",
189 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
190 OPT_BOOLEAN(0, "squash", &squash,
191 "create a single commit instead of doing a merge"),
192 OPT_BOOLEAN(0, "commit", &option_commit,
193 "perform a commit if the merge succeeds (default)"),
194 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
195 "allow fast-forward (default)"),
196 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
197 "abort if fast-forward is not possible"),
198 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
199 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
200 "merge strategy to use", option_parse_strategy),
201 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
202 "option for selected merge strategy", option_parse_x),
203 OPT_CALLBACK('m', "message", &merge_msg, "message",
204 "merge commit message (for a non-fast-forward merge)",
205 option_parse_message),
206 OPT__VERBOSITY(&verbosity),
207 OPT_BOOLEAN(0, "abort", &abort_current_merge,
208 "abort the current in-progress merge"),
209 OPT_SET_INT(0, "progress", &show_progress, "force progress reporting", 1),
210 OPT_END()
213 /* Cleans up metadata that is uninteresting after a succeeded merge. */
214 static void drop_save(void)
216 unlink(git_path("MERGE_HEAD"));
217 unlink(git_path("MERGE_MSG"));
218 unlink(git_path("MERGE_MODE"));
221 static void save_state(void)
223 int len;
224 struct child_process cp;
225 struct strbuf buffer = STRBUF_INIT;
226 const char *argv[] = {"stash", "create", NULL};
228 memset(&cp, 0, sizeof(cp));
229 cp.argv = argv;
230 cp.out = -1;
231 cp.git_cmd = 1;
233 if (start_command(&cp))
234 die(_("could not run stash."));
235 len = strbuf_read(&buffer, cp.out, 1024);
236 close(cp.out);
238 if (finish_command(&cp) || len < 0)
239 die(_("stash failed"));
240 else if (!len)
241 return;
242 strbuf_setlen(&buffer, buffer.len-1);
243 if (get_sha1(buffer.buf, stash))
244 die(_("not a valid object: %s"), buffer.buf);
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(void)
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_setup_done(&opts) < 0)
395 die(_("diff_setup_done failed"));
396 diff_tree_sha1(head, new_head, "", &opts);
397 diffcore_std(&opts);
398 diff_flush(&opts);
401 /* Run a post-merge hook */
402 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
404 strbuf_release(&reflog_message);
407 /* Get the name for the merge commit's message. */
408 static void merge_name(const char *remote, struct strbuf *msg)
410 struct object *remote_head;
411 unsigned char branch_head[20], buf_sha[20];
412 struct strbuf buf = STRBUF_INIT;
413 struct strbuf bname = STRBUF_INIT;
414 const char *ptr;
415 char *found_ref;
416 int len, early;
418 strbuf_branchname(&bname, remote);
419 remote = bname.buf;
421 memset(branch_head, 0, sizeof(branch_head));
422 remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
423 if (!remote_head)
424 die(_("'%s' does not point to a commit"), remote);
426 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
427 if (!prefixcmp(found_ref, "refs/heads/")) {
428 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
429 sha1_to_hex(branch_head), remote);
430 goto cleanup;
432 if (!prefixcmp(found_ref, "refs/remotes/")) {
433 strbuf_addf(msg, "%s\t\tremote-tracking branch '%s' of .\n",
434 sha1_to_hex(branch_head), remote);
435 goto cleanup;
439 /* See if remote matches <name>^^^.. or <name>~<number> */
440 for (len = 0, ptr = remote + strlen(remote);
441 remote < ptr && ptr[-1] == '^';
442 ptr--)
443 len++;
444 if (len)
445 early = 1;
446 else {
447 early = 0;
448 ptr = strrchr(remote, '~');
449 if (ptr) {
450 int seen_nonzero = 0;
452 len++; /* count ~ */
453 while (*++ptr && isdigit(*ptr)) {
454 seen_nonzero |= (*ptr != '0');
455 len++;
457 if (*ptr)
458 len = 0; /* not ...~<number> */
459 else if (seen_nonzero)
460 early = 1;
461 else if (len == 1)
462 early = 1; /* "name~" is "name~1"! */
465 if (len) {
466 struct strbuf truname = STRBUF_INIT;
467 strbuf_addstr(&truname, "refs/heads/");
468 strbuf_addstr(&truname, remote);
469 strbuf_setlen(&truname, truname.len - len);
470 if (resolve_ref(truname.buf, buf_sha, 1, NULL)) {
471 strbuf_addf(msg,
472 "%s\t\tbranch '%s'%s of .\n",
473 sha1_to_hex(remote_head->sha1),
474 truname.buf + 11,
475 (early ? " (early part)" : ""));
476 strbuf_release(&truname);
477 goto cleanup;
481 if (!strcmp(remote, "FETCH_HEAD") &&
482 !access(git_path("FETCH_HEAD"), R_OK)) {
483 FILE *fp;
484 struct strbuf line = STRBUF_INIT;
485 char *ptr;
487 fp = fopen(git_path("FETCH_HEAD"), "r");
488 if (!fp)
489 die_errno(_("could not open '%s' for reading"),
490 git_path("FETCH_HEAD"));
491 strbuf_getline(&line, fp, '\n');
492 fclose(fp);
493 ptr = strstr(line.buf, "\tnot-for-merge\t");
494 if (ptr)
495 strbuf_remove(&line, ptr-line.buf+1, 13);
496 strbuf_addbuf(msg, &line);
497 strbuf_release(&line);
498 goto cleanup;
500 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
501 sha1_to_hex(remote_head->sha1), remote);
502 cleanup:
503 strbuf_release(&buf);
504 strbuf_release(&bname);
507 static void parse_branch_merge_options(char *bmo)
509 const char **argv;
510 int argc;
512 if (!bmo)
513 return;
514 argc = split_cmdline(bmo, &argv);
515 if (argc < 0)
516 die(_("Bad branch.%s.mergeoptions string: %s"), branch,
517 split_cmdline_strerror(argc));
518 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
519 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
520 argc++;
521 argv[0] = "branch.*.mergeoptions";
522 parse_options(argc, argv, NULL, builtin_merge_options,
523 builtin_merge_usage, 0);
524 free(argv);
527 static int git_merge_config(const char *k, const char *v, void *cb)
529 int status;
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.ff")) {
548 int boolval = git_config_maybe_bool(k, v);
549 if (0 <= boolval) {
550 allow_fast_forward = boolval;
551 } else if (v && !strcmp(v, "only")) {
552 allow_fast_forward = 1;
553 fast_forward_only = 1;
554 } /* do not barf on values from future versions of git */
555 return 0;
556 } else if (!strcmp(k, "merge.defaulttoupstream")) {
557 default_to_upstream = git_config_bool(k, v);
558 return 0;
560 status = fmt_merge_msg_config(k, v, cb);
561 if (status)
562 return status;
563 return git_diff_ui_config(k, v, cb);
566 static int read_tree_trivial(unsigned char *common, unsigned char *head,
567 unsigned char *one)
569 int i, nr_trees = 0;
570 struct tree *trees[MAX_UNPACK_TREES];
571 struct tree_desc t[MAX_UNPACK_TREES];
572 struct unpack_trees_options opts;
574 memset(&opts, 0, sizeof(opts));
575 opts.head_idx = 2;
576 opts.src_index = &the_index;
577 opts.dst_index = &the_index;
578 opts.update = 1;
579 opts.verbose_update = 1;
580 opts.trivial_merges_only = 1;
581 opts.merge = 1;
582 trees[nr_trees] = parse_tree_indirect(common);
583 if (!trees[nr_trees++])
584 return -1;
585 trees[nr_trees] = parse_tree_indirect(head);
586 if (!trees[nr_trees++])
587 return -1;
588 trees[nr_trees] = parse_tree_indirect(one);
589 if (!trees[nr_trees++])
590 return -1;
591 opts.fn = threeway_merge;
592 cache_tree_free(&active_cache_tree);
593 for (i = 0; i < nr_trees; i++) {
594 parse_tree(trees[i]);
595 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
597 if (unpack_trees(nr_trees, t, &opts))
598 return -1;
599 return 0;
602 static void write_tree_trivial(unsigned char *sha1)
604 if (write_cache_as_tree(sha1, 0, NULL))
605 die(_("git write-tree failed to write a tree"));
608 static const char *merge_argument(struct commit *commit)
610 if (commit)
611 return sha1_to_hex(commit->object.sha1);
612 else
613 return EMPTY_TREE_SHA1_HEX;
616 int try_merge_command(const char *strategy, size_t xopts_nr,
617 const char **xopts, struct commit_list *common,
618 const char *head_arg, struct commit_list *remotes)
620 const char **args;
621 int i = 0, x = 0, ret;
622 struct commit_list *j;
623 struct strbuf buf = STRBUF_INIT;
625 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
626 commit_list_count(remotes)) * sizeof(char *));
627 strbuf_addf(&buf, "merge-%s", strategy);
628 args[i++] = buf.buf;
629 for (x = 0; x < xopts_nr; x++) {
630 char *s = xmalloc(strlen(xopts[x])+2+1);
631 strcpy(s, "--");
632 strcpy(s+2, xopts[x]);
633 args[i++] = s;
635 for (j = common; j; j = j->next)
636 args[i++] = xstrdup(merge_argument(j->item));
637 args[i++] = "--";
638 args[i++] = head_arg;
639 for (j = remotes; j; j = j->next)
640 args[i++] = xstrdup(merge_argument(j->item));
641 args[i] = NULL;
642 ret = run_command_v_opt(args, RUN_GIT_CMD);
643 strbuf_release(&buf);
644 i = 1;
645 for (x = 0; x < xopts_nr; x++)
646 free((void *)args[i++]);
647 for (j = common; j; j = j->next)
648 free((void *)args[i++]);
649 i += 2;
650 for (j = remotes; j; j = j->next)
651 free((void *)args[i++]);
652 free(args);
653 discard_cache();
654 if (read_cache() < 0)
655 die(_("failed to read the cache"));
656 resolve_undo_clear();
658 return ret;
661 static int try_merge_strategy(const char *strategy, struct commit_list *common,
662 const char *head_arg)
664 int index_fd;
665 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
667 index_fd = hold_locked_index(lock, 1);
668 refresh_cache(REFRESH_QUIET);
669 if (active_cache_changed &&
670 (write_cache(index_fd, active_cache, active_nr) ||
671 commit_locked_index(lock)))
672 return error(_("Unable to write index."));
673 rollback_lock_file(lock);
675 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
676 int clean, x;
677 struct commit *result;
678 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
679 int index_fd;
680 struct commit_list *reversed = NULL;
681 struct merge_options o;
682 struct commit_list *j;
684 if (remoteheads->next) {
685 error(_("Not handling anything other than two heads merge."));
686 return 2;
689 init_merge_options(&o);
690 if (!strcmp(strategy, "subtree"))
691 o.subtree_shift = "";
693 o.renormalize = option_renormalize;
694 o.show_rename_progress =
695 show_progress == -1 ? isatty(2) : show_progress;
697 for (x = 0; x < xopts_nr; x++)
698 if (parse_merge_opt(&o, xopts[x]))
699 die(_("Unknown option for merge-recursive: -X%s"), xopts[x]);
701 o.branch1 = head_arg;
702 o.branch2 = remoteheads->item->util;
704 for (j = common; j; j = j->next)
705 commit_list_insert(j->item, &reversed);
707 index_fd = hold_locked_index(lock, 1);
708 clean = merge_recursive(&o, lookup_commit(head),
709 remoteheads->item, reversed, &result);
710 if (active_cache_changed &&
711 (write_cache(index_fd, active_cache, active_nr) ||
712 commit_locked_index(lock)))
713 die (_("unable to write %s"), get_index_file());
714 rollback_lock_file(lock);
715 return clean ? 0 : 1;
716 } else {
717 return try_merge_command(strategy, xopts_nr, xopts,
718 common, head_arg, remoteheads);
722 static void count_diff_files(struct diff_queue_struct *q,
723 struct diff_options *opt, void *data)
725 int *count = data;
727 (*count) += q->nr;
730 static int count_unmerged_entries(void)
732 int i, ret = 0;
734 for (i = 0; i < active_nr; i++)
735 if (ce_stage(active_cache[i]))
736 ret++;
738 return ret;
741 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
743 struct tree *trees[MAX_UNPACK_TREES];
744 struct unpack_trees_options opts;
745 struct tree_desc t[MAX_UNPACK_TREES];
746 int i, fd, nr_trees = 0;
747 struct dir_struct dir;
748 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
750 refresh_cache(REFRESH_QUIET);
752 fd = hold_locked_index(lock_file, 1);
754 memset(&trees, 0, sizeof(trees));
755 memset(&opts, 0, sizeof(opts));
756 memset(&t, 0, sizeof(t));
757 memset(&dir, 0, sizeof(dir));
758 dir.flags |= DIR_SHOW_IGNORED;
759 dir.exclude_per_dir = ".gitignore";
760 opts.dir = &dir;
762 opts.head_idx = 1;
763 opts.src_index = &the_index;
764 opts.dst_index = &the_index;
765 opts.update = 1;
766 opts.verbose_update = 1;
767 opts.merge = 1;
768 opts.fn = twoway_merge;
769 setup_unpack_trees_porcelain(&opts, "merge");
771 trees[nr_trees] = parse_tree_indirect(head);
772 if (!trees[nr_trees++])
773 return -1;
774 trees[nr_trees] = parse_tree_indirect(remote);
775 if (!trees[nr_trees++])
776 return -1;
777 for (i = 0; i < nr_trees; i++) {
778 parse_tree(trees[i]);
779 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
781 if (unpack_trees(nr_trees, t, &opts))
782 return -1;
783 if (write_cache(fd, active_cache, active_nr) ||
784 commit_locked_index(lock_file))
785 die(_("unable to write new index file"));
786 return 0;
789 static void split_merge_strategies(const char *string, struct strategy **list,
790 int *nr, int *alloc)
792 char *p, *q, *buf;
794 if (!string)
795 return;
797 buf = xstrdup(string);
798 q = buf;
799 for (;;) {
800 p = strchr(q, ' ');
801 if (!p) {
802 ALLOC_GROW(*list, *nr + 1, *alloc);
803 (*list)[(*nr)++].name = xstrdup(q);
804 free(buf);
805 return;
806 } else {
807 *p = '\0';
808 ALLOC_GROW(*list, *nr + 1, *alloc);
809 (*list)[(*nr)++].name = xstrdup(q);
810 q = ++p;
815 static void add_strategies(const char *string, unsigned attr)
817 struct strategy *list = NULL;
818 int list_alloc = 0, list_nr = 0, i;
820 memset(&list, 0, sizeof(list));
821 split_merge_strategies(string, &list, &list_nr, &list_alloc);
822 if (list) {
823 for (i = 0; i < list_nr; i++)
824 append_strategy(get_strategy(list[i].name));
825 return;
827 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
828 if (all_strategy[i].attr & attr)
829 append_strategy(&all_strategy[i]);
833 static void write_merge_msg(void)
835 int fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
836 if (fd < 0)
837 die_errno(_("Could not open '%s' for writing"),
838 git_path("MERGE_MSG"));
839 if (write_in_full(fd, merge_msg.buf, merge_msg.len) != merge_msg.len)
840 die_errno(_("Could not write to '%s'"), git_path("MERGE_MSG"));
841 close(fd);
844 static void read_merge_msg(void)
846 strbuf_reset(&merge_msg);
847 if (strbuf_read_file(&merge_msg, git_path("MERGE_MSG"), 0) < 0)
848 die_errno(_("Could not read from '%s'"), git_path("MERGE_MSG"));
851 static void run_prepare_commit_msg(void)
853 write_merge_msg();
854 run_hook(get_index_file(), "prepare-commit-msg",
855 git_path("MERGE_MSG"), "merge", NULL, NULL);
856 read_merge_msg();
859 static int merge_trivial(void)
861 unsigned char result_tree[20], result_commit[20];
862 struct commit_list *parent = xmalloc(sizeof(*parent));
864 write_tree_trivial(result_tree);
865 printf(_("Wonderful.\n"));
866 parent->item = lookup_commit(head);
867 parent->next = xmalloc(sizeof(*parent->next));
868 parent->next->item = remoteheads->item;
869 parent->next->next = NULL;
870 run_prepare_commit_msg();
871 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
872 finish(result_commit, "In-index merge");
873 drop_save();
874 return 0;
877 static int finish_automerge(struct commit_list *common,
878 unsigned char *result_tree,
879 const char *wt_strategy)
881 struct commit_list *parents = NULL, *j;
882 struct strbuf buf = STRBUF_INIT;
883 unsigned char result_commit[20];
885 free_commit_list(common);
886 if (allow_fast_forward) {
887 parents = remoteheads;
888 commit_list_insert(lookup_commit(head), &parents);
889 parents = reduce_heads(parents);
890 } else {
891 struct commit_list **pptr = &parents;
893 pptr = &commit_list_insert(lookup_commit(head),
894 pptr)->next;
895 for (j = remoteheads; j; j = j->next)
896 pptr = &commit_list_insert(j->item, pptr)->next;
898 free_commit_list(remoteheads);
899 strbuf_addch(&merge_msg, '\n');
900 run_prepare_commit_msg();
901 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
902 strbuf_addf(&buf, "Merge made by the '%s' strategy.", wt_strategy);
903 finish(result_commit, buf.buf);
904 strbuf_release(&buf);
905 drop_save();
906 return 0;
909 static int suggest_conflicts(int renormalizing)
911 FILE *fp;
912 int pos;
914 fp = fopen(git_path("MERGE_MSG"), "a");
915 if (!fp)
916 die_errno(_("Could not open '%s' for writing"),
917 git_path("MERGE_MSG"));
918 fprintf(fp, "\nConflicts:\n");
919 for (pos = 0; pos < active_nr; pos++) {
920 struct cache_entry *ce = active_cache[pos];
922 if (ce_stage(ce)) {
923 fprintf(fp, "\t%s\n", ce->name);
924 while (pos + 1 < active_nr &&
925 !strcmp(ce->name,
926 active_cache[pos + 1]->name))
927 pos++;
930 fclose(fp);
931 rerere(allow_rerere_auto);
932 printf(_("Automatic merge failed; "
933 "fix conflicts and then commit the result.\n"));
934 return 1;
937 static struct commit *is_old_style_invocation(int argc, const char **argv)
939 struct commit *second_token = NULL;
940 if (argc > 2) {
941 unsigned char second_sha1[20];
943 if (get_sha1(argv[1], second_sha1))
944 return NULL;
945 second_token = lookup_commit_reference_gently(second_sha1, 0);
946 if (!second_token)
947 die(_("'%s' is not a commit"), argv[1]);
948 if (hashcmp(second_token->object.sha1, head))
949 return NULL;
951 return second_token;
954 static int evaluate_result(void)
956 int cnt = 0;
957 struct rev_info rev;
959 /* Check how many files differ. */
960 init_revisions(&rev, "");
961 setup_revisions(0, NULL, &rev, NULL);
962 rev.diffopt.output_format |=
963 DIFF_FORMAT_CALLBACK;
964 rev.diffopt.format_callback = count_diff_files;
965 rev.diffopt.format_callback_data = &cnt;
966 run_diff_files(&rev, 0);
969 * Check how many unmerged entries are
970 * there.
972 cnt += count_unmerged_entries();
974 return cnt;
978 * Pretend as if the user told us to merge with the tracking
979 * branch we have for the upstream of the current branch
981 static int setup_with_upstream(const char ***argv)
983 struct branch *branch = branch_get(NULL);
984 int i;
985 const char **args;
987 if (!branch)
988 die(_("No current branch."));
989 if (!branch->remote)
990 die(_("No remote for the current branch."));
991 if (!branch->merge_nr)
992 die(_("No default upstream defined for the current branch."));
994 args = xcalloc(branch->merge_nr + 1, sizeof(char *));
995 for (i = 0; i < branch->merge_nr; i++) {
996 if (!branch->merge[i]->dst)
997 die(_("No remote tracking branch for %s from %s"),
998 branch->merge[i]->src, branch->remote_name);
999 args[i] = branch->merge[i]->dst;
1001 args[i] = NULL;
1002 *argv = args;
1003 return i;
1006 int cmd_merge(int argc, const char **argv, const char *prefix)
1008 unsigned char result_tree[20];
1009 struct strbuf buf = STRBUF_INIT;
1010 const char *head_arg;
1011 int flag, head_invalid = 0, i;
1012 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
1013 struct commit_list *common = NULL;
1014 const char *best_strategy = NULL, *wt_strategy = NULL;
1015 struct commit_list **remotes = &remoteheads;
1017 if (argc == 2 && !strcmp(argv[1], "-h"))
1018 usage_with_options(builtin_merge_usage, builtin_merge_options);
1021 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1022 * current branch.
1024 branch = resolve_ref("HEAD", head, 0, &flag);
1025 if (branch && !prefixcmp(branch, "refs/heads/"))
1026 branch += 11;
1027 if (is_null_sha1(head))
1028 head_invalid = 1;
1030 git_config(git_merge_config, NULL);
1032 if (branch_mergeoptions)
1033 parse_branch_merge_options(branch_mergeoptions);
1034 argc = parse_options(argc, argv, prefix, builtin_merge_options,
1035 builtin_merge_usage, 0);
1036 if (shortlog_len < 0)
1037 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
1039 if (verbosity < 0 && show_progress == -1)
1040 show_progress = 0;
1042 if (abort_current_merge) {
1043 int nargc = 2;
1044 const char *nargv[] = {"reset", "--merge", NULL};
1046 if (!file_exists(git_path("MERGE_HEAD")))
1047 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1049 /* Invoke 'git reset --merge' */
1050 return cmd_reset(nargc, nargv, prefix);
1053 if (read_cache_unmerged())
1054 die_resolve_conflict("merge");
1056 if (file_exists(git_path("MERGE_HEAD"))) {
1058 * There is no unmerged entry, don't advise 'git
1059 * add/rm <file>', just 'git commit'.
1061 if (advice_resolve_conflict)
1062 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1063 "Please, commit your changes before you can merge."));
1064 else
1065 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1067 if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
1068 if (advice_resolve_conflict)
1069 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1070 "Please, commit your changes before you can merge."));
1071 else
1072 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1074 resolve_undo_clear();
1076 if (verbosity < 0)
1077 show_diffstat = 0;
1079 if (squash) {
1080 if (!allow_fast_forward)
1081 die(_("You cannot combine --squash with --no-ff."));
1082 option_commit = 0;
1085 if (!allow_fast_forward && fast_forward_only)
1086 die(_("You cannot combine --no-ff with --ff-only."));
1088 if (!abort_current_merge) {
1089 if (!argc && default_to_upstream)
1090 argc = setup_with_upstream(&argv);
1091 else if (argc == 1 && !strcmp(argv[0], "-"))
1092 argv[0] = "@{-1}";
1094 if (!argc)
1095 usage_with_options(builtin_merge_usage,
1096 builtin_merge_options);
1099 * This could be traditional "merge <msg> HEAD <commit>..." and
1100 * the way we can tell it is to see if the second token is HEAD,
1101 * but some people might have misused the interface and used a
1102 * committish that is the same as HEAD there instead.
1103 * Traditional format never would have "-m" so it is an
1104 * additional safety measure to check for it.
1107 if (!have_message && is_old_style_invocation(argc, argv)) {
1108 strbuf_addstr(&merge_msg, argv[0]);
1109 head_arg = argv[1];
1110 argv += 2;
1111 argc -= 2;
1112 } else if (head_invalid) {
1113 struct object *remote_head;
1115 * If the merged head is a valid one there is no reason
1116 * to forbid "git merge" into a branch yet to be born.
1117 * We do the same for "git pull".
1119 if (argc != 1)
1120 die(_("Can merge only exactly one commit into "
1121 "empty head"));
1122 if (squash)
1123 die(_("Squash commit into empty head not supported yet"));
1124 if (!allow_fast_forward)
1125 die(_("Non-fast-forward commit does not make sense into "
1126 "an empty head"));
1127 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
1128 if (!remote_head)
1129 die(_("%s - not something we can merge"), argv[0]);
1130 read_empty(remote_head->sha1, 0);
1131 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
1132 DIE_ON_ERR);
1133 return 0;
1134 } else {
1135 struct strbuf merge_names = STRBUF_INIT;
1137 /* We are invoked directly as the first-class UI. */
1138 head_arg = "HEAD";
1141 * All the rest are the commits being merged;
1142 * prepare the standard merge summary message to
1143 * be appended to the given message. If remote
1144 * is invalid we will die later in the common
1145 * codepath so we discard the error in this
1146 * loop.
1148 for (i = 0; i < argc; i++)
1149 merge_name(argv[i], &merge_names);
1151 if (!have_message || shortlog_len) {
1152 fmt_merge_msg(&merge_names, &merge_msg, !have_message,
1153 shortlog_len);
1154 if (merge_msg.len)
1155 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1159 if (head_invalid || !argc)
1160 usage_with_options(builtin_merge_usage,
1161 builtin_merge_options);
1163 strbuf_addstr(&buf, "merge");
1164 for (i = 0; i < argc; i++)
1165 strbuf_addf(&buf, " %s", argv[i]);
1166 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1167 strbuf_reset(&buf);
1169 for (i = 0; i < argc; i++) {
1170 struct object *o;
1171 struct commit *commit;
1173 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
1174 if (!o)
1175 die(_("%s - not something we can merge"), argv[i]);
1176 commit = lookup_commit(o->sha1);
1177 commit->util = (void *)argv[i];
1178 remotes = &commit_list_insert(commit, remotes)->next;
1180 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1181 setenv(buf.buf, argv[i], 1);
1182 strbuf_reset(&buf);
1185 if (!use_strategies) {
1186 if (!remoteheads->next)
1187 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1188 else
1189 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1192 for (i = 0; i < use_strategies_nr; i++) {
1193 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1194 allow_fast_forward = 0;
1195 if (use_strategies[i]->attr & NO_TRIVIAL)
1196 allow_trivial = 0;
1199 if (!remoteheads->next)
1200 common = get_merge_bases(lookup_commit(head),
1201 remoteheads->item, 1);
1202 else {
1203 struct commit_list *list = remoteheads;
1204 commit_list_insert(lookup_commit(head), &list);
1205 common = get_octopus_merge_bases(list);
1206 free(list);
1209 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1210 DIE_ON_ERR);
1212 if (!common)
1213 ; /* No common ancestors found. We need a real merge. */
1214 else if (!remoteheads->next && !common->next &&
1215 common->item == remoteheads->item) {
1217 * If head can reach all the merge then we are up to date.
1218 * but first the most common case of merging one remote.
1220 finish_up_to_date("Already up-to-date.");
1221 return 0;
1222 } else if (allow_fast_forward && !remoteheads->next &&
1223 !common->next &&
1224 !hashcmp(common->item->object.sha1, head)) {
1225 /* Again the most common case of merging one remote. */
1226 struct strbuf msg = STRBUF_INIT;
1227 struct object *o;
1228 char hex[41];
1230 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1232 if (verbosity >= 0)
1233 printf(_("Updating %s..%s\n"),
1234 hex,
1235 find_unique_abbrev(remoteheads->item->object.sha1,
1236 DEFAULT_ABBREV));
1237 strbuf_addstr(&msg, "Fast-forward");
1238 if (have_message)
1239 strbuf_addstr(&msg,
1240 " (no commit created; -m option ignored)");
1241 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1242 0, NULL, OBJ_COMMIT);
1243 if (!o)
1244 return 1;
1246 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1247 return 1;
1249 finish(o->sha1, msg.buf);
1250 drop_save();
1251 return 0;
1252 } else if (!remoteheads->next && common->next)
1255 * We are not doing octopus and not fast-forward. Need
1256 * a real merge.
1258 else if (!remoteheads->next && !common->next && option_commit) {
1260 * We are not doing octopus, not fast-forward, and have
1261 * only one common.
1263 refresh_cache(REFRESH_QUIET);
1264 if (allow_trivial && !fast_forward_only) {
1265 /* See if it is really trivial. */
1266 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1267 printf(_("Trying really trivial in-index merge...\n"));
1268 if (!read_tree_trivial(common->item->object.sha1,
1269 head, remoteheads->item->object.sha1))
1270 return merge_trivial();
1271 printf(_("Nope.\n"));
1273 } else {
1275 * An octopus. If we can reach all the remote we are up
1276 * to date.
1278 int up_to_date = 1;
1279 struct commit_list *j;
1281 for (j = remoteheads; j; j = j->next) {
1282 struct commit_list *common_one;
1285 * Here we *have* to calculate the individual
1286 * merge_bases again, otherwise "git merge HEAD^
1287 * HEAD^^" would be missed.
1289 common_one = get_merge_bases(lookup_commit(head),
1290 j->item, 1);
1291 if (hashcmp(common_one->item->object.sha1,
1292 j->item->object.sha1)) {
1293 up_to_date = 0;
1294 break;
1297 if (up_to_date) {
1298 finish_up_to_date("Already up-to-date. Yeeah!");
1299 return 0;
1303 if (fast_forward_only)
1304 die(_("Not possible to fast-forward, aborting."));
1306 /* We are going to make a new commit. */
1307 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1310 * At this point, we need a real merge. No matter what strategy
1311 * we use, it would operate on the index, possibly affecting the
1312 * working tree, and when resolved cleanly, have the desired
1313 * tree in the index -- this means that the index must be in
1314 * sync with the head commit. The strategies are responsible
1315 * to ensure this.
1317 if (use_strategies_nr != 1) {
1319 * Stash away the local changes so that we can try more
1320 * than one.
1322 save_state();
1323 } else {
1324 memcpy(stash, null_sha1, 20);
1327 for (i = 0; i < use_strategies_nr; i++) {
1328 int ret;
1329 if (i) {
1330 printf(_("Rewinding the tree to pristine...\n"));
1331 restore_state();
1333 if (use_strategies_nr != 1)
1334 printf(_("Trying merge strategy %s...\n"),
1335 use_strategies[i]->name);
1337 * Remember which strategy left the state in the working
1338 * tree.
1340 wt_strategy = use_strategies[i]->name;
1342 ret = try_merge_strategy(use_strategies[i]->name,
1343 common, head_arg);
1344 if (!option_commit && !ret) {
1345 merge_was_ok = 1;
1347 * This is necessary here just to avoid writing
1348 * the tree, but later we will *not* exit with
1349 * status code 1 because merge_was_ok is set.
1351 ret = 1;
1354 if (ret) {
1356 * The backend exits with 1 when conflicts are
1357 * left to be resolved, with 2 when it does not
1358 * handle the given merge at all.
1360 if (ret == 1) {
1361 int cnt = evaluate_result();
1363 if (best_cnt <= 0 || cnt <= best_cnt) {
1364 best_strategy = use_strategies[i]->name;
1365 best_cnt = cnt;
1368 if (merge_was_ok)
1369 break;
1370 else
1371 continue;
1374 /* Automerge succeeded. */
1375 write_tree_trivial(result_tree);
1376 automerge_was_ok = 1;
1377 break;
1381 * If we have a resulting tree, that means the strategy module
1382 * auto resolved the merge cleanly.
1384 if (automerge_was_ok)
1385 return finish_automerge(common, result_tree, wt_strategy);
1388 * Pick the result from the best strategy and have the user fix
1389 * it up.
1391 if (!best_strategy) {
1392 restore_state();
1393 if (use_strategies_nr > 1)
1394 fprintf(stderr,
1395 _("No merge strategy handled the merge.\n"));
1396 else
1397 fprintf(stderr, _("Merge with strategy %s failed.\n"),
1398 use_strategies[0]->name);
1399 return 2;
1400 } else if (best_strategy == wt_strategy)
1401 ; /* We already have its result in the working tree. */
1402 else {
1403 printf(_("Rewinding the tree to pristine...\n"));
1404 restore_state();
1405 printf(_("Using the %s to prepare resolving by hand.\n"),
1406 best_strategy);
1407 try_merge_strategy(best_strategy, common, head_arg);
1410 if (squash)
1411 finish(NULL, NULL);
1412 else {
1413 int fd;
1414 struct commit_list *j;
1416 for (j = remoteheads; j; j = j->next)
1417 strbuf_addf(&buf, "%s\n",
1418 sha1_to_hex(j->item->object.sha1));
1419 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1420 if (fd < 0)
1421 die_errno(_("Could not open '%s' for writing"),
1422 git_path("MERGE_HEAD"));
1423 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1424 die_errno(_("Could not write to '%s'"), git_path("MERGE_HEAD"));
1425 close(fd);
1426 strbuf_addch(&merge_msg, '\n');
1427 write_merge_msg();
1428 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1429 if (fd < 0)
1430 die_errno(_("Could not open '%s' for writing"),
1431 git_path("MERGE_MODE"));
1432 strbuf_reset(&buf);
1433 if (!allow_fast_forward)
1434 strbuf_addf(&buf, "no-ff");
1435 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1436 die_errno(_("Could not write to '%s'"), git_path("MERGE_MODE"));
1437 close(fd);
1440 if (merge_was_ok) {
1441 fprintf(stderr, _("Automatic merge went well; "
1442 "stopped before committing as requested\n"));
1443 return 0;
1444 } else
1445 return suggest_conflicts(option_renormalize);