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)
$(trace-gen) mdbook build doc/manual -d $(docdir)/manual
@cp doc/manual/highlight.pack.js $(docdir)/manual/highlight.js
endif

View file

@ -7,17 +7,19 @@ for determining if the results are the same.
For purposes of demonstration, we'll use the following Nix file,
`deterministic.nix` for testing:
let
inherit (import <nixpkgs> {}) runCommand;
in {
stable = runCommand "stable" {} ''
touch $out
'';
unstable = runCommand "unstable" {} ''
echo $RANDOM > $out
'';
}
```nix
let
inherit (import <nixpkgs> {}) runCommand;
in {
stable = runCommand "stable" {} ''
touch $out
'';
unstable = runCommand "unstable" {} ''
echo $RANDOM > $out
'';
}
```
Additionally, `nix.conf` contains:
@ -26,10 +28,12 @@ Additionally, `nix.conf` contains:
where `/etc/nix/my-diff-hook` is an executable file containing:
#!/bin/sh
exec >&2
echo "For derivation $3:"
/run/current-system/sw/bin/diff -r "$1" "$2"
```bash
#!/bin/sh
exec >&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.
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
code of 0:
$ nix-build ./deterministic.nix -A stable
this derivation will be built:
/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv
building '/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv'...
/nix/store/yyxlzw3vqaas7wfp04g0b1xg51f2czgq-stable
$ nix-build ./deterministic.nix -A stable --check
checking outputs of '/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv'...
/nix/store/yyxlzw3vqaas7wfp04g0b1xg51f2czgq-stable
```console
$ nix-build ./deterministic.nix -A stable
this derivation will be built:
/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv
building '/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv'...
/nix/store/yyxlzw3vqaas7wfp04g0b1xg51f2czgq-stable
$ nix-build ./deterministic.nix -A stable --check
checking outputs of '/nix/store/z98fasz2jqy9gs0xbvdj939p27jwda38-stable.drv'...
/nix/store/yyxlzw3vqaas7wfp04g0b1xg51f2czgq-stable
```
If the build is not deterministic, Nix will exit with a status code of
1:
$ nix-build ./deterministic.nix -A unstable
this derivation will be built:
/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv
building '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'...
/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable
$ nix-build ./deterministic.nix -A unstable --check
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
```console
$ nix-build ./deterministic.nix -A unstable
this derivation will be built:
/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv
building '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'...
/nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable
$ nix-build ./deterministic.nix -A unstable --check
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
```
In the Nix daemon's log, we will now see:
For derivation /nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv:
1c1
< 8108
---
> 30204
```
For derivation /nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv:
1c1
< 8108
---
> 30204
```
Using `--check` with `--keep-failed` will cause Nix to keep the second
build's output in a special, `.check` path:
$ nix-build ./deterministic.nix -A unstable --check --keep-failed
checking outputs of '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'...
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'
```console
$ nix-build ./deterministic.nix -A unstable --check --keep-failed
checking outputs of '/nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv'...
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
`/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
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.
@ -130,10 +146,12 @@ reproducibly:
An example output of this configuration:
$ nix-build ./test.nix -A unstable
this derivation will be built:
/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv
building '/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv' (round 1/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
/nix/store/6xg356v9gl03hpbbg8gws77n19qanh02-unstable
```console
$ nix-build ./test.nix -A unstable
this derivation will be built:
/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv
building '/nix/store/ch6llwpr2h8c3jmnf3f2ghkhx59aa97f-unstable.drv' (round 1/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
/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
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
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
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
bash: nix-store: command not found
error: cannot connect to 'mac'
```console
bash: nix-store: command not found
error: cannot connect to 'mac'
```
then you need to ensure that the `PATH` of non-interactive login shells
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
`x86_64-darwin` on a Linux machine:
$ uname
Linux
```console
$ uname
Linux
$ nix build \
'(with import <nixpkgs> { system = "x86_64-darwin"; }; runCommand "foo" {} "uname > $out")' \
--builders 'ssh://mac x86_64-darwin'
[1/0/1 built, 0.0 MiB DL] building foo on ssh://mac
$ cat ./result
Darwin
$ nix build \
'(with import <nixpkgs> { system = "x86_64-darwin"; }; runCommand "foo" {} "uname > $out")' \
--builders 'ssh://mac x86_64-darwin'
[1/0/1 built, 0.0 MiB DL] building foo on ssh://mac
$ cat ./result
Darwin
```
It is possible to specify multiple builders separated by a semicolon or
a newline, e.g.
```
```console
--builders 'ssh://mac x86_64-darwin ; ssh://beastie x86_64-freebsd'
```
@ -91,8 +99,10 @@ default, set it to `-`.
the `requiredSystemFeatures` attribute, then Nix will only perform
the derivation on a machine that has the specified features. For
instance, the attribute
requiredSystemFeatures = [ "kvm" ];
```nix
requiredSystemFeatures = [ "kvm" ];
```
will cause the build to be performed on a machine that has the `kvm`
feature.
@ -111,11 +121,15 @@ For example, the machine specification
specifies several machines that can perform `i686-linux` builds.
However, `poochie` will only do builds that have the attribute
requiredSystemFeatures = [ "benchmark" ];
```nix
requiredSystemFeatures = [ "benchmark" ];
```
or
requiredSystemFeatures = [ "benchmark" "kvm" ];
```nix
requiredSystemFeatures = [ "benchmark" "kvm" ];
```
`itchy` cannot do builds that require `kvm`, but `scratchy` does support
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
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
# cat /etc/nix/key.public
example-nix-cache-1:1/cKDz3QCCOmwcztD2eV6Coggp6rqc9DGjWv7C0G+rM=
```console
# nix-store --generate-binary-cache-key example-nix-cache-1 /etc/nix/key.private /etc/nix/key.public
# 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
`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`:
#!/bin/sh
set -eu
set -f # disable globbing
export IFS=' '
echo "Signing paths" $OUT_PATHS
nix sign-paths --key-file /etc/nix/key.private $OUT_PATHS
echo "Uploading paths" $OUT_PATHS
exec nix copy --to 's3://example-nix-cache' $OUT_PATHS
```bash
#!/bin/sh
set -eu
set -f # disable globbing
export IFS=' '
echo "Signing paths" $OUT_PATHS
nix sign-paths --key-file /etc/nix/key.private $OUT_PATHS
echo "Uploading paths" $OUT_PATHS
exec nix copy --to 's3://example-nix-cache' $OUT_PATHS
```
> **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:
# chmod +x /etc/nix/upload-to-cache.sh
```console
# chmod +x /etc/nix/upload-to-cache.sh
```
# Updating Nix Configuration
@ -80,27 +86,33 @@ Then, restart the `nix-daemon`.
Build any derivation, for example:
$ nix-build -E '(import <nixpkgs> {}).writeText "example" (builtins.toString builtins.currentTime)'
this derivation will be built:
/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'...
post-build-hook: Signing paths /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
post-build-hook: Uploading paths /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
/nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
```console
$ nix-build -E '(import <nixpkgs> {}).writeText "example" (builtins.toString builtins.currentTime)'
this derivation will be built:
/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'...
post-build-hook: Signing paths /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
post-build-hook: Uploading paths /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
/nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
```
Then delete the path from the store, and try substituting it from the
binary cache:
$ rm ./result
$ nix-store --delete /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
```console
$ rm ./result
$ nix-store --delete /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
```
Now, copy the path back from the cache:
$ nix-store --realise /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
copying path '/nix/store/m8bmqwrch6l3h8s0k3d673xpmipcdpsa-example from 's3://example-nix-cache'...
warning: you did not specify '--add-root'; the result might be removed by the garbage collector
/nix/store/m8bmqwrch6l3h8s0k3d673xpmipcdpsa-example
```console
$ nix-store --realise /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example
copying path '/nix/store/m8bmqwrch6l3h8s0k3d673xpmipcdpsa-example from 's3://example-nix-cache'...
warning: you did not specify '--add-root'; the result might be removed by the garbage collector
/nix/store/m8bmqwrch6l3h8s0k3d673xpmipcdpsa-example
```
# Conclusion

View file

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

View file

@ -54,9 +54,11 @@ Most Nix commands interpret the following environment variables:
Note that if youre symlinking the Nix store so that you can put it
on another file system than the root file system, on Linux youre
better off using `bind` mount points, e.g.,
$ mkdir /nix
$ mount -o bind /mnt/otherdisk/nix /nix
```console
$ mkdir /nix
$ mount -o bind /mnt/otherdisk/nix /nix
```
Consult the mount 8 manual page for details.

View file

@ -66,20 +66,24 @@ The following common options are supported:
# Examples
$ nix-build '<nixpkgs>' -A firefox
store derivation is /nix/store/qybprl8sz2lc...-firefox-1.5.0.7.drv
/nix/store/d18hyl92g30l...-firefox-1.5.0.7
```console
$ nix-build '<nixpkgs>' -A firefox
store derivation is /nix/store/qybprl8sz2lc...-firefox-1.5.0.7.drv
/nix/store/d18hyl92g30l...-firefox-1.5.0.7
$ ls -l result
lrwxrwxrwx ... result -> /nix/store/d18hyl92g30l...-firefox-1.5.0.7
$ ls -l result
lrwxrwxrwx ... result -> /nix/store/d18hyl92g30l...-firefox-1.5.0.7
$ ls ./result/bin/
firefox firefox-config
$ ls ./result/bin/
firefox firefox-config
```
If a derivation has multiple outputs, `nix-build` will build the default
(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`.
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
specific output:
$ nix-build '<nixpkgs>' -A openssl.man
```console
$ nix-build '<nixpkgs>' -A openssl.man
```
This will create a symlink `result-man`.
Build a Nix expression given on the command line:
$ nix-build -E 'with import <nixpkgs> { }; runCommand "foo" { } "echo bar > $out"'
$ cat ./result
bar
```console
$ nix-build -E 'with import <nixpkgs> { }; runCommand "foo" { } "echo bar > $out"'
$ cat ./result
bar
```
Build the GNU Hello package from the latest revision of the master
branch of Nixpkgs:
$ nix-build https://github.com/NixOS/nixpkgs/archive/master.tar.gz -A hello
# Environment variables
```console
$ nix-build https://github.com/NixOS/nixpkgs/archive/master.tar.gz -A hello
```

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:
$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable
$ nix-channel --update
$ nix-env -iA nixpkgs.hello
```console
$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable
$ nix-channel --update
$ nix-env -iA nixpkgs.hello
```
You can revert channel updates using `--rollback`:
$ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version'
"14.04.527.0e935f1"
```console
$ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version'
"14.04.527.0e935f1"
$ nix-channel --rollback
switching from generation 483 to 482
$ nix-channel --rollback
switching from generation 483 to 482
$ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version'
"14.04.526.dbadfad"
$ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version'
"14.04.526.dbadfad"
```
# 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
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:
$ 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
environment:
$ nix-copy-closure --from alice@itchy.labs \
/nix/store/0dj0503hjxy5mbwlafv1rsbdiyx1gkdy-subversion-1.4.4
$ nix-env -i /nix/store/0dj0503hjxy5mbwlafv1rsbdiyx1gkdy-subversion-1.4.4
```console
$ nix-copy-closure --from alice@itchy.labs \
/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
`bar.nix`, then the default Nix expression will essentially be
{
foo = import ~/.nix-defexpr/foo.nix;
bar = import ~/.nix-defexpr/bar.nix;
}
```nix
{
foo = import ~/.nix-defexpr/foo.nix;
bar = import ~/.nix-defexpr/bar.nix;
}
```
The file `manifest.nix` is always ignored. Subdirectories without a
`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:
$ nix-env --install gcc-3.3.2
installing `gcc-3.3.2'
uninstalling `gcc-3.1'
```console
$ nix-env --install gcc-3.3.2
installing `gcc-3.3.2'
uninstalling `gcc-3.1'
```
Note the previously installed version is removed, since
`--preserve-installed` was not specified.
To install an arbitrary version:
$ nix-env --install gcc
installing `gcc-3.3.2'
```console
$ nix-env --install gcc
installing `gcc-3.3.2'
```
To install using a specific attribute:
$ nix-env -i -A gcc40mips
$ nix-env -i -A xorg.xorgserver
```console
$ nix-env -i -A gcc40mips
$ nix-env -i -A xorg.xorgserver
```
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:
$ 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
`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:
$ 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:
$ nix-env -f ./foo.nix -i -E \
'f: (f {system = "i686-linux";}).subversionWithJava'
```console
$ nix-env -f ./foo.nix -i -E \
'f: (f {system = "i686-linux";}).subversionWithJava'
```
I.e., this evaluates to `(f: (f {system =
"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:
$ nix-env -f '<nixpkgs>' -iA hello --dry-run
(dry run; not doing anything)
installing hello-2.10
this path will be fetched (0.04 MiB download, 0.19 MiB unpacked):
/nix/store/wkhdf9jinag5750mqlax6z2zbwhqb76n-hello-2.10
...
```console
$ nix-env -f '<nixpkgs>' -iA hello --dry-run
(dry run; not doing anything)
installing hello-2.10
this path will be fetched (0.04 MiB download, 0.19 MiB unpacked):
/nix/store/wkhdf9jinag5750mqlax6z2zbwhqb76n-hello-2.10
...
```
To install Firefox from the latest revision in the Nixpkgs/NixOS 14.12
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`
@ -353,18 +375,26 @@ For the other flags, see `--install`.
## Examples
$ nix-env --upgrade gcc
upgrading `gcc-3.3.1' to `gcc-3.4'
```console
$ 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)
upgrading `gcc-3.4' to `gcc-3.3.2'
```console
$ 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
(no upgrades available, so nothing happens)
```console
$ nix-env --upgrade pan
(no upgrades available, so nothing happens)
```
$ nix-env -u (try to upgrade everything)
upgrading `hello-2.1.2' to `hello-2.1.3'
upgrading `mozilla-1.2' to `mozilla-1.4'
```console
$ nix-env -u (try to upgrade everything)
upgrading `hello-2.1.2' to `hello-2.1.3'
upgrading `mozilla-1.2' to `mozilla-1.4'
```
## Versions
@ -416,8 +446,10 @@ designated by the symbolic names *drvnames* are removed.
## Examples
$ nix-env --uninstall gcc
$ nix-env -e '.*' (remove everything)
```console
$ nix-env --uninstall gcc
$ nix-env -e '.*' (remove everything)
```
# 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
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`
@ -473,37 +507,43 @@ environment build script:
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.
To disable the currently installed Firefox, then install a new Firefox
while the old remains part of the profile:
$ nix-env -q
firefox-2.0.0.9 (the current one)
```console
$ nix-env -q
firefox-2.0.0.9 (the current one)
$ nix-env --preserve-installed -i firefox-2.0.0.11
installing `firefox-2.0.0.11'
building path(s) `/nix/store/myy0y59q3ig70dgq37jqwg1j0rsapzsl-user-environment'
collision between `/nix/store/...-firefox-2.0.0.11/bin/firefox'
and `/nix/store/...-firefox-2.0.0.9/bin/firefox'.
(i.e., cant have two active at the same time)
$ nix-env --preserve-installed -i firefox-2.0.0.11
installing `firefox-2.0.0.11'
building path(s) `/nix/store/myy0y59q3ig70dgq37jqwg1j0rsapzsl-user-environment'
collision between `/nix/store/...-firefox-2.0.0.11/bin/firefox'
and `/nix/store/...-firefox-2.0.0.9/bin/firefox'.
(i.e., cant have two active at the same time)
$ nix-env --set-flag active false firefox
setting flag on `firefox-2.0.0.9'
$ nix-env --set-flag active false firefox
setting flag on `firefox-2.0.0.9'
$ nix-env --preserve-installed -i firefox-2.0.0.11
installing `firefox-2.0.0.11'
$ nix-env --preserve-installed -i firefox-2.0.0.11
installing `firefox-2.0.0.11'
$ nix-env -q
firefox-2.0.0.11 (the enabled one)
firefox-2.0.0.9 (the disabled one)
$ nix-env -q
firefox-2.0.0.11 (the enabled one)
firefox-2.0.0.9 (the disabled one)
```
To make files from `binutils` take precedence over files from `gcc`:
$ nix-env --set-flag priority 5 binutils
$ nix-env --set-flag priority 10 gcc
```console
$ nix-env --set-flag priority 5 binutils
$ nix-env --set-flag priority 10 gcc
```
# Operation `--query`
@ -633,66 +673,82 @@ derivation is shown unless `--no-name` is specified.
To show installed packages:
$ nix-env -q
bison-1.875c
docbook-xml-4.2
firefox-1.0.4
MPlayer-1.0pre7
ORBit2-2.8.3
```console
$ nix-env -q
bison-1.875c
docbook-xml-4.2
firefox-1.0.4
MPlayer-1.0pre7
ORBit2-2.8.3
```
To show available packages:
$ nix-env -qa
firefox-1.0.7
GConf-2.4.0.1
MPlayer-1.0pre7
ORBit2-2.8.3
```console
$ nix-env -qa
firefox-1.0.7
GConf-2.4.0.1
MPlayer-1.0pre7
ORBit2-2.8.3
```
To show the status of available packages:
$ nix-env -qas
-P- firefox-1.0.7 (not installed but present)
--S GConf-2.4.0.1 (not present, but there is a substitute for fast installation)
--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)
```console
$ nix-env -qas
-P- firefox-1.0.7 (not installed but present)
--S GConf-2.4.0.1 (not present, but there is a substitute for fast installation)
--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`:
$ nix-env -f ./foo.nix -qa
foo-1.2.3
```console
$ nix-env -f ./foo.nix -qa
foo-1.2.3
```
To compare installed versions to whats available:
$ nix-env -qc
...
acrobat-reader-7.0 - ? (package is not available at all)
autoconf-2.59 = 2.59 (same version)
firefox-1.0.4 < 1.0.7 (a more recent version is available)
...
```console
$ nix-env -qc
...
acrobat-reader-7.0 - ? (package is not available at all)
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:
$ nix-env -qa '.*zip.*'
bzip2-1.0.6
gzip-1.6
zip-3.0
```console
$ nix-env -qa '.*zip.*'
bzip2-1.0.6
gzip-1.6
zip-3.0
```
To show all packages with “`firefox`” or “`chromium`” in the name:
$ nix-env -qa '.*(firefox|chromium).*'
chromium-37.0.2062.94
chromium-beta-38.0.2125.24
firefox-32.0.3
firefox-with-plugins-13.0.1
```console
$ nix-env -qa '.*(firefox|chromium).*'
chromium-37.0.2062.94
chromium-beta-38.0.2125.24
firefox-32.0.3
firefox-with-plugins-13.0.1
```
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`
@ -707,7 +763,9 @@ the symlink `~/.nix-profile` is made to point to *path*.
## Examples
$ nix-env -S ~/my-profile
```console
$ nix-env -S ~/my-profile
```
# Operation `--list-generations`
@ -724,11 +782,13 @@ generation, and indicates the current generation.
## Examples
$ nix-env --list-generations
95 2004-02-06 11:48:24
96 2004-02-06 11:49:01
97 2004-02-06 16:22:45
98 2004-02-06 16:24:33 (current)
```console
$ nix-env --list-generations
95 2004-02-06 11:48:24
96 2004-02-06 11:49:01
97 2004-02-06 16:22:45
98 2004-02-06 16:24:33 (current)
```
# Operation `--delete-generations`
@ -750,13 +810,21 @@ generations is important to make garbage collection effective.
## 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`
@ -776,8 +844,10 @@ Switching will fail if the specified generation does not exist.
## Examples
$ nix-env -G 42
switching from generation 50 to 42
```console
$ nix-env -G 42
switching from generation 50 to 42
```
# Operation `--rollback`
@ -794,11 +864,15 @@ generation, if it exists. It is just a convenience wrapper around
## Examples
$ nix-env --rollback
switching from generation 92 to 91
```console
$ nix-env --rollback
switching from generation 92 to 91
```
$ nix-env --rollback
error: no generation older than the current (91) exists
```console
$ nix-env --rollback
error: no generation older than the current (91) exists
```
# Environment variables

View file

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

View file

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

View file

@ -59,13 +59,19 @@ Nix store is also printed.
# Examples
$ nix-prefetch-url ftp://ftp.gnu.org/pub/gnu/hello/hello-2.10.tar.gz
0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i
```console
$ 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
0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i
/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz
```console
$ nix-prefetch-url --print-path mirror://gnu/hello/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
079agjlv0hrv7fxnx9ngipx14gyncbkllxrp9cccnh3a50fxcmy7
/nix/store/19zrmhm3m40xxaw81c8cqm6aljgrnwj2-0.8.tar.gz
```console
$ nix-prefetch-url --unpack --print-path https://github.com/NixOS/patchelf/archive/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
to `nix-shell`. For example, the derivation attribute
shellHook =
''
echo "Hello shell"
'';
```nix
shellHook =
''
echo "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
shell in which to build it:
$ nix-shell '<nixpkgs>' -A pan
[nix-shell]$ unpackPhase
[nix-shell]$ cd pan-*
[nix-shell]$ configurePhase
[nix-shell]$ buildPhase
[nix-shell]$ ./pan/gui/pan
```shell
$ nix-shell '<nixpkgs>' -A pan
[nix-shell]$ unpackPhase
[nix-shell]$ cd pan-*
[nix-shell]$ configurePhase
[nix-shell]$ buildPhase
[nix-shell]$ ./pan/gui/pan
```
To clear the environment first, and do some additional automatic
initialisation of the interactive shell:
$ nix-shell '<nixpkgs>' -A pan --pure \
--command 'export NIX_DEBUG=1; export NIX_CORES=8; return'
```shell
$ nix-shell '<nixpkgs>' -A pan --pure \
--command 'export NIX_DEBUG=1; export NIX_CORES=8; return'
```
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
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:
$ nix-shell -p sqlite xorg.libX11
[nix-shell]$ echo $NIX_LDFLAGS
… -L/nix/store/j1zg5v…-sqlite-3.8.0.2/lib -L/nix/store/0gmcz9…-libX11-1.6.1/lib …
```shell
$ nix-shell -p sqlite xorg.libX11
[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
the `buildInputs = [ ... ]` shown above, not only package names. So the
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
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
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
Pan 0.139
[nix-shell:~]$ pan --version
Pan 0.139
```
# 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
done by starting the script with the following lines:
#! /usr/bin/env nix-shell
#! nix-shell -i real-interpreter -p packages
```bash
#! /usr/bin/env nix-shell
#! nix-shell -i real-interpreter -p packages
```
where *real-interpreter* is the “real” script interpreter that will be
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
`prettytable` package:
#! /usr/bin/env nix-shell
#! nix-shell -i python -p python pythonPackages.prettytable
```python
#! /usr/bin/env nix-shell
#! nix-shell -i python -p python pythonPackages.prettytable
import prettytable
import prettytable
# Print a simple table.
t = prettytable.PrettyTable(["N", "N^2"])
for n in range(1, 10): t.add_row([n, n * n])
print t
# Print a simple table.
t = prettytable.PrettyTable(["N", "N^2"])
for n in range(1, 10): t.add_row([n, n * n])
print t
```
Similarly, the following is a Perl script that specifies that it
requires Perl and the `HTML::TokeParser::Simple` and `LWP` packages:
#! /usr/bin/env nix-shell
#! nix-shell -i perl -p perl perlPackages.HTMLTokeParserSimple perlPackages.LWP
```perl
#! /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.
my $p = HTML::TokeParser::Simple->new(url => 'http://nixos.org/');
# Fetch nixos.org and print all hrefs.
my $p = HTML::TokeParser::Simple->new(url => 'http://nixos.org/');
while (my $token = $p->get_tag("a")) {
my $href = $token->get_attr("href");
print "$href\n" if $href;
}
while (my $token = $p->get_tag("a")) {
my $href = $token->get_attr("href");
print "$href\n" if $href;
}
```
Sometimes you need to pass a simple Nix expression to customize a
package like Terraform:
#! /usr/bin/env nix-shell
#! nix-shell -i bash -p "terraform.withPlugins (plugins: [ plugins.openstack ])"
```bash
#! /usr/bin/env nix-shell
#! nix-shell -i bash -p "terraform.withPlugins (plugins: [ plugins.openstack ])"
terraform apply
terraform apply
```
> **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
branch):
#! /usr/bin/env nix-shell
#! 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
```haskell
#! /usr/bin/env nix-shell
#! 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 Text.HTML.TagSoup
import Network.HTTP
import Text.HTML.TagSoup
-- Fetch nixos.org and print all hrefs.
main = do
resp <- Network.HTTP.simpleHTTP (getRequest "http://nixos.org/")
body <- getResponseBody resp
let tags = filter (isTagOpenName "a") $ parseTags body
let tags' = map (fromAttrib "href") tags
mapM_ putStrLn $ filter (/= "") tags'
-- Fetch nixos.org and print all hrefs.
main = do
resp <- Network.HTTP.simpleHTTP (getRequest "http://nixos.org/")
body <- getResponseBody resp
let tags = filter (isTagOpenName "a") $ parseTags body
let tags' = map (fromAttrib "href") tags
mapM_ putStrLn $ filter (/= "") tags'
```
If you want to be even more precise, you can specify a specific revision
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
example, the Python example could have been written as:
#! /usr/bin/env nix-shell
#! nix-shell deps.nix -i python
```python
#! /usr/bin/env nix-shell
#! nix-shell deps.nix -i python
```
where the file `deps.nix` in the same directory as the `#!`-script
contains:
with import <nixpkgs> {};
```nix
with import <nixpkgs> {};
runCommand "dummy" { buildInputs = [ python pythonPackages.prettytable ]; } ""
runCommand "dummy" { buildInputs = [ python pythonPackages.prettytable ]; } ""
```

