How to compute the git hash-object of a directory?

Depending why you wish to do this, the following git command might be useful:

git ls-files -s somedirectory | git hash-object --stdin

This give a single hash which takes into account the filenames and contents.

It works like this. The git ls-files -s .... outputs a list of files and their hashes as text to stdout, then git hash-object generates a hash for the data it receives from stdin.

My use case for this is the following - I want to know whether the (git managed) files in a directory in one branch exactly(*) match those in another branch. The specific use is to compare the "directory hashes" decide whether I need to re-generate derived files which are cached.

By default git ls-files will list files in sub-directories too. If you don't want that, try looking at answers to "how to git ls-file for just one directory level. There are also various other options to git ls-files, including the ability to specify a list of files to include.

(*) excluding hash-collisions


git hash-object -t tree is expecting the file parameter to be a file that describes the entries in the tree, rather than a directory in the filesystem. I understand from the comment here that this command is expecting a file that describes the tree in a binary format, and that it would be easier to use git mktree for you to create the tree object.

git mktree understands input of the format you get from (for example) git ls-tree HEAD. There is a nice example of constructing a tree from scratch using git hash-object and git mktree in the Git Community Book.

Tags:

Git