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