diff options
author | Christian Zagrodnick <cz@flyingcircus.io> | 2015-11-24 10:00:44 +0100 |
---|---|---|
committer | Vladimír Čunát <vcunat@gmail.com> | 2015-11-25 08:50:02 +0100 |
commit | 1cdacc6aa2f604fbdec60919dcd72cd7cde4551f (patch) | |
tree | b83e5ad6ffd13ece5e699b3c39a203b0c390c5aa /lib | |
parent | 882344e480cc37f15a9ecffebfc8f6c931c59282 (diff) |
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.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/strings.nix | 8 | ||||
-rw-r--r-- | lib/tests.nix | 22 |
2 files changed, 24 insertions, 6 deletions
diff --git a/lib/strings.nix b/lib/strings.nix index e72bdc6d968c2..bf6cbd2cbfa83 100644 --- a/lib/strings.nix +++ b/lib/strings.nix @@ -223,4 +223,12 @@ rec { # Check whether a value is a store path. isStorePath = x: builtins.substring 0 1 (toString x) == "/" && dirOf (builtins.toPath x) == builtins.storeDir; + # Convert string to int + # Obviously, it is a bit hacky to use fromJSON that way. + toInt = str: + let may_be_int = builtins.fromJSON str; in + if builtins.isInt may_be_int + then may_be_int + else throw "Could not convert ${str} to int."; + } diff --git a/lib/tests.nix b/lib/tests.nix index 298bdffc37906..1fb2cbf5b5361 100644 --- a/lib/tests.nix +++ b/lib/tests.nix @@ -7,7 +7,7 @@ runTests { expr = id 1; expected = 1; }; - + testConst = { expr = const 2 3; expected = 2; @@ -19,12 +19,12 @@ runTests { expected = true; }; */ - + testAnd = { expr = and true false; expected = false; }; - + testFix = { expr = fix (x: {a = if x ? a then "a" else "b";}); expected = {a = "a";}; @@ -67,7 +67,7 @@ runTests { }; testOverridableDelayableArgsTest = { - expr = + expr = let res1 = defaultOverridableDelayableArgs id {}; res2 = defaultOverridableDelayableArgs id { a = 7; }; res3 = let x = defaultOverridableDelayableArgs id { a = 7; }; @@ -87,7 +87,7 @@ runTests { in (x2.replace) { a = 10; }; # and override the value by 10 # fixed tests (delayed args): (when using them add some comments, please) - resFixed1 = + resFixed1 = let x = defaultOverridableDelayableArgs id ( x : { a = 7; c = x.fixed.b; }); y = x.merge (x : { name = "name-${builtins.toString x.fixed.c}"; }); in (y.merge) { b = 10; }; @@ -109,5 +109,15 @@ runTests { expr = sort builtins.lessThan [ 40 2 30 42 ]; expected = [2 30 40 42]; }; - + + testToIntShouldConvertStringToInt = { + expr = toInt "27"; + expected = 27; + }; + + testToIntShouldThrowErrorIfItCouldNotConvertToInt = { + expr = builtins.tryEval (toInt "\"foo\""); + expected = { success = false; value = false; }; + }; + } |