diff options
Diffstat (limited to 'nixpkgs/lib/strings.nix')
-rw-r--r-- | nixpkgs/lib/strings.nix | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/nixpkgs/lib/strings.nix b/nixpkgs/lib/strings.nix index 4f9509ffe7c0..74e3eaa0722d 100644 --- a/nixpkgs/lib/strings.nix +++ b/nixpkgs/lib/strings.nix @@ -315,6 +315,21 @@ rec { */ escapeNixString = s: escape ["$"] (builtins.toJSON s); + /* Quotes a string if it can't be used as an identifier directly. + + Type: string -> string + + Example: + escapeNixIdentifier "hello" + => "hello" + escapeNixIdentifier "0abc" + => "\"0abc\"" + */ + escapeNixIdentifier = s: + # Regex from https://github.com/NixOS/nix/blob/d048577909e383439c2549e849c5c2f2016c997e/src/libexpr/lexer.l#L91 + if builtins.match "[a-zA-Z_][a-zA-Z0-9_'-]*" s != null + then s else escapeNixString s; + # Obsolete - use replaceStrings instead. replaceChars = builtins.replaceStrings or ( del: new: s: @@ -678,4 +693,36 @@ rec { => "1.0" */ fileContents = file: removeSuffix "\n" (builtins.readFile file); + + + /* Creates a valid derivation name from a potentially invalid one. + + Type: sanitizeDerivationName :: String -> String + + Example: + sanitizeDerivationName "../hello.bar # foo" + => "-hello.bar-foo" + sanitizeDerivationName "" + => "unknown" + sanitizeDerivationName pkgs.hello + => "-nix-store-2g75chlbpxlrqn15zlby2dfh8hr9qwbk-hello-2.10" + */ + sanitizeDerivationName = string: lib.pipe string [ + # Get rid of string context. This is safe under the assumption that the + # resulting string is only used as a derivation name + builtins.unsafeDiscardStringContext + # Strip all leading "." + (x: builtins.elemAt (builtins.match "\\.*(.*)" x) 0) + # Split out all invalid characters + # https://github.com/NixOS/nix/blob/2.3.2/src/libstore/store-api.cc#L85-L112 + # https://github.com/NixOS/nix/blob/2242be83c61788b9c0736a92bb0b5c7bbfc40803/nix-rust/src/store/path.rs#L100-L125 + (builtins.split "[^[:alnum:]+._?=-]+") + # Replace invalid character ranges with a "-" + (concatMapStrings (s: if lib.isList s then "-" else s)) + # Limit to 211 characters (minus 4 chars for ".drv") + (x: substring (lib.max (stringLength x - 207) 0) (-1) x) + # If the result is empty, replace it with "unknown" + (x: if stringLength x == 0 then "unknown" else x) + ]; + } |