contrib/ciabot: git-describe commit instead of HEAD
[debian-git.git] / builtin / merge.c
blob10f091b51960cd6ae913b1c4d2ab9e6931862351
1 /*
2 * Builtin "git merge"
4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
7 */
9 #include "cache.h"
10 #include "parse-options.h"
11 #include "builtin.h"
12 #include "run-command.h"
13 #include "diff.h"
14 #include "refs.h"
15 #include "commit.h"
16 #include "diffcore.h"
17 #include "revision.h"
18 #include "unpack-trees.h"
19 #include "cache-tree.h"
20 #include "dir.h"
21 #include "utf8.h"
22 #include "log-tree.h"
23 #include "color.h"
24 #include "rerere.h"
25 #include "help.h"
26 #include "merge-recursive.h"
27 #include "resolve-undo.h"
29 #define DEFAULT_TWOHEAD (1<<0)
30 #define DEFAULT_OCTOPUS (1<<1)
31 #define NO_FAST_FORWARD (1<<2)
32 #define NO_TRIVIAL (1<<3)
34 struct strategy {
35 const char *name;
36 unsigned attr;
39 static const char * const builtin_merge_usage[] = {
40 "git merge [options] <remote>...",
41 "git merge [options] <msg> HEAD <remote>",
42 NULL
45 static int show_diffstat = 1, shortlog_len, squash;
46 static int option_commit = 1, allow_fast_forward = 1;
47 static int fast_forward_only;
48 static int allow_trivial = 1, have_message;
49 static struct strbuf merge_msg;
50 static struct commit_list *remoteheads;
51 static unsigned char head[20], stash[20];
52 static struct strategy **use_strategies;
53 static size_t use_strategies_nr, use_strategies_alloc;
54 static const char **xopts;
55 static size_t xopts_nr, xopts_alloc;
56 static const char *branch;
57 static int option_renormalize;
58 static int verbosity;
59 static int allow_rerere_auto;
61 static struct strategy all_strategy[] = {
62 { "recursive", DEFAULT_TWOHEAD | NO_TRIVIAL },
63 { "octopus", DEFAULT_OCTOPUS },
64 { "resolve", 0 },
65 { "ours", NO_FAST_FORWARD | NO_TRIVIAL },
66 { "subtree", NO_FAST_FORWARD | NO_TRIVIAL },
69 static const char *pull_twohead, *pull_octopus;
71 static int option_parse_message(const struct option *opt,
72 const char *arg, int unset)
74 struct strbuf *buf = opt->value;
76 if (unset)
77 strbuf_setlen(buf, 0);
78 else if (arg) {
79 strbuf_addf(buf, "%s%s", buf->len ? "\n\n" : "", arg);
80 have_message = 1;
81 } else
82 return error("switch `m' requires a value");
83 return 0;
86 static struct strategy *get_strategy(const char *name)
88 int i;
89 struct strategy *ret;
90 static struct cmdnames main_cmds, other_cmds;
91 static int loaded;
93 if (!name)
94 return NULL;
96 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
97 if (!strcmp(name, all_strategy[i].name))
98 return &all_strategy[i];
100 if (!loaded) {
101 struct cmdnames not_strategies;
102 loaded = 1;
104 memset(&not_strategies, 0, sizeof(struct cmdnames));
105 load_command_list("git-merge-", &main_cmds, &other_cmds);
106 for (i = 0; i < main_cmds.cnt; i++) {
107 int j, found = 0;
108 struct cmdname *ent = main_cmds.names[i];
109 for (j = 0; j < ARRAY_SIZE(all_strategy); j++)
110 if (!strncmp(ent->name, all_strategy[j].name, ent->len)
111 && !all_strategy[j].name[ent->len])
112 found = 1;
113 if (!found)
114 add_cmdname(&not_strategies, ent->name, ent->len);
116 exclude_cmds(&main_cmds, &not_strategies);
118 if (!is_in_cmdlist(&main_cmds, name) && !is_in_cmdlist(&other_cmds, name)) {
119 fprintf(stderr, "Could not find merge strategy '%s'.\n", name);
120 fprintf(stderr, "Available strategies are:");
121 for (i = 0; i < main_cmds.cnt; i++)
122 fprintf(stderr, " %s", main_cmds.names[i]->name);
123 fprintf(stderr, ".\n");
124 if (other_cmds.cnt) {
125 fprintf(stderr, "Available custom strategies are:");
126 for (i = 0; i < other_cmds.cnt; i++)
127 fprintf(stderr, " %s", other_cmds.names[i]->name);
128 fprintf(stderr, ".\n");
130 exit(1);
133 ret = xcalloc(1, sizeof(struct strategy));
134 ret->name = xstrdup(name);
135 ret->attr = NO_TRIVIAL;
136 return ret;
139 static void append_strategy(struct strategy *s)
141 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
142 use_strategies[use_strategies_nr++] = s;
145 static int option_parse_strategy(const struct option *opt,
146 const char *name, int unset)
148 if (unset)
149 return 0;
151 append_strategy(get_strategy(name));
152 return 0;
155 static int option_parse_x(const struct option *opt,
156 const char *arg, int unset)
158 if (unset)
159 return 0;
161 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
162 xopts[xopts_nr++] = xstrdup(arg);
163 return 0;
166 static int option_parse_n(const struct option *opt,
167 const char *arg, int unset)
169 show_diffstat = unset;
170 return 0;
173 static struct option builtin_merge_options[] = {
174 { OPTION_CALLBACK, 'n', NULL, NULL, NULL,
175 "do not show a diffstat at the end of the merge",
176 PARSE_OPT_NOARG, option_parse_n },
177 OPT_BOOLEAN(0, "stat", &show_diffstat,
178 "show a diffstat at the end of the merge"),
179 OPT_BOOLEAN(0, "summary", &show_diffstat, "(synonym to --stat)"),
180 { OPTION_INTEGER, 0, "log", &shortlog_len, "n",
181 "add (at most <n>) entries from shortlog to merge commit message",
182 PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
183 OPT_BOOLEAN(0, "squash", &squash,
184 "create a single commit instead of doing a merge"),
185 OPT_BOOLEAN(0, "commit", &option_commit,
186 "perform a commit if the merge succeeds (default)"),
187 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
188 "allow fast-forward (default)"),
189 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
190 "abort if fast-forward is not possible"),
191 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
192 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
193 "merge strategy to use", option_parse_strategy),
194 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
195 "option for selected merge strategy", option_parse_x),
196 OPT_CALLBACK('m', "message", &merge_msg, "message",
197 "message to be used for the merge commit (if any)",
198 option_parse_message),
199 OPT__VERBOSITY(&verbosity),
200 OPT_END()
203 /* Cleans up metadata that is uninteresting after a succeeded merge. */
204 static void drop_save(void)
206 unlink(git_path("MERGE_HEAD"));
207 unlink(git_path("MERGE_MSG"));
208 unlink(git_path("MERGE_MODE"));
211 static void save_state(void)
213 int len;
214 struct child_process cp;
215 struct strbuf buffer = STRBUF_INIT;
216 const char *argv[] = {"stash", "create", NULL};
218 memset(&cp, 0, sizeof(cp));
219 cp.argv = argv;
220 cp.out = -1;
221 cp.git_cmd = 1;
223 if (start_command(&cp))
224 die("could not run stash.");
225 len = strbuf_read(&buffer, cp.out, 1024);
226 close(cp.out);
228 if (finish_command(&cp) || len < 0)
229 die("stash failed");
230 else if (!len)
231 return;
232 strbuf_setlen(&buffer, buffer.len-1);
233 if (get_sha1(buffer.buf, stash))
234 die("not a valid object: %s", buffer.buf);
237 static void reset_hard(unsigned const char *sha1, int verbose)
239 int i = 0;
240 const char *args[6];
242 args[i++] = "read-tree";
243 if (verbose)
244 args[i++] = "-v";
245 args[i++] = "--reset";
246 args[i++] = "-u";
247 args[i++] = sha1_to_hex(sha1);
248 args[i] = NULL;
250 if (run_command_v_opt(args, RUN_GIT_CMD))
251 die("read-tree failed");
254 static void restore_state(void)
256 struct strbuf sb = STRBUF_INIT;
257 const char *args[] = { "stash", "apply", NULL, NULL };
259 if (is_null_sha1(stash))
260 return;
262 reset_hard(head, 1);
264 args[2] = sha1_to_hex(stash);
267 * It is OK to ignore error here, for example when there was
268 * nothing to restore.
270 run_command_v_opt(args, RUN_GIT_CMD);
272 strbuf_release(&sb);
273 refresh_cache(REFRESH_QUIET);
276 /* This is called when no merge was necessary. */
277 static void finish_up_to_date(const char *msg)
279 if (verbosity >= 0)
280 printf("%s%s\n", squash ? " (nothing to squash)" : "", msg);
281 drop_save();
284 static void squash_message(void)
286 struct rev_info rev;
287 struct commit *commit;
288 struct strbuf out = STRBUF_INIT;
289 struct commit_list *j;
290 int fd;
291 struct pretty_print_context ctx = {0};
293 printf("Squash commit -- not updating HEAD\n");
294 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
295 if (fd < 0)
296 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
298 init_revisions(&rev, NULL);
299 rev.ignore_merges = 1;
300 rev.commit_format = CMIT_FMT_MEDIUM;
302 commit = lookup_commit(head);
303 commit->object.flags |= UNINTERESTING;
304 add_pending_object(&rev, &commit->object, NULL);
306 for (j = remoteheads; j; j = j->next)
307 add_pending_object(&rev, &j->item->object, NULL);
309 setup_revisions(0, NULL, &rev, NULL);
310 if (prepare_revision_walk(&rev))
311 die("revision walk setup failed");
313 ctx.abbrev = rev.abbrev;
314 ctx.date_mode = rev.date_mode;
316 strbuf_addstr(&out, "Squashed commit of the following:\n");
317 while ((commit = get_revision(&rev)) != NULL) {
318 strbuf_addch(&out, '\n');
319 strbuf_addf(&out, "commit %s\n",
320 sha1_to_hex(commit->object.sha1));
321 pretty_print_commit(rev.commit_format, commit, &out, &ctx);
323 if (write(fd, out.buf, out.len) < 0)
324 die_errno("Writing SQUASH_MSG");
325 if (close(fd))
326 die_errno("Finishing SQUASH_MSG");
327 strbuf_release(&out);
330 static void finish(const unsigned char *new_head, const char *msg)
332 struct strbuf reflog_message = STRBUF_INIT;
334 if (!msg)
335 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
336 else {
337 if (verbosity >= 0)
338 printf("%s\n", msg);
339 strbuf_addf(&reflog_message, "%s: %s",
340 getenv("GIT_REFLOG_ACTION"), msg);
342 if (squash) {
343 squash_message();
344 } else {
345 if (verbosity >= 0 && !merge_msg.len)
346 printf("No merge message -- not updating HEAD\n");
347 else {
348 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
349 update_ref(reflog_message.buf, "HEAD",
350 new_head, head, 0,
351 DIE_ON_ERR);
353 * We ignore errors in 'gc --auto', since the
354 * user should see them.
356 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
359 if (new_head && show_diffstat) {
360 struct diff_options opts;
361 diff_setup(&opts);
362 opts.output_format |=
363 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
364 opts.detect_rename = DIFF_DETECT_RENAME;
365 if (diff_use_color_default > 0)
366 DIFF_OPT_SET(&opts, COLOR_DIFF);
367 if (diff_setup_done(&opts) < 0)
368 die("diff_setup_done failed");
369 diff_tree_sha1(head, new_head, "", &opts);
370 diffcore_std(&opts);
371 diff_flush(&opts);
374 /* Run a post-merge hook */
375 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
377 strbuf_release(&reflog_message);
380 /* Get the name for the merge commit's message. */
381 static void merge_name(const char *remote, struct strbuf *msg)
383 struct object *remote_head;
384 unsigned char branch_head[20], buf_sha[20];
385 struct strbuf buf = STRBUF_INIT;
386 struct strbuf bname = STRBUF_INIT;
387 const char *ptr;
388 char *found_ref;
389 int len, early;
391 strbuf_branchname(&bname, remote);
392 remote = bname.buf;
394 memset(branch_head, 0, sizeof(branch_head));
395 remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
396 if (!remote_head)
397 die("'%s' does not point to a commit", remote);
399 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
400 if (!prefixcmp(found_ref, "refs/heads/")) {
401 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
402 sha1_to_hex(branch_head), remote);
403 goto cleanup;
405 if (!prefixcmp(found_ref, "refs/remotes/")) {
406 strbuf_addf(msg, "%s\t\tremote branch '%s' of .\n",
407 sha1_to_hex(branch_head), remote);
408 goto cleanup;
412 /* See if remote matches <name>^^^.. or <name>~<number> */
413 for (len = 0, ptr = remote + strlen(remote);
414 remote < ptr && ptr[-1] == '^';
415 ptr--)
416 len++;
417 if (len)
418 early = 1;
419 else {
420 early = 0;
421 ptr = strrchr(remote, '~');
422 if (ptr) {
423 int seen_nonzero = 0;
425 len++; /* count ~ */
426 while (*++ptr && isdigit(*ptr)) {
427 seen_nonzero |= (*ptr != '0');
428 len++;
430 if (*ptr)
431 len = 0; /* not ...~<number> */
432 else if (seen_nonzero)
433 early = 1;
434 else if (len == 1)
435 early = 1; /* "name~" is "name~1"! */
438 if (len) {
439 struct strbuf truname = STRBUF_INIT;
440 strbuf_addstr(&truname, "refs/heads/");
441 strbuf_addstr(&truname, remote);
442 strbuf_setlen(&truname, truname.len - len);
443 if (resolve_ref(truname.buf, buf_sha, 1, NULL)) {
444 strbuf_addf(msg,
445 "%s\t\tbranch '%s'%s of .\n",
446 sha1_to_hex(remote_head->sha1),
447 truname.buf + 11,
448 (early ? " (early part)" : ""));
449 strbuf_release(&truname);
450 goto cleanup;
454 if (!strcmp(remote, "FETCH_HEAD") &&
455 !access(git_path("FETCH_HEAD"), R_OK)) {
456 FILE *fp;
457 struct strbuf line = STRBUF_INIT;
458 char *ptr;
460 fp = fopen(git_path("FETCH_HEAD"), "r");
461 if (!fp)
462 die_errno("could not open '%s' for reading",
463 git_path("FETCH_HEAD"));
464 strbuf_getline(&line, fp, '\n');
465 fclose(fp);
466 ptr = strstr(line.buf, "\tnot-for-merge\t");
467 if (ptr)
468 strbuf_remove(&line, ptr-line.buf+1, 13);
469 strbuf_addbuf(msg, &line);
470 strbuf_release(&line);
471 goto cleanup;
473 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
474 sha1_to_hex(remote_head->sha1), remote);
475 cleanup:
476 strbuf_release(&buf);
477 strbuf_release(&bname);
480 static int git_merge_config(const char *k, const char *v, void *cb)
482 if (branch && !prefixcmp(k, "branch.") &&
483 !prefixcmp(k + 7, branch) &&
484 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
485 const char **argv;
486 int argc;
487 char *buf;
489 buf = xstrdup(v);
490 argc = split_cmdline(buf, &argv);
491 if (argc < 0)
492 die("Bad branch.%s.mergeoptions string: %s", branch,
493 split_cmdline_strerror(argc));
494 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
495 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
496 argc++;
497 parse_options(argc, argv, NULL, builtin_merge_options,
498 builtin_merge_usage, 0);
499 free(buf);
502 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
503 show_diffstat = git_config_bool(k, v);
504 else if (!strcmp(k, "pull.twohead"))
505 return git_config_string(&pull_twohead, k, v);
506 else if (!strcmp(k, "pull.octopus"))
507 return git_config_string(&pull_octopus, k, v);
508 else if (!strcmp(k, "merge.renormalize"))
509 option_renormalize = git_config_bool(k, v);
510 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary")) {
511 int is_bool;
512 shortlog_len = git_config_bool_or_int(k, v, &is_bool);
513 if (!is_bool && shortlog_len < 0)
514 return error("%s: negative length %s", k, v);
515 if (is_bool && shortlog_len)
516 shortlog_len = DEFAULT_MERGE_LOG_LEN;
517 return 0;
519 return git_diff_ui_config(k, v, cb);
522 static int read_tree_trivial(unsigned char *common, unsigned char *head,
523 unsigned char *one)
525 int i, nr_trees = 0;
526 struct tree *trees[MAX_UNPACK_TREES];
527 struct tree_desc t[MAX_UNPACK_TREES];
528 struct unpack_trees_options opts;
530 memset(&opts, 0, sizeof(opts));
531 opts.head_idx = 2;
532 opts.src_index = &the_index;
533 opts.dst_index = &the_index;
534 opts.update = 1;
535 opts.verbose_update = 1;
536 opts.trivial_merges_only = 1;
537 opts.merge = 1;
538 trees[nr_trees] = parse_tree_indirect(common);
539 if (!trees[nr_trees++])
540 return -1;
541 trees[nr_trees] = parse_tree_indirect(head);
542 if (!trees[nr_trees++])
543 return -1;
544 trees[nr_trees] = parse_tree_indirect(one);
545 if (!trees[nr_trees++])
546 return -1;
547 opts.fn = threeway_merge;
548 cache_tree_free(&active_cache_tree);
549 for (i = 0; i < nr_trees; i++) {
550 parse_tree(trees[i]);
551 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
553 if (unpack_trees(nr_trees, t, &opts))
554 return -1;
555 return 0;
558 static void write_tree_trivial(unsigned char *sha1)
560 if (write_cache_as_tree(sha1, 0, NULL))
561 die("git write-tree failed to write a tree");
564 int try_merge_command(const char *strategy, struct commit_list *common,
565 const char *head_arg, struct commit_list *remotes)
567 const char **args;
568 int i = 0, x = 0, ret;
569 struct commit_list *j;
570 struct strbuf buf = STRBUF_INIT;
572 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
573 commit_list_count(remotes)) * sizeof(char *));
574 strbuf_addf(&buf, "merge-%s", strategy);
575 args[i++] = buf.buf;
576 for (x = 0; x < xopts_nr; x++) {
577 char *s = xmalloc(strlen(xopts[x])+2+1);
578 strcpy(s, "--");
579 strcpy(s+2, xopts[x]);
580 args[i++] = s;
582 for (j = common; j; j = j->next)
583 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
584 args[i++] = "--";
585 args[i++] = head_arg;
586 for (j = remotes; j; j = j->next)
587 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
588 args[i] = NULL;
589 ret = run_command_v_opt(args, RUN_GIT_CMD);
590 strbuf_release(&buf);
591 i = 1;
592 for (x = 0; x < xopts_nr; x++)
593 free((void *)args[i++]);
594 for (j = common; j; j = j->next)
595 free((void *)args[i++]);
596 i += 2;
597 for (j = remotes; j; j = j->next)
598 free((void *)args[i++]);
599 free(args);
600 discard_cache();
601 if (read_cache() < 0)
602 die("failed to read the cache");
603 resolve_undo_clear();
605 return ret;
608 static int try_merge_strategy(const char *strategy, struct commit_list *common,
609 const char *head_arg)
611 int index_fd;
612 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
614 index_fd = hold_locked_index(lock, 1);
615 refresh_cache(REFRESH_QUIET);
616 if (active_cache_changed &&
617 (write_cache(index_fd, active_cache, active_nr) ||
618 commit_locked_index(lock)))
619 return error("Unable to write index.");
620 rollback_lock_file(lock);
622 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
623 int clean, x;
624 struct commit *result;
625 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
626 int index_fd;
627 struct commit_list *reversed = NULL;
628 struct merge_options o;
629 struct commit_list *j;
631 if (remoteheads->next) {
632 error("Not handling anything other than two heads merge.");
633 return 2;
636 init_merge_options(&o);
637 if (!strcmp(strategy, "subtree"))
638 o.subtree_shift = "";
640 o.renormalize = option_renormalize;
642 for (x = 0; x < xopts_nr; x++)
643 if (parse_merge_opt(&o, xopts[x]))
644 die("Unknown option for merge-recursive: -X%s", xopts[x]);
646 o.branch1 = head_arg;
647 o.branch2 = remoteheads->item->util;
649 for (j = common; j; j = j->next)
650 commit_list_insert(j->item, &reversed);
652 index_fd = hold_locked_index(lock, 1);
653 clean = merge_recursive(&o, lookup_commit(head),
654 remoteheads->item, reversed, &result);
655 if (active_cache_changed &&
656 (write_cache(index_fd, active_cache, active_nr) ||
657 commit_locked_index(lock)))
658 die ("unable to write %s", get_index_file());
659 rollback_lock_file(lock);
660 return clean ? 0 : 1;
661 } else {
662 return try_merge_command(strategy, common, head_arg, remoteheads);
666 static void count_diff_files(struct diff_queue_struct *q,
667 struct diff_options *opt, void *data)
669 int *count = data;
671 (*count) += q->nr;
674 static int count_unmerged_entries(void)
676 int i, ret = 0;
678 for (i = 0; i < active_nr; i++)
679 if (ce_stage(active_cache[i]))
680 ret++;
682 return ret;
685 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
687 struct tree *trees[MAX_UNPACK_TREES];
688 struct unpack_trees_options opts;
689 struct tree_desc t[MAX_UNPACK_TREES];
690 int i, fd, nr_trees = 0;
691 struct dir_struct dir;
692 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
694 refresh_cache(REFRESH_QUIET);
696 fd = hold_locked_index(lock_file, 1);
698 memset(&trees, 0, sizeof(trees));
699 memset(&opts, 0, sizeof(opts));
700 memset(&t, 0, sizeof(t));
701 memset(&dir, 0, sizeof(dir));
702 dir.flags |= DIR_SHOW_IGNORED;
703 dir.exclude_per_dir = ".gitignore";
704 opts.dir = &dir;
706 opts.head_idx = 1;
707 opts.src_index = &the_index;
708 opts.dst_index = &the_index;
709 opts.update = 1;
710 opts.verbose_update = 1;
711 opts.merge = 1;
712 opts.fn = twoway_merge;
713 setup_unpack_trees_porcelain(&opts, "merge");
715 trees[nr_trees] = parse_tree_indirect(head);
716 if (!trees[nr_trees++])
717 return -1;
718 trees[nr_trees] = parse_tree_indirect(remote);
719 if (!trees[nr_trees++])
720 return -1;
721 for (i = 0; i < nr_trees; i++) {
722 parse_tree(trees[i]);
723 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
725 if (unpack_trees(nr_trees, t, &opts))
726 return -1;
727 if (write_cache(fd, active_cache, active_nr) ||
728 commit_locked_index(lock_file))
729 die("unable to write new index file");
730 return 0;
733 static void split_merge_strategies(const char *string, struct strategy **list,
734 int *nr, int *alloc)
736 char *p, *q, *buf;
738 if (!string)
739 return;
741 buf = xstrdup(string);
742 q = buf;
743 for (;;) {
744 p = strchr(q, ' ');
745 if (!p) {
746 ALLOC_GROW(*list, *nr + 1, *alloc);
747 (*list)[(*nr)++].name = xstrdup(q);
748 free(buf);
749 return;
750 } else {
751 *p = '\0';
752 ALLOC_GROW(*list, *nr + 1, *alloc);
753 (*list)[(*nr)++].name = xstrdup(q);
754 q = ++p;
759 static void add_strategies(const char *string, unsigned attr)
761 struct strategy *list = NULL;
762 int list_alloc = 0, list_nr = 0, i;
764 memset(&list, 0, sizeof(list));
765 split_merge_strategies(string, &list, &list_nr, &list_alloc);
766 if (list) {
767 for (i = 0; i < list_nr; i++)
768 append_strategy(get_strategy(list[i].name));
769 return;
771 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
772 if (all_strategy[i].attr & attr)
773 append_strategy(&all_strategy[i]);
777 static int merge_trivial(void)
779 unsigned char result_tree[20], result_commit[20];
780 struct commit_list *parent = xmalloc(sizeof(*parent));
782 write_tree_trivial(result_tree);
783 printf("Wonderful.\n");
784 parent->item = lookup_commit(head);
785 parent->next = xmalloc(sizeof(*parent->next));
786 parent->next->item = remoteheads->item;
787 parent->next->next = NULL;
788 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
789 finish(result_commit, "In-index merge");
790 drop_save();
791 return 0;
794 static int finish_automerge(struct commit_list *common,
795 unsigned char *result_tree,
796 const char *wt_strategy)
798 struct commit_list *parents = NULL, *j;
799 struct strbuf buf = STRBUF_INIT;
800 unsigned char result_commit[20];
802 free_commit_list(common);
803 if (allow_fast_forward) {
804 parents = remoteheads;
805 commit_list_insert(lookup_commit(head), &parents);
806 parents = reduce_heads(parents);
807 } else {
808 struct commit_list **pptr = &parents;
810 pptr = &commit_list_insert(lookup_commit(head),
811 pptr)->next;
812 for (j = remoteheads; j; j = j->next)
813 pptr = &commit_list_insert(j->item, pptr)->next;
815 free_commit_list(remoteheads);
816 strbuf_addch(&merge_msg, '\n');
817 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
818 strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
819 finish(result_commit, buf.buf);
820 strbuf_release(&buf);
821 drop_save();
822 return 0;
825 static int suggest_conflicts(int renormalizing)
827 FILE *fp;
828 int pos;
830 fp = fopen(git_path("MERGE_MSG"), "a");
831 if (!fp)
832 die_errno("Could not open '%s' for writing",
833 git_path("MERGE_MSG"));
834 fprintf(fp, "\nConflicts:\n");
835 for (pos = 0; pos < active_nr; pos++) {
836 struct cache_entry *ce = active_cache[pos];
838 if (ce_stage(ce)) {
839 fprintf(fp, "\t%s\n", ce->name);
840 while (pos + 1 < active_nr &&
841 !strcmp(ce->name,
842 active_cache[pos + 1]->name))
843 pos++;
846 fclose(fp);
847 rerere(allow_rerere_auto);
848 printf("Automatic merge failed; "
849 "fix conflicts and then commit the result.\n");
850 return 1;
853 static struct commit *is_old_style_invocation(int argc, const char **argv)
855 struct commit *second_token = NULL;
856 if (argc > 2) {
857 unsigned char second_sha1[20];
859 if (get_sha1(argv[1], second_sha1))
860 return NULL;
861 second_token = lookup_commit_reference_gently(second_sha1, 0);
862 if (!second_token)
863 die("'%s' is not a commit", argv[1]);
864 if (hashcmp(second_token->object.sha1, head))
865 return NULL;
867 return second_token;
870 static int evaluate_result(void)
872 int cnt = 0;
873 struct rev_info rev;
875 /* Check how many files differ. */
876 init_revisions(&rev, "");
877 setup_revisions(0, NULL, &rev, NULL);
878 rev.diffopt.output_format |=
879 DIFF_FORMAT_CALLBACK;
880 rev.diffopt.format_callback = count_diff_files;
881 rev.diffopt.format_callback_data = &cnt;
882 run_diff_files(&rev, 0);
885 * Check how many unmerged entries are
886 * there.
888 cnt += count_unmerged_entries();
890 return cnt;
893 int cmd_merge(int argc, const char **argv, const char *prefix)
895 unsigned char result_tree[20];
896 struct strbuf buf = STRBUF_INIT;
897 const char *head_arg;
898 int flag, head_invalid = 0, i;
899 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
900 struct commit_list *common = NULL;
901 const char *best_strategy = NULL, *wt_strategy = NULL;
902 struct commit_list **remotes = &remoteheads;
904 if (read_cache_unmerged()) {
905 die_resolve_conflict("merge");
907 if (file_exists(git_path("MERGE_HEAD"))) {
909 * There is no unmerged entry, don't advise 'git
910 * add/rm <file>', just 'git commit'.
912 if (advice_resolve_conflict)
913 die("You have not concluded your merge (MERGE_HEAD exists).\n"
914 "Please, commit your changes before you can merge.");
915 else
916 die("You have not concluded your merge (MERGE_HEAD exists).");
919 resolve_undo_clear();
921 * Check if we are _not_ on a detached HEAD, i.e. if there is a
922 * current branch.
924 branch = resolve_ref("HEAD", head, 0, &flag);
925 if (branch && !prefixcmp(branch, "refs/heads/"))
926 branch += 11;
927 if (is_null_sha1(head))
928 head_invalid = 1;
930 git_config(git_merge_config, NULL);
932 /* for color.ui */
933 if (diff_use_color_default == -1)
934 diff_use_color_default = git_use_color_default;
936 argc = parse_options(argc, argv, prefix, builtin_merge_options,
937 builtin_merge_usage, 0);
938 if (verbosity < 0)
939 show_diffstat = 0;
941 if (squash) {
942 if (!allow_fast_forward)
943 die("You cannot combine --squash with --no-ff.");
944 option_commit = 0;
947 if (!allow_fast_forward && fast_forward_only)
948 die("You cannot combine --no-ff with --ff-only.");
950 if (!argc)
951 usage_with_options(builtin_merge_usage,
952 builtin_merge_options);
955 * This could be traditional "merge <msg> HEAD <commit>..." and
956 * the way we can tell it is to see if the second token is HEAD,
957 * but some people might have misused the interface and used a
958 * committish that is the same as HEAD there instead.
959 * Traditional format never would have "-m" so it is an
960 * additional safety measure to check for it.
963 if (!have_message && is_old_style_invocation(argc, argv)) {
964 strbuf_addstr(&merge_msg, argv[0]);
965 head_arg = argv[1];
966 argv += 2;
967 argc -= 2;
968 } else if (head_invalid) {
969 struct object *remote_head;
971 * If the merged head is a valid one there is no reason
972 * to forbid "git merge" into a branch yet to be born.
973 * We do the same for "git pull".
975 if (argc != 1)
976 die("Can merge only exactly one commit into "
977 "empty head");
978 if (squash)
979 die("Squash commit into empty head not supported yet");
980 if (!allow_fast_forward)
981 die("Non-fast-forward commit does not make sense into "
982 "an empty head");
983 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
984 if (!remote_head)
985 die("%s - not something we can merge", argv[0]);
986 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
987 DIE_ON_ERR);
988 reset_hard(remote_head->sha1, 0);
989 return 0;
990 } else {
991 struct strbuf merge_names = STRBUF_INIT;
993 /* We are invoked directly as the first-class UI. */
994 head_arg = "HEAD";
997 * All the rest are the commits being merged;
998 * prepare the standard merge summary message to
999 * be appended to the given message. If remote
1000 * is invalid we will die later in the common
1001 * codepath so we discard the error in this
1002 * loop.
1004 for (i = 0; i < argc; i++)
1005 merge_name(argv[i], &merge_names);
1007 if (!have_message || shortlog_len) {
1008 fmt_merge_msg(&merge_names, &merge_msg, !have_message,
1009 shortlog_len);
1010 if (merge_msg.len)
1011 strbuf_setlen(&merge_msg, merge_msg.len - 1);
1015 if (head_invalid || !argc)
1016 usage_with_options(builtin_merge_usage,
1017 builtin_merge_options);
1019 strbuf_addstr(&buf, "merge");
1020 for (i = 0; i < argc; i++)
1021 strbuf_addf(&buf, " %s", argv[i]);
1022 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1023 strbuf_reset(&buf);
1025 for (i = 0; i < argc; i++) {
1026 struct object *o;
1027 struct commit *commit;
1029 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
1030 if (!o)
1031 die("%s - not something we can merge", argv[i]);
1032 commit = lookup_commit(o->sha1);
1033 commit->util = (void *)argv[i];
1034 remotes = &commit_list_insert(commit, remotes)->next;
1036 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1037 setenv(buf.buf, argv[i], 1);
1038 strbuf_reset(&buf);
1041 if (!use_strategies) {
1042 if (!remoteheads->next)
1043 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1044 else
1045 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1048 for (i = 0; i < use_strategies_nr; i++) {
1049 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1050 allow_fast_forward = 0;
1051 if (use_strategies[i]->attr & NO_TRIVIAL)
1052 allow_trivial = 0;
1055 if (!remoteheads->next)
1056 common = get_merge_bases(lookup_commit(head),
1057 remoteheads->item, 1);
1058 else {
1059 struct commit_list *list = remoteheads;
1060 commit_list_insert(lookup_commit(head), &list);
1061 common = get_octopus_merge_bases(list);
1062 free(list);
1065 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1066 DIE_ON_ERR);
1068 if (!common)
1069 ; /* No common ancestors found. We need a real merge. */
1070 else if (!remoteheads->next && !common->next &&
1071 common->item == remoteheads->item) {
1073 * If head can reach all the merge then we are up to date.
1074 * but first the most common case of merging one remote.
1076 finish_up_to_date("Already up-to-date.");
1077 return 0;
1078 } else if (allow_fast_forward && !remoteheads->next &&
1079 !common->next &&
1080 !hashcmp(common->item->object.sha1, head)) {
1081 /* Again the most common case of merging one remote. */
1082 struct strbuf msg = STRBUF_INIT;
1083 struct object *o;
1084 char hex[41];
1086 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1088 if (verbosity >= 0)
1089 printf("Updating %s..%s\n",
1090 hex,
1091 find_unique_abbrev(remoteheads->item->object.sha1,
1092 DEFAULT_ABBREV));
1093 strbuf_addstr(&msg, "Fast-forward");
1094 if (have_message)
1095 strbuf_addstr(&msg,
1096 " (no commit created; -m option ignored)");
1097 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1098 0, NULL, OBJ_COMMIT);
1099 if (!o)
1100 return 1;
1102 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1103 return 1;
1105 finish(o->sha1, msg.buf);
1106 drop_save();
1107 return 0;
1108 } else if (!remoteheads->next && common->next)
1111 * We are not doing octopus and not fast-forward. Need
1112 * a real merge.
1114 else if (!remoteheads->next && !common->next && option_commit) {
1116 * We are not doing octopus, not fast-forward, and have
1117 * only one common.
1119 refresh_cache(REFRESH_QUIET);
1120 if (allow_trivial && !fast_forward_only) {
1121 /* See if it is really trivial. */
1122 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1123 printf("Trying really trivial in-index merge...\n");
1124 if (!read_tree_trivial(common->item->object.sha1,
1125 head, remoteheads->item->object.sha1))
1126 return merge_trivial();
1127 printf("Nope.\n");
1129 } else {
1131 * An octopus. If we can reach all the remote we are up
1132 * to date.
1134 int up_to_date = 1;
1135 struct commit_list *j;
1137 for (j = remoteheads; j; j = j->next) {
1138 struct commit_list *common_one;
1141 * Here we *have* to calculate the individual
1142 * merge_bases again, otherwise "git merge HEAD^
1143 * HEAD^^" would be missed.
1145 common_one = get_merge_bases(lookup_commit(head),
1146 j->item, 1);
1147 if (hashcmp(common_one->item->object.sha1,
1148 j->item->object.sha1)) {
1149 up_to_date = 0;
1150 break;
1153 if (up_to_date) {
1154 finish_up_to_date("Already up-to-date. Yeeah!");
1155 return 0;
1159 if (fast_forward_only)
1160 die("Not possible to fast-forward, aborting.");
1162 /* We are going to make a new commit. */
1163 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1166 * At this point, we need a real merge. No matter what strategy
1167 * we use, it would operate on the index, possibly affecting the
1168 * working tree, and when resolved cleanly, have the desired
1169 * tree in the index -- this means that the index must be in
1170 * sync with the head commit. The strategies are responsible
1171 * to ensure this.
1173 if (use_strategies_nr != 1) {
1175 * Stash away the local changes so that we can try more
1176 * than one.
1178 save_state();
1179 } else {
1180 memcpy(stash, null_sha1, 20);
1183 for (i = 0; i < use_strategies_nr; i++) {
1184 int ret;
1185 if (i) {
1186 printf("Rewinding the tree to pristine...\n");
1187 restore_state();
1189 if (use_strategies_nr != 1)
1190 printf("Trying merge strategy %s...\n",
1191 use_strategies[i]->name);
1193 * Remember which strategy left the state in the working
1194 * tree.
1196 wt_strategy = use_strategies[i]->name;
1198 ret = try_merge_strategy(use_strategies[i]->name,
1199 common, head_arg);
1200 if (!option_commit && !ret) {
1201 merge_was_ok = 1;
1203 * This is necessary here just to avoid writing
1204 * the tree, but later we will *not* exit with
1205 * status code 1 because merge_was_ok is set.
1207 ret = 1;
1210 if (ret) {
1212 * The backend exits with 1 when conflicts are
1213 * left to be resolved, with 2 when it does not
1214 * handle the given merge at all.
1216 if (ret == 1) {
1217 int cnt = evaluate_result();
1219 if (best_cnt <= 0 || cnt <= best_cnt) {
1220 best_strategy = use_strategies[i]->name;
1221 best_cnt = cnt;
1224 if (merge_was_ok)
1225 break;
1226 else
1227 continue;
1230 /* Automerge succeeded. */
1231 write_tree_trivial(result_tree);
1232 automerge_was_ok = 1;
1233 break;
1237 * If we have a resulting tree, that means the strategy module
1238 * auto resolved the merge cleanly.
1240 if (automerge_was_ok)
1241 return finish_automerge(common, result_tree, wt_strategy);
1244 * Pick the result from the best strategy and have the user fix
1245 * it up.
1247 if (!best_strategy) {
1248 restore_state();
1249 if (use_strategies_nr > 1)
1250 fprintf(stderr,
1251 "No merge strategy handled the merge.\n");
1252 else
1253 fprintf(stderr, "Merge with strategy %s failed.\n",
1254 use_strategies[0]->name);
1255 return 2;
1256 } else if (best_strategy == wt_strategy)
1257 ; /* We already have its result in the working tree. */
1258 else {
1259 printf("Rewinding the tree to pristine...\n");
1260 restore_state();
1261 printf("Using the %s to prepare resolving by hand.\n",
1262 best_strategy);
1263 try_merge_strategy(best_strategy, common, head_arg);
1266 if (squash)
1267 finish(NULL, NULL);
1268 else {
1269 int fd;
1270 struct commit_list *j;
1272 for (j = remoteheads; j; j = j->next)
1273 strbuf_addf(&buf, "%s\n",
1274 sha1_to_hex(j->item->object.sha1));
1275 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1276 if (fd < 0)
1277 die_errno("Could not open '%s' for writing",
1278 git_path("MERGE_HEAD"));
1279 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1280 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1281 close(fd);
1282 strbuf_addch(&merge_msg, '\n');
1283 fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1284 if (fd < 0)
1285 die_errno("Could not open '%s' for writing",
1286 git_path("MERGE_MSG"));
1287 if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1288 merge_msg.len)
1289 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1290 close(fd);
1291 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1292 if (fd < 0)
1293 die_errno("Could not open '%s' for writing",
1294 git_path("MERGE_MODE"));
1295 strbuf_reset(&buf);
1296 if (!allow_fast_forward)
1297 strbuf_addf(&buf, "no-ff");
1298 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1299 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1300 close(fd);
1303 if (merge_was_ok) {
1304 fprintf(stderr, "Automatic merge went well; "
1305 "stopped before committing as requested\n");
1306 return 0;
1307 } else
1308 return suggest_conflicts(option_renormalize);