Search code examples
gitgithubgithub-api

How to recover lost commits without using git reflog?


By somehow I accidentally forcefully pushed a branch and I didn't pull commits that only existed in remote.

Usually, when this happens it can be recovered with the git reflog command but this time the lost commits were only in the remote repo.

How I can recover those commits that only existed in the GitHub repository?


Solution

  • It can be done with a few steps with the GitHub API:

    1. Go to this URL: https://api.github.com/repos/<user>/<repo>/events

    This will return/show a JSON object where you can search for the lost commit using CTRL+F and putting the commit message or maybe the author.

    1. Copy the full SHA of the commit and paste it in the following command:
    curl -u <user>:<password> -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '{"ref":"refs/heads/recover-commits", "sha":"<full_commit_sha>"}' https://api.github.com/repos/<user>/<repo>/git/refs
    

    Fields:

    • <user>:<password>: Username and password of your GitHub account.

    • refs/heads/<branch-name>: ref of the new branch, must have two slashes and start with "refs". What comes after the last slash is the name of the branch

    • sha: the sha of the commit, example: "efdec9f65bf420b1af91ad1aded915a42c5fa34d"

    • <repo>: repository name.

    It'll send a request using GitHub API to create a new branch named, in this case, 'recover-commits' that points to that commit.

    1. If successful it should return something like this: HTTP/1.1 201 Created Server: GitHub.com ...

    2. From there you can cherry-pick or merge the commits back into your main branch.

    Source.