diff --git a/lib/default.nix b/lib/default.nix index bb99a1be8a8..cabc1549c07 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 a111e1e2597..de135d1c274 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 00eeaa2a77d..7b3a6b4e60b 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 = {