commit ed7d2f478b5c44b14e72f1b824ea5eb5e3def022
parent 6a4ad6d8f50b60f18d63d3c0452e9c1c98565ce3
Author: figsoda <figsoda@pm.me>
Date: Fri, 23 Jun 2023 23:26:17 -0400
parent 6a4ad6d8f50b60f18d63d3c0452e9c1c98565ce3
Author: figsoda <figsoda@pm.me>
Date: Fri, 23 Jun 2023 23:26:17 -0400
Merge pull request #17 from nix-community/prepend
7 files changed, 41 insertions(+), 0 deletions(-)
diff --git a/docs/src/api/transformers.md b/docs/src/api/transformers.md @@ -46,3 +46,12 @@ Type: `[ String ] -> { ... } -> { ... }` This transformer will lift the contents of `default` into the module. It will fail if `default` is not an attribute set, or has any overlapping attributes with the module. + +## `transformers.prependUnderscore` + +Source: [`src/transformers/prependUnderscore.nix`](https://github.com/nix-community/haumea/blob/main/src/transformers/prependUnderscore.nix) + +Type: `[ String ] -> { ... } -> { ... }` + +This transformer prepnds `_` to attributes that are not valid identifiers, e.g. `42` -> `_42`. +Attributes that are already valid identifiers (e.g. `foo`) are left unchanged.
diff --git a/src/transformers/prependUnderscore.nix b/src/transformers/prependUnderscore.nix @@ -0,0 +1,18 @@ +{ lib }: + +let + inherit (builtins) + substring + elem + ; + inherit (lib) + mapAttrs' + stringToCharacters + nameValuePair + ; + + start = stringToCharacters "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"; +in + +_: mapAttrs' (name: nameValuePair + (if elem (substring 0 1 name) start then name else "_${name}"))
diff --git a/tests/prependUnderscore/__fixture/'bar.nix b/tests/prependUnderscore/__fixture/'bar.nix @@ -0,0 +1 @@ +"'bar"
diff --git a/tests/prependUnderscore/__fixture/0foo/bar.nix b/tests/prependUnderscore/__fixture/0foo/bar.nix @@ -0,0 +1 @@ +"0foo.bar"
diff --git a/tests/prependUnderscore/__fixture/baz.nix b/tests/prependUnderscore/__fixture/baz.nix @@ -0,0 +1 @@ +"baz"
diff --git a/tests/prependUnderscore/expected.nix b/tests/prependUnderscore/expected.nix @@ -0,0 +1,5 @@ +{ + _0foo.bar = "0foo.bar"; + _'bar = "'bar"; + baz = "baz"; +}
diff --git a/tests/prependUnderscore/expr.nix b/tests/prependUnderscore/expr.nix @@ -0,0 +1,6 @@ +{ haumea }: + +haumea.load { + src = ./__fixture; + transformer = haumea.transformers.prependUnderscore; +}