Thursday, 27 December 2018

GIT: Retrieving files from the history

28.1. View file in different revision

The git show command allows to see and retrieve files from branches, commits and tags. It allows seeing the status of these files in the selected branch, commit or tag without checking them out into your working tree.
By default, this command addresses a file from the root of the repository, not the current directory. If you want the current directory then you have to use the ./ specifier. For example to address the pom.xml file the current directory use: ./pom.xml
The following commands demonstrate that. You can also make a copy of the file.
# [reference] can be a branch, tag, HEAD or commit ID
# [file_path] is the file name including path

git show [reference]:[file_path]

# to make a copy to copiedfile.txt

git show [reference]:[file_path] > copiedfile.txt

# assume you have two pom.xml files. One in the root of the Git
# repository and one in the current working directory

# address the pom.xml in the git root folder
git show HEAD:pom.xml

# address the pom in the current directory
git show HEAD:./pom.xml

28.2. Restore a deleted file in a Git repo

You can checkout a file from the commit. To find the commit which deleted the file you can use the git log or the git ref-list command as demonstrated by the following command.
# see history of file
git log -- <file_path>

# checkout file based on predecessors the last commit which affect it
# this was the commit which delete the file
git checkout [commit] ^ -- <file_path>

# alternatively use git rev-list
git rev-list -n 1 HEAD -- <file_path>

# afterwards, the same checkout based on the predecessors
git checkout [commit] ^ -- <file_path>

0 comments:

Post a Comment