1 /*
2 * Builtin "git merge"
3 *
4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
5 *
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;
37 };
39 static const char * const builtin_merge_usage[] = {
40 "git merge [options] <remote>...",
41 "git merge [options] <msg> HEAD <remote>",
42 NULL
43 };
45 static int show_diffstat = 1, option_log, squash;
46 static int option_commit = 1, allow_fast_forward = 1;
47 static int fast_forward_only;
48 static int allow_trivial = 1, have_message;
49 static struct strbuf merge_msg;
50 static struct commit_list *remoteheads;
51 static unsigned char head[20], stash[20];
52 static struct strategy **use_strategies;
53 static size_t use_strategies_nr, use_strategies_alloc;
54 static const char **xopts;
55 static size_t xopts_nr, xopts_alloc;
56 static const char *branch;
57 static int 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 },
67 };
69 static const char *pull_twohead, *pull_octopus;
71 static int option_parse_message(const struct option *opt,
72 const char *arg, int unset)
73 {
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;
84 }
86 static struct strategy *get_strategy(const char *name)
87 {
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(¬_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(¬_strategies, ent->name, ent->len);
115 }
116 exclude_cmds(&main_cmds, ¬_strategies);
117 }
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");
129 }
130 exit(1);
131 }
133 ret = xcalloc(1, sizeof(struct strategy));
134 ret->name = xstrdup(name);
135 ret->attr = NO_TRIVIAL;
136 return ret;
137 }
139 static void append_strategy(struct strategy *s)
140 {
141 ALLOC_GROW(use_strategies, use_strategies_nr + 1, use_strategies_alloc);
142 use_strategies[use_strategies_nr++] = s;
143 }
145 static int option_parse_strategy(const struct option *opt,
146 const char *name, int unset)
147 {
148 if (unset)
149 return 0;
151 append_strategy(get_strategy(name));
152 return 0;
153 }
155 static int option_parse_x(const struct option *opt,
156 const char *arg, int unset)
157 {
158 if (unset)
159 return 0;
161 ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
162 xopts[xopts_nr++] = xstrdup(arg);
163 return 0;
164 }
166 static int option_parse_n(const struct option *opt,
167 const char *arg, int unset)
168 {
169 show_diffstat = unset;
170 return 0;
171 }
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 OPT_BOOLEAN(0, "log", &option_log,
181 "add list of one-line log to merge commit message"),
182 OPT_BOOLEAN(0, "squash", &squash,
183 "create a single commit instead of doing a merge"),
184 OPT_BOOLEAN(0, "commit", &option_commit,
185 "perform a commit if the merge succeeds (default)"),
186 OPT_BOOLEAN(0, "ff", &allow_fast_forward,
187 "allow fast-forward (default)"),
188 OPT_BOOLEAN(0, "ff-only", &fast_forward_only,
189 "abort if fast-forward is not possible"),
190 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
191 OPT_CALLBACK('s', "strategy", &use_strategies, "strategy",
192 "merge strategy to use", option_parse_strategy),
193 OPT_CALLBACK('X', "strategy-option", &xopts, "option=value",
194 "option for selected merge strategy", option_parse_x),
195 OPT_CALLBACK('m', "message", &merge_msg, "message",
196 "message to be used for the merge commit (if any)",
197 option_parse_message),
198 OPT__VERBOSITY(&verbosity),
199 OPT_END()
200 };
202 /* Cleans up metadata that is uninteresting after a succeeded merge. */
203 static void drop_save(void)
204 {
205 unlink(git_path("MERGE_HEAD"));
206 unlink(git_path("MERGE_MSG"));
207 unlink(git_path("MERGE_MODE"));
208 }
210 static void save_state(void)
211 {
212 int len;
213 struct child_process cp;
214 struct strbuf buffer = STRBUF_INIT;
215 const char *argv[] = {"stash", "create", NULL};
217 memset(&cp, 0, sizeof(cp));
218 cp.argv = argv;
219 cp.out = -1;
220 cp.git_cmd = 1;
222 if (start_command(&cp))
223 die("could not run stash.");
224 len = strbuf_read(&buffer, cp.out, 1024);
225 close(cp.out);
227 if (finish_command(&cp) || len < 0)
228 die("stash failed");
229 else if (!len)
230 return;
231 strbuf_setlen(&buffer, buffer.len-1);
232 if (get_sha1(buffer.buf, stash))
233 die("not a valid object: %s", buffer.buf);
234 }
236 static void read_empty(unsigned const char *sha1, int verbose)
237 {
238 int i = 0;
239 const char *args[7];
241 args[i++] = "read-tree";
242 if (verbose)
243 args[i++] = "-v";
244 args[i++] = "-m";
245 args[i++] = "-u";
246 args[i++] = EMPTY_TREE_SHA1_HEX;
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");
252 }
254 static void reset_hard(unsigned const char *sha1, int verbose)
255 {
256 int i = 0;
257 const char *args[6];
259 args[i++] = "read-tree";
260 if (verbose)
261 args[i++] = "-v";
262 args[i++] = "--reset";
263 args[i++] = "-u";
264 args[i++] = sha1_to_hex(sha1);
265 args[i] = NULL;
267 if (run_command_v_opt(args, RUN_GIT_CMD))
268 die("read-tree failed");
269 }
271 static void restore_state(void)
272 {
273 struct strbuf sb = STRBUF_INIT;
274 const char *args[] = { "stash", "apply", NULL, NULL };
276 if (is_null_sha1(stash))
277 return;
279 reset_hard(head, 1);
281 args[2] = sha1_to_hex(stash);
283 /*
284 * It is OK to ignore error here, for example when there was
285 * nothing to restore.
286 */
287 run_command_v_opt(args, RUN_GIT_CMD);
289 strbuf_release(&sb);
290 refresh_cache(REFRESH_QUIET);
291 }
293 /* This is called when no merge was necessary. */
294 static void finish_up_to_date(const char *msg)
295 {
296 if (verbosity >= 0)
297 printf("%s%s\n", squash ? " (nothing to squash)" : "", msg);
298 drop_save();
299 }
301 static void squash_message(void)
302 {
303 struct rev_info rev;
304 struct commit *commit;
305 struct strbuf out = STRBUF_INIT;
306 struct commit_list *j;
307 int fd;
308 struct pretty_print_context ctx = {0};
310 printf("Squash commit -- not updating HEAD\n");
311 fd = open(git_path("SQUASH_MSG"), O_WRONLY | O_CREAT, 0666);
312 if (fd < 0)
313 die_errno("Could not write to '%s'", git_path("SQUASH_MSG"));
315 init_revisions(&rev, NULL);
316 rev.ignore_merges = 1;
317 rev.commit_format = CMIT_FMT_MEDIUM;
319 commit = lookup_commit(head);
320 commit->object.flags |= UNINTERESTING;
321 add_pending_object(&rev, &commit->object, NULL);
323 for (j = remoteheads; j; j = j->next)
324 add_pending_object(&rev, &j->item->object, NULL);
326 setup_revisions(0, NULL, &rev, NULL);
327 if (prepare_revision_walk(&rev))
328 die("revision walk setup failed");
330 ctx.abbrev = rev.abbrev;
331 ctx.date_mode = rev.date_mode;
333 strbuf_addstr(&out, "Squashed commit of the following:\n");
334 while ((commit = get_revision(&rev)) != NULL) {
335 strbuf_addch(&out, '\n');
336 strbuf_addf(&out, "commit %s\n",
337 sha1_to_hex(commit->object.sha1));
338 pretty_print_commit(rev.commit_format, commit, &out, &ctx);
339 }
340 if (write(fd, out.buf, out.len) < 0)
341 die_errno("Writing SQUASH_MSG");
342 if (close(fd))
343 die_errno("Finishing SQUASH_MSG");
344 strbuf_release(&out);
345 }
347 static void finish(const unsigned char *new_head, const char *msg)
348 {
349 struct strbuf reflog_message = STRBUF_INIT;
351 if (!msg)
352 strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION"));
353 else {
354 if (verbosity >= 0)
355 printf("%s\n", msg);
356 strbuf_addf(&reflog_message, "%s: %s",
357 getenv("GIT_REFLOG_ACTION"), msg);
358 }
359 if (squash) {
360 squash_message();
361 } else {
362 if (verbosity >= 0 && !merge_msg.len)
363 printf("No merge message -- not updating HEAD\n");
364 else {
365 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
366 update_ref(reflog_message.buf, "HEAD",
367 new_head, head, 0,
368 DIE_ON_ERR);
369 /*
370 * We ignore errors in 'gc --auto', since the
371 * user should see them.
372 */
373 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
374 }
375 }
376 if (new_head && show_diffstat) {
377 struct diff_options opts;
378 diff_setup(&opts);
379 opts.output_format |=
380 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
381 opts.detect_rename = DIFF_DETECT_RENAME;
382 if (diff_use_color_default > 0)
383 DIFF_OPT_SET(&opts, COLOR_DIFF);
384 if (diff_setup_done(&opts) < 0)
385 die("diff_setup_done failed");
386 diff_tree_sha1(head, new_head, "", &opts);
387 diffcore_std(&opts);
388 diff_flush(&opts);
389 }
391 /* Run a post-merge hook */
392 run_hook(NULL, "post-merge", squash ? "1" : "0", NULL);
394 strbuf_release(&reflog_message);
395 }
397 /* Get the name for the merge commit's message. */
398 static void merge_name(const char *remote, struct strbuf *msg)
399 {
400 struct object *remote_head;
401 unsigned char branch_head[20], buf_sha[20];
402 struct strbuf buf = STRBUF_INIT;
403 struct strbuf bname = STRBUF_INIT;
404 const char *ptr;
405 char *found_ref;
406 int len, early;
408 strbuf_branchname(&bname, remote);
409 remote = bname.buf;
411 memset(branch_head, 0, sizeof(branch_head));
412 remote_head = peel_to_type(remote, 0, NULL, OBJ_COMMIT);
413 if (!remote_head)
414 die("'%s' does not point to a commit", remote);
416 if (dwim_ref(remote, strlen(remote), branch_head, &found_ref) > 0) {
417 if (!prefixcmp(found_ref, "refs/heads/")) {
418 strbuf_addf(msg, "%s\t\tbranch '%s' of .\n",
419 sha1_to_hex(branch_head), remote);
420 goto cleanup;
421 }
422 if (!prefixcmp(found_ref, "refs/remotes/")) {
423 strbuf_addf(msg, "%s\t\tremote branch '%s' of .\n",
424 sha1_to_hex(branch_head), remote);
425 goto cleanup;
426 }
427 }
429 /* See if remote matches <name>^^^.. or <name>~<number> */
430 for (len = 0, ptr = remote + strlen(remote);
431 remote < ptr && ptr[-1] == '^';
432 ptr--)
433 len++;
434 if (len)
435 early = 1;
436 else {
437 early = 0;
438 ptr = strrchr(remote, '~');
439 if (ptr) {
440 int seen_nonzero = 0;
442 len++; /* count ~ */
443 while (*++ptr && isdigit(*ptr)) {
444 seen_nonzero |= (*ptr != '0');
445 len++;
446 }
447 if (*ptr)
448 len = 0; /* not ...~<number> */
449 else if (seen_nonzero)
450 early = 1;
451 else if (len == 1)
452 early = 1; /* "name~" is "name~1"! */
453 }
454 }
455 if (len) {
456 struct strbuf truname = STRBUF_INIT;
457 strbuf_addstr(&truname, "refs/heads/");
458 strbuf_addstr(&truname, remote);
459 strbuf_setlen(&truname, truname.len - len);
460 if (resolve_ref(truname.buf, buf_sha, 1, NULL)) {
461 strbuf_addf(msg,
462 "%s\t\tbranch '%s'%s of .\n",
463 sha1_to_hex(remote_head->sha1),
464 truname.buf + 11,
465 (early ? " (early part)" : ""));
466 strbuf_release(&truname);
467 goto cleanup;
468 }
469 }
471 if (!strcmp(remote, "FETCH_HEAD") &&
472 !access(git_path("FETCH_HEAD"), R_OK)) {
473 FILE *fp;
474 struct strbuf line = STRBUF_INIT;
475 char *ptr;
477 fp = fopen(git_path("FETCH_HEAD"), "r");
478 if (!fp)
479 die_errno("could not open '%s' for reading",
480 git_path("FETCH_HEAD"));
481 strbuf_getline(&line, fp, '\n');
482 fclose(fp);
483 ptr = strstr(line.buf, "\tnot-for-merge\t");
484 if (ptr)
485 strbuf_remove(&line, ptr-line.buf+1, 13);
486 strbuf_addbuf(msg, &line);
487 strbuf_release(&line);
488 goto cleanup;
489 }
490 strbuf_addf(msg, "%s\t\tcommit '%s'\n",
491 sha1_to_hex(remote_head->sha1), remote);
492 cleanup:
493 strbuf_release(&buf);
494 strbuf_release(&bname);
495 }
497 static int git_merge_config(const char *k, const char *v, void *cb)
498 {
499 if (branch && !prefixcmp(k, "branch.") &&
500 !prefixcmp(k + 7, branch) &&
501 !strcmp(k + 7 + strlen(branch), ".mergeoptions")) {
502 const char **argv;
503 int argc;
504 char *buf;
506 buf = xstrdup(v);
507 argc = split_cmdline(buf, &argv);
508 if (argc < 0)
509 die("Bad branch.%s.mergeoptions string: %s", branch,
510 split_cmdline_strerror(argc));
511 argv = xrealloc(argv, sizeof(*argv) * (argc + 2));
512 memmove(argv + 1, argv, sizeof(*argv) * (argc + 1));
513 argc++;
514 parse_options(argc, argv, NULL, builtin_merge_options,
515 builtin_merge_usage, 0);
516 free(buf);
517 }
519 if (!strcmp(k, "merge.diffstat") || !strcmp(k, "merge.stat"))
520 show_diffstat = git_config_bool(k, v);
521 else if (!strcmp(k, "pull.twohead"))
522 return git_config_string(&pull_twohead, k, v);
523 else if (!strcmp(k, "pull.octopus"))
524 return git_config_string(&pull_octopus, k, v);
525 else if (!strcmp(k, "merge.log") || !strcmp(k, "merge.summary"))
526 option_log = git_config_bool(k, v);
527 else if (!strcmp(k, "merge.renormalize"))
528 option_renormalize = git_config_bool(k, v);
529 return git_diff_ui_config(k, v, cb);
530 }
532 static int read_tree_trivial(unsigned char *common, unsigned char *head,
533 unsigned char *one)
534 {
535 int i, nr_trees = 0;
536 struct tree *trees[MAX_UNPACK_TREES];
537 struct tree_desc t[MAX_UNPACK_TREES];
538 struct unpack_trees_options opts;
540 memset(&opts, 0, sizeof(opts));
541 opts.head_idx = 2;
542 opts.src_index = &the_index;
543 opts.dst_index = &the_index;
544 opts.update = 1;
545 opts.verbose_update = 1;
546 opts.trivial_merges_only = 1;
547 opts.merge = 1;
548 trees[nr_trees] = parse_tree_indirect(common);
549 if (!trees[nr_trees++])
550 return -1;
551 trees[nr_trees] = parse_tree_indirect(head);
552 if (!trees[nr_trees++])
553 return -1;
554 trees[nr_trees] = parse_tree_indirect(one);
555 if (!trees[nr_trees++])
556 return -1;
557 opts.fn = threeway_merge;
558 cache_tree_free(&active_cache_tree);
559 for (i = 0; i < nr_trees; i++) {
560 parse_tree(trees[i]);
561 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
562 }
563 if (unpack_trees(nr_trees, t, &opts))
564 return -1;
565 return 0;
566 }
568 static void write_tree_trivial(unsigned char *sha1)
569 {
570 if (write_cache_as_tree(sha1, 0, NULL))
571 die("git write-tree failed to write a tree");
572 }
574 int try_merge_command(const char *strategy, struct commit_list *common,
575 const char *head_arg, struct commit_list *remotes)
576 {
577 const char **args;
578 int i = 0, x = 0, ret;
579 struct commit_list *j;
580 struct strbuf buf = STRBUF_INIT;
582 args = xmalloc((4 + xopts_nr + commit_list_count(common) +
583 commit_list_count(remotes)) * sizeof(char *));
584 strbuf_addf(&buf, "merge-%s", strategy);
585 args[i++] = buf.buf;
586 for (x = 0; x < xopts_nr; x++) {
587 char *s = xmalloc(strlen(xopts[x])+2+1);
588 strcpy(s, "--");
589 strcpy(s+2, xopts[x]);
590 args[i++] = s;
591 }
592 for (j = common; j; j = j->next)
593 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
594 args[i++] = "--";
595 args[i++] = head_arg;
596 for (j = remotes; j; j = j->next)
597 args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1));
598 args[i] = NULL;
599 ret = run_command_v_opt(args, RUN_GIT_CMD);
600 strbuf_release(&buf);
601 i = 1;
602 for (x = 0; x < xopts_nr; x++)
603 free((void *)args[i++]);
604 for (j = common; j; j = j->next)
605 free((void *)args[i++]);
606 i += 2;
607 for (j = remotes; j; j = j->next)
608 free((void *)args[i++]);
609 free(args);
610 discard_cache();
611 if (read_cache() < 0)
612 die("failed to read the cache");
613 resolve_undo_clear();
615 return ret;
616 }
618 static int try_merge_strategy(const char *strategy, struct commit_list *common,
619 const char *head_arg)
620 {
621 int index_fd;
622 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
624 index_fd = hold_locked_index(lock, 1);
625 refresh_cache(REFRESH_QUIET);
626 if (active_cache_changed &&
627 (write_cache(index_fd, active_cache, active_nr) ||
628 commit_locked_index(lock)))
629 return error("Unable to write index.");
630 rollback_lock_file(lock);
632 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) {
633 int clean, x;
634 struct commit *result;
635 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
636 int index_fd;
637 struct commit_list *reversed = NULL;
638 struct merge_options o;
639 struct commit_list *j;
641 if (remoteheads->next) {
642 error("Not handling anything other than two heads merge.");
643 return 2;
644 }
646 init_merge_options(&o);
647 if (!strcmp(strategy, "subtree"))
648 o.subtree_shift = "";
650 o.renormalize = option_renormalize;
652 /*
653 * NEEDSWORK: merge with table in builtin/merge-recursive
654 */
655 for (x = 0; x < xopts_nr; x++) {
656 if (!strcmp(xopts[x], "ours"))
657 o.recursive_variant = MERGE_RECURSIVE_OURS;
658 else if (!strcmp(xopts[x], "theirs"))
659 o.recursive_variant = MERGE_RECURSIVE_THEIRS;
660 else if (!strcmp(xopts[x], "subtree"))
661 o.subtree_shift = "";
662 else if (!prefixcmp(xopts[x], "subtree="))
663 o.subtree_shift = xopts[x]+8;
664 else if (!strcmp(xopts[x], "renormalize"))
665 o.renormalize = 1;
666 else if (!strcmp(xopts[x], "no-renormalize"))
667 o.renormalize = 0;
668 else
669 die("Unknown option for merge-recursive: -X%s", xopts[x]);
670 }
672 o.branch1 = head_arg;
673 o.branch2 = remoteheads->item->util;
675 for (j = common; j; j = j->next)
676 commit_list_insert(j->item, &reversed);
678 index_fd = hold_locked_index(lock, 1);
679 clean = merge_recursive(&o, lookup_commit(head),
680 remoteheads->item, reversed, &result);
681 if (active_cache_changed &&
682 (write_cache(index_fd, active_cache, active_nr) ||
683 commit_locked_index(lock)))
684 die ("unable to write %s", get_index_file());
685 rollback_lock_file(lock);
686 return clean ? 0 : 1;
687 } else {
688 return try_merge_command(strategy, common, head_arg, remoteheads);
689 }
690 }
692 static void count_diff_files(struct diff_queue_struct *q,
693 struct diff_options *opt, void *data)
694 {
695 int *count = data;
697 (*count) += q->nr;
698 }
700 static int count_unmerged_entries(void)
701 {
702 int i, ret = 0;
704 for (i = 0; i < active_nr; i++)
705 if (ce_stage(active_cache[i]))
706 ret++;
708 return ret;
709 }
711 int checkout_fast_forward(const unsigned char *head, const unsigned char *remote)
712 {
713 struct tree *trees[MAX_UNPACK_TREES];
714 struct unpack_trees_options opts;
715 struct tree_desc t[MAX_UNPACK_TREES];
716 int i, fd, nr_trees = 0;
717 struct dir_struct dir;
718 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
720 refresh_cache(REFRESH_QUIET);
722 fd = hold_locked_index(lock_file, 1);
724 memset(&trees, 0, sizeof(trees));
725 memset(&opts, 0, sizeof(opts));
726 memset(&t, 0, sizeof(t));
727 memset(&dir, 0, sizeof(dir));
728 dir.flags |= DIR_SHOW_IGNORED;
729 dir.exclude_per_dir = ".gitignore";
730 opts.dir = &dir;
732 opts.head_idx = 1;
733 opts.src_index = &the_index;
734 opts.dst_index = &the_index;
735 opts.update = 1;
736 opts.verbose_update = 1;
737 opts.merge = 1;
738 opts.fn = twoway_merge;
739 setup_unpack_trees_porcelain(&opts, "merge");
741 trees[nr_trees] = parse_tree_indirect(head);
742 if (!trees[nr_trees++])
743 return -1;
744 trees[nr_trees] = parse_tree_indirect(remote);
745 if (!trees[nr_trees++])
746 return -1;
747 for (i = 0; i < nr_trees; i++) {
748 parse_tree(trees[i]);
749 init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
750 }
751 if (unpack_trees(nr_trees, t, &opts))
752 return -1;
753 if (write_cache(fd, active_cache, active_nr) ||
754 commit_locked_index(lock_file))
755 die("unable to write new index file");
756 return 0;
757 }
759 static void split_merge_strategies(const char *string, struct strategy **list,
760 int *nr, int *alloc)
761 {
762 char *p, *q, *buf;
764 if (!string)
765 return;
767 buf = xstrdup(string);
768 q = buf;
769 for (;;) {
770 p = strchr(q, ' ');
771 if (!p) {
772 ALLOC_GROW(*list, *nr + 1, *alloc);
773 (*list)[(*nr)++].name = xstrdup(q);
774 free(buf);
775 return;
776 } else {
777 *p = '\0';
778 ALLOC_GROW(*list, *nr + 1, *alloc);
779 (*list)[(*nr)++].name = xstrdup(q);
780 q = ++p;
781 }
782 }
783 }
785 static void add_strategies(const char *string, unsigned attr)
786 {
787 struct strategy *list = NULL;
788 int list_alloc = 0, list_nr = 0, i;
790 memset(&list, 0, sizeof(list));
791 split_merge_strategies(string, &list, &list_nr, &list_alloc);
792 if (list) {
793 for (i = 0; i < list_nr; i++)
794 append_strategy(get_strategy(list[i].name));
795 return;
796 }
797 for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
798 if (all_strategy[i].attr & attr)
799 append_strategy(&all_strategy[i]);
801 }
803 static int merge_trivial(void)
804 {
805 unsigned char result_tree[20], result_commit[20];
806 struct commit_list *parent = xmalloc(sizeof(*parent));
808 write_tree_trivial(result_tree);
809 printf("Wonderful.\n");
810 parent->item = lookup_commit(head);
811 parent->next = xmalloc(sizeof(*parent->next));
812 parent->next->item = remoteheads->item;
813 parent->next->next = NULL;
814 commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL);
815 finish(result_commit, "In-index merge");
816 drop_save();
817 return 0;
818 }
820 static int finish_automerge(struct commit_list *common,
821 unsigned char *result_tree,
822 const char *wt_strategy)
823 {
824 struct commit_list *parents = NULL, *j;
825 struct strbuf buf = STRBUF_INIT;
826 unsigned char result_commit[20];
828 free_commit_list(common);
829 if (allow_fast_forward) {
830 parents = remoteheads;
831 commit_list_insert(lookup_commit(head), &parents);
832 parents = reduce_heads(parents);
833 } else {
834 struct commit_list **pptr = &parents;
836 pptr = &commit_list_insert(lookup_commit(head),
837 pptr)->next;
838 for (j = remoteheads; j; j = j->next)
839 pptr = &commit_list_insert(j->item, pptr)->next;
840 }
841 free_commit_list(remoteheads);
842 strbuf_addch(&merge_msg, '\n');
843 commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL);
844 strbuf_addf(&buf, "Merge made by %s.", wt_strategy);
845 finish(result_commit, buf.buf);
846 strbuf_release(&buf);
847 drop_save();
848 return 0;
849 }
851 static int suggest_conflicts(int renormalizing)
852 {
853 FILE *fp;
854 int pos;
856 fp = fopen(git_path("MERGE_MSG"), "a");
857 if (!fp)
858 die_errno("Could not open '%s' for writing",
859 git_path("MERGE_MSG"));
860 fprintf(fp, "\nConflicts:\n");
861 for (pos = 0; pos < active_nr; pos++) {
862 struct cache_entry *ce = active_cache[pos];
864 if (ce_stage(ce)) {
865 fprintf(fp, "\t%s\n", ce->name);
866 while (pos + 1 < active_nr &&
867 !strcmp(ce->name,
868 active_cache[pos + 1]->name))
869 pos++;
870 }
871 }
872 fclose(fp);
873 rerere(allow_rerere_auto);
874 printf("Automatic merge failed; "
875 "fix conflicts and then commit the result.\n");
876 return 1;
877 }
879 static struct commit *is_old_style_invocation(int argc, const char **argv)
880 {
881 struct commit *second_token = NULL;
882 if (argc > 2) {
883 unsigned char second_sha1[20];
885 if (get_sha1(argv[1], second_sha1))
886 return NULL;
887 second_token = lookup_commit_reference_gently(second_sha1, 0);
888 if (!second_token)
889 die("'%s' is not a commit", argv[1]);
890 if (hashcmp(second_token->object.sha1, head))
891 return NULL;
892 }
893 return second_token;
894 }
896 static int evaluate_result(void)
897 {
898 int cnt = 0;
899 struct rev_info rev;
901 /* Check how many files differ. */
902 init_revisions(&rev, "");
903 setup_revisions(0, NULL, &rev, NULL);
904 rev.diffopt.output_format |=
905 DIFF_FORMAT_CALLBACK;
906 rev.diffopt.format_callback = count_diff_files;
907 rev.diffopt.format_callback_data = &cnt;
908 run_diff_files(&rev, 0);
910 /*
911 * Check how many unmerged entries are
912 * there.
913 */
914 cnt += count_unmerged_entries();
916 return cnt;
917 }
919 int cmd_merge(int argc, const char **argv, const char *prefix)
920 {
921 unsigned char result_tree[20];
922 struct strbuf buf = STRBUF_INIT;
923 const char *head_arg;
924 int flag, head_invalid = 0, i;
925 int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
926 struct commit_list *common = NULL;
927 const char *best_strategy = NULL, *wt_strategy = NULL;
928 struct commit_list **remotes = &remoteheads;
930 if (read_cache_unmerged()) {
931 die_resolve_conflict("merge");
932 }
933 if (file_exists(git_path("MERGE_HEAD"))) {
934 /*
935 * There is no unmerged entry, don't advise 'git
936 * add/rm <file>', just 'git commit'.
937 */
938 if (advice_resolve_conflict)
939 die("You have not concluded your merge (MERGE_HEAD exists).\n"
940 "Please, commit your changes before you can merge.");
941 else
942 die("You have not concluded your merge (MERGE_HEAD exists).");
943 }
945 resolve_undo_clear();
946 /*
947 * Check if we are _not_ on a detached HEAD, i.e. if there is a
948 * current branch.
949 */
950 branch = resolve_ref("HEAD", head, 0, &flag);
951 if (branch && !prefixcmp(branch, "refs/heads/"))
952 branch += 11;
953 if (is_null_sha1(head))
954 head_invalid = 1;
956 git_config(git_merge_config, NULL);
958 /* for color.ui */
959 if (diff_use_color_default == -1)
960 diff_use_color_default = git_use_color_default;
962 argc = parse_options(argc, argv, prefix, builtin_merge_options,
963 builtin_merge_usage, 0);
964 if (verbosity < 0)
965 show_diffstat = 0;
967 if (squash) {
968 if (!allow_fast_forward)
969 die("You cannot combine --squash with --no-ff.");
970 option_commit = 0;
971 }
973 if (!allow_fast_forward && fast_forward_only)
974 die("You cannot combine --no-ff with --ff-only.");
976 if (!argc)
977 usage_with_options(builtin_merge_usage,
978 builtin_merge_options);
980 /*
981 * This could be traditional "merge <msg> HEAD <commit>..." and
982 * the way we can tell it is to see if the second token is HEAD,
983 * but some people might have misused the interface and used a
984 * committish that is the same as HEAD there instead.
985 * Traditional format never would have "-m" so it is an
986 * additional safety measure to check for it.
987 */
989 if (!have_message && is_old_style_invocation(argc, argv)) {
990 strbuf_addstr(&merge_msg, argv[0]);
991 head_arg = argv[1];
992 argv += 2;
993 argc -= 2;
994 } else if (head_invalid) {
995 struct object *remote_head;
996 /*
997 * If the merged head is a valid one there is no reason
998 * to forbid "git merge" into a branch yet to be born.
999 * We do the same for "git pull".
1000 */
1001 if (argc != 1)
1002 die("Can merge only exactly one commit into "
1003 "empty head");
1004 if (squash)
1005 die("Squash commit into empty head not supported yet");
1006 if (!allow_fast_forward)
1007 die("Non-fast-forward commit does not make sense into "
1008 "an empty head");
1009 remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
1010 if (!remote_head)
1011 die("%s - not something we can merge", argv[0]);
1012 update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
1013 DIE_ON_ERR);
1014 read_empty(remote_head->sha1, 0);
1015 return 0;
1016 } else {
1017 struct strbuf merge_names = STRBUF_INIT;
1019 /* We are invoked directly as the first-class UI. */
1020 head_arg = "HEAD";
1022 /*
1023 * All the rest are the commits being merged;
1024 * prepare the standard merge summary message to
1025 * be appended to the given message. If remote
1026 * is invalid we will die later in the common
1027 * codepath so we discard the error in this
1028 * loop.
1029 */
1030 for (i = 0; i < argc; i++)
1031 merge_name(argv[i], &merge_names);
1033 if (have_message && option_log)
1034 fmt_merge_msg_shortlog(&merge_names, &merge_msg);
1035 else if (!have_message)
1036 fmt_merge_msg(option_log, &merge_names, &merge_msg);
1039 if (!(have_message && !option_log) && merge_msg.len)
1040 strbuf_setlen(&merge_msg, merge_msg.len-1);
1041 }
1043 if (head_invalid || !argc)
1044 usage_with_options(builtin_merge_usage,
1045 builtin_merge_options);
1047 strbuf_addstr(&buf, "merge");
1048 for (i = 0; i < argc; i++)
1049 strbuf_addf(&buf, " %s", argv[i]);
1050 setenv("GIT_REFLOG_ACTION", buf.buf, 0);
1051 strbuf_reset(&buf);
1053 for (i = 0; i < argc; i++) {
1054 struct object *o;
1055 struct commit *commit;
1057 o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
1058 if (!o)
1059 die("%s - not something we can merge", argv[i]);
1060 commit = lookup_commit(o->sha1);
1061 commit->util = (void *)argv[i];
1062 remotes = &commit_list_insert(commit, remotes)->next;
1064 strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
1065 setenv(buf.buf, argv[i], 1);
1066 strbuf_reset(&buf);
1067 }
1069 if (!use_strategies) {
1070 if (!remoteheads->next)
1071 add_strategies(pull_twohead, DEFAULT_TWOHEAD);
1072 else
1073 add_strategies(pull_octopus, DEFAULT_OCTOPUS);
1074 }
1076 for (i = 0; i < use_strategies_nr; i++) {
1077 if (use_strategies[i]->attr & NO_FAST_FORWARD)
1078 allow_fast_forward = 0;
1079 if (use_strategies[i]->attr & NO_TRIVIAL)
1080 allow_trivial = 0;
1081 }
1083 if (!remoteheads->next)
1084 common = get_merge_bases(lookup_commit(head),
1085 remoteheads->item, 1);
1086 else {
1087 struct commit_list *list = remoteheads;
1088 commit_list_insert(lookup_commit(head), &list);
1089 common = get_octopus_merge_bases(list);
1090 free(list);
1091 }
1093 update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
1094 DIE_ON_ERR);
1096 if (!common)
1097 ; /* No common ancestors found. We need a real merge. */
1098 else if (!remoteheads->next && !common->next &&
1099 common->item == remoteheads->item) {
1100 /*
1101 * If head can reach all the merge then we are up to date.
1102 * but first the most common case of merging one remote.
1103 */
1104 finish_up_to_date("Already up-to-date.");
1105 return 0;
1106 } else if (allow_fast_forward && !remoteheads->next &&
1107 !common->next &&
1108 !hashcmp(common->item->object.sha1, head)) {
1109 /* Again the most common case of merging one remote. */
1110 struct strbuf msg = STRBUF_INIT;
1111 struct object *o;
1112 char hex[41];
1114 strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));
1116 if (verbosity >= 0)
1117 printf("Updating %s..%s\n",
1118 hex,
1119 find_unique_abbrev(remoteheads->item->object.sha1,
1120 DEFAULT_ABBREV));
1121 strbuf_addstr(&msg, "Fast-forward");
1122 if (have_message)
1123 strbuf_addstr(&msg,
1124 " (no commit created; -m option ignored)");
1125 o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
1126 0, NULL, OBJ_COMMIT);
1127 if (!o)
1128 return 1;
1130 if (checkout_fast_forward(head, remoteheads->item->object.sha1))
1131 return 1;
1133 finish(o->sha1, msg.buf);
1134 drop_save();
1135 return 0;
1136 } else if (!remoteheads->next && common->next)
1137 ;
1138 /*
1139 * We are not doing octopus and not fast-forward. Need
1140 * a real merge.
1141 */
1142 else if (!remoteheads->next && !common->next && option_commit) {
1143 /*
1144 * We are not doing octopus, not fast-forward, and have
1145 * only one common.
1146 */
1147 refresh_cache(REFRESH_QUIET);
1148 if (allow_trivial && !fast_forward_only) {
1149 /* See if it is really trivial. */
1150 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1151 printf("Trying really trivial in-index merge...\n");
1152 if (!read_tree_trivial(common->item->object.sha1,
1153 head, remoteheads->item->object.sha1))
1154 return merge_trivial();
1155 printf("Nope.\n");
1156 }
1157 } else {
1158 /*
1159 * An octopus. If we can reach all the remote we are up
1160 * to date.
1161 */
1162 int up_to_date = 1;
1163 struct commit_list *j;
1165 for (j = remoteheads; j; j = j->next) {
1166 struct commit_list *common_one;
1168 /*
1169 * Here we *have* to calculate the individual
1170 * merge_bases again, otherwise "git merge HEAD^
1171 * HEAD^^" would be missed.
1172 */
1173 common_one = get_merge_bases(lookup_commit(head),
1174 j->item, 1);
1175 if (hashcmp(common_one->item->object.sha1,
1176 j->item->object.sha1)) {
1177 up_to_date = 0;
1178 break;
1179 }
1180 }
1181 if (up_to_date) {
1182 finish_up_to_date("Already up-to-date. Yeeah!");
1183 return 0;
1184 }
1185 }
1187 if (fast_forward_only)
1188 die("Not possible to fast-forward, aborting.");
1190 /* We are going to make a new commit. */
1191 git_committer_info(IDENT_ERROR_ON_NO_NAME);
1193 /*
1194 * At this point, we need a real merge. No matter what strategy
1195 * we use, it would operate on the index, possibly affecting the
1196 * working tree, and when resolved cleanly, have the desired
1197 * tree in the index -- this means that the index must be in
1198 * sync with the head commit. The strategies are responsible
1199 * to ensure this.
1200 */
1201 if (use_strategies_nr != 1) {
1202 /*
1203 * Stash away the local changes so that we can try more
1204 * than one.
1205 */
1206 save_state();
1207 } else {
1208 memcpy(stash, null_sha1, 20);
1209 }
1211 for (i = 0; i < use_strategies_nr; i++) {
1212 int ret;
1213 if (i) {
1214 printf("Rewinding the tree to pristine...\n");
1215 restore_state();
1216 }
1217 if (use_strategies_nr != 1)
1218 printf("Trying merge strategy %s...\n",
1219 use_strategies[i]->name);
1220 /*
1221 * Remember which strategy left the state in the working
1222 * tree.
1223 */
1224 wt_strategy = use_strategies[i]->name;
1226 ret = try_merge_strategy(use_strategies[i]->name,
1227 common, head_arg);
1228 if (!option_commit && !ret) {
1229 merge_was_ok = 1;
1230 /*
1231 * This is necessary here just to avoid writing
1232 * the tree, but later we will *not* exit with
1233 * status code 1 because merge_was_ok is set.
1234 */
1235 ret = 1;
1236 }
1238 if (ret) {
1239 /*
1240 * The backend exits with 1 when conflicts are
1241 * left to be resolved, with 2 when it does not
1242 * handle the given merge at all.
1243 */
1244 if (ret == 1) {
1245 int cnt = evaluate_result();
1247 if (best_cnt <= 0 || cnt <= best_cnt) {
1248 best_strategy = use_strategies[i]->name;
1249 best_cnt = cnt;
1250 }
1251 }
1252 if (merge_was_ok)
1253 break;
1254 else
1255 continue;
1256 }
1258 /* Automerge succeeded. */
1259 write_tree_trivial(result_tree);
1260 automerge_was_ok = 1;
1261 break;
1262 }
1264 /*
1265 * If we have a resulting tree, that means the strategy module
1266 * auto resolved the merge cleanly.
1267 */
1268 if (automerge_was_ok)
1269 return finish_automerge(common, result_tree, wt_strategy);
1271 /*
1272 * Pick the result from the best strategy and have the user fix
1273 * it up.
1274 */
1275 if (!best_strategy) {
1276 restore_state();
1277 if (use_strategies_nr > 1)
1278 fprintf(stderr,
1279 "No merge strategy handled the merge.\n");
1280 else
1281 fprintf(stderr, "Merge with strategy %s failed.\n",
1282 use_strategies[0]->name);
1283 return 2;
1284 } else if (best_strategy == wt_strategy)
1285 ; /* We already have its result in the working tree. */
1286 else {
1287 printf("Rewinding the tree to pristine...\n");
1288 restore_state();
1289 printf("Using the %s to prepare resolving by hand.\n",
1290 best_strategy);
1291 try_merge_strategy(best_strategy, common, head_arg);
1292 }
1294 if (squash)
1295 finish(NULL, NULL);
1296 else {
1297 int fd;
1298 struct commit_list *j;
1300 for (j = remoteheads; j; j = j->next)
1301 strbuf_addf(&buf, "%s\n",
1302 sha1_to_hex(j->item->object.sha1));
1303 fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
1304 if (fd < 0)
1305 die_errno("Could not open '%s' for writing",
1306 git_path("MERGE_HEAD"));
1307 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1308 die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
1309 close(fd);
1310 strbuf_addch(&merge_msg, '\n');
1311 fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
1312 if (fd < 0)
1313 die_errno("Could not open '%s' for writing",
1314 git_path("MERGE_MSG"));
1315 if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
1316 merge_msg.len)
1317 die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
1318 close(fd);
1319 fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
1320 if (fd < 0)
1321 die_errno("Could not open '%s' for writing",
1322 git_path("MERGE_MODE"));
1323 strbuf_reset(&buf);
1324 if (!allow_fast_forward)
1325 strbuf_addf(&buf, "no-ff");
1326 if (write_in_full(fd, buf.buf, buf.len) != buf.len)
1327 die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
1328 close(fd);
1329 }
1331 if (merge_was_ok) {
1332 fprintf(stderr, "Automatic merge went well; "
1333 "stopped before committing as requested\n");
1334 return 0;
1335 } else
1336 return suggest_conflicts(option_renormalize);
1337 }