Enable syntax highlighting

This commit is contained in:
Eelco Dolstra 2020-07-31 15:43:25 +02:00
parent 0c94c17644
commit 1d0a7b54fa
No known key found for this signature in database
GPG key ID: 8170B4726D7198DE
46 changed files with 1770 additions and 1155 deletions

File diff suppressed because one or more lines are too long

View file

@ -29,5 +29,6 @@ install: $(docdir)/manual/index.html
$(docdir)/manual/index.html: $(MANUAL_SRCS) $(docdir)/manual/index.html: $(MANUAL_SRCS)
$(trace-gen) mdbook build doc/manual -d $(docdir)/manual $(trace-gen) mdbook build doc/manual -d $(docdir)/manual
@cp doc/manual/highlight.pack.js $(docdir)/manual/highlight.js
endif endif

View file

@ -7,9 +7,10 @@ for determining if the results are the same.
For purposes of demonstration, we'll use the following Nix file, For purposes of demonstration, we'll use the following Nix file,
`deterministic.nix` for testing: `deterministic.nix` for testing:
let ```nix
let
inherit (import <nixpkgs> {}) runCommand; inherit (import <nixpkgs> {}) runCommand;
in { in {
stable = runCommand "stable" {} '' stable = runCommand "stable" {} ''
touch $out touch $out
''; '';
@ -17,7 +18,8 @@ For purposes of demonstration, we'll use the following Nix file,
unstable = runCommand "unstable" {} '' unstable = runCommand "unstable" {} ''
echo $RANDOM > $out echo $RANDOM > $out
''; '';
} }
```
Additionally, `nix.conf` contains: Additionally, `nix.conf` contains:
@ -26,10 +28,12 @@ Additionally, `nix.conf` contains:
where `/etc/nix/my-diff-hook` is an executable file containing: where `/etc/nix/my-diff-hook` is an executable file containing:
#!/bin/sh ```bash
exec >&2 #!/bin/sh
echo "For derivation $3:" exec >&2
/run/current-system/sw/bin/diff -r "$1" "$2" echo "For derivation $3:"
/run/current-system/sw/bin/diff -r "$1" "$2"
```
The diff hook is executed by the same user and group who ran the build. The diff hook is executed by the same user and group who ran the build.
However, the diff hook does not have write access to the store path just However, the diff hook does not have write access to the store path just
@ -43,44 +47,55 @@ to the build command.
If the build passes and is deterministic, Nix will exit with a status If the build passes and is deterministic, Nix will exit with a status
code of 0: code of 0:
$ nix-build ./deterministic.nix -A stable ```console
this derivation will be built: $ nix-build ./deterministic.nix -A stable
this derivation will be built:
/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv /nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv
building '/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv'... building '/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv'...
/nix/store/yyxlzw3vqaas7wfp04g0b1xg51f2czgq-stable /nix/store/yyxlzw3vqaas7wfp04g0b1xg51f2czgq-stable
$ nix-build ./deterministic.nix -A stable --check $ nix-build ./deterministic.nix -A stable --check
checking outputs of '/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv'... checking outputs of '/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv'...
/nix/store/yyxlzw3vqaas7wfp04g0b1xg51f2czgq-stable /nix/store/yyxlzw3vqaas7wfp04g0b1xg51f2czgq-stable
```
If the build is not deterministic, Nix will exit with a status code of If the build is not deterministic, Nix will exit with a status code of
1: 1:
$ nix-build ./deterministic.nix -A unstable ```console
this derivation will be built: $ nix-build ./deterministic.nix -A unstable
this derivation will be built:
/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv /nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv
building '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'... building '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'...
/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable /nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable
$ nix-build ./deterministic.nix -A unstable --check $ nix-build ./deterministic.nix -A unstable --check
checking outputs of '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'... checking outputs of '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'...
error: derivation '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv' may not be deterministic: output '/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable' differs error: derivation '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv' may
not be deterministic: output '/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable' differs
```
In the Nix daemon's log, we will now see: In the Nix daemon's log, we will now see:
For derivation /nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv: ```
1c1 For derivation /nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv:
< 8108 1c1
--- < 8108
> 30204 ---
> 30204
```
Using `--check` with `--keep-failed` will cause Nix to keep the second Using `--check` with `--keep-failed` will cause Nix to keep the second
build's output in a special, `.check` path: build's output in a special, `.check` path:
$ nix-build ./deterministic.nix -A unstable --check --keep-failed ```console
checking outputs of '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'... $ nix-build ./deterministic.nix -A unstable --check --keep-failed
note: keeping build directory '/tmp/nix-build-unstable.drv-0' checking outputs of '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'...
error: derivation '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv' may not be deterministic: output '/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable' differs from '/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable.check' note: keeping build directory '/tmp/nix-build-unstable.drv-0'
error: derivation '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv' may
not be deterministic: output '/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable' differs
from '/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable.check'
```
In particular, notice the In particular, notice the
`/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable.check` output. Nix `/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable.check` output. Nix
@ -102,7 +117,8 @@ has copied the build results to that directory where you can examine it.
already. If the derivation has not been built Nix will fail with the already. If the derivation has not been built Nix will fail with the
error: error:
error: some outputs of '/nix/store/hzi1h60z2qf0nb85iwnpvrai3j2w7rr6-unstable.drv' are not valid, so checking is not possible error: some outputs of '/nix/store/hzi1h60z2qf0nb85iwnpvrai3j2w7rr6-unstable.drv'
are not valid, so checking is not possible
Run the build without `--check`, and then try with `--check` again. Run the build without `--check`, and then try with `--check` again.
@ -130,10 +146,12 @@ reproducibly:
An example output of this configuration: An example output of this configuration:
$ nix-build ./test.nix -A unstable ```console
this derivation will be built: $ nix-build ./test.nix -A unstable
this derivation will be built:
/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv /nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv
building '/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv' (round 1/2)... building '/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv' (round 1/2)...
building '/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv' (round 2/2)... building '/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv' (round 2/2)...
output '/nix/store/6xg356v9gl03hpbbg8gws77n19qanh02-unstable' of '/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv' differs from '/nix/store/6xg356v9gl03hpbbg8gws77n19qanh02-unstable.check' from previous round output '/nix/store/6xg356v9gl03hpbbg8gws77n19qanh02-unstable' of '/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv' differs from '/nix/store/6xg356v9gl03hpbbg8gws77n19qanh02-unstable.check' from previous round
/nix/store/6xg356v9gl03hpbbg8gws77n19qanh02-unstable /nix/store/6xg356v9gl03hpbbg8gws77n19qanh02-unstable
```

View file

@ -11,12 +11,16 @@ To forward a build to a remote machine, its required that the remote
machine is accessible via SSH and that it has Nix installed. You can machine is accessible via SSH and that it has Nix installed. You can
test whether connecting to the remote Nix instance works, e.g. test whether connecting to the remote Nix instance works, e.g.
$ nix ping-store --store ssh://mac ```console
$ nix ping-store --store ssh://mac
```
will try to connect to the machine named `mac`. It is possible to will try to connect to the machine named `mac`. It is possible to
specify an SSH identity file as part of the remote store URI, e.g. specify an SSH identity file as part of the remote store URI, e.g.
$ nix ping-store --store ssh://mac?ssh-key=/home/alice/my-key ```console
$ nix ping-store --store ssh://mac?ssh-key=/home/alice/my-key
```
Since builds should be non-interactive, the key should not have a Since builds should be non-interactive, the key should not have a
passphrase. Alternatively, you can load identities ahead of time into passphrase. Alternatively, you can load identities ahead of time into
@ -24,8 +28,10 @@ passphrase. Alternatively, you can load identities ahead of time into
If you get the error If you get the error
bash: nix-store: command not found ```console
error: cannot connect to 'mac' bash: nix-store: command not found
error: cannot connect to 'mac'
```
then you need to ensure that the `PATH` of non-interactive login shells then you need to ensure that the `PATH` of non-interactive login shells
contains Nix. contains Nix.
@ -43,21 +49,23 @@ the Nix configuration file. The former is convenient for testing. For
example, the following command allows you to build a derivation for example, the following command allows you to build a derivation for
`x86_64-darwin` on a Linux machine: `x86_64-darwin` on a Linux machine:
$ uname ```console
Linux $ uname
Linux
$ nix build \ $ nix build \
'(with import <nixpkgs> { system = "x86_64-darwin"; }; runCommand "foo" {} "uname > $out")' \ '(with import <nixpkgs> { system = "x86_64-darwin"; }; runCommand "foo" {} "uname > $out")' \
--builders 'ssh://mac x86_64-darwin' --builders 'ssh://mac x86_64-darwin'
[1/0/1 built, 0.0 MiB DL] building foo on ssh://mac [1/0/1 built, 0.0 MiB DL] building foo on ssh://mac
$ cat ./result $ cat ./result
Darwin Darwin
```
It is possible to specify multiple builders separated by a semicolon or It is possible to specify multiple builders separated by a semicolon or
a newline, e.g. a newline, e.g.
``` ```console
--builders 'ssh://mac x86_64-darwin ; ssh://beastie x86_64-freebsd' --builders 'ssh://mac x86_64-darwin ; ssh://beastie x86_64-freebsd'
``` ```
@ -92,7 +100,9 @@ default, set it to `-`.
the derivation on a machine that has the specified features. For the derivation on a machine that has the specified features. For
instance, the attribute instance, the attribute
```nix
requiredSystemFeatures = [ "kvm" ]; requiredSystemFeatures = [ "kvm" ];
```
will cause the build to be performed on a machine that has the `kvm` will cause the build to be performed on a machine that has the `kvm`
feature. feature.
@ -111,11 +121,15 @@ For example, the machine specification
specifies several machines that can perform `i686-linux` builds. specifies several machines that can perform `i686-linux` builds.
However, `poochie` will only do builds that have the attribute However, `poochie` will only do builds that have the attribute
requiredSystemFeatures = [ "benchmark" ]; ```nix
requiredSystemFeatures = [ "benchmark" ];
```
or or
requiredSystemFeatures = [ "benchmark" "kvm" ]; ```nix
requiredSystemFeatures = [ "benchmark" "kvm" ];
```
`itchy` cannot do builds that require `kvm`, but `scratchy` does support `itchy` cannot do builds that require `kvm`, but `scratchy` does support
such builds. For regular builds, `itchy` will be preferred over such builds. For regular builds, `itchy` will be preferred over

View file

@ -27,9 +27,11 @@ Use `nix-store --generate-binary-cache-key` to create our public and
private signing keys. We will sign paths with the private key, and private signing keys. We will sign paths with the private key, and
distribute the public key for verifying the authenticity of the paths. distribute the public key for verifying the authenticity of the paths.
# nix-store --generate-binary-cache-key example-nix-cache-1 /etc/nix/key.private /etc/nix/key.public ```console
# cat /etc/nix/key.public # nix-store --generate-binary-cache-key example-nix-cache-1 /etc/nix/key.private /etc/nix/key.public
example-nix-cache-1:1/cKDz3QCCOmwcztD2eV6Coggp6rqc9DGjWv7C0G+rM= # cat /etc/nix/key.public
example-nix-cache-1:1/cKDz3QCCOmwcztD2eV6Coggp6rqc9DGjWv7C0G+rM=
```
Then, add the public key and the cache URL to your `nix.conf`'s Then, add the public key and the cache URL to your `nix.conf`'s
`trusted-public-keys` and `substituters` options: `trusted-public-keys` and `substituters` options:
@ -43,16 +45,18 @@ We will restart the Nix daemon in a later step.
Write the following script to `/etc/nix/upload-to-cache.sh`: Write the following script to `/etc/nix/upload-to-cache.sh`:
#!/bin/sh ```bash
#!/bin/sh
set -eu set -eu
set -f # disable globbing set -f # disable globbing
export IFS=' ' export IFS=' '
echo "Signing paths" $OUT_PATHS echo "Signing paths" $OUT_PATHS
nix sign-paths --key-file /etc/nix/key.private $OUT_PATHS nix sign-paths --key-file /etc/nix/key.private $OUT_PATHS
echo "Uploading paths" $OUT_PATHS echo "Uploading paths" $OUT_PATHS
exec nix copy --to 's3://example-nix-cache' $OUT_PATHS exec nix copy --to 's3://example-nix-cache' $OUT_PATHS
```
> **Note** > **Note**
> >
@ -65,7 +69,9 @@ Write the following script to `/etc/nix/upload-to-cache.sh`:
Then make sure the hook program is executable by the `root` user: Then make sure the hook program is executable by the `root` user:
# chmod +x /etc/nix/upload-to-cache.sh ```console
# chmod +x /etc/nix/upload-to-cache.sh
```
# Updating Nix Configuration # Updating Nix Configuration
@ -80,27 +86,33 @@ Then, restart the `nix-daemon`.
Build any derivation, for example: Build any derivation, for example:
$ nix-build -E '(import <nixpkgs> {}).writeText "example" (builtins.toString builtins.currentTime)' ```console
this derivation will be built: $ nix-build -E '(import <nixpkgs> {}).writeText "example" (builtins.toString builtins.currentTime)'
this derivation will be built:
/nix/store/s4pnfbkalzy5qz57qs6yybna8wylkig6-example.drv /nix/store/s4pnfbkalzy5qz57qs6yybna8wylkig6-example.drv
building '/nix/store/s4pnfbkalzy5qz57qs6yybna8wylkig6-example.drv'... building '/nix/store/s4pnfbkalzy5qz57qs6yybna8wylkig6-example.drv'...
running post-build-hook '/home/grahamc/projects/github.com/NixOS/nix/post-hook.sh'... running post-build-hook '/home/grahamc/projects/github.com/NixOS/nix/post-hook.sh'...
post-build-hook: Signing paths /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example post-build-hook: Signing paths /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
post-build-hook: Uploading paths /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example post-build-hook: Uploading paths /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
/nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
```
Then delete the path from the store, and try substituting it from the Then delete the path from the store, and try substituting it from the
binary cache: binary cache:
$ rm ./result ```console
$ nix-store --delete /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example $ rm ./result
$ nix-store --delete /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
```
Now, copy the path back from the cache: Now, copy the path back from the cache:
$ nix-store --realise /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example ```console
copying path '/nix/store/m8bmqwrch6l3h8s0k3d673xpmipcdpsa-example from 's3://example-nix-cache'... $ nix-store --realise /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
warning: you did not specify '--add-root'; the result might be removed by the garbage collector copying path '/nix/store/m8bmqwrch6l3h8s0k3d673xpmipcdpsa-example from 's3://example-nix-cache'...
/nix/store/m8bmqwrch6l3h8s0k3d673xpmipcdpsa-example warning: you did not specify '--add-root'; the result might be removed by the garbage collector
/nix/store/m8bmqwrch6l3h8s0k3d673xpmipcdpsa-example
```
# Conclusion # Conclusion

View file

@ -70,11 +70,11 @@ The following settings are currently available:
Note that trusted users are always allowed to connect. Note that trusted users are always allowed to connect.
- `auto-optimise-store` - `auto-optimise-store`
If set to `true`, Nix automatically detects files in the store that If set to `true`, Nix automatically detects files in the store
have identical contents, and replaces them with hard links to a that have identical contents, and replaces them with hard links to
single copy. This saves disk space. If set to `false` (the default), a single copy. This saves disk space. If set to `false` (the
you can still run `nix-store default), you can still run `nix-store --optimise` to get rid of
--optimise` to get rid of duplicate files. duplicate files.
- `builders` - `builders`
A list of machines on which to perform builds. A list of machines on which to perform builds.
@ -215,10 +215,12 @@ The following settings are currently available:
the default mirror `http://tarballs.nixos.org/`, when building the the default mirror `http://tarballs.nixos.org/`, when building the
derivation derivation
```nix
builtins.fetchurl { builtins.fetchurl {
url = "https://example.org/foo-1.2.3.tar.xz"; url = "https://example.org/foo-1.2.3.tar.xz";
sha256 = "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"; sha256 = "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae";
} }
```
Nix will attempt to download this file from Nix will attempt to download this file from
`http://tarballs.nixos.org/sha256/2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae` `http://tarballs.nixos.org/sha256/2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae`
@ -233,8 +235,7 @@ The following settings are currently available:
If set to `true` (the default), Nix will write the build log of a If set to `true` (the default), Nix will write the build log of a
derivation (i.e. the standard output and error of its builder) to derivation (i.e. the standard output and error of its builder) to
the directory `/nix/var/log/nix/drvs`. The build log can be the directory `/nix/var/log/nix/drvs`. The build log can be
retrieved using the command `nix-store -l retrieved using the command `nix-store -l path`.
path`.
- `keep-derivations` - `keep-derivations`
If `true` (default), the garbage collector will keep the derivations If `true` (default), the garbage collector will keep the derivations
@ -504,10 +505,9 @@ The following settings are currently available:
- `secret-key-files` - `secret-key-files`
A whitespace-separated list of files containing secret (private) A whitespace-separated list of files containing secret (private)
keys. These are used to sign locally-built paths. They can be keys. These are used to sign locally-built paths. They can be
generated using `nix-store generated using `nix-store --generate-binary-cache-key`. The
--generate-binary-cache-key`. The corresponding public key can be corresponding public key can be distributed to other users, who
distributed to other users, who can add it to `trusted-public-keys` can add it to `trusted-public-keys` in their `nix.conf`.
in their `nix.conf`.
- `show-trace` - `show-trace`
Causes Nix to print out a stack trace in case of Nix expression Causes Nix to print out a stack trace in case of Nix expression
@ -601,18 +601,17 @@ The following settings are currently available:
- `trusted-public-keys` - `trusted-public-keys`
A whitespace-separated list of public keys. When paths are copied A whitespace-separated list of public keys. When paths are copied
from another Nix store (such as a binary cache), they must be signed from another Nix store (such as a binary cache), they must be
with one of these keys. For example: signed with one of these keys. For example:
`cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= `cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=
hydra.nixos.org-1:CNHJZBh9K4tP3EKF6FkkgeVYsS3ohTl+oS0Qa8bezVs=`. hydra.nixos.org-1:CNHJZBh9K4tP3EKF6FkkgeVYsS3ohTl+oS0Qa8bezVs=`.
- `trusted-substituters` - `trusted-substituters`
A list of URLs of substituters, separated by whitespace. These are A list of URLs of substituters, separated by whitespace. These are
not used by default, but can be enabled by users of the Nix daemon not used by default, but can be enabled by users of the Nix daemon
by specifying `--option by specifying `--option substituters urls` on the command
substituters urls` on the command line. Unprivileged users are only line. Unprivileged users are only allowed to pass a subset of the
allowed to pass a subset of the URLs listed in `substituters` and URLs listed in `substituters` and `trusted-substituters`.
`trusted-substituters`.
- `trusted-users` - `trusted-users`
A list of names of users (separated by whitespace) that have A list of names of users (separated by whitespace) that have

View file

@ -55,8 +55,10 @@ Most Nix commands interpret the following environment variables:
on another file system than the root file system, on Linux youre on another file system than the root file system, on Linux youre
better off using `bind` mount points, e.g., better off using `bind` mount points, e.g.,
```console
$ mkdir /nix $ mkdir /nix
$ mount -o bind /mnt/otherdisk/nix /nix $ mount -o bind /mnt/otherdisk/nix /nix
```
Consult the mount 8 manual page for details. Consult the mount 8 manual page for details.

View file

@ -66,20 +66,24 @@ The following common options are supported:
# Examples # Examples
$ nix-build '<nixpkgs>' -A firefox ```console
store derivation is /nix/store/qybprl8sz2lc...-firefox-1.5.0.7.drv $ nix-build '<nixpkgs>' -A firefox
/nix/store/d18hyl92g30l...-firefox-1.5.0.7 store derivation is /nix/store/qybprl8sz2lc...-firefox-1.5.0.7.drv
/nix/store/d18hyl92g30l...-firefox-1.5.0.7
$ ls -l result $ ls -l result
lrwxrwxrwx ... result -> /nix/store/d18hyl92g30l...-firefox-1.5.0.7 lrwxrwxrwx ... result -> /nix/store/d18hyl92g30l...-firefox-1.5.0.7
$ ls ./result/bin/ $ ls ./result/bin/
firefox firefox-config firefox firefox-config
```
If a derivation has multiple outputs, `nix-build` will build the default If a derivation has multiple outputs, `nix-build` will build the default
(first) output. You can also build all outputs: (first) output. You can also build all outputs:
$ nix-build '<nixpkgs>' -A openssl.all ```console
$ nix-build '<nixpkgs>' -A openssl.all
```
This will create a symlink for each output named `result-outputname`. This will create a symlink for each output named `result-outputname`.
The suffix is omitted if the output name is `out`. So if `openssl` has The suffix is omitted if the output name is `out`. So if `openssl` has
@ -87,19 +91,23 @@ outputs `out`, `bin` and `man`, `nix-build` will create symlinks
`result`, `result-bin` and `result-man`. Its also possible to build a `result`, `result-bin` and `result-man`. Its also possible to build a
specific output: specific output:
$ nix-build '<nixpkgs>' -A openssl.man ```console
$ nix-build '<nixpkgs>' -A openssl.man
```
This will create a symlink `result-man`. This will create a symlink `result-man`.
Build a Nix expression given on the command line: Build a Nix expression given on the command line:
$ nix-build -E 'with import <nixpkgs> { }; runCommand "foo" { } "echo bar > $out"' ```console
$ cat ./result $ nix-build -E 'with import <nixpkgs> { }; runCommand "foo" { } "echo bar > $out"'
bar $ cat ./result
bar
```
Build the GNU Hello package from the latest revision of the master Build the GNU Hello package from the latest revision of the master
branch of Nixpkgs: branch of Nixpkgs:
$ nix-build https://github.com/NixOS/nixpkgs/archive/master.tar.gz -A hello ```console
$ nix-build https://github.com/NixOS/nixpkgs/archive/master.tar.gz -A hello
# Environment variables ```

