Nix (builtins) & Nixpkgs (lib) Functions

Nix Builtin Functions


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.

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

evaluates to

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



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



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.


e1, e2

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



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 "" "
    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='' version='1.0'>
      <xsl:template match='/'>
          <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>

  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. 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'?>
      <attr name="path">
        <string value="/bugtracker" />
      <attr name="war">
        <path value="/nix/store/d1jh9pasa7k2...-jira/lib/atlassian-jira.war" />
      <attr name="path">
        <string value="/wiki" />
      <attr name="war">
        <path value="/nix/store/y6423b1yi4sx...-uberwiki/uberwiki.war" />

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}.



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



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



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.


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 and its build script into one file:

{ stdenv, fetchurl, perl }:

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

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


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

  src = fetchurl {
    url = "";
    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 "" "
  source $stdenv/setup
  cp ${configFile} $out/etc/foo.conf

Note that ${configFile} is an antiquotation, 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:

  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.



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).



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


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.


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".


e1, e2

Return the difference between the numbers e1 and e2.



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



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.



Split a string representing a version into its components, by the same version splitting logic underlying the version comparison in nix-env -u.


regex, str

Returns a list composed of non matched strings interleaved with the lists of the extended POSIX regular expression 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" ] " " ].


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.


e1, e2

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


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".


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; }.



Return the contents of the file path as a string.



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".



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".



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



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


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 ]; }



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"; }.


e1, e2

Return the product of the numbers e1 and e2.


regex, str

Returns a list if the extended POSIX regular expression 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" ].


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; }.

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" ].



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:

  [ { name = "foo"; value = 123; }
    { name = "bar"; value = 456; }

evaluates to

{ foo = 123; bar = 456; }


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.



Return the length of the list e.



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



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



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


This function is deprecated; just write e == null instead.



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



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



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



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



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



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


e1, e2

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



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.


Unlike some languages, import is a regular function in Nix. Paths using the angle bracket syntax (e.g., import <foo>) are normal path values.

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;


x: x + 456

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



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 [].


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".


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".


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.


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" ]; }



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.



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.)


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.



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; } ]


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 ].



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: ...) = { }.



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; }.


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.



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.


e1, e2


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")

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.


f, list

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



Download the specified URL and return the path of the downloaded file. This function is not available if restricted evaluation mode is enabled.



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 {};

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 = "";
  sha256 = "1jppksrfvbk5ypiqdz4cddxdl8z6zyzdb2srq8fcffr327ld5jj2";
}) {};

stdenv.mkDerivation {}

This function is not available if restricted evaluation mode is enabled.



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):

Here are some examples of how to use fetchGit.



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

builtins.fetchClosure {
  fromStore = "";
  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 /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.


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.


x, xs

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


e1, e2

Return the quotient of the numbers e1 and e2.



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.


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.


separator, list

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


f, list

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



Concatenate a list of lists into a single list.


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.



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.


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].


e1, e2

Return the bitwise XOR of the integers e1 and e2.


e1, e2

Return the bitwise OR of the integers e1 and e2.


e1, e2

Return the bitwise AND of the integers e1 and e2.



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.



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



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" ].


pred, list

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


pred, list

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


e1, e2

Return the sum of the numbers e1 and e2.



Abort Nix expression evaluation and print the error message s.

Nixpkgs Library Functions

Assert functions


pred, msg

assertMsg :: Bool -> String -> Bool

Print a trace message if pred is false.

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


name, val, xs

assertOneOf :: String -> String -> StringList -> Bool

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

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"

Attribute-Set Functions


attrPath, default, set

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

Return an attribute from within nested attribute sets.

Extracting a value from a nested attribute set:

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

No value at the path, instead using the default:

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


attrPath, set

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

Determine if an attribute exists within a nested attribute set.

A nested value does exist inside a set:

  [ "a" "b" "c" "d" ]
  { a = { b = { c = { d = 123; }; }; }; }
=> true


attrPath, value

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

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

Creating a new nested attribute set:

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


attrPath, set

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

Like except without a default, and it will throw if the value doesn’t exist.

Succesfully getting a value from an attribute set:

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

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

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


nameList, set

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

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

Getting several values from an attribute set:

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

Getting missing values from an attribute set:

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



attrValues :: AttrSet -> [Any]

Get all the attribute values from an attribute set.


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


attr, sets

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

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

Collect an attribute from a list of attribute sets.:

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


pred, name, value, set, name, value

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

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

Filtering an attributeset:

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


pred, name, value, set, name, value

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

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

