lib/strings: add a `toInt` helper (close #11242)

While the function itself is pretty easy, it's not straitforward to find a way to convert string to int with nix.

authored by Christian Zagrodnick and committed by Vladimír Čunát 1cdacc6a 882344e4

+24 -6
+8
lib/strings.nix
··· 223 223 # Check whether a value is a store path. 224 224 isStorePath = x: builtins.substring 0 1 (toString x) == "/" && dirOf (builtins.toPath x) == builtins.storeDir; 225 225 226 + # Convert string to int 227 + # Obviously, it is a bit hacky to use fromJSON that way. 228 + toInt = str: 229 + let may_be_int = builtins.fromJSON str; in 230 + if builtins.isInt may_be_int 231 + then may_be_int 232 + else throw "Could not convert ${str} to int."; 233 + 226 234 }
+16 -6
lib/tests.nix
··· 7 7 expr = id 1; 8 8 expected = 1; 9 9 }; 10 - 10 + 11 11 testConst = { 12 12 expr = const 2 3; 13 13 expected = 2; ··· 19 19 expected = true; 20 20 }; 21 21 */ 22 - 22 + 23 23 testAnd = { 24 24 expr = and true false; 25 25 expected = false; 26 26 }; 27 - 27 + 28 28 testFix = { 29 29 expr = fix (x: {a = if x ? a then "a" else "b";}); 30 30 expected = {a = "a";}; ··· 67 67 }; 68 68 69 69 testOverridableDelayableArgsTest = { 70 - expr = 70 + expr = 71 71 let res1 = defaultOverridableDelayableArgs id {}; 72 72 res2 = defaultOverridableDelayableArgs id { a = 7; }; 73 73 res3 = let x = defaultOverridableDelayableArgs id { a = 7; }; ··· 87 87 in (x2.replace) { a = 10; }; # and override the value by 10 88 88 89 89 # fixed tests (delayed args): (when using them add some comments, please) 90 - resFixed1 = 90 + resFixed1 = 91 91 let x = defaultOverridableDelayableArgs id ( x : { a = 7; c = x.fixed.b; }); 92 92 y = x.merge (x : { name = "name-${builtins.toString x.fixed.c}"; }); 93 93 in (y.merge) { b = 10; }; ··· 109 109 expr = sort builtins.lessThan [ 40 2 30 42 ]; 110 110 expected = [2 30 40 42]; 111 111 }; 112 - 112 + 113 + testToIntShouldConvertStringToInt = { 114 + expr = toInt "27"; 115 + expected = 27; 116 + }; 117 + 118 + testToIntShouldThrowErrorIfItCouldNotConvertToInt = { 119 + expr = builtins.tryEval (toInt "\"foo\""); 120 + expected = { success = false; value = false; }; 121 + }; 122 + 113 123 }