When I’m working with Git, there are times I want to check if I can do a fast-forward merge but I do NOT want to actually perform the merge.
Let’s assume I’m on the main
branch and I want to merge the branch feat/x
into main
.
The following would merge the feat/x
branch into main
, only if it is a fast-forward merge (otherwise, it fails).
git merge --ff-only feat/x
Just Check, Don’t Merge
I want to do this same check but without actually merging. I can do this with
git merge-base --is-ancestor main feat/x && \
echo 'can ff-merge' || echo 'can NOT ff-merge'
A fast-forward merge can only be done when the most recent commit on the target branch is an ancestor in the source branch (i.e. the commit at the tip of the receiving branch (main
) must appear somewhere in the branch providing the new commits (feat/x
) ).
Generalizing
Since git merge
requires only the branch we are merging in, we can modify this command so we use our current branch as the target branch.
git merge-base --is-ancestor $(git branch --show-current) feat/x \
&& echo 'can ff-merge' || echo 'can NOT ff-merge'
We’ve replace main
with $(git branch --show-current)
which will use the name of our current branch. Now we can use this line and we only need to change feat/x
to whatever branch we are merging in.
Git Alias
Git allows us to define an alias to save some typing, this is a great opportunity for an alias. By adding the following to my ~./gitconfig file.
[alias]
can-ff-merge = "!f() { \
[ -e "${1}" ] && echo "Missing branch name to merge" && exit 1; \
git "merge-base --is-ancestor \
$(git branch --show-current) ${1}" \
&& echo 'Yes, this can ff-merge' && exit 0 \
|| echo 'No, this can NOT ff-merge' && exit 1; \
}; f"
Now, I can type
git can-ff-merge feat/x
Leave a Reply