Relative imports in NixOs Configuration by using the root directory somehow?

In my NixOs configuration.nix I have an import statement due to my folder structure
as follows:

{
  config,
  pkgs,
...
}:
let
  rootDir = "../../";
in {

  imports = [ 
     ./${rootDir}/modules/mystuff.nix 
  ];

}

I am wondering if I can somehow use $rootDir also in mystuff.nix by of course passing it to the module like

imports = [
  (import ./${rootDir}/modules/mystuff.nix {inherit config pkgs rootDir;})

but for that to work rootDir should be an absolute path. Can I somehow turn ../../modules into an absolute path?
Is therre something in the nixpkgs library?

Or is there even a root dir variable where I evaluated my nix rebuild command like

nixos-rebuild switch --flake ~/myflake#mysystem

I am not entirely sure about this either. But you might have a look at this NixOS Wiki article:

https://nixos.wiki/wiki/Nix_Language:_Tips_%26_Tricks#Coercing_a_relative_path_with_interpolated_variables_to_an_absolute_path_.28for_imports.29

Let’s see if that helps.

1 Like

In your configuration.nix, you can add the following to imports:

{
  config,
  pkgs,
...
}:
let
  rootDir = ./../..;
in {

  imports = [ 
     { _module.args = { inherit rootDir; }; }
     (rootDir + "/modules/mystuff.nix") 
  ];

}

Then in any of your modules, you can just get a rootDir parameter like you would config or pkgs.

1 Like

As your switch command is a flake, you can also use self to reference the flake, and then follow the path in your configuration structure.

So ${self}/modules/my stuff.nix should be an absolute path to the mystuff.nix

Tho it was not really what you asked for, but maybe it also helps.

1 Like

I actually used this solution yes as inputs.self + /modules/mystuff.nix .