git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #13546 from zimbatm/document-stdlib

Document stdlib

commit721462634fbc00e1fbfd5790eeab92fbc171c2b8 authorDomen Kožar <domen@dev.si> dateThu 10 Mar 2016, 12:31 (11 years ago) parentb1274ee7883ca7
3 files changed+602−147
lib/attrsets.nix+110−29 lib/lists.nix+218−56 lib/strings.nix+274−62
lib/attrsets.nix+110−29
@@ -12,9 +12,15 @@ rec {
1212 inherit (builtins) attrNames listToAttrs hasAttr isAttrs getAttr;
1313
1414
15− /* Return an attribute from nested attribute sets. For instance
16− ["x" "y"] applied to some set e returns e.x.y, if it exists. The
17− default value is returned otherwise. */
15+ /* Return an attribute from nested attribute sets.
16+
17+ Example:
18+ x = { a = { b = 3; }; }
19+ attrByPath ["a" "b"] 6 x
20+ => 3
21+ attrByPath ["z" "z"] 6 x
22+ => 6
23+ */
1824 attrByPath = attrPath: default: e:
1925 let attr = head attrPath;
2026 in
@@ -24,8 +30,15 @@ rec {
2430 else default;
2531
2632 /* Return if an attribute from nested attribute set exists.
27− For instance ["x" "y"] applied to some set e returns true, if e.x.y exists. False
28− is returned otherwise. */
33+
34+ Example:
35+ x = { a = { b = 3; }; }
36+ hasAttrByPath ["a" "b"] x
37+ => true
38+ hasAttrByPath ["z" "z"] x
39+ => false
40+
41+ */
2942 hasAttrByPath = attrPath: e:
3043 let attr = head attrPath;
3144 in
@@ -35,14 +48,28 @@ rec {
3548 else false;
3649
3750
38− /* Return nested attribute set in which an attribute is set. For instance
39− ["x" "y"] applied with some value v returns `x.y = v;' */
51+ /* Return nested attribute set in which an attribute is set.
52+
53+ Example:
54+ setAttrByPath ["a" "b"] 3
55+ => { a = { b = 3; }; }
56+ */
4057 setAttrByPath = attrPath: value:
4158 if attrPath == [] then value
4259 else listToAttrs
4360 [ { name = head attrPath; value = setAttrByPath (tail attrPath) value; } ];
4461
4562
63+ /* Like `getAttrPath' without a default value. If it doesn't find the
64+ path it will throw.
65+
66+ Example:
67+ x = { a = { b = 3; }; }
68+ getAttrFromPath ["a" "b"] x
69+ => 3
70+ getAttrFromPath ["z" "z"] x
71+ => error: cannot find attribute `z.z'
72+ */
4673 getAttrFromPath = attrPath: set:
4774 let errorMsg = "cannot find attribute `" + concatStringsSep "." attrPath + "'";
4875 in attrByPath attrPath (abort errorMsg) set;
@@ -109,9 +136,11 @@ rec {
109136 ) (attrNames set)
110137 );
111138
112− /* foldAttrs: apply fold functions to values grouped by key. Eg accumulate values as list:
113− foldAttrs (n: a: [n] ++ a) [] [{ a = 2; } { a = 3; }]
114− => { a = [ 2 3 ]; }
139+ /* Apply fold functions to values grouped by key.
140+
141+ Example:
142+ foldAttrs (n: a: [n] ++ a) [] [{ a = 2; } { a = 3; }]
143+ => { a = [ 2 3 ]; }
115144 */
116145 foldAttrs = op: nul: list_of_attrs:
117146 fold (n: a:
@@ -147,7 +176,12 @@ rec {
147176
148177
149178 /* Utility function that creates a {name, value} pair as expected by
150− builtins.listToAttrs. */
179+ builtins.listToAttrs.
180+
181+ Example:
182+ nameValuePair "some" 6
183+ => { name = "some"; value = 6; }
184+ */
151185 nameValuePair = name: value: { inherit name value; };
152186
153187
@@ -248,11 +282,19 @@ rec {
248282 listToAttrs (map (n: nameValuePair n (f n)) names);
249283
250284
251− /* Check whether the argument is a derivation. */
252− isDerivation = x: isAttrs x && x ? type && x.type == "derivation";
285+ /* Check whether the argument is a derivation. Any set with
286+ { type = "derivation"; } counts as a derivation.
253287
288+ Example:
289+ nixpkgs = import <nixpkgs> {}
290+ isDerivation nixpkgs.ruby
291+ => true
292+ isDerivation "foobar"
293+ => false
294+ */
295+ isDerivation = x: isAttrs x && x ? type && x.type == "derivation";
254296
255− /* Convert a store path to a fake derivation. */
297+ /* Converts a store path to a fake derivation. */
256298 toDerivation = path:
257299 let path' = builtins.storePath path; in
258300 { type = "derivation";
@@ -262,32 +304,49 @@ rec {
262304 };
263305
264306
265− /* If the Boolean `cond' is true, return the attribute set `as',
266− otherwise an empty attribute set. */
307+ /* If `cond' is true, return the attribute set `as',
308+ otherwise an empty attribute set.
309+
310+ Example:
311+ optionalAttrs (true) { my = "set"; }
312+ => { my = "set"; }
313+ optionalAttrs (false) { my = "set"; }
314+ => { }
315+ */
267316 optionalAttrs = cond: as: if cond then as else {};
268317
269318
270319 /* Merge sets of attributes and use the function f to merge attributes
271− values. */
320+ values.
321+
322+ Example:
323+ zipAttrsWithNames ["a"] (name: vs: vs) [{a = "x";} {a = "y"; b = "z";}]
324+ => { a = ["x" "y"]; }
325+ */
272326 zipAttrsWithNames = names: f: sets:
273327 listToAttrs (map (name: {
274328 inherit name;
275329 value = f name (catAttrs name sets);
276330 }) names);
277331
278− # implentation note: Common names appear multiple times in the list of
279− # names, hopefully this does not affect the system because the maximal
280− # laziness avoid computing twice the same expression and listToAttrs does
281− # not care about duplicated attribute names.
332+ /* Implentation note: Common names appear multiple times in the list of
333+ names, hopefully this does not affect the system because the maximal
334+ laziness avoid computing twice the same expression and listToAttrs does
335+ not care about duplicated attribute names.
336+
337+ Example:
338+ zipAttrsWith (name: values: values) [{a = "x";} {a = "y"; b = "z";}]
339+ => { a = ["x" "y"]; b = ["z"] }
340+ */
282341 zipAttrsWith = f: sets: zipAttrsWithNames (concatMap attrNames sets) f sets;
342+ /* Like `zipAttrsWith' with `(name: values: value)' as the function.
283343
344+ Example:
345+ zipAttrs [{a = "x";} {a = "y"; b = "z";}]
346+ => { a = ["x" "y"]; b = ["z"] }
347+ */
284348 zipAttrs = zipAttrsWith (name: values: values);
285349
286− /* backward compatibility */
287− zipWithNames = zipAttrsWithNames;
288− zip = builtins.trace "lib.zip is deprecated, use lib.zipAttrsWith instead" zipAttrsWith;
289−
290−
291350 /* Does the same as the update operator '//' except that attributes are
292351 merged until the given pedicate is verified. The predicate should
293352 accept 3 arguments which are the path to reach the attribute, a part of
@@ -351,6 +410,15 @@ rec {
351410 !(isAttrs lhs && isAttrs rhs)
352411 ) lhs rhs;
353412
413+ /* Returns true if the pattern is contained in the set. False otherwise.
414+
415+ FIXME(zimbatm): this example doesn't work !!!
416+
417+ Example:
418+ sys = mkSystem { }
419+ matchAttrs { cpu = { bits = 64; }; } sys
420+ => true
421+ */
354422 matchAttrs = pattern: attrs:
355423 fold or false (attrValues (zipAttrsWithNames (attrNames pattern) (n: values:
356424 let pat = head values; val = head (tail values); in
@@ -359,10 +427,23 @@ rec {
359427 else pat == val
360428 ) [pattern attrs]));
361429
362− # override only the attributes that are already present in the old set
363− # useful for deep-overriding
430+ /* Override only the attributes that are already present in the old set
431+ useful for deep-overriding.
432+
433+ Example:
434+ x = { a = { b = 4; c = 3; }; }
435+ overrideExisting x { a = { b = 6; d = 2; }; }
436+ => { a = { b = 6; d = 2; }; }
437+ */
364438 overrideExisting = old: new:
365439 old // listToAttrs (map (attr: nameValuePair attr (attrByPath [attr] old.${attr} new)) (attrNames old));
366440
367− deepSeqAttrs = x: y: deepSeqList (attrValues x) y;
441+
442+ /*** deprecated stuff ***/
443+
444+ deepSeqAttrs = throw "removed 2016-02-29 because unused and broken";
445+ zipWithNames = zipAttrsWithNames;
446+ zip = builtins.trace
447+ "lib.zip is deprecated, use lib.zipAttrsWith instead" zipAttrsWith;
448+
368449}
lib/lists.nix+218−56
@@ -6,17 +6,26 @@ rec {
66
77 inherit (builtins) head tail length isList elemAt concatLists filter elem genList;
88
9−
10− # Create a list consisting of a single element. `singleton x' is
11− # sometimes more convenient with respect to indentation than `[x]'
12− # when x spans multiple lines.
9+ /* Create a list consisting of a single element. `singleton x' is
10+ sometimes more convenient with respect to indentation than `[x]'
11+ when x spans multiple lines.
12+
13+ Example:
14+ singleton "foo"
15+ => [ "foo" ]
16+ */
1317 singleton = x: [x];
1418
19+ /* "Fold" a binary function `op' between successive elements of
20+ `list' with `nul' as the starting value, i.e., `fold op nul [x_1
21+ x_2 ... x_n] == op x_1 (op x_2 ... (op x_n nul))'. (This is
22+ Haskell's foldr).
1523
16− # "Fold" a binary function `op' between successive elements of
17− # `list' with `nul' as the starting value, i.e., `fold op nul [x_1
18− # x_2 ... x_n] == op x_1 (op x_2 ... (op x_n nul))'. (This is
19− # Haskell's foldr).
24+ Example:
25+ concat = fold (a: b: a + b) "z"
26+ concat [ "a" "b" "c" ]
27+ => "abcnul"
28+ */
2029 fold = op: nul: list:
2130 let
2231 len = length list;
@@ -26,8 +35,14 @@ rec {
2635 else op (elemAt list n) (fold' (n + 1));
2736 in fold' 0;
2837
29− # Left fold: `fold op nul [x_1 x_2 ... x_n] == op (... (op (op nul
30− # x_1) x_2) ... x_n)'.
38+ /* Left fold: `fold op nul [x_1 x_2 ... x_n] == op (... (op (op nul
39+ x_1) x_2) ... x_n)'.
40+
41+ Example:
42+ lconcat = foldl (a: b: a + b) "z"
43+ lconcat [ "a" "b" "c" ]
44+ => "zabc"
45+ */
3146 foldl = op: nul: list:
3247 let
3348 len = length list;
@@ -37,13 +52,22 @@ rec {
3752 else op (foldl' (n - 1)) (elemAt list n);
3853 in foldl' (length list - 1);
3954
55+ /* Strict version of foldl.
4056
41− # Strict version of foldl.
57+ The difference is that evaluation is forced upon access. Usually used
58+ with small whole results (in contract with lazily-generated list or large
59+ lists where only a part is consumed.)
60+ */
4261 foldl' = builtins.foldl' or foldl;
4362
63+ /* Map with index
64+
65+ FIXME(zimbatm): why does this start to count at 1?
4466
45− # Map with index: `imap (i: v: "${v}-${toString i}") ["a" "b"] ==
46− # ["a-1" "b-2"]'. FIXME: why does this start to count at 1?
67+ Example:
68+ imap (i: v: "${v}-${toString i}") ["a" "b"]
69+ => [ "a-1" "b-2" ]
70+ */
4771 imap =
4872 if builtins ? genList then
4973 f: list: genList (n: f (n + 1) (elemAt list n)) (length list)
@@ -57,73 +81,141 @@ rec {
5781 else [ (f (n + 1) (elemAt list n)) ] ++ imap' (n + 1);
5882 in imap' 0;
5983
84+ /* Map and concatenate the result.
6085
61− # Map and concatenate the result.
86+ Example:
87+ concatMap (x: [x] ++ ["z"]) ["a" "b"]
88+ => [ "a" "z" "b" "z" ]
89+ */
6290 concatMap = f: list: concatLists (map f list);
6391
92+ /* Flatten the argument into a single list; that is, nested lists are
93+ spliced into the top-level lists.
6494
65− # Flatten the argument into a single list; that is, nested lists are
66− # spliced into the top-level lists. E.g., `flatten [1 [2 [3] 4] 5]
67− # == [1 2 3 4 5]' and `flatten 1 == [1]'.
95+ Example:
96+ flatten [1 [2 [3] 4] 5]
97+ => [1 2 3 4 5]
98+ flatten 1
99+ => [1]
100+ */
68101 flatten = x:
69102 if isList x
70103 then foldl' (x: y: x ++ (flatten y)) [] x
71104 else [x];
72105
106+ /* Remove elements equal to 'e' from a list. Useful for buildInputs.
73107
74− # Remove elements equal to 'e' from a list. Useful for buildInputs.
108+ Example:
109+ remove 3 [ 1 3 4 3 ]
110+ => [ 1 4 ]
111+ */
75112 remove = e: filter (x: x != e);
76113
77−
78− # Find the sole element in the list matching the specified
79− # predicate, returns `default' if no such element exists, or
80− # `multiple' if there are multiple matching elements.
114+ /* Find the sole element in the list matching the specified
115+ predicate, returns `default' if no such element exists, or
116+ `multiple' if there are multiple matching elements.
117+
118+ Example:
119+ findSingle (x: x == 3) "none" "multiple" [ 1 3 3 ]
120+ => "multiple"
121+ findSingle (x: x == 3) "none" "multiple" [ 1 3 ]
122+ => 3
123+ findSingle (x: x == 3) "none" "multiple" [ 1 9 ]
124+ => "none"
125+ */
81126 findSingle = pred: default: multiple: list:
82127 let found = filter pred list; len = length found;
83128 in if len == 0 then default
84129 else if len != 1 then multiple
85130 else head found;
86131
132+ /* Find the first element in the list matching the specified
133+ predicate or returns `default' if no such element exists.
87134
88− # Find the first element in the list matching the specified
89− # predicate or returns `default' if no such element exists.
135+ Example:
136+ findFirst (x: x > 3) 7 [ 1 6 4 ]
137+ => 6
138+ findFirst (x: x > 9) 7 [ 1 6 4 ]
139+ => 7
140+ */
90141 findFirst = pred: default: list:
91142 let found = filter pred list;
92143 in if found == [] then default else head found;
93144
145+ /* Return true iff function `pred' returns true for at least element
146+ of `list'.
94147
95− # Return true iff function `pred' returns true for at least element
96− # of `list'.
148+ Example:
149+ any isString [ 1 "a" { } ]
150+ => true
151+ any isString [ 1 { } ]
152+ => false
153+ */
97154 any = builtins.any or (pred: fold (x: y: if pred x then true else y) false);
98155
156+ /* Return true iff function `pred' returns true for all elements of
157+ `list'.
99158
100− # Return true iff function `pred' returns true for all elements of
101− # `list'.
159+ Example:
160+ all (x: x < 3) [ 1 2 ]
161+ => true
162+ all (x: x < 3) [ 1 2 3 ]
163+ => false
164+ */
102165 all = builtins.all or (pred: fold (x: y: if pred x then y else false) true);
103166
167+ /* Count how many times function `pred' returns true for the elements
168+ of `list'.
104169
105− # Count how many times function `pred' returns true for the elements
106− # of `list'.
170+ Example:
171+ count (x: x == 3) [ 3 2 3 4 6 ]
172+ => 2
173+ */
107174 count = pred: foldl' (c: x: if pred x then c + 1 else c) 0;
108175
176+ /* Return a singleton list or an empty list, depending on a boolean
177+ value. Useful when building lists with optional elements
178+ (e.g. `++ optional (system == "i686-linux") flashplayer').
109179
110− # Return a singleton list or an empty list, depending on a boolean
111− # value. Useful when building lists with optional elements
112− # (e.g. `++ optional (system == "i686-linux") flashplayer').
180+ Example:
181+ optional true "foo"
182+ => [ "foo" ]
183+ optional false "foo"
184+ => [ ]
185+ */
113186 optional = cond: elem: if cond then [elem] else [];
114187
188+ /* Return a list or an empty list, dependening on a boolean value.
115189
116− # Return a list or an empty list, dependening on a boolean value.
190+ Example:
191+ optionals true [ 2 3 ]
192+ => [ 2 3 ]
193+ optionals false [ 2 3 ]
194+ => [ ]
195+ */
117196 optionals = cond: elems: if cond then elems else [];
118197
119198
120− # If argument is a list, return it; else, wrap it in a singleton
121− # list. If you're using this, you should almost certainly
122− # reconsider if there isn't a more "well-typed" approach.
199+ /* If argument is a list, return it; else, wrap it in a singleton
200+ list. If you're using this, you should almost certainly
201+ reconsider if there isn't a more "well-typed" approach.
202+
203+ Example:
204+ toList [ 1 2 ]
205+ => [ 1 2 ]
206+ toList "hi"
207+ => [ "hi "]
208+ */
123209 toList = x: if isList x then x else [x];
124210
211+ /* Return a list of integers from `first' up to and including `last'.
125212
126− # Return a list of integers from `first' up to and including `last'.
213+ Example:
214+ range 2 4
215+ => [ 2 3 4 ]
216+ range 3 2
217+ => [ ]
218+ */
127219 range =
128220 if builtins ? genList then
129221 first: last:
@@ -136,9 +228,13 @@ rec {
136228 then []
137229 else [first] ++ range (first + 1) last;
138230
231+ /* Splits the elements of a list in two lists, `right' and
232+ `wrong', depending on the evaluation of a predicate.
139233
140− # Partition the elements of a list in two lists, `right' and
141− # `wrong', depending on the evaluation of a predicate.
234+ Example:
235+ partition (x: x > 2) [ 5 1 2 3 4 ]
236+ => { right = [ 5 3 4 ]; wrong = [ 1 2 ]; }
237+ */
142238 partition = pred:
143239 fold (h: t:
144240 if pred h
@@ -146,7 +242,14 @@ rec {
146242 else { right = t.right; wrong = [h] ++ t.wrong; }
147243 ) { right = []; wrong = []; };
148244
245+ /* Merges two lists of the same size together. If the sizes aren't the same
246+ the merging stops at the shortest. How both lists are merged is defined
247+ by the first argument.
149248
249+ Example:
250+ zipListsWith (a: b: a + b) ["h" "l"] ["e" "o"]
251+ => ["he" "lo"]
252+ */
150253 zipListsWith =
151254 if builtins ? genList then
152255 f: fst: snd: genList (n: f (elemAt fst n) (elemAt snd n)) (min (length fst) (length snd))
@@ -161,21 +264,37 @@ rec {
161264 else [];
162265 in zipListsWith' 0;
163266
267+ /* Merges two lists of the same size together. If the sizes aren't the same
268+ the merging stops at the shortest.
269+
270+ Example:
271+ zipLists [ 1 2 ] [ "a" "b" ]
272+ => [ { fst = 1; snd = "a"; } { fst = 2; snd = "b"; } ]
273+ */
164274 zipLists = zipListsWith (fst: snd: { inherit fst snd; });
165275
276+ /* Reverse the order of the elements of a list.
166277
167− # Reverse the order of the elements of a list.
278+ Example:
279+
280+ reverseList [ "b" "o" "j" ]
281+ => [ "j" "o" "b" ]
282+ */
168283 reverseList =
169284 if builtins ? genList then
170285 xs: let l = length xs; in genList (n: elemAt xs (l - n - 1)) l
171286 else
172287 fold (e: acc: acc ++ [ e ]) [];
173288
289+ /* Sort a list based on a comparator function which compares two
290+ elements and returns true if the first argument is strictly below
291+ the second argument. The returned list is sorted in an increasing
292+ order. The implementation does a quick-sort.
174293
175− # Sort a list based on a comparator function which compares two
176− # elements and returns true if the first argument is strictly below
177− # the second argument. The returned list is sorted in an increasing
178− # order. The implementation does a quick-sort.
294+ Example:
295+ sort (a: b: a < b) [ 5 3 7 ]
296+ => [ 3 5 7 ]
297+ */
179298 sort = builtins.sort or (
180299 strictLess: list:
181300 let
@@ -193,8 +312,14 @@ rec {
193312 if len < 2 then list
194313 else (sort strictLess pivot.left) ++ [ first ] ++ (sort strictLess pivot.right));
195314
315+ /* Return the first (at most) N elements of a list.
196316
197− # Return the first (at most) N elements of a list.
317+ Example:
318+ take 2 [ "a" "b" "c" "d" ]
319+ => [ "a" "b" ]
320+ take 2 [ ]
321+ => [ ]
322+ */
198323 take =
199324 if builtins ? genList then
200325 count: sublist 0 count
@@ -209,8 +334,14 @@ rec {
209334 [ (elemAt list n) ] ++ take' (n + 1);
210335 in take' 0;
211336
337+ /* Remove the first (at most) N elements of a list.
212338
213− # Remove the first (at most) N elements of a list.
339+ Example:
340+ drop 2 [ "a" "b" "c" "d" ]
341+ => [ "c" "d" ]
342+ drop 2 [ ]
343+ => [ ]
344+ */
214345 drop =
215346 if builtins ? genList then
216347 count: list: sublist count (length list) list
@@ -225,9 +356,15 @@ rec {
225356 drop' (n - 1) ++ [ (elemAt list n) ];
226357 in drop' (len - 1);
227358
359+ /* Return a list consisting of at most ‘count’ elements of ‘list’,
360+ starting at index ‘start’.
228361
229− # Return a list consisting of at most ‘count’ elements of ‘list’,
230− # starting at index ‘start’.
362+ Example:
363+ sublist 1 3 [ "a" "b" "c" "d" "e" ]
364+ => [ "b" "c" "d" ]
365+ sublist 1 3 [ ]
366+ => [ ]
367+ */
231368 sublist = start: count: list:
232369 let len = length list; in
233370 genList
@@ -236,23 +373,36 @@ rec {
236373 else if start + count > len then len - start
237374 else count);
238375
376+ /* Return the last element of a list.
239377
240− # Return the last element of a list.
378+ Example:
379+ last [ 1 2 3 ]
380+ => 3
381+ */
241382 last = list:
242383 assert list != []; elemAt list (length list - 1);
243384
385+ /* Return all elements but the last
244386
245− # Return all elements but the last
387+ Example:
388+ init [ 1 2 3 ]
389+ => [ 1 2 ]
390+ */
246391 init = list: assert list != []; take (length list - 1) list;
247392
248393
249− deepSeqList = xs: y: if any (x: deepSeq x false) xs then y else y;
394+ /* FIXME(zimbatm) Not used anywhere
395+ */
396+ crossLists = f: foldl (fs: args: concatMap (f: map f args) fs) [f];
250397
251398
252− crossLists = f: foldl (fs: args: concatMap (f: map f args) fs) [f];
399+ /* Remove duplicate elements from the list. O(n^2) complexity.
253400
401+ Example:
254402
255− # Remove duplicate elements from the list. O(n^2) complexity.
403+ unique [ 3 2 3 4 ]
404+ => [ 3 2 4 ]
405+ */
256406 unique = list:
257407 if list == [] then
258408 []
@@ -262,12 +412,24 @@ rec {
262412 xs = unique (drop 1 list);
263413 in [x] ++ remove x xs;
264414
415+ /* Intersects list 'e' and another list. O(nm) complexity.
265416
266− # Intersects list 'e' and another list. O(nm) complexity.
417+ Example:
418+ intersectLists [ 1 2 3 ] [ 6 3 2 ]
419+ => [ 3 2 ]
420+ */
267421 intersectLists = e: filter (x: elem x e);
268422
423+ /* Subtracts list 'e' from another list. O(nm) complexity.
269424
270− # Subtracts list 'e' from another list. O(nm) complexity.
425+ Example:
426+ subtractLists [ 3 2 ] [ 1 2 3 4 5 3 ]
427+ => [ 1 4 5 ]
428+ */
271429 subtractLists = e: filter (x: !(elem x e));
272430
431+ /*** deprecated stuff ***/
432+
433+ deepSeqList = throw "removed 2016-02-29 because unused and broken";
434+
273435}
lib/strings.nix+274−62
@@ -10,65 +10,147 @@ rec {
1010
1111 inherit (builtins) stringLength substring head tail isString replaceStrings;
1212
13+ /* Concatenate a list of strings.
1314
14− # Concatenate a list of strings.
15+ Example:
16+ concatStrings ["foo" "bar"]
17+ => "foobar"
18+ */
1519 concatStrings =
1620 if builtins ? concatStringsSep then
1721 builtins.concatStringsSep ""
1822 else
1923 lib.foldl' (x: y: x + y) "";
2024
25+ /* Map a function over a list and concatenate the resulting strings.
2126
22− # Map a function over a list and concatenate the resulting strings.
27+ Example:
28+ concatMapStrings (x: "a" + x) ["foo" "bar"]
29+ => "afooabar"
30+ */
2331 concatMapStrings = f: list: concatStrings (map f list);
32+
33+ /* Like `concatMapStrings' except that the f functions also gets the
34+ position as a parameter.
35+
36+ Example:
37+ concatImapStrings (pos: x: "${toString pos}-${x}") ["foo" "bar"]
38+ => "1-foo2-bar"
39+ */
2440 concatImapStrings = f: list: concatStrings (lib.imap f list);
2541
42+ /* Place an element between each element of a list
2643
27− # Place an element between each element of a list, e.g.,
28− # `intersperse "," ["a" "b" "c"]' returns ["a" "," "b" "," "c"].
44+ Example:
45+ intersperse "/" ["usr" "local" "bin"]
46+ => ["usr" "/" "local" "/" "bin"].
47+ */
2948 intersperse = separator: list:
3049 if list == [] || length list == 1
3150 then list
3251 else tail (lib.concatMap (x: [separator x]) list);
3352
53+ /* Concatenate a list of strings with a separator between each element
3454
35− # Concatenate a list of strings with a separator between each element, e.g.
36− # concatStringsSep " " ["foo" "bar" "xyzzy"] == "foo bar xyzzy"
55+ Example:
56+ concatStringsSep "/" ["usr" "local" "bin"]
57+ => "usr/local/bin"
58+ */
3759 concatStringsSep = builtins.concatStringsSep or (separator: list:
3860 concatStrings (intersperse separator list));
3961
62+ /* First maps over the list and then concatenates it.
63+
64+ Example:
65+ concatMapStringsSep "-" (x: toUpper x) ["foo" "bar" "baz"]
66+ => "FOO-BAR-BAZ"
67+ */
4068 concatMapStringsSep = sep: f: list: concatStringsSep sep (map f list);
69+
70+ /* First imaps over the list and then concatenates it.
71+
72+ Example:
73+
74+ concatImapStringsSep "-" (pos: x: toString (x / pos)) [ 6 6 6 ]
75+ => "6-3-2"
76+ */
4177 concatImapStringsSep = sep: f: list: concatStringsSep sep (lib.imap f list);
4278
79+ /* Construct a Unix-style search path consisting of each `subDir"
80+ directory of the given list of packages.
4381
44− # Construct a Unix-style search path consisting of each `subDir"
45− # directory of the given list of packages. For example,
46− # `makeSearchPath "bin" ["x" "y" "z"]' returns "x/bin:y/bin:z/bin".
82+ Example:
83+ makeSearchPath "bin" ["/root" "/usr" "/usr/local"]
84+ => "/root/bin:/usr/bin:/usr/local/bin"
85+ makeSearchPath "bin" ["/"]
86+ => "//bin"
87+ */
4788 makeSearchPath = subDir: packages:
4889 concatStringsSep ":" (map (path: path + "/" + subDir) packages);
4990
91+ /* Construct a library search path (such as RPATH) containing the
92+ libraries for a set of packages
5093
51− # Construct a library search path (such as RPATH) containing the
52− # libraries for a set of packages, e.g. "${pkg1}/lib:${pkg2}/lib:...".
94+ Example:
95+ makeLibraryPath [ "/usr" "/usr/local" ]
96+ => "/usr/lib:/usr/local/lib"
97+ pkgs = import <nixpkgs> { }
98+ makeLibraryPath [ pkgs.openssl pkgs.zlib ]
99+ => "/nix/store/9rz8gxhzf8sw4kf2j2f1grr49w8zx5vj-openssl-1.0.1r/lib:/nix/store/wwh7mhwh269sfjkm6k5665b5kgp7jrk2-zlib-1.2.8/lib"
100+ */
53101 makeLibraryPath = makeSearchPath "lib";
54102
55− # Construct a binary search path (such as $PATH) containing the
56− # binaries for a set of packages, e.g. "${pkg1}/bin:${pkg2}/bin:...".
103+ /* Construct a binary search path (such as $PATH) containing the
104+ binaries for a set of packages.
105+
106+ Example:
107+ makeBinPath ["/root" "/usr" "/usr/local"]
108+ => "/root/bin:/usr/bin:/usr/local/bin"
109+ */
57110 makeBinPath = makeSearchPath "bin";
58111
59112
60− # Idem for Perl search paths.
113+ /* Construct a perl search path (such as $PERL5LIB)
114+
115+ FIXME(zimbatm): this should be moved in perl-specific code
116+
117+ Example:
118+ pkgs = import <nixpkgs> { }
119+ makePerlPath [ pkgs.perlPackages.NetSMTP ]
120+ => "/nix/store/n0m1fk9c960d8wlrs62sncnadygqqc6y-perl-Net-SMTP-1.25/lib/perl5/site_perl"
121+ */
61122 makePerlPath = makeSearchPath "lib/perl5/site_perl";
62123
124+ /* Dependening on the boolean `cond', return either the given string
125+ or the empty string. Useful to contatenate against a bigger string.
63126
64− # Dependening on the boolean `cond', return either the given string
65− # or the empty string.
127+ Example:
128+ optionalString true "some-string"
129+ => "some-string"
130+ optionalString false "some-string"
131+ => ""
132+ */
66133 optionalString = cond: string: if cond then string else "";
67134
135+ /* Determine whether a string has given prefix.
68136
69− # Determine whether a string has given prefix/suffix.
137+ Example:
138+ hasPrefix "foo" "foobar"
139+ => true
140+ hasPrefix "foo" "barfoo"
141+ => false
142+ */
70143 hasPrefix = pref: str:
71144 substring 0 (stringLength pref) str == pref;
145+
146+ /* Determine whether a string has given suffix.
147+
148+ Example:
149+ hasSuffix "foo" "foobar"
150+ => false
151+ hasSuffix "foo" "barfoo"
152+ => true
153+ */
72154 hasSuffix = suff: str:
73155 let
74156 lenStr = stringLength str;
@@ -76,36 +158,55 @@ rec {
76158 in lenStr >= lenSuff &&
77159 substring (lenStr - lenSuff) lenStr str == suff;
78160
79−
80− # Convert a string to a list of characters (i.e. singleton strings).
81− # For instance, "abc" becomes ["a" "b" "c"]. This allows you to,
82− # e.g., map a function over each character. However, note that this
83− # will likely be horribly inefficient; Nix is not a general purpose
84− # programming language. Complex string manipulations should, if
85− # appropriate, be done in a derivation.
161+ /* Convert a string to a list of characters (i.e. singleton strings).
162+ This allows you to, e.g., map a function over each character. However,
163+ note that this will likely be horribly inefficient; Nix is not a
164+ general purpose programming language. Complex string manipulations
165+ should, if appropriate, be done in a derivation.
166+ Also note that Nix treats strings as a list of bytes and thus doesn't
167+ handle unicode.
168+
169+ Example:
170+ stringToCharacters ""
171+ => [ ]
172+ stringToCharacters "abc"
173+ => [ "a" "b" "c" ]
174+ stringToCharacters "💩"
175+ => [ "�" "�" "�" "�" ]
176+ */
86177 stringToCharacters = s:
87178 map (p: substring p 1 s) (lib.range 0 (stringLength s - 1));
88179
180+ /* Manipulate a string character by character and replace them by
181+ strings before concatenating the results.
89182
90− # Manipulate a string charactter by character and replace them by
91− # strings before concatenating the results.
183+ Example:
184+ stringAsChars (x: if x == "a" then "i" else x) "nax"
185+ => "nix"
186+ */
92187 stringAsChars = f: s:
93188 concatStrings (
94189 map f (stringToCharacters s)
95190 );
96191
192+ /* Escape occurrence of the elements of ‘list’ in ‘string’ by
193+ prefixing it with a backslash.
97194
98− # Escape occurrence of the elements of ‘list’ in ‘string’ by
99− # prefixing it with a backslash. For example, ‘escape ["(" ")"]
100− # "(foo)"’ returns the string ‘\(foo\)’.
195+ Example:
196+ escape ["(" ")"] "(foo)"
197+ => "\\(foo\\)"
198+ */
101199 escape = list: replaceChars list (map (c: "\\${c}") list);
102200
201+ /* Escape all characters that have special meaning in the Bourne shell.
103202
104− # Escape all characters that have special meaning in the Bourne shell.
203+ Example:
204+ escapeShellArg "so([<>])me"
205+ => "so\\(\\[\\<\\>\\]\\)me"
206+ */
105207 escapeShellArg = lib.escape (stringToCharacters "\\ ';$`()|<>\t*[]");
106208
107−
108− # Obsolete - use replaceStrings instead.
209+ /* Obsolete - use replaceStrings instead. */
109210 replaceChars = builtins.replaceStrings or (
110211 del: new: s:
111212 let
@@ -119,21 +220,52 @@ rec {
119220 in
120221 stringAsChars subst s);
121222
122−
123223 # Case conversion utilities.
124224 lowerChars = stringToCharacters "abcdefghijklmnopqrstuvwxyz";
125225 upperChars = stringToCharacters "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
226+
227+ /* Converts an ASCII string to lower-case.
228+
229+ Example:
230+ toLower "HOME"
231+ => "home"
232+ */
126233 toLower = replaceChars upperChars lowerChars;
234+
235+ /* Converts an ASCII string to upper-case.
236+
237+ Example:
238+ toLower "home"
239+ => "HOME"
240+ */
127241 toUpper = replaceChars lowerChars upperChars;
128242
243+ /* Appends string context from another string. This is an implementation
244+ detail of Nix.
129245
130− # Appends string context from another string.
246+ Strings in Nix carry an invisible `context' which is a list of strings
247+ representing store paths. If the string is later used in a derivation
248+ attribute, the derivation will properly populate the inputDrvs and
249+ inputSrcs.
250+
251+ Example:
252+ pkgs = import <nixpkgs> { };
253+ addContextFrom pkgs.coreutils "bar"
254+ => "bar"
255+ */
131256 addContextFrom = a: b: substring 0 0 a + b;
132257
258+ /* Cut a string with a separator and produces a list of strings which
259+ were separated by this separator.
260+
261+ NOTE: this function is not performant and should be avoided
133262
134− # Cut a string with a separator and produces a list of strings which
135− # were separated by this separator; e.g., `splitString "."
136− # "foo.bar.baz"' returns ["foo" "bar" "baz"].
263+ Example:
264+ splitString "." "foo.bar.baz"
265+ => [ "foo" "bar" "baz" ]
266+ splitString "/" "/usr/local/bin"
267+ => [ "" "usr" "local" "bin" ]
268+ */
137269 splitString = _sep: _s:
138270 let
139271 sep = addContextFrom _s _sep;
@@ -157,10 +289,15 @@ rec {
157289 in
158290 recurse 0 0;
159291
292+ /* Return the suffix of the second argument if the first argument matches
293+ its prefix.
160294
161− # return the suffix of the second argument if the first argument match its
162− # prefix. e.g.,
163− # `removePrefix "foo." "foo.bar.baz"' returns "bar.baz".
295+ Example:
296+ removePrefix "foo." "foo.bar.baz"
297+ => "bar.baz"
298+ removePrefix "xxx" "foo.bar.baz"
299+ => "foo.bar.baz"
300+ */
164301 removePrefix = pre: s:
165302 let
166303 preLen = stringLength pre;
@@ -171,6 +308,15 @@ rec {
171308 else
172309 s;
173310
311+ /* Return the prefix of the second argument if the first argument matches
312+ its suffix.
313+
314+ Example:
315+ removeSuffix "front" "homefront"
316+ => "home"
317+ removeSuffix "xxx" "homefront"
318+ => "homefront"
319+ */
174320 removeSuffix = suf: s:
175321 let
176322 sufLen = stringLength suf;
@@ -181,25 +327,49 @@ rec {
181327 else
182328 s;
183329
184− # Return true iff string v1 denotes a version older than v2.
330+ /* Return true iff string v1 denotes a version older than v2.
331+
332+ Example:
333+ versionOlder "1.1" "1.2"
334+ => true
335+ versionOlder "1.1" "1.1"
336+ => false
337+ */
185338 versionOlder = v1: v2: builtins.compareVersions v2 v1 == 1;
186339
340+ /* Return true iff string v1 denotes a version equal to or newer than v2.
187341
188− # Return true iff string v1 denotes a version equal to or newer than v2.
342+ Example:
343+ versionAtLeast "1.1" "1.0"
344+ => true
345+ versionAtLeast "1.1" "1.1"
346+ => true
347+ versionAtLeast "1.1" "1.2"
348+ => false
349+ */
189350 versionAtLeast = v1: v2: !versionOlder v1 v2;
190351
352+ /* This function takes an argument that's either a derivation or a
353+ derivation's "name" attribute and extracts the version part from that
354+ argument.
191355
192− # This function takes an argument that's either a derivation or a
193− # derivation's "name" attribute and extracts the version part from that
194− # argument. For example:
195− #
196− # lib.getVersion "youtube-dl-2016.01.01" ==> "2016.01.01"
197− # lib.getVersion pkgs.youtube-dl ==> "2016.01.01"
356+ Example:
357+ getVersion "youtube-dl-2016.01.01"
358+ => "2016.01.01"
359+ getVersion pkgs.youtube-dl
360+ => "2016.01.01"
361+ */
198362 getVersion = x: (builtins.parseDrvName (x.name or x)).version;
199363
364+ /* Extract name with version from URL. Ask for separator which is
365+ supposed to start extension.
200366
201− # Extract name with version from URL. Ask for separator which is
202− # supposed to start extension.
367+ Example:
368+ nameFromURL "https://nixos.org/releases/nix/nix-1.7/nix-1.7-x86_64-linux.tar.bz2" "-"
369+ => "nix"
370+ nameFromURL "https://nixos.org/releases/nix/nix-1.7/nix-1.7-x86_64-linux.tar.bz2" "_"
371+ => "nix-1.7-x86"
372+ */
203373 nameFromURL = url: sep:
204374 let
205375 components = splitString "/" url;
@@ -207,14 +377,24 @@ rec {
207377 name = builtins.head (splitString sep filename);
208378 in assert name != filename; name;
209379
380+ /* Create an --{enable,disable}-<feat> string that can be passed to
381+ standard GNU Autoconf scripts.
210382
211− # Create an --{enable,disable}-<feat> string that can be passed to
212− # standard GNU Autoconf scripts.
383+ Example:
384+ enableFeature true "shared"
385+ => "--enable-shared"
386+ enableFeature false "shared"
387+ => "--disable-shared"
388+ */
213389 enableFeature = enable: feat: "--${if enable then "enable" else "disable"}-${feat}";
214390
391+ /* Create a fixed width string with additional prefix to match
392+ required width.
215393
216− # Create a fixed width string with additional prefix to match
217− # required width.
394+ Example:
395+ fixedWidthString 5 "0" (toString 15)
396+ => "00015"
397+ */
218398 fixedWidthString = width: filler: str:
219399 let
220400 strw = lib.stringLength str;
@@ -223,25 +403,58 @@ rec {
223403 assert strw <= width;
224404 if strw == width then str else filler + fixedWidthString reqWidth filler str;
225405
406+ /* Format a number adding leading zeroes up to fixed width.
226407
227− # Format a number adding leading zeroes up to fixed width.
408+ Example:
409+ fixedWidthNumber 5 15
410+ => "00015"
411+ */
228412 fixedWidthNumber = width: n: fixedWidthString width "0" (toString n);
229413
414+ /* Check whether a value is a store path.
230415
231− # Check whether a value is a store path.
416+ Example:
417+ isStorePath "/nix/store/d945ibfx9x185xf04b890y4f9g3cbb63-python-2.7.11/bin/python"
418+ => false
419+ isStorePath "/nix/store/d945ibfx9x185xf04b890y4f9g3cbb63-python-2.7.11/"
420+ => true
421+ isStorePath pkgs.python
422+ => true
423+ */
232424 isStorePath = x: builtins.substring 0 1 (toString x) == "/" && dirOf (builtins.toPath x) == builtins.storeDir;
233425
234− # Convert string to int
235− # Obviously, it is a bit hacky to use fromJSON that way.
426+ /* Convert string to int
427+ Obviously, it is a bit hacky to use fromJSON that way.
428+
429+ Example:
430+ toInt "1337"
431+ => 1337
432+ toInt "-4"
433+ => -4
434+ toInt "3.14"
435+ => error: floating point JSON numbers are not supported
436+ */
236437 toInt = str:
237438 let may_be_int = builtins.fromJSON str; in
238439 if builtins.isInt may_be_int
239440 then may_be_int
240441 else throw "Could not convert ${str} to int.";
241442
242− # Read a list of paths from `file', relative to the `rootPath'. Lines
243− # beginning with `#' are treated as comments and ignored. Whitespace
244− # is significant.
443+ /* Read a list of paths from `file', relative to the `rootPath'. Lines
444+ beginning with `#' are treated as comments and ignored. Whitespace
445+ is significant.
446+
447+ NOTE: this function is not performant and should be avoided
448+
449+ Example:
450+ readPathsFromFile /prefix
451+ ./pkgs/development/libraries/qt-5/5.4/qtbase/series
452+ => [ "/prefix/dlopen-resolv.patch" "/prefix/tzdir.patch"
453+ "/prefix/dlopen-libXcursor.patch" "/prefix/dlopen-openssl.patch"
454+ "/prefix/dlopen-dbus.patch" "/prefix/xdg-config-dirs.patch"
455+ "/prefix/nix-profiles-library-paths.patch"
456+ "/prefix/compose-search-path.patch" ]
457+ */
245458 readPathsFromFile = rootPath: file:
246459 let
247460 root = toString rootPath;
@@ -253,5 +466,4 @@ rec {
253466 absolutePaths = builtins.map (path: builtins.toPath (root + "/" + path)) relativePaths;
254467 in
255468 absolutePaths;
256−
257469}