query
On this page

escapeNixIdentifier

lib.strings.escapeNixIdentifier

Docs pulled from | This Revision | 30 minutes ago


Quotes a string s if it can't be used as an identifier directly.

Inputs

s
1. Function argument

Type

escapeNixIdentifier :: String -> String

Examples

lib.strings.escapeNixIdentifier usage example

escapeNixIdentifier "hello"
=> "hello"
escapeNixIdentifier "0abc"
=> "\"0abc\""

Noogle detected

Implementation

The following is the current implementation of this function.

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) && (!lib.elem s nixKeywords) then
      s
    else
      escapeNixString s;