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