diff options
| author | tv <tv@krebsco.de> | 2026-09-02 14:42:06 +0200 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-09-02 14:42:06 +0200 |
| commit | c38fc8b48bce642534175f100f5b98a2ec63fcc4 (patch) | |
| tree | 0a378cb58dcf05e11b3ac5a96412859b3d1913b1 | |
| parent | b8cd5cfc79b964351271470ca99a9a2da430aaf2 (diff) | |
lib: add readPath
| -rw-r--r-- | lib/pure.nix | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/lib/pure.nix b/lib/pure.nix index ab4be9a..50b9676 100644 --- a/lib/pure.nix +++ b/lib/pure.nix @@ -239,4 +239,45 @@ in stockholm.lib // { lib = stockholm.lib; } +// +rec { + # Reads a filesystem path into a Nix datum + # - regular files become strings containing their contents; + # - directories become attrsets recursively containing their entries; + # - symlinks to directories or regular files are dereferenced and read as their targets. + readPath = + let + readHandlers.regular = readRegular; + readHandlers.directory = readDirectory; + readHandlers.symlink = readSymlink; + + readRegular = path: + builtins.readFile path; + + readDirectory = path: + builtins.mapAttrs + (name: _type: readPath (path + "/${name}")) + (builtins.readDir path); + + readSymlink = path: + if canBeTraversedAsDirectory path then + readDirectory path + else + readRegular path; + + # The trailing "/." causes symlinks to be dereferenced. + canBeTraversedAsDirectory = path: + builtins.pathExists "${toString path}/."; + + in + path: + let + type = builtins.readFileType path; + in + if builtins.hasAttr type readHandlers then + readHandlers.${type} path + else + throw "Unsupported file type: ${toString path} (type=${type})"; + +} |
