about summary refs log tree commit diff stats
path: root/modules/by-name-overlay.nix
blob: b96c1d255f2b7677de936eabefde0463db9cacb2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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