summary refs log tree commit diff
path: root/lib/asserts.nix
diff options
context:
space:
mode:
authorProfpatsch <mail@profpatsch.de>2018-08-08 19:26:52 +0200
committerProfpatsch <mail@profpatsch.de>2018-09-06 18:14:27 +0200
commitefdf618330a22f837f0e5e446028e918a5b4dd8a (patch)
tree6b9ad4353a2e470a3bccbbdca89247047263062b /lib/asserts.nix
parent3e45b61a9920466a8ea06b8ad9350d56ade435bc (diff)
downloadnixpkgs-efdf618330a22f837f0e5e446028e918a5b4dd8a.tar
nixpkgs-efdf618330a22f837f0e5e446028e918a5b4dd8a.tar.gz
nixpkgs-efdf618330a22f837f0e5e446028e918a5b4dd8a.tar.bz2
nixpkgs-efdf618330a22f837f0e5e446028e918a5b4dd8a.tar.lz
nixpkgs-efdf618330a22f837f0e5e446028e918a5b4dd8a.tar.xz
nixpkgs-efdf618330a22f837f0e5e446028e918a5b4dd8a.tar.zst
nixpkgs-efdf618330a22f837f0e5e446028e918a5b4dd8a.zip
lib: move assertMsg and assertOneOf to their own library file
Since the `assertOneOf` uses `lib.generators`, they are not really trivial
anymore and should go into their own library file.
Diffstat (limited to 'lib/asserts.nix')
-rw-r--r--lib/asserts.nix44
1 files changed, 44 insertions, 0 deletions
diff --git a/lib/asserts.nix b/lib/asserts.nix
new file mode 100644
index 00000000000..8a5f1fb3feb
--- /dev/null
+++ b/lib/asserts.nix
@@ -0,0 +1,44 @@
+{ lib }:
+
+rec {
+
+  /* Print a trace message if pred is false.
+     Intended to be used to augment asserts with helpful error messages.
+
+     Example:
+       assertMsg false "nope"
+       => false
+       stderr> trace: nope
+
+       assert (assertMsg ("foo" == "bar") "foo is not bar, silly"); ""
+       stderr> trace: foo is not bar, silly
+       stderr> assert failed at …
+
+     Type:
+       assertMsg :: Bool -> String -> Bool
+  */
+  # TODO(Profpatsch): add tests that check stderr
+  assertMsg = pred: msg:
+    if pred
+    then true
+    else builtins.trace msg false;
+
+  /* Specialized `assertMsg` for checking if val is one of the elements
+     of a list. Useful for checking enums.
+
+     Example:
+       let sslLibrary = "libressl"
+       in assertOneOf "sslLibrary" sslLibrary [ "openssl" "bearssl" ]
+       => false
+       stderr> trace: sslLibrary must be one of "openssl", "bearssl", but is: "libressl"
+
+     Type:
+       assertOneOf :: String -> ComparableVal -> List ComparableVal -> Bool
+  */
+  assertOneOf = name: val: xs: assertMsg
+    (lib.elem val xs)
+    "${name} must be one of ${
+      lib.generators.toPretty {} xs}, but is: ${
+        lib.generators.toPretty {} val}";
+
+}