When working with Git branches, it’s often necessary to keep different branches such as “develop,” “release,” or “staging” branches. With Git, it’s easy to fast forward a branch to keep it up to date with another branch, such as updating the release branch to include changes on staging.
Fast-Forwarding a Git Branch
In Git, branches are just pointers to a specific commit, called the HEAD of the branch. The branch is simply a label that can change when the branch is updated with new commits or merged with another.
To merge two divergent branches together, you can use git merge
. Usually, this creates a “merge commit” that combines the histories of the two branches, such as commits from a feature branch being pulled into the main branch with a pull request.
However, if the two branches have the same history, Git will do a special fast-forward merge. In the example above, the release
branch HEAD is included in develop
‘s history, meaning there is no need for a merge commit. Instead, release
is updated to point to develop
.
There’s no special git fast-forward
command for this; it’s a simple merge like any other. When merging, you want to check out the branch that is going to receive the changes. In this case, release
is the branch being updated, so we check out release:
git checkout release
Then we can merge the develop branch into it, which will perform the fast forward:
git merge develop
If you’re using a Git GUI client, this process may be more intuitive. Most clients will have an option to right click the outdated branch, and bring it up to date with the one you’re working on.
Fast-Forwarding Remote Branches
One thing to note is that fast-forwarding will update your local repository only. You will need to push to Github to update the remote. If you’re using a GUI client, you may see the label for the remote repository being out of date until you push.
Fast forwarding the branch doesn’t create a commit, but it should still trigger CI/CD pipelines such as Github Actions. If it doesn’t, there is an option to always create a merge commit:
git merge --no-ff
This can also be useful in some cases for maintaining a more explicit branch topology, where feature branches will always be separate from the main branch and create a merge commit when they are combined. By default, if you didn’t change anything on the main branch when you merge in the feature, Git will fast-forward the main branch instead of creating the usual merge commit that you might expect. The --no-ff
flag will prevent that behaviour.
Alternatively, if you’d like to attempt to fast forward, and fail if a merge commit is required, you can use the --ff-only
flag.