1/* String manipulation functions. */
5inherit (builtins) length;
32 unsafeDiscardStringContext
35 /* Concatenate a list of strings.
37 Type: concatStrings :: [string] -> string
40 concatStrings ["foo" "bar"]
43 concatStrings = builtins.concatStringsSep "";
45 /* Map a function over a list and concatenate the resulting strings.
47 Type: concatMapStrings :: (a -> string) -> [a] -> string
50 concatMapStrings (x: "a" + x) ["foo" "bar"]
53 concatMapStrings = f: list: concatStrings (map f list);
55 /* Like `concatMapStrings` except that the f functions also gets the
56 position as a parameter.
58 Type: concatImapStrings :: (int -> a -> string) -> [a] -> string
61 concatImapStrings (pos: x: "${toString pos}-${x}") ["foo" "bar"]
64 concatImapStrings = f: list: concatStrings (lib.imap1 f list);
66 /* Place an element between each element of a list
68 Type: intersperse :: a -> [a] -> [a]
71 intersperse "/" ["usr" "local" "bin"]
72 => ["usr" "/" "local" "/" "bin"].
75 # Separator to add between elements
79 if list == [] || length list == 1
81 else tail (lib.concatMap (x: [separator x]) list);
83 /* Concatenate a list of strings with a separator between each element
85 Type: concatStringsSep :: string -> [string] -> string
88 concatStringsSep "/" ["usr" "local" "bin"]
91 concatStringsSep = builtins.concatStringsSep or (separator: list:
92 concatStrings (intersperse separator list));
94 /* Maps a function over a list of strings and then concatenates the
95 result with the specified separator interspersed between
98 Type: concatMapStringsSep :: string -> (string -> string) -> [string] -> string
101 concatMapStringsSep "-" (x: toUpper x) ["foo" "bar" "baz"]
104 concatMapStringsSep =
105 # Separator to add between elements
107 # Function to map over the list
109 # List of input strings
110 list: concatStringsSep sep (map f list);
112 /* Same as `concatMapStringsSep`, but the mapping function
113 additionally receives the position of its argument.
115 Type: concatIMapStringsSep :: string -> (int -> string -> string) -> [string] -> string
118 concatImapStringsSep "-" (pos: x: toString (x / pos)) [ 6 6 6 ]
121 concatImapStringsSep =
122 # Separator to add between elements
124 # Function that receives elements and their positions
126 # List of input strings
127 list: concatStringsSep sep (lib.imap1 f list);
129 /* Construct a Unix-style, colon-separated search path consisting of
130 the given `subDir` appended to each of the given paths.
132 Type: makeSearchPath :: string -> [string] -> string
135 makeSearchPath "bin" ["/root" "/usr" "/usr/local"]
136 => "/root/bin:/usr/bin:/usr/local/bin"
137 makeSearchPath "bin" [""]
141 # Directory name to append
145 concatStringsSep ":" (map (path: path + "/" + subDir) (filter (x: x != null) paths));
147 /* Construct a Unix-style search path by appending the given
148 `subDir` to the specified `output` of each of the packages. If no
149 output by the given name is found, fallback to `.out` and then to
152 Type: string -> string -> [package] -> string
155 makeSearchPathOutput "dev" "bin" [ pkgs.openssl pkgs.zlib ]
156 => "/nix/store/9rz8gxhzf8sw4kf2j2f1grr49w8zx5vj-openssl-1.0.1r-dev/bin:/nix/store/wwh7mhwh269sfjkm6k5665b5kgp7jrk2-zlib-1.2.8/bin"
158 makeSearchPathOutput =
159 # Package output to use
161 # Directory name to append
164 pkgs: makeSearchPath subDir (map (lib.getOutput output) pkgs);
166 /* Construct a library search path (such as RPATH) containing the
167 libraries for a set of packages
170 makeLibraryPath [ "/usr" "/usr/local" ]
171 => "/usr/lib:/usr/local/lib"
172 pkgs = import <nixpkgs> { }
173 makeLibraryPath [ pkgs.openssl pkgs.zlib ]
174 => "/nix/store/9rz8gxhzf8sw4kf2j2f1grr49w8zx5vj-openssl-1.0.1r/lib:/nix/store/wwh7mhwh269sfjkm6k5665b5kgp7jrk2-zlib-1.2.8/lib"
176 makeLibraryPath = makeSearchPathOutput "lib" "lib";
178 /* Construct a binary search path (such as $PATH) containing the
179 binaries for a set of packages.
182 makeBinPath ["/root" "/usr" "/usr/local"]
183 => "/root/bin:/usr/bin:/usr/local/bin"
185 makeBinPath = makeSearchPathOutput "bin" "bin";
187 /* Depending on the boolean `cond', return either the given string
188 or the empty string. Useful to concatenate against a bigger string.
190 Type: optionalString :: bool -> string -> string
193 optionalString true "some-string"
195 optionalString false "some-string"
201 # String to return if condition is true
202 string: if cond then string else "";
204 /* Determine whether a string has given prefix.
206 Type: hasPrefix :: string -> string -> bool
209 hasPrefix "foo" "foobar"
211 hasPrefix "foo" "barfoo"
215 # Prefix to check for
218 str: substring 0 (stringLength pref) str == pref;
220 /* Determine whether a string has given suffix.
222 Type: hasSuffix :: string -> string -> bool
225 hasSuffix "foo" "foobar"
227 hasSuffix "foo" "barfoo"
231 # Suffix to check for
236 lenContent = stringLength content;
237 lenSuffix = stringLength suffix;
238 in lenContent >= lenSuffix &&
239 substring (lenContent - lenSuffix) lenContent content == suffix;
241 /* Determine whether a string contains the given infix
243 Type: hasInfix :: string -> string -> bool
252 hasInfix "foo" "abcd"
255 hasInfix = infix: content:
257 drop = x: substring 1 (stringLength x) x;
258 in hasPrefix infix content
259 || content != "" && hasInfix infix (drop content);
261 /* Convert a string to a list of characters (i.e. singleton strings).
262 This allows you to, e.g., map a function over each character. However,
263 note that this will likely be horribly inefficient; Nix is not a
264 general purpose programming language. Complex string manipulations
265 should, if appropriate, be done in a derivation.
266 Also note that Nix treats strings as a list of bytes and thus doesn't
269 Type: stringToCharacters :: string -> [string]
272 stringToCharacters ""
274 stringToCharacters "abc"
276 stringToCharacters "💩"
277 => [ "�" "�" "�" "�" ]
279 stringToCharacters = s:
280 map (p: substring p 1 s) (lib.range 0 (stringLength s - 1));
282 /* Manipulate a string character by character and replace them by
283 strings before concatenating the results.
285 Type: stringAsChars :: (string -> string) -> string -> string
288 stringAsChars (x: if x == "a" then "i" else x) "nax"
292 # Function to map over each individual character
296 map f (stringToCharacters s)
299 /* Escape occurrence of the elements of `list` in `string` by
300 prefixing it with a backslash.
302 Type: escape :: [string] -> string -> string
305 escape ["(" ")"] "(foo)"
308 escape = list: replaceChars list (map (c: "\\${c}") list);
310 /* Quote string to be used safely within the Bourne shell.
312 Type: escapeShellArg :: string -> string
315 escapeShellArg "esc'ape\nme"
316 => "'esc'\\''ape\nme'"
318 escapeShellArg = arg: "'${replaceStrings ["'"] ["'\\''"] (toString arg)}'";
320 /* Quote all arguments to be safely passed to the Bourne shell.
322 Type: escapeShellArgs :: [string] -> string
325 escapeShellArgs ["one" "two three" "four'five"]
326 => "'one' 'two three' 'four'\\''five'"
328 escapeShellArgs = concatMapStringsSep " " escapeShellArg;
330 /* Turn a string into a Nix expression representing that string
332 Type: string -> string
335 escapeNixString "hello\${}\n"
336 => "\"hello\\\${}\\n\""
338 escapeNixString = s: escape ["$"] (toJSON s);
340 /* Turn a string into an exact regular expression
342 Type: string -> string
345 escapeRegex "[^a-z]*"
348 escapeRegex = escape (stringToCharacters "\\[{()^$?*+|.");
350 /* Quotes a string if it can't be used as an identifier directly.
352 Type: string -> string
355 escapeNixIdentifier "hello"
357 escapeNixIdentifier "0abc"
360 escapeNixIdentifier = s:
361 # Regex from https://github.com/NixOS/nix/blob/d048577909e383439c2549e849c5c2f2016c997e/src/libexpr/lexer.l#L91
362 if match "[a-zA-Z_][a-zA-Z0-9_'-]*" s != null
363 then s else escapeNixString s;
365 # Obsolete - use replaceStrings instead.
366 replaceChars = builtins.replaceStrings or (
369 substList = lib.zipLists del new;
371 let found = lib.findFirst (sub: sub.fst == c) null substList; in
372 if found == null then
377 stringAsChars subst s);
379 # Case conversion utilities.
380 lowerChars = stringToCharacters "abcdefghijklmnopqrstuvwxyz";
381 upperChars = stringToCharacters "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
383 /* Converts an ASCII string to lower-case.
385 Type: toLower :: string -> string
391 toLower = replaceChars upperChars lowerChars;
393 /* Converts an ASCII string to upper-case.
395 Type: toUpper :: string -> string
401 toUpper = replaceChars lowerChars upperChars;
403 /* Appends string context from another string. This is an implementation
406 Strings in Nix carry an invisible `context` which is a list of strings
407 representing store paths. If the string is later used in a derivation
408 attribute, the derivation will properly populate the inputDrvs and
412 pkgs = import <nixpkgs> { };
413 addContextFrom pkgs.coreutils "bar"
416 addContextFrom = a: b: substring 0 0 a + b;
418 /* Cut a string with a separator and produces a list of strings which
419 were separated by this separator.
422 splitString "." "foo.bar.baz"
423 => [ "foo" "bar" "baz" ]
424 splitString "/" "/usr/local/bin"
425 => [ "" "usr" "local" "bin" ]
427 splitString = _sep: _s:
429 sep = builtins.unsafeDiscardStringContext _sep;
430 s = builtins.unsafeDiscardStringContext _s;
431 splits = builtins.filter builtins.isString (builtins.split (escapeRegex sep) s);
433 map (v: addContextFrom _sep (addContextFrom _s v)) splits;
435 /* Return a string without the specified prefix, if the prefix matches.
437 Type: string -> string -> string
440 removePrefix "foo." "foo.bar.baz"
442 removePrefix "xxx" "foo.bar.baz"
446 # Prefix to remove if it matches
451 preLen = stringLength prefix;
452 sLen = stringLength str;
454 if hasPrefix prefix str then
455 substring preLen (sLen - preLen) str
459 /* Return a string without the specified suffix, if the suffix matches.
461 Type: string -> string -> string
464 removeSuffix "front" "homefront"
466 removeSuffix "xxx" "homefront"
470 # Suffix to remove if it matches
475 sufLen = stringLength suffix;
476 sLen = stringLength str;
478 if sufLen <= sLen && suffix == substring (sLen - sufLen) sufLen str then
479 substring 0 (sLen - sufLen) str
483 /* Return true if string v1 denotes a version older than v2.
486 versionOlder "1.1" "1.2"
488 versionOlder "1.1" "1.1"
491 versionOlder = v1: v2: compareVersions v2 v1 == 1;
493 /* Return true if string v1 denotes a version equal to or newer than v2.
496 versionAtLeast "1.1" "1.0"
498 versionAtLeast "1.1" "1.1"
500 versionAtLeast "1.1" "1.2"
503 versionAtLeast = v1: v2: !versionOlder v1 v2;
505 /* This function takes an argument that's either a derivation or a
506 derivation's "name" attribute and extracts the name part from that
510 getName "youtube-dl-2016.01.01"
512 getName pkgs.youtube-dl
517 parse = drv: (parseDrvName drv).name;
520 else x.pname or (parse x.name);
522 /* This function takes an argument that's either a derivation or a
523 derivation's "name" attribute and extracts the version part from that
527 getVersion "youtube-dl-2016.01.01"
529 getVersion pkgs.youtube-dl
534 parse = drv: (parseDrvName drv).version;
537 else x.version or (parse x.name);
539 /* Extract name with version from URL. Ask for separator which is
540 supposed to start extension.
543 nameFromURL "https://nixos.org/releases/nix/nix-1.7/nix-1.7-x86_64-linux.tar.bz2" "-"
545 nameFromURL "https://nixos.org/releases/nix/nix-1.7/nix-1.7-x86_64-linux.tar.bz2" "_"
548 nameFromURL = url: sep:
550 components = splitString "/" url;
551 filename = lib.last components;
552 name = head (splitString sep filename);
553 in assert name != filename; name;
555 /* Create an --{enable,disable}-<feat> string that can be passed to
556 standard GNU Autoconf scripts.
559 enableFeature true "shared"
561 enableFeature false "shared"
562 => "--disable-shared"
564 enableFeature = enable: feat:
565 assert isString feat; # e.g. passing openssl instead of "openssl"
566 "--${if enable then "enable" else "disable"}-${feat}";
568 /* Create an --{enable-<feat>=<value>,disable-<feat>} string that can be passed to
569 standard GNU Autoconf scripts.
572 enableFeatureAs true "shared" "foo"
573 => "--enable-shared=foo"
574 enableFeatureAs false "shared" (throw "ignored")
575 => "--disable-shared"
577 enableFeatureAs = enable: feat: value: enableFeature enable feat + optionalString enable "=${value}";
579 /* Create an --{with,without}-<feat> string that can be passed to
580 standard GNU Autoconf scripts.
583 withFeature true "shared"
585 withFeature false "shared"
586 => "--without-shared"
588 withFeature = with_: feat:
589 assert isString feat; # e.g. passing openssl instead of "openssl"
590 "--${if with_ then "with" else "without"}-${feat}";
592 /* Create an --{with-<feat>=<value>,without-<feat>} string that can be passed to
593 standard GNU Autoconf scripts.
596 withFeatureAs true "shared" "foo"
597 => "--with-shared=foo"
598 withFeatureAs false "shared" (throw "ignored")
599 => "--without-shared"
601 withFeatureAs = with_: feat: value: withFeature with_ feat + optionalString with_ "=${value}";
603 /* Create a fixed width string with additional prefix to match
606 This function will fail if the input string is longer than the
609 Type: fixedWidthString :: int -> string -> string
612 fixedWidthString 5 "0" (toString 15)
615 fixedWidthString = width: filler: str:
617 strw = lib.stringLength str;
618 reqWidth = width - (lib.stringLength filler);
620 assert lib.assertMsg (strw <= width)
621 "fixedWidthString: requested string length (${
622 toString width}) must not be shorter than actual length (${
624 if strw == width then str else filler + fixedWidthString reqWidth filler str;
626 /* Format a number adding leading zeroes up to fixed width.
629 fixedWidthNumber 5 15
632 fixedWidthNumber = width: n: fixedWidthString width "0" (toString n);
634 /* Convert a float to a string, but emit a warning when precision is lost
635 during the conversion
638 floatToString 0.000001
640 floatToString 0.0000001
641 => trace: warning: Imprecise conversion from float to string 0.000000
644 floatToString = float: let
645 result = toString float;
646 precise = float == fromJSON result;
647 in if precise then result
648 else lib.warn "Imprecise conversion from float to string ${result}" result;
650 /* Check whether a value can be coerced to a string */
651 isCoercibleToString = x:
652 elem (typeOf x) [ "path" "string" "null" "int" "float" "bool" ] ||
653 (isList x && lib.all isCoercibleToString x) ||
657 /* Check whether a value is a store path.
660 isStorePath "/nix/store/d945ibfx9x185xf04b890y4f9g3cbb63-python-2.7.11/bin/python"
662 isStorePath "/nix/store/d945ibfx9x185xf04b890y4f9g3cbb63-python-2.7.11/"
664 isStorePath pkgs.python
666 isStorePath [] || isStorePath 42 || isStorePath {} || …
670 if isCoercibleToString x then
671 let str = toString x; in
672 substring 0 1 str == "/"
673 && dirOf str == storeDir
677 /* Parse a string as an int.
687 => error: floating point JSON numbers are not supported
689 # Obviously, it is a bit hacky to use fromJSON this way.
691 let may_be_int = fromJSON str; in
694 else throw "Could not convert ${str} to int.";
696 /* Read a list of paths from `file`, relative to the `rootPath`.
697 Lines beginning with `#` are treated as comments and ignored.
698 Whitespace is significant.
700 NOTE: This function is not performant and should be avoided.
703 readPathsFromFile /prefix
704 ./pkgs/development/libraries/qt-5/5.4/qtbase/series
705 => [ "/prefix/dlopen-resolv.patch" "/prefix/tzdir.patch"
706 "/prefix/dlopen-libXcursor.patch" "/prefix/dlopen-openssl.patch"
707 "/prefix/dlopen-dbus.patch" "/prefix/xdg-config-dirs.patch"
708 "/prefix/nix-profiles-library-paths.patch"
709 "/prefix/compose-search-path.patch" ]
711 readPathsFromFile = lib.warn "lib.readPathsFromFile is deprecated, use a list instead"
714 lines = lib.splitString "\n" (readFile file);
715 removeComments = lib.filter (line: line != "" && !(lib.hasPrefix "#" line));
716 relativePaths = removeComments lines;
717 absolutePaths = map (path: rootPath + "/${path}") relativePaths;
721 /* Read the contents of a file removing the trailing \n
723 Type: fileContents :: path -> string
726 $ echo "1.0" > ./version
728 fileContents ./version
731 fileContents = file: removeSuffix "\n" (readFile file);
734 /* Creates a valid derivation name from a potentially invalid one.
736 Type: sanitizeDerivationName :: String -> String
739 sanitizeDerivationName "../hello.bar # foo"
741 sanitizeDerivationName ""
743 sanitizeDerivationName pkgs.hello
744 => "-nix-store-2g75chlbpxlrqn15zlby2dfh8hr9qwbk-hello-2.10"
746 sanitizeDerivationName = string: lib.pipe string [
747 # Get rid of string context. This is safe under the assumption that the
748 # resulting string is only used as a derivation name
749 unsafeDiscardStringContext
750 # Strip all leading "."
751 (x: elemAt (match "\\.*(.*)" x) 0)
752 # Split out all invalid characters
753 # https://github.com/NixOS/nix/blob/2.3.2/src/libstore/store-api.cc#L85-L112
754 # https://github.com/NixOS/nix/blob/2242be83c61788b9c0736a92bb0b5c7bbfc40803/nix-rust/src/store/path.rs#L100-L125
755 (split "[^[:alnum:]+._?=-]+")
756 # Replace invalid character ranges with a "-"
757 (concatMapStrings (s: if lib.isList s then "-" else s))
758 # Limit to 211 characters (minus 4 chars for ".drv")
759 (x: substring (lib.max (stringLength x - 207) 0) (-1) x)
760 # If the result is empty, replace it with "unknown"
761 (x: if stringLength x == 0 then "unknown" else x)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list