llakala / nixos

My NixOS config
3 stars 1 forks source link

Import directories automatically without default.nix #24

Closed llakala closed 2 months ago

llakala commented 2 months ago

We've already created an importAll function to import everything in a directory:

importAll =
  dir:
    lib.mapAttrsToList
    (
      n: _: dir + "/${n}"
    )
    (builtins.readDir dir);

This function was a really great reference: https://github.com/Julow/env/blob/e4674d5870c5c15861f9410f8cd11a255f35b117/common.nix#L7 Next, we need to create a wrapper function so we can pass in a list of paths, and importAll on each of those paths. Here's a beta version of the wrapper function that might work, but more investigation is needed:

lib.concatLists (map importAll dirs);
llakala commented 2 months ago

The scope of this one is a bit past us since it's using recursion which we don't need, but still something to be aware of https://github.com/evanjs/nixos_cfg/blob/master/config/new-modules/default.nix

llakala commented 2 months ago

Update, importing a single folder now properly excludes anything that isn't a nix file:

importNixFiles = dir:
  lib.mapAttrsToList
  (
     file: _: dir + "/${file}"
  )
  (lib.filterAttrs
    (
      file: _: lib.hasSuffix ".nix" file
    )
    (builtins.readDir dir)
  );

We also have a good version of importing lots of different folders at once:

  importFolders = dirs:
  lib.concatLists
  (map importNixFiles dirs);

However, there are somewhat large issues. Currently these are:

llakala commented 2 months ago

Update, empty lists now work properly using an if statement. Update, empty lists now work properly using an if statement. The function could hypothetically be improved in the future, but I'm happy with where it's at now. HerThe function could hypothetically be improved in the future, but I'm happy with where it's at now. Here it is for posterity:

importNixFiles = dir:
  if builtins.pathExists dir then # If folder has contents
    lib.mapAttrsToList
    (file: _: dir + "/${file}")
    (lib.filterAttrs
      (file: _: lib.hasSuffix ".nix" file) # Only import .nix files
      (builtins.readDir dir)
    )
  else # If directory is empty, return empty list
    [];

For now, this is good enough for our needs. Future scope could include: