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