I want to share a cool function. get_import_dir will search hierarchically your directory for .nix modules. This way, you can freely manage your nix configuration in different module files and folders without even having to declare these modules in your main configuration file. You can edit file_to_not_import to add file names to ignore by the function. ./. means the current directory.
Here is the beginning of my configuration file:
{
pkgs,
lib,
...
}:
let
file_to_not_import = [
"flake.nix"
"configuration.nix"
"userdata.nix"
];
in
let
userdata = import ./userdata.nix;
get_import_dir =
dir:
lib.flatten (
lib.pipe dir [
builtins.readDir
(lib.filterAttrs (name: type: type == "directory" || lib.hasSuffix ".nix" name))
(lib.filterAttrs (name: _: !(lib.elem name file_to_not_import)))
(lib.mapAttrsToList (
name: type: if type == "directory" then get_import_dir (dir + ("/" + name)) else dir + ("/" + name)
))
]
);
in
{
imports = get_import_dir ./.;
Nice! You might also (although it’s more complicated so that comes with its own tradeoffs) be interested in haumea if you are interested in autoloading
I also created a separate top-level dir modules, so that all files can be imported and I don’t have to write these kinds of exclusion criteria like filtering out flake.nix etc. The code above went into modules/default.nix, and all modules can be imported via adding modules/ to imports.
Of course you can modify it to adapt to your usecase.