2

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.

haru
  • 23
  • 2
  • If there are other clones of the remote repository, those other clones may have commits that contain the file. If not: well, you added [tag:github] as a tag; GitHub keep *all* commits and you may be able to locate the commit hash ID somehow (using something other than Git) and use that to retrieve the commit *from* GitHub, and that will give you the file back. But Git itself won't be any help unless you already downloaded the necessary commits from GitHub. – torek Jun 23 '22 at 11:58

3 Answers3

3

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
LeGEC
  • 46,477
  • 5
  • 57
  • 104
  • very helpful, getting the commit SHAs associated with hidden push events is also possible with the gitlab events API like `curl -H 'PRIVATE-TOKEN: ' "https://gitlab.example.com/api/v4/events?action=pushed&scope=all"` – Sam Jun 22 '23 at 14:46
0

As per my Knowledge The Answer is NO you can't recover file If you've created readme file on remote and didn't take pull in your local before force push. Still You can refer this answer

Monish Khatri
  • 820
  • 1
  • 7
  • 24
0

Follow these steps:

Step1: Open your local repository in your terminal

Step2: Type one of this command depending on your branch name

git reflog origin/main 

or

git reflog origin/master

Step3: You will be seeing various numbers,these are the sha of the commit try each of them in place of sha in below command you will get your readme.md file data for sure

git show <sha>:README.md > readme-github.md

NOTE:- This method works fine for me

JKvishu
  • 1
  • 2