Search code examples
gitgithubgit-commitgit-pushgit-reset

i lost my readme file because i did 'git push --force' in local but I don't know how to get it back. The readme file was created in remote


I lost my readme file because I did

git push -f origin main

in local. But I don't know how to get it back.

I found this solution

git reset before-commit
git push -f origin main

The readme file was created in remote. So before commit doesn't have readmefile
so i can't use this solution.
I want my file back

I don't know if I explained it well because I don't speak English, but thank you in advance.


Solution

  • On your local clone : check

    git reflog origin/main
    

    to see if you haven't got a local copy of the previous commit.


    Through Github : check the Events API

    curl -u <username> https://api.github.com/repos/:owner/:repo/events
    
    # you should find the sha you are looking for in that first command
    
    # you can then try to fetch that specific commit locally:
    git fetch origin <sha-from-step-1>
    
    # or use the API again to create a branch directly on the remote :
    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
    

    (source : https://medium.com/git-tips/githubs-reflog-a9ff21ff765f)


    Once you have that commit locally, there are several ways to get some content out of it.

    If you are interested only in the content of README.md, one way to get the version from that commit is :

    git show <sha of that commit>:README.md > readme-github.md
    
    # you can now open readme-github.md in an editor, and copy/paste as
    # much as you need