Working with 2 or more branches in Git like a pro

productivity

Working%20with%202%20or%20more%20branches%20in%20Git%20like%20a%20pro%205ead6716c12b409b86f405c1be036a7b/text.png

How many times it happens that you are working on a feature branch like feature-1. You have done some of the development work, changes are done in a lot of files. At that moment you get to do a bug fix in the main branch. For many years, my workflow involved the following steps to switch from feature-1 to bugfix-1:

# Temporarily store the non-committed changes
git stash 
git checkout -b bugfix-1
# Make sure that bugfix-1 is up to date with the main branch
git fetch && git reset --hard origin/main
# .... do your work and push the changes...

Now, get back to feature-1 branch.

git checkout feature-1
git stash apply

This approach had it's drawbacks:

  • What if there are more changes stashed on it, a simple git stash apply would apply the wrong changes.
    • It can be solved by naming the stash git stash save feature-1 and applying it later using git stash apply stash^{/feature-1}
  • If you had changes in your package.json you would have to do an npm install which would update node_modules and then come back to the feature-1 branch to find out that the build is broken here because node_modules aren't up to date. Then you have to do an npm install again.
  • git stash doesn't shelve git ignored files or untracked changes while doing a hard reset you might lose those changes if say that one of the untracked files is committed in bugfix-1

Apart from these drawbacks, I didn't find this approach intuitive. I just wanted to simply work on another branch.

I even tried making a copy of the repo dir itself, but that was slow because doing an entire repo clone can take time.

This was all when I didn't look hard for the solution from git itself. Well, git provide a very simple way to achieve this.

Welcome worktree :)

# Create a bugfix-1 dir with the main branch checked out in it.
git worktree add ../bugfix-1 main 

# Now go and work with your branch.
cd ../bugfix-1
git fetch && git reset --hard origin/main
git checkout -b bugfix-1

Using this approach, I can contribute in parallel in more than 1 branch. You can simultaneously test out the branches without one branch impacting the other branch at all.

I thought of talking about it in my blog today because it saved me again as I had a requirement to compare 3 branches to understand what are the differences b/w them. The goal was to create a framework that would allow the code from 3 branches to exist simultaneously in a single branch.

... Loading comments