From 9473cff40820af0af213845ed102f3a941e46096 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Fri, 24 Sep 2021 00:54:00 +0200 Subject: [PATCH] lib: modules: refactor 'mapModules' Introduce the recursive version of this function, then refactor to reduce repetition. --- lib/modules.nix | 49 ++++++++++++++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/lib/modules.nix b/lib/modules.nix index 455015b..5b8c4c3 100644 --- a/lib/modules.nix +++ b/lib/modules.nix @@ -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; }