

`builtins.abort s`
------------------


 Abort Nix expression evaluation and print the error message *s*.

 
`builtins.add e1 e2`
--------------------


 Return the sum of the numbers *e1* and *e2*.

 
`builtins.all pred list`
------------------------


 Return `true` if the function *pred* returns `true` for all elements of *list*, and `false` otherwise.

 
`builtins.any pred list`
------------------------


 Return `true` if the function *pred* returns `true` for at least one element of *list*, and `false` otherwise.

 
`builtins.attrNames set`
------------------------


 Return the names of the attributes in the set *set* in an alphabetically sorted list. For instance, `builtins.attrNames { y = 1; x = "foo"; }` evaluates to `[ "x" "y" ]`.

 
`builtins.attrValues set`
-------------------------


 Return the values of the attributes in the set *set* in the order corresponding to the sorted attribute names.

 
`builtins.baseNameOf s`
-----------------------


 Return the *base name* of the string *s*, that is, everything following the final slash in the string. This is similar to the GNU `basename` command.

 
`builtins.bitAnd e1 e2`
-----------------------


 Return the bitwise AND of the integers *e1* and *e2*.

 
`builtins.bitOr e1 e2`
----------------------


 Return the bitwise OR of the integers *e1* and *e2*.

 
`builtins.bitXor e1 e2`
-----------------------


 Return the bitwise XOR of the integers *e1* and *e2*.

 
`builtins.break v`
------------------


 In debug mode (enabled using `--debugger`), pause Nix expression evaluation and enter the REPL. Otherwise, return the argument `v`.

 
`builtins.catAttrs attr list`
-----------------------------


 Collect each attribute named *attr* from a list of attribute sets. Attrsets that don't contain the named attribute are ignored. For example,

 
```
builtins.catAttrs "a" [{a = 1;} {b = 0;} {a = 2;}]

```
 evaluates to `[1 2]`.

 
`builtins.ceil double`
----------------------


 Converts an IEEE-754 double-precision floating-point number (*double*) to the next higher integer.

 If the datatype is neither an integer nor a "float", an evaluation error will be thrown.

 