View file

@ -47,13 +47,15 @@ have an effect.
The `--indirect` flag causes a uniquely named symlink to *path* to
be stored in `/nix/var/nix/gcroots/auto/`. For instance,
$ nix-store --add-root /home/eelco/bla/result --indirect -r ...
```console
$ nix-store --add-root /home/eelco/bla/result --indirect -r ...
$ ls -l /nix/var/nix/gcroots/auto
lrwxrwxrwx 1 ... 2005-03-13 21:10 dn54lcypm8f8... -> /home/eelco/bla/result
$ ls -l /nix/var/nix/gcroots/auto
lrwxrwxrwx 1 ... 2005-03-13 21:10 dn54lcypm8f8... -> /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
$ 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
```
Thus, when `/home/eelco/bla/result` is removed, the GC root in the
`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
[`nix-instantiate`](nix-instantiate.md):
$ nix-store -r $(nix-instantiate ./test.nix)
/nix/store/31axcgrlbfsxzmfff1gyj1bf62hvkby2-aterm-2.3.1
```console
$ nix-store -r $(nix-instantiate ./test.nix)
/nix/store/31axcgrlbfsxzmfff1gyj1bf62hvkby2-aterm-2.3.1
```
This is essentially what [`nix-build`](nix-build.md) does.
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`
@ -190,9 +196,11 @@ The following flags are available:
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:
$ cat <<EOF >>/root/.ssh/authorized_keys
command="nice -n20 nix-store --serve --write" ssh-rsa AAAAB3NzaC1yc2EAAAA...
EOF
```console
$ cat <<EOF >>/root/.ssh/authorized_keys
command="nice -n20 nix-store --serve --write" ssh-rsa AAAAB3NzaC1yc2EAAAA...
EOF
```
# Operation `--gc`
@ -245,14 +253,18 @@ number of bytes that would be freed.
To delete all unreachable paths, just do:
$ nix-store --gc
deleting `/nix/store/kq82idx6g0nyzsp2s14gfsc38npai7lf-cairo-1.0.4.tar.gz.drv'
...
8825586 bytes freed (8.42 MiB)
```console
$ nix-store --gc
deleting `/nix/store/kq82idx6g0nyzsp2s14gfsc38npai7lf-cairo-1.0.4.tar.gz.drv'
...
8825586 bytes freed (8.42 MiB)
```
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`
@ -274,9 +286,11 @@ paths in the store that refer to it (i.e., depend on it).
## Example
$ nix-store --delete /nix/store/zq0h41l75vlb4z45kzgjjmsjxvcv1qk7-mesa-6.4
0 bytes freed (0.00 MiB)
error: cannot delete path `/nix/store/zq0h41l75vlb4z45kzgjjmsjxvcv1qk7-mesa-6.4' since it is still alive
```console
$ nix-store --delete /nix/store/zq0h41l75vlb4z45kzgjjmsjxvcv1qk7-mesa-6.4
0 bytes freed (0.00 MiB)
error: cannot delete path `/nix/store/zq0h41l75vlb4z45kzgjjmsjxvcv1qk7-mesa-6.4' since it is still alive
```
# Operation `--query`
@ -407,18 +421,22 @@ symlink.
Print the closure (runtime dependencies) of the `svn` program in the
current user environment:
$ nix-store -qR $(which svn)
/nix/store/5mbglq5ldqld8sj57273aljwkfvj22mc-subversion-1.1.4
/nix/store/9lz9yc6zgmc0vlqmn2ipcpkjlmbi51vv-glibc-2.3.4
...
```console
$ nix-store -qR $(which svn)
/nix/store/5mbglq5ldqld8sj57273aljwkfvj22mc-subversion-1.1.4
/nix/store/9lz9yc6zgmc0vlqmn2ipcpkjlmbi51vv-glibc-2.3.4
...
```
Print the build-time dependencies of `svn`:
$ nix-store -qR $(nix-store -qd $(which svn))
/nix/store/02iizgn86m42q905rddvg4ja975bk2i4-grep-2.5.1.tar.bz2.drv
/nix/store/07a2bzxmzwz5hp58nf03pahrv2ygwgs3-gcc-wrapper.sh
/nix/store/0ma7c9wsbaxahwwl04gbw3fcd806ski4-glibc-2.3.4.drv
... lots of other paths ...
```console
$ nix-store -qR $(nix-store -qd $(which svn))
/nix/store/02iizgn86m42q905rddvg4ja975bk2i4-grep-2.5.1.tar.bz2.drv
/nix/store/07a2bzxmzwz5hp58nf03pahrv2ygwgs3-gcc-wrapper.sh
/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 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:
$ nix-store -q --tree $(nix-store -qd $(which svn))
/nix/store/7i5082kfb6yjbqdbiwdhhza0am2xvh6c-subversion-1.1.4.drv
+---/nix/store/d8afh10z72n8l1cr5w42366abiblgn54-builder.sh
+---/nix/store/fmzxmpjx2lh849ph0l36snfj9zdibw67-bash-3.0.drv
| +---/nix/store/570hmhmx3v57605cqg9yfvvyh0nnb8k8-bash
| +---/nix/store/p3srsbd8dx44v2pg6nbnszab5mcwx03v-builder.sh
...
```console
$ nix-store -q --tree $(nix-store -qd $(which svn))
/nix/store/7i5082kfb6yjbqdbiwdhhza0am2xvh6c-subversion-1.1.4.drv
+---/nix/store/d8afh10z72n8l1cr5w42366abiblgn54-builder.sh
+---/nix/store/fmzxmpjx2lh849ph0l36snfj9zdibw67-bash-3.0.drv
| +---/nix/store/570hmhmx3v57605cqg9yfvvyh0nnb8k8-bash
| +---/nix/store/p3srsbd8dx44v2pg6nbnszab5mcwx03v-builder.sh
...
```
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)))
/nix/store/23ny9l9wixx21632y2wi4p585qhva1q8-sylpheed-1.0.0
/nix/store/5mbglq5ldqld8sj57273aljwkfvj22mc-subversion-1.1.4
/nix/store/dpmvp969yhdqs7lm2r1a3gng7pyq6vy4-subversion-1.1.3
/nix/store/l51240xqsgg8a7yrbqdx1rfzyv6l26fx-lynx-2.8.5
```console
$ nix-store -q --referrers $(nix-store -q --binding openssl $(nix-store -qd $(which svn)))
/nix/store/23ny9l9wixx21632y2wi4p585qhva1q8-sylpheed-1.0.0
/nix/store/5mbglq5ldqld8sj57273aljwkfvj22mc-subversion-1.1.4
/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
library) used by `svn`:
$ nix-store -q --referrers-closure $(ldd $(which svn) | grep /libc.so | awk '{print $3}')
/nix/store/034a6h4vpz9kds5r6kzb9lhh81mscw43-libgnomeprintui-2.8.2
/nix/store/15l3yi0d45prm7a82pcrknxdh6nzmxza-gawk-3.1.4
...
```console
$ nix-store -q --referrers-closure $(ldd $(which svn) | grep /libc.so | awk '{print $3}')
/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
by an ELF executable.
@ -456,16 +480,20 @@ by an ELF executable.
Make a picture of the runtime dependency graph of the current user
environment:
$ nix-store -q --graph ~/.nix-profile | dot -Tps > graph.ps
$ gv graph.ps
```console
$ 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
depends on `svn`:
$ nix-store -q --roots $(which svn)
/nix/var/nix/profiles/default-81-link
/nix/var/nix/profiles/default-82-link
/nix/var/nix/profiles/per-user/eelco/profile-97-link
```console
$ nix-store -q --roots $(which svn)
/nix/var/nix/profiles/default-81-link
/nix/var/nix/profiles/default-82-link
/nix/var/nix/profiles/per-user/eelco/profile-97-link
```
# Operation `--add`
@ -480,8 +508,10 @@ prints the resulting paths in the Nix store on standard output.
## Example
$ nix-store --add ./foo.c
/nix/store/m7lrha58ph6rcnv109yzx1nk1cj7k7zf-foo.c
```console
$ nix-store --add ./foo.c
/nix/store/m7lrha58ph6rcnv109yzx1nk1cj7k7zf-foo.c
```
# Operation `--add-fixed`
@ -505,8 +535,10 @@ This operation has the following options:
## Example
$ nix-store --add-fixed sha256 ./hello-2.10.tar.gz
/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz
```console
$ nix-store --add-fixed sha256 ./hello-2.10.tar.gz
/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz
```
# Operation `--verify`
@ -554,7 +586,9 @@ path has changed, and 1 otherwise.
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`
@ -578,14 +612,16 @@ substitutes are available, then repair is not possible.
## Example
$ nix-store --verify-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13
path `/nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13' was modified!
expected hash `2db57715ae90b7e31ff1f2ecb8c12ec1cc43da920efcbe3b22763f36a1861588',
got `481c5aa5483ebc97c20457bb8bca24deea56550d3985cda0027f67fe54b808e4'
```console
$ nix-store --verify-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13
path `/nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13' was modified!
expected hash `2db57715ae90b7e31ff1f2ecb8c12ec1cc43da920efcbe3b22763f36a1861588',
got `481c5aa5483ebc97c20457bb8bca24deea56550d3985cda0027f67fe54b808e4'
$ nix-store --repair-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13
fetching path `/nix/store/d7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13'...
$ nix-store --repair-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13
fetching path `/nix/store/d7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13'...
```
# 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
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:
$ nix-store --import < out
```console
$ nix-store --import < out
```
# Operation `--import`
@ -695,11 +735,13 @@ Use `-vv` or `-vvv` to get some progress indication.
## Example
$ 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
```console
$ 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
```
# Operation `--read-log`
@ -721,13 +763,15 @@ substitute, then the log is unavailable.
## Example
$ nix-store -l $(which ktorrent)
building /nix/store/dhc73pvzpnzxhdgpimsd9sw39di66ph1-ktorrent-2.2.1
unpacking sources
unpacking source archive /nix/store/p8n1jpqs27mgkjw07pb5269717nzf5f8-ktorrent-2.2.1.tar.gz
ktorrent-2.2.1/
ktorrent-2.2.1/NEWS
...
```console
$ nix-store -l $(which ktorrent)
building /nix/store/dhc73pvzpnzxhdgpimsd9sw39di66ph1-ktorrent-2.2.1
unpacking sources
unpacking source archive /nix/store/p8n1jpqs27mgkjw07pb5269717nzf5f8-ktorrent-2.2.1.tar.gz
ktorrent-2.2.1/
ktorrent-2.2.1/NEWS
...
```
# Operation `--dump-db`
@ -773,12 +817,14 @@ of the builder are placed in the variable `_args`.
## Example
$ 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 system; system='x86_64-linux'
export _args; _args='-e /nix/store/9krlzvny65gdc8s7kpb6lkx8cd02c25c-default-builder.sh'
```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 system; system='x86_64-linux'
export _args; _args='-e /nix/store/9krlzvny65gdc8s7kpb6lkx8cd02c25c-default-builder.sh'
```
# Operation `--generate-binary-cache-key`

