From febff1dccd2c173472fe4a6bed2e620429c5b1ba Mon Sep 17 00:00:00 2001 From: Jacob Abel Date: Sat, 21 May 2022 22:34:11 -0400 Subject: lib/strings: allow toInt to parse zero-padded strings --- lib/strings.nix | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) (limited to 'lib/strings.nix') diff --git a/lib/strings.nix b/lib/strings.nix index be217cb064697..8f3568fc1fc5b 100644 --- a/lib/strings.nix +++ b/lib/strings.nix @@ -792,15 +792,27 @@ rec { => 1337 toInt "-4" => -4 + toInt " 123 " + => 123 + toInt "00024" + => 24 toInt "3.14" => error: floating point JSON numbers are not supported */ # Obviously, it is a bit hacky to use fromJSON this way. toInt = str: - let may_be_int = fromJSON str; in - if isInt may_be_int - then may_be_int - else throw "Could not convert ${str} to int."; + let + strippedInput = match "[[:space:]]*(0*)(.*)" str; + isNonZeroEmpty = match "[[:space:]]*" (lib.last strippedInput) == []; + isZeroNonEmpty = head strippedInput != ""; + mayBeInt = fromJSON (lib.last strippedInput); + in + if isNonZeroEmpty && isZeroNonEmpty + then 0 + else + if isInt mayBeInt + then mayBeInt + else throw "Could not convert ${str} to int."; /* Read a list of paths from `file`, relative to the `rootPath`. Lines beginning with `#` are treated as comments and ignored. -- cgit 1.4.1