How is the nix hash for a directory generated?

I’d like to implement the logic to generate the nix hash of a directory.

I want to get the hash that nix hash path /path/to/dir gives you, but without relaying on nix (I want to re-implement that logic in a different programming language)

It looks to me that the C++ implementation is here:

But is that algorithm explained/documented somewhere?

1 Like

I remember having seen it explained somewhere, though I am not sure if that was in an official documentation.

The gist of what I read was:

  1. strip all file attributes and permissions and ownerships that can’t exist in the store
  2. store the folder in a NAR (nix archive)
  3. Get the hash of that
1 Like

Then, the next question is how to generate a NAR. I found this gist:

1 Like

I’m not sure if the details have changed, but nobbz might be thinking of Eelco’s thesis–I think there’s a section in there on the hashing at least:


I implemented the NAR serialization algorithm from (Figure 5.2, page 101) in clojure:

The hash from the NAR is the hash for a directory :slight_smile:

Thanks to you both @NobbZ @abathur