Path Hasher - A PHP implementation of Nix’s NAR format

Heya everyone,

I have just released Path Hasher, a PHP library that deterministically serialises and hashes filesystem paths using the NAR (Nix ARchive) format introduced by Eelco Dolstra in his PhD thesis.

What it offers

  • Serialise files, directories and symlinks into the canonical NAR format.
  • Compute hashes in hex, SRI and Nix base32 encodings, matching the output of nix hash path <path>.
  • Extract or reconstruct filesystem trees from NAR archives.

Why I created it

  1. To understand how the NAR format works and how it’s built.
  2. To provide deterministic serialisation of paths/directories in PHP—without needing any external tooling.
  3. To ease adoption of the NAR format in the PHP ecosystem (and specifically with Composer) — e.g., see this Composer pull request comment.
  4. Because it was fun.

Performances

❯ nix hash path /home/pol/Code/drupol/nixpkgs/pkgs/by-name/
sha256-cAPagRB1zSY5EOcuX27fhyjzY4XmkMj3kvX7cQ8xd6I=

❯ php hash.php /home/pol/Code/drupol/nixpkgs/pkgs/by-name/
sha256-cAPagRB1zSY5EOcuX27fhyjzY4XmkMj3kvX7cQ8xd6I=⏎                                                                                                                                                                                                                                                                                                                                                                                                                                                  
 
❯ hyperfine "nix hash path /home/pol/Code/drupol/nixpkgs/pkgs/by-name/" --warmup 2
Benchmark 1: nix hash path /home/pol/Code/drupol/nixpkgs/pkgs/by-name/
  Time (mean ± σ):     354.2 ms ±   7.2 ms    [User: 237.9 ms, System: 114.1 ms]
  Range (min … max):   346.4 ms … 371.6 ms    10 runs
 
❯ hyperfine "php hash.php /home/pol/Code/drupol/nixpkgs/pkgs/by-name/" --warmup 2
Benchmark 1: php hash.php /home/pol/Code/drupol/nixpkgs/pkgs/by-name/
  Time (mean ± σ):     431.1 ms ±   7.9 ms    [User: 269.4 ms, System: 158.8 ms]
  Range (min … max):   423.7 ms … 449.9 ms    10 runs
9 Likes

You might find this PR i am working on of interest: Add documentation for NAR spec in kaitai by fzakaria · Pull Request #14345 · NixOS/nix · GitHub

(and Make `nix nar [cat|ls]` lazy by fzakaria · Pull Request #14273 · NixOS/nix · GitHub for comparing efficiency)

3 Likes