about summary refs log tree commit diff stats
path: root/modules/by-name-overlay.nix
diff options
context:
space:
mode:
Diffstat (limited to 'modules/by-name-overlay.nix')
-rw-r--r--modules/by-name-overlay.nix48
1 files changed, 48 insertions, 0 deletions
diff --git a/modules/by-name-overlay.nix b/modules/by-name-overlay.nix
new file mode 100644
index 00000000..b96c1d25
--- /dev/null
+++ b/modules/by-name-overlay.nix
@@ -0,0 +1,48 @@
+# Adapted from this: https://github.com/NixOS/nixpkgs/blob/1814b56453c91192f6d5a6276079948f9fe96c18/pkgs/top-level/by-name-overlay.nix
+{baseDirectory}: let
+  # Taken straight out of the `nixpkgs/lib/lists.nix` file.
+  # We can't depended on `pkgs` (and thus on `lib`), because the `pkgs` module argument
+  # is only defined in modules we import.
+  flatten = x:
+    if builtins.isList x
+    then builtins.concatMap flatten x
+    else [x];
+  # Same thing as flatten.
+  warn =
+    # Since Nix 2.23, https://github.com/NixOS/nix/pull/10592
+    builtins.warn
+    or (
+      # Do not eta reduce v, so that we have the same strictness as `builtins.warn`.
+      msg: v:
+      # `builtins.warn` requires a string message, so we enforce that in our implementation, so that callers aren't accidentally incompatible with newer Nix versions.
+        assert builtins.isString msg;
+          builtins.trace "[1;35mevaluation warning:[0m ${msg}" v
+    );
+  # Same thing as flatten.
+  mapAttrsToList = f: attrs:
+    builtins.map (name: f name attrs.${name}) (builtins.attrNames attrs);
+
+  # Module files for a single shard
+  # Type: String -> String -> ListOf Path
+  namesForShard = shard: type:
+    if type != "directory"
+    then warn "Ignored non-directory, whilst importing by-name modules: '${shard}'" []
+    else let
+      mkPath = name: _type: let
+        path = baseDirectory + "/${shard}/${name}/module.nix";
+      in
+        if builtins.pathExists path
+        then path
+        else warn "'${builtins.toString path}' does not exist. Skipped" null;
+    in
+      flatten
+      (builtins.filter (it: it != null)
+        (mapAttrsToList
+          mkPath
+          (builtins.readDir (baseDirectory + "/${shard}"))));
+
+  # A list of all module paths.
+  # These can the be simply injected into `import`
+  moduleFiles = flatten (mapAttrsToList namesForShard (builtins.readDir baseDirectory));
+in
+  moduleFiles