DEV Community

Cover image for How to clean your git history
Slava Vasenin for Visual Composer

Posted on

How to clean your git history

Hi!
I want to share you a short instruction on how to remove wrong or mistaken commits from a remote repository when you don't want to make a revert.

Check changes and find what commits you want to remove.

$ git log --stat

Use the interactive rebase command.

$ git rebase -i HEAD~X

Put the number of commits instead of X which you want to remove. Better to add a bit more to view the previous ones also. So, you need to remove 1 commit add number 3.

You will see something like this:

pick a0b45b373 Dynamic field featured image url fixed
pick 8e8d27747 Update render condition for feedback popup component
pick 843770a32 Add dev.to version

# Rebase 680ac7c26..843770a32 onto 680ac7c26 (3 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit

I use Vim as default text editor for Git.

Replace the word pick with the word drop or d for those commits that you want to remove. I remove only one, but I also checked and see that previous commits not related to my changes.

pick a0b45b373 Dynamic field featured image url fixed
pick 8e8d27747 Update render condition for feedback popup component
d 843770a32 Add dev.to version

Save and exit from your editor.

Check git status.

$ git status
On branch master
Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
  (use "git pull" to update your local branch)

nothing to commit, working tree clean

In some cases, there can be merge conflicts after rebase. Follow instructions to solve them.

The next step is to push it to your remote repository. You need to force this push because the remote repository will think that your current branch is behind.

git push -f

Go and check your remote repository.

That it. Thanks and Good luck 🚀

Cover image by Diana Mounter

Top comments (0)