diff options
author | Robert Helgesson <robert@rycee.net> | 2021-10-03 11:28:03 +0200 |
---|---|---|
committer | Robert Helgesson <robert@rycee.net> | 2021-10-03 11:28:03 +0200 |
commit | e75f346aa309515fa220f6d2124a27f72e245b69 (patch) | |
tree | 9980881c64dd5b4f9b4076abde8a62414a7d7f30 /lib | |
parent | a7eb89bdba881d71c49b94ea3e12af9b8b10768d (diff) | |
download | nixlib-e75f346aa309515fa220f6d2124a27f72e245b69.tar nixlib-e75f346aa309515fa220f6d2124a27f72e245b69.tar.gz nixlib-e75f346aa309515fa220f6d2124a27f72e245b69.tar.bz2 nixlib-e75f346aa309515fa220f6d2124a27f72e245b69.tar.lz nixlib-e75f346aa309515fa220f6d2124a27f72e245b69.tar.xz nixlib-e75f346aa309515fa220f6d2124a27f72e245b69.tar.zst nixlib-e75f346aa309515fa220f6d2124a27f72e245b69.zip |
lib: add function escapeXML
Given a string, this function returns a string that can be inserted verbatim in an XML document.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/default.nix | 2 | ||||
-rw-r--r-- | lib/strings.nix | 13 | ||||
-rw-r--r-- | lib/tests/misc.nix | 5 |
3 files changed, 19 insertions, 1 deletions
diff --git a/lib/default.nix b/lib/default.nix index bb99a1be8a8c..cabc1549c07b 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -91,7 +91,7 @@ let concatImapStringsSep makeSearchPath makeSearchPathOutput makeLibraryPath makeBinPath optionalString hasInfix hasPrefix hasSuffix stringToCharacters stringAsChars escape - escapeShellArg escapeShellArgs escapeRegex replaceChars lowerChars + escapeShellArg escapeShellArgs escapeRegex escapeXML replaceChars lowerChars upperChars toLower toUpper addContextFrom splitString removePrefix removeSuffix versionOlder versionAtLeast getName getVersion diff --git a/lib/strings.nix b/lib/strings.nix index a111e1e2597b..de135d1c2746 100644 --- a/lib/strings.nix +++ b/lib/strings.nix @@ -362,6 +362,19 @@ rec { if match "[a-zA-Z_][a-zA-Z0-9_'-]*" s != null then s else escapeNixString s; + /* Escapes a string such that it is safe to include verbatim in an XML + document. + + Type: string -> string + + Example: + escapeXML ''"test" 'test' < & >'' + => "\\[\\^a-z]\\*" + */ + escapeXML = builtins.replaceStrings + ["\"" "'" "<" ">" "&"] + [""" "'" "<" ">" "&"]; + # Obsolete - use replaceStrings instead. replaceChars = builtins.replaceStrings or ( del: new: s: diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index 00eeaa2a77d7..7b3a6b4e60b8 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -246,6 +246,11 @@ runTests { }; }; + testEscapeXML = { + expr = escapeXML ''"test" 'test' < & >''; + expected = ""test" 'test' < & >"; + }; + # LISTS testFilter = { |