View file

@ -158,11 +158,13 @@ Most Nix commands accept the following command-line options:
For instance, the top-level `default.nix` in Nixpkgs is actually a
function:
{ # The system (e.g., `i686-linux') for which to build the packages.
system ? builtins.currentSystem
...
}: ...
```nix
{ # The system (e.g., `i686-linux') for which to build the packages.
system ? builtins.currentSystem
...
}: ...
```
So if you call this Nix expression (e.g., when you do `nix-env -i
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
references (dependencies) of the output of the builder. For example,
allowedReferences = [];
```nix
allowedReferences = [];
```
enforces that the output of a derivation cannot have any 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
recursively. For example,
allowedRequisites = [ foobar ];
```nix
allowedRequisites = [ foobar ];
```
enforces that the output of a derivation cannot have any other
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
example,
disallowedReferences = [ foo ];
```nix
disallowedReferences = [ foo ];
```
enforces that the output of a derivation cannot have a direct
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
dependencies recursively. For example,
disallowedRequisites = [ foobar ];
```nix
disallowedRequisites = [ foobar ];
```
enforces that the output of a derivation cannot have any runtime
dependency on `foobar` or any other derivation depending recursively
@ -50,20 +58,20 @@ Derivations can declare some infrequently used optional attributes.
- `exportReferencesGraph`
This attribute allows builders access to the references graph of
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
attribute should be a list of pairs `[ name1
path1 name2
path2 ...
]`. The references graph of each *pathN* will be stored in a text
file *nameN* in the temporary build directory. The text files have
the format used by `nix-store
--register-validity` (with the deriver fields left empty). For
example, when the following derivation is built:
whose references graph the builder needs to know. The value of
this attribute should be a list of pairs `[ name1 path1 name2
path2 ... ]`. The references graph of each *pathN* will be stored
in a text file *nameN* in the temporary build directory. The text
files have the format used by `nix-store --register-validity`
(with the deriver fields left empty). For example, when the
following derivation is built:
derivation {
...
exportReferencesGraph = [ "libfoo-graph" libfoo ];
};
```nix
derivation {
...
exportReferencesGraph = [ "libfoo-graph" libfoo ];
};
```
the references graph of `libfoo` is placed in the file
`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,
`fetchurl` in Nixpkgs has the line
impureEnvVars = [ "http_proxy" "https_proxy" ... ];
```nix
impureEnvVars = [ "http_proxy" "https_proxy" ... ];
```
to make it use the proxy server configuration specified by the user
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
the file. For example,
fetchurl {
url = "http://ftp.gnu.org/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
}
```nix
fetchurl {
url = "http://ftp.gnu.org/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
}
```
It sometimes happens that the URL of the file changes, e.g., because
servers are reorganised or no longer available. We then must update
the call to `fetchurl`, e.g.,
fetchurl {
url = "ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
}
```nix
fetchurl {
url = "ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
}
```
If a `fetchurl` derivation was treated like a normal derivation, the
output paths of the derivation and *all derivations depending on it*
@ -147,23 +161,25 @@ Derivations can declare some infrequently used optional attributes.
As an example, here is the (simplified) Nix expression for
`fetchurl`:
{ stdenv, curl }: # The curl program is used for downloading.
{ url, sha256 }:
stdenv.mkDerivation {
name = baseNameOf (toString url);
builder = ./builder.sh;
buildInputs = [ curl ];
# This is a fixed-output derivation; the output must be a regular
# file with SHA256 hash sha256.
outputHashMode = "flat";
outputHashAlgo = "sha256";
outputHash = sha256;
inherit url;
}
```nix
{ stdenv, curl }: # The curl program is used for downloading.
{ url, sha256 }:
stdenv.mkDerivation {
name = baseNameOf (toString url);
builder = ./builder.sh;
buildInputs = [ curl ];
# This is a fixed-output derivation; the output must be a regular
# file with SHA256 hash sha256.
outputHashMode = "flat";
outputHashAlgo = "sha256";
outputHash = sha256;
inherit url;
}
```
The `outputHashAlgo` attribute specifies the hash algorithm used to
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
than environment variables. For example, if you have
```
```nix
passAsFile = ["big"];
big = "a very long string";
```
then when the builder runs, the environment variable `bigPath` will
contain the absolute path to a temporary file containing `a very
long
string`. That is, for any attribute *x* listed in `passAsFile`, Nix
will pass an environment variable `xPath` holding the path of the
file containing the value of attribute *x*. This is useful when you
need to pass large strings to a builder, since most operating
systems impose a limit on the size of the environment (typically, a
few hundred kilobyte).
then when the builder runs, the environment variable `bigPath`
will contain the absolute path to a temporary file containing `a
very long string`. That is, for any attribute *x* listed in
`passAsFile`, Nix will pass an environment variable `xPath`
holding the path of the file containing the value of attribute
*x*. This is useful when you need to pass large strings to a
builder, since most operating systems impose a limit on the size
of the environment (typically, a few hundred kilobyte).
- `preferLocalBuild`
If this attribute is set to `true` and [distributed building is

View file

@ -8,25 +8,27 @@ packages are imported and called with the appropriate arguments. Here
are some fragments of `all-packages.nix`, with annotations of what
they mean:
...
rec { ①
hello = import ../applications/misc/hello/ex-1 ② { ③
inherit fetchurl stdenv perl;
};
perl = import ../development/interpreters/perl { ④
inherit fetchurl stdenv;
};
fetchurl = import ../build-support/fetchurl {
inherit stdenv; ...
};
stdenv = ...;
}
```nix
...
rec { ①
hello = import ../applications/misc/hello/ex-1 ② { ③
inherit fetchurl stdenv perl;
};
perl = import ../development/interpreters/perl { ④
inherit fetchurl stdenv;
};
fetchurl = import ../build-support/fetchurl {
inherit stdenv; ...
};
stdenv = ...;
}
```
1. This file defines a set of attributes, all of which are concrete
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
> corresponding attribute from the Nixpkgs set, like this:
>
> hello = callPackage ../applications/misc/hello/ex-1 { };
> ```nix
> hello = callPackage ../applications/misc/hello/ex-1 { };
> ```
>
> If necessary, you can set or override arguments:
>
> hello = callPackage ../applications/misc/hello/ex-1 { stdenv = myStdenv; };
> ```nix
> hello = callPackage ../applications/misc/hello/ex-1 { stdenv = myStdenv; };
> ```
4. Likewise, we have to instantiate Perl, `fetchurl`, and the standard
environment.

View file

@ -3,15 +3,17 @@
Here is the builder referenced from Hello's Nix expression (stored in
`pkgs/applications/misc/hello/ex-1/builder.sh`):
source $stdenv/setup ①
PATH=$perl/bin:$PATH ②
tar xvfz $src ③
cd hello-*
./configure --prefix=$out ④
make ⑤
make install
```bash
source $stdenv/setup ①
PATH=$perl/bin:$PATH ②
tar xvfz $src ③
cd hello-*
./configure --prefix=$out ④
make ⑤
make install
```
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

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
the Nix installation, e.g.,
if builtins ? getEnv then builtins.getEnv "PATH" else ""
```nix
if builtins ? getEnv then builtins.getEnv "PATH" else ""
```
This allows a Nix expression to fall back gracefully on older Nix
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
a particular version of Nixpkgs, e.g.
with import (fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz) {};
stdenv.mkDerivation { … }
```nix
with import (fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz) {};
stdenv.mkDerivation { … }
```
The fetched tarball is cached for a certain amount of time (1 hour
by default) in `~/.cache/nix/tarballs/`. You can change the cache
@ -124,19 +128,21 @@ For instance, `derivation` is also available as `builtins.derivation`.
of seconds` or in the Nix configuration file with this option: `
number of seconds to cache `.
Note that when obtaining the hash with ` nix-prefetch-url
` the option `--unpack` is required.
Note that when obtaining the hash with ` nix-prefetch-url ` the
option `--unpack` is required.
This function can also verify the contents against a hash. In that
case, the function takes a set instead of a URL. The set requires
the attribute `url` and the attribute `sha256`, e.g.
with import (fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz";
sha256 = "1jppksrfvbk5ypiqdz4cddxdl8z6zyzdb2srq8fcffr327ld5jj2";
}) {};
stdenv.mkDerivation { … }
```nix
with import (fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz";
sha256 = "1jppksrfvbk5ypiqdz4cddxdl8z6zyzdb2srq8fcffr327ld5jj2";
}) {};
stdenv.mkDerivation { … }
```
This function is not available if [restricted evaluation
mode](../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:
builtins.fetchGit {
url = "git@github.com:my-secret/repository.git";
ref = "master";
rev = "adab8b916a45068c044658c4158d81878f9ed1c3";
}
```nix
builtins.fetchGit {
url = "git@github.com:my-secret/repository.git";
ref = "master";
rev = "adab8b916a45068c044658c4158d81878f9ed1c3";
}
```
- To fetch an arbitrary reference:
builtins.fetchGit {
url = "https://github.com/NixOS/nix.git";
ref = "refs/heads/0.5-release";
}
```nix
builtins.fetchGit {
url = "https://github.com/NixOS/nix.git";
ref = "refs/heads/0.5-release";
}
```
- If the revision you're looking for is in the default branch of
the git repository you don't strictly need to specify the branch
@ -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
the `ref` attribute as well.
builtins.fetchGit {
url = "https://github.com/nixos/nix.git";
rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
ref = "1.11-maintenance";
}
```nix
builtins.fetchGit {
url = "https://github.com/nixos/nix.git";
rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
ref = "1.11-maintenance";
}
```
> **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
the git repository you may omit the `ref` attribute.
builtins.fetchGit {
url = "https://github.com/nixos/nix.git";
rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
}
```nix
builtins.fetchGit {
url = "https://github.com/nixos/nix.git";
rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452";
}
```
- To fetch a specific tag:
builtins.fetchGit {
url = "https://github.com/nixos/nix.git";
ref = "refs/tags/1.9";
}
```nix
builtins.fetchGit {
url = "https://github.com/nixos/nix.git";
ref = "refs/tags/1.9";
}
```
- To fetch the latest version of a remote branch:
builtins.fetchGit {
url = "ssh://git@github.com/nixos/nix.git";
ref = "master";
}
```nix
builtins.fetchGit {
url = "ssh://git@github.com/nixos/nix.git";
ref = "master";
}
```
> **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
the directory `source-dir` as an input to a Nix expression, e.g.
stdenv.mkDerivation {
...
src = ./source-dir;
}
```nix
stdenv.mkDerivation {
...
src = ./source-dir;
}
```
However, if `source-dir` is a Subversion working copy, then all
those annoying `.svn` subdirectories will also be copied to the
@ -259,10 +279,10 @@ For instance, `derivation` is also available as `builtins.derivation`.
causing lots of spurious rebuilds. With `filterSource` you can
filter out the `.svn` directories:
```
src = builtins.filterSource
(path: type: type != "directory" || baseNameOf path != ".svn")
./source-dir;
```nix
src = builtins.filterSource
(path: type: type != "directory" || baseNameOf path != ".svn")
./source-dir;
```
Thus, the first argument *e1* must be a predicate function that is
@ -279,10 +299,10 @@ For instance, `derivation` is also available as `builtins.derivation`.
- `builtins.foldl` *op* *nul* *list*
Reduce a list by applying a binary operator, from left to right,
e.g. `foldl op nul [x0 x1 x2 ...] = op (op
(op nul x0) x1) x2) ...`. The operator is applied strictly, i.e.,
its arguments are evaluated first. For example, `foldl (x: y: x +
y) 0 [1 2 3]` evaluates to 6.
e.g. `foldl op nul [x0 x1 x2 ...] = op (op (op nul x0) x1) x2)
...`. The operator is applied strictly, i.e., its arguments are
evaluated first. For example, `foldl (x: y: x + y) 0 [1 2 3]`
evaluates to 6.
- `builtins.functionArgs` *f*
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*
Convert a JSON string to a Nix value. For example,
builtins.fromJSON ''{"x": [1, 2, 3], "y": null}''
```nix
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*
Generate list of size *length*, with each element *i* equal to the
value returned by *generator* `i`. For example,
builtins.genList (x: x * x) 5
```nix
builtins.genList (x: x * x) 5
```
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
have a calling expression
rec {
x = 123;
y = import ./foo.nix;
}
```nix
rec {
x = 123;
y = import ./foo.nix;
}
```
then the following `foo.nix` will give an error:
x + 456
```nix
x + 456
```
since `x` is not in scope in `foo.nix`. If you want `x` to be
available in `foo.nix`, you should pass it as a function argument:
rec {
x = 123;
y = import ./foo.nix x;
}
```nix
rec {
x = 123;
y = import ./foo.nix x;
}
```
and
x: x + 456
```nix
x: x + 456
```
(The function argument doesnt have to be called `x` in `foo.nix`;
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,
and an attribute `value` specifying its value. Example:
builtins.listToAttrs
[ { name = "foo"; value = 123; }
{ name = "bar"; value = 456; }
]
```nix
builtins.listToAttrs
[ { name = "foo"; value = 123; }
{ name = "bar"; value = 456; }
]
```
evaluates to
{ foo = 123; bar = 456; }
```nix
{ foo = 123; bar = 456; }
```
- `map` *f* *list*; `builtins.map` *f* *list*
Apply the function *f* to each element in the list *list*. For
example,
map (x: "foo" + x) [ "bar" "bla" "abc" ]
```nix
map (x: "foo" + x) [ "bar" "bla" "abc" ]
```
evaluates to `[ "foobar" "foobla" "fooabc"
]`.
evaluates to `[ "foobar" "foobla" "fooabc" ]`.
- `builtins.match` *regex* *str*
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
in the list is a regex group.
builtins.match "ab" "abc"
```nix
builtins.match "ab" "abc"
```
Evaluates to `null`.
builtins.match "abc" "abc"
```nix
builtins.match "abc" "abc"
```
Evaluates to `[ ]`.
builtins.match "a(b)(c)" "abc"
```nix
builtins.match "a(b)(c)" "abc"
```
Evaluates to `[ "b" "c" ]`.
builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" " FOO "
```nix
builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" " FOO "
```
Evaluates to `[ "foo" ]`.
@ -534,11 +578,12 @@ For instance, `derivation` is also available as `builtins.derivation`.
- `builtins.readDir` *path*
Return the contents of the directory *path* as a set mapping
directory entries to the corresponding file type. For instance, if
directory `A` contains a regular file `B` and another directory `C`,
then `builtins.readDir
./A` will return the set
directory `A` contains a regular file `B` and another directory
`C`, then `builtins.readDir ./A` will return the set
{ B = "regular"; C = "directory"; }
```nix
{ B = "regular"; C = "directory"; }
```
The possible values for the file type are `"regular"`,
`"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
dont have to exist in *set*. For instance,
removeAttrs { x = 1; y = 2; z = 3; } [ "a" "x" "z" ]
```nix
removeAttrs { x = 1; y = 2; z = 3; } [ "a" "x" "z" ]
```
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*
with the corresponding string in *to*. For example,
builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar"
```nix
builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar"
```
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.
For example,
builtins.sort builtins.lessThan [ 483 249 526 147 42 77 ]
```nix
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
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
sequences is a regex group.
builtins.split "(a)b" "abc"
```nix
builtins.split "(a)b" "abc"
```
Evaluates to `[ "" [ "a" ] "c" ]`.
builtins.split "([ac])" "abc"
```nix
builtins.split "([ac])" "abc"
```
Evaluates to `[ "" [ "a" ] "b" [ "c" ] "" ]`.
builtins.split "(a)|(c)" "abc"
```nix
builtins.split "(a)|(c)" "abc"
```
Evaluates to `[ "" [ "a" null ] "b" [ null "c" ] "" ]`.
builtins.split "([[:upper:]]+)" " FOO "
```nix
builtins.split "([[:upper:]]+)" " 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
non-negative. For example,
builtins.substring 0 3 "nixos"
```nix
builtins.substring 0 3 "nixos"
```
evaluates to `"nix"`.
@ -645,45 +705,47 @@ For instance, `derivation` is also available as `builtins.derivation`.
“inline”. For instance, the following Nix expression combines the
[Nix expression for GNU Hello](expression-syntax.md) and its
[build script](build-script.md) into one file:
{ stdenv, fetchurl, perl }:
stdenv.mkDerivation {
name = "hello-2.1.1";
builder = builtins.toFile "builder.sh" "
source $stdenv/setup
PATH=$perl/bin:$PATH
tar xvfz $src
cd hello-*
./configure --prefix=$out
make
make install
";
src = fetchurl {
url = "http://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
};
inherit perl;
}
```nix
{ stdenv, fetchurl, perl }:
stdenv.mkDerivation {
name = "hello-2.1.1";
builder = builtins.toFile "builder.sh" "
source $stdenv/setup
PATH=$perl/bin:$PATH
tar xvfz $src
cd hello-*
./configure --prefix=$out
make
make install
";
src = fetchurl {
url = "http://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
};
inherit perl;
}
```
It is even possible for one file to refer to another, e.g.,
```
builder = let
configFile = builtins.toFile "foo.conf" "
# This is some dummy configuration file.
...
";
in builtins.toFile "builder.sh" "
source $stdenv/setup
```nix
builder = let
configFile = builtins.toFile "foo.conf" "
# This is some dummy configuration file.
...
cp ${configFile} $out/etc/foo.conf
";
```
in builtins.toFile "builder.sh" "
source $stdenv/setup
...
cp ${configFile} $out/etc/foo.conf
";
```
Note that `${configFile}` is an
[antiquotation](language-values.md), so the result of the
@ -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
other, like so:
let
foo = builtins.toFile "foo" "...${bar}...";
bar = builtins.toFile "bar" "...${foo}...";
in foo
```nix
let
foo = builtins.toFile "foo" "...${bar}...";
bar = builtins.toFile "bar" "...${foo}...";
in foo
```
This is not allowed because it would cause a cyclic dependency in
the computation of the cryptographic hashes for `foo` and `bar`.
@ -744,40 +808,42 @@ For instance, `derivation` is also available as `builtins.derivation`.
Here is an example where this is the case:
{ stdenv, fetchurl, libxslt, jira, uberwiki }:
stdenv.mkDerivation (rec {
name = "web-server";
buildInputs = [ libxslt ];
builder = builtins.toFile "builder.sh" "
source $stdenv/setup
mkdir $out
echo "$servlets" | xsltproc ${stylesheet} - > $out/server-conf.xml ①
";
stylesheet = builtins.toFile "stylesheet.xsl" ②
"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
<xsl:template match='/'>
<Configure>
<xsl:for-each select='/expr/list/attrs'>
<Call name='addWebApplication'>
<Arg><xsl:value-of select=\"attr[@name = 'path']/string/@value\" /></Arg>
<Arg><xsl:value-of select=\"attr[@name = 'war']/path/@value\" /></Arg>
</Call>
</xsl:for-each>
</Configure>
</xsl:template>
</xsl:stylesheet>
";
servlets = builtins.toXML [ ③
{ path = "/bugtracker"; war = jira + "/lib/atlassian-jira.war"; }
{ path = "/wiki"; war = uberwiki + "/uberwiki.war"; }
];
})
```nix
{ stdenv, fetchurl, libxslt, jira, uberwiki }:
stdenv.mkDerivation (rec {
name = "web-server";
buildInputs = [ libxslt ];
builder = builtins.toFile "builder.sh" "
source $stdenv/setup
mkdir $out
echo "$servlets" | xsltproc ${stylesheet} - > $out/server-conf.xml ①
";
stylesheet = builtins.toFile "stylesheet.xsl" ②
"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
<xsl:template match='/'>
<Configure>
<xsl:for-each select='/expr/list/attrs'>
<Call name='addWebApplication'>
<Arg><xsl:value-of select=\"attr[@name = 'path']/string/@value\" /></Arg>
<Arg><xsl:value-of select=\"attr[@name = 'war']/path/@value\" /></Arg>
</Call>
</xsl:for-each>
</Configure>
</xsl:template>
</xsl:stylesheet>
";
servlets = builtins.toXML [ ③
{ path = "/bugtracker"; war = jira + "/lib/atlassian-jira.war"; }
{ path = "/wiki"; war = uberwiki + "/uberwiki.war"; }
];
})
```
The builder is supposed to generate the configuration file for a
[Jetty servlet container](http://jetty.mortbay.org/). A servlet
@ -796,27 +862,29 @@ For instance, `derivation` is also available as `builtins.derivation`.
configuration file for the Jetty server. The XML representation
produced at point ③ by `toXML` is as follows:
<?xml version='1.0' encoding='utf-8'?>
<expr>
<list>
<attrs>
<attr name="path">
<string value="/bugtracker" />
</attr>
<attr name="war">
<path value="/nix/store/d1jh9pasa7k2...-jira/lib/atlassian-jira.war" />
</attr>
</attrs>
<attrs>
<attr name="path">
<string value="/wiki" />
</attr>
<attr name="war">
<path value="/nix/store/y6423b1yi4sx...-uberwiki/uberwiki.war" />
</attr>
</attrs>
</list>
</expr>
```xml
<?xml version='1.0' encoding='utf-8'?>
<expr>
<list>
<attrs>
<attr name="path">
<string value="/bugtracker" />
</attr>
<attr name="war">
<path value="/nix/store/d1jh9pasa7k2...-jira/lib/atlassian-jira.war" />
</attr>
</attrs>
<attrs>
<attr name="path">
<string value="/wiki" />
</attr>
<attr name="war">
<path value="/nix/store/y6423b1yi4sx...-uberwiki/uberwiki.war" />
</attr>
</attrs>
</list>
</expr>
```
Note that we used the `toFile` built-in to write the builder and
the stylesheet “inline” in the Nix expression. The path of the
@ -830,13 +898,13 @@ For instance, `derivation` is also available as `builtins.derivation`.
- `builtins.tryEval` *e*
Try to shallowly evaluate *e*. Return a set containing the
attributes `success` (`true` if *e* evaluated successfully, `false`
if an error was thrown) and `value`, equalling *e* if successful and
`false` otherwise. Note that this doesn't evaluate *e* deeply, so
` let e = { x = throw ""; }; in (builtins.tryEval e).success
` will be `true`. Using ` builtins.deepSeq
` one can get the expected result: `let e = { x = throw "";
}; in (builtins.tryEval (builtins.deepSeq e e)).success` will be
attributes `success` (`true` if *e* evaluated successfully,
`false` if an error was thrown) and `value`, equalling *e* if
successful and `false` otherwise. Note that this doesn't evaluate
*e* deeply, so ` let e = { x = throw ""; }; in (builtins.tryEval
e).success ` will be `true`. Using ` builtins.deepSeq ` one can
get the expected result: `let e = { x = throw ""; }; in
(builtins.tryEval (builtins.deepSeq e e)).success` will be
`false`.
- `builtins.typeOf` *e*

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
library package could specify:
outputs = [ "lib" "headers" "doc" ];
```nix
outputs = [ "lib" "headers" "doc" ];
```
This will cause Nix to pass environment variables `lib`, `headers`
and `doc` to the builder containing the intended store paths of each
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
derivation by selecting it as an attribute, e.g.
buildInputs = [ pkg.lib pkg.headers ];
```nix
buildInputs = [ pkg.lib pkg.headers ];
```
The first element of `outputs` determines the *default output*.
Thus, you could also write
buildInputs = [ pkg pkg.headers ];
```nix
buildInputs = [ pkg pkg.headers ];
```
since `pkg` is equivalent to `pkg.lib`.

View file

@ -2,17 +2,19 @@
Here is a Nix expression for GNU Hello:
{ stdenv, fetchurl, perl }: ①
stdenv.mkDerivation { ②
name = "hello-2.1.1"; ③
builder = ./builder.sh; ④
src = fetchurl { ⑤
url = "ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
};
inherit perl; ⑥
}
```nix
{ stdenv, fetchurl, perl }: ①
stdenv.mkDerivation { ②
name = "hello-2.1.1"; ③
builder = ./builder.sh; ④
src = fetchurl { ⑤
url = "ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz";
sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465";
};
inherit perl; ⑥
}
```
This file is actually already in the Nix Packages collection in
`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
Perl interpreter.
Nix functions generally have the form `{ x, y, ...,
z }: e` where `x`, `y`, etc. are the names of the expected
arguments, and where *e* is the body of the function. So here, the
entire remainder of the file is the body of the function; when given
the required arguments, the body should describe how to build an
instance of the Hello package.
Nix functions generally have the form `{ x, y, ..., z }: e` where
`x`, `y`, etc. are the names of the expected arguments, and where
*e* is the body of the function. So here, the entire remainder of
the file is the body of the function; when given the required
arguments, the body should describe how to build an instance of
the Hello package.
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
built by humans instead of computers). We perform a derivation by
calling `stdenv.mkDerivation`. `mkDerivation` is a function provided
by `stdenv` that builds a package from a set of *attributes*. A set
is just a list of key/value pairs where each key is a string and
each value is an arbitrary Nix expression. They take the general
form `{
name1 =
expr1; ...
nameN =
exprN; }`.
calling `stdenv.mkDerivation`. `mkDerivation` is a function
provided by `stdenv` that builds a package from a set of
*attributes*. A set is just a list of key/value pairs where each
key is a string and each value is an arbitrary Nix
expression. They take the general form `{ name1 = expr1; ...
nameN = exprN; }`.
3. The attribute `name` specifies the symbolic name and version of the
package. Nix doesn't really care about these things, but they are
used by for instance `nix-env
-q` to show a “human-readable” name for packages. This attribute is
required by `mkDerivation`.
3. The attribute `name` specifies the symbolic name and version of
the package. Nix doesn't really care about these things, but they
are used by for instance `nix-env -q` to show a “human-readable”
name for packages. This attribute is required by `mkDerivation`.
4. The attribute `builder` specifies the builder. This attribute can
sometimes be omitted, in which case `mkDerivation` will fill in a
@ -83,8 +81,10 @@ elements (referenced from the figure by number):
`perl` function argument to the builder. All attributes in the set
are actually passed as environment variables to the builder, so
declaring an attribute
perl = perl;
```nix
perl = perl;
```
will do the trick: it binds an attribute `perl` to the function
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
something like this:
PATH=$perl/bin:$PATH
tar xvfz $src
cd hello-*
./configure --prefix=$out
make
make install
```bash
PATH=$perl/bin:$PATH
tar xvfz $src
cd hello-*
./configure --prefix=$out
make
make install
```
The builders for almost all Unix packages look like this — set up some
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
the generic build facilities looks like:
buildInputs="$perl" ①
source $stdenv/setup ②
genericBuild ③
```bash
buildInputs="$perl" ①
source $stdenv/setup ②
genericBuild ③
```
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
have been set in the Nix expression, like this:
```
```nix
buildInputs = [ perl ];
```
The `perl` attribute can then be removed, and the builder becomes even
shorter:
source $stdenv/setup
genericBuild
```bash
source $stdenv/setup
genericBuild
```
In fact, `mkDerivation` provides a default builder that looks exactly
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
each other. For example,
rec {
x = y;
y = 123;
}.x
```nix
rec {
x = y;
y = 123;
}.x
```
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
@ -19,10 +21,12 @@ recursive set, they are.
Recursive sets of course introduce the danger of infinite recursion. For
example, the expression
rec {
x = y;
y = x;
}.x
```nix
rec {
x = y;
y = x;
}.x
```
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.
For instance,
let
x = "foo";
y = "bar";
in x + y
```nix
let
x = "foo";
y = "bar";
in x + y
```
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`
keyword. For instance,
let x = 123; in
{ inherit x;
y = 456;
}
```nix
let x = 123; in
{ inherit x;
y = 456;
}
```
is equivalent to
let x = 123; in
{ x = x;
y = 456;
}
```nix
let x = 123; in
{ x = x;
y = 456;
}
```
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
also possible to inherit attributes from another set. For instance, in
this fragment from `all-packages.nix`,
```
graphviz = (import ../tools/graphics/graphviz) {
inherit fetchurl stdenv libpng libjpeg expat x11 yacc;
inherit (xlibs) libXaw;
};
```nix
graphviz = (import ../tools/graphics/graphviz) {
inherit fetchurl stdenv libpng libjpeg expat x11 yacc;
inherit (xlibs) libXaw;
};
xlibs = {
libX11 = ...;
libXaw = ...;
...
}
libpng = ...;
libjpg = ...;
xlibs = {
libX11 = ...;
libXaw = ...;
...
}
libpng = ...;
libjpg = ...;
...
```
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
...
inherit x y z;
inherit (src-set) a b c;
...
```nix
...
inherit x y z;
inherit (src-set) a b c;
...
```
is equivalent to
...
x = x; y = y; z = z;
a = src-set.a; b = src-set.b; c = src-set.c;
...
```nix
...
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
defining a set.
@ -105,7 +119,9 @@ defining a set.
Functions have the following form:
pattern: body
```nix
pattern: body
```
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
@ -114,42 +130,51 @@ three kinds of patterns:
- If a pattern is a single identifier, then the function matches any
argument. Example:
let negate = x: !x;
concat = x: y: x + y;
in if negate true then concat "foo" "bar" else ""
```nix
let negate = x: !x;
concat = x: y: x + y;
in if negate true then concat "foo" "bar" else ""
```
Note that `concat` is a function that takes one argument and returns
a function that takes another argument. This allows partial
parameterisation (i.e., only filling some of the arguments of a
function); e.g.,
map (concat "foo") [ "bar" "bla" "abc" ]
```nix
map (concat "foo") [ "bar" "bla" "abc" ]
```
evaluates to `[ "foobar" "foobla"
"fooabc" ]`.
evaluates to `[ "foobar" "foobla" "fooabc" ]`.
- A *set pattern* of the form `{ name1, name2, …, nameN }` matches a
set containing the listed attributes, and binds the values of those
attributes to variables in the function body. For example, the
function
{ x, y, z }: z + y + x
```nix
{ x, y, z }: z + y + 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
additional arguments, you can use an ellipsis (`...`):
{ x, y, z, ... }: z + y + x
```nix
{ x, y, z, ... }: z + y + x
```
This works on any set that contains at least the three named
attributes.
It is possible to provide *default values* for attributes, in which
case they are allowed to be missing. A default value is specified by
writing `name ?
e`, where *e* is an arbitrary expression. For example,
It is possible to provide *default values* for attributes, in
which case they are allowed to be missing. A default value is
specified by writing `name ? e`, where *e* is an arbitrary
expression. For example,
{ x, y ? "foo", z ? "bar" }: z + y + x
```nix
{ x, y ? "foo", z ? "bar" }: z + y + x
```
specifies a function that only requires an attribute named `x`, but
optionally accepts `y` and `z`.
@ -157,14 +182,14 @@ three kinds of patterns:
- An `@`-pattern provides a means of referring to the whole value
being matched:
```
args@{ x, y, z, ... }: z + y + x + args.a
```nix
args@{ x, y, z, ... }: z + y + x + args.a
```
but can also be written as:
```
{ x, y, z, ... } @ args: z + y + x + args.a
```nix
{ x, y, z, ... } @ args: z + y + x + args.a
```
Here `args` is bound to the entire argument, which is further
@ -182,24 +207,30 @@ three kinds of patterns:
>
> For instance
>
> let
> function = args@{ a ? 23, ... }: args;
> in
> function {}
> ```nix
> let
> function = args@{ a ? 23, ... }: args;
> in
> function {}
> ````
>
> will evaluate to an empty attribute set.
Note that functions do not have names. If you want to give them a name,
you can bind them to an attribute, e.g.,
let concat = { x, y }: x + y;
in concat { x = "foo"; y = "bar"; }
```nix
let concat = { x, y }: x + y;
in concat { x = "foo"; y = "bar"; }
```
## Conditionals
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
(`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
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
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
assertions can be used:.
{ localServer ? false
, httpServer ? false
, sslSupport ? false
, pythonBindings ? false
, javaSwigBindings ? false
, javahlBindings ? false
, stdenv, fetchurl
, openssl ? null, httpd ? null, db4 ? null, expat, swig ? null, j2sdk ? null
}:
assert localServer -> db4 != null; ①
assert httpServer -> httpd != null && httpd.expat == expat; ②
assert sslSupport -> openssl != null && (httpServer -> httpd.openssl == openssl); ③
assert pythonBindings -> swig != null && swig.pythonSupport;
assert javaSwigBindings -> swig != null && swig.javaSupport;
assert javahlBindings -> j2sdk != null;
stdenv.mkDerivation {
name = "subversion-1.1.1";
...
openssl = if sslSupport then openssl else null; ④
...
}
```nix
{ localServer ? false
, httpServer ? false
, sslSupport ? false
, pythonBindings ? false
, javaSwigBindings ? false
, javahlBindings ? false
, stdenv, fetchurl
, openssl ? null, httpd ? null, db4 ? null, expat, swig ? null, j2sdk ? null
}:
assert localServer -> db4 != null; ①
assert httpServer -> httpd != null && httpd.expat == expat; ②
assert sslSupport -> openssl != null && (httpServer -> httpd.openssl == openssl); ③
assert pythonBindings -> swig != null && swig.pythonSupport;
assert javaSwigBindings -> swig != null && swig.javaSupport;
assert javahlBindings -> j2sdk != null;
stdenv.mkDerivation {
name = "subversion-1.1.1";
...
openssl = if sslSupport then openssl else null; ④
...
}
```
The points of interest are:
@ -273,19 +308,25 @@ The points of interest are:
A *with-expression*,
with e1; e2
```nix
with e1; e2
```
introduces the set *e1* into the lexical scope of the expression *e2*.
For instance,
let as = { x = "foo"; y = "bar"; };
in with as; x + y
```nix
let as = { x = "foo"; y = "bar"; };
in with as; x + y
```
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
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
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
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
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 can be single-line, started with a `#` character, or
inline/multi-line, enclosed within `/*
... */`.
inline/multi-line, enclosed within `/* ... */`.

View file

@ -19,24 +19,30 @@ Nix has the following basic data types:
into a string (meaning that it must be a string, a path, or a
derivation). For instance, rather than writing
"--with-freetype2-library=" + freetype + "/lib"
```nix
"--with-freetype2-library=" + freetype + "/lib"
```
(where `freetype` is a derivation), you can instead write the more
natural
"--with-freetype2-library=${freetype}/lib"
```nix
"--with-freetype2-library=${freetype}/lib"
```
The latter is automatically translated to the former. A more
complicated example (from the Nix expression for
[Qt](http://www.trolltech.com/products/qt)):
configureFlags = "
-system-zlib -system-libpng -system-libjpeg
${if openglSupport then "-dlopen-opengl
-L${mesa}/lib -I${mesa}/include
-L${libXmu}/lib -I${libXmu}/include" else ""}
${if threadSupport then "-thread" else "-no-thread"}
";
```nix
configureFlags = "
-system-zlib -system-libpng -system-libjpeg
${if openglSupport then "-dlopen-opengl
-L${mesa}/lib -I${mesa}/include
-L${libXmu}/lib -I${libXmu}/include" else ""}
${if threadSupport then "-thread" else "-no-thread"}
";
```
Note that Nix expressions and strings can be arbitrarily nested; in
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*,
which is enclosed between pairs of *double single-quotes*, like so:
''
This is the first line.
This is the second line.
This is the third line.
''
```nix
''
This is the first line.
This is the second line.
This is the third line.
''
```
This kind of string literal intelligently strips indentation from
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
each line, so the resulting string is
"This is the first line.\nThis is the second line.\n This is the third line.\n"
```nix
"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
ignored if there is no non-whitespace text on the initial line.
@ -82,17 +92,19 @@ Nix has the following basic data types:
configuration files because `''` is much less common than `"`.
Example:
stdenv.mkDerivation {
...
postInstall =
''
mkdir $out/bin $out/etc
cp foo $out/bin
echo "Hello World" > $out/etc/foo.conf
${if enableBar then "cp bar $out/bin" else ""}
'';
...
}
```nix
stdenv.mkDerivation {
...
postInstall =
''
mkdir $out/bin $out/etc
cp foo $out/bin
echo "Hello World" > $out/etc/foo.conf
${if enableBar then "cp bar $out/bin" else ""}
'';
...
}
```
Finally, as a convenience, *URIs* as defined in appendix B of
[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
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
the function `f`. Note that function calls have to be enclosed in
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
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
terminated by a semicolon. For example:
{ x = 123;
text = "Hello";
y = f { bla = 456; };
}
```nix
{ x = 123;
text = "Hello";
y = f { bla = 456; };
}
```
This defines a set with attributes named `x`, `text`, `y`. The order of
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
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
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.
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
case where an attribute name is just a single antiquotation, the quotes
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
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
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`.
@ -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
passed in first , e.g.,
let add = { __functor = self: x: x + self.x; };
inc = add // { x = 1; };
in inc 1
```nix
let add = { __functor = self: x: x + self.x; };
inc = add // { x = 1; };
in inc 1
```
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

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
`result` in the current directory:
$ nix-build -A hello
building path `/nix/store/632d2b22514d...-hello-2.1.1'
hello-2.1.1/
hello-2.1.1/intl/
hello-2.1.1/intl/ChangeLog
...
$ ls -l result
lrwxrwxrwx ... 2006-09-29 10:43 result -> /nix/store/632d2b22514d...-hello-2.1.1
$ ./result/bin/hello
Hello, world!
```console
$ nix-build -A hello
building path `/nix/store/632d2b22514d...-hello-2.1.1'
hello-2.1.1/
hello-2.1.1/intl/
hello-2.1.1/intl/ChangeLog
...
$ ls -l result
lrwxrwxrwx ... 2006-09-29 10:43 result -> /nix/store/632d2b22514d...-hello-2.1.1
$ ./result/bin/hello
Hello, world!
```
The `-A` option selects the `hello` attribute. This is faster than
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
(or perform other derivations if available) until the build finishes:
$ nix-build -A hello
waiting for lock on `/nix/store/0h5b7hp8d4hqfrw8igvx97x1xawrjnac-hello-2.1.1x'
```console
$ 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
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
latest version of Nix from GitHub:
$ git clone https://github.com/NixOS/nix.git
$ cd nix
```console
$ git clone https://github.com/NixOS/nix.git
$ cd nix
```
To build Nix for the current operating system/architecture use
$ nix-build
```console
$ nix-build
```
or if you have a flakes-enabled nix:
$ nix build
```console
$ nix build
```
This will build `defaultPackage` attribute defined in the `flake.nix`
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.
$ 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
variables are set up so that those dependencies can be found:
$ nix-shell
```console
$ nix-shell
```
To build Nix itself in this shell:
[nix-shell]$ ./bootstrap.sh
[nix-shell]$ ./configure $configureFlags
[nix-shell]$ make -j $NIX_BUILD_CORES
```console
[nix-shell]$ ./bootstrap.sh
[nix-shell]$ ./configure $configureFlags
[nix-shell]$ make -j $NIX_BUILD_CORES
```
To install it in `$(pwd)/inst` and test it:
[nix-shell]$ make install
[nix-shell]$ make installcheck
[nix-shell]$ ./inst/bin/nix --version
nix (Nix) 2.4
```console
[nix-shell]$ make install
[nix-shell]$ make installcheck
[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:
$ nix develop
```console
$ nix develop
```

View file

@ -3,16 +3,20 @@
After unpacking or checking out the Nix sources, issue the following
commands:
$ ./configure options...
$ make
$ make install
```console
$ ./configure options...
$ make
$ make install
```
Nix requires GNU Make so you may need to invoke `gmake` instead.
When building from the Git repository, these should be preceded by the
command:
$ ./bootstrap.sh
```console
$ ./bootstrap.sh
```
The installation path can be specified by passing the `--prefix=prefix`
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
this:
source prefix/etc/profile.d/nix.sh
```bash
source prefix/etc/profile.d/nix.sh
```
# `NIX_SSL_CERT_FILE`
@ -23,13 +25,17 @@ and use its own certificate bundle.
Set the environment variable and install Nix
$ export NIX_SSL_CERT_FILE=/etc/ssl/my-certificate-bundle.crt
$ sh <(curl -L https://nixos.org/nix/install)
```console
$ 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`,
`/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**
>
@ -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
service, then restart it:
$ sudo launchctl setenv NIX_SSL_CERT_FILE /etc/ssl/my-certificate-bundle.crt
$ sudo launchctl kickstart -k system/org.nixos.nix-daemon
```console
$ 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

View file

@ -3,8 +3,8 @@
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:
```
$ sh <(curl -L https://nixos.org/nix/install)
```console
$ sh <(curl -L https://nixos.org/nix/install)
```
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:
```
sh <(curl -L https://nixos.org/nix/install) --no-daemon
```console
$ sh <(curl -L https://nixos.org/nix/install) --no-daemon
```
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
manually create `/nix` first as root, e.g.:
$ mkdir /nix
$ chown alice /nix
```console
$ mkdir /nix
$ chown alice /nix
```
The install script will modify the first writable file from amongst
`.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:
$ rm -rf /nix
```console
$ rm -rf /nix
```
# Multi User Installation
@ -53,7 +57,9 @@ service for the Nix daemon.
You can instruct the installer to perform a multi-user installation on
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
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:
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:
sudo systemctl stop nix-daemon.socket
sudo systemctl stop nix-daemon.service
sudo systemctl disable nix-daemon.socket
sudo systemctl disable nix-daemon.service
sudo systemctl daemon-reload
# If you are on macOS, you will need to run:
sudo launchctl unload /Library/LaunchDaemons/org.nixos.nix-daemon.plist
sudo rm /Library/LaunchDaemons/org.nixos.nix-daemon.plist
```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:
sudo systemctl stop nix-daemon.socket
sudo systemctl stop nix-daemon.service
sudo systemctl disable nix-daemon.socket
sudo systemctl disable nix-daemon.service
sudo systemctl daemon-reload
# If you are on macOS, you will need to run:
sudo launchctl unload /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`,
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"
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
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
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
@ -221,11 +233,15 @@ as a helpful reference if you run into trouble.
`apfs.util` to trigger creation (not deletion) of new entries
without a reboot:
alice$ /System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util -B
```console
alice$ /System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util -B
```
3. Create the new APFS volume with diskutil:
alice$ sudo diskutil apfs addVolume diskX APFS 'Nix Store' -mountpoint /nix
```console
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
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
installation script:
```
sh <(curl -L https://nixos.org/nix/install)
```console
$ sh <(curl -L https://nixos.org/nix/install)
```
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`
inside the binary tarball:
alice$ cd /tmp
alice$ tar xfj nix-1.8-x86_64-darwin.tar.bz2
alice$ cd nix-1.8-x86_64-darwin
alice$ ./install
```console
alice$ cd /tmp
alice$ tar xfj nix-1.8-x86_64-darwin.tar.bz2
alice$ cd nix-1.8-x86_64-darwin
alice$ ./install
```
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

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
as follows:
$ 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)" \
nixbld$n; done
```console
$ 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)" \
nixbld$n; done
```
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
@ -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
follows (as `root`):
$ nix-daemon
```console
$ nix-daemon
```
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
`daemon`. So you should put a line like
export NIX_REMOTE=daemon
```console
export NIX_REMOTE=daemon
```
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
`nix-users`, do
$ chgrp nix-users /nix/var/nix/daemon-socket
$ chmod ug=rwx,o= /nix/var/nix/daemon-socket
```console
$ 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
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
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
[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
old version:
$ nix-env --upgrade some-packages
$ nix-env --rollback
```console
$ nix-env --upgrade some-packages
$ nix-env --rollback
```
## Garbage collection
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
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
_garbage collector_:
$ nix-collect-garbage
```console
$ nix-collect-garbage
```
This deletes all packages that arent in use by any user profile or by
a currently running program.
@ -115,7 +121,9 @@ each other in the Nix store.
Nix expressions generally describe how to build a package from
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
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
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
the package:
[nix-shell]$ tar xf $src
[nix-shell]$ cd pan-*
[nix-shell]$ ./configure
[nix-shell]$ make
[nix-shell]$ ./pan/gui/pan
```console
[nix-shell]$ tar xf $src
[nix-shell]$ cd pan-*
[nix-shell]$ ./configure
[nix-shell]$ make
[nix-shell]$ ./pan/gui/pan
```
## 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
as follows:
$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable
$ nix-channel --update
```console
$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable
$ nix-channel --update
```
> **Note**
>
@ -44,14 +46,16 @@ as follows:
You can view the set of available packages in Nixpkgs:
$ nix-env -qa
aterm-2.2
bash-3.0
binutils-2.15
bison-1.875d
blackdown-1.4.2
bzip2-1.0.2
```console
$ nix-env -qa
aterm-2.2
bash-3.0
binutils-2.15
bison-1.875d
blackdown-1.4.2
bzip2-1.0.2
```
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
@ -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
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
Nixpkgs.
You can select specific packages by name:
$ nix-env -qa firefox
firefox-34.0.5
firefox-with-plugins-34.0.5
```console
$ nix-env -qa firefox
firefox-34.0.5
firefox-with-plugins-34.0.5
```
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.,
whether they are installed into the user environment and/or present in
the system:
$ nix-env -qas
-PS bash-3.0
--S binutils-2.15
IPS bison-1.875d
```console
$ nix-env -qas
-PS bash-3.0
--S binutils-2.15
IPS bison-1.875d
```
The first character (`I`) indicates whether the package is installed in
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,
$ nix-env -i subversion
```console
$ nix-env -i subversion
```
will install the package called `subversion` (which is, of course, the
[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:
$ 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
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
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:
$ nix-env -u
```console
$ nix-env -u
```
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
upgraded by `nix-env -u`, you can do
$ nix-env -u --dry-run
(dry run; not doing anything)
upgrading `libxslt-1.1.0' to `libxslt-1.1.10'
upgrading `graphviz-1.10' to `graphviz-1.12'
upgrading `coreutils-5.0' to `coreutils-5.2.1'
```console
$ nix-env -u --dry-run
(dry run; not doing anything)
upgrading `libxslt-1.1.0' to `libxslt-1.1.10'
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
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
whatever port you like:
$ nix-serve -p 8080
```console
$ nix-serve -p 8080
```
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:
@ -28,7 +34,9 @@ which should print something like:
On the client side, you can tell Nix to use your binary cache using
`--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
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.,
$ 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
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
--remove`:
$ nix-channel --remove nixpkgs
```console
$ nix-channel --remove nixpkgs
```
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
(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,
you can then say
$ nix-env -u
```console
$ nix-env -u
```
to upgrade all packages in your profile to the latest versions available
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:
$ nix-env --delete-generations old
```console
$ nix-env --delete-generations old
```
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
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.
After removing appropriate old generations you can run the garbage
collector as follows:
$ nix-store --gc
```console
$ nix-store --gc
```
The behaviour of the gargage collector is affected by the
`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
deleted:
$ nix-store --gc --print-dead
```console
$ nix-store --gc --print-dead
```
Likewise, the option `--print-live` will show the paths that *wont* be
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
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.

View file

@ -5,7 +5,9 @@ are symlinks in the directory `prefix/nix/var/nix/gcroots`. For
instance, the following command makes the path
`/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
`/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
$ /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
`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
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.
@ -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,
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
Subversion.
@ -57,11 +63,13 @@ Subversion.
Generations are grouped together into *profiles* so that different users
dont interfere with each other if they dont want to. For example:
$ 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 -> default-43-link
```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 -> default-43-link
```
This shows a profile called `default`. The file `default` itself is
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
$ nix-env --rollback
```console
$ nix-env --rollback
```
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
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
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
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
command `nix-env --switch-profile`:
$ nix-env --switch-profile /nix/var/nix/profiles/my-profile
$ nix-env --switch-profile /nix/var/nix/profiles/default
```console
$ nix-env --switch-profile /nix/var/nix/profiles/my-profile
$ nix-env --switch-profile /nix/var/nix/profiles/default
```
These commands switch to the `my-profile` and default profile,
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
(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.

View file

@ -51,25 +51,27 @@ cache's documentation.
Your bucket will need the following bucket policy:
{
"Id": "DirectReads",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowDirectReads",
"Action": [
"s3:GetObject",
"s3:GetBucketLocation"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::example-nix-cache",
"arn:aws:s3:::example-nix-cache/*"
],
"Principal": "*"
}
]
}
```json
{
"Id": "DirectReads",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowDirectReads",
"Action": [
"s3:GetObject",
"s3:GetBucketLocation"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::example-nix-cache",
"arn:aws:s3:::example-nix-cache/*"
],
"Principal": "*"
}
]
}
```
## Authenticated Reads to your S3 binary cache
@ -101,35 +103,43 @@ for authenticating requests to Amazon S3.
Your account will need the following IAM policy to upload to the cache:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "UploadToCache",
"Effect": "Allow",
"Action": [
"s3:AbortMultipartUpload",
"s3:GetBucketLocation",
"s3:GetObject",
"s3:ListBucket",
"s3:ListBucketMultipartUploads",
"s3:ListMultipartUploadParts",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::example-nix-cache",
"arn:aws:s3:::example-nix-cache/*"
]
}
"Sid": "UploadToCache",
"Effect": "Allow",
"Action": [
"s3:AbortMultipartUpload",
"s3:GetBucketLocation",
"s3:GetObject",
"s3:ListBucket",
"s3:ListBucketMultipartUploads",
"s3:ListMultipartUploadParts",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::example-nix-cache",
"arn:aws:s3:::example-nix-cache/*"
]
}
]
}
```
## Examples
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:
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
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
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
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
$ 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
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
`configuration.nix`:
nix.sshServe.enable = true;
nix.sshServe.keys = [ "ssh-dss AAAAB3NzaC1k... bob@example.org" ];
```nix
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
connect.

View file

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

View file

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

View file

@ -49,7 +49,8 @@ struct NarAccessor : public FSAccessor
: 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(), '/');
while (parents.size() > level) parents.pop();