From c38fc8b48bce642534175f100f5b98a2ec63fcc4 Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 2 Sep 2026 14:42:06 +0200 Subject: lib: add readPath --- lib/pure.nix | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'lib') 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})"; + +} -- cgit v1.3.1