DEV Community

Cover image for How to Slice Out Bad Commits and Keep Your Git Tree Clean
Gouranga Das Samrat
Gouranga Das Samrat

Posted on

How to Slice Out Bad Commits and Keep Your Git Tree Clean

How to Slice Out Bad Commits and Keep Your Git Tree Clean

I was working on a large scale project. I messed up my git history again. It’s a tangle of messy commits I need gone.

Rewriting history manually feels like untangling headphones. It’s slow, error-prone, and I’m terrified of breaking my branch.

Here’s how to do it in simple steps

Here’s a cleaner way to slice out those unwanted commits:

I found a small but magical command: git rebase --onto to surgically remove a range of commits.

Suppose you got a git tree that has commit that looks like below:

A --- B --- C --- D --- E --- F

Now you want to delete commits B, C, D, E. You can do this easily using below:

git rebase --onto B^ E
Enter fullscreen mode Exit fullscreen mode

This command rewrites history by replanting your branch’s good commits onto a new base, skipping the bad ones.

Important point to remember

If the branch you are working on is a shared branch (e.g., main), and you want to update the remote history to match your new rewritten history, you need to force-push.

This replaces the remote branch history with your local rewritten history.

  • Force-pushing rewrites history. This can break things for others if they have already pulled the previous history.
  • If you’re working on a team, coordinate with others before force-pushing.
  • Consider using --force-with-lease instead of --force as a safer option:
git push --force-with-lease
Enter fullscreen mode Exit fullscreen mode

This only force-pushes if your local view of the remote is up to date and it prevents you from accidentally overwriting someone else’s push.

Final takeaway

This simple trick save me hours when I messed up my Git history. Try it for yourself and share your thoughts in comment.

Thank you. Let’s meet again with a new cool trick.

Thank you for being a part of the community

Top comments (0)