aboutsummaryrefslogtreecommitdiff
path: root/asserts.nix
diff options
context:
space:
mode:
authorRobert Hensing <robert@roberthensing.nl>2023-08-16 15:46:37 +0200
committerRobert Hensing <robert@roberthensing.nl>2023-08-16 15:46:37 +0200
commit63e0b5d081fed582ac6a0a66f402dc525953524b (patch)
tree1bdcd7fc8a6a40b2e805bad759b36e64e911036b /asserts.nix
GC root for fetched nixpkgs/lib content
Diffstat (limited to 'asserts.nix')
-rw-r--r--asserts.nix53
1 files changed, 53 insertions, 0 deletions
diff --git a/asserts.nix b/asserts.nix
new file mode 100644
index 000000000..98e0b490a
--- /dev/null
+++ b/asserts.nix
@@ -0,0 +1,53 @@
+{ lib }:
+
+rec {
+
+ /* Throw if pred is false, else return pred.
+ Intended to be used to augment asserts with helpful error messages.
+
+ Example:
+ assertMsg false "nope"
+ stderr> error: nope
+
+ assert assertMsg ("foo" == "bar") "foo is not bar, silly"; ""
+ stderr> error: foo is not bar, silly
+
+ Type:
+ assertMsg :: Bool -> String -> Bool
+ */
+ # TODO(Profpatsch): add tests that check stderr
+ assertMsg =
+ # Predicate that needs to succeed, otherwise `msg` is thrown
+ pred:
+ # Message to throw in case `pred` fails
+ msg:
+ pred || builtins.throw msg;
+
+ /* Specialized `assertMsg` for checking if `val` is one of the elements
+ of the list `xs`. Useful for checking enums.
+
+ Example:
+ let sslLibrary = "libressl";
+ in assertOneOf "sslLibrary" sslLibrary [ "openssl" "bearssl" ]
+ stderr> error: sslLibrary must be one of [
+ stderr> "openssl"
+ stderr> "bearssl"
+ stderr> ], but is: "libressl"
+
+ Type:
+ assertOneOf :: String -> ComparableVal -> List ComparableVal -> Bool
+ */
+ assertOneOf =
+ # The name of the variable the user entered `val` into, for inclusion in the error message
+ name:
+ # The value of what the user provided, to be compared against the values in `xs`
+ val:
+ # The list of valid values
+ xs:
+ assertMsg
+ (lib.elem val xs)
+ "${name} must be one of ${
+ lib.generators.toPretty {} xs}, but is: ${
+ lib.generators.toPretty {} val}";
+
+}