From 513f9490b6c1b8cc242c1f4d3676e78bf24a464a Mon Sep 17 00:00:00 2001 From: phaer Date: Fri, 6 Dec 2024 14:09:33 +0100 Subject: [PATCH] Optionally request "publisher" in modules Closes #23 --- docs/folder-structure.md | 6 ++++++ lib/default.nix | 16 +++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/docs/folder-structure.md b/docs/folder-structure.md index 6c72d7f..9397782 100644 --- a/docs/folder-structure.md +++ b/docs/folder-structure.md @@ -184,6 +184,12 @@ For the following folder names, we also map them to the following outputs: These and other unrecognized types also make to `modules..`. +Each module can optionally be wrapped in a function that takes a single named +argument called `publisher`. If used, that function will be called with `publisher` +set to the current, defining flake before exposing that module. +This can be used to reference the defining flake when the module +is imported in another flake and the module argument `flake` points the consumer. + ### `package.nix`, `formatter.nix`, `packages/(.nix|/default.nix)` This `packages/` folder contains all your packages. diff --git a/lib/default.nix b/lib/default.nix index 94aeb13..65f5c04 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -204,6 +204,18 @@ let ) (lib.attrsToList hosts) ); + # Check if the given module is wrapped in a function expecting "publisher" as a named argument, + # and - if so - call that function with the current flake. This enables us to reference + # the publishing flake when re-using exported modules in consuming, downstream flakes. + withPublisher = + module: + let + module' = if builtins.isString module || builtins.isPath module then import module else module; + wantsPublisher = + builtins.isFunction module' && builtins.hasAttr "publisher" (builtins.functionArgs module'); + in + if wantsPublisher then lib.modules.importApply module { publisher = flake; } else module; + modules = let path = src + "/modules"; @@ -212,7 +224,9 @@ let ); in lib.optionalAttrs (builtins.pathExists path) ( - lib.genAttrs moduleDirs (name: importDir (path + "/${name}") entriesPath) + lib.genAttrs moduleDirs ( + name: lib.mapAttrs (_name: module: withPublisher module) (importDir (path + "/${name}") entriesPath) + ) ); in # FIXME: maybe there are two layers to this. The blueprint, and then the mapping to flake outputs.