1{ lib }:
2
3rec {
4
5 /**
6 Throw if pred is false, else return pred.
7 Intended to be used to augment asserts with helpful error messages.
8
9 # Inputs
10
11 `pred`
12
13 : Predicate that needs to succeed, otherwise `msg` is thrown
14
15 `msg`
16
17 : Message to throw in case `pred` fails
18
19 # Type
20
21 ```
22 assertMsg :: Bool -> String -> Bool
23 ```
24
25 # Examples
26 :::{.example}
27 ## `lib.asserts.assertMsg` usage example
28
29 ```nix
30 assertMsg false "nope"
31 stderr> error: nope
32 assert assertMsg ("foo" == "bar") "foo is not bar, silly"; ""
33 stderr> error: foo is not bar, silly
34 ```
35
36 :::
37 */
38 # TODO(Profpatsch): add tests that check stderr
39 assertMsg = pred: msg: pred || builtins.throw msg;
40
41 /**
42 Specialized `assertMsg` for checking if `val` is one of the elements
43 of the list `xs`. Useful for checking enums.
44
45 # Inputs
46
47 `name`
48
49 : The name of the variable the user entered `val` into, for inclusion in the error message
50
51 `val`
52
53 : The value of what the user provided, to be compared against the values in `xs`
54
55 `xs`
56
57 : The list of valid values
58
59 # Type
60
61 ```
62 assertOneOf :: String -> ComparableVal -> List ComparableVal -> Bool
63 ```
64
65 # Examples
66 :::{.example}
67 ## `lib.asserts.assertOneOf` usage example
68
69 ```nix
70 let sslLibrary = "libressl";
71 in assertOneOf "sslLibrary" sslLibrary [ "openssl" "bearssl" ]
72 stderr> error: sslLibrary must be one of [
73 stderr> "openssl"
74 stderr> "bearssl"
75 stderr> ], but is: "libressl"
76 ```
77
78 :::
79 */
80 assertOneOf =
81 name: val: xs:
82 assertMsg (lib.elem val xs) "${name} must be one of ${lib.generators.toPretty { } xs}, but is: ${
83 lib.generators.toPretty { } val
84 }";
85
86 /**
87 Specialized `assertMsg` for checking if every one of `vals` is one of the elements
88 of the list `xs`. Useful for checking lists of supported attributes.
89
90 # Inputs
91
92 `name`
93
94 : The name of the variable the user entered `val` into, for inclusion in the error message
95
96 `vals`
97
98 : The list of values of what the user provided, to be compared against the values in `xs`
99
100 `xs`
101
102 : The list of valid values
103
104 # Type
105
106 ```
107 assertEachOneOf :: String -> List ComparableVal -> List ComparableVal -> Bool
108 ```
109
110 # Examples
111 :::{.example}
112 ## `lib.asserts.assertEachOneOf` usage example
113
114 ```nix
115 let sslLibraries = [ "libressl" "bearssl" ];
116 in assertEachOneOf "sslLibraries" sslLibraries [ "openssl" "bearssl" ]
117 stderr> error: each element in sslLibraries must be one of [
118 stderr> "openssl"
119 stderr> "bearssl"
120 stderr> ], but is: [
121 stderr> "libressl"
122 stderr> "bearssl"
123 stderr> ]
124 ```
125
126 :::
127 */
128 assertEachOneOf =
129 name: vals: xs:
130 assertMsg (lib.all (val: lib.elem val xs) vals)
131 "each element in ${name} must be one of ${lib.generators.toPretty { } xs}, but is: ${
132 lib.generators.toPretty { } vals
133 }";
134}