Nix Flashcards

Nix commands

1
Q

Abort Nix expression evaluation and print the error message s.

A

abort s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

abort s

A

Abort Nix expression evaluation and print the error message s.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

add e1 e2

A

Return the sum of the numbers e1 and e2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Return the sum of the numbers e1 and e2.

A

add e1 e2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

all pred list

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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

A

all pred list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

any pred list

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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

A

any pred list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

attrNames set

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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

A

attrNames set

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

attrValues set

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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

A

attrValues set

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

baseNameOf s

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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.

A

baseNameOf s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

bitAnd e1 e2

A

Return the bitwise AND of the integers e1 and e2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Return the bitwise AND of the integers e1 and e2.

A

bitAnd e1 e2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

bitOr e1 e2

A

Return the bitwise OR of the integers e1 and e2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Return the bitwise OR of the integers e1 and e2.

A

bitOr e1 e2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

bitXor e1 e2

A

Return the bitwise XOR of the integers e1 and e2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Return the bitwise XOR of the integers e1 and e2.

A

bitXor e1 e2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

break v

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

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

A

break v

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

catAttrs attr list

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

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

A

catAttrs attr list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
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.
26
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.
ceil double
27
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.
28
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.
compareVersions s1 s2
29
concatLists lists
Concatenate a list of lists into a single list.
30
Concatenate a list of lists into a single list.
concatLists lists
31
concatMap f list
This function is equivalent to builtins.concatLists (map f list) but is more efficient.
32
This function is equivalent to builtins.concatLists (map f list) but is more efficient.
concatMap f list
33
concatStringsSep separator list
Concatenate a list of strings with a separator between each element, e.g. concatStringsSep "/" ["usr" "local" "bin"] == "usr/local/bin".
34
Concatenate a list of strings with a separator between each element, e.g. concatStringsSep "/" ["usr" "local" "bin"] == "usr/local/bin".
concatStringsSep separator list
35
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.
36
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.
deepSeq e1 e2
37
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.
38
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.
dirOf s
39
div e1 e2
Return the quotient of the numbers e1 and e2.
40
Return the quotient of the numbers e1 and e2.
div e1 e2
41
elem x xs
Return true if a value equal to x occurs in the list xs, and false otherwise.
42
Return true if a value equal to x occurs in the list xs, and false otherwise.
elem x xs
43
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.
44
Return element n from the list xs. Elements are counted starting from 0. A fatal error occurs if the index is out of bounds.
elemAt xs n
45
filter f list
Return a list consisting of the elements of list for which the function f returns true.
46
Return a list consisting of the elements of list for which the function f returns true.
filter f list
47
flakeRefToString attrs
Convert a flake reference from attribute set format to URL format. For example: builtins.flakeRefToString { dir = "lib"; owner = "NixOS"; ref = "23.05"; repo = "nixpkgs"; type = "github"; } evaluates to "github:NixOS/nixpkgs/23.05?dir=lib" This function is only available if the flakes experimental feature is enabled.
48
Convert a flake reference from attribute set format to URL format. For example: builtins.flakeRefToString { dir = "lib"; owner = "NixOS"; ref = "23.05"; repo = "nixpkgs"; type = "github"; } evaluates to "github:NixOS/nixpkgs/23.05?dir=lib" This function is only available if the flakes experimental feature is enabled.
flakeRefToString attrs
49
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.
50
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.
floor double
51
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) .... For example, foldl' (x: y: x + y) 0 [1 2 3] evaluates to 6. The return value of each application of op is evaluated immediately, even for intermediate values.
52
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) .... For example, foldl' (x: y: x + y) 0 [1 2 3] evaluates to 6. The return value of each application of op is evaluated immediately, even for intermediate values.
foldl' op nul list
53
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; }.
54
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; }.
fromJSON e
55
fromTOML e
Convert a TOML string to a Nix value. For example, builtins.fromTOML '' x=1 s="a" [table] y=2 '' returns the value { s = "a"; table = { y = 2; }; x = 1; }.
56
Convert a TOML string to a Nix value. For example, builtins.fromTOML '' x=1 s="a" [table] y=2 '' returns the value { s = "a"; table = { y = 2; }; x = 1; }.
fromTOML e
57
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: ...) = { }.
58
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: ...) = { }.
functionArgs f
59
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 ].
60
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 ].
genList generator length
61
genericClosure attrset
Take an attrset with values named startSet and operator in order to return a list of attrsets by starting with the startSet and recursively applying the operator function to each item. The attrsets in the startSet and the attrsets produced by operator must contain a value named key which is comparable. The result is produced by calling operator for each item with a value for key that has not been called yet including newly produced items. The function terminates when no new items are produced. The resulting list of attrsets contains only attrsets with a unique key. 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; } ]
62
Take an attrset with values named startSet and operator in order to return a list of attrsets by starting with the startSet and recursively applying the operator function to each item. The attrsets in the startSet and the attrsets produced by operator must contain a value named key which is comparable. The result is produced by calling operator for each item with a value for key that has not been called yet including newly produced items. The function terminates when no new items are produced. The resulting list of attrsets contains only attrsets with a unique key. 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; } ]
genericClosure attrset
63
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.
64
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.
getAttr s set
65
getContext s
Return the string context of s. The string context tracks references to derivations within a string. It is represented as an attribute set of store derivation paths mapping to output names. Using string interpolation on a derivation will add that derivation to the string context. For example, builtins.getContext "${derivation { name = "a"; builder = "b"; system = "c"; }}" evaluates to { "/nix/store/arhvjaf6zmlyn8vh8fgn55rpwnxq0n7l-a.drv" = { outputs = [ "out" ]; }; }
66
Return the string context of s. The string context tracks references to derivations within a string. It is represented as an attribute set of store derivation paths mapping to output names. Using string interpolation on a derivation will add that derivation to the string context. For example, builtins.getContext "${derivation { name = "a"; builder = "b"; system = "c"; }}" evaluates to { "/nix/store/arhvjaf6zmlyn8vh8fgn55rpwnxq0n7l-a.drv" = { outputs = [ "out" ]; }; }
getContext s
67
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.)
68
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.)
getEnv s
69
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 the flakes experimental feature is enabled.
70
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 the flakes experimental feature is enabled.
getFlake args
71
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" ]; }
72
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" ]; }
groupBy f list
73
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.
74
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.
hasAttr s set
75
hasContext s
Return true if string s has a non-empty context. The context can be obtained with getContext.
76
Return true if string s has a non-empty context. The context can be obtained with getContext.
hasContext s
77
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".
78
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".
hashFile type p
79
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".
80
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".
hashString type s
81
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 [].
82
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 [].
head list
83
import path
Load, parse and return the Nix expression in the file path. The value path can be a path, a string, or an attribute set with an __toString attribute or a outPath attribute (as derivations or flake inputs typically have). 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 ) 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; } and x: x + 456 (The function argument doesn’t have to be called x in foo.nix; any name would work.)
84
Load, parse and return the Nix expression in the file path. The value path can be a path, a string, or an attribute set with an __toString attribute or a outPath attribute (as derivations or flake inputs typically have). 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 ) 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; } and x: x + 456 (The function argument doesn’t have to be called x in foo.nix; any name would work.)
import path
85
intersectAttrs e1 e2
Return a set consisting of the attributes in the set e2 which have the same name as some attribute in e1. Performs in O(n log m) where n is the size of the smaller set and m the larger set's size.
86
Return a set consisting of the attributes in the set e2 which have the same name as some attribute in e1. Performs in O(n log m) where n is the size of the smaller set and m the larger set's size.
intersectAttrs e1 e2
87
isAttrs e
Return true if e evaluates to a set, and false otherwise.
88
Return true if e evaluates to a set, and false otherwise.
isAttrs e
89
isBool e
Return true if e evaluates to a bool, and false otherwise.
90
Return true if e evaluates to a bool, and false otherwise.
isBool e
91
isFloat e
Return true if e evaluates to a float, and false otherwise.
92
Return true if e evaluates to a float, and false otherwise.
isFloat e
93
isFunction e
Return true if e evaluates to a function, and false otherwise.
94
Return true if e evaluates to a function, and false otherwise.
isFunction e
95
isInt e
Return true if e evaluates to an integer, and false otherwise.
96
Return true if e evaluates to an integer, and false otherwise.
isInt e
97
isList e
Return true if e evaluates to a list, and false otherwise.
98
Return true if e evaluates to a list, and false otherwise.
isList e
99
isNull e
Return true if e evaluates to null, and false otherwise. Warning This function is deprecated; just write e == null instead.
100
Return true if e evaluates to null, and false otherwise. Warning This function is deprecated; just write e == null instead.
isNull e
101
isPath e
Return true if e evaluates to a path, and false otherwise.
102
Return true if e evaluates to a path, and false otherwise.
isPath e
103
isString e
Return true if e evaluates to a string, and false otherwise.
104
Return true if e evaluates to a string, and false otherwise.
isString e
105
length e
Return the length of the list e.
106
Return the length of the list e.
length e
107
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.
108
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.
lessThan e1 e2
109
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. In case of duplicate occurrences of the same name, the first takes precedence. Example: builtins.listToAttrs [ { name = "foo"; value = 123; } { name = "bar"; value = 456; } { name = "bar"; value = 420; } ] evaluates to { foo = 123; bar = 456; }
110
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. In case of duplicate occurrences of the same name, the first takes precedence. Example: builtins.listToAttrs [ { name = "foo"; value = 123; } { name = "bar"; value = 456; } { name = "bar"; value = 420; } ] evaluates to { foo = 123; bar = 456; }
listToAttrs e
111
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" ].
112
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" ].
map f list
113
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; }.
114
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; }.
mapAttrs f attrset
115
match 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" ].
116
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" ].
match regex str
117
mul e1 e2
Return the product of the numbers e1 and e2.
118
Return the product of the numbers e1 and e2.
mul e1 e2
119
outputOf derivation-reference output-name
Return the output path of a derivation, literally or using a placeholder if needed. If the derivation has a statically-known output path (i.e. the derivation output is input-addressed, or fixed content-addresed), the output path will just be returned. But if the derivation is content-addressed or if the derivation is itself not-statically produced (i.e. is the output of another derivation), a placeholder will be returned instead. derivation reference must be a string that may contain a regular store path to a derivation, or may be a placeholder reference. If the derivation is produced by a derivation, you must explicitly select drv.outPath. This primop can be chained arbitrarily deeply. For instance, builtins.outputOf (builtins.outputOf myDrv "out) "out" will return a placeholder for the output of the output of myDrv. This primop corresponds to the ^ sigil for derivable paths, e.g. as part of installable syntax on the command line. This function is only available if the dynamic-derivations experimental feature is enabled.
120
Return the output path of a derivation, literally or using a placeholder if needed. If the derivation has a statically-known output path (i.e. the derivation output is input-addressed, or fixed content-addresed), the output path will just be returned. But if the derivation is content-addressed or if the derivation is itself not-statically produced (i.e. is the output of another derivation), a placeholder will be returned instead. derivation reference must be a string that may contain a regular store path to a derivation, or may be a placeholder reference. If the derivation is produced by a derivation, you must explicitly select drv.outPath. This primop can be chained arbitrarily deeply. For instance, builtins.outputOf (builtins.outputOf myDrv "out) "out" will return a placeholder for the output of the output of myDrv. This primop corresponds to the ^ sigil for derivable paths, e.g. as part of installable syntax on the command line. This function is only available if the dynamic-derivations experimental feature is enabled.
outputOf derivation-reference output-name
121
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 not followed by a letter, 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"; }.
122
Split the string s into a package name and version. The package name is everything up to but not including the first dash not followed by a letter, 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"; }.
parseDrvName s
123
parseFlakeRef flake-ref
Parse a flake reference, and return its exploded form. For example: builtins.parseFlakeRef "github:NixOS/nixpkgs/23.05?dir=lib" evaluates to: { dir = "lib"; owner = "NixOS"; ref = "23.05"; repo = "nixpkgs"; type = "github"; } This function is only available if the flakes experimental feature is enabled.
124
Parse a flake reference, and return its exploded form. For example: builtins.parseFlakeRef "github:NixOS/nixpkgs/23.05?dir=lib" evaluates to: { dir = "lib"; owner = "NixOS"; ref = "23.05"; repo = "nixpkgs"; type = "github"; } This function is only available if the flakes experimental feature is enabled.
parseFlakeRef flake-ref
125
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 ]; }
126
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 ]; }
partition pred list
127
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.
128
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.
path args
129
pathExists path
Return true if the path path exists at evaluation time, and false otherwise.
130
Return true if the path path exists at evaluation time, and false otherwise.
pathExists path
131
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".
132
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".
placeholder output
133
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".
134
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".
readDir path
135
readFile path
Return the contents of the file path as a string.
136
Return the contents of the file path as a string.
readFile path
137
readFileType p
Determine the directory entry type of a filesystem node, being one of "directory", "regular", "symlink", or "unknown".
138
Determine the directory entry type of a filesystem node, being one of "directory", "regular", "symlink", or "unknown".
readFileType p
139
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; }.
140
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; }.
removeAttrs set list
141
replaceStrings from to s
Given string s, replace every occurrence of the strings in from with the corresponding string in to. The argument to is lazy, that is, it is only evaluated when its corresponding pattern in from is matched in the string s Example: builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar" evaluates to "fabir".
142
Given string s, replace every occurrence of the strings in from with the corresponding string in to. The argument to is lazy, that is, it is only evaluated when its corresponding pattern in from is matched in the string s Example: builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar" evaluates to "fabir".
replaceStrings from to s
143
seq e1 e2
Evaluate e1, then evaluate and return e2. This ensures that a computation is strict in the value of e1.
144
Evaluate e1, then evaluate and return e2. This ensures that a computation is strict in the value of e1.
seq e1 e2
145
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.
146
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.
sort comparator list
147
split 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" ] " " ].
148
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" ] " " ].
split regex str
149
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.
150
Split a string representing a version into its components, by the same version splitting logic underlying the version comparison in nix-env -u.
splitVersion s
151
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). Not available in pure evaluation mode. See also builtins.fetchClosure.
152
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). Not available in pure evaluation mode. See also builtins.fetchClosure.
storePath path
153
stringLength e
Return the length of the string e. If e is not a string, evaluation is aborted.
154
Return the length of the string e. If e is not a string, evaluation is aborted.
stringLength e
155
sub e1 e2
Return the difference between the numbers e1 and e2.
156
Return the difference between the numbers e1 and e2.
sub e1 e2
157
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".
158
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".
substring start len s
159
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.
160
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.
tail list
161
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).
162
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).
throw s
163
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 and its build script 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 a string interpolation, 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.
164
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 "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 a string interpolation, 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.
toFile name s
165
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.
166
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.
toJSON e
167
toPath s
DEPRECATED. Use /. + "/path" to convert a string into an absolute path. For relative paths, use ./. + "/path".
168
DEPRECATED. Use /. + "/path" to convert a string into an absolute path. For relative paths, use ./. + "/path".
toPath s
169
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.
170
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.
toString e
171
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" ② " "; 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: 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}.
172
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" ② " "; 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: 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}.
toXML e
173
trace e1 e2
Evaluate e1 and print its abstract syntax representation on standard error. Then return e2. This function is useful for debugging.
174
Evaluate e1 and print its abstract syntax representation on standard error. Then return e2. This function is useful for debugging.
trace e1 e2
175
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.
176
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.
traceVerbose e1 e2
177
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.
178
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.
tryEval e
179
typeOf e
Return a string representing the type of the value e, namely "int", "bool", "string", "path", "null", "set", "list", "lambda" or "float".
180
Return a string representing the type of the value e, namely "int", "bool", "string", "path", "null", "set", "list", "lambda" or "float".
typeOf e
181
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" ]; }; }
182
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" ]; }; }
zipAttrsWith f list
183
fetchClosure args
Fetch a store path closure from a binary cache, and return the store path as a string with context. This function can be invoked in three ways, that we will discuss in order of preference. Fetch a content-addressed store path Example: builtins.fetchClosure { fromStore = "https://cache.nixos.org"; fromPath = /nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1; } This is the simplest invocation, and it does not require the user of the expression to configure trusted-public-keys to ensure their authenticity. If your store path is input addressed instead of content addressed, consider the other two invocations. Fetch any store path and rewrite it to a fully content-addressed store path Example: builtins.fetchClosure { fromStore = "https://cache.nixos.org"; fromPath = /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1; toPath = /nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1; } This example fetches /nix/store/r2jd... from the specified binary cache, and rewrites it into the content-addressed store path /nix/store/ldbh.... Like the previous example, no extra configuration or privileges are required. To find out the correct value for toPath given a fromPath, 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' Alternatively, set toPath = "" and find the correct toPath in the error message. Fetch an input-addressed store path as is Example: builtins.fetchClosure { fromStore = "https://cache.nixos.org"; fromPath = /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1; inputAddressed = true; } It is possible to fetch an input-addressed store path and return it as is. However, this is the least preferred way of invoking fetchClosure, because it requires that the input-addressed paths are trusted by the Nix configuration. builtins.storePath fetchClosure is similar to builtins.storePath in that it allows you to use a previously built store path in a Nix expression. However, fetchClosure is more reproducible because it specifies a binary cache from which the path can be fetched. Also, using content-addressed store paths does not require users to configure trusted-public-keys to ensure their authenticity. This function is only available if the fetch-closure experimental feature is enabled.
184
Fetch a store path closure from a binary cache, and return the store path as a string with context. This function can be invoked in three ways, that we will discuss in order of preference. Fetch a content-addressed store path Example: builtins.fetchClosure { fromStore = "https://cache.nixos.org"; fromPath = /nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1; } This is the simplest invocation, and it does not require the user of the expression to configure trusted-public-keys to ensure their authenticity. If your store path is input addressed instead of content addressed, consider the other two invocations. Fetch any store path and rewrite it to a fully content-addressed store path Example: builtins.fetchClosure { fromStore = "https://cache.nixos.org"; fromPath = /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1; toPath = /nix/store/ldbhlwhh39wha58rm61bkiiwm6j7211j-git-2.33.1; } This example fetches /nix/store/r2jd... from the specified binary cache, and rewrites it into the content-addressed store path /nix/store/ldbh.... Like the previous example, no extra configuration or privileges are required. To find out the correct value for toPath given a fromPath, 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' Alternatively, set toPath = "" and find the correct toPath in the error message. Fetch an input-addressed store path as is Example: builtins.fetchClosure { fromStore = "https://cache.nixos.org"; fromPath = /nix/store/r2jd6ygnmirm2g803mksqqjm4y39yi6i-git-2.33.1; inputAddressed = true; } It is possible to fetch an input-addressed store path and return it as is. However, this is the least preferred way of invoking fetchClosure, because it requires that the input-addressed paths are trusted by the Nix configuration. builtins.storePath fetchClosure is similar to builtins.storePath in that it allows you to use a previously built store path in a Nix expression. However, fetchClosure is more reproducible because it specifies a binary cache from which the path can be fetched. Also, using content-addressed store paths does not require users to configure trusted-public-keys to ensure their authenticity. This function is only available if the fetch-closure experimental feature is enabled.
fetchClosure args
185
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 (default: basename of the URL) The name of the directory the repo should be exported to in the store. rev (default: the tip of ref) The Git revision to fetch. This is typically a commit hash. ref (default: HEAD) The Git reference under which to look for the requested revision. This is often a branch or tag name. By default, the ref value is prefixed with refs/heads/. As of 2.3.0, Nix will not prefix refs/heads/ if ref starts with refs/. submodules (default: false) A Boolean parameter that specifies whether submodules should be checked out. shallow (default: false) A Boolean parameter that specifies whether fetching from a shallow remote repository is allowed. This still performs a full clone of what is available on the remote. allRefs Whether to fetch all references of the repository. With this argument being true, it's possible to load a rev from any ref (by default only revs 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"; } Nix will refetch the branch according to the tarball-ttl setting. This behavior is disabled in pure evaluation mode. To fetch the content of a checked-out work directory: builtins.fetchGit ./work-dir If the URL points to a local directory, and no ref or rev is given, fetchGit will use the current content of the checked-out files, even if they are not committed or added to Git's index. It will only consider files added to the Git repository, as listed by git ls-files.
186
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 (default: basename of the URL) The name of the directory the repo should be exported to in the store. rev (default: the tip of ref) The Git revision to fetch. This is typically a commit hash. ref (default: HEAD) The Git reference under which to look for the requested revision. This is often a branch or tag name. By default, the ref value is prefixed with refs/heads/. As of 2.3.0, Nix will not prefix refs/heads/ if ref starts with refs/. submodules (default: false) A Boolean parameter that specifies whether submodules should be checked out. shallow (default: false) A Boolean parameter that specifies whether fetching from a shallow remote repository is allowed. This still performs a full clone of what is available on the remote. allRefs Whether to fetch all references of the repository. With this argument being true, it's possible to load a rev from any ref (by default only revs 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"; } Nix will refetch the branch according to the tarball-ttl setting. This behavior is disabled in pure evaluation mode. To fetch the content of a checked-out work directory: builtins.fetchGit ./work-dir If the URL points to a local directory, and no ref or rev is given, fetchGit will use the current content of the checked-out files, even if they are not committed or added to Git's index. It will only consider files added to the Git repository, as listed by git ls-files.
fetchGit args
187
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 { … } Not available in restricted evaluation mode.
188
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 { … } Not available in restricted evaluation mode.
fetchTarball args
189
fetchurl url
fetchurl url Download the specified URL and return the path of the downloaded file. Not available in restricted evaluation mode.
190
fetchurl url Download the specified URL and return the path of the downloaded file. Not available in restricted evaluation mode.
fetchurl url