add more string processing helpers

This commit is contained in:
Valentin Gagarin 2024-11-13 15:24:41 +01:00 committed by Valentin Gagarin
parent e77b55e8e9
commit 779eb8b192

View file

@ -1,5 +1,19 @@
{ lib }:
rec {
/**
Recursively replace occurrences of `from` with `to` within `string`
Example:
replaceStringRec "--" "-" "hello-----world"
=> "hello-world"
*/
replaceStringsRec = from: to: string:
let
replaced = lib.replaceStrings [ from ] [ to ] string;
in
if replaced == string then string else replaceStringsRec from to replaced;
/**
Create a URL-safe slug from any string
*/
@ -22,14 +36,30 @@ rec {
matched = builtins.match "(-*)([^-].*[^-]|[^-])(-*)" s;
in
with lib; optionalString (!isNull matched) (builtins.elemAt matched 1);
in
trimHyphens (replaceStringsRec "--" "-" replaced);
collapseHyphens = s:
squash = replaceStringsRec "\n\n" "\n";
/**
Trim trailing spaces and squash non-leading spaces
*/
trim = string:
let
result = builtins.replaceStrings [ "--" ] [ "-" ] s;
trimLine = line:
with lib;
let
# separate leading spaces from the rest
parts = split "(^ *)" line;
spaces = head (elemAt parts 1);
rest = elemAt parts 2;
# drop trailing spaces
body = head (split " *$" rest);
in
if result == s then s else collapseHyphens result;
if body == "" then "" else
spaces + replaceStringsRec " " " " body;
in
trimHyphens (collapseHyphens replaced);
join "\n" (map trimLine (splitLines string));
join = lib.concatStringsSep;