Jay
Jay

Reputation: 10460

how can one restore a file that disappeared after git checkout -b

I did the following:

  1. git clone [fork]
  2. worked for a few days, creating new files 1 & 2
  3. git add newfile1
  4. git add newfile2
  5. git checkout -b new_branch
  6. git checkout master

At this point, I expected newfile1 and newfile2 to be waiting for me, but they are not. Everything has reverted back to the original master, as what is currently on the github server.

Is my work waiting for me somewhere? Or has it become a recycled bunch of bits?

Upvotes: 0

Views: 122

Answers (1)

Boris Brodski
Boris Brodski

Reputation: 8695

After repeating your steps my git status shows me

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   newfile1
#       new file:   newfile2
#

This mean, that you did something else to your repository, that you didn't considered important nor potentially harmful.

And now to your actual question: Yes, you might be able to do it.

  • First do a complete backup of your .git directory
  • Create a file all-objects.sh with this script (source: https://gist.github.com/ctindall/4588884)

    #!/bin/sh
    set -e
    
    cd "$(git rev-parse --show-cdup)"
    
    # Find all the objects that are in packs:
    
    if [ "$(ls -A .git/objects/pack)" ]
    then
        for p in .git/objects/pack/pack-*.idx
            do
                    git show-index < $p | cut -f 2 -d ' '
            done
    fi
    
    # And now find all loose objects:
    
    find .git/objects/ | egrep '[0-9a-f]{38}$' | \
      sed -r 's,^.*([0-9a-f][0-9a-f])/([0-9a-f]{38}),\1\2,'
    
  • If you on Linux/Mac: make it executable: chmod a+x all-objects.sh
  • Remember some small part of the missing data (string, method name, ...)
  • Find this part changing grep parameter in the following script

    for rev in $(./s.sh) ; do
      C=$(git show $rev | grep <METHOD_NAME_OR_SOMETHING_FROM_MISSING_FILE> )
      if [[ "$C" != "" ]] ; then
        echo $rev
        echo $C
      fi
    done
    

Upvotes: 3

Related Questions