Git: check if file exists in some version

In my application, I use git to version control some external files

I use commands like git show HEAD~1:some_file to get a specific version (based on the git tag, commit hash, or relation to HEAD) of the file. When the file does not exist, the message "fatal" is displayed (I think the pipe is stderr). eg.

fatal: Path 'some_file' does not exist in 'HEAD ~ 1'

Is there a clean command to check for a file in a specific version?

+4
source share
3 answers

The best I have found so far:

 git ls-tree -r HEAD~1 --name-only 

Lists file names in a specific version. I need to analyze the output and filter a specific file. Therefore, it is slightly smaller than I hoped, but a piece of cake.

+3
source

How do you use this? In a script? You can always check the exit code. And git cat-file might be better suited:

 git cat-file -e HEAD~1:some_file 

With the -e option, it will exit with a non-zero error code if the object does not exist, and with 0 when it does. However, it will also print fatal: Not a valid object name , but can be easily suppressed.

+10
source

Since all you need is the exit code from the command, you can redirect stdout and stderr to / dev / null:

 git show HEAD~1:some_file > /dev/null 2>&1 

Exit code 0 means the file exists.

You can use this whole line in your Ruby system call:

 exit_code = system("git show HEAD~1:some_file > /dev/null 2>&1") 

For those who do this in Bash, you can get the exit code as follows:

 git show HEAD~1:some_file > /dev/null 2>&1 if [ $? -ne 0 ]; then # the file does not exist fi 
+3
source

Source: https://habr.com/ru/post/1499098/


All Articles