git.iko.soy/typeable/nixpkgs
on master help sign in
lib/strings: document all the functions
commit7883ca774b1fe8b59c455053d434b92d7b65d3d5 authorzimbatm <zimbatm@zimbatm.com> dateSun 28 Feb 2016, 23:27 (11 years ago) parentc71e2d4
1 file changed+274−62
lib/strings.nix+274−62
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}