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