summaryrefslogtreecommitdiff
path: root/lib/strings.nix
diff options
context:
space:
mode:
authorSilvan Mosberger <contact@infinisil.com>2024-07-26 01:13:31 +0200
committerGitHub <noreply@github.com>2024-07-26 01:13:31 +0200
commit91a3ba906496b71d49aa1af46ab57cef5124eb9d (patch)
tree21acd51739088ed7863a03aaa20ea080b4a82603 /lib/strings.nix
parentMerge pull request #329944 from r-ryantm/auto-update/yor (diff)
parentlib.strings: add `trim` and `trimWith` (diff)
downloadnixpkgs-91a3ba906496b71d49aa1af46ab57cef5124eb9d.tar.gz
Merge pull request #315411 from MattSturgeon/trim
lib.strings: add `trim` and `trimWith`
Diffstat (limited to 'lib/strings.nix')
-rw-r--r--lib/strings.nix62
1 files changed, 62 insertions, 0 deletions
diff --git a/lib/strings.nix b/lib/strings.nix
index 67bb669d04e0..18ef707750bb 100644
--- a/lib/strings.nix
+++ b/lib/strings.nix
@@ -157,6 +157,68 @@ rec {
*/
replicate = n: s: concatStrings (lib.lists.replicate n s);
+ /*
+ Remove leading and trailing whitespace from a string.
+
+ Whitespace is defined as any of the following characters:
+ " ", "\t" "\r" "\n"
+
+ Type: trim :: string -> string
+
+ Example:
+ trim " hello, world! "
+ => "hello, world!"
+ */
+ trim = trimWith {
+ start = true;
+ end = true;
+ };
+
+ /*
+ Remove leading and/or trailing whitespace from a string.
+
+ Whitespace is defined as any of the following characters:
+ " ", "\t" "\r" "\n"
+
+ Type: trimWith :: Attrs -> string -> string
+
+ Example:
+ trimWith { start = true; } " hello, world! "}
+ => "hello, world! "
+ trimWith { end = true; } " hello, world! "}
+ => " hello, world!"
+ */
+ trimWith =
+ {
+ # Trim leading whitespace
+ start ? false,
+ # Trim trailing whitespace
+ end ? false,
+ }:
+ s:
+ let
+ # Define our own whitespace character class instead of using
+ # `[:space:]`, which is not well-defined.
+ chars = " \t\r\n";
+
+ # To match up until trailing whitespace, we need to capture a
+ # group that ends with a non-whitespace character.
+ regex =
+ if start && end then
+ "[${chars}]*(.*[^${chars}])[${chars}]*"
+ else if start then
+ "[${chars}]*(.*)"
+ else if end then
+ "(.*[^${chars}])[${chars}]*"
+ else
+ "(.*)";
+
+ # If the string was empty or entirely whitespace,
+ # then the regex may not match and `res` will be `null`.
+ res = match regex s;
+ in
+ optionalString (res != null) (head res);
+
/* Construct a Unix-style, colon-separated search path consisting of
the given `subDir` appended to each of the given paths.