From c93e9fda0fada3e4a48f416d1f38c5a57852e492 Mon Sep 17 00:00:00 2001 From: Pacman99 Date: Sat, 1 May 2021 17:46:54 -0700 Subject: [PATCH] lib: init importers section --- lib/importers.nix | 64 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 lib/importers.nix diff --git a/lib/importers.nix b/lib/importers.nix new file mode 100644 index 00000000..ea07373d --- /dev/null +++ b/lib/importers.nix @@ -0,0 +1,64 @@ +{ lib }: +let + recImport = { dir, _import ? base: import "${dir}/${base}.nix" }: + lib.mapFilterAttrs + (_: v: v != null) + (n: v: + if n != "default.nix" && lib.hasSuffix ".nix" n && v == "regular" + then + let name = lib.removeSuffix ".nix" n; in lib.nameValuePair (name) (_import name) + else + lib.nameValuePair ("") (null)) + (lib.safeReadDir dir); + + mkProfileAttrs = + /** + Synopsis: mkProfileAttrs _path_ + + Recursively collect the subdirs of _path_ containing a default.nix into attrs. + This sets a contract, eliminating ambiguity for _default.nix_ living under the + profile directory. + + Example: + let profiles = mkProfileAttrs ./profiles; in + assert profiles ? core.default; 0 + **/ + dir: + let + imports = + let + files = lib.safeReadDir dir; + + p = n: v: + v == "directory" + && n != "profiles"; + in + lib.filterAttrs p files; + + f = n: _: + lib.optionalAttrs + (lib.pathExists "${dir}/${n}/default.nix") + { default = "${dir}/${n}"; } + // mkProfileAttrs "${dir}/${n}"; + in + lib.mapAttrs f imports; + +in +{ + inherit recImport mkProfileAttrs; + + pathsIn = dir: + let + fullPath = name: "${toString dir}/${name}"; + in + map fullPath (lib.attrNames (lib.safeReadDir dir)); + + importHosts = dir: + recImport { + inherit dir; + _import = base: { + modules = import "${toString dir}/${base}.nix"; + }; + }; +} +