Kaho
Kaho

Reputation: 73

Retrieve the previous state of the forked repository

I accidentally pushed the wrong commit, which was the first commit, to the main branch of the forked repository.

Since that forked repository has a lot of directories, I always downloaded only directories that I would work on at the time on my local machine. Then, I created or modified files.

Before I pushed the first commit(the wrong one), I always had uploaded those new files or modified files on the GitHub repository using the GitHub web UI. I'd never committed to Git at that moment.

Once I uploaded those files, I deleted them from my local machine.

Then, I committed a file to Git and pushed it to GitHub(used the following command git push -f)...now there is only one file in the repository.

I wanted to undo this and get back the forked repository with all files I uploaded. (I did undo the commit with git update-ref -d HEAD command, but there's no change on GitHub of course.)

I hope this explains my situation well enough, and please help me out.

(I thought I needed to ask the GitHub Support team and did, but still can't solve it yet...)

Upvotes: 3

Views: 1795

Answers (1)

VonC
VonC

Reputation: 1329122

You need to use the GitHub poor man's reflog and query the GitHub Events API in order to get the most recent "previous" commit.

curl -u <username> https://api.github.com/repos/:owner/:repo/events

(replace :owner and :repo by your GitHub login and repository name)

From there, you can create a branch (on GitHub side) based on that commit:

curl -u <github-username> -X POST -d '{"ref":"refs/heads/<new-branch-name>", "sha":"<sha-from-step-1>"}' https://api.github.com/repos/:owner/:repo/git/refs

You can the fetch from origin, and locally reset your main branch to said "rescue" branch

git switch -C main origin/<new-branch-name>
git push -f

Note: you might need to add a personal access token when using curl

curl -i -u username:$token https://api.github.com/...

See Creating a personal access token.

Upvotes: 2

Related Questions