lib/strings.escapeNixIdentifier: quote keywords

Previously `lib.strings.escapeNixIdentifier "assert"` would return `"assert"`; This is wrong, `assert` is not a valid identifier unless quoted.\

This also fixes `lib.generators.toPretty`: `toPretty {} { "assert" = false; }` would previously return an invalid expression.
This commit is contained in:
Shelvacu
2026-01-02 13:47:32 -08:00
committed by Shelvacu on fw
parent 40e4909fdd
commit 5018a33b62
2 changed files with 36 additions and 2 deletions
+19 -1
View File
@@ -1432,9 +1432,27 @@ rec {
:::
*/
escapeNixIdentifier =
let
# see https://nix.dev/manual/nix/2.26/language/identifiers#keywords
nixKeywords = [
"assert"
"else"
"if"
"in"
"inherit"
"let"
"or"
"rec"
"then"
"with"
];
in
s:
# Regex from https://github.com/NixOS/nix/blob/d048577909e383439c2549e849c5c2f2016c997e/src/libexpr/lexer.l#L91
if match "[a-zA-Z_][a-zA-Z0-9_'-]*" s != null then s else escapeNixString s;
if (match "[a-zA-Z_][a-zA-Z0-9_'-]*" s != null) && (!lib.elem s nixKeywords) then
s
else
escapeNixString s;
/**
Escapes a string `s` such that it is safe to include verbatim in an XML
+17 -1
View File
@@ -865,6 +865,21 @@ runTests {
expected = "'á'";
};
testEscapeNixIdentifierNoQuote = {
expr = strings.escapeNixIdentifier "foo";
expected = ''foo'';
};
testEscapeNixIdentifierNumber = {
expr = strings.escapeNixIdentifier "1foo";
expected = ''"1foo"'';
};
testEscapeNixIdentifierKeyword = {
expr = strings.escapeNixIdentifier "assert";
expected = ''"assert"'';
};
testSplitStringsDerivation = {
expr = lib.dropEnd 1 (strings.splitString "/" dummyDerivation);
expected = strings.splitString "/" builtins.storeDir;
@@ -2785,6 +2800,7 @@ runTests {
];
emptylist = [ ];
attrs = {
"assert" = false;
foo = null;
"foo b/ar" = "baz";
};
@@ -2804,7 +2820,7 @@ runTests {
functionArgs = "<function, args: {arg?, foo}>";
list = "[ 3 4 ${function} [ false ] ]";
emptylist = "[ ]";
attrs = "{ foo = null; \"foo b/ar\" = \"baz\"; }";
attrs = "{ \"assert\" = false; foo = null; \"foo b/ar\" = \"baz\"; }";
emptyattrs = "{ }";
drv = "<derivation ${deriv.name}>";
};