Path Hasher is a PHP library for deterministically serializing and hashing filesystem objects (files, directories, and symlinks) using the NAR (Nix ARchive) format designed by Eelco Dolstra for the Nix ecosystem.
This library enables you to:
- Serialize any filesystem path into the NAR format, ensuring consistent and reproducible results across platforms.
- Compute cryptographic hashes of paths in multiple encodings (hex, SRI, Nix
base32), matching the output of the
nix hash path <path>command. - Extract or reconstruct filesystem trees from NAR archives.
See chapter 5 of Eelco Dolstra’s PhD thesis for technical details about the NAR format.
composer require loophp/path-hasher
<?php
use Loophp\PathHasher\NAR;
$path = '/path/to/your/file_or_directory';
$hash = (new NAR())->hash($path);
echo $hash; // Outputs the SRI hash (e.g., sha256-<base64>)The equivalent CLI command is:
nix hash path /path/to/your/file_or_directoryThe two outputs will match.
To generate a NAR archive from a given path:
<?php
use Loophp\PathHasher\NAR;
$nar = new NAR();
$handle = fopen('vendor.nar', 'w');
foreach ($nar->stream('./vendor') as $chunk) {
fwrite($handle, $chunk);
}
fclose($handle);Methods available are:
hash: Compute the SRI hash of a given path.extract: Extract a NAR archive to a specified directory.stream: Get a stream generator of the NAR archive.computeHashes: Compute hashes of the NAR archive with different algorithms.
Every time changes are introduced into the library, Github runs the tests.
The library has tests written with PHPUnit. Feel free to check them out in
the tests directory.
Before each commit, some inspections are executed with GrumPHP; run
composer grumphp to check manually.
Feel free to contribute by sending pull requests. We are a usually very responsive team and we will help you going through your pull request from the beginning to the end.
For some reasons, if you can't contribute to the code and willing to help, sponsoring is a good, sound and safe way to show us some gratitude for the hours we invested in this package.
Sponsor me on Github and/or any of the contributors.