flake/lib.nixosSystem: add `_file`-keys for error-location

When inlining a module with a problematic declaration, you usually get
get a not-so helpful error like this:

    $ cat flake.nix
    {
      description = "A very basic flake";
      inputs.nixpkgs.url = path:../.;
      outputs = { self, nixpkgs }: {
        nixosConfigurations.foo = nixpkgs.lib.nixosSystem {
          system = "x86_64-linux";
          modules = [
            ({ lib, ... }: { services.wrong = 2; })
            { services.nginx.enable = true; }
          ];
        };
      };
    }
    $ nixos-rebuild build --flake .#foo -L
    error: The option `services.wrong' does not exist. Definition values:
           - In `<unknown-file>': 2

While it's certainly possible to guess where this comes from, this is
IMHO fairly confusing for beginners (and kinda reminds me of the
infamous "infinite recursion at undefined position"-error).

The module-system determines the position of a declaration using the
`_file`-key: this is either `toString path` if `path` is e.g. a value
from `imports = [ ./foo.nix ]` or the file used as `NIXOS_CONFIG` in
`<nixpkgs/nixos>`.

However such a mechanism doesn't exist (yet) for inlined flake modules,
so I tried to implement this in a fairly basic way:

* For non-path declarations, the position of `modules` inside the
  `flake.nix` which declares these modules is determined by doing
  `unsafeGetAttrPos` on the `modules`-argument of `lib.nixosSystem`.

  So the `flake.nix` from above would now raise the following
  error-message:

        $ nixos-rebuild build --flake .#foo -L
        error: The option `services.wrong' does not exist. Definition values:
               - In `/nix/store/4vi3nhqjyma73ygs4f93q38qjkhkaxw8-source/flake.nix': 2

Co-authored-by: Cole Helbling <cole.e.helbling@outlook.com>
Co-authored-by: Silvan Mosberger <github@infinisil.com>
Co-authored-by: Robert Hensing <robert@roberthensing.nl>
This commit is contained in:
Maximilian Bosch 2021-07-11 01:33:17 +02:00
parent aa1561e780
commit e14c245934
No known key found for this signature in database
GPG Key ID: 091DBF4D1FC46B8E
1 changed files with 13 additions and 1 deletions

View File

@ -47,8 +47,20 @@
})
];
})).config;
moduleDeclarationFile =
(builtins.unsafeGetAttrPos "modules" args).file;
# Add the invoking file as error message location for modules
# that don't have their own locations; presumably inline modules.
addModuleDeclarationFile =
m: {
_file = moduleDeclarationFile;
imports = [ m ];
};
in
modules ++ [
map addModuleDeclarationFile modules ++ [
{
system.nixos.versionSuffix =
".${final.substring 0 8 (self.lastModifiedDate or self.lastModified or "19700101")}.${self.shortRev or "dirty"}";