Remove commit from history

275.9k views Asked by At

I entered a curseword in my code and I pushed the code on the master branch. I pushed a few more times after that so people do not pull the bad stuff, but I can still find the curseword in the commits history.

I don't want to add the file to .gitignore because we need that file.

Is there a way to delete the commit from history?

4

There are 4 answers

6
Maciej Oziębły On BEST ANSWER

If it's only on your local PC (or noone checked out your changes):

  1. Use:
    git log
    

to find the commit you want to remove. Copy hash (the long sqeuence like: e8348ebe553102018c...).

  1. Use:
    git rebase -i [hash]~
    
    : for example
    git rebase -i e8348~
    

Just remove the commit you don't need and save the file.

Interactive git rebase can let you also fix the broken commit - there is no need to remove it.

If you pushed changes to the server or someone already got your changes - never change history - it'd cause serious problems for your team.

5
David Deutsch On

Once you push to the repo, you really don't want to go about changing history. However, if you are absolutely sure that nobody has pulled/fetched from the repo since your offending commit, you have 2 options.

If you want to remove the "bad" commit altogether (and every commit that came after that), do a git reset --hard ABC (assuming ABC is the hash of the "bad" commit's elder sibling — the one you want to see as the new head commit of that branch). Then do a git push --force (or git push -f).

If you just want to edit that commit, and preserve the commits that came after it, do a git rebase -i ABC~. This will launch your editor, showing the list of your commits, starting with the offending one. Change the flag from "pick" to "e", save the file and close the editor. Then make the necessary changes to the files, and do a git commit -a --amend, then do git rebase --continue. Follow it all up with a git push -f.

I want to repeat, these options are only available to you if nobody has done a pull or fetch that contains your offending commit. If they have, doing these steps will just make matters worse.

7
NutCracker On

This works for me:

  1. git log to find the commit you want to remove and copy its hash
  2. git rebase -i <commit_hash>~ which opens your text editor
  3. in text editor, switch from pick to drop for your particular commit
2
Ali Miskeen On

I was working with a team recently and found out that git has solution for this

all on this link

https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository

which is using git-filter-repo and BFG Repo-Cleaner

here is a cool video for exactly that

https://www.youtube.com/watch?v=z8tIOYg_oho