Steve
Steve

Reputation: 347

git: How to undo my last "git push -f" without previous versions?

I have a repo1 on github and had the latest clean version (let's call it "latest-version").

I cloned it but...

I did:

rm -fr .git
git init
git remote add origin <repo1 url>"

Then, I modified various files and ran "git push -f origin master" to overwrite all the files.

With no previous history/log in my local .git directory, how can I remove my last push so that I can get back the "latest-version" files on repo1?

That is, I wish I didn't run any of the above commands and just had the original "latest-version" files.

Thanks much in advance!

Upvotes: 3

Views: 67

Answers (1)

SIREN
SIREN

Reputation: 181

You can try GitHub's reflog.

Taken from:

First, use GitHub’s Events API to retrieve the commit SHA:

$ curl https://api.github.com/repos/<user>/<repo>/events

This will return a JSON response which you can read through to find the last commit from the lost branch. Use the commit message and approximate times to narrow your search.

Next, use GitHub’s Refs API to create a new branch pointing to that commit:

$ curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '{"ref": "refs/heads/your-new-branch", "sha": "384f275933d5b762cdb27175aeff1263a8a7b7f7"}' https://api.github.com/repos/<user>/<repo>/git/refs

The "ref" in the JSON above is Git ref we want to create, it must be of the form refs/heads/your-new-branch, where your-new-branch is the name of the branch we want to create in Git. The "sha" is the commit that we want this new branch to point to.

Now if you pull up your repository in GitHub, you will see the new branch and doing a git fetch will retrieve that new branch to your local repository.

Probably you will need to authenticate. Here is the authentication documentation https://docs.github.com/en/rest/overview/resources-in-the-rest-api#authentication

Upvotes: 4

Related Questions