lib: modules: refactor 'mapModules'

Introduce the recursive version of this function, then refactor to
reduce repetition.
This commit is contained in:
Bruno BELANYI 2021-09-24 00:54:00 +02:00
parent 2b0b6f2004
commit 9473cff408

View file

@ -3,6 +3,31 @@ let
inherit (builtins) readDir pathExists; inherit (builtins) readDir pathExists;
inherit (lib) hasPrefix hasSuffix nameValuePair removeSuffix; inherit (lib) hasPrefix hasSuffix nameValuePair removeSuffix;
inherit (self.attrs) mapFilterAttrs; inherit (self.attrs) mapFilterAttrs;
implOptionalRecursion = recurse:
let
recurseStep =
if recurse
then (n: path: fn: nameValuePair n (impl path fn))
else (_: _: _: nameValuePair "" null);
impl = dir: fn:
mapFilterAttrs
(n: _: n != "" && !(hasPrefix "_" n))
(n: v:
let
path = "${toString dir}/${n}";
in
if v == "directory"
then
if pathExists "${path}/default.nix"
then nameValuePair n (fn path)
else recurseStep n path fn
else if v == "regular" && n != "default.nix" && hasSuffix ".nix" n
then nameValuePair (removeSuffix ".nix" n) (fn path)
else nameValuePair "" null)
(readDir dir);
in
impl;
in in
{ {
# Find all nix modules in a directory, discard any prefixed with "_", # Find all nix modules in a directory, discard any prefixed with "_",
@ -13,19 +38,13 @@ in
# path # path
# (path -> any) # (path -> any)
# attrs # attrs
mapModules = dir: fn: mapModules = implOptionalRecursion false;
mapFilterAttrs
(n: v: # Recursive version of mapModules.
v != null && #
!(hasPrefix "_" n)) # mapModulesRec ::
(n: v: # path
let path = "${toString dir}/${n}"; in # (path -> any)
if v == "directory" && pathExists "${path}/default.nix" # attrs
then nameValuePair n (fn path) mapModulesRec = implOptionalRecursion true;
else if v == "regular" &&
n != "default.nix" &&
hasSuffix ".nix" n
then nameValuePair (removeSuffix ".nix" n) (fn path)
else nameValuePair "" null)
(readDir dir);
} }