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 /* Specialized `assertMsg` for checking if every one of `vals` is one of the elements
54 of the list `xs`. Useful for checking lists of supported attributes.
55
56 Example:
57 let sslLibraries = [ "libressl" "bearssl" ];
58 in assertEachOneOf "sslLibraries" sslLibraries [ "openssl" "bearssl" ]
59 stderr> error: each element in sslLibraries must be one of [
60 stderr> "openssl"
61 stderr> "bearssl"
62 stderr> ], but is: [
63 stderr> "libressl"
64 stderr> "bearssl"
65 stderr> ]
66
67 Type:
68 assertEachOneOf :: String -> List ComparableVal -> List ComparableVal -> Bool
69 */
70 assertEachOneOf =
71 # The name of the variable the user entered `val` into, for inclusion in the error message
72 name:
73 # The list of values of what the user provided, to be compared against the values in `xs`
74 vals:
75 # The list of valid values
76 xs:
77 assertMsg
78 (lib.all (val: lib.elem val xs) vals)
79 "each element in ${name} must be one of ${
80 lib.generators.toPretty {} xs}, but is: ${
81 lib.generators.toPretty {} vals}";
82}