Get name of current file - is it possible?

Hi, I’m currently making modules for a flake and want to make the boilerplate more generic.

Example
cfg = config.modules.$(FILENAME MINUS .nix ENDING);

this is the specific problem I don’t know how to express, is there any way to do so?

Have a look at Haumea, which parses filenames into attribute names: GitHub - nix-community/haumea: Filesystem-based module system for Nix [maintainer=@figsoda]

If you want reflection, e.g. thisfile = getThisFileNameWithoutExtension; note that this would be impure. Rather read the file name (like in Haumea) pass this as an argument to the function in the file.

1 Like

Thanks for the reply!

Looking at Haumea (very new to nix in general) I am confused by my lack of basic understanding. My hope was that there was a builtIn function that handled this, and I think I understand why it’s considered impure. However since the import is hard-coded in the configuration, changing the file name just break the import outright, so I fail to see how this matters (would love an explanation if offered).

The whole idea is to avoid having 2 places that store the same data, specifically a module name. Having the name be reliant on the file name felt like the obvious solution, but somewhere we need to evaluate either where to send what or sending everything and evaluating in each imported file.

Or maybe I think too much like it’s an imperative language :melting_face:

This was the best we could come up with. Sadly we had to use the directory name but in the end I think it worked out better:

let 
 name = baseNameOf ./.
in
{
  imports = [];

  options.namespace.${name} = with lib; {
    enable = mkEnableOption (name + " module");
    # More options to go here
  };

  config = {};
  }

Using this in the repl said we were fine if given the path to the file, but there is no way to dynamically say this file. ./. was the closest we could get to.

After all this, I wonder if it’s worth sending a feature request for nameBaseOf . to evaluate to the current file, since it currently just infinitely loops (unclear why, haven’t looked at the source).