Skip to content

Commit f9eb3d1

Browse files
committed
lib/strings: Introduce escapeNixIdentifier
1 parent f9e94b9 commit f9eb3d1

1 file changed

Lines changed: 15 additions & 0 deletions

File tree

lib/strings.nix

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,21 @@ rec {
315315
*/
316316
escapeNixString = s: escape ["$"] (builtins.toJSON s);
317317

318+
/* Quotes a string if it can't be used as an identifier directly.
319+
320+
Type: string -> string
321+
322+
Example:
323+
escapeNixIdentifier "hello"
324+
=> "hello"
325+
escapeNixIdentifier "0abc"
326+
=> "\"0abc\""
327+
*/
328+
escapeNixIdentifier = s:
329+
# Regex from https://github.com/NixOS/nix/blob/d048577909e383439c2549e849c5c2f2016c997e/src/libexpr/lexer.l#L91
330+
if builtins.match "[a-zA-Z_][a-zA-Z0-9_'-]*" s != null
331+
then s else escapeNixString s;
332+
318333
# Obsolete - use replaceStrings instead.
319334
replaceChars = builtins.replaceStrings or (
320335
del: new: s:

0 commit comments

Comments
 (0)