Home > database >  Git: Undo a commit after several good commits have been commited afterwards
Git: Undo a commit after several good commits have been commited afterwards

Time:02-14

I have a beginner question around git and GitHub i was hoping someone could help with.

I have accidentally committed a change in piece of code that contains credentials on my local private repository on my local machine.

My pseudo commit history looks like the below and i am using the desktop application for GitHub to make these commits. I made the mistaken commit at id 3 but then all my other commits from four to seven are a big body of work and I do not wish to lose them.

Since this is my own repository the quick method might be to simply copy out the files i changed and revert back all my changes to id 3 and then copy in my good changed files. I was wondering if there was a better Git way

commit first change  id 1
commit second change id 2
commit third change  id 3 - here is where the password was committed
commit first change  id 4
commit second change id 5
commit first change  id 6
commit second change id 7

Thank you very much for your time

CodePudding user response:

You either can do squash:

git rebase -i <commit_id or HEAD~5>
# move your cursor on the commit line & delete that commit by pressing double `d`
git push -f origin <branch>

It helps to delete selected commits only, without changing commits after and before that commit.

Or, soft reset and commit:

git reset --soft <commit_id or HEAD~5>
git add .
git commit -m "<message>"
git push -f origin <branch>

It deletes all commits from the commit_id or HEAD~5 and makes a single commit.

CodePudding user response:

Since you tagged GitHub as well. Be sure to contact GitHub support to have them expunge the commit from their issue and PR links as well as the caches.

Do reset the password. Once pushed the password is out there.

The official process would be to:

  • Git clone --mirror a fresh copy of the repo. To be sure you have everything
  • git filter-ropo to remove the password from all commits
  • Then run the garbage collector to remove all unreferenced commits: git reflog expire --expire=now --all && git gc --prune=now --aggressive
  • Then force push the repo
  • Then contact GitHub support to remove the old commits from the caches.
  • Then contact all other contributors to get a fresh clone of to rebase their branches into the updated repository.
  • Related