• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Dev Tips / Check If We Can Do a Git Fast-Forward Merge

Check If We Can Do a Git Fast-Forward Merge

Last updated on August 31, 2022 by Sal Ferrarello

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
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit
Warning! This is a draft, not a finalized post. See full draft disclosure.

Filed Under: Dev Tips, Draft, Solution Tagged With: fast-forward, Git

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in