Search code examples
gitgithubgit-push

Recovering file history after a forced push


I just tried to migrate my files for a certain repository on my local machine to another directory and appear to have failed miserably.

Having copy-pasted the source files to a new folder, I went through the following to try and make a commit to the original GitHub repository by doing the following in the new directory:

git init
git add .
git commit -m 'migration'
git remote add origin https://github.com/UN/REP.git
git push origin master

This (as I've grown used to with git by now) threw me an error:

 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/UN/REP.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Clueless as to why this may be the case, I just naively forced the push

git push -f origin master

Now, none of the files have kept their edit history as the repository is showing only one (the forced) commit.

Is there any way to get the edit history back for this repository?

I read a few questions about recovery after/undoing a forced push but 1) i have no idea what they're talking about and 2) I think I may be saved by the fact that I still have the old .git folder in the old folder I was using before I migrated.


Solution

  • Unfortunately, it is reported on SO that you cannot use git reflog on the remote. git can I view the reflog of a remote?

    If you have the old .git folder, I think you should be saved. Try running git reset --hard in a folder containing a copy of your .git folder.

    I just tried this with one of my repos. I made a copy of just the .git folder and copied it to a blank folder. I then opened a shell and navigated to this new folder that contains nothing but the .git folder the typed the command git reset --hard and git immediately put the files for the last branch I was on in the folder.

    Edit: Based on the comments below, I think that @MichaelChirico has misunderstood my answer. Let me try to be more clear.

    Suppose your .git directory is in c:\Michael\project.

    Step 1: Create a new directory: c:\temp\project.

    Step 2: Open a shell.

    Step 3: Change directory to c:\temp\project.

    Step 4: Type ls. You should see that the directory contains .git and nothing else.

    Step 5: Type git reset --hard.

    Step 6: See that you now have files in c:\temp\project again.

    Step 7: If the files aren't the branch you want, use git checkout to change branches.