commit a2ee9e11a74cc01cafdfb0a8f87a4abda2bdf009
parent 6a4ad6d8f50b60f18d63d3c0452e9c1c98565ce3
Author: figsoda <figsoda@pm.me>
Date: Thu, 22 Jun 2023 20:02:59 -0400
parent 6a4ad6d8f50b60f18d63d3c0452e9c1c98565ce3
Author: figsoda <figsoda@pm.me>
Date: Thu, 22 Jun 2023 20:02:59 -0400
transformers.prependUnderscore: init
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; +}