Recursively filtering an attribute set:

  (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 = { };


op, val, col, nul, list_of_attrs, val, col

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

Apply fold function to values grouped by key.

Combining an attribute of lists in to one attribute set:

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


pred, value, attrs, value

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

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

Collecting all lists from an attribute set:

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

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

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


name, value

nameValuePair :: String -> Any -> AttrSet

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

Creating a name value pair:

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


fn, name, value, name, value


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

Modifying each value of an attribute set:

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


fn, name, value, set, name, value

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

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.

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"; }


fn, name, value, set, name, value

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

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

Combine attribute values and names in to a list:

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


f, name_path, value, set, name_path, value

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

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.

A contrived example of using lib.attrsets.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";


cond, attributeset, f, name_path, value, set, attributeset, name_path, value

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

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.

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

  ({ 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\"}";


names, f, name, name

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

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

Generate an attrset based on names only:

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



isDerivation :: Any -> Bool

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

A package is a derivation:

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

Anything else is not a derivation:

lib.attrsets.isDerivation "foobar"
=> false



toDerivation :: Path -> Derivation

Converts a store path to a fake derivation.


cond, as

optionalAttrs :: Bool -> AttrSet

Conditionally return an attribute set or an empty attribute set.

Return the provided attribute set when cond is true:

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

Return an empty attribute set when cond is false:

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


names, f, name, vs, sets, name, vs

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

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

Summing a list of attribute sets of numbers:

  [ "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"; }


f, name, vs, sets, name, vs

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

Merge sets of attributes and use the function f to merge attribute values. Similar to where all key names are passed for names.

Summing a list of attribute sets of numbers:

  (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"; }



zipAttrs :: [ AttrSet ] -> AttrSet

Merge sets of attributes and combine each attribute value in to a list. Similar to where the merge function returns a list of all values.

Combining a list of attribute sets:

    { a = 1; b = 1; c = 1; }
    { a = 10; }
    { b = 100; }
    { c = 1000; }
=> { a = [ 1 10 ]; b = [ 1 100 ]; c = [ 1 1000 ]; }


pred, path, l, r, lhs, rhs, path, l, r

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

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.

Recursively merging two attribute sets:

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


lhs, rhs

recursiveUpdate :: AttrSet -> AttrSet -> AttrSet

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.

Recursively merging two attribute sets:

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



recurseIntoAttrs :: AttrSet -> AttrSet

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

Making Nix look inside an attribute set:

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



cartesianProductOfSets :: AttrSet -> [ AttrSet ]

Return the cartesian product of attribute set value combinations.

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; }

Customisation functions


drv, f

overrideDerivation drv f' takes a derivation (i.e., the result of a call to the builtin functionderivation’) and returns a new derivation in which the attributes of the original are overridden according to the function f'. The functionf’ is called with the original derivation attributes.


f, origArgs

makeOverridable takes a function from attribute set to attribute set and injects override attribute which can be used to override arguments of the function.


autoArgs, fn, args

Call the package function in the file fn' with the required arguments automatically. The function is called with the argumentsargs’, but any missing arguments are obtained from `autoArgs’. This function is intended to be partially parameterised, e.g.,


autoArgs, fn, args

Like callPackage, but for a function that returns an attribute set of derivations. The override function is added to the individual attributes.


condition, passthru, drv

Add attributes to each output of a derivation without changing the derivation itself and check a given condition when evaluating.



Strip a derivation of all non-essential attributes, returning only those needed by hydra-eval-jobs. Also strictly evaluate the result to ensure that there are no thunks kept alive to prevent garbage collection.


newScope, f

Make a set of packages with a common scope. All packages called with the provided callPackage' will be evaluated with the same arguments. Any package in the set may depend on any other. TheoverrideScope’function allows subsequent modification of the package set in a consistent way, i.e. all packages in the set will be called with the overridden packages. The package sets may be hierarchical: the packages in the set are called with the scope provided bynewScope’ and the set provides a `newScope’ attribute which can form the parent scope for later package sets.


splicePackages, newScope, otherSplices, keep, extra, f

Like the above, but aims to support cross compilation. It’s still ugly, but hopefully it helps a little bit.

Debugging functions


pred, msg, x

traceIf :: bool -> string -> a -> a

Conditionally trace the supplied message, based on a predicate.

lib.debug.traceIf usage example:

traceIf true "hello" 3
trace: hello
=> 3


f, x

traceValFn :: (a -> b) -> a -> a

Trace the supplied value after applying a function to it, and return the original value.

lib.debug.traceValFn usage example:

traceValFn (v: "mystring ${v}") "foo"
trace: mystring foo
=> "foo"



traceVal :: a -> a

Trace the supplied value and return it.

lib.debug.traceVal usage example:

traceVal 42
# trace: 42
=> 42


x, y

traceSeq :: a -> b -> b

builtins.trace, but the value is builtins.deepSeqed first.

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


depth, x, y

Like traceSeq, but only evaluate down to depth n. This is very useful because lots of traceSeq usages lead to an infinite recursion.

lib.debug.traceSeqN usage example:

traceSeqN 2 { a.b.c = 3; } null
trace: { a = { b = {}; }; }
=> null


f, v

A combination of traceVal and traceSeq that applies a provided function to the value to be traced after deepSeqing it.



A combination of traceVal and traceSeq.


f, depth, v

A combination of traceVal and traceSeqN that applies a provided function to the value to be traced.



A combination of traceVal and traceSeqN.


depth, name, f, v

Trace the input and output of a function f named name, both down to depth.

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; }



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.



Create a test assuming that list elements are true.

lib.debug.testAllTrue usage example:

{ testX = allTrue [ true ]; }

Generator functions



Convert a value to a sensible default string representation. * The builtin toString function has some strange defaults, * suitable for bash scripts but not much else.


pattern, mkValueString, sep, k, v, mkValueString

Generate a line of key k and value v, separated by * character sep. If sep appears in k, it is escaped. * Helper for synaxes with different separators. mkValueString specifies how values should be formatted. mkKeyValueDefault {} “:” “f:oo” “bar” * > “f:oo:bar”


pattern, mkKeyValue, listsAsDuplicateKeys, mkKeyValue, listsAsDuplicateKeys

Generate a key-value-style config file from an attrset. mkKeyValue is the same as in toINI.


pattern, mkSectionName, mkKeyValue, listsAsDuplicateKeys, attrsOfAttrs, mkSectionName, mkKeyValue, listsAsDuplicateKeys

Generate an INI-style config file from an * attrset of sections to an attrset of key-value pairs. generators.toINI {} { * foo = { hi = “${pkgs.hello}”; ciao = “bar”; }; * baz = { “also, integers” = 42; }; * } > [baz] > also, integers=42 > > [foo] > ciao=bar > hi=/nix/store/y93qql1p5ggfnaqjjqhxcw0vqw95rlz0-hello-2.10 * The mk* configuration attributes can generically change * the way sections and key-value strings are generated. For more examples see the test cases in ./tests/misc.nix.


pattern, mkSectionName, mkKeyValue, listsAsDuplicateKeys, pattern, globalSection, sections, mkSectionName, mkKeyValue, listsAsDuplicateKeys, globalSection, sections

Generate an INI-style config file from an attrset * specifying the global section (no header), and an * attrset of sections to an attrset of key-value pairs. generators.toINIWithGlobalSection {} { * globalSection = { * someGlobalKey = “hi”; * }; * sections = { * foo = { hi = “${pkgs.hello}”; ciao = “bar”; }; * baz = { “also, integers” = 42; }; * } > someGlobalKey=hi > > [baz] > also, integers=42 > > [foo] > ciao=bar > hi=/nix/store/y93qql1p5ggfnaqjjqhxcw0vqw95rlz0-hello-2.10 * The mk* configuration attributes can generically change * the way sections and key-value strings are generated. For more examples see the test cases in ./tests/misc.nix. If you don’t need a global section, you can also use * generators.toINI directly, which only takes * the part in sections.



Generate a git-config file from an attrset. It has two major differences from the regular INI format: 1. values are indented with tabs * 2. sections can have sub-sections generators.toGitINI { * url.”ssh://“.insteadOf =””; * = “edolstra”; * } > [url “ssh://”] > insteadOf = > > [user] > name = edolstra



Generates JSON from an arbitrary (non-function) value. * For more information see the documentation of the builtin.



YAML has been a strict superset of JSON since 1.2, so we * use toJSON. Before it only had a few differences referring * to implicit typing rules, so it should work with older * parsers as well.


pattern, allowPrettyValues, multiline, allowPrettyValues, multiline

Pretty print a value, akin to builtins.trace. * Should probably be a builtin as well.



Translate a simple Nix expression to Dhall notation. * Note that integers are translated to Integer and never * the Natural type.

List manipulation functions



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.

lib.lists.singleton usage example:

singleton "foo"
=> [ "foo" ]


xs, f

forEach :: [a] -> (a -> b) -> [b]

Apply the function to each element in the list. Same as map, but arguments flipped.

lib.lists.forEach usage example:

forEach [ 1 2 ] (x:
toString x
=> [ "1" "2" ]


op, nul, list

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)).

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"



fold is an alias of foldr for historic reasons


op, nul, list

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).

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"



foldl' :: (b -> a -> b) -> b -> [a] -> b

Strict version of foldl.


f, list

imap0 :: (int -> a -> b) -> [a] -> [b]

Map with index starting from 0

lib.lists.imap0 usage example:

imap0 (i: v: "${v}-${toString i}") ["a" "b"]
=> [ "a-0" "b-1" ]


f, list

imap1 :: (int -> a -> b) -> [a] -> [b]

Map with index starting from 1

lib.lists.imap1 usage example:

imap1 (i: v: "${v}-${toString i}") ["a" "b"]
=> [ "a-1" "b-2" ]



concatMap :: (a -> [b]) -> [a] -> [b]

Map and concatenate the result.

lib.lists.concatMap usage example:

concatMap (x: [x] ++ ["z"]) ["a" "b"]
=> [ "a" "z" "b" "z" ]



Flatten the argument into a single list; that is, nested lists are spliced into the top-level lists.

lib.lists.flatten usage example:

flatten [1 [2 [3] 4] 5]
=> [1 2 3 4 5]
flatten 1
=> [1]



remove :: a -> [a] -> [a]

Remove elements equal to ‘e’ from a list. Useful for buildInputs.

lib.lists.remove usage example:

remove 3 [ 1 3 4 3 ]
=> [ 1 4 ]


pred, default, multiple, list

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.

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"


pred, default, list

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.

lib.lists.findFirst usage example:

findFirst (x: x > 3) 7 [ 1 6 4 ]
=> 6
findFirst (x: x > 9) 7 [ 1 6 4 ]
=> 7



any :: (a -> bool) -> [a] -> bool

Return true if function pred returns true for at least one element of list.

lib.lists.any usage example:

any isString [ 1 "a" { } ]
=> true
any isString [ 1 { } ]
=> false



all :: (a -> bool) -> [a] -> bool

Return true if function pred returns true for all elements of list.

lib.lists.all usage example:

all (x: x < 3) [ 1 2 ]
=> true
all (x: x < 3) [ 1 2 3 ]
=> false



count :: (a -> bool) -> [a] -> int

Count how many elements of list match the supplied predicate function.

lib.lists.count usage example:

count (x: x == 3) [ 3 2 3 4 6 ]
=> 2


cond, elem

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’).

lib.lists.optional usage example:

optional true "foo"
=> [ "foo" ]
optional false "foo"
=> [ ]


cond, elems

optionals :: bool -> [a] -> [a]

Return a list or an empty list, depending on a boolean value.

lib.lists.optionals usage example:

optionals true [ 2 3 ]
=> [ 2 3 ]
optionals false [ 2 3 ]
=> [ ]



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.

lib.lists.toList usage example:

toList [ 1 2 ]
=> [ 1 2 ]
toList "hi"
=> [ "hi "]


first, last

range :: int -> int -> [int]

Return a list of integers from first' up to and includinglast’.

lib.lists.range usage example:

range 2 4
=> [ 2 3 4 ]
range 3 2
=> [ ]



(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.

lib.lists.partition usage example:

partition (x: x > 2) [ 5 1 2 3 4 ]
=> { right = [ 5 3 4 ]; wrong = [ 1 2 ]; }


op, nul, pred, lst

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.

lib.lists.groupBy’ usage example:

groupBy (x: boolToString (x > 2)) [ 5 1 2 3 4 ]
=> { true = [ 5 3 4 ]; false = [ 1 2 ]; }
groupBy (x: [ {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; }


f, fst, snd

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.

lib.lists.zipListsWith usage example:

zipListsWith (a: b: a + b) ["h" "l"] ["e" "o"]
=> ["he" "lo"]



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.

lib.lists.zipLists usage example:

zipLists [ 1 2 ] [ "a" "b" ]
=> [ { fst = 1; snd = "a"; } { fst = 2; snd = "b"; } ]



reverseList :: [a] -> [a]

Reverse the order of the elements of a list.

lib.lists.reverseList usage example:

reverseList [ "b" "o" "j" ]
=> [ "j" "o" "b" ]


stopOnCycles, before, list

Depth-First Search (DFS) for lists list != [].

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


before, list

Sort a list based on a partial ordering using DFS. This implementation is O(N^2), if your ordering is linear, use sort instead.

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 ]; }



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.

lib.lists.sort usage example:

sort (a: b: a < b) [ 5 3 7 ]
=> [ 3 5 7 ]


cmp, a, b

Compare two lists element-by-element.

lib.lists.compareLists usage example:

compareLists compare [] []
=> 0
compareLists compare [] [ "a" ]
=> -1
compareLists compare [ "a" ] []
=> 1
compareLists compare [ "a" "b" ] [ "a" "c" ]
=> -1



Sort list using “Natural sorting”. Numeric portions of strings are sorted in numeric order.

lib.lists.naturalSort usage example:

naturalSort ["disk11" "disk8" "disk100" "disk9"]
=> ["disk8" "disk9" "disk11" "disk100"]
naturalSort ["" "" ""]
=> ["" "" ""]
naturalSort ["v0.2" "v0.15" "v0.0.9"]
=> [ "v0.0.9" "v0.2" "v0.15" ]



take :: int -> [a] -> [a]

Return the first (at most) N elements of a list.

lib.lists.take usage example:

take 2 [ "a" "b" "c" "d" ]
=> [ "a" "b" ]
take 2 [ ]
=> [ ]


count, list

drop :: int -> [a] -> [a]

Remove the first (at most) N elements of a list.

lib.lists.drop usage example:

drop 2 [ "a" "b" "c" "d" ]
=> [ "c" "d" ]
drop 2 [ ]
=> [ ]


start, count, list

sublist :: int -> int -> [a] -> [a]

Return a list consisting of at most count elements of list, starting at index start.

lib.lists.sublist usage example:

sublist 1 3 [ "a" "b" "c" "d" "e" ]
=> [ "b" "c" "d" ]
sublist 1 3 [ ]
=> [ ]



last :: [a] -> a

Return the last element of a list.

lib.lists.last usage example:

last [ 1 2 3 ]
=> 3



init :: [a] -> [a]

Return all elements but the last.

lib.lists.init usage example:

init [ 1 2 3 ]
=> [ 1 2 ]



Return the image of the cross product of some lists by a function.

lib.lists.crossLists usage example:

crossLists (x:y: "${toString x}${toString y}") [[1 2] [3 4]]
=> [ "13" "14" "23" "24" ]



unique :: [a] -> [a]

Remove duplicate elements from the list. O(n^2) complexity.

lib.lists.unique usage example:

unique [ 3 2 3 4 ]
=> [ 3 2 4 ]



Intersects list ‘e’ and another list. O(nm) complexity.

lib.lists.intersectLists usage example:

intersectLists [ 1 2 3 ] [ 6 3 2 ]
=> [ 3 2 ]



Subtracts list ‘e’ from another list. O(nm) complexity.

lib.lists.subtractLists usage example:

subtractLists [ 3 2 ] [ 1 2 3 4 5 3 ]
=> [ 1 4 5 ]


a, b

Test if two lists have no common element. It should be slightly more efficient than (intersectLists a b == [])

Meta functions


newAttrs, drv

Add to or override the meta attributes of the given derivation.

lib.meta.addMetaAttrs usage example:

addMetaAttrs {description = "Bla blah";} somePkg



Disable Hydra builds of given derivation.


name, drv

Change the symbolic name of a package for presentation purposes (i.e., so that nix-env users can tell them apart).


updater, drv

Like `setName’, but takes the previous name as an argument.

lib.meta.updateName usage example:

updateName (oldName: oldName + "-experimental") somePkg



Append a suffix to the name of a package (before the version part).


f, set

Apply a function to each derivation and only to derivations in an attrset.



Set the nix-env priority of the package.



Decrease the nix-env priority of the package, i.e., other versions/variants of the package will be preferred.



Apply lowPrio to an attrset with derivations



Increase the nix-env priority of the package, i.e., this version/variant of the package will be preferred.



Apply hiPrio to an attrset with derivations


platform, elem

Check to see if a platform is matched by the given meta.platforms element.


platform, pkg

Check if a package is available on a given platform.



getLicenseFromSpdxId :: str -> AttrSet

Get the corresponding attribute in lib.licenses from the SPDX ID. For SPDX IDs, see

lib.meta.getLicenseFromSpdxId usage example:

lib.getLicenseFromSpdxId "MIT" ==
=> true
lib.getLicenseFromSpdxId "mIt" ==
=> true
lib.getLicenseFromSpdxId "MY LICENSE"
=> trace: warning: getLicenseFromSpdxId: No license matches the given SPDX ID: MY LICENSE
=> { shortName = "MY LICENSE"; }



getExe :: derivation -> string

Get the path to the main program of a derivation with either meta.mainProgram or pname or name

lib.meta.getExe usage example:

getExe pkgs.hello
=> "/nix/store/g124820p9hlv4lj8qplzxw1c44dxaw1k-hello-2.12/bin/hello"
getExe pkgs.mustache-go
=> "/nix/store/am9ml4f4ywvivxnkiaqwr0hyxka1xjsf-mustache-go-1.3.0/bin/mustache"

Modules functions



Evaluate a set of modules. The result is a set with the attributes:



Collects all modules recursively into the form


file, m

Wrap a module with a default location for reporting errors.


file, key, m

Massage a module into canonical form, that is, a set consisting of ‘options’, ‘config’ and ‘imports’ attributes.


prefix, modules

Merge a list of modules. This will recurse over the option declarations in all modules, combining them into a single set. At the same time, for each option declaration, it will merge the corresponding option definitions in all machines, returning them in the ‘value’ attribute of each option.


attr, f, modules

byName is like foldAttrs, but will look for attributes to merge in the specified attribute name.



Merge multiple option declarations into a single declaration. In general, there should be only one declaration of each option. The exception is the ‘options’ attribute, which specifies sub-options. These can be specified multiple times to allow one module to add sub-options to an option declared somewhere else (e.g. multiple modules define sub-options for ‘fileSystems’).


loc, opt, defs

Merge all the definitions of an option to produce the final config value.



Given a config set, expand mkMerge properties, and push down the other properties into the children. The result is a list of config sets that do not have properties at top-level. For example,



Given a config value, expand mkMerge properties, and discharge any mkIf conditions. That is, this is the place where mkIf conditions are actually evaluated. The result is a list of config values. For example, ‘mkIf false x’ yields ‘[]’, ‘mkIf true x’ yields ‘[x]’, and



Given a list of config values, process the mkOverride properties, that is, return the values that have the highest (that is, numerically lowest) priority, and strip the mkOverride properties. For example,



Sort a list of properties. The sort priority of a property is 1000 by default, but can be overridden by wrapping the property using mkOrder.


condition, content



modules, args



optionName, replacementInstructions, pattern, options, options

Return a module that causes a warning to be shown if the specified option is defined. For example,


from, to

Return a module that causes a warning to be shown if the specified “from” option is defined; the defined value is however forwarded to the “to” option. This can be used to rename options while providing backward compatibility. For example,


from, to, mergeFn, pattern, config, options, config, options

Return a module that causes a warning to be shown if any of the “from” option is defined; the defined values can be used in the “mergeFn” to set the “to” value. This function can be used to merge multiple options into one that has a different type.


from, to, changeFn

Single “from” version of mkMergedOptionModule. Return a module that causes a warning to be shown if the “from” option is defined; the defined value can be used in the “mergeFn” to set the “to” value. This function can be used to change an option into another that has a different type.


from, to

Like ‘mkRenamedOptionModule’, but doesn’t show a warning.


opt, f

mkDerivedConfig : Option a -> (a -> Definition b) -> Definition b



Use this function to import a JSON file as NixOS configuration.



Use this function to import a TOML file as NixOS configuration.

NixOS / nixpkgs option handling



isOption :: a -> bool

Returns true when the given argument is an option

lib.options.isOption usage example:

isOption 1             // => false
isOption (mkOption {}) // => true


pattern, default, defaultText, example, description, relatedPackages, type, apply, internal, visible, readOnly, default, defaultText, example, description, relatedPackages, type, apply, internal, visible, readOnly

Creates an Option attribute set. mkOption accepts an attribute set with the following keys:

lib.options.mkOption usage example:

mkOption { }  // => { _type = "option"; }
mkOption { default = "foo"; } // => { _type = "option"; default = "foo"; }



Creates an Option attribute set for a boolean value option i.e an option to be toggled on or off:

lib.options.mkEnableOption usage example:

mkEnableOption "foo"
=> { _type = "option"; default = false; description = "Whether to enable foo."; example = true; type = { ... }; }


pkgs, name, pattern, default, example, default, example

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.

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.packages.ghc924.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 = { ... }; }



This option accepts anything, but it does not produce any result.


loc, defs

“Merge” option definitions by checking that they all have the same value.



getValues :: [ { value :: a } ] -> [a]

Extracts values of all “value” keys of the given list.

lib.options.getValues usage example:

getValues [ { value = 1; } { value = 2; } ] // => [ 1 2 ]
getValues [ ]                               // => [ ]



getFiles :: [ { file :: a } ] -> [a]

Extracts values of all “file” keys of the given list

lib.options.getFiles usage example:

getFiles [ { file = "file1"; } { file = "file2"; } ] // => [ "file1" "file2" ]
getFiles [ ]                                         // => [ ]



This function recursively removes all derivation attributes from x except for the name attribute.



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.



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.



Transition marker for documentation that’s already migrated to markdown syntax.



For use in the defaultText and example option attributes. Causes the given MD text to be inserted verbatim in the documentation, for when a literalExpression would be too hard to read.



Convert an option, described as a list of the option parts in to a safe, human readable version.

lib.options.showOption usage example:

(showOption ["foo" "bar" "baz"]) == ""
(showOption ["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"

Source filtering functions



Returns the type of a path: regular (for file), symlink, or directory.



Returns true if the path exists and is a directory, false otherwise.



Returns true if the path exists and is a regular file, false otherwise.


name, type

A basic filter for cleanSourceWith that removes directories of version control system, backup files (*~) and some generated files.



Filters a source tree removing version control files and directories using cleanSourceFilter.

lib.sources.cleanSource usage example:

cleanSource ./.


pattern, src, filter, name, src, filter, name

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.

lib.sources.cleanSourceWith usage example:

lib.cleanSourceWith {
filter = f;
src = lib.cleanSourceWith {
filter = g;
src = ./.;
# Succeeds!

builtins.filterSource f (builtins.filterSource g ./.)
# Fails!



sources.trace :: sourceLike -> Source

Add logging to a source, for troubleshooting the filtering behavior.


src, regexes

Filter sources by a list of regular expressions.

lib.sources.sourceByRegex usage example:

src = sourceByRegex ./my-subproject [".*\.py$" "^database.sql$"]


src, exts

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.

lib.sources.sourceFilesBySuffices usage example:

sourceFilesBySuffices ./. [ ".xml" ".c" ]



Get the commit id of a git repo.

lib.sources.commitIdFromGitRepo usage example:

commitIdFromGitRepo <nixpkgs/.git>

String manipulation functions



concatStrings :: [string] -> string

Concatenate a list of strings.

lib.strings.concatStrings usage example:

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


f, list

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

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

lib.strings.concatMapStrings usage example:

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


f, list

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

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

lib.strings.concatImapStrings usage example:

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


separator, list

intersperse :: a -> [a] -> [a]

Place an element between each element of a list

lib.strings.intersperse usage example:

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



concatStringsSep :: string -> [string] -> string

Concatenate a list of strings with a separator between each element

lib.strings.concatStringsSep usage example:

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


sep, f, list

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.

lib.strings.concatMapStringsSep usage example:

concatMapStringsSep "-" (x: toUpper x)  ["foo" "bar" "baz"]


sep, f, list

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

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

lib.strings.concatImapStringsSep usage example:

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


subDir, paths

makeSearchPath :: string -> [string] -> string

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

lib.strings.makeSearchPath usage example:

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


output, subDir, pkgs

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.

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"



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

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"



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

lib.strings.makeBinPath usage example:

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


cond, string

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.

lib.strings.optionalString usage example:

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


pref, str

hasPrefix :: string -> string -> bool

Determine whether a string has given prefix.

lib.strings.hasPrefix usage example:

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


suffix, content

hasSuffix :: string -> string -> bool

Determine whether a string has given suffix.

lib.strings.hasSuffix usage example:

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


infix, content

hasInfix :: string -> string -> bool

Determine whether a string contains the given infix

lib.strings.hasInfix usage example:

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



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.

lib.strings.stringToCharacters usage example:

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


f, s

stringAsChars :: (string -> string) -> string -> string

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

lib.strings.stringAsChars usage example:

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



escape :: [string] -> string -> string

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

lib.strings.escape usage example:

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



escapeShellArg :: string -> string

Quote string to be used safely within the Bourne shell.

lib.strings.escapeShellArg usage example:

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



escapeShellArgs :: [string] -> string

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

lib.strings.escapeShellArgs usage example:

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



string -> bool

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

lib.strings.isValidPosixName usage example:

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


name, value

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

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

lib.strings.toShellVar usage example:

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



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

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

lib.strings.toShellVars usage example:

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



string -> string

Turn a string into a Nix expression representing that string

lib.strings.escapeNixString usage example:

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



string -> string

Turn a string into an exact regular expression

lib.strings.escapeRegex usage example:

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



string -> string

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

lib.strings.escapeNixIdentifier usage example:

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



string -> string

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

lib.strings.escapeXML usage example:

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



toLower :: string -> string

Converts an ASCII string to lower-case.

lib.strings.toLower usage example:

toLower "HOME"
=> "home"



toUpper :: string -> string

Converts an ASCII string to upper-case.

lib.strings.toUpper usage example:

toUpper "home"
=> "HOME"


a, b

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

lib.strings.addContextFrom usage example:

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


__sep, s

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

lib.strings.splitString usage example:

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


prefix, str

string -> string -> string

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

lib.strings.removePrefix usage example:

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


suffix, str

string -> string -> string

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

lib.strings.removeSuffix usage example:

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


v1, v2

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

lib.strings.versionOlder usage example:

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


v1, v2

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

lib.strings.versionAtLeast usage example:

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



This function takes an argument that’s either a derivation or a derivation’s “name” attribute and extracts the name part from that argument.

lib.strings.getName usage example:

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



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

lib.strings.getVersion usage example:

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


url, sep

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

lib.strings.nameFromURL usage example:

nameFromURL "" "-"
=> "nix"
nameFromURL "" "_"
=> "nix-1.7-x86"


enable, feat

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

lib.strings.enableFeature usage example:

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


enable, feat, value

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

lib.strings.enableFeatureAs usage example:

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


with, feat_

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

lib.strings.withFeature usage example:

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


with, feat, value_

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

lib.strings.withFeatureAs usage example:

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


width, filler, str

fixedWidthString :: int -> string -> string -> string

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

lib.strings.fixedWidthString usage example:

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


width, n

Format a number adding leading zeroes up to fixed width.

lib.strings.fixedWidthNumber usage example:

fixedWidthNumber 5 15
=> "00015"



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

lib.strings.floatToString usage example:

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



Check whether a value can be coerced to a string



Check whether a value is a store path.

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



string -> int

Parse a string as an int.

lib.strings.toInt usage example:

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



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

lib.strings.readPathsFromFile usage example:

readPathsFromFile /prefix
=> [ "/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/compose-search-path.patch" ]



fileContents :: path -> string

Read the contents of a file removing the trailing

lib.strings.fileContents usage example:

$ echo "1.0" > ./version

fileContents ./version
=> "1.0"



sanitizeDerivationName :: String -> String

Creates a valid derivation name from a potentially invalid one.

lib.strings.sanitizeDerivationName usage example:

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


a, b

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

lib.strings.levenshtein usage example:

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


a, b

Returns the length of the prefix common to both strings.


a, b

Returns the length of the suffix common to both strings.



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

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

Miscellaneous functions


id :: a -> a

The identity function For when you need a function that does “nothing”.


x, y

const :: a -> b -> a

The constant function

lib.trivial.const usage example:

let f = const 5; in f 10
=> 5


val, functions

pipe :: a -> [<functions>] -> <return type of last function>

Pipes a value through a list of functions, left to right.

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

# 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.


x, y

concat :: [a] -> [a] -> [a]

Concatenate two lists

lib.trivial.concat usage example:

concat [ 1 2 ] [ 3 4 ]
=> [ 1 2 3 4 ]


x, y

boolean “or”


x, y

boolean “and”



bitwise “and”



bitwise “or”



bitwise “xor”



bitwise “not”



boolToString :: bool -> string

Convert a boolean to a string.


x, y

Merge two attribute sets shallowly, right side trumps left

lib.trivial.mergeAttrs usage example:

mergeAttrs { a = 1; b = 2; } { b = 3; c = 4; }
=> { a = 1; b = 3; c = 4; }


f, a, b

flip :: (a -> b -> c) -> (b -> a -> c)

Flip the order of the arguments of a binary function.

lib.trivial.flip usage example:

flip concat [1] [2]
=> [ 2 1 ]


f, a

Apply function if the supplied argument is non-null.

lib.trivial.mapNullable usage example:

mapNullable (x: x+1) null
=> null
mapNullable (x: x+1) 22
=> 23



Returns the current full nixpkgs version number.



Returns the current nixpkgs release number as string.



The latest release that is supported, at the time of release branch-off, if applicable.



Whether a feature is supported in all supported releases (at the time of release branch-off, if applicable). See oldestSupportedRelease.



Returns the current nixpkgs release code name.



Returns the current nixpkgs version suffix as string.



revisionWithDefault :: string -> string

Attempts to return the the current revision of nixpkgs and returns the supplied default value otherwise.



inNixShell :: bool

Determine whether the function is being called from inside a Nix shell.



inPureEvalMode :: bool

Determine whether the function is being called from inside pure-eval mode by seeing whether builtins contains currentSystem. If not, we must be in pure-eval mode.


x, y

Return minimum of two numbers.


x, y

Return maximum of two numbers.


base, int

Integer modulus

lib.trivial.mod usage example:

mod 11 10
=> 1
mod 1 10
=> 1

a, b

C-style comparisons


p, yes, no, a, b

(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.

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



Reads a JSON file.



Reads a TOML file.



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.


cond, msg

bool -> string -> a -> a

Like warn, but only warn when the first argument is true.


cond, msg

bool -> string -> a -> a

Like warnIf, but negated (warn if the first argument is false).


cond, msg

bool -> string -> a -> a

Like the assert b; e expression, but with a custom error message and without the semicolon.

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


cond, msg

bool -> string -> a -> a

Like throwIfNot, but negated (throw if the first argument is true).


msg, valid, given

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.

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


f, args

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)



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.



Check whether something is a function or something annotated with function args.



Turns any non-callable values into constant functions. Returns callable values as is.

lib.trivial.toFunction usage example:

nix-repl> lib.toFunction 1 2

nix-repl> lib.toFunction (x: x + 1) 2



Convert the given positive integer to a string of its hexadecimal representation. For example:


base, i

toBaseDigits base i converts the positive integer i to a list of its digits in the given base. For example:

Versions functions



Break a version string into its component parts.

lib.versions.splitVersion usage example:

splitVersion "1.2.3"
=> ["1" "2" "3"]



Get the major version string from a string.

lib.versions.major usage example:

major "1.2.3"
=> "1"



Get the minor version string from a string.

lib.versions.minor usage example:

minor "1.2.3"
=> "2"



Get the patch version string from a string.

lib.versions.patch usage example:

patch "1.2.3"
=> "3"



Get string of the first two parts (major and minor) of a version string.

lib.versions.majorMinor usage example:

majorMinor "1.2.3"
=> "1.2"

Theme: jez/pandoc-markdown-css-theme