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