Faster rebasing with git reset
Lately I’ve been needing to rebase and squash my commits more frequently. I’ve always been averse to doing anything like this because I’ve basically always screwed it up when using the command line. But thanks to this pro-tip I stumbled on, rewriting commits on an existing branch and PR has never been easier.
Rather than do the git rebase -i
dance, this approach resets your changes so you can selectively add what you need and write new commits. So much more approachable to me with my Git experience.
Here’s the crux of the tip from the post that uses git reset
to uncommit the differences between your feature_branch
and master
:
# Switch to the master branch and make sure you are up to date.
git checkout master
git fetch # this may be necessary (depending on your git config) to receive updates on origin/master
git pull
# Merge the feature branch into the master branch.
git merge feature_branch
# Reset the master branch to origin's state.
git reset origin/master
# Git now considers all changes as unstaged changes.
# We can add these changes as one commit.
# Adding . will also add untracked files.
git add --all
git commit
From here, add your files and changes in pieces as you like, write new commit messages, and then push your branch. If your branch is already pushed to origin
, you may need to force push (git push origin feature_branch --force
). Be aware force pushing can have unintended consequences, so test these things out first in a safe environment.
This page is nearly 10 years old and it’s still highly relevant. It also includes details on how to do a proper git rebase
for comparison. Hope it’s as helpful to you as it’s been to me with my open source projects and more.