View file

@ -51,20 +51,24 @@ The list of subscribed channels is stored in `~/.nix-channels`.
To subscribe to the Nixpkgs channel and install the GNU Hello package: To subscribe to the Nixpkgs channel and install the GNU Hello package:
$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable ```console
$ nix-channel --update $ nix-channel --add https://nixos.org/channels/nixpkgs-unstable
$ nix-env -iA nixpkgs.hello $ nix-channel --update
$ nix-env -iA nixpkgs.hello
```
You can revert channel updates using `--rollback`: You can revert channel updates using `--rollback`:
$ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version' ```console
"14.04.527.0e935f1" $ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version'
"14.04.527.0e935f1"
$ nix-channel --rollback $ nix-channel --rollback
switching from generation 483 to 482 switching from generation 483 to 482
$ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version' $ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version'
"14.04.526.dbadfad" "14.04.526.dbadfad"
```
# Files # Files

View file

@ -27,4 +27,6 @@ generations that were active at that point in time).
To delete from the Nix store everything that is not used by the current To delete from the Nix store everything that is not used by the current
generations of each profile, do generations of each profile, do
$ nix-collect-garbage -d ```console
$ nix-collect-garbage -d
```

View file

@ -73,11 +73,15 @@ and second to send the dump of those paths. If this bothers you, use
Copy Firefox with all its dependencies to a remote machine: Copy Firefox with all its dependencies to a remote machine:
$ nix-copy-closure --to alice@itchy.labs $(type -tP firefox) ```console
$ nix-copy-closure --to alice@itchy.labs $(type -tP firefox)
```
Copy Subversion from a remote machine and then install it into a user Copy Subversion from a remote machine and then install it into a user
environment: environment:
$ nix-copy-closure --from alice@itchy.labs \ ```console
$ nix-copy-closure --from alice@itchy.labs \
/nix/store/0dj0503hjxy5mbwlafv1rsbdiyx1gkdy-subversion-1.4.4 /nix/store/0dj0503hjxy5mbwlafv1rsbdiyx1gkdy-subversion-1.4.4
$ nix-env -i /nix/store/0dj0503hjxy5mbwlafv1rsbdiyx1gkdy-subversion-1.4.4 $ nix-env -i /nix/store/0dj0503hjxy5mbwlafv1rsbdiyx1gkdy-subversion-1.4.4
```

View file

@ -127,10 +127,12 @@ have an effect.
For example, if `~/.nix-defexpr` contains two files, `foo.nix` and For example, if `~/.nix-defexpr` contains two files, `foo.nix` and
`bar.nix`, then the default Nix expression will essentially be `bar.nix`, then the default Nix expression will essentially be
```nix
{ {
foo = import ~/.nix-defexpr/foo.nix; foo = import ~/.nix-defexpr/foo.nix;
bar = import ~/.nix-defexpr/bar.nix; bar = import ~/.nix-defexpr/bar.nix;
} }
```
The file `manifest.nix` is always ignored. Subdirectories without a The file `manifest.nix` is always ignored. Subdirectories without a
`default.nix` file are traversed recursively in search of more Nix `default.nix` file are traversed recursively in search of more Nix
@ -240,44 +242,60 @@ a number of possible ways:
To install a specific version of `gcc` from the active Nix expression: To install a specific version of `gcc` from the active Nix expression:
$ nix-env --install gcc-3.3.2 ```console
installing `gcc-3.3.2' $ nix-env --install gcc-3.3.2
uninstalling `gcc-3.1' installing `gcc-3.3.2'
uninstalling `gcc-3.1'
```
Note the previously installed version is removed, since Note the previously installed version is removed, since
`--preserve-installed` was not specified. `--preserve-installed` was not specified.
To install an arbitrary version: To install an arbitrary version:
$ nix-env --install gcc ```console
installing `gcc-3.3.2' $ nix-env --install gcc
installing `gcc-3.3.2'
```
To install using a specific attribute: To install using a specific attribute:
$ nix-env -i -A gcc40mips ```console
$ nix-env -i -A xorg.xorgserver $ nix-env -i -A gcc40mips
$ nix-env -i -A xorg.xorgserver
```
To install all derivations in the Nix expression `foo.nix`: To install all derivations in the Nix expression `foo.nix`:
$ nix-env -f ~/foo.nix -i '.*' ```console
$ nix-env -f ~/foo.nix -i '.*'
```
To copy the store path with symbolic name `gcc` from another profile: To copy the store path with symbolic name `gcc` from another profile:
$ nix-env -i --from-profile /nix/var/nix/profiles/foo gcc ```console
$ nix-env -i --from-profile /nix/var/nix/profiles/foo gcc
```
To install a specific store derivation (typically created by To install a specific store derivation (typically created by
`nix-instantiate`): `nix-instantiate`):
$ nix-env -i /nix/store/fibjb1bfbpm5mrsxc4mh2d8n37sxh91i-gcc-3.4.3.drv ```console
$ nix-env -i /nix/store/fibjb1bfbpm5mrsxc4mh2d8n37sxh91i-gcc-3.4.3.drv
```
To install a specific output path: To install a specific output path:
$ nix-env -i /nix/store/y3cgx0xj1p4iv9x0pnnmdhr8iyg741vk-gcc-3.4.3 ```console
$ nix-env -i /nix/store/y3cgx0xj1p4iv9x0pnnmdhr8iyg741vk-gcc-3.4.3
```
To install from a Nix expression specified on the command-line: To install from a Nix expression specified on the command-line:
$ nix-env -f ./foo.nix -i -E \ ```console
$ nix-env -f ./foo.nix -i -E \
'f: (f {system = "i686-linux";}).subversionWithJava' 'f: (f {system = "i686-linux";}).subversionWithJava'
```
I.e., this evaluates to `(f: (f {system = I.e., this evaluates to `(f: (f {system =
"i686-linux";}).subversionWithJava) (import ./foo.nix)`, thus selecting "i686-linux";}).subversionWithJava) (import ./foo.nix)`, thus selecting
@ -286,17 +304,21 @@ function defined in `./foo.nix`.
A dry-run tells you which paths will be downloaded or built from source: A dry-run tells you which paths will be downloaded or built from source:
$ nix-env -f '<nixpkgs>' -iA hello --dry-run ```console
(dry run; not doing anything) $ nix-env -f '<nixpkgs>' -iA hello --dry-run
installing hello-2.10 (dry run; not doing anything)
this path will be fetched (0.04 MiB download, 0.19 MiB unpacked): installing hello-2.10
this path will be fetched (0.04 MiB download, 0.19 MiB unpacked):
/nix/store/wkhdf9jinag5750mqlax6z2zbwhqb76n-hello-2.10 /nix/store/wkhdf9jinag5750mqlax6z2zbwhqb76n-hello-2.10
... ...
```
To install Firefox from the latest revision in the Nixpkgs/NixOS 14.12 To install Firefox from the latest revision in the Nixpkgs/NixOS 14.12
channel: channel:
$ nix-env -f https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz -iA firefox ```console
$ nix-env -f https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz -iA firefox
```
# Operation `--upgrade` # Operation `--upgrade`
@ -353,18 +375,26 @@ For the other flags, see `--install`.
## Examples ## Examples
$ nix-env --upgrade gcc ```console
upgrading `gcc-3.3.1' to `gcc-3.4' $ nix-env --upgrade gcc
upgrading `gcc-3.3.1' to `gcc-3.4'
```
$ nix-env -u gcc-3.3.2 --always (switch to a specific version) ```console
upgrading `gcc-3.4' to `gcc-3.3.2' $ nix-env -u gcc-3.3.2 --always (switch to a specific version)
upgrading `gcc-3.4' to `gcc-3.3.2'
```
$ nix-env --upgrade pan ```console
(no upgrades available, so nothing happens) $ nix-env --upgrade pan
(no upgrades available, so nothing happens)
```
$ nix-env -u (try to upgrade everything) ```console
upgrading `hello-2.1.2' to `hello-2.1.3' $ nix-env -u (try to upgrade everything)
upgrading `mozilla-1.2' to `mozilla-1.4' upgrading `hello-2.1.2' to `hello-2.1.3'
upgrading `mozilla-1.2' to `mozilla-1.4'
```
## Versions ## Versions
@ -416,8 +446,10 @@ designated by the symbolic names *drvnames* are removed.
## Examples ## Examples
$ nix-env --uninstall gcc ```console
$ nix-env -e '.*' (remove everything) $ nix-env --uninstall gcc
$ nix-env -e '.*' (remove everything)
```
# Operation `--set` # Operation `--set`
@ -435,7 +467,9 @@ that it contains exactly the specified derivation, and nothing else.
The following updates a profile such that its current generation will The following updates a profile such that its current generation will
contain just Firefox: contain just Firefox:
$ nix-env -p /nix/var/nix/profiles/browser --set firefox ```console
$ nix-env -p /nix/var/nix/profiles/browser --set firefox
```
# Operation `--set-flag` # Operation `--set-flag`
@ -473,37 +507,43 @@ environment build script:
To prevent the currently installed Firefox from being upgraded: To prevent the currently installed Firefox from being upgraded:
$ nix-env --set-flag keep true firefox ```console
$ nix-env --set-flag keep true firefox
```
After this, `nix-env -u` will ignore Firefox. After this, `nix-env -u` will ignore Firefox.
To disable the currently installed Firefox, then install a new Firefox To disable the currently installed Firefox, then install a new Firefox
while the old remains part of the profile: while the old remains part of the profile:
$ nix-env -q ```console
firefox-2.0.0.9 (the current one) $ nix-env -q
firefox-2.0.0.9 (the current one)
$ nix-env --preserve-installed -i firefox-2.0.0.11 $ nix-env --preserve-installed -i firefox-2.0.0.11
installing `firefox-2.0.0.11' installing `firefox-2.0.0.11'
building path(s) `/nix/store/myy0y59q3ig70dgq37jqwg1j0rsapzsl-user-environment' building path(s) `/nix/store/myy0y59q3ig70dgq37jqwg1j0rsapzsl-user-environment'
collision between `/nix/store/...-firefox-2.0.0.11/bin/firefox' collision between `/nix/store/...-firefox-2.0.0.11/bin/firefox'
and `/nix/store/...-firefox-2.0.0.9/bin/firefox'. and `/nix/store/...-firefox-2.0.0.9/bin/firefox'.
(i.e., cant have two active at the same time) (i.e., cant have two active at the same time)
$ nix-env --set-flag active false firefox $ nix-env --set-flag active false firefox
setting flag on `firefox-2.0.0.9' setting flag on `firefox-2.0.0.9'
$ nix-env --preserve-installed -i firefox-2.0.0.11 $ nix-env --preserve-installed -i firefox-2.0.0.11
installing `firefox-2.0.0.11' installing `firefox-2.0.0.11'
$ nix-env -q $ nix-env -q
firefox-2.0.0.11 (the enabled one) firefox-2.0.0.11 (the enabled one)
firefox-2.0.0.9 (the disabled one) firefox-2.0.0.9 (the disabled one)
```
To make files from `binutils` take precedence over files from `gcc`: To make files from `binutils` take precedence over files from `gcc`:
$ nix-env --set-flag priority 5 binutils ```console
$ nix-env --set-flag priority 10 gcc $ nix-env --set-flag priority 5 binutils
$ nix-env --set-flag priority 10 gcc
```
# Operation `--query` # Operation `--query`
@ -633,66 +673,82 @@ derivation is shown unless `--no-name` is specified.
To show installed packages: To show installed packages:
$ nix-env -q ```console
bison-1.875c $ nix-env -q
docbook-xml-4.2 bison-1.875c
firefox-1.0.4 docbook-xml-4.2
MPlayer-1.0pre7 firefox-1.0.4
ORBit2-2.8.3 MPlayer-1.0pre7
ORBit2-2.8.3
```
To show available packages: To show available packages:
$ nix-env -qa ```console
firefox-1.0.7 $ nix-env -qa
GConf-2.4.0.1 firefox-1.0.7
MPlayer-1.0pre7 GConf-2.4.0.1
ORBit2-2.8.3 MPlayer-1.0pre7
ORBit2-2.8.3
```
To show the status of available packages: To show the status of available packages:
$ nix-env -qas ```console
-P- firefox-1.0.7 (not installed but present) $ nix-env -qas
--S GConf-2.4.0.1 (not present, but there is a substitute for fast installation) -P- firefox-1.0.7 (not installed but present)
--S MPlayer-1.0pre3 (i.e., this is not the installed MPlayer, even though the version is the same!) --S GConf-2.4.0.1 (not present, but there is a substitute for fast installation)
IP- ORBit2-2.8.3 (installed and by definition present) --S MPlayer-1.0pre3 (i.e., this is not the installed MPlayer, even though the version is the same!)
IP- ORBit2-2.8.3 (installed and by definition present)
```
To show available packages in the Nix expression `foo.nix`: To show available packages in the Nix expression `foo.nix`:
$ nix-env -f ./foo.nix -qa ```console
foo-1.2.3 $ nix-env -f ./foo.nix -qa
foo-1.2.3
```
To compare installed versions to whats available: To compare installed versions to whats available:
$ nix-env -qc ```console
... $ nix-env -qc
acrobat-reader-7.0 - ? (package is not available at all) ...
autoconf-2.59 = 2.59 (same version) acrobat-reader-7.0 - ? (package is not available at all)
firefox-1.0.4 < 1.0.7 (a more recent version is available) autoconf-2.59 = 2.59 (same version)
... firefox-1.0.4 < 1.0.7 (a more recent version is available)
...
```
To show all packages with “`zip`” in the name: To show all packages with “`zip`” in the name:
$ nix-env -qa '.*zip.*' ```console
bzip2-1.0.6 $ nix-env -qa '.*zip.*'
gzip-1.6 bzip2-1.0.6
zip-3.0 gzip-1.6
zip-3.0
```
To show all packages with “`firefox`” or “`chromium`” in the name: To show all packages with “`firefox`” or “`chromium`” in the name:
$ nix-env -qa '.*(firefox|chromium).*' ```console
chromium-37.0.2062.94 $ nix-env -qa '.*(firefox|chromium).*'
chromium-beta-38.0.2125.24 chromium-37.0.2062.94
firefox-32.0.3 chromium-beta-38.0.2125.24
firefox-with-plugins-13.0.1 firefox-32.0.3
firefox-with-plugins-13.0.1
```
To show all packages in the latest revision of the Nixpkgs repository: To show all packages in the latest revision of the Nixpkgs repository:
$ nix-env -f https://github.com/NixOS/nixpkgs/archive/master.tar.gz -qa ```console
$ nix-env -f https://github.com/NixOS/nixpkgs/archive/master.tar.gz -qa
```
# Operation `--switch-profile` # Operation `--switch-profile`
@ -707,7 +763,9 @@ the symlink `~/.nix-profile` is made to point to *path*.
## Examples ## Examples
$ nix-env -S ~/my-profile ```console
$ nix-env -S ~/my-profile
```
# Operation `--list-generations` # Operation `--list-generations`
@ -724,11 +782,13 @@ generation, and indicates the current generation.
## Examples ## Examples
$ nix-env --list-generations ```console
$ nix-env --list-generations
95 2004-02-06 11:48:24 95 2004-02-06 11:48:24
96 2004-02-06 11:49:01 96 2004-02-06 11:49:01
97 2004-02-06 16:22:45 97 2004-02-06 16:22:45
98 2004-02-06 16:24:33 (current) 98 2004-02-06 16:24:33 (current)
```
# Operation `--delete-generations` # Operation `--delete-generations`
@ -750,13 +810,21 @@ generations is important to make garbage collection effective.
## Examples ## Examples
$ nix-env --delete-generations 3 4 8 ```console
$ nix-env --delete-generations 3 4 8
```
$ nix-env --delete-generations +5 ```console
$ nix-env --delete-generations +5
```
$ nix-env --delete-generations 30d ```console
$ nix-env --delete-generations 30d
```
$ nix-env -p other_profile --delete-generations old ```console
$ nix-env -p other_profile --delete-generations old
```
# Operation `--switch-generation` # Operation `--switch-generation`
@ -776,8 +844,10 @@ Switching will fail if the specified generation does not exist.
## Examples ## Examples
$ nix-env -G 42 ```console
switching from generation 50 to 42 $ nix-env -G 42
switching from generation 50 to 42
```
# Operation `--rollback` # Operation `--rollback`
@ -794,11 +864,15 @@ generation, if it exists. It is just a convenience wrapper around
## Examples ## Examples
$ nix-env --rollback ```console
switching from generation 92 to 91 $ nix-env --rollback
switching from generation 92 to 91
```
$ nix-env --rollback ```console
error: no generation older than the current (91) exists $ nix-env --rollback
error: no generation older than the current (91) exists
```
# Environment variables # Environment variables

View file

@ -61,38 +61,44 @@ md5sum`.
Computing the same hash as `nix-prefetch-url`: Computing the same hash as `nix-prefetch-url`:
$ nix-prefetch-url file://<(echo test) ```console
1lkgqb6fclns49861dwk9rzb6xnfkxbpws74mxnx01z9qyv1pjpj $ nix-prefetch-url file://<(echo test)
$ nix-hash --type sha256 --flat --base32 <(echo test) 1lkgqb6fclns49861dwk9rzb6xnfkxbpws74mxnx01z9qyv1pjpj
1lkgqb6fclns49861dwk9rzb6xnfkxbpws74mxnx01z9qyv1pjpj $ nix-hash --type sha256 --flat --base32 <(echo test)
1lkgqb6fclns49861dwk9rzb6xnfkxbpws74mxnx01z9qyv1pjpj
```
Computing hashes: Computing hashes:
$ mkdir test ```console
$ echo "hello" > test/world $ mkdir test
$ echo "hello" > test/world
$ nix-hash test/ (MD5 hash; default) $ nix-hash test/ (MD5 hash; default)
8179d3caeff1869b5ba1744e5a245c04 8179d3caeff1869b5ba1744e5a245c04
$ nix-store --dump test/ | md5sum (for comparison) $ nix-store --dump test/ | md5sum (for comparison)
8179d3caeff1869b5ba1744e5a245c04 - 8179d3caeff1869b5ba1744e5a245c04 -
$ nix-hash --type sha1 test/ $ nix-hash --type sha1 test/
e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6 e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6
$ nix-hash --type sha1 --base32 test/ $ nix-hash --type sha1 --base32 test/
nvd61k9nalji1zl9rrdfmsmvyyjqpzg4 nvd61k9nalji1zl9rrdfmsmvyyjqpzg4
$ nix-hash --type sha256 --flat test/ $ nix-hash --type sha256 --flat test/
error: reading file `test/': Is a directory error: reading file `test/': Is a directory
$ nix-hash --type sha256 --flat test/world $ nix-hash --type sha256 --flat test/world
5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03 5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03
```
Converting between hexadecimal and base-32: Converting between hexadecimal and base-32:
$ nix-hash --type sha1 --to-base32 e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6 ```console
nvd61k9nalji1zl9rrdfmsmvyyjqpzg4 $ nix-hash --type sha1 --to-base32 e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6
nvd61k9nalji1zl9rrdfmsmvyyjqpzg4
$ nix-hash --type sha1 --to-base16 nvd61k9nalji1zl9rrdfmsmvyyjqpzg4 $ nix-hash --type sha1 --to-base16 nvd61k9nalji1zl9rrdfmsmvyyjqpzg4
e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6 e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6
```

View file

@ -85,61 +85,77 @@ standard input.
Instantiating store derivations from a Nix expression, and building them Instantiating store derivations from a Nix expression, and building them
using `nix-store`: using `nix-store`:
$ nix-instantiate test.nix (instantiate) ```console
/nix/store/cigxbmvy6dzix98dxxh9b6shg7ar5bvs-perl-BerkeleyDB-0.26.drv $ nix-instantiate test.nix (instantiate)
/nix/store/cigxbmvy6dzix98dxxh9b6shg7ar5bvs-perl-BerkeleyDB-0.26.drv
$ nix-store -r $(nix-instantiate test.nix) (build) $ nix-store -r $(nix-instantiate test.nix) (build)
... ...
/nix/store/qhqk4n8ci095g3sdp93x7rgwyh9rdvgk-perl-BerkeleyDB-0.26 (output path) /nix/store/qhqk4n8ci095g3sdp93x7rgwyh9rdvgk-perl-BerkeleyDB-0.26 (output path)
$ ls -l /nix/store/qhqk4n8ci095g3sdp93x7rgwyh9rdvgk-perl-BerkeleyDB-0.26 $ ls -l /nix/store/qhqk4n8ci095g3sdp93x7rgwyh9rdvgk-perl-BerkeleyDB-0.26
dr-xr-xr-x 2 eelco users 4096 1970-01-01 01:00 lib dr-xr-xr-x 2 eelco users 4096 1970-01-01 01:00 lib
... ...
```
You can also give a Nix expression on the command line: You can also give a Nix expression on the command line:
$ nix-instantiate -E 'with import <nixpkgs> { }; hello' ```console
/nix/store/j8s4zyv75a724q38cb0r87rlczaiag4y-hello-2.8.drv $ nix-instantiate -E 'with import <nixpkgs> { }; hello'
/nix/store/j8s4zyv75a724q38cb0r87rlczaiag4y-hello-2.8.drv
```
This is equivalent to: This is equivalent to:
$ nix-instantiate '<nixpkgs>' -A hello ```console
$ nix-instantiate '<nixpkgs>' -A hello
```
Parsing and evaluating Nix expressions: Parsing and evaluating Nix expressions:
$ nix-instantiate --parse -E '1 + 2' ```console
1 + 2 $ nix-instantiate --parse -E '1 + 2'
1 + 2
```
$ nix-instantiate --eval -E '1 + 2' ```console
3 $ nix-instantiate --eval -E '1 + 2'
3
```
$ nix-instantiate --eval --xml -E '1 + 2' ```console
<?xml version='1.0' encoding='utf-8'?> $ nix-instantiate --eval --xml -E '1 + 2'
<expr> <?xml version='1.0' encoding='utf-8'?>
<expr>
<int value="3" /> <int value="3" />
</expr> </expr>
```
The difference between non-strict and strict evaluation: The difference between non-strict and strict evaluation:
$ nix-instantiate --eval --xml -E 'rec { x = "foo"; y = x; }' ```console
... $ nix-instantiate --eval --xml -E 'rec { x = "foo"; y = x; }'
...
<attr name="x"> <attr name="x">
<string value="foo" /> <string value="foo" />
</attr> </attr>
<attr name="y"> <attr name="y">
<unevaluated /> <unevaluated />
</attr> </attr>
... ...
```
Note that `y` is left unevaluated (the XML representation doesnt Note that `y` is left unevaluated (the XML representation doesnt
attempt to show non-normal forms). attempt to show non-normal forms).
$ nix-instantiate --eval --xml --strict -E 'rec { x = "foo"; y = x; }' ```console
... $ nix-instantiate --eval --xml --strict -E 'rec { x = "foo"; y = x; }'
...
<attr name="x"> <attr name="x">
<string value="foo" /> <string value="foo" />
</attr> </attr>
<attr name="y"> <attr name="y">
<string value="foo" /> <string value="foo" />
</attr> </attr>
... ...
```

View file

@ -59,13 +59,19 @@ Nix store is also printed.
# Examples # Examples
$ nix-prefetch-url ftp://ftp.gnu.org/pub/gnu/hello/hello-2.10.tar.gz ```console
0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i $ nix-prefetch-url ftp://ftp.gnu.org/pub/gnu/hello/hello-2.10.tar.gz
0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i
```
$ nix-prefetch-url --print-path mirror://gnu/hello/hello-2.10.tar.gz ```console
0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i $ nix-prefetch-url --print-path mirror://gnu/hello/hello-2.10.tar.gz
/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz 0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i
/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz
```
$ nix-prefetch-url --unpack --print-path https://github.com/NixOS/patchelf/archive/0.8.tar.gz ```console
079agjlv0hrv7fxnx9ngipx14gyncbkllxrp9cccnh3a50fxcmy7 $ nix-prefetch-url --unpack --print-path https://github.com/NixOS/patchelf/archive/0.8.tar.gz
/nix/store/19zrmhm3m40xxaw81c8cqm6aljgrnwj2-0.8.tar.gz 079agjlv0hrv7fxnx9ngipx14gyncbkllxrp9cccnh3a50fxcmy7
/nix/store/19zrmhm3m40xxaw81c8cqm6aljgrnwj2-0.8.tar.gz
```

View file

@ -39,10 +39,12 @@ after `$stdenv/setup` has been sourced. Since this hook is not executed
by regular Nix builds, it allows you to perform initialisation specific by regular Nix builds, it allows you to perform initialisation specific
to `nix-shell`. For example, the derivation attribute to `nix-shell`. For example, the derivation attribute
shellHook = ```nix
shellHook =
'' ''
echo "Hello shell" echo "Hello shell"
''; '';
```
will cause `nix-shell` to print `Hello shell`. will cause `nix-shell` to print `Hello shell`.
@ -108,46 +110,58 @@ The following common options are supported:
To build the dependencies of the package Pan, and start an interactive To build the dependencies of the package Pan, and start an interactive
shell in which to build it: shell in which to build it:
$ nix-shell '<nixpkgs>' -A pan ```shell
[nix-shell]$ unpackPhase $ nix-shell '<nixpkgs>' -A pan
[nix-shell]$ cd pan-* [nix-shell]$ unpackPhase
[nix-shell]$ configurePhase [nix-shell]$ cd pan-*
[nix-shell]$ buildPhase [nix-shell]$ configurePhase
[nix-shell]$ ./pan/gui/pan [nix-shell]$ buildPhase
[nix-shell]$ ./pan/gui/pan
```
To clear the environment first, and do some additional automatic To clear the environment first, and do some additional automatic
initialisation of the interactive shell: initialisation of the interactive shell:
$ nix-shell '<nixpkgs>' -A pan --pure \ ```shell
$ nix-shell '<nixpkgs>' -A pan --pure \
--command 'export NIX_DEBUG=1; export NIX_CORES=8; return' --command 'export NIX_DEBUG=1; export NIX_CORES=8; return'
```
Nix expressions can also be given on the command line using the `-E` and Nix expressions can also be given on the command line using the `-E` and
`-p` flags. For instance, the following starts a shell containing the `-p` flags. For instance, the following starts a shell containing the
packages `sqlite` and `libX11`: packages `sqlite` and `libX11`:
$ nix-shell -E 'with import <nixpkgs> { }; runCommand "dummy" { buildInputs = [ sqlite xorg.libX11 ]; } ""' ```shell
$ nix-shell -E 'with import <nixpkgs> { }; runCommand "dummy" { buildInputs = [ sqlite xorg.libX11 ]; } ""'
```
A shorter way to do the same is: A shorter way to do the same is:
$ nix-shell -p sqlite xorg.libX11 ```shell
[nix-shell]$ echo $NIX_LDFLAGS $ nix-shell -p sqlite xorg.libX11
… -L/nix/store/j1zg5v…-sqlite-3.8.0.2/lib -L/nix/store/0gmcz9…-libX11-1.6.1/lib … [nix-shell]$ echo $NIX_LDFLAGS
… -L/nix/store/j1zg5v…-sqlite-3.8.0.2/lib -L/nix/store/0gmcz9…-libX11-1.6.1/lib …
```
Note that `-p` accepts multiple full nix expressions that are valid in Note that `-p` accepts multiple full nix expressions that are valid in
the `buildInputs = [ ... ]` shown above, not only package names. So the the `buildInputs = [ ... ]` shown above, not only package names. So the
following is also legal: following is also legal:
$ nix-shell -p sqlite 'git.override { withManual = false; }' ```shell
$ nix-shell -p sqlite 'git.override { withManual = false; }'
```
The `-p` flag looks up Nixpkgs in the Nix search path. You can override The `-p` flag looks up Nixpkgs in the Nix search path. You can override
it by passing `-I` or setting `NIX_PATH`. For example, the following it by passing `-I` or setting `NIX_PATH`. For example, the following
gives you a shell containing the Pan package from a specific revision of gives you a shell containing the Pan package from a specific revision of
Nixpkgs: Nixpkgs:
$ nix-shell -p pan -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/8a3eea054838b55aca962c3fbde9c83c102b8bf2.tar.gz ```shell
$ nix-shell -p pan -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/8a3eea054838b55aca962c3fbde9c83c102b8bf2.tar.gz
[nix-shell:~]$ pan --version [nix-shell:~]$ pan --version
Pan 0.139 Pan 0.139
```
# Use as a `#!`-interpreter # Use as a `#!`-interpreter
@ -155,8 +169,10 @@ You can use `nix-shell` as a script interpreter to allow scripts written
in arbitrary languages to obtain their own dependencies via Nix. This is in arbitrary languages to obtain their own dependencies via Nix. This is
done by starting the script with the following lines: done by starting the script with the following lines:
#! /usr/bin/env nix-shell ```bash
#! nix-shell -i real-interpreter -p packages #! /usr/bin/env nix-shell
#! nix-shell -i real-interpreter -p packages
```
where *real-interpreter* is the “real” script interpreter that will be where *real-interpreter* is the “real” script interpreter that will be
invoked by `nix-shell` after it has obtained the dependencies and invoked by `nix-shell` after it has obtained the dependencies and
@ -170,39 +186,45 @@ because many operating systems only allow one argument in `#!` lines.
For example, here is a Python script that depends on Python and the For example, here is a Python script that depends on Python and the
`prettytable` package: `prettytable` package:
#! /usr/bin/env nix-shell ```python
#! nix-shell -i python -p python pythonPackages.prettytable #! /usr/bin/env nix-shell
#! nix-shell -i python -p python pythonPackages.prettytable
import prettytable import prettytable
# Print a simple table. # Print a simple table.
t = prettytable.PrettyTable(["N", "N^2"]) t = prettytable.PrettyTable(["N", "N^2"])
for n in range(1, 10): t.add_row([n, n * n]) for n in range(1, 10): t.add_row([n, n * n])
print t print t
```
Similarly, the following is a Perl script that specifies that it Similarly, the following is a Perl script that specifies that it
requires Perl and the `HTML::TokeParser::Simple` and `LWP` packages: requires Perl and the `HTML::TokeParser::Simple` and `LWP` packages:
#! /usr/bin/env nix-shell ```perl
#! nix-shell -i perl -p perl perlPackages.HTMLTokeParserSimple perlPackages.LWP #! /usr/bin/env nix-shell
#! nix-shell -i perl -p perl perlPackages.HTMLTokeParserSimple perlPackages.LWP
use HTML::TokeParser::Simple; use HTML::TokeParser::Simple;
# Fetch nixos.org and print all hrefs. # Fetch nixos.org and print all hrefs.
my $p = HTML::TokeParser::Simple->new(url => 'http://nixos.org/'); my $p = HTML::TokeParser::Simple->new(url => 'http://nixos.org/');
while (my $token = $p->get_tag("a")) { while (my $token = $p->get_tag("a")) {
my $href = $token->get_attr("href"); my $href = $token->get_attr("href");
print "$href\n" if $href; print "$href\n" if $href;
} }
```
Sometimes you need to pass a simple Nix expression to customize a Sometimes you need to pass a simple Nix expression to customize a
package like Terraform: package like Terraform:
#! /usr/bin/env nix-shell ```bash
#! nix-shell -i bash -p "terraform.withPlugins (plugins: [ plugins.openstack ])" #! /usr/bin/env nix-shell
#! nix-shell -i bash -p "terraform.withPlugins (plugins: [ plugins.openstack ])"
terraform apply terraform apply
```
> **Note** > **Note**
> >
@ -213,20 +235,22 @@ Finally, using the merging of multiple nix-shell shebangs the following
Haskell script uses a specific branch of Nixpkgs/NixOS (the 18.03 stable Haskell script uses a specific branch of Nixpkgs/NixOS (the 18.03 stable
branch): branch):
#! /usr/bin/env nix-shell ```haskell
#! nix-shell -i runghc -p "haskellPackages.ghcWithPackages (ps: [ps.HTTP ps.tagsoup])" #! /usr/bin/env nix-shell
#! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/nixos-18.03.tar.gz #! nix-shell -i runghc -p "haskellPackages.ghcWithPackages (ps: [ps.HTTP ps.tagsoup])"
#! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/nixos-18.03.tar.gz
import Network.HTTP import Network.HTTP
import Text.HTML.TagSoup import Text.HTML.TagSoup
-- Fetch nixos.org and print all hrefs. -- Fetch nixos.org and print all hrefs.
main = do main = do
resp <- Network.HTTP.simpleHTTP (getRequest "http://nixos.org/") resp <- Network.HTTP.simpleHTTP (getRequest "http://nixos.org/")
body <- getResponseBody resp body <- getResponseBody resp
let tags = filter (isTagOpenName "a") $ parseTags body let tags = filter (isTagOpenName "a") $ parseTags body
let tags' = map (fromAttrib "href") tags let tags' = map (fromAttrib "href") tags
mapM_ putStrLn $ filter (/= "") tags' mapM_ putStrLn $ filter (/= "") tags'
```
If you want to be even more precise, you can specify a specific revision If you want to be even more precise, you can specify a specific revision
of Nixpkgs: of Nixpkgs:
@ -237,12 +261,16 @@ The examples above all used `-p` to get dependencies from Nixpkgs. You
can also use a Nix expression to build your own dependencies. For can also use a Nix expression to build your own dependencies. For
example, the Python example could have been written as: example, the Python example could have been written as:
#! /usr/bin/env nix-shell ```python
#! nix-shell deps.nix -i python #! /usr/bin/env nix-shell
#! nix-shell deps.nix -i python
```
where the file `deps.nix` in the same directory as the `#!`-script where the file `deps.nix` in the same directory as the `#!`-script
contains: contains:
with import <nixpkgs> {}; ```nix
with import <nixpkgs> {};
runCommand "dummy" { buildInputs = [ python pythonPackages.prettytable ]; } "" runCommand "dummy" { buildInputs = [ python pythonPackages.prettytable ]; } ""
```

