# Modified copy of github:NixOS/nixpkgs pkgs/top-level/by-name-overlay.nix
# as of commit c0d0be00d4ecc4b51d2d6948e37466194c1e6c51

# This file turns the pkgs/by-name directory into an overlay that adds all the defined packages.
# No validity checks are done here.

# Type: Path -> Overlay
baseDirectory:
let
  lib = (import ../../outputs.nix {}).lib;

  inherit (builtins)
    readDir
    ;

  inherit (lib.attrsets)
    mapAttrs
    mapAttrsToList
    mergeAttrsList
    ;

  # Package files for a single shard
  # Type: String -> String -> String -> AttrsOf Path
  namesForShard = nixFilename: shard: type:
    if type != "directory" then
      # Ignore all non-directories.
      { }
    else
      mapAttrs
        (name: _: baseDirectory + "/${shard}/${name}/${nixFilename}")
        (readDir (baseDirectory + "/${shard}"));

  # The attribute set mapping names to the package files defining them
  # Type: String -> AttrsOf Path
  packageFiles = nixFilename: lib.pipe baseDirectory [
    readDir
    (mapAttrsToList (namesForShard nixFilename))
    mergeAttrsList
    # Filter out paths that don't have a ${nixFilename} file
    (lib.filterAttrs (_: lib.pathExists))
  ];
in
self: super:
mapAttrs (name: file:
  self.callPackage file { inherit self super; package = super.${name}; }
) (packageFiles "override.nix")
// mapAttrs (name: file:
  self.callPackage file { }
) (packageFiles "package.nix")