1{ lib }:
2
3rec {
4
5 /* Throw if pred is false, else return pred.
6 Intended to be used to augment asserts with helpful error messages.
7
8 Example:
9 assertMsg false "nope"
10 stderr> error: nope
11
12 assert assertMsg ("foo" == "bar") "foo is not bar, silly"; ""
13 stderr> error: foo is not bar, silly
14
15 Type:
16 assertMsg :: Bool -> String -> Bool
17 */
18 # TODO(Profpatsch): add tests that check stderr
19 assertMsg =
20 # Predicate that needs to succeed, otherwise `msg` is thrown
21 pred:
22 # Message to throw in case `pred` fails
23 msg:
24 pred || builtins.throw msg;
25
26 /* Specialized `assertMsg` for checking if `val` is one of the elements
27 of the list `xs`. Useful for checking enums.
28
29 Example:
30 let sslLibrary = "libressl";
31 in assertOneOf "sslLibrary" sslLibrary [ "openssl" "bearssl" ]
32 stderr> error: sslLibrary must be one of [
33 stderr> "openssl"
34 stderr> "bearssl"
35 stderr> ], but is: "libressl"
36
37 Type:
38 assertOneOf :: String -> ComparableVal -> List ComparableVal -> Bool
39 */
40 assertOneOf =
41 # The name of the variable the user entered `val` into, for inclusion in the error message
42 name:
43 # The value of what the user provided, to be compared against the values in `xs`
44 val:
45 # The list of valid values
46 xs:
47 assertMsg
48 (lib.elem val xs)
49 "${name} must be one of ${
50 lib.generators.toPretty {} xs}, but is: ${
51 lib.generators.toPretty {} val}";
52
53}