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 bad9b8a06b
commit 8467fda721

View file

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