View file

@ -47,6 +47,7 @@ have an effect.
The `--indirect` flag causes a uniquely named symlink to *path* to The `--indirect` flag causes a uniquely named symlink to *path* to
be stored in `/nix/var/nix/gcroots/auto/`. For instance, be stored in `/nix/var/nix/gcroots/auto/`. For instance,
```console
$ nix-store --add-root /home/eelco/bla/result --indirect -r ... $ nix-store --add-root /home/eelco/bla/result --indirect -r ...
$ ls -l /nix/var/nix/gcroots/auto $ ls -l /nix/var/nix/gcroots/auto
@ -54,6 +55,7 @@ have an effect.
$ ls -l /home/eelco/bla/result $ ls -l /home/eelco/bla/result
lrwxrwxrwx 1 ... 2005-03-13 21:10 /home/eelco/bla/result -> /nix/store/1r11343n6qd4...-f-spot-0.0.10 lrwxrwxrwx 1 ... 2005-03-13 21:10 /home/eelco/bla/result -> /nix/store/1r11343n6qd4...-f-spot-0.0.10
```
Thus, when `/home/eelco/bla/result` is removed, the GC root in the Thus, when `/home/eelco/bla/result` is removed, the GC root in the
`auto` directory becomes a dangling symlink and will be ignored by `auto` directory becomes a dangling symlink and will be ignored by
@ -157,14 +159,18 @@ or.
This operation is typically used to build store derivations produced by This operation is typically used to build store derivations produced by
[`nix-instantiate`](nix-instantiate.md): [`nix-instantiate`](nix-instantiate.md):
$ nix-store -r $(nix-instantiate ./test.nix) ```console
/nix/store/31axcgrlbfsxzmfff1gyj1bf62hvkby2-aterm-2.3.1 $ nix-store -r $(nix-instantiate ./test.nix)
/nix/store/31axcgrlbfsxzmfff1gyj1bf62hvkby2-aterm-2.3.1
```
This is essentially what [`nix-build`](nix-build.md) does. This is essentially what [`nix-build`](nix-build.md) does.
To test whether a previously-built derivation is deterministic: To test whether a previously-built derivation is deterministic:
$ nix-build '<nixpkgs>' -A hello --check -K ```console
$ nix-build '<nixpkgs>' -A hello --check -K
```
# Operation `--serve` # Operation `--serve`
@ -190,9 +196,11 @@ The following flags are available:
To turn a host into a build server, the `authorized_keys` file can be To turn a host into a build server, the `authorized_keys` file can be
used to provide build access to a given SSH public key: used to provide build access to a given SSH public key:
$ cat <<EOF >>/root/.ssh/authorized_keys ```console
command="nice -n20 nix-store --serve --write" ssh-rsa AAAAB3NzaC1yc2EAAAA... $ cat <<EOF >>/root/.ssh/authorized_keys
EOF command="nice -n20 nix-store --serve --write" ssh-rsa AAAAB3NzaC1yc2EAAAA...
EOF
```
# Operation `--gc` # Operation `--gc`
@ -245,14 +253,18 @@ number of bytes that would be freed.
To delete all unreachable paths, just do: To delete all unreachable paths, just do:
$ nix-store --gc ```console
deleting `/nix/store/kq82idx6g0nyzsp2s14gfsc38npai7lf-cairo-1.0.4.tar.gz.drv' $ nix-store --gc
... deleting `/nix/store/kq82idx6g0nyzsp2s14gfsc38npai7lf-cairo-1.0.4.tar.gz.drv'
8825586 bytes freed (8.42 MiB) ...
8825586 bytes freed (8.42 MiB)
```
To delete at least 100 MiBs of unreachable paths: To delete at least 100 MiBs of unreachable paths:
$ nix-store --gc --max-freed $((100 * 1024 * 1024)) ```console
$ nix-store --gc --max-freed $((100 * 1024 * 1024))
```
# Operation `--delete` # Operation `--delete`
@ -274,9 +286,11 @@ paths in the store that refer to it (i.e., depend on it).
## Example ## Example
$ nix-store --delete /nix/store/zq0h41l75vlb4z45kzgjjmsjxvcv1qk7-mesa-6.4 ```console
0 bytes freed (0.00 MiB) $ nix-store --delete /nix/store/zq0h41l75vlb4z45kzgjjmsjxvcv1qk7-mesa-6.4
error: cannot delete path `/nix/store/zq0h41l75vlb4z45kzgjjmsjxvcv1qk7-mesa-6.4' since it is still alive 0 bytes freed (0.00 MiB)
error: cannot delete path `/nix/store/zq0h41l75vlb4z45kzgjjmsjxvcv1qk7-mesa-6.4' since it is still alive
```
# Operation `--query` # Operation `--query`
@ -407,18 +421,22 @@ symlink.
Print the closure (runtime dependencies) of the `svn` program in the Print the closure (runtime dependencies) of the `svn` program in the
current user environment: current user environment:
$ nix-store -qR $(which svn) ```console
/nix/store/5mbglq5ldqld8sj57273aljwkfvj22mc-subversion-1.1.4 $ nix-store -qR $(which svn)
/nix/store/9lz9yc6zgmc0vlqmn2ipcpkjlmbi51vv-glibc-2.3.4 /nix/store/5mbglq5ldqld8sj57273aljwkfvj22mc-subversion-1.1.4
... /nix/store/9lz9yc6zgmc0vlqmn2ipcpkjlmbi51vv-glibc-2.3.4
...
```
Print the build-time dependencies of `svn`: Print the build-time dependencies of `svn`:
$ nix-store -qR $(nix-store -qd $(which svn)) ```console
/nix/store/02iizgn86m42q905rddvg4ja975bk2i4-grep-2.5.1.tar.bz2.drv $ nix-store -qR $(nix-store -qd $(which svn))
/nix/store/07a2bzxmzwz5hp58nf03pahrv2ygwgs3-gcc-wrapper.sh /nix/store/02iizgn86m42q905rddvg4ja975bk2i4-grep-2.5.1.tar.bz2.drv
/nix/store/0ma7c9wsbaxahwwl04gbw3fcd806ski4-glibc-2.3.4.drv /nix/store/07a2bzxmzwz5hp58nf03pahrv2ygwgs3-gcc-wrapper.sh
... lots of other paths ... /nix/store/0ma7c9wsbaxahwwl04gbw3fcd806ski4-glibc-2.3.4.drv
... lots of other paths ...
```
The difference with the previous example is that we ask the closure of The difference with the previous example is that we ask the closure of
the derivation (`-qd`), not the closure of the output path that contains the derivation (`-qd`), not the closure of the output path that contains
@ -426,29 +444,35 @@ the derivation (`-qd`), not the closure of the output path that contains
Show the build-time dependencies as a tree: Show the build-time dependencies as a tree:
$ nix-store -q --tree $(nix-store -qd $(which svn)) ```console
/nix/store/7i5082kfb6yjbqdbiwdhhza0am2xvh6c-subversion-1.1.4.drv $ nix-store -q --tree $(nix-store -qd $(which svn))
+---/nix/store/d8afh10z72n8l1cr5w42366abiblgn54-builder.sh /nix/store/7i5082kfb6yjbqdbiwdhhza0am2xvh6c-subversion-1.1.4.drv
+---/nix/store/fmzxmpjx2lh849ph0l36snfj9zdibw67-bash-3.0.drv +---/nix/store/d8afh10z72n8l1cr5w42366abiblgn54-builder.sh
| +---/nix/store/570hmhmx3v57605cqg9yfvvyh0nnb8k8-bash +---/nix/store/fmzxmpjx2lh849ph0l36snfj9zdibw67-bash-3.0.drv
| +---/nix/store/p3srsbd8dx44v2pg6nbnszab5mcwx03v-builder.sh | +---/nix/store/570hmhmx3v57605cqg9yfvvyh0nnb8k8-bash
... | +---/nix/store/p3srsbd8dx44v2pg6nbnszab5mcwx03v-builder.sh
...
```
Show all paths that depend on the same OpenSSL library as `svn`: Show all paths that depend on the same OpenSSL library as `svn`:
$ nix-store -q --referrers $(nix-store -q --binding openssl $(nix-store -qd $(which svn))) ```console
/nix/store/23ny9l9wixx21632y2wi4p585qhva1q8-sylpheed-1.0.0 $ nix-store -q --referrers $(nix-store -q --binding openssl $(nix-store -qd $(which svn)))
/nix/store/5mbglq5ldqld8sj57273aljwkfvj22mc-subversion-1.1.4 /nix/store/23ny9l9wixx21632y2wi4p585qhva1q8-sylpheed-1.0.0
/nix/store/dpmvp969yhdqs7lm2r1a3gng7pyq6vy4-subversion-1.1.3 /nix/store/5mbglq5ldqld8sj57273aljwkfvj22mc-subversion-1.1.4
/nix/store/l51240xqsgg8a7yrbqdx1rfzyv6l26fx-lynx-2.8.5 /nix/store/dpmvp969yhdqs7lm2r1a3gng7pyq6vy4-subversion-1.1.3
/nix/store/l51240xqsgg8a7yrbqdx1rfzyv6l26fx-lynx-2.8.5
```
Show all paths that directly or indirectly depend on the Glibc (C Show all paths that directly or indirectly depend on the Glibc (C
library) used by `svn`: library) used by `svn`:
$ nix-store -q --referrers-closure $(ldd $(which svn) | grep /libc.so | awk '{print $3}') ```console
/nix/store/034a6h4vpz9kds5r6kzb9lhh81mscw43-libgnomeprintui-2.8.2 $ nix-store -q --referrers-closure $(ldd $(which svn) | grep /libc.so | awk '{print $3}')
/nix/store/15l3yi0d45prm7a82pcrknxdh6nzmxza-gawk-3.1.4 /nix/store/034a6h4vpz9kds5r6kzb9lhh81mscw43-libgnomeprintui-2.8.2
... /nix/store/15l3yi0d45prm7a82pcrknxdh6nzmxza-gawk-3.1.4
...
```
Note that `ldd` is a command that prints out the dynamic libraries used Note that `ldd` is a command that prints out the dynamic libraries used
by an ELF executable. by an ELF executable.
@ -456,16 +480,20 @@ by an ELF executable.
Make a picture of the runtime dependency graph of the current user Make a picture of the runtime dependency graph of the current user
environment: environment:
$ nix-store -q --graph ~/.nix-profile | dot -Tps > graph.ps ```console
$ gv graph.ps $ nix-store -q --graph ~/.nix-profile | dot -Tps > graph.ps
$ gv graph.ps
```
Show every garbage collector root that points to a store path that Show every garbage collector root that points to a store path that
depends on `svn`: depends on `svn`:
$ nix-store -q --roots $(which svn) ```console
/nix/var/nix/profiles/default-81-link $ nix-store -q --roots $(which svn)
/nix/var/nix/profiles/default-82-link /nix/var/nix/profiles/default-81-link
/nix/var/nix/profiles/per-user/eelco/profile-97-link /nix/var/nix/profiles/default-82-link
/nix/var/nix/profiles/per-user/eelco/profile-97-link
```
# Operation `--add` # Operation `--add`
@ -480,8 +508,10 @@ prints the resulting paths in the Nix store on standard output.
## Example ## Example
$ nix-store --add ./foo.c ```console
/nix/store/m7lrha58ph6rcnv109yzx1nk1cj7k7zf-foo.c $ nix-store --add ./foo.c
/nix/store/m7lrha58ph6rcnv109yzx1nk1cj7k7zf-foo.c
```
# Operation `--add-fixed` # Operation `--add-fixed`
@ -505,8 +535,10 @@ This operation has the following options:
## Example ## Example
$ nix-store --add-fixed sha256 ./hello-2.10.tar.gz ```console
/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz $ nix-store --add-fixed sha256 ./hello-2.10.tar.gz
/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz
```
# Operation `--verify` # Operation `--verify`
@ -554,7 +586,9 @@ path has changed, and 1 otherwise.
To verify the integrity of the `svn` command and all its dependencies: To verify the integrity of the `svn` command and all its dependencies:
$ nix-store --verify-path $(nix-store -qR $(which svn)) ```console
$ nix-store --verify-path $(nix-store -qR $(which svn))
```
# Operation `--repair-path` # Operation `--repair-path`
@ -578,14 +612,16 @@ substitutes are available, then repair is not possible.
## Example ## Example
$ nix-store --verify-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13 ```console
path `/nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13' was modified! $ nix-store --verify-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13
path `/nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13' was modified!
expected hash `2db57715ae90b7e31ff1f2ecb8c12ec1cc43da920efcbe3b22763f36a1861588', expected hash `2db57715ae90b7e31ff1f2ecb8c12ec1cc43da920efcbe3b22763f36a1861588',
got `481c5aa5483ebc97c20457bb8bca24deea56550d3985cda0027f67fe54b808e4' got `481c5aa5483ebc97c20457bb8bca24deea56550d3985cda0027f67fe54b808e4'
$ nix-store --repair-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13 $ nix-store --repair-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13
fetching path `/nix/store/d7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13'... fetching path `/nix/store/d7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13'...
```
# Operation `--dump` # Operation `--dump`
@ -651,11 +687,15 @@ a store path references other store paths that are missing in the target
Nix store, the import will fail. To copy a whole closure, do something Nix store, the import will fail. To copy a whole closure, do something
like: like:
$ nix-store --export $(nix-store -qR paths) > out ```console
$ nix-store --export $(nix-store -qR paths) > out
```
To import the whole closure again, run: To import the whole closure again, run:
$ nix-store --import < out ```console
$ nix-store --import < out
```
# Operation `--import` # Operation `--import`
@ -695,11 +735,13 @@ Use `-vv` or `-vvv` to get some progress indication.
## Example ## Example
$ nix-store --optimise ```console
hashing files in `/nix/store/qhqx7l2f1kmwihc9bnxs7rc159hsxnf3-gcc-4.1.1' $ nix-store --optimise
... hashing files in `/nix/store/qhqx7l2f1kmwihc9bnxs7rc159hsxnf3-gcc-4.1.1'
541838819 bytes (516.74 MiB) freed by hard-linking 54143 files; ...
there are 114486 files with equal contents out of 215894 files in total 541838819 bytes (516.74 MiB) freed by hard-linking 54143 files;
there are 114486 files with equal contents out of 215894 files in total
```
# Operation `--read-log` # Operation `--read-log`
@ -721,13 +763,15 @@ substitute, then the log is unavailable.
## Example ## Example
$ nix-store -l $(which ktorrent) ```console
building /nix/store/dhc73pvzpnzxhdgpimsd9sw39di66ph1-ktorrent-2.2.1 $ nix-store -l $(which ktorrent)
unpacking sources building /nix/store/dhc73pvzpnzxhdgpimsd9sw39di66ph1-ktorrent-2.2.1
unpacking source archive /nix/store/p8n1jpqs27mgkjw07pb5269717nzf5f8-ktorrent-2.2.1.tar.gz unpacking sources
ktorrent-2.2.1/ unpacking source archive /nix/store/p8n1jpqs27mgkjw07pb5269717nzf5f8-ktorrent-2.2.1.tar.gz
ktorrent-2.2.1/NEWS ktorrent-2.2.1/
... ktorrent-2.2.1/NEWS
...
```
# Operation `--dump-db` # Operation `--dump-db`
@ -773,12 +817,14 @@ of the builder are placed in the variable `_args`.
## Example ## Example
$ nix-store --print-env $(nix-instantiate '<nixpkgs>' -A firefox) ```console
$ nix-store --print-env $(nix-instantiate '<nixpkgs>' -A firefox)
export src; src='/nix/store/plpj7qrwcz94z2psh6fchsi7s8yihc7k-firefox-12.0.source.tar.bz2'
export stdenv; stdenv='/nix/store/7c8asx3yfrg5dg1gzhzyq2236zfgibnn-stdenv' export src; src='/nix/store/plpj7qrwcz94z2psh6fchsi7s8yihc7k-firefox-12.0.source.tar.bz2'
export system; system='x86_64-linux' export stdenv; stdenv='/nix/store/7c8asx3yfrg5dg1gzhzyq2236zfgibnn-stdenv'
export _args; _args='-e /nix/store/9krlzvny65gdc8s7kpb6lkx8cd02c25c-default-builder.sh' export system; system='x86_64-linux'
export _args; _args='-e /nix/store/9krlzvny65gdc8s7kpb6lkx8cd02c25c-default-builder.sh'
```
# Operation `--generate-binary-cache-key` # Operation `--generate-binary-cache-key`

View file

@ -159,10 +159,12 @@ Most Nix commands accept the following command-line options:
For instance, the top-level `default.nix` in Nixpkgs is actually a For instance, the top-level `default.nix` in Nixpkgs is actually a
function: function:
```nix
{ # The system (e.g., `i686-linux') for which to build the packages. { # The system (e.g., `i686-linux') for which to build the packages.
system ? builtins.currentSystem system ? builtins.currentSystem
... ...
}: ... }: ...
```
So if you call this Nix expression (e.g., when you do `nix-env -i So if you call this Nix expression (e.g., when you do `nix-env -i
pkgname`), the function will be called automatically using the pkgname`), the function will be called automatically using the

View file

@ -6,7 +6,9 @@ Derivations can declare some infrequently used optional attributes.
The optional attribute `allowedReferences` specifies a list of legal The optional attribute `allowedReferences` specifies a list of legal
references (dependencies) of the output of the builder. For example, references (dependencies) of the output of the builder. For example,
```nix
allowedReferences = []; allowedReferences = [];
```
enforces that the output of a derivation cannot have any runtime enforces that the output of a derivation cannot have any runtime
dependencies on its inputs. To allow an output to have a runtime dependencies on its inputs. To allow an output to have a runtime
@ -20,7 +22,9 @@ Derivations can declare some infrequently used optional attributes.
the legal requisites of the whole closure, so all the dependencies the legal requisites of the whole closure, so all the dependencies
recursively. For example, recursively. For example,
```nix
allowedRequisites = [ foobar ]; allowedRequisites = [ foobar ];
```
enforces that the output of a derivation cannot have any other enforces that the output of a derivation cannot have any other
runtime dependency than `foobar`, and in addition it enforces that runtime dependency than `foobar`, and in addition it enforces that
@ -31,7 +35,9 @@ Derivations can declare some infrequently used optional attributes.
illegal references (dependencies) of the output of the builder. For illegal references (dependencies) of the output of the builder. For
example, example,
```nix
disallowedReferences = [ foo ]; disallowedReferences = [ foo ];
```
enforces that the output of a derivation cannot have a direct enforces that the output of a derivation cannot have a direct
runtime dependencies on the derivation `foo`. runtime dependencies on the derivation `foo`.
@ -41,7 +47,9 @@ Derivations can declare some infrequently used optional attributes.
specifies illegal requisites for the whole closure, so all the specifies illegal requisites for the whole closure, so all the
dependencies recursively. For example, dependencies recursively. For example,
```nix
disallowedRequisites = [ foobar ]; disallowedRequisites = [ foobar ];
```
enforces that the output of a derivation cannot have any runtime enforces that the output of a derivation cannot have any runtime
dependency on `foobar` or any other derivation depending recursively dependency on `foobar` or any other derivation depending recursively
@ -50,20 +58,20 @@ Derivations can declare some infrequently used optional attributes.
- `exportReferencesGraph` - `exportReferencesGraph`
This attribute allows builders access to the references graph of This attribute allows builders access to the references graph of
their inputs. The attribute is a list of inputs in the Nix store their inputs. The attribute is a list of inputs in the Nix store
whose references graph the builder needs to know. The value of this whose references graph the builder needs to know. The value of
attribute should be a list of pairs `[ name1 this attribute should be a list of pairs `[ name1 path1 name2
path1 name2 path2 ... ]`. The references graph of each *pathN* will be stored
path2 ... in a text file *nameN* in the temporary build directory. The text
]`. The references graph of each *pathN* will be stored in a text files have the format used by `nix-store --register-validity`
file *nameN* in the temporary build directory. The text files have (with the deriver fields left empty). For example, when the
the format used by `nix-store following derivation is built:
--register-validity` (with the deriver fields left empty). For
example, when the following derivation is built:
```nix
derivation { derivation {
... ...
exportReferencesGraph = [ "libfoo-graph" libfoo ]; exportReferencesGraph = [ "libfoo-graph" libfoo ];
}; };
```
the references graph of `libfoo` is placed in the file the references graph of `libfoo` is placed in the file
`libfoo-graph` in the temporary build directory. `libfoo-graph` in the temporary build directory.
@ -84,7 +92,9 @@ Derivations can declare some infrequently used optional attributes.
environment variables to be passed unmodified. For example, environment variables to be passed unmodified. For example,
`fetchurl` in Nixpkgs has the line `fetchurl` in Nixpkgs has the line
```nix
impureEnvVars = [ "http_proxy" "https_proxy" ... ]; impureEnvVars = [ "http_proxy" "https_proxy" ... ];
```
to make it use the proxy server configuration specified by the user to make it use the proxy server configuration specified by the user
in the environment variables `http_proxy` and friends. in the environment variables `http_proxy` and friends.
@ -116,19 +126,23 @@ Derivations can declare some infrequently used optional attributes.
been modified, the caller must also specify a cryptographic hash of been modified, the caller must also specify a cryptographic hash of
the file. For example, the file. For example,
```nix
fetchurl { fetchurl {
url = "http://ftp.gnu.org/pub/gnu/hello/hello-2.1.1.tar.gz"; url = "http://ftp.gnu.org/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465"; sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
} }
```
It sometimes happens that the URL of the file changes, e.g., because It sometimes happens that the URL of the file changes, e.g., because
servers are reorganised or no longer available. We then must update servers are reorganised or no longer available. We then must update
the call to `fetchurl`, e.g., the call to `fetchurl`, e.g.,
```nix
fetchurl { fetchurl {
url = "ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz"; url = "ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465"; sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
} }
```
If a `fetchurl` derivation was treated like a normal derivation, the If a `fetchurl` derivation was treated like a normal derivation, the
output paths of the derivation and *all derivations depending on it* output paths of the derivation and *all derivations depending on it*
@ -147,6 +161,7 @@ Derivations can declare some infrequently used optional attributes.
As an example, here is the (simplified) Nix expression for As an example, here is the (simplified) Nix expression for
`fetchurl`: `fetchurl`:
```nix
{ stdenv, curl }: # The curl program is used for downloading. { stdenv, curl }: # The curl program is used for downloading.
{ url, sha256 }: { url, sha256 }:
@ -164,6 +179,7 @@ Derivations can declare some infrequently used optional attributes.
inherit url; inherit url;
} }
```
The `outputHashAlgo` attribute specifies the hash algorithm used to The `outputHashAlgo` attribute specifies the hash algorithm used to
compute the hash. It can currently be `"sha1"`, `"sha256"` or compute the hash. It can currently be `"sha1"`, `"sha256"` or
@ -196,21 +212,19 @@ Derivations can declare some infrequently used optional attributes.
A list of names of attributes that should be passed via files rather A list of names of attributes that should be passed via files rather
than environment variables. For example, if you have than environment variables. For example, if you have
``` ```nix
passAsFile = ["big"]; passAsFile = ["big"];
big = "a very long string"; big = "a very long string";
``` ```
then when the builder runs, the environment variable `bigPath` will then when the builder runs, the environment variable `bigPath`
contain the absolute path to a temporary file containing `a very will contain the absolute path to a temporary file containing `a
long very long string`. That is, for any attribute *x* listed in
string`. That is, for any attribute *x* listed in `passAsFile`, Nix `passAsFile`, Nix will pass an environment variable `xPath`
will pass an environment variable `xPath` holding the path of the holding the path of the file containing the value of attribute
file containing the value of attribute *x*. This is useful when you *x*. This is useful when you need to pass large strings to a
need to pass large strings to a builder, since most operating builder, since most operating systems impose a limit on the size
systems impose a limit on the size of the environment (typically, a of the environment (typically, a few hundred kilobyte).
few hundred kilobyte).
- `preferLocalBuild` - `preferLocalBuild`
If this attribute is set to `true` and [distributed building is If this attribute is set to `true` and [distributed building is

View file

@ -8,9 +8,10 @@ packages are imported and called with the appropriate arguments. Here
are some fragments of `all-packages.nix`, with annotations of what are some fragments of `all-packages.nix`, with annotations of what
they mean: they mean:
... ```nix
...
rec { ① rec { ①
hello = import ../applications/misc/hello/ex-1 ② { ③ hello = import ../applications/misc/hello/ex-1 ② { ③
inherit fetchurl stdenv perl; inherit fetchurl stdenv perl;
@ -26,7 +27,8 @@ they mean:
stdenv = ...; stdenv = ...;
} }
```
1. This file defines a set of attributes, all of which are concrete 1. This file defines a set of attributes, all of which are concrete
derivations (i.e., not functions). In fact, we define a *mutually derivations (i.e., not functions). In fact, we define a *mutually
@ -64,11 +66,15 @@ they mean:
> calls a function, filling in any missing arguments by passing the > calls a function, filling in any missing arguments by passing the
> corresponding attribute from the Nixpkgs set, like this: > corresponding attribute from the Nixpkgs set, like this:
> >
> ```nix
> hello = callPackage ../applications/misc/hello/ex-1 { }; > hello = callPackage ../applications/misc/hello/ex-1 { };
> ```
> >
> If necessary, you can set or override arguments: > If necessary, you can set or override arguments:
> >
> ```nix
> hello = callPackage ../applications/misc/hello/ex-1 { stdenv = myStdenv; }; > hello = callPackage ../applications/misc/hello/ex-1 { stdenv = myStdenv; };
> ```
4. Likewise, we have to instantiate Perl, `fetchurl`, and the standard 4. Likewise, we have to instantiate Perl, `fetchurl`, and the standard
environment. environment.

View file

@ -3,15 +3,17 @@
Here is the builder referenced from Hello's Nix expression (stored in Here is the builder referenced from Hello's Nix expression (stored in
`pkgs/applications/misc/hello/ex-1/builder.sh`): `pkgs/applications/misc/hello/ex-1/builder.sh`):
source $stdenv/setup ① ```bash
source $stdenv/setup ①
PATH=$perl/bin:$PATH ② PATH=$perl/bin:$PATH ②
tar xvfz $src ③ tar xvfz $src ③
cd hello-* cd hello-*
./configure --prefix=$out ④ ./configure --prefix=$out ④
make ⑤ make ⑤
make install make install
```
The builder can actually be made a lot shorter by using the *generic The builder can actually be made a lot shorter by using the *generic
builder* functions provided by `stdenv`, but here we write out the build builder* functions provided by `stdenv`, but here we write out the build

View file

@ -51,7 +51,9 @@ For instance, `derivation` is also available as `builtins.derivation`.
You can use `builtins` to test for the availability of features in You can use `builtins` to test for the availability of features in
the Nix installation, e.g., the Nix installation, e.g.,
```nix
if builtins ? getEnv then builtins.getEnv "PATH" else "" if builtins ? getEnv then builtins.getEnv "PATH" else ""
```
This allows a Nix expression to fall back gracefully on older Nix This allows a Nix expression to fall back gracefully on older Nix
installations that dont have the desired built-in function. installations that dont have the desired built-in function.
@ -114,9 +116,11 @@ For instance, `derivation` is also available as `builtins.derivation`.
function is to obtain external Nix expression dependencies, such as function is to obtain external Nix expression dependencies, such as
a particular version of Nixpkgs, e.g. a particular version of Nixpkgs, e.g.
```nix
with import (fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz) {}; with import (fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz) {};
stdenv.mkDerivation { … } stdenv.mkDerivation { … }
```
The fetched tarball is cached for a certain amount of time (1 hour The fetched tarball is cached for a certain amount of time (1 hour
by default) in `~/.cache/nix/tarballs/`. You can change the cache by default) in `~/.cache/nix/tarballs/`. You can change the cache
@ -124,19 +128,21 @@ For instance, `derivation` is also available as `builtins.derivation`.
of seconds` or in the Nix configuration file with this option: ` of seconds` or in the Nix configuration file with this option: `
number of seconds to cache `. number of seconds to cache `.
Note that when obtaining the hash with ` nix-prefetch-url Note that when obtaining the hash with ` nix-prefetch-url ` the
` the option `--unpack` is required. option `--unpack` is required.
This function can also verify the contents against a hash. In that 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 case, the function takes a set instead of a URL. The set requires
the attribute `url` and the attribute `sha256`, e.g. the attribute `url` and the attribute `sha256`, e.g.
```nix
with import (fetchTarball { with import (fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz"; url = "https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz";
sha256 = "1jppksrfvbk5ypiqdz4cddxdl8z6zyzdb2srq8fcffr327ld5jj2"; sha256 = "1jppksrfvbk5ypiqdz4cddxdl8z6zyzdb2srq8fcffr327ld5jj2";
}) {}; }) {};
stdenv.mkDerivation { … } stdenv.mkDerivation { … }
```
This function is not available if [restricted evaluation This function is not available if [restricted evaluation
mode](../command-ref/conf-file.md) is enabled. mode](../command-ref/conf-file.md) is enabled.
@ -172,18 +178,22 @@ For instance, `derivation` is also available as `builtins.derivation`.
- To fetch a private repository over SSH: - To fetch a private repository over SSH:
```nix
builtins.fetchGit { builtins.fetchGit {
url = "git@github.com:my-secret/repository.git"; url = "git@github.com:my-secret/repository.git";
ref = "master"; ref = "master";
rev = "adab8b916a45068c044658c4158d81878f9ed1c3"; rev = "adab8b916a45068c044658c4158d81878f9ed1c3";
} }
```
- To fetch an arbitrary reference: - To fetch an arbitrary reference:
```nix
builtins.fetchGit { builtins.fetchGit {
url = "https://github.com/NixOS/nix.git"; url = "https://github.com/NixOS/nix.git";
ref = "refs/heads/0.5-release"; ref = "refs/heads/0.5-release";
} }
```
- If the revision you're looking for is in the default branch of - 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 the git repository you don't strictly need to specify the branch
@ -193,11 +203,13 @@ For instance, `derivation` is also available as `builtins.derivation`.
branch for the non-default branch you will need to specify the branch for the non-default branch you will need to specify the
the `ref` attribute as well. the `ref` attribute as well.
```nix
builtins.fetchGit { builtins.fetchGit {
url = "https://github.com/nixos/nix.git"; url = "https://github.com/nixos/nix.git";
rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452"; rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
ref = "1.11-maintenance"; ref = "1.11-maintenance";
} }
```
> **Note** > **Note**
> >
@ -211,24 +223,30 @@ For instance, `derivation` is also available as `builtins.derivation`.
- If the revision you're looking for is in the default branch of - If the revision you're looking for is in the default branch of
the git repository you may omit the `ref` attribute. the git repository you may omit the `ref` attribute.
```nix
builtins.fetchGit { builtins.fetchGit {
url = "https://github.com/nixos/nix.git"; url = "https://github.com/nixos/nix.git";
rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452"; rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
} }
```
- To fetch a specific tag: - To fetch a specific tag:
```nix
builtins.fetchGit { builtins.fetchGit {
url = "https://github.com/nixos/nix.git"; url = "https://github.com/nixos/nix.git";
ref = "refs/tags/1.9"; ref = "refs/tags/1.9";
} }
```
- To fetch the latest version of a remote branch: - To fetch the latest version of a remote branch:
```nix
builtins.fetchGit { builtins.fetchGit {
url = "ssh://git@github.com/nixos/nix.git"; url = "ssh://git@github.com/nixos/nix.git";
ref = "master"; ref = "master";
} }
```
> **Note** > **Note**
> >
@ -248,10 +266,12 @@ For instance, `derivation` is also available as `builtins.derivation`.
filtering certain files. For instance, suppose that you want to use filtering certain files. For instance, suppose that you want to use
the directory `source-dir` as an input to a Nix expression, e.g. the directory `source-dir` as an input to a Nix expression, e.g.
```nix
stdenv.mkDerivation { stdenv.mkDerivation {
... ...
src = ./source-dir; src = ./source-dir;
} }
```
However, if `source-dir` is a Subversion working copy, then all However, if `source-dir` is a Subversion working copy, then all
those annoying `.svn` subdirectories will also be copied to the those annoying `.svn` subdirectories will also be copied to the
@ -259,7 +279,7 @@ For instance, `derivation` is also available as `builtins.derivation`.
causing lots of spurious rebuilds. With `filterSource` you can causing lots of spurious rebuilds. With `filterSource` you can
filter out the `.svn` directories: filter out the `.svn` directories:
``` ```nix
src = builtins.filterSource src = builtins.filterSource
(path: type: type != "directory" || baseNameOf path != ".svn") (path: type: type != "directory" || baseNameOf path != ".svn")
./source-dir; ./source-dir;
@ -279,10 +299,10 @@ For instance, `derivation` is also available as `builtins.derivation`.
- `builtins.foldl` *op* *nul* *list* - `builtins.foldl` *op* *nul* *list*
Reduce a list by applying a binary operator, from left to right, Reduce a list by applying a binary operator, from left to right,
e.g. `foldl op nul [x0 x1 x2 ...] = op (op e.g. `foldl op nul [x0 x1 x2 ...] = op (op (op nul x0) x1) x2)
(op nul x0) x1) x2) ...`. The operator is applied strictly, i.e., ...`. The operator is applied strictly, i.e., its arguments are
its arguments are evaluated first. For example, `foldl (x: y: x + evaluated first. For example, `foldl (x: y: x + y) 0 [1 2 3]`
y) 0 [1 2 3]` evaluates to 6. evaluates to 6.
- `builtins.functionArgs` *f* - `builtins.functionArgs` *f*
Return a set containing the names of the formal arguments expected Return a set containing the names of the formal arguments expected
@ -298,16 +318,19 @@ For instance, `derivation` is also available as `builtins.derivation`.
- `builtins.fromJSON` *e* - `builtins.fromJSON` *e*
Convert a JSON string to a Nix value. For example, Convert a JSON string to a Nix value. For example,
```nix
builtins.fromJSON ''{"x": [1, 2, 3], "y": null}'' builtins.fromJSON ''{"x": [1, 2, 3], "y": null}''
```
returns the value `{ x = [ 1 2 3 ]; y = null; returns the value `{ x = [ 1 2 3 ]; y = null; }`.
}`.
- `builtins.genList` *generator* *length* - `builtins.genList` *generator* *length*
Generate list of size *length*, with each element *i* equal to the Generate list of size *length*, with each element *i* equal to the
value returned by *generator* `i`. For example, value returned by *generator* `i`. For example,
```nix
builtins.genList (x: x * x) 5 builtins.genList (x: x * x) 5
```
returns the list `[ 0 1 4 9 16 ]`. returns the list `[ 0 1 4 9 16 ]`.
@ -369,26 +392,34 @@ For instance, `derivation` is also available as `builtins.derivation`.
variables that are in scope at the call site. For instance, if you variables that are in scope at the call site. For instance, if you
have a calling expression have a calling expression
```nix
rec { rec {
x = 123; x = 123;
y = import ./foo.nix; y = import ./foo.nix;
} }
```
then the following `foo.nix` will give an error: then the following `foo.nix` will give an error:
```nix
x + 456 x + 456
```
since `x` is not in scope in `foo.nix`. If you want `x` to be 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: available in `foo.nix`, you should pass it as a function argument:
```nix
rec { rec {
x = 123; x = 123;
y = import ./foo.nix x; y = import ./foo.nix x;
} }
```
and and
```nix
x: x + 456 x: x + 456
```
(The function argument doesnt have to be called `x` in `foo.nix`; (The function argument doesnt have to be called `x` in `foo.nix`;
any name would work.) any name would work.)
@ -442,23 +473,28 @@ For instance, `derivation` is also available as `builtins.derivation`.
string-valued attribute `name` specifying the name of the attribute, string-valued attribute `name` specifying the name of the attribute,
and an attribute `value` specifying its value. Example: and an attribute `value` specifying its value. Example:
```nix
builtins.listToAttrs builtins.listToAttrs
[ { name = "foo"; value = 123; } [ { name = "foo"; value = 123; }
{ name = "bar"; value = 456; } { name = "bar"; value = 456; }
] ]
```
evaluates to evaluates to
```nix
{ foo = 123; bar = 456; } { foo = 123; bar = 456; }
```
- `map` *f* *list*; `builtins.map` *f* *list* - `map` *f* *list*; `builtins.map` *f* *list*
Apply the function *f* to each element in the list *list*. For Apply the function *f* to each element in the list *list*. For
example, example,
```nix
map (x: "foo" + x) [ "bar" "bla" "abc" ] map (x: "foo" + x) [ "bar" "bla" "abc" ]
```
evaluates to `[ "foobar" "foobla" "fooabc" evaluates to `[ "foobar" "foobla" "fooabc" ]`.
]`.
- `builtins.match` *regex* *str* - `builtins.match` *regex* *str*
Returns a list if the [extended POSIX regular Returns a list if the [extended POSIX regular
@ -466,19 +502,27 @@ For instance, `derivation` is also available as `builtins.derivation`.
*regex* matches *str* precisely, otherwise returns `null`. Each item *regex* matches *str* precisely, otherwise returns `null`. Each item
in the list is a regex group. in the list is a regex group.
```nix
builtins.match "ab" "abc" builtins.match "ab" "abc"
```
Evaluates to `null`. Evaluates to `null`.
```nix
builtins.match "abc" "abc" builtins.match "abc" "abc"
```
Evaluates to `[ ]`. Evaluates to `[ ]`.
```nix
builtins.match "a(b)(c)" "abc" builtins.match "a(b)(c)" "abc"
```
Evaluates to `[ "b" "c" ]`. Evaluates to `[ "b" "c" ]`.
```nix
builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" " FOO " builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" " FOO "
```
Evaluates to `[ "foo" ]`. Evaluates to `[ "foo" ]`.
@ -534,11 +578,12 @@ For instance, `derivation` is also available as `builtins.derivation`.
- `builtins.readDir` *path* - `builtins.readDir` *path*
Return the contents of the directory *path* as a set mapping Return the contents of the directory *path* as a set mapping
directory entries to the corresponding file type. For instance, if directory entries to the corresponding file type. For instance, if
directory `A` contains a regular file `B` and another directory `C`, directory `A` contains a regular file `B` and another directory
then `builtins.readDir `C`, then `builtins.readDir ./A` will return the set
./A` will return the set
```nix
{ B = "regular"; C = "directory"; } { B = "regular"; C = "directory"; }
```
The possible values for the file type are `"regular"`, The possible values for the file type are `"regular"`,
`"directory"`, `"symlink"` and `"unknown"`. `"directory"`, `"symlink"` and `"unknown"`.
@ -550,7 +595,9 @@ For instance, `derivation` is also available as `builtins.derivation`.
Remove the attributes listed in *list* from *set*. The attributes Remove the attributes listed in *list* from *set*. The attributes
dont have to exist in *set*. For instance, dont have to exist in *set*. For instance,
```nix
removeAttrs { x = 1; y = 2; z = 3; } [ "a" "x" "z" ] removeAttrs { x = 1; y = 2; z = 3; } [ "a" "x" "z" ]
```
evaluates to `{ y = 2; }`. evaluates to `{ y = 2; }`.
@ -558,7 +605,9 @@ For instance, `derivation` is also available as `builtins.derivation`.
Given string *s*, replace every occurrence of the strings in *from* Given string *s*, replace every occurrence of the strings in *from*
with the corresponding string in *to*. For example, with the corresponding string in *to*. For example,
```nix
builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar" builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar"
```
evaluates to `"fabir"`. evaluates to `"fabir"`.
@ -572,10 +621,11 @@ For instance, `derivation` is also available as `builtins.derivation`.
if the first element is less than the second, and `false` otherwise. if the first element is less than the second, and `false` otherwise.
For example, For example,
```nix
builtins.sort builtins.lessThan [ 483 249 526 147 42 77 ] builtins.sort builtins.lessThan [ 483 249 526 147 42 77 ]
```
produces the list `[ 42 77 147 249 483 526 produces the list `[ 42 77 147 249 483 526 ]`.
]`.
This is a stable sort: it preserves the relative order of elements This is a stable sort: it preserves the relative order of elements
deemed equal by the comparator. deemed equal by the comparator.
@ -587,19 +637,27 @@ For instance, `derivation` is also available as `builtins.derivation`.
*regex* matches of *str*. Each item in the lists of matched *regex* matches of *str*. Each item in the lists of matched
sequences is a regex group. sequences is a regex group.
```nix
builtins.split "(a)b" "abc" builtins.split "(a)b" "abc"
```
Evaluates to `[ "" [ "a" ] "c" ]`. Evaluates to `[ "" [ "a" ] "c" ]`.
```nix
builtins.split "([ac])" "abc" builtins.split "([ac])" "abc"
```
Evaluates to `[ "" [ "a" ] "b" [ "c" ] "" ]`. Evaluates to `[ "" [ "a" ] "b" [ "c" ] "" ]`.
```nix
builtins.split "(a)|(c)" "abc" builtins.split "(a)|(c)" "abc"
```
Evaluates to `[ "" [ "a" null ] "b" [ null "c" ] "" ]`. Evaluates to `[ "" [ "a" null ] "b" [ null "c" ] "" ]`.
```nix
builtins.split "([[:upper:]]+)" " FOO " builtins.split "([[:upper:]]+)" " FOO "
```
Evaluates to `[ " " [ "FOO" ] " " ]`. Evaluates to `[ " " [ "FOO" ] " " ]`.
@ -623,7 +681,9 @@ For instance, `derivation` is also available as `builtins.derivation`.
substring up to the end of the string is returned. *start* must be substring up to the end of the string is returned. *start* must be
non-negative. For example, non-negative. For example,
```nix
builtins.substring 0 3 "nixos" builtins.substring 0 3 "nixos"
```
evaluates to `"nix"`. evaluates to `"nix"`.
@ -646,6 +706,7 @@ For instance, `derivation` is also available as `builtins.derivation`.
[Nix expression for GNU Hello](expression-syntax.md) and its [Nix expression for GNU Hello](expression-syntax.md) and its
[build script](build-script.md) into one file: [build script](build-script.md) into one file:
```nix
{ stdenv, fetchurl, perl }: { stdenv, fetchurl, perl }:
stdenv.mkDerivation { stdenv.mkDerivation {
@ -669,10 +730,11 @@ For instance, `derivation` is also available as `builtins.derivation`.
}; };
inherit perl; inherit perl;
} }
```
It is even possible for one file to refer to another, e.g., It is even possible for one file to refer to another, e.g.,
``` ```nix
builder = let builder = let
configFile = builtins.toFile "foo.conf" " configFile = builtins.toFile "foo.conf" "
# This is some dummy configuration file. # This is some dummy configuration file.
@ -694,10 +756,12 @@ For instance, `derivation` is also available as `builtins.derivation`.
It is however *not* allowed to have files mutually referring to each It is however *not* allowed to have files mutually referring to each
other, like so: other, like so:
```nix
let let
foo = builtins.toFile "foo" "...${bar}..."; foo = builtins.toFile "foo" "...${bar}...";
bar = builtins.toFile "bar" "...${foo}..."; bar = builtins.toFile "bar" "...${foo}...";
in foo in foo
```
This is not allowed because it would cause a cyclic dependency in This is not allowed because it would cause a cyclic dependency in
the computation of the cryptographic hashes for `foo` and `bar`. the computation of the cryptographic hashes for `foo` and `bar`.
@ -744,6 +808,7 @@ For instance, `derivation` is also available as `builtins.derivation`.
Here is an example where this is the case: Here is an example where this is the case:
```nix
{ stdenv, fetchurl, libxslt, jira, uberwiki }: { stdenv, fetchurl, libxslt, jira, uberwiki }:
stdenv.mkDerivation (rec { stdenv.mkDerivation (rec {
@ -778,6 +843,7 @@ For instance, `derivation` is also available as `builtins.derivation`.
{ path = "/wiki"; war = uberwiki + "/uberwiki.war"; } { path = "/wiki"; war = uberwiki + "/uberwiki.war"; }
]; ];
}) })
```
The builder is supposed to generate the configuration file for a The builder is supposed to generate the configuration file for a
[Jetty servlet container](http://jetty.mortbay.org/). A servlet [Jetty servlet container](http://jetty.mortbay.org/). A servlet
@ -796,6 +862,7 @@ For instance, `derivation` is also available as `builtins.derivation`.
configuration file for the Jetty server. The XML representation configuration file for the Jetty server. The XML representation
produced at point ③ by `toXML` is as follows: produced at point ③ by `toXML` is as follows:
```xml
<?xml version='1.0' encoding='utf-8'?> <?xml version='1.0' encoding='utf-8'?>
<expr> <expr>
<list> <list>
@ -817,6 +884,7 @@ For instance, `derivation` is also available as `builtins.derivation`.
</attrs> </attrs>
</list> </list>
</expr> </expr>
```
Note that we used the `toFile` built-in to write the builder and Note that we used the `toFile` built-in to write the builder and
the stylesheet “inline” in the Nix expression. The path of the the stylesheet “inline” in the Nix expression. The path of the
@ -830,13 +898,13 @@ For instance, `derivation` is also available as `builtins.derivation`.
- `builtins.tryEval` *e* - `builtins.tryEval` *e*
Try to shallowly evaluate *e*. Return a set containing the Try to shallowly evaluate *e*. Return a set containing the
attributes `success` (`true` if *e* evaluated successfully, `false` attributes `success` (`true` if *e* evaluated successfully,
if an error was thrown) and `value`, equalling *e* if successful and `false` if an error was thrown) and `value`, equalling *e* if
`false` otherwise. Note that this doesn't evaluate *e* deeply, so successful and `false` otherwise. Note that this doesn't evaluate
` let e = { x = throw ""; }; in (builtins.tryEval e).success *e* deeply, so ` let e = { x = throw ""; }; in (builtins.tryEval
` will be `true`. Using ` builtins.deepSeq e).success ` will be `true`. Using ` builtins.deepSeq ` one can
` one can get the expected result: `let e = { x = throw ""; get the expected result: `let e = { x = throw ""; }; in
}; in (builtins.tryEval (builtins.deepSeq e e)).success` will be (builtins.tryEval (builtins.deepSeq e e)).success` will be
`false`. `false`.
- `builtins.typeOf` *e* - `builtins.typeOf` *e*

View file

@ -57,23 +57,34 @@ the attributes of which specify the inputs of the build.
and it doesnt need the documentation at build time. Thus, the and it doesnt need the documentation at build time. Thus, the
library package could specify: library package could specify:
```nix
outputs = [ "lib" "headers" "doc" ]; outputs = [ "lib" "headers" "doc" ];
```
This will cause Nix to pass environment variables `lib`, `headers` This will cause Nix to pass environment variables `lib`, `headers`
and `doc` to the builder containing the intended store paths of each and `doc` to the builder containing the intended store paths of each
output. The builder would typically do something like output. The builder would typically do something like
./configure --libdir=$lib/lib --includedir=$headers/include --docdir=$doc/share/doc ```bash
./configure \
--libdir=$lib/lib \
--includedir=$headers/include \
--docdir=$doc/share/doc
```
for an Autoconf-style package. You can refer to each output of a for an Autoconf-style package. You can refer to each output of a
derivation by selecting it as an attribute, e.g. derivation by selecting it as an attribute, e.g.
```nix
buildInputs = [ pkg.lib pkg.headers ]; buildInputs = [ pkg.lib pkg.headers ];
```
The first element of `outputs` determines the *default output*. The first element of `outputs` determines the *default output*.
Thus, you could also write Thus, you could also write
```nix
buildInputs = [ pkg pkg.headers ]; buildInputs = [ pkg pkg.headers ];
```
since `pkg` is equivalent to `pkg.lib`. since `pkg` is equivalent to `pkg.lib`.

View file

@ -2,9 +2,10 @@
Here is a Nix expression for GNU Hello: Here is a Nix expression for GNU Hello:
{ stdenv, fetchurl, perl }: ① ```nix
{ stdenv, fetchurl, perl }: ①
stdenv.mkDerivation { ② stdenv.mkDerivation { ②
name = "hello-2.1.1"; ③ name = "hello-2.1.1"; ③
builder = ./builder.sh; ④ builder = ./builder.sh; ④
src = fetchurl { ⑤ src = fetchurl { ⑤
@ -12,7 +13,8 @@ Here is a Nix expression for GNU Hello:
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465"; sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
}; };
inherit perl; ⑥ inherit perl; ⑥
} }
```
This file is actually already in the Nix Packages collection in This file is actually already in the Nix Packages collection in
`pkgs/applications/misc/hello/ex-1/default.nix`. It is customary to `pkgs/applications/misc/hello/ex-1/default.nix`. It is customary to
@ -31,31 +33,27 @@ elements (referenced from the figure by number):
etc. `fetchurl` is a function that downloads files. `perl` is the etc. `fetchurl` is a function that downloads files. `perl` is the
Perl interpreter. Perl interpreter.
Nix functions generally have the form `{ x, y, ..., Nix functions generally have the form `{ x, y, ..., z }: e` where
z }: e` where `x`, `y`, etc. are the names of the expected `x`, `y`, etc. are the names of the expected arguments, and where
arguments, and where *e* is the body of the function. So here, the *e* is the body of the function. So here, the entire remainder of
entire remainder of the file is the body of the function; when given the file is the body of the function; when given the required
the required arguments, the body should describe how to build an arguments, the body should describe how to build an instance of
instance of the Hello package. the Hello package.
2. So we have to build a package. Building something from other stuff 2. So we have to build a package. Building something from other stuff
is called a *derivation* in Nix (as opposed to sources, which are is called a *derivation* in Nix (as opposed to sources, which are
built by humans instead of computers). We perform a derivation by built by humans instead of computers). We perform a derivation by
calling `stdenv.mkDerivation`. `mkDerivation` is a function provided calling `stdenv.mkDerivation`. `mkDerivation` is a function
by `stdenv` that builds a package from a set of *attributes*. A set provided by `stdenv` that builds a package from a set of
is just a list of key/value pairs where each key is a string and *attributes*. A set is just a list of key/value pairs where each
each value is an arbitrary Nix expression. They take the general key is a string and each value is an arbitrary Nix
form `{ expression. They take the general form `{ name1 = expr1; ...
name1 = nameN = exprN; }`.
expr1; ...
nameN =
exprN; }`.
3. The attribute `name` specifies the symbolic name and version of the 3. The attribute `name` specifies the symbolic name and version of
package. Nix doesn't really care about these things, but they are the package. Nix doesn't really care about these things, but they
used by for instance `nix-env are used by for instance `nix-env -q` to show a “human-readable”
-q` to show a “human-readable” name for packages. This attribute is name for packages. This attribute is required by `mkDerivation`.
required by `mkDerivation`.
4. The attribute `builder` specifies the builder. This attribute can 4. The attribute `builder` specifies the builder. This attribute can
sometimes be omitted, in which case `mkDerivation` will fill in a sometimes be omitted, in which case `mkDerivation` will fill in a
@ -84,7 +82,9 @@ elements (referenced from the figure by number):
are actually passed as environment variables to the builder, so are actually passed as environment variables to the builder, so
declaring an attribute declaring an attribute
```nix
perl = perl; perl = perl;
```
will do the trick: it binds an attribute `perl` to the function will do the trick: it binds an attribute `perl` to the function
argument which also happens to be called `perl`. However, it looks a argument which also happens to be called `perl`. However, it looks a

View file

@ -3,12 +3,14 @@
Recall that the [build script for GNU Hello](build-script.md) looked Recall that the [build script for GNU Hello](build-script.md) looked
something like this: something like this:
PATH=$perl/bin:$PATH ```bash
tar xvfz $src PATH=$perl/bin:$PATH
cd hello-* tar xvfz $src
./configure --prefix=$out cd hello-*
make ./configure --prefix=$out
make install make
make install
```
The builders for almost all Unix packages look like this — set up some The builders for almost all Unix packages look like this — set up some
environment variables, unpack the sources, configure, build, and environment variables, unpack the sources, configure, build, and
@ -16,11 +18,13 @@ install. For this reason the standard environment provides some Bash
functions that automate the build process. Here is what a builder using functions that automate the build process. Here is what a builder using
the generic build facilities looks like: the generic build facilities looks like:
buildInputs="$perl" ① ```bash
buildInputs="$perl" ①
source $stdenv/setup ② source $stdenv/setup ②
genericBuild ③ genericBuild ③
```
Here is what each line means: Here is what each line means:
@ -45,15 +49,17 @@ Here is what each line means:
Discerning readers will note that the `buildInputs` could just as well Discerning readers will note that the `buildInputs` could just as well
have been set in the Nix expression, like this: have been set in the Nix expression, like this:
``` ```nix
buildInputs = [ perl ]; buildInputs = [ perl ];
``` ```
The `perl` attribute can then be removed, and the builder becomes even The `perl` attribute can then be removed, and the builder becomes even
shorter: shorter:
source $stdenv/setup ```bash
genericBuild source $stdenv/setup
genericBuild
```
In fact, `mkDerivation` provides a default builder that looks exactly In fact, `mkDerivation` provides a default builder that looks exactly
like that, so it is actually possible to omit the builder for Hello like that, so it is actually possible to omit the builder for Hello

View file

@ -5,10 +5,12 @@
Recursive sets are just normal sets, but the attributes can refer to Recursive sets are just normal sets, but the attributes can refer to
each other. For example, each other. For example,
rec { ```nix
rec {
x = y; x = y;
y = 123; y = 123;
}.x }.x
```
evaluates to `123`. Note that without `rec` the binding `x = y;` would evaluates to `123`. Note that without `rec` the binding `x = y;` would
refer to the variable `y` in the surrounding scope, if one exists, and refer to the variable `y` in the surrounding scope, if one exists, and
@ -19,10 +21,12 @@ recursive set, they are.
Recursive sets of course introduce the danger of infinite recursion. For Recursive sets of course introduce the danger of infinite recursion. For
example, the expression example, the expression
rec { ```nix
rec {
x = y; x = y;
y = x; y = x;
}.x }.x
```
will crash with an `infinite recursion encountered` error message. will crash with an `infinite recursion encountered` error message.
@ -31,10 +35,12 @@ will crash with an `infinite recursion encountered` error message.
A let-expression allows you to define local variables for an expression. A let-expression allows you to define local variables for an expression.
For instance, For instance,
let ```nix
let
x = "foo"; x = "foo";
y = "bar"; y = "bar";
in x + y in x + y
```
evaluates to `"foobar"`. evaluates to `"foobar"`.
@ -45,38 +51,42 @@ copy variables from the surrounding lexical scope (e.g., when you want
to propagate attributes). This can be shortened using the `inherit` to propagate attributes). This can be shortened using the `inherit`
keyword. For instance, keyword. For instance,
let x = 123; in ```nix
{ inherit x; let x = 123; in
{ inherit x;
y = 456; y = 456;
} }
```
is equivalent to is equivalent to
let x = 123; in ```nix
{ x = x; let x = 123; in
{ x = x;
y = 456; y = 456;
} }
```
and both evaluate to `{ x = 123; y = 456; }`. (Note that this works and both evaluate to `{ x = 123; y = 456; }`. (Note that this works
because `x` is added to the lexical scope by the `let` construct.) It is because `x` is added to the lexical scope by the `let` construct.) It is
also possible to inherit attributes from another set. For instance, in also possible to inherit attributes from another set. For instance, in
this fragment from `all-packages.nix`, this fragment from `all-packages.nix`,
``` ```nix
graphviz = (import ../tools/graphics/graphviz) { graphviz = (import ../tools/graphics/graphviz) {
inherit fetchurl stdenv libpng libjpeg expat x11 yacc; inherit fetchurl stdenv libpng libjpeg expat x11 yacc;
inherit (xlibs) libXaw; inherit (xlibs) libXaw;
}; };
xlibs = { xlibs = {
libX11 = ...; libX11 = ...;
libXaw = ...; libXaw = ...;
... ...
} }
libpng = ...; libpng = ...;
libjpg = ...; libjpg = ...;
... ...
``` ```
the set used in the function call to the function defined in the set used in the function call to the function defined in
@ -86,17 +96,21 @@ surrounding scope (`fetchurl` ... `yacc`), but also inherits `libXaw`
Summarizing the fragment Summarizing the fragment
... ```nix
inherit x y z; ...
inherit (src-set) a b c; inherit x y z;
... inherit (src-set) a b c;
...
```
is equivalent to is equivalent to
... ```nix
x = x; y = y; z = z; ...
a = src-set.a; b = src-set.b; c = src-set.c; x = x; y = y; z = z;
... a = src-set.a; b = src-set.b; c = src-set.c;
...
```
when used while defining local variables in a let-expression or while when used while defining local variables in a let-expression or while
defining a set. defining a set.
@ -105,7 +119,9 @@ defining a set.
Functions have the following form: Functions have the following form:
pattern: body ```nix
pattern: body
```
The pattern specifies what the argument of the function must look like, The pattern specifies what the argument of the function must look like,
and binds variables in the body to (parts of) the argument. There are and binds variables in the body to (parts of) the argument. There are
@ -114,42 +130,51 @@ three kinds of patterns:
- If a pattern is a single identifier, then the function matches any - If a pattern is a single identifier, then the function matches any
argument. Example: argument. Example:
```nix
let negate = x: !x; let negate = x: !x;
concat = x: y: x + y; concat = x: y: x + y;
in if negate true then concat "foo" "bar" else "" in if negate true then concat "foo" "bar" else ""
```
Note that `concat` is a function that takes one argument and returns Note that `concat` is a function that takes one argument and returns
a function that takes another argument. This allows partial a function that takes another argument. This allows partial
parameterisation (i.e., only filling some of the arguments of a parameterisation (i.e., only filling some of the arguments of a
function); e.g., function); e.g.,
```nix
map (concat "foo") [ "bar" "bla" "abc" ] map (concat "foo") [ "bar" "bla" "abc" ]
```
evaluates to `[ "foobar" "foobla" evaluates to `[ "foobar" "foobla" "fooabc" ]`.
"fooabc" ]`.
- A *set pattern* of the form `{ name1, name2, …, nameN }` matches a - A *set pattern* of the form `{ name1, name2, …, nameN }` matches a
set containing the listed attributes, and binds the values of those set containing the listed attributes, and binds the values of those
attributes to variables in the function body. For example, the attributes to variables in the function body. For example, the
function function
```nix
{ x, y, z }: z + y + x { x, y, z }: z + y + x
```
can only be called with a set containing exactly the attributes `x`, can only be called with a set containing exactly the attributes `x`,
`y` and `z`. No other attributes are allowed. If you want to allow `y` and `z`. No other attributes are allowed. If you want to allow
additional arguments, you can use an ellipsis (`...`): additional arguments, you can use an ellipsis (`...`):
```nix
{ x, y, z, ... }: z + y + x { x, y, z, ... }: z + y + x
```
This works on any set that contains at least the three named This works on any set that contains at least the three named
attributes. attributes.
It is possible to provide *default values* for attributes, in which It is possible to provide *default values* for attributes, in
case they are allowed to be missing. A default value is specified by which case they are allowed to be missing. A default value is
writing `name ? specified by writing `name ? e`, where *e* is an arbitrary
e`, where *e* is an arbitrary expression. For example, expression. For example,
```nix
{ x, y ? "foo", z ? "bar" }: z + y + x { x, y ? "foo", z ? "bar" }: z + y + x
```
specifies a function that only requires an attribute named `x`, but specifies a function that only requires an attribute named `x`, but
optionally accepts `y` and `z`. optionally accepts `y` and `z`.
@ -157,13 +182,13 @@ three kinds of patterns:
- An `@`-pattern provides a means of referring to the whole value - An `@`-pattern provides a means of referring to the whole value
being matched: being matched:
``` ```nix
args@{ x, y, z, ... }: z + y + x + args.a args@{ x, y, z, ... }: z + y + x + args.a
``` ```
but can also be written as: but can also be written as:
``` ```nix
{ x, y, z, ... } @ args: z + y + x + args.a { x, y, z, ... } @ args: z + y + x + args.a
``` ```
@ -182,24 +207,30 @@ three kinds of patterns:
> >
> For instance > For instance
> >
> ```nix
> let > let
> function = args@{ a ? 23, ... }: args; > function = args@{ a ? 23, ... }: args;
> in > in
> function {} > function {}
> ````
> >
> will evaluate to an empty attribute set. > will evaluate to an empty attribute set.
Note that functions do not have names. If you want to give them a name, Note that functions do not have names. If you want to give them a name,
you can bind them to an attribute, e.g., you can bind them to an attribute, e.g.,
let concat = { x, y }: x + y; ```nix
in concat { x = "foo"; y = "bar"; } let concat = { x, y }: x + y;
in concat { x = "foo"; y = "bar"; }
```
## Conditionals ## Conditionals
Conditionals look like this: Conditionals look like this:
if e1 then e2 else e3 ```nix
if e1 then e2 else e3
```
where *e1* is an expression that should evaluate to a Boolean value where *e1* is an expression that should evaluate to a Boolean value
(`true` or `false`). (`true` or `false`).
@ -209,7 +240,9 @@ where *e1* is an expression that should evaluate to a Boolean value
Assertions are generally used to check that certain requirements on or Assertions are generally used to check that certain requirements on or
between features and dependencies hold. They look like this: between features and dependencies hold. They look like this:
assert e1; e2 ```nix
assert e1; e2
```
where *e1* is an expression that should evaluate to a Boolean value. If where *e1* is an expression that should evaluate to a Boolean value. If
it evaluates to `true`, *e2* is returned; otherwise expression it evaluates to `true`, *e2* is returned; otherwise expression
@ -218,29 +251,31 @@ evaluation is aborted and a backtrace is printed.
Here is a Nix expression for the Subversion package that shows how Here is a Nix expression for the Subversion package that shows how
assertions can be used:. assertions can be used:.
{ localServer ? false ```nix
, httpServer ? false { localServer ? false
, sslSupport ? false , httpServer ? false
, pythonBindings ? false , sslSupport ? false
, javaSwigBindings ? false , pythonBindings ? false
, javahlBindings ? false , javaSwigBindings ? false
, stdenv, fetchurl , javahlBindings ? false
, openssl ? null, httpd ? null, db4 ? null, expat, swig ? null, j2sdk ? null , stdenv, fetchurl
}: , openssl ? null, httpd ? null, db4 ? null, expat, swig ? null, j2sdk ? null
}:
assert localServer -> db4 != null; ① assert localServer -> db4 != null; ①
assert httpServer -> httpd != null && httpd.expat == expat; ② assert httpServer -> httpd != null && httpd.expat == expat; ②
assert sslSupport -> openssl != null && (httpServer -> httpd.openssl == openssl); ③ assert sslSupport -> openssl != null && (httpServer -> httpd.openssl == openssl); ③
assert pythonBindings -> swig != null && swig.pythonSupport; assert pythonBindings -> swig != null && swig.pythonSupport;
assert javaSwigBindings -> swig != null && swig.javaSupport; assert javaSwigBindings -> swig != null && swig.javaSupport;
assert javahlBindings -> j2sdk != null; assert javahlBindings -> j2sdk != null;
stdenv.mkDerivation { stdenv.mkDerivation {
name = "subversion-1.1.1"; name = "subversion-1.1.1";
... ...
openssl = if sslSupport then openssl else null; ④ openssl = if sslSupport then openssl else null; ④
... ...
} }
```
The points of interest are: The points of interest are:
@ -273,19 +308,25 @@ The points of interest are:
A *with-expression*, A *with-expression*,
with e1; e2 ```nix
with e1; e2
```
introduces the set *e1* into the lexical scope of the expression *e2*. introduces the set *e1* into the lexical scope of the expression *e2*.
For instance, For instance,
let as = { x = "foo"; y = "bar"; }; ```nix
in with as; x + y let as = { x = "foo"; y = "bar"; };
in with as; x + y
```
evaluates to `"foobar"` since the `with` adds the `x` and `y` attributes evaluates to `"foobar"` since the `with` adds the `x` and `y` attributes
of `as` to the lexical scope in the expression `x + y`. The most common of `as` to the lexical scope in the expression `x + y`. The most common
use of `with` is in conjunction with the `import` function. E.g., use of `with` is in conjunction with the `import` function. E.g.,
with (import ./definitions.nix); ... ```nix
with (import ./definitions.nix); ...
```
makes all attributes defined in the file `definitions.nix` available as makes all attributes defined in the file `definitions.nix` available as
if they were defined locally in a `let`-expression. if they were defined locally in a `let`-expression.
@ -293,14 +334,17 @@ if they were defined locally in a `let`-expression.
The bindings introduced by `with` do not shadow bindings introduced by The bindings introduced by `with` do not shadow bindings introduced by
other means, e.g. other means, e.g.
let a = 3; in with { a = 1; }; let a = 4; in with { a = 2; }; ... ```nix
let a = 3; in with { a = 1; }; let a = 4; in with { a = 2; }; ...
```
establishes the same scope as establishes the same scope as
let a = 1; in let a = 2; in let a = 3; in let a = 4; in ... ```nix
let a = 1; in let a = 2; in let a = 3; in let a = 4; in ...
```
## Comments ## Comments
Comments can be single-line, started with a `#` character, or Comments can be single-line, started with a `#` character, or
inline/multi-line, enclosed within `/* inline/multi-line, enclosed within `/* ... */`.
... */`.

View file

@ -19,17 +19,22 @@ Nix has the following basic data types:
into a string (meaning that it must be a string, a path, or a into a string (meaning that it must be a string, a path, or a
derivation). For instance, rather than writing derivation). For instance, rather than writing
```nix
"--with-freetype2-library=" + freetype + "/lib" "--with-freetype2-library=" + freetype + "/lib"
```
(where `freetype` is a derivation), you can instead write the more (where `freetype` is a derivation), you can instead write the more
natural natural
```nix
"--with-freetype2-library=${freetype}/lib" "--with-freetype2-library=${freetype}/lib"
```
The latter is automatically translated to the former. A more The latter is automatically translated to the former. A more
complicated example (from the Nix expression for complicated example (from the Nix expression for
[Qt](http://www.trolltech.com/products/qt)): [Qt](http://www.trolltech.com/products/qt)):
```nix
configureFlags = " configureFlags = "
-system-zlib -system-libpng -system-libjpeg -system-zlib -system-libpng -system-libjpeg
${if openglSupport then "-dlopen-opengl ${if openglSupport then "-dlopen-opengl
@ -37,6 +42,7 @@ Nix has the following basic data types:
-L${libXmu}/lib -I${libXmu}/include" else ""} -L${libXmu}/lib -I${libXmu}/include" else ""}
${if threadSupport then "-thread" else "-no-thread"} ${if threadSupport then "-thread" else "-no-thread"}
"; ";
```
Note that Nix expressions and strings can be arbitrarily nested; in Note that Nix expressions and strings can be arbitrarily nested; in
this case the outer string contains various antiquotations that this case the outer string contains various antiquotations that
@ -46,11 +52,13 @@ Nix has the following basic data types:
The second way to write string literals is as an *indented string*, The second way to write string literals is as an *indented string*,
which is enclosed between pairs of *double single-quotes*, like so: which is enclosed between pairs of *double single-quotes*, like so:
```nix
'' ''
This is the first line. This is the first line.
This is the second line. This is the second line.
This is the third line. This is the third line.
'' ''
```
This kind of string literal intelligently strips indentation from This kind of string literal intelligently strips indentation from
the start of each line. To be precise, it strips from each line a the start of each line. To be precise, it strips from each line a
@ -60,7 +68,9 @@ Nix has the following basic data types:
line is indented four spaces. Thus, two spaces are stripped from line is indented four spaces. Thus, two spaces are stripped from
each line, so the resulting string is each line, so the resulting string is
```nix
"This is the first line.\nThis is the second line.\n This is the third line.\n" "This is the first line.\nThis is the second line.\n This is the third line.\n"
```
Note that the whitespace and newline following the opening `''` is Note that the whitespace and newline following the opening `''` is
ignored if there is no non-whitespace text on the initial line. ignored if there is no non-whitespace text on the initial line.
@ -82,6 +92,7 @@ Nix has the following basic data types:
configuration files because `''` is much less common than `"`. configuration files because `''` is much less common than `"`.
Example: Example:
```nix
stdenv.mkDerivation { stdenv.mkDerivation {
... ...
postInstall = postInstall =
@ -93,6 +104,7 @@ Nix has the following basic data types:
''; '';
... ...
} }
```
Finally, as a convenience, *URIs* as defined in appendix B of Finally, as a convenience, *URIs* as defined in appendix B of
[RFC 2396](http://www.ietf.org/rfc/rfc2396.txt) can be written *as [RFC 2396](http://www.ietf.org/rfc/rfc2396.txt) can be written *as
@ -136,13 +148,17 @@ Nix has the following basic data types:
Lists are formed by enclosing a whitespace-separated list of values Lists are formed by enclosing a whitespace-separated list of values
between square brackets. For example, between square brackets. For example,
[ 123 ./foo.nix "abc" (f { x = y; }) ] ```nix
[ 123 ./foo.nix "abc" (f { x = y; }) ]
```
defines a list of four elements, the last being the result of a call to defines a list of four elements, the last being the result of a call to
the function `f`. Note that function calls have to be enclosed in the function `f`. Note that function calls have to be enclosed in
parentheses. If they had been omitted, e.g., parentheses. If they had been omitted, e.g.,
[ 123 ./foo.nix "abc" f { x = y; } ] ```nix
[ 123 ./foo.nix "abc" f { x = y; } ]
```
the result would be a list of five elements, the fourth one being a the result would be a list of five elements, the fourth one being a
function and the fifth being a set. function and the fifth being a set.
@ -159,10 +175,12 @@ Sets are just a list of name/value pairs (called *attributes*) enclosed
in curly brackets, where each value is an arbitrary expression in curly brackets, where each value is an arbitrary expression
terminated by a semicolon. For example: terminated by a semicolon. For example:
{ x = 123; ```nix
{ x = 123;
text = "Hello"; text = "Hello";
y = f { bla = 456; }; y = f { bla = 456; };
} }
```
This defines a set with attributes named `x`, `text`, `y`. The order of This defines a set with attributes named `x`, `text`, `y`. The order of
the attributes is irrelevant. An attribute name may only occur once. the attributes is irrelevant. An attribute name may only occur once.
@ -170,24 +188,32 @@ the attributes is irrelevant. An attribute name may only occur once.
Attributes can be selected from a set using the `.` operator. For Attributes can be selected from a set using the `.` operator. For
instance, instance,
{ a = "Foo"; b = "Bar"; }.a ```nix
{ a = "Foo"; b = "Bar"; }.a
```
evaluates to `"Foo"`. It is possible to provide a default value in an evaluates to `"Foo"`. It is possible to provide a default value in an
attribute selection using the `or` keyword. For example, attribute selection using the `or` keyword. For example,
{ a = "Foo"; b = "Bar"; }.c or "Xyzzy" ```nix
{ a = "Foo"; b = "Bar"; }.c or "Xyzzy"
```
will evaluate to `"Xyzzy"` because there is no `c` attribute in the set. will evaluate to `"Xyzzy"` because there is no `c` attribute in the set.
You can use arbitrary double-quoted strings as attribute names: You can use arbitrary double-quoted strings as attribute names:
{ "foo ${bar}" = 123; "nix-1.0" = 456; }."foo ${bar}" ```nix
{ "foo ${bar}" = 123; "nix-1.0" = 456; }."foo ${bar}"
```
This will evaluate to `123` (Assuming `bar` is antiquotable). In the This will evaluate to `123` (Assuming `bar` is antiquotable). In the
case where an attribute name is just a single antiquotation, the quotes case where an attribute name is just a single antiquotation, the quotes
can be dropped: can be dropped:
{ foo = 123; }.${bar} or 456 ```nix
{ foo = 123; }.${bar} or 456
```
This will evaluate to `123` if `bar` evaluates to `"foo"` when coerced This will evaluate to `123` if `bar` evaluates to `"foo"` when coerced
to a string and `456` otherwise (again assuming `bar` is antiquotable). to a string and `456` otherwise (again assuming `bar` is antiquotable).
@ -196,7 +222,9 @@ In the special case where an attribute name inside of a set declaration
evaluates to `null` (which is normally an error, as `null` is not evaluates to `null` (which is normally an error, as `null` is not
antiquotable), that attribute is simply not added to the set: antiquotable), that attribute is simply not added to the set:
{ ${if foo then "bar" else null} = true; } ```nix
{ ${if foo then "bar" else null} = true; }
```
This will evaluate to `{}` if `foo` evaluates to `false`. This will evaluate to `{}` if `foo` evaluates to `false`.
@ -205,9 +233,11 @@ itself a function or a set with a `__functor` attribute whose value is
callable) can be applied as if it were a function, with the set itself callable) can be applied as if it were a function, with the set itself
passed in first , e.g., passed in first , e.g.,
let add = { __functor = self: x: x + self.x; }; ```nix
let add = { __functor = self: x: x + self.x; };
inc = add // { x = 1; }; inc = add // { x = 1; };
in inc 1 in inc 1
```
evaluates to `2`. This can be used to attach metadata to a function evaluates to `2`. This can be used to attach metadata to a function
without the caller needing to treat it specially, or to implement a form without the caller needing to treat it specially, or to implement a form

View file

@ -6,18 +6,20 @@ yet. The best way to test the package is by using the command
`nix-build`, which builds a Nix expression and creates a symlink named `nix-build`, which builds a Nix expression and creates a symlink named
`result` in the current directory: `result` in the current directory:
$ nix-build -A hello ```console
building path `/nix/store/632d2b22514d...-hello-2.1.1' $ nix-build -A hello
hello-2.1.1/ building path `/nix/store/632d2b22514d...-hello-2.1.1'
hello-2.1.1/intl/ hello-2.1.1/
hello-2.1.1/intl/ChangeLog hello-2.1.1/intl/
... hello-2.1.1/intl/ChangeLog
...
$ ls -l result $ ls -l result
lrwxrwxrwx ... 2006-09-29 10:43 result -> /nix/store/632d2b22514d...-hello-2.1.1 lrwxrwxrwx ... 2006-09-29 10:43 result -> /nix/store/632d2b22514d...-hello-2.1.1
$ ./result/bin/hello $ ./result/bin/hello
Hello, world! Hello, world!
```
The `-A` option selects the `hello` attribute. This is faster than The `-A` option selects the `hello` attribute. This is faster than
using the symbolic package name specified by the `name` attribute using the symbolic package name specified by the `name` attribute
@ -50,8 +52,10 @@ simultaneously, and they try to build the same derivation, the first Nix
instance that gets there will perform the build, while the others block instance that gets there will perform the build, while the others block
(or perform other derivations if available) until the build finishes: (or perform other derivations if available) until the build finishes:
$ nix-build -A hello ```console
waiting for lock on `/nix/store/0h5b7hp8d4hqfrw8igvx97x1xawrjnac-hello-2.1.1x' $ nix-build -A hello
waiting for lock on `/nix/store/0h5b7hp8d4hqfrw8igvx97x1xawrjnac-hello-2.1.1x'
```
So it is always safe to run multiple instances of Nix in parallel (which So it is always safe to run multiple instances of Nix in parallel (which
isnt the case with, say, `make`). isnt the case with, say, `make`).

View file

@ -3,45 +3,63 @@
This section provides some notes on how to hack on Nix. To get the This section provides some notes on how to hack on Nix. To get the
latest version of Nix from GitHub: latest version of Nix from GitHub:
$ git clone https://github.com/NixOS/nix.git ```console
$ cd nix $ git clone https://github.com/NixOS/nix.git
$ cd nix
```
To build Nix for the current operating system/architecture use To build Nix for the current operating system/architecture use
$ nix-build ```console
$ nix-build
```
or if you have a flakes-enabled nix: or if you have a flakes-enabled nix:
$ nix build ```console
$ nix build
```
This will build `defaultPackage` attribute defined in the `flake.nix` This will build `defaultPackage` attribute defined in the `flake.nix`
file. To build for other platforms add one of the following suffixes to file. To build for other platforms add one of the following suffixes to
it: aarch64-linux, i686-linux, x86\_64-darwin, x86\_64-linux. i.e. it: aarch64-linux, i686-linux, x86\_64-darwin, x86\_64-linux. i.e.
$ nix-build -A defaultPackage.x86_64-linux ```console
$ nix-build -A defaultPackage.x86_64-linux
```
To build all dependencies and start a shell in which all environment To build all dependencies and start a shell in which all environment
variables are set up so that those dependencies can be found: variables are set up so that those dependencies can be found:
$ nix-shell ```console
$ nix-shell
```
To build Nix itself in this shell: To build Nix itself in this shell:
[nix-shell]$ ./bootstrap.sh ```console
[nix-shell]$ ./configure $configureFlags [nix-shell]$ ./bootstrap.sh
[nix-shell]$ make -j $NIX_BUILD_CORES [nix-shell]$ ./configure $configureFlags
[nix-shell]$ make -j $NIX_BUILD_CORES
```
To install it in `$(pwd)/inst` and test it: To install it in `$(pwd)/inst` and test it:
[nix-shell]$ make install ```console
[nix-shell]$ make installcheck [nix-shell]$ make install
[nix-shell]$ ./inst/bin/nix --version [nix-shell]$ make installcheck
nix (Nix) 2.4 [nix-shell]$ ./inst/bin/nix --version
nix (Nix) 2.4
```
If you have a flakes-enabled nix you can replace: If you have a flakes-enabled Nix you can replace:
$ nix-shell ```console
$ nix-shell
```
by: by:
$ nix develop ```console
$ nix develop
```

View file

@ -3,16 +3,20 @@
After unpacking or checking out the Nix sources, issue the following After unpacking or checking out the Nix sources, issue the following
commands: commands:
$ ./configure options... ```console
$ make $ ./configure options...
$ make install $ make
$ make install
```
Nix requires GNU Make so you may need to invoke `gmake` instead. Nix requires GNU Make so you may need to invoke `gmake` instead.
When building from the Git repository, these should be preceded by the When building from the Git repository, these should be preceded by the
command: command:
$ ./bootstrap.sh ```console
$ ./bootstrap.sh
```
The installation path can be specified by passing the `--prefix=prefix` The installation path can be specified by passing the `--prefix=prefix`
to `configure`. The default installation directory is `/usr/local`. You to `configure`. The default installation directory is `/usr/local`. You

View file

@ -10,7 +10,9 @@ environment variables is to include the file
`prefix/etc/profile.d/nix.sh` in your `~/.profile` (or similar), like `prefix/etc/profile.d/nix.sh` in your `~/.profile` (or similar), like
this: this:
source prefix/etc/profile.d/nix.sh ```bash
source prefix/etc/profile.d/nix.sh
```
# `NIX_SSL_CERT_FILE` # `NIX_SSL_CERT_FILE`
@ -23,13 +25,17 @@ and use its own certificate bundle.
Set the environment variable and install Nix Set the environment variable and install Nix
$ export NIX_SSL_CERT_FILE=/etc/ssl/my-certificate-bundle.crt ```console
$ sh <(curl -L https://nixos.org/nix/install) $ export NIX_SSL_CERT_FILE=/etc/ssl/my-certificate-bundle.crt
$ sh <(curl -L https://nixos.org/nix/install)
```
In the shell profile and rc files (for example, `/etc/bashrc`, In the shell profile and rc files (for example, `/etc/bashrc`,
`/etc/zshrc`), add the following line: `/etc/zshrc`), add the following line:
export NIX_SSL_CERT_FILE=/etc/ssl/my-certificate-bundle.crt ```bash
export NIX_SSL_CERT_FILE=/etc/ssl/my-certificate-bundle.crt
```
> **Note** > **Note**
> >
@ -41,8 +47,10 @@ In the shell profile and rc files (for example, `/etc/bashrc`,
On macOS you must specify the environment variable for the Nix daemon On macOS you must specify the environment variable for the Nix daemon
service, then restart it: service, then restart it:
$ sudo launchctl setenv NIX_SSL_CERT_FILE /etc/ssl/my-certificate-bundle.crt ```console
$ sudo launchctl kickstart -k system/org.nixos.nix-daemon $ sudo launchctl setenv NIX_SSL_CERT_FILE /etc/ssl/my-certificate-bundle.crt
$ sudo launchctl kickstart -k system/org.nixos.nix-daemon
```
## Proxy Environment Variables ## Proxy Environment Variables

View file

@ -3,8 +3,8 @@
If you are using Linux or macOS versions up to 10.14 (Mojave), the If you are using Linux or macOS versions up to 10.14 (Mojave), the
easiest way to install Nix is to run the following command: easiest way to install Nix is to run the following command:
``` ```console
$ sh <(curl -L https://nixos.org/nix/install) $ sh <(curl -L https://nixos.org/nix/install)
``` ```
If you're using macOS 10.15 (Catalina) or newer, consult [the macOS If you're using macOS 10.15 (Catalina) or newer, consult [the macOS
@ -18,8 +18,8 @@ installation is highly recommended.
To explicitly select a single-user installation on your system: To explicitly select a single-user installation on your system:
``` ```console
sh <(curl -L https://nixos.org/nix/install) --no-daemon $ sh <(curl -L https://nixos.org/nix/install) --no-daemon
``` ```
This will perform a single-user installation of Nix, meaning that `/nix` This will perform a single-user installation of Nix, meaning that `/nix`
@ -28,8 +28,10 @@ account, *not* as root. The script will invoke `sudo` to create `/nix`
if it doesnt already exist. If you dont have `sudo`, you should if it doesnt already exist. If you dont have `sudo`, you should
manually create `/nix` first as root, e.g.: manually create `/nix` first as root, e.g.:
$ mkdir /nix ```console
$ chown alice /nix $ mkdir /nix
$ chown alice /nix
```
The install script will modify the first writable file from amongst The install script will modify the first writable file from amongst
`.bash_profile`, `.bash_login` and `.profile` to source `.bash_profile`, `.bash_login` and `.profile` to source
@ -39,7 +41,9 @@ the install script to disable this behaviour.
You can uninstall Nix simply by running: You can uninstall Nix simply by running:
$ rm -rf /nix ```console
$ rm -rf /nix
```
# Multi User Installation # Multi User Installation
@ -53,7 +57,9 @@ service for the Nix daemon.
You can instruct the installer to perform a multi-user installation on You can instruct the installer to perform a multi-user installation on
your system: your system:
sh <(curl -L https://nixos.org/nix/install) --daemon ```console
$ sh <(curl -L https://nixos.org/nix/install) --daemon
```
The multi-user installation of Nix will create build users between the The multi-user installation of Nix will create build users between the
user IDs 30001 and 30032, and a group with the group ID 30000. You user IDs 30001 and 30032, and a group with the group ID 30000. You
@ -72,18 +78,20 @@ extension. The installer will also create `/etc/profile.d/nix.sh`.
You can uninstall Nix with the following commands: You can uninstall Nix with the following commands:
sudo rm -rf /etc/profile/nix.sh /etc/nix /nix ~root/.nix-profile ~root/.nix-defexpr ~root/.nix-channels ~/.nix-profile ~/.nix-defexpr ~/.nix-channels ```console
sudo rm -rf /etc/profile/nix.sh /etc/nix /nix ~root/.nix-profile ~root/.nix-defexpr ~root/.nix-channels ~/.nix-profile ~/.nix-defexpr ~/.nix-channels
# If you are on Linux with systemd, you will need to run: # If you are on Linux with systemd, you will need to run:
sudo systemctl stop nix-daemon.socket sudo systemctl stop nix-daemon.socket
sudo systemctl stop nix-daemon.service sudo systemctl stop nix-daemon.service
sudo systemctl disable nix-daemon.socket sudo systemctl disable nix-daemon.socket
sudo systemctl disable nix-daemon.service sudo systemctl disable nix-daemon.service
sudo systemctl daemon-reload sudo systemctl daemon-reload
# If you are on macOS, you will need to run: # If you are on macOS, you will need to run:
sudo launchctl unload /Library/LaunchDaemons/org.nixos.nix-daemon.plist sudo launchctl unload /Library/LaunchDaemons/org.nixos.nix-daemon.plist
sudo rm /Library/LaunchDaemons/org.nixos.nix-daemon.plist sudo rm /Library/LaunchDaemons/org.nixos.nix-daemon.plist
```
There may also be references to Nix in `/etc/profile`, `/etc/bashrc`, There may also be references to Nix in `/etc/profile`, `/etc/bashrc`,
and `/etc/zshrc` which you may remove. and `/etc/zshrc` which you may remove.
@ -110,7 +118,9 @@ chip](https://www.apple.com/euro/mac/shared/docs/Apple_T2_Security_Chip_Overview
your drive will still be encrypted at rest (in which case "unencrypted" your drive will still be encrypted at rest (in which case "unencrypted"
is a bit of a misnomer). To use this approach, just install Nix with: is a bit of a misnomer). To use this approach, just install Nix with:
$ sh <(curl -L https://nixos.org/nix/install) --darwin-use-unencrypted-nix-store-volume ```console
$ sh <(curl -L https://nixos.org/nix/install) --darwin-use-unencrypted-nix-store-volume
```
If you don't like the sound of this, you'll want to weigh the other If you don't like the sound of this, you'll want to weigh the other
approaches and tradeoffs detailed in this section. approaches and tradeoffs detailed in this section.
@ -184,7 +194,9 @@ there are a few things to weigh:
If you are comfortable navigating these tradeoffs, you can encrypt the If you are comfortable navigating these tradeoffs, you can encrypt the
volume with something along the lines of: volume with something along the lines of:
alice$ diskutil apfs enableFileVault /nix -user disk ```console
alice$ diskutil apfs enableFileVault /nix -user disk
```
## Symlink the Nix store to a custom location ## Symlink the Nix store to a custom location
@ -221,11 +233,15 @@ as a helpful reference if you run into trouble.
`apfs.util` to trigger creation (not deletion) of new entries `apfs.util` to trigger creation (not deletion) of new entries
without a reboot: without a reboot:
```console
alice$ /System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util -B alice$ /System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util -B
```
3. Create the new APFS volume with diskutil: 3. Create the new APFS volume with diskutil:
```console
alice$ sudo diskutil apfs addVolume diskX APFS 'Nix Store' -mountpoint /nix alice$ sudo diskutil apfs addVolume diskX APFS 'Nix Store' -mountpoint /nix
```
4. Using `vifs`, add the new mount to `/etc/fstab`. If it doesn't 4. Using `vifs`, add the new mount to `/etc/fstab`. If it doesn't
already have other entries, it should look something like: already have other entries, it should look something like:
@ -248,8 +264,8 @@ since 1.11.16, at `https://releases.nixos.org/nix/nix-version/install`.
These install scripts can be used the same as the main NixOS.org These install scripts can be used the same as the main NixOS.org
installation script: installation script:
``` ```console
sh <(curl -L https://nixos.org/nix/install) $ sh <(curl -L https://nixos.org/nix/install)
``` ```
In the same directory of the install script are sha256 sums, and gpg In the same directory of the install script are sha256 sums, and gpg
@ -263,10 +279,12 @@ dependencies. (This is what the install script at
it somewhere (e.g. in `/tmp`), and then run the script named `install` it somewhere (e.g. in `/tmp`), and then run the script named `install`
inside the binary tarball: inside the binary tarball:
alice$ cd /tmp ```console
alice$ tar xfj nix-1.8-x86_64-darwin.tar.bz2 alice$ cd /tmp
alice$ cd nix-1.8-x86_64-darwin alice$ tar xfj nix-1.8-x86_64-darwin.tar.bz2
alice$ ./install alice$ cd nix-1.8-x86_64-darwin
alice$ ./install
```
If you need to edit the multi-user installation script to use different If you need to edit the multi-user installation script to use different
group ID or a different user ID range, modify the variables set in the group ID or a different user ID range, modify the variables set in the

View file

@ -28,10 +28,12 @@ group should have no other members. The build users should not be
members of any other group. On Linux, you can create the group and users members of any other group. On Linux, you can create the group and users
as follows: as follows:
$ groupadd -r nixbld ```console
$ for n in $(seq 1 10); do useradd -c "Nix build user $n" \ $ groupadd -r nixbld
$ for n in $(seq 1 10); do useradd -c "Nix build user $n" \
-d /var/empty -g nixbld -G nixbld -M -N -r -s "$(which nologin)" \ -d /var/empty -g nixbld -G nixbld -M -N -r -s "$(which nologin)" \
nixbld$n; done nixbld$n; done
```
This creates 10 build users. There can never be more concurrent builds This creates 10 build users. There can never be more concurrent builds
than the number of build users, so you may want to increase this if you than the number of build users, so you may want to increase this if you
@ -42,7 +44,9 @@ expect to do many builds at the same time.
The [Nix daemon](../command-ref/nix-daemon.md) should be started as The [Nix daemon](../command-ref/nix-daemon.md) should be started as
follows (as `root`): follows (as `root`):
$ nix-daemon ```console
$ nix-daemon
```
Youll want to put that line somewhere in your systems boot scripts. Youll want to put that line somewhere in your systems boot scripts.
@ -50,7 +54,9 @@ To let unprivileged users use the daemon, they should set the
[`NIX_REMOTE` environment variable](../command-ref/env-common.md) to [`NIX_REMOTE` environment variable](../command-ref/env-common.md) to
`daemon`. So you should put a line like `daemon`. So you should put a line like
export NIX_REMOTE=daemon ```console
export NIX_REMOTE=daemon
```
into the users login scripts. into the users login scripts.
@ -61,8 +67,10 @@ permissions on the directory `/nix/var/nix/daemon-socket`. For instance,
if you want to restrict the use of Nix to the members of a group called if you want to restrict the use of Nix to the members of a group called
`nix-users`, do `nix-users`, do
$ chgrp nix-users /nix/var/nix/daemon-socket ```console
$ chmod ug=rwx,o= /nix/var/nix/daemon-socket $ chgrp nix-users /nix/var/nix/daemon-socket
$ chmod ug=rwx,o= /nix/var/nix/daemon-socket
```
This way, users who are not in the `nix-users` group cannot connect to This way, users who are not in the `nix-users` group cannot connect to
the Unix domain socket `/nix/var/nix/daemon-socket/socket`, so they the Unix domain socket `/nix/var/nix/daemon-socket/socket`, so they

View file

@ -10,7 +10,9 @@ Alternatively, the most recent sources of Nix can be obtained from its
following command will check out the latest revision into a directory following command will check out the latest revision into a directory
called `nix`: called `nix`:
$ git clone https://github.com/NixOS/nix ```console
$ git clone https://github.com/NixOS/nix
```
Likewise, specific releases can be obtained from the Likewise, specific releases can be obtained from the
[tags](https://github.com/NixOS/nix/tags) of the repository. [tags](https://github.com/NixOS/nix/tags) of the repository.

View file

@ -75,21 +75,27 @@ And since packages arent overwritten, the old versions are still
there after an upgrade. This means that you can _roll back_ to the there after an upgrade. This means that you can _roll back_ to the
old version: old version:
$ nix-env --upgrade some-packages ```console
$ nix-env --rollback $ nix-env --upgrade some-packages
$ nix-env --rollback
```
## Garbage collection ## Garbage collection
When you uninstall a package like this… When you uninstall a package like this…
$ nix-env --uninstall firefox ```console
$ nix-env --uninstall firefox
```
the package isnt deleted from the system right away (after all, you the package isnt deleted from the system right away (after all, you
might want to do a rollback, or it might be in the profiles of other might want to do a rollback, or it might be in the profiles of other
users). Instead, unused packages can be deleted safely by running the users). Instead, unused packages can be deleted safely by running the
_garbage collector_: _garbage collector_:
$ nix-collect-garbage ```console
$ nix-collect-garbage
```
This deletes all packages that arent in use by any user profile or by This deletes all packages that arent in use by any user profile or by
a currently running program. a currently running program.
@ -115,7 +121,9 @@ each other in the Nix store.
Nix expressions generally describe how to build a package from Nix expressions generally describe how to build a package from
source, so an installation action like source, so an installation action like
$ nix-env --install firefox ```console
$ nix-env --install firefox
```
_could_ cause quite a bit of build activity, as not only Firefox but _could_ cause quite a bit of build activity, as not only Firefox but
also all its dependencies (all the way up to the C library and the also all its dependencies (all the way up to the C library and the
@ -149,16 +157,20 @@ For example, the following command gets all dependencies of the
Pan newsreader, as described by [its Pan newsreader, as described by [its
Nix expression](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/networking/newsreaders/pan/default.nix): Nix expression](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/networking/newsreaders/pan/default.nix):
$ nix-shell '<nixpkgs>' -A pan ```console
$ nix-shell '<nixpkgs>' -A pan
```
Youre then dropped into a shell where you can edit, build and test Youre then dropped into a shell where you can edit, build and test
the package: the package:
[nix-shell]$ tar xf $src ```console
[nix-shell]$ cd pan-* [nix-shell]$ tar xf $src
[nix-shell]$ ./configure [nix-shell]$ cd pan-*
[nix-shell]$ make [nix-shell]$ ./configure
[nix-shell]$ ./pan/gui/pan [nix-shell]$ make
[nix-shell]$ ./pan/gui/pan
```
## Portability ## Portability

View file

@ -31,8 +31,10 @@ automatically added to your list of “subscribed” channels when you
install Nix. If this is not the case for some reason, you can add it install Nix. If this is not the case for some reason, you can add it
as follows: as follows:
$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable ```console
$ nix-channel --update $ nix-channel --add https://nixos.org/channels/nixpkgs-unstable
$ nix-channel --update
```
> **Note** > **Note**
> >
@ -44,14 +46,16 @@ as follows:
You can view the set of available packages in Nixpkgs: You can view the set of available packages in Nixpkgs:
$ nix-env -qa ```console
aterm-2.2 $ nix-env -qa
bash-3.0 aterm-2.2
binutils-2.15 bash-3.0
bison-1.875d binutils-2.15
blackdown-1.4.2 bison-1.875d
bzip2-1.0.2 blackdown-1.4.2
bzip2-1.0.2
```
The flag `-q` specifies a query operation, and `-a` means that you want The flag `-q` specifies a query operation, and `-a` means that you want
to show the “available” (i.e., installable) packages, as opposed to the to show the “available” (i.e., installable) packages, as opposed to the
@ -59,31 +63,39 @@ installed packages. If you downloaded Nixpkgs yourself, or if you
checked it out from GitHub, then you need to pass the path to your checked it out from GitHub, then you need to pass the path to your
Nixpkgs tree using the `-f` flag: Nixpkgs tree using the `-f` flag:
$ nix-env -qaf /path/to/nixpkgs ```console
$ nix-env -qaf /path/to/nixpkgs
```
where */path/to/nixpkgs* is where youve unpacked or checked out where */path/to/nixpkgs* is where youve unpacked or checked out
Nixpkgs. Nixpkgs.
You can select specific packages by name: You can select specific packages by name:
$ nix-env -qa firefox ```console
firefox-34.0.5 $ nix-env -qa firefox
firefox-with-plugins-34.0.5 firefox-34.0.5
firefox-with-plugins-34.0.5
```
and using regular expressions: and using regular expressions:
$ nix-env -qa 'firefox.*' ```console
$ nix-env -qa 'firefox.*'
```
It is also possible to see the *status* of available packages, i.e., It is also possible to see the *status* of available packages, i.e.,
whether they are installed into the user environment and/or present in whether they are installed into the user environment and/or present in
the system: the system:
$ nix-env -qas ```console
$ nix-env -qas
-PS bash-3.0
--S binutils-2.15 -PS bash-3.0
IPS bison-1.875d --S binutils-2.15
IPS bison-1.875d
```
The first character (`I`) indicates whether the package is installed in The first character (`I`) indicates whether the package is installed in
your current user environment. The second (`P`) indicates whether it is your current user environment. The second (`P`) indicates whether it is
@ -96,7 +108,9 @@ Nix knows that it can fetch a pre-built package from somewhere
You can install a package using `nix-env -i`. For instance, You can install a package using `nix-env -i`. For instance,
$ nix-env -i subversion ```console
$ nix-env -i subversion
```
will install the package called `subversion` (which is, of course, the will install the package called `subversion` (which is, of course, the
[Subversion version management system](http://subversion.tigris.org/)). [Subversion version management system](http://subversion.tigris.org/)).
@ -121,12 +135,16 @@ will install the package called `subversion` (which is, of course, the
Naturally, packages can also be uninstalled: Naturally, packages can also be uninstalled:
$ nix-env -e subversion ```console
$ nix-env -e subversion
```
Upgrading to a new version is just as easy. If you have a new release of Upgrading to a new version is just as easy. If you have a new release of
Nix Packages, you can do: Nix Packages, you can do:
$ nix-env -u subversion ```console
$ nix-env -u subversion
```
This will *only* upgrade Subversion if there is a “newer” version in the This will *only* upgrade Subversion if there is a “newer” version in the
new set of Nix expressions, as defined by some pretty arbitrary rules new set of Nix expressions, as defined by some pretty arbitrary rules
@ -137,14 +155,18 @@ whatever version is in the Nix expressions, use `-i` instead of `-u`;
You can also upgrade all packages for which there are newer versions: You can also upgrade all packages for which there are newer versions:
$ nix-env -u ```console
$ nix-env -u
```
Sometimes its useful to be able to ask what `nix-env` would do, without Sometimes its useful to be able to ask what `nix-env` would do, without
actually doing it. For instance, to find out what packages would be actually doing it. For instance, to find out what packages would be
upgraded by `nix-env -u`, you can do upgraded by `nix-env -u`, you can do
$ nix-env -u --dry-run ```console
(dry run; not doing anything) $ nix-env -u --dry-run
upgrading `libxslt-1.1.0' to `libxslt-1.1.10' (dry run; not doing anything)
upgrading `graphviz-1.10' to `graphviz-1.12' upgrading `libxslt-1.1.0' to `libxslt-1.1.10'
upgrading `coreutils-5.0' to `coreutils-5.2.1' upgrading `graphviz-1.10' to `graphviz-1.12'
upgrading `coreutils-5.0' to `coreutils-5.2.1'
```

View file

@ -8,16 +8,22 @@ usually uses to fetch pre-built binaries from <https://cache.nixos.org>.
The daemon that handles binary cache requests via HTTP, `nix-serve`, is The daemon that handles binary cache requests via HTTP, `nix-serve`, is
not part of the Nix distribution, but you can install it from Nixpkgs: not part of the Nix distribution, but you can install it from Nixpkgs:
$ nix-env -i nix-serve ```console
$ nix-env -i nix-serve
```
You can then start the server, listening for HTTP connections on You can then start the server, listening for HTTP connections on
whatever port you like: whatever port you like:
$ nix-serve -p 8080 ```console
$ nix-serve -p 8080
```
To check whether it works, try the following on the client: To check whether it works, try the following on the client:
$ curl http://avalon:8080/nix-cache-info ```console
$ curl http://avalon:8080/nix-cache-info
```
which should print something like: which should print something like:
@ -28,7 +34,9 @@ which should print something like:
On the client side, you can tell Nix to use your binary cache using On the client side, you can tell Nix to use your binary cache using
`--option extra-binary-caches`, e.g.: `--option extra-binary-caches`, e.g.:
$ nix-env -i firefox --option extra-binary-caches http://avalon:8080/ ```console
$ nix-env -i firefox --option extra-binary-caches http://avalon:8080/
```
The option `extra-binary-caches` tells Nix to use this binary cache in The option `extra-binary-caches` tells Nix to use this binary cache in
addition to your default caches, such as <https://cache.nixos.org>. addition to your default caches, such as <https://cache.nixos.org>.

View file

@ -15,7 +15,9 @@ To see the list of official NixOS channels, visit
You can “subscribe” to a channel using `nix-channel --add`, e.g., You can “subscribe” to a channel using `nix-channel --add`, e.g.,
$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable ```console
$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable
```
subscribes you to a channel that always contains that latest version of subscribes you to a channel that always contains that latest version of
the Nix Packages collection. (Subscribing really just means that the URL the Nix Packages collection. (Subscribing really just means that the URL
@ -24,11 +26,15 @@ calls to `nix-channel
--update`.) You can “unsubscribe” using `nix-channel --update`.) You can “unsubscribe” using `nix-channel
--remove`: --remove`:
$ nix-channel --remove nixpkgs ```console
$ nix-channel --remove nixpkgs
```
To obtain the latest Nix expressions available in a channel, do To obtain the latest Nix expressions available in a channel, do
$ nix-channel --update ```console
$ nix-channel --update
```
This downloads and unpacks the Nix expressions in every channel This downloads and unpacks the Nix expressions in every channel
(downloaded from `url/nixexprs.tar.bz2`). It also makes the union of (downloaded from `url/nixexprs.tar.bz2`). It also makes the union of
@ -36,7 +42,9 @@ each channels Nix expressions available by default to `nix-env`
operations (via the symlink `~/.nix-defexpr/channels`). Consequently, operations (via the symlink `~/.nix-defexpr/channels`). Consequently,
you can then say you can then say
$ nix-env -u ```console
$ nix-env -u
```
to upgrade all packages in your profile to the latest versions available to upgrade all packages in your profile to the latest versions available
in the subscribed channels. in the subscribed channels.

View file

@ -18,23 +18,31 @@ be done if you are certain that you will not need to roll back.
To delete all old (non-current) generations of your current profile: To delete all old (non-current) generations of your current profile:
$ nix-env --delete-generations old ```console
$ nix-env --delete-generations old
```
Instead of `old` you can also specify a list of generations, e.g., Instead of `old` you can also specify a list of generations, e.g.,
$ nix-env --delete-generations 10 11 14 ```console
$ nix-env --delete-generations 10 11 14
```
To delete all generations older than a specified number of days (except To delete all generations older than a specified number of days (except
the current generation), use the `d` suffix. For example, the current generation), use the `d` suffix. For example,
$ nix-env --delete-generations 14d ```console
$ nix-env --delete-generations 14d
```
deletes all generations older than two weeks. deletes all generations older than two weeks.
After removing appropriate old generations you can run the garbage After removing appropriate old generations you can run the garbage
collector as follows: collector as follows:
$ nix-store --gc ```console
$ nix-store --gc
```
The behaviour of the gargage collector is affected by the The behaviour of the gargage collector is affected by the
`keep-derivations` (default: true) and `keep-outputs` (default: false) `keep-derivations` (default: true) and `keep-outputs` (default: false)
@ -47,7 +55,9 @@ sense to keep outputs to ensure that rebuild times are quick.) If you
are feeling uncertain, you can also first view what files would be are feeling uncertain, you can also first view what files would be
deleted: deleted:
$ nix-store --gc --print-dead ```console
$ nix-store --gc --print-dead
```
Likewise, the option `--print-live` will show the paths that *wont* be Likewise, the option `--print-live` will show the paths that *wont* be
deleted. deleted.
@ -56,6 +66,8 @@ There is also a convenient little utility `nix-collect-garbage`, which
when invoked with the `-d` (`--delete-old`) switch deletes all old when invoked with the `-d` (`--delete-old`) switch deletes all old
generations of all profiles in `/nix/var/nix/profiles`. So generations of all profiles in `/nix/var/nix/profiles`. So
$ nix-collect-garbage -d ```console
$ nix-collect-garbage -d
```
is a quick and easy way to clean up your system. is a quick and easy way to clean up your system.

View file

@ -5,7 +5,9 @@ are symlinks in the directory `prefix/nix/var/nix/gcroots`. For
instance, the following command makes the path instance, the following command makes the path
`/nix/store/d718ef...-foo` a root of the collector: `/nix/store/d718ef...-foo` a root of the collector:
$ ln -s /nix/store/d718ef...-foo /nix/var/nix/gcroots/bar ```console
$ ln -s /nix/store/d718ef...-foo /nix/var/nix/gcroots/bar
```
That is, after this command, the garbage collector will not remove That is, after this command, the garbage collector will not remove
`/nix/store/d718ef...-foo` or any of its dependencies. `/nix/store/d718ef...-foo` or any of its dependencies.

View file

@ -22,7 +22,9 @@ store looks like:
Of course, you wouldnt want to type Of course, you wouldnt want to type
$ /nix/store/dpmvp969yhdq...-subversion-1.1.3/bin/svn ```console
$ /nix/store/dpmvp969yhdq...-subversion-1.1.3/bin/svn
```
every time you want to run Subversion. Of course we could set up the every time you want to run Subversion. Of course we could set up the
`PATH` environment variable to include the `bin` directory of every `PATH` environment variable to include the `bin` directory of every
@ -36,7 +38,9 @@ environment `/nix/store/0c1p5z4kda11...-user-env` contains a symlink to
just Subversion 1.1.2 (arrows in the figure indicate symlinks). This just Subversion 1.1.2 (arrows in the figure indicate symlinks). This
would be what we would obtain if we had done would be what we would obtain if we had done
$ nix-env -i subversion ```console
$ nix-env -i subversion
```
on a set of Nix expressions that contained Subversion 1.1.2. on a set of Nix expressions that contained Subversion 1.1.2.
@ -49,7 +53,9 @@ since every time you perform a `nix-env` operation, a new user
environment is generated based on the current one. For instance, environment is generated based on the current one. For instance,
generation 43 was created from generation 42 when we did generation 43 was created from generation 42 when we did
$ nix-env -i subversion firefox ```console
$ nix-env -i subversion firefox
```
on a set of Nix expressions that contained Firefox and a new version of on a set of Nix expressions that contained Firefox and a new version of
Subversion. Subversion.
@ -57,11 +63,13 @@ Subversion.
Generations are grouped together into *profiles* so that different users Generations are grouped together into *profiles* so that different users
dont interfere with each other if they dont want to. For example: dont interfere with each other if they dont want to. For example:
$ ls -l /nix/var/nix/profiles/ ```console
... $ ls -l /nix/var/nix/profiles/
lrwxrwxrwx 1 eelco ... default-42-link -> /nix/store/0c1p5z4kda11...-user-env ...
lrwxrwxrwx 1 eelco ... default-43-link -> /nix/store/3aw2pdyx2jfc...-user-env lrwxrwxrwx 1 eelco ... default-42-link -> /nix/store/0c1p5z4kda11...-user-env
lrwxrwxrwx 1 eelco ... default -> default-43-link lrwxrwxrwx 1 eelco ... default-43-link -> /nix/store/3aw2pdyx2jfc...-user-env
lrwxrwxrwx 1 eelco ... default -> default-43-link
```
This shows a profile called `default`. The file `default` itself is This shows a profile called `default`. The file `default` itself is
actually a symlink that points to the current generation. When we do a actually a symlink that points to the current generation. When we do a
@ -75,18 +83,24 @@ store.)
If you find that you want to undo a `nix-env` operation, you can just do If you find that you want to undo a `nix-env` operation, you can just do
$ nix-env --rollback ```console
$ nix-env --rollback
```
which will just make the current generation link point at the previous which will just make the current generation link point at the previous
link. E.g., `default` would be made to point at `default-42-link`. You link. E.g., `default` would be made to point at `default-42-link`. You
can also switch to a specific generation: can also switch to a specific generation:
$ nix-env --switch-generation 43 ```console
$ nix-env --switch-generation 43
```
which in this example would roll forward to generation 43 again. You can which in this example would roll forward to generation 43 again. You can
also see all available generations: also see all available generations:
$ nix-env --list-generations ```console
$ nix-env --list-generations
```
You generally wouldnt have `/nix/var/nix/profiles/some-profile/bin` in You generally wouldnt have `/nix/var/nix/profiles/some-profile/bin` in
your `PATH`. Rather, there is a symlink `~/.nix-profile` that points to your `PATH`. Rather, there is a symlink `~/.nix-profile` that points to
@ -96,9 +110,11 @@ initialisation script `/nix/etc/profile.d/nix.sh` does). This makes it
easier to switch to a different profile. You can do that using the easier to switch to a different profile. You can do that using the
command `nix-env --switch-profile`: command `nix-env --switch-profile`:
$ nix-env --switch-profile /nix/var/nix/profiles/my-profile ```console
$ nix-env --switch-profile /nix/var/nix/profiles/my-profile
$ nix-env --switch-profile /nix/var/nix/profiles/default $ nix-env --switch-profile /nix/var/nix/profiles/default
```
These commands switch to the `my-profile` and default profile, These commands switch to the `my-profile` and default profile,
respectively. If the profile doesnt exist, it will be created respectively. If the profile doesnt exist, it will be created
@ -110,6 +126,8 @@ All `nix-env` operations work on the profile pointed to by
`~/.nix-profile`, but you can override this using the `--profile` option `~/.nix-profile`, but you can override this using the `--profile` option
(abbreviation `-p`): (abbreviation `-p`):
$ nix-env -p /nix/var/nix/profiles/other-profile -i subversion ```console
$ nix-env -p /nix/var/nix/profiles/other-profile -i subversion
```
This will *not* change the `~/.nix-profile` symlink. This will *not* change the `~/.nix-profile` symlink.

View file

@ -51,7 +51,8 @@ cache's documentation.
Your bucket will need the following bucket policy: Your bucket will need the following bucket policy:
{ ```json
{
"Id": "DirectReads", "Id": "DirectReads",
"Version": "2012-10-17", "Version": "2012-10-17",
"Statement": [ "Statement": [
@ -69,7 +70,8 @@ Your bucket will need the following bucket policy:
"Principal": "*" "Principal": "*"
} }
] ]
} }
```
## Authenticated Reads to your S3 binary cache ## Authenticated Reads to your S3 binary cache
@ -101,7 +103,8 @@ for authenticating requests to Amazon S3.
Your account will need the following IAM policy to upload to the cache: Your account will need the following IAM policy to upload to the cache:
{ ```json
{
"Version": "2012-10-17", "Version": "2012-10-17",
"Statement": [ "Statement": [
{ {
@ -122,14 +125,21 @@ Your account will need the following IAM policy to upload to the cache:
] ]
} }
] ]
} }
```
## Examples ## Examples
To upload with a specific credential profile for Amazon S3: To upload with a specific credential profile for Amazon S3:
nix copy --to 's3://example-nix-cache?profile=cache-upload&region=eu-west-2' nixpkgs.hello ```console
$ nix copy nixpkgs.hello \
--to 's3://example-nix-cache?profile=cache-upload&region=eu-west-2'
```
To upload to an S3-compatible binary cache: To upload to an S3-compatible binary cache:
nix copy --to 's3://example-nix-cache?profile=cache-upload&scheme=https&endpoint=minio.example.com' nixpkgs.hello ```console
$ nix copy nixpkgs.hello --to \
's3://example-nix-cache?profile=cache-upload&scheme=https&endpoint=minio.example.com'
```

View file

@ -5,7 +5,9 @@ Nix store via SSH. For example, the following installs Firefox,
automatically fetching any store paths in Firefoxs closure if they are automatically fetching any store paths in Firefoxs closure if they are
available on the server `avalon`: available on the server `avalon`:
$ nix-env -i firefox --substituters ssh://alice@avalon ```console
$ nix-env -i firefox --substituters ssh://alice@avalon
```
This works similar to the binary cache substituter that Nix usually This works similar to the binary cache substituter that Nix usually
uses, only using SSH instead of HTTP: if a store path `P` is needed, Nix uses, only using SSH instead of HTTP: if a store path `P` is needed, Nix
@ -22,11 +24,17 @@ building from source.
You can also copy the closure of some store path, without installing it You can also copy the closure of some store path, without installing it
into your profile, e.g. into your profile, e.g.
$ nix-store -r /nix/store/m85bxg…-firefox-34.0.5 --substituters ssh://alice@avalon ```console
$ nix-store -r /nix/store/m85bxg…-firefox-34.0.5 --substituters
ssh://alice@avalon
```
This is essentially equivalent to doing This is essentially equivalent to doing
$ nix-copy-closure --from alice@avalon /nix/store/m85bxg…-firefox-34.0.5 ```console
$ nix-copy-closure --from alice@avalon
/nix/store/m85bxg…-firefox-34.0.5
```
You can use SSHs *forced command* feature to set up a restricted user You can use SSHs *forced command* feature to set up a restricted user
account for SSH substituter access, allowing read-only access to the account for SSH substituter access, allowing read-only access to the
@ -45,8 +53,10 @@ to `sshd_config` to restrict the user `nix-ssh`:
On NixOS, you can accomplish the same by adding the following to your On NixOS, you can accomplish the same by adding the following to your
`configuration.nix`: `configuration.nix`:
nix.sshServe.enable = true; ```nix
nix.sshServe.keys = [ "ssh-dss AAAAB3NzaC1k... bob@example.org" ]; nix.sshServe.enable = true;
nix.sshServe.keys = [ "ssh-dss AAAAB3NzaC1k... bob@example.org" ];
```
where the latter line lists the public keys of users that are allowed to where the latter line lists the public keys of users that are allowed to
connect. connect.

View file

@ -6,7 +6,9 @@ to subsequent chapters.
1. Install single-user Nix by running the following: 1. Install single-user Nix by running the following:
```console
$ bash <(curl -L https://nixos.org/nix/install) $ bash <(curl -L https://nixos.org/nix/install)
```
This will install Nix in `/nix`. The install script will create This will install Nix in `/nix`. The install script will create
`/nix` using `sudo`, so make sure you have sufficient rights. (For `/nix` using `sudo`, so make sure you have sufficient rights. (For
@ -16,6 +18,7 @@ to subsequent chapters.
1. See what installable packages are currently available in the 1. See what installable packages are currently available in the
channel: channel:
```console
$ nix-env -qa $ nix-env -qa
docbook-xml-4.3 docbook-xml-4.3
docbook-xml-4.5 docbook-xml-4.5
@ -23,33 +26,43 @@ to subsequent chapters.
hello-2.9 hello-2.9
libxslt-1.1.28 libxslt-1.1.28
```
1. Install some packages from the channel: 1. Install some packages from the channel:
```console
$ nix-env -i hello $ nix-env -i hello
```
This should download pre-built packages; it should not build them This should download pre-built packages; it should not build them
locally (if it does, something went wrong). locally (if it does, something went wrong).
1. Test that they work: 1. Test that they work:
```console
$ which hello $ which hello
/home/eelco/.nix-profile/bin/hello /home/eelco/.nix-profile/bin/hello
$ hello $ hello
Hello, world! Hello, world!
```
1. Uninstall a package: 1. Uninstall a package:
```console
$ nix-env -e hello $ nix-env -e hello
```
1. You can also test a package without installing it: 1. You can also test a package without installing it:
```console
$ nix-shell -p hello $ nix-shell -p hello
```
This builds or downloads GNU Hello and its dependencies, then drops This builds or downloads GNU Hello and its dependencies, then drops
you into a Bash shell where the `hello` command is present, all you into a Bash shell where the `hello` command is present, all
without affecting your normal environment: without affecting your normal environment:
```console
[nix-shell:~]$ hello [nix-shell:~]$ hello
Hello, world! Hello, world!
@ -57,11 +70,14 @@ to subsequent chapters.
$ hello $ hello
hello: command not found hello: command not found
```
1. To keep up-to-date with the channel, do: 1. To keep up-to-date with the channel, do:
```console
$ nix-channel --update nixpkgs $ nix-channel --update nixpkgs
$ nix-env -u '*' $ nix-env -u '*'
```
The latter command will upgrade each installed package for which The latter command will upgrade each installed package for which
there is a “newer” version (as determined by comparing the version there is a “newer” version (as determined by comparing the version
@ -70,10 +86,14 @@ to subsequent chapters.
1. If you're unhappy with the result of a `nix-env` action (e.g., an 1. If you're unhappy with the result of a `nix-env` action (e.g., an
upgraded package turned out not to work properly), you can go back: upgraded package turned out not to work properly), you can go back:
```console
$ nix-env --rollback $ nix-env --rollback
```
1. You should periodically run the Nix garbage collector to get rid of 1. You should periodically run the Nix garbage collector to get rid of
unused packages, since uninstalls or upgrades don't actually delete unused packages, since uninstalls or upgrades don't actually delete
them: them:
```console
$ nix-collect-garbage -d $ nix-collect-garbage -d
```

View file

@ -467,6 +467,7 @@
configureFlags+=" --prefix=$prefix" configureFlags+=" --prefix=$prefix"
PKG_CONFIG_PATH=$prefix/lib/pkgconfig:$PKG_CONFIG_PATH PKG_CONFIG_PATH=$prefix/lib/pkgconfig:$PKG_CONFIG_PATH
PATH=$prefix/bin:$PATH PATH=$prefix/bin:$PATH
export MANPATH=/home/eelco/Dev/nix/inst/share/man:$MANPATH
unset PYTHONPATH unset PYTHONPATH
''; '';
}); });

View file

@ -49,7 +49,8 @@ struct NarAccessor : public FSAccessor
: acc(acc), source(source) : acc(acc), source(source)
{ } { }
void createMember(const Path & path, NarMember member) { void createMember(const Path & path, NarMember member)
{
size_t level = std::count(path.begin(), path.end(), '/'); size_t level = std::count(path.begin(), path.end(), '/');
while (parents.size() > level) parents.pop(); while (parents.size() > level) parents.pop();