By restoring a recent commit, previous to the ones you want to delete, and then adding the ones you want to recover.
Based on here. Cherry Pick method.
Let's say these are our recent commits:
Number | Hash | Commit Message | Author |
---|---|---|---|
1 | 2c6a45b | Updated main code. | John |
2 | ae45fab | Uploaded super secret file 2 by mistake. | James |
3 | 77b9b82 | Uploaded super secret file 1 by mistake. | James |
4 | 3c9093c | Updated README.md | John |
5 | b3d92c5 | Updated requirements.txt | John |
Ok, so James commited 2 files that we do not want to be public, even if he makes another commit deleting it.
We clone the repo if we don't have it already:
git clone https://github.com/Username/SuperImportantRepo.git
Next, we get the hash of the commit we want to restore (in this case number 4) and we checkout. Don't worry, we will add the commit 1 later (Only one in this case).
git log # Get the hash
git checkout <hash> # Checkout
Now we make a temporal branch from that checkout.
git checkout -b temp # The name you want, in this case temp
Now we add the commit (or commits) after the ones we want to delete. In this case number 1.
git cherry-pick <hash>
git cherry-pick <hash> # If we had more than one.
...
Check that everything is fine with:
git status
Now checkout back to your broken branch, the one with the James files:
git checkout <old branch>
Now we need to do a hard reset on that branch, to the commit previous to the one bad ones (Line 24).
git reset --hard <hash> # In this case number 4
Now merge the fixed branch (temp
) into the broken one.
git merge <main branch>
git push --force origin <main branch main> # Will overwrite the remote repo!
Number | Hash | Commit Message | Author |
---|---|---|---|
1 | 2c6a45b | Updated main code. | John |
2 | ae45fab | Uploaded super secret file 2 by mistake. | James |
3 | 77b9b82 | Uploaded super secret file 1 by mistake. | James |
4 | 3c9093c | Updated README.md | John |
5 | b3d92c5 | Updated requirements.txt | John |
git checkout 3c9093c # Checkout the last usable commit.
git checkout -b temp # Create a new branch to work on (temp).
git cherry-pick 2c6a45b # Run through commit 1.
git checkout master # Checkout master.
git reset --hard 3c9093c # Reset master to last usable commit.
git merge temp # Merge our new branch (temp) onto master.
git push --hard origin master # Push master to the remote repo.