Rajeev Ranjan
Rajeev Ranjan

Reputation: 13

Unable to do git revert after forced push to remote repository

I created a new folder in my system. There, I did git init and then added remote origin like

git remote add origin https://github.com/usrname/reponame

Then, without taking pull, I forcefully pushed my local change to existing git repo using -f command which deleted previous data and stored new one.

Now I want my previous data of that git repo. Just after git push, I executed git reset --hard HEAD~1, but got this error:

Error message

I also tried git reset --hard last_commit_id, which I got after forced update but getting error like fatal: ambiguous argument '0...4': unknown revision or path not in the working tree.

I even did git log --all or git reflog, but not getting previous commit IDs and data.

Upvotes: 0

Views: 126

Answers (2)

VonC
VonC

Reputation: 1328562

HEAD~1 does not exist locally, since you just initialized your local repository.

Assuming the remote repository was not a new repository, but one where multiple pushes did occur (before your last forced push, which overrode everything), you could try and retrieve the previous push (the one done before your force push)

For that, you can use the poor man reflog, which uses the GitHub API to retrieve the public push event and its associated SHA1. (curl -u <username>:<token> https://api.github.com/repos/<user>/<repo>/events)
Replace <user> by your GitHub username, and <repo> by your repository name. Use a PAT (Personal Access Token) as <token>.

You would then need, as mentioned in the previous link, to create a GitHub branch "tmp" to reference that old SHA1 (still using GitHub API).
From there, you can fetch, and reset your local master to the fetched origin/tmp

git switch -C master origin/tmp

The OP used the blobs / get a blob GitHub API to

see full details of my last to last commit using SHA.
In full details, I got html_ulr which took me to a GitHub page which where I was able to download the files

Upvotes: 3

Dev-vruper
Dev-vruper

Reputation: 430

Instead doing a reset, you could perform a revert on the branch to revert the commit that was pushed forcefully. Something like

git revert HEAD~1

git push origin master

Upvotes: 0

Related Questions