[Howto] Rebase feature branches in Git/Github

Git-Icon-1788CUpdating a feature branch to the actual state of the upstream main branch can be troublesome. Here is a workflow that works – at least for me.

Developing with Git is amazing, due to the possibilities to work with feature branches, remote repositories and so on. However, at some point, after some hours of development, the base of a feature branch will be outdated and it makes sense to update it before a pull request is send upstream. This is best done via rebasing. Here is a short work flow for a typical feature branch rebase I often need when developing for example Ansible modules.

  1. First, checkout the main branch, here devel.
  2. Update the main branch from the upstream repository.
  3. Rebase the local copy of the main branch.
  4. Push it to the remote origin, most likely your personal fork of the Git repo.
  5. Check out the feature branch
  6. Rebase the feature branch to the main branch.
  7. Force push the new history to the remote feature branch, most likely again your personal fork of the Git repo.

In terms of code this means:

$ git checkout devel
$ git fetch upstream devel
$ git rebase upstream/devel
$ git push
$ git checkout feature_branch
$ git rebase origin/devel
$ git push -f

This looks rather clean and easy – but I have to admit it took me quite some errors and Git cherry picking to finally get what is needed and what actually works.

[Short Tip] Git, cherry-pick and push

Git-Icon-1788C

Much too often, when working with Git and working on long time pull requests, I tend to screw up the Git history. For that reason, I often have to cherry pick a commit into a new branch and push that one upstream to the feature branch – with force.

First, identify the actual commits you want to cherry pick. You need to get the correct hash there. Then, create a new branch, cherry pick the commit, force the new branch upstream, delete the old branch, and rename the new one.

git log --author liquidat
git branch mywork_feature_tmp
git cherry-pick abcdefgh123456
git push --force origin HEAD:mywork_feature
git checkout devel
git branch -D mywork_feature
git branch -m mywork_feature_tmp mywork_feature

My hope is that in some point in the future I will be able to fix such broken Git repos at that point without cherry-pick. But until then, the current way works for me…