4 * Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
6 * Based on git-merge.sh by Junio C Hamano.
9 #define USE_THE_INDEX_VARIABLE
15 #include "environment.h"
18 #include "object-name.h"
19 #include "parse-options.h"
21 #include "run-command.h"
24 #include "diff-merges.h"
31 #include "unpack-trees.h"
32 #include "cache-tree.h"
38 #include "merge-recursive.h"
39 #include "merge-ort-wrappers.h"
40 #include "resolve-undo.h"
42 #include "fmt-merge-msg.h"
43 #include "sequencer.h"
44 #include "string-list.h"
48 #include "commit-reach.h"
49 #include "wt-status.h"
50 #include "commit-graph.h"
52 #define DEFAULT_TWOHEAD (1<<0)
53 #define DEFAULT_OCTOPUS (1<<1)
54 #define NO_FAST_FORWARD (1<<2)
55 #define NO_TRIVIAL (1<<3)
62 static const char * const builtin_merge_usage
[] = {
63 N_("git merge [<options>] [<commit>...]"),
65 "git merge --continue",
69 static int show_diffstat
= 1, shortlog_len
= -1, squash
;
70 static int option_commit
= -1;
71 static int option_edit
= -1;
72 static int allow_trivial
= 1, have_message
, verify_signatures
;
73 static int check_trust_level
= 1;
74 static int overwrite_ignore
= 1;
75 static struct strbuf merge_msg
= STRBUF_INIT
;
76 static struct strategy
**use_strategies
;
77 static size_t use_strategies_nr
, use_strategies_alloc
;
78 static struct strvec xopts
= STRVEC_INIT
;
79 static const char *branch
;
80 static char *branch_mergeoptions
;
82 static int allow_rerere_auto
;
83 static int abort_current_merge
;
84 static int quit_current_merge
;
85 static int continue_current_merge
;
86 static int allow_unrelated_histories
;
87 static int show_progress
= -1;
88 static int default_to_upstream
= 1;
90 static const char *sign_commit
;
93 static char *into_name
;
95 static struct strategy all_strategy
[] = {
96 { "recursive", NO_TRIVIAL
},
97 { "octopus", DEFAULT_OCTOPUS
},
98 { "ort", DEFAULT_TWOHEAD
| NO_TRIVIAL
},
100 { "ours", NO_FAST_FORWARD
| NO_TRIVIAL
},
101 { "subtree", NO_FAST_FORWARD
| NO_TRIVIAL
},
104 static const char *pull_twohead
, *pull_octopus
;
112 static enum ff_type fast_forward
= FF_ALLOW
;
114 static const char *cleanup_arg
;
115 static enum commit_msg_cleanup_mode cleanup_mode
;
117 static int option_parse_message(const struct option
*opt
,
118 const char *arg
, int unset
)
120 struct strbuf
*buf
= opt
->value
;
123 strbuf_setlen(buf
, 0);
125 strbuf_addf(buf
, "%s%s", buf
->len
? "\n\n" : "", arg
);
128 return error(_("switch `m' requires a value"));
132 static enum parse_opt_result
option_read_message(struct parse_opt_ctx_t
*ctx
,
133 const struct option
*opt
,
134 const char *arg_not_used
,
137 struct strbuf
*buf
= opt
->value
;
140 BUG_ON_OPT_ARG(arg_not_used
);
142 BUG("-F cannot be negated");
147 } else if (ctx
->argc
> 1) {
151 return error(_("option `%s' requires a value"), opt
->long_name
);
154 strbuf_addch(buf
, '\n');
155 if (ctx
->prefix
&& !is_absolute_path(arg
))
156 arg
= prefix_filename(ctx
->prefix
, arg
);
157 if (strbuf_read_file(buf
, arg
, 0) < 0)
158 return error(_("could not read file '%s'"), arg
);
164 static struct strategy
*get_strategy(const char *name
)
167 struct strategy
*ret
;
168 static struct cmdnames main_cmds
, other_cmds
;
170 char *default_strategy
= getenv("GIT_TEST_MERGE_ALGORITHM");
175 if (default_strategy
&&
176 !strcmp(default_strategy
, "ort") &&
177 !strcmp(name
, "recursive")) {
181 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
182 if (!strcmp(name
, all_strategy
[i
].name
))
183 return &all_strategy
[i
];
186 struct cmdnames not_strategies
;
189 memset(¬_strategies
, 0, sizeof(struct cmdnames
));
190 load_command_list("git-merge-", &main_cmds
, &other_cmds
);
191 for (i
= 0; i
< main_cmds
.cnt
; i
++) {
193 struct cmdname
*ent
= main_cmds
.names
[i
];
194 for (j
= 0; !found
&& j
< ARRAY_SIZE(all_strategy
); j
++)
195 if (!xstrncmpz(all_strategy
[j
].name
, ent
->name
, ent
->len
))
198 add_cmdname(¬_strategies
, ent
->name
, ent
->len
);
200 exclude_cmds(&main_cmds
, ¬_strategies
);
202 if (!is_in_cmdlist(&main_cmds
, name
) && !is_in_cmdlist(&other_cmds
, name
)) {
203 fprintf(stderr
, _("Could not find merge strategy '%s'.\n"), name
);
204 fprintf(stderr
, _("Available strategies are:"));
205 for (i
= 0; i
< main_cmds
.cnt
; i
++)
206 fprintf(stderr
, " %s", main_cmds
.names
[i
]->name
);
207 fprintf(stderr
, ".\n");
208 if (other_cmds
.cnt
) {
209 fprintf(stderr
, _("Available custom strategies are:"));
210 for (i
= 0; i
< other_cmds
.cnt
; i
++)
211 fprintf(stderr
, " %s", other_cmds
.names
[i
]->name
);
212 fprintf(stderr
, ".\n");
217 CALLOC_ARRAY(ret
, 1);
218 ret
->name
= xstrdup(name
);
219 ret
->attr
= NO_TRIVIAL
;
223 static void append_strategy(struct strategy
*s
)
225 ALLOC_GROW(use_strategies
, use_strategies_nr
+ 1, use_strategies_alloc
);
226 use_strategies
[use_strategies_nr
++] = s
;
229 static int option_parse_strategy(const struct option
*opt UNUSED
,
230 const char *name
, int unset
)
235 append_strategy(get_strategy(name
));
239 static struct option builtin_merge_options
[] = {
240 OPT_SET_INT('n', NULL
, &show_diffstat
,
241 N_("do not show a diffstat at the end of the merge"), 0),
242 OPT_BOOL(0, "stat", &show_diffstat
,
243 N_("show a diffstat at the end of the merge")),
244 OPT_BOOL(0, "summary", &show_diffstat
, N_("(synonym to --stat)")),
245 { OPTION_INTEGER
, 0, "log", &shortlog_len
, N_("n"),
246 N_("add (at most <n>) entries from shortlog to merge commit message"),
247 PARSE_OPT_OPTARG
, NULL
, DEFAULT_MERGE_LOG_LEN
},
248 OPT_BOOL(0, "squash", &squash
,
249 N_("create a single commit instead of doing a merge")),
250 OPT_BOOL(0, "commit", &option_commit
,
251 N_("perform a commit if the merge succeeds (default)")),
252 OPT_BOOL('e', "edit", &option_edit
,
253 N_("edit message before committing")),
254 OPT_CLEANUP(&cleanup_arg
),
255 OPT_SET_INT(0, "ff", &fast_forward
, N_("allow fast-forward (default)"), FF_ALLOW
),
256 OPT_SET_INT_F(0, "ff-only", &fast_forward
,
257 N_("abort if fast-forward is not possible"),
258 FF_ONLY
, PARSE_OPT_NONEG
),
259 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto
),
260 OPT_BOOL(0, "verify-signatures", &verify_signatures
,
261 N_("verify that the named commit has a valid GPG signature")),
262 OPT_CALLBACK('s', "strategy", NULL
, N_("strategy"),
263 N_("merge strategy to use"), option_parse_strategy
),
264 OPT_STRVEC('X', "strategy-option", &xopts
, N_("option=value"),
265 N_("option for selected merge strategy")),
266 OPT_CALLBACK('m', "message", &merge_msg
, N_("message"),
267 N_("merge commit message (for a non-fast-forward merge)"),
268 option_parse_message
),
269 { OPTION_LOWLEVEL_CALLBACK
, 'F', "file", &merge_msg
, N_("path"),
270 N_("read message from file"), PARSE_OPT_NONEG
,
271 NULL
, 0, option_read_message
},
272 OPT_STRING(0, "into-name", &into_name
, N_("name"),
273 N_("use <name> instead of the real target")),
274 OPT__VERBOSITY(&verbosity
),
275 OPT_BOOL(0, "abort", &abort_current_merge
,
276 N_("abort the current in-progress merge")),
277 OPT_BOOL(0, "quit", &quit_current_merge
,
278 N_("--abort but leave index and working tree alone")),
279 OPT_BOOL(0, "continue", &continue_current_merge
,
280 N_("continue the current in-progress merge")),
281 OPT_BOOL(0, "allow-unrelated-histories", &allow_unrelated_histories
,
282 N_("allow merging unrelated histories")),
283 OPT_SET_INT(0, "progress", &show_progress
, N_("force progress reporting"), 1),
284 { OPTION_STRING
, 'S', "gpg-sign", &sign_commit
, N_("key-id"),
285 N_("GPG sign commit"), PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
286 OPT_AUTOSTASH(&autostash
),
287 OPT_BOOL(0, "overwrite-ignore", &overwrite_ignore
, N_("update ignored files (default)")),
288 OPT_BOOL(0, "signoff", &signoff
, N_("add a Signed-off-by trailer")),
289 OPT_BOOL(0, "no-verify", &no_verify
, N_("bypass pre-merge-commit and commit-msg hooks")),
293 static int save_state(struct object_id
*stash
)
296 struct child_process cp
= CHILD_PROCESS_INIT
;
297 struct strbuf buffer
= STRBUF_INIT
;
298 struct lock_file lock_file
= LOCK_INIT
;
302 fd
= repo_hold_locked_index(the_repository
, &lock_file
, 0);
303 refresh_index(&the_index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
305 repo_update_index_if_able(the_repository
, &lock_file
);
306 rollback_lock_file(&lock_file
);
308 strvec_pushl(&cp
.args
, "stash", "create", NULL
);
312 if (start_command(&cp
))
313 die(_("could not run stash."));
314 len
= strbuf_read(&buffer
, cp
.out
, 1024);
317 if (finish_command(&cp
) || len
< 0)
318 die(_("stash failed"));
319 else if (!len
) /* no changes */
321 strbuf_setlen(&buffer
, buffer
.len
-1);
322 if (repo_get_oid(the_repository
, buffer
.buf
, stash
))
323 die(_("not a valid object: %s"), buffer
.buf
);
326 strbuf_release(&buffer
);
330 static void read_empty(const struct object_id
*oid
)
332 struct child_process cmd
= CHILD_PROCESS_INIT
;
334 strvec_pushl(&cmd
.args
, "read-tree", "-m", "-u", empty_tree_oid_hex(),
335 oid_to_hex(oid
), NULL
);
338 if (run_command(&cmd
))
339 die(_("read-tree failed"));
342 static void reset_hard(const struct object_id
*oid
)
344 struct child_process cmd
= CHILD_PROCESS_INIT
;
346 strvec_pushl(&cmd
.args
, "read-tree", "-v", "--reset", "-u",
347 oid_to_hex(oid
), NULL
);
350 if (run_command(&cmd
))
351 die(_("read-tree failed"));
354 static void restore_state(const struct object_id
*head
,
355 const struct object_id
*stash
)
357 struct child_process cmd
= CHILD_PROCESS_INIT
;
361 if (is_null_oid(stash
))
364 strvec_pushl(&cmd
.args
, "stash", "apply", "--index", "--quiet", NULL
);
365 strvec_push(&cmd
.args
, oid_to_hex(stash
));
368 * It is OK to ignore error here, for example when there was
369 * nothing to restore.
375 discard_index(&the_index
);
376 if (repo_read_index(the_repository
) < 0)
377 die(_("could not read index"));
380 /* This is called when no merge was necessary. */
381 static void finish_up_to_date(void)
383 if (verbosity
>= 0) {
385 puts(_("Already up to date. (nothing to squash)"));
387 puts(_("Already up to date."));
389 remove_merge_branch_state(the_repository
);
392 static void squash_message(struct commit
*commit
, struct commit_list
*remoteheads
)
395 struct strbuf out
= STRBUF_INIT
;
396 struct commit_list
*j
;
397 struct pretty_print_context ctx
= {0};
399 printf(_("Squash commit -- not updating HEAD\n"));
401 repo_init_revisions(the_repository
, &rev
, NULL
);
402 diff_merges_suppress(&rev
);
403 rev
.commit_format
= CMIT_FMT_MEDIUM
;
405 commit
->object
.flags
|= UNINTERESTING
;
406 add_pending_object(&rev
, &commit
->object
, NULL
);
408 for (j
= remoteheads
; j
; j
= j
->next
)
409 add_pending_object(&rev
, &j
->item
->object
, NULL
);
411 setup_revisions(0, NULL
, &rev
, NULL
);
412 if (prepare_revision_walk(&rev
))
413 die(_("revision walk setup failed"));
415 ctx
.abbrev
= rev
.abbrev
;
416 ctx
.date_mode
= rev
.date_mode
;
417 ctx
.fmt
= rev
.commit_format
;
419 strbuf_addstr(&out
, "Squashed commit of the following:\n");
420 while ((commit
= get_revision(&rev
)) != NULL
) {
421 strbuf_addch(&out
, '\n');
422 strbuf_addf(&out
, "commit %s\n",
423 oid_to_hex(&commit
->object
.oid
));
424 pretty_print_commit(&ctx
, commit
, &out
);
426 write_file_buf(git_path_squash_msg(the_repository
), out
.buf
, out
.len
);
427 strbuf_release(&out
);
428 release_revisions(&rev
);
431 static void finish(struct commit
*head_commit
,
432 struct commit_list
*remoteheads
,
433 const struct object_id
*new_head
, const char *msg
)
435 struct strbuf reflog_message
= STRBUF_INIT
;
436 const struct object_id
*head
= &head_commit
->object
.oid
;
439 strbuf_addstr(&reflog_message
, getenv("GIT_REFLOG_ACTION"));
443 strbuf_addf(&reflog_message
, "%s: %s",
444 getenv("GIT_REFLOG_ACTION"), msg
);
447 squash_message(head_commit
, remoteheads
);
449 if (verbosity
>= 0 && !merge_msg
.len
)
450 printf(_("No merge message -- not updating HEAD\n"));
452 update_ref(reflog_message
.buf
, "HEAD", new_head
, head
,
453 0, UPDATE_REFS_DIE_ON_ERR
);
455 * We ignore errors in 'gc --auto', since the
456 * user should see them.
458 run_auto_maintenance(verbosity
< 0);
461 if (new_head
&& show_diffstat
) {
462 struct diff_options opts
;
463 repo_diff_setup(the_repository
, &opts
);
464 init_diffstat_widths(&opts
);
465 opts
.output_format
|=
466 DIFF_FORMAT_SUMMARY
| DIFF_FORMAT_DIFFSTAT
;
467 opts
.detect_rename
= DIFF_DETECT_RENAME
;
468 diff_setup_done(&opts
);
469 diff_tree_oid(head
, new_head
, "", &opts
);
474 /* Run a post-merge hook */
475 run_hooks_l("post-merge", squash
? "1" : "0", NULL
);
478 apply_autostash_ref(the_repository
, "MERGE_AUTOSTASH");
479 strbuf_release(&reflog_message
);
482 /* Get the name for the merge commit's message. */
483 static void merge_name(const char *remote
, struct strbuf
*msg
)
485 struct commit
*remote_head
;
486 struct object_id branch_head
;
487 struct strbuf bname
= STRBUF_INIT
;
488 struct merge_remote_desc
*desc
;
490 char *found_ref
= NULL
;
493 strbuf_branchname(&bname
, remote
, 0);
496 oidclr(&branch_head
);
497 remote_head
= get_merge_parent(remote
);
499 die(_("'%s' does not point to a commit"), remote
);
501 if (repo_dwim_ref(the_repository
, remote
, strlen(remote
), &branch_head
,
502 &found_ref
, 0) > 0) {
503 if (starts_with(found_ref
, "refs/heads/")) {
504 strbuf_addf(msg
, "%s\t\tbranch '%s' of .\n",
505 oid_to_hex(&branch_head
), remote
);
508 if (starts_with(found_ref
, "refs/tags/")) {
509 strbuf_addf(msg
, "%s\t\ttag '%s' of .\n",
510 oid_to_hex(&branch_head
), remote
);
513 if (starts_with(found_ref
, "refs/remotes/")) {
514 strbuf_addf(msg
, "%s\t\tremote-tracking branch '%s' of .\n",
515 oid_to_hex(&branch_head
), remote
);
520 /* See if remote matches <name>^^^.. or <name>~<number> */
521 for (len
= 0, ptr
= remote
+ strlen(remote
);
522 remote
< ptr
&& ptr
[-1] == '^';
529 ptr
= strrchr(remote
, '~');
531 int seen_nonzero
= 0;
534 while (*++ptr
&& isdigit(*ptr
)) {
535 seen_nonzero
|= (*ptr
!= '0');
539 len
= 0; /* not ...~<number> */
540 else if (seen_nonzero
)
543 early
= 1; /* "name~" is "name~1"! */
547 struct strbuf truname
= STRBUF_INIT
;
548 strbuf_addf(&truname
, "refs/heads/%s", remote
);
549 strbuf_setlen(&truname
, truname
.len
- len
);
550 if (ref_exists(truname
.buf
)) {
552 "%s\t\tbranch '%s'%s of .\n",
553 oid_to_hex(&remote_head
->object
.oid
),
555 (early
? " (early part)" : ""));
556 strbuf_release(&truname
);
559 strbuf_release(&truname
);
562 desc
= merge_remote_util(remote_head
);
563 if (desc
&& desc
->obj
&& desc
->obj
->type
== OBJ_TAG
) {
564 strbuf_addf(msg
, "%s\t\t%s '%s'\n",
565 oid_to_hex(&desc
->obj
->oid
),
566 type_name(desc
->obj
->type
),
571 strbuf_addf(msg
, "%s\t\tcommit '%s'\n",
572 oid_to_hex(&remote_head
->object
.oid
), remote
);
575 strbuf_release(&bname
);
578 static void parse_branch_merge_options(char *bmo
)
585 argc
= split_cmdline(bmo
, &argv
);
587 die(_("Bad branch.%s.mergeoptions string: %s"), branch
,
588 _(split_cmdline_strerror(argc
)));
589 REALLOC_ARRAY(argv
, argc
+ 2);
590 MOVE_ARRAY(argv
+ 1, argv
, argc
+ 1);
592 argv
[0] = "branch.*.mergeoptions";
593 parse_options(argc
, argv
, NULL
, builtin_merge_options
,
594 builtin_merge_usage
, 0);
598 static int git_merge_config(const char *k
, const char *v
,
599 const struct config_context
*ctx
, void *cb
)
605 skip_prefix(k
, "branch.", &str
) &&
606 skip_prefix(str
, branch
, &str
) &&
607 !strcmp(str
, ".mergeoptions")) {
608 free(branch_mergeoptions
);
609 branch_mergeoptions
= xstrdup(v
);
613 if (!strcmp(k
, "merge.diffstat") || !strcmp(k
, "merge.stat"))
614 show_diffstat
= git_config_bool(k
, v
);
615 else if (!strcmp(k
, "merge.verifysignatures"))
616 verify_signatures
= git_config_bool(k
, v
);
617 else if (!strcmp(k
, "pull.twohead"))
618 return git_config_string(&pull_twohead
, k
, v
);
619 else if (!strcmp(k
, "pull.octopus"))
620 return git_config_string(&pull_octopus
, k
, v
);
621 else if (!strcmp(k
, "commit.cleanup"))
622 return git_config_string(&cleanup_arg
, k
, v
);
623 else if (!strcmp(k
, "merge.ff")) {
624 int boolval
= git_parse_maybe_bool(v
);
626 fast_forward
= boolval
? FF_ALLOW
: FF_NO
;
627 } else if (v
&& !strcmp(v
, "only")) {
628 fast_forward
= FF_ONLY
;
629 } /* do not barf on values from future versions of git */
631 } else if (!strcmp(k
, "merge.defaulttoupstream")) {
632 default_to_upstream
= git_config_bool(k
, v
);
634 } else if (!strcmp(k
, "commit.gpgsign")) {
635 sign_commit
= git_config_bool(k
, v
) ? "" : NULL
;
637 } else if (!strcmp(k
, "gpg.mintrustlevel")) {
638 check_trust_level
= 0;
639 } else if (!strcmp(k
, "merge.autostash")) {
640 autostash
= git_config_bool(k
, v
);
644 status
= fmt_merge_msg_config(k
, v
, ctx
, cb
);
647 return git_diff_ui_config(k
, v
, ctx
, cb
);
650 static int read_tree_trivial(struct object_id
*common
, struct object_id
*head
,
651 struct object_id
*one
)
654 struct tree
*trees
[MAX_UNPACK_TREES
];
655 struct tree_desc t
[MAX_UNPACK_TREES
];
656 struct unpack_trees_options opts
;
658 memset(&opts
, 0, sizeof(opts
));
660 opts
.src_index
= &the_index
;
661 opts
.dst_index
= &the_index
;
663 opts
.verbose_update
= 1;
664 opts
.trivial_merges_only
= 1;
666 opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
667 trees
[nr_trees
] = parse_tree_indirect(common
);
668 if (!trees
[nr_trees
++])
670 trees
[nr_trees
] = parse_tree_indirect(head
);
671 if (!trees
[nr_trees
++])
673 trees
[nr_trees
] = parse_tree_indirect(one
);
674 if (!trees
[nr_trees
++])
676 opts
.fn
= threeway_merge
;
677 cache_tree_free(&the_index
.cache_tree
);
678 for (i
= 0; i
< nr_trees
; i
++) {
679 parse_tree(trees
[i
]);
680 init_tree_desc(t
+i
, trees
[i
]->buffer
, trees
[i
]->size
);
682 if (unpack_trees(nr_trees
, t
, &opts
))
687 static void write_tree_trivial(struct object_id
*oid
)
689 if (write_index_as_tree(oid
, &the_index
, get_index_file(), 0, NULL
))
690 die(_("git write-tree failed to write a tree"));
693 static int try_merge_strategy(const char *strategy
, struct commit_list
*common
,
694 struct commit_list
*remoteheads
,
697 const char *head_arg
= "HEAD";
699 if (repo_refresh_and_write_index(the_repository
, REFRESH_QUIET
,
700 SKIP_IF_UNCHANGED
, 0, NULL
, NULL
,
702 return error(_("Unable to write index."));
704 if (!strcmp(strategy
, "recursive") || !strcmp(strategy
, "subtree") ||
705 !strcmp(strategy
, "ort")) {
706 struct lock_file lock
= LOCK_INIT
;
708 struct commit
*result
;
709 struct commit_list
*reversed
= NULL
;
710 struct merge_options o
;
711 struct commit_list
*j
;
713 if (remoteheads
->next
) {
714 error(_("Not handling anything other than two heads merge."));
718 init_merge_options(&o
, the_repository
);
719 if (!strcmp(strategy
, "subtree"))
720 o
.subtree_shift
= "";
722 o
.show_rename_progress
=
723 show_progress
== -1 ? isatty(2) : show_progress
;
725 for (x
= 0; x
< xopts
.nr
; x
++)
726 if (parse_merge_opt(&o
, xopts
.v
[x
]))
727 die(_("unknown strategy option: -X%s"), xopts
.v
[x
]);
729 o
.branch1
= head_arg
;
730 o
.branch2
= merge_remote_util(remoteheads
->item
)->name
;
732 for (j
= common
; j
; j
= j
->next
)
733 commit_list_insert(j
->item
, &reversed
);
735 repo_hold_locked_index(the_repository
, &lock
,
737 if (!strcmp(strategy
, "ort"))
738 clean
= merge_ort_recursive(&o
, head
, remoteheads
->item
,
741 clean
= merge_recursive(&o
, head
, remoteheads
->item
,
744 rollback_lock_file(&lock
);
747 if (write_locked_index(&the_index
, &lock
,
748 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
749 die(_("unable to write %s"), get_index_file());
750 return clean
? 0 : 1;
752 return try_merge_command(the_repository
,
753 strategy
, xopts
.nr
, xopts
.v
,
754 common
, head_arg
, remoteheads
);
758 static void count_diff_files(struct diff_queue_struct
*q
,
759 struct diff_options
*opt UNUSED
, void *data
)
766 static int count_unmerged_entries(void)
770 for (i
= 0; i
< the_index
.cache_nr
; i
++)
771 if (ce_stage(the_index
.cache
[i
]))
777 static void add_strategies(const char *string
, unsigned attr
)
782 struct string_list list
= STRING_LIST_INIT_DUP
;
783 struct string_list_item
*item
;
784 string_list_split(&list
, string
, ' ', -1);
785 for_each_string_list_item(item
, &list
)
786 append_strategy(get_strategy(item
->string
));
787 string_list_clear(&list
, 0);
790 for (i
= 0; i
< ARRAY_SIZE(all_strategy
); i
++)
791 if (all_strategy
[i
].attr
& attr
)
792 append_strategy(&all_strategy
[i
]);
796 static void read_merge_msg(struct strbuf
*msg
)
798 const char *filename
= git_path_merge_msg(the_repository
);
800 if (strbuf_read_file(msg
, filename
, 0) < 0)
801 die_errno(_("Could not read from '%s'"), filename
);
804 static void write_merge_state(struct commit_list
*);
805 static void abort_commit(struct commit_list
*remoteheads
, const char *err_msg
)
808 error("%s", err_msg
);
810 _("Not committing merge; use 'git commit' to complete the merge.\n"));
811 write_merge_state(remoteheads
);
815 static const char merge_editor_comment
[] =
816 N_("Please enter a commit message to explain why this merge is necessary,\n"
817 "especially if it merges an updated upstream into a topic branch.\n"
820 static const char scissors_editor_comment
[] =
821 N_("An empty message aborts the commit.\n");
823 static const char no_scissors_editor_comment
[] =
824 N_("Lines starting with '%c' will be ignored, and an empty message aborts\n"
827 static void write_merge_heads(struct commit_list
*);
828 static void prepare_to_commit(struct commit_list
*remoteheads
)
830 struct strbuf msg
= STRBUF_INIT
;
831 const char *index_file
= get_index_file();
836 if (run_commit_hook(0 < option_edit
, index_file
, &invoked_hook
,
837 "pre-merge-commit", NULL
))
838 abort_commit(remoteheads
, NULL
);
840 * Re-read the index as pre-merge-commit hook could have updated it,
841 * and write it out as a tree. We must do this before we invoke
842 * the editor and after we invoke run_status above.
845 discard_index(&the_index
);
847 read_index_from(&the_index
, index_file
, get_git_dir());
848 strbuf_addbuf(&msg
, &merge_msg
);
850 BUG("the control must not reach here under --squash");
851 if (0 < option_edit
) {
852 strbuf_addch(&msg
, '\n');
853 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
854 wt_status_append_cut_line(&msg
);
855 strbuf_commented_addf(&msg
, comment_line_char
, "\n");
857 strbuf_commented_addf(&msg
, comment_line_char
,
858 _(merge_editor_comment
));
859 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
860 strbuf_commented_addf(&msg
, comment_line_char
,
861 _(scissors_editor_comment
));
863 strbuf_commented_addf(&msg
, comment_line_char
,
864 _(no_scissors_editor_comment
), comment_line_char
);
867 append_signoff(&msg
, ignored_log_message_bytes(msg
.buf
, msg
.len
), 0);
868 write_merge_heads(remoteheads
);
869 write_file_buf(git_path_merge_msg(the_repository
), msg
.buf
, msg
.len
);
870 if (run_commit_hook(0 < option_edit
, get_index_file(), NULL
,
871 "prepare-commit-msg",
872 git_path_merge_msg(the_repository
), "merge", NULL
))
873 abort_commit(remoteheads
, NULL
);
874 if (0 < option_edit
) {
875 if (launch_editor(git_path_merge_msg(the_repository
), NULL
, NULL
))
876 abort_commit(remoteheads
, NULL
);
879 if (!no_verify
&& run_commit_hook(0 < option_edit
, get_index_file(),
881 git_path_merge_msg(the_repository
), NULL
))
882 abort_commit(remoteheads
, NULL
);
884 read_merge_msg(&msg
);
885 cleanup_message(&msg
, cleanup_mode
, 0);
887 abort_commit(remoteheads
, _("Empty commit message."));
888 strbuf_release(&merge_msg
);
889 strbuf_addbuf(&merge_msg
, &msg
);
890 strbuf_release(&msg
);
893 static int merge_trivial(struct commit
*head
, struct commit_list
*remoteheads
)
895 struct object_id result_tree
, result_commit
;
896 struct commit_list
*parents
, **pptr
= &parents
;
898 if (repo_refresh_and_write_index(the_repository
, REFRESH_QUIET
,
899 SKIP_IF_UNCHANGED
, 0, NULL
, NULL
,
901 return error(_("Unable to write index."));
903 write_tree_trivial(&result_tree
);
904 printf(_("Wonderful.\n"));
905 pptr
= commit_list_append(head
, pptr
);
906 pptr
= commit_list_append(remoteheads
->item
, pptr
);
907 prepare_to_commit(remoteheads
);
908 if (commit_tree(merge_msg
.buf
, merge_msg
.len
, &result_tree
, parents
,
909 &result_commit
, NULL
, sign_commit
))
910 die(_("failed to write commit object"));
911 finish(head
, remoteheads
, &result_commit
, "In-index merge");
912 remove_merge_branch_state(the_repository
);
916 static int finish_automerge(struct commit
*head
,
918 struct commit_list
*common
,
919 struct commit_list
*remoteheads
,
920 struct object_id
*result_tree
,
921 const char *wt_strategy
)
923 struct commit_list
*parents
= NULL
;
924 struct strbuf buf
= STRBUF_INIT
;
925 struct object_id result_commit
;
927 write_tree_trivial(result_tree
);
928 free_commit_list(common
);
929 parents
= remoteheads
;
930 if (!head_subsumed
|| fast_forward
== FF_NO
)
931 commit_list_insert(head
, &parents
);
932 prepare_to_commit(remoteheads
);
933 if (commit_tree(merge_msg
.buf
, merge_msg
.len
, result_tree
, parents
,
934 &result_commit
, NULL
, sign_commit
))
935 die(_("failed to write commit object"));
936 strbuf_addf(&buf
, "Merge made by the '%s' strategy.", wt_strategy
);
937 finish(head
, remoteheads
, &result_commit
, buf
.buf
);
938 strbuf_release(&buf
);
939 remove_merge_branch_state(the_repository
);
943 static int suggest_conflicts(void)
945 const char *filename
;
947 struct strbuf msgbuf
= STRBUF_INIT
;
949 filename
= git_path_merge_msg(the_repository
);
950 fp
= xfopen(filename
, "a");
953 * We can't use cleanup_mode because if we're not using the editor,
954 * get_cleanup_mode will return COMMIT_MSG_CLEANUP_SPACE instead, even
955 * though the message is meant to be processed later by git-commit.
956 * Thus, we will get the cleanup mode which is returned when we _are_
959 append_conflicts_hint(&the_index
, &msgbuf
,
960 get_cleanup_mode(cleanup_arg
, 1));
961 fputs(msgbuf
.buf
, fp
);
962 strbuf_release(&msgbuf
);
964 repo_rerere(the_repository
, allow_rerere_auto
);
965 printf(_("Automatic merge failed; "
966 "fix conflicts and then commit the result.\n"));
970 static int evaluate_result(void)
975 /* Check how many files differ. */
976 repo_init_revisions(the_repository
, &rev
, "");
977 setup_revisions(0, NULL
, &rev
, NULL
);
978 rev
.diffopt
.output_format
|=
979 DIFF_FORMAT_CALLBACK
;
980 rev
.diffopt
.format_callback
= count_diff_files
;
981 rev
.diffopt
.format_callback_data
= &cnt
;
982 run_diff_files(&rev
, 0);
985 * Check how many unmerged entries are
988 cnt
+= count_unmerged_entries();
990 release_revisions(&rev
);
995 * Pretend as if the user told us to merge with the remote-tracking
996 * branch we have for the upstream of the current branch
998 static int setup_with_upstream(const char ***argv
)
1000 struct branch
*branch
= branch_get(NULL
);
1005 die(_("No current branch."));
1006 if (!branch
->remote_name
)
1007 die(_("No remote for the current branch."));
1008 if (!branch
->merge_nr
)
1009 die(_("No default upstream defined for the current branch."));
1011 args
= xcalloc(st_add(branch
->merge_nr
, 1), sizeof(char *));
1012 for (i
= 0; i
< branch
->merge_nr
; i
++) {
1013 if (!branch
->merge
[i
]->dst
)
1014 die(_("No remote-tracking branch for %s from %s"),
1015 branch
->merge
[i
]->src
, branch
->remote_name
);
1016 args
[i
] = branch
->merge
[i
]->dst
;
1023 static void write_merge_heads(struct commit_list
*remoteheads
)
1025 struct commit_list
*j
;
1026 struct strbuf buf
= STRBUF_INIT
;
1028 for (j
= remoteheads
; j
; j
= j
->next
) {
1029 struct object_id
*oid
;
1030 struct commit
*c
= j
->item
;
1031 struct merge_remote_desc
*desc
;
1033 desc
= merge_remote_util(c
);
1034 if (desc
&& desc
->obj
) {
1035 oid
= &desc
->obj
->oid
;
1037 oid
= &c
->object
.oid
;
1039 strbuf_addf(&buf
, "%s\n", oid_to_hex(oid
));
1041 write_file_buf(git_path_merge_head(the_repository
), buf
.buf
, buf
.len
);
1044 if (fast_forward
== FF_NO
)
1045 strbuf_addstr(&buf
, "no-ff");
1046 write_file_buf(git_path_merge_mode(the_repository
), buf
.buf
, buf
.len
);
1047 strbuf_release(&buf
);
1050 static void write_merge_state(struct commit_list
*remoteheads
)
1052 write_merge_heads(remoteheads
);
1053 strbuf_addch(&merge_msg
, '\n');
1054 write_file_buf(git_path_merge_msg(the_repository
), merge_msg
.buf
,
1058 static int default_edit_option(void)
1060 static const char name
[] = "GIT_MERGE_AUTOEDIT";
1061 const char *e
= getenv(name
);
1062 struct stat st_stdin
, st_stdout
;
1065 /* an explicit -m msg without --[no-]edit */
1069 int v
= git_parse_maybe_bool(e
);
1071 die(_("Bad value '%s' in environment '%s'"), e
, name
);
1075 /* Use editor if stdin and stdout are the same and is a tty */
1076 return (!fstat(0, &st_stdin
) &&
1077 !fstat(1, &st_stdout
) &&
1078 isatty(0) && isatty(1) &&
1079 st_stdin
.st_dev
== st_stdout
.st_dev
&&
1080 st_stdin
.st_ino
== st_stdout
.st_ino
&&
1081 st_stdin
.st_mode
== st_stdout
.st_mode
);
1084 static struct commit_list
*reduce_parents(struct commit
*head_commit
,
1086 struct commit_list
*remoteheads
)
1088 struct commit_list
*parents
, **remotes
;
1091 * Is the current HEAD reachable from another commit being
1092 * merged? If so we do not want to record it as a parent of
1093 * the resulting merge, unless --no-ff is given. We will flip
1094 * this variable to 0 when we find HEAD among the independent
1095 * tips being merged.
1099 /* Find what parents to record by checking independent ones. */
1100 parents
= reduce_heads(remoteheads
);
1101 free_commit_list(remoteheads
);
1104 remotes
= &remoteheads
;
1106 struct commit
*commit
= pop_commit(&parents
);
1107 if (commit
== head_commit
)
1110 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1115 static void prepare_merge_message(struct strbuf
*merge_names
, struct strbuf
*merge_msg
)
1117 struct fmt_merge_msg_opts opts
;
1119 memset(&opts
, 0, sizeof(opts
));
1120 opts
.add_title
= !have_message
;
1121 opts
.shortlog_len
= shortlog_len
;
1122 opts
.credit_people
= (0 < option_edit
);
1123 opts
.into_name
= into_name
;
1125 fmt_merge_msg(merge_names
, merge_msg
, &opts
);
1127 strbuf_setlen(merge_msg
, merge_msg
->len
- 1);
1130 static void handle_fetch_head(struct commit_list
**remotes
, struct strbuf
*merge_names
)
1132 const char *filename
;
1134 struct strbuf fetch_head_file
= STRBUF_INIT
;
1135 const unsigned hexsz
= the_hash_algo
->hexsz
;
1138 merge_names
= &fetch_head_file
;
1140 filename
= git_path_fetch_head(the_repository
);
1141 fd
= xopen(filename
, O_RDONLY
);
1143 if (strbuf_read(merge_names
, fd
, 0) < 0)
1144 die_errno(_("could not read '%s'"), filename
);
1146 die_errno(_("could not close '%s'"), filename
);
1148 for (pos
= 0; pos
< merge_names
->len
; pos
= npos
) {
1149 struct object_id oid
;
1151 struct commit
*commit
;
1153 ptr
= strchr(merge_names
->buf
+ pos
, '\n');
1155 npos
= ptr
- merge_names
->buf
+ 1;
1157 npos
= merge_names
->len
;
1159 if (npos
- pos
< hexsz
+ 2 ||
1160 get_oid_hex(merge_names
->buf
+ pos
, &oid
))
1161 commit
= NULL
; /* bad */
1162 else if (memcmp(merge_names
->buf
+ pos
+ hexsz
, "\t\t", 2))
1163 continue; /* not-for-merge */
1165 char saved
= merge_names
->buf
[pos
+ hexsz
];
1166 merge_names
->buf
[pos
+ hexsz
] = '\0';
1167 commit
= get_merge_parent(merge_names
->buf
+ pos
);
1168 merge_names
->buf
[pos
+ hexsz
] = saved
;
1173 die(_("not something we can merge in %s: %s"),
1174 filename
, merge_names
->buf
+ pos
);
1176 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1179 if (merge_names
== &fetch_head_file
)
1180 strbuf_release(&fetch_head_file
);
1183 static struct commit_list
*collect_parents(struct commit
*head_commit
,
1185 int argc
, const char **argv
,
1186 struct strbuf
*merge_msg
)
1189 struct commit_list
*remoteheads
= NULL
;
1190 struct commit_list
**remotes
= &remoteheads
;
1191 struct strbuf merge_names
= STRBUF_INIT
, *autogen
= NULL
;
1193 if (merge_msg
&& (!have_message
|| shortlog_len
))
1194 autogen
= &merge_names
;
1197 remotes
= &commit_list_insert(head_commit
, remotes
)->next
;
1199 if (argc
== 1 && !strcmp(argv
[0], "FETCH_HEAD")) {
1200 handle_fetch_head(remotes
, autogen
);
1201 remoteheads
= reduce_parents(head_commit
, head_subsumed
, remoteheads
);
1203 for (i
= 0; i
< argc
; i
++) {
1204 struct commit
*commit
= get_merge_parent(argv
[i
]);
1206 help_unknown_ref(argv
[i
], "merge",
1207 _("not something we can merge"));
1208 remotes
= &commit_list_insert(commit
, remotes
)->next
;
1210 remoteheads
= reduce_parents(head_commit
, head_subsumed
, remoteheads
);
1212 struct commit_list
*p
;
1213 for (p
= remoteheads
; p
; p
= p
->next
)
1214 merge_name(merge_remote_util(p
->item
)->name
, autogen
);
1219 prepare_merge_message(autogen
, merge_msg
);
1220 strbuf_release(autogen
);
1226 static int merging_a_throwaway_tag(struct commit
*commit
)
1229 struct object_id oid
;
1230 int is_throwaway_tag
= 0;
1232 /* Are we merging a tag? */
1233 if (!merge_remote_util(commit
) ||
1234 !merge_remote_util(commit
)->obj
||
1235 merge_remote_util(commit
)->obj
->type
!= OBJ_TAG
)
1236 return is_throwaway_tag
;
1239 * Now we know we are merging a tag object. Are we downstream
1240 * and following the tags from upstream? If so, we must have
1241 * the tag object pointed at by "refs/tags/$T" where $T is the
1242 * tagname recorded in the tag object. We want to allow such
1243 * a "just to catch up" merge to fast-forward.
1245 * Otherwise, we are playing an integrator's role, making a
1246 * merge with a throw-away tag from a contributor with
1247 * something like "git pull $contributor $signed_tag".
1248 * We want to forbid such a merge from fast-forwarding
1249 * by default; otherwise we would not keep the signature
1252 tag_ref
= xstrfmt("refs/tags/%s",
1253 ((struct tag
*)merge_remote_util(commit
)->obj
)->tag
);
1254 if (!read_ref(tag_ref
, &oid
) &&
1255 oideq(&oid
, &merge_remote_util(commit
)->obj
->oid
))
1256 is_throwaway_tag
= 0;
1258 is_throwaway_tag
= 1;
1260 return is_throwaway_tag
;
1263 int cmd_merge(int argc
, const char **argv
, const char *prefix
)
1265 struct object_id result_tree
, stash
, head_oid
;
1266 struct commit
*head_commit
;
1267 struct strbuf buf
= STRBUF_INIT
;
1268 int i
, ret
= 0, head_subsumed
;
1269 int best_cnt
= -1, merge_was_ok
= 0, automerge_was_ok
= 0;
1270 struct commit_list
*common
= NULL
;
1271 const char *best_strategy
= NULL
, *wt_strategy
= NULL
;
1272 struct commit_list
*remoteheads
= NULL
, *p
;
1273 void *branch_to_free
;
1274 int orig_argc
= argc
;
1276 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1277 usage_with_options(builtin_merge_usage
, builtin_merge_options
);
1279 prepare_repo_settings(the_repository
);
1280 the_repository
->settings
.command_requires_full_index
= 0;
1283 * Check if we are _not_ on a detached HEAD, i.e. if there is a
1286 branch
= branch_to_free
= resolve_refdup("HEAD", 0, &head_oid
, NULL
);
1288 skip_prefix(branch
, "refs/heads/", &branch
);
1290 if (!pull_twohead
) {
1291 char *default_strategy
= getenv("GIT_TEST_MERGE_ALGORITHM");
1292 if (default_strategy
&& !strcmp(default_strategy
, "ort"))
1293 pull_twohead
= "ort";
1296 init_diff_ui_defaults();
1297 git_config(git_merge_config
, NULL
);
1299 if (!branch
|| is_null_oid(&head_oid
))
1302 head_commit
= lookup_commit_or_die(&head_oid
, "HEAD");
1304 if (branch_mergeoptions
)
1305 parse_branch_merge_options(branch_mergeoptions
);
1306 argc
= parse_options(argc
, argv
, prefix
, builtin_merge_options
,
1307 builtin_merge_usage
, 0);
1308 if (shortlog_len
< 0)
1309 shortlog_len
= (merge_log_config
> 0) ? merge_log_config
: 0;
1311 if (verbosity
< 0 && show_progress
== -1)
1314 if (abort_current_merge
) {
1316 const char *nargv
[] = {"reset", "--merge", NULL
};
1317 char stash_oid_hex
[GIT_MAX_HEXSZ
+ 1];
1318 struct object_id stash_oid
= {0};
1321 usage_msg_opt(_("--abort expects no arguments"),
1322 builtin_merge_usage
, builtin_merge_options
);
1324 if (!file_exists(git_path_merge_head(the_repository
)))
1325 die(_("There is no merge to abort (MERGE_HEAD missing)."));
1327 if (!read_ref("MERGE_AUTOSTASH", &stash_oid
))
1328 delete_ref("", "MERGE_AUTOSTASH", &stash_oid
, REF_NO_DEREF
);
1330 /* Invoke 'git reset --merge' */
1331 ret
= cmd_reset(nargc
, nargv
, prefix
);
1333 if (!is_null_oid(&stash_oid
)) {
1334 oid_to_hex_r(stash_oid_hex
, &stash_oid
);
1335 apply_autostash_oid(stash_oid_hex
);
1341 if (quit_current_merge
) {
1343 usage_msg_opt(_("--quit expects no arguments"),
1344 builtin_merge_usage
,
1345 builtin_merge_options
);
1347 remove_merge_branch_state(the_repository
);
1351 if (continue_current_merge
) {
1353 const char *nargv
[] = {"commit", NULL
};
1356 usage_msg_opt(_("--continue expects no arguments"),
1357 builtin_merge_usage
, builtin_merge_options
);
1359 if (!file_exists(git_path_merge_head(the_repository
)))
1360 die(_("There is no merge in progress (MERGE_HEAD missing)."));
1362 /* Invoke 'git commit' */
1363 ret
= cmd_commit(nargc
, nargv
, prefix
);
1367 if (repo_read_index_unmerged(the_repository
))
1368 die_resolve_conflict("merge");
1370 if (file_exists(git_path_merge_head(the_repository
))) {
1372 * There is no unmerged entry, don't advise 'git
1373 * add/rm <file>', just 'git commit'.
1375 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
))
1376 die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
1377 "Please, commit your changes before you merge."));
1379 die(_("You have not concluded your merge (MERGE_HEAD exists)."));
1381 if (ref_exists("CHERRY_PICK_HEAD")) {
1382 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
))
1383 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
1384 "Please, commit your changes before you merge."));
1386 die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
1388 resolve_undo_clear_index(&the_index
);
1390 if (option_edit
< 0)
1391 option_edit
= default_edit_option();
1393 cleanup_mode
= get_cleanup_mode(cleanup_arg
, 0 < option_edit
);
1399 if (fast_forward
== FF_NO
)
1400 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--no-ff.");
1401 if (option_commit
> 0)
1402 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--commit.");
1404 * squash can now silently disable option_commit - this is not
1405 * a problem as it is only overriding the default, not a user
1411 if (option_commit
< 0)
1415 if (default_to_upstream
)
1416 argc
= setup_with_upstream(&argv
);
1418 die(_("No commit specified and merge.defaultToUpstream not set."));
1419 } else if (argc
== 1 && !strcmp(argv
[0], "-")) {
1424 usage_with_options(builtin_merge_usage
,
1425 builtin_merge_options
);
1429 * If the merged head is a valid one there is no reason
1430 * to forbid "git merge" into a branch yet to be born.
1431 * We do the same for "git pull".
1433 struct object_id
*remote_head_oid
;
1435 die(_("Squash commit into empty head not supported yet"));
1436 if (fast_forward
== FF_NO
)
1437 die(_("Non-fast-forward commit does not make sense into "
1439 remoteheads
= collect_parents(head_commit
, &head_subsumed
,
1442 die(_("%s - not something we can merge"), argv
[0]);
1443 if (remoteheads
->next
)
1444 die(_("Can merge only exactly one commit into empty head"));
1446 if (verify_signatures
)
1447 verify_merge_signature(remoteheads
->item
, verbosity
,
1450 remote_head_oid
= &remoteheads
->item
->object
.oid
;
1451 read_empty(remote_head_oid
);
1452 update_ref("initial pull", "HEAD", remote_head_oid
, NULL
, 0,
1453 UPDATE_REFS_DIE_ON_ERR
);
1458 * All the rest are the commits being merged; prepare
1459 * the standard merge summary message to be appended
1460 * to the given message.
1462 remoteheads
= collect_parents(head_commit
, &head_subsumed
,
1463 argc
, argv
, &merge_msg
);
1465 if (!head_commit
|| !argc
)
1466 usage_with_options(builtin_merge_usage
,
1467 builtin_merge_options
);
1469 if (verify_signatures
) {
1470 for (p
= remoteheads
; p
; p
= p
->next
) {
1471 verify_merge_signature(p
->item
, verbosity
,
1476 strbuf_addstr(&buf
, "merge");
1477 for (p
= remoteheads
; p
; p
= p
->next
)
1478 strbuf_addf(&buf
, " %s", merge_remote_util(p
->item
)->name
);
1479 setenv("GIT_REFLOG_ACTION", buf
.buf
, 0);
1482 for (p
= remoteheads
; p
; p
= p
->next
) {
1483 struct commit
*commit
= p
->item
;
1484 strbuf_addf(&buf
, "GITHEAD_%s",
1485 oid_to_hex(&commit
->object
.oid
));
1486 setenv(buf
.buf
, merge_remote_util(commit
)->name
, 1);
1488 if (fast_forward
!= FF_ONLY
&& merging_a_throwaway_tag(commit
))
1489 fast_forward
= FF_NO
;
1492 if (!use_strategies
&& !pull_twohead
&&
1493 remoteheads
&& !remoteheads
->next
) {
1494 char *default_strategy
= getenv("GIT_TEST_MERGE_ALGORITHM");
1495 if (default_strategy
)
1496 append_strategy(get_strategy(default_strategy
));
1498 if (!use_strategies
) {
1500 ; /* already up-to-date */
1501 else if (!remoteheads
->next
)
1502 add_strategies(pull_twohead
, DEFAULT_TWOHEAD
);
1504 add_strategies(pull_octopus
, DEFAULT_OCTOPUS
);
1507 for (i
= 0; i
< use_strategies_nr
; i
++) {
1508 if (use_strategies
[i
]->attr
& NO_FAST_FORWARD
)
1509 fast_forward
= FF_NO
;
1510 if (use_strategies
[i
]->attr
& NO_TRIVIAL
)
1515 ; /* already up-to-date */
1516 else if (!remoteheads
->next
) {
1517 if (repo_get_merge_bases(the_repository
, head_commit
,
1518 remoteheads
->item
, &common
) < 0) {
1523 struct commit_list
*list
= remoteheads
;
1524 commit_list_insert(head_commit
, &list
);
1525 if (get_octopus_merge_bases(list
, &common
) < 0) {
1533 update_ref("updating ORIG_HEAD", "ORIG_HEAD",
1534 &head_commit
->object
.oid
, NULL
, 0, UPDATE_REFS_DIE_ON_ERR
);
1536 if (remoteheads
&& !common
) {
1537 /* No common ancestors found. */
1538 if (!allow_unrelated_histories
)
1539 die(_("refusing to merge unrelated histories"));
1540 /* otherwise, we need a real merge. */
1541 } else if (!remoteheads
||
1542 (!remoteheads
->next
&& !common
->next
&&
1543 common
->item
== remoteheads
->item
)) {
1545 * If head can reach all the merge then we are up to date.
1546 * but first the most common case of merging one remote.
1548 finish_up_to_date();
1550 } else if (fast_forward
!= FF_NO
&& !remoteheads
->next
&&
1552 oideq(&common
->item
->object
.oid
, &head_commit
->object
.oid
)) {
1553 /* Again the most common case of merging one remote. */
1554 const char *msg
= have_message
?
1555 "Fast-forward (no commit created; -m option ignored)" :
1557 struct commit
*commit
;
1559 if (verbosity
>= 0) {
1560 printf(_("Updating %s..%s\n"),
1561 repo_find_unique_abbrev(the_repository
, &head_commit
->object
.oid
,
1563 repo_find_unique_abbrev(the_repository
, &remoteheads
->item
->object
.oid
,
1566 commit
= remoteheads
->item
;
1573 create_autostash_ref(the_repository
, "MERGE_AUTOSTASH");
1574 if (checkout_fast_forward(the_repository
,
1575 &head_commit
->object
.oid
,
1576 &commit
->object
.oid
,
1577 overwrite_ignore
)) {
1578 apply_autostash_ref(the_repository
, "MERGE_AUTOSTASH");
1583 finish(head_commit
, remoteheads
, &commit
->object
.oid
, msg
);
1584 remove_merge_branch_state(the_repository
);
1586 } else if (!remoteheads
->next
&& common
->next
)
1589 * We are not doing octopus and not fast-forward. Need
1592 else if (!remoteheads
->next
&& !common
->next
&& option_commit
) {
1594 * We are not doing octopus, not fast-forward, and have
1597 refresh_index(&the_index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
1598 if (allow_trivial
&& fast_forward
!= FF_ONLY
) {
1600 * Must first ensure that index matches HEAD before
1601 * attempting a trivial merge.
1603 struct tree
*head_tree
= repo_get_commit_tree(the_repository
,
1605 struct strbuf sb
= STRBUF_INIT
;
1607 if (repo_index_has_changes(the_repository
, head_tree
,
1609 error(_("Your local changes to the following files would be overwritten by merge:\n %s"),
1611 strbuf_release(&sb
);
1616 /* See if it is really trivial. */
1617 git_committer_info(IDENT_STRICT
);
1618 printf(_("Trying really trivial in-index merge...\n"));
1619 if (!read_tree_trivial(&common
->item
->object
.oid
,
1620 &head_commit
->object
.oid
,
1621 &remoteheads
->item
->object
.oid
)) {
1622 ret
= merge_trivial(head_commit
, remoteheads
);
1625 printf(_("Nope.\n"));
1629 * An octopus. If we can reach all the remote we are up
1633 struct commit_list
*j
;
1635 for (j
= remoteheads
; j
; j
= j
->next
) {
1636 struct commit_list
*common_one
= NULL
;
1637 struct commit
*common_item
;
1640 * Here we *have* to calculate the individual
1641 * merge_bases again, otherwise "git merge HEAD^
1642 * HEAD^^" would be missed.
1644 if (repo_get_merge_bases(the_repository
, head_commit
,
1645 j
->item
, &common_one
) < 0)
1648 common_item
= common_one
->item
;
1649 free_commit_list(common_one
);
1650 if (!oideq(&common_item
->object
.oid
, &j
->item
->object
.oid
)) {
1656 finish_up_to_date();
1661 if (fast_forward
== FF_ONLY
)
1662 die_ff_impossible();
1665 create_autostash_ref(the_repository
, "MERGE_AUTOSTASH");
1667 /* We are going to make a new commit. */
1668 git_committer_info(IDENT_STRICT
);
1671 * At this point, we need a real merge. No matter what strategy
1672 * we use, it would operate on the index, possibly affecting the
1673 * working tree, and when resolved cleanly, have the desired
1674 * tree in the index -- this means that the index must be in
1675 * sync with the head commit. The strategies are responsible
1678 * Stash away the local changes so that we can try more than one
1679 * and/or recover from merge strategies bailing while leaving the
1680 * index and working tree polluted.
1682 if (save_state(&stash
))
1685 for (i
= 0; i
< use_strategies_nr
; i
++) {
1688 printf(_("Rewinding the tree to pristine...\n"));
1689 restore_state(&head_commit
->object
.oid
, &stash
);
1691 if (use_strategies_nr
!= 1)
1692 printf(_("Trying merge strategy %s...\n"),
1693 use_strategies
[i
]->name
);
1695 * Remember which strategy left the state in the working
1698 wt_strategy
= use_strategies
[i
]->name
;
1700 ret
= try_merge_strategy(wt_strategy
,
1701 common
, remoteheads
,
1704 * The backend exits with 1 when conflicts are
1705 * left to be resolved, with 2 when it does not
1706 * handle the given merge at all.
1711 * This strategy worked; no point in trying
1715 best_strategy
= wt_strategy
;
1718 cnt
= (use_strategies_nr
> 1) ? evaluate_result() : 0;
1719 if (best_cnt
<= 0 || cnt
<= best_cnt
) {
1720 best_strategy
= wt_strategy
;
1727 * If we have a resulting tree, that means the strategy module
1728 * auto resolved the merge cleanly.
1730 if (merge_was_ok
&& option_commit
) {
1731 automerge_was_ok
= 1;
1732 ret
= finish_automerge(head_commit
, head_subsumed
,
1733 common
, remoteheads
,
1734 &result_tree
, wt_strategy
);
1739 * Pick the result from the best strategy and have the user fix
1742 if (!best_strategy
) {
1743 restore_state(&head_commit
->object
.oid
, &stash
);
1744 if (use_strategies_nr
> 1)
1746 _("No merge strategy handled the merge.\n"));
1748 fprintf(stderr
, _("Merge with strategy %s failed.\n"),
1749 use_strategies
[0]->name
);
1750 apply_autostash_ref(the_repository
, "MERGE_AUTOSTASH");
1753 } else if (best_strategy
== wt_strategy
)
1754 ; /* We already have its result in the working tree. */
1756 printf(_("Rewinding the tree to pristine...\n"));
1757 restore_state(&head_commit
->object
.oid
, &stash
);
1758 printf(_("Using the %s strategy to prepare resolving by hand.\n"),
1760 try_merge_strategy(best_strategy
, common
, remoteheads
,
1765 finish(head_commit
, remoteheads
, NULL
, NULL
);
1767 git_test_write_commit_graph_or_die();
1769 write_merge_state(remoteheads
);
1772 fprintf(stderr
, _("Automatic merge went well; "
1773 "stopped before committing as requested\n"));
1775 ret
= suggest_conflicts();
1777 printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1780 if (!automerge_was_ok
) {
1781 free_commit_list(common
);
1782 free_commit_list(remoteheads
);
1784 strbuf_release(&buf
);
1785 free(branch_to_free
);
1786 discard_index(&the_index
);