`builtins.compareVersions s1 s2`
--------------------------------


 Compare two strings representing versions and return `-1` if version *s1* is older than version *s2*, `0` if they are the same, and `1` if *s1* is newer than *s2*. The version comparison algorithm is the same as the one used by [`nix-env -u`](https://nixos.org/manual/nix/stable/command-ref/nix-env.html#operation---upgrade).

 
`builtins.concatLists lists`
----------------------------


 Concatenate a list of lists into a single list.

 
`builtins.concatMap f list`
---------------------------


 This function is equivalent to `builtins.concatLists (map f list)` but is more efficient.

 
`builtins.concatStringsSep separator list`
------------------------------------------


 Concatenate a list of strings with a separator between each element, e.g. `concatStringsSep "/" ["usr" "local" "bin"] == "usr/local/bin"`.

 
`builtins.deepSeq e1 e2`
------------------------


 This is like `seq e1 e2`, except that *e1* is evaluated *deeply*: if it’s a list or set, its elements or attributes are also evaluated recursively.

 
`builtins.dirOf s`
------------------


 Return the directory part of the string *s*, that is, everything before the final slash in the string. This is similar to the GNU `dirname` command.

 
`builtins.div e1 e2`
--------------------


 Return the quotient of the numbers *e1* and *e2*.

 
`builtins.elem x xs`
--------------------


 Return `true` if a value equal to *x* occurs in the list *xs*, and `false` otherwise.

 
`builtins.elemAt xs n`
----------------------


 Return element *n* from the list *xs*. Elements are counted starting from 0. A fatal error occurs if the index is out of bounds.

 
`builtins.fetchClosure args`
----------------------------


 Fetch a Nix store closure from a binary cache, rewriting it into content-addressed form. For example,

 
```
builtins.fetchClosure {
  fromStore = "https://cache.nixos.org";
  fromPath = /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1;
  toPath = /nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1;
}

```
 fetches `/nix/store/r2jd...` from the specified binary cache, and rewrites it into the content-addressed store path `/nix/store/ldbh...`.

 If `fromPath` is already content-addressed, or if you are allowing impure evaluation (`--impure`), then `toPath` may be omitted.

 To find out the correct value for `toPath` given a `fromPath`, you can use `nix store make-content-addressed`:

 
```
# nix store make-content-addressed --from https://cache.nixos.org /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1
rewrote '/nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1' to '/nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1'

```
 This function is similar to `builtins.storePath` in that it allows you to use a previously built store path in a Nix expression. However, it is more reproducible because it requires specifying a binary cache from which the path can be fetched. Also, requiring a content-addressed final store path avoids the need for users to configure binary cache public keys.

 This function is only available if you enable the experimental feature `fetch-closure`.

 
`builtins.fetchGit args`
------------------------


 Fetch a path from git. *args* can be a URL, in which case the HEAD of the repo at that URL is fetched. Otherwise, it can be an attribute with the following attributes (all except `url` optional):

 * url  
 The URL of the repo.
* name  
 The name of the directory the repo should be exported to in the store. Defaults to the basename of the URL.
* rev  
 The git revision to fetch. Defaults to the tip of `ref`.
* ref  
 The git ref to look for the requested revision under. This is often a branch or tag name. Defaults to `HEAD`.

 By default, the `ref` value is prefixed with `refs/heads/`. As of Nix 2.3.0 Nix will not prefix `refs/heads/` if `ref` starts with `refs/`.
* submodules  
 A Boolean parameter that specifies whether submodules should be checked out. Defaults to `false`.
* shallow  
 A Boolean parameter that specifies whether fetching a shallow clone is allowed. Defaults to `false`.
* allRefs  
 Whether to fetch all refs of the repository. With this argument being true, it's possible to load a `rev` from *any* `ref` (by default only `rev`s from the specified `ref` are supported).

 Here are some examples of how to use `fetchGit`.

 * To fetch a private repository over SSH:

 
```
builtins.fetchGit {
  url = "git@github.com:my-secret/repository.git";
  ref = "master";
  rev = "adab8b916a45068c044658c4158d81878f9ed1c3";
}

```
* To fetch an arbitrary reference:

 
```
builtins.fetchGit {
  url = "https://github.com/NixOS/nix.git";
  ref = "refs/heads/0.5-release";
}

```
* If the revision you're looking for is in the default branch of the git repository you don't strictly need to specify the branch name in the `ref` attribute.

 However, if the revision you're looking for is in a future branch for the non-default branch you will need to specify the the `ref` attribute as well.

 
```
builtins.fetchGit {
  url = "https://github.com/nixos/nix.git";
  rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
  ref = "1.11-maintenance";
}

```
 
>  **Note**
> 
>  It is nice to always specify the branch which a revision belongs to. Without the branch being specified, the fetcher might fail if the default branch changes. Additionally, it can be confusing to try a commit from a non-default branch and see the fetch fail. If the branch is specified the fault is much more obvious.
> 
>
* If the revision you're looking for is in the default branch of the git repository you may omit the `ref` attribute.

 
```
builtins.fetchGit {
  url = "https://github.com/nixos/nix.git";
  rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
}

```
* To fetch a specific tag:

 
```
builtins.fetchGit {
  url = "https://github.com/nixos/nix.git";
  ref = "refs/tags/1.9";
}

```
* To fetch the latest version of a remote branch:

 
```
builtins.fetchGit {
  url = "ssh://git@github.com/nixos/nix.git";
  ref = "master";
}

```
 
>  **Note**
> 
>  Nix will refetch the branch in accordance with the option `tarball-ttl`.
> 
>  

 
>  **Note**
> 
>  This behavior is disabled in *Pure evaluation mode*.
> 
>

 
`builtins.fetchTarball args`
----------------------------


 Download the specified URL, unpack it and return the path of the unpacked tree. The file must be a tape archive (`.tar`) compressed with `gzip`, `bzip2` or `xz`. The top-level path component of the files in the tarball is removed, so it is best if the tarball contains a single directory at top level. The typical use of the function is to obtain external Nix expression dependencies, such as a particular version of Nixpkgs, e.g.

 
```
with import (fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz) {};

stdenv.mkDerivation { … }

```
 The fetched tarball is cached for a certain amount of time (1 hour by default) in `~/.cache/nix/tarballs/`. You can change the cache timeout either on the command line with `--tarball-ttl` *number-of-seconds* or in the Nix configuration file by adding the line `tarball-ttl =`  *number-of-seconds*.

 Note that when obtaining the hash with `nix-prefetch-url` the option `--unpack` is required.

 This function can also verify the contents against a hash. In that case, the function takes a set instead of a URL. The set requires the attribute `url` and the attribute `sha256`, e.g.

 
```
with import (fetchTarball {
  url = "https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz";
  sha256 = "1jppksrfvbk5ypiqdz4cddxdl8z6zyzdb2srq8fcffr327ld5jj2";
}) {};

stdenv.mkDerivation { … }

```
 This function is not available if [restricted evaluation mode](https://nixos.org/manual/nix/stable/command-ref/conf-file.html) is enabled.

 
`builtins.fetchurl url`
-----------------------


 Download the specified URL and return the path of the downloaded file. This function is not available if [restricted evaluation mode](https://nixos.org/manual/nix/stable/command-ref/conf-file.html) is enabled.

 
`builtins.filter f list`
------------------------


 Return a list consisting of the elements of *list* for which the function *f* returns `true`.

 
`builtins.filterSource e1 e2`
-----------------------------


 
>  **Warning**
> 
>  `filterSource` should not be used to filter store paths. Since `filterSource` uses the name of the input directory while naming the output directory, doing so will produce a directory name in the form of `<hash2>-<hash>-<name>`, where `<hash>-<name>` is the name of the input directory. Since `<hash>` depends on the unfiltered directory, the name of the output directory will indirectly depend on files that are filtered out by the function. This will trigger a rebuild even when a filtered out file is changed. Use `builtins.path` instead, which allows specifying the name of the output directory.
> 
>  

 This function allows you to copy sources into the Nix store while filtering certain files. For instance, suppose that you want to use the directory `source-dir` as an input to a Nix expression, e.g.

 
```
stdenv.mkDerivation {
  ...
  src = ./source-dir;
}

```
 However, if `source-dir` is a Subversion working copy, then all those annoying `.svn` subdirectories will also be copied to the store. Worse, the contents of those directories may change a lot, causing lots of spurious rebuilds. With `filterSource` you can filter out the `.svn` directories:

 
```
src = builtins.filterSource
  (path: type: type != "directory" || baseNameOf path != ".svn")
  ./source-dir;

```
 Thus, the first argument *e1* must be a predicate function that is called for each regular file, directory or symlink in the source tree *e2*. If the function returns `true`, the file is copied to the Nix store, otherwise it is omitted. The function is called with two arguments. The first is the full path of the file. The second is a string that identifies the type of the file, which is either `"regular"`, `"directory"`, `"symlink"` or `"unknown"` (for other kinds of files such as device nodes or fifos — but note that those cannot be copied to the Nix store, so if the predicate returns `true` for them, the copy will fail). If you exclude a directory, the entire corresponding subtree of *e2* will be excluded.

 
`builtins.floor double`
-----------------------


 Converts an IEEE-754 double-precision floating-point number (*double*) to the next lower integer.

 If the datatype is neither an integer nor a "float", an evaluation error will be thrown.

 
`builtins.foldl' op nul list`
-----------------------------


 Reduce a list by applying a binary operator, from left to right, e.g. `foldl' op nul [x0 x1 x2 ...] = op (op (op nul x0) x1) x2) ...`. The operator is applied strictly, i.e., its arguments are evaluated first. For example, `foldl' (x: y: x + y) 0 [1 2 3]` evaluates to 6.

 
`builtins.fromJSON e`
---------------------


 Convert a JSON string to a Nix value. For example,

 
```
builtins.fromJSON ''{"x": [1, 2, 3], "y": null}''

```
 returns the value `{ x = [ 1 2 3 ]; y = null; }`.

 
`builtins.functionArgs f`
-------------------------


 Return a set containing the names of the formal arguments expected by the function *f*. The value of each attribute is a Boolean denoting whether the corresponding argument has a default value. For instance, `functionArgs ({ x, y ? 123}: ...) = { x = false; y = true; }`.

 "Formal argument" here refers to the attributes pattern-matched by the function. Plain lambdas are not included, e.g. `functionArgs (x: ...) = { }`.

 
`builtins.genList generator length`
-----------------------------------


 Generate list of size *length*, with each element *i* equal to the value returned by *generator* `i`. For example,

 
```
builtins.genList (x: x * x) 5

```
 returns the list `[ 0 1 4 9 16 ]`.

 
`builtins.genericClosure attrset`
---------------------------------


 Take an *attrset* with values named `startSet` and `operator` in order to return a *list of attrsets* by starting with the `startSet`, recursively applying the `operator` function to each element. The *attrsets* in the `startSet` and produced by the `operator` must each contain value named `key` which are comparable to each other. The result is produced by repeatedly calling the operator for each element encountered with a unique key, terminating when no new elements are produced. For example,

 
```
builtins.genericClosure {
  startSet = [ {key = 5;} ];
  operator = item: [{
    key = if (item.key / 2 ) * 2 == item.key
         then item.key / 2
         else 3 * item.key + 1;
  }];
}

```
 evaluates to

 
```
[ { key = 5; } { key = 16; } { key = 8; } { key = 4; } { key = 2; } { key = 1; } ]

```
 
`builtins.getAttr s set`
------------------------


 `getAttr` returns the attribute named *s* from *set*. Evaluation aborts if the attribute doesn’t exist. This is a dynamic version of the `.` operator, since *s* is an expression rather than an identifier.

 
`builtins.getEnv s`
-------------------


 `getEnv` returns the value of the environment variable *s*, or an empty string if the variable doesn’t exist. This function should be used with care, as it can introduce all sorts of nasty environment dependencies in your Nix expression.

 `getEnv` is used in Nix Packages to locate the file `~/.nixpkgs/config.nix`, which contains user-local settings for Nix Packages. (That is, it does a `getEnv "HOME"` to locate the user’s home directory.)

 
`builtins.getFlake args`
------------------------


 Fetch a flake from a flake reference, and return its output attributes and some metadata. For example:

 
```
(builtins.getFlake "nix/55bc52401966fbffa525c574c14f67b00bc4fb3a").packages.x86_64-linux.nix

```
 Unless impure evaluation is allowed (`--impure`), the flake reference must be "locked", e.g. contain a Git revision or content hash. An example of an unlocked usage is:

 
```
(builtins.getFlake "github:edolstra/dwarffs").rev

```
 This function is only available if you enable the experimental feature `flakes`.

 
`builtins.groupBy f list`
-------------------------


 Groups elements of *list* together by the string returned from the function *f* called on each element. It returns an attribute set where each attribute value contains the elements of *list* that are mapped to the same corresponding attribute name returned by *f*.

 For example,

 
```
builtins.groupBy (builtins.substring 0 1) ["foo" "bar" "baz"]

```
 evaluates to

 
```
{ b = [ "bar" "baz" ]; f = [ "foo" ]; }

```
 
`builtins.hasAttr s set`
------------------------


 `hasAttr` returns `true` if *set* has an attribute named *s*, and `false` otherwise. This is a dynamic version of the `?` operator, since *s* is an expression rather than an identifier.

 
`builtins.hashFile type p`
--------------------------


 Return a base-16 representation of the cryptographic hash of the file at path *p*. The hash algorithm specified by *type* must be one of `"md5"`, `"sha1"`, `"sha256"` or `"sha512"`.

 
`builtins.hashString type s`
----------------------------


 Return a base-16 representation of the cryptographic hash of string *s*. The hash algorithm specified by *type* must be one of `"md5"`, `"sha1"`, `"sha256"` or `"sha512"`.

 
`builtins.head list`
--------------------


 Return the first element of a list; abort evaluation if the argument isn’t a list or is an empty list. You can test whether a list is empty by comparing it with `[]`.

 
`builtins.import path`
----------------------


 Load, parse and return the Nix expression in the file *path*. If *path* is a directory, the file `default.nix` in that directory is loaded. Evaluation aborts if the file doesn’t exist or contains an incorrect Nix expression. `import` implements Nix’s module system: you can put any Nix expression (such as a set or a function) in a separate file, and use it from Nix expressions in other files.

 
>  **Note**
> 
>  Unlike some languages, `import` is a regular function in Nix. Paths using the angle bracket syntax (e.g., `import` *<foo>*) are [normal path values](https://nixos.org/manual/nix/stable/expressions/language-values.html).
> 
>  

 A Nix expression loaded by `import` must not contain any *free variables* (identifiers that are not defined in the Nix expression itself and are not built-in). Therefore, it cannot refer to variables that are in scope at the call site. For instance, if you have a calling expression

 
```
rec {
  x = 123;
  y = import ./foo.nix;
}

```
 then the following `foo.nix` will give an error:

 
```
x + 456

```
 since `x` is not in scope in `foo.nix`. If you want `x` to be available in `foo.nix`, you should pass it as a function argument:

 
```
rec {
  x = 123;
  y = import ./foo.nix x;
}

```
 and

 
```
x: x + 456

```
 (The function argument doesn’t have to be called `x` in `foo.nix`; any name would work.)

 
`builtins.intersectAttrs e1 e2`
-------------------------------


 Return a set consisting of the attributes in the set *e2* that also exist in the set *e1*.

 
`builtins.isAttrs e`
--------------------


 Return `true` if *e* evaluates to a set, and `false` otherwise.

 
`builtins.isBool e`
-------------------


 Return `true` if *e* evaluates to a bool, and `false` otherwise.

 
`builtins.isFloat e`
--------------------


 Return `true` if *e* evaluates to a float, and `false` otherwise.

 
`builtins.isFunction e`
-----------------------


 Return `true` if *e* evaluates to a function, and `false` otherwise.

 
`builtins.isInt e`
------------------


 Return `true` if *e* evaluates to an integer, and `false` otherwise.

 
`builtins.isList e`
-------------------


 Return `true` if *e* evaluates to a list, and `false` otherwise.

 
`builtins.isNull e`
-------------------


 Return `true` if *e* evaluates to `null`, and `false` otherwise.

 
>  **Warning**
> 
>  This function is *deprecated*; just write `e == null` instead.
> 
>  

 
`builtins.isPath e`
-------------------


 Return `true` if *e* evaluates to a path, and `false` otherwise.

 
`builtins.isString e`
---------------------


 Return `true` if *e* evaluates to a string, and `false` otherwise.

 
`builtins.length e`
-------------------


 Return the length of the list *e*.

 
`builtins.lessThan e1 e2`
-------------------------


 Return `true` if the number *e1* is less than the number *e2*, and `false` otherwise. Evaluation aborts if either *e1* or *e2* does not evaluate to a number.

 
`builtins.listToAttrs e`
------------------------


 Construct a set from a list specifying the names and values of each attribute. Each element of the list should be a set consisting of a string-valued attribute `name` specifying the name of the attribute, and an attribute `value` specifying its value. Example:

 
```
builtins.listToAttrs
  [ { name = "foo"; value = 123; }
    { name = "bar"; value = 456; }
  ]

```
 evaluates to

 
```
{ foo = 123; bar = 456; }

```
 
`builtins.map f list`
---------------------


 Apply the function *f* to each element in the list *list*. For example,

 
```
map (x: "foo" + x) [ "bar" "bla" "abc" ]

```
 evaluates to `[ "foobar" "foobla" "fooabc" ]`.

 
`builtins.mapAttrs f attrset`
-----------------------------


 Apply function *f* to every element of *attrset*. For example,

 
```
builtins.mapAttrs (name: value: value * 10) { a = 1; b = 2; }

```
 evaluates to `{ a = 10; b = 20; }`.

 
`builtins.match regex str`
--------------------------


 Returns a list if the [extended POSIX regular expression](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04) *regex* matches *str* precisely, otherwise returns `null`. Each item in the list is a regex group.

 
```
builtins.match "ab" "abc"

```
 Evaluates to `null`.

 
```
builtins.match "abc" "abc"

```
 Evaluates to `[ ]`.

 
```
builtins.match "a(b)(c)" "abc"

```
 Evaluates to `[ "b" "c" ]`.

 
```
builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" "  FOO   "

```
 Evaluates to `[ "FOO" ]`.

 
`builtins.mul e1 e2`
--------------------


 Return the product of the numbers *e1* and *e2*.

 
`builtins.parseDrvName s`
-------------------------


 Split the string *s* into a package name and version. The package name is everything up to but not including the first dash followed by a digit, and the version is everything following that dash. The result is returned in a set `{ name, version }`. Thus, `builtins.parseDrvName "nix-0.12pre12876"` returns `{ name = "nix"; version = "0.12pre12876"; }`.

 
`builtins.partition pred list`
------------------------------


 Given a predicate function *pred*, this function returns an attrset containing a list named `right`, containing the elements in *list* for which *pred* returned `true`, and a list named `wrong`, containing the elements for which it returned `false`. For example,

 
```
builtins.partition (x: x > 10) [1 23 9 3 42]

```
 evaluates to

 
```
{ right = [ 23 42 ]; wrong = [ 1 9 3 ]; }

```
 
`builtins.path args`
--------------------


 An enrichment of the built-in path type, based on the attributes present in *args*. All are optional except `path`:

 * path  
 The underlying path.
* name  
 The name of the path when added to the store. This can used to reference paths that have nix-illegal characters in their names, like `@`.
* filter  
 A function of the type expected by `builtins.filterSource`, with the same semantics.
* recursive  
 When `false`, when `path` is added to the store it is with a flat hash, rather than a hash of the NAR serialization of the file. Thus, `path` must refer to a regular file, not a directory. This allows similar behavior to `fetchurl`. Defaults to `true`.
* sha256  
 When provided, this is the expected hash of the file at the path. Evaluation will fail if the hash is incorrect, and providing a hash allows `builtins.path` to be used even when the `pure-eval` nix config option is on.

 
`builtins.pathExists path`
--------------------------


 Return `true` if the path *path* exists at evaluation time, and `false` otherwise.

 
`builtins.placeholder output`
-----------------------------


 Return a placeholder string for the specified *output* that will be substituted by the corresponding output path at build time. Typical outputs would be `"out"`, `"bin"` or `"dev"`.

 
`builtins.readDir path`
-----------------------


 Return the contents of the directory *path* as a set mapping directory entries to the corresponding file type. For instance, if directory `A` contains a regular file `B` and another directory `C`, then `builtins.readDir ./A` will return the set

 
```
{ B = "regular"; C = "directory"; }

```
 The possible values for the file type are `"regular"`, `"directory"`, `"symlink"` and `"unknown"`.

 
`builtins.readFile path`
------------------------


 Return the contents of the file *path* as a string.

 
`builtins.removeAttrs set list`
-------------------------------


 Remove the attributes listed in *list* from *set*. The attributes don’t have to exist in *set*. For instance,

 
```
removeAttrs { x = 1; y = 2; z = 3; } [ "a" "x" "z" ]

```
 evaluates to `{ y = 2; }`.

 
`builtins.replaceStrings from to s`
-----------------------------------


 Given string *s*, replace every occurrence of the strings in *from* with the corresponding string in *to*. For example,

 
```
builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar"

```
 evaluates to `"fabir"`.

 
`builtins.seq e1 e2`
--------------------


 Evaluate *e1*, then evaluate and return *e2*. This ensures that a computation is strict in the value of *e1*.

 
`builtins.sort comparator list`
-------------------------------


 Return *list* in sorted order. It repeatedly calls the function *comparator* with two elements. The comparator should return `true` if the first element is less than the second, and `false` otherwise. For example,

 
```
builtins.sort builtins.lessThan [ 483 249 526 147 42 77 ]

```
 produces the list `[ 42 77 147 249 483 526 ]`.

 This is a stable sort: it preserves the relative order of elements deemed equal by the comparator.

 
`builtins.split regex str`
--------------------------


 Returns a list composed of non matched strings interleaved with the lists of the [extended POSIX regular expression](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04) *regex* matches of *str*. Each item in the lists of matched sequences is a regex group.

 
```
builtins.split "(a)b" "abc"

```
 Evaluates to `[ "" [ "a" ] "c" ]`.

 
```
builtins.split "([ac])" "abc"

```
 Evaluates to `[ "" [ "a" ] "b" [ "c" ] "" ]`.

 
```
builtins.split "(a)|(c)" "abc"

```
 Evaluates to `[ "" [ "a" null ] "b" [ null "c" ] "" ]`.

 
```
builtins.split "([[:upper:]]+)" " FOO "

```
 Evaluates to `[ " " [ "FOO" ] " " ]`.

 
`builtins.splitVersion s`
-------------------------


 Split a string representing a version into its components, by the same version splitting logic underlying the version comparison in [`nix-env -u`](https://nixos.org/manual/nix/stable/command-ref/nix-env.html#operation---upgrade).

 
`builtins.storePath path`
-------------------------


 This function allows you to define a dependency on an already existing store path. For example, the derivation attribute `src = builtins.storePath /nix/store/f1d18v1y…-source` causes the derivation to depend on the specified path, which must exist or be substitutable. Note that this differs from a plain path (e.g. `src = /nix/store/f1d18v1y…-source`) in that the latter causes the path to be *copied* again to the Nix store, resulting in a new path (e.g. `/nix/store/ld01dnzc…-source-source`).

 This function is not available in pure evaluation mode.

 
`builtins.stringLength e`
-------------------------


 Return the length of the string *e*. If *e* is not a string, evaluation is aborted.

 
`builtins.sub e1 e2`
--------------------


 Return the difference between the numbers *e1* and *e2*.

 
`builtins.substring start len s`
--------------------------------


 Return the substring of *s* from character position *start* (zero-based) up to but not including *start + len*. If *start* is greater than the length of the string, an empty string is returned, and if *start + len* lies beyond the end of the string, only the substring up to the end of the string is returned. *start* must be non-negative. For example,

 
```
builtins.substring 0 3 "nixos"

```
 evaluates to `"nix"`.

 
`builtins.tail list`
--------------------


 Return the second to last elements of a list; abort evaluation if the argument isn’t a list or is an empty list.

 
>  **Warning**
> 
>  This function should generally be avoided since it's inefficient: unlike Haskell's `tail`, it takes O(n) time, so recursing over a list by repeatedly calling `tail` takes O(n^2) time.
> 
>  

 
`builtins.throw s`
------------------


 Throw an error message *s*. This usually aborts Nix expression evaluation, but in `nix-env -qa` and other commands that try to evaluate a set of derivations to get information about those derivations, a derivation that throws an error is silently skipped (which is not the case for `abort`).

 
`builtins.toFile name s`
------------------------


 Store the string *s* in a file in the Nix store and return its path. The file has suffix *name*. This file can be used as an input to derivations. One application is to write builders “inline”. For instance, the following Nix expression combines the [Nix expression for GNU Hello](https://nixos.org/manual/nix/stable/expressions/expression-syntax.html) and its [build script](https://nixos.org/manual/nix/stable/expressions/build-script.html) into one file:

 
```
{ stdenv, fetchurl, perl }:

stdenv.mkDerivation {
  name = "hello-2.1.1";

  builder = builtins.toFile "builder.sh" "
    source $stdenv/setup

    PATH=$perl/bin:$PATH

    tar xvfz $src
    cd hello-*
    ./configure --prefix=$out
    make
    make install
  ";

  src = fetchurl {
    url = "http://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
    sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
  };
  inherit perl;
}

```
 It is even possible for one file to refer to another, e.g.,

 
```
builder = let
  configFile = builtins.toFile "foo.conf" "
    # This is some dummy configuration file.
    ...
  ";
in builtins.toFile "builder.sh" "
  source $stdenv/setup
  ...
  cp ${configFile} $out/etc/foo.conf
";

```
 Note that `${configFile}` is an [antiquotation](https://nixos.org/manual/nix/stable/expressions/language-values.html), so the result of the expression `configFile` (i.e., a path like `/nix/store/m7p7jfny445k...-foo.conf`) will be spliced into the resulting string.

 It is however *not* allowed to have files mutually referring to each other, like so:

 
```
let
  foo = builtins.toFile "foo" "...${bar}...";
  bar = builtins.toFile "bar" "...${foo}...";
in foo

```
 This is not allowed because it would cause a cyclic dependency in the computation of the cryptographic hashes for `foo` and `bar`.

 It is also not possible to reference the result of a derivation. If you are using Nixpkgs, the `writeTextFile` function is able to do that.

 
`builtins.toJSON e`
-------------------


 Return a string containing a JSON representation of *e*. Strings, integers, floats, booleans, nulls and lists are mapped to their JSON equivalents. Sets (except derivations) are represented as objects. Derivations are translated to a JSON string containing the derivation’s output path. Paths are copied to the store and represented as a JSON string of the resulting store path.

 
`builtins.toPath s`
-------------------


 **DEPRECATED.** Use `/. + "/path"` to convert a string into an absolute path. For relative paths, use `./. + "/path"`.

 
`builtins.toString e`
---------------------


 Convert the expression *e* to a string. *e* can be:

 * A string (in which case the string is returned unmodified).
* A path (e.g., `toString /foo/bar` yields `"/foo/bar"`.
* A set containing `{ __toString = self: ...; }` or `{ outPath = ...; }`.
* An integer.
* A list, in which case the string representations of its elements are joined with spaces.
* A Boolean (`false` yields `""`, `true` yields `"1"`).
* `null`, which yields the empty string.

 
`builtins.toXML e`
------------------


 Return a string containing an XML representation of *e*. The main application for `toXML` is to communicate information with the builder in a more structured format than plain environment variables.

 Here is an example where this is the case:

 
```
{ stdenv, fetchurl, libxslt, jira, uberwiki }:

stdenv.mkDerivation (rec {
  name = "web-server";

  buildInputs = [ libxslt ];

  builder = builtins.toFile "builder.sh" "
    source $stdenv/setup
    mkdir $out
    echo "$servlets" | xsltproc ${stylesheet} - > $out/server-conf.xml ①
  ";

  stylesheet = builtins.toFile "stylesheet.xsl" ②
   "<?xml version='1.0' encoding='UTF-8'?>
    <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
      <xsl:template match='/'>
        <Configure>
          <xsl:for-each select='/expr/list/attrs'>
            <Call name='addWebApplication'>
              <Arg><xsl:value-of select=\"attr[@name = 'path']/string/@value\" /></Arg>
              <Arg><xsl:value-of select=\"attr[@name = 'war']/path/@value\" /></Arg>
            </Call>
          </xsl:for-each>
        </Configure>
      </xsl:template>
    </xsl:stylesheet>
  ";

  servlets = builtins.toXML [ ③
    { path = "/bugtracker"; war = jira + "/lib/atlassian-jira.war"; }
    { path = "/wiki"; war = uberwiki + "/uberwiki.war"; }
  ];
})

```
 The builder is supposed to generate the configuration file for a [Jetty servlet container](http://jetty.mortbay.org/). A servlet container contains a number of servlets (`*.war` files) each exported under a specific URI prefix. So the servlet configuration is a list of sets containing the `path` and `war` of the servlet (①). This kind of information is difficult to communicate with the normal method of passing information through an environment variable, which just concatenates everything together into a string (which might just work in this case, but wouldn’t work if fields are optional or contain lists themselves). Instead the Nix expression is converted to an XML representation with `toXML`, which is unambiguous and can easily be processed with the appropriate tools. For instance, in the example an XSLT stylesheet (at point ②) is applied to it (at point ①) to generate the XML configuration file for the Jetty server. The XML representation produced at point ③ by `toXML` is as follows:

 
```
<?xml version='1.0' encoding='utf-8'?>
<expr>
  <list>
    <attrs>
      <attr name="path">
        <string value="/bugtracker" />
      </attr>
      <attr name="war">
        <path value="/nix/store/d1jh9pasa7k2...-jira/lib/atlassian-jira.war" />
      </attr>
    </attrs>
    <attrs>
      <attr name="path">
        <string value="/wiki" />
      </attr>
      <attr name="war">
        <path value="/nix/store/y6423b1yi4sx...-uberwiki/uberwiki.war" />
      </attr>
    </attrs>
  </list>
</expr>

```
 Note that we used the `toFile` built-in to write the builder and the stylesheet “inline” in the Nix expression. The path of the stylesheet is spliced into the builder using the syntax `xsltproc ${stylesheet}`.

 
`builtins.trace e1 e2`
----------------------


 Evaluate *e1* and print its abstract syntax representation on standard error. Then return *e2*. This function is useful for debugging.

 
`builtins.traceVerbose e1 e2`
-----------------------------


 Evaluate *e1* and print its abstract syntax representation on standard error if `--trace-verbose` is enabled. Then return *e2*. This function is useful for debugging.

 
`builtins.tryEval e`
--------------------


 Try to shallowly evaluate *e*. Return a set containing the attributes `success` (`true` if *e* evaluated successfully, `false` if an error was thrown) and `value`, equalling *e* if successful and `false` otherwise. `tryEval` will only prevent errors created by `throw` or `assert` from being thrown. Errors `tryEval` will not catch are for example those created by `abort` and type errors generated by builtins. Also note that this doesn't evaluate *e* deeply, so `let e = { x = throw ""; }; in (builtins.tryEval e).success` will be `true`. Using `builtins.deepSeq` one can get the expected result: `let e = { x = throw ""; }; in (builtins.tryEval (builtins.deepSeq e e)).success` will be `false`.

 
`builtins.typeOf e`
-------------------


 Return a string representing the type of the value *e*, namely `"int"`, `"bool"`, `"string"`, `"path"`, `"null"`, `"set"`, `"list"`, `"lambda"` or `"float"`.

 
`builtins.zipAttrsWith f list`
------------------------------


 Transpose a list of attribute sets into an attribute set of lists, then apply `mapAttrs`.

 `f` receives two arguments: the attribute name and a non-empty list of all values encountered for that attribute name.

 The result is an attribute set where the attribute names are the union of the attribute names in each element of `list`. The attribute values are the return values of `f`.

 
```
builtins.zipAttrsWith
  (name: values: { inherit name values; })
  [ { a = "x"; } { a = "y"; b = "z"; } ]

```
 evaluates to

 
```
{
  a = { name = "a"; values = [ "x" "y" ]; };
  b = { name = "b"; values = [ "z" ]; };
}

```
 

 © 2022 NixOS Contributors  
Licensed under the LGPL License.  

<https://nixos.org/manual/nix/stable/expressions/builtins.html>

`lib.asserts.assertMsg`
-----------------------


##### 
`assertMsg :: Bool -> String -> Bool`



 Located at [lib/asserts.nix:19](https://github.com/NixOS/nixpkgs/blob/master/lib/asserts.nix#L19) in `<nixpkgs>`. 


 Print a trace message if `pred` is false. 


 Intended to be used to augment asserts with helpful error messages. 



 `pred` 
 Condition under which the `msg` should *not* be printed. 


 `msg` 
 Message to print. 




**Example: Printing when the predicate is false**



```

assert lib.asserts.assertMsg ("foo" == "bar") "foo is not bar, silly"
stderr> trace: foo is not bar, silly
stderr> assert failed

```


  

`lib.asserts.assertOneOf`
-------------------------


##### 
`assertOneOf :: String -> String ->
 StringList -> Bool`



 Located at [lib/asserts.nix:36](https://github.com/NixOS/nixpkgs/blob/master/lib/asserts.nix#L36) in `<nixpkgs>`. 


 Specialized `asserts.assertMsg` for checking if `val` is one of the elements of `xs`. Useful for checking enums. 



 `name` 
 The name of the variable the user entered `val` into, for inclusion in the error message. 


 `val` 
 The value of what the user provided, to be compared against the values in `xs`. 


 `xs` 
 The list of valid values. 




**Example: Ensuring a user provided a possible value**



```

let sslLibrary = "bearssl";
in lib.asserts.assertOneOf "sslLibrary" sslLibrary [ "openssl" "libressl" ];
=> false
stderr> trace: sslLibrary must be one of "openssl", "libressl", but is: "bearssl"
        
```


  

`lib.attrset.attrByPath`
------------------------


##### 
`attrByPath :: [String] -> Any -> AttrSet -> Any`



 Located at [lib/attrsets.nix:24](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L24) in `<nixpkgs>`. 


 Return an attribute from within nested attribute sets. 



 `attrPath` 
 A list of strings representing the path through the nested attribute set `set`. 


 `default` 
 Default value if `attrPath` does not resolve to an existing value. 


 `set` 
 The nested attributeset to select values from. 




**Example: Extracting a value from a nested attribute set**



```

let set = { a = { b = 3; }; };
in lib.attrsets.attrByPath [ "a" "b" ] 0 set
=> 3

```


  

**Example: No value at the path, instead using the default**



```

lib.attrsets.attrByPath [ "a" "b" ] 0 {}
=> 0

```


  

`lib.attrsets.hasAttrByPath`
----------------------------


##### 
`hasAttrByPath :: [String] -> AttrSet -> Bool`



 Located at [lib/attrsets.nix:42](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L42) in `<nixpkgs>`. 


 Determine if an attribute exists within a nested attribute set. 



 `attrPath` 
 A list of strings representing the path through the nested attribute set `set`. 


 `set` 
 The nested attributeset to check. 




**Example: A nested value does exist inside a set**



```

lib.attrsets.hasAttrByPath
  [ "a" "b" "c" "d" ]
  { a = { b = { c = { d = 123; }; }; }; }
=> true

```


  

`lib.attrsets.setAttrByPath`
----------------------------


##### 
`setAttrByPath :: [String] -> Any -> AttrSet`



 Located at [lib/attrsets.nix:57](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L57) in `<nixpkgs>`. 


 Create a new attribute set with `value` set at the nested attribute location specified in `attrPath`. 



 `attrPath` 
 A list of strings representing the path through the nested attribute set. 


 `value` 
 The value to set at the location described by `attrPath`. 




**Example: Creating a new nested attribute set**



```

lib.attrsets.setAttrByPath [ "a" "b" ] 3
=> { a = { b = 3; }; }

```


  

`lib.attrsets.getAttrFromPath`
------------------------------


##### 
`getAttrFromPath :: [String] -> AttrSet -> Value`



 Located at [lib/attrsets.nix:76](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L76) in `<nixpkgs>`. 


 Like [Section 5.1.2.1, “`lib.attrset.attrByPath`”](#function-library-lib.attrsets.attrByPath "5.1.2.1. lib.attrset.attrByPath") except without a default, and it will throw if the value doesn't exist. 



 `attrPath` 
 A list of strings representing the path through the nested attribute set `set`. 


 `set` 
 The nested attribute set to find the value in. 




**Example: Succesfully getting a value from an attribute set**



```

lib.attrsets.getAttrFromPath [ "a" "b" ] { a = { b = 3; }; }
=> 3

```


  

**Example: Throwing after failing to get a value from an attribute set**



```

lib.attrsets.getAttrFromPath [ "x" "y" ] { }
=> error: cannot find attribute `x.y'

```


  

`lib.attrsets.attrVals`
-----------------------


##### 
`attrVals :: [String] -> AttrSet -> [Any]`



 Located at [lib/attrsets.nix:184](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L184) in `<nixpkgs>`. 


 Return the specified attributes from a set. All values must exist. 



 `nameList` 
 The list of attributes to fetch from `set`. Each attribute name must exist on the attrbitue set. 


 `set` 
 The set to get attribute values from. 




**Example: Getting several values from an attribute set**



```

lib.attrsets.attrVals [ "a" "b" "c" ] { a = 1; b = 2; c = 3; }
=> [ 1 2 3 ]

```


  

**Example: Getting missing values from an attribute set**



```

lib.attrsets.attrVals [ "d" ] { }
error: attribute 'd' missing

```


  

`lib.attrsets.attrValues`
-------------------------


##### 
`attrValues :: AttrSet -> [Any]`



 Located at [lib/attrsets.nix:194](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L194) in `<nixpkgs>`. 


 Get all the attribute values from an attribute set. 


 Provides a backwards-compatible interface of `builtins.attrValues` for Nix version older than 1.8. 



 `attrs` 
 The attribute set. 




**Example:** 



```

lib.attrsets.attrValues { a = 1; b = 2; c = 3; }
=> [ 1 2 3 ]

```


  

`lib.attrsets.catAttrs`
-----------------------


##### 
`catAttrs :: String -> [AttrSet] -> [Any]`



 Located at [lib/attrsets.nix:213](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L213) in `<nixpkgs>`. 


 Collect each attribute named `attr' from the list of attribute sets, `sets`. Sets that don't contain the named attribute are ignored. 


 Provides a backwards-compatible interface of `builtins.catAttrs` for Nix version older than 1.9. 



 `attr` 
 Attribute name to select from each attribute set in `sets`. 


 `sets` 
 The list of attribute sets to select `attr` from. 




**Example: Collect an attribute from a list of attribute sets.**



 Attribute sets which don't have the attribute are ignored. 



```

catAttrs "a" [{a = 1;} {b = 0;} {a = 2;}]
=> [ 1 2 ]
      
```



  

`lib.attrsets.filterAttrs`
--------------------------


##### 
`filterAttrs :: (String -> Any -> Bool) -> AttrSet -> AttrSet`



 Located at [lib/attrsets.nix:224](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L224) in `<nixpkgs>`. 


 Filter an attribute set by removing all attributes for which the given predicate return false. 



 `pred` 

 `String -> Any -> Bool` 


 Predicate which returns true to include an attribute, or returns false to exclude it. 



 `name` 
 The attribute's name 


 `value` 
 The attribute's value 



 Returns `true` to include the attribute, `false` to exclude the attribute. 



 `set` 
 The attribute set to filter 




**Example: Filtering an attributeset**



```

filterAttrs (n: v: n == "foo") { foo = 1; bar = 2; }
=> { foo = 1; }

```


  

`lib.attrsets.filterAttrsRecursive`
-----------------------------------


##### 
`filterAttrsRecursive :: (String -> Any -> Bool) -> AttrSet -> AttrSet`



 Located at [lib/attrsets.nix:235](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L235) in `<nixpkgs>`. 


 Filter an attribute set recursively by removing all attributes for which the given predicate return false. 



 `pred` 

 `String -> Any -> Bool` 


 Predicate which returns true to include an attribute, or returns false to exclude it. 



 `name` 
 The attribute's name 


 `value` 
 The attribute's value 



 Returns `true` to include the attribute, `false` to exclude the attribute. 



 `set` 
 The attribute set to filter 




**Example: Recursively filtering an attribute set**



```

lib.attrsets.filterAttrsRecursive
  (n: v: v != null)
  {
    levelA = {
      example = "hi";
      levelB = {
        hello = "there";
        this-one-is-present = {
          this-is-excluded = null;
        };
      };
      this-one-is-also-excluded = null;
    };
    also-excluded = null;
  }
=> {
     levelA = {
       example = "hi";
       levelB = {
         hello = "there";
         this-one-is-present = { };
       };
     };
   }
     
```


  

`lib.attrsets.foldAttrs`
------------------------


##### 
`foldAttrs :: (Any -> Any -> Any) -> Any -> [AttrSets] -> Any`



 Located at [lib/attrsets.nix:254](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L254) in `<nixpkgs>`. 


 Apply fold function to values grouped by key. 



 `op` 

 `Any -> Any -> Any` 


 Given a value `val` and a collector `col`, combine the two. 



 `val` 
 An attribute's value 


 `col` 
 The result of previous `op` calls with other values and `nul`. 




 `nul` 
 The null-value, the starting value. 


 `list_of_attrs` 
 A list of attribute sets to fold together by key. 




**Example: Combining an attribute of lists in to one attribute set**



```

lib.attrsets.foldAttrs
  (n: a: [n] ++ a) []
  [
    { a = 2; b = 7; }
    { a = 3; }
    { b = 6; }
  ]
=> { a = [ 2 3 ]; b = [ 7 6 ]; }

```


  

`lib.attrsets.collect`
----------------------


##### 
`collect :: (Any -> Bool) -> AttrSet -> [Any]`



 Located at [lib/attrsets.nix:278](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L278) in `<nixpkgs>`. 


 Recursively collect sets that verify a given predicate named `pred` from the set `attrs`. The recursion stops when `pred` returns `true`. 



 `pred` 

 `Any -> Bool` 


 Given an attribute's value, determine if recursion should stop. 



 `value` 
 The attribute set value. 




 `attrs` 
 The attribute set to recursively collect. 




**Example: Collecting all lists from an attribute set**



```

lib.attrsets.collect isList { a = { b = ["b"]; }; c = [1]; }
=> [["b"] [1]]

```


  

**Example: Collecting all attribute-sets which contain the outPath attribute name.**



```

collect (x: x ? outPath)
  { a = { outPath = "a/"; }; b = { outPath = "b/"; }; }
=> [{ outPath = "a/"; } { outPath = "b/"; }]

```


  

`lib.attrsets.nameValuePair`
----------------------------


##### 
`nameValuePair :: String -> Any -> AttrSet`



 Located at [lib/attrsets.nix:312](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L312) in `<nixpkgs>`. 


 Utility function that creates a `{name, value}` pair as expected by `builtins.listToAttrs`. 



 `name` 
 The attribute name. 


 `value` 
 The attribute value. 




**Example: Creating a name value pair**



```

nameValuePair "some" 6
=> { name = "some"; value = 6; }

```


  

`lib.attrsets.mapAttrs`
-----------------------



 Located at [lib/attrsets.nix:325](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L325) in `<nixpkgs>`. 


 Apply a function to each element in an attribute set, creating a new attribute set. 


 Provides a backwards-compatible interface of `builtins.mapAttrs` for Nix version older than 2.1. 



 `fn` 

 `String -> Any -> Any` 


 Given an attribute's name and value, return a new value. 



 `name` 
 The name of the attribute. 


 `value` 
 The attribute's value. 






**Example: Modifying each value of an attribute set**



```

lib.attrsets.mapAttrs
  (name: value: name + "-" + value)
  { x = "foo"; y = "bar"; }
=> { x = "x-foo"; y = "y-bar"; }

```


  

`lib.attrsets.mapAttrs'`
------------------------


##### 
`mapAttrs' :: (String -> Any -> { name = String; value = Any }) -> AttrSet -> AttrSet`



 Located at [lib/attrsets.nix:339](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L339) in `<nixpkgs>`. 


 Like `mapAttrs`, but allows the name of each attribute to be changed in addition to the value. The applied function should return both the new name and value as a `nameValuePair`. 



 `fn` 

 `String -> Any -> { name = String; value = Any }` 


 Given an attribute's name and value, return a new [name value pair](#function-library-lib.attrsets.nameValuePair "5.1.2.12. lib.attrsets.nameValuePair"). 



 `name` 
 The name of the attribute. 


 `value` 
 The attribute's value. 




 `set` 
 The attribute set to map over. 




**Example: Change the name and value of each attribute of an attribute set**



```

lib.attrsets.mapAttrs' (name: value: lib.attrsets.nameValuePair ("foo_" + name) ("bar-" + value))
   { x = "a"; y = "b"; }
=> { foo_x = "bar-a"; foo_y = "bar-b"; }

    
```


  

`lib.attrsets.mapAttrsToList`
-----------------------------


##### 
`mapAttrsToList :: (String -> Any -> Any) ->
 AttrSet -> [Any]`



 Located at [lib/attrsets.nix:355](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L355) in `<nixpkgs>`. 


 Call `fn` for each attribute in the given `set` and return the result in a list. 



 `fn` 

 `String -> Any -> Any` 


 Given an attribute's name and value, return a new value. 



 `name` 
 The name of the attribute. 


 `value` 
 The attribute's value. 




 `set` 
 The attribute set to map over. 




**Example: Combine attribute values and names in to a list**



```

lib.attrsets.mapAttrsToList (name: value: "${name}=${value}")
   { x = "a"; y = "b"; }
=> [ "x=a" "y=b" ]

```


  

`lib.attrsets.mapAttrsRecursive`
--------------------------------


##### 
`mapAttrsRecursive :: ([String] > Any -> Any) -> AttrSet -> AttrSet`



 Located at [lib/attrsets.nix:372](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L372) in `<nixpkgs>`. 


 Like `mapAttrs`, except that it recursively applies itself to attribute sets. Also, the first argument of the argument function is a *list* of the names of the containing attributes. 



 `f` 

 `[ String ] -> Any -> Any` 


 Given a list of attribute names and value, return a new value. 



 `name_path` 

 The list of attribute names to this value. 


 For example, the `name_path` for the `example` string in the attribute set `{ foo = { bar = "example"; }; }` is `[ "foo" "bar" ]`. 



 `value` 
 The attribute's value. 




 `set` 
 The attribute set to recursively map over. 




**Example: A contrived example of using lib.attrsets.mapAttrsRecursive**



```

mapAttrsRecursive
  (path: value: concatStringsSep "-" (path ++ [value]))
  {
    n = {
      a = "A";
      m = {
        b = "B";
        c = "C";
      };
    };
    d = "D";
  }
=> {
     n = {
       a = "n-a-A";
       m = {
         b = "n-m-b-B";
         c = "n-m-c-C";
       };
     };
     d = "d-D";
   }
    
```


  

`lib.attrsets.mapAttrsRecursiveCond`
------------------------------------


##### 
`mapAttrsRecursiveCond :: (AttrSet -> Bool) -> ([ String ] -> Any -> Any) -> AttrSet -> AttrSet`



 Located at [lib/attrsets.nix:393](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L393) in `<nixpkgs>`. 


 Like `mapAttrsRecursive`, but it takes an additional predicate function that tells it whether to recursive into an attribute set. If it returns false, `mapAttrsRecursiveCond` does not recurse, but does apply the map function. It is returns true, it does recurse, and does not apply the map function. 



 `cond` 

 `(AttrSet -> Bool)` 


 Determine if `mapAttrsRecursive` should recurse deeper in to the attribute set. 



 `attributeset` 
 An attribute set. 




 `f` 

 `[ String ] -> Any -> Any` 


 Given a list of attribute names and value, return a new value. 



 `name_path` 

 The list of attribute names to this value. 


 For example, the `name_path` for the `example` string in the attribute set `{ foo = { bar = "example"; }; }` is `[ "foo" "bar" ]`. 



 `value` 
 The attribute's value. 




 `set` 
 The attribute set to recursively map over. 




**Example: Only convert attribute values to JSON if the containing attribute set is marked for recursion**



```

lib.attrsets.mapAttrsRecursiveCond
  ({ recurse ? false, ... }: recurse)
  (name: value: builtins.toJSON value)
  {
    dorecur = {
      recurse = true;
      hello = "there";
    };
    dontrecur = {
      converted-to- = "json";
    };
  }
=> {
     dorecur = {
       hello = "\"there\"";
       recurse = "true";
     };
     dontrecur = "{\"converted-to\":\"json\"}";
   }
    
```


  

`lib.attrsets.genAttrs`
-----------------------


##### 
`genAttrs :: [ String ] -> (String -> Any) -> AttrSet`



 Located at [lib/attrsets.nix:413](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L413) in `<nixpkgs>`. 


 Generate an attribute set by mapping a function over a list of attribute names. 



 `names` 
 Names of values in the resulting attribute set. 


 `f` 

 `String -> Any` 


 Takes the name of the attribute and return the attribute's value. 



 `name` 
 The name of the attribute to generate a value for. 






**Example: Generate an attrset based on names only**



```

lib.attrsets.genAttrs [ "foo" "bar" ] (name: "x_${name}")
=> { foo = "x_foo"; bar = "x_bar"; }
     
```


  

`lib.attrsets.isDerivation`
---------------------------


##### 
`isDerivation :: Any -> Bool`



 Located at [lib/attrsets.nix:427](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L427) in `<nixpkgs>`. 


 Check whether the argument is a derivation. Any set with `{ type = "derivation"; }` counts as a derivation. 



 `value` 
 The value which is possibly a derivation. 




**Example: A package is a derivation**



```

lib.attrsets.isDerivation (import <nixpkgs> {}).ruby
=> true
     
```


  

**Example: Anything else is not a derivation**



```

lib.attrsets.isDerivation "foobar"
=> false
     
```


  

`lib.attrsets.toDerivation`
---------------------------


##### 
`toDerivation :: Path -> Derivation`



 Located at [lib/attrsets.nix:430](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L430) in `<nixpkgs>`. 


 Converts a store path to a fake derivation. 



 `path` 
 A store path to convert to a derivation. 



`lib.attrsets.optionalAttrs`
----------------------------


##### 
`optionalAttrs :: Bool -> AttrSet`



 Located at [lib/attrsets.nix:453](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L453) in `<nixpkgs>`. 


 Conditionally return an attribute set or an empty attribute set. 



 `cond` 
 Condition under which the `as` attribute set is returned. 


 `as` 
 The attribute set to return if `cond` is true. 




**Example: Return the provided attribute set when cond is true**



```

lib.attrsets.optionalAttrs true { my = "set"; }
=> { my = "set"; }
     
```


  

**Example: Return an empty attribute set when cond is false**



```

lib.attrsets.optionalAttrs false { my = "set"; }
=> { }
     
```


  

`lib.attrsets.zipAttrsWithNames`
--------------------------------


##### 
`zipAttrsWithNames :: [ String ] -> (String -> [ Any ] -> Any) -> [ AttrSet ] -> AttrSet`



 Located at [lib/attrsets.nix:463](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L463) in `<nixpkgs>`. 


 Merge sets of attributes and use the function `f` to merge attribute values where the attribute name is in `names`. 



 `names` 
 A list of attribute names to zip. 


 `f` 

 `(String -> [ Any ] -> Any` 


 Accepts an attribute name, all the values, and returns a combined value. 



 `name` 
 The name of the attribute each value came from. 


 `vs` 
 A list of values collected from the list of attribute sets. 




 `sets` 
 A list of attribute sets to zip together. 




**Example: Summing a list of attribute sets of numbers**



```

lib.attrsets.zipAttrsWithNames
  [ "a" "b" ]
  (name: vals: "${name} ${toString (builtins.foldl' (a: b: a + b) 0 vals)}")
  [
    { a = 1; b = 1; c = 1; }
    { a = 10; }
    { b = 100; }
    { c = 1000; }
  ]
=> { a = "a 11"; b = "b 101"; }
     
```


  

`lib.attrsets.zipAttrsWith`
---------------------------


##### 
`zipAttrsWith :: (String -> [ Any ] -> Any) -> [ AttrSet ] -> AttrSet`



 Located at [lib/attrsets.nix:478](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L478) in `<nixpkgs>`. 


 Merge sets of attributes and use the function `f` to merge attribute values. Similar to [Section 5.1.2.22, “`lib.attrsets.zipAttrsWithNames`”](#function-library-lib.attrsets.zipAttrsWithNames "5.1.2.22. lib.attrsets.zipAttrsWithNames") where all key names are passed for `names`. 



 `f` 

 `(String -> [ Any ] -> Any` 


 Accepts an attribute name, all the values, and returns a combined value. 



 `name` 
 The name of the attribute each value came from. 


 `vs` 
 A list of values collected from the list of attribute sets. 




 `sets` 
 A list of attribute sets to zip together. 




**Example: Summing a list of attribute sets of numbers**



```

lib.attrsets.zipAttrsWith
  (name: vals: "${name} ${toString (builtins.foldl' (a: b: a + b) 0 vals)}")
  [
    { a = 1; b = 1; c = 1; }
    { a = 10; }
    { b = 100; }
    { c = 1000; }
  ]
=> { a = "a 11"; b = "b 101"; c = "c 1001"; }
     
```


  

`lib.attrsets.zipAttrs`
-----------------------


##### 
`zipAttrs :: [ AttrSet ] -> AttrSet`



 Located at [lib/attrsets.nix:486](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L486) in `<nixpkgs>`. 


 Merge sets of attributes and combine each attribute value in to a list. Similar to [Section 5.1.2.23, “`lib.attrsets.zipAttrsWith`”](#function-library-lib.attrsets.zipAttrsWith "5.1.2.23. lib.attrsets.zipAttrsWith") where the merge function returns a list of all values. 



 `sets` 
 A list of attribute sets to zip together. 




**Example: Combining a list of attribute sets**



```

lib.attrsets.zipAttrs
  [
    { a = 1; b = 1; c = 1; }
    { a = 10; }
    { b = 100; }
    { c = 1000; }
  ]
=> { a = [ 1 10 ]; b = [ 1 100 ]; c = [ 1 1000 ]; }
     
```


  

`lib.attrsets.recursiveUpdateUntil`
-----------------------------------


##### 
`recursiveUpdateUntil :: ( [ String ] -> AttrSet -> AttrSet -> Bool ) -> AttrSet -> AttrSet -> AttrSet`



 Located at [lib/attrsets.nix:516](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L516) in `<nixpkgs>`. 


 Does the same as the update operator `//` except that attributes are merged until the given predicate is verified. The predicate should accept 3 arguments which are the path to reach the attribute, a part of the first attribute set and a part of the second attribute set. When the predicate is verified, the value of the first attribute set is replaced by the value of the second attribute set. 



 `pred` 

 `[ String ] -> AttrSet -> AttrSet -> Bool` 



 `path` 
 The path to the values in the left and right hand sides. 


 `l` 
 The left hand side value. 


 `r` 
 The right hand side value. 




 `lhs` 
 The left hand attribute set of the merge. 


 `rhs` 
 The right hand attribute set of the merge. 




**Example: Recursively merging two attribute sets**



```

lib.attrsets.recursiveUpdateUntil (path: l: r: path == ["foo"])
  {
    # first attribute set
    foo.bar = 1;
    foo.baz = 2;
    bar = 3;
  }
  {
    #second attribute set
    foo.bar = 1;
    foo.quz = 2;
    baz = 4;
  }
=> {
  foo.bar = 1; # 'foo.*' from the second set
  foo.quz = 2; #
  bar = 3;     # 'bar' from the first set
  baz = 4;     # 'baz' from the second set
}
     
```


  

`lib.attrsets.recursiveUpdate`
------------------------------


##### 
`recursiveUpdate :: AttrSet -> AttrSet -> AttrSet`



 Located at [lib/attrsets.nix:547](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L547) in `<nixpkgs>`. 


 A recursive variant of the update operator `//`. The recursion stops when one of the attribute values is not an attribute set, in which case the right hand side value takes precedence over the left hand side value. 



 `lhs` 
 The left hand attribute set of the merge. 


 `rhs` 
 The right hand attribute set of the merge. 




**Example: Recursively merging two attribute sets**



```

recursiveUpdate
  {
    boot.loader.grub.enable = true;
    boot.loader.grub.device = "/dev/hda";
  }
  {
    boot.loader.grub.device = "";
  }
=> {
  boot.loader.grub.enable = true;
  boot.loader.grub.device = "";
}

```


  

`lib.attrsets.recurseIntoAttrs`
-------------------------------


##### 
`recurseIntoAttrs :: AttrSet -> AttrSet`



 Located at [lib/attrsets.nix:617](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L617) in `<nixpkgs>`. 


 Make various Nix tools consider the contents of the resulting attribute set when looking for what to build, find, etc. 


 This function only affects a single attribute set; it does not apply itself recursively for nested attribute sets. 



 `attrs` 
 An attribute set to scan for derivations. 




**Example: Making Nix look inside an attribute set**



```

{ pkgs ? import <nixpkgs> {} }:
{
  myTools = pkgs.lib.recurseIntoAttrs {
    inherit (pkgs) hello figlet;
  };
}

```


  

`lib.attrsets.cartesianProductOfSets`
-------------------------------------


##### 
`cartesianProductOfSets :: AttrSet -> [ AttrSet ]`



 Located at [lib/attrsets.nix:297](https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix#L297) in `<nixpkgs>`. 


 Return the cartesian product of attribute set value combinations. 



 `set` 
 An attribute set with attributes that carry lists of values. 




**Example: Creating the cartesian product of a list of attribute values**



```

cartesianProductOfSets { a = [ 1 2 ]; b = [ 10 20 ]; }
=> [
     { a = 1; b = 10; }
     { a = 1; b = 20; }
     { a = 2; b = 10; }
     { a = 2; b = 20; }
   ]

```


  

`lib.strings.concatStrings`
---------------------------


##### 
`concatStrings :: [string] -> string`



 Concatenate a list of strings. 



**Example: lib.strings.concatStrings usage example**



```

concatStrings ["foo" "bar"]
=> "foobar"

```


  
 Located at [lib/strings.nix:44](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L44) in `<nixpkgs>`. 


`lib.strings.concatMapStrings`
------------------------------


##### 
`concatMapStrings :: (a -> string) -> [a] -> string`



 Map a function over a list and concatenate the resulting strings. 



 `f` 
 Function argument 


 `list` 
 Function argument 




**Example: lib.strings.concatMapStrings usage example**



```

concatMapStrings (x: "a" + x) ["foo" "bar"]
=> "afooabar"

```


  
 Located at [lib/strings.nix:54](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L54) in `<nixpkgs>`. 


`lib.strings.concatImapStrings`
-------------------------------


##### 
`concatImapStrings :: (int -> a -> string) -> [a] -> string`



 Like `concatMapStrings` except that the f functions also gets the position as a parameter. 



 `f` 
 Function argument 


 `list` 
 Function argument 




**Example: lib.strings.concatImapStrings usage example**



```

concatImapStrings (pos: x: "${toString pos}-${x}") ["foo" "bar"]
=> "1-foo2-bar"

```


  
 Located at [lib/strings.nix:65](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L65) in `<nixpkgs>`. 


`lib.strings.intersperse`
-------------------------


##### 
`intersperse :: a -> [a] -> [a]`



 Place an element between each element of a list 



 `separator` 
 Separator to add between elements 


 `list` 
 Input list 




**Example: lib.strings.intersperse usage example**



```

intersperse "/" ["usr" "local" "bin"]
=> ["usr" "/" "local" "/" "bin"].

```


  
 Located at [lib/strings.nix:75](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L75) in `<nixpkgs>`. 


`lib.strings.concatStringsSep`
------------------------------


##### 
`concatStringsSep :: string -> [string] -> string`



 Concatenate a list of strings with a separator between each element 



**Example: lib.strings.concatStringsSep usage example**



```

concatStringsSep "/" ["usr" "local" "bin"]
=> "usr/local/bin"

```


  
 Located at [lib/strings.nix:92](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L92) in `<nixpkgs>`. 


`lib.strings.concatMapStringsSep`
---------------------------------


##### 
`concatMapStringsSep :: string -> (a -> string) -> [a] -> string`



 Maps a function over a list of strings and then concatenates the result with the specified separator interspersed between elements. 



 `sep` 
 Separator to add between elements 


 `f` 
 Function to map over the list 


 `list` 
 List of input strings 




**Example: lib.strings.concatMapStringsSep usage example**



```

concatMapStringsSep "-" (x: toUpper x)  ["foo" "bar" "baz"]
=> "FOO-BAR-BAZ"

```


  
 Located at [lib/strings.nix:105](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L105) in `<nixpkgs>`. 


`lib.strings.concatImapStringsSep`
----------------------------------


##### 
`concatIMapStringsSep :: string -> (int -> a -> string) -> [a] -> string`



 Same as `concatMapStringsSep`, but the mapping function additionally receives the position of its argument. 



 `sep` 
 Separator to add between elements 


 `f` 
 Function that receives elements and their positions 


 `list` 
 List of input strings 




**Example: lib.strings.concatImapStringsSep usage example**



```

concatImapStringsSep "-" (pos: x: toString (x / pos)) [ 6 6 6 ]
=> "6-3-2"

```


  
 Located at [lib/strings.nix:122](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L122) in `<nixpkgs>`. 


`lib.strings.makeSearchPath`
----------------------------


##### 
`makeSearchPath :: string -> [string] -> string`



 Construct a Unix-style, colon-separated search path consisting of the given `subDir` appended to each of the given paths. 



 `subDir` 
 Directory name to append 


 `paths` 
 List of base paths 




**Example: lib.strings.makeSearchPath usage example**



```

makeSearchPath "bin" ["/root" "/usr" "/usr/local"]
=> "/root/bin:/usr/bin:/usr/local/bin"
makeSearchPath "bin" [""]
=> "/bin"

```


  
 Located at [lib/strings.nix:141](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L141) in `<nixpkgs>`. 


`lib.strings.makeSearchPathOutput`
----------------------------------


##### 
`string -> string -> [package] -> string`



 Construct a Unix-style search path by appending the given `subDir` to the specified `output` of each of the packages. If no output by the given name is found, fallback to `.out` and then to the default. 



 `output` 
 Package output to use 


 `subDir` 
 Directory name to append 


 `pkgs` 
 List of packages 




**Example: lib.strings.makeSearchPathOutput usage example**



```

makeSearchPathOutput "dev" "bin" [ pkgs.openssl pkgs.zlib ]
=> "/nix/store/9rz8gxhzf8sw4kf2j2f1grr49w8zx5vj-openssl-1.0.1r-dev/bin:/nix/store/wwh7mhwh269sfjkm6k5665b5kgp7jrk2-zlib-1.2.8/bin"

```


  
 Located at [lib/strings.nix:159](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L159) in `<nixpkgs>`. 

`lib.strings.makeLibraryPath`
-----------------------------


 Construct a library search path (such as RPATH) containing the libraries for a set of packages 



**Example: lib.strings.makeLibraryPath usage example**



```

makeLibraryPath [ "/usr" "/usr/local" ]
=> "/usr/lib:/usr/local/lib"
pkgs = import <nixpkgs> { }
makeLibraryPath [ pkgs.openssl pkgs.zlib ]
=> "/nix/store/9rz8gxhzf8sw4kf2j2f1grr49w8zx5vj-openssl-1.0.1r/lib:/nix/store/wwh7mhwh269sfjkm6k5665b5kgp7jrk2-zlib-1.2.8/lib"

```


  
 Located at [lib/strings.nix:177](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L177) in `<nixpkgs>`. 

`lib.strings.makeBinPath`
-------------------------


 Construct a binary search path (such as $PATH) containing the binaries for a set of packages. 



**Example: lib.strings.makeBinPath usage example**



```

makeBinPath ["/root" "/usr" "/usr/local"]
=> "/root/bin:/usr/bin:/usr/local/bin"

```


  
 Located at [lib/strings.nix:186](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L186) in `<nixpkgs>`. 


`lib.strings.optionalString`
----------------------------


##### 
`optionalString :: bool -> string -> string`



 Depending on the boolean `cond', return either the given string or the empty string. Useful to concatenate against a bigger string. 



 `cond` 
 Condition 


 `string` 
 String to return if condition is true 




**Example: lib.strings.optionalString usage example**



```

optionalString true "some-string"
=> "some-string"
optionalString false "some-string"
=> ""

```


  
 Located at [lib/strings.nix:199](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L199) in `<nixpkgs>`. 


`lib.strings.hasPrefix`
-----------------------


##### 
`hasPrefix :: string -> string -> bool`



 Determine whether a string has given prefix. 



 `pref` 
 Prefix to check for 


 `str` 
 Input string 




**Example: lib.strings.hasPrefix usage example**



```

hasPrefix "foo" "foobar"
=> true
hasPrefix "foo" "barfoo"
=> false

```


  
 Located at [lib/strings.nix:215](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L215) in `<nixpkgs>`. 


`lib.strings.hasSuffix`
-----------------------


##### 
`hasSuffix :: string -> string -> bool`



 Determine whether a string has given suffix. 



 `suffix` 
 Suffix to check for 


 `content` 
 Input string 




**Example: lib.strings.hasSuffix usage example**



```

hasSuffix "foo" "foobar"
=> false
hasSuffix "foo" "barfoo"
=> true

```


  
 Located at [lib/strings.nix:231](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L231) in `<nixpkgs>`. 


`lib.strings.hasInfix`
----------------------


##### 
`hasInfix :: string -> string -> bool`



 Determine whether a string contains the given infix 



 `infix` 
 Function argument 


 `content` 
 Function argument 




**Example: lib.strings.hasInfix usage example**



```

hasInfix "bc" "abcd"
=> true
hasInfix "ab" "abcd"
=> true
hasInfix "cd" "abcd"
=> true
hasInfix "foo" "abcd"
=> false

```


  
 Located at [lib/strings.nix:256](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L256) in `<nixpkgs>`. 


`lib.strings.stringToCharacters`
--------------------------------


##### 
`stringToCharacters :: string -> [string]`



 Convert a string to a list of characters (i.e. singleton strings). This allows you to, e.g., map a function over each character. However, note that this will likely be horribly inefficient; Nix is not a general purpose programming language. Complex string manipulations should, if appropriate, be done in a derivation. Also note that Nix treats strings as a list of bytes and thus doesn't handle unicode. 



 `s` 
 Function argument 




**Example: lib.strings.stringToCharacters usage example**



```

stringToCharacters ""
=> [ ]
stringToCharacters "abc"
=> [ "a" "b" "c" ]
stringToCharacters "💩"
=> [ "�" "�" "�" "�" ]

```


  
 Located at [lib/strings.nix:277](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L277) in `<nixpkgs>`. 


`lib.strings.stringAsChars`
---------------------------


##### 
`stringAsChars :: (string -> string) -> string -> string`



 Manipulate a string character by character and replace them by strings before concatenating the results. 



 `f` 
 Function to map over each individual character 


 `s` 
 Input string 




**Example: lib.strings.stringAsChars usage example**



```

stringAsChars (x: if x == "a" then "i" else x) "nax"
=> "nix"

```


  
 Located at [lib/strings.nix:289](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L289) in `<nixpkgs>`. 


`lib.strings.escape`
--------------------


##### 
`escape :: [string] -> string -> string`



 Escape occurrence of the elements of `list` in `string` by prefixing it with a backslash. 



 `list` 
 Function argument 




**Example: lib.strings.escape usage example**



```

escape ["(" ")"] "(foo)"
=> "\\(foo\\)"

```


  
 Located at [lib/strings.nix:306](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L306) in `<nixpkgs>`. 


`lib.strings.escapeShellArg`
----------------------------


##### 
`escapeShellArg :: string -> string`



 Quote string to be used safely within the Bourne shell. 



 `arg` 
 Function argument 




**Example: lib.strings.escapeShellArg usage example**



```

escapeShellArg "esc'ape\nme"
=> "'esc'\\''ape\nme'"

```


  
 Located at [lib/strings.nix:316](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L316) in `<nixpkgs>`. 


`lib.strings.escapeShellArgs`
-----------------------------


##### 
`escapeShellArgs :: [string] -> string`



 Quote all arguments to be safely passed to the Bourne shell. 



**Example: lib.strings.escapeShellArgs usage example**



```

escapeShellArgs ["one" "two three" "four'five"]
=> "'one' 'two three' 'four'\\''five'"

```


  
 Located at [lib/strings.nix:326](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L326) in `<nixpkgs>`. 


`lib.strings.isValidPosixName`
------------------------------


##### 
`string -> bool`



 Test whether the given name is a valid POSIX shell variable name. 



 `name` 
 Function argument 




**Example: lib.strings.isValidPosixName usage example**



```

isValidPosixName "foo_bar000"
=> true
isValidPosixName "0-bad.jpg"
=> false

```


  
 Located at [lib/strings.nix:338](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L338) in `<nixpkgs>`. 


`lib.strings.toShellVar`
------------------------


##### 
`string -> (string | listOf string | attrsOf string) -> string`



 Translate a Nix value into a shell variable declaration, with proper escaping. 


 The value can be a string (mapped to a regular variable), a list of strings (mapped to a Bash-style array) or an attribute set of strings (mapped to a Bash-style associative array). Note that "string" includes string-coercible values like paths or derivations. 


 Strings are translated into POSIX sh-compatible code; lists and attribute sets assume a shell that understands Bash syntax (e.g. Bash or ZSH). 



 `name` 
 Function argument 


 `value` 
 Function argument 




**Example: lib.strings.toShellVar usage example**



```

''
${toShellVar "foo" "some string"}
[[ "$foo" == "some string" ]]
''

```


  
 Located at [lib/strings.nix:358](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L358) in `<nixpkgs>`. 


`lib.strings.toShellVars`
-------------------------


##### 
`attrsOf (string | listOf string | attrsOf string) -> string`



 Translate an attribute set into corresponding shell variable declarations using `toShellVar`. 



 `vars` 
 Function argument 




**Example: lib.strings.toShellVars usage example**



```

let
foo = "value";
bar = foo;
in ''
${toShellVars { inherit foo bar; }}
[[ "$foo" == "$bar" ]]
''

```


  
 Located at [lib/strings.nix:386](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L386) in `<nixpkgs>`. 


`lib.strings.escapeNixString`
-----------------------------


##### 
`string -> string`



 Turn a string into a Nix expression representing that string 



 `s` 
 Function argument 




**Example: lib.strings.escapeNixString usage example**



```

escapeNixString "hello\${}\n"
=> "\"hello\\\${}\\n\""

```


  
 Located at [lib/strings.nix:396](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L396) in `<nixpkgs>`. 


`lib.strings.escapeRegex`
-------------------------


##### 
`string -> string`



 Turn a string into an exact regular expression 



**Example: lib.strings.escapeRegex usage example**



```

escapeRegex "[^a-z]*"
=> "\\[\\^a-z]\\*"

```


  
 Located at [lib/strings.nix:406](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L406) in `<nixpkgs>`. 


`lib.strings.escapeNixIdentifier`
---------------------------------


##### 
`string -> string`



 Quotes a string if it can't be used as an identifier directly. 



 `s` 
 Function argument 




**Example: lib.strings.escapeNixIdentifier usage example**



```

escapeNixIdentifier "hello"
=> "hello"
escapeNixIdentifier "0abc"
=> "\"0abc\""

```


  
 Located at [lib/strings.nix:418](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L418) in `<nixpkgs>`. 


`lib.strings.escapeXML`
-----------------------


##### 
`string -> string`



 Escapes a string such that it is safe to include verbatim in an XML document. 



**Example: lib.strings.escapeXML usage example**



```

escapeXML ''"test" 'test' < & >''
=> "&quot;test&quot; &apos;test&apos; &lt; &amp; &gt;"

```


  
 Located at [lib/strings.nix:432](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L432) in `<nixpkgs>`. 


`lib.strings.toLower`
---------------------


##### 
`toLower :: string -> string`



 Converts an ASCII string to lower-case. 



**Example: lib.strings.toLower usage example**



```

toLower "HOME"
=> "home"

```


  
 Located at [lib/strings.nix:462](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L462) in `<nixpkgs>`. 


`lib.strings.toUpper`
---------------------


##### 
`toUpper :: string -> string`



 Converts an ASCII string to upper-case. 



**Example: lib.strings.toUpper usage example**



```

toUpper "home"
=> "HOME"

```


  
 Located at [lib/strings.nix:472](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L472) in `<nixpkgs>`. 

`lib.strings.addContextFrom`
----------------------------


 Appends string context from another string. This is an implementation detail of Nix. 


 Strings in Nix carry an invisible `context` which is a list of strings representing store paths. If the string is later used in a derivation attribute, the derivation will properly populate the inputDrvs and inputSrcs. 



 `a` 
 Function argument 


 `b` 
 Function argument 




**Example: lib.strings.addContextFrom usage example**



```

pkgs = import <nixpkgs> { };
addContextFrom pkgs.coreutils "bar"
=> "bar"

```


  
 Located at [lib/strings.nix:487](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L487) in `<nixpkgs>`. 

`lib.strings.splitString`
-------------------------


 Cut a string with a separator and produces a list of strings which were separated by this separator. 



 `_sep` 
 Function argument 


 `_s` 
 Function argument 




**Example: lib.strings.splitString usage example**



```

splitString "." "foo.bar.baz"
=> [ "foo" "bar" "baz" ]
splitString "/" "/usr/local/bin"
=> [ "" "usr" "local" "bin" ]

```


  
 Located at [lib/strings.nix:498](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L498) in `<nixpkgs>`. 


`lib.strings.removePrefix`
--------------------------


##### 
`string -> string -> string`



 Return a string without the specified prefix, if the prefix matches. 



 `prefix` 
 Prefix to remove if it matches 


 `str` 
 Input string 




**Example: lib.strings.removePrefix usage example**



```

removePrefix "foo." "foo.bar.baz"
=> "bar.baz"
removePrefix "xxx" "foo.bar.baz"
=> "foo.bar.baz"

```


  
 Located at [lib/strings.nix:516](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L516) in `<nixpkgs>`. 


`lib.strings.removeSuffix`
--------------------------


##### 
`string -> string -> string`



 Return a string without the specified suffix, if the suffix matches. 



 `suffix` 
 Suffix to remove if it matches 


 `str` 
 Input string 




**Example: lib.strings.removeSuffix usage example**



```

removeSuffix "front" "homefront"
=> "home"
removeSuffix "xxx" "homefront"
=> "homefront"

```


  
 Located at [lib/strings.nix:540](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L540) in `<nixpkgs>`. 

`lib.strings.versionOlder`
--------------------------


 Return true if string v1 denotes a version older than v2. 



 `v1` 
 Function argument 


 `v2` 
 Function argument 




**Example: lib.strings.versionOlder usage example**



```

versionOlder "1.1" "1.2"
=> true
versionOlder "1.1" "1.1"
=> false

```


  
 Located at [lib/strings.nix:562](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L562) in `<nixpkgs>`. 

`lib.strings.versionAtLeast`
----------------------------


 Return true if string v1 denotes a version equal to or newer than v2. 



 `v1` 
 Function argument 


 `v2` 
 Function argument 




**Example: lib.strings.versionAtLeast usage example**



```

versionAtLeast "1.1" "1.0"
=> true
versionAtLeast "1.1" "1.1"
=> true
versionAtLeast "1.1" "1.2"
=> false

```


  
 Located at [lib/strings.nix:574](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L574) in `<nixpkgs>`. 

`lib.strings.getName`
---------------------


 This function takes an argument that's either a derivation or a derivation's "name" attribute and extracts the name part from that argument. 



 `x` 
 Function argument 




**Example: lib.strings.getName usage example**



```

getName "youtube-dl-2016.01.01"
=> "youtube-dl"
getName pkgs.youtube-dl
=> "youtube-dl"

```


  
 Located at [lib/strings.nix:586](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L586) in `<nixpkgs>`. 

`lib.strings.getVersion`
------------------------


 This function takes an argument that's either a derivation or a derivation's "name" attribute and extracts the version part from that argument. 



 `x` 
 Function argument 




**Example: lib.strings.getVersion usage example**



```

getVersion "youtube-dl-2016.01.01"
=> "2016.01.01"
getVersion pkgs.youtube-dl
=> "2016.01.01"

```


  
 Located at [lib/strings.nix:603](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L603) in `<nixpkgs>`. 

`lib.strings.nameFromURL`
-------------------------


 Extract name with version from URL. Ask for separator which is supposed to start extension. 



 `url` 
 Function argument 


 `sep` 
 Function argument 




**Example: lib.strings.nameFromURL usage example**



```

nameFromURL "https://nixos.org/releases/nix/nix-1.7/nix-1.7-x86_64-linux.tar.bz2" "-"
=> "nix"
nameFromURL "https://nixos.org/releases/nix/nix-1.7/nix-1.7-x86_64-linux.tar.bz2" "_"
=> "nix-1.7-x86"

```


  
 Located at [lib/strings.nix:619](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L619) in `<nixpkgs>`. 

`lib.strings.enableFeature`
---------------------------


 Create an --{enable,disable}-<feat> string that can be passed to standard GNU Autoconf scripts. 



 `enable` 
 Function argument 


 `feat` 
 Function argument 




**Example: lib.strings.enableFeature usage example**



```

enableFeature true "shared"
=> "--enable-shared"
enableFeature false "shared"
=> "--disable-shared"

```


  
 Located at [lib/strings.nix:635](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L635) in `<nixpkgs>`. 

`lib.strings.enableFeatureAs`
-----------------------------


 Create an --{enable-<feat>=<value>,disable-<feat>} string that can be passed to standard GNU Autoconf scripts. 



 `enable` 
 Function argument 


 `feat` 
 Function argument 


 `value` 
 Function argument 




**Example: lib.strings.enableFeatureAs usage example**



```

enableFeatureAs true "shared" "foo"
=> "--enable-shared=foo"
enableFeatureAs false "shared" (throw "ignored")
=> "--disable-shared"

```


  
 Located at [lib/strings.nix:648](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L648) in `<nixpkgs>`. 

`lib.strings.withFeature`
-------------------------


 Create an --{with,without}-<feat> string that can be passed to standard GNU Autoconf scripts. 



 `with_` 
 Function argument 


 `feat` 
 Function argument 




**Example: lib.strings.withFeature usage example**



```

withFeature true "shared"
=> "--with-shared"
withFeature false "shared"
=> "--without-shared"

```


  
 Located at [lib/strings.nix:659](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L659) in `<nixpkgs>`. 

`lib.strings.withFeatureAs`
---------------------------


 Create an --{with-<feat>=<value>,without-<feat>} string that can be passed to standard GNU Autoconf scripts. 



 `with_` 
 Function argument 


 `feat` 
 Function argument 


 `value` 
 Function argument 




**Example: lib.strings.withFeatureAs usage example**



```

withFeatureAs true "shared" "foo"
=> "--with-shared=foo"
withFeatureAs false "shared" (throw "ignored")
=> "--without-shared"

```


  
 Located at [lib/strings.nix:672](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L672) in `<nixpkgs>`. 


`lib.strings.fixedWidthString`
------------------------------


##### 
`fixedWidthString :: int -> string -> string -> string`



 Create a fixed width string with additional prefix to match required width. 


 This function will fail if the input string is longer than the requested length. 



 `width` 
 Function argument 


 `filler` 
 Function argument 


 `str` 
 Function argument 




**Example: lib.strings.fixedWidthString usage example**



```

fixedWidthString 5 "0" (toString 15)
=> "00015"

```


  
 Located at [lib/strings.nix:686](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L686) in `<nixpkgs>`. 

`lib.strings.fixedWidthNumber`
------------------------------


 Format a number adding leading zeroes up to fixed width. 



 `width` 
 Function argument 


 `n` 
 Function argument 




**Example: lib.strings.fixedWidthNumber usage example**



```

fixedWidthNumber 5 15
=> "00015"

```


  
 Located at [lib/strings.nix:703](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L703) in `<nixpkgs>`. 

`lib.strings.floatToString`
---------------------------


 Convert a float to a string, but emit a warning when precision is lost during the conversion 



 `float` 
 Function argument 




**Example: lib.strings.floatToString usage example**



```

floatToString 0.000001
=> "0.000001"
floatToString 0.0000001
=> trace: warning: Imprecise conversion from float to string 0.000000
"0.000000"

```


  
 Located at [lib/strings.nix:715](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L715) in `<nixpkgs>`. 

`lib.strings.isCoercibleToString`
---------------------------------


 Check whether a value can be coerced to a string 



 `x` 
 Function argument 



 Located at [lib/strings.nix:722](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L722) in `<nixpkgs>`. 

`lib.strings.isStorePath`
-------------------------


 Check whether a value is a store path. 



 `x` 
 Function argument 




**Example: lib.strings.isStorePath usage example**



```

isStorePath "/nix/store/d945ibfx9x185xf04b890y4f9g3cbb63-python-2.7.11/bin/python"
=> false
isStorePath "/nix/store/d945ibfx9x185xf04b890y4f9g3cbb63-python-2.7.11"
=> true
isStorePath pkgs.python
=> true
isStorePath [] || isStorePath 42 || isStorePath {} || …
=> false

```


  
 Located at [lib/strings.nix:740](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L740) in `<nixpkgs>`. 


`lib.strings.toInt`
-------------------


##### 
`string -> int`



 Parse a string as an int. 



 `str` 
 Function argument 




**Example: lib.strings.toInt usage example**



```

toInt "1337"
=> 1337
toInt "-4"
=> -4
toInt "3.14"
=> error: floating point JSON numbers are not supported

```


  
 Located at [lib/strings.nix:761](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L761) in `<nixpkgs>`. 

`lib.strings.readPathsFromFile`
-------------------------------


 Read a list of paths from `file`, relative to the `rootPath`. Lines beginning with `#` are treated as comments and ignored. Whitespace is significant. 


 NOTE: This function is not performant and should be avoided. 



**Example: lib.strings.readPathsFromFile usage example**



```

readPathsFromFile /prefix
./pkgs/development/libraries/qt-5/5.4/qtbase/series
=> [ "/prefix/dlopen-resolv.patch" "/prefix/tzdir.patch"
"/prefix/dlopen-libXcursor.patch" "/prefix/dlopen-openssl.patch"
"/prefix/dlopen-dbus.patch" "/prefix/xdg-config-dirs.patch"
"/prefix/nix-profiles-library-paths.patch"
"/prefix/compose-search-path.patch" ]

```


  
 Located at [lib/strings.nix:782](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L782) in `<nixpkgs>`. 


`lib.strings.fileContents`
--------------------------


##### 
`fileContents :: path -> string`



 Read the contents of a file removing the trailing \n 



 `file` 
 Function argument 




**Example: lib.strings.fileContents usage example**



```

$ echo "1.0" > ./version

fileContents ./version
=> "1.0"

```


  
 Located at [lib/strings.nix:802](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L802) in `<nixpkgs>`. 


`lib.strings.sanitizeDerivationName`
------------------------------------


##### 
`sanitizeDerivationName :: String -> String`



 Creates a valid derivation name from a potentially invalid one. 



**Example: lib.strings.sanitizeDerivationName usage example**



```

sanitizeDerivationName "../hello.bar # foo"
=> "-hello.bar-foo"
sanitizeDerivationName ""
=> "unknown"
sanitizeDerivationName pkgs.hello
=> "-nix-store-2g75chlbpxlrqn15zlby2dfh8hr9qwbk-hello-2.10"

```


  
 Located at [lib/strings.nix:817](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L817) in `<nixpkgs>`. 


`lib.strings.levenshtein`
-------------------------


##### 
`levenshtein :: string -> string -> int`



 Computes the Levenshtein distance between two strings. Complexity O(n\*m) where n and m are the lengths of the strings. Algorithm adjusted from https://stackoverflow.com/a/9750974/6605742 



 `a` 
 Function argument 


 `b` 
 Function argument 




**Example: lib.strings.levenshtein usage example**



```

levenshtein "foo" "foo"
=> 0
levenshtein "book" "hook"
=> 1
levenshtein "hello" "Heyo"
=> 3

```


  
 Located at [lib/strings.nix:856](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L856) in `<nixpkgs>`. 

`lib.strings.commonPrefixLength`
--------------------------------


 Returns the length of the prefix common to both strings. 



 `a` 
 Function argument 


 `b` 
 Function argument 



 Located at [lib/strings.nix:877](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L877) in `<nixpkgs>`. 

`lib.strings.commonSuffixLength`
--------------------------------


 Returns the length of the suffix common to both strings. 



 `a` 
 Function argument 


 `b` 
 Function argument 



 Located at [lib/strings.nix:885](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L885) in `<nixpkgs>`. 


`lib.strings.levenshteinAtMost`
-------------------------------


##### 
`levenshteinAtMost :: int -> string -> string -> bool`



 Returns whether the levenshtein distance between two strings is at most some value Complexity is O(min(n,m)) for k <= 2 and O(n\*m) otherwise 



**Example: lib.strings.levenshteinAtMost usage example**



```

levenshteinAtMost 0 "foo" "foo"
=> true
levenshteinAtMost 1 "foo" "boa"
=> false
levenshteinAtMost 2 "foo" "boa"
=> true
levenshteinAtMost 2 "This is a sentence" "this is a sentense."
=> false
levenshteinAtMost 3 "This is a sentence" "this is a sentense."
=> true

```


  
 Located at [lib/strings.nix:909](https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix#L909) in `<nixpkgs>`. 


`lib.trivial.id`
----------------


##### 
`id :: a -> a`



 The identity function For when you need a function that does “nothing”. 



 `x` 
 The value to return 



 Located at [lib/trivial.nix:12](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L12) in `<nixpkgs>`. 


`lib.trivial.const`
-------------------


##### 
`const :: a -> b -> a`



 The constant function 


 Ignores the second argument. If called with only one argument, constructs a function that always returns a static value. 



 `x` 
 Value to return 


 `y` 
 Value to ignore 




**Example: lib.trivial.const usage example**



```

let f = const 5; in f 10
=> 5

```


  
 Located at [lib/trivial.nix:26](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L26) in `<nixpkgs>`. 


`lib.trivial.pipe`
------------------


##### 
`pipe :: a -> [<functions>] -> <return type of last function>`



 Pipes a value through a list of functions, left to right. 



 `val` 
 Function argument 


 `functions` 
 Function argument 




**Example: lib.trivial.pipe usage example**



```

pipe 2 [
(x: x + 2)  # 2 + 2 = 4
(x: x * 2)  # 4 * 2 = 8
]
=> 8

# ideal to do text transformations
pipe [ "a/b" "a/c" ] [

# create the cp command
(map (file: ''cp "${src}/${file}" $out\n''))

# concatenate all commands into one string
lib.concatStrings

# make that string into a nix derivation
(pkgs.runCommand "copy-to-out" {})

]
=> <drv which copies all files to $out>

The output type of each function has to be the input type
of the next function, and the last function returns the
final value.

```


  
 Located at [lib/trivial.nix:61](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L61) in `<nixpkgs>`. 


`lib.trivial.concat`
--------------------


##### 
`concat :: [a] -> [a] -> [a]`



 Concatenate two lists 



 `x` 
 Function argument 


 `y` 
 Function argument 




**Example: lib.trivial.concat usage example**



```

concat [ 1 2 ] [ 3 4 ]
=> [ 1 2 3 4 ]

```


  
 Located at [lib/trivial.nix:80](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L80) in `<nixpkgs>`. 

`lib.trivial.or`
----------------


 boolean “or” 



 `x` 
 Function argument 


 `y` 
 Function argument 



 Located at [lib/trivial.nix:83](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L83) in `<nixpkgs>`. 

`lib.trivial.and`
-----------------


 boolean “and” 



 `x` 
 Function argument 


 `y` 
 Function argument 



 Located at [lib/trivial.nix:86](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L86) in `<nixpkgs>`. 

`lib.trivial.bitAnd`
--------------------


 bitwise “and” 


 Located at [lib/trivial.nix:89](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L89) in `<nixpkgs>`. 

`lib.trivial.bitOr`
-------------------


 bitwise “or” 


 Located at [lib/trivial.nix:94](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L94) in `<nixpkgs>`. 

`lib.trivial.bitXor`
--------------------


 bitwise “xor” 


 Located at [lib/trivial.nix:99](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L99) in `<nixpkgs>`. 

`lib.trivial.bitNot`
--------------------


 bitwise “not” 


 Located at [lib/trivial.nix:104](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L104) in `<nixpkgs>`. 


`lib.trivial.boolToString`
--------------------------


##### 
`boolToString :: bool -> string`



 Convert a boolean to a string. 


 This function uses the strings "true" and "false" to represent boolean values. Calling `toString` on a bool instead returns "1" and "" (sic!). 



 `b` 
 Function argument 



 Located at [lib/trivial.nix:114](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L114) in `<nixpkgs>`. 

`lib.trivial.mergeAttrs`
------------------------


 Merge two attribute sets shallowly, right side trumps left 


 mergeAttrs :: attrs -> attrs -> attrs 



 `x` 
 Left attribute set 


 `y` 
 Right attribute set (higher precedence for equal keys) 




**Example: lib.trivial.mergeAttrs usage example**



```

mergeAttrs { a = 1; b = 2; } { b = 3; c = 4; }
=> { a = 1; b = 3; c = 4; }

```


  
 Located at [lib/trivial.nix:124](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L124) in `<nixpkgs>`. 


`lib.trivial.flip`
------------------


##### 
`flip :: (a -> b -> c) -> (b -> a -> c)`



 Flip the order of the arguments of a binary function. 



 `f` 
 Function argument 


 `a` 
 Function argument 


 `b` 
 Function argument 




**Example: lib.trivial.flip usage example**



```

flip concat [1] [2]
=> [ 2 1 ]

```


  
 Located at [lib/trivial.nix:138](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L138) in `<nixpkgs>`. 

`lib.trivial.mapNullable`
-------------------------


 Apply function if the supplied argument is non-null. 



 `f` 
 Function to call 


 `a` 
 Argument to check for null before passing it to `f` 




**Example: lib.trivial.mapNullable usage example**



```

mapNullable (x: x+1) null
=> null
mapNullable (x: x+1) 22
=> 23

```


  
 Located at [lib/trivial.nix:148](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L148) in `<nixpkgs>`. 

`lib.trivial.version`
---------------------


 Returns the current full nixpkgs version number. 


 Located at [lib/trivial.nix:164](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L164) in `<nixpkgs>`. 

`lib.trivial.release`
---------------------


 Returns the current nixpkgs release number as string. 


 Located at [lib/trivial.nix:167](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L167) in `<nixpkgs>`. 

`lib.trivial.oldestSupportedRelease`
------------------------------------


 The latest release that is supported, at the time of release branch-off, if applicable. 


 Ideally, out-of-tree modules should be able to evaluate cleanly with all supported Nixpkgs versions (master, release and old release until EOL). So if possible, deprecation warnings should take effect only when all out-of-tree expressions/libs/modules can upgrade to the new way without losing support for supported Nixpkgs versions. 


 This release number allows deprecation warnings to be implemented such that they take effect as soon as the oldest release reaches end of life. 


 Located at [lib/trivial.nix:180](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L180) in `<nixpkgs>`. 

`lib.trivial.isInOldestRelease`
-------------------------------


 Whether a feature is supported in all supported releases (at the time of release branch-off, if applicable). See `oldestSupportedRelease`. 



 `release` 
 Release number of feature introduction as an integer, e.g. 2111 for 21.11. Set it to the upcoming release, matching the nixpkgs/.version file. 



 Located at [lib/trivial.nix:186](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L186) in `<nixpkgs>`. 

`lib.trivial.codeName`
----------------------


 Returns the current nixpkgs release code name. 


 On each release the first letter is bumped and a new animal is chosen starting with that new letter. 


 Located at [lib/trivial.nix:198](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L198) in `<nixpkgs>`. 

`lib.trivial.versionSuffix`
---------------------------


 Returns the current nixpkgs version suffix as string. 


 Located at [lib/trivial.nix:201](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L201) in `<nixpkgs>`. 


`lib.trivial.revisionWithDefault`
---------------------------------


##### 
`revisionWithDefault :: string -> string`



 Attempts to return the the current revision of nixpkgs and returns the supplied default value otherwise. 



 `default` 
 Default value to return if revision can not be determined 



 Located at [lib/trivial.nix:212](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L212) in `<nixpkgs>`. 


`lib.trivial.inNixShell`
------------------------


##### 
`inNixShell :: bool`



 Determine whether the function is being called from inside a Nix shell. 


 Located at [lib/trivial.nix:230](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L230) in `<nixpkgs>`. 

`lib.trivial.min`
-----------------


 Return minimum of two numbers. 



 `x` 
 Function argument 


 `y` 
 Function argument 



 Located at [lib/trivial.nix:236](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L236) in `<nixpkgs>`. 

`lib.trivial.max`
-----------------


 Return maximum of two numbers. 



 `x` 
 Function argument 


 `y` 
 Function argument 



 Located at [lib/trivial.nix:239](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L239) in `<nixpkgs>`. 

`lib.trivial.mod`
-----------------


 Integer modulus 



 `base` 
 Function argument 


 `int` 
 Function argument 




**Example: lib.trivial.mod usage example**



```

mod 11 10
=> 1
mod 1 10
=> 1

```


  
 Located at [lib/trivial.nix:249](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L249) in `<nixpkgs>`. 

`lib.trivial.compare`
---------------------


 C-style comparisons 


 a < b, compare a b => -1 a == b, compare a b => 0 a > b, compare a b => 1 



 `a` 
 Function argument 


 `b` 
 Function argument 



 Located at [lib/trivial.nix:260](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L260) in `<nixpkgs>`. 


`lib.trivial.splitByAndCompare`
-------------------------------


##### 
`(a -> bool) -> (a -> a -> int) -> (a -> a -> int) -> (a -> a -> int)`



 Split type into two subtypes by predicate `p`, take all elements of the first subtype to be less than all the elements of the second subtype, compare elements of a single subtype with `yes` and `no` respectively. 



 `p` 
 Predicate 


 `yes` 
 Comparison function if predicate holds for both values 


 `no` 
 Comparison function if predicate holds for neither value 


 `a` 
 First value to compare 


 `b` 
 Second value to compare 




**Example: lib.trivial.splitByAndCompare usage example**



```

let cmp = splitByAndCompare (hasPrefix "foo") compare compare; in

cmp "a" "z" => -1
cmp "fooa" "fooz" => -1

cmp "f" "a" => 1
cmp "fooa" "a" => -1
# while
compare "fooa" "a" => 1

```


  
 Located at [lib/trivial.nix:285](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L285) in `<nixpkgs>`. 

`lib.trivial.importJSON`
------------------------


 Reads a JSON file. 


 Type :: path -> any 



 `path` 
 Function argument 



 Located at [lib/trivial.nix:305](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L305) in `<nixpkgs>`. 

`lib.trivial.importTOML`
------------------------


 Reads a TOML file. 


 Type :: path -> any 



 `path` 
 Function argument 



 Located at [lib/trivial.nix:312](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L312) in `<nixpkgs>`. 


`lib.trivial.warn`
------------------


##### 
`string -> a -> a`



 Print a warning before returning the second argument. This function behaves like `builtins.trace`, but requires a string message and formats it as a warning, including the `warning: ` prefix. 


 To get a call stack trace and abort evaluation, set the environment variable `NIX\_ABORT\_ON\_WARN=true` and set the Nix options `--option pure-eval false --show-trace` 


 Located at [lib/trivial.nix:340](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L340) in `<nixpkgs>`. 


`lib.trivial.warnIf`
--------------------


##### 
`bool -> string -> a -> a`



 Like warn, but only warn when the first argument is `true`. 



 `cond` 
 Function argument 


 `msg` 
 Function argument 



 Located at [lib/trivial.nix:350](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L350) in `<nixpkgs>`. 


`lib.trivial.warnIfNot`
-----------------------


##### 
`bool -> string -> a -> a`



 Like warnIf, but negated (warn if the first argument is `false`). 



 `cond` 
 Function argument 


 `msg` 
 Function argument 



 Located at [lib/trivial.nix:357](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L357) in `<nixpkgs>`. 


`lib.trivial.throwIfNot`
------------------------


##### 
`bool -> string -> a -> a`



 Like the `assert b; e` expression, but with a custom error message and without the semicolon. 


 If true, return the identity function, `r: r`. 


 If false, throw the error message. 


 Calls can be juxtaposed using function application, as `(r: r) a = a`, so `(r: r) (r: r) a = a`, and so forth. 



 `cond` 
 Function argument 


 `msg` 
 Function argument 




**Example: lib.trivial.throwIfNot usage example**



```


throwIfNot (lib.isList overlays) "The overlays argument to nixpkgs must be a list."
lib.foldr (x: throwIfNot (lib.isFunction x) "All overlays passed to nixpkgs must be functions.") (r: r) overlays
pkgs

```


  
 Located at [lib/trivial.nix:379](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L379) in `<nixpkgs>`. 


`lib.trivial.throwIf`
---------------------


##### 
`bool -> string -> a -> a`



 Like throwIfNot, but negated (throw if the first argument is `true`). 



 `cond` 
 Function argument 


 `msg` 
 Function argument 



 Located at [lib/trivial.nix:386](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L386) in `<nixpkgs>`. 


`lib.trivial.checkListOfEnum`
-----------------------------


##### 
`String -> List ComparableVal -> List ComparableVal -> a -> a`



 Check if the elements in a list are valid values from a enum, returning the identity function, or throwing an error message otherwise. 



 `msg` 
 Function argument 


 `valid` 
 Function argument 


 `given` 
 Function argument 




**Example: lib.trivial.checkListOfEnum usage example**



```

let colorVariants = ["bright" "dark" "black"]
in checkListOfEnum "color variants" [ "standard" "light" "dark" ] colorVariants;
=>
error: color variants: bright, black unexpected; valid ones: standard, light, dark


```


  
 Located at [lib/trivial.nix:398](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L398) in `<nixpkgs>`. 

`lib.trivial.setFunctionArgs`
-----------------------------


 Add metadata about expected function arguments to a function. The metadata should match the format given by builtins.functionArgs, i.e. a set from expected argument to a bool representing whether that argument has a default or not. setFunctionArgs : (a → b) → Map String Bool → (a → b) 


 This function is necessary because you can't dynamically create a function of the { a, b ? foo, ... }: format, but some facilities like callPackage expect to be able to query expected arguments. 



 `f` 
 Function argument 


 `args` 
 Function argument 



 Located at [lib/trivial.nix:421](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L421) in `<nixpkgs>`. 

`lib.trivial.functionArgs`
--------------------------


 Extract the expected function arguments from a function. This works both with nix-native { a, b ? foo, ... }: style functions and functions with args set with 'setFunctionArgs'. It has the same return type and semantics as builtins.functionArgs. setFunctionArgs : (a → b) → Map String Bool. 



 `f` 
 Function argument 



 Located at [lib/trivial.nix:433](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L433) in `<nixpkgs>`. 

`lib.trivial.isFunction`
------------------------


 Check whether something is a function or something annotated with function args. 



 `f` 
 Function argument 



 Located at [lib/trivial.nix:441](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L441) in `<nixpkgs>`. 

`lib.trivial.toFunction`
------------------------


 Turns any non-callable values into constant functions. Returns callable values as is. 



 `v` 
 Any value 




**Example: lib.trivial.toFunction usage example**



```


nix-repl> lib.toFunction 1 2
1

nix-repl> lib.toFunction (x: x + 1) 2
3

```


  
 Located at [lib/trivial.nix:456](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L456) in `<nixpkgs>`. 

`lib.trivial.toHexString`
-------------------------


 Convert the given positive integer to a string of its hexadecimal representation. For example: 


 toHexString 0 => "0" 


 toHexString 16 => "10" 


 toHexString 250 => "FA" 



 `i` 
 Function argument 



 Located at [lib/trivial.nix:472](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L472) in `<nixpkgs>`. 

`lib.trivial.toBaseDigits`
--------------------------


 `toBaseDigits base i` converts the positive integer i to a list of its digits in the given base. For example: 


 toBaseDigits 10 123 => [ 1 2 3 ] 


 toBaseDigits 2 6 => [ 1 1 0 ] 


 toBaseDigits 16 250 => [ 15 10 ] 



 `base` 
 Function argument 


 `i` 
 Function argument 



 Located at [lib/trivial.nix:498](https://github.com/NixOS/nixpkgs/blob/master/lib/trivial.nix#L498) in `<nixpkgs>`. 


`lib.lists.singleton`
---------------------


##### 
`singleton :: a -> [a]`



 Create a list consisting of a single element. `singleton x` is sometimes more convenient with respect to indentation than `[x]` when x spans multiple lines. 



 `x` 
 Function argument 




**Example: lib.lists.singleton usage example**



```

singleton "foo"
=> [ "foo" ]

```


  
 Located at [lib/lists.nix:23](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L23) in `<nixpkgs>`. 


`lib.lists.forEach`
-------------------


##### 
`forEach :: [a] -> (a -> b) -> [b]`



 Apply the function to each element in the list. Same as `map`, but arguments flipped. 



 `xs` 
 Function argument 


 `f` 
 Function argument 




**Example: lib.lists.forEach usage example**



```

forEach [ 1 2 ] (x:
toString x
)
=> [ "1" "2" ]

```


  
 Located at [lib/lists.nix:36](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L36) in `<nixpkgs>`. 


`lib.lists.foldr`
-----------------


##### 
`foldr :: (a -> b -> b) -> b -> [a] -> b`



 “right fold” a binary function `op` between successive elements of `list` with `nul' as the starting value, i.e., `foldr op nul [x\_1 x\_2 ... x\_n] == op x\_1 (op x\_2 ... (op x\_n nul))`. 



 `op` 
 Function argument 


 `nul` 
 Function argument 


 `list` 
 Function argument 




**Example: lib.lists.foldr usage example**



```

concat = foldr (a: b: a + b) "z"
concat [ "a" "b" "c" ]
=> "abcz"
# different types
strange = foldr (int: str: toString (int + 1) + str) "a"
strange [ 1 2 3 4 ]
=> "2345a"

```


  
 Located at [lib/lists.nix:53](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L53) in `<nixpkgs>`. 

`lib.lists.fold`
----------------


 `fold` is an alias of `foldr` for historic reasons 


 Located at [lib/lists.nix:64](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L64) in `<nixpkgs>`. 


`lib.lists.foldl`
-----------------


##### 
`foldl :: (b -> a -> b) -> b -> [a] -> b`



 “left fold”, like `foldr`, but from the left: `foldl op nul [x\_1 x\_2 ... x\_n] == op (... (op (op nul x\_1) x\_2) ... x\_n)`. 



 `op` 
 Function argument 


 `nul` 
 Function argument 


 `list` 
 Function argument 




**Example: lib.lists.foldl usage example**



```

lconcat = foldl (a: b: a + b) "z"
lconcat [ "a" "b" "c" ]
=> "zabc"
# different types
lstrange = foldl (str: int: str + toString (int + 1)) "a"
lstrange [ 1 2 3 4 ]
=> "a2345"

```


  
 Located at [lib/lists.nix:81](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L81) in `<nixpkgs>`. 


`lib.lists.foldl'`
------------------


##### 
`foldl' :: (b -> a -> b) -> b -> [a] -> b`



 Strict version of `foldl`. 


 The difference is that evaluation is forced upon access. Usually used with small whole results (in contrast with lazily-generated list or large lists where only a part is consumed.) 


 Located at [lib/lists.nix:97](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L97) in `<nixpkgs>`. 


`lib.lists.imap0`
-----------------


##### 
`imap0 :: (int -> a -> b) -> [a] -> [b]`



 Map with index starting from 0 



 `f` 
 Function argument 


 `list` 
 Function argument 




**Example: lib.lists.imap0 usage example**



```

imap0 (i: v: "${v}-${toString i}") ["a" "b"]
=> [ "a-0" "b-1" ]

```


  
 Located at [lib/lists.nix:107](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L107) in `<nixpkgs>`. 


`lib.lists.imap1`
-----------------


##### 
`imap1 :: (int -> a -> b) -> [a] -> [b]`



 Map with index starting from 1 



 `f` 
 Function argument 


 `list` 
 Function argument 




**Example: lib.lists.imap1 usage example**



```

imap1 (i: v: "${v}-${toString i}") ["a" "b"]
=> [ "a-1" "b-2" ]

```


  
 Located at [lib/lists.nix:117](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L117) in `<nixpkgs>`. 


`lib.lists.concatMap`
---------------------


##### 
`concatMap :: (a -> [b]) -> [a] -> [b]`



 Map and concatenate the result. 



**Example: lib.lists.concatMap usage example**



```

concatMap (x: [x] ++ ["z"]) ["a" "b"]
=> [ "a" "z" "b" "z" ]

```


  
 Located at [lib/lists.nix:127](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L127) in `<nixpkgs>`. 

`lib.lists.flatten`
-------------------


 Flatten the argument into a single list; that is, nested lists are spliced into the top-level lists. 



 `x` 
 Function argument 




**Example: lib.lists.flatten usage example**



```

flatten [1 [2 [3] 4] 5]
=> [1 2 3 4 5]
flatten 1
=> [1]

```


  
 Located at [lib/lists.nix:138](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L138) in `<nixpkgs>`. 


`lib.lists.remove`
------------------


##### 
`remove :: a -> [a] -> [a]`



 Remove elements equal to 'e' from a list. Useful for buildInputs. 



 `e` 
 Element to remove from the list 




**Example: lib.lists.remove usage example**



```

remove 3 [ 1 3 4 3 ]
=> [ 1 4 ]

```


  
 Located at [lib/lists.nix:151](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L151) in `<nixpkgs>`. 


`lib.lists.findSingle`
----------------------


##### 
`findSingle :: (a -> bool) -> a -> a -> [a] -> a`



 Find the sole element in the list matching the specified predicate, returns `default` if no such element exists, or `multiple` if there are multiple matching elements. 



 `pred` 
 Predicate 


 `default` 
 Default value to return if element was not found. 


 `multiple` 
 Default value to return if more than one element was found 


 `list` 
 Input list 




**Example: lib.lists.findSingle usage example**



```

findSingle (x: x == 3) "none" "multiple" [ 1 3 3 ]
=> "multiple"
findSingle (x: x == 3) "none" "multiple" [ 1 3 ]
=> 3
findSingle (x: x == 3) "none" "multiple" [ 1 9 ]
=> "none"

```


  
 Located at [lib/lists.nix:169](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L169) in `<nixpkgs>`. 


`lib.lists.findFirst`
---------------------


##### 
`findFirst :: (a -> bool) -> a -> [a] -> a`



 Find the first element in the list matching the specified predicate or return `default` if no such element exists. 



 `pred` 
 Predicate 


 `default` 
 Default value to return 


 `list` 
 Input list 




**Example: lib.lists.findFirst usage example**



```

findFirst (x: x > 3) 7 [ 1 6 4 ]
=> 6
findFirst (x: x > 9) 7 [ 1 6 4 ]
=> 7

```


  
 Located at [lib/lists.nix:194](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L194) in `<nixpkgs>`. 


`lib.lists.any`
---------------


##### 
`any :: (a -> bool) -> [a] -> bool`



 Return true if function `pred` returns true for at least one element of `list`. 



**Example: lib.lists.any usage example**



```

any isString [ 1 "a" { } ]
=> true
any isString [ 1 { } ]
=> false

```


  
 Located at [lib/lists.nix:215](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L215) in `<nixpkgs>`. 


`lib.lists.all`
---------------


##### 
`all :: (a -> bool) -> [a] -> bool`



 Return true if function `pred` returns true for all elements of `list`. 



**Example: lib.lists.all usage example**



```

all (x: x < 3) [ 1 2 ]
=> true
all (x: x < 3) [ 1 2 3 ]
=> false

```


  
 Located at [lib/lists.nix:228](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L228) in `<nixpkgs>`. 


`lib.lists.count`
-----------------


##### 
`count :: (a -> bool) -> [a] -> int`



 Count how many elements of `list` match the supplied predicate function. 



 `pred` 
 Predicate 




**Example: lib.lists.count usage example**



```

count (x: x == 3) [ 3 2 3 4 6 ]
=> 2

```


  
 Located at [lib/lists.nix:239](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L239) in `<nixpkgs>`. 


`lib.lists.optional`
--------------------


##### 
`optional :: bool -> a -> [a]`



 Return a singleton list or an empty list, depending on a boolean value. Useful when building lists with optional elements (e.g. `++ optional (system == "i686-linux") firefox'). 



 `cond` 
 Function argument 


 `elem` 
 Function argument 




**Example: lib.lists.optional usage example**



```

optional true "foo"
=> [ "foo" ]
optional false "foo"
=> [ ]

```


  
 Located at [lib/lists.nix:255](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L255) in `<nixpkgs>`. 


`lib.lists.optionals`
---------------------


##### 
`optionals :: bool -> [a] -> [a]`



 Return a list or an empty list, depending on a boolean value. 



 `cond` 
 Condition 


 `elems` 
 List to return if condition is true 




**Example: lib.lists.optionals usage example**



```

optionals true [ 2 3 ]
=> [ 2 3 ]
optionals false [ 2 3 ]
=> [ ]

```


  
 Located at [lib/lists.nix:267](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L267) in `<nixpkgs>`. 

`lib.lists.toList`
------------------


 If argument is a list, return it; else, wrap it in a singleton list. If you're using this, you should almost certainly reconsider if there isn't a more "well-typed" approach. 



 `x` 
 Function argument 




**Example: lib.lists.toList usage example**



```

toList [ 1 2 ]
=> [ 1 2 ]
toList "hi"
=> [ "hi "]

```


  
 Located at [lib/lists.nix:284](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L284) in `<nixpkgs>`. 


`lib.lists.range`
-----------------


##### 
`range :: int -> int -> [int]`



 Return a list of integers from `first' up to and including `last'. 



 `first` 
 First integer in the range 


 `last` 
 Last integer in the range 




**Example: lib.lists.range usage example**



```

range 2 4
=> [ 2 3 4 ]
range 3 2
=> [ ]

```


  
 Located at [lib/lists.nix:296](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L296) in `<nixpkgs>`. 


`lib.lists.partition`
---------------------


##### 
`(a -> bool) -> [a] -> { right :: [a], wrong :: [a] }`



 Splits the elements of a list in two lists, `right` and `wrong`, depending on the evaluation of a predicate. 



**Example: lib.lists.partition usage example**



```

partition (x: x > 2) [ 5 1 2 3 4 ]
=> { right = [ 5 3 4 ]; wrong = [ 1 2 ]; }

```


  
 Located at [lib/lists.nix:315](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L315) in `<nixpkgs>`. 

`lib.lists.groupBy'`
--------------------


 Splits the elements of a list into many lists, using the return value of a predicate. Predicate should return a string which becomes keys of attrset `groupBy' returns. 


 `groupBy'` allows to customise the combining function and initial value 



 `op` 
 Function argument 


 `nul` 
 Function argument 


 `pred` 
 Function argument 


 `lst` 
 Function argument 




**Example: lib.lists.groupBy' usage example**



```

groupBy (x: boolToString (x > 2)) [ 5 1 2 3 4 ]
=> { true = [ 5 3 4 ]; false = [ 1 2 ]; }
groupBy (x: x.name) [ {name = "icewm"; script = "icewm &";}
{name = "xfce";  script = "xfce4-session &";}
{name = "icewm"; script = "icewmbg &";}
{name = "mate";  script = "gnome-session &";}
]
=> { icewm = [ { name = "icewm"; script = "icewm &"; }
{ name = "icewm"; script = "icewmbg &"; } ];
mate  = [ { name = "mate";  script = "gnome-session &"; } ];
xfce  = [ { name = "xfce";  script = "xfce4-session &"; } ];
}

groupBy' builtins.add 0 (x: boolToString (x > 2)) [ 5 1 2 3 4 ]
=> { true = 12; false = 3; }

```


  
 Located at [lib/lists.nix:344](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L344) in `<nixpkgs>`. 


`lib.lists.zipListsWith`
------------------------


##### 
`zipListsWith :: (a -> b -> c) -> [a] -> [b] -> [c]`



 Merges two lists of the same size together. If the sizes aren't the same the merging stops at the shortest. How both lists are merged is defined by the first argument. 



 `f` 
 Function to zip elements of both lists 


 `fst` 
 First list 


 `snd` 
 Second list 




**Example: lib.lists.zipListsWith usage example**



```

zipListsWith (a: b: a + b) ["h" "l"] ["e" "o"]
=> ["he" "lo"]

```


  
 Located at [lib/lists.nix:364](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L364) in `<nixpkgs>`. 


`lib.lists.zipLists`
--------------------


##### 
`zipLists :: [a] -> [b] -> [{ fst :: a, snd :: b}]`



 Merges two lists of the same size together. If the sizes aren't the same the merging stops at the shortest. 



**Example: lib.lists.zipLists usage example**



```

zipLists [ 1 2 ] [ "a" "b" ]
=> [ { fst = 1; snd = "a"; } { fst = 2; snd = "b"; } ]

```


  
 Located at [lib/lists.nix:383](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L383) in `<nixpkgs>`. 


`lib.lists.reverseList`
-----------------------


##### 
`reverseList :: [a] -> [a]`



 Reverse the order of the elements of a list. 



 `xs` 
 Function argument 




**Example: lib.lists.reverseList usage example**



```


reverseList [ "b" "o" "j" ]
=> [ "j" "o" "b" ]

```


  
 Located at [lib/lists.nix:394](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L394) in `<nixpkgs>`. 

`lib.lists.listDfs`
-------------------


 Depth-First Search (DFS) for lists `list != []`. 


 `before a b == true` means that `b` depends on `a` (there's an edge from `b` to `a`). 



 `stopOnCycles` 
 Function argument 


 `before` 
 Function argument 


 `list` 
 Function argument 




**Example: lib.lists.listDfs usage example**



```

listDfs true hasPrefix [ "/home/user" "other" "/" "/home" ]
== { minimal = "/";                  # minimal element
visited = [ "/home/user" ];     # seen elements (in reverse order)
rest    = [ "/home" "other" ];  # everything else
}

listDfs true hasPrefix [ "/home/user" "other" "/" "/home" "/" ]
== { cycle   = "/";                  # cycle encountered at this element
loops   = [ "/" ];              # and continues to these elements
visited = [ "/" "/home/user" ]; # elements leading to the cycle (in reverse order)
rest    = [ "/home" "other" ];  # everything else

```


  
 Located at [lib/lists.nix:416](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L416) in `<nixpkgs>`. 

`lib.lists.toposort`
--------------------


 Sort a list based on a partial ordering using DFS. This implementation is O(N^2), if your ordering is linear, use `sort` instead. 


 `before a b == true` means that `b` should be after `a` in the result. 



 `before` 
 Function argument 


 `list` 
 Function argument 




**Example: lib.lists.toposort usage example**



```


toposort hasPrefix [ "/home/user" "other" "/" "/home" ]
== { result = [ "/" "/home" "/home/user" "other" ]; }

toposort hasPrefix [ "/home/user" "other" "/" "/home" "/" ]
== { cycle = [ "/home/user" "/" "/" ]; # path leading to a cycle
loops = [ "/" ]; }                # loops back to these elements

toposort hasPrefix [ "other" "/home/user" "/home" "/" ]
== { result = [ "other" "/" "/home" "/home/user" ]; }

toposort (a: b: a < b) [ 3 2 1 ] == { result = [ 1 2 3 ]; }

```


  
 Located at [lib/lists.nix:455](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L455) in `<nixpkgs>`. 

`lib.lists.sort`
----------------


 Sort a list based on a comparator function which compares two elements and returns true if the first argument is strictly below the second argument. The returned list is sorted in an increasing order. The implementation does a quick-sort. 



**Example: lib.lists.sort usage example**



```

sort (a: b: a < b) [ 5 3 7 ]
=> [ 3 5 7 ]

```


  
 Located at [lib/lists.nix:483](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L483) in `<nixpkgs>`. 

`lib.lists.compareLists`
------------------------


 Compare two lists element-by-element. 



 `cmp` 
 Function argument 


 `a` 
 Function argument 


 `b` 
 Function argument 




**Example: lib.lists.compareLists usage example**



```

compareLists compare [] []
=> 0
compareLists compare [] [ "a" ]
=> -1
compareLists compare [ "a" ] []
=> 1
compareLists compare [ "a" "b" ] [ "a" "c" ]
=> 1

```


  
 Located at [lib/lists.nix:512](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L512) in `<nixpkgs>`. 

`lib.lists.naturalSort`
-----------------------


 Sort list using "Natural sorting". Numeric portions of strings are sorted in numeric order. 



 `lst` 
 Function argument 




**Example: lib.lists.naturalSort usage example**



```

naturalSort ["disk11" "disk8" "disk100" "disk9"]
=> ["disk8" "disk9" "disk11" "disk100"]
naturalSort ["10.46.133.149" "10.5.16.62" "10.54.16.25"]
=> ["10.5.16.62" "10.46.133.149" "10.54.16.25"]
naturalSort ["v0.2" "v0.15" "v0.0.9"]
=> [ "v0.0.9" "v0.2" "v0.15" ]

```


  
 Located at [lib/lists.nix:535](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L535) in `<nixpkgs>`. 


`lib.lists.take`
----------------


##### 
`take :: int -> [a] -> [a]`



 Return the first (at most) N elements of a list. 



 `count` 
 Number of elements to take 




**Example: lib.lists.take usage example**



```

take 2 [ "a" "b" "c" "d" ]
=> [ "a" "b" ]
take 2 [ ]
=> [ ]

```


  
 Located at [lib/lists.nix:553](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L553) in `<nixpkgs>`. 


`lib.lists.drop`
----------------


##### 
`drop :: int -> [a] -> [a]`



 Remove the first (at most) N elements of a list. 



 `count` 
 Number of elements to drop 


 `list` 
 Input list 




**Example: lib.lists.drop usage example**



```

drop 2 [ "a" "b" "c" "d" ]
=> [ "c" "d" ]
drop 2 [ ]
=> [ ]

```


  
 Located at [lib/lists.nix:567](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L567) in `<nixpkgs>`. 


`lib.lists.sublist`
-------------------


##### 
`sublist :: int -> int -> [a] -> [a]`



 Return a list consisting of at most `count` elements of `list`, starting at index `start`. 



 `start` 
 Index at which to start the sublist 


 `count` 
 Number of elements to take 


 `list` 
 Input list 




**Example: lib.lists.sublist usage example**



```

sublist 1 3 [ "a" "b" "c" "d" "e" ]
=> [ "b" "c" "d" ]
sublist 1 3 [ ]
=> [ ]

```


  
 Located at [lib/lists.nix:584](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L584) in `<nixpkgs>`. 


`lib.lists.last`
----------------


##### 
`last :: [a] -> a`



 Return the last element of a list. 


 This function throws an error if the list is empty. 



 `list` 
 Function argument 




**Example: lib.lists.last usage example**



```

last [ 1 2 3 ]
=> 3

```


  
 Located at [lib/lists.nix:608](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L608) in `<nixpkgs>`. 


`lib.lists.init`
----------------


##### 
`init :: [a] -> [a]`



 Return all elements but the last. 


 This function throws an error if the list is empty. 



 `list` 
 Function argument 




**Example: lib.lists.init usage example**



```

init [ 1 2 3 ]
=> [ 1 2 ]

```


  
 Located at [lib/lists.nix:622](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L622) in `<nixpkgs>`. 

`lib.lists.crossLists`
----------------------


 Return the image of the cross product of some lists by a function. 



**Example: lib.lists.crossLists usage example**



```

crossLists (x:y: "${toString x}${toString y}") [[1 2] [3 4]]
=> [ "13" "14" "23" "24" ]

```


  
 Located at [lib/lists.nix:633](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L633) in `<nixpkgs>`. 


`lib.lists.unique`
------------------


##### 
`unique :: [a] -> [a]`



 Remove duplicate elements from the list. O(n^2) complexity. 



**Example: lib.lists.unique usage example**



```

unique [ 3 2 3 4 ]
=> [ 3 2 4 ]

```


  
 Located at [lib/lists.nix:646](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L646) in `<nixpkgs>`. 

`lib.lists.intersectLists`
--------------------------


 Intersects list 'e' and another list. O(nm) complexity. 



 `e` 
 Function argument 




**Example: lib.lists.intersectLists usage example**



```

intersectLists [ 1 2 3 ] [ 6 3 2 ]
=> [ 3 2 ]

```


  
 Located at [lib/lists.nix:654](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L654) in `<nixpkgs>`. 

`lib.lists.subtractLists`
-------------------------


 Subtracts list 'e' from another list. O(nm) complexity. 



 `e` 
 Function argument 




**Example: lib.lists.subtractLists usage example**



```

subtractLists [ 3 2 ] [ 1 2 3 4 5 3 ]
=> [ 1 4 5 ]

```


  
 Located at [lib/lists.nix:662](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L662) in `<nixpkgs>`. 

`lib.lists.mutuallyExclusive`
-----------------------------


 Test if two lists have no common element. It should be slightly more efficient than (intersectLists a b == []) 



 `a` 
 Function argument 


 `b` 
 Function argument 



 Located at [lib/lists.nix:667](https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix#L667) in `<nixpkgs>`. 


`lib.debug.traceIf`
-------------------


##### 
`traceIf :: bool -> string -> a -> a`



 Conditionally trace the supplied message, based on a predicate. 



 `pred` 
 Predicate to check 


 `msg` 
 Message that should be traced 


 `x` 
 Value to return 




**Example: lib.debug.traceIf usage example**



```

traceIf true "hello" 3
trace: hello
=> 3

```


  
 Located at [lib/debug.nix:51](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L51) in `<nixpkgs>`. 


`lib.debug.traceValFn`
----------------------


##### 
`traceValFn :: (a -> b) -> a -> a`



 Trace the supplied value after applying a function to it, and return the original value. 



 `f` 
 Function to apply 


 `x` 
 Value to trace and return 




**Example: lib.debug.traceValFn usage example**



```

traceValFn (v: "mystring ${v}") "foo"
trace: mystring foo
=> "foo"

```


  
 Located at [lib/debug.nix:69](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L69) in `<nixpkgs>`. 


`lib.debug.traceVal`
--------------------


##### 
`traceVal :: a -> a`



 Trace the supplied value and return it. 



**Example: lib.debug.traceVal usage example**



```

traceVal 42
# trace: 42
=> 42

```


  
 Located at [lib/debug.nix:84](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L84) in `<nixpkgs>`. 


`lib.debug.traceSeq`
--------------------


##### 
`traceSeq :: a -> b -> b`



 `builtins.trace`, but the value is `builtins.deepSeq`ed first. 



 `x` 
 The value to trace 


 `y` 
 The value to return 




**Example: lib.debug.traceSeq usage example**



```

trace { a.b.c = 3; } null
trace: { a = <CODE>; }
=> null
traceSeq { a.b.c = 3; } null
trace: { a = { b = { c = 3; }; }; }
=> null

```


  
 Located at [lib/debug.nix:98](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L98) in `<nixpkgs>`. 

`lib.debug.traceSeqN`
---------------------


 Like `traceSeq`, but only evaluate down to depth n. This is very useful because lots of `traceSeq` usages lead to an infinite recursion. 



 `depth` 
 Function argument 


 `x` 
 Function argument 


 `y` 
 Function argument 




**Example: lib.debug.traceSeqN usage example**



```

traceSeqN 2 { a.b.c = 3; } null
trace: { a = { b = {…}; }; }
=> null

```


  
 Located at [lib/debug.nix:113](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L113) in `<nixpkgs>`. 

`lib.debug.traceValSeqFn`
-------------------------


 A combination of `traceVal` and `traceSeq` that applies a provided function to the value to be traced after `deepSeq`ing it. 



 `f` 
 Function to apply 


 `v` 
 Value to trace 



 Located at [lib/debug.nix:130](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L130) in `<nixpkgs>`. 

`lib.debug.traceValSeq`
-----------------------


 A combination of `traceVal` and `traceSeq`. 


 Located at [lib/debug.nix:137](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L137) in `<nixpkgs>`. 

`lib.debug.traceValSeqNFn`
--------------------------


 A combination of `traceVal` and `traceSeqN` that applies a provided function to the value to be traced. 



 `f` 
 Function to apply 


 `depth` 
 Function argument 


 `v` 
 Value to trace 



 Located at [lib/debug.nix:141](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L141) in `<nixpkgs>`. 

`lib.debug.traceValSeqN`
------------------------


 A combination of `traceVal` and `traceSeqN`. 


 Located at [lib/debug.nix:149](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L149) in `<nixpkgs>`. 

`lib.debug.traceFnSeqN`
-----------------------


 Trace the input and output of a function `f` named `name`, both down to `depth`. 


 This is useful for adding around a function call, to see the before/after of values as they are transformed. 



 `depth` 
 Function argument 


 `name` 
 Function argument 


 `f` 
 Function argument 


 `v` 
 Function argument 




**Example: lib.debug.traceFnSeqN usage example**



```

traceFnSeqN 2 "id" (x: x) { a.b.c = 3; }
trace: { fn = "id"; from = { a.b = {…}; }; to = { a.b = {…}; }; }
=> { a.b.c = 3; }

```


  
 Located at [lib/debug.nix:162](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L162) in `<nixpkgs>`. 

`lib.debug.runTests`
--------------------


 Evaluate a set of tests. A test is an attribute set `{expr, expected}`, denoting an expression and its expected result. The result is a list of failed tests, each represented as `{name, expected, actual}`, denoting the attribute name of the failing test and its expected and actual results. 


 Used for regression testing of the functions in lib; see tests.nix for an example. Only tests having names starting with "test" are run. 


 Add attr { tests = ["testName"]; } to run these tests only. 



 `tests` 
 Tests to run 



 Located at [lib/debug.nix:188](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L188) in `<nixpkgs>`. 

`lib.debug.testAllTrue`
-----------------------


 Create a test assuming that list elements are `true`. 



 `expr` 
 Function argument 




**Example: lib.debug.testAllTrue usage example**



```

{ testX = allTrue [ true ]; }

```


  
 Located at [lib/debug.nix:204](https://github.com/NixOS/nixpkgs/blob/master/lib/debug.nix#L204) in `<nixpkgs>`. 


`lib.options.isOption`
----------------------


##### 
`isOption :: a -> bool`



 Returns true when the given argument is an option 



**Example: lib.options.isOption usage example**



```

isOption 1             // => false
isOption (mkOption {}) // => true

```


  
 Located at [lib/options.nix:50](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L50) in `<nixpkgs>`. 

`lib.options.mkOption`
----------------------


 Creates an Option attribute set. mkOption accepts an attribute set with the following keys: 


 All keys default to `null` when not given. 



 `pattern` 

 Structured function argument 



 `default` 
 Default value used when no definition is given in the configuration. 


 `defaultText` 
 Textual representation of the default, for the manual. 


 `example` 
 Example value used in the manual. 


 `description` 
 String describing the option. 


 `relatedPackages` 
 Related packages used in the manual (see `genRelatedPackages` in ../nixos/lib/make-options-doc/default.nix). 


 `type` 
 Option type, providing type-checking and value merging. 


 `apply` 
 Function that converts the option value to something else. 


 `internal` 
 Whether the option is for NixOS developers only. 


 `visible` 
 Whether the option shows up in the manual. Default: true. Use false to hide the option and any sub-options from submodules. Use "shallow" to hide only sub-options. 


 `readOnly` 
 Whether the option can be set only once 






**Example: lib.options.mkOption usage example**



```

mkOption { }  // => { _type = "option"; }
mkOption { default = "foo"; } // => { _type = "option"; default = "foo"; }

```


  
 Located at [lib/options.nix:60](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L60) in `<nixpkgs>`. 

`lib.options.mkEnableOption`
----------------------------


 Creates an Option attribute set for a boolean value option i.e an option to be toggled on or off: 



 `name` 
 Name for the created option 




**Example: lib.options.mkEnableOption usage example**



```

mkEnableOption "foo"
=> { _type = "option"; default = false; description = "Whether to enable foo."; example = true; type = { ... }; }

```


  
 Located at [lib/options.nix:92](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L92) in `<nixpkgs>`. 


`lib.options.mkPackageOption`
-----------------------------


##### 
`mkPackageOption :: pkgs -> string -> { default :: [string], example :: null | string | [string] } -> optionThe package is specified as a list of strings representing its attribute path in nixpkgs.Because of this, you need to pass nixpkgs itself as the first argument.The second argument is the name of the option, used in the description "The <name> package to use.".You can also pass an example value, either a literal string or a package's attribute path.You can omit the default path if the name of the option is also attribute path in nixpkgs.`



 Creates an Option attribute set for an option that specifies the package a module should use for some purpose. 



 `pkgs` 
 Package set (a specific version of nixpkgs) 


 `name` 
 Name for the package, shown in option description 


 `pattern` 

 Structured function argument 



 `default` 
 Function argument 


 `example` 
 Function argument 






**Example: lib.options.mkPackageOption usage example**



```

mkPackageOption pkgs "hello" { }
=> { _type = "option"; default = «derivation /nix/store/3r2vg51hlxj3cx5vscp0vkv60bqxkaq0-hello-2.10.drv»; defaultText = { ... }; description = "The hello package to use."; type = { ... }; }


mkPackageOption pkgs "GHC" {
default = [ "ghc" ];
example = "pkgs.haskell.package.ghc922.ghc.withPackages (hkgs: [ hkgs.primes ])";
}
=> { _type = "option"; default = «derivation /nix/store/jxx55cxsjrf8kyh3fp2ya17q99w7541r-ghc-8.10.7.drv»; defaultText = { ... }; description = "The GHC package to use."; example = { ... }; type = { ... }; }

```


  
 Located at [lib/options.nix:127](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L127) in `<nixpkgs>`. 

`lib.options.mkSinkUndeclaredOptions`
-------------------------------------


 This option accepts anything, but it does not produce any result. 


 This is useful for sharing a module across different module sets without having to implement similar features as long as the values of the options are not accessed. 



 `attrs` 
 Function argument 



 Located at [lib/options.nix:149](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L149) in `<nixpkgs>`. 

`lib.options.mergeEqualOption`
------------------------------


 "Merge" option definitions by checking that they all have the same value. 



 `loc` 
 Function argument 


 `defs` 
 Function argument 



 Located at [lib/options.nix:182](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L182) in `<nixpkgs>`. 


`lib.options.getValues`
-----------------------


##### 
`getValues :: [ { value :: a } ] -> [a]`



 Extracts values of all "value" keys of the given list. 



**Example: lib.options.getValues usage example**



```

getValues [ { value = 1; } { value = 2; } ] // => [ 1 2 ]
getValues [ ]                               // => [ ]

```


  
 Located at [lib/options.nix:202](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L202) in `<nixpkgs>`. 


`lib.options.getFiles`
----------------------


##### 
`getFiles :: [ { file :: a } ] -> [a]`



 Extracts values of all "file" keys of the given list 



**Example: lib.options.getFiles usage example**



```

getFiles [ { file = "file1"; } { file = "file2"; } ] // => [ "file1" "file2" ]
getFiles [ ]                                         // => [ ]

```


  
 Located at [lib/options.nix:212](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L212) in `<nixpkgs>`. 

`lib.options.scrubOptionValue`
------------------------------


 This function recursively removes all derivation attributes from `x` except for the `name` attribute. 


 This is to make the generation of `options.xml` much more efficient: the XML representation of derivations is very large (on the order of megabytes) and is not actually used by the manual generator. 



 `x` 
 Function argument 



 Located at [lib/options.nix:255](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L255) in `<nixpkgs>`. 

`lib.options.literalExpression`
-------------------------------


 For use in the `defaultText` and `example` option attributes. Causes the given string to be rendered verbatim in the documentation as Nix code. This is necessary for complex values, e.g. functions, or values that depend on other values or packages. 



 `text` 
 Function argument 



 Located at [lib/options.nix:268](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L268) in `<nixpkgs>`. 

`lib.options.literalDocBook`
----------------------------


 For use in the `defaultText` and `example` option attributes. Causes the given DocBook text to be inserted verbatim in the documentation, for when a `literalExpression` would be too hard to read. 



 `text` 
 Function argument 



 Located at [lib/options.nix:279](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L279) in `<nixpkgs>`. 

`lib.options.showOption`
------------------------


 Convert an option, described as a list of the option parts in to a safe, human readable version. 



 `parts` 
 Function argument 




**Example: lib.options.showOption usage example**



```

(showOption ["foo" "bar" "baz"]) == "foo.bar.baz"
(showOption ["foo" "bar.baz" "tux"]) == "foo.bar.baz.tux"

Placeholders will not be quoted as they are not actual values:
(showOption ["foo" "*" "bar"]) == "foo.*.bar"
(showOption ["foo" "<name>" "bar"]) == "foo.<name>.bar"

Unlike attributes, options can also start with numbers:
(showOption ["windowManager" "2bwm" "enable"]) == "windowManager.2bwm.enable"

```


  
 Located at [lib/options.nix:299](https://github.com/NixOS/nixpkgs/blob/master/lib/options.nix#L299) in `<nixpkgs>`. 

`lib.sources.pathType`
----------------------


 Returns the type of a path: regular (for file), symlink, or directory. 



 `path` 
 Function argument 



 Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`. 

`lib.sources.pathIsDirectory`
-----------------------------


 Returns true if the path exists and is a directory, false otherwise. 



 `path` 
 Function argument 



 Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`. 

`lib.sources.pathIsRegularFile`
-------------------------------


 Returns true if the path exists and is a regular file, false otherwise. 



 `path` 
 Function argument 



 Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`. 

`lib.sources.cleanSourceFilter`
-------------------------------


 A basic filter for `cleanSourceWith` that removes directories of version control system, backup files (\*~) and some generated files. 



 `name` 
 Function argument 


 `type` 
 Function argument 



 Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`. 

`lib.sources.cleanSource`
-------------------------


 Filters a source tree removing version control files and directories using cleanSourceFilter. 



 `src` 
 Function argument 




**Example: lib.sources.cleanSource usage example**



```

cleanSource ./.

```


  
 Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`. 

`lib.sources.cleanSourceWith`
-----------------------------


 Like `builtins.filterSource`, except it will compose with itself, allowing you to chain multiple calls together without any intermediate copies being put in the nix store. 



 `pattern` 

 Structured function argument 



 `src` 
 A path or cleanSourceWith result to filter and/or rename. 


 `filter` 
 Optional with default value: constant true (include everything) 


 `name` 
 Optional name to use as part of the store path. 






**Example: lib.sources.cleanSourceWith usage example**



```

lib.cleanSourceWith {
filter = f;
src = lib.cleanSourceWith {
filter = g;
src = ./.;
};
}
# Succeeds!

builtins.filterSource f (builtins.filterSource g ./.)
# Fails!

```


  
 Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`. 


`lib.sources.trace`
-------------------


##### 
`sources.trace :: sourceLike -> Source`



 Add logging to a source, for troubleshooting the filtering behavior. 



 `src` 
 Source to debug. The returned source will behave like this source, but also log its filter invocations. 



 Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`. 

`lib.sources.sourceByRegex`
---------------------------


 Filter sources by a list of regular expressions. 



 `src` 
 Function argument 


 `regexes` 
 Function argument 




**Example: lib.sources.sourceByRegex usage example**



```
src = sourceByRegex ./my-subproject [".*\.py$" "^database.sql$"]

```


  
 Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`. 


`lib.sources.sourceFilesBySuffices`
-----------------------------------


##### 
`sourceLike -> [String] -> Source`



 Get all files ending with the specified suffices from the given source directory or its descendants, omitting files that do not match any suffix. The result of the example below will include files like `./dir/module.c` and `./dir/subdir/doc.xml` if present. 



 `src` 
 Path or source containing the files to be returned 


 `exts` 
 A list of file suffix strings 




**Example: lib.sources.sourceFilesBySuffices usage example**



```

sourceFilesBySuffices ./. [ ".xml" ".c" ]

```


  
 Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`. 

`lib.sources.commitIdFromGitRepo`
---------------------------------


 Get the commit id of a git repo. 



**Example: lib.sources.commitIdFromGitRepo usage example**



```
commitIdFromGitRepo <nixpkgs/.git>

```


  
 Located at [lib/sources.nix:265](https://github.com/NixOS/nixpkgs/blob/master/lib/sources.nix#L265) in `<nixpkgs>`. 


`pkgs.fetchurl` and `pkgs.fetchzip`
------------------------------------


 Two basic fetchers are `fetchurl` and `fetchzip`. Both of these have two required arguments, a URL and a hash. The hash is typically `sha256`, although many more hash algorithms are supported. Nixpkgs contributors are currently recommended to use `sha256`. This hash will be used by Nix to identify your source. A typical usage of `fetchurl` is provided below. 



```

{ stdenv, fetchurl }:

stdenv.mkDerivation {
  name = "hello";
  src = fetchurl {
    url = "http://www.example.org/hello.tar.gz";
    sha256 = "1111111111111111111111111111111111111111111111111111";
  };
}

```

 The main difference between `fetchurl` and `fetchzip` is in how they store the contents. `fetchurl` will store the unaltered contents of the URL within the Nix store. `fetchzip` on the other hand, will decompress the archive for you, making files and directories directly accessible in the future. `fetchzip` can only be used with archives. Despite the name, `fetchzip` is not limited to .zip files and can also be used with any tarball. 


 `fetchpatch` works very similarly to `fetchurl` with the same arguments expected. It expects patch files as a source and performs normalization on them before computing the checksum. For example, it will remove comments or other unstable parts that are sometimes added by version control systems and can change over time. 


 Most other fetchers return a directory rather than a single file. 

`pkgs.fetchsvn`
---------------


 Used with Subversion. Expects `url` to a Subversion directory, `rev`, and `sha256`. 

`pkgs.fetchgit`
---------------


 Used with Git. Expects `url` to a Git repo, `rev`, and `sha256`. `rev` in this case can be full the git commit id (SHA1 hash) or a tag name like `refs/tags/v1.0`. 


 Additionally, the following optional arguments can be given: `fetchSubmodules = true` makes `fetchgit` also fetch the submodules of a repository. If `deepClone` is set to true, the entire repository is cloned as opposing to just creating a shallow clone. `deepClone = true` also implies `leaveDotGit = true` which means that the `.git` directory of the clone won’t be removed after checkout. 


 If only parts of the repository are needed, `sparseCheckout` can be used. This will prevent git from fetching unnecessary blobs from server, see [git sparse-checkout](https://git-scm.com/docs/git-sparse-checkout) and [git clone –filter](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---filterltfilter-specgt) for more information: 



```

{ stdenv, fetchgit }:

stdenv.mkDerivation {
  name = "hello";
  src = fetchgit {
    url = "https://...";
    sparseCheckout = ''
      path/to/be/included
      another/path
    '';
    sha256 = "0000000000000000000000000000000000000000000000000000";
  };
}

```
`pkgs.fetchfossil`
------------------


 Used with Fossil. Expects `url` to a Fossil archive, `rev`, and `sha256`. 

`pkgs.fetchcvs`
---------------


 Used with CVS. Expects `cvsRoot`, `tag`, and `sha256`. 

`pkgs.fetchhg`
--------------


 Used with Mercurial. Expects `url`, `rev`, and `sha256`. 


 A number of fetcher functions wrap part of `fetchurl` and `fetchzip`. They are mainly convenience functions intended for commonly used destinations of source code in Nixpkgs. These wrapper fetchers are listed below. 

`pkgs.fetchFromGitea`
---------------------


 `fetchFromGitea` expects five arguments. `domain` is the gitea server name. `owner` is a string corresponding to the Gitea user or organization that controls this repository. `repo` corresponds to the name of the software repository. These are located at the top of every Gitea HTML page as `owner`/`repo`. `rev` corresponds to the Git commit hash or tag (e.g `v1.0`) that will be downloaded from Git. Finally, `sha256` corresponds to the hash of the extracted directory. Again, other hash algorithms are also available but `sha256` is currently preferred. 

`pkgs.fetchFromGitHub`
----------------------


 `fetchFromGitHub` expects four arguments. `owner` is a string corresponding to the GitHub user or organization that controls this repository. `repo` corresponds to the name of the software repository. These are located at the top of every GitHub HTML page as `owner`/`repo`. `rev` corresponds to the Git commit hash or tag (e.g `v1.0`) that will be downloaded from Git. Finally, `sha256` corresponds to the hash of the extracted directory. Again, other hash algorithms are also available, but `sha256` is currently preferred. 


 `fetchFromGitHub` uses `fetchzip` to download the source archive generated by GitHub for the specified revision. If `leaveDotGit`, `deepClone` or `fetchSubmodules` are set to `true`, `fetchFromGitHub` will use `fetchgit` instead. Refer to its section for documentation of these options. 

`pkgs.fetchFromGitLab`
----------------------


 This is used with GitLab repositories. The arguments expected are very similar to `fetchFromGitHub` above. 

`pkgs.fetchFromGitiles`
-----------------------


 This is used with Gitiles repositories. The arguments expected are similar to `fetchgit`. 

`pkgs.fetchFromBitbucket`
-------------------------


 This is used with BitBucket repositories. The arguments expected are very similar to fetchFromGitHub above. 

`pkgs.fetchFromSavannah`
------------------------


 This is used with Savannah repositories. The arguments expected are very similar to `fetchFromGitHub` above. 

`pkgs.fetchFromRepoOrCz`
------------------------


 This is used with repo.or.cz repositories. The arguments expected are very similar to `fetchFromGitHub` above. 

`pkgs.fetchFromSourcehut`
-------------------------


 This is used with sourcehut repositories. Similar to `fetchFromGitHub` above, it expects `owner`, `repo`, `rev` and `sha256`, but don’t forget the tilde (~) in front of the username! Expected arguments also include `vc` (“git” (default) or “hg”), `domain` and `fetchSubmodules`. 


 If `fetchSubmodules` is `true`, `fetchFromSourcehut` uses `fetchgit` or `fetchhg` with `fetchSubmodules` or `fetchSubrepos` set to `true`, respectively. Otherwise, the fetcher uses `fetchzip`. 

`pkgs.runCommand`
-----------------


 This takes three arguments, `name`, `env`, and `buildCommand`. `name` is just the name that Nix will append to the store path in the same way that `stdenv.mkDerivation` uses its `name` attribute. `env` is an attribute set specifying environment variables that will be set for this derivation. These attributes are then passed to the wrapped `stdenv.mkDerivation`. `buildCommand` specifies the commands that will be run to create this derivation. Note that you will need to create `$out` for Nix to register the command as successful. 


 An example of using `runCommand` is provided below. 



```

(import <nixpkgs> {}).runCommand "my-example" {} ''
  echo My example command is running

  mkdir $out

  echo I can write data to the Nix store > $out/message

  echo I can also run basic commands like:

  echo ls
  ls

  echo whoami
  whoami

  echo date
  date
''

```
`pkgs.runCommandCC`
-------------------


 This works just like `runCommand`. The only difference is that it also provides a C compiler in `buildCommand`’s environment. To minimize your dependencies, you should only use this if you are sure you will need a C compiler as part of running your command. 

`pkgs.runCommandLocal`
----------------------


 Variant of `runCommand` that forces the derivation to be built locally, it is not substituted. This is intended for very cheap commands (<1s execution time). It saves on the network round-trip and can speed up a build. 


Note
 This sets [`allowSubstitutes` to `false`](https://nixos.org/nix/manual/#adv-attr-allowSubstitutes), so only use `runCommandLocal` if you are certain the user will always have a builder for the `system` of the derivation. This should be true for most trivial use cases (e.g., just copying some files to a different location or adding symlinks) because there the `system` is usually the same as `builtins.currentSystem`. 


`pkgs.writeTextFile`, `pkgs.writeText`, `pkgs.writeTextDir`, `pkgs.writeScript`, `pkgs.writeScriptBin`
-------------------------------------------------------------------------------------------------------


 These functions write `text` to the Nix store. This is useful for creating scripts from Nix expressions. `writeTextFile` takes an attribute set and expects two arguments, `name` and `text`. `name` corresponds to the name used in the Nix store path. `text` will be the contents of the file. You can also set `executable` to true to make this file have the executable bit set. 


 Many more commands wrap `writeTextFile` including `writeText`, `writeTextDir`, `writeScript`, and `writeScriptBin`. These are convenience functions over `writeTextFile`. 


 Here are a few examples: 



```

# Writes my-file to /nix/store/<store path>
writeTextFile {
  name = "my-file";
  text = ''
    Contents of File
  '';
}
# See also the `writeText` helper function below.

# Writes executable my-file to /nix/store/<store path>/bin/my-file
writeTextFile {
  name = "my-file";
  text = ''
    Contents of File
  '';
  executable = true;
  destination = "/bin/my-file";
}
# Writes contents of file to /nix/store/<store path>
writeText "my-file"
  ''
  Contents of File
  '';
# Writes contents of file to /nix/store/<store path>/share/my-file
writeTextDir "share/my-file"
  ''
  Contents of File
  '';
# Writes my-file to /nix/store/<store path> and makes executable
writeScript "my-file"
  ''
  Contents of File
  '';
# Writes my-file to /nix/store/<store path>/bin/my-file and makes executable.
writeScriptBin "my-file"
  ''
  Contents of File
  '';
# Writes my-file to /nix/store/<store path> and makes executable.
writeShellScript "my-file"
  ''
  Contents of File
  '';
# Writes my-file to /nix/store/<store path>/bin/my-file and makes executable.
writeShellScriptBin "my-file"
  ''
  Contents of File
  '';

```

`pkgs.concatTextFile`, `pkgs.concatText`, `pkgs.concatScript`
--------------------------------------------------------------


 These functions concatenate `files` to the Nix store in a single file. This is useful for configuration files structured in lines of text. `concatTextFile` takes an attribute set and expects two arguments, `name` and `files`. `name` corresponds to the name used in the Nix store path. `files` will be the files to be concatenated. You can also set `executable` to true to make this file have the executable bit set. `concatText` and`concatScript` are simple wrappers over `concatTextFile`. 


 Here are a few examples: 



```


# Writes my-file to /nix/store/<store path>
concatTextFile {
  name = "my-file";
  files = [ drv1 "${drv2}/path/to/file" ];
}
# See also the `concatText` helper function below.

# Writes executable my-file to /nix/store/<store path>/bin/my-file
concatTextFile {
  name = "my-file";
  files = [ drv1 "${drv2}/path/to/file" ];
  executable = true;
  destination = "/bin/my-file";
}
# Writes contents of files to /nix/store/<store path>
concatText "my-file" [ file1 file2 ]

# Writes contents of files to /nix/store/<store path>
concatScript "my-file" [ file1 file2 ]

```
`pkgs.writeShellApplication`
----------------------------


 This can be used to easily produce a shell script that has some dependencies (`runtimeInputs`). It automatically sets the `PATH` of the script to contain all of the listed inputs, sets some sanity shellopts (`errexit`, `nounset`, `pipefail`), and checks the resulting script with [`shellcheck`](https://github.com/koalaman/shellcheck). 


 For example, look at the following code: 



```

writeShellApplication {
  name = "show-nixos-org";

  runtimeInputs = [ curl w3m ];

  text = ''
    curl -s 'https://nixos.org' | w3m -dump -T text/html
  '';
}

```

 Unlike with normal `writeShellScriptBin`, there is no need to manually write out `${curl}/bin/curl`, setting the PATH was handled by `writeShellApplication`. Moreover, the script is being checked with `shellcheck` for more strict validation. 

`pkgs.symlinkJoin`
------------------


 This can be used to put many derivations into the same directory structure. It works by creating a new derivation and adding symlinks to each of the paths listed. It expects two arguments, `name`, and `paths`. `name` is the name used in the Nix store path for the created derivation. `paths` is a list of paths that will be symlinked. These paths can be to Nix store derivations or any other subdirectory contained within. Here is an example: 



```

# adds symlinks of hello and stack to current build and prints "links added"
symlinkJoin { name = "myexample"; paths = [ pkgs.hello pkgs.stack ]; postBuild = "echo links added"; }

```

 This creates a derivation with a directory structure like the following: 



```

/nix/store/sglsr5g079a5235hy29da3mq3hv8sjmm-myexample
|-- bin
|   |-- hello -> /nix/store/qy93dp4a3rqyn2mz63fbxjg228hffwyw-hello-2.10/bin/hello
|   `-- stack -> /nix/store/6lzdpxshx78281vy056lbk553ijsdr44-stack-2.1.3.1/bin/stack
`-- share
    |-- bash-completion
    |   `-- completions
    |       `-- stack -> /nix/store/6lzdpxshx78281vy056lbk553ijsdr44-stack-2.1.3.1/share/bash-completion/completions/stack
    |-- fish
    |   `-- vendor_completions.d
    |       `-- stack.fish -> /nix/store/6lzdpxshx78281vy056lbk553ijsdr44-stack-2.1.3.1/share/fish/vendor_completions.d/stack.fish
...

```
`pkgs.writeReferencesToFile`
----------------------------


 Writes the closure of transitive dependencies to a file. 


 This produces the equivalent of `nix-store -q --requisites`. 


 For example, 



```

writeReferencesToFile (writeScriptBin "hi" ''${hello}/bin/hello'')

```

 produces an output path `/nix/store/<hash>-runtime-deps` containing 



```

/nix/store/<hash>-hello-2.10
/nix/store/<hash>-hi
/nix/store/<hash>-libidn2-2.3.0
/nix/store/<hash>-libunistring-0.9.10
/nix/store/<hash>-glibc-2.32-40

```

 You can see that this includes `hi`, the original input path, `hello`, which is a direct reference, but also the other paths that are indirectly required to run `hello`. 

`pkgs.writeDirectReferencesToFile`
----------------------------------


 Writes the set of references to the output file, that is, their immediate dependencies. 


 This produces the equivalent of `nix-store -q --references`. 


 For example, 



```

writeDirectReferencesToFile (writeScriptBin "hi" ''${hello}/bin/hello'')

```

 produces an output path `/nix/store/<hash>-runtime-references` containing 



```

/nix/store/<hash>-hello-2.10

```

 but none of `hello`’s dependencies because those are not referenced directly by `hi`’s output. 

`pkgs.buildFHSUserEnv`
----------------------


 `buildFHSUserEnv` provides a way to build and run FHS-compatible lightweight sandboxes. It creates an isolated root with bound `/nix/store`, so its footprint in terms of disk space needed is quite small. This allows one to run software which is hard or unfeasible to patch for NixOS – 3rd-party source trees with FHS assumptions, games distributed as tarballs, software with integrity checking and/or external self-updated binaries. It uses Linux namespaces feature to create temporary lightweight environments which are destroyed after all child processes exit, without root user rights requirement. Accepted arguments are: 


* `name` Environment name.
* `targetPkgs` Packages to be installed for the main host’s architecture (i.e. x86\_64 on x86\_64 installations). Along with libraries binaries are also installed.
* `multiPkgs` Packages to be installed for all architectures supported by a host (i.e. i686 and x86\_64 on x86\_64 installations). Only libraries are installed by default.
* `extraBuildCommands` Additional commands to be executed for finalizing the directory structure.
* `extraBuildCommandsMulti` Like `extraBuildCommands`, but executed only on multilib architectures.
* `extraOutputsToInstall` Additional derivation outputs to be linked for both target and multi-architecture packages.
* `extraInstallCommands` Additional commands to be executed for finalizing the derivation with runner script.
* `runScript` A command that would be executed inside the sandbox and passed all the command line arguments. It defaults to `bash`.
* `profile` Optional script for `/etc/profile` within the sandbox.

 One can create a simple environment using a `shell.nix` like that: 



```

{ pkgs ? import <nixpkgs> {} }:

(pkgs.buildFHSUserEnv {
  name = "simple-x11-env";
  targetPkgs = pkgs: (with pkgs;
    [ udev
      alsa-lib
    ]) ++ (with pkgs.xorg;
    [ libX11
      libXcursor
      libXrandr
    ]);
  multiPkgs = pkgs: (with pkgs;
    [ udev
      alsa-lib
    ]);
  runScript = "bash";
}).env

```

 Running `nix-shell` would then drop you into a shell with these libraries and binaries available. You can use this to run closed-source applications which expect FHS structure without hassles: simply change `runScript` to the application path, e.g. `./bin/start.sh` – relative paths are supported. 


 Additionally, the FHS builder links all relocated gsettings-schemas (the glib setup-hook moves them to `share/gsettings-schemas/${name}/glib-2.0/schemas`) to their standard FHS location. This means you don’t need to wrap binaries with `wrapGAppsHook`. 

`pkgs.mkShell`
--------------


 `pkgs.mkShell` is a specialized `stdenv.mkDerivation` that removes some repetition when using it with `nix-shell` (or `nix develop`). 


### Usage


 Here is a common usage example: 



```

{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
  packages = [ pkgs.gnumake ];

  inputsFrom = [ pkgs.hello pkgs.gnutar ];

  shellHook = ''
    export DEBUG=1
  '';
}

```
### Attributes


* `name` (default: `nix-shell`). Set the name of the derivation.
* `packages` (default: `[]`). Add executable packages to the `nix-shell` environment.
* `inputsFrom` (default: `[]`). Add build dependencies of the listed derivations to the `nix-shell` environment.
* `shellHook` (default: `""`). Bash statements that are executed by `nix-shell`.

 … all the attributes of `stdenv.mkDerivation`. 

### Building the shell


 This derivation output will contain a text file that contains a reference to all the build inputs. This is useful in CI where we want to make sure that every derivation, and its dependencies, build properly. Or when creating a GC root so that the build dependencies don’t get garbage-collected. 

`pkgs.appimageTools`
--------------------


 `pkgs.appimageTools` is a set of functions for extracting and wrapping [AppImage](https://appimage.org/) files. They are meant to be used if traditional packaging from source is infeasible, or it would take too long. To quickly run an AppImage file, `pkgs.appimage-run` can be used as well. 


Warning
 The `appimageTools` API is unstable and may be subject to backwards-incompatible changes in the future. 

### `AppImage formats`


 There are different formats for AppImages, see [the specification](https://github.com/AppImage/AppImageSpec/blob/74ad9ca2f94bf864a4a0dac1f369dd4f00bd1c28/draft.md#image-format) for details. 


* Type 1 images are ISO 9660 files that are also ELF executables.
* Type 2 images are ELF executables with an appended filesystem.

 They can be told apart with `file -k`: 



```

$ file -k type1.AppImage
type1.AppImage: ELF 64-bit LSB executable, x86-64, version 1 (SYSV) ISO 9660 CD-ROM filesystem data 'AppImage' (Lepton 3.x), scale 0-0,
spot sensor temperature 0.000000, unit celsius, color scheme 0, calibration: offset 0.000000, slope 0.000000, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.18, BuildID[sha1]=d629f6099d2344ad82818172add1d38c5e11bc6d, stripped\012- data

$ file -k type2.AppImage
type2.AppImage: ELF 64-bit LSB executable, x86-64, version 1 (SYSV) (Lepton 3.x), scale 232-60668, spot sensor temperature -4.187500, color scheme 15, show scale bar, calibration: offset -0.000000, slope 0.000000 (Lepton 2.x), scale 4111-45000, spot sensor temperature 412442.250000, color scheme 3, minimum point enabled, calibration: offset -75402534979642766821519867692934234112.000000, slope 5815371847733706829839455140374904832.000000, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.18, BuildID[sha1]=79dcc4e55a61c293c5e19edbd8d65b202842579f, stripped\012- data

```

 Note how the type 1 AppImage is described as an `ISO 9660 CD-ROM filesystem`, and the type 2 AppImage is not. 

### `Wrapping`


 Depending on the type of AppImage you’re wrapping, you’ll have to use `wrapType1` or `wrapType2`. 



```

appimageTools.wrapType2 { # or wrapType1
  name = "patchwork";
  src = fetchurl {
    url = "https://github.com/ssbc/patchwork/releases/download/v3.11.4/Patchwork-3.11.4-linux-x86_64.AppImage";
    sha256 = "1blsprpkvm0ws9b96gb36f0rbf8f5jgmw4x6dsb1kswr4ysf591s";
  };
  extraPkgs = pkgs: with pkgs; [ ];
}

```

* `name` specifies the name of the resulting image.
* `src` specifies the AppImage file to extract.
* `extraPkgs` allows you to pass a function to include additional packages inside the FHS environment your AppImage is going to run in. There are a few ways to learn which dependencies an application needs: 



	+ Looking through the extracted AppImage files, reading its scripts and running `patchelf` and `ldd` on its executables. This can also be done in `appimage-run`, by setting `APPIMAGE_DEBUG_EXEC=bash`.
	+ Running `strace -vfefile` on the wrapped executable, looking for libraries that can’t be found.
`pkgs.dockerTools`
------------------


 `pkgs.dockerTools` is a set of functions for creating and manipulating Docker images according to the [Docker Image Specification v1.2.0](https://github.com/moby/moby/blob/master/image/spec/v1.2.md#docker-image-specification-v120). Docker itself is not used to perform any of the operations done by these functions. 


### `pkgs.dockerTools.buildImage`


 This function is analogous to the `docker build` command, in that it can be used to build a Docker-compatible repository tarball containing a single image with one or multiple layers. As such, the result is suitable for being loaded in Docker with `docker load`. 


 The parameters of `buildImage` with relative example values are described below: 



```

buildImage {
  name = "redis";
  tag = "latest";

  fromImage = someBaseImage;
  fromImageName = null;
  fromImageTag = "latest";

  contents = pkgs.redis;
  runAsRoot = ''
    #!${pkgs.runtimeShell}
    mkdir -p /data
  '';

  config = {
    Cmd = [ "/bin/redis-server" ];
    WorkingDir = "/data";
    Volumes = { "/data" = { }; };
  };
}

```

 The above example will build a Docker image `redis/latest` from the given base image. Loading and running this image in Docker results in `redis-server` being started automatically. 


* `name` specifies the name of the resulting image. This is the only required argument for `buildImage`.
* `tag` specifies the tag of the resulting image. By default it’s `null`, which indicates that the nix output hash will be used as tag.
* `fromImage` is the repository tarball containing the base image. It must be a valid Docker image, such as exported by `docker save`. By default it’s `null`, which can be seen as equivalent to `FROM scratch` of a `Dockerfile`.
* `fromImageName` can be used to further specify the base image within the repository, in case it contains multiple images. By default it’s `null`, in which case `buildImage` will peek the first image available in the repository.
* `fromImageTag` can be used to further specify the tag of the base image within the repository, in case an image contains multiple tags. By default it’s `null`, in which case `buildImage` will peek the first tag available for the base image.
* `contents` is a derivation that will be copied in the new layer of the resulting image. This can be similarly seen as `ADD contents/ /` in a `Dockerfile`. By default it’s `null`.
* `runAsRoot` is a bash script that will run as root in an environment that overlays the existing layers of the base image with the new resulting layer, including the previously copied `contents` derivation. This can be similarly seen as `RUN ...` in a `Dockerfile`.


>  ***NOTE:*** Using this parameter requires the `kvm` device to be available. 
> 
> 


* `config` is used to specify the configuration of the containers that will be started off the built image in Docker. The available options are listed in the [Docker Image Specification v1.2.0](https://github.com/moby/moby/blob/master/image/spec/v1.2.md#image-json-field-descriptions).

 After the new layer has been created, its closure (to which `contents`, `config` and `runAsRoot` contribute) will be copied in the layer itself. Only new dependencies that are not already in the existing layers will be copied. 


 At the end of the process, only one new single layer will be produced and added to the resulting image. 


 The resulting repository will only list the single image `image/tag`. In the case of [the `buildImage` example](#ex-dockerTools-buildImage), it would be `redis/latest`. 


 It is possible to inspect the arguments with which an image was built using its `buildArgs` attribute. 



>  ***NOTE:*** If you see errors similar to `getProtocolByName: does not exist (no such protocol name: tcp)` you may need to add `pkgs.iana-etc` to `contents`. 
> 
> 



>  ***NOTE:*** If you see errors similar to `Error_Protocol ("certificate has unknown CA",True,UnknownCa)` you may need to add `pkgs.cacert` to `contents`. 
> 
> 


 By default `buildImage` will use a static date of one second past the UNIX Epoch. This allows `buildImage` to produce binary reproducible images. When listing images with `docker images`, the newly created images will be listed like this: 



```

$ docker images
REPOSITORY   TAG      IMAGE ID       CREATED        SIZE
hello        latest   08c791c7846e   48 years ago   25.2MB

```

 You can break binary reproducibility but have a sorted, meaningful `CREATED` column by setting `created` to `now`. 



```

pkgs.dockerTools.buildImage {
  name = "hello";
  tag = "latest";
  created = "now";
  contents = pkgs.hello;

  config.Cmd = [ "/bin/hello" ];
}

```

 Now the Docker CLI will display a reasonable date and sort the images as expected: 



```

$ docker images
REPOSITORY   TAG      IMAGE ID       CREATED              SIZE
hello        latest   de2bf4786de6   About a minute ago   25.2MB

```

 However, the produced images will not be binary reproducible. 

### `pkgs.dockerTools.buildLayeredImage`


 Create a Docker image with many of the store paths being on their own layer to improve sharing between images. The image is realized into the Nix store as a gzipped tarball. Depending on the intended usage, many users might prefer to use `streamLayeredImage` instead, which this function uses internally. 



 `name` 
 The name of the resulting image. 


 `tag` *optional* 

 Tag of the generated image. 


 *Default:* the output path’s hash 



 `fromImage` *optional* 

 The repository tarball containing the base image. It must be a valid Docker image, such as one exported by `docker save`. 


 *Default:* `null`, which can be seen as equivalent to `FROM scratch` of a `Dockerfile`. 



 `contents` *optional* 

 Top-level paths in the container. Either a single derivation, or a list of derivations. 


 *Default:* `[]` 



 `config` *optional* 

 Run-time configuration of the container. A full list of the options are available at in the [Docker Image Specification v1.2.0](https://github.com/moby/moby/blob/master/image/spec/v1.2.md#image-json-field-descriptions). 


 *Default:* `{}` 



 `created` *optional* 

 Date and time the layers were created. Follows the same `now` exception supported by `buildImage`. 


 *Default:* `1970-01-01T00:00:01Z` 



 `maxLayers` *optional* 

 Maximum number of layers to create. 


 *Default:* `100` 


 *Maximum:* `125` 



 `extraCommands` *optional* 
 Shell commands to run while building the final layer, without access to most of the layer contents. Changes to this layer are “on top” of all the other layers, so can create additional directories and files. 


 `fakeRootCommands` *optional* 
 Shell commands to run while creating the archive for the final layer in a fakeroot environment. Unlike `extraCommands`, you can run `chown` to change the owners of the files in the archive, changing fakeroot’s state instead of the real filesystem. The latter would require privileges that the build user does not have. Static binaries do not interact with the fakeroot environment. By default all files in the archive will be owned by root. 


 `enableFakechroot` *optional* 

 Whether to run in `fakeRootCommands` in `fakechroot`, making programs behave as though `/` is the root of the image being created, while files in the Nix store are available as usual. This allows scripts that perform installation in `/` to work as expected. Considering that `fakechroot` is implemented via the same mechanism as `fakeroot`, the same caveats apply. 


 *Default:* `false` 




#### 
`Behavior of` `contents` in the final image


 Each path directly listed in `contents` will have a symlink in the root of the image. 


 For example: 



```

pkgs.dockerTools.buildLayeredImage {
  name = "hello";
  contents = [ pkgs.hello ];
}

```

 will create symlinks for all the paths in the `hello` package: 



```

/bin/hello -> /nix/store/h1zb1padqbbb7jicsvkmrym3r6snphxg-hello-2.10/bin/hello
/share/info/hello.info -> /nix/store/h1zb1padqbbb7jicsvkmrym3r6snphxg-hello-2.10/share/info/hello.info
/share/locale/bg/LC_MESSAGES/hello.mo -> /nix/store/h1zb1padqbbb7jicsvkmrym3r6snphxg-hello-2.10/share/locale/bg/LC_MESSAGES/hello.mo

```
#### 
`Automatic inclusion of` `config` references


 The closure of `config` is automatically included in the closure of the final image. 


 This allows you to make very simple Docker images with very little code. This container will start up and run `hello`: 



```

pkgs.dockerTools.buildLayeredImage {
  name = "hello";
  config.Cmd = [ "${pkgs.hello}/bin/hello" ];
}

```
#### 
`Adjusting` `maxLayers`


 Increasing the `maxLayers` increases the number of layers which have a chance to be shared between different images. 


 Modern Docker installations support up to 128 layers, but older versions support as few as 42. 


 If the produced image will not be extended by other Docker builds, it is safe to set `maxLayers` to `128`. However, it will be impossible to extend the image further. 


 The first (`maxLayers-2`) most “popular” paths will have their own individual layers, then layer #`maxLayers-1` will contain all the remaining “unpopular” paths, and finally layer #`maxLayers` will contain the Image configuration. 


 Docker’s Layers are not inherently ordered, they are content-addressable and are not explicitly layered until they are composed in to an Image. 

### `pkgs.dockerTools.streamLayeredImage`


 Builds a script which, when run, will stream an uncompressed tarball of a Docker image to stdout. The arguments to this function are as for `buildLayeredImage`. This method of constructing an image does not realize the image into the Nix store, so it saves on IO and disk/cache space, particularly with large images. 


 The image produced by running the output script can be piped directly into `docker load`, to load it into the local docker daemon: 



```

$(nix-build) | docker load

```

 Alternatively, the image be piped via `gzip` into `skopeo`, e.g., to copy it into a registry: 



```

$(nix-build) | gzip --fast | skopeo copy docker-archive:/dev/stdin docker://some_docker_registry/myimage:tag

```
### `pkgs.dockerTools.pullImage`


 This function is analogous to the `docker pull` command, in that it can be used to pull a Docker image from a Docker registry. By default [Docker Hub](https://hub.docker.com/) is used to pull images. 


 Its parameters are described in the example below: 



```

pullImage {
  imageName = "nixos/nix";
  imageDigest =
    "sha256:20d9485b25ecfd89204e843a962c1bd70e9cc6858d65d7f5fadc340246e2116b";
  finalImageName = "nix";
  finalImageTag = "1.11";
  sha256 = "0mqjy3zq2v6rrhizgb9nvhczl87lcfphq9601wcprdika2jz7qh8";
  os = "linux";
  arch = "x86_64";
}

```

* `imageName` specifies the name of the image to be downloaded, which can also include the registry namespace (e.g. `nixos`). This argument is required.
* `imageDigest` specifies the digest of the image to be downloaded. This argument is required.
* `finalImageName`, if specified, this is the name of the image to be created. Note it is never used to fetch the image since we prefer to rely on the immutable digest ID. By default it’s equal to `imageName`.
* `finalImageTag`, if specified, this is the tag of the image to be created. Note it is never used to fetch the image since we prefer to rely on the immutable digest ID. By default it’s `latest`.
* `sha256` is the checksum of the whole fetched image. This argument is required.
* `os`, if specified, is the operating system of the fetched image. By default it’s `linux`.
* `arch`, if specified, is the cpu architecture of the fetched image. By default it’s `x86_64`.

 `nix-prefetch-docker` command can be used to get required image parameters: 



```

$ nix run nixpkgs.nix-prefetch-docker -c nix-prefetch-docker --image-name mysql --image-tag 5

```

 Since a given `imageName` may transparently refer to a manifest list of images which support multiple architectures and/or operating systems, you can supply the `--os` and `--arch` arguments to specify exactly which image you want. By default it will match the OS and architecture of the host the command is run on. 



```

$ nix-prefetch-docker --image-name mysql --image-tag 5 --arch x86_64 --os linux

```

 Desired image name and tag can be set using `--final-image-name` and `--final-image-tag` arguments: 



```

$ nix-prefetch-docker --image-name mysql --image-tag 5 --final-image-name eu.gcr.io/my-project/mysql --final-image-tag prod

```
### `pkgs.dockerTools.exportImage`


 This function is analogous to the `docker export` command, in that it can be used to flatten a Docker image that contains multiple layers. It is in fact the result of the merge of all the layers of the image. As such, the result is suitable for being imported in Docker with `docker import`. 



>  ***NOTE:*** Using this function requires the `kvm` device to be available. 
> 
> 


 The parameters of `exportImage` are the following: 



```

exportImage {
  fromImage = someLayeredImage;
  fromImageName = null;
  fromImageTag = null;

  name = someLayeredImage.name;
}

```

 The parameters relative to the base image have the same synopsis as described in [buildImage](#ssec-pkgs-dockerTools-buildImage "15.2.1. buildImage"), except that `fromImage` is the only required argument in this case. 


 The `name` argument is the name of the derivation output, which defaults to `fromImage.name`. 

### `pkgs.dockerTools.shadowSetup`


 This constant string is a helper for setting up the base files for managing users and groups, only if such files don’t exist already. It is suitable for being used in a [`buildImage` `runAsRoot`](#ex-dockerTools-buildImage-runAsRoot) script for cases like in the example below: 



```

buildImage {
  name = "shadow-basic";

  runAsRoot = ''
    #!${pkgs.runtimeShell}
    ${pkgs.dockerTools.shadowSetup}
    groupadd -r redis
    useradd -r -g redis redis
    mkdir /data
    chown redis:redis /data
  '';
}

```

 Creating base files like `/etc/passwd` or `/etc/login.defs` is necessary for shadow-utils to manipulate users and groups. 

`pkgs.ociTools`
---------------


 `pkgs.ociTools` is a set of functions for creating containers according to the [OCI container specification v1.0.0](https://github.com/opencontainers/runtime-spec). Beyond that, it makes no assumptions about the container runner you choose to use to run the created container. 


### `pkgs.ociTools.buildContainer`


 This function creates a simple OCI container that runs a single command inside of it. An OCI container consists of a `config.json` and a rootfs directory. The nix store of the container will contain all referenced dependencies of the given command. 


 The parameters of `buildContainer` with an example value are described below: 



```

buildContainer {
  args = [
    (with pkgs;
      writeScript "run.sh" ''
        #!${bash}/bin/bash
        exec ${bash}/bin/bash
      '').outPath
  ];

  mounts = {
    "/data" = {
      type = "none";
      source = "/var/lib/mydata";
      options = [ "bind" ];
    };
  };

  readonly = false;
}

```

* `args` specifies a set of arguments to run inside the container. This is the only required argument for `buildContainer`. All referenced packages inside the derivation will be made available inside the container.
* `mounts` specifies additional mount points chosen by the user. By default only a minimal set of necessary filesystems are mounted into the container (e.g procfs, cgroupfs)
* `readonly` makes the container's rootfs read-only if it is set to true. The default value is false `false`.
`pkgs.snapTools`
----------------


 `pkgs.snapTools` is a set of functions for creating Snapcraft images. Snap and Snapcraft is not used to perform these operations. 


### `The makeSnap Function`


 `makeSnap` takes a single named argument, `meta`. This argument mirrors [the upstream `snap.yaml` format](https://docs.snapcraft.io/snap-format) exactly. 


 The `base` should not be specified, as `makeSnap` will force set it. 


 Currently, `makeSnap` does not support creating GUI stubs. 

### `Build a Hello World Snap`


 The following expression packages GNU Hello as a Snapcraft snap. 



```

let
  inherit (import <nixpkgs> { }) snapTools hello;
in snapTools.makeSnap {
  meta = {
    name = "hello";
    summary = hello.meta.description;
    description = hello.meta.longDescription;
    architectures = [ "amd64" ];
    confinement = "strict";
    apps.hello.command = "${hello}/bin/hello";
  };
}

```

 `nix-build` this expression and install it with `snap install ./result --dangerous`. `hello` will now be the Snapcraft version of the package. 

### `Build a Graphical Snap`


 Graphical programs require many more integrations with the host. This example uses Firefox as an example because it is one of the most complicated programs we could package. 



```

let
  inherit (import <nixpkgs> { }) snapTools firefox;
in snapTools.makeSnap {
  meta = {
    name = "nix-example-firefox";
    summary = firefox.meta.description;
    architectures = [ "amd64" ];
    apps.nix-example-firefox = {
      command = "${firefox}/bin/firefox";
      plugs = [
        "pulseaudio"
        "camera"
        "browser-support"
        "avahi-observe"
        "cups-control"
        "desktop"
        "desktop-legacy"
        "gsettings"
        "home"
        "network"
        "mount-observe"
        "removable-media"
        "x11"
      ];
    };
    confinement = "strict";
  };
}

```

 `nix-build` this expression and install it with `snap install ./result --dangerous`. `nix-example-firefox` will now be the Snapcraft version of the Firefox package. 


 The specific meaning behind plugs can be looked up in the [Snapcraft interface documentation](https://docs.snapcraft.io/supported-interfaces). 



 © 2022 NixOS Contributors  
Licensed under the LGPL License.  

<https://nixos.org/manual/nixpkgs/stable/index.html>

nix