Skip to content

Commit 4eb89bd

Browse files
committed
feat: improve scopedImport with _file attribute and scoped in builtins
also properly override builtins.nixPath in addition to __nixPath.
1 parent 4ebb10a commit 4eb89bd

2 files changed

Lines changed: 37 additions & 9 deletions

File tree

‎default.nix‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,33 @@ let
2323
files = leafs path;
2424
in
2525
{
26-
imports = if scoped == { } then files else map scoped-import files;
26+
imports = if scoped == { } then files else map scoped-import-module files;
2727
};
2828

29-
scoped-import = builtins.scopedImport (
30-
{
31-
inherit builtins;
32-
__nixPath = [ ];
33-
}
34-
// scoped
35-
);
29+
# Like builtins.scopedImport but:
30+
# - propagate builtins (but not other free variables) accross nested invocations
31+
# - add in scope: `__scoped` and `builtins.scoped` for potential reuse in nested invocations
32+
scoped-import =
33+
scoped:
34+
builtins.scopedImport (
35+
{
36+
builtins = builtins // {
37+
nixPath = [ ];
38+
inherit scoped;
39+
};
40+
__nixPath = [ ];
41+
__scoped = scoped;
42+
}
43+
// scoped
44+
);
45+
46+
scoped-import-module = file: {
47+
# Let's not lose track of the original file even if scope-imported:
48+
_file = file;
49+
imports = [
50+
(builtins.scopedImport scoped file)
51+
];
52+
};
3653

3754
leafs =
3855
let

‎docs/src/content/docs/reference/api.mdx‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,10 +169,21 @@ The provided attributes are merged into the scope used by `builtins.scopedImport
169169
Multiple `.addScoped` calls accumulate:
170170

171171
```nix
172-
import-tree (it: it.addScoped { foo = 42 }) (it: it.addScoped { bar = 99 })
172+
import-tree (it: it.addScoped { foo = 42 }) (it: it.addScoped { bar = 99 }) ./modules
173173
# modules can access both foo and bar
174174
```
175175

176+
Scoped variables can be accessed inside scoped-imported modules as `builtins.scoped`:
177+
178+
```nix
179+
# module.nix
180+
{
181+
imports = [ (import-tree.addScoped (builtins.scoped // { bar = foo; }) ./other-modules) ];
182+
# other-modules can now access `bar` directly in addition to `foo` and `mylib`
183+
}
184+
185+
```
186+
176187
---
177188

178189
## Output

0 commit comments

Comments
 (0)