diff --git a/.dir-locals.el b/.dir-locals.el index 8b21d4e40..a2d1dc48d 100644 --- a/.dir-locals.el +++ b/.dir-locals.el @@ -1,6 +1,7 @@ ((c++-mode . ( (c-file-style . "k&r") (c-basic-offset . 4) + (c-block-comment-prefix . " ") (indent-tabs-mode . nil) (tab-width . 4) (show-trailing-whitespace . t) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7755466a0..829111b67 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,5 +10,8 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - - uses: cachix/install-nix-action@v10 - - run: nix-build release.nix --arg nix '{ outPath = ./.; revCount = 123; shortRev = "abcdefgh"; }' --arg systems '[ builtins.currentSystem ]' -A installerScript -A perlBindings + with: + fetch-depth: 0 + - uses: cachix/install-nix-action@v11 + #- run: nix flake check + - run: nix-build -A checks.$(if [[ `uname` = Linux ]]; then echo x86_64-linux; else echo x86_64-darwin; fi) diff --git a/.gitignore b/.gitignore index 983026570..b087cd8d5 100644 --- a/.gitignore +++ b/.gitignore @@ -5,31 +5,22 @@ perl/Makefile.config /aclocal.m4 /autom4te.cache /precompiled-headers.h.gch -/precompiled-headers.h.pch /config.* /configure /stamp-h1 /svn-revision /libtool -/corepkgs/config.nix - -# /corepkgs/channels/ -/corepkgs/channels/unpack.sh - -# /corepkgs/nar/ -/corepkgs/nar/nar.sh -/corepkgs/nar/unnar.sh - # /doc/manual/ -/doc/manual/manual.html -/doc/manual/manual.xmli -/doc/manual/manual.pdf -/doc/manual/manual.is-valid /doc/manual/*.1 /doc/manual/*.5 /doc/manual/*.8 -/doc/manual/version.txt +/doc/manual/nix.json +/doc/manual/conf-file.json +/doc/manual/builtins.json +/doc/manual/src/command-ref/nix.md +/doc/manual/src/command-ref/conf-file.md +/doc/manual/src/expressions/builtins.md # /scripts/ /scripts/nix-profile.sh @@ -106,7 +97,7 @@ perl/Makefile.config /src/resolve-system-dependencies/resolve-system-dependencies -inst/ +outputs/ *.a *.o @@ -125,4 +116,10 @@ GRTAGS GSYMS GTAGS +# ccls +/.ccls-cache + +# auto-generated compilation database +compile_commands.json + nix-rust/target diff --git a/.version b/.version index 7208c2182..f398a2061 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -2.4 \ No newline at end of file +3.0 \ No newline at end of file diff --git a/Makefile b/Makefile index 332e6e971..c50d2c40f 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,7 @@ makefiles = \ src/resolve-system-dependencies/local.mk \ scripts/local.mk \ corepkgs/local.mk \ + misc/bash/local.mk \ misc/systemd/local.mk \ misc/launchd/local.mk \ misc/upstart/local.mk \ @@ -25,7 +26,7 @@ OPTIMIZE = 1 ifeq ($(OPTIMIZE), 1) GLOBAL_CXXFLAGS += -O3 else - GLOBAL_CXXFLAGS += -O0 + GLOBAL_CXXFLAGS += -O0 -U_FORTIFY_SOURCE endif include mk/lib.mk diff --git a/Makefile.config.in b/Makefile.config.in index b632444e8..3845b3be0 100644 --- a/Makefile.config.in +++ b/Makefile.config.in @@ -19,6 +19,7 @@ LIBLZMA_LIBS = @LIBLZMA_LIBS@ OPENSSL_LIBS = @OPENSSL_LIBS@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_VERSION = @PACKAGE_VERSION@ +SHELL = @bash@ SODIUM_LIBS = @SODIUM_LIBS@ SQLITE3_LIBS = @SQLITE3_LIBS@ bash = @bash@ @@ -40,5 +41,3 @@ sandbox_shell = @sandbox_shell@ storedir = @storedir@ sysconfdir = @sysconfdir@ system = @system@ -xmllint = @xmllint@ -xsltproc = @xsltproc@ diff --git a/README.md b/README.md index a1588284d..11fe5f932 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,10 @@ for more details. ## Installation -On Linux and macOS the easiest way to Install Nix is to run the following shell command +On Linux and macOS the easiest way to install Nix is to run the following shell command (as a user other than root): -``` +```console $ curl -L https://nixos.org/nix/install | sh ``` @@ -20,27 +20,8 @@ Information on additional installation methods is available on the [Nix download ## Building And Developing -### Building Nix - -You can build Nix using one of the targets provided by [release.nix](./release.nix): - -``` -$ nix-build ./release.nix -A build.aarch64-linux -$ nix-build ./release.nix -A build.x86_64-darwin -$ nix-build ./release.nix -A build.i686-linux -$ nix-build ./release.nix -A build.x86_64-linux -``` - -### Development Environment - -You can use the provided `shell.nix` to get a working development environment: - -``` -$ nix-shell -$ ./bootstrap.sh -$ ./configure -$ make -``` +See our [Hacking guide](https://hydra.nixos.org/job/nix/master/build.x86_64-linux/latest/download-by-type/doc/manual/hacking.html) in our manual for instruction on how to +build nix from source with nix-build or how to get a development environment. ## Additional Resources diff --git a/configure.ac b/configure.ac index c3007b4b6..eecb107d7 100644 --- a/configure.ac +++ b/configure.ac @@ -117,12 +117,11 @@ fi ]) NEED_PROG(bash, bash) -AC_PATH_PROG(xmllint, xmllint, false) -AC_PATH_PROG(xsltproc, xsltproc, false) AC_PATH_PROG(flex, flex, false) AC_PATH_PROG(bison, bison, false) AC_PATH_PROG(dot, dot) AC_PATH_PROG(lsof, lsof, lsof) +NEED_PROG(jq, jq) AC_SUBST(coreutils, [$(dirname $(type -p cat))]) diff --git a/corepkgs/config.nix.in b/corepkgs/config.nix.in deleted file mode 100644 index cb9945944..000000000 --- a/corepkgs/config.nix.in +++ /dev/null @@ -1,13 +0,0 @@ -# FIXME: remove this file? -let - fromEnv = var: def: - let val = builtins.getEnv var; in - if val != "" then val else def; -in rec { - nixBinDir = fromEnv "NIX_BIN_DIR" "@bindir@"; - nixPrefix = "@prefix@"; - nixLibexecDir = fromEnv "NIX_LIBEXEC_DIR" "@libexecdir@"; - nixLocalstateDir = "@localstatedir@"; - nixSysconfDir = "@sysconfdir@"; - nixStoreDir = fromEnv "NIX_STORE_DIR" "@storedir@"; -} diff --git a/corepkgs/local.mk b/corepkgs/local.mk index 2c72d3a31..0bc91cfab 100644 --- a/corepkgs/local.mk +++ b/corepkgs/local.mk @@ -1,8 +1,4 @@ corepkgs_FILES = \ - unpack-channel.nix \ - derivation.nix \ fetchurl.nix -$(foreach file,config.nix $(corepkgs_FILES),$(eval $(call install-data-in,$(d)/$(file),$(datadir)/nix/corepkgs))) - -template-files += $(d)/config.nix +$(foreach file,$(corepkgs_FILES),$(eval $(call install-data-in,$(d)/$(file),$(datadir)/nix/corepkgs))) diff --git a/default.nix b/default.nix new file mode 100644 index 000000000..71d1a80ad --- /dev/null +++ b/default.nix @@ -0,0 +1,3 @@ +(import (fetchTarball https://github.com/edolstra/flake-compat/archive/master.tar.gz) { + src = ./.; +}).defaultNix diff --git a/doc/manual/advanced-topics/advanced-topics.xml b/doc/manual/advanced-topics/advanced-topics.xml deleted file mode 100644 index 871b7eb1d..000000000 --- a/doc/manual/advanced-topics/advanced-topics.xml +++ /dev/null @@ -1,14 +0,0 @@ - - -Advanced Topics - - - - - - - diff --git a/doc/manual/advanced-topics/cores-vs-jobs.xml b/doc/manual/advanced-topics/cores-vs-jobs.xml deleted file mode 100644 index 4d58ac7c5..000000000 --- a/doc/manual/advanced-topics/cores-vs-jobs.xml +++ /dev/null @@ -1,121 +0,0 @@ - - -Tuning Cores and Jobs - -Nix has two relevant settings with regards to how your CPU cores -will be utilized: and -. This chapter will talk about what -they are, how they interact, and their configuration trade-offs. - - - - - - Dictates how many separate derivations will be built at the same - time. If you set this to zero, the local machine will do no - builds. Nix will still substitute from binary caches, and build - remotely if remote builders are configured. - - - - - - Suggests how many cores each derivation should use. Similar to - make -j. - - - - -The setting determines the value of -NIX_BUILD_CORES. NIX_BUILD_CORES is equal -to , unless -equals 0, in which case NIX_BUILD_CORES -will be the total number of cores in the system. - -The maximum number of consumed cores is a simple multiplication, - * NIX_BUILD_CORES. - -The balance on how to set these two independent variables depends -upon each builder's workload and hardware. Here are a few example -scenarios on a machine with 24 cores: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Balancing 24 Build Cores
NIX_BUILD_CORESMaximum ProcessesResult
1242424 - One derivation will be built at a time, each one can use 24 - cores. Undersold if a job can’t use 24 cores. -
46624 - Four derivations will be built at once, each given access to - six cores. -
126672 - 12 derivations will be built at once, each given access to six - cores. This configuration is over-sold. If all 12 derivations - being built simultaneously try to use all six cores, the - machine's performance will be degraded due to extensive context - switching between the 12 builds. -
241124 - 24 derivations can build at the same time, each using a single - core. Never oversold, but derivations which require many cores - will be very slow to compile. -
24024576 - 24 derivations can build at the same time, each using all the - available cores of the machine. Very likely to be oversold, - and very likely to suffer context switches. -
- -It is up to the derivations' build script to respect -host's requested cores-per-build by following the value of the -NIX_BUILD_CORES environment variable. - -
diff --git a/doc/manual/advanced-topics/diff-hook.xml b/doc/manual/advanced-topics/diff-hook.xml deleted file mode 100644 index f01ab71b3..000000000 --- a/doc/manual/advanced-topics/diff-hook.xml +++ /dev/null @@ -1,205 +0,0 @@ - - -Verifying Build Reproducibility with <option linkend="conf-diff-hook">diff-hook</option> - -Check build reproducibility by running builds multiple times -and comparing their results. - -Specify a program with Nix's to -compare build results when two builds produce different results. Note: -this hook is only executed if the results are not the same, this hook -is not used 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 - ''; -} - - -Additionally, nix.conf contains: - - -diff-hook = /etc/nix/my-diff-hook -run-diff-hook = true - - -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" - - - - -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 built. - -
- - Spot-Checking Build Determinism - - - - Verify a path which already exists in the Nix store by passing - 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 - - - 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 - - -In the Nix daemon's log, we will now see: - -For derivation /nix/store/cgl13lbj1w368r5z8gywipl1ifli7dhk-unstable.drv: -1c1 -< 8108 ---- -> 30204 - - - - Using with - 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' - - - In particular, notice the - /nix/store/krpqk0l9ib0ibi1d2w52z293zw455cap-unstable.check - output. Nix has copied the build results to that directory where you - can examine it. - - - <literal>.check</literal> paths are not registered store paths - - Check paths are not protected against garbage collection, - and this path will be deleted on the next garbage collection. - - The path is guaranteed to be alive for the duration of - 's execution, but may be deleted - any time after. - - If the comparison is performed as part of automated tooling, - please use the diff-hook or author your tooling to handle the case - where the build was not deterministic and also a check path does - not exist. - - - - is only usable if the derivation has - been built on the system 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 - - - Run the build without , and then try with - again. - -
- -
- - Automatic and Optionally Enforced Determinism Verification - - - - Automatically verify every build at build time by executing the - build multiple times. - - - - Setting and - in your - nix.conf permits the automated verification - of every build Nix performs. - - - - The following configuration will run each build three times, and - will require the build to be deterministic: - - -enforce-determinism = true -repeat = 2 - - - - - Setting to false as in - the following configuration will run the build multiple times, - execute the build hook, but will allow the build to succeed even - if it does not build reproducibly: - - -enforce-determinism = false -repeat = 1 - - - - - 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 - - -
-
diff --git a/doc/manual/advanced-topics/distributed-builds.xml b/doc/manual/advanced-topics/distributed-builds.xml deleted file mode 100644 index 9ac4a92cd..000000000 --- a/doc/manual/advanced-topics/distributed-builds.xml +++ /dev/null @@ -1,190 +0,0 @@ - - -Remote Builds - -Nix supports remote builds, where a local Nix installation can -forward Nix builds to other machines. This allows multiple builds to -be performed in parallel and allows Nix to perform multi-platform -builds in a semi-transparent way. For instance, if you perform a -build for a x86_64-darwin on an -i686-linux machine, Nix can automatically forward -the build to a x86_64-darwin machine, if -available. - -To forward a build to a remote machine, it’s 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 - - -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 - - -Since builds should be non-interactive, the key should not have a -passphrase. Alternatively, you can load identities ahead of time into -ssh-agent or gpg-agent. - -If you get the error - - -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. - -If you are building via the Nix daemon, it is the Nix -daemon user account (that is, root) that should -have SSH access to the remote machine. If you can’t or don’t want to -configure root to be able to access to remote -machine, you can use a private Nix store instead by passing -e.g. --store ~/my-nix. - -The list of remote machines can be specified on the command line -or in 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 - -$ 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. - - - --builders 'ssh://mac x86_64-darwin ; ssh://beastie x86_64-freebsd' - - - -Each machine specification consists of the following elements, -separated by spaces. Only the first element is required. -To leave a field at its default, set it to -. - - - - The URI of the remote store in the format - ssh://[username@]hostname, - e.g. ssh://nix@mac or - ssh://mac. For backward compatibility, - ssh:// may be omitted. The hostname may be an - alias defined in your - ~/.ssh/config. - - A comma-separated list of Nix platform type - identifiers, such as x86_64-darwin. It is - possible for a machine to support multiple platform types, e.g., - i686-linux,x86_64-linux. If omitted, this - defaults to the local platform type. - - The SSH identity file to be used to log in to the - remote machine. If omitted, SSH will use its regular - identities. - - The maximum number of builds that Nix will execute - in parallel on the machine. Typically this should be equal to the - number of CPU cores. For instance, the machine - itchy in the example will execute up to 8 builds - in parallel. - - The “speed factor”, indicating the relative speed of - the machine. If there are multiple machines of the right type, Nix - will prefer the fastest, taking load into account. - - A comma-separated list of supported - features. If a derivation has the - requiredSystemFeatures attribute, then Nix will - only perform the derivation on a machine that has the specified - features. For instance, the attribute - - -requiredSystemFeatures = [ "kvm" ]; - - - will cause the build to be performed on a machine that has the - kvm feature. - - A comma-separated list of mandatory - features. A machine will only be used to build a - derivation if all of the machine’s mandatory features appear in the - derivation’s requiredSystemFeatures - attribute.. - - - -For example, the machine specification - - -nix@scratchy.labs.cs.uu.nl i686-linux /home/nix/.ssh/id_scratchy_auto 8 1 kvm -nix@itchy.labs.cs.uu.nl i686-linux /home/nix/.ssh/id_scratchy_auto 8 2 -nix@poochie.labs.cs.uu.nl i686-linux /home/nix/.ssh/id_scratchy_auto 1 2 kvm benchmark - - -specifies several machines that can perform -i686-linux builds. However, -poochie will only do builds that have the attribute - - -requiredSystemFeatures = [ "benchmark" ]; - - -or - - -requiredSystemFeatures = [ "benchmark" "kvm" ]; - - -itchy cannot do builds that require -kvm, but scratchy does support -such builds. For regular builds, itchy will be -preferred over scratchy because it has a higher -speed factor. - -Remote builders can also be configured in -nix.conf, e.g. - - -builders = ssh://mac x86_64-darwin ; ssh://beastie x86_64-freebsd - - -Finally, remote builders can be configured in a separate configuration -file included in via the syntax -@file. For example, - - -builders = @/etc/nix/machines - - -causes the list of machines in /etc/nix/machines -to be included. (This is the default.) - -If you want the builders to use caches, you likely want to set -the option builders-use-substitutes -in your local nix.conf. - -To build only on remote builders and disable building on the local machine, -you can use the option . - - diff --git a/doc/manual/advanced-topics/post-build-hook.xml b/doc/manual/advanced-topics/post-build-hook.xml deleted file mode 100644 index 6cc286ee1..000000000 --- a/doc/manual/advanced-topics/post-build-hook.xml +++ /dev/null @@ -1,160 +0,0 @@ - - -Using the <option linkend="conf-post-build-hook">post-build-hook</option> -Uploading to an S3-compatible binary cache after each build - - -
- Implementation Caveats - Here we use the post-build hook to upload to a binary cache. - This is a simple and working example, but it is not suitable for all - use cases. - - The post build hook program runs after each executed build, - and blocks the build loop. The build loop exits if the hook program - fails. - - Concretely, this implementation will make Nix slow or unusable - when the internet is slow or unreliable. - - A more advanced implementation might pass the store paths to a - user-supplied daemon or queue for processing the store paths outside - of the build loop. -
- -
- Prerequisites - - - This tutorial assumes you have configured an S3-compatible binary cache - according to the instructions at - , and - that the root user's default AWS profile can - upload to the bucket. - -
- -
- Set up a Signing Key - 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= - - -Then, add the public key and the cache URL to your -nix.conf's -and like: - - -substituters = https://cache.nixos.org/ s3://example-nix-cache -trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= example-nix-cache-1:1/cKDz3QCCOmwcztD2eV6Coggp6rqc9DGjWv7C0G+rM= - - -We will restart the Nix daemon in a later step. -
- -
- Implementing the build hook - 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 - - - - Should <literal>$OUT_PATHS</literal> be quoted? - - The $OUT_PATHS variable is a space-separated - list of Nix store paths. In this case, we expect and want the - shell to perform word splitting to make each output path its - own argument to nix sign-paths. Nix guarantees - the paths will not contain any spaces, however a store path - might contain glob characters. The set -f - disables globbing in the shell. - - - - Then make sure the hook program is executable by the root user: - -# chmod +x /etc/nix/upload-to-cache.sh - -
- -
- Updating Nix Configuration - - Edit /etc/nix/nix.conf to run our hook, - by adding the following configuration snippet at the end: - - -post-build-hook = /etc/nix/upload-to-cache.sh - - -Then, restart the nix-daemon. -
- -
- Testing - - 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 - - - Then delete the path from the store, and try substituting it from the binary cache: - -$ 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 - -
-
- Conclusion - - We now have a Nix installation configured to automatically sign and - upload every local build to a remote binary cache. - - - - Before deploying this to production, be sure to consider the - implementation caveats in . - -
-
diff --git a/doc/manual/book.toml b/doc/manual/book.toml new file mode 100644 index 000000000..fee41dfb3 --- /dev/null +++ b/doc/manual/book.toml @@ -0,0 +1,2 @@ +[output.html] +additional-css = ["custom.css"] diff --git a/doc/manual/command-ref/command-ref.xml b/doc/manual/command-ref/command-ref.xml deleted file mode 100644 index cfad9b7d7..000000000 --- a/doc/manual/command-ref/command-ref.xml +++ /dev/null @@ -1,20 +0,0 @@ - - -Command Reference - - -This section lists commands and options that you can use when you -work with Nix. - - - - - - - - - diff --git a/doc/manual/command-ref/conf-file.xml b/doc/manual/command-ref/conf-file.xml index 1fa74a143..d0f1b09ca 100644 --- a/doc/manual/command-ref/conf-file.xml +++ b/doc/manual/command-ref/conf-file.xml @@ -373,16 +373,15 @@ false. hashed-mirrors A list of web servers used by - builtins.fetchurl to obtain files by - hash. The default is - http://tarballs.nixos.org/. Given a hash type - ht and a base-16 hash + builtins.fetchurl to obtain files by hash. + Given a hash type ht and a base-16 hash h, Nix will try to download the file from hashed-mirror/ht/h. This allows files to be downloaded even if they have disappeared - from their original URI. For example, given the default mirror - http://tarballs.nixos.org/, when building the derivation + from their original URI. For example, given the hashed mirror + http://tarballs.example.com/, when building the + derivation builtins.fetchurl { @@ -392,7 +391,7 @@ builtins.fetchurl { Nix will attempt to download this file from - http://tarballs.nixos.org/sha256/2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae + http://tarballs.example.com/sha256/2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae first. If it is not available there, if will try the original URI. diff --git a/doc/manual/command-ref/env-common.xml b/doc/manual/command-ref/env-common.xml deleted file mode 100644 index 8466cc463..000000000 --- a/doc/manual/command-ref/env-common.xml +++ /dev/null @@ -1,209 +0,0 @@ - - -Common Environment Variables - - -Most Nix commands interpret the following environment variables: - - - -IN_NIX_SHELL - - Indicator that tells if the current environment was set up by - nix-shell. Since Nix 2.0 the values are - "pure" and "impure" - - - -NIX_PATH - - - - A colon-separated list of directories used to look up Nix - expressions enclosed in angle brackets (i.e., - <path>). For - instance, the value - - -/home/eelco/Dev:/etc/nixos - - will cause Nix to look for paths relative to - /home/eelco/Dev and - /etc/nixos, in this order. It is also - possible to match paths against a prefix. For example, the value - - -nixpkgs=/home/eelco/Dev/nixpkgs-branch:/etc/nixos - - will cause Nix to search for - <nixpkgs/path> in - /home/eelco/Dev/nixpkgs-branch/path - and - /etc/nixos/nixpkgs/path. - - If a path in the Nix search path starts with - http:// or https://, it is - interpreted as the URL of a tarball that will be downloaded and - unpacked to a temporary location. The tarball must consist of a - single top-level directory. For example, setting - NIX_PATH to - - -nixpkgs=https://github.com/NixOS/nixpkgs/archive/nixos-15.09.tar.gz - - tells Nix to download the latest revision in the Nixpkgs/NixOS - 15.09 channel. - - A following shorthand can be used to refer to the official channels: - - nixpkgs=channel:nixos-15.09 - - - The search path can be extended using the option, which takes precedence over - NIX_PATH. - - - - -NIX_IGNORE_SYMLINK_STORE - - - - Normally, the Nix store directory (typically - /nix/store) is not allowed to contain any - symlink components. This is to prevent “impure” builds. Builders - sometimes “canonicalise” paths by resolving all symlink components. - Thus, builds on different machines (with - /nix/store resolving to different locations) - could yield different results. This is generally not a problem, - except when builds are deployed to machines where - /nix/store resolves differently. If you are - sure that you’re not going to do that, you can set - NIX_IGNORE_SYMLINK_STORE to 1. - - Note that if you’re symlinking the Nix store so that you can - put it on another file system than the root file system, on Linux - you’re better off using bind mount points, e.g., - - -$ mkdir /nix -$ mount -o bind /mnt/otherdisk/nix /nix - - Consult the mount - 8 manual page for details. - - - - - - -NIX_STORE_DIR - - Overrides the location of the Nix store (default - prefix/store). - - - - -NIX_DATA_DIR - - Overrides the location of the Nix static data - directory (default - prefix/share). - - - - -NIX_LOG_DIR - - Overrides the location of the Nix log directory - (default prefix/var/log/nix). - - - - -NIX_STATE_DIR - - Overrides the location of the Nix state directory - (default prefix/var/nix). - - - - -NIX_CONF_DIR - - Overrides the location of the system Nix configuration - directory (default - prefix/etc/nix). - - - -NIX_USER_CONF_FILES - - Overrides the location of the user Nix configuration files - to load from (defaults to the XDG spec locations). The variable is treated - as a list separated by the : token. - - - -TMPDIR - - Use the specified directory to store temporary - files. In particular, this includes temporary build directories; - these can take up substantial amounts of disk space. The default is - /tmp. - - - - -NIX_REMOTE - - This variable should be set to - daemon if you want to use the Nix daemon to - execute Nix operations. This is necessary in multi-user Nix installations. - If the Nix daemon's Unix socket is at some non-standard path, - this variable should be set to unix://path/to/socket. - Otherwise, it should be left unset. - - - - -NIX_SHOW_STATS - - If set to 1, Nix will print some - evaluation statistics, such as the number of values - allocated. - - - - -NIX_COUNT_CALLS - - If set to 1, Nix will print how - often functions were called during Nix expression evaluation. This - is useful for profiling your Nix expressions. - - - - -GC_INITIAL_HEAP_SIZE - - If Nix has been configured to use the Boehm garbage - collector, this variable sets the initial size of the heap in bytes. - It defaults to 384 MiB. Setting it to a low value reduces memory - consumption, but will increase runtime due to the overhead of - garbage collection. - - - - - - - - diff --git a/doc/manual/command-ref/files.xml b/doc/manual/command-ref/files.xml deleted file mode 100644 index 7bbc96e89..000000000 --- a/doc/manual/command-ref/files.xml +++ /dev/null @@ -1,14 +0,0 @@ - - -Files - -This section lists configuration files that you can use when you -work with Nix. - - - - \ No newline at end of file diff --git a/doc/manual/command-ref/main-commands.xml b/doc/manual/command-ref/main-commands.xml deleted file mode 100644 index 0f4169243..000000000 --- a/doc/manual/command-ref/main-commands.xml +++ /dev/null @@ -1,17 +0,0 @@ - - -Main Commands - -This section lists commands and options that you can use when you -work with Nix. - - - - - - - \ No newline at end of file diff --git a/doc/manual/command-ref/nix-build.xml b/doc/manual/command-ref/nix-build.xml deleted file mode 100644 index 886d25910..000000000 --- a/doc/manual/command-ref/nix-build.xml +++ /dev/null @@ -1,190 +0,0 @@ - - - - nix-build - 1 - Nix - - - - - nix-build - build a Nix expression - - - - - nix-build - - name value - name value - - - - - - attrPath - - - - - - - - - outlink - - paths - - - -Description - -The nix-build command builds the derivations -described by the Nix expressions in paths. -If the build succeeds, it places a symlink to the result in the -current directory. The symlink is called result. -If there are multiple Nix expressions, or the Nix expressions evaluate -to multiple derivations, multiple sequentially numbered symlinks are -created (result, result-2, -and so on). - -If no paths are specified, then -nix-build will use default.nix -in the current directory, if it exists. - -If an element of paths starts with -http:// or https://, it is -interpreted as the URL of a tarball that will be downloaded and -unpacked to a temporary location. The tarball must include a single -top-level directory containing at least a file named -default.nix. - -nix-build is essentially a wrapper around -nix-instantiate -(to translate a high-level Nix expression to a low-level store -derivation) and nix-store ---realise (to build the store derivation). - -The result of the build is automatically registered as -a root of the Nix garbage collector. This root disappears -automatically when the result symlink is deleted -or renamed. So don’t rename the symlink. - - - - -Options - -All options not listed here are passed to nix-store ---realise, except for and - / which are passed to -nix-instantiate. See -also . - - - - - - Do not create a symlink to the output path. Note - that as a result the output does not become a root of the garbage - collector, and so might be deleted by nix-store - --gc. - - - - - Show what store paths would be built or downloaded. - - - / - outlink - - Change the name of the symlink to the output path - created from result to - outlink. - - - - - -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 - -$ ls -l result -lrwxrwxrwx ... result -> /nix/store/d18hyl92g30l...-firefox-1.5.0.7 - -$ 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 - -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 outputs out, -bin and man, -nix-build will create symlinks -result, result-bin and -result-man. It’s also possible to build a specific -output: - -$ 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 - - - - -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 - - - - - - - - - diff --git a/doc/manual/command-ref/nix-channel.xml b/doc/manual/command-ref/nix-channel.xml deleted file mode 100644 index ebcf56aff..000000000 --- a/doc/manual/command-ref/nix-channel.xml +++ /dev/null @@ -1,181 +0,0 @@ - - - - nix-channel - 1 - Nix - - - - - nix-channel - manage Nix channels - - - - - nix-channel - - url name - name - - names - generation - - - - -Description - -A Nix channel is a mechanism that allows you to automatically -stay up-to-date with a set of pre-built Nix expressions. A Nix -channel is just a URL that points to a place containing a set of Nix -expressions. See also . - -To see the list of official NixOS channels, visit . - -This command has the following operations: - - - - url [name] - - Adds a channel named - name with URL - url to the list of subscribed channels. - If name is omitted, it defaults to the - last component of url, with the - suffixes -stable or - -unstable removed. - - - - name - - Removes the channel named - name from the list of subscribed - channels. - - - - - - Prints the names and URLs of all subscribed - channels on standard output. - - - - [names…] - - Downloads the Nix expressions of all subscribed - channels (or only those included in - names if specified) and makes them the - default for nix-env operations (by symlinking - them from the directory - ~/.nix-defexpr). - - - - [generation] - - Reverts the previous call to nix-channel - --update. Optionally, you can specify a specific channel - generation number to restore. - - - - - - - -Note that does not automatically perform -an update. - -The list of subscribed channels is stored in -~/.nix-channels. - - - -Examples - -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 - -You can revert channel updates using : - - -$ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version' -"14.04.527.0e935f1" - -$ nix-channel --rollback -switching from generation 483 to 482 - -$ nix-instantiate --eval -E '(import <nixpkgs> {}).lib.version' -"14.04.526.dbadfad" - - - - -Files - - - - /nix/var/nix/profiles/per-user/username/channels - - nix-channel uses a - nix-env profile to keep track of previous - versions of the subscribed channels. Every time you run - nix-channel --update, a new channel generation - (that is, a symlink to the channel Nix expressions in the Nix store) - is created. This enables nix-channel --rollback - to revert to previous versions. - - - - ~/.nix-defexpr/channels - - This is a symlink to - /nix/var/nix/profiles/per-user/username/channels. It - ensures that nix-env can find your channels. In - a multi-user installation, you may also have - ~/.nix-defexpr/channels_root, which links to - the channels of the root user. - - - - - - - -Channel format - -A channel URL should point to a directory containing the -following files: - - - - nixexprs.tar.xz - - A tarball containing Nix expressions and files - referenced by them (such as build scripts and patches). At the - top level, the tarball should contain a single directory. That - directory must contain a file default.nix - that serves as the channel’s “entry point”. - - - - - - - - diff --git a/doc/manual/command-ref/nix-collect-garbage.xml b/doc/manual/command-ref/nix-collect-garbage.xml deleted file mode 100644 index 43e068796..000000000 --- a/doc/manual/command-ref/nix-collect-garbage.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - nix-collect-garbage - 1 - Nix - - - - - nix-collect-garbage - delete unreachable store paths - - - - - nix-collect-garbage - - - period - bytes - - - - -Description - -The command nix-collect-garbage is mostly an -alias of nix-store ---gc, that is, it deletes all unreachable paths in -the Nix store to clean up your system. However, it provides two -additional options: (), -which deletes all old generations of all profiles in -/nix/var/nix/profiles by invoking -nix-env --delete-generations old on all profiles -(of course, this makes rollbacks to previous configurations -impossible); and - period, -where period is a value such as 30d, which deletes -all generations older than the specified number of days in all profiles -in /nix/var/nix/profiles (except for the generations -that were active at that point in time). - - - - -Example - -To delete from the Nix store everything that is not used by the -current generations of each profile, do - - -$ nix-collect-garbage -d - - - - - - diff --git a/doc/manual/command-ref/nix-copy-closure.xml b/doc/manual/command-ref/nix-copy-closure.xml deleted file mode 100644 index e6dcf180a..000000000 --- a/doc/manual/command-ref/nix-copy-closure.xml +++ /dev/null @@ -1,169 +0,0 @@ - - - - nix-copy-closure - 1 - Nix - - - - - nix-copy-closure - copy a closure to or from a remote machine via SSH - - - - - nix-copy-closure - - - - - - - - - - - - - - user@machine - - paths - - - - -Description - -nix-copy-closure gives you an easy and -efficient way to exchange software between machines. Given one or -more Nix store paths on the local -machine, nix-copy-closure computes the closure of -those paths (i.e. all their dependencies in the Nix store), and copies -all paths in the closure to the remote machine via the -ssh (Secure Shell) command. With the -, the direction is reversed: -the closure of paths on a remote machine is -copied to the Nix store on the local machine. - -This command is efficient because it only sends the store paths -that are missing on the target machine. - -Since nix-copy-closure calls -ssh, you may be asked to type in the appropriate -password or passphrase. In fact, you may be asked -twice because nix-copy-closure -currently connects twice to the remote machine, first to get the set -of paths missing on the target machine, and second to send the dump of -those paths. If this bothers you, use -ssh-agent. - - -Options - - - - - - Copy the closure of - paths from the local Nix store to the - Nix store on machine. This is the - default. - - - - - - Copy the closure of - paths from the Nix store on - machine to the local Nix - store. - - - - - - Enable compression of the SSH - connection. - - - - - - Also copy the outputs of store derivations - included in the closure. - - - - / - - Attempt to download missing paths on the target - machine using Nix’s substitute mechanism. Any paths that cannot - be substituted on the target are still copied normally from the - source. This is useful, for instance, if the connection between - the source and target machine is slow, but the connection between - the target machine and nixos.org (the default - binary cache server) is fast. - - - - - - Show verbose output. - - - - - - - - -Environment variables - - - - NIX_SSHOPTS - - Additional options to be passed to - ssh on the command line. - - - - - - - - -Examples - -Copy Firefox with all its dependencies to a remote machine: - - -$ 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 - - - - - - - - - - diff --git a/doc/manual/command-ref/nix-daemon.xml b/doc/manual/command-ref/nix-daemon.xml deleted file mode 100644 index a2161f033..000000000 --- a/doc/manual/command-ref/nix-daemon.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - nix-daemon - 8 - Nix - - - - - nix-daemon - Nix multi-user support daemon - - - - - nix-daemon - - - - -Description - -The Nix daemon is necessary in multi-user Nix installations. It -performs build actions and other operations on the Nix store on behalf -of unprivileged users. - - - - - diff --git a/doc/manual/command-ref/nix-env.xml b/doc/manual/command-ref/nix-env.xml deleted file mode 100644 index 55f25d959..000000000 --- a/doc/manual/command-ref/nix-env.xml +++ /dev/null @@ -1,1503 +0,0 @@ - - - - nix-env - 1 - Nix - - - - - nix-env - manipulate or query Nix user environments - - - - - nix-env - - name value - name value - - - - - - path - - - - - - - path - - - - system - - - operation - options - arguments - - - - -Description - -The command nix-env is used to manipulate Nix -user environments. User environments are sets of software packages -available to a user at some point in time. In other words, they are a -synthesised view of the programs available in the Nix store. There -may be many user environments: different users can have different -environments, and individual users can switch between different -environments. - -nix-env takes exactly one -operation flag which indicates the subcommand to -be performed. These are documented below. - - - - - - - -Selectors - -Several commands, such as nix-env -q and -nix-env -i, take a list of arguments that specify -the packages on which to operate. These are extended regular -expressions that must match the entire name of the package. (For -details on regular expressions, see -regex7.) -The match is case-sensitive. The regular expression can optionally be -followed by a dash and a version number; if omitted, any version of -the package will match. Here are some examples: - - - - - firefox - Matches the package name - firefox and any version. - - - - firefox-32.0 - Matches the package name - firefox and version - 32.0. - - - - gtk\\+ - Matches the package name - gtk+. The + character must - be escaped using a backslash to prevent it from being interpreted - as a quantifier, and the backslash must be escaped in turn with - another backslash to ensure that the shell passes it - on. - - - - .\* - Matches any package name. This is the default for - most commands. - - - - '.*zip.*' - Matches any package name containing the string - zip. Note the dots: '*zip*' - does not work, because in a regular expression, the character - * is interpreted as a - quantifier. - - - - '.*(firefox|chromium).*' - Matches any package name containing the strings - firefox or - chromium. - - - - - - - - - - - - -Common options - -This section lists the options that are common to all -operations. These options are allowed for every subcommand, though -they may not always have an effect. See -also . - - - - / path - - Specifies the Nix expression (designated below as - the active Nix expression) used by the - , , and - operations to obtain - derivations. The default is - ~/.nix-defexpr. - - If the argument starts with http:// or - https://, it is interpreted as the URL of a - tarball that will be downloaded and unpacked to a temporary - location. The tarball must include a single top-level directory - containing at least a file named default.nix. - - - - - - / path - - Specifies the profile to be used by those - operations that operate on a profile (designated below as the - active profile). A profile is a sequence of - user environments called generations, one of - which is the current - generation. - - - - - - For the , - , , - , - and - operations, this flag will cause - nix-env to print what - would be done if this flag had not been - specified, without actually doing it. - - also prints out which paths will - be substituted (i.e., - downloaded) and which paths will be built from source (because no - substitute is available). - - - - system - - By default, operations such as show derivations matching any platform. This - option allows you to use derivations for the specified platform - system. - - - - - - - - - - - - - - - -Files - - - - ~/.nix-defexpr - - The source for the default Nix - expressions used by the , - , and operations to obtain derivations. The - option may be used to override this - default. - - If ~/.nix-defexpr is a file, - it is loaded as a Nix expression. If the expression - is a set, it is used as the default Nix expression. - If the expression is a function, an empty set is passed - as argument and the return value is used as - the default Nix expression. - - If ~/.nix-defexpr is a directory - containing a default.nix file, that file - is loaded as in the above paragraph. - - If ~/.nix-defexpr is a directory without - a default.nix file, then its contents - (both files and subdirectories) are loaded as Nix expressions. - The expressions are combined into a single set, each expression - under an attribute with the same name as the original file - or subdirectory. - - - 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; -} - - - - The file manifest.nix is always ignored. - Subdirectories without a default.nix file - are traversed recursively in search of more Nix expressions, - but the names of these intermediate directories are not - added to the attribute paths of the default Nix expression. - - The command nix-channel places symlinks - to the downloaded Nix expressions from each subscribed channel in - this directory. - - - - - ~/.nix-profile - - A symbolic link to the user's current profile. By - default, this symlink points to - prefix/var/nix/profiles/default. - The PATH environment variable should include - ~/.nix-profile/bin for the user environment - to be visible to the user. - - - - - - - - - - - -Operation <option>--install</option> - -Synopsis - - - nix-env - - - - - - - - - - - - - - args - - - - - -Description - -The install operation creates a new user environment, based on -the current generation of the active profile, to which a set of store -paths described by args is added. The -arguments args map to store paths in a -number of possible ways: - - - - By default, args is a set - of derivation names denoting derivations in the active Nix - expression. These are realised, and the resulting output paths are - installed. Currently installed derivations with a name equal to the - name of a derivation being added are removed unless the option - is - specified. - - If there are multiple derivations matching a name in - args that have the same name (e.g., - gcc-3.3.6 and gcc-4.1.1), then - the derivation with the highest priority is - used. A derivation can define a priority by declaring the - meta.priority attribute. This attribute should - be a number, with a higher value denoting a lower priority. The - default priority is 0. - - If there are multiple matching derivations with the same - priority, then the derivation with the highest version will be - installed. - - You can force the installation of multiple derivations with - the same name by being specific about the versions. For instance, - nix-env -i gcc-3.3.6 gcc-4.1.1 will install both - version of GCC (and will probably cause a user environment - conflict!). - - If - () is specified, the arguments are - attribute paths that select attributes from the - top-level Nix expression. This is faster than using derivation - names and unambiguous. To find out the attribute paths of available - packages, use nix-env -qaP. - - If - path is given, - args is a set of names denoting installed - store paths in the profile path. This is - an easy way to copy user environment elements from one profile to - another. - - If is given, - args are Nix functions that are called with the - active Nix expression as their single argument. The derivations - returned by those function calls are installed. This allows - derivations to be specified in an unambiguous way, which is necessary - if there are multiple derivations with the same - name. - - If args are store - derivations, then these are realised, and the resulting - output paths are installed. - - If args are store paths - that are not store derivations, then these are realised and - installed. - - By default all outputs are installed for each derivation. - That can be reduced by setting meta.outputsToInstall. - - - - - - - - - -Flags - - - - / - - Use only derivations for which a substitute is - registered, i.e., there is a pre-built binary available that can - be downloaded in lieu of building the derivation. Thus, no - packages will be built from source. - - - - - - - Do not remove derivations with a name matching one - of the derivations being installed. Usually, trying to have two - versions of the same package installed in the same generation of a - profile will lead to an error in building the generation, due to - file name clashes between the two versions. However, this is not - the case for all packages. - - - - - - - Remove all previously installed packages first. - This is equivalent to running nix-env -e '.*' - first, except that everything happens in a single - transaction. - - - - - - - - -Examples - -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' - -Note the previously installed version is removed, since - was not specified. - -To install an arbitrary version: - - -$ 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 - - - -To install all derivations in the Nix expression foo.nix: - - -$ 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 - - - -To install a specific store derivation (typically created by -nix-instantiate): - - -$ 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 - - - -To install from a Nix expression specified on the command-line: - - -$ 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 the subversionWithJava attribute from the -set returned by calling the 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 - ... - - - -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 - - - - - - - - - - - - -Operation <option>--upgrade</option> - -Synopsis - - - nix-env - - - - - - - - - - - - args - - - - -Description - -The upgrade operation creates a new user environment, based on -the current generation of the active profile, in which all store paths -are replaced for which there are newer versions in the set of paths -described by args. Paths for which there -are no newer versions are left untouched; this is not an error. It is -also not an error if an element of args -matches no installed derivations. - -For a description of how args is -mapped to a set of store paths, see . If -args describes multiple store paths with -the same symbolic name, only the one with the highest version is -installed. - - - -Flags - - - - - - Only upgrade a derivation to newer versions. This - is the default. - - - - - - In addition to upgrading to newer versions, also - “upgrade” to derivations that have the same version. Version are - not a unique identification of a derivation, so there may be many - derivations that have the same version. This flag may be useful - to force “synchronisation” between the installed and available - derivations. - - - - - - Only “upgrade” to derivations - that have the same version. This may not seem very useful, but it - actually is, e.g., when there is a new release of Nixpkgs and you - want to replace installed applications with the same versions - built against newer dependencies (to reduce the number of - dependencies floating around on your system). - - - - - - In addition to upgrading to newer versions, also - “upgrade” to derivations that have the same or a lower version. - I.e., derivations may actually be downgraded depending on what is - available in the active Nix expression. - - - - - -For the other flags, see . - - - -Examples - - -$ 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' - -$ 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' - - - -Versions - -The upgrade operation determines whether a derivation -y is an upgrade of a derivation -x by looking at their respective -name attributes. The names (e.g., -gcc-3.3.1 are split into two parts: the package -name (gcc), and the version -(3.3.1). The version part starts after the first -dash not followed by a letter. x is considered an -upgrade of y if their package names match, and the -version of y is higher that that of -x. - -The versions are compared by splitting them into contiguous -components of numbers and letters. E.g., 3.3.1pre5 -is split into [3, 3, 1, "pre", 5]. These lists are -then compared lexicographically (from left to right). Corresponding -components a and b are compared -as follows. If they are both numbers, integer comparison is used. If -a is an empty string and b is a -number, a is considered less than -b. The special string component -pre (for pre-release) is -considered to be less than other components. String components are -considered less than number components. Otherwise, they are compared -lexicographically (i.e., using case-sensitive string comparison). - -This is illustrated by the following examples: - - -1.0 < 2.3 -2.1 < 2.3 -2.3 = 2.3 -2.5 > 2.3 -3.1 > 2.3 -2.3.1 > 2.3 -2.3.1 > 2.3a -2.3pre1 < 2.3 -2.3pre3 < 2.3pre12 -2.3a < 2.3c -2.3pre1 < 2.3c -2.3pre1 < 2.3q - - - - - - - - - - - -Operation <option>--uninstall</option> - -Synopsis - - - nix-env - - - - - drvnames - - - -Description - -The uninstall operation creates a new user environment, based on -the current generation of the active profile, from which the store -paths designated by the symbolic names -names are removed. - - - -Examples - - -$ nix-env --uninstall gcc -$ nix-env -e '.*' (remove everything) - - - - - - - - - -Operation <option>--set</option> - -Synopsis - - - nix-env - - drvname - - - -Description - -The operation modifies the current generation of a -profile so that it contains exactly the specified derivation, and nothing else. - - - - -Examples - - -The following updates a profile such that its current generation will contain -just Firefox: - - -$ nix-env -p /nix/var/nix/profiles/browser --set firefox - - - - - - - - - - - -Operation <option>--set-flag</option> - -Synopsis - - - nix-env - - name - value - drvnames - - - -Description - -The operation allows meta attributes -of installed packages to be modified. There are several attributes -that can be usefully modified, because they affect the behaviour of -nix-env or the user environment build -script: - - - - priority can be changed to - resolve filename clashes. The user environment build script uses - the meta.priority attribute of derivations to - resolve filename collisions between packages. Lower priority values - denote a higher priority. For instance, the GCC wrapper package and - the Binutils package in Nixpkgs both have a file - bin/ld, so previously if you tried to install - both you would get a collision. Now, on the other hand, the GCC - wrapper declares a higher priority than Binutils, so the former’s - bin/ld is symlinked in the user - environment. - - keep can be set to - true to prevent the package from being upgraded - or replaced. This is useful if you want to hang on to an older - version of a package. - - active can be set to - false to “disable” the package. That is, no - symlinks will be generated to the files of the package, but it - remains part of the profile (so it won’t be garbage-collected). It - can be set back to true to re-enable the - package. - - - - - - - -Examples - -To prevent the currently installed Firefox from being upgraded: - - -$ 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) - -$ 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., can’t have two active at the same time) - -$ 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 -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 - - - - - - - - - - - -Operation <option>--query</option> - -Synopsis - - - nix-env - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - attribute-path - - - - - names - - - - - -Description - -The query operation displays information about either the store -paths that are installed in the current generation of the active -profile (), or the derivations that are -available for installation in the active Nix expression -(). It only prints information about -derivations whose symbolic name matches one of -names. - -The derivations are sorted by their name -attributes. - - - - -Source selection - -The following flags specify the set of things on which the query -operates. - - - - - - The query operates on the store paths that are - installed in the current generation of the active profile. This - is the default. - - - - - - - The query operates on the derivations that are - available in the active Nix expression. - - - - - - - - -Queries - -The following flags specify what information to display about -the selected derivations. Multiple flags may be specified, in which -case the information is shown in the order given here. Note that the -name of the derivation is shown unless is -specified. - - - - - - - - Print the result in an XML representation suitable - for automatic processing by other tools. The root element is - called items, which contains a - item element for each available or installed - derivation. The fields discussed below are all stored in - attributes of the item - elements. - - - - - - Print the result in a JSON representation suitable - for automatic processing by other tools. - - - - / - - Show only derivations for which a substitute is - registered, i.e., there is a pre-built binary available that can - be downloaded in lieu of building the derivation. Thus, this - shows all packages that probably can be installed - quickly. - - - - - - - Print the status of the - derivation. The status consists of three characters. The first - is I or -, indicating - whether the derivation is currently installed in the current - generation of the active profile. This is by definition the case - for , but not for - . The second is P - or -, indicating whether the derivation is - present on the system. This indicates whether installation of an - available derivation will require the derivation to be built. The - third is S or -, indicating - whether a substitute is available for the - derivation. - - - - - - - Print the attribute path of - the derivation, which can be used to unambiguously select it using - the option - available in commands that install derivations like - nix-env --install. This option only works - together with - - - - - - Suppress printing of the name - attribute of each derivation. - - - - / - - - Compare installed versions to available versions, - or vice versa (if is given). This is - useful for quickly seeing whether upgrades for installed - packages are available in a Nix expression. A column is added - with the following meaning: - - - - < version - - A newer version of the package is available - or installed. - - - - = version - - At most the same version of the package is - available or installed. - - - - > version - - Only older versions of the package are - available or installed. - - - - - ? - - No version of the package is available or - installed. - - - - - - - - - - - - Print the system attribute of - the derivation. - - - - - - Print the path of the store - derivation. - - - - - - Print the output path of the - derivation. - - - - - - Print a short (one-line) description of the - derivation, if available. The description is taken from the - meta.description attribute of the - derivation. - - - - - - Print all of the meta-attributes of the - derivation. This option is only available with - or . - - - - - - - - -Examples - -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 - - - - - -To show available packages: - - -$ 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) - - - - - -To show available packages in the Nix expression foo.nix: - - -$ nix-env -f ./foo.nix -qa -foo-1.2.3 - - - - -To compare installed versions to what’s 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) -... - - - - -To show all packages with “zip” in the name: - - -$ 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 - - - - - -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 - - - - - - - - - - - - -Operation <option>--switch-profile</option> - -Synopsis - - - nix-env - - - - - path - - - - - -Description - -This operation makes path the current -profile for the user. That is, the symlink -~/.nix-profile is made to point to -path. - - - -Examples - - -$ nix-env -S ~/my-profile - - - - - - - - - -Operation <option>--list-generations</option> - -Synopsis - - - nix-env - - - - - - -Description - -This operation print a list of all the currently existing -generations for the active profile. These may be switched to using -the operation. It also prints -the creation date of the 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) - - - - - - - - - -Operation <option>--delete-generations</option> - -Synopsis - - - nix-env - - generations - - - - - -Description - -This operation deletes the specified generations of the current -profile. The generations can be a list of generation numbers, the -special value old to delete all non-current -generations, a value such as 30d to delete all -generations older than the specified number of days (except for the -generation that was active at that point in time), or a value such as -+5 to keep the last 5 generations -ignoring any newer than current, e.g., if 30 is the current -generation +5 will delete generation 25 -and all older generations. -Periodically deleting old generations is important to make garbage collection -effective. - - - -Examples - - -$ nix-env --delete-generations 3 4 8 - -$ nix-env --delete-generations +5 - -$ nix-env --delete-generations 30d - -$ nix-env -p other_profile --delete-generations old - - - - - - - - - -Operation <option>--switch-generation</option> - -Synopsis - - - nix-env - - - - - generation - - - - - -Description - -This operation makes generation number -generation the current generation of the -active profile. That is, if the -profile is the path to -the active profile, then the symlink -profile is made to -point to -profile-generation-link, -which is in turn a symlink to the actual user environment in the Nix -store. - -Switching will fail if the specified generation does not exist. - - - - -Examples - - -$ nix-env -G 42 -switching from generation 50 to 42 - - - - - - - - - -Operation <option>--rollback</option> - -Synopsis - - - nix-env - - - - - -Description - -This operation switches to the “previous” generation of the -active profile, that is, the highest numbered generation lower than -the current generation, if it exists. It is just a convenience -wrapper around and -. - - - - -Examples - - -$ nix-env --rollback -switching from generation 92 to 91 - -$ nix-env --rollback -error: no generation older than the current (91) exists - - - - - - -Environment variables - - - - NIX_PROFILE - - Location of the Nix profile. Defaults to the - target of the symlink ~/.nix-profile, if it - exists, or /nix/var/nix/profiles/default - otherwise. - - - - - - - - - - diff --git a/doc/manual/command-ref/nix-hash.xml b/doc/manual/command-ref/nix-hash.xml deleted file mode 100644 index 80263e18e..000000000 --- a/doc/manual/command-ref/nix-hash.xml +++ /dev/null @@ -1,176 +0,0 @@ - - - - nix-hash - 1 - Nix - - - - - nix-hash - compute the cryptographic hash of a path - - - - - nix-hash - - - - hashAlgo - path - - - nix-hash - - hash - - - nix-hash - - hash - - - - -Description - -The command nix-hash computes the -cryptographic hash of the contents of each -path and prints it on standard output. By -default, it computes an MD5 hash, but other hash algorithms are -available as well. The hash is printed in hexadecimal. To generate -the same hash as nix-prefetch-url you have to -specify multiple arguments, see below for an example. - -The hash is computed over a serialisation -of each path: a dump of the file system tree rooted at the path. This -allows directories and symlinks to be hashed as well as regular files. -The dump is in the NAR format produced by nix-store -. Thus, nix-hash -path yields the same -cryptographic hash as nix-store --dump -path | md5sum. - - - - -Options - - - - - - Print the cryptographic hash of the contents of - each regular file path. That is, do - not compute the hash over the dump of - path. The result is identical to that - produced by the GNU commands md5sum and - sha1sum. - - - - - - Print the hash in a base-32 representation rather - than hexadecimal. This base-32 representation is more compact and - can be used in Nix expressions (such as in calls to - fetchurl). - - - - - - Truncate hashes longer than 160 bits (such as - SHA-256) to 160 bits. - - - - hashAlgo - - Use the specified cryptographic hash algorithm, - which can be one of md5, - sha1, and - sha256. - - - - - - Don’t hash anything, but convert the base-32 hash - representation hash to - hexadecimal. - - - - - - Don’t hash anything, but convert the hexadecimal - hash representation hash to - base-32. - - - - - - - - -Examples - -Computing the same hash as nix-prefetch-url: - -$ nix-prefetch-url file://<(echo test) -1lkgqb6fclns49861dwk9rzb6xnfkxbpws74mxnx01z9qyv1pjpj -$ nix-hash --type sha256 --flat --base32 <(echo test) -1lkgqb6fclns49861dwk9rzb6xnfkxbpws74mxnx01z9qyv1pjpj - - - -Computing hashes: - - -$ mkdir test -$ echo "hello" > test/world - -$ nix-hash test/ (MD5 hash; default) -8179d3caeff1869b5ba1744e5a245c04 - -$ nix-store --dump test/ | md5sum (for comparison) -8179d3caeff1869b5ba1744e5a245c04 - - -$ nix-hash --type sha1 test/ -e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6 - -$ 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/world -5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03 - - - -Converting between hexadecimal and base-32: - - -$ nix-hash --type sha1 --to-base32 e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6 -nvd61k9nalji1zl9rrdfmsmvyyjqpzg4 - -$ nix-hash --type sha1 --to-base16 nvd61k9nalji1zl9rrdfmsmvyyjqpzg4 -e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6 - - - - - - - diff --git a/doc/manual/command-ref/nix-instantiate.xml b/doc/manual/command-ref/nix-instantiate.xml deleted file mode 100644 index 53f06aed1..000000000 --- a/doc/manual/command-ref/nix-instantiate.xml +++ /dev/null @@ -1,266 +0,0 @@ - - - - nix-instantiate - 1 - Nix - - - - - nix-instantiate - instantiate store derivations from Nix expressions - - - - - nix-instantiate - - - - - - - - - - - name value - - - - - - attrPath - - path - - - - - - files - - - nix-instantiate - - files - - - - -Description - -The command nix-instantiate generates store derivations from (high-level) -Nix expressions. It evaluates the Nix expressions in each of -files (which defaults to -./default.nix). Each top-level expression -should evaluate to a derivation, a list of derivations, or a set of -derivations. The paths of the resulting store derivations are printed -on standard output. - -If files is the character --, then a Nix expression will be read from standard -input. - -See also for a list of common options. - - - - -Options - - - - - path - - - See the corresponding - options in nix-store. - - - - - - Just parse the input files, and print their - abstract syntax trees on standard output in ATerm - format. - - - - - - Just parse and evaluate the input files, and print - the resulting values on standard output. No instantiation of - store derivations takes place. - - - - - - Look up the given files in Nix’s search path (as - specified by the NIX_PATH - environment variable). If found, print the corresponding absolute - paths on standard output. For instance, if - NIX_PATH is - nixpkgs=/home/alice/nixpkgs, then - nix-instantiate --find-file nixpkgs/default.nix - will print - /home/alice/nixpkgs/default.nix. - - - - - - When used with , - recursively evaluate list elements and attributes. Normally, such - sub-expressions are left unevaluated (since the Nix expression - language is lazy). - - This option can cause non-termination, because lazy - data structures can be infinitely large. - - - - - - - - When used with , print the resulting - value as an JSON representation of the abstract syntax tree rather - than as an ATerm. - - - - - - When used with , print the resulting - value as an XML representation of the abstract syntax tree rather than as - an ATerm. The schema is the same as that used by the toXML built-in. - - - - - - - When used with , perform - evaluation in read/write mode so nix language features that - require it will still work (at the cost of needing to do - instantiation of every evaluated derivation). If this option is - not enabled, there may be uninstantiated store paths in the final - output. - - - - - - - - - - - - - - -Examples - -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 - -$ 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 -... - - - -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 - - -This is equivalent to: - - -$ nix-instantiate '<nixpkgs>' -A hello - - - - -Parsing and evaluating Nix expressions: - - -$ nix-instantiate --parse -E '1 + 2' -1 + 2 - -$ nix-instantiate --eval -E '1 + 2' -3 - -$ nix-instantiate --eval --xml -E '1 + 2' - - - -]]> - - - -The difference between non-strict and strict evaluation: - - -$ nix-instantiate --eval --xml -E 'rec { x = "foo"; y = x; }' -... - - - - - ]]> -... - -Note that y is left unevaluated (the XML -representation doesn’t attempt to show non-normal forms). - - -$ nix-instantiate --eval --xml --strict -E 'rec { x = "foo"; y = x; }' -... - - - - - ]]> -... - - - - - - -Environment variables - - - - - - - - - diff --git a/doc/manual/command-ref/nix-prefetch-url.xml b/doc/manual/command-ref/nix-prefetch-url.xml deleted file mode 100644 index 621ded72e..000000000 --- a/doc/manual/command-ref/nix-prefetch-url.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - - nix-prefetch-url - 1 - Nix - - - - - nix-prefetch-url - copy a file from a URL into the store and print its hash - - - - - nix-prefetch-url - - hashAlgo - - - name - url - hash - - - -Description - -The command nix-prefetch-url downloads the -file referenced by the URL url, prints its -cryptographic hash, and copies it into the Nix store. The file name -in the store is -hash-baseName, -where baseName is everything following the -final slash in url. - -This command is just a convenience for Nix expression writers. -Often a Nix expression fetches some source distribution from the -network using the fetchurl expression contained in -Nixpkgs. However, fetchurl requires a -cryptographic hash. If you don't know the hash, you would have to -download the file first, and then fetchurl would -download it again when you build your Nix expression. Since -fetchurl uses the same name for the downloaded file -as nix-prefetch-url, the redundant download can be -avoided. - -If hash is specified, then a download -is not performed if the Nix store already contains a file with the -same hash and base name. Otherwise, the file is downloaded, and an -error is signaled if the actual hash of the file does not match the -specified hash. - -This command prints the hash on standard output. Additionally, -if the option is used, the path of the -downloaded file in the Nix store is also printed. - - - - -Options - - - - hashAlgo - - Use the specified cryptographic hash algorithm, - which can be one of md5, - sha1, and - sha256. - - - - - - Print the store path of the downloaded file on - standard output. - - - - - - Unpack the archive (which must be a tarball or zip - file) and add the result to the Nix store. The resulting hash can - be used with functions such as Nixpkgs’s - fetchzip or - fetchFromGitHub. - - - - name - - Override the name of the file in the Nix store. By - default, this is - hash-basename, - where basename is the last component of - url. Overriding the name is necessary - when basename contains characters that - are not allowed in Nix store paths. - - - - - - - - -Examples - - -$ 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 - -$ nix-prefetch-url --unpack --print-path https://github.com/NixOS/patchelf/archive/0.8.tar.gz -079agjlv0hrv7fxnx9ngipx14gyncbkllxrp9cccnh3a50fxcmy7 -/nix/store/19zrmhm3m40xxaw81c8cqm6aljgrnwj2-0.8.tar.gz - - - - - - diff --git a/doc/manual/command-ref/nix-shell.xml b/doc/manual/command-ref/nix-shell.xml deleted file mode 100644 index 2fef323c5..000000000 --- a/doc/manual/command-ref/nix-shell.xml +++ /dev/null @@ -1,411 +0,0 @@ - - - - nix-shell - 1 - Nix - - - - - nix-shell - start an interactive shell based on a Nix expression - - - - - nix-shell - name value - name value - - - - - - attrPath - - cmd - cmd - regexp - - name - - - - - - - - - packages - expressions - - - - path - - - - -Description - -The command nix-shell will build the -dependencies of the specified derivation, but not the derivation -itself. It will then start an interactive shell in which all -environment variables defined by the derivation -path have been set to their corresponding -values, and the script $stdenv/setup has been -sourced. This is useful for reproducing the environment of a -derivation for development. - -If path is not given, -nix-shell defaults to -shell.nix if it exists, and -default.nix otherwise. - -If path starts with -http:// or https://, it is -interpreted as the URL of a tarball that will be downloaded and -unpacked to a temporary location. The tarball must include a single -top-level directory containing at least a file named -default.nix. - -If the derivation defines the variable -shellHook, it will be evaluated 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" - ''; - - -will cause nix-shell to print Hello shell. - - - - -Options - -All options not listed here are passed to nix-store ---realise, except for and - / which are passed to -nix-instantiate. See -also . - - - - cmd - - In the environment of the derivation, run the - shell command cmd. This command is - executed in an interactive shell. (Use to - use a non-interactive shell instead.) However, a call to - exit is implicitly added to the command, so the - shell will exit after running the command. To prevent this, add - return at the end; e.g. --command - "echo Hello; return" will print Hello - and then drop you into the interactive shell. This can be useful - for doing any additional initialisation. - - - - cmd - - Like , but executes the - command in a non-interactive shell. This means (among other - things) that if you hit Ctrl-C while the command is running, the - shell exits. - - - - regexp - - Do not build any dependencies whose store path - matches the regular expression regexp. - This option may be specified multiple times. - - - - - - If this flag is specified, the environment is - almost entirely cleared before the interactive shell is started, - so you get an environment that more closely corresponds to the - “real” Nix build. A few variables, in particular - HOME, USER and - DISPLAY, are retained. Note that - ~/.bashrc and (depending on your Bash - installation) /etc/bashrc are still sourced, - so any variables set there will affect the interactive - shell. - - - - / packages - - Set up an environment in which the specified - packages are present. The command line arguments are interpreted - as attribute names inside the Nix Packages collection. Thus, - nix-shell -p libjpeg openjdk will start a shell - in which the packages denoted by the attribute names - libjpeg and openjdk are - present. - - - - interpreter - - The chained script interpreter to be invoked by - nix-shell. Only applicable in - #!-scripts (described below). - - - - name - - When a shell is started, - keep the listed environment variables. - - - - - -The following common options are supported: - - - - - - - - -Environment variables - - - - NIX_BUILD_SHELL - - Shell used to start the interactive environment. - Defaults to the bash found in PATH. - - - - - - - - -Examples - -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 - - -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' - - -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 ]; } ""' - - -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 … - - -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; }' - - -The -p flag looks up Nixpkgs in the Nix search -path. You can override it by passing 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 - -[nix-shell:~]$ pan --version -Pan 0.139 - - - - - - - -Use as a <literal>#!</literal>-interpreter - -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 - - -where real-interpreter is the “real” script -interpreter that will be invoked by nix-shell after -it has obtained the dependencies and initialised the environment, and -packages are the attribute names of the -dependencies in Nixpkgs. - -The lines starting with #! nix-shell specify -nix-shell options (see above). Note that you cannot -write #! /usr/bin/env nix-shell -i ... 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 - -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 - - - - -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 - -use HTML::TokeParser::Simple; - -# 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; -} - - - - -Sometimes you need to pass a simple Nix expression to customize -a package like Terraform: - - - -You must use double quotes (") when -passing a simple Nix expression in a nix-shell shebang. - - -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): - - - -If you want to be even more precise, you can specify a specific -revision of Nixpkgs: - - -#! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/0672315759b3e15e2121365f067c1c8c56bb4722.tar.gz - - - - -The examples above all used 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 - - -where the file deps.nix in the same directory -as the #!-script contains: - - -with import <nixpkgs> {}; - -runCommand "dummy" { buildInputs = [ python pythonPackages.prettytable ]; } "" - - - - - - - -Environment variables - - - - - - - - - diff --git a/doc/manual/command-ref/nix-store.xml b/doc/manual/command-ref/nix-store.xml deleted file mode 100644 index d71f9d8e4..000000000 --- a/doc/manual/command-ref/nix-store.xml +++ /dev/null @@ -1,1516 +0,0 @@ - - - - nix-store - 1 - Nix - - - - - nix-store - manipulate or query the Nix store - - - - - nix-store - - path - - operation - options - arguments - - - - -Description - -The command nix-store performs primitive -operations on the Nix store. You generally do not need to run this -command manually. - -nix-store takes exactly one -operation flag which indicates the subcommand to -be performed. These are documented below. - - - - - - - -Common options - -This section lists the options that are common to all -operations. These options are allowed for every subcommand, though -they may not always have an effect. See -also for a list of common -options. - - - - path - - Causes the result of a realisation - ( and ) - to be registered as a root of the garbage collector (see ). The root is stored in - path, which must be inside a directory - that is scanned for roots by the garbage collector (i.e., - typically in a subdirectory of - /nix/var/nix/gcroots/) - unless the flag - is used. - - If there are multiple results, then multiple symlinks will - be created by sequentially numbering symlinks beyond the first one - (e.g., foo, foo-2, - foo-3, and so on). - - - - - - - - In conjunction with , this option - allows roots to be stored outside of the GC - roots directory. This is useful for commands such as - nix-build that place a symlink to the build - result in the current directory; such a build result should not be - garbage-collected unless the symlink is removed. - - The 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 ... - -$ 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 - - Thus, when /home/eelco/bla/result is removed, - the GC root in the auto directory becomes a - dangling symlink and will be ignored by the collector. - - Note that it is not possible to move or rename - indirect GC roots, since the symlink in the - auto directory will still point to the old - location. - - - - - - - - - - - - - - - - - -Operation <option>--realise</option> - -Synopsis - - - nix-store - - - - - paths - - - - - -Description - -The operation essentially “builds” -the specified store paths. Realisation is a somewhat overloaded term: - - - - If the store path is a - derivation, realisation ensures that the output - paths of the derivation are valid (i.e., the output path and its - closure exist in the file system). This can be done in several - ways. First, it is possible that the outputs are already valid, in - which case we are done immediately. Otherwise, there may be substitutes that produce the - outputs (e.g., by downloading them). Finally, the outputs can be - produced by performing the build action described by the - derivation. - - If the store path is not a derivation, realisation - ensures that the specified path is valid (i.e., it and its closure - exist in the file system). If the path is already valid, we are - done immediately. Otherwise, the path and any missing paths in its - closure may be produced through substitutes. If there are no - (successful) subsitutes, realisation fails. - - - - - -The output path of each derivation is printed on standard -output. (For non-derivations argument, the argument itself is -printed.) - -The following flags are available: - - - - - - Print on standard error a description of what - packages would be built or downloaded, without actually performing - the operation. - - - - - - If a non-derivation path does not have a - substitute, then silently ignore it. - - - - - - This option allows you to check whether a - derivation is deterministic. It rebuilds the specified derivation - and checks whether the result is bitwise-identical with the - existing outputs, printing an error if that’s not the case. The - outputs of the specified derivation must already exist. When used - with , if an output path is not identical to - the corresponding output from the previous build, the new output - path is left in - /nix/store/name.check. - - See also the configuration - option, which repeats a derivation a number of times and prevents - its outputs from being registered as “valid” in the Nix store - unless they are identical. - - - - - -Special exit codes: - - - - 100 - Generic build failure, the builder process - returned with a non-zero exit code. - - - 101 - Build timeout, the build was aborted because it - did not complete within the specified timeout. - - - - 102 - Hash mismatch, the build output was rejected - because it does not match the specified outputHash. - - - - 104 - Not deterministic, the build succeeded in check - mode but the resulting output is not binary reproducable. - - - - - -With the flag it's possible for -multiple failures to occur, in this case the 1xx status codes are or combined -using binary or. -1100100 - ^^^^ - |||`- timeout - ||`-- output hash mismatch - |`--- build failure - `---- not deterministic - - - - - -Examples - -This operation is typically used to build store derivations -produced by nix-instantiate: - - -$ nix-store -r $(nix-instantiate ./test.nix) -/nix/store/31axcgrlbfsxzmfff1gyj1bf62hvkby2-aterm-2.3.1 - -This is essentially what nix-build does. - -To test whether a previously-built derivation is deterministic: - - -$ nix-build '<nixpkgs>' -A hello --check -K - - - - - - - - - - - - - -Operation <option>--serve</option> - -Synopsis - - - nix-store - - - - - - -Description - -The operation provides access to -the Nix store over stdin and stdout, and is intended to be used -as a means of providing Nix store access to a restricted ssh user. - - -The following flags are available: - - - - - - Allow the connected client to request the realization - of derivations. In effect, this can be used to make the host act - as a remote builder. - - - - - - - - -Examples - -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 - - - - - - - - - - - - - -Operation <option>--gc</option> - -Synopsis - - - nix-store - - - - - - - bytes - - - - -Description - -Without additional flags, the operation -performs a garbage collection on the Nix store. That is, all paths in -the Nix store not reachable via file system references from a set of -“roots”, are deleted. - -The following suboperations may be specified: - - - - - - This operation prints on standard output the set - of roots used by the garbage collector. What constitutes a root - is described in . - - - - - - This operation prints on standard output the set - of “live” store paths, which are all the store paths reachable - from the roots. Live paths should never be deleted, since that - would break consistency — it would become possible that - applications are installed that reference things that are no - longer present in the store. - - - - - - This operation prints out on standard output the - set of “dead” store paths, which is just the opposite of the set - of live paths: any path in the store that is not live (with - respect to the roots) is dead. - - - - - -By default, all unreachable paths are deleted. The following -options control what gets deleted and in what order: - - - - bytes - - Keep deleting paths until at least - bytes bytes have been deleted, then - stop. The argument bytes can be - followed by the multiplicative suffix K, - M, G or - T, denoting KiB, MiB, GiB or TiB - units. - - - - - - - -The behaviour of the collector is also influenced by the keep-outputs -and keep-derivations -variables in the Nix configuration file. - -By default, the collector prints the total number of freed bytes -when it finishes (or when it is interrupted). With -, it prints the number of bytes that would -be freed. - - - - -Examples - -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) - - - -To delete at least 100 MiBs of unreachable paths: - - -$ nix-store --gc --max-freed $((100 * 1024 * 1024)) - - - - - - - - - - - - -Operation <option>--delete</option> - -Synopsis - - - nix-store - - - paths - - - - -Description - -The operation deletes the store paths -paths from the Nix store, but only if it is -safe to do so; that is, when the path is not reachable from a root of -the garbage collector. This means that you can only delete paths that -would also be deleted by nix-store --gc. Thus, ---delete is a more targeted version of ---gc. - -With the option , reachability -from the roots is ignored. However, the path still won’t be deleted -if there are other 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 - - - - - - - - - -Operation <option>--query</option> - -Synopsis - - - nix-store - - - - - - - - - - - - - - - - name - name - - - - - - - - - paths - - - - - -Description - -The operation displays various bits of -information about the store paths . The queries are described below. At -most one query can be specified. The default query is -. - -The paths paths may also be symlinks -from outside of the Nix store, to the Nix store. In that case, the -query is applied to the target of the symlink. - - - - - -Common query options - - - - - - - For each argument to the query that is a store - derivation, apply the query to the output path of the derivation - instead. - - - - - - - Realise each argument to the query first (see - nix-store - --realise). - - - - - - - - -Queries - - - - - - Prints out the output paths of the store - derivations paths. These are the paths - that will be produced when the derivation is - built. - - - - - - - Prints out the closure of the store path - paths. - - This query has one option: - - - - - - Also include the output path of store - derivations, and their closures. - - - - - - This query can be used to implement various kinds of - deployment. A source deployment is obtained - by distributing the closure of a store derivation. A - binary deployment is obtained by distributing - the closure of an output path. A cache - deployment (combined source/binary deployment, - including binaries of build-time-only dependencies) is obtained by - distributing the closure of a store derivation and specifying the - option . - - - - - - - - Prints the set of references of the store paths - paths, that is, their immediate - dependencies. (For all dependencies, use - .) - - - - - - Prints the set of referrers of - the store paths paths, that is, the - store paths currently existing in the Nix store that refer to one - of paths. Note that contrary to the - references, the set of referrers is not constant; it can change as - store paths are added or removed. - - - - - - Prints the closure of the set of store paths - paths under the referrers relation; that - is, all store paths that directly or indirectly refer to one of - paths. These are all the path currently - in the Nix store that are dependent on - paths. - - - - - - - Prints the deriver of the store paths - paths. If the path has no deriver - (e.g., if it is a source file), or if the deriver is not known - (e.g., in the case of a binary-only deployment), the string - unknown-deriver is printed. - - - - - - Prints the references graph of the store paths - paths in the format of the - dot tool of AT&T's Graphviz package. - This can be used to visualise dependency graphs. To obtain a - build-time dependency graph, apply this to a store derivation. To - obtain a runtime dependency graph, apply it to an output - path. - - - - - - Prints the references graph of the store paths - paths as a nested ASCII tree. - References are ordered by descending closure size; this tends to - flatten the tree, making it more readable. The query only - recurses into a store path when it is first encountered; this - prevents a blowup of the tree representation of the - graph. - - - - - - Prints the references graph of the store paths - paths in the GraphML file format. - This can be used to visualise dependency graphs. To obtain a - build-time dependency graph, apply this to a store derivation. To - obtain a runtime dependency graph, apply it to an output - path. - - - - name - name - - Prints the value of the attribute - name (i.e., environment variable) of - the store derivations paths. It is an - error for a derivation to not have the specified - attribute. - - - - - - Prints the SHA-256 hash of the contents of the - store paths paths (that is, the hash of - the output of nix-store --dump on the given - paths). Since the hash is stored in the Nix database, this is a - fast operation. - - - - - - Prints the size in bytes of the contents of the - store paths paths — to be precise, the - size of the output of nix-store --dump on the - given paths. Note that the actual disk space required by the - store paths may be higher, especially on filesystems with large - cluster sizes. - - - - - - Prints the garbage collector roots that point, - directly or indirectly, at the store paths - paths. - - - - - - - - -Examples - -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 -... - - - -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 ... - -The difference with the previous example is that we ask the closure of -the derivation (), not the closure of the output -path that contains svn. - -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 -... - - - -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 - - - -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 -... - -Note that ldd is a command that prints out the -dynamic libraries used 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 - - - -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 - - - - - - - - - - - - - - - - - - - -Operation <option>--add</option> - -Synopsis - - - nix-store - - paths - - - - -Description - -The operation adds the specified paths to -the Nix store. It prints the resulting paths in the Nix store on -standard output. - - - -Example - - -$ nix-store --add ./foo.c -/nix/store/m7lrha58ph6rcnv109yzx1nk1cj7k7zf-foo.c - - - - - - - -Operation <option>--add-fixed</option> - -Synopsis - - - nix-store - - - algorithm - paths - - - - -Description - -The operation adds the specified paths to -the Nix store. Unlike paths are registered using the -specified hashing algorithm, resulting in the same output path as a fixed-output -derivation. This can be used for sources that are not available from a public -url or broke since the download expression was written. - - -This operation has the following options: - - - - - - - Use recursive instead of flat hashing mode, used when adding directories - to the store. - - - - - - - - - - -Example - - -$ nix-store --add-fixed sha256 ./hello-2.10.tar.gz -/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz - - - - - - - - - -Operation <option>--verify</option> - - - Synopsis - - nix-store - - - - - - -Description - -The operation verifies the internal -consistency of the Nix database, and the consistency between the Nix -database and the Nix store. Any inconsistencies encountered are -automatically repaired. Inconsistencies are generally the result of -the Nix store or database being modified by non-Nix tools, or of bugs -in Nix itself. - -This operation has the following options: - - - - - - Checks that the contents of every valid store path - has not been altered by computing a SHA-256 hash of the contents - and comparing it with the hash stored in the Nix database at build - time. Paths that have been modified are printed out. For large - stores, is obviously quite - slow. - - - - - - If any valid path is missing from the store, or - (if is given) the contents of a - valid path has been modified, then try to repair the path by - redownloading it. See nix-store --repair-path - for details. - - - - - - - - - - - - - - - -Operation <option>--verify-path</option> - - - Synopsis - - nix-store - - paths - - - -Description - -The operation compares the -contents of the given store paths to their cryptographic hashes stored -in Nix’s database. For every changed path, it prints a warning -message. The exit status is 0 if no path has changed, and 1 -otherwise. - - - -Example - -To verify the integrity of the svn command and all its dependencies: - - -$ nix-store --verify-path $(nix-store -qR $(which svn)) - - - - - - - - - - - -Operation <option>--repair-path</option> - - - Synopsis - - nix-store - - paths - - - -Description - -The operation attempts to -“repair” the specified paths by redownloading them using the available -substituters. If no substitutes are available, then repair is not -possible. - -During repair, there is a very small time window during -which the old path (if it exists) is moved out of the way and replaced -with the new path. If repair is interrupted in between, then the -system may be left in a broken state (e.g., if the path contains a -critical system component like the GNU C Library). - - - -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' - -$ nix-store --repair-path /nix/store/dj7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13 -fetching path `/nix/store/d7a81wsm1ijwwpkks3725661h3263p5-glibc-2.13'... -… - - - - - - - - - -Operation <option>--dump</option> - - - Synopsis - - nix-store - - path - - - -Description - -The operation produces a NAR (Nix -ARchive) file containing the contents of the file system tree rooted -at path. The archive is written to -standard output. - -A NAR archive is like a TAR or Zip archive, but it contains only -the information that Nix considers important. For instance, -timestamps are elided because all files in the Nix store have their -timestamp set to 0 anyway. Likewise, all permissions are left out -except for the execute bit, because all files in the Nix store have -444 or 555 permission. - -Also, a NAR archive is canonical, meaning -that “equal” paths always produce the same NAR archive. For instance, -directory entries are always sorted so that the actual on-disk order -doesn’t influence the result. This means that the cryptographic hash -of a NAR dump of a path is usable as a fingerprint of the contents of -the path. Indeed, the hashes of store paths stored in Nix’s database -(see nix-store -q ---hash) are SHA-256 hashes of the NAR dump of each -store path. - -NAR archives support filenames of unlimited length and 64-bit -file sizes. They can contain regular files, directories, and symbolic -links, but not other types of files (such as device nodes). - -A Nix archive can be unpacked using nix-store ---restore. - - - - - - - - - -Operation <option>--restore</option> - - - Synopsis - - nix-store - - path - - - -Description - -The operation unpacks a NAR archive -to path, which must not already exist. The -archive is read from standard input. - - - - - - - - - -Operation <option>--export</option> - - - Synopsis - - nix-store - - paths - - - -Description - -The operation writes a serialisation -of the specified store paths to standard output in a format that can -be imported into another Nix store with nix-store --import. This -is like nix-store ---dump, except that the NAR archive produced by that command -doesn’t contain the necessary meta-information to allow it to be -imported into another Nix store (namely, the set of references of the -path). - -This command does not produce a closure of -the specified paths, so if 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 - -To import the whole closure again, run: - - -$ nix-store --import < out - - - - - - - - - - - -Operation <option>--import</option> - - - Synopsis - - nix-store - - - - -Description - -The operation reads a serialisation of -a set of store paths produced by nix-store --export from -standard input and adds those store paths to the Nix store. Paths -that already exist in the Nix store are ignored. If a path refers to -another path that doesn’t exist in the Nix store, the import -fails. - - - - - - - - - -Operation <option>--optimise</option> - - - Synopsis - - nix-store - - - - -Description - -The operation reduces Nix store disk -space usage by finding identical files in the store and hard-linking -them to each other. It typically reduces the size of the store by -something like 25-35%. Only regular files and symlinks are -hard-linked in this manner. Files are considered identical when they -have the same NAR archive serialisation: that is, regular files must -have the same contents and permission (executable or non-executable), -and symlinks must have the same contents. - -After completion, or when the command is interrupted, a report -on the achieved savings is printed on standard error. - -Use or 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 - - - - - - - - - - -Operation <option>--read-log</option> - - - Synopsis - - nix-store - - - - - paths - - - -Description - -The operation prints the build log -of the specified store paths on standard output. The build log is -whatever the builder of a derivation wrote to standard output and -standard error. If a store path is not a derivation, the deriver of -the store path is used. - -Build logs are kept in -/nix/var/log/nix/drvs. However, there is no -guarantee that a build log is available for any particular store path. -For instance, if the path was downloaded as a pre-built binary through -a 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 -... - - - - - - - - - - -Operation <option>--dump-db</option> - - - Synopsis - - nix-store - - paths - - - -Description - -The operation writes a dump of the -Nix database to standard output. It can be loaded into an empty Nix -store using . This is useful for making -backups and when migrating to different database schemas. - -By default, will dump the entire Nix -database. When one or more store paths is passed, only the subset of -the Nix database for those store paths is dumped. As with -, the user is responsible for passing all the -store paths for a closure. See for an -example. - - - - - - - - -Operation <option>--load-db</option> - - - Synopsis - - nix-store - - - - -Description - -The operation reads a dump of the Nix -database created by from standard input and -loads it into the Nix database. - - - - - - - - -Operation <option>--print-env</option> - - - Synopsis - - nix-store - - drvpath - - - -Description - -The operation prints out the -environment of a derivation in a format that can be evaluated by a -shell. The command line arguments 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' - - - - - - - - - -Operation <option>--generate-binary-cache-key</option> - - - Synopsis - - nix-store - - - - - - - - - -Description - -This command generates an Ed25519 key pair that can -be used to create a signed binary cache. It takes three mandatory -parameters: - - - - A key name, such as - cache.example.org-1, that is used to look up keys - on the client when it verifies signatures. It can be anything, but - it’s suggested to use the host name of your cache - (e.g. cache.example.org) with a suffix denoting - the number of the key (to be incremented every time you need to - revoke a key). - - The file name where the secret key is to be - stored. - - The file name where the public key is to be - stored. - - - - - - - - - - - - -Environment variables - - - - - - - - - diff --git a/doc/manual/command-ref/opt-common-syn.xml b/doc/manual/command-ref/opt-common-syn.xml deleted file mode 100644 index 2660e3bb1..000000000 --- a/doc/manual/command-ref/opt-common-syn.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - format - - - - - - - - - - - - - number - - - - number - - - - number - - - - number - - - - - - - - - - - - - - - - - - path - - - - name - value - - - - diff --git a/doc/manual/command-ref/opt-common.xml b/doc/manual/command-ref/opt-common.xml deleted file mode 100644 index a68eef1d0..000000000 --- a/doc/manual/command-ref/opt-common.xml +++ /dev/null @@ -1,405 +0,0 @@ - - -Common Options - - -Most Nix commands accept the following command-line options: - - - - - - Prints out a summary of the command syntax and - exits. - - - - - - - Prints out the Nix version number on standard output - and exits. - - - - / - - - - Increases the level of verbosity of diagnostic messages - printed on standard error. For each Nix operation, the information - printed on standard output is well-defined; any diagnostic - information is printed on standard error, never on standard - output. - - This option may be specified repeatedly. Currently, the - following verbosity levels exist: - - - - 0 - “Errors only”: only print messages - explaining why the Nix invocation failed. - - - 1 - “Informational”: print - useful messages about what Nix is doing. - This is the default. - - - 2 - “Talkative”: print more informational - messages. - - - 3 - “Chatty”: print even more - informational messages. - - - 4 - “Debug”: print debug - information. - - - 5 - “Vomit”: print vast amounts of debug - information. - - - - - - - - - - - - - - Decreases the level of verbosity of diagnostic messages - printed on standard error. This is the inverse option to - / . - - - This option may be specified repeatedly. See the previous - verbosity levels list. - - - - - - - format - - - - This option can be used to change the output of the log format, with - format being one of: - - - - raw - This is the raw format, as outputted by nix-build. - - - internal-json - Outputs the logs in a structured manner. NOTE: the json schema is not guarantees to be stable between releases. - - - bar - Only display a progress bar during the builds. - - - bar-with-logs - Display the raw logs, with the progress bar at the bottom. - - - - - - - - - / - - By default, output written by builders to standard - output and standard error is echoed to the Nix command's standard - error. This option suppresses this behaviour. Note that the - builder's standard output and error are always written to a log file - in - prefix/nix/var/log/nix. - - - - - / -number - - - - Sets the maximum number of build jobs that Nix will - perform in parallel to the specified number. Specify - auto to use the number of CPUs in the system. - The default is specified by the max-jobs - configuration setting, which itself defaults to - 1. A higher value is useful on SMP systems or to - exploit I/O latency. - - Setting it to 0 disallows building on the local - machine, which is useful when you want builds to happen only on remote - builders. - - - - - - - - - Sets the value of the NIX_BUILD_CORES - environment variable in the invocation of builders. Builders can - use this variable at their discretion to control the maximum amount - of parallelism. For instance, in Nixpkgs, if the derivation - attribute enableParallelBuilding is set to - true, the builder passes the - flag to GNU Make. - It defaults to the value of the cores - configuration setting, if set, or 1 otherwise. - The value 0 means that the builder should use all - available CPU cores in the system. - - - - - - - Sets the maximum number of seconds that a builder - can go without producing any data on standard output or standard - error. The default is specified by the max-silent-time - configuration setting. 0 means no - time-out. - - - - - - Sets the maximum number of seconds that a builder - can run. The default is specified by the timeout - configuration setting. 0 means no - timeout. - - - - / - - Keep going in case of failed builds, to the - greatest extent possible. That is, if building an input of some - derivation fails, Nix will still build the other inputs, but not the - derivation itself. Without this option, Nix stops if any build - fails (except for builds of substitutes), possibly killing builds in - progress (in case of parallel or distributed builds). - - - - - / - - Specifies that in case of a build failure, the - temporary directory (usually in /tmp) in which - the build takes place should not be deleted. The path of the build - directory is printed as an informational message. - - - - - - - - - - Whenever Nix attempts to build a derivation for which - substitutes are known for each output path, but realising the output - paths through the substitutes fails, fall back on building the - derivation. - - The most common scenario in which this is useful is when we - have registered substitutes in order to perform binary distribution - from, say, a network repository. If the repository is down, the - realisation of the derivation will fail. When this option is - specified, Nix will build the derivation instead. Thus, - installation from binaries falls back on installation from source. - This option is not the default since it is generally not desirable - for a transient failure in obtaining the substitutes to lead to a - full build from source (with the related consumption of - resources). - - - - - - - - - - Disables the build hook mechanism. This allows to ignore remote - builders if they are setup on the machine. - - It's useful in cases where the bandwidth between the client and the - remote builder is too low. In that case it can take more time to upload the - sources to the remote builder and fetch back the result than to do the - computation locally. - - - - - - - - - - When this option is used, no attempt is made to open - the Nix database. Most Nix operations do need database access, so - those operations will fail. - - - - - name value - - This option is accepted by - nix-env, nix-instantiate, - nix-shell and nix-build. - When evaluating Nix expressions, the expression evaluator will - automatically try to call functions that - it encounters. It can automatically call functions for which every - argument has a default value - (e.g., { argName ? - defaultValue }: - ...). With - , you can also call functions that have - arguments without a default value (or override a default value). - That is, if the evaluator encounters a function with an argument - named name, it will call it with value - value. - - 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 - ... -}: ... - - So if you call this Nix expression (e.g., when you do - nix-env -i pkgname), - the function will be called automatically using the value builtins.currentSystem - for the system argument. You can override this - using , e.g., nix-env -i - pkgname --arg system - \"i686-freebsd\". (Note that since the argument is a Nix - string literal, you have to escape the quotes.) - - - - - name value - - This option is like , only the - value is not a Nix expression but a string. So instead of - --arg system \"i686-linux\" (the outer quotes are - to keep the shell happy) you can say --argstr system - i686-linux. - - - - - / -attrPath - - Select an attribute from the top-level Nix - expression being evaluated. (nix-env, - nix-instantiate, nix-build and - nix-shell only.) The attribute - path attrPath is a sequence of - attribute names separated by dots. For instance, given a top-level - Nix expression e, the attribute path - xorg.xorgserver would cause the expression - e.xorg.xorgserver to - be used. See nix-env - --install for some concrete examples. - - In addition to attribute names, you can also specify array - indices. For instance, the attribute path - foo.3.bar selects the bar - attribute of the fourth element of the array in the - foo attribute of the top-level - expression. - - - - - / - - Interpret the command line arguments as a list of - Nix expressions to be parsed and evaluated, rather than as a list - of file names of Nix expressions. - (nix-instantiate, nix-build - and nix-shell only.) - - For nix-shell, this option is commonly used - to give you a shell in which you can build the packages returned - by the expression. If you want to get a shell which contain the - built packages ready for use, give your - expression to the nix-shell -p convenience flag - instead. - - - - - path - - Add a path to the Nix expression search path. This - option may be given multiple times. See the NIX_PATH environment variable for - information on the semantics of the Nix search path. Paths added - through take precedence over - NIX_PATH. - - - - - name value - - Set the Nix configuration option - name to value. - This overrides settings in the Nix configuration file (see - nix.conf5). - - - - - - - Fix corrupted or missing store paths by - redownloading or rebuilding them. Note that this is slow because it - requires computing a cryptographic hash of the contents of every - path in the closure of the build. Also note the warning under - nix-store --repair-path. - - - - - - - - diff --git a/doc/manual/command-ref/opt-inst-syn.xml b/doc/manual/command-ref/opt-inst-syn.xml deleted file mode 100644 index e8c3f1ec6..000000000 --- a/doc/manual/command-ref/opt-inst-syn.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - path - - diff --git a/doc/manual/command-ref/utilities.xml b/doc/manual/command-ref/utilities.xml deleted file mode 100644 index 893f5b5b5..000000000 --- a/doc/manual/command-ref/utilities.xml +++ /dev/null @@ -1,20 +0,0 @@ - - -Utilities - -This section lists utilities that you can use when you -work with Nix. - - - - - - - - - - diff --git a/doc/manual/custom.css b/doc/manual/custom.css new file mode 100644 index 000000000..69d48d4a7 --- /dev/null +++ b/doc/manual/custom.css @@ -0,0 +1,7 @@ +h1:not(:first-of-type) { + margin-top: 1.3em; +} + +h2 { + margin-top: 1em; +} diff --git a/doc/manual/expressions/advanced-attributes.xml b/doc/manual/expressions/advanced-attributes.xml deleted file mode 100644 index 5759ff50e..000000000 --- a/doc/manual/expressions/advanced-attributes.xml +++ /dev/null @@ -1,351 +0,0 @@ -
- -Advanced Attributes - -Derivations can declare some infrequently used optional -attributes. - - - - allowedReferences - - The optional attribute - allowedReferences specifies a list of legal - references (dependencies) of the output of the builder. For - example, - - -allowedReferences = []; - - - enforces that the output of a derivation cannot have any runtime - dependencies on its inputs. To allow an output to have a runtime - dependency on itself, use "out" as a list item. - This is used in NixOS to check that generated files such as - initial ramdisks for booting Linux don’t have accidental - dependencies on other paths in the Nix store. - - - - - allowedRequisites - - This attribute is similar to - allowedReferences, but it specifies the legal - requisites of the whole closure, so all the dependencies - recursively. For example, - - -allowedRequisites = [ foobar ]; - - - enforces that the output of a derivation cannot have any other - runtime dependency than foobar, and in addition - it enforces that foobar itself doesn't - introduce any other dependency itself. - - - - disallowedReferences - - The optional attribute - disallowedReferences specifies a list of illegal - references (dependencies) of the output of the builder. For - example, - - -disallowedReferences = [ foo ]; - - - enforces that the output of a derivation cannot have a direct runtime - dependencies on the derivation foo. - - - - - disallowedRequisites - - This attribute is similar to - disallowedReferences, but it specifies illegal - requisites for the whole closure, so all the dependencies - recursively. For example, - - -disallowedRequisites = [ foobar ]; - - - enforces that the output of a derivation cannot have any - runtime dependency on foobar or any other derivation - depending recursively on foobar. - - - - - 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: - - -derivation { - ... - exportReferencesGraph = [ "libfoo-graph" libfoo ]; -}; - - - the references graph of libfoo is placed in the - file libfoo-graph in the temporary build - directory. - - exportReferencesGraph is useful for - builders that want to do something with the closure of a store - path. Examples include the builders in NixOS that generate the - initial ramdisk for booting Linux (a cpio - archive containing the closure of the boot script) and the - ISO-9660 image for the installation CD (which is populated with a - Nix store containing the closure of a bootable NixOS - configuration). - - - - - impureEnvVars - - This attribute allows you to specify a list of - environment variables that should be passed from the environment - of the calling user to the builder. Usually, the environment is - cleared completely when the builder is executed, but with this - attribute you can allow specific environment variables to be - passed unmodified. For example, fetchurl in - Nixpkgs has the line - - -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. - - This attribute is only allowed in fixed-output derivations, where - impurities such as these are okay since (the hash of) the output - is known in advance. It is ignored for all other - derivations. - - impureEnvVars implementation takes - environment variables from the current builder process. When a daemon is - building its environmental variables are used. Without the daemon, the - environmental variables come from the environment of the - nix-build. - - - - - - outputHash - outputHashAlgo - outputHashMode - - These attributes declare that the derivation is a - so-called fixed-output derivation, which - means that a cryptographic hash of the output is already known in - advance. When the build of a fixed-output derivation finishes, - Nix computes the cryptographic hash of the output and compares it - to the hash declared with these attributes. If there is a - mismatch, the build fails. - - The rationale for fixed-output derivations is derivations - such as those produced by the fetchurl - function. This function downloads a file from a given URL. To - ensure that the downloaded file has not 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"; -} - - - 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"; -} - - - If a fetchurl derivation was treated like a - normal derivation, the output paths of the derivation and - all derivations depending on it would change. - For instance, if we were to change the URL of the Glibc source - distribution in Nixpkgs (a package on which almost all other - packages depend) massive rebuilds would be needed. This is - unfortunate for a change which we know cannot have a real effect - as it propagates upwards through the dependency graph. - - For fixed-output derivations, on the other hand, the name of - the output path only depends on the outputHash* - and name attributes, while all other attributes - are ignored for the purpose of computing the output path. (The - name attribute is included because it is part - of the path.) - - 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; -} - - - - - The outputHashAlgo attribute specifies - the hash algorithm used to compute the hash. It can currently be - "sha1", "sha256" or - "sha512". - - The outputHashMode attribute determines - how the hash is computed. It must be one of the following two - values: - - - - "flat" - - The output must be a non-executable regular - file. If it isn’t, the build fails. The hash is simply - computed over the contents of that file (so it’s equal to what - Unix commands like sha256sum or - sha1sum produce). - - This is the default. - - - - "recursive" - - The hash is computed over the NAR archive dump - of the output (i.e., the result of nix-store - --dump). In this case, the output can be - anything, including a directory tree. - - - - - - - - The outputHash attribute, finally, must - be a string containing the hash in either hexadecimal or base-32 - notation. (See the nix-hash command - for information about converting to and from base-32 - notation.) - - - - - passAsFile - - A list of names of attributes that should be - passed via files rather than environment variables. For example, - if you have - - -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). - - - - - preferLocalBuild - - If this attribute is set to - true and distributed building is - enabled, then, if possible, the derivaton will be built - locally instead of forwarded to a remote machine. This is - appropriate for trivial builders where the cost of doing a - download or remote build would exceed the cost of building - locally. - - - - - allowSubstitutes - - - If this attribute is set to - false, then Nix will always build this - derivation; it will not try to substitute its outputs. This is - useful for very trivial derivations (such as - writeText in Nixpkgs) that are cheaper to - build than to substitute from a binary cache. - - You need to have a builder configured which satisfies - the derivation’s system attribute, since the - derivation cannot be substituted. Thus it is usually a good idea - to align system with - builtins.currentSystem when setting - allowSubstitutes to false. - For most trivial derivations this should be the case. - - - - - - - - -
diff --git a/doc/manual/expressions/arguments-variables.xml b/doc/manual/expressions/arguments-variables.xml deleted file mode 100644 index bf60cb7ee..000000000 --- a/doc/manual/expressions/arguments-variables.xml +++ /dev/null @@ -1,121 +0,0 @@ -
- -Arguments and Variables - - - -Composing GNU Hello -(<filename>all-packages.nix</filename>) - -... - -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 = ...; - -} - - - -The Nix expression in is a -function; it is missing some arguments that have to be filled in -somewhere. In the Nix Packages collection this is done in the file -pkgs/top-level/all-packages.nix, where all -Nix expressions for packages are imported and called with the -appropriate arguments. shows -some fragments of -all-packages.nix. - - - - - - This file defines a set of attributes, all of which are - concrete derivations (i.e., not functions). In fact, we define a - mutually recursive set of attributes. That - is, the attributes can refer to each other. This is precisely - what we want since we want to plug the - various packages into each other. - - - - - - Here we import the Nix expression for - GNU Hello. The import operation just loads and returns the - specified Nix expression. In fact, we could just have put the - contents of in - all-packages.nix at this point. That - would be completely equivalent, but it would make the file rather - bulky. - - Note that we refer to - ../applications/misc/hello/ex-1, not - ../applications/misc/hello/ex-1/default.nix. - When you try to import a directory, Nix automatically appends - /default.nix to the file name. - - - - - - This is where the actual composition takes place. Here we - call the function imported from - ../applications/misc/hello/ex-1 with a set - containing the things that the function expects, namely - fetchurl, stdenv, and - perl. We use inherit again to use the - attributes defined in the surrounding scope (we could also have - written fetchurl = fetchurl;, etc.). - - The result of this function call is an actual derivation - that can be built by Nix (since when we fill in the arguments of - the function, what we get is its body, which is the call to - stdenv.mkDerivation in ). - - Nixpkgs has a convenience function - callPackage that imports and 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 { }; - - - If necessary, you can set or override arguments: - - -hello = callPackage ../applications/misc/hello/ex-1 { stdenv = myStdenv; }; - - - - - - - - - Likewise, we have to instantiate Perl, - fetchurl, and the standard environment. - - - - - -
\ No newline at end of file diff --git a/doc/manual/expressions/build-script.xml b/doc/manual/expressions/build-script.xml deleted file mode 100644 index 7bad8f808..000000000 --- a/doc/manual/expressions/build-script.xml +++ /dev/null @@ -1,119 +0,0 @@ -
- -Build Script - -Build script for GNU Hello -(<filename>builder.sh</filename>) - -source $stdenv/setup - -PATH=$perl/bin:$PATH - -tar xvfz $src -cd hello-* -./configure --prefix=$out -make -make install - - - shows the builder referenced -from Hello's Nix expression (stored in -pkgs/applications/misc/hello/ex-1/builder.sh). -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 steps to -elucidate what a builder does. It performs the following -steps: - - - - - - When Nix runs a builder, it initially completely clears the - environment (except for the attributes declared in the - derivation). For instance, the PATH variable is - emptyActually, it's initialised to - /path-not-set to prevent Bash from setting it - to a default value.. This is done to prevent - undeclared inputs from being used in the build process. If for - example the PATH contained - /usr/bin, then you might accidentally use - /usr/bin/gcc. - - So the first step is to set up the environment. This is - done by calling the setup script of the - standard environment. The environment variable - stdenv points to the location of the standard - environment being used. (It wasn't specified explicitly as an - attribute in , but - mkDerivation adds it automatically.) - - - - - - Since Hello needs Perl, we have to make sure that Perl is in - the PATH. The perl environment - variable points to the location of the Perl package (since it - was passed in as an attribute to the derivation), so - $perl/bin is the - directory containing the Perl interpreter. - - - - - - Now we have to unpack the sources. The - src attribute was bound to the result of - fetching the Hello source tarball from the network, so the - src environment variable points to the location in - the Nix store to which the tarball was downloaded. After - unpacking, we cd to the resulting source - directory. - - The whole build is performed in a temporary directory - created in /tmp, by the way. This directory is - removed after the builder finishes, so there is no need to clean - up the sources afterwards. Also, the temporary directory is - always newly created, so you don't have to worry about files from - previous builds interfering with the current build. - - - - - - GNU Hello is a typical Autoconf-based package, so we first - have to run its configure script. In Nix - every package is stored in a separate location in the Nix store, - for instance - /nix/store/9a54ba97fb71b65fda531012d0443ce2-hello-2.1.1. - Nix computes this path by cryptographically hashing all attributes - of the derivation. The path is passed to the builder through the - out environment variable. So here we give - configure the parameter - --prefix=$out to cause Hello to be installed in - the expected location. - - - - - - Finally we build Hello (make) and install - it into the location specified by out - (make install). - - - - - -If you are wondering about the absence of error checking on the -result of various commands called in the builder: this is because the -shell script is evaluated with Bash's option, -which causes the script to be aborted if any command fails without an -error check. - -
\ No newline at end of file diff --git a/doc/manual/expressions/builder-syntax.xml b/doc/manual/expressions/builder-syntax.xml deleted file mode 100644 index e51bade44..000000000 --- a/doc/manual/expressions/builder-syntax.xml +++ /dev/null @@ -1,119 +0,0 @@ -
- -Builder Syntax - -Build script for GNU Hello -(<filename>builder.sh</filename>) - -source $stdenv/setup - -PATH=$perl/bin:$PATH - -tar xvfz $src -cd hello-* -./configure --prefix=$out -make -make install - - - shows the builder referenced -from Hello's Nix expression (stored in -pkgs/applications/misc/hello/ex-1/builder.sh). -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 steps to -elucidate what a builder does. It performs the following -steps: - - - - - - When Nix runs a builder, it initially completely clears the - environment (except for the attributes declared in the - derivation). For instance, the PATH variable is - emptyActually, it's initialised to - /path-not-set to prevent Bash from setting it - to a default value.. This is done to prevent - undeclared inputs from being used in the build process. If for - example the PATH contained - /usr/bin, then you might accidentally use - /usr/bin/gcc. - - So the first step is to set up the environment. This is - done by calling the setup script of the - standard environment. The environment variable - stdenv points to the location of the standard - environment being used. (It wasn't specified explicitly as an - attribute in , but - mkDerivation adds it automatically.) - - - - - - Since Hello needs Perl, we have to make sure that Perl is in - the PATH. The perl environment - variable points to the location of the Perl package (since it - was passed in as an attribute to the derivation), so - $perl/bin is the - directory containing the Perl interpreter. - - - - - - Now we have to unpack the sources. The - src attribute was bound to the result of - fetching the Hello source tarball from the network, so the - src environment variable points to the location in - the Nix store to which the tarball was downloaded. After - unpacking, we cd to the resulting source - directory. - - The whole build is performed in a temporary directory - created in /tmp, by the way. This directory is - removed after the builder finishes, so there is no need to clean - up the sources afterwards. Also, the temporary directory is - always newly created, so you don't have to worry about files from - previous builds interfering with the current build. - - - - - - GNU Hello is a typical Autoconf-based package, so we first - have to run its configure script. In Nix - every package is stored in a separate location in the Nix store, - for instance - /nix/store/9a54ba97fb71b65fda531012d0443ce2-hello-2.1.1. - Nix computes this path by cryptographically hashing all attributes - of the derivation. The path is passed to the builder through the - out environment variable. So here we give - configure the parameter - --prefix=$out to cause Hello to be installed in - the expected location. - - - - - - Finally we build Hello (make) and install - it into the location specified by out - (make install). - - - - - -If you are wondering about the absence of error checking on the -result of various commands called in the builder: this is because the -shell script is evaluated with Bash's option, -which causes the script to be aborted if any command fails without an -error check. - -
\ No newline at end of file diff --git a/doc/manual/expressions/builtins.xml b/doc/manual/expressions/builtins.xml deleted file mode 100644 index a18c5801a..000000000 --- a/doc/manual/expressions/builtins.xml +++ /dev/null @@ -1,1668 +0,0 @@ -
- -Built-in Functions - -This section lists the functions and constants built into the -Nix expression evaluator. (The built-in function -derivation is discussed above.) Some built-ins, -such as derivation, are always in scope of every -Nix expression; you can just access them right away. But to prevent -polluting the namespace too much, most built-ins are not in scope. -Instead, you can access them through the builtins -built-in value, which is a set that contains all built-in functions -and values. For instance, derivation is also -available as builtins.derivation. - - - - - - - abort s - builtins.abort s - - Abort Nix expression evaluation, print error - message s. - - - - - - builtins.add - e1 e2 - - - Return the sum of the numbers - e1 and - e2. - - - - - - builtins.all - pred list - - Return true if the function - pred returns true - for all elements of list, - and false otherwise. - - - - - - builtins.any - pred list - - Return true if the function - pred returns true - for at least one element of list, - and false otherwise. - - - - - - builtins.attrNames - set - - Return the names of the attributes in the set - set in an alphabetically sorted list. For instance, - builtins.attrNames { y = 1; x = "foo"; } - evaluates to [ "x" "y" ]. - - - - - - builtins.attrValues - set - - Return the values of the attributes in the set - set in the order corresponding to the - sorted attribute names. - - - - - - baseNameOf s - - Return the base name of the - string s, that is, everything following - the final slash in the string. This is similar to the GNU - basename command. - - - - - - builtins.bitAnd - e1 e2 - - Return the bitwise AND of the integers - e1 and - e2. - - - - - - builtins.bitOr - e1 e2 - - Return the bitwise OR of the integers - e1 and - e2. - - - - - - builtins.bitXor - e1 e2 - - Return the bitwise XOR of the integers - e1 and - e2. - - - - - - builtins - - The set builtins contains all - the built-in functions and values. 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 "" - - This allows a Nix expression to fall back gracefully on older Nix - installations that don’t have the desired built-in - function. - - - - - - builtins.compareVersions - s1 s2 - - Compare two strings representing versions and - return -1 if version - s1 is older than version - s2, 0 if they are - the same, and 1 if - s1 is newer than - s2. The version comparison algorithm - is the same as the one used by nix-env - -u. - - - - - - builtins.concatLists - lists - - Concatenate a list of lists into a single - list. - - - - - builtins.concatStringsSep - separator list - - Concatenate a list of strings with a separator - between each element, e.g. concatStringsSep "/" - ["usr" "local" "bin"] == "usr/local/bin" - - - - - builtins.currentSystem - - The built-in value currentSystem - evaluates to the Nix platform identifier for the Nix installation - on which the expression is being evaluated, such as - "i686-linux" or - "x86_64-darwin". - - - - - - - - - - - - builtins.deepSeq - e1 e2 - - This is like seq - e1 - e2, except that - e1 is evaluated - deeply: if it’s a list or set, its elements - or attributes are also evaluated recursively. - - - - - - derivation - attrs - builtins.derivation - attrs - - derivation is described in - . - - - - - - dirOf s - builtins.dirOf s - - Return the directory part of the string - s, that is, everything before the final - slash in the string. This is similar to the GNU - dirname command. - - - - - - builtins.div - e1 e2 - - Return the quotient of the numbers - e1 and - e2. - - - - - builtins.elem - x xs - - Return true if a value equal to - x occurs in the list - xs, and false - otherwise. - - - - - - builtins.elemAt - xs n - - Return element n from - the list xs. Elements are counted - starting from 0. A fatal error occurs if the index is out of - bounds. - - - - - - builtins.fetchurl - url - - Download the specified URL and return the path of - the downloaded file. This function is not available if restricted evaluation mode is - enabled. - - - - - - fetchTarball - url - builtins.fetchTarball - url - - Download the specified URL, unpack it and return - the path of the unpacked tree. The file must be a tape archive - (.tar) compressed with - gzip, bzip2 or - xz. The top-level path component of the files - in the tarball is removed, so it is best if the tarball contains a - single directory at top level. The typical use of the function is - to obtain external Nix expression dependencies, such as a - particular version of Nixpkgs, e.g. - - -with import (fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz) {}; - -stdenv.mkDerivation { … } - - - - The fetched tarball is cached for a certain amount of time - (1 hour by default) in ~/.cache/nix/tarballs/. - You can change the cache timeout either on the command line with - 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. - - - This function can also verify the contents against a hash. - In that case, the function takes a set instead of a URL. The set - requires the attribute url and the attribute - sha256, e.g. - - -with import (fetchTarball { - url = "https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz"; - sha256 = "1jppksrfvbk5ypiqdz4cddxdl8z6zyzdb2srq8fcffr327ld5jj2"; -}) {}; - -stdenv.mkDerivation { … } - - - - - This function is not available if restricted evaluation mode is - enabled. - - - - - - builtins.fetchGit - args - - - - - Fetch a path from git. args can be - a URL, in which case the HEAD of the repo at that URL is - fetched. Otherwise, it can be an attribute with the following - attributes (all except url optional): - - - - - url - - - The URL of the repo. - - - - - name - - - The name of the directory the repo should be exported to - in the store. Defaults to the basename of the URL. - - - - - rev - - - The git revision to fetch. Defaults to the tip of - ref. - - - - - ref - - - The git ref to look for the requested revision under. - This is often a branch or tag name. Defaults to - HEAD. - - - - By default, the ref value is prefixed - with refs/heads/. As of Nix 2.3.0 - Nix will not prefix refs/heads/ if - ref starts with refs/. - - - - - submodules - - - A Boolean parameter that specifies whether submodules - should be checked out. Defaults to - false. - - - - - - - Fetching a private repository over SSH - builtins.fetchGit { - url = "git@github.com:my-secret/repository.git"; - ref = "master"; - rev = "adab8b916a45068c044658c4158d81878f9ed1c3"; -} - - - - Fetching an arbitrary ref - builtins.fetchGit { - url = "https://github.com/NixOS/nix.git"; - ref = "refs/heads/0.5-release"; -} - - - - Fetching a repository's specific commit on an arbitrary branch - - If the revision you're looking for is in the default branch - of the git repository you don't strictly need to specify - the branch name in the ref attribute. - - - However, if the revision you're looking for is in a future - branch for the non-default branch you will need to specify - the the ref attribute as well. - - builtins.fetchGit { - url = "https://github.com/nixos/nix.git"; - rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452"; - ref = "1.11-maintenance"; -} - - - It is nice to always specify the branch which a revision - belongs to. Without the branch being specified, the - fetcher might fail if the default branch changes. - Additionally, it can be confusing to try a commit from a - non-default branch and see the fetch fail. If the branch - is specified the fault is much more obvious. - - - - - - Fetching a repository's specific commit on the default branch - - 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"; -} - - - - Fetching a tag - builtins.fetchGit { - url = "https://github.com/nixos/nix.git"; - ref = "refs/tags/1.9"; -} - - - - Fetching the latest version of a remote branch - - builtins.fetchGit can behave impurely - fetch the latest version of a remote branch. - - Nix will refetch the branch in accordance to - . - This behavior is disabled in - Pure evaluation mode. - builtins.fetchGit { - url = "ssh://git@github.com/nixos/nix.git"; - ref = "master"; -} - - - - - - builtins.filter - f xs - - Return a list consisting of the elements of - xs for which the function - f returns - true. - - - - - - builtins.filterSource - e1 e2 - - - - This function allows you to copy sources into the Nix - store while filtering certain files. For instance, suppose that - you want to use the directory source-dir as - an input to a Nix expression, e.g. - - -stdenv.mkDerivation { - ... - src = ./source-dir; -} - - - However, if source-dir is a Subversion - working copy, then all those annoying .svn - subdirectories will also be copied to the store. Worse, the - contents of those directories may change a lot, causing lots of - spurious rebuilds. With filterSource you - can filter out the .svn directories: - - - src = builtins.filterSource - (path: type: type != "directory" || baseNameOf path != ".svn") - ./source-dir; - - - - - Thus, the first argument e1 - must be a predicate function that is called for each regular - file, directory or symlink in the source tree - e2. If the function returns - true, the file is copied to the Nix store, - otherwise it is omitted. The function is called with two - arguments. The first is the full path of the file. The second - is a string that identifies the type of the file, which is - either "regular", - "directory", "symlink" or - "unknown" (for other kinds of files such as - device nodes or fifos — but note that those cannot be copied to - the Nix store, so if the predicate returns - true for them, the copy will fail). If you - exclude a directory, the entire corresponding subtree of - e2 will be excluded. - - - - - - - - builtins.foldl’ - op nul list - - Reduce a list by applying a binary operator, from - left to right, e.g. foldl’ op nul [x0 x1 x2 ...] = op (op - (op nul x0) x1) x2) .... The operator is applied - strictly, i.e., its arguments are evaluated first. For example, - foldl’ (x: y: x + y) 0 [1 2 3] evaluates to - 6. - - - - - - builtins.functionArgs - f - - - Return a set containing the names of the formal arguments expected - by the function f. - The value of each attribute is a Boolean denoting whether the corresponding - argument has a default value. For instance, - functionArgs ({ x, y ? 123}: ...) = { x = false; y = true; }. - - - "Formal argument" here refers to the attributes pattern-matched by - the function. Plain lambdas are not included, e.g. - functionArgs (x: ...) = { }. - - - - - - builtins.fromJSON e - - Convert a JSON string to a Nix - value. For example, - - -builtins.fromJSON ''{"x": [1, 2, 3], "y": null}'' - - - returns the value { x = [ 1 2 3 ]; y = null; - }. - - - - - - builtins.genList - generator length - - Generate list of size - length, with each element - i equal to the value returned by - generator i. For - example, - - -builtins.genList (x: x * x) 5 - - - returns the list [ 0 1 4 9 16 ]. - - - - - - builtins.getAttr - s set - - getAttr returns the attribute - named s from - set. Evaluation aborts if the - attribute doesn’t exist. This is a dynamic version of the - . operator, since s - is an expression rather than an identifier. - - - - - - builtins.getEnv - s - - getEnv returns the value of - the environment variable s, or an empty - string if the variable doesn’t exist. This function should be - used with care, as it can introduce all sorts of nasty environment - dependencies in your Nix expression. - - getEnv is used in Nix Packages to - locate the file ~/.nixpkgs/config.nix, which - contains user-local settings for Nix Packages. (That is, it does - a getEnv "HOME" to locate the user’s home - directory.) - - - - - - builtins.hasAttr - s set - - hasAttr returns - true if set has an - attribute named s, and - false otherwise. This is a dynamic version of - the ? operator, since - s is an expression rather than an - identifier. - - - - - - builtins.hashString - type s - - Return a base-16 representation of the - cryptographic hash of string s. The - hash algorithm specified by type must - be one of "md5", "sha1", - "sha256" or "sha512". - - - - - - builtins.hashFile - type p - - Return a base-16 representation of the - cryptographic hash of the file at path p. The - hash algorithm specified by type must - be one of "md5", "sha1", - "sha256" or "sha512". - - - - - - builtins.head - list - - Return the first element of a list; abort - evaluation if the argument isn’t a list or is an empty list. You - can test whether a list is empty by comparing it with - []. - - - - - - import - path - builtins.import - path - - Load, parse and return the Nix expression in the - file path. If path - is a directory, the file default.nix - in that directory is loaded. Evaluation aborts if the - file doesn’t exist or contains an incorrect Nix expression. - import implements Nix’s module system: you - can put any Nix expression (such as a set or a function) in a - separate file, and use it from Nix expressions in other - files. - - Unlike some languages, import is a regular - function in Nix. Paths using the angle bracket syntax (e.g., - import <foo>) are normal path - values (see ). - - A Nix expression loaded by import must - not contain any free variables (identifiers - that are not defined in the Nix expression itself and are not - built-in). Therefore, it cannot refer to variables that are in - scope at the call site. For instance, if you have a calling - expression - - -rec { - x = 123; - y = import ./foo.nix; -} - - then the following foo.nix will give an - error: - - -x + 456 - - since x is not in scope in - foo.nix. If you want x - to be available in foo.nix, you should pass - it as a function argument: - - -rec { - x = 123; - y = import ./foo.nix x; -} - - and - - -x: x + 456 - - (The function argument doesn’t have to be called - x in foo.nix; any name - would work.) - - - - - - builtins.intersectAttrs - e1 e2 - - Return a set consisting of the attributes in the - set e2 that also exist in the set - e1. - - - - - - builtins.isAttrs - e - - Return true if - e evaluates to a set, and - false otherwise. - - - - - - builtins.isList - e - - Return true if - e evaluates to a list, and - false otherwise. - - - - - builtins.isFunction - e - - Return true if - e evaluates to a function, and - false otherwise. - - - - - - builtins.isString - e - - Return true if - e evaluates to a string, and - false otherwise. - - - - - - builtins.isInt - e - - Return true if - e evaluates to an int, and - false otherwise. - - - - - - builtins.isFloat - e - - Return true if - e evaluates to a float, and - false otherwise. - - - - - - builtins.isBool - e - - Return true if - e evaluates to a bool, and - false otherwise. - - - - builtins.isPath - e - - Return true if - e evaluates to a path, and - false otherwise. - - - - - isNull - e - builtins.isNull - e - - Return true if - e evaluates to null, - and false otherwise. - - This function is deprecated; - just write e == null instead. - - - - - - - - builtins.length - e - - Return the length of the list - e. - - - - - - builtins.lessThan - e1 e2 - - Return true if the number - e1 is less than the number - e2, and false - otherwise. Evaluation aborts if either - e1 or e2 - does not evaluate to a number. - - - - - - builtins.listToAttrs - e - - Construct a set from a list specifying the names - and values of each attribute. Each element of the list should be - a set consisting of a string-valued attribute - name specifying the name of the attribute, and - an attribute value specifying its value. - Example: - - -builtins.listToAttrs - [ { name = "foo"; value = 123; } - { name = "bar"; value = 456; } - ] - - - evaluates to - - -{ foo = 123; bar = 456; } - - - - - - - - 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" ] - - evaluates to [ "foobar" "foobla" "fooabc" - ]. - - - - - - builtins.match - regex str - - Returns a list if the extended - POSIX regular expression regex - matches str precisely, otherwise returns - null. Each item in the list is a regex group. - - -builtins.match "ab" "abc" - - -Evaluates to null. - - -builtins.match "abc" "abc" - - -Evaluates to [ ]. - - -builtins.match "a(b)(c)" "abc" - - -Evaluates to [ "b" "c" ]. - - -builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" " FOO " - - -Evaluates to [ "foo" ]. - - - - - - builtins.mul - e1 e2 - - Return the product of the numbers - e1 and - e2. - - - - - - builtins.parseDrvName - s - - Split the string s into - a package name and version. The package name is everything up to - but not including the first dash followed by a digit, and the - version is everything following that dash. The result is returned - in a set { name, version }. Thus, - builtins.parseDrvName "nix-0.12pre12876" - returns { name = "nix"; version = "0.12pre12876"; - }. - - - - - - builtins.path - args - - - - - An enrichment of the built-in path type, based on the attributes - present in args. All are optional - except path: - - - - - path - - The underlying path. - - - - name - - - The name of the path when added to the store. This can - used to reference paths that have nix-illegal characters - in their names, like @. - - - - - filter - - - A function of the type expected by - builtins.filterSource, - with the same semantics. - - - - - recursive - - - When false, when - path is added to the store it is with a - flat hash, rather than a hash of the NAR serialization of - the file. Thus, path must refer to a - regular file, not a directory. This allows similar - behavior to fetchurl. Defaults to - true. - - - - - sha256 - - - When provided, this is the expected hash of the file at - the path. Evaluation will fail if the hash is incorrect, - and providing a hash allows - builtins.path to be used even when the - pure-eval nix config option is on. - - - - - - - - - builtins.pathExists - path - - Return true if the path - path exists at evaluation time, and - false otherwise. - - - - - builtins.placeholder - output - - Return a placeholder string for the specified - output that will be substituted by the - corresponding output path at build time. Typical outputs would be - "out", "bin" or - "dev". - - - - builtins.readDir - path - - Return the contents of the directory - path as a set mapping directory entries - to the corresponding file type. For instance, if directory - A contains a regular file - B and another directory - C, then builtins.readDir - ./A will return the set - - -{ B = "regular"; C = "directory"; } - - The possible values for the file type are - "regular", "directory", - "symlink" and - "unknown". - - - - - - builtins.readFile - path - - Return the contents of the file - path as a string. - - - - - - removeAttrs - set list - builtins.removeAttrs - set list - - Remove the attributes listed in - list from - set. The attributes don’t have to - exist in set. For instance, - - -removeAttrs { x = 1; y = 2; z = 3; } [ "a" "x" "z" ] - - evaluates to { y = 2; }. - - - - - - builtins.replaceStrings - from to s - - Given string s, replace - every occurrence of the strings in from - with the corresponding string in - to. For example, - - -builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar" - - - evaluates to "fabir". - - - - - - builtins.seq - e1 e2 - - Evaluate e1, then - evaluate and return e2. This ensures - that a computation is strict in the value of - e1. - - - - - - builtins.sort - comparator list - - Return list in sorted - order. It repeatedly calls the function - comparator with two elements. The - comparator should return true if the first - element is less than the second, and false - otherwise. For example, - - -builtins.sort builtins.lessThan [ 483 249 526 147 42 77 ] - - - produces the list [ 42 77 147 249 483 526 - ]. - - This is a stable sort: it preserves the relative order of - elements deemed equal by the comparator. - - - - - - builtins.split - regex str - - Returns a list composed of non matched strings interleaved - with the lists of the extended - POSIX regular expression regex matches - of str. Each item in the lists of matched - sequences is a regex group. - - -builtins.split "(a)b" "abc" - - -Evaluates to [ "" [ "a" ] "c" ]. - - -builtins.split "([ac])" "abc" - - -Evaluates to [ "" [ "a" ] "b" [ "c" ] "" ]. - - -builtins.split "(a)|(c)" "abc" - - -Evaluates to [ "" [ "a" null ] "b" [ null "c" ] "" ]. - - -builtins.split "([[:upper:]]+)" " FOO " - - -Evaluates to [ " " [ "FOO" ] " " ]. - - - - - - - builtins.splitVersion - s - - Split a string representing a version into its - components, by the same version splitting logic underlying the - version comparison in - nix-env -u. - - - - - - builtins.stringLength - e - - Return the length of the string - e. If e is - not a string, evaluation is aborted. - - - - - - builtins.sub - e1 e2 - - Return the difference between the numbers - e1 and - e2. - - - - - - builtins.substring - start len - s - - Return the substring of - s from character position - start (zero-based) up to but not - including start + len. If - start is greater than the length of the - string, an empty string is returned, and if start + - len lies beyond the end of the string, only the - substring up to the end of the string is returned. - start must be - non-negative. For example, - - -builtins.substring 0 3 "nixos" - - - evaluates to "nix". - - - - - - - builtins.tail - list - - Return the second to last elements of a list; - abort evaluation if the argument isn’t a list or is an empty - list. - - - - - - throw - s - builtins.throw - s - - Throw an error message - s. This usually aborts Nix expression - evaluation, but in nix-env -qa and other - commands that try to evaluate a set of derivations to get - information about those derivations, a derivation that throws an - error is silently skipped (which is not the case for - abort). - - - - - - builtins.toFile - name - s - - Store the string s in a - file in the Nix store and return its path. The file has suffix - name. This file can be used as an - input to derivations. One application is to write builders - “inline”. For instance, the following Nix expression combines - and into one file: - - -{ stdenv, fetchurl, perl }: - -stdenv.mkDerivation { - name = "hello-2.1.1"; - - builder = builtins.toFile "builder.sh" " - source $stdenv/setup - - PATH=$perl/bin:$PATH - - tar xvfz $src - cd hello-* - ./configure --prefix=$out - make - make install - "; - - src = fetchurl { - url = "http://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz"; - sha256 = "1md7jsfd8pa45z73bz1kszpp01yw6x5ljkjk2hx7wl800any6465"; - }; - inherit perl; -} - - - - It is even possible for one file to refer to another, e.g., - - - builder = let - configFile = builtins.toFile "foo.conf" " - # This is some dummy configuration file. - ... - "; - in builtins.toFile "builder.sh" " - source $stdenv/setup - ... - cp ${configFile} $out/etc/foo.conf - "; - - Note that ${configFile} is an antiquotation - (see ), so the result of the - expression configFile (i.e., a path like - /nix/store/m7p7jfny445k...-foo.conf) will be - spliced into the resulting string. - - It is however not allowed to have files - mutually referring to each other, like so: - - -let - foo = builtins.toFile "foo" "...${bar}..."; - bar = builtins.toFile "bar" "...${foo}..."; -in foo - - This is not allowed because it would cause a cyclic dependency in - the computation of the cryptographic hashes for - foo and bar. - It is also not possible to reference the result of a derivation. - If you are using Nixpkgs, the writeTextFile function is able to - do that. - - - - - - builtins.toJSON e - - Return a string containing a JSON representation - of e. Strings, integers, floats, booleans, - nulls and lists are mapped to their JSON equivalents. Sets - (except derivations) are represented as objects. Derivations are - translated to a JSON string containing the derivation’s output - path. Paths are copied to the store and represented as a JSON - string of the resulting store path. - - - - - - builtins.toPath s - - DEPRECATED. Use /. + "/path" - to convert a string into an absolute path. For relative paths, - use ./. + "/path". - - - - - - - toString e - builtins.toString e - - Convert the expression - e to a string. - e can be: - - A string (in which case the string is returned unmodified). - A path (e.g., toString /foo/bar yields "/foo/bar". - A set containing { __toString = self: ...; }. - An integer. - A list, in which case the string representations of its elements are joined with spaces. - A Boolean (false yields "", true yields "1"). - null, which yields the empty string. - - - - - - - - builtins.toXML e - - Return a string containing an XML representation - of e. The main application for - toXML is to communicate information with the - builder in a more structured format than plain environment - variables. - - - - shows an example where this is - the case. The builder is supposed to generate the configuration - file for a Jetty - servlet container. A servlet container contains a number - of servlets (*.war files) each exported under - a specific URI prefix. So the servlet configuration is a list of - sets containing the path and - war of the servlet (). This kind of information is - difficult to communicate with the normal method of passing - information through an environment variable, which just - concatenates everything together into a string (which might just - work in this case, but wouldn’t work if fields are optional or - contain lists themselves). Instead the Nix expression is - converted to an XML representation with - toXML, which is unambiguous and can easily be - processed with the appropriate tools. For instance, in the - example an XSLT stylesheet () is applied to it () to - generate the XML configuration file for the Jetty server. The XML - representation produced from by toXML is shown in . - - Note that uses the toFile built-in to write the - builder and the stylesheet “inline” in the Nix expression. The - path of the stylesheet is spliced into the builder at - xsltproc ${stylesheet} - .... - - Passing information to a builder - using <function>toXML</function> - - $out/server-conf.xml]]> - - - - - - - - - - - - - "; - - servlets = builtins.toXML []]> - - - - XML representation produced by - <function>toXML</function> - - - - - - - - - - - - - - - - - - - - - -]]> - - - - - - - - - - builtins.trace - e1 e2 - - Evaluate e1 and print its - abstract syntax representation on standard error. Then return - e2. This function is useful for - debugging. - - - - - builtins.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 - false. - - - - - - - builtins.typeOf - e - - Return a string representing the type of the value - e, namely "int", - "bool", "string", - "path", "null", - "set", "list", - "lambda" or - "float". - - - - - - - -
diff --git a/doc/manual/expressions/derivations.xml b/doc/manual/expressions/derivations.xml deleted file mode 100644 index 6f6297565..000000000 --- a/doc/manual/expressions/derivations.xml +++ /dev/null @@ -1,211 +0,0 @@ -
- -Derivations - -The most important built-in function is -derivation, which is used to describe a single -derivation (a build action). It takes as input a set, the attributes -of which specify the inputs of the build. - - - - There must be an attribute named - system whose value must be a string specifying a - Nix platform identifier, such as "i686-linux" or - "x86_64-darwin"To figure out - your platform identifier, look at the line Checking for the - canonical Nix system name in the output of Nix's - configure script. The build - can only be performed on a machine and operating system matching the - platform identifier. (Nix can automatically forward builds for - other platforms by forwarding them to other machines; see .) - - There must be an attribute named - name whose value must be a string. This is used - as a symbolic name for the package by nix-env, - and it is appended to the output paths of the - derivation. - - There must be an attribute named - builder that identifies the program that is - executed to perform the build. It can be either a derivation or a - source (a local file reference, e.g., - ./builder.sh). - - Every attribute is passed as an environment variable - to the builder. Attribute values are translated to environment - variables as follows: - - - - Strings and numbers are just passed - verbatim. - - A path (e.g., - ../foo/sources.tar) causes the referenced - file to be copied to the store; its location in the store is put - in the environment variable. The idea is that all sources - should reside in the Nix store, since all inputs to a derivation - should reside in the Nix store. - - A derivation causes that - derivation to be built prior to the present derivation; its - default output path is put in the environment - variable. - - Lists of the previous types are also allowed. - They are simply concatenated, separated by - spaces. - - true is passed as the string - 1, false and - null are passed as an empty string. - - - - - - The optional attribute args - specifies command-line arguments to be passed to the builder. It - should be a list. - - The optional attribute outputs - specifies a list of symbolic outputs of the derivation. By default, - a derivation produces a single output path, denoted as - out. However, derivations can produce multiple - output paths. This is useful because it allows outputs to be - downloaded or garbage-collected separately. For instance, imagine a - library package that provides a dynamic library, header files, and - documentation. A program that links against the library doesn’t - need the header files and documentation at runtime, and it doesn’t - need the documentation at build time. Thus, the library package - could specify: - -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 - - 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 ]; - - The first element of outputs determines the - default output. Thus, you could also write - -buildInputs = [ pkg pkg.headers ]; - - since pkg is equivalent to - pkg.lib. - - - -The function mkDerivation in the Nixpkgs -standard environment is a wrapper around -derivation that adds a default value for -system and always uses Bash as the builder, to -which the supplied builder is passed as a command-line argument. See -the Nixpkgs manual for details. - -The builder is executed as follows: - - - - A temporary directory is created under the directory - specified by TMPDIR (default - /tmp) where the build will take place. The - current directory is changed to this directory. - - The environment is cleared and set to the derivation - attributes, as specified above. - - In addition, the following variables are set: - - - - NIX_BUILD_TOP contains the path of - the temporary directory for this build. - - Also, TMPDIR, - TEMPDIR, TMP, TEMP - are set to point to the temporary directory. This is to prevent - the builder from accidentally writing temporary files anywhere - else. Doing so might cause interference by other - processes. - - PATH is set to - /path-not-set to prevent shells from - initialising it to their built-in default value. - - HOME is set to - /homeless-shelter to prevent programs from - using /etc/passwd or the like to find the - user's home directory, which could cause impurity. Usually, when - HOME is set, it is used as the location of the home - directory, even if it points to a non-existent - path. - - NIX_STORE is set to the path of the - top-level Nix store directory (typically, - /nix/store). - - For each output declared in - outputs, the corresponding environment variable - is set to point to the intended path in the Nix store for that - output. Each output path is a concatenation of the cryptographic - hash of all build inputs, the name attribute - and the output name. (The output name is omitted if it’s - out.) - - - - - - If an output path already exists, it is removed. - Also, locks are acquired to prevent multiple Nix instances from - performing the same build at the same time. - - A log of the combined standard output and error is - written to /nix/var/log/nix. - - The builder is executed with the arguments specified - by the attribute args. If it exits with exit - code 0, it is considered to have succeeded. - - The temporary directory is removed (unless the - option was specified). - - If the build was successful, Nix scans each output - path for references to input paths by looking for the hash parts of - the input paths. Since these are potential runtime dependencies, - Nix registers them as dependencies of the output - paths. - - After the build, Nix sets the last-modified - timestamp on all files in the build result to 1 (00:00:01 1/1/1970 - UTC), sets the group to the default group, and sets the mode of the - file to 0444 or 0555 (i.e., read-only, with execute permission - enabled if the file was originally executable). Note that possible - setuid and setgid bits are - cleared. Setuid and setgid programs are not currently supported by - Nix. This is because the Nix archives used in deployment have no - concept of ownership information, and because it makes the build - result dependent on the user performing the build. - - - - - - - -
diff --git a/doc/manual/expressions/expression-language.xml b/doc/manual/expressions/expression-language.xml deleted file mode 100644 index 240ef80f1..000000000 --- a/doc/manual/expressions/expression-language.xml +++ /dev/null @@ -1,30 +0,0 @@ - - -Nix Expression Language - -The Nix expression language is a pure, lazy, functional -language. Purity means that operations in the language don't have -side-effects (for instance, there is no variable assignment). -Laziness means that arguments to functions are evaluated only when -they are needed. Functional means that functions are -normal values that can be passed around and manipulated -in interesting ways. The language is not a full-featured, general -purpose language. Its main job is to describe packages, -compositions of packages, and the variability within -packages. - -This section presents the various features of the -language. - - - - - - - - - diff --git a/doc/manual/expressions/expression-syntax.xml b/doc/manual/expressions/expression-syntax.xml deleted file mode 100644 index a3de20713..000000000 --- a/doc/manual/expressions/expression-syntax.xml +++ /dev/null @@ -1,148 +0,0 @@ -
- -Expression Syntax - -Nix expression for GNU Hello -(<filename>default.nix</filename>) - -{ 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; -} - - - shows a Nix expression for GNU -Hello. It's actually already in the Nix Packages collection in -pkgs/applications/misc/hello/ex-1/default.nix. -It is customary to place each package in a separate directory and call -the single Nix expression in that directory -default.nix. The file has the following elements -(referenced from the figure by number): - - - - - - This states that the expression is a - function that expects to be called with three - arguments: stdenv, fetchurl, - and perl. They are needed to build Hello, but - we don't know how to build them here; that's why they are function - arguments. stdenv is a package that is used - by almost all Nix Packages packages; it provides a - standard environment consisting of the things you - would expect in a basic Unix environment: a C/C++ compiler (GCC, - to be precise), the Bash shell, fundamental Unix tools such as - cp, grep, - tar, 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. - - - - - - 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; }. - - - - - - 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. - - - - - - The attribute builder specifies the - builder. This attribute can sometimes be omitted, in which case - mkDerivation will fill in a default builder - (which does a configure; make; make install, in - essence). Hello is sufficiently simple that the default builder - would suffice, but in this case, we will show an actual builder - for educational purposes. The value - ./builder.sh refers to the shell script shown - in , discussed below. - - - - - - The builder has to know what the sources of the package - are. Here, the attribute src is bound to the - result of a call to the fetchurl function. - Given a URL and a SHA-256 hash of the expected contents of the file - at that URL, this function builds a derivation that downloads the - file and checks its hash. So the sources are a dependency that - like all other dependencies is built before Hello itself is - built. - - Instead of src any other name could have - been used, and in fact there can be any number of sources (bound - to different attributes). However, src is - customary, and it's also expected by the default builder (which we - don't use in this example). - - - - - - Since the derivation requires Perl, we have to pass the - value of the 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; - - will do the trick: it binds an attribute perl - to the function argument which also happens to be called - perl. However, it looks a bit silly, so there - is a shorter syntax. The inherit keyword - causes the specified attributes to be bound to whatever variables - with the same name happen to be in scope. - - - - - - - -
diff --git a/doc/manual/expressions/generic-builder.xml b/doc/manual/expressions/generic-builder.xml deleted file mode 100644 index db7ff405d..000000000 --- a/doc/manual/expressions/generic-builder.xml +++ /dev/null @@ -1,98 +0,0 @@ -
- -Generic Builder Syntax - -Recall from that the builder -looked something like this: - - -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 -install. For this reason the standard environment provides some Bash -functions that automate the build process. A builder using the -generic build facilities in shown in . - -Build script using the generic -build functions - -buildInputs="$perl" - -source $stdenv/setup - -genericBuild - - - - - - - The buildInputs variable tells - setup to use the indicated packages as - inputs. This means that if a package provides a - bin subdirectory, it's added to - PATH; if it has a include - subdirectory, it's added to GCC's header search path; and so - on.How does it work? setup - tries to source the file - pkg/nix-support/setup-hook - of all dependencies. These “setup hooks” can then set up whatever - environment variables they want; for instance, the setup hook for - Perl sets the PERL5LIB environment variable to - contain the lib/site_perl directories of all - inputs. - - - - - - - The function genericBuild is defined in - the file $stdenv/setup. - - - - - - The final step calls the shell function - genericBuild, which performs the steps that - were done explicitly in . The - generic builder is smart enough to figure out whether to unpack - the sources using gzip, - bzip2, etc. It can be customised in many ways; - see the Nixpkgs manual for details. - - - - - -Discerning readers will note that the -buildInputs could just as well have been set in the Nix -expression, like this: - - - buildInputs = [ perl ]; - -The perl attribute can then be removed, and the -builder becomes even shorter: - - -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 entirely. - -
diff --git a/doc/manual/expressions/language-constructs.xml b/doc/manual/expressions/language-constructs.xml deleted file mode 100644 index 0d0cbbe15..000000000 --- a/doc/manual/expressions/language-constructs.xml +++ /dev/null @@ -1,409 +0,0 @@ -
- -Language Constructs - -Recursive sets - -Recursive sets are just normal sets, but the attributes can -refer to each other. For example, - - -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 would be invalid if no such variable exists. That -is, in a normal (non-recursive) set, attributes are not added to the -lexical scope; in a recursive set, they are. - -Recursive sets of course introduce the danger of infinite -recursion. For example, - - -rec { - x = y; - y = x; -}.x - -does not terminateActually, Nix detects infinite -recursion in this case and aborts (infinite recursion -encountered).. - - - - -Let-expressions - -A let-expression allows you to define local variables for an -expression. For instance, - - -let - x = "foo"; - y = "bar"; -in x + y - -evaluates to "foobar". - - - - - - -Inheriting attributes - -When defining a set or in a let-expression it is often convenient to 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; -} - -is equivalent to - - -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; - }; - - xlibs = { - libX11 = ...; - libXaw = ...; - ... - } - - libpng = ...; - libjpg = ...; - ... - -the set used in the function call to the function defined in -../tools/graphics/graphviz inherits a number of -variables from the surrounding scope (fetchurl -... yacc), but also inherits -libXaw (the X Athena Widgets) from the -xlibs (X11 client-side libraries) set. - - -Summarizing the fragment - - -... -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; -... - -when used while defining local variables in a let-expression or -while defining a set. - - - - -Functions - -Functions have the following form: - - -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 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 "" - - 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" ] - - 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 - - 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 - - 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, - - -{ x, y ? "foo", z ? "bar" }: z + y + x - - specifies a function that only requires an attribute named - x, but optionally accepts y - and z. - - - An @-pattern provides a means of referring - to the whole value being matched: - - args@{ x, y, z, ... }: z + y + x + args.a - -but can also be written as: - - { x, y, z, ... } @ args: z + y + x + args.a - - Here args is bound to the entire argument, which - is further matched against the pattern { x, y, z, - ... }. @-pattern makes mainly sense with an - ellipsis(...) as you can access attribute names as - a, using args.a, which was given as an - additional attribute to the function. - - - - - The args@ expression is bound to the argument passed to the function which - means that attributes with defaults that aren't explicitly specified in the function call - won't cause an evaluation error, but won't exist in args. - - - For instance - -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"; } - - - - - - -Conditionals - -Conditionals look like this: - - -if e1 then e2 else e3 - -where e1 is an expression that should -evaluate to a Boolean value (true or -false). - - - - -Assertions - -Assertions are generally used to check that certain requirements -on or between features and dependencies hold. They look like this: - - -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 evaluation is aborted and a backtrace is printed. - -Nix expression for Subversion - -{ 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; - ... -} - - - show how assertions are -used in the Nix expression for Subversion. - - - - - This assertion states that if Subversion is to have support - for local repositories, then Berkeley DB is needed. So if the - Subversion function is called with the - localServer argument set to - true but the db4 argument - set to null, then the evaluation fails. - - - - This is a more subtle condition: if Subversion is built with - Apache (httpServer) support, then the Expat - library (an XML library) used by Subversion should be same as the - one used by Apache. This is because in this configuration - Subversion code ends up being linked with Apache code, and if the - Expat libraries do not match, a build- or runtime link error or - incompatibility might occur. - - - - This assertion says that in order for Subversion to have SSL - support (so that it can access https URLs), an - OpenSSL library must be passed. Additionally, it says that - if Apache support is enabled, then Apache's - OpenSSL should match Subversion's. (Note that if Apache support - is not enabled, we don't care about Apache's OpenSSL.) - - - - The conditional here is not really related to assertions, - but is worth pointing out: it ensures that if SSL support is - disabled, then the Subversion derivation is not dependent on - OpenSSL, even if a non-null value was passed. - This prevents an unnecessary rebuild of Subversion if OpenSSL - changes. - - - - - - - - -With-expressions - -A with-expression, - - -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 - -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); ... - -makes all attributes defined in the file -definitions.nix available as 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; }; ... - -establishes the same scope as - - -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 /* -... */. - - - - -
diff --git a/doc/manual/expressions/language-operators.xml b/doc/manual/expressions/language-operators.xml deleted file mode 100644 index 4f11bf529..000000000 --- a/doc/manual/expressions/language-operators.xml +++ /dev/null @@ -1,222 +0,0 @@ -
- -Operators - - lists the operators in the -Nix expression language, in order of precedence (from strongest to -weakest binding). - - - Operators - - - - Name - Syntax - Associativity - Description - Precedence - - - - - Select - e . - attrpath - [ or def ] - - none - Select attribute denoted by the attribute path - attrpath from set - e. (An attribute path is a - dot-separated list of attribute names.) If the attribute - doesn’t exist, return def if - provided, otherwise abort evaluation. - 1 - - - Application - e1 e2 - left - Call function e1 with - argument e2. - 2 - - - Arithmetic Negation - - e - none - Arithmetic negation. - 3 - - - Has Attribute - e ? - attrpath - none - Test whether set e contains - the attribute denoted by attrpath; - return true or - false. - 4 - - - List Concatenation - e1 ++ e2 - right - List concatenation. - 5 - - - Multiplication - - e1 * e2, - - left - Arithmetic multiplication. - 6 - - - Division - - e1 / e2 - - left - Arithmetic division. - 6 - - - Addition - - e1 + e2 - - left - Arithmetic addition. - 7 - - - Subtraction - - e1 - e2 - - left - Arithmetic subtraction. - 7 - - - String Concatenation - - string1 + string2 - - left - String concatenation. - 7 - - - Not - ! e - none - Boolean negation. - 8 - - - Update - e1 // - e2 - right - Return a set consisting of the attributes in - e1 and - e2 (with the latter taking - precedence over the former in case of equally named - attributes). - 9 - - - Less Than - - e1 < e2, - - none - Arithmetic comparison. - 10 - - - Less Than or Equal To - - e1 <= e2 - - none - Arithmetic comparison. - 10 - - - Greater Than - - e1 > e2 - - none - Arithmetic comparison. - 10 - - - Greater Than or Equal To - - e1 >= e2 - - none - Arithmetic comparison. - 10 - - - Equality - - e1 == e2 - - none - Equality. - 11 - - - Inequality - - e1 != e2 - - none - Inequality. - 11 - - - Logical AND - e1 && - e2 - left - Logical AND. - 12 - - - Logical OR - e1 || - e2 - left - Logical OR. - 13 - - - Logical Implication - e1 -> - e2 - none - Logical implication (equivalent to - !e1 || - e2). - 14 - - - -
- -
diff --git a/doc/manual/expressions/language-values.xml b/doc/manual/expressions/language-values.xml deleted file mode 100644 index bb2090c88..000000000 --- a/doc/manual/expressions/language-values.xml +++ /dev/null @@ -1,313 +0,0 @@ -
- -Values - - -Simple Values - -Nix has the following basic data types: - - - - - - Strings can be written in three - ways. - - The most common way is to enclose the string between double - quotes, e.g., "foo bar". Strings can span - multiple lines. The special characters " and - \ and the character sequence - ${ must be escaped by prefixing them with a - backslash (\). Newlines, carriage returns and - tabs can be written as \n, - \r and \t, - respectively. - - You can include the result of an expression into a string by - enclosing it in - ${...}, a feature - known as antiquotation. The enclosed - expression must evaluate to something that can be coerced 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" - - (where freetype is a derivation), you can - instead write the more natural - - -"--with-freetype2-library=${freetype}/lib" - - The latter is automatically translated to the former. A more - complicated example (from the Nix expression for 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"} -"; - - Note that Nix expressions and strings can be arbitrarily nested; - in this case the outer string contains various antiquotations that - themselves contain strings (e.g., "-thread"), - some of which in turn contain expressions (e.g., - ${mesa}). - - 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. -'' - - This kind of string literal intelligently strips indentation from - the start of each line. To be precise, it strips from each line a - number of spaces equal to the minimal indentation of the string as - a whole (disregarding the indentation of empty lines). For - instance, the first and second line are indented two space, while - the third 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" - - - - Note that the whitespace and newline following the opening - '' is ignored if there is no non-whitespace - text on the initial line. - - Antiquotation - (${expr}) is - supported in indented strings. - - Since ${ and '' have - special meaning in indented strings, you need a way to quote them. - $ can be escaped by prefixing it with - '' (that is, two single quotes), i.e., - ''$. '' can be escaped by - prefixing it with ', i.e., - '''. $ removes any special meaning - from the following $. Linefeed, carriage-return and tab - characters can be written as ''\n, - ''\r, ''\t, and ''\ - escapes any other character. - - - - Indented strings are primarily useful in that they allow - multi-line string literals to follow the indentation of the - enclosing Nix expression, and that less escaping is typically - necessary for strings representing languages such as shell scripts - and 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 ""} - ''; - ... -} - - - - - Finally, as a convenience, URIs as - defined in appendix B of RFC 2396 - can be written as is, without quotes. For - instance, the string - "http://example.org/foo.tar.bz2" - can also be written as - http://example.org/foo.tar.bz2. - - - - Numbers, which can be integers (like - 123) or floating point (like - 123.43 or .27e13). - - Numbers are type-compatible: pure integer operations will always - return integers, whereas any operation involving at least one floating point - number will have a floating point number as a result. - - Paths, e.g., - /bin/sh or ./builder.sh. - A path must contain at least one slash to be recognised as such; for - instance, builder.sh is not a - pathIt's parsed as an expression that selects the - attribute sh from the variable - builder.. If the file name is - relative, i.e., if it does not begin with a slash, it is made - absolute at parse time relative to the directory of the Nix - expression that contained it. For instance, if a Nix expression in - /foo/bar/bla.nix refers to - ../xyzzy/fnord.nix, the absolute path is - /foo/xyzzy/fnord.nix. - - If the first component of a path is a ~, - it is interpreted as if the rest of the path were relative to the - user's home directory. e.g. ~/foo would be - equivalent to /home/edolstra/foo for a user - whose home directory is /home/edolstra. - - - Paths can also be specified between angle brackets, e.g. - <nixpkgs>. This means that the directories - listed in the environment variable - NIX_PATH will be searched - for the given file or directory name. - - - - - Booleans with values - true and - false. - - The null value, denoted as - null. - - - - - - - - -Lists - -Lists are formed by enclosing a whitespace-separated list of -values between square brackets. For example, - - -[ 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; } ] - -the result would be a list of five elements, the fourth one being a -function and the fifth being a set. - -Note that lists are only lazy in values, and they are strict in length. - - - - - -Sets - -Sets are really the core of the language, since ultimately the -Nix language is all about creating derivations, which are really just -sets of attributes to be passed to build scripts. - -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; }; -} - -This defines a set with attributes named x, -text, y. The order of 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 - -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" - -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}" - - -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 - -This will evaluate to 123 if -bar evaluates to "foo" when -coerced to a string and 456 otherwise (again -assuming bar is antiquotable). - -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; } - -This will evaluate to {} if foo -evaluates to false. - -A set that has a __functor attribute whose value -is callable (i.e. is 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 - - -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 of object-oriented programming, for example. - - - - - - -
diff --git a/doc/manual/expressions/simple-building-testing.xml b/doc/manual/expressions/simple-building-testing.xml deleted file mode 100644 index ce0a1636d..000000000 --- a/doc/manual/expressions/simple-building-testing.xml +++ /dev/null @@ -1,76 +0,0 @@ -
- -Building and Testing - -You can now try to build Hello. Of course, you could do -nix-env -i hello, but you may not want to install a -possibly broken package just 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! - -The option selects -the hello attribute. This is faster than using the -symbolic package name specified by the name -attribute (which also happens to be hello) and is -unambiguous (there can be multiple packages with the symbolic name -hello, but there can be only one attribute in a set -named hello). - -nix-build registers the -./result symlink as a garbage collection root, so -unless and until you delete the ./result symlink, -the output of the build will be safely kept on your system. You can -use nix-build’s switch to give the symlink another -name. - -Nix has transactional semantics. Once a build finishes -successfully, Nix makes a note of this in its database: it registers -that the path denoted by out is now -valid. If you try to build the derivation again, Nix -will see that the path is already valid and finish immediately. If a -build fails, either because it returns a non-zero exit code, because -Nix or the builder are killed, or because the machine crashes, then -the output paths will not be registered as valid. If you try to build -the derivation again, Nix will remove the output paths if they exist -(e.g., because the builder died half-way through make -install) and try again. Note that there is no -negative caching: Nix doesn't remember that a build -failed, and so a failed build can always be repeated. This is because -Nix cannot distinguish between permanent failures (e.g., a compiler -error due to a syntax error in the source) and transient failures -(e.g., a disk full condition). - -Nix also performs locking. If you run multiple Nix builds -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' - -So it is always safe to run multiple instances of Nix in parallel -(which isn’t the case with, say, make). - -
diff --git a/doc/manual/expressions/simple-expression.xml b/doc/manual/expressions/simple-expression.xml deleted file mode 100644 index 29fd872ee..000000000 --- a/doc/manual/expressions/simple-expression.xml +++ /dev/null @@ -1,47 +0,0 @@ - - -A Simple Nix Expression - -This section shows how to add and test the GNU Hello -package to the Nix Packages collection. Hello is a program -that prints out the text Hello, world!. - -To add a package to the Nix Packages collection, you generally -need to do three things: - - - - Write a Nix expression for the package. This is a - file that describes all the inputs involved in building the package, - such as dependencies, sources, and so on. - - Write a builder. This is a - shell scriptIn fact, it can be written in any - language, but typically it's a bash shell - script. that actually builds the package from - the inputs. - - Add the package to the file - pkgs/top-level/all-packages.nix. The Nix - expression written in the first step is a - function; it requires other packages in order - to build it. In this step you put it all together, i.e., you call - the function with the right arguments to build the actual - package. - - - - - - - - - - - - diff --git a/doc/manual/expressions/writing-nix-expressions.xml b/doc/manual/expressions/writing-nix-expressions.xml deleted file mode 100644 index 6646dddf0..000000000 --- a/doc/manual/expressions/writing-nix-expressions.xml +++ /dev/null @@ -1,26 +0,0 @@ - - -Writing Nix Expressions - - -This chapter shows you how to write Nix expressions, which -instruct Nix how to build packages. It starts with a -simple example (a Nix expression for GNU Hello), and then moves -on to a more in-depth look at the Nix expression language. - -This chapter is mostly about the Nix expression language. -For more extensive information on adding packages to the Nix Packages -collection (such as functions in the standard environment and coding -conventions), please consult its -manual. - - - - - - diff --git a/doc/manual/generate-builtins.nix b/doc/manual/generate-builtins.nix new file mode 100644 index 000000000..416a7fdba --- /dev/null +++ b/doc/manual/generate-builtins.nix @@ -0,0 +1,14 @@ +with builtins; +with import ./utils.nix; + +builtins: + +concatStrings (map + (name: + let builtin = builtins.${name}; in + " - `builtins.${name}` " + concatStringsSep " " (map (s: "*${s}*") builtin.args) + + " \n\n" + + concatStrings (map (s: " ${s}\n") (splitLines builtin.doc)) + "\n\n" + ) + (attrNames builtins)) + diff --git a/doc/manual/generate-manpage.nix b/doc/manual/generate-manpage.nix new file mode 100644 index 000000000..4709c0e2c --- /dev/null +++ b/doc/manual/generate-manpage.nix @@ -0,0 +1,56 @@ +with builtins; +with import ./utils.nix; + +let + + showCommand = + { command, section, def }: + "${section} Name\n\n" + + "`${command}` - ${def.description}\n\n" + + "${section} Synopsis\n\n" + + showSynopsis { inherit command; args = def.args; } + + (if def ? doc + then "${section} Description\n\n" + def.doc + "\n\n" + else "") + + (let s = showFlags def.flags; in + if s != "" + then "${section} Flags\n\n${s}" + else "") + + (if def.examples or [] != [] + then + "${section} Examples\n\n" + + concatStrings (map ({ description, command }: "${description}\n\n```console\n${command}\n```\n\n") def.examples) + else "") + + (if def.commands or [] != [] + then concatStrings ( + map (name: + "# Subcommand `${command} ${name}`\n\n" + + showCommand { command = command + " " + name; section = "##"; def = def.commands.${name}; }) + (attrNames def.commands)) + else ""); + + showFlags = flags: + concatStrings + (map (longName: + let flag = flags.${longName}; in + if flag.category or "" != "config" + then + " - `--${longName}`" + + (if flag ? shortName then " / `${flag.shortName}`" else "") + + (if flag ? labels then " " + (concatStringsSep " " (map (s: "*${s}*") flag.labels)) else "") + + " \n" + + " " + flag.description + "\n\n" + else "") + (attrNames flags)); + + showSynopsis = + { command, args }: + "`${command}` [*flags*...] ${concatStringsSep " " + (map (arg: "*${arg.label}*" + (if arg ? arity then "" else "...")) args)}\n\n"; + +in + +command: + +"Title: nix\n\n" ++ showCommand { command = "nix"; section = "#"; def = command; } diff --git a/doc/manual/generate-options.nix b/doc/manual/generate-options.nix new file mode 100644 index 000000000..3c31a4eec --- /dev/null +++ b/doc/manual/generate-options.nix @@ -0,0 +1,26 @@ +with builtins; +with import ./utils.nix; + +options: + +concatStrings (map + (name: + let option = options.${name}; in + " - `${name}` \n\n" + + concatStrings (map (s: " ${s}\n") (splitLines option.description)) + "\n\n" + + " **Default:** " + ( + if option.value == "" || option.value == [] + then "*empty*" + else if isBool option.value + then (if option.value then "`true`" else "`false`") + else + # n.b. a StringMap value type is specified as a string, but + # this shows the value type. The empty stringmap is "null" in + # JSON, but that converts to "{ }" here. + (if isAttrs option.value then "`\"\"`" + else "`" + toString option.value + "`")) + "\n\n" + + (if option.aliases != [] + then " **Deprecated alias:** " + (concatStringsSep ", " (map (s: "`${s}`") option.aliases)) + "\n\n" + else "") + ) + (attrNames options)) diff --git a/doc/manual/glossary/glossary.xml b/doc/manual/glossary/glossary.xml deleted file mode 100644 index e3162ed8d..000000000 --- a/doc/manual/glossary/glossary.xml +++ /dev/null @@ -1,199 +0,0 @@ - - -Glossary - - - - - -derivation - - A description of a build action. The result of a - derivation is a store object. Derivations are typically specified - in Nix expressions using the derivation - primitive. These are translated into low-level - store derivations (implicitly by - nix-env and nix-build, or - explicitly by nix-instantiate). - - - - -store - - The location in the file system where store objects - live. Typically /nix/store. - - - - -store path - - The location in the file system of a store object, - i.e., an immediate child of the Nix store - directory. - - - - -store object - - A file that is an immediate child of the Nix store - directory. These can be regular files, but also entire directory - trees. Store objects can be sources (objects copied from outside of - the store), derivation outputs (objects produced by running a build - action), or derivations (files describing a build - action). - - - - -substitute - - A substitute is a command invocation stored in the - Nix database that describes how to build a store object, bypassing - the normal build mechanism (i.e., derivations). Typically, the - substitute builds the store object by downloading a pre-built - version of the store object from some server. - - - - -purity - - The assumption that equal Nix derivations when run - always produce the same output. This cannot be guaranteed in - general (e.g., a builder can rely on external inputs such as the - network or the system time) but the Nix model assumes - it. - - - - -Nix expression - - A high-level description of software packages and - compositions thereof. Deploying software using Nix entails writing - Nix expressions for your packages. Nix expressions are translated - to derivations that are stored in the Nix store. These derivations - can then be built. - - - - -reference - - - A store path P is said to have a - reference to a store path Q if the store object - at P contains the path Q - somewhere. The references of a store path are - the set of store paths to which it has a reference. - - A derivation can reference other derivations and sources - (but not output paths), whereas an output path only references other - output paths. - - - - - -reachable - - A store path Q is reachable from - another store path P if Q is in the - closure of the - references relation. - - - -closure - - The closure of a store path is the set of store - paths that are directly or indirectly “reachable” from that store - path; that is, it’s the closure of the path under the references relation. For a package, the - closure of its derivation is equivalent to the build-time - dependencies, while the closure of its output path is equivalent to its - runtime dependencies. For correct deployment it is necessary to deploy whole - closures, since otherwise at runtime files could be missing. The command - nix-store -qR prints out closures of store paths. - - As an example, if the store object at path P contains - a reference to path Q, then Q is - in the closure of P. Further, if Q - references R then R is also in - the closure of P. - - - - - -output path - - A store path produced by a derivation. - - - - -deriver - - The deriver of an output path is the store - derivation that built it. - - - - -validity - - A store path is considered - valid if it exists in the file system, is - listed in the Nix database as being valid, and if all paths in its - closure are also valid. - - - - -user environment - - An automatically generated store object that - consists of a set of symlinks to “active” applications, i.e., other - store paths. These are generated automatically by nix-env. See . - - - - - - -profile - - A symlink to the current user environment of a user, e.g., - /nix/var/nix/profiles/default. - - - - -NAR - - A Nix - ARchive. This is a serialisation of a path in - the Nix store. It can contain regular files, directories and - symbolic links. NARs are generated and unpacked using - nix-store --dump and nix-store - --restore. - - - - - - - - - diff --git a/doc/manual/hacking.xml b/doc/manual/hacking.xml deleted file mode 100644 index b671811d3..000000000 --- a/doc/manual/hacking.xml +++ /dev/null @@ -1,41 +0,0 @@ - - -Hacking - -This section provides some notes on how to hack on Nix. To get -the latest version of Nix from GitHub: - -$ git clone git://github.com/NixOS/nix.git -$ cd nix - - - -To build it and its dependencies: - -$ nix-build release.nix -A build.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 - -To build Nix itself in this shell: - -[nix-shell]$ ./bootstrap.sh -[nix-shell]$ configurePhase -[nix-shell]$ make - -To install it in $(pwd)/inst and test it: - -[nix-shell]$ make install -[nix-shell]$ make installcheck - - - - - diff --git a/doc/manual/highlight.pack.js b/doc/manual/highlight.pack.js new file mode 100644 index 000000000..fba8b4a5a --- /dev/null +++ b/doc/manual/highlight.pack.js @@ -0,0 +1,6 @@ +/* + Highlight.js 10.1.2 (edd73d24) + License: BSD-3-Clause + Copyright (c) 2006-2020, Ivan Sagalaev +*/ +var hljs=function(){"use strict";function e(n){Object.freeze(n);var t="function"==typeof n;return Object.getOwnPropertyNames(n).forEach((function(r){!Object.hasOwnProperty.call(n,r)||null===n[r]||"object"!=typeof n[r]&&"function"!=typeof n[r]||t&&("caller"===r||"callee"===r||"arguments"===r)||Object.isFrozen(n[r])||e(n[r])})),n}class n{constructor(e){void 0===e.data&&(e.data={}),this.data=e.data}ignoreMatch(){this.ignore=!0}}function t(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function r(e,...n){var t={};for(const n in e)t[n]=e[n];return n.forEach((function(e){for(const n in e)t[n]=e[n]})),t}function a(e){return e.nodeName.toLowerCase()}var i=Object.freeze({__proto__:null,escapeHTML:t,inherit:r,nodeStream:function(e){var n=[];return function e(t,r){for(var i=t.firstChild;i;i=i.nextSibling)3===i.nodeType?r+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:r,node:i}),r=e(i,r),a(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:r,node:i}));return r}(e,0),n},mergeStreams:function(e,n,r){var i=0,s="",o=[];function l(){return e.length&&n.length?e[0].offset!==n[0].offset?e[0].offset"}function u(e){s+=""}function d(e){("start"===e.event?c:u)(e.node)}for(;e.length||n.length;){var g=l();if(s+=t(r.substring(i,g[0].offset)),i=g[0].offset,g===e){o.reverse().forEach(u);do{d(g.splice(0,1)[0]),g=l()}while(g===e&&g.length&&g[0].offset===i);o.reverse().forEach(c)}else"start"===g[0].event?o.push(g[0].node):o.pop(),d(g.splice(0,1)[0])}return s+t(r.substr(i))}});const s="",o=e=>!!e.kind;class l{constructor(e,n){this.buffer="",this.classPrefix=n.classPrefix,e.walk(this)}addText(e){this.buffer+=t(e)}openNode(e){if(!o(e))return;let n=e.kind;e.sublanguage||(n=`${this.classPrefix}${n}`),this.span(n)}closeNode(e){o(e)&&(this.buffer+=s)}value(){return this.buffer}span(e){this.buffer+=``}}class c{constructor(){this.rootNode={children:[]},this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){const n={kind:e,children:[]};this.add(n),this.stack.push(n)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,n){return"string"==typeof n?e.addText(n):n.children&&(e.openNode(n),n.children.forEach(n=>this._walk(e,n)),e.closeNode(n)),e}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{c._collapse(e)}))}}class u extends c{constructor(e){super(),this.options=e}addKeyword(e,n){""!==e&&(this.openNode(n),this.addText(e),this.closeNode())}addText(e){""!==e&&this.add(e)}addSublanguage(e,n){const t=e.root;t.kind=n,t.sublanguage=!0,this.add(t)}toHTML(){return new l(this,this.options).value()}finalize(){return!0}}function d(e){return e?"string"==typeof e?e:e.source:null}const g="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",h={begin:"\\\\[\\s\\S]",relevance:0},f={className:"string",begin:"'",end:"'",illegal:"\\n",contains:[h]},p={className:"string",begin:'"',end:'"',illegal:"\\n",contains:[h]},b={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},m=function(e,n,t={}){var a=r({className:"comment",begin:e,end:n,contains:[]},t);return a.contains.push(b),a.contains.push({className:"doctag",begin:"(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",relevance:0}),a},v=m("//","$"),x=m("/\\*","\\*/"),E=m("#","$");var _=Object.freeze({__proto__:null,IDENT_RE:"[a-zA-Z]\\w*",UNDERSCORE_IDENT_RE:"[a-zA-Z_]\\w*",NUMBER_RE:"\\b\\d+(\\.\\d+)?",C_NUMBER_RE:g,BINARY_NUMBER_RE:"\\b(0b[01]+)",RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const n=/^#![ ]*\//;return e.binary&&(e.begin=function(...e){return e.map(e=>d(e)).join("")}(n,/.*\b/,e.binary,/\b.*/)),r({className:"meta",begin:n,end:/$/,relevance:0,"on:begin":(e,n)=>{0!==e.index&&n.ignoreMatch()}},e)},BACKSLASH_ESCAPE:h,APOS_STRING_MODE:f,QUOTE_STRING_MODE:p,PHRASAL_WORDS_MODE:b,COMMENT:m,C_LINE_COMMENT_MODE:v,C_BLOCK_COMMENT_MODE:x,HASH_COMMENT_MODE:E,NUMBER_MODE:{className:"number",begin:"\\b\\d+(\\.\\d+)?",relevance:0},C_NUMBER_MODE:{className:"number",begin:g,relevance:0},BINARY_NUMBER_MODE:{className:"number",begin:"\\b(0b[01]+)",relevance:0},CSS_NUMBER_MODE:{className:"number",begin:"\\b\\d+(\\.\\d+)?(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},REGEXP_MODE:{begin:/(?=\/[^/\n]*\/)/,contains:[{className:"regexp",begin:/\//,end:/\/[gimuy]*/,illegal:/\n/,contains:[h,{begin:/\[/,end:/\]/,relevance:0,contains:[h]}]}]},TITLE_MODE:{className:"title",begin:"[a-zA-Z]\\w*",relevance:0},UNDERSCORE_TITLE_MODE:{className:"title",begin:"[a-zA-Z_]\\w*",relevance:0},METHOD_GUARD:{begin:"\\.\\s*[a-zA-Z_]\\w*",relevance:0},END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,n)=>{n.data._beginMatch=e[1]},"on:end":(e,n)=>{n.data._beginMatch!==e[1]&&n.ignoreMatch()}})}}),N="of and for in not or if then".split(" ");function w(e,n){return n?+n:function(e){return N.includes(e.toLowerCase())}(e)?0:1}const R=t,y=r,{nodeStream:O,mergeStreams:k}=i,M=Symbol("nomatch");return function(t){var a=[],i=Object.create(null),s=Object.create(null),o=[],l=!0,c=/(^(<[^>]+>|\t|)+|\n)/gm,g="Could not find the language '{}', did you forget to load/include a language module?";const h={disableAutodetect:!0,name:"Plain text",contains:[]};var f={noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:null,__emitter:u};function p(e){return f.noHighlightRe.test(e)}function b(e,n,t,r){var a={code:n,language:e};S("before:highlight",a);var i=a.result?a.result:m(a.language,a.code,t,r);return i.code=a.code,S("after:highlight",i),i}function m(e,t,a,s){var o=t;function c(e,n){var t=E.case_insensitive?n[0].toLowerCase():n[0];return Object.prototype.hasOwnProperty.call(e.keywords,t)&&e.keywords[t]}function u(){null!=y.subLanguage?function(){if(""!==A){var e=null;if("string"==typeof y.subLanguage){if(!i[y.subLanguage])return void k.addText(A);e=m(y.subLanguage,A,!0,O[y.subLanguage]),O[y.subLanguage]=e.top}else e=v(A,y.subLanguage.length?y.subLanguage:null);y.relevance>0&&(I+=e.relevance),k.addSublanguage(e.emitter,e.language)}}():function(){if(!y.keywords)return void k.addText(A);let e=0;y.keywordPatternRe.lastIndex=0;let n=y.keywordPatternRe.exec(A),t="";for(;n;){t+=A.substring(e,n.index);const r=c(y,n);if(r){const[e,a]=r;k.addText(t),t="",I+=a,k.addKeyword(n[0],e)}else t+=n[0];e=y.keywordPatternRe.lastIndex,n=y.keywordPatternRe.exec(A)}t+=A.substr(e),k.addText(t)}(),A=""}function h(e){return e.className&&k.openNode(e.className),y=Object.create(e,{parent:{value:y}})}function p(e){return 0===y.matcher.regexIndex?(A+=e[0],1):(L=!0,0)}var b={};function x(t,r){var i=r&&r[0];if(A+=t,null==i)return u(),0;if("begin"===b.type&&"end"===r.type&&b.index===r.index&&""===i){if(A+=o.slice(r.index,r.index+1),!l){const n=Error("0 width match regex");throw n.languageName=e,n.badRule=b.rule,n}return 1}if(b=r,"begin"===r.type)return function(e){var t=e[0],r=e.rule;const a=new n(r),i=[r.__beforeBegin,r["on:begin"]];for(const n of i)if(n&&(n(e,a),a.ignore))return p(t);return r&&r.endSameAsBegin&&(r.endRe=RegExp(t.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")),r.skip?A+=t:(r.excludeBegin&&(A+=t),u(),r.returnBegin||r.excludeBegin||(A=t)),h(r),r.returnBegin?0:t.length}(r);if("illegal"===r.type&&!a){const e=Error('Illegal lexeme "'+i+'" for mode "'+(y.className||"")+'"');throw e.mode=y,e}if("end"===r.type){var s=function(e){var t=e[0],r=o.substr(e.index),a=function e(t,r,a){let i=function(e,n){var t=e&&e.exec(n);return t&&0===t.index}(t.endRe,a);if(i){if(t["on:end"]){const e=new n(t);t["on:end"](r,e),e.ignore&&(i=!1)}if(i){for(;t.endsParent&&t.parent;)t=t.parent;return t}}if(t.endsWithParent)return e(t.parent,r,a)}(y,e,r);if(!a)return M;var i=y;i.skip?A+=t:(i.returnEnd||i.excludeEnd||(A+=t),u(),i.excludeEnd&&(A=t));do{y.className&&k.closeNode(),y.skip||y.subLanguage||(I+=y.relevance),y=y.parent}while(y!==a.parent);return a.starts&&(a.endSameAsBegin&&(a.starts.endRe=a.endRe),h(a.starts)),i.returnEnd?0:t.length}(r);if(s!==M)return s}if("illegal"===r.type&&""===i)return 1;if(B>1e5&&B>3*r.index)throw Error("potential infinite loop, way more iterations than matches");return A+=i,i.length}var E=T(e);if(!E)throw console.error(g.replace("{}",e)),Error('Unknown language: "'+e+'"');var _=function(e){function n(n,t){return RegExp(d(n),"m"+(e.case_insensitive?"i":"")+(t?"g":""))}class t{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,n){n.position=this.position++,this.matchIndexes[this.matchAt]=n,this.regexes.push([n,e]),this.matchAt+=function(e){return RegExp(e.toString()+"|").exec("").length-1}(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map(e=>e[1]);this.matcherRe=n(function(e,n="|"){for(var t=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./,r=0,a="",i=0;i0&&(a+=n),a+="(";o.length>0;){var l=t.exec(o);if(null==l){a+=o;break}a+=o.substring(0,l.index),o=o.substring(l.index+l[0].length),"\\"===l[0][0]&&l[1]?a+="\\"+(+l[1]+s):(a+=l[0],"("===l[0]&&r++)}a+=")"}return a}(e),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;const n=this.matcherRe.exec(e);if(!n)return null;const t=n.findIndex((e,n)=>n>0&&void 0!==e),r=this.matchIndexes[t];return n.splice(0,t),Object.assign(n,r)}}class a{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const n=new t;return this.rules.slice(e).forEach(([e,t])=>n.addRule(e,t)),n.compile(),this.multiRegexes[e]=n,n}considerAll(){this.regexIndex=0}addRule(e,n){this.rules.push([e,n]),"begin"===n.type&&this.count++}exec(e){const n=this.getMatcher(this.regexIndex);n.lastIndex=this.lastIndex;const t=n.exec(e);return t&&(this.regexIndex+=t.position+1,this.regexIndex===this.count&&(this.regexIndex=0)),t}}function i(e,n){const t=e.input[e.index-1],r=e.input[e.index+e[0].length];"."!==t&&"."!==r||n.ignoreMatch()}if(e.contains&&e.contains.includes("self"))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return function t(s,o){const l=s;if(s.compiled)return l;s.compiled=!0,s.__beforeBegin=null,s.keywords=s.keywords||s.beginKeywords;let c=null;if("object"==typeof s.keywords&&(c=s.keywords.$pattern,delete s.keywords.$pattern),s.keywords&&(s.keywords=function(e,n){var t={};return"string"==typeof e?r("keyword",e):Object.keys(e).forEach((function(n){r(n,e[n])})),t;function r(e,r){n&&(r=r.toLowerCase()),r.split(" ").forEach((function(n){var r=n.split("|");t[r[0]]=[e,w(r[0],r[1])]}))}}(s.keywords,e.case_insensitive)),s.lexemes&&c)throw Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");return l.keywordPatternRe=n(s.lexemes||c||/\w+/,!0),o&&(s.beginKeywords&&(s.begin="\\b("+s.beginKeywords.split(" ").join("|")+")(?=\\b|\\s)",s.__beforeBegin=i),s.begin||(s.begin=/\B|\b/),l.beginRe=n(s.begin),s.endSameAsBegin&&(s.end=s.begin),s.end||s.endsWithParent||(s.end=/\B|\b/),s.end&&(l.endRe=n(s.end)),l.terminator_end=d(s.end)||"",s.endsWithParent&&o.terminator_end&&(l.terminator_end+=(s.end?"|":"")+o.terminator_end)),s.illegal&&(l.illegalRe=n(s.illegal)),void 0===s.relevance&&(s.relevance=1),s.contains||(s.contains=[]),s.contains=[].concat(...s.contains.map((function(e){return function(e){return e.variants&&!e.cached_variants&&(e.cached_variants=e.variants.map((function(n){return r(e,{variants:null},n)}))),e.cached_variants?e.cached_variants:function e(n){return!!n&&(n.endsWithParent||e(n.starts))}(e)?r(e,{starts:e.starts?r(e.starts):null}):Object.isFrozen(e)?r(e):e}("self"===e?s:e)}))),s.contains.forEach((function(e){t(e,l)})),s.starts&&t(s.starts,o),l.matcher=function(e){const n=new a;return e.contains.forEach(e=>n.addRule(e.begin,{rule:e,type:"begin"})),e.terminator_end&&n.addRule(e.terminator_end,{type:"end"}),e.illegal&&n.addRule(e.illegal,{type:"illegal"}),n}(l),l}(e)}(E),N="",y=s||_,O={},k=new f.__emitter(f);!function(){for(var e=[],n=y;n!==E;n=n.parent)n.className&&e.unshift(n.className);e.forEach(e=>k.openNode(e))}();var A="",I=0,S=0,B=0,L=!1;try{for(y.matcher.considerAll();;){B++,L?L=!1:(y.matcher.lastIndex=S,y.matcher.considerAll());const e=y.matcher.exec(o);if(!e)break;const n=x(o.substring(S,e.index),e);S=e.index+n}return x(o.substr(S)),k.closeAllNodes(),k.finalize(),N=k.toHTML(),{relevance:I,value:N,language:e,illegal:!1,emitter:k,top:y}}catch(n){if(n.message&&n.message.includes("Illegal"))return{illegal:!0,illegalBy:{msg:n.message,context:o.slice(S-100,S+100),mode:n.mode},sofar:N,relevance:0,value:R(o),emitter:k};if(l)return{illegal:!1,relevance:0,value:R(o),emitter:k,language:e,top:y,errorRaised:n};throw n}}function v(e,n){n=n||f.languages||Object.keys(i);var t=function(e){const n={relevance:0,emitter:new f.__emitter(f),value:R(e),illegal:!1,top:h};return n.emitter.addText(e),n}(e),r=t;return n.filter(T).filter(I).forEach((function(n){var a=m(n,e,!1);a.language=n,a.relevance>r.relevance&&(r=a),a.relevance>t.relevance&&(r=t,t=a)})),r.language&&(t.second_best=r),t}function x(e){return f.tabReplace||f.useBR?e.replace(c,e=>"\n"===e?f.useBR?"
":e:f.tabReplace?e.replace(/\t/g,f.tabReplace):e):e}function E(e){let n=null;const t=function(e){var n=e.className+" ";n+=e.parentNode?e.parentNode.className:"";const t=f.languageDetectRe.exec(n);if(t){var r=T(t[1]);return r||(console.warn(g.replace("{}",t[1])),console.warn("Falling back to no-highlight mode for this block.",e)),r?t[1]:"no-highlight"}return n.split(/\s+/).find(e=>p(e)||T(e))}(e);if(p(t))return;S("before:highlightBlock",{block:e,language:t}),f.useBR?(n=document.createElement("div")).innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n"):n=e;const r=n.textContent,a=t?b(t,r,!0):v(r),i=O(n);if(i.length){const e=document.createElement("div");e.innerHTML=a.value,a.value=k(i,O(e),r)}a.value=x(a.value),S("after:highlightBlock",{block:e,result:a}),e.innerHTML=a.value,e.className=function(e,n,t){var r=n?s[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),e.includes(r)||a.push(r),a.join(" ").trim()}(e.className,t,a.language),e.result={language:a.language,re:a.relevance,relavance:a.relevance},a.second_best&&(e.second_best={language:a.second_best.language,re:a.second_best.relevance,relavance:a.second_best.relevance})}const N=()=>{if(!N.called){N.called=!0;var e=document.querySelectorAll("pre code");a.forEach.call(e,E)}};function T(e){return e=(e||"").toLowerCase(),i[e]||i[s[e]]}function A(e,{languageName:n}){"string"==typeof e&&(e=[e]),e.forEach(e=>{s[e]=n})}function I(e){var n=T(e);return n&&!n.disableAutodetect}function S(e,n){var t=e;o.forEach((function(e){e[t]&&e[t](n)}))}Object.assign(t,{highlight:b,highlightAuto:v,fixMarkup:x,highlightBlock:E,configure:function(e){f=y(f,e)},initHighlighting:N,initHighlightingOnLoad:function(){window.addEventListener("DOMContentLoaded",N,!1)},registerLanguage:function(e,n){var r=null;try{r=n(t)}catch(n){if(console.error("Language definition for '{}' could not be registered.".replace("{}",e)),!l)throw n;console.error(n),r=h}r.name||(r.name=e),i[e]=r,r.rawDefinition=n.bind(null,t),r.aliases&&A(r.aliases,{languageName:e})},listLanguages:function(){return Object.keys(i)},getLanguage:T,registerAliases:A,requireLanguage:function(e){var n=T(e);if(n)return n;throw Error("The '{}' language is required, but not loaded.".replace("{}",e))},autoDetection:I,inherit:y,addPlugin:function(e){o.push(e)}}),t.debugMode=function(){l=!1},t.safeMode=function(){l=!0},t.versionString="10.1.2";for(const n in _)"object"==typeof _[n]&&e(_[n]);return Object.assign(t,_),t}({})}();"object"==typeof exports&&"undefined"!=typeof module&&(module.exports=hljs);hljs.registerLanguage("xml",function(){"use strict";return function(e){var n={className:"symbol",begin:"&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;"},a={begin:"\\s",contains:[{className:"meta-keyword",begin:"#?[a-z_][a-z1-9_-]+",illegal:"\\n"}]},s=e.inherit(a,{begin:"\\(",end:"\\)"}),t=e.inherit(e.APOS_STRING_MODE,{className:"meta-string"}),i=e.inherit(e.QUOTE_STRING_MODE,{className:"meta-string"}),c={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,contains:[{className:"meta",begin:"",relevance:10,contains:[a,i,t,s,{begin:"\\[",end:"\\]",contains:[{className:"meta",begin:"",contains:[a,s,i,t]}]}]},e.COMMENT("\x3c!--","--\x3e",{relevance:10}),{begin:"<\\!\\[CDATA\\[",end:"\\]\\]>",relevance:10},n,{className:"meta",begin:/<\?xml/,end:/\?>/,relevance:10},{className:"tag",begin:")",end:">",keywords:{name:"style"},contains:[c],starts:{end:"",returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:")",end:">",keywords:{name:"script"},contains:[c],starts:{end:"<\/script>",returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:"",contains:[{className:"name",begin:/[^\/><\s]+/,relevance:0},c]}]}}}());hljs.registerLanguage("markdown",function(){"use strict";return function(n){const e={begin:"<",end:">",subLanguage:"xml",relevance:0},a={begin:"\\[.+?\\][\\(\\[].*?[\\)\\]]",returnBegin:!0,contains:[{className:"string",begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0,relevance:0},{className:"link",begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}],relevance:10},i={className:"strong",contains:[],variants:[{begin:/_{2}/,end:/_{2}/},{begin:/\*{2}/,end:/\*{2}/}]},s={className:"emphasis",contains:[],variants:[{begin:/\*(?!\*)/,end:/\*/},{begin:/_(?!_)/,end:/_/,relevance:0}]};i.contains.push(s),s.contains.push(i);var c=[e,a];return i.contains=i.contains.concat(c),s.contains=s.contains.concat(c),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:c=c.concat(i,s)},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:c}]}]},e,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},i,s,{className:"quote",begin:"^>\\s+",contains:c,end:"$"},{className:"code",variants:[{begin:"(`{3,})(.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})(.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},{begin:"^[-\\*]{3,}",end:"$"},a,{begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]}]}}}());hljs.registerLanguage("perl",function(){"use strict";return function(e){var n={$pattern:/[\w.]+/,keyword:"getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qq fileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmget sub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedir ioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when"},t={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:n},s={begin:"->{",end:"}"},r={variants:[{begin:/\$\d/},{begin:/[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/},{begin:/[\$%@][^\s\w{]/,relevance:0}]},i=[e.BACKSLASH_ESCAPE,t,r],a=[r,e.HASH_COMMENT_MODE,e.COMMENT("^\\=\\w","\\=cut",{endsWithParent:!0}),s,{className:"string",contains:i,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*\\<",end:"\\>",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:"{\\w+}",contains:[],relevance:0},{begin:"-?\\w+\\s*\\=\\>",contains:[],relevance:0}]},{className:"number",begin:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",relevance:0},{begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[e.HASH_COMMENT_MODE,{className:"regexp",begin:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",relevance:10},{className:"regexp",begin:"(m|qr)?/",end:"/[a-z]*",contains:[e.BACKSLASH_ESCAPE],relevance:0}]},{className:"function",beginKeywords:"sub",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return t.contains=a,s.contains=a,{name:"Perl",aliases:["pl","pm"],keywords:n,contains:a}}}());hljs.registerLanguage("plaintext",function(){"use strict";return function(t){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}}}());hljs.registerLanguage("ini",function(){"use strict";function e(e){return e?"string"==typeof e?e:e.source:null}function n(...n){return n.map(n=>e(n)).join("")}return function(a){var s={className:"number",relevance:0,variants:[{begin:/([\+\-]+)?[\d]+_[\d_]+/},{begin:a.NUMBER_RE}]},i=a.COMMENT();i.variants=[{begin:/;/,end:/$/},{begin:/#/,end:/$/}];var t={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{begin:/\$\{(.*?)}/}]},r={className:"literal",begin:/\bon|off|true|false|yes|no\b/},l={className:"string",contains:[a.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}]},c={begin:/\[/,end:/\]/,contains:[i,r,t,l,s,"self"],relevance:0},g="("+[/[A-Za-z0-9_-]+/,/"(\\"|[^"])*"/,/'[^']*'/].map(n=>e(n)).join("|")+")";return{name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/,contains:[i,{className:"section",begin:/\[+/,end:/\]+/},{begin:n(g,"(\\s*\\.\\s*",g,")*",n("(?=",/\s*=\s*[^#\s]/,")")),className:"attr",starts:{end:/$/,contains:[i,c,r,t,l,s]}}]}}}());hljs.registerLanguage("json",function(){"use strict";return function(n){var e={literal:"true false null"},i=[n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE],t=[n.QUOTE_STRING_MODE,n.C_NUMBER_MODE],a={end:",",endsWithParent:!0,excludeEnd:!0,contains:t,keywords:e},l={begin:"{",end:"}",contains:[{className:"attr",begin:/"/,end:/"/,contains:[n.BACKSLASH_ESCAPE],illegal:"\\n"},n.inherit(a,{begin:/:/})].concat(i),illegal:"\\S"},s={begin:"\\[",end:"\\]",contains:[n.inherit(a)],illegal:"\\S"};return t.push(l,s),i.forEach((function(n){t.push(n)})),{name:"JSON",contains:t,keywords:e,illegal:"\\S"}}}());hljs.registerLanguage("ruby",function(){"use strict";return function(e){var n="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",a={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},s={className:"doctag",begin:"@[A-Za-z]+"},i={begin:"#<",end:">"},r=[e.COMMENT("#","$",{contains:[s]}),e.COMMENT("^\\=begin","^\\=end",{contains:[s],relevance:10}),e.COMMENT("^__END__","\\n$")],c={className:"subst",begin:"#\\{",end:"}",keywords:a},t={className:"string",contains:[e.BACKSLASH_ESCAPE,c],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:"%[qQwWx]?\\(",end:"\\)"},{begin:"%[qQwWx]?\\[",end:"\\]"},{begin:"%[qQwWx]?{",end:"}"},{begin:"%[qQwWx]?<",end:">"},{begin:"%[qQwWx]?/",end:"/"},{begin:"%[qQwWx]?%",end:"%"},{begin:"%[qQwWx]?-",end:"-"},{begin:"%[qQwWx]?\\|",end:"\\|"},{begin:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{begin:/<<[-~]?'?(\w+)(?:.|\n)*?\n\s*\1\b/,returnBegin:!0,contains:[{begin:/<<[-~]?'?/},e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[e.BACKSLASH_ESCAPE,c]})]}]},b={className:"params",begin:"\\(",end:"\\)",endsParent:!0,keywords:a},d=[t,i,{className:"class",beginKeywords:"class module",end:"$|;",illegal:/=/,contains:[e.inherit(e.TITLE_MODE,{begin:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{begin:"<\\s*",contains:[{begin:"("+e.IDENT_RE+"::)?"+e.IDENT_RE}]}].concat(r)},{className:"function",beginKeywords:"def",end:"$|;",contains:[e.inherit(e.TITLE_MODE,{begin:n}),b].concat(r)},{begin:e.IDENT_RE+"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(\\!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[t,{begin:n}],relevance:0},{className:"number",begin:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",relevance:0},{begin:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{className:"params",begin:/\|/,end:/\|/,keywords:a},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[i,{className:"regexp",contains:[e.BACKSLASH_ESCAPE,c],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:"%r{",end:"}[a-z]*"},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(r),relevance:0}].concat(r);c.contains=d,b.contains=d;var g=[{begin:/^\s*=>/,starts:{end:"$",contains:d}},{className:"meta",begin:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+>|(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>)",starts:{end:"$",contains:d}}];return{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:a,illegal:/\/\*/,contains:r.concat(g).concat(d)}}}());hljs.registerLanguage("yaml",function(){"use strict";return function(e){var n="true false yes no null",a="[\\w#;/?:@&=+$,.~*\\'()[\\]]+",s={className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:"{{",end:"}}"},{begin:"%{",end:"}"}]}]},i=e.inherit(s,{variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),l={end:",",endsWithParent:!0,excludeEnd:!0,contains:[],keywords:n,relevance:0},t={begin:"{",end:"}",contains:[l],illegal:"\\n",relevance:0},g={begin:"\\[",end:"\\]",contains:[l],illegal:"\\n",relevance:0},b=[{className:"attr",variants:[{begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---s*$",relevance:10},{className:"string",begin:"[\\|>]([0-9]?[+-])?[ ]*\\n( *)[\\S ]+\\n(\\2[\\S ]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+a},{className:"type",begin:"!<"+a+">"},{className:"type",begin:"!"+a},{className:"type",begin:"!!"+a},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"\\-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:n,keywords:{literal:n}},{className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},{className:"number",begin:e.C_NUMBER_RE+"\\b"},t,g,s],c=[...b];return c.pop(),c.push(i),l.contains=c,{name:"YAML",case_insensitive:!0,aliases:["yml","YAML"],contains:b}}}());hljs.registerLanguage("haskell",function(){"use strict";return function(e){var n={variants:[e.COMMENT("--","$"),e.COMMENT("{-","-}",{contains:["self"]})]},i={className:"meta",begin:"{-#",end:"#-}"},a={className:"meta",begin:"^#",end:"$"},s={className:"type",begin:"\\b[A-Z][\\w']*",relevance:0},l={begin:"\\(",end:"\\)",illegal:'"',contains:[i,a,{className:"type",begin:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},e.inherit(e.TITLE_MODE,{begin:"[_a-z][\\w']*"}),n]};return{name:"Haskell",aliases:["hs"],keywords:"let in if then else case of where do module import hiding qualified type data newtype deriving class instance as default infix infixl infixr foreign export ccall stdcall cplusplus jvm dotnet safe unsafe family forall mdo proc rec",contains:[{beginKeywords:"module",end:"where",keywords:"module where",contains:[l,n],illegal:"\\W\\.|;"},{begin:"\\bimport\\b",end:"$",keywords:"import qualified as hiding",contains:[l,n],illegal:"\\W\\.|;"},{className:"class",begin:"^(\\s*)?(class|instance)\\b",end:"where",keywords:"class family instance where",contains:[s,l,n]},{className:"class",begin:"\\b(data|(new)?type)\\b",end:"$",keywords:"data family type newtype deriving",contains:[i,s,l,{begin:"{",end:"}",contains:l.contains},n]},{beginKeywords:"default",end:"$",contains:[s,l,n]},{beginKeywords:"infix infixl infixr",end:"$",contains:[e.C_NUMBER_MODE,n]},{begin:"\\bforeign\\b",end:"$",keywords:"foreign import export ccall stdcall cplusplus jvm dotnet safe unsafe",contains:[s,e.QUOTE_STRING_MODE,n]},{className:"meta",begin:"#!\\/usr\\/bin\\/env runhaskell",end:"$"},i,a,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE,s,e.inherit(e.TITLE_MODE,{begin:"^[_a-z][\\w']*"}),n,{begin:"->|<-"}]}}}());hljs.registerLanguage("nix",function(){"use strict";return function(e){var n={keyword:"rec with let in inherit assert if else then",literal:"true false or and null",built_in:"import abort baseNameOf dirOf isNull builtins map removeAttrs throw toString derivation"},i={className:"subst",begin:/\$\{/,end:/}/,keywords:n},t={className:"string",contains:[i],variants:[{begin:"''",end:"''"},{begin:'"',end:'"'}]},s=[e.NUMBER_MODE,e.HASH_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,t,{begin:/[a-zA-Z0-9-_]+(\s*=)/,returnBegin:!0,relevance:0,contains:[{className:"attr",begin:/\S+/}]}];return i.contains=s,{name:"Nix",aliases:["nixos"],keywords:n,contains:s}}}());hljs.registerLanguage("bash",function(){"use strict";return function(e){const s={};Object.assign(s,{className:"variable",variants:[{begin:/\$[\w\d#@][\w\d_]*/},{begin:/\$\{/,end:/\}/,contains:[{begin:/:-/,contains:[s]}]}]});const t={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},n={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,s,t]};t.contains.push(n);const a={begin:/\$\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,s]},i=e.SHEBANG({binary:"(fish|bash|zsh|sh|csh|ksh|tcsh|dash|scsh)",relevance:10}),c={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b-?[a-z\._]+\b/,keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},contains:[i,e.SHEBANG(),c,a,e.HASH_COMMENT_MODE,n,{className:"",begin:/\\"/},{className:"string",begin:/'/,end:/'/},s]}}}());hljs.registerLanguage("shell",function(){"use strict";return function(s){return{name:"Shell Session",aliases:["console"],contains:[{className:"meta",begin:"^\\s{0,3}[/\\w\\d\\[\\]()@-]*[>%$#]",starts:{end:"$",subLanguage:"bash"}}]}}}());hljs.registerLanguage("python",function(){"use strict";return function(e){var n={keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10",built_in:"Ellipsis NotImplemented",literal:"False None True"},a={className:"meta",begin:/^(>>>|\.\.\.) /},i={className:"subst",begin:/\{/,end:/\}/,keywords:n,illegal:/#/},s={begin:/\{\{/,relevance:0},r={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/(u|b)?r?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,a],relevance:10},{begin:/(u|b)?r?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,a],relevance:10},{begin:/(fr|rf|f)'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,a,s,i]},{begin:/(fr|rf|f)"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,a,s,i]},{begin:/(u|r|ur)'/,end:/'/,relevance:10},{begin:/(u|r|ur)"/,end:/"/,relevance:10},{begin:/(b|br)'/,end:/'/},{begin:/(b|br)"/,end:/"/},{begin:/(fr|rf|f)'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,s,i]},{begin:/(fr|rf|f)"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,s,i]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},l={className:"number",relevance:0,variants:[{begin:e.BINARY_NUMBER_RE+"[lLjJ]?"},{begin:"\\b(0o[0-7]+)[lLjJ]?"},{begin:e.C_NUMBER_RE+"[lLjJ]?"}]},t={className:"params",variants:[{begin:/\(\s*\)/,skip:!0,className:null},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,contains:["self",a,l,r,e.HASH_COMMENT_MODE]}]};return i.contains=[r,l,a],{name:"Python",aliases:["py","gyp","ipython"],keywords:n,illegal:/(<\/|->|\?)|=>/,contains:[a,l,{beginKeywords:"if",relevance:0},r,e.HASH_COMMENT_MODE,{variants:[{className:"function",beginKeywords:"def"},{className:"class",beginKeywords:"class"}],end:/:/,illegal:/[${=;\n,]/,contains:[e.UNDERSCORE_TITLE_MODE,t,{begin:/->/,endsWithParent:!0,keywords:"None"}]},{className:"meta",begin:/^[\t ]*@/,end:/$/},{begin:/\b(print|exec)\(/}]}}}()); \ No newline at end of file diff --git a/doc/manual/installation/building-source.xml b/doc/manual/installation/building-source.xml deleted file mode 100644 index 772cda9cc..000000000 --- a/doc/manual/installation/building-source.xml +++ /dev/null @@ -1,49 +0,0 @@ -
- -Building Nix from Source - -After unpacking or checking out the Nix sources, issue the -following commands: - - -$ ./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 - - - -The installation path can be specified by passing the - to -configure. The default installation directory is -/usr/local. You can change this to any location -you like. You must have write permission to the -prefix path. - -Nix keeps its store (the place where -packages are stored) in /nix/store by default. -This can be changed using -. - -It is best not to change the Nix -store from its default, since doing so makes it impossible to use -pre-built binaries from the standard Nixpkgs channels — that is, all -packages will need to be built from source. - -Nix keeps state (such as its database and log files) in -/nix/var by default. This can be changed using -. - -
diff --git a/doc/manual/installation/env-variables.xml b/doc/manual/installation/env-variables.xml deleted file mode 100644 index cc52f5b4a..000000000 --- a/doc/manual/installation/env-variables.xml +++ /dev/null @@ -1,89 +0,0 @@ - - -Environment Variables - -To use Nix, some environment variables should be set. In -particular, PATH should contain the directories -prefix/bin and -~/.nix-profile/bin. The first directory contains -the Nix tools themselves, while ~/.nix-profile is -a symbolic link to the current user environment -(an automatically generated package consisting of symlinks to -installed packages). The simplest way to set the required 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 - -
- -<envar>NIX_SSL_CERT_FILE</envar> - -If you need to specify a custom certificate bundle to account -for an HTTPS-intercepting man in the middle proxy, you must specify -the path to the certificate bundle in the environment variable -NIX_SSL_CERT_FILE. - - -If you don't specify a NIX_SSL_CERT_FILE -manually, Nix will install 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) - - - 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 - - - - -You must not add the export and then do the install, as -the Nix installer will detect the presense of Nix configuration, and -abort. - -
-<envar>NIX_SSL_CERT_FILE</envar> with macOS and the Nix daemon - -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 - -
- -
- -Proxy Environment Variables - -The Nix installer has special handling for these proxy-related -environment variables: -http_proxy, https_proxy, -ftp_proxy, no_proxy, -HTTP_PROXY, HTTPS_PROXY, -FTP_PROXY, NO_PROXY. - -If any of these variables are set when running the Nix installer, -then the installer will create an override file at -/etc/systemd/system/nix-daemon.service.d/override.conf -so nix-daemon will use them. - -
- -
-
diff --git a/doc/manual/installation/installation.xml b/doc/manual/installation/installation.xml deleted file mode 100644 index 878959352..000000000 --- a/doc/manual/installation/installation.xml +++ /dev/null @@ -1,34 +0,0 @@ - - -Installation - - -This section describes how to install and configure Nix for first-time use. - - - - - - - - - - - diff --git a/doc/manual/installation/installing-binary.xml b/doc/manual/installation/installing-binary.xml deleted file mode 100644 index 64c7a37fb..000000000 --- a/doc/manual/installation/installing-binary.xml +++ /dev/null @@ -1,469 +0,0 @@ - - -Installing a Binary Distribution - - - 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) - - - - If you're using macOS 10.15 (Catalina) or newer, consult - the macOS installation instructions - before installing. - - - - As of Nix 2.1.0, the Nix installer will always default to creating a - single-user installation, however opting in to the multi-user - installation is highly recommended. - - - -
- Single User Installation - - - To explicitly select a single-user installation on your system: - - - sh <(curl -L https://nixos.org/nix/install) --no-daemon - - - - -This will perform a single-user installation of Nix, meaning that -/nix is owned by the invoking user. You should -run this under your usual user account, not as -root. The script will invoke sudo to create -/nix if it doesn’t already exist. If you don’t -have sudo, you should manually create -/nix first as root, e.g.: - - -$ mkdir /nix -$ chown alice /nix - - -The install script will modify the first writable file from amongst -.bash_profile, .bash_login -and .profile to source -~/.nix-profile/etc/profile.d/nix.sh. You can set -the NIX_INSTALLER_NO_MODIFY_PROFILE environment -variable before executing the install script to disable this -behaviour. - - - -You can uninstall Nix simply by running: - - -$ rm -rf /nix - - - -
- -
- Multi User Installation - - The multi-user Nix installation creates system users, and a system - service for the Nix daemon. - - - - Supported Systems - - - Linux running systemd, with SELinux disabled - - macOS - - - - You can instruct the installer to perform a multi-user - installation on your system: - - - 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 should run this under your usual user account, - not as root. The script will invoke - sudo as needed. - - - - If you need Nix to use a different group ID or user ID set, you - will have to download the tarball manually and edit the install - script. - - - - The installer will modify /etc/bashrc, and - /etc/zshrc if they exist. The installer will - first back up these files with a - .backup-before-nix 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 - - - There may also be references to Nix in - /etc/profile, - /etc/bashrc, and - /etc/zshrc which you may remove. - - -
- -
- macOS Installation - - - Starting with macOS 10.15 (Catalina), the root filesystem is read-only. - This means /nix can no longer live on your system - volume, and that you'll need a workaround to install Nix. - - - - The recommended approach, which creates an unencrypted APFS volume - for your Nix store and a "synthetic" empty directory to mount it - over at /nix, is least likely to impair Nix - or your system. - - - - With all separate-volume approaches, it's possible something on - your system (particularly daemons/services and restored apps) may - need access to your Nix store before the volume is mounted. Adding - additional encryption makes this more likely. - - - - If you're using a recent Mac with a - T2 chip, - 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 - - - If you don't like the sound of this, you'll want to weigh the - other approaches and tradeoffs detailed in this section. - - - - Eventual solutions? - - All of the known workarounds have drawbacks, but we hope - better solutions will be available in the future. Some that - we have our eye on are: - - - - - A true firmlink would enable the Nix store to live on the - primary data volume without the build problems caused by - the symlink approach. End users cannot currently - create true firmlinks. - - - - - If the Nix store volume shared FileVault encryption - with the primary data volume (probably by using the same - volume group and role), FileVault encryption could be - easily supported by the installer without requiring - manual setup by each user. - - - - - -
- Change the Nix store path prefix - - Changing the default prefix for the Nix store is a simple - approach which enables you to leave it on your root volume, - where it can take full advantage of FileVault encryption if - enabled. Unfortunately, this approach also opts your device out - of some benefits that are enabled by using the same prefix - across systems: - - - - - Your system won't be able to take advantage of the binary - cache (unless someone is able to stand up and support - duplicate caching infrastructure), which means you'll - spend more time waiting for builds. - - - - - It's harder to build and deploy packages to Linux systems. - - - - - - - - It would also possible (and often requested) to just apply this - change ecosystem-wide, but it's an intrusive process that has - side effects we want to avoid for now. - - - - -
- -
- Use a separate encrypted volume - - If you like, you can also add encryption to the recommended - approach taken by the installer. You can do this by pre-creating - an encrypted volume before you run the installer--or you can - run the installer and encrypt the volume it creates later. - - - - In either case, adding encryption to a second volume isn't quite - as simple as enabling FileVault for your boot volume. Before you - dive in, there are a few things to weigh: - - - - - The additional volume won't be encrypted with your existing - FileVault key, so you'll need another mechanism to decrypt - the volume. - - - - - You can store the password in Keychain to automatically - decrypt the volume on boot--but it'll have to wait on Keychain - and may not mount before your GUI apps restore. If any of - your launchd agents or apps depend on Nix-installed software - (for example, if you use a Nix-installed login shell), the - restore may fail or break. - - - On a case-by-case basis, you may be able to work around this - problem by using wait4path to block - execution until your executable is available. - - - It's also possible to decrypt and mount the volume earlier - with a login hook--but this mechanism appears to be - deprecated and its future is unclear. - - - - - You can hard-code the password in the clear, so that your - store volume can be decrypted before Keychain is available. - - - - - 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 - - -
- -
- - Symlink the Nix store to a custom location - - Another simple approach is using /etc/synthetic.conf - to symlink the Nix store to the data volume. This option also - enables your store to share any configured FileVault encryption. - Unfortunately, builds that resolve the symlink may leak the - canonical path or even fail. - - - Because of these downsides, we can't recommend this approach. - - -
- -
- Notes on the recommended approach - - This section goes into a little more detail on the recommended - approach. You don't need to understand it to run the installer, - but it can serve as a helpful reference if you run into trouble. - - - - - In order to compose user-writable locations into the new - read-only system root, Apple introduced a new concept called - firmlinks, which it describes as a - "bi-directional wormhole" between two filesystems. You can - see the current firmlinks in /usr/share/firmlinks. - Unfortunately, firmlinks aren't (currently?) user-configurable. - - - - For special cases like NFS mount points or package manager roots, - synthetic.conf(5) - supports limited user-controlled file-creation (of symlinks, - and synthetic empty directories) at /. - To create a synthetic empty directory for mounting at /nix, - add the following line to /etc/synthetic.conf - (create it if necessary): - - - nix - - - - - This configuration is applied at boot time, but you can use - apfs.util to trigger creation (not deletion) - of new entries without a reboot: - - - alice$ /System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util -B - - - - - Create the new APFS volume with diskutil: - - - alice$ sudo diskutil apfs addVolume diskX APFS 'Nix Store' -mountpoint /nix - - - - - Using vifs, add the new mount to - /etc/fstab. If it doesn't already have - other entries, it should look something like: - - - -# -# Warning - this file should only be modified with vifs(8) -# -# Failure to do so is unsupported and may be destructive. -# -LABEL=Nix\040Store /nix apfs rw,nobrowse - - - - The nobrowse setting will keep Spotlight from indexing this - volume, and keep it from showing up on your desktop. - - - -
- -
- -
- Installing a pinned Nix version from a URL - - - NixOS.org hosts version-specific installation URLs for all Nix - versions 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) - - - - - In the same directory of the install script are sha256 sums, and - gpg signature files. - -
- -
- Installing from a binary tarball - - - You can also download a binary tarball that contains Nix and all - its dependencies. (This is what the install script at - https://nixos.org/nix/install does automatically.) You - should unpack 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 - - - - - 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 file named - install-multi-user. - -
-
diff --git a/doc/manual/installation/installing-source.xml b/doc/manual/installation/installing-source.xml deleted file mode 100644 index c261a109d..000000000 --- a/doc/manual/installation/installing-source.xml +++ /dev/null @@ -1,16 +0,0 @@ - - -Installing Nix from Source - -If no binary package is available, you can download and compile -a source distribution. - - - - - - diff --git a/doc/manual/installation/multi-user.xml b/doc/manual/installation/multi-user.xml deleted file mode 100644 index 69ae1ef27..000000000 --- a/doc/manual/installation/multi-user.xml +++ /dev/null @@ -1,107 +0,0 @@ -
- -Multi-User Mode - -To allow a Nix store to be shared safely among multiple users, -it is important that users are not able to run builders that modify -the Nix store or database in arbitrary ways, or that interfere with -builds started by other users. If they could do so, they could -install a Trojan horse in some package and compromise the accounts of -other users. - -To prevent this, the Nix store and database are owned by some -privileged user (usually root) and builders are -executed under special user accounts (usually named -nixbld1, nixbld2, etc.). When a -unprivileged user runs a Nix command, actions that operate on the Nix -store (such as builds) are forwarded to a Nix -daemon running under the owner of the Nix store/database -that performs the operation. - -Multi-user mode has one important limitation: only -root and a set of trusted -users specified in nix.conf can specify arbitrary -binary caches. So while unprivileged users may install packages from -arbitrary Nix expressions, they may not get pre-built -binaries. - - - - -Setting up the build users - -The build users are the special UIDs under -which builds are performed. They should all be members of the -build users group nixbld. -This 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 - - -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 expect to do many builds at the same time. - - - - - - -Running the daemon - -The Nix daemon should be -started as follows (as root): - - -$ nix-daemon - -You’ll want to put that line somewhere in your system’s boot -scripts. - -To let unprivileged users use the daemon, they should set the -NIX_REMOTE environment -variable to daemon. So you should put a -line like - - -export NIX_REMOTE=daemon - -into the users’ login scripts. - - - - - - -Restricting access - -To limit which users can perform Nix operations, you can use the -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 - - -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 cannot -perform Nix operations. - - - - -
diff --git a/doc/manual/installation/nix-security.xml b/doc/manual/installation/nix-security.xml deleted file mode 100644 index d888ff14d..000000000 --- a/doc/manual/installation/nix-security.xml +++ /dev/null @@ -1,27 +0,0 @@ - - -Security - -Nix has two basic security models. First, it can be used in -“single-user mode”, which is similar to what most other package -management tools do: there is a single user (typically root) who performs all package -management operations. All other users can then use the installed -packages, but they cannot perform package management operations -themselves. - -Alternatively, you can configure Nix in “multi-user mode”. In -this model, all users can perform package management operations — for -instance, every user can install software without requiring root -privileges. Nix ensures that this is secure. For instance, it’s not -possible for one user to overwrite a package used by another user with -a Trojan horse. - - - - - \ No newline at end of file diff --git a/doc/manual/installation/obtaining-source.xml b/doc/manual/installation/obtaining-source.xml deleted file mode 100644 index 968822cc0..000000000 --- a/doc/manual/installation/obtaining-source.xml +++ /dev/null @@ -1,30 +0,0 @@ -
- -Obtaining a Source Distribution - -The source tarball of the most recent stable release can be -downloaded from the Nix homepage. -You can also grab the most -recent development release. - -Alternatively, the most recent sources of Nix can be obtained -from its Git -repository. For example, the following command will check out -the latest revision into a directory called -nix: - - -$ git clone https://github.com/NixOS/nix - -Likewise, specific releases can be obtained from the tags of the -repository. - -
\ No newline at end of file diff --git a/doc/manual/installation/prerequisites-source.xml b/doc/manual/installation/prerequisites-source.xml deleted file mode 100644 index fa6da9b1e..000000000 --- a/doc/manual/installation/prerequisites-source.xml +++ /dev/null @@ -1,113 +0,0 @@ -
- -Prerequisites - - - - GNU Autoconf - () - and the autoconf-archive macro collection - (). - These are only needed to run the bootstrap script, and are not necessary - if your source distribution came with a pre-built - ./configure script. - - GNU Make. - - Bash Shell. The ./configure script - relies on bashisms, so Bash is required. - - A version of GCC or Clang that supports C++17. - - pkg-config to locate - dependencies. If your distribution does not provide it, you can get - it from . - - The OpenSSL library to calculate cryptographic hashes. - If your distribution does not provide it, you can get it from . - - The libbrotlienc and - libbrotlidec libraries to provide implementation - of the Brotli compression algorithm. They are available for download - from the official repository . - - The bzip2 compressor program and the - libbz2 library. Thus you must have bzip2 - installed, including development headers and libraries. If your - distribution does not provide these, you can obtain bzip2 from . - - liblzma, which is provided by - XZ Utils. If your distribution does not provide this, you can - get it from . - - cURL and its library. If your distribution does not - provide it, you can get it from . - - The SQLite embedded database library, version 3.6.19 - or higher. If your distribution does not provide it, please install - it from . - - The Boehm - garbage collector to reduce the evaluator’s memory - consumption (optional). To enable it, install - pkgconfig and the Boehm garbage collector, and - pass the flag to - configure. - - The boost library of version - 1.66.0 or higher. It can be obtained from the official web site - . - - The editline library of version - 1.14.0 or higher. It can be obtained from the its repository - . - - The xmllint and - xsltproc programs to build this manual and the - man-pages. These are part of the libxml2 and - libxslt packages, respectively. You also need - the DocBook - XSL stylesheets and optionally the DocBook 5.0 RELAX NG - schemas. Note that these are only required if you modify the - manual sources or when you are building from the Git - repository. - - Recent versions of Bison and Flex to build the - parser. (This is because Nix needs GLR support in Bison and - reentrancy support in Flex.) For Bison, you need version 2.6, which - can be obtained from the GNU FTP - server. For Flex, you need version 2.5.35, which is - available on SourceForge. - Slightly older versions may also work, but ancient versions like the - ubiquitous 2.5.4a won't. Note that these are only required if you - modify the parser or when you are building from the Git - repository. - - The libseccomp is used to provide - syscall filtering on Linux. This is an optional dependency and can - be disabled passing a - option to the configure script (Not recommended - unless your system doesn't support - libseccomp). To get the library, visit . - - - -
diff --git a/doc/manual/installation/single-user.xml b/doc/manual/installation/single-user.xml deleted file mode 100644 index 09cdaa5d4..000000000 --- a/doc/manual/installation/single-user.xml +++ /dev/null @@ -1,21 +0,0 @@ -
- -Single-User Mode - -In single-user mode, all Nix operations that access the database -in prefix/var/nix/db -or modify the Nix store in -prefix/store must be -performed under the user ID that owns those directories. This is -typically root. (If you -install from RPM packages, that’s in fact the default ownership.) -However, on single-user machines, it is often convenient to -chown those directories to your normal user account -so that you don’t have to su to root all the time. - -
\ No newline at end of file diff --git a/doc/manual/installation/supported-platforms.xml b/doc/manual/installation/supported-platforms.xml deleted file mode 100644 index 3e74be49d..000000000 --- a/doc/manual/installation/supported-platforms.xml +++ /dev/null @@ -1,36 +0,0 @@ - - -Supported Platforms - -Nix is currently supported on the following platforms: - - - - Linux (i686, x86_64, aarch64). - - macOS (x86_64). - - - - - - - - - - diff --git a/doc/manual/installation/upgrading.xml b/doc/manual/installation/upgrading.xml deleted file mode 100644 index 592f63895..000000000 --- a/doc/manual/installation/upgrading.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - Upgrading Nix - - - Multi-user Nix users on macOS can upgrade Nix by running: - sudo -i sh -c 'nix-channel --update && - nix-env -iA nixpkgs.nix && - launchctl remove org.nixos.nix-daemon && - launchctl load /Library/LaunchDaemons/org.nixos.nix-daemon.plist' - - - - - Single-user installations of Nix should run this: - nix-channel --update; nix-env -iA nixpkgs.nix nixpkgs.cacert - - - - Multi-user Nix users on Linux should run this with sudo: - nix-channel --update; nix-env -iA nixpkgs.nix nixpkgs.cacert; systemctl daemon-reload; systemctl restart nix-daemon - - diff --git a/doc/manual/introduction/about-nix.xml b/doc/manual/introduction/about-nix.xml deleted file mode 100644 index c21ed34dd..000000000 --- a/doc/manual/introduction/about-nix.xml +++ /dev/null @@ -1,268 +0,0 @@ - - -About Nix - -Nix is a purely functional package manager. -This means that it treats packages like values in purely functional -programming languages such as Haskell — they are built by functions -that don’t have side-effects, and they never change after they have -been built. Nix stores packages in the Nix -store, usually the directory -/nix/store, where each package has its own unique -subdirectory such as - - -/nix/store/b6gvzjyb2pg0kjfwrjmg1vfhh54ad73z-firefox-33.1/ - - -where b6gvzjyb2pg0… is a unique identifier for the -package that captures all its dependencies (it’s a cryptographic hash -of the package’s build dependency graph). This enables many powerful -features. - - -Multiple versions - -You can have multiple versions or variants of a package -installed at the same time. This is especially important when -different applications have dependencies on different versions of the -same package — it prevents the “DLL hell”. Because of the hashing -scheme, different versions of a package end up in different paths in -the Nix store, so they don’t interfere with each other. - -An important consequence is that operations like upgrading or -uninstalling an application cannot break other applications, since -these operations never “destructively” update or delete files that are -used by other packages. - - - - -Complete dependencies - -Nix helps you make sure that package dependency specifications -are complete. In general, when you’re making a package for a package -management system like RPM, you have to specify for each package what -its dependencies are, but there are no guarantees that this -specification is complete. If you forget a dependency, then the -package will build and work correctly on your -machine if you have the dependency installed, but not on the end -user's machine if it's not there. - -Since Nix on the other hand doesn’t install packages in “global” -locations like /usr/bin but in package-specific -directories, the risk of incomplete dependencies is greatly reduced. -This is because tools such as compilers don’t search in per-packages -directories such as -/nix/store/5lbfaxb722zp…-openssl-0.9.8d/include, -so if a package builds correctly on your system, this is because you -specified the dependency explicitly. This takes care of the build-time -dependencies. - -Once a package is built, runtime dependencies are found by -scanning binaries for the hash parts of Nix store paths (such as -r8vvq9kq…). This sounds risky, but it works -extremely well. - - - - -Multi-user support - -Nix has multi-user support. This means that non-privileged -users can securely install software. Each user can have a different -profile, a set of packages in the Nix store that -appear in the user’s PATH. If a user installs a -package that another user has already installed previously, the -package won’t be built or downloaded a second time. At the same time, -it is not possible for one user to inject a Trojan horse into a -package that might be used by another user. - - - - -Atomic upgrades and rollbacks - -Since package management operations never overwrite packages in -the Nix store but just add new versions in different paths, they are -atomic. So during a package upgrade, there is no -time window in which the package has some files from the old version -and some files from the new version — which would be bad because a -program might well crash if it’s started during that period. - -And since packages aren’t 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 - - - - - -Garbage collection - -When you uninstall a package like this… - - -$ nix-env --uninstall firefox - - -the package isn’t 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 - - -This deletes all packages that aren’t in use by any user profile or by -a currently running program. - - - - -Functional package language - -Packages are built from Nix expressions, -which is a simple functional language. A Nix expression describes -everything that goes into a package build action (a “derivation”): -other packages, sources, the build script, environment variables for -the build script, etc. Nix tries very hard to ensure that Nix -expressions are deterministic: building a Nix -expression twice should yield the same result. - -Because it’s a functional language, it’s easy to support -building variants of a package: turn the Nix expression into a -function and call it any number of times with the appropriate -arguments. Due to the hashing scheme, variants don’t conflict with -each other in the Nix store. - - - - -Transparent source/binary deployment - -Nix expressions generally describe how to build a package from -source, so an installation action like - - -$ 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 compiler) would have to built, at least if they are -not already in the Nix store. This is a source deployment -model. For most users, building from source is not very -pleasant as it takes far too long. However, Nix can automatically -skip building from source and instead use a binary -cache, a web server that provides pre-built binaries. For -instance, when asked to build -/nix/store/b6gvzjyb2pg0…-firefox-33.1 from source, -Nix would first check if the file -https://cache.nixos.org/b6gvzjyb2pg0….narinfo exists, and -if so, fetch the pre-built binary referenced from there; otherwise, it -would fall back to building from source. - - - - - - - -Nix Packages collection - -We provide a large set of Nix expressions containing hundreds of -existing Unix packages, the Nix Packages -collection (Nixpkgs). - - - - -Managing build environments - -Nix is extremely useful for developers as it makes it easy to -automatically set up the build environment for a package. Given a -Nix expression that describes the dependencies of your package, the -command nix-shell will build or download those -dependencies if they’re not already in your Nix store, and then start -a Bash shell in which all necessary environment variables (such as -compiler search paths) are set. - -For example, the following command gets all dependencies of the -Pan newsreader, as described by its -Nix expression: - - -$ nix-shell '<nixpkgs>' -A pan - - -You’re 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 - - - - - - - -Portability - -Nix runs on Linux and macOS. - - - - -NixOS - -NixOS is a Linux distribution based on Nix. It uses Nix not -just for package management but also to manage the system -configuration (e.g., to build configuration files in -/etc). This means, among other things, that it -is easy to roll back the entire configuration of the system to an -earlier state. Also, users can install software without root -privileges. For more information and downloads, see the NixOS homepage. - - - - -License - -Nix is released under the terms of the GNU -LGPLv2.1 or (at your option) any later version. - - - - - diff --git a/doc/manual/introduction/introduction.xml b/doc/manual/introduction/introduction.xml deleted file mode 100644 index 12b2cc761..000000000 --- a/doc/manual/introduction/introduction.xml +++ /dev/null @@ -1,12 +0,0 @@ - - -Introduction - - - - - diff --git a/doc/manual/introduction/quick-start.xml b/doc/manual/introduction/quick-start.xml deleted file mode 100644 index 1992c14ed..000000000 --- a/doc/manual/introduction/quick-start.xml +++ /dev/null @@ -1,124 +0,0 @@ - - -Quick Start - -This chapter is for impatient people who don't like reading -documentation. For more in-depth information you are kindly referred -to subsequent chapters. - - - -Install single-user Nix by running the following: - - -$ 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 other installation -methods, see .) - -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 -... - - - -Install some packages from the channel: - - -$ nix-env -i hello - -This should download pre-built packages; it should not build them -locally (if it does, something went wrong). - -Test that they work: - - -$ which hello -/home/eelco/.nix-profile/bin/hello -$ hello -Hello, world! - - - - -Uninstall a package: - - -$ nix-env -e hello - - - -You can also test a package without installing it: - - -$ 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! - -[nix-shell:~]$ exit - -$ hello -hello: command not found - - - - -To keep up-to-date with the channel, do: - - -$ 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 -numbers). - -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 - - - -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 - - - - - - - - diff --git a/doc/manual/local.mk b/doc/manual/local.mk index ce05c6234..d308c7cf6 100644 --- a/doc/manual/local.mk +++ b/doc/manual/local.mk @@ -1,84 +1,62 @@ - ifeq ($(doc_generate),yes) -XSLTPROC = $(xsltproc) --nonet $(xmlflags) \ - --param section.autolabel 1 \ - --param section.label.includes.component.label 1 \ - --param xref.with.number.and.title 1 \ - --param toc.section.depth 3 \ - --param admon.style \'\' \ - --param callout.graphics 0 \ - --param contrib.inline.enabled 0 \ - --stringparam generate.toc "book toc" \ - --param keep.relative.image.uris 0 - -docbookxsl = http://docbook.sourceforge.net/release/xsl-ns/current -docbookrng = http://docbook.org/xml/5.0/rng/docbook.rng - -MANUAL_SRCS := $(call rwildcard, $(d), *.xml) - - -# Do XInclude processing / RelaxNG validation -$(d)/manual.xmli: $(d)/manual.xml $(MANUAL_SRCS) $(d)/version.txt - $(trace-gen) $(xmllint) --nonet --xinclude $< -o $@.tmp - @mv $@.tmp $@ - -$(d)/version.txt: - $(trace-gen) echo -n $(PACKAGE_VERSION) > $@ - -# Note: RelaxNG validation requires xmllint >= 2.7.4. -$(d)/manual.is-valid: $(d)/manual.xmli - $(trace-gen) $(XSLTPROC) --novalid --stringparam profile.condition manual \ - $(docbookxsl)/profiling/profile.xsl $< 2> /dev/null | \ - $(xmllint) --nonet --noout --relaxng $(docbookrng) - - @touch $@ - -clean-files += $(d)/manual.xmli $(d)/version.txt $(d)/manual.is-valid - -dist-files += $(d)/manual.xmli $(d)/version.txt $(d)/manual.is-valid - +MANUAL_SRCS := $(call rwildcard, $(d)/src, *.md) # Generate man pages. man-pages := $(foreach n, \ - nix-env.1 nix-build.1 nix-shell.1 nix-store.1 nix-instantiate.1 \ + nix-env.1 nix-build.1 nix-shell.1 nix-store.1 nix-instantiate.1 nix.1 \ nix-collect-garbage.1 \ nix-prefetch-url.1 nix-channel.1 \ nix-hash.1 nix-copy-closure.1 \ nix.conf.5 nix-daemon.8, \ $(d)/$(n)) -$(firstword $(man-pages)): $(d)/manual.xmli $(d)/manual.is-valid - $(trace-gen) $(XSLTPROC) --novalid --stringparam profile.condition manpage \ - $(docbookxsl)/profiling/profile.xsl $< 2> /dev/null | \ - (cd doc/manual && $(XSLTPROC) $(docbookxsl)/manpages/docbook.xsl -) - -$(wordlist 2, $(words $(man-pages)), $(man-pages)): $(firstword $(man-pages)) - clean-files += $(d)/*.1 $(d)/*.5 $(d)/*.8 dist-files += $(man-pages) +nix-eval = $(bindir)/nix eval --experimental-features nix-command -I nix/corepkgs=corepkgs --store dummy:// --impure --raw --expr + +$(d)/%.1: $(d)/src/command-ref/%.md + $(trace-gen) lowdown -sT man $^ -o $@ + +$(d)/%.8: $(d)/src/command-ref/%.md + $(trace-gen) lowdown -sT man $^ -o $@ + +$(d)/nix.conf.5: $(d)/src/command-ref/conf-file.md + $(trace-gen) lowdown -sT man $^ -o $@ + +$(d)/src/command-ref/nix.md: $(d)/nix.json $(d)/generate-manpage.nix $(bindir)/nix + $(trace-gen) $(nix-eval) 'import doc/manual/generate-manpage.nix (builtins.fromJSON (builtins.readFile $<))' > $@.tmp + @mv $@.tmp $@ + +$(d)/src/command-ref/conf-file.md: $(d)/conf-file.json $(d)/generate-options.nix $(d)/src/command-ref/conf-file-prefix.md $(bindir)/nix + @cat doc/manual/src/command-ref/conf-file-prefix.md > $@.tmp + $(trace-gen) $(nix-eval) 'import doc/manual/generate-options.nix (builtins.fromJSON (builtins.readFile $<))' >> $@.tmp + @mv $@.tmp $@ + +$(d)/nix.json: $(bindir)/nix + $(trace-gen) $(bindir)/nix __dump-args > $@.tmp + @mv $@.tmp $@ + +$(d)/conf-file.json: $(bindir)/nix + $(trace-gen) env -i NIX_CONF_DIR=/dummy HOME=/dummy NIX_SSL_CERT_FILE=/dummy/no-ca-bundle.crt $(bindir)/nix show-config --json --experimental-features nix-command > $@.tmp + @mv $@.tmp $@ + +$(d)/src/expressions/builtins.md: $(d)/builtins.json $(d)/generate-builtins.nix $(d)/src/expressions/builtins-prefix.md $(bindir)/nix + @cat doc/manual/src/expressions/builtins-prefix.md > $@.tmp + $(trace-gen) $(nix-eval) 'import doc/manual/generate-builtins.nix (builtins.fromJSON (builtins.readFile $<))' >> $@.tmp + @mv $@.tmp $@ + +$(d)/builtins.json: $(bindir)/nix + $(trace-gen) NIX_PATH=nix/corepkgs=corepkgs $(bindir)/nix __dump-builtins > $@.tmp + mv $@.tmp $@ # Generate the HTML manual. -$(d)/manual.html: $(d)/manual.xml $(MANUAL_SRCS) $(d)/manual.is-valid - $(trace-gen) $(XSLTPROC) --xinclude --stringparam profile.condition manual \ - $(docbookxsl)/profiling/profile.xsl $< | \ - $(XSLTPROC) --output $@ $(docbookxsl)/xhtml/docbook.xsl - - -$(foreach file, $(d)/manual.html, $(eval $(call install-data-in, $(file), $(docdir)/manual))) - -$(foreach file, $(wildcard $(d)/figures/*.png), $(eval $(call install-data-in, $(file), $(docdir)/manual/figures))) - -$(eval $(call install-symlink, manual.html, $(docdir)/manual/index.html)) - - -all: $(d)/manual.html - - - -clean-files += $(d)/manual.html - -dist-files += $(d)/manual.html +install: $(docdir)/manual/index.html +$(docdir)/manual/index.html: $(MANUAL_SRCS) $(d)/book.toml $(d)/custom.css $(d)/src/command-ref/nix.md $(d)/src/command-ref/conf-file.md $(d)/src/expressions/builtins.md + $(trace-gen) mdbook build doc/manual -d $(docdir)/manual + @cp doc/manual/highlight.pack.js $(docdir)/manual/highlight.js endif diff --git a/doc/manual/manual.xml b/doc/manual/manual.xml deleted file mode 100644 index 87d9de28a..000000000 --- a/doc/manual/manual.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - Nix Package Manager Guide - Version - - - - Eelco - Dolstra - - Author - - - - 2004-2018 - Eelco Dolstra - - - - - - - - - - - - - - - - - - - - diff --git a/doc/manual/nix-lang-ref.xml b/doc/manual/nix-lang-ref.xml deleted file mode 100644 index 86273ac3d..000000000 --- a/doc/manual/nix-lang-ref.xml +++ /dev/null @@ -1,182 +0,0 @@ - - Nix Language Reference - - - Grammar - - - Expressions - - - Expr - - - - - - - ExprFunction - - '{' '}' ':' - | - - - - - - ExprAssert - - 'assert' ';' - | - - - - - - ExprIf - - 'if' 'then' - 'else' - | - - - - - - ExprOp - - '!' - | - '==' - | - '!=' - | - '&&' - | - '||' - | - '->' - | - '//' - | - '~' - | - '?' - | - - - - - - ExprApp - - '.' - | - - - - - - ExprSelect - - - | - - - - - - ExprSimple - - | - | - | - | - - | - 'true' | 'false' | 'null' - | - '(' ')' - | - '{' * '}' - | - 'let' '{' * '}' - | - 'rec' '{' * '}' - | - '[' * ']' - - - - - Bind - - '=' ';' - | - 'inherit' ('(' ')')? * ';' - - - - - Formals - - ',' - | - - - - - Formal - - - | - '?' - - - - - - - Terminals - - - Id - [a-zA-Z\_][a-zA-Z0-9\_\']* - - - - Int - [0-9]+ - - - - Str - \"[^\n\"]*\" - - - - Path - [a-zA-Z0-9\.\_\-\+]*(\/[a-zA-Z0-9\.\_\-\+]+)+ - - - - Uri - [a-zA-Z][a-zA-Z0-9\+\-\.]*\:[a-zA-Z0-9\%\/\?\:\@\&\=\+\$\,\-\_\.\!\~\*\']+ - - - - Whitespace - - [ \t\n]+ - | - \#[^\n]* - | - \/\*(.|\n)*\*\/ - - - - - - - - diff --git a/doc/manual/packages/basic-package-mgmt.xml b/doc/manual/packages/basic-package-mgmt.xml deleted file mode 100644 index 0f21297f3..000000000 --- a/doc/manual/packages/basic-package-mgmt.xml +++ /dev/null @@ -1,194 +0,0 @@ - - -Basic Package Management - -The main command for package management is nix-env. You can use -it to install, upgrade, and erase packages, and to query what -packages are installed or are available for installation. - -In Nix, different users can have different “views” -on the set of installed applications. That is, there might be lots of -applications present on the system (possibly in many different -versions), but users can have a specific selection of those active — -where “active” just means that it appears in a directory -in the user’s PATH. Such a view on the set of -installed applications is called a user -environment, which is just a directory tree consisting of -symlinks to the files of the active applications. - -Components are installed from a set of Nix -expressions that tell Nix how to build those packages, -including, if necessary, their dependencies. There is a collection of -Nix expressions called the Nixpkgs package collection that contains -packages ranging from basic development stuff such as GCC and Glibc, -to end-user applications like Mozilla Firefox. (Nix is however not -tied to the Nixpkgs package collection; you could write your own Nix -expressions based on Nixpkgs, or completely new ones.) - -You can manually download the latest version of Nixpkgs from -. However, -it’s much more convenient to use the Nixpkgs -channel, since it makes it easy to stay up to -date with new versions of Nixpkgs. (Channels are described in more -detail in .) Nixpkgs is 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 - - - - -On NixOS, you’re automatically subscribed to a NixOS -channel corresponding to your NixOS major release -(e.g. http://nixos.org/channels/nixos-14.12). A NixOS -channel is identical to the Nixpkgs channel, except that it contains -only Linux binaries and is updated only if a set of regression tests -succeed. - -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 -… - -The flag specifies a query operation, and - means that you want to show the “available” (i.e., -installable) packages, as opposed to the 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 - flag: - - -$ nix-env -qaf /path/to/nixpkgs - - -where /path/to/nixpkgs is where you’ve -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 - - -and using regular expressions: - - -$ 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 -… - -The first character (I) indicates whether the -package is installed in your current user environment. The second -(P) indicates whether it is present on your system -(in which case installing it into your user environment would be a -very quick operation). The last one (S) indicates -whether there is a so-called substitute for the -package, which is Nix’s mechanism for doing binary deployment. It -just means that Nix knows that it can fetch a pre-built package from -somewhere (typically a network server) instead of building it -locally. - -You can install a package using nix-env -i. -For instance, - - -$ nix-env -i subversion - -will install the package called subversion (which -is, of course, the Subversion version -management system). - -When you ask Nix to install a package, it will first try -to get it in pre-compiled form from a binary -cache. By default, Nix will use the binary cache -https://cache.nixos.org; it contains binaries for most -packages in Nixpkgs. Only if no binary is available in the binary -cache, Nix will build the package from source. So if nix-env --i subversion results in Nix building stuff from source, -then either the package is not built for your platform by the Nixpkgs -build servers, or your version of Nixpkgs is too old or too new. For -instance, if you have a very recent checkout of Nixpkgs, then the -Nixpkgs build servers may not have had a chance to build everything -and upload the resulting binaries to -https://cache.nixos.org. The Nixpkgs channel is only -updated after all binaries have been uploaded to the cache, so if you -stick to the Nixpkgs channel (rather than using a Git checkout of the -Nixpkgs tree), you will get binaries for most packages. - -Naturally, packages can also be uninstalled: - - -$ 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 - -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 regarding ordering of version -numbers (which generally do what you’d expect of them). To just -unconditionally replace Subversion with whatever version is in the Nix -expressions, use -i instead of --u; -i will remove -whatever version is already installed. - -You can also upgrade all packages for which there are newer -versions: - - -$ nix-env -u - - - -Sometimes it’s 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' - - - - diff --git a/doc/manual/packages/binary-cache-substituter.xml b/doc/manual/packages/binary-cache-substituter.xml deleted file mode 100644 index c6ceb9c80..000000000 --- a/doc/manual/packages/binary-cache-substituter.xml +++ /dev/null @@ -1,70 +0,0 @@ -
- -Serving a Nix store via HTTP - -You can easily share the Nix store of a machine via HTTP. This -allows other machines to fetch store paths from that machine to speed -up installations. It uses the same binary cache -mechanism that Nix 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 - - -You can then start the server, listening for HTTP connections on -whatever port you like: - - -$ nix-serve -p 8080 - - -To check whether it works, try the following on the client: - - -$ curl http://avalon:8080/nix-cache-info - - -which should print something like: - - -StoreDir: /nix/store -WantMassQuery: 1 -Priority: 30 - - - - -On the client side, you can tell Nix to use your binary cache -using , e.g.: - - -$ nix-env -i firefox --option extra-binary-caches http://avalon:8080/ - - -The option tells Nix to use this -binary cache in addition to your default caches, such as -https://cache.nixos.org. Thus, for any path in the closure -of Firefox, Nix will first check if the path is available on the -server avalon or another binary caches. If not, it -will fall back to building from source. - -You can also tell Nix to always use your binary cache by adding -a line to the nix.conf -configuration file like this: - - -binary-caches = http://avalon:8080/ https://cache.nixos.org/ - - - - -
diff --git a/doc/manual/packages/channels.xml b/doc/manual/packages/channels.xml deleted file mode 100644 index 1ed2bba52..000000000 --- a/doc/manual/packages/channels.xml +++ /dev/null @@ -1,60 +0,0 @@ - - -Channels - -If you want to stay up to date with a set of packages, it’s not -very convenient to manually download the latest set of Nix expressions -for those packages and upgrade using nix-env. -Fortunately, there’s a better way: Nix -channels. - -A Nix channel is just a URL that points to a place that contains -a set of Nix expressions and a manifest. Using the command nix-channel you -can automatically stay up to date with whatever is available at that -URL. - -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 - -subscribes you to a channel that always contains that latest version -of the Nix Packages collection. (Subscribing really just means that -the URL is added to the file ~/.nix-channels, -where it is read by subsequent calls to nix-channel ---update.) You can “unsubscribe” using nix-channel ---remove: - - -$ nix-channel --remove nixpkgs - - - -To obtain the latest Nix expressions available in a channel, do - - -$ 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 each channel’s Nix expressions available by -default to nix-env operations (via the symlink -~/.nix-defexpr/channels). Consequently, you can -then say - - -$ nix-env -u - -to upgrade all packages in your profile to the latest versions -available in the subscribed channels. - - diff --git a/doc/manual/packages/copy-closure.xml b/doc/manual/packages/copy-closure.xml deleted file mode 100644 index 012030e3e..000000000 --- a/doc/manual/packages/copy-closure.xml +++ /dev/null @@ -1,50 +0,0 @@ -
- -Copying Closures Via SSH - -The command nix-copy-closure copies a Nix -store path along with all its dependencies to or from another machine -via the SSH protocol. It doesn’t copy store paths that are already -present on the target machine. For example, the following command -copies Firefox with all its dependencies: - - -$ nix-copy-closure --to alice@itchy.example.org $(type -p firefox) - -See for details. - -With nix-store ---export and nix-store --import you can -write the closure of a store path (that is, the path and all its -dependencies) to a file, and then unpack that file into another Nix -store. For example, - - -$ nix-store --export $(nix-store -qR $(type -p firefox)) > firefox.closure - -writes the closure of Firefox to a file. You can then copy this file -to another machine and install the closure: - - -$ nix-store --import < firefox.closure - -Any store paths in the closure that are already present in the target -store are ignored. It is also possible to pipe the export into -another command, e.g. to copy and install a closure directly to/on -another machine: - - -$ nix-store --export $(nix-store -qR $(type -p firefox)) | bzip2 | \ - ssh alice@itchy.example.org "bunzip2 | nix-store --import" - -However, nix-copy-closure is generally more -efficient because it only copies paths that are not already present in -the target Nix store. - -
diff --git a/doc/manual/packages/garbage-collection.xml b/doc/manual/packages/garbage-collection.xml deleted file mode 100644 index b506f22b0..000000000 --- a/doc/manual/packages/garbage-collection.xml +++ /dev/null @@ -1,86 +0,0 @@ - - -Garbage Collection - -nix-env operations such as upgrades -() and uninstall () never -actually delete packages from the system. All they do (as shown -above) is to create a new user environment that no longer contains -symlinks to the “deleted” packages. - -Of course, since disk space is not infinite, unused packages -should be removed at some point. You can do this by running the Nix -garbage collector. It will remove from the Nix store any package -not used (directly or indirectly) by any generation of any -profile. - -Note however that as long as old generations reference a -package, it will not be deleted. After all, we wouldn’t be able to -do a rollback otherwise. So in order for garbage collection to be -effective, you should also delete (some) old generations. Of course, -this should only 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 - -Instead of old you can also specify a list of -generations, e.g., - - -$ 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 - -deletes all generations older than two weeks. - -After removing appropriate old generations you can run the -garbage collector as follows: - - -$ nix-store --gc - -The behaviour of the gargage collector is affected by the -keep-derivations (default: true) and keep-outputs -(default: false) options in the Nix configuration file. The defaults will ensure -that all derivations that are build-time dependencies of garbage collector roots -will be kept and that all output paths that are runtime dependencies -will be kept as well. All other derivations or paths will be collected. -(This is usually what you want, but while you are developing -it may make 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 - -Likewise, the option will show the paths -that won’t be deleted. - -There is also a convenient little utility -nix-collect-garbage, which when invoked with the - () switch deletes all -old generations of all profiles in -/nix/var/nix/profiles. So - - -$ nix-collect-garbage -d - -is a quick and easy way to clean up your system. - - - - diff --git a/doc/manual/packages/garbage-collector-roots.xml b/doc/manual/packages/garbage-collector-roots.xml deleted file mode 100644 index 8338e5392..000000000 --- a/doc/manual/packages/garbage-collector-roots.xml +++ /dev/null @@ -1,29 +0,0 @@ -
- -Garbage Collector Roots - -The roots of the garbage collector are all store paths to which -there 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 - -That is, after this command, the garbage collector will not remove -/nix/store/d718ef...-foo or any of its -dependencies. - -Subdirectories of -prefix/nix/var/nix/gcroots -are also searched for symlinks. Symlinks to non-store paths are -followed and searched for roots, but symlinks to non-store paths -inside the paths reached in that way are not -followed to prevent infinite recursion. - -
\ No newline at end of file diff --git a/doc/manual/packages/package-management.xml b/doc/manual/packages/package-management.xml deleted file mode 100644 index 61e55faeb..000000000 --- a/doc/manual/packages/package-management.xml +++ /dev/null @@ -1,23 +0,0 @@ - - -Package Management - - -This chapter discusses how to do package management with Nix, -i.e., how to obtain, install, upgrade, and erase packages. This is -the “user’s” perspective of the Nix system — people -who want to create packages should consult -. - - - - - - - - - diff --git a/doc/manual/packages/profiles.xml b/doc/manual/packages/profiles.xml deleted file mode 100644 index 4d10319ab..000000000 --- a/doc/manual/packages/profiles.xml +++ /dev/null @@ -1,158 +0,0 @@ - - -Profiles - -Profiles and user environments are Nix’s mechanism for -implementing the ability to allow different users to have different -configurations, and to do atomic upgrades and rollbacks. To -understand how they work, it’s useful to know a bit about how Nix -works. In Nix, packages are stored in unique locations in the -Nix store (typically, -/nix/store). For instance, a particular version -of the Subversion package might be stored in a directory -/nix/store/dpmvp969yhdqs7lm2r1a3gng7pyq6vy4-subversion-1.1.3/, -while another version might be stored in -/nix/store/5mq2jcn36ldlmh93yj1n8s9c95pj7c5s-subversion-1.1.2. -The long strings prefixed to the directory names are cryptographic -hashes160-bit truncations of SHA-256 hashes encoded in -a base-32 notation, to be precise. of -all inputs involved in building the package — -sources, dependencies, compiler flags, and so on. So if two -packages differ in any way, they end up in different locations in -the file system, so they don’t interfere with each other. shows a part of a typical Nix -store. - -
User environments - - - - - -
- -Of course, you wouldn’t want to type - - -$ /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 package we want to use, -but this is not very convenient since changing PATH -doesn’t take effect for already existing processes. The solution Nix -uses is to create directory trees of symlinks to -activated packages. These are called -user environments and they are packages -themselves (though automatically generated by -nix-env), so they too reside in the Nix store. For -instance, in the user -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 - -on a set of Nix expressions that contained Subversion 1.1.2. - -This doesn’t in itself solve the problem, of course; you -wouldn’t want to type -/nix/store/0c1p5z4kda11...-user-env/bin/svn -either. That’s why there are symlinks outside of the store that point -to the user environments in the store; for instance, the symlinks -default-42-link and -default-43-link in the example. These are called -generations 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 - -on a set of Nix expressions that contained Firefox and a new version -of Subversion. - -Generations are grouped together into -profiles so that different users don’t interfere -with each other if they don’t 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 - -This shows a profile called default. The file -default itself is actually a symlink that points -to the current generation. When we do a nix-env -operation, a new user environment and generation link are created -based on the current one, and finally the default -symlink is made to point at the new generation. This last step is -atomic on Unix, which explains how we can do atomic upgrades. (Note -that the building/installing of new packages doesn’t interfere in -any way with old packages, since they are stored in different -locations in the Nix store.) - -If you find that you want to undo a nix-env -operation, you can just do - - -$ 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 - -which in this example would roll forward to generation 43 again. You -can also see all available generations: - - -$ nix-env --list-generations - -You generally wouldn’t have -/nix/var/nix/profiles/some-profile/bin -in your PATH. Rather, there is a symlink -~/.nix-profile that points to your current -profile. This means that you should put -~/.nix-profile/bin in your PATH -(and indeed, that’s what the 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 - -These commands switch to the my-profile and -default profile, respectively. If the profile doesn’t exist, it will -be created automatically. You should be careful about storing a -profile in another location than the profiles -directory, since otherwise it might not be used as a root of the -garbage collector (see ). - -All nix-env operations work on the profile -pointed to by ~/.nix-profile, but you can override -this using the option (abbreviation -): - - -$ nix-env -p /nix/var/nix/profiles/other-profile -i subversion - -This will not change the -~/.nix-profile symlink. - -
diff --git a/doc/manual/packages/s3-substituter.xml b/doc/manual/packages/s3-substituter.xml deleted file mode 100644 index 868b5a66d..000000000 --- a/doc/manual/packages/s3-substituter.xml +++ /dev/null @@ -1,182 +0,0 @@ - -
- -Serving a Nix store via AWS S3 or S3-compatible Service - -Nix has built-in support for storing and fetching store paths -from Amazon S3 and S3 compatible services. This uses the same -binary cache mechanism that Nix usually uses to -fetch prebuilt binaries from cache.nixos.org. - -The following options can be specified as URL parameters to -the S3 URL: - - - profile - - - The name of the AWS configuration profile to use. By default - Nix will use the default profile. - - - - - region - - - The region of the S3 bucket. us–east-1 by - default. - - - - If your bucket is not in us–east-1, you - should always explicitly specify the region parameter. - - - - - endpoint - - - The URL to your S3-compatible service, for when not using - Amazon S3. Do not specify this value if you're using Amazon - S3. - - This endpoint must support HTTPS and will use - path-based addressing instead of virtual host based - addressing. - - - - scheme - - - The scheme used for S3 requests, https - (default) or http. This option allows you to - disable HTTPS for binary caches which don't support it. - - HTTPS should be used if the cache might contain - sensitive information. - - - - -In this example we will use the bucket named -example-nix-cache. - -
- Anonymous Reads to your S3-compatible binary cache - - If your binary cache is publicly accessible and does not - require authentication, the simplest and easiest way to use Nix with - your S3 compatible binary cache is to use the HTTP URL for that - cache. - - For AWS S3 the binary cache URL for example bucket will be - exactly https://example-nix-cache.s3.amazonaws.com or - s3://example-nix-cache. For S3 compatible binary caches, - consult that cache's documentation. - - Your bucket will need the following bucket policy: - - -
- -
- Authenticated Reads to your S3 binary cache - - For AWS S3 the binary cache URL for example bucket will be - exactly s3://example-nix-cache. - - Nix will use the default - credential provider chain for authenticating requests to - Amazon S3. - - Nix supports authenticated reads from Amazon S3 and S3 - compatible binary caches. - - Your bucket will need a bucket policy allowing the desired - users to perform the s3:GetObject and - s3:GetBucketLocation action on all objects in the - bucket. The anonymous policy in can be updated to - have a restricted Principal to support - this. -
- - -
- Authenticated Writes to your S3-compatible binary cache - - Nix support fully supports writing to Amazon S3 and S3 - compatible buckets. The binary cache URL for our example bucket will - be s3://example-nix-cache. - - Nix will use the default - credential provider chain for authenticating requests to - Amazon S3. - - Your account will need the following IAM policy to - upload to the cache: - - - - - Uploading with a specific credential profile for Amazon S3 - nix copy --to 's3://example-nix-cache?profile=cache-upload&region=eu-west-2' nixpkgs.hello - - - Uploading to an S3-Compatible Binary Cache - nix copy --to 's3://example-nix-cache?profile=cache-upload&scheme=https&endpoint=minio.example.com' nixpkgs.hello - -
-
diff --git a/doc/manual/packages/sharing-packages.xml b/doc/manual/packages/sharing-packages.xml deleted file mode 100644 index bb6c52b8f..000000000 --- a/doc/manual/packages/sharing-packages.xml +++ /dev/null @@ -1,20 +0,0 @@ - - -Sharing Packages Between Machines - -Sometimes you want to copy a package from one machine to -another. Or, you want to install some packages and you know that -another machine already has some or all of those packages or their -dependencies. In that case there are mechanisms to quickly copy -packages between machines. - - - - - - - diff --git a/doc/manual/packages/ssh-substituter.xml b/doc/manual/packages/ssh-substituter.xml deleted file mode 100644 index 8db3f9662..000000000 --- a/doc/manual/packages/ssh-substituter.xml +++ /dev/null @@ -1,73 +0,0 @@ -
- -Serving a Nix store via SSH - -You can tell Nix to automatically fetch needed binaries from a -remote Nix store via SSH. For example, the following installs Firefox, -automatically fetching any store paths in Firefox’s closure if they -are available on the server avalon: - - -$ 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 will first check if it’s available -in the Nix store on avalon. If not, it will fall -back to using the binary cache substituter, and then to building from -source. - -The SSH substituter currently does not allow you to enter -an SSH passphrase interactively. Therefore, you should use -ssh-add to load the decrypted private key into -ssh-agent. - -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 - - -This is essentially equivalent to doing - - -$ nix-copy-closure --from alice@avalon /nix/store/m85bxg…-firefox-34.0.5 - - - - -You can use SSH’s forced command feature to -set up a restricted user account for SSH substituter access, allowing -read-only access to the local Nix store, but nothing more. For -example, add the following lines to sshd_config -to restrict the user nix-ssh: - - -Match User nix-ssh - AllowAgentForwarding no - AllowTcpForwarding no - PermitTTY no - PermitTunnel no - X11Forwarding no - ForceCommand nix-store --serve -Match All - - -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" ]; - - -where the latter line lists the public keys of users that are allowed -to connect. - -
diff --git a/doc/manual/release-notes/release-notes.xml b/doc/manual/release-notes/release-notes.xml deleted file mode 100644 index 2655d68e3..000000000 --- a/doc/manual/release-notes/release-notes.xml +++ /dev/null @@ -1,51 +0,0 @@ - - -Nix Release Notes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/doc/manual/release-notes/rl-0.10.1.xml b/doc/manual/release-notes/rl-0.10.1.xml deleted file mode 100644 index 95829323d..000000000 --- a/doc/manual/release-notes/rl-0.10.1.xml +++ /dev/null @@ -1,13 +0,0 @@ -
- -Release 0.10.1 (2006-10-11) - -This release fixes two somewhat obscure bugs that occur when -evaluating Nix expressions that are stored inside the Nix store -(NIX-67). These do not affect most users. - -
diff --git a/doc/manual/release-notes/rl-0.10.xml b/doc/manual/release-notes/rl-0.10.xml deleted file mode 100644 index 9afec4de9..000000000 --- a/doc/manual/release-notes/rl-0.10.xml +++ /dev/null @@ -1,323 +0,0 @@ -
- -Release 0.10 (2006-10-06) - -This version of Nix uses Berkeley DB 4.4 instead of 4.3. -The database is upgraded automatically, but you should be careful not -to use old versions of Nix that still use Berkeley DB 4.3. In -particular, if you use a Nix installed through Nix, you should run - - -$ nix-store --clear-substitutes - -first. - -Also, the database schema has changed slighted to fix a -performance issue (see below). When you run any Nix 0.10 command for -the first time, the database will be upgraded automatically. This is -irreversible. - - - - - - - - nix-env usability improvements: - - - - An option - (or ) has been added to nix-env - --query to allow you to compare installed versions of - packages to available versions, or vice versa. An easy way to - see if you are up to date with what’s in your subscribed - channels is nix-env -qc \*. - - nix-env --query now takes as - arguments a list of package names about which to show - information, just like , etc.: for - example, nix-env -q gcc. Note that to show - all derivations, you need to specify - \*. - - nix-env -i - pkgname will now install - the highest available version of - pkgname, rather than installing all - available versions (which would probably give collisions) - (NIX-31). - - nix-env (-i|-u) --dry-run now - shows exactly which missing paths will be built or - substituted. - - nix-env -qa --description - shows human-readable descriptions of packages, provided that - they have a meta.description attribute (which - most packages in Nixpkgs don’t have yet). - - - - - - - New language features: - - - - Reference scanning (which happens after each - build) is much faster and takes a constant amount of - memory. - - String interpolation. Expressions like - - -"--with-freetype2-library=" + freetype + "/lib" - - can now be written as - - -"--with-freetype2-library=${freetype}/lib" - - You can write arbitrary expressions within - ${...}, not just - identifiers. - - Multi-line string literals. - - String concatenations can now involve - derivations, as in the example "--with-freetype2-library=" - + freetype + "/lib". This was not previously possible - because we need to register that a derivation that uses such a - string is dependent on freetype. The - evaluator now properly propagates this information. - Consequently, the subpath operator (~) has - been deprecated. - - Default values of function arguments can now - refer to other function arguments; that is, all arguments are in - scope in the default values - (NIX-45). - - - - Lots of new built-in primitives, such as - functions for list manipulation and integer arithmetic. See the - manual for a complete list. All primops are now available in - the set builtins, allowing one to test for - the availability of primop in a backwards-compatible - way. - - Real let-expressions: let x = ...; - ... z = ...; in .... - - - - - - - New commands nix-pack-closure and - nix-unpack-closure than can be used to easily - transfer a store path with all its dependencies to another machine. - Very convenient whenever you have some package on your machine and - you want to copy it somewhere else. - - - XML support: - - - - nix-env -q --xml prints the - installed or available packages in an XML representation for - easy processing by other tools. - - nix-instantiate --eval-only - --xml prints an XML representation of the resulting - term. (The new flag forces ‘deep’ - evaluation of the result, i.e., list elements and attributes are - evaluated recursively.) - - In Nix expressions, the primop - builtins.toXML converts a term to an XML - representation. This is primarily useful for passing structured - information to builders. - - - - - - - You can now unambiguously specify which derivation to - build or install in nix-env, - nix-instantiate and nix-build - using the / flags, which - takes an attribute name as argument. (Unlike symbolic package names - such as subversion-1.4.0, attribute names in an - attribute set are unique.) For instance, a quick way to perform a - test build of a package in Nixpkgs is nix-build - pkgs/top-level/all-packages.nix -A - foo. nix-env -q - --attr shows the attribute names corresponding to each - derivation. - - - If the top-level Nix expression used by - nix-env, nix-instantiate or - nix-build evaluates to a function whose arguments - all have default values, the function will be called automatically. - Also, the new command-line switch can be used to specify - function arguments on the command line. - - - nix-install-package --url - URL allows a package to be - installed directly from the given URL. - - - Nix now works behind an HTTP proxy server; just set - the standard environment variables http_proxy, - https_proxy, ftp_proxy or - all_proxy appropriately. Functions such as - fetchurl in Nixpkgs also respect these - variables. - - - nix-build -o - symlink allows the symlink to - the build result to be named something other than - result. - - - - - - Platform support: - - - - Support for 64-bit platforms, provided a suitably - patched ATerm library is used. Also, files larger than 2 - GiB are now supported. - - Added support for Cygwin (Windows, - i686-cygwin), Mac OS X on Intel - (i686-darwin) and Linux on PowerPC - (powerpc-linux). - - Users of SMP and multicore machines will - appreciate that the number of builds to be performed in parallel - can now be specified in the configuration file in the - build-max-jobs setting. - - - - - - - Garbage collector improvements: - - - - Open files (such as running programs) are now - used as roots of the garbage collector. This prevents programs - that have been uninstalled from being garbage collected while - they are still running. The script that detects these - additional runtime roots - (find-runtime-roots.pl) is inherently - system-specific, but it should work on Linux and on all - platforms that have the lsof - utility. - - nix-store --gc - (a.k.a. nix-collect-garbage) prints out the - number of bytes freed on standard output. nix-store - --gc --print-dead shows how many bytes would be freed - by an actual garbage collection. - - nix-collect-garbage -d - removes all old generations of all profiles - before calling the actual garbage collector (nix-store - --gc). This is an easy way to get rid of all old - packages in the Nix store. - - nix-store now has an - operation to delete specific paths - from the Nix store. It won’t delete reachable (non-garbage) - paths unless is - specified. - - - - - - - Berkeley DB 4.4’s process registry feature is used - to recover from crashed Nix processes. - - - - A performance issue has been fixed with the - referer table, which stores the inverse of the - references table (i.e., it tells you what store - paths refer to a given path). Maintaining this table could take a - quadratic amount of time, as well as a quadratic amount of Berkeley - DB log file space (in particular when running the garbage collector) - (NIX-23). - - Nix now catches the TERM and - HUP signals in addition to the - INT signal. So you can now do a killall - nix-store without triggering a database - recovery. - - bsdiff updated to version - 4.3. - - Substantial performance improvements in expression - evaluation and nix-env -qa, all thanks to Valgrind. Memory use has - been reduced by a factor 8 or so. Big speedup by memoisation of - path hashing. - - Lots of bug fixes, notably: - - - - Make sure that the garbage collector can run - successfully when the disk is full - (NIX-18). - - nix-env now locks the profile - to prevent races between concurrent nix-env - operations on the same profile - (NIX-7). - - Removed misleading messages from - nix-env -i (e.g., installing - `foo' followed by uninstalling - `foo') (NIX-17). - - - - - - Nix source distributions are a lot smaller now since - we no longer include a full copy of the Berkeley DB source - distribution (but only the bits we need). - - Header files are now installed so that external - programs can use the Nix libraries. - - - -
diff --git a/doc/manual/release-notes/rl-0.11.xml b/doc/manual/release-notes/rl-0.11.xml deleted file mode 100644 index 7ad0ab5b7..000000000 --- a/doc/manual/release-notes/rl-0.11.xml +++ /dev/null @@ -1,261 +0,0 @@ -
- -Release 0.11 (2007-12-31) - -Nix 0.11 has many improvements over the previous stable release. -The most important improvement is secure multi-user support. It also -features many usability enhancements and language extensions, many of -them prompted by NixOS, the purely functional Linux distribution based -on Nix. Here is an (incomplete) list: - - - - - - Secure multi-user support. A single Nix store can - now be shared between multiple (possible untrusted) users. This is - an important feature for NixOS, where it allows non-root users to - install software. The old setuid method for sharing a store between - multiple users has been removed. Details for setting up a - multi-user store can be found in the manual. - - - The new command nix-copy-closure - gives you an easy and efficient way to exchange software between - machines. It copies the missing parts of the closure of a set of - store path to or from a remote machine via - ssh. - - - A new kind of string literal: strings between double - single-quotes ('') have indentation - “intelligently” removed. This allows large strings (such as shell - scripts or configuration file fragments in NixOS) to cleanly follow - the indentation of the surrounding expression. It also requires - much less escaping, since '' is less common in - most languages than ". - - - nix-env - modifies the current generation of a profile so that it contains - exactly the specified derivation, and nothing else. For example, - nix-env -p /nix/var/nix/profiles/browser --set - firefox lets the profile named - browser contain just Firefox. - - - nix-env now maintains - meta-information about installed packages in profiles. The - meta-information is the contents of the meta - attribute of derivations, such as description or - homepage. The command nix-env -q --xml - --meta shows all meta-information. - - - nix-env now uses the - meta.priority attribute of derivations to resolve - filename collisions between packages. Lower priority values denote - a higher priority. For instance, the GCC wrapper package and the - Binutils package in Nixpkgs both have a file - bin/ld, so previously if you tried to install - both you would get a collision. Now, on the other hand, the GCC - wrapper declares a higher priority than Binutils, so the former’s - bin/ld is symlinked in the user - environment. - - - nix-env -i / -u: instead of - breaking package ties by version, break them by priority and version - number. That is, if there are multiple packages with the same name, - then pick the package with the highest priority, and only use the - version if there are multiple packages with the same - priority. - - This makes it possible to mark specific versions/variant in - Nixpkgs more or less desirable than others. A typical example would - be a beta version of some package (e.g., - gcc-4.2.0rc1) which should not be installed even - though it is the highest version, except when it is explicitly - selected (e.g., nix-env -i - gcc-4.2.0rc1). - - - nix-env --set-flag allows meta - attributes of installed packages to be modified. There are several - attributes that can be usefully modified, because they affect the - behaviour of nix-env or the user environment - build script: - - - - meta.priority can be changed - to resolve filename clashes (see above). - - meta.keep can be set to - true to prevent the package from being - upgraded or replaced. Useful if you want to hang on to an older - version of a package. - - meta.active can be set to - false to “disable” the package. That is, no - symlinks will be generated to the files of the package, but it - remains part of the profile (so it won’t be garbage-collected). - Set it back to true to re-enable the - package. - - - - - - - nix-env -q now has a flag - () that causes - nix-env to show only those derivations whose - output is already in the Nix store or that can be substituted (i.e., - downloaded from somewhere). In other words, it shows the packages - that can be installed “quickly”, i.e., don’t need to be built from - source. The flag is also available in - nix-env -i and nix-env -u to - filter out derivations for which no pre-built binary is - available. - - - The new option (in - nix-env, nix-instantiate and - nix-build) is like , except - that the value is a string. For example, --argstr system - i686-linux is equivalent to --arg system - \"i686-linux\" (note that - prevents annoying quoting around shell arguments). - - - nix-store has a new operation - () - paths that shows the build log of the given - paths. - - - - - - Nix now uses Berkeley DB 4.5. The database is - upgraded automatically, but you should be careful not to use old - versions of Nix that still use Berkeley DB 4.4. - - - - - - The option - (corresponding to the configuration setting - build-max-silent-time) allows you to set a - timeout on builds — if a build produces no output on - stdout or stderr for the given - number of seconds, it is terminated. This is useful for recovering - automatically from builds that are stuck in an infinite - loop. - - - nix-channel: each subscribed - channel is its own attribute in the top-level expression generated - for the channel. This allows disambiguation (e.g. nix-env - -i -A nixpkgs_unstable.firefox). - - - The substitutes table has been removed from the - database. This makes operations such as nix-pull - and nix-channel --update much, much - faster. - - - nix-pull now supports - bzip2-compressed manifests. This speeds up - channels. - - - nix-prefetch-url now has a - limited form of caching. This is used by - nix-channel to prevent unnecessary downloads when - the channel hasn’t changed. - - - nix-prefetch-url now by default - computes the SHA-256 hash of the file instead of the MD5 hash. In - calls to fetchurl you should pass the - sha256 attribute instead of - md5. You can pass either a hexadecimal or a - base-32 encoding of the hash. - - - Nix can now perform builds in an automatically - generated “chroot”. This prevents a builder from accessing stuff - outside of the Nix store, and thus helps ensure purity. This is an - experimental feature. - - - The new command nix-store - --optimise reduces Nix store disk space usage by finding - identical files in the store and hard-linking them to each other. - It typically reduces the size of the store by something like - 25-35%. - - - ~/.nix-defexpr can now be a - directory, in which case the Nix expressions in that directory are - combined into an attribute set, with the file names used as the - names of the attributes. The command nix-env - --import (which set the - ~/.nix-defexpr symlink) is - removed. - - - Derivations can specify the new special attribute - allowedReferences to enforce that the references - in the output of a derivation are a subset of a declared set of - paths. For example, if allowedReferences is an - empty list, then the output must not have any references. This is - used in NixOS to check that generated files such as initial ramdisks - for booting Linux don’t have any dependencies. - - - The new attribute - exportReferencesGraph allows builders access to - the references graph of their inputs. This is used in NixOS for - tasks such as generating ISO-9660 images that contain a Nix store - populated with the closure of certain paths. - - - Fixed-output derivations (like - fetchurl) can define the attribute - impureEnvVars to allow external environment - variables to be passed to builders. This is used in Nixpkgs to - support proxy configuration, among other things. - - - Several new built-in functions: - builtins.attrNames, - builtins.filterSource, - builtins.isAttrs, - builtins.isFunction, - builtins.listToAttrs, - builtins.stringLength, - builtins.sub, - builtins.substring, - throw, - builtins.trace, - builtins.readFile. - - - - -
diff --git a/doc/manual/release-notes/rl-0.12.xml b/doc/manual/release-notes/rl-0.12.xml deleted file mode 100644 index fdba8c4d5..000000000 --- a/doc/manual/release-notes/rl-0.12.xml +++ /dev/null @@ -1,175 +0,0 @@ -
- -Release 0.12 (2008-11-20) - - - - - Nix no longer uses Berkeley DB to store Nix store metadata. - The principal advantages of the new storage scheme are: it works - properly over decent implementations of NFS (allowing Nix stores - to be shared between multiple machines); no recovery is needed - when a Nix process crashes; no write access is needed for - read-only operations; no more running out of Berkeley DB locks on - certain operations. - - You still need to compile Nix with Berkeley DB support if - you want Nix to automatically convert your old Nix store to the - new schema. If you don’t need this, you can build Nix with the - configure option - . - - After the automatic conversion to the new schema, you can - delete the old Berkeley DB files: - - -$ cd /nix/var/nix/db -$ rm __db* log.* derivers references referrers reserved validpaths DB_CONFIG - - The new metadata is stored in the directories - /nix/var/nix/db/info and - /nix/var/nix/db/referrer. Though the - metadata is stored in human-readable plain-text files, they are - not intended to be human-editable, as Nix is rather strict about - the format. - - The new storage schema may or may not require less disk - space than the Berkeley DB environment, mostly depending on the - cluster size of your file system. With 1 KiB clusters (which - seems to be the ext3 default nowadays) it - usually takes up much less space. - - - There is a new substituter that copies paths - directly from other (remote) Nix stores mounted somewhere in the - filesystem. For instance, you can speed up an installation by - mounting some remote Nix store that already has the packages in - question via NFS or sshfs. The environment - variable NIX_OTHER_STORES specifies the locations of - the remote Nix directories, - e.g. /mnt/remote-fs/nix. - - New nix-store operations - and to dump - and reload the Nix database. - - The garbage collector has a number of new options to - allow only some of the garbage to be deleted. The option - tells the - collector to stop after at least N bytes - have been deleted. The option tells it to stop after the - link count on /nix/store has dropped below - N. This is useful for very large Nix - stores on filesystems with a 32000 subdirectories limit (like - ext3). The option - causes store paths to be deleted in order of ascending last access - time. This allows non-recently used stuff to be deleted. The - option - specifies an upper limit to the last accessed time of paths that may - be deleted. For instance, - - - $ nix-store --gc -v --max-atime $(date +%s -d "2 months ago") - - deletes everything that hasn’t been accessed in two months. - - nix-env now uses optimistic - profile locking when performing an operation like installing or - upgrading, instead of setting an exclusive lock on the profile. - This allows multiple nix-env -i / -u / -e - operations on the same profile in parallel. If a - nix-env operation sees at the end that the profile - was changed in the meantime by another process, it will just - restart. This is generally cheap because the build results are - still in the Nix store. - - The option is now - supported by nix-store -r and - nix-build. - - The information previously shown by - (i.e., which derivations will be built - and which paths will be substituted) is now always shown by - nix-env, nix-store -r and - nix-build. The total download size of - substitutable paths is now also shown. For instance, a build will - show something like - - -the following derivations will be built: - /nix/store/129sbxnk5n466zg6r1qmq1xjv9zymyy7-activate-configuration.sh.drv - /nix/store/7mzy971rdm8l566ch8hgxaf89x7lr7ik-upstart-jobs.drv - ... -the following paths will be downloaded/copied (30.02 MiB): - /nix/store/4m8pvgy2dcjgppf5b4cj5l6wyshjhalj-samba-3.2.4 - /nix/store/7h1kwcj29ip8vk26rhmx6bfjraxp0g4l-libunwind-0.98.6 - ... - - - - Language features: - - - - @-patterns as in Haskell. For instance, in a - function definition - - f = args @ {x, y, z}: ...; - - args refers to the argument as a whole, which - is further pattern-matched against the attribute set pattern - {x, y, z}. - - ...” (ellipsis) patterns. - An attribute set pattern can now say ... at - the end of the attribute name list to specify that the function - takes at least the listed attributes, while - ignoring additional attributes. For instance, - - {stdenv, fetchurl, fuse, ...}: ... - - defines a function that accepts any attribute set that includes - at least the three listed attributes. - - New primops: - builtins.parseDrvName (split a package name - string like "nix-0.12pre12876" into its name - and version components, e.g. "nix" and - "0.12pre12876"), - builtins.compareVersions (compare two version - strings using the same algorithm that nix-env - uses), builtins.length (efficiently compute - the length of a list), builtins.mul (integer - multiplication), builtins.div (integer - division). - - - - - - - - nix-prefetch-url now supports - mirror:// URLs, provided that the environment - variable NIXPKGS_ALL points at a Nixpkgs - tree. - - Removed the commands - nix-pack-closure and - nix-unpack-closure. You can do almost the same - thing but much more efficiently by doing nix-store --export - $(nix-store -qR paths) > closure and - nix-store --import < - closure. - - Lots of bug fixes, including a big performance bug in - the handling of with-expressions. - - - -
diff --git a/doc/manual/release-notes/rl-0.13.xml b/doc/manual/release-notes/rl-0.13.xml deleted file mode 100644 index cce2e4a26..000000000 --- a/doc/manual/release-notes/rl-0.13.xml +++ /dev/null @@ -1,106 +0,0 @@ -
- -Release 0.13 (2009-11-05) - -This is primarily a bug fix release. It has some new -features: - - - - - Syntactic sugar for writing nested attribute sets. Instead of - - -{ - foo = { - bar = 123; - xyzzy = true; - }; - a = { b = { c = "d"; }; }; -} - - - you can write - - -{ - foo.bar = 123; - foo.xyzzy = true; - a.b.c = "d"; -} - - - This is useful, for instance, in NixOS configuration files. - - - - - Support for Nix channels generated by Hydra, the Nix-based - continuous build system. (Hydra generates NAR archives on the - fly, so the size and hash of these archives isn’t known in - advance.) - - - - Support i686-linux builds directly on - x86_64-linux Nix installations. This is - implemented using the personality() syscall, - which causes uname to return - i686 in child processes. - - - - Various improvements to the chroot - support. Building in a chroot works quite well - now. - - - - Nix no longer blocks if it tries to build a path and another - process is already building the same path. Instead it tries to - build another buildable path first. This improves - parallelism. - - - - Support for large (> 4 GiB) files in NAR archives. - - - - Various (performance) improvements to the remote build - mechanism. - - - - New primops: builtins.addErrorContext (to - add a string to stack traces — useful for debugging), - builtins.isBool, - builtins.isString, - builtins.isInt, - builtins.intersectAttrs. - - - - OpenSolaris support (Sander van der Burg). - - - - Stack traces are no longer displayed unless the - option is used. - - - - The scoping rules for inherit - (e) ... in recursive - attribute sets have changed. The expression - e can now refer to the attributes - defined in the containing set. - - - - -
diff --git a/doc/manual/release-notes/rl-0.14.xml b/doc/manual/release-notes/rl-0.14.xml deleted file mode 100644 index e5fe9da78..000000000 --- a/doc/manual/release-notes/rl-0.14.xml +++ /dev/null @@ -1,46 +0,0 @@ -
- -Release 0.14 (2010-02-04) - -This release has the following improvements: - - - - - The garbage collector now starts deleting garbage much - faster than before. It no longer determines liveness of all paths - in the store, but does so on demand. - - - - Added a new operation, nix-store --query - --roots, that shows the garbage collector roots that - directly or indirectly point to the given store paths. - - - - Removed support for converting Berkeley DB-based Nix - databases to the new schema. - - - - Removed the and - garbage collector options. They were - not very useful in practice. - - - - On Windows, Nix now requires Cygwin 1.7.x. - - - - A few bug fixes. - - - - -
diff --git a/doc/manual/release-notes/rl-0.15.xml b/doc/manual/release-notes/rl-0.15.xml deleted file mode 100644 index 9f58a8efc..000000000 --- a/doc/manual/release-notes/rl-0.15.xml +++ /dev/null @@ -1,14 +0,0 @@ -
- -Release 0.15 (2010-03-17) - -This is a bug-fix release. Among other things, it fixes -building on Mac OS X (Snow Leopard), and improves the contents of -/etc/passwd and /etc/group -in chroot builds. - -
diff --git a/doc/manual/release-notes/rl-0.16.xml b/doc/manual/release-notes/rl-0.16.xml deleted file mode 100644 index af1edc0eb..000000000 --- a/doc/manual/release-notes/rl-0.16.xml +++ /dev/null @@ -1,55 +0,0 @@ -
- -Release 0.16 (2010-08-17) - -This release has the following improvements: - - - - - The Nix expression evaluator is now much faster in most - cases: typically, 3 - to 8 times compared to the old implementation. It also - uses less memory. It no longer depends on the ATerm - library. - - - - - Support for configurable parallelism inside builders. Build - scripts have always had the ability to perform multiple build - actions in parallel (for instance, by running make -j - 2), but this was not desirable because the number of - actions to be performed in parallel was not configurable. Nix - now has an option as well as a configuration - setting build-cores = - N that causes the - environment variable NIX_BUILD_CORES to be set to - N when the builder is invoked. The - builder can use this at its discretion to perform a parallel - build, e.g., by calling make -j - N. In Nixpkgs, this can be - enabled on a per-package basis by setting the derivation - attribute enableParallelBuilding to - true. - - - - - nix-store -q now supports XML output - through the flag. - - - - Several bug fixes. - - - - -
diff --git a/doc/manual/release-notes/rl-0.5.xml b/doc/manual/release-notes/rl-0.5.xml deleted file mode 100644 index e9f8bf270..000000000 --- a/doc/manual/release-notes/rl-0.5.xml +++ /dev/null @@ -1,11 +0,0 @@ -
- -Release 0.5 and earlier - -Please refer to the Subversion commit log messages. - -
diff --git a/doc/manual/release-notes/rl-0.6.xml b/doc/manual/release-notes/rl-0.6.xml deleted file mode 100644 index 6dc6521d3..000000000 --- a/doc/manual/release-notes/rl-0.6.xml +++ /dev/null @@ -1,122 +0,0 @@ -
- -Release 0.6 (2004-11-14) - - - - - Rewrite of the normalisation engine. - - - - Multiple builds can now be performed in parallel - (option ). - - Distributed builds. Nix can now call a shell - script to forward builds to Nix installations on remote - machines, which may or may not be of the same platform - type. - - Option allows - recovery from broken substitutes. - - Option causes - building of other (unaffected) derivations to continue if one - failed. - - - - - - - - Improvements to the garbage collector (i.e., it - should actually work now). - - Setuid Nix installations allow a Nix store to be - shared among multiple users. - - Substitute registration is much faster - now. - - A utility nix-build to build a - Nix expression and create a symlink to the result int the current - directory; useful for testing Nix derivations. - - Manual updates. - - - - nix-env changes: - - - - Derivations for other platforms are filtered out - (which can be overridden using - ). - - by default now - uninstall previous derivations with the same - name. - - allows upgrading to a - specific version. - - New operation - to remove profile - generations (necessary for effective garbage - collection). - - Nicer output (sorted, - columnised). - - - - - - - - More sensible verbosity levels all around (builder - output is now shown always, unless is - given). - - - - Nix expression language changes: - - - - New language construct: with - E1; - E2 brings all attributes - defined in the attribute set E1 in - scope in E2. - - Added a map - function. - - Various new operators (e.g., string - concatenation). - - - - - - - - Expression evaluation is much - faster. - - An Emacs mode for editing Nix expressions (with - syntax highlighting and indentation) has been - added. - - Many bug fixes. - - - -
diff --git a/doc/manual/release-notes/rl-0.7.xml b/doc/manual/release-notes/rl-0.7.xml deleted file mode 100644 index 6f95db436..000000000 --- a/doc/manual/release-notes/rl-0.7.xml +++ /dev/null @@ -1,35 +0,0 @@ -
- -Release 0.7 (2005-01-12) - - - - Binary patching. When upgrading components using - pre-built binaries (through nix-pull / nix-channel), Nix can - automatically download and apply binary patches to already installed - components instead of full downloads. Patching is “smart”: if there - is a sequence of patches to an installed - component, Nix will use it. Patches are currently generated - automatically between Nixpkgs (pre-)releases. - - Simplifications to the substitute - mechanism. - - Nix-pull now stores downloaded manifests in - /nix/var/nix/manifests. - - Metadata on files in the Nix store is canonicalised - after builds: the last-modified timestamp is set to 0 (00:00:00 - 1/1/1970), the mode is set to 0444 or 0555 (readable and possibly - executable by all; setuid/setgid bits are dropped), and the group is - set to the default. This ensures that the result of a build and an - installation through a substitute is the same; and that timestamp - dependencies are revealed. - - - -
diff --git a/doc/manual/release-notes/rl-0.8.1.xml b/doc/manual/release-notes/rl-0.8.1.xml deleted file mode 100644 index f7ffca0f8..000000000 --- a/doc/manual/release-notes/rl-0.8.1.xml +++ /dev/null @@ -1,21 +0,0 @@ -
- -Release 0.8.1 (2005-04-13) - -This is a bug fix release. - - - - Patch downloading was broken. - - The garbage collector would not delete paths that - had references from invalid (but substitutable) - paths. - - - -
diff --git a/doc/manual/release-notes/rl-0.8.xml b/doc/manual/release-notes/rl-0.8.xml deleted file mode 100644 index 825798fa9..000000000 --- a/doc/manual/release-notes/rl-0.8.xml +++ /dev/null @@ -1,246 +0,0 @@ -
- -Release 0.8 (2005-04-11) - -NOTE: the hashing scheme in Nix 0.8 changed (as detailed below). -As a result, nix-pull manifests and channels built -for Nix 0.7 and below will not work anymore. However, the Nix -expression language has not changed, so you can still build from -source. Also, existing user environments continue to work. Nix 0.8 -will automatically upgrade the database schema of previous -installations when it is first run. - -If you get the error message - - -you have an old-style manifest `/nix/var/nix/manifests/[...]'; please -delete it - -you should delete previously downloaded manifests: - - -$ rm /nix/var/nix/manifests/* - -If nix-channel gives the error message - - -manifest `http://catamaran.labs.cs.uu.nl/dist/nix/channels/[channel]/MANIFEST' -is too old (i.e., for Nix <= 0.7) - -then you should unsubscribe from the offending channel -(nix-channel --remove -URL; leave out -/MANIFEST), and subscribe to the same URL, with -channels replaced by channels-v3 -(e.g., ). - -Nix 0.8 has the following improvements: - - - - The cryptographic hashes used in store paths are now - 160 bits long, but encoded in base-32 so that they are still only 32 - characters long (e.g., - /nix/store/csw87wag8bqlqk7ipllbwypb14xainap-atk-1.9.0). - (This is actually a 160 bit truncation of a SHA-256 - hash.) - - Big cleanups and simplifications of the basic store - semantics. The notion of “closure store expressions” is gone (and - so is the notion of “successors”); the file system references of a - store path are now just stored in the database. - - For instance, given any store path, you can query its closure: - - -$ nix-store -qR $(which firefox) -... lots of paths ... - - Also, Nix now remembers for each store path the derivation that - built it (the “deriver”): - - -$ nix-store -qR $(which firefox) -/nix/store/4b0jx7vq80l9aqcnkszxhymsf1ffa5jd-firefox-1.0.1.drv - - So to see the build-time dependencies, you can do - - -$ nix-store -qR $(nix-store -qd $(which firefox)) - - or, in a nicer format: - - -$ nix-store -q --tree $(nix-store -qd $(which firefox)) - - - - File system references are also stored in reverse. For - instance, you can query all paths that directly or indirectly use a - certain Glibc: - - -$ nix-store -q --referrers-closure \ - /nix/store/8lz9yc6zgmc0vlqmn2ipcpkjlmbi51vv-glibc-2.3.4 - - - - - - The concept of fixed-output derivations has been - formalised. Previously, functions such as - fetchurl in Nixpkgs used a hack (namely, - explicitly specifying a store path hash) to prevent changes to, say, - the URL of the file from propagating upwards through the dependency - graph, causing rebuilds of everything. This can now be done cleanly - by specifying the outputHash and - outputHashAlgo attributes. Nix itself checks - that the content of the output has the specified hash. (This is - important for maintaining certain invariants necessary for future - work on secure shared stores.) - - One-click installation :-) It is now possible to - install any top-level component in Nixpkgs directly, through the web - — see, e.g., . - All you have to do is associate - /nix/bin/nix-install-package with the MIME type - application/nix-package (or the extension - .nixpkg), and clicking on a package link will - cause it to be installed, with all appropriate dependencies. If you - just want to install some specific application, this is easier than - subscribing to a channel. - - nix-store -r - PATHS now builds all the - derivations PATHS in parallel. Previously it did them sequentially - (though exploiting possible parallelism between subderivations). - This is nice for build farms. - - nix-channel has new operations - and - . - - New ways of installing components into user - environments: - - - - Copy from another user environment: - - -$ nix-env -i --from-profile .../other-profile firefox - - - - Install a store derivation directly (bypassing the - Nix expression language entirely): - - -$ nix-env -i /nix/store/z58v41v21xd3...-aterm-2.3.1.drv - - (This is used to implement nix-install-package, - which is therefore immune to evolution in the Nix expression - language.) - - Install an already built store path directly: - - -$ nix-env -i /nix/store/hsyj5pbn0d9i...-aterm-2.3.1 - - - - Install the result of a Nix expression specified - as a command-line argument: - - -$ nix-env -f .../i686-linux.nix -i -E 'x: x.firefoxWrapper' - - The difference with the normal installation mode is that - does not use the name - attributes of derivations. Therefore, this can be used to - disambiguate multiple derivations with the same - name. - - - - A hash of the contents of a store path is now stored - in the database after a successful build. This allows you to check - whether store paths have been tampered with: nix-store - --verify --check-contents. - - - - Implemented a concurrent garbage collector. It is now - always safe to run the garbage collector, even if other Nix - operations are happening simultaneously. - - However, there can still be GC races if you use - nix-instantiate and nix-store - --realise directly to build things. To prevent races, - use the flag of those commands. - - - - The garbage collector now finally deletes paths in - the right order (i.e., topologically sorted under the “references” - relation), thus making it safe to interrupt the collector without - risking a store that violates the closure - invariant. - - Likewise, the substitute mechanism now downloads - files in the right order, thus preserving the closure invariant at - all times. - - The result of nix-build is now - registered as a root of the garbage collector. If the - ./result link is deleted, the GC root - disappears automatically. - - - - The behaviour of the garbage collector can be changed - globally by setting options in - /nix/etc/nix/nix.conf. - - - - gc-keep-derivations specifies - whether deriver links should be followed when searching for live - paths. - - gc-keep-outputs specifies - whether outputs of derivations should be followed when searching - for live paths. - - env-keep-derivations - specifies whether user environments should store the paths of - derivations when they are added (thus keeping the derivations - alive). - - - - - - New nix-env query flags - and - . - - fetchurl allows SHA-1 and SHA-256 - in addition to MD5. Just specify the attribute - sha1 or sha256 instead of - md5. - - Manual updates. - - - - - -
diff --git a/doc/manual/release-notes/rl-0.9.1.xml b/doc/manual/release-notes/rl-0.9.1.xml deleted file mode 100644 index 85d11f416..000000000 --- a/doc/manual/release-notes/rl-0.9.1.xml +++ /dev/null @@ -1,13 +0,0 @@ -
- -Release 0.9.1 (2005-09-20) - -This bug fix release addresses a problem with the ATerm library -when the flag in -configure was not used. - -
diff --git a/doc/manual/release-notes/rl-0.9.2.xml b/doc/manual/release-notes/rl-0.9.2.xml deleted file mode 100644 index cb705e98a..000000000 --- a/doc/manual/release-notes/rl-0.9.2.xml +++ /dev/null @@ -1,28 +0,0 @@ -
- -Release 0.9.2 (2005-09-21) - -This bug fix release fixes two problems on Mac OS X: - - - - If Nix was linked against statically linked versions - of the ATerm or Berkeley DB library, there would be dynamic link - errors at runtime. - - nix-pull and - nix-push intermittently failed due to race - conditions involving pipes and child processes with error messages - such as open2: open(GLOB(0x180b2e4), >&=9) failed: Bad - file descriptor at /nix/bin/nix-pull line 77 (issue - NIX-14). - - - - - -
diff --git a/doc/manual/release-notes/rl-0.9.xml b/doc/manual/release-notes/rl-0.9.xml deleted file mode 100644 index fd1e633f7..000000000 --- a/doc/manual/release-notes/rl-0.9.xml +++ /dev/null @@ -1,98 +0,0 @@ -
- -Release 0.9 (2005-09-16) - -NOTE: this version of Nix uses Berkeley DB 4.3 instead of 4.2. -The database is upgraded automatically, but you should be careful not -to use old versions of Nix that still use Berkeley DB 4.2. In -particular, if you use a Nix installed through Nix, you should run - - -$ nix-store --clear-substitutes - -first. - - - - - Unpacking of patch sequences is much faster now - since we no longer do redundant unpacking and repacking of - intermediate paths. - - Nix now uses Berkeley DB 4.3. - - The derivation primitive is - lazier. Attributes of dependent derivations can mutually refer to - each other (as long as there are no data dependencies on the - outPath and drvPath attributes - computed by derivation). - - For example, the expression derivation - attrs now evaluates to (essentially) - - -attrs // { - type = "derivation"; - outPath = derivation! attrs; - drvPath = derivation! attrs; -} - - where derivation! is a primop that does the - actual derivation instantiation (i.e., it does what - derivation used to do). The advantage is that - it allows commands such as nix-env -qa and - nix-env -i to be much faster since they no longer - need to instantiate all derivations, just the - name attribute. - - Also, it allows derivations to cyclically reference each - other, for example, - - -webServer = derivation { - ... - hostName = "svn.cs.uu.nl"; - services = [svnService]; -}; - -svnService = derivation { - ... - hostName = webServer.hostName; -}; - - Previously, this would yield a black hole (infinite recursion). - - - - nix-build now defaults to using - ./default.nix if no Nix expression is - specified. - - nix-instantiate, when applied to - a Nix expression that evaluates to a function, will call the - function automatically if all its arguments have - defaults. - - Nix now uses libtool to build dynamic libraries. - This reduces the size of executables. - - A new list concatenation operator - ++. For example, [1 2 3] ++ [4 5 - 6] evaluates to [1 2 3 4 5 - 6]. - - Some currently undocumented primops to support - low-level build management using Nix (i.e., using Nix as a Make - replacement). See the commit messages for r3578 - and r3580. - - Various bug fixes and performance - improvements. - - - -
diff --git a/doc/manual/release-notes/rl-1.0.xml b/doc/manual/release-notes/rl-1.0.xml deleted file mode 100644 index ff11168d0..000000000 --- a/doc/manual/release-notes/rl-1.0.xml +++ /dev/null @@ -1,119 +0,0 @@ -
- -Release 1.0 (2012-05-11) - -There have been numerous improvements and bug fixes since the -previous release. Here are the most significant: - - - - - Nix can now optionally use the Boehm garbage collector. - This significantly reduces the Nix evaluator’s memory footprint, - especially when evaluating large NixOS system configurations. It - can be enabled using the configure - option. - - - - Nix now uses SQLite for its database. This is faster and - more flexible than the old ad hoc format. - SQLite is also used to cache the manifests in - /nix/var/nix/manifests, resulting in a - significant speedup. - - - - Nix now has an search path for expressions. The search path - is set using the environment variable NIX_PATH and - the command line option. In Nix expressions, - paths between angle brackets are used to specify files that must - be looked up in the search path. For instance, the expression - <nixpkgs/default.nix> looks for a file - nixpkgs/default.nix relative to every element - in the search path. - - - - The new command nix-build --run-env - builds all dependencies of a derivation, then starts a shell in an - environment containing all variables from the derivation. This is - useful for reproducing the environment of a derivation for - development. - - - - The new command nix-store --verify-path - verifies that the contents of a store path have not - changed. - - - - The new command nix-store --print-env - prints out the environment of a derivation in a format that can be - evaluated by a shell. - - - - Attribute names can now be arbitrary strings. For instance, - you can write { "foo-1.2" = …; "bla bla" = …; }."bla - bla". - - - - Attribute selection can now provide a default value using - the or operator. For instance, the expression - x.y.z or e evaluates to the attribute - x.y.z if it exists, and e - otherwise. - - - - The right-hand side of the ? operator can - now be an attribute path, e.g., attrs ? - a.b.c. - - - - On Linux, Nix will now make files in the Nix store immutable - on filesystems that support it. This prevents accidental - modification of files in the store by the root user. - - - - Nix has preliminary support for derivations with multiple - outputs. This is useful because it allows parts of a package to - be deployed and garbage-collected separately. For instance, - development parts of a package such as header files or static - libraries would typically not be part of the closure of an - application, resulting in reduced disk usage and installation - time. - - - - The Nix store garbage collector is faster and holds the - global lock for a shorter amount of time. - - - - The option (corresponding to the - configuration setting build-timeout) allows you - to set an absolute timeout on builds — if a build runs for more than - the given number of seconds, it is terminated. This is useful for - recovering automatically from builds that are stuck in an infinite - loop but keep producing output, and for which - --max-silent-time is ineffective. - - - - Nix development has moved to GitHub (). - - - - -
diff --git a/doc/manual/release-notes/rl-1.1.xml b/doc/manual/release-notes/rl-1.1.xml deleted file mode 100644 index 2f26e7a24..000000000 --- a/doc/manual/release-notes/rl-1.1.xml +++ /dev/null @@ -1,100 +0,0 @@ -
- -Release 1.1 (2012-07-18) - -This release has the following improvements: - - - - - On Linux, when doing a chroot build, Nix now uses various - namespace features provided by the Linux kernel to improve - build isolation. Namely: - - The private network namespace ensures that - builders cannot talk to the outside world (or vice versa): each - build only sees a private loopback interface. This also means - that two concurrent builds can listen on the same port (e.g. as - part of a test) without conflicting with each - other. - The PID namespace causes each build to start as - PID 1. Processes outside of the chroot are not visible to those - on the inside. On the other hand, processes inside the chroot - are visible from the outside (though with - different PIDs). - The IPC namespace prevents the builder from - communicating with outside processes using SysV IPC mechanisms - (shared memory, message queues, semaphores). It also ensures - that all IPC objects are destroyed when the builder - exits. - The UTS namespace ensures that builders see a - hostname of localhost rather than the actual - hostname. - The private mount namespace was already used by - Nix to ensure that the bind-mounts used to set up the chroot are - cleaned up automatically. - - - - - - Build logs are now compressed using - bzip2. The command nix-store - -l decompresses them on the fly. This can be disabled - by setting the option build-compress-log to - false. - - - - The creation of build logs in - /nix/var/log/nix/drvs can be disabled by - setting the new option build-keep-log to - false. This is useful, for instance, for Hydra - build machines. - - - - Nix now reserves some space in - /nix/var/nix/db/reserved to ensure that the - garbage collector can run successfully if the disk is full. This - is necessary because SQLite transactions fail if the disk is - full. - - - - Added a basic fetchurl function. This - is not intended to replace the fetchurl in - Nixpkgs, but is useful for bootstrapping; e.g., it will allow us - to get rid of the bootstrap binaries in the Nixpkgs source tree - and download them instead. You can use it by doing - import <nix/fetchurl.nix> { url = - url; sha256 = - "hash"; }. (Shea Levy) - - - - Improved RPM spec file. (Michel Alexandre Salim) - - - - Support for on-demand socket-based activation in the Nix - daemon with systemd. - - - - Added a manpage for - nix.conf5. - - - - When using the Nix daemon, the flag in - nix-env -qa is now much faster. - - - - -
diff --git a/doc/manual/release-notes/rl-1.10.xml b/doc/manual/release-notes/rl-1.10.xml deleted file mode 100644 index 689a95466..000000000 --- a/doc/manual/release-notes/rl-1.10.xml +++ /dev/null @@ -1,64 +0,0 @@ -
- -Release 1.10 (2015-09-03) - -This is primarily a bug fix release. It also has a number of new -features: - - - - - A number of builtin functions have been added to reduce - Nixpkgs/NixOS evaluation time and memory consumption: - all, - any, - concatStringsSep, - foldl’, - genList, - replaceStrings, - sort. - - - - - The garbage collector is more robust when the disk is full. - - - - Nix supports a new API for building derivations that doesn’t - require a .drv file to be present on disk; it - only requires an in-memory representation of the derivation. This - is used by the Hydra continuous build system to make remote builds - more efficient. - - - - The function <nix/fetchurl.nix> now - uses a builtin builder (i.e. it doesn’t - require starting an external process; the download is performed by - Nix itself). This ensures that derivation paths don’t change when - Nix is upgraded, and obviates the need for ugly hacks to support - chroot execution. - - - - now prints some configuration - information, in particular what compile-time optional features are - enabled, and the paths of various directories. - - - - Build users have their supplementary groups set correctly. - - - - -This release has contributions from Eelco Dolstra, Guillaume -Maudoux, Iwan Aucamp, Jaka Hudoklin, Kirill Elagin, Ludovic Courtès, -Manolis Ragkousis, Nicolas B. Pierron and Shea Levy. - -
diff --git a/doc/manual/release-notes/rl-1.11.10.xml b/doc/manual/release-notes/rl-1.11.10.xml deleted file mode 100644 index 415388b3e..000000000 --- a/doc/manual/release-notes/rl-1.11.10.xml +++ /dev/null @@ -1,31 +0,0 @@ -
- -Release 1.11.10 (2017-06-12) - -This release fixes a security bug in Nix’s “build user” build -isolation mechanism. Previously, Nix builders had the ability to -create setuid binaries owned by a nixbld -user. Such a binary could then be used by an attacker to assume a -nixbld identity and interfere with subsequent -builds running under the same UID. - -To prevent this issue, Nix now disallows builders to create -setuid and setgid binaries. On Linux, this is done using a seccomp BPF -filter. Note that this imposes a small performance penalty (e.g. 1% -when building GNU Hello). Using seccomp, we now also prevent the -creation of extended attributes and POSIX ACLs since these cannot be -represented in the NAR format and (in the case of POSIX ACLs) allow -bypassing regular Nix store permissions. On macOS, the restriction is -implemented using the existing sandbox mechanism, which now uses a -minimal “allow all except the creation of setuid/setgid binaries” -profile when regular sandboxing is disabled. On other platforms, the -“build user” mechanism is now disabled. - -Thanks go to Linus Heckemann for discovering and reporting this -bug. - -
diff --git a/doc/manual/release-notes/rl-1.11.xml b/doc/manual/release-notes/rl-1.11.xml deleted file mode 100644 index fe422dd1f..000000000 --- a/doc/manual/release-notes/rl-1.11.xml +++ /dev/null @@ -1,141 +0,0 @@ -
- -Release 1.11 (2016-01-19) - -This is primarily a bug fix release. It also has a number of new -features: - - - - - nix-prefetch-url can now download URLs - specified in a Nix expression. For example, - - -$ nix-prefetch-url -A hello.src - - - will prefetch the file specified by the - fetchurl call in the attribute - hello.src from the Nix expression in the - current directory, and print the cryptographic hash of the - resulting file on stdout. This differs from nix-build -A - hello.src in that it doesn't verify the hash, and is - thus useful when you’re updating a Nix expression. - - You can also prefetch the result of functions that unpack a - tarball, such as fetchFromGitHub. For example: - - -$ nix-prefetch-url --unpack https://github.com/NixOS/patchelf/archive/0.8.tar.gz - - - or from a Nix expression: - - -$ nix-prefetch-url -A nix-repl.src - - - - - - - - The builtin function - <nix/fetchurl.nix> now supports - downloading and unpacking NARs. This removes the need to have - multiple downloads in the Nixpkgs stdenv bootstrap process (like a - separate busybox binary for Linux, or curl/mkdir/sh/bzip2 for - Darwin). Now all those files can be combined into a single NAR, - optionally compressed using xz. - - - - Nix now supports SHA-512 hashes for verifying fixed-output - derivations, and in builtins.hashString. - - - - - The new flag will cause every build to - be executed N+1 times. If the build - output differs between any round, the build is rejected, and the - output paths are not registered as valid. This is primarily - useful to verify build determinism. (We already had a - option to repeat a previously succeeded - build. However, with , non-deterministic - builds are registered in the DB. Preventing that is useful for - Hydra to ensure that non-deterministic builds don't end up - getting published to the binary cache.) - - - - - - The options and , if they - detect a difference between two runs of the same derivation and - is given, will make the output of the other - run available under - store-path-check. This - makes it easier to investigate the non-determinism using tools - like diffoscope, e.g., - - -$ nix-build pkgs/stdenv/linux -A stage1.pkgs.zlib --check -K -error: derivation ‘/nix/store/l54i8wlw2265…-zlib-1.2.8.drv’ may not -be deterministic: output ‘/nix/store/11a27shh6n2i…-zlib-1.2.8’ -differs from ‘/nix/store/11a27shh6n2i…-zlib-1.2.8-check’ - -$ diffoscope /nix/store/11a27shh6n2i…-zlib-1.2.8 /nix/store/11a27shh6n2i…-zlib-1.2.8-check -… -├── lib/libz.a -│ ├── metadata -│ │ @@ -1,15 +1,15 @@ -│ │ -rw-r--r-- 30001/30000 3096 Jan 12 15:20 2016 adler32.o -… -│ │ +rw-r--r-- 30001/30000 3096 Jan 12 15:28 2016 adler32.o -… - - - - - - Improved FreeBSD support. - - - - nix-env -qa --xml --meta now prints - license information. - - - - The maximum number of parallel TCP connections that the - binary cache substituter will use has been decreased from 150 to - 25. This should prevent upsetting some broken NAT routers, and - also improves performance. - - - - All "chroot"-containing strings got renamed to "sandbox". - In particular, some Nix options got renamed, but the old names - are still accepted as lower-priority aliases. - - - - - -This release has contributions from Anders Claesson, Anthony -Cowley, Bjørn Forsman, Brian McKenna, Danny Wilson, davidak, Eelco Dolstra, -Fabian Schmitthenner, FrankHB, Ilya Novoselov, janus, Jim Garrison, John -Ericson, Jude Taylor, Ludovic Courtès, Manuel Jacob, Mathnerd314, -Pascal Wittmann, Peter Simons, Philip Potter, Preston Bennes, Rommel -M. Martinez, Sander van der Burg, Shea Levy, Tim Cuthbertson, Tuomas -Tynkkynen, Utku Demir and Vladimír Čunát. - -
diff --git a/doc/manual/release-notes/rl-1.2.xml b/doc/manual/release-notes/rl-1.2.xml deleted file mode 100644 index 748fd9e67..000000000 --- a/doc/manual/release-notes/rl-1.2.xml +++ /dev/null @@ -1,157 +0,0 @@ -
- -Release 1.2 (2012-12-06) - -This release has the following improvements and changes: - - - - - Nix has a new binary substituter mechanism: the - binary cache. A binary cache contains - pre-built binaries of Nix packages. Whenever Nix wants to build a - missing Nix store path, it will check a set of binary caches to - see if any of them has a pre-built binary of that path. The - configuration setting contains a - list of URLs of binary caches. For instance, doing - -$ nix-env -i thunderbird --option binary-caches http://cache.nixos.org - - will install Thunderbird and its dependencies, using the available - pre-built binaries in http://cache.nixos.org. - The main advantage over the old “manifest”-based method of getting - pre-built binaries is that you don’t have to worry about your - manifest being in sync with the Nix expressions you’re installing - from; i.e., you don’t need to run nix-pull to - update your manifest. It’s also more scalable because you don’t - need to redownload a giant manifest file every time. - - - A Nix channel can provide a binary cache URL that will be - used automatically if you subscribe to that channel. If you use - the Nixpkgs or NixOS channels - (http://nixos.org/channels) you automatically get the - cache http://cache.nixos.org. - - Binary caches are created using nix-push. - For details on the operation and format of binary caches, see the - nix-push manpage. More details are provided in - this - nix-dev posting. - - - - Multiple output support should now be usable. A derivation - can declare that it wants to produce multiple store paths by - saying something like - -outputs = [ "lib" "headers" "doc" ]; - - This will cause Nix to pass the intended store path of each output - to the builder through the environment variables - lib, headers and - doc. Other packages can refer to a specific - output by referring to - pkg.output, - e.g. - -buildInputs = [ pkg.lib pkg.headers ]; - - If you install a package with multiple outputs using - nix-env, each output path will be symlinked - into the user environment. - - - - Dashes are now valid as part of identifiers and attribute - names. - - - - The new operation nix-store --repair-path - allows corrupted or missing store paths to be repaired by - redownloading them. nix-store --verify --check-contents - --repair will scan and repair all paths in the Nix - store. Similarly, nix-env, - nix-build, nix-instantiate - and nix-store --realise have a - flag to detect and fix bad paths by - rebuilding or redownloading them. - - - - Nix no longer sets the immutable bit on files in the Nix - store. Instead, the recommended way to guard the Nix store - against accidental modification on Linux is to make it a read-only - bind mount, like this: - - -$ mount --bind /nix/store /nix/store -$ mount -o remount,ro,bind /nix/store - - - Nix will automatically make /nix/store - writable as needed (using a private mount namespace) to allow - modifications. - - - - Store optimisation (replacing identical files in the store - with hard links) can now be done automatically every time a path - is added to the store. This is enabled by setting the - configuration option auto-optimise-store to - true (disabled by default). - - - - Nix now supports xz compression for NARs - in addition to bzip2. It compresses about 30% - better on typical archives and decompresses about twice as - fast. - - - - Basic Nix expression evaluation profiling: setting the - environment variable NIX_COUNT_CALLS to - 1 will cause Nix to print how many times each - primop or function was executed. - - - - New primops: concatLists, - elem, elemAt and - filter. - - - - The command nix-copy-closure has a new - flag () to - download missing paths on the target machine using the substitute - mechanism. - - - - The command nix-worker has been renamed - to nix-daemon. Support for running the Nix - worker in “slave” mode has been removed. - - - - The flag of every Nix command now - invokes man. - - - - Chroot builds are now supported on systemd machines. - - - - -This release has contributions from Eelco Dolstra, Florian -Friesdorf, Mats Erik Andersson and Shea Levy. - -
diff --git a/doc/manual/release-notes/rl-1.3.xml b/doc/manual/release-notes/rl-1.3.xml deleted file mode 100644 index e2009ee3b..000000000 --- a/doc/manual/release-notes/rl-1.3.xml +++ /dev/null @@ -1,19 +0,0 @@ -
- -Release 1.3 (2013-01-04) - -This is primarily a bug fix release. When this version is first -run on Linux, it removes any immutable bits from the Nix store and -increases the schema version of the Nix store. (The previous release -removed support for setting the immutable bit; this release clears any -remaining immutable bits to make certain operations more -efficient.) - -This release has contributions from Eelco Dolstra and Stuart -Pernsteiner. - -
diff --git a/doc/manual/release-notes/rl-1.4.xml b/doc/manual/release-notes/rl-1.4.xml deleted file mode 100644 index aefb22f2b..000000000 --- a/doc/manual/release-notes/rl-1.4.xml +++ /dev/null @@ -1,39 +0,0 @@ -
- -Release 1.4 (2013-02-26) - -This release fixes a security bug in multi-user operation. It -was possible for derivations to cause the mode of files outside of the -Nix store to be changed to 444 (read-only but world-readable) by -creating hard links to those files (details). - -There are also the following improvements: - - - - New built-in function: - builtins.hashString. - - Build logs are now stored in - /nix/var/log/nix/drvs/XX/, - where XX is the first two characters of - the derivation. This is useful on machines that keep a lot of build - logs (such as Hydra servers). - - The function corepkgs/fetchurl - can now make the downloaded file executable. This will allow - getting rid of all bootstrap binaries in the Nixpkgs source - tree. - - Language change: The expression "${./path} - ..." now evaluates to a string instead of a - path. - - - -
diff --git a/doc/manual/release-notes/rl-1.5.1.xml b/doc/manual/release-notes/rl-1.5.1.xml deleted file mode 100644 index 035c8dbcb..000000000 --- a/doc/manual/release-notes/rl-1.5.1.xml +++ /dev/null @@ -1,12 +0,0 @@ -
- -Release 1.5.1 (2013-02-28) - -The bug fix to the bug fix had a bug itself, of course. But -this time it will work for sure! - -
diff --git a/doc/manual/release-notes/rl-1.5.2.xml b/doc/manual/release-notes/rl-1.5.2.xml deleted file mode 100644 index 7e81dd243..000000000 --- a/doc/manual/release-notes/rl-1.5.2.xml +++ /dev/null @@ -1,12 +0,0 @@ -
- -Release 1.5.2 (2013-05-13) - -This is primarily a bug fix release. It has contributions from -Eelco Dolstra, Lluís Batlle i Rossell and Shea Levy. - -
diff --git a/doc/manual/release-notes/rl-1.5.xml b/doc/manual/release-notes/rl-1.5.xml deleted file mode 100644 index 8e279d769..000000000 --- a/doc/manual/release-notes/rl-1.5.xml +++ /dev/null @@ -1,12 +0,0 @@ -
- -Release 1.5 (2013-02-27) - -This is a brown paper bag release to fix a regression introduced -by the hard link security fix in 1.4. - -
diff --git a/doc/manual/release-notes/rl-1.6.1.xml b/doc/manual/release-notes/rl-1.6.1.xml deleted file mode 100644 index 9ecc52734..000000000 --- a/doc/manual/release-notes/rl-1.6.1.xml +++ /dev/null @@ -1,69 +0,0 @@ -
- -Release 1.6.1 (2013-10-28) - -This is primarily a bug fix release. Changes of interest -are: - - - - - Nix 1.6 accidentally changed the semantics of antiquoted - paths in strings, such as "${/foo}/bar". This - release reverts to the Nix 1.5.3 behaviour. - - - - Previously, Nix optimised expressions such as - "${expr}" to - expr. Thus it neither checked whether - expr could be coerced to a string, nor - applied such coercions. This meant that - "${123}" evaluatued to 123, - and "${./foo}" evaluated to - ./foo (even though - "${./foo} " evaluates to - "/nix/store/hash-foo "). - Nix now checks the type of antiquoted expressions and - applies coercions. - - - - Nix now shows the exact position of undefined variables. In - particular, undefined variable errors in a with - previously didn't show any position - information, so this makes it a lot easier to fix such - errors. - - - - Undefined variables are now treated consistently. - Previously, the tryEval function would catch - undefined variables inside a with but not - outside. Now tryEval never catches undefined - variables. - - - - Bash completion in nix-shell now works - correctly. - - - - Stack traces are less verbose: they no longer show calls to - builtin functions and only show a single line for each derivation - on the call stack. - - - - New built-in function: builtins.typeOf, - which returns the type of its argument as a string. - - - - -
diff --git a/doc/manual/release-notes/rl-1.6.xml b/doc/manual/release-notes/rl-1.6.xml deleted file mode 100644 index 580563420..000000000 --- a/doc/manual/release-notes/rl-1.6.xml +++ /dev/null @@ -1,127 +0,0 @@ -
- -Release 1.6 (2013-09-10) - -In addition to the usual bug fixes, this release has several new -features: - - - - - The command nix-build --run-env has been - renamed to nix-shell. - - - - nix-shell now sources - $stdenv/setup inside the - interactive shell, rather than in a parent shell. This ensures - that shell functions defined by stdenv can be - used in the interactive shell. - - - - nix-shell has a new flag - to clear the environment, so you get an - environment that more closely corresponds to the “real” Nix build. - - - - - nix-shell now sets the shell prompt - (PS1) to ensure that Nix shells are distinguishable - from your regular shells. - - - - nix-env no longer requires a - * argument to match all packages, so - nix-env -qa is equivalent to nix-env - -qa '*'. - - - - nix-env -i has a new flag - () to remove all - previous packages from the profile. This makes it easier to do - declarative package management similar to NixOS’s - . For instance, if you - have a specification my-packages.nix like this: - - -with import <nixpkgs> {}; -[ thunderbird - geeqie - ... -] - - - then after any change to this file, you can run: - - -$ nix-env -f my-packages.nix -ir - - - to update your profile to match the specification. - - - - The ‘with’ language construct is now more - lazy. It only evaluates its argument if a variable might actually - refer to an attribute in the argument. For instance, this now - works: - - -let - pkgs = with pkgs; { foo = "old"; bar = foo; } // overrides; - overrides = { foo = "new"; }; -in pkgs.bar - - - This evaluates to "new", while previously it - gave an “infinite recursion” error. - - - - Nix now has proper integer arithmetic operators. For - instance, you can write x + y instead of - builtins.add x y, or x < - y instead of builtins.lessThan x y. - The comparison operators also work on strings. - - - - On 64-bit systems, Nix integers are now 64 bits rather than - 32 bits. - - - - When using the Nix daemon, the nix-daemon - worker process now runs on the same CPU as the client, on systems - that support setting CPU affinity. This gives a significant speedup - on some systems. - - - - If a stack overflow occurs in the Nix evaluator, you now get - a proper error message (rather than “Segmentation fault”) on some - systems. - - - - In addition to directories, you can now bind-mount regular - files in chroots through the (now misnamed) option - . - - - - -This release has contributions from Domen Kožar, Eelco Dolstra, -Florian Friesdorf, Gergely Risko, Ivan Kozik, Ludovic Courtès and Shea -Levy. - -
diff --git a/doc/manual/release-notes/rl-1.7.xml b/doc/manual/release-notes/rl-1.7.xml deleted file mode 100644 index 44ecaa78d..000000000 --- a/doc/manual/release-notes/rl-1.7.xml +++ /dev/null @@ -1,263 +0,0 @@ -
- -Release 1.7 (2014-04-11) - -In addition to the usual bug fixes, this release has the -following new features: - - - - - Antiquotation is now allowed inside of quoted attribute - names (e.g. set."${foo}"). In the case where - the attribute name is just a single antiquotation, the quotes can - be dropped (e.g. the above example can be written - set.${foo}). If an attribute name inside of a - set declaration evaluates to null (e.g. - { ${null} = false; }), then that attribute is - not added to the set. - - - - Experimental support for cryptographically signed binary - caches. See the - commit for details. - - - - An experimental new substituter, - download-via-ssh, that fetches binaries from - remote machines via SSH. Specifying the flags --option - use-ssh-substituter true --option ssh-substituter-hosts - user@hostname will cause Nix - to download binaries from the specified machine, if it has - them. - - - - nix-store -r and - nix-build have a new flag, - , that builds a previously built - derivation again, and prints an error message if the output is not - exactly the same. This helps to verify whether a derivation is - truly deterministic. For example: - - -$ nix-build '<nixpkgs>' -A patchelf - -$ nix-build '<nixpkgs>' -A patchelf --check - -error: derivation `/nix/store/1ipvxs…-patchelf-0.6' may not be deterministic: - hash mismatch in output `/nix/store/4pc1dm…-patchelf-0.6.drv' - - - - - - - - The nix-instantiate flags - and - have been renamed to and - , respectively. - - - - nix-instantiate, - nix-build and nix-shell now - have a flag (or ) that - allows you to specify the expression to be evaluated as a command - line argument. For instance, nix-instantiate --eval -E - '1 + 2' will print 3. - - - - nix-shell improvements: - - - - - It has a new flag, (or - ), that sets up a build environment - containing the specified packages from Nixpkgs. For example, - the command - - -$ nix-shell -p sqlite xorg.libX11 hello - - - will start a shell in which the given packages are - present. - - - - It now uses shell.nix as the - default expression, falling back to - default.nix if the former doesn’t - exist. This makes it convenient to have a - shell.nix in your project to set up a - nice development environment. - - - - It evaluates the derivation attribute - shellHook, if set. Since - stdenv does not normally execute this hook, - it allows you to do nix-shell-specific - setup. - - - - It preserves the user’s timezone setting. - - - - - - - - In chroots, Nix now sets up a /dev - containing only a minimal set of devices (such as - /dev/null). Note that it only does this if - you don’t have /dev - listed in your setting; - otherwise, it will bind-mount the /dev from - outside the chroot. - - Similarly, if you don’t have /dev/pts listed - in , Nix will mount a private - devpts filesystem on the chroot’s - /dev/pts. - - - - - New built-in function: builtins.toJSON, - which returns a JSON representation of a value. - - - - nix-env -q has a new flag - to print a JSON representation of the - installed or available packages. - - - - nix-env now supports meta attributes with - more complex values, such as attribute sets. - - - - The flag now allows attribute names with - dots in them, e.g. - - -$ nix-instantiate --eval '<nixos>' -A 'config.systemd.units."nscd.service".text' - - - - - - - The option to - nix-store --gc now accepts a unit - specifier. For example, nix-store --gc --max-freed - 1G will free up to 1 gigabyte of disk space. - - - - nix-collect-garbage has a new flag - - Nd, which deletes - all user environment generations older than - N days. Likewise, nix-env - --delete-generations accepts a - Nd age limit. - - - - Nix now heuristically detects whether a build failure was - due to a disk-full condition. In that case, the build is not - flagged as “permanently failed”. This is mostly useful for Hydra, - which needs to distinguish between permanent and transient build - failures. - - - - There is a new symbol __curPos that - expands to an attribute set containing its file name and line and - column numbers, e.g. { file = "foo.nix"; line = 10; - column = 5; }. There also is a new builtin function, - unsafeGetAttrPos, that returns the position of - an attribute. This is used by Nixpkgs to provide location - information in error messages, e.g. - - -$ nix-build '<nixpkgs>' -A libreoffice --argstr system x86_64-darwin -error: the package ‘libreoffice-4.0.5.2’ in ‘.../applications/office/libreoffice/default.nix:263’ - is not supported on ‘x86_64-darwin’ - - - - - - - The garbage collector is now more concurrent with other Nix - processes because it releases certain locks earlier. - - - - The binary tarball installer has been improved. You can now - install Nix by running: - - -$ bash <(curl https://nixos.org/nix/install) - - - - - - - More evaluation errors include position information. For - instance, selecting a missing attribute will print something like - - -error: attribute `nixUnstabl' missing, at /etc/nixos/configurations/misc/eelco/mandark.nix:216:15 - - - - - - - The command nix-setuid-helper is - gone. - - - - Nix no longer uses Automake, but instead has a - non-recursive, GNU Make-based build system. - - - - All installed libraries now have the prefix - libnix. In particular, this gets rid of - libutil, which could clash with libraries with - the same name from other packages. - - - - Nix now requires a compiler that supports C++11. - - - - -This release has contributions from Danny Wilson, Domen Kožar, -Eelco Dolstra, Ian-Woo Kim, Ludovic Courtès, Maxim Ivanov, Petr -Rockai, Ricardo M. Correia and Shea Levy. - -
diff --git a/doc/manual/release-notes/rl-1.8.xml b/doc/manual/release-notes/rl-1.8.xml deleted file mode 100644 index c854c5c5f..000000000 --- a/doc/manual/release-notes/rl-1.8.xml +++ /dev/null @@ -1,123 +0,0 @@ -
- -Release 1.8 (2014-12-14) - - - - Breaking change: to address a race condition, the - remote build hook mechanism now uses nix-store - --serve on the remote machine. This requires build slaves - to be updated to Nix 1.8. - - Nix now uses HTTPS instead of HTTP to access the - default binary cache, - cache.nixos.org. - - nix-env selectors are now regular - expressions. For instance, you can do - - -$ nix-env -qa '.*zip.*' - - - to query all packages with a name containing - zip. - - nix-store --read-log can now - fetch remote build logs. If a build log is not available locally, - then ‘nix-store -l’ will now try to download it from the servers - listed in the ‘log-servers’ option in nix.conf. For instance, if you - have the configuration option - - -log-servers = http://hydra.nixos.org/log - - -then it will try to get logs from -http://hydra.nixos.org/log/base name of the -store path. This allows you to do things like: - - -$ nix-store -l $(which xterm) - - - and get a log even if xterm wasn't built - locally. - - New builtin functions: - attrValues, deepSeq, - fromJSON, readDir, - seq. - - nix-instantiate --eval now has a - flag to print the resulting value in JSON - format. - - nix-copy-closure now uses - nix-store --serve on the remote side to send or - receive closures. This fixes a race condition between - nix-copy-closure and the garbage - collector. - - Derivations can specify the new special attribute - allowedRequisites, which has a similar meaning to - allowedReferences. But instead of only enforcing - to explicitly specify the immediate references, it requires the - derivation to specify all the dependencies recursively (hence the - name, requisites) that are used by the resulting - output. - - On Mac OS X, Nix now handles case collisions when - importing closures from case-sensitive file systems. This is mostly - useful for running NixOps on Mac OS X. - - The Nix daemon has new configuration options - (specifying the users and groups that - are allowed to connect to the daemon) and - (specifying the users and groups that - can perform privileged operations like specifying untrusted binary - caches). - - The configuration option - now defaults to the number of available - CPU cores. - - Build users are now used by default when Nix is - invoked as root. This prevents builds from accidentally running as - root. - - Nix now includes systemd units and Upstart - jobs. - - Speed improvements to nix-store - --optimise. - - Language change: the == operator - now ignores string contexts (the “dependencies” of a - string). - - Nix now filters out Nix-specific ANSI escape - sequences on standard error. They are supposed to be invisible, but - some terminals show them anyway. - - Various commands now automatically pipe their output - into the pager as specified by the PAGER environment - variable. - - Several improvements to reduce memory consumption in - the evaluator. - - - -This release has contributions from Adam Szkoda, Aristid -Breitkreuz, Bob van der Linden, Charles Strahan, darealshinji, Eelco -Dolstra, Gergely Risko, Joel Taylor, Ludovic Courtès, Marko Durkovic, -Mikey Ariel, Paul Colomiets, Ricardo M. Correia, Ricky Elrod, Robert -Helgesson, Rob Vermaas, Russell O'Connor, Shea Levy, Shell Turner, -Sönke Hahn, Steve Purcell, Vladimír Čunát and Wout Mertens. - -
diff --git a/doc/manual/release-notes/rl-1.9.xml b/doc/manual/release-notes/rl-1.9.xml deleted file mode 100644 index c8406bd20..000000000 --- a/doc/manual/release-notes/rl-1.9.xml +++ /dev/null @@ -1,216 +0,0 @@ -
- -Release 1.9 (2015-06-12) - -In addition to the usual bug fixes, this release has the -following new features: - - - - - Signed binary cache support. You can enable signature - checking by adding the following to nix.conf: - - -signed-binary-caches = * -binary-cache-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= - - - This will prevent Nix from downloading any binary from the cache - that is not signed by one of the keys listed in - . - - Signature checking is only supported if you built Nix with - the libsodium package. - - Note that while Nix has had experimental support for signed - binary caches since version 1.7, this release changes the - signature format in a backwards-incompatible way. - - - - - - Automatic downloading of Nix expression tarballs. In various - places, you can now specify the URL of a tarball containing Nix - expressions (such as Nixpkgs), which will be downloaded and - unpacked automatically. For example: - - - - In nix-env: - - -$ nix-env -f https://github.com/NixOS/nixpkgs-channels/archive/nixos-14.12.tar.gz -iA firefox - - - This installs Firefox from the latest tested and built revision - of the NixOS 14.12 channel. - - In nix-build and - nix-shell: - - -$ nix-build https://github.com/NixOS/nixpkgs/archive/master.tar.gz -A hello - - - This builds GNU Hello from the latest revision of the Nixpkgs - master branch. - - In the Nix search path (as specified via - NIX_PATH or ). For example, to - start a shell containing the Pan package from a specific version - of Nixpkgs: - - -$ nix-shell -p pan -I nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/8a3eea054838b55aca962c3fbde9c83c102b8bf2.tar.gz - - - - - In nixos-rebuild (on NixOS): - - -$ nixos-rebuild test -I nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/nixos-unstable.tar.gz - - - - - In Nix expressions, via the new builtin function fetchTarball: - - -with import (fetchTarball https://github.com/NixOS/nixpkgs-channels/archive/nixos-14.12.tar.gz) {}; … - - - (This is not allowed in restricted mode.) - - - - - - - - nix-shell improvements: - - - - nix-shell now has a flag - to execute a command in the - nix-shell environment, - e.g. nix-shell --run make. This is like - the existing flag, except that it - uses a non-interactive shell (ensuring that hitting Ctrl-C won’t - drop you into the child shell). - - nix-shell can now be used as - a #!-interpreter. This allows you to write - scripts that dynamically fetch their own dependencies. For - example, here is a Haskell script that, when invoked, first - downloads GHC and the Haskell packages on which it depends: - - -#! /usr/bin/env nix-shell -#! nix-shell -i runghc -p haskellPackages.ghc haskellPackages.HTTP - -import Network.HTTP - -main = do - resp <- Network.HTTP.simpleHTTP (getRequest "http://nixos.org/") - body <- getResponseBody resp - print (take 100 body) - - - Of course, the dependencies are cached in the Nix store, so the - second invocation of this script will be much - faster. - - - - - - - - Chroot improvements: - - - - Chroot builds are now supported on Mac OS X - (using its sandbox mechanism). - - If chroots are enabled, they are now used for - all derivations, including fixed-output derivations (such as - fetchurl). The latter do have network - access, but can no longer access the host filesystem. If you - need the old behaviour, you can set the option - to - relaxed. - - On Linux, if chroots are enabled, builds are - performed in a private PID namespace once again. (This - functionality was lost in Nix 1.8.) - - Store paths listed in - are now automatically - expanded to their closure. For instance, if you want - /nix/store/…-bash/bin/sh mounted in your - chroot as /bin/sh, you only need to say - build-chroot-dirs = - /bin/sh=/nix/store/…-bash/bin/sh; it is no longer - necessary to specify the dependencies of Bash. - - - - - - The new derivation attribute - passAsFile allows you to specify that the - contents of derivation attributes should be passed via files rather - than environment variables. This is useful if you need to pass very - long strings that exceed the size limit of the environment. The - Nixpkgs function writeTextFile uses - this. - - You can now use ~ in Nix file - names to refer to your home directory, e.g. import - ~/.nixpkgs/config.nix. - - Nix has a new option - that allows limiting what paths the Nix evaluator has access to. By - passing --option restrict-eval true to Nix, the - evaluator will throw an exception if an attempt is made to access - any file outside of the Nix search path. This is primarily intended - for Hydra to ensure that a Hydra jobset only refers to its declared - inputs (and is therefore reproducible). - - nix-env now only creates a new - “generation” symlink in /nix/var/nix/profiles - if something actually changed. - - The environment variable NIX_PAGER - can now be set to override PAGER. You can set it to - cat to disable paging for Nix commands - only. - - Failing <...> - lookups now show position information. - - Improved Boehm GC use: we disabled scanning for - interior pointers, which should reduce the “Repeated - allocation of very large block” warnings and associated - retention of memory. - - - -This release has contributions from aszlig, Benjamin Staffin, -Charles Strahan, Christian Theune, Daniel Hahler, Danylo Hlynskyi -Daniel Peebles, Dan Peebles, Domen Kožar, Eelco Dolstra, Harald van -Dijk, Hoang Xuan Phu, Jaka Hudoklin, Jeff Ramnani, j-keck, Linquize, -Luca Bruno, Michael Merickel, Oliver Dunkl, Rob Vermaas, Rok Garbas, -Shea Levy, Tobias Geerinckx-Rice and William A. Kennington III. - -
- diff --git a/doc/manual/release-notes/rl-2.0.xml b/doc/manual/release-notes/rl-2.0.xml deleted file mode 100644 index 4c683dd3d..000000000 --- a/doc/manual/release-notes/rl-2.0.xml +++ /dev/null @@ -1,1012 +0,0 @@ -
- -Release 2.0 (2018-02-22) - -The following incompatible changes have been made: - - - - - The manifest-based substituter mechanism - (download-using-manifests) has been removed. It - has been superseded by the binary cache substituter mechanism - since several years. As a result, the following programs have been - removed: - - - nix-pull - nix-generate-patches - bsdiff - bspatch - - - - - - The “copy from other stores” substituter mechanism - (copy-from-other-stores and the - NIX_OTHER_STORES environment variable) has been - removed. It was primarily used by the NixOS installer to copy - available paths from the installation medium. The replacement is - to use a chroot store as a substituter - (e.g. --substituters /mnt), or to build into a - chroot store (e.g. --store /mnt --substituters /). - - - - The command nix-push has been removed as - part of the effort to eliminate Nix's dependency on Perl. You can - use nix copy instead, e.g. nix copy - --to file:///tmp/my-binary-cache paths… - - - - The “nested” log output feature () has been removed. As a result, - nix-log2xml was also removed. - - - - OpenSSL-based signing has been removed. This - feature was never well-supported. A better alternative is provided - by the and - options. - - - - Failed build caching has been removed. This - feature was introduced to support the Hydra continuous build - system, but Hydra no longer uses it. - - - - nix-mode.el has been removed from - Nix. It is now a separate - repository and can be installed through the MELPA package - repository. - - - - -This release has the following new features: - - - - - It introduces a new command named nix, - which is intended to eventually replace all - nix-* commands with a more consistent and - better designed user interface. It currently provides replacements - for some (but not all) of the functionality provided by - nix-store, nix-build, - nix-shell -p, nix-env -qa, - nix-instantiate --eval, - nix-push and - nix-copy-closure. It has the following major - features: - - - - - Unlike the legacy commands, it has a consistent way to - refer to packages and package-like arguments (like store - paths). For example, the following commands all copy the GNU - Hello package to a remote machine: - - nix copy --to ssh://machine nixpkgs.hello - nix copy --to ssh://machine /nix/store/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9-hello-2.10 - nix copy --to ssh://machine '(with import <nixpkgs> {}; hello)' - - By contrast, nix-copy-closure only accepted - store paths as arguments. - - - - It is self-documenting: shows - all available command-line arguments. If - is given after a subcommand, it shows - examples for that subcommand. nix - --help-config shows all configuration - options. - - - - It is much less verbose. By default, it displays a - single-line progress indicator that shows how many packages - are left to be built or downloaded, and (if there are running - builds) the most recent line of builder output. If a build - fails, it shows the last few lines of builder output. The full - build log can be retrieved using nix - log. - - - - It provides - all nix.conf configuration options as - command line flags. For example, instead of --option - http-connections 100 you can write - --http-connections 100. Boolean options can - be written as - --foo or - --no-foo - (e.g. ). - - - - Many subcommands have a flag to - write results to stdout in JSON format. - - - - - Please note that the nix command - is a work in progress and the interface is subject to - change. - - It provides the following high-level (“porcelain”) - subcommands: - - - - - nix build is a replacement for - nix-build. - - - - nix run executes a command in an - environment in which the specified packages are available. It - is (roughly) a replacement for nix-shell - -p. Unlike that command, it does not execute the - command in a shell, and has a flag (-c) - that specifies the unquoted command line to be - executed. - - It is particularly useful in conjunction with chroot - stores, allowing Linux users who do not have permission to - install Nix in /nix/store to still use - binary substitutes that assume - /nix/store. For example, - - nix run --store ~/my-nix nixpkgs.hello -c hello --greeting 'Hi everybody!' - - downloads (or if not substitutes are available, builds) the - GNU Hello package into - ~/my-nix/nix/store, then runs - hello in a mount namespace where - ~/my-nix/nix/store is mounted onto - /nix/store. - - - - nix search replaces nix-env - -qa. It searches the available packages for - occurrences of a search string in the attribute name, package - name or description. Unlike nix-env -qa, it - has a cache to speed up subsequent searches. - - - - nix copy copies paths between - arbitrary Nix stores, generalising - nix-copy-closure and - nix-push. - - - - nix repl replaces the external - program nix-repl. It provides an - interactive environment for evaluating and building Nix - expressions. Note that it uses linenoise-ng - instead of GNU Readline. - - - - nix upgrade-nix upgrades Nix to the - latest stable version. This requires that Nix is installed in - a profile. (Thus it won’t work on NixOS, or if it’s installed - outside of the Nix store.) - - - - nix verify checks whether store paths - are unmodified and/or “trusted” (see below). It replaces - nix-store --verify and nix-store - --verify-path. - - - - nix log shows the build log of a - package or path. If the build log is not available locally, it - will try to obtain it from the configured substituters (such - as cache.nixos.org, which now provides build - logs). - - - - nix edit opens the source code of a - package in your editor. - - - - nix eval replaces - nix-instantiate --eval. - - - - nix - why-depends shows why one store path has another in - its closure. This is primarily useful to finding the causes of - closure bloat. For example, - - nix why-depends nixpkgs.vlc nixpkgs.libdrm.dev - - shows a chain of files and fragments of file contents that - cause the VLC package to have the “dev” output of - libdrm in its closure — an undesirable - situation. - - - - nix path-info shows information about - store paths, replacing nix-store -q. A - useful feature is the option - (). For example, the following command show - the closure sizes of every path in the current NixOS system - closure, sorted by size: - - nix path-info -rS /run/current-system | sort -nk2 - - - - - - nix optimise-store replaces - nix-store --optimise. The main difference - is that it has a progress indicator. - - - - - A number of low-level (“plumbing”) commands are also - available: - - - - - nix ls-store and nix - ls-nar list the contents of a store path or NAR - file. The former is primarily useful in conjunction with - remote stores, e.g. - - nix ls-store --store https://cache.nixos.org/ -lR /nix/store/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9-hello-2.10 - - lists the contents of path in a binary cache. - - - - nix cat-store and nix - cat-nar allow extracting a file from a store path or - NAR file. - - - - nix dump-path writes the contents of - a store path to stdout in NAR format. This replaces - nix-store --dump. - - - - nix - show-derivation displays a store derivation in JSON - format. This is an alternative to - pp-aterm. - - - - nix - add-to-store replaces nix-store - --add. - - - - nix sign-paths signs store - paths. - - - - nix copy-sigs copies signatures from - one store to another. - - - - nix show-config shows all - configuration options and their current values. - - - - - - - - The store abstraction that Nix has had for a long time to - support store access via the Nix daemon has been extended - significantly. In particular, substituters (which used to be - external programs such as - download-from-binary-cache) are now subclasses - of the abstract Store class. This allows - many Nix commands to operate on such store types. For example, - nix path-info shows information about paths in - your local Nix store, while nix path-info --store - https://cache.nixos.org/ shows information about paths - in the specified binary cache. Similarly, - nix-copy-closure, nix-push - and substitution are all instances of the general notion of - copying paths between different kinds of Nix stores. - - Stores are specified using an URI-like syntax, - e.g. https://cache.nixos.org/ or - ssh://machine. The following store types are supported: - - - - - - LocalStore (stori URI - local or an absolute path) and the misnamed - RemoteStore (daemon) - provide access to a local Nix store, the latter via the Nix - daemon. You can use auto or the empty - string to auto-select a local or daemon store depending on - whether you have write permission to the Nix store. It is no - longer necessary to set the NIX_REMOTE - environment variable to use the Nix daemon. - - As noted above, LocalStore now - supports chroot builds, allowing the “physical” location of - the Nix store - (e.g. /home/alice/nix/store) to differ - from its “logical” location (typically - /nix/store). This allows non-root users - to use Nix while still getting the benefits from prebuilt - binaries from cache.nixos.org. - - - - - - BinaryCacheStore is the abstract - superclass of all binary cache stores. It supports writing - build logs and NAR content listings in JSON format. - - - - - - HttpBinaryCacheStore - (http://, https://) - supports binary caches via HTTP or HTTPS. If the server - supports PUT requests, it supports - uploading store paths via commands such as nix - copy. - - - - - - LocalBinaryCacheStore - (file://) supports binary caches in the - local filesystem. - - - - - - S3BinaryCacheStore - (s3://) supports binary caches stored in - Amazon S3, if enabled at compile time. - - - - - - LegacySSHStore (ssh://) - is used to implement remote builds and - nix-copy-closure. - - - - - - SSHStore - (ssh-ng://) supports arbitrary Nix - operations on a remote machine via the same protocol used by - nix-daemon. - - - - - - - - - - - - Security has been improved in various ways: - - - - - Nix now stores signatures for local store - paths. When paths are copied between stores (e.g., copied from - a binary cache to a local store), signatures are - propagated. - - Locally-built paths are signed automatically using the - secret keys specified by the - store option. Secret/public key pairs can be generated using - nix-store - --generate-binary-cache-key. - - In addition, locally-built store paths are marked as - “ultimately trusted”, but this bit is not propagated when - paths are copied between stores. - - - - Content-addressable store paths no longer require - signatures — they can be imported into a store by unprivileged - users even if they lack signatures. - - - - The command nix verify checks whether - the specified paths are trusted, i.e., have a certain number - of trusted signatures, are ultimately trusted, or are - content-addressed. - - - - Substitutions from binary caches now - require signatures by default. This was already the case on - NixOS. - - - - In Linux sandbox builds, we now - use /build instead of - /tmp as the temporary build - directory. This fixes potential security problems when a build - accidentally stores its TMPDIR in some - security-sensitive place, such as an RPATH. - - - - - - - - - - Pure evaluation mode. With the - --pure-eval flag, Nix enables a variant of the existing - restricted evaluation mode that forbids access to anything that could cause - different evaluations of the same command line arguments to produce a - different result. This includes builtin functions such as - builtins.getEnv, but more importantly, - all filesystem or network access unless a content hash - or commit hash is specified. For example, calls to - builtins.fetchGit are only allowed if a - rev attribute is specified. - - The goal of this feature is to enable true reproducibility - and traceability of builds (including NixOS system configurations) - at the evaluation level. For example, in the future, - nixos-rebuild might build configurations from a - Nix expression in a Git repository in pure mode. That expression - might fetch other repositories such as Nixpkgs via - builtins.fetchGit. The commit hash of the - top-level repository then uniquely identifies a running system, - and, in conjunction with that repository, allows it to be - reproduced or modified. - - - - - There are several new features to support binary - reproducibility (i.e. to help ensure that multiple builds of the - same derivation produce exactly the same output). When - is set to - false, it’s no - longer a fatal error if build rounds produce different - output. Also, a hook named is provided - to allow you to run tools such as diffoscope - when build rounds produce different output. - - - - Configuring remote builds is a lot easier now. Provided you - are not using the Nix daemon, you can now just specify a remote - build machine on the command line, e.g. --option builders - 'ssh://my-mac x86_64-darwin'. The environment variable - NIX_BUILD_HOOK has been removed and is no longer - needed. The environment variable NIX_REMOTE_SYSTEMS - is still supported for compatibility, but it is also possible to - specify builders in nix.conf by setting the - option builders = - @path. - - - - If a fixed-output derivation produces a result with an - incorrect hash, the output path is moved to the location - corresponding to the actual hash and registered as valid. Thus, a - subsequent build of the fixed-output derivation with the correct - hash is unnecessary. - - - - nix-shell now - sets the IN_NIX_SHELL environment variable - during evaluation and in the shell itself. This can be used to - perform different actions depending on whether you’re in a Nix - shell or in a regular build. Nixpkgs provides - lib.inNixShell to check this variable during - evaluation. - - - - NIX_PATH is now lazy, so URIs in the path are - only downloaded if they are needed for evaluation. - - - - You can now use - channel:channel-name as a - short-hand for - https://nixos.org/channels/channel-name/nixexprs.tar.xz. For - example, nix-build channel:nixos-15.09 -A hello - will build the GNU Hello package from the - nixos-15.09 channel. In the future, this may - use Git to fetch updates more efficiently. - - - - When is given, the last - 10 lines of the build log will be shown if a build - fails. - - - - Networking has been improved: - - - - - HTTP/2 is now supported. This makes binary cache lookups - much - more efficient. - - - - We now retry downloads on many HTTP errors, making - binary caches substituters more resilient to temporary - failures. - - - - HTTP credentials can now be configured via the standard - netrc mechanism. - - - - If S3 support is enabled at compile time, - s3:// URIs are supported - in all places where Nix allows URIs. - - - - Brotli compression is now supported. In particular, - cache.nixos.org build logs are now compressed using - Brotli. - - - - - - - - - - nix-env now - ignores packages with bad derivation names (in particular those - starting with a digit or containing a dot). - - - - Many configuration options have been renamed, either because - they were unnecessarily verbose - (e.g. is now just - ) or to reflect generalised behaviour - (e.g. is now - because it allows arbitrary store - URIs). The old names are still supported for compatibility. - - - - The option can now - be set to auto to use the number of CPUs in the - system. - - - - Hashes can now - be specified in base-64 format, in addition to base-16 and the - non-standard base-32. - - - - nix-shell now uses - bashInteractive from Nixpkgs, rather than the - bash command that happens to be in the caller’s - PATH. This is especially important on macOS where - the bash provided by the system is seriously - outdated and cannot execute stdenv’s setup - script. - - - - Nix can now automatically trigger a garbage collection if - free disk space drops below a certain level during a build. This - is configured using the and - options. - - - - nix-store -q --roots and - nix-store --gc --print-roots now show temporary - and in-memory roots. - - - - - Nix can now be extended with plugins. See the documentation of - the option for more details. - - - - - -The Nix language has the following new features: - - - - - It supports floating point numbers. They are based on the - C++ float type and are supported by the - existing numerical operators. Export and import to and from JSON - and XML works, too. - - - - Derivation attributes can now reference the outputs of the - derivation using the placeholder builtin - function. For example, the attribute - - -configureFlags = "--prefix=${placeholder "out"} --includedir=${placeholder "dev"}"; - - - will cause the configureFlags environment variable - to contain the actual store paths corresponding to the - out and dev outputs. - - - - - - -The following builtin functions are new or extended: - - - - - builtins.fetchGit - allows Git repositories to be fetched at evaluation time. Thus it - differs from the fetchgit function in - Nixpkgs, which fetches at build time and cannot be used to fetch - Nix expressions during evaluation. A typical use case is to import - external NixOS modules from your configuration, e.g. - - imports = [ (builtins.fetchGit https://github.com/edolstra/dwarffs + "/module.nix") ]; - - - - - - Similarly, builtins.fetchMercurial - allows you to fetch Mercurial repositories. - - - - builtins.path generalises - builtins.filterSource and path literals - (e.g. ./foo). It allows specifying a store path - name that differs from the source path name - (e.g. builtins.path { path = ./foo; name = "bar"; - }) and also supports filtering out unwanted - files. - - - - builtins.fetchurl and - builtins.fetchTarball now support - sha256 and name - attributes. - - - - builtins.split - splits a string using a POSIX extended regular expression as the - separator. - - - - builtins.partition - partitions the elements of a list into two lists, depending on a - Boolean predicate. - - - - <nix/fetchurl.nix> now uses the - content-addressable tarball cache at - http://tarballs.nixos.org/, just like - fetchurl in - Nixpkgs. (f2682e6e18a76ecbfb8a12c17e3a0ca15c084197) - - - - In restricted and pure evaluation mode, builtin functions - that download from the network (such as - fetchGit) are permitted to fetch underneath a - list of URI prefixes specified in the option - . - - - - - - -The Nix build environment has the following changes: - - - - - Values such as Booleans, integers, (nested) lists and - attribute sets can now - be passed to builders in a non-lossy way. If the special attribute - __structuredAttrs is set to - true, the other derivation attributes are - serialised in JSON format and made available to the builder via - the file .attrs.json in the builder’s temporary - directory. This obviates the need for - passAsFile since JSON files have no size - restrictions, unlike process environments. - - As - a convenience to Bash builders, Nix writes a script named - .attrs.sh to the builder’s directory that - initialises shell variables corresponding to all attributes that - are representable in Bash. This includes non-nested (associative) - arrays. For example, the attribute hardening.format = - true ends up as the Bash associative array element - ${hardening[format]}. - - - - Builders can now - communicate what build phase they are in by writing messages to - the file descriptor specified in NIX_LOG_FD. The - current phase is shown by the nix progress - indicator. - - - - - In Linux sandbox builds, we now - provide a default /bin/sh (namely - ash from BusyBox). - - - - In structured attribute mode, - exportReferencesGraph exports - extended information about closures in JSON format. In particular, - it includes the sizes and hashes of paths. This is primarily - useful for NixOS image builders. - - - - Builds are now - killed as soon as Nix receives EOF on the builder’s stdout or - stderr. This fixes a bug that allowed builds to hang Nix - indefinitely, regardless of - timeouts. - - - - The configuration - option can now specify optional paths by appending a - ?, e.g. /dev/nvidiactl? will - bind-mount /dev/nvidiactl only if it - exists. - - - - On Linux, builds are now executed in a user - namespace with UID 1000 and GID 100. - - - - - - -A number of significant internal changes were made: - - - - - Nix no longer depends on Perl and all Perl components have - been rewritten in C++ or removed. The Perl bindings that used to - be part of Nix have been moved to a separate package, - nix-perl. - - - - All Store classes are now - thread-safe. RemoteStore supports multiple - concurrent connections to the daemon. This is primarily useful in - multi-threaded programs such as - hydra-queue-runner. - - - - - - -This release has contributions from - -Adrien Devresse, -Alexander Ried, -Alex Cruice, -Alexey Shmalko, -AmineChikhaoui, -Andy Wingo, -Aneesh Agrawal, -Anthony Cowley, -Armijn Hemel, -aszlig, -Ben Gamari, -Benjamin Hipple, -Benjamin Staffin, -Benno Fünfstück, -Bjørn Forsman, -Brian McKenna, -Charles Strahan, -Chase Adams, -Chris Martin, -Christian Theune, -Chris Warburton, -Daiderd Jordan, -Dan Connolly, -Daniel Peebles, -Dan Peebles, -davidak, -David McFarland, -Dmitry Kalinkin, -Domen Kožar, -Eelco Dolstra, -Emery Hemingway, -Eric Litak, -Eric Wolf, -Fabian Schmitthenner, -Frederik Rietdijk, -Gabriel Gonzalez, -Giorgio Gallo, -Graham Christensen, -Guillaume Maudoux, -Harmen, -Iavael, -James Broadhead, -James Earl Douglas, -Janus Troelsen, -Jeremy Shaw, -Joachim Schiele, -Joe Hermaszewski, -Joel Moberg, -Johannes 'fish' Ziemke, -Jörg Thalheim, -Jude Taylor, -kballou, -Keshav Kini, -Kjetil Orbekk, -Langston Barrett, -Linus Heckemann, -Ludovic Courtès, -Manav Rathi, -Marc Scholten, -Markus Hauck, -Matt Audesse, -Matthew Bauer, -Matthias Beyer, -Matthieu Coudron, -N1X, -Nathan Zadoks, -Neil Mayhew, -Nicolas B. Pierron, -Niklas Hambüchen, -Nikolay Amiantov, -Ole Jørgen Brønner, -Orivej Desh, -Peter Simons, -Peter Stuart, -Pyry Jahkola, -regnat, -Renzo Carbonara, -Rhys, -Robert Vollmert, -Scott Olson, -Scott R. Parish, -Sergei Trofimovich, -Shea Levy, -Sheena Artrip, -Spencer Baugh, -Stefan Junker, -Susan Potter, -Thomas Tuegel, -Timothy Allen, -Tristan Hume, -Tuomas Tynkkynen, -tv, -Tyson Whitehead, -Vladimír Čunát, -Will Dietz, -wmertens, -Wout Mertens, -zimbatm and -Zoran Plesivčak. - - -
diff --git a/doc/manual/release-notes/rl-2.1.xml b/doc/manual/release-notes/rl-2.1.xml deleted file mode 100644 index 16c243fc1..000000000 --- a/doc/manual/release-notes/rl-2.1.xml +++ /dev/null @@ -1,133 +0,0 @@ -
- -Release 2.1 (2018-09-02) - -This is primarily a bug fix release. It also reduces memory -consumption in certain situations. In addition, it has the following -new features: - - - - - The Nix installer will no longer default to the Multi-User - installation for macOS. You can still instruct the installer to - run in multi-user mode. - - - - - The Nix installer now supports performing a Multi-User - installation for Linux computers which are running systemd. You - can select a Multi-User installation by passing the - flag to the installer: sh <(curl - https://nixos.org/nix/install) --daemon. - - - The multi-user installer cannot handle systems with SELinux. - If your system has SELinux enabled, you can force the installer to run - in single-user mode. - - - - New builtin functions: - builtins.bitAnd, - builtins.bitOr, - builtins.bitXor, - builtins.fromTOML, - builtins.concatMap, - builtins.mapAttrs. - - - - - The S3 binary cache store now supports uploading NARs larger - than 5 GiB. - - - - The S3 binary cache store now supports uploading to - S3-compatible services with the endpoint - option. - - - - The flag is no longer required - to recover from disappeared NARs in binary caches. - - - - nix-daemon now respects - . - - - - nix run now respects - nix-support/propagated-user-env-packages. - - - - -This release has contributions from - -Adrien Devresse, -Aleksandr Pashkov, -Alexandre Esteves, -Amine Chikhaoui, -Andrew Dunham, -Asad Saeeduddin, -aszlig, -Ben Challenor, -Ben Gamari, -Benjamin Hipple, -Bogdan Seniuc, -Corey O'Connor, -Daiderd Jordan, -Daniel Peebles, -Daniel Poelzleithner, -Danylo Hlynskyi, -Dmitry Kalinkin, -Domen Kožar, -Doug Beardsley, -Eelco Dolstra, -Erik Arvstedt, -Félix Baylac-Jacqué, -Gleb Peregud, -Graham Christensen, -Guillaume Maudoux, -Ivan Kozik, -John Arnold, -Justin Humm, -Linus Heckemann, -Lorenzo Manacorda, -Matthew Justin Bauer, -Matthew O'Gorman, -Maximilian Bosch, -Michael Bishop, -Michael Fiano, -Michael Mercier, -Michael Raskin, -Michael Weiss, -Nicolas Dudebout, -Peter Simons, -Ryan Trinkle, -Samuel Dionne-Riel, -Sean Seefried, -Shea Levy, -Symphorien Gibol, -Tim Engler, -Tim Sears, -Tuomas Tynkkynen, -volth, -Will Dietz, -Yorick van Pelt and -zimbatm. - - -
diff --git a/doc/manual/release-notes/rl-2.2.xml b/doc/manual/release-notes/rl-2.2.xml deleted file mode 100644 index d29eb87e8..000000000 --- a/doc/manual/release-notes/rl-2.2.xml +++ /dev/null @@ -1,143 +0,0 @@ -
- -Release 2.2 (2019-01-11) - -This is primarily a bug fix release. It also has the following -changes: - - - - - In derivations that use structured attributes (i.e. that - specify set the __structuredAttrs attribute to - true to cause all attributes to be passed to - the builder in JSON format), you can now specify closure checks - per output, e.g.: - - -outputChecks."out" = { - # The closure of 'out' must not be larger than 256 MiB. - maxClosureSize = 256 * 1024 * 1024; - - # It must not refer to C compiler or to the 'dev' output. - disallowedRequisites = [ stdenv.cc "dev" ]; -}; - -outputChecks."dev" = { - # The 'dev' output must not be larger than 128 KiB. - maxSize = 128 * 1024; -}; - - - - - - - - The derivation attribute - requiredSystemFeatures is now enforced for - local builds, and not just to route builds to remote builders. - The supported features of a machine can be specified through the - configuration setting system-features. - - By default, system-features includes - kvm if /dev/kvm - exists. For compatibility, it also includes the pseudo-features - nixos-test, benchmark and - big-parallel which are used by Nixpkgs to route - builds to particular Hydra build machines. - - - - - Sandbox builds are now enabled by default on Linux. - - - - The new command nix doctor shows - potential issues with your Nix installation. - - - - The fetchGit builtin function now uses a - caching scheme that puts different remote repositories in distinct - local repositories, rather than a single shared repository. This - may require more disk space but is faster. - - - - The dirOf builtin function now works on - relative paths. - - - - Nix now supports SRI hashes, - allowing the hash algorithm and hash to be specified in a single - string. For example, you can write: - - -import <nix/fetchurl.nix> { - url = https://nixos.org/releases/nix/nix-2.1.3/nix-2.1.3.tar.xz; - hash = "sha256-XSLa0FjVyADWWhFfkZ2iKTjFDda6mMXjoYMXLRSYQKQ="; -}; - - - instead of - - -import <nix/fetchurl.nix> { - url = https://nixos.org/releases/nix/nix-2.1.3/nix-2.1.3.tar.xz; - sha256 = "5d22dad058d5c800d65a115f919da22938c50dd6ba98c5e3a183172d149840a4"; -}; - - - - - In fixed-output derivations, the - outputHashAlgo attribute is no longer mandatory - if outputHash specifies the hash. - - nix hash-file and nix - hash-path now print hashes in SRI format by - default. They also use SHA-256 by default instead of SHA-512 - because that's what we use most of the time in Nixpkgs. - - - - Integers are now 64 bits on all platforms. - - - - The evaluator now prints profiling statistics (enabled via - the NIX_SHOW_STATS and - NIX_COUNT_CALLS environment variables) in JSON - format. - - - - The option in nix-store - --query has been removed. Instead, there now is an - option to output the dependency graph - in GraphML format. - - - - All nix-* commands are now symlinks to - nix. This saves a bit of disk space. - - - - nix repl now uses - libeditline or - libreadline. - - - - -
- diff --git a/doc/manual/release-notes/rl-2.3.xml b/doc/manual/release-notes/rl-2.3.xml deleted file mode 100644 index 0ad7d641f..000000000 --- a/doc/manual/release-notes/rl-2.3.xml +++ /dev/null @@ -1,91 +0,0 @@ -
- -Release 2.3 (2019-09-04) - -This is primarily a bug fix release. However, it makes some -incompatible changes: - - - - - Nix now uses BSD file locks instead of POSIX file - locks. Because of this, you should not use Nix 2.3 and previous - releases at the same time on a Nix store. - - - - -It also has the following changes: - - - - - builtins.fetchGit's ref - argument now allows specifying an absolute remote ref. - Nix will automatically prefix ref with - refs/heads only if ref doesn't - already begin with refs/. - - - - - The installer now enables sandboxing by default on Linux when the - system has the necessary kernel support. - - - - - The max-jobs setting now defaults to 1. - - - - New builtin functions: - builtins.isPath, - builtins.hashFile. - - - - - The nix command has a new - () flag to - print build log output to stderr, rather than showing the last log - line in the progress bar. To distinguish between concurrent - builds, log lines are prefixed by the name of the package. - - - - - Builds are now executed in a pseudo-terminal, and the - TERM environment variable is set to - xterm-256color. This allows many programs - (e.g. gcc, clang, - cmake) to print colorized log output. - - - - Add convenience flag. This flag - disables substituters; sets the tarball-ttl - setting to infinity (ensuring that any previously downloaded files - are considered current); and disables retrying downloads and sets - the connection timeout to the minimum. This flag is enabled - automatically if there are no configured non-loopback network - interfaces. - - - - Add a post-build-hook setting to run a - program after a build has succeeded. - - - - Add a trace-function-calls setting to log - the duration of Nix function calls to stderr. - - - - -
diff --git a/doc/manual/schemas.xml b/doc/manual/schemas.xml deleted file mode 100644 index 691a517b9..000000000 --- a/doc/manual/schemas.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/doc/manual/src/SUMMARY.md b/doc/manual/src/SUMMARY.md new file mode 100644 index 000000000..8281f683f --- /dev/null +++ b/doc/manual/src/SUMMARY.md @@ -0,0 +1,105 @@ +# Table of Contents + +- [Introduction](introduction.md) +- [Quick Start](quick-start.md) +- [Installation](installation/installation.md) + - [Supported Platforms](installation/supported-platforms.md) + - [Installing a Binary Distribution](installation/installing-binary.md) + - [Installing Nix from Source](installation/installing-source.md) + - [Prerequisites](installation/prerequisites-source.md) + - [Obtaining a Source Distribution](installation/obtaining-source.md) + - [Building Nix from Source](installation/building-source.md) + - [Security](installation/nix-security.md) + - [Single-User Mode](installation/single-user.md) + - [Multi-User Mode](installation/multi-user.md) + - [Environment Variables](installation/env-variables.md) + - [Upgrading Nix](installation/upgrading.md) +- [Package Management](package-management/package-management.md) + - [Basic Package Management](package-management/basic-package-mgmt.md) + - [Profiles](package-management/profiles.md) + - [Garbage Collection](package-management/garbage-collection.md) + - [Garbage Collector Roots](package-management/garbage-collector-roots.md) + - [Channels](package-management/channels.md) + - [Sharing Packages Between Machines](package-management/sharing-packages.md) + - [Serving a Nix store via HTTP](package-management/binary-cache-substituter.md) + - [Copying Closures via SSH](package-management/copy-closure.md) + - [Serving a Nix store via SSH](package-management/ssh-substituter.md) + - [Serving a Nix store via S3](package-management/s3-substituter.md) +- [Writing Nix Expressions](expressions/writing-nix-expressions.md) + - [A Simple Nix Expression](expressions/simple-expression.md) + - [Expression Syntax](expressions/expression-syntax.md) + - [Build Script](expressions/build-script.md) + - [Arguments and Variables](expressions/arguments-variables.md) + - [Building and Testing](expressions/simple-building-testing.md) + - [Generic Builder Syntax](expressions/generic-builder.md) + - [Writing Nix Expressions](expressions/expression-language.md) + - [Values](expressions/language-values.md) + - [Language Constructs](expressions/language-constructs.md) + - [Operators](expressions/language-operators.md) + - [Derivations](expressions/derivations.md) + - [Advanced Attributes](expressions/advanced-attributes.md) + - [Built-in Constants](expressions/builtin-constants.md) + - [Built-in Functions](expressions/builtins.md) +- [Advanced Topics](advanced-topics/advanced-topics.md) + - [Remote Builds](advanced-topics/distributed-builds.md) + - [Tuning Cores and Jobs](advanced-topics/cores-vs-jobs.md) + - [Verifying Build Reproducibility](advanced-topics/diff-hook.md) + - [Using the `post-build-hook`](advanced-topics/post-build-hook.md) +- [Command Reference](command-ref/command-ref.md) + - [Common Options](command-ref/opt-common.md) + - [Common Environment Variables](command-ref/env-common.md) + - [Main Commands](command-ref/main-commands.md) + - [nix-env](command-ref/nix-env.md) + - [nix-build](command-ref/nix-build.md) + - [nix-shell](command-ref/nix-shell.md) + - [nix-store](command-ref/nix-store.md) + - [Utilities](command-ref/utilities.md) + - [nix-channel](command-ref/nix-channel.md) + - [nix-collect-garbage](command-ref/nix-collect-garbage.md) + - [nix-copy-closure](command-ref/nix-copy-closure.md) + - [nix-daemon](command-ref/nix-daemon.md) + - [nix-hash](command-ref/nix-hash.md) + - [nix-instantiate](command-ref/nix-instantiate.md) + - [nix-prefetch-url](command-ref/nix-prefetch-url.md) + - [Experimental Commands](command-ref/experimental-commands.md) + - [nix](command-ref/nix.md) + - [Files](command-ref/files.md) + - [nix.conf](command-ref/conf-file.md) +- [Glossary](glossary.md) +- [Hacking](hacking.md) +- [Release Notes](release-notes/release-notes.md) + - [Release 2.3 (2019-09-04)](release-notes/rl-2.3.md) + - [Release 2.2 (2019-01-11)](release-notes/rl-2.2.md) + - [Release 2.1 (2018-09-02)](release-notes/rl-2.1.md) + - [Release 2.0 (2018-02-22)](release-notes/rl-2.0.md) + - [Release 1.11.10 (2017-06-12)](release-notes/rl-1.11.10.md) + - [Release 1.11 (2016-01-19)](release-notes/rl-1.11.md) + - [Release 1.10 (2015-09-03)](release-notes/rl-1.10.md) + - [Release 1.9 (2015-06-12)](release-notes/rl-1.9.md) + - [Release 1.8 (2014-12-14)](release-notes/rl-1.8.md) + - [Release 1.7 (2014-04-11)](release-notes/rl-1.7.md) + - [Release 1.6.1 (2013-10-28)](release-notes/rl-1.6.1.md) + - [Release 1.6 (2013-09-10)](release-notes/rl-1.6.md) + - [Release 1.5.2 (2013-05-13)](release-notes/rl-1.5.2.md) + - [Release 1.5 (2013-02-27)](release-notes/rl-1.5.md) + - [Release 1.4 (2013-02-26)](release-notes/rl-1.4.md) + - [Release 1.3 (2013-01-04)](release-notes/rl-1.3.md) + - [Release 1.2 (2012-12-06)](release-notes/rl-1.2.md) + - [Release 1.1 (2012-07-18)](release-notes/rl-1.1.md) + - [Release 1.0 (2012-05-11)](release-notes/rl-1.0.md) + - [Release 0.16 (2010-08-17)](release-notes/rl-0.16.md) + - [Release 0.15 (2010-03-17)](release-notes/rl-0.15.md) + - [Release 0.14 (2010-02-04)](release-notes/rl-0.14.md) + - [Release 0.13 (2009-11-05)](release-notes/rl-0.13.md) + - [Release 0.12 (2008-11-20)](release-notes/rl-0.12.md) + - [Release 0.11 (2007-12-31)](release-notes/rl-0.11.md) + - [Release 0.10.1 (2006-10-11)](release-notes/rl-0.10.1.md) + - [Release 0.10 (2006-10-06)](release-notes/rl-0.10.md) + - [Release 0.9.2 (2005-09-21)](release-notes/rl-0.9.2.md) + - [Release 0.9.1 (2005-09-20)](release-notes/rl-0.9.1.md) + - [Release 0.9 (2005-09-16)](release-notes/rl-0.9.md) + - [Release 0.8.1 (2005-04-13)](release-notes/rl-0.8.1.md) + - [Release 0.8 (2005-04-11)](release-notes/rl-0.8.md) + - [Release 0.7 (2005-01-12)](release-notes/rl-0.7.md) + - [Release 0.6 (2004-11-14)](release-notes/rl-0.6.md) + - [Release 0.5 and earlier](release-notes/rl-0.5.md) diff --git a/doc/manual/src/advanced-topics/advanced-topics.md b/doc/manual/src/advanced-topics/advanced-topics.md new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/doc/manual/src/advanced-topics/advanced-topics.md @@ -0,0 +1 @@ + diff --git a/doc/manual/src/advanced-topics/cores-vs-jobs.md b/doc/manual/src/advanced-topics/cores-vs-jobs.md new file mode 100644 index 000000000..4a9058ca1 --- /dev/null +++ b/doc/manual/src/advanced-topics/cores-vs-jobs.md @@ -0,0 +1,39 @@ +# Tuning Cores and Jobs + +Nix has two relevant settings with regards to how your CPU cores will +be utilized: `cores` and `max-jobs`. This chapter will talk about what +they are, how they interact, and their configuration trade-offs. + + - `max-jobs` + Dictates how many separate derivations will be built at the same + time. If you set this to zero, the local machine will do no + builds. Nix will still substitute from binary caches, and build + remotely if remote builders are configured. + + - `cores` + Suggests how many cores each derivation should use. Similar to + `make -j`. + +The `cores` setting determines the value of +`NIX_BUILD_CORES`. `NIX_BUILD_CORES` is equal to `cores`, unless +`cores` equals `0`, in which case `NIX_BUILD_CORES` will be the total +number of cores in the system. + +The maximum number of consumed cores is a simple multiplication, +`max-jobs` \* `NIX_BUILD_CORES`. + +The balance on how to set these two independent variables depends upon +each builder's workload and hardware. Here are a few example scenarios +on a machine with 24 cores: + +| `max-jobs` | `cores` | `NIX_BUILD_CORES` | Maximum Processes | Result | +| --------------------- | ------------------ | ----------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | 24 | 24 | 24 | One derivation will be built at a time, each one can use 24 cores. Undersold if a job can’t use 24 cores. | +| 4 | 6 | 6 | 24 | Four derivations will be built at once, each given access to six cores. | +| 12 | 6 | 6 | 72 | 12 derivations will be built at once, each given access to six cores. This configuration is over-sold. If all 12 derivations being built simultaneously try to use all six cores, the machine's performance will be degraded due to extensive context switching between the 12 builds. | +| 24 | 1 | 1 | 24 | 24 derivations can build at the same time, each using a single core. Never oversold, but derivations which require many cores will be very slow to compile. | +| 24 | 0 | 24 | 576 | 24 derivations can build at the same time, each using all the available cores of the machine. Very likely to be oversold, and very likely to suffer context switches. | + +It is up to the derivations' build script to respect host's requested +cores-per-build by following the value of the `NIX_BUILD_CORES` +environment variable. diff --git a/doc/manual/src/advanced-topics/diff-hook.md b/doc/manual/src/advanced-topics/diff-hook.md new file mode 100644 index 000000000..7a2622b3d --- /dev/null +++ b/doc/manual/src/advanced-topics/diff-hook.md @@ -0,0 +1,157 @@ +# Verifying Build Reproducibility + +You can use Nix's `diff-hook` setting to compare build results. Note +that this hook is only executed if the results differ; it is not used +for determining if the results are the same. + +For purposes of demonstration, we'll use the following Nix file, +`deterministic.nix` for testing: + +```nix +let + inherit (import {}) runCommand; +in { + stable = runCommand "stable" {} '' + touch $out + ''; + + unstable = runCommand "unstable" {} '' + echo $RANDOM > $out + ''; +} +``` + +Additionally, `nix.conf` contains: + + diff-hook = /etc/nix/my-diff-hook + run-diff-hook = true + +where `/etc/nix/my-diff-hook` is an executable file containing: + +```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 +built. + +# Spot-Checking Build Determinism + +Verify a path which already exists in the Nix store by passing `--check` +to the build command. + +If the build passes and is deterministic, Nix will exit with a status +code of 0: + +```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: + +```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 +``` + +Using `--check` with `--keep-failed` will cause Nix to keep the second +build's output in a special, `.check` path: + +```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 +has copied the build results to that directory where you can examine it. + +> **Note** +> +> Check paths are not protected against garbage collection, and this +> path will be deleted on the next garbage collection. +> +> The path is guaranteed to be alive for the duration of +> the `diff-hook`'s execution, but may be deleted any time after. +> +> If the comparison is performed as part of automated tooling, please +> use the diff-hook or author your tooling to handle the case where the +> build was not deterministic and also a check path does not exist. + +`--check` is only usable if the derivation has been built on the system +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 + +Run the build without `--check`, and then try with `--check` again. + +# Automatic and Optionally Enforced Determinism Verification + +Automatically verify every build at build time by executing the build +multiple times. + +Setting `repeat` and `enforce-determinism` in your `nix.conf` permits +the automated verification of every build Nix performs. + +The following configuration will run each build three times, and will +require the build to be deterministic: + + enforce-determinism = true + repeat = 2 + +Setting `enforce-determinism` to false as in the following +configuration will run the build multiple times, execute the build +hook, but will allow the build to succeed even if it does not build +reproducibly: + + enforce-determinism = false + repeat = 1 + +An example output of this configuration: + +```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 +``` diff --git a/doc/manual/src/advanced-topics/distributed-builds.md b/doc/manual/src/advanced-topics/distributed-builds.md new file mode 100644 index 000000000..c6966a50b --- /dev/null +++ b/doc/manual/src/advanced-topics/distributed-builds.md @@ -0,0 +1,154 @@ +# Remote Builds + +Nix supports remote builds, where a local Nix installation can forward +Nix builds to other machines. This allows multiple builds to be +performed in parallel and allows Nix to perform multi-platform builds in +a semi-transparent way. For instance, if you perform a build for a +`x86_64-darwin` on an `i686-linux` machine, Nix can automatically +forward the build to a `x86_64-darwin` machine, if available. + +To forward a build to a remote machine, it’s 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. + +```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. + +```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 +`ssh-agent` or `gpg-agent`. + +If you get the error + +```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. + +> **Warning** +> +> If you are building via the Nix daemon, it is the Nix daemon user +> account (that is, `root`) that should have SSH access to the remote +> machine. If you can’t or don’t want to configure `root` to be able to +> access to remote machine, you can use a private Nix store instead by +> passing e.g. `--store ~/my-nix`. + +The list of remote machines can be specified on the command line or in +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: + +```console +$ uname +Linux + +$ nix build \ + '(with import { 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' +``` + +Each machine specification consists of the following elements, separated +by spaces. Only the first element is required. To leave a field at its +default, set it to `-`. + +1. The URI of the remote store in the format + `ssh://[username@]hostname`, e.g. `ssh://nix@mac` or `ssh://mac`. + For backward compatibility, `ssh://` may be omitted. The hostname + may be an alias defined in your `~/.ssh/config`. + +2. A comma-separated list of Nix platform type identifiers, such as + `x86_64-darwin`. It is possible for a machine to support multiple + platform types, e.g., `i686-linux,x86_64-linux`. If omitted, this + defaults to the local platform type. + +3. The SSH identity file to be used to log in to the remote machine. If + omitted, SSH will use its regular identities. + +4. The maximum number of builds that Nix will execute in parallel on + the machine. Typically this should be equal to the number of CPU + cores. For instance, the machine `itchy` in the example will execute + up to 8 builds in parallel. + +5. The “speed factor”, indicating the relative speed of the machine. If + there are multiple machines of the right type, Nix will prefer the + fastest, taking load into account. + +6. A comma-separated list of *supported features*. If a derivation has + the `requiredSystemFeatures` attribute, then Nix will only perform + the derivation on a machine that has the specified features. For + instance, the attribute + + ```nix + requiredSystemFeatures = [ "kvm" ]; + ``` + + will cause the build to be performed on a machine that has the `kvm` + feature. + +7. A comma-separated list of *mandatory features*. A machine will only + be used to build a derivation if all of the machine’s mandatory + features appear in the derivation’s `requiredSystemFeatures` + attribute.. + +For example, the machine specification + + nix@scratchy.labs.cs.uu.nl i686-linux /home/nix/.ssh/id_scratchy_auto 8 1 kvm + nix@itchy.labs.cs.uu.nl i686-linux /home/nix/.ssh/id_scratchy_auto 8 2 + nix@poochie.labs.cs.uu.nl i686-linux /home/nix/.ssh/id_scratchy_auto 1 2 kvm benchmark + +specifies several machines that can perform `i686-linux` builds. +However, `poochie` will only do builds that have the attribute + +```nix +requiredSystemFeatures = [ "benchmark" ]; +``` + +or + +```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 +`scratchy` because it has a higher speed factor. + +Remote builders can also be configured in `nix.conf`, e.g. + + builders = ssh://mac x86_64-darwin ; ssh://beastie x86_64-freebsd + +Finally, remote builders can be configured in a separate configuration +file included in `builders` via the syntax `@file`. For example, + + builders = @/etc/nix/machines + +causes the list of machines in `/etc/nix/machines` to be included. (This +is the default.) + +If you want the builders to use caches, you likely want to set the +option `builders-use-substitutes` in your local `nix.conf`. + +To build only on remote builders and disable building on the local +machine, you can use the option `--max-jobs 0`. diff --git a/doc/manual/src/advanced-topics/post-build-hook.md b/doc/manual/src/advanced-topics/post-build-hook.md new file mode 100644 index 000000000..bbdabed41 --- /dev/null +++ b/doc/manual/src/advanced-topics/post-build-hook.md @@ -0,0 +1,123 @@ +# Using the `post-build-hook` + +# Implementation Caveats + +Here we use the post-build hook to upload to a binary cache. This is a +simple and working example, but it is not suitable for all use cases. + +The post build hook program runs after each executed build, and blocks +the build loop. The build loop exits if the hook program fails. + +Concretely, this implementation will make Nix slow or unusable when the +internet is slow or unreliable. + +A more advanced implementation might pass the store paths to a +user-supplied daemon or queue for processing the store paths outside of +the build loop. + +# Prerequisites + +This tutorial assumes you have [configured an S3-compatible binary +cache](../package-management/s3-substituter.md), and that the `root` +user's default AWS profile can upload to the bucket. + +# Set up a Signing Key + +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. + +```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: + + substituters = https://cache.nixos.org/ s3://example-nix-cache + trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= example-nix-cache-1:1/cKDz3QCCOmwcztD2eV6Coggp6rqc9DGjWv7C0G+rM= + +We will restart the Nix daemon in a later step. + +# Implementing the build hook + +Write the following script to `/etc/nix/upload-to-cache.sh`: + +```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** +> +> The `$OUT_PATHS` variable is a space-separated list of Nix store +> paths. In this case, we expect and want the shell to perform word +> splitting to make each output path its own argument to `nix +> sign-paths`. Nix guarantees the paths will not contain any spaces, +> however a store path might contain glob characters. The `set -f` +> disables globbing in the shell. + +Then make sure the hook program is executable by the `root` user: + +```console +# chmod +x /etc/nix/upload-to-cache.sh +``` + +# Updating Nix Configuration + +Edit `/etc/nix/nix.conf` to run our hook, by adding the following +configuration snippet at the end: + + post-build-hook = /etc/nix/upload-to-cache.sh + +Then, restart the `nix-daemon`. + +# Testing + +Build any derivation, for example: + +```console +$ nix-build -E '(import {}).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: + +```console +$ rm ./result +$ nix-store --delete /nix/store/ibcyipq5gf91838ldx40mjsp0b8w9n18-example +``` + +Now, copy the path back from the cache: + +```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 + +We now have a Nix installation configured to automatically sign and +upload every local build to a remote binary cache. + +Before deploying this to production, be sure to consider the +[implementation caveats](#implementation-caveats). diff --git a/doc/manual/src/command-ref/command-ref.md b/doc/manual/src/command-ref/command-ref.md new file mode 100644 index 000000000..6a78075db --- /dev/null +++ b/doc/manual/src/command-ref/command-ref.md @@ -0,0 +1,2 @@ +This section lists commands and options that you can use when you work +with Nix. diff --git a/doc/manual/src/command-ref/conf-file-prefix.md b/doc/manual/src/command-ref/conf-file-prefix.md new file mode 100644 index 000000000..04c6cd859 --- /dev/null +++ b/doc/manual/src/command-ref/conf-file-prefix.md @@ -0,0 +1,39 @@ +Title: nix.conf + +# Name + +`nix.conf` - Nix configuration file + +# Description + +By default Nix reads settings from the following places: + + - The system-wide configuration file `sysconfdir/nix/nix.conf` (i.e. + `/etc/nix/nix.conf` on most systems), or `$NIX_CONF_DIR/nix.conf` if + `NIX_CONF_DIR` is set. Values loaded in this file are not forwarded + to the Nix daemon. The client assumes that the daemon has already + loaded them. + + - If `NIX_USER_CONF_FILES` is set, then each path separated by `:` + will be loaded in reverse order. + + Otherwise it will look for `nix/nix.conf` files in `XDG_CONFIG_DIRS` + and `XDG_CONFIG_HOME`. If these are unset, it will look in + `$HOME/.config/nix.conf`. + +The configuration files consist of `name = +value` pairs, one per line. Other files can be included with a line like +`include +path`, where *path* is interpreted relative to the current conf file and +a missing file is an error unless `!include` is used instead. Comments +start with a `#` character. Here is an example configuration file: + + keep-outputs = true # Nice for developers + keep-derivations = true # Idem + +You can override settings on the command line using the `--option` flag, +e.g. `--option keep-outputs +false`. + +The following settings are currently available: + diff --git a/doc/manual/src/command-ref/env-common.md b/doc/manual/src/command-ref/env-common.md new file mode 100644 index 000000000..03016dba7 --- /dev/null +++ b/doc/manual/src/command-ref/env-common.md @@ -0,0 +1,115 @@ +# Common Environment Variables + +Most Nix commands interpret the following environment variables: + + - `IN_NIX_SHELL` + Indicator that tells if the current environment was set up by + `nix-shell`. Since Nix 2.0 the values are `"pure"` and `"impure"` + + - `NIX_PATH` + A colon-separated list of directories used to look up Nix + expressions enclosed in angle brackets (i.e., ``). For + instance, the value + + /home/eelco/Dev:/etc/nixos + + will cause Nix to look for paths relative to `/home/eelco/Dev` and + `/etc/nixos`, in this order. It is also possible to match paths + against a prefix. For example, the value + + nixpkgs=/home/eelco/Dev/nixpkgs-branch:/etc/nixos + + will cause Nix to search for `` in + `/home/eelco/Dev/nixpkgs-branch/path` and `/etc/nixos/nixpkgs/path`. + + If a path in the Nix search path starts with `http://` or + `https://`, it is interpreted as the URL of a tarball that will be + downloaded and unpacked to a temporary location. The tarball must + consist of a single top-level directory. For example, setting + `NIX_PATH` to + + nixpkgs=https://github.com/NixOS/nixpkgs/archive/nixos-15.09.tar.gz + + tells Nix to download the latest revision in the Nixpkgs/NixOS 15.09 + channel. + + A following shorthand can be used to refer to the official channels: + + nixpkgs=channel:nixos-15.09 + + The search path can be extended using the `-I` option, which takes + precedence over `NIX_PATH`. + + - `NIX_IGNORE_SYMLINK_STORE` + Normally, the Nix store directory (typically `/nix/store`) is not + allowed to contain any symlink components. This is to prevent + “impure” builds. Builders sometimes “canonicalise” paths by + resolving all symlink components. Thus, builds on different machines + (with `/nix/store` resolving to different locations) could yield + different results. This is generally not a problem, except when + builds are deployed to machines where `/nix/store` resolves + differently. If you are sure that you’re not going to do that, you + can set `NIX_IGNORE_SYMLINK_STORE` to `1`. + + Note that if you’re symlinking the Nix store so that you can put it + on another file system than the root file system, on Linux you’re + better off using `bind` mount points, e.g., + + ```console + $ mkdir /nix + $ mount -o bind /mnt/otherdisk/nix /nix + ``` + + Consult the mount 8 manual page for details. + + - `NIX_STORE_DIR` + Overrides the location of the Nix store (default `prefix/store`). + + - `NIX_DATA_DIR` + Overrides the location of the Nix static data directory (default + `prefix/share`). + + - `NIX_LOG_DIR` + Overrides the location of the Nix log directory (default + `prefix/var/log/nix`). + + - `NIX_STATE_DIR` + Overrides the location of the Nix state directory (default + `prefix/var/nix`). + + - `NIX_CONF_DIR` + Overrides the location of the system Nix configuration directory + (default `prefix/etc/nix`). + + - `NIX_USER_CONF_FILES` + Overrides the location of the user Nix configuration files to load + from (defaults to the XDG spec locations). The variable is treated + as a list separated by the `:` token. + + - `TMPDIR` + Use the specified directory to store temporary files. In particular, + this includes temporary build directories; these can take up + substantial amounts of disk space. The default is `/tmp`. + + - `NIX_REMOTE` + This variable should be set to `daemon` if you want to use the Nix + daemon to execute Nix operations. This is necessary in [multi-user + Nix installations](../installation/multi-user.md). If the Nix + daemon's Unix socket is at some non-standard path, this variable + should be set to `unix://path/to/socket`. Otherwise, it should be + left unset. + + - `NIX_SHOW_STATS` + If set to `1`, Nix will print some evaluation statistics, such as + the number of values allocated. + + - `NIX_COUNT_CALLS` + If set to `1`, Nix will print how often functions were called during + Nix expression evaluation. This is useful for profiling your Nix + expressions. + + - `GC_INITIAL_HEAP_SIZE` + If Nix has been configured to use the Boehm garbage collector, this + variable sets the initial size of the heap in bytes. It defaults to + 384 MiB. Setting it to a low value reduces memory consumption, but + will increase runtime due to the overhead of garbage collection. diff --git a/doc/manual/src/command-ref/experimental-commands.md b/doc/manual/src/command-ref/experimental-commands.md new file mode 100644 index 000000000..cfa6f8b73 --- /dev/null +++ b/doc/manual/src/command-ref/experimental-commands.md @@ -0,0 +1,8 @@ +# Experimental Commands + +This section lists experimental commands. + +> **Warning** +> +> These commands may be removed in the future, or their syntax may +> change in incompatible ways. diff --git a/doc/manual/src/command-ref/files.md b/doc/manual/src/command-ref/files.md new file mode 100644 index 000000000..df5646c05 --- /dev/null +++ b/doc/manual/src/command-ref/files.md @@ -0,0 +1,4 @@ +# Files + +This section lists configuration files that you can use when you work +with Nix. diff --git a/doc/manual/src/command-ref/main-commands.md b/doc/manual/src/command-ref/main-commands.md new file mode 100644 index 000000000..e4f1f1d0e --- /dev/null +++ b/doc/manual/src/command-ref/main-commands.md @@ -0,0 +1,4 @@ +# Main Commands + +This section lists commands and options that you can use when you work +with Nix. diff --git a/doc/manual/src/command-ref/nix-build.md b/doc/manual/src/command-ref/nix-build.md new file mode 100644 index 000000000..4bcb8db40 --- /dev/null +++ b/doc/manual/src/command-ref/nix-build.md @@ -0,0 +1,113 @@ +Title: nix-build + +# Name + +`nix-build` - build a Nix expression + +# Synopsis + +`nix-build` [*paths…*] + [`--arg` *name* *value*] + [`--argstr` *name* *value*] + [{`--attr` | `-A`} *attrPath*] + [`--no-out-link`] + [`--dry-run`] + [{`--out-link` | `-o`} *outlink*] + +# Description + +The `nix-build` command builds the derivations described by the Nix +expressions in *paths*. If the build succeeds, it places a symlink to +the result in the current directory. The symlink is called `result`. If +there are multiple Nix expressions, or the Nix expressions evaluate to +multiple derivations, multiple sequentially numbered symlinks are +created (`result`, `result-2`, and so on). + +If no *paths* are specified, then `nix-build` will use `default.nix` in +the current directory, if it exists. + +If an element of *paths* starts with `http://` or `https://`, it is +interpreted as the URL of a tarball that will be downloaded and unpacked +to a temporary location. The tarball must include a single top-level +directory containing at least a file named `default.nix`. + +`nix-build` is essentially a wrapper around +[`nix-instantiate`](nix-instantiate.md) (to translate a high-level Nix +expression to a low-level store derivation) and [`nix-store +--realise`](nix-store.md#operation---realise) (to build the store +derivation). + +> **Warning** +> +> The result of the build is automatically registered as a root of the +> Nix garbage collector. This root disappears automatically when the +> `result` symlink is deleted or renamed. So don’t rename the symlink. + +# Options + +All options not listed here are passed to `nix-store +--realise`, except for `--arg` and `--attr` / `-A` which are passed to +`nix-instantiate`. + + - `--no-out-link` + Do not create a symlink to the output path. Note that as a result + the output does not become a root of the garbage collector, and so + might be deleted by `nix-store + --gc`. + + - `--dry-run` + Show what store paths would be built or downloaded. + + - `--out-link` / `-o` *outlink* + Change the name of the symlink to the output path created from + `result` to *outlink*. + +The following common options are supported: + +# Examples + +```console +$ nix-build '' -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 ./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: + +```console +$ nix-build '' -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 +outputs `out`, `bin` and `man`, `nix-build` will create symlinks +`result`, `result-bin` and `result-man`. It’s also possible to build a +specific output: + +```console +$ nix-build '' -A openssl.man +``` + +This will create a symlink `result-man`. + +Build a Nix expression given on the command line: + +```console +$ nix-build -E 'with import { }; runCommand "foo" { } "echo bar > $out"' +$ cat ./result +bar +``` + +Build the GNU Hello package from the latest revision of the master +branch of Nixpkgs: + +```console +$ nix-build https://github.com/NixOS/nixpkgs/archive/master.tar.gz -A hello +``` diff --git a/doc/manual/src/command-ref/nix-channel.md b/doc/manual/src/command-ref/nix-channel.md new file mode 100644 index 000000000..f0e205967 --- /dev/null +++ b/doc/manual/src/command-ref/nix-channel.md @@ -0,0 +1,98 @@ +Title: nix-channel + +# Name + +`nix-channel` - manage Nix channels + +# Synopsis + +`nix-channel` {`--add` url [*name*] | `--remove` *name* | `--list` | `--update` [*names…*] | `--rollback` [*generation*] } + +# Description + +A Nix channel is a mechanism that allows you to automatically stay +up-to-date with a set of pre-built Nix expressions. A Nix channel is +just a URL that points to a place containing a set of Nix expressions. + +To see the list of official NixOS channels, visit +. + +This command has the following operations: + + - `--add` *url* \[*name*\] + Adds a channel named *name* with URL *url* to the list of subscribed + channels. If *name* is omitted, it defaults to the last component of + *url*, with the suffixes `-stable` or `-unstable` removed. + + - `--remove` *name* + Removes the channel named *name* from the list of subscribed + channels. + + - `--list` + Prints the names and URLs of all subscribed channels on standard + output. + + - `--update` \[*names*…\] + Downloads the Nix expressions of all subscribed channels (or only + those included in *names* if specified) and makes them the default + for `nix-env` operations (by symlinking them from the directory + `~/.nix-defexpr`). + + - `--rollback` \[*generation*\] + Reverts the previous call to `nix-channel + --update`. Optionally, you can specify a specific channel generation + number to restore. + +Note that `--add` does not automatically perform an update. + +The list of subscribed channels is stored in `~/.nix-channels`. + +# Examples + +To subscribe to the Nixpkgs channel and install the GNU Hello package: + +```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`: + +```console +$ nix-instantiate --eval -E '(import {}).lib.version' +"14.04.527.0e935f1" + +$ nix-channel --rollback +switching from generation 483 to 482 + +$ nix-instantiate --eval -E '(import {}).lib.version' +"14.04.526.dbadfad" +``` + +# Files + + - `/nix/var/nix/profiles/per-user/username/channels` + `nix-channel` uses a `nix-env` profile to keep track of previous + versions of the subscribed channels. Every time you run `nix-channel + --update`, a new channel generation (that is, a symlink to the + channel Nix expressions in the Nix store) is created. This enables + `nix-channel --rollback` to revert to previous versions. + + - `~/.nix-defexpr/channels` + This is a symlink to + `/nix/var/nix/profiles/per-user/username/channels`. It ensures that + `nix-env` can find your channels. In a multi-user installation, you + may also have `~/.nix-defexpr/channels_root`, which links to the + channels of the root user. + +# Channel format + +A channel URL should point to a directory containing the following +files: + + - `nixexprs.tar.xz` + A tarball containing Nix expressions and files referenced by them + (such as build scripts and patches). At the top level, the tarball + should contain a single directory. That directory must contain a + file `default.nix` that serves as the channel’s “entry point”. diff --git a/doc/manual/src/command-ref/nix-collect-garbage.md b/doc/manual/src/command-ref/nix-collect-garbage.md new file mode 100644 index 000000000..62a6b7ca0 --- /dev/null +++ b/doc/manual/src/command-ref/nix-collect-garbage.md @@ -0,0 +1,32 @@ +Title: nix-collect-garbage + +# Name + +`nix-collect-garbage` - delete unreachable store paths + +# Synopsis + +`nix-collect-garbage` [`--delete-old`] [`-d`] [`--delete-older-than` *period*] [`--max-freed` *bytes*] [`--dry-run`] + +# Description + +The command `nix-collect-garbage` is mostly an alias of [`nix-store +--gc`](nix-store.md#operation---gc), that is, it deletes all +unreachable paths in the Nix store to clean up your system. However, +it provides two additional options: `-d` (`--delete-old`), which +deletes all old generations of all profiles in `/nix/var/nix/profiles` +by invoking `nix-env --delete-generations old` on all profiles (of +course, this makes rollbacks to previous configurations impossible); +and `--delete-older-than` *period*, where period is a value such as +`30d`, which deletes all generations older than the specified number +of days in all profiles in `/nix/var/nix/profiles` (except for the +generations that were active at that point in time). + +# Example + +To delete from the Nix store everything that is not used by the current +generations of each profile, do + +```console +$ nix-collect-garbage -d +``` diff --git a/doc/manual/src/command-ref/nix-copy-closure.md b/doc/manual/src/command-ref/nix-copy-closure.md new file mode 100644 index 000000000..5ce320af7 --- /dev/null +++ b/doc/manual/src/command-ref/nix-copy-closure.md @@ -0,0 +1,87 @@ +Title: nix-copy-closure + +# Name + +`nix-copy-closure` - copy a closure to or from a remote machine via SSH + +# Synopsis + +`nix-copy-closure` + [`--to` | `--from`] + [`--gzip`] + [`--include-outputs`] + [`--use-substitutes` | `-s`] + [`-v`] + _user@machine_ _paths_ + +# Description + +`nix-copy-closure` gives you an easy and efficient way to exchange +software between machines. Given one or more Nix store _paths_ on the +local machine, `nix-copy-closure` computes the closure of those paths +(i.e. all their dependencies in the Nix store), and copies all paths +in the closure to the remote machine via the `ssh` (Secure Shell) +command. With the `--from` option, the direction is reversed: the +closure of _paths_ on a remote machine is copied to the Nix store on +the local machine. + +This command is efficient because it only sends the store paths +that are missing on the target machine. + +Since `nix-copy-closure` calls `ssh`, you may be asked to type in the +appropriate password or passphrase. In fact, you may be asked _twice_ +because `nix-copy-closure` currently connects twice to the remote +machine, first to get the set of paths missing on the target machine, +and second to send the dump of those paths. If this bothers you, use +`ssh-agent`. + +# Options + + - `--to` + Copy the closure of _paths_ from the local Nix store to the Nix + store on _machine_. This is the default. + + - `--from` + Copy the closure of _paths_ from the Nix store on _machine_ to the + local Nix store. + + - `--gzip` + Enable compression of the SSH connection. + + - `--include-outputs` + Also copy the outputs of store derivations included in the closure. + + - `--use-substitutes` / `-s` + Attempt to download missing paths on the target machine using Nix’s + substitute mechanism. Any paths that cannot be substituted on the + target are still copied normally from the source. This is useful, + for instance, if the connection between the source and target + machine is slow, but the connection between the target machine and + `nixos.org` (the default binary cache server) is + fast. + + - `-v` + Show verbose output. + +# Environment variables + + - `NIX_SSHOPTS` + Additional options to be passed to `ssh` on the command + line. + +# Examples + +Copy Firefox with all its dependencies to a remote machine: + +```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: + +```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 +``` diff --git a/doc/manual/src/command-ref/nix-daemon.md b/doc/manual/src/command-ref/nix-daemon.md new file mode 100644 index 000000000..bd5d25026 --- /dev/null +++ b/doc/manual/src/command-ref/nix-daemon.md @@ -0,0 +1,15 @@ +Title: nix-daemon + +# Name + +`nix-daemon` - Nix multi-user support daemon + +# Synopsis + +`nix-daemon` + +# Description + +The Nix daemon is necessary in multi-user Nix installations. It performs +build actions and other operations on the Nix store on behalf of +unprivileged users. diff --git a/doc/manual/src/command-ref/nix-env.md b/doc/manual/src/command-ref/nix-env.md new file mode 100644 index 000000000..ee838581b --- /dev/null +++ b/doc/manual/src/command-ref/nix-env.md @@ -0,0 +1,882 @@ +Title: nix-env + +# Name + +`nix-env` - manipulate or query Nix user environments + +# Synopsis + +`nix-env` + [`--option` *name* *value*] + [`--arg` *name* *value*] + [`--argstr` *name* *value*] + [{`--file` | `-f`} *path*] + [{`--profile` | `-p`} *path(] + [`--system-filter` *system*] + [`--dry-run`] + *operation* [*options…*] [*arguments…*] + +# Description + +The command `nix-env` is used to manipulate Nix user environments. User +environments are sets of software packages available to a user at some +point in time. In other words, they are a synthesised view of the +programs available in the Nix store. There may be many user +environments: different users can have different environments, and +individual users can switch between different environments. + +`nix-env` takes exactly one *operation* flag which indicates the +subcommand to be performed. These are documented below. + +# Selectors + +Several commands, such as `nix-env -q` and `nix-env -i`, take a list of +arguments that specify the packages on which to operate. These are +extended regular expressions that must match the entire name of the +package. (For details on regular expressions, see regex7.) The match is +case-sensitive. The regular expression can optionally be followed by a +dash and a version number; if omitted, any version of the package will +match. Here are some examples: + + - `firefox` + Matches the package name `firefox` and any version. + + - `firefox-32.0` + Matches the package name `firefox` and version `32.0`. + + - `gtk\\+` + Matches the package name `gtk+`. The `+` character must be escaped + using a backslash to prevent it from being interpreted as a + quantifier, and the backslash must be escaped in turn with another + backslash to ensure that the shell passes it on. + + - `.\*` + Matches any package name. This is the default for most commands. + + - `'.*zip.*'` + Matches any package name containing the string `zip`. Note the dots: + `'*zip*'` does not work, because in a regular expression, the + character `*` is interpreted as a quantifier. + + - `'.*(firefox|chromium).*'` + Matches any package name containing the strings `firefox` or + `chromium`. + +# Common options + +This section lists the options that are common to all operations. These +options are allowed for every subcommand, though they may not always +have an effect. + + - `--file` / `-f` *path* + Specifies the Nix expression (designated below as the *active Nix + expression*) used by the `--install`, `--upgrade`, and `--query + --available` operations to obtain derivations. The default is + `~/.nix-defexpr`. + + If the argument starts with `http://` or `https://`, it is + interpreted as the URL of a tarball that will be downloaded and + unpacked to a temporary location. The tarball must include a single + top-level directory containing at least a file named `default.nix`. + + - `--profile` / `-p` *path* + Specifies the profile to be used by those operations that operate on + a profile (designated below as the *active profile*). A profile is a + sequence of user environments called *generations*, one of which is + the *current generation*. + + - `--dry-run` + For the `--install`, `--upgrade`, `--uninstall`, + `--switch-generation`, `--delete-generations` and `--rollback` + operations, this flag will cause `nix-env` to print what *would* be + done if this flag had not been specified, without actually doing it. + + `--dry-run` also prints out which paths will be + [substituted](../glossary.md) (i.e., downloaded) and which paths + will be built from source (because no substitute is available). + + - `--system-filter` *system* + By default, operations such as `--query + --available` show derivations matching any platform. This option + allows you to use derivations for the specified platform *system*. + + + +# Files + + - `~/.nix-defexpr` + The source for the default Nix expressions used by the + `--install`, `--upgrade`, and `--query --available` operations to + obtain derivations. The `--file` option may be used to override + this default. + + If `~/.nix-defexpr` is a file, it is loaded as a Nix expression. If + the expression is a set, it is used as the default Nix expression. + If the expression is a function, an empty set is passed as argument + and the return value is used as the default Nix expression. + + If `~/.nix-defexpr` is a directory containing a `default.nix` file, + that file is loaded as in the above paragraph. + + If `~/.nix-defexpr` is a directory without a `default.nix` file, + then its contents (both files and subdirectories) are loaded as Nix + expressions. The expressions are combined into a single set, each + expression under an attribute with the same name as the original + file or subdirectory. + + For example, if `~/.nix-defexpr` contains two files, `foo.nix` and + `bar.nix`, then the default Nix expression will essentially be + + ```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 + expressions, but the names of these intermediate directories are not + added to the attribute paths of the default Nix expression. + + The command `nix-channel` places symlinks to the downloaded Nix + expressions from each subscribed channel in this directory. + + - `~/.nix-profile` + A symbolic link to the user's current profile. By default, this + symlink points to `prefix/var/nix/profiles/default`. The `PATH` + environment variable should include `~/.nix-profile/bin` for the + user environment to be visible to the user. + +# Operation `--install` + +## Synopsis + +`nix-env` {`--install` | `-i`} *args…* + [{`--prebuilt-only` | `-b`}] + [{`--attr` | `-A`}] + [`--from-expression`] [`-E`] + [`--from-profile` *path*] + [`--preserve-installed` | `-P`] + [`--remove-all` | `-r`] + +## Description + +The install operation creates a new user environment, based on the +current generation of the active profile, to which a set of store paths +described by *args* is added. The arguments *args* map to store paths in +a number of possible ways: + + - By default, *args* is a set of derivation names denoting derivations + in the active Nix expression. These are realised, and the resulting + output paths are installed. Currently installed derivations with a + name equal to the name of a derivation being added are removed + unless the option `--preserve-installed` is specified. + + If there are multiple derivations matching a name in *args* that + have the same name (e.g., `gcc-3.3.6` and `gcc-4.1.1`), then the + derivation with the highest *priority* is used. A derivation can + define a priority by declaring the `meta.priority` attribute. This + attribute should be a number, with a higher value denoting a lower + priority. The default priority is `0`. + + If there are multiple matching derivations with the same priority, + then the derivation with the highest version will be installed. + + You can force the installation of multiple derivations with the same + name by being specific about the versions. For instance, `nix-env -i + gcc-3.3.6 gcc-4.1.1` will install both version of GCC (and will + probably cause a user environment conflict\!). + + - If `--attr` (`-A`) is specified, the arguments are *attribute + paths* that select attributes from the top-level Nix + expression. This is faster than using derivation names and + unambiguous. To find out the attribute paths of available + packages, use `nix-env -qaP`. + + - If `--from-profile` *path* is given, *args* is a set of names + denoting installed store paths in the profile *path*. This is an + easy way to copy user environment elements from one profile to + another. + + - If `--from-expression` is given, *args* are Nix + [functions](../expressions/language-constructs.md#functions) + that are called with the active Nix expression as their single + argument. The derivations returned by those function calls are + installed. This allows derivations to be specified in an + unambiguous way, which is necessary if there are multiple + derivations with the same name. + + - If *args* are store derivations, then these are + [realised](nix-store.md#operation---realise), and the resulting output paths + are installed. + + - If *args* are store paths that are not store derivations, then these + are [realised](nix-store.md#operation---realise) and installed. + + - By default all outputs are installed for each derivation. That can + be reduced by setting `meta.outputsToInstall`. + +## Flags + + - `--prebuilt-only` / `-b` + Use only derivations for which a substitute is registered, i.e., + there is a pre-built binary available that can be downloaded in lieu + of building the derivation. Thus, no packages will be built from + source. + + - `--preserve-installed`; `-P` + Do not remove derivations with a name matching one of the + derivations being installed. Usually, trying to have two versions of + the same package installed in the same generation of a profile will + lead to an error in building the generation, due to file name + clashes between the two versions. However, this is not the case for + all packages. + + - `--remove-all`; `-r` + Remove all previously installed packages first. This is equivalent + to running `nix-env -e '.*'` first, except that everything happens + in a single transaction. + +## Examples + +To install a specific version of `gcc` from the active Nix expression: + +```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: + +```console +$ nix-env --install gcc +installing `gcc-3.3.2' +``` + +To install using a specific attribute: + +```console +$ nix-env -i -A gcc40mips +$ nix-env -i -A xorg.xorgserver +``` + +To install all derivations in the Nix expression `foo.nix`: + +```console +$ nix-env -f ~/foo.nix -i '.*' +``` + +To copy the store path with symbolic name `gcc` from another profile: + +```console +$ nix-env -i --from-profile /nix/var/nix/profiles/foo gcc +``` + +To install a specific store derivation (typically created by +`nix-instantiate`): + +```console +$ nix-env -i /nix/store/fibjb1bfbpm5mrsxc4mh2d8n37sxh91i-gcc-3.4.3.drv +``` + +To install a specific output path: + +```console +$ nix-env -i /nix/store/y3cgx0xj1p4iv9x0pnnmdhr8iyg741vk-gcc-3.4.3 +``` + +To install from a Nix expression specified on the command-line: + +```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 +the `subversionWithJava` attribute from the set returned by calling the +function defined in `./foo.nix`. + +A dry-run tells you which paths will be downloaded or built from source: + +```console +$ nix-env -f '' -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: + +```console +$ nix-env -f https://github.com/NixOS/nixpkgs/archive/nixos-14.12.tar.gz -iA firefox +``` + +# Operation `--upgrade` + +## Synopsis + +`nix-env` {`--upgrade` | `-u`} *args* + [`--lt` | `--leq` | `--eq` | `--always`] + [{`--prebuilt-only` | `-b`}] + [{`--attr` | `-A`}] + [`--from-expression`] [`-E`] + [`--from-profile` *path*] + [`--preserve-installed` | `-P`] + +## Description + +The upgrade operation creates a new user environment, based on the +current generation of the active profile, in which all store paths are +replaced for which there are newer versions in the set of paths +described by *args*. Paths for which there are no newer versions are +left untouched; this is not an error. It is also not an error if an +element of *args* matches no installed derivations. + +For a description of how *args* is mapped to a set of store paths, see +[`--install`](#operation---install). If *args* describes multiple +store paths with the same symbolic name, only the one with the highest +version is installed. + +## Flags + + - `--lt` + Only upgrade a derivation to newer versions. This is the default. + + - `--leq` + In addition to upgrading to newer versions, also “upgrade” to + derivations that have the same version. Version are not a unique + identification of a derivation, so there may be many derivations + that have the same version. This flag may be useful to force + “synchronisation” between the installed and available derivations. + + - `--eq` + *Only* “upgrade” to derivations that have the same version. This may + not seem very useful, but it actually is, e.g., when there is a new + release of Nixpkgs and you want to replace installed applications + with the same versions built against newer dependencies (to reduce + the number of dependencies floating around on your system). + + - `--always` + In addition to upgrading to newer versions, also “upgrade” to + derivations that have the same or a lower version. I.e., derivations + may actually be downgraded depending on what is available in the + active Nix expression. + +For the other flags, see `--install`. + +## Examples + +```console +$ nix-env --upgrade gcc +upgrading `gcc-3.3.1' to `gcc-3.4' +``` + +```console +$ 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 --upgrade pan +(no upgrades available, so nothing happens) +``` + +```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 + +The upgrade operation determines whether a derivation `y` is an upgrade +of a derivation `x` by looking at their respective `name` attributes. +The names (e.g., `gcc-3.3.1` are split into two parts: the package name +(`gcc`), and the version (`3.3.1`). The version part starts after the +first dash not followed by a letter. `x` is considered an upgrade of `y` +if their package names match, and the version of `y` is higher that that +of `x`. + +The versions are compared by splitting them into contiguous components +of numbers and letters. E.g., `3.3.1pre5` is split into `[3, 3, 1, +"pre", 5]`. These lists are then compared lexicographically (from left +to right). Corresponding components `a` and `b` are compared as follows. +If they are both numbers, integer comparison is used. If `a` is an empty +string and `b` is a number, `a` is considered less than `b`. The special +string component `pre` (for *pre-release*) is considered to be less than +other components. String components are considered less than number +components. Otherwise, they are compared lexicographically (i.e., using +case-sensitive string comparison). + +This is illustrated by the following examples: + + 1.0 < 2.3 + 2.1 < 2.3 + 2.3 = 2.3 + 2.5 > 2.3 + 3.1 > 2.3 + 2.3.1 > 2.3 + 2.3.1 > 2.3a + 2.3pre1 < 2.3 + 2.3pre3 < 2.3pre12 + 2.3a < 2.3c + 2.3pre1 < 2.3c + 2.3pre1 < 2.3q + +# Operation `--uninstall` + +## Synopsis + +`nix-env` {`--uninstall` | `-e`} *drvnames…* + +## Description + +The uninstall operation creates a new user environment, based on the +current generation of the active profile, from which the store paths +designated by the symbolic names *drvnames* are removed. + +## Examples + +```console +$ nix-env --uninstall gcc +$ nix-env -e '.*' (remove everything) +``` + +# Operation `--set` + +## Synopsis + +`nix-env` `--set` *drvname* + +## Description + +The `--set` operation modifies the current generation of a profile so +that it contains exactly the specified derivation, and nothing else. + +## Examples + +The following updates a profile such that its current generation will +contain just Firefox: + +```console +$ nix-env -p /nix/var/nix/profiles/browser --set firefox +``` + +# Operation `--set-flag` + +## Synopsis + +`nix-env` `--set-flag` *name* *value* *drvnames* + +## Description + +The `--set-flag` operation allows meta attributes of installed packages +to be modified. There are several attributes that can be usefully +modified, because they affect the behaviour of `nix-env` or the user +environment build script: + + - `priority` can be changed to resolve filename clashes. The user + environment build script uses the `meta.priority` attribute of + derivations to resolve filename collisions between packages. Lower + priority values denote a higher priority. For instance, the GCC + wrapper package and the Binutils package in Nixpkgs both have a file + `bin/ld`, so previously if you tried to install both you would get a + collision. Now, on the other hand, the GCC wrapper declares a higher + priority than Binutils, so the former’s `bin/ld` is symlinked in the + user environment. + + - `keep` can be set to `true` to prevent the package from being + upgraded or replaced. This is useful if you want to hang on to an + older version of a package. + + - `active` can be set to `false` to “disable” the package. That is, no + symlinks will be generated to the files of the package, but it + remains part of the profile (so it won’t be garbage-collected). It + can be set back to `true` to re-enable the package. + +## Examples + +To prevent the currently installed Firefox from being upgraded: + +```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: + +```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., can’t have two active at the same time) + +$ 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 -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`: + +```console +$ nix-env --set-flag priority 5 binutils +$ nix-env --set-flag priority 10 gcc +``` + +# Operation `--query` + +## Synopsis + +`nix-env` {`--query` | `-q`} *names…* + [`--installed` | `--available` | `-a`] + [{`--status` | `-s`}] + [{`--attr-path` | `-P`}] + [`--no-name`] + [{`--compare-versions` | `-c`}] + [`--system`] + [`--drv-path`] + [`--out-path`] + [`--description`] + [`--meta`] + [`--xml`] + [`--json`] + [{`--prebuilt-only` | `-b`}] + [{`--attr` | `-A`} *attribute-path*] + +## Description + +The query operation displays information about either the store paths +that are installed in the current generation of the active profile +(`--installed`), or the derivations that are available for installation +in the active Nix expression (`--available`). It only prints information +about derivations whose symbolic name matches one of *names*. + +The derivations are sorted by their `name` attributes. + +## Source selection + +The following flags specify the set of things on which the query +operates. + + - `--installed` + The query operates on the store paths that are installed in the + current generation of the active profile. This is the default. + + - `--available`; `-a` + The query operates on the derivations that are available in the + active Nix expression. + +## Queries + +The following flags specify what information to display about the +selected derivations. Multiple flags may be specified, in which case the +information is shown in the order given here. Note that the name of the +derivation is shown unless `--no-name` is specified. + + - `--xml` + Print the result in an XML representation suitable for automatic + processing by other tools. The root element is called `items`, which + contains a `item` element for each available or installed + derivation. The fields discussed below are all stored in attributes + of the `item` elements. + + - `--json` + Print the result in a JSON representation suitable for automatic + processing by other tools. + + - `--prebuilt-only` / `-b` + Show only derivations for which a substitute is registered, i.e., + there is a pre-built binary available that can be downloaded in lieu + of building the derivation. Thus, this shows all packages that + probably can be installed quickly. + + - `--status`; `-s` + Print the *status* of the derivation. The status consists of three + characters. The first is `I` or `-`, indicating whether the + derivation is currently installed in the current generation of the + active profile. This is by definition the case for `--installed`, + but not for `--available`. The second is `P` or `-`, indicating + whether the derivation is present on the system. This indicates + whether installation of an available derivation will require the + derivation to be built. The third is `S` or `-`, indicating whether + a substitute is available for the derivation. + + - `--attr-path`; `-P` + Print the *attribute path* of the derivation, which can be used to + unambiguously select it using the `--attr` option available in + commands that install derivations like `nix-env --install`. This + option only works together with `--available` + + - `--no-name` + Suppress printing of the `name` attribute of each derivation. + + - `--compare-versions` / `-c` + Compare installed versions to available versions, or vice versa (if + `--available` is given). This is useful for quickly seeing whether + upgrades for installed packages are available in a Nix expression. A + column is added with the following meaning: + + - `<` *version* + A newer version of the package is available or installed. + + - `=` *version* + At most the same version of the package is available or + installed. + + - `>` *version* + Only older versions of the package are available or installed. + + - `- ?` + No version of the package is available or installed. + + - `--system` + Print the `system` attribute of the derivation. + + - `--drv-path` + Print the path of the store derivation. + + - `--out-path` + Print the output path of the derivation. + + - `--description` + Print a short (one-line) description of the derivation, if + available. The description is taken from the `meta.description` + attribute of the derivation. + + - `--meta` + Print all of the meta-attributes of the derivation. This option is + only available with `--xml` or `--json`. + +## Examples + +To show installed packages: + +```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: + +```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: + +```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`: + +```console +$ nix-env -f ./foo.nix -qa +foo-1.2.3 +``` + +To compare installed versions to what’s 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: + +```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: + +```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: + +```console +$ nix-env -f https://github.com/NixOS/nixpkgs/archive/master.tar.gz -qa +``` + +# Operation `--switch-profile` + +## Synopsis + +`nix-env` {`--switch-profile` | `-S`} *path* + +## Description + +This operation makes *path* the current profile for the user. That is, +the symlink `~/.nix-profile` is made to point to *path*. + +## Examples + +```console +$ nix-env -S ~/my-profile +``` + +# Operation `--list-generations` + +## Synopsis + +`nix-env` `--list-generations` + +## Description + +This operation print a list of all the currently existing generations +for the active profile. These may be switched to using the +`--switch-generation` operation. It also prints the creation date of the +generation, and indicates the current generation. + +## Examples + +```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` + +## Synopsis + +`nix-env` `--delete-generations` *generations* + +## Description + +This operation deletes the specified generations of the current profile. +The generations can be a list of generation numbers, the special value +`old` to delete all non-current generations, a value such as `30d` to +delete all generations older than the specified number of days (except +for the generation that was active at that point in time), or a value +such as `+5` to keep the last `5` generations ignoring any newer than +current, e.g., if `30` is the current generation `+5` will delete +generation `25` and all older generations. Periodically deleting old +generations is important to make garbage collection effective. + +## Examples + +```console +$ nix-env --delete-generations 3 4 8 +``` + +```console +$ nix-env --delete-generations +5 +``` + +```console +$ nix-env --delete-generations 30d +``` + +```console +$ nix-env -p other_profile --delete-generations old +``` + +# Operation `--switch-generation` + +## Synopsis + +`nix-env` {`--switch-generation` | `-G`} *generation* + +## Description + +This operation makes generation number *generation* the current +generation of the active profile. That is, if the `profile` is the path +to the active profile, then the symlink `profile` is made to point to +`profile-generation-link`, which is in turn a symlink to the actual user +environment in the Nix store. + +Switching will fail if the specified generation does not exist. + +## Examples + +```console +$ nix-env -G 42 +switching from generation 50 to 42 +``` + +# Operation `--rollback` + +## Synopsis + +`nix-env` `--rollback` + +## Description + +This operation switches to the “previous” generation of the active +profile, that is, the highest numbered generation lower than the current +generation, if it exists. It is just a convenience wrapper around +`--list-generations` and `--switch-generation`. + +## Examples + +```console +$ nix-env --rollback +switching from generation 92 to 91 +``` + +```console +$ nix-env --rollback +error: no generation older than the current (91) exists +``` + +# Environment variables + + - `NIX_PROFILE` + Location of the Nix profile. Defaults to the target of the symlink + `~/.nix-profile`, if it exists, or `/nix/var/nix/profiles/default` + otherwise. diff --git a/doc/manual/src/command-ref/nix-hash.md b/doc/manual/src/command-ref/nix-hash.md new file mode 100644 index 000000000..d3f91f8e9 --- /dev/null +++ b/doc/manual/src/command-ref/nix-hash.md @@ -0,0 +1,104 @@ +Title: nix-hash + +# Name + +`nix-hash` - compute the cryptographic hash of a path + +# Synopsis + +`nix-hash` [`--flat`] [`--base32`] [`--truncate`] [`--type` *hashAlgo*] *path…* + +`nix-hash` `--to-base16` *hash…* + +`nix-hash` `--to-base32` *hash…* + +# Description + +The command `nix-hash` computes the cryptographic hash of the contents +of each *path* and prints it on standard output. By default, it computes +an MD5 hash, but other hash algorithms are available as well. The hash +is printed in hexadecimal. To generate the same hash as +`nix-prefetch-url` you have to specify multiple arguments, see below for +an example. + +The hash is computed over a *serialisation* of each path: a dump of +the file system tree rooted at the path. This allows directories and +symlinks to be hashed as well as regular files. The dump is in the +*NAR format* produced by [`nix-store +--dump`](nix-store.md#operation---dump). Thus, `nix-hash path` +yields the same cryptographic hash as `nix-store --dump path | +md5sum`. + +# Options + + - `--flat` + Print the cryptographic hash of the contents of each regular file + *path*. That is, do not compute the hash over the dump of *path*. + The result is identical to that produced by the GNU commands + `md5sum` and `sha1sum`. + + - `--base32` + Print the hash in a base-32 representation rather than hexadecimal. + This base-32 representation is more compact and can be used in Nix + expressions (such as in calls to `fetchurl`). + + - `--truncate` + Truncate hashes longer than 160 bits (such as SHA-256) to 160 bits. + + - `--type` *hashAlgo* + Use the specified cryptographic hash algorithm, which can be one of + `md5`, `sha1`, and `sha256`. + + - `--to-base16` + Don’t hash anything, but convert the base-32 hash representation + *hash* to hexadecimal. + + - `--to-base32` + Don’t hash anything, but convert the hexadecimal hash representation + *hash* to base-32. + +# Examples + +Computing the same hash as `nix-prefetch-url`: + +```console +$ nix-prefetch-url file://<(echo test) +1lkgqb6fclns49861dwk9rzb6xnfkxbpws74mxnx01z9qyv1pjpj +$ nix-hash --type sha256 --flat --base32 <(echo test) +1lkgqb6fclns49861dwk9rzb6xnfkxbpws74mxnx01z9qyv1pjpj +``` + +Computing hashes: + +```console +$ mkdir test +$ echo "hello" > test/world + +$ nix-hash test/ (MD5 hash; default) +8179d3caeff1869b5ba1744e5a245c04 + +$ nix-store --dump test/ | md5sum (for comparison) +8179d3caeff1869b5ba1744e5a245c04 - + +$ nix-hash --type sha1 test/ +e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6 + +$ 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/world +5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03 +``` + +Converting between hexadecimal and base-32: + +```console +$ nix-hash --type sha1 --to-base32 e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6 +nvd61k9nalji1zl9rrdfmsmvyyjqpzg4 + +$ nix-hash --type sha1 --to-base16 nvd61k9nalji1zl9rrdfmsmvyyjqpzg4 +e4fd8ba5f7bbeaea5ace89fe10255536cd60dab6 +``` diff --git a/doc/manual/src/command-ref/nix-instantiate.md b/doc/manual/src/command-ref/nix-instantiate.md new file mode 100644 index 000000000..d09f5ed6a --- /dev/null +++ b/doc/manual/src/command-ref/nix-instantiate.md @@ -0,0 +1,160 @@ +Title: nix-instantiate + +# Name + +`nix-instantiate` - instantiate store derivations from Nix expressions + +# Synopsis + +`nix-instantiate` + [`--parse` | `--eval` [`--strict`] [`--json`] [`--xml`] ] + [`--read-write-mode`] + [`--arg` *name* *value*] + [{`--attr`| `-A`} *attrPath*] + [`--add-root` *path*] + [`--expr` | `-E`] + *files…* + +`nix-instantiate` `--find-file` *files…* + +# Description + +The command `nix-instantiate` generates [store +derivations](../glossary.md) from (high-level) Nix expressions. It +evaluates the Nix expressions in each of *files* (which defaults to +*./default.nix*). Each top-level expression should evaluate to a +derivation, a list of derivations, or a set of derivations. The paths +of the resulting store derivations are printed on standard output. + +If *files* is the character `-`, then a Nix expression will be read from +standard input. + +# Options + + - `--add-root` *path* + See the [corresponding option](nix-store.md) in `nix-store`. + + - `--parse` + Just parse the input files, and print their abstract syntax trees on + standard output in ATerm format. + + - `--eval` + Just parse and evaluate the input files, and print the resulting + values on standard output. No instantiation of store derivations + takes place. + + - `--find-file` + Look up the given files in Nix’s search path (as specified by the + `NIX_PATH` environment variable). If found, print the corresponding + absolute paths on standard output. For instance, if `NIX_PATH` is + `nixpkgs=/home/alice/nixpkgs`, then `nix-instantiate --find-file + nixpkgs/default.nix` will print `/home/alice/nixpkgs/default.nix`. + + - `--strict` + When used with `--eval`, recursively evaluate list elements and + attributes. Normally, such sub-expressions are left unevaluated + (since the Nix expression language is lazy). + + > **Warning** + > + > This option can cause non-termination, because lazy data + > structures can be infinitely large. + + - `--json` + When used with `--eval`, print the resulting value as an JSON + representation of the abstract syntax tree rather than as an ATerm. + + - `--xml` + When used with `--eval`, print the resulting value as an XML + representation of the abstract syntax tree rather than as an ATerm. + The schema is the same as that used by the [`toXML` + built-in](../expressions/builtins.md). + + - `--read-write-mode` + When used with `--eval`, perform evaluation in read/write mode so + nix language features that require it will still work (at the cost + of needing to do instantiation of every evaluated derivation). If + this option is not enabled, there may be uninstantiated store paths + in the final output. + + + +# Examples + +Instantiating store derivations from a Nix expression, and building them +using `nix-store`: + +```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) + +$ 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: + +```console +$ nix-instantiate -E 'with import { }; hello' +/nix/store/j8s4zyv75a724q38cb0r87rlczaiag4y-hello-2.8.drv +``` + +This is equivalent to: + +```console +$ nix-instantiate '' -A hello +``` + +Parsing and evaluating Nix expressions: + +```console +$ nix-instantiate --parse -E '1 + 2' +1 + 2 +``` + +```console +$ nix-instantiate --eval -E '1 + 2' +3 +``` + +```console +$ nix-instantiate --eval --xml -E '1 + 2' + + + + +``` + +The difference between non-strict and strict evaluation: + +```console +$ nix-instantiate --eval --xml -E 'rec { x = "foo"; y = x; }' +... + + + + + + +... +``` + +Note that `y` is left unevaluated (the XML representation doesn’t +attempt to show non-normal forms). + +```console +$ nix-instantiate --eval --xml --strict -E 'rec { x = "foo"; y = x; }' +... + + + + + + +... +``` diff --git a/doc/manual/src/command-ref/nix-prefetch-url.md b/doc/manual/src/command-ref/nix-prefetch-url.md new file mode 100644 index 000000000..1307c7c37 --- /dev/null +++ b/doc/manual/src/command-ref/nix-prefetch-url.md @@ -0,0 +1,80 @@ +Title: nix-prefetch-url + +# Name + +`nix-prefetch-url` - copy a file from a URL into the store and print its hash + +# Synopsis + +`nix-prefetch-url` *url* [*hash*] + [`--type` *hashAlgo*] + [`--print-path`] + [`--unpack`] + [`--name` *name*] + +# Description + +The command `nix-prefetch-url` downloads the file referenced by the URL +*url*, prints its cryptographic hash, and copies it into the Nix store. +The file name in the store is `hash-baseName`, where *baseName* is +everything following the final slash in *url*. + +This command is just a convenience for Nix expression writers. Often a +Nix expression fetches some source distribution from the network using +the `fetchurl` expression contained in Nixpkgs. However, `fetchurl` +requires a cryptographic hash. If you don't know the hash, you would +have to download the file first, and then `fetchurl` would download it +again when you build your Nix expression. Since `fetchurl` uses the same +name for the downloaded file as `nix-prefetch-url`, the redundant +download can be avoided. + +If *hash* is specified, then a download is not performed if the Nix +store already contains a file with the same hash and base name. +Otherwise, the file is downloaded, and an error is signaled if the +actual hash of the file does not match the specified hash. + +This command prints the hash on standard output. Additionally, if the +option `--print-path` is used, the path of the downloaded file in the +Nix store is also printed. + +# Options + + - `--type` *hashAlgo* + Use the specified cryptographic hash algorithm, which can be one of + `md5`, `sha1`, and `sha256`. + + - `--print-path` + Print the store path of the downloaded file on standard output. + + - `--unpack` + Unpack the archive (which must be a tarball or zip file) and add the + result to the Nix store. The resulting hash can be used with + functions such as Nixpkgs’s `fetchzip` or `fetchFromGitHub`. + + - `--executable` + Set the executable bit on the downloaded file. + + - `--name` *name* + Override the name of the file in the Nix store. By default, this is + `hash-basename`, where *basename* is the last component of *url*. + Overriding the name is necessary when *basename* contains characters + that are not allowed in Nix store paths. + +# Examples + +```console +$ nix-prefetch-url ftp://ftp.gnu.org/pub/gnu/hello/hello-2.10.tar.gz +0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i +``` + +```console +$ 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 --unpack --print-path https://github.com/NixOS/patchelf/archive/0.8.tar.gz +079agjlv0hrv7fxnx9ngipx14gyncbkllxrp9cccnh3a50fxcmy7 +/nix/store/19zrmhm3m40xxaw81c8cqm6aljgrnwj2-0.8.tar.gz +``` diff --git a/doc/manual/src/command-ref/nix-shell.md b/doc/manual/src/command-ref/nix-shell.md new file mode 100644 index 000000000..fc42a202a --- /dev/null +++ b/doc/manual/src/command-ref/nix-shell.md @@ -0,0 +1,276 @@ +Title: nix-shell + +# Name + +`nix-shell` - start an interactive shell based on a Nix expression + +# Synopsis + +`nix-shell` + [`--arg` *name* *value*] + [`--argstr` *name* *value*] + [{`--attr` | `-A`} *attrPath*] + [`--command` *cmd*] + [`--run` *cmd*] + [`--exclude` *regexp*] + [--pure] + [--keep *name*] + {{`--packages` | `-p`} {*packages* | *expressions*} … | [*path*]} + +# Description + +The command `nix-shell` will build the dependencies of the specified +derivation, but not the derivation itself. It will then start an +interactive shell in which all environment variables defined by the +derivation *path* have been set to their corresponding values, and the +script `$stdenv/setup` has been sourced. This is useful for reproducing +the environment of a derivation for development. + +If *path* is not given, `nix-shell` defaults to `shell.nix` if it +exists, and `default.nix` otherwise. + +If *path* starts with `http://` or `https://`, it is interpreted as the +URL of a tarball that will be downloaded and unpacked to a temporary +location. The tarball must include a single top-level directory +containing at least a file named `default.nix`. + +If the derivation defines the variable `shellHook`, it will be evaluated +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 + +```nix +shellHook = + '' + echo "Hello shell" + ''; +``` + +will cause `nix-shell` to print `Hello shell`. + +# Options + +All options not listed here are passed to `nix-store +--realise`, except for `--arg` and `--attr` / `-A` which are passed to +`nix-instantiate`. + + - `--command` *cmd* + In the environment of the derivation, run the shell command *cmd*. + This command is executed in an interactive shell. (Use `--run` to + use a non-interactive shell instead.) However, a call to `exit` is + implicitly added to the command, so the shell will exit after + running the command. To prevent this, add `return` at the end; + e.g. `--command "echo Hello; return"` will print `Hello` and then + drop you into the interactive shell. This can be useful for doing + any additional initialisation. + + - `--run` *cmd* + Like `--command`, but executes the command in a non-interactive + shell. This means (among other things) that if you hit Ctrl-C while + the command is running, the shell exits. + + - `--exclude` *regexp* + Do not build any dependencies whose store path matches the regular + expression *regexp*. This option may be specified multiple times. + + - `--pure` + If this flag is specified, the environment is almost entirely + cleared before the interactive shell is started, so you get an + environment that more closely corresponds to the “real” Nix build. A + few variables, in particular `HOME`, `USER` and `DISPLAY`, are + retained. Note that `~/.bashrc` and (depending on your Bash + installation) `/etc/bashrc` are still sourced, so any variables set + there will affect the interactive shell. + + - `--packages` / `-p` *packages*… + Set up an environment in which the specified packages are present. + The command line arguments are interpreted as attribute names inside + the Nix Packages collection. Thus, `nix-shell -p libjpeg openjdk` + will start a shell in which the packages denoted by the attribute + names `libjpeg` and `openjdk` are present. + + - `-i` *interpreter* + The chained script interpreter to be invoked by `nix-shell`. Only + applicable in `#!`-scripts (described below). + + - `--keep` *name* + When a `--pure` shell is started, keep the listed environment + variables. + +The following common options are supported: + +# Environment variables + + - `NIX_BUILD_SHELL` + Shell used to start the interactive environment. Defaults to the + `bash` found in `PATH`. + +# Examples + +To build the dependencies of the package Pan, and start an interactive +shell in which to build it: + +```console +$ nix-shell '' -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: + +```console +$ nix-shell '' -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`: + +```console +$ nix-shell -E 'with import { }; runCommand "dummy" { buildInputs = [ sqlite xorg.libX11 ]; } ""' +``` + +A shorter way to do the same is: + +```console +$ 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: + +```console +$ 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: + +```console +$ nix-shell -p pan -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/8a3eea054838b55aca962c3fbde9c83c102b8bf2.tar.gz + +[nix-shell:~]$ pan --version +Pan 0.139 +``` + +# Use as a `#!`-interpreter + +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: + +```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 +initialised the environment, and *packages* are the attribute names of +the dependencies in Nixpkgs. + +The lines starting with `#! nix-shell` specify `nix-shell` options (see +above). Note that you cannot write `#! /usr/bin/env nix-shell -i ...` +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: + +```python +#! /usr/bin/env nix-shell +#! nix-shell -i python -p python pythonPackages.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 +``` + +Similarly, the following is a Perl script that specifies that it +requires Perl and the `HTML::TokeParser::Simple` and `LWP` packages: + +```perl +#! /usr/bin/env nix-shell +#! nix-shell -i perl -p perl perlPackages.HTMLTokeParserSimple perlPackages.LWP + +use HTML::TokeParser::Simple; + +# 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; +} +``` + +Sometimes you need to pass a simple Nix expression to customize a +package like Terraform: + +```bash +#! /usr/bin/env nix-shell +#! nix-shell -i bash -p "terraform.withPlugins (plugins: [ plugins.openstack ])" + +terraform apply +``` + +> **Note** +> +> You must use double quotes (`"`) when passing a simple Nix expression +> in a nix-shell shebang. + +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): + +```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 + +-- 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: + + #! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/0672315759b3e15e2121365f067c1c8c56bb4722.tar.gz + +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: + +```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: + +```nix +with import {}; + +runCommand "dummy" { buildInputs = [ python pythonPackages.prettytable ]; } "" +``` diff --git a/doc/manual/src/command-ref/nix-store.md b/doc/manual/src/command-ref/nix-store.md new file mode 100644 index 000000000..4680339e4 --- /dev/null +++ b/doc/manual/src/command-ref/nix-store.md @@ -0,0 +1,835 @@ +Title: nix-store + +# Name + +`nix-store` - manipulate or query the Nix store + +# Synopsis + +`nix-store` *operation* [*options…*] [*arguments…*] + [`--option` *name* *value*] + [`--add-root` *path*] + +# Description + +The command `nix-store` performs primitive operations on the Nix store. +You generally do not need to run this command manually. + +`nix-store` takes exactly one *operation* flag which indicates the +subcommand to be performed. These are documented below. + +# Common options + +This section lists the options that are common to all operations. These +options are allowed for every subcommand, though they may not always +have an effect. + + - `--add-root` *path* + Causes the result of a realisation (`--realise` and + `--force-realise`) to be registered as a root of the garbage + collector. *path* will be created as a symlink to the resulting + store path. In addition, a uniquely named symlink to *path* will + be created in `/nix/var/nix/gcroots/auto/`. For instance, + + ```console + $ nix-store --add-root /home/eelco/bla/result -r ... + + $ 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 + ``` + + Thus, when `/home/eelco/bla/result` is removed, the GC root in the + `auto` directory becomes a dangling symlink and will be ignored by + the collector. + + > **Warning** + > + > Note that it is not possible to move or rename GC roots, since + > the symlink in the `auto` directory will still point to the old + > location. + + If there are multiple results, then multiple symlinks will be + created by sequentially numbering symlinks beyond the first one + (e.g., `foo`, `foo-2`, `foo-3`, and so on). + +# Operation `--realise` + +## Synopsis + +`nix-store` {`--realise` | `-r`} *paths…* [`--dry-run`] + +## Description + +The operation `--realise` essentially “builds” the specified store +paths. Realisation is a somewhat overloaded term: + + - If the store path is a *derivation*, realisation ensures that the + output paths of the derivation are [valid](../glossary.md) (i.e., + the output path and its closure exist in the file system). This + can be done in several ways. First, it is possible that the + outputs are already valid, in which case we are done + immediately. Otherwise, there may be [substitutes](../glossary.md) + that produce the outputs (e.g., by downloading them). Finally, the + outputs can be produced by performing the build action described + by the derivation. + + - If the store path is not a derivation, realisation ensures that the + specified path is valid (i.e., it and its closure exist in the file + system). If the path is already valid, we are done immediately. + Otherwise, the path and any missing paths in its closure may be + produced through substitutes. If there are no (successful) + subsitutes, realisation fails. + +The output path of each derivation is printed on standard output. (For +non-derivations argument, the argument itself is printed.) + +The following flags are available: + + - `--dry-run` + Print on standard error a description of what packages would be + built or downloaded, without actually performing the operation. + + - `--ignore-unknown` + If a non-derivation path does not have a substitute, then silently + ignore it. + + - `--check` + This option allows you to check whether a derivation is + deterministic. It rebuilds the specified derivation and checks + whether the result is bitwise-identical with the existing outputs, + printing an error if that’s not the case. The outputs of the + specified derivation must already exist. When used with `-K`, if an + output path is not identical to the corresponding output from the + previous build, the new output path is left in + `/nix/store/name.check.` + + See also the `build-repeat` configuration option, which repeats a + derivation a number of times and prevents its outputs from being + registered as “valid” in the Nix store unless they are identical. + +Special exit codes: + + - `100` + Generic build failure, the builder process returned with a non-zero + exit code. + + - `101` + Build timeout, the build was aborted because it did not complete + within the specified `timeout`. + + - `102` + Hash mismatch, the build output was rejected because it does not + match the [`outputHash` attribute of the + derivation](../expressions/advanced-attributes.md). + + - `104` + Not deterministic, the build succeeded in check mode but the + resulting output is not binary reproducable. + +With the `--keep-going` flag it's possible for multiple failures to +occur, in this case the 1xx status codes are or combined using binary +or. + + 1100100 + ^^^^ + |||`- timeout + ||`-- output hash mismatch + |`--- build failure + `---- not deterministic + +## Examples + +This operation is typically used to build store derivations produced by +[`nix-instantiate`](nix-instantiate.md): + +```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: + +```console +$ nix-build '' -A hello --check -K +``` + +# Operation `--serve` + +## Synopsis + +`nix-store` `--serve` [`--write`] + +## Description + +The operation `--serve` provides access to the Nix store over stdin and +stdout, and is intended to be used as a means of providing Nix store +access to a restricted ssh user. + +The following flags are available: + + - `--write` + Allow the connected client to request the realization of + derivations. In effect, this can be used to make the host act as a + remote builder. + +## Examples + +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: + +```console +$ cat <>/root/.ssh/authorized_keys +command="nice -n20 nix-store --serve --write" ssh-rsa AAAAB3NzaC1yc2EAAAA... +EOF +``` + +# Operation `--gc` + +## Synopsis + +`nix-store` `--gc` [`--print-roots` | `--print-live` | `--print-dead`] [`--max-freed` *bytes*] + +## Description + +Without additional flags, the operation `--gc` performs a garbage +collection on the Nix store. That is, all paths in the Nix store not +reachable via file system references from a set of “roots”, are deleted. + +The following suboperations may be specified: + + - `--print-roots` + This operation prints on standard output the set of roots used by + the garbage collector. + + - `--print-live` + This operation prints on standard output the set of “live” store + paths, which are all the store paths reachable from the roots. Live + paths should never be deleted, since that would break consistency — + it would become possible that applications are installed that + reference things that are no longer present in the store. + + - `--print-dead` + This operation prints out on standard output the set of “dead” store + paths, which is just the opposite of the set of live paths: any path + in the store that is not live (with respect to the roots) is dead. + +By default, all unreachable paths are deleted. The following options +control what gets deleted and in what order: + + - `--max-freed` *bytes* + Keep deleting paths until at least *bytes* bytes have been deleted, + then stop. The argument *bytes* can be followed by the + multiplicative suffix `K`, `M`, `G` or `T`, denoting KiB, MiB, GiB + or TiB units. + +The behaviour of the collector is also influenced by the +`keep-outputs` and `keep-derivations` variables in the Nix +configuration file. + +By default, the collector prints the total number of freed bytes when it +finishes (or when it is interrupted). With `--print-dead`, it prints the +number of bytes that would be freed. + +## Examples + +To delete all unreachable paths, just do: + +```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: + +```console +$ nix-store --gc --max-freed $((100 * 1024 * 1024)) +``` + +# Operation `--delete` + +## Synopsis + +`nix-store` `--delete` [`--ignore-liveness`] *paths…* + +## Description + +The operation `--delete` deletes the store paths *paths* from the Nix +store, but only if it is safe to do so; that is, when the path is not +reachable from a root of the garbage collector. This means that you can +only delete paths that would also be deleted by `nix-store --gc`. Thus, +`--delete` is a more targeted version of `--gc`. + +With the option `--ignore-liveness`, reachability from the roots is +ignored. However, the path still won’t be deleted if there are other +paths in the store that refer to it (i.e., depend on it). + +## Example + +```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` + +## Synopsis + +`nix-store` {`--query` | `-q`} + {`--outputs` | `--requisites` | `-R` | `--references` | + `--referrers` | `--referrers-closure` | `--deriver` | `-d` | + `--graph` | `--tree` | `--binding` *name* | `-b` *name* | `--hash` | + `--size` | `--roots`} + [`--use-output`] [`-u`] [`--force-realise`] [`-f`] + *paths…* + +## Description + +The operation `--query` displays various bits of information about the +store paths . The queries are described below. At most one query can be +specified. The default query is `--outputs`. + +The paths *paths* may also be symlinks from outside of the Nix store, to +the Nix store. In that case, the query is applied to the target of the +symlink. + +## Common query options + + - `--use-output`; `-u` + For each argument to the query that is a store derivation, apply the + query to the output path of the derivation instead. + + - `--force-realise`; `-f` + Realise each argument to the query first (see [`nix-store + --realise`](#operation---realise)). + +## Queries + + - `--outputs` + Prints out the [output paths](../glossary.md) of the store + derivations *paths*. These are the paths that will be produced when + the derivation is built. + + - `--requisites`; `-R` + Prints out the [closure](../glossary.md) of the store path *paths*. + + This query has one option: + + - `--include-outputs` + Also include the output path of store derivations, and their + closures. + + This query can be used to implement various kinds of deployment. A + *source deployment* is obtained by distributing the closure of a + store derivation. A *binary deployment* is obtained by distributing + the closure of an output path. A *cache deployment* (combined + source/binary deployment, including binaries of build-time-only + dependencies) is obtained by distributing the closure of a store + derivation and specifying the option `--include-outputs`. + + - `--references` + Prints the set of [references](../glossary.md) of the store paths + *paths*, that is, their immediate dependencies. (For *all* + dependencies, use `--requisites`.) + + - `--referrers` + Prints the set of *referrers* of the store paths *paths*, that is, + the store paths currently existing in the Nix store that refer to + one of *paths*. Note that contrary to the references, the set of + referrers is not constant; it can change as store paths are added or + removed. + + - `--referrers-closure` + Prints the closure of the set of store paths *paths* under the + referrers relation; that is, all store paths that directly or + indirectly refer to one of *paths*. These are all the path currently + in the Nix store that are dependent on *paths*. + + - `--deriver`; `-d` + Prints the [deriver](../glossary.md) of the store paths *paths*. If + the path has no deriver (e.g., if it is a source file), or if the + deriver is not known (e.g., in the case of a binary-only + deployment), the string `unknown-deriver` is printed. + + - `--graph` + Prints the references graph of the store paths *paths* in the format + of the `dot` tool of AT\&T's [Graphviz + package](http://www.graphviz.org/). This can be used to visualise + dependency graphs. To obtain a build-time dependency graph, apply + this to a store derivation. To obtain a runtime dependency graph, + apply it to an output path. + + - `--tree` + Prints the references graph of the store paths *paths* as a nested + ASCII tree. References are ordered by descending closure size; this + tends to flatten the tree, making it more readable. The query only + recurses into a store path when it is first encountered; this + prevents a blowup of the tree representation of the graph. + + - `--graphml` + Prints the references graph of the store paths *paths* in the + [GraphML](http://graphml.graphdrawing.org/) file format. This can be + used to visualise dependency graphs. To obtain a build-time + dependency graph, apply this to a store derivation. To obtain a + runtime dependency graph, apply it to an output path. + + - `--binding` *name*; `-b` *name* + Prints the value of the attribute *name* (i.e., environment + variable) of the store derivations *paths*. It is an error for a + derivation to not have the specified attribute. + + - `--hash` + Prints the SHA-256 hash of the contents of the store paths *paths* + (that is, the hash of the output of `nix-store --dump` on the given + paths). Since the hash is stored in the Nix database, this is a fast + operation. + + - `--size` + Prints the size in bytes of the contents of the store paths *paths* + — to be precise, the size of the output of `nix-store --dump` on + the given paths. Note that the actual disk space required by the + store paths may be higher, especially on filesystems with large + cluster sizes. + + - `--roots` + Prints the garbage collector roots that point, directly or + indirectly, at the store paths *paths*. + +## Examples + +Print the closure (runtime dependencies) of the `svn` program in the +current user environment: + +```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`: + +```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 +`svn`. + +Show the build-time dependencies as a tree: + +```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`: + +```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`: + +```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. + +Make a picture of the runtime dependency graph of the current user +environment: + +```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`: + +```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` + +## Synopsis + +`nix-store` `--add` *paths…* + +## Description + +The operation `--add` adds the specified paths to the Nix store. It +prints the resulting paths in the Nix store on standard output. + +## Example + +```console +$ nix-store --add ./foo.c +/nix/store/m7lrha58ph6rcnv109yzx1nk1cj7k7zf-foo.c +``` + +# Operation `--add-fixed` + +## Synopsis + +`nix-store` `--add-fixed` [`--recursive`] *algorithm* *paths…* + +## Description + +The operation `--add-fixed` adds the specified paths to the Nix store. +Unlike `--add` paths are registered using the specified hashing +algorithm, resulting in the same output path as a fixed-output +derivation. This can be used for sources that are not available from a +public url or broke since the download expression was written. + +This operation has the following options: + + - `--recursive` + Use recursive instead of flat hashing mode, used when adding + directories to the store. + +## Example + +```console +$ nix-store --add-fixed sha256 ./hello-2.10.tar.gz +/nix/store/3x7dwzq014bblazs7kq20p9hyzz0qh8g-hello-2.10.tar.gz +``` + +# Operation `--verify` + +## Synopsis + +`nix-store` `--verify` [`--check-contents`] [`--repair`] + +## Description + +The operation `--verify` verifies the internal consistency of the Nix +database, and the consistency between the Nix database and the Nix +store. Any inconsistencies encountered are automatically repaired. +Inconsistencies are generally the result of the Nix store or database +being modified by non-Nix tools, or of bugs in Nix itself. + +This operation has the following options: + + - `--check-contents` + Checks that the contents of every valid store path has not been + altered by computing a SHA-256 hash of the contents and comparing it + with the hash stored in the Nix database at build time. Paths that + have been modified are printed out. For large stores, + `--check-contents` is obviously quite slow. + + - `--repair` + If any valid path is missing from the store, or (if + `--check-contents` is given) the contents of a valid path has been + modified, then try to repair the path by redownloading it. See + `nix-store --repair-path` for details. + +# Operation `--verify-path` + +## Synopsis + +`nix-store` `--verify-path` *paths…* + +## Description + +The operation `--verify-path` compares the contents of the given store +paths to their cryptographic hashes stored in Nix’s database. For every +changed path, it prints a warning message. The exit status is 0 if no +path has changed, and 1 otherwise. + +## Example + +To verify the integrity of the `svn` command and all its dependencies: + +```console +$ nix-store --verify-path $(nix-store -qR $(which svn)) +``` + +# Operation `--repair-path` + +## Synopsis + +`nix-store` `--repair-path` *paths…* + +## Description + +The operation `--repair-path` attempts to “repair” the specified paths +by redownloading them using the available substituters. If no +substitutes are available, then repair is not possible. + +> **Warning** +> +> During repair, there is a very small time window during which the old +> path (if it exists) is moved out of the way and replaced with the new +> path. If repair is interrupted in between, then the system may be left +> in a broken state (e.g., if the path contains a critical system +> component like the GNU C Library). + +## Example + +```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'... +… +``` + +# Operation `--dump` + +## Synopsis + +`nix-store` `--dump` *path* + +## Description + +The operation `--dump` produces a NAR (Nix ARchive) file containing the +contents of the file system tree rooted at *path*. The archive is +written to standard output. + +A NAR archive is like a TAR or Zip archive, but it contains only the +information that Nix considers important. For instance, timestamps are +elided because all files in the Nix store have their timestamp set to 0 +anyway. Likewise, all permissions are left out except for the execute +bit, because all files in the Nix store have 444 or 555 permission. + +Also, a NAR archive is *canonical*, meaning that “equal” paths always +produce the same NAR archive. For instance, directory entries are +always sorted so that the actual on-disk order doesn’t influence the +result. This means that the cryptographic hash of a NAR dump of a +path is usable as a fingerprint of the contents of the path. Indeed, +the hashes of store paths stored in Nix’s database (see `nix-store -q +--hash`) are SHA-256 hashes of the NAR dump of each store path. + +NAR archives support filenames of unlimited length and 64-bit file +sizes. They can contain regular files, directories, and symbolic links, +but not other types of files (such as device nodes). + +A Nix archive can be unpacked using `nix-store +--restore`. + +# Operation `--restore` + +## Synopsis + +`nix-store` `--restore` *path* + +## Description + +The operation `--restore` unpacks a NAR archive to *path*, which must +not already exist. The archive is read from standard input. + +# Operation `--export` + +## Synopsis + +`nix-store` `--export` *paths…* + +## Description + +The operation `--export` writes a serialisation of the specified store +paths to standard output in a format that can be imported into another +Nix store with `nix-store --import`. This is like `nix-store +--dump`, except that the NAR archive produced by that command doesn’t +contain the necessary meta-information to allow it to be imported into +another Nix store (namely, the set of references of the path). + +This command does not produce a *closure* of the specified paths, so if +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: + +```console +$ nix-store --export $(nix-store -qR paths) > out +``` + +To import the whole closure again, run: + +```console +$ nix-store --import < out +``` + +# Operation `--import` + +## Synopsis + +`nix-store` `--import` + +## Description + +The operation `--import` reads a serialisation of a set of store paths +produced by `nix-store --export` from standard input and adds those +store paths to the Nix store. Paths that already exist in the Nix store +are ignored. If a path refers to another path that doesn’t exist in the +Nix store, the import fails. + +# Operation `--optimise` + +## Synopsis + +`nix-store` `--optimise` + +## Description + +The operation `--optimise` reduces Nix store disk space usage by finding +identical files in the store and hard-linking them to each other. It +typically reduces the size of the store by something like 25-35%. Only +regular files and symlinks are hard-linked in this manner. Files are +considered identical when they have the same NAR archive serialisation: +that is, regular files must have the same contents and permission +(executable or non-executable), and symlinks must have the same +contents. + +After completion, or when the command is interrupted, a report on the +achieved savings is printed on standard error. + +Use `-vv` or `-vvv` to get some progress indication. + +## Example + +```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` + +## Synopsis + +`nix-store` {`--read-log` | `-l`} *paths…* + +## Description + +The operation `--read-log` prints the build log of the specified store +paths on standard output. The build log is whatever the builder of a +derivation wrote to standard output and standard error. If a store path +is not a derivation, the deriver of the store path is used. + +Build logs are kept in `/nix/var/log/nix/drvs`. However, there is no +guarantee that a build log is available for any particular store path. +For instance, if the path was downloaded as a pre-built binary through a +substitute, then the log is unavailable. + +## Example + +```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` + +## Synopsis + +`nix-store` `--dump-db` [*paths…*] + +## Description + +The operation `--dump-db` writes a dump of the Nix database to standard +output. It can be loaded into an empty Nix store using `--load-db`. This +is useful for making backups and when migrating to different database +schemas. + +By default, `--dump-db` will dump the entire Nix database. When one or +more store paths is passed, only the subset of the Nix database for +those store paths is dumped. As with `--export`, the user is responsible +for passing all the store paths for a closure. See `--export` for an +example. + +# Operation `--load-db` + +## Synopsis + +`nix-store` `--load-db` + +## Description + +The operation `--load-db` reads a dump of the Nix database created by +`--dump-db` from standard input and loads it into the Nix database. + +# Operation `--print-env` + +## Synopsis + +`nix-store` `--print-env` *drvpath* + +## Description + +The operation `--print-env` prints out the environment of a derivation +in a format that can be evaluated by a shell. The command line arguments +of the builder are placed in the variable `_args`. + +## Example + +```console +$ nix-store --print-env $(nix-instantiate '' -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` + +## Synopsis + +`nix-store` `--generate-binary-cache-key` *key-name* *secret-key-file* *public-key-file* + +## Description + +This command generates an [Ed25519 key pair](http://ed25519.cr.yp.to/) +that can be used to create a signed binary cache. It takes three +mandatory parameters: + +1. A key name, such as `cache.example.org-1`, that is used to look up + keys on the client when it verifies signatures. It can be anything, + but it’s suggested to use the host name of your cache (e.g. + `cache.example.org`) with a suffix denoting the number of the key + (to be incremented every time you need to revoke a key). + +2. The file name where the secret key is to be stored. + +3. The file name where the public key is to be stored. diff --git a/doc/manual/src/command-ref/opt-common-syn.md b/doc/manual/src/command-ref/opt-common-syn.md new file mode 100644 index 000000000..b66d318c2 --- /dev/null +++ b/doc/manual/src/command-ref/opt-common-syn.md @@ -0,0 +1,57 @@ +\--help + +\--version + +\--verbose + +\-v + +\--quiet + +\--log-format + +format + +\--no-build-output + +\-Q + +\--max-jobs + +\-j + +number + +\--cores + +number + +\--max-silent-time + +number + +\--timeout + +number + +\--keep-going + +\-k + +\--keep-failed + +\-K + +\--fallback + +\--readonly-mode + +\-I + +path + +\--option + +name + +value diff --git a/doc/manual/src/command-ref/opt-common.md b/doc/manual/src/command-ref/opt-common.md new file mode 100644 index 000000000..9650f53f8 --- /dev/null +++ b/doc/manual/src/command-ref/opt-common.md @@ -0,0 +1,228 @@ +# Common Options + +Most Nix commands accept the following command-line options: + + - `--help` + Prints out a summary of the command syntax and exits. + + - `--version` + Prints out the Nix version number on standard output and exits. + + - `--verbose` / `-v` + Increases the level of verbosity of diagnostic messages printed on + standard error. For each Nix operation, the information printed on + standard output is well-defined; any diagnostic information is + printed on standard error, never on standard output. + + This option may be specified repeatedly. Currently, the following + verbosity levels exist: + + - 0 + “Errors only”: only print messages explaining why the Nix + invocation failed. + + - 1 + “Informational”: print *useful* messages about what Nix is + doing. This is the default. + + - 2 + “Talkative”: print more informational messages. + + - 3 + “Chatty”: print even more informational messages. + + - 4 + “Debug”: print debug information. + + - 5 + “Vomit”: print vast amounts of debug information. + + - `--quiet` + Decreases the level of verbosity of diagnostic messages printed on + standard error. This is the inverse option to `-v` / `--verbose`. + + This option may be specified repeatedly. See the previous verbosity + levels list. + + - `--log-format` *format* + This option can be used to change the output of the log format, with + *format* being one of: + + - raw + This is the raw format, as outputted by nix-build. + + - internal-json + Outputs the logs in a structured manner. + + > **Warning** + > + > While the schema itself is relatively stable, the format of + > the error-messages (namely of the `msg`-field) can change + > between releases. + + - bar + Only display a progress bar during the builds. + + - bar-with-logs + Display the raw logs, with the progress bar at the bottom. + + - `--no-build-output` / `-Q` + By default, output written by builders to standard output and + standard error is echoed to the Nix command's standard error. This + option suppresses this behaviour. Note that the builder's standard + output and error are always written to a log file in + `prefix/nix/var/log/nix`. + + - `--max-jobs` / `-j` *number* + Sets the maximum number of build jobs that Nix will perform in + parallel to the specified number. Specify `auto` to use the number + of CPUs in the system. The default is specified by the `max-jobs` + configuration setting, which itself defaults to `1`. A higher + value is useful on SMP systems or to exploit I/O latency. + + Setting it to `0` disallows building on the local machine, which is + useful when you want builds to happen only on remote builders. + + - `--cores` + Sets the value of the `NIX_BUILD_CORES` environment variable in + the invocation of builders. Builders can use this variable at + their discretion to control the maximum amount of parallelism. For + instance, in Nixpkgs, if the derivation attribute + `enableParallelBuilding` is set to `true`, the builder passes the + `-jN` flag to GNU Make. It defaults to the value of the `cores` + configuration setting, if set, or `1` otherwise. The value `0` + means that the builder should use all available CPU cores in the + system. + + - `--max-silent-time` + Sets the maximum number of seconds that a builder can go without + producing any data on standard output or standard error. The + default is specified by the `max-silent-time` configuration + setting. `0` means no time-out. + + - `--timeout` + Sets the maximum number of seconds that a builder can run. The + default is specified by the `timeout` configuration setting. `0` + means no timeout. + + - `--keep-going` / `-k` + Keep going in case of failed builds, to the greatest extent + possible. That is, if building an input of some derivation fails, + Nix will still build the other inputs, but not the derivation + itself. Without this option, Nix stops if any build fails (except + for builds of substitutes), possibly killing builds in progress (in + case of parallel or distributed builds). + + - `--keep-failed` / `-K` + Specifies that in case of a build failure, the temporary directory + (usually in `/tmp`) in which the build takes place should not be + deleted. The path of the build directory is printed as an + informational message. + + - `--fallback` + Whenever Nix attempts to build a derivation for which substitutes + are known for each output path, but realising the output paths + through the substitutes fails, fall back on building the derivation. + + The most common scenario in which this is useful is when we have + registered substitutes in order to perform binary distribution from, + say, a network repository. If the repository is down, the + realisation of the derivation will fail. When this option is + specified, Nix will build the derivation instead. Thus, installation + from binaries falls back on installation from source. This option is + not the default since it is generally not desirable for a transient + failure in obtaining the substitutes to lead to a full build from + source (with the related consumption of resources). + + - `--no-build-hook` + Disables the build hook mechanism. This allows to ignore remote + builders if they are setup on the machine. + + It's useful in cases where the bandwidth between the client and the + remote builder is too low. In that case it can take more time to + upload the sources to the remote builder and fetch back the result + than to do the computation locally. + + - `--readonly-mode` + When this option is used, no attempt is made to open the Nix + database. Most Nix operations do need database access, so those + operations will fail. + + - `--arg` *name* *value* + This option is accepted by `nix-env`, `nix-instantiate`, + `nix-shell` and `nix-build`. When evaluating Nix expressions, the + expression evaluator will automatically try to call functions that + it encounters. It can automatically call functions for which every + argument has a [default + value](../expressions/language-constructs.md#functions) (e.g., + `{ argName ? defaultValue }: ...`). With `--arg`, you can also + call functions that have arguments without a default value (or + override a default value). That is, if the evaluator encounters a + function with an argument named *name*, it will call it with value + *value*. + + For instance, the top-level `default.nix` in Nixpkgs is actually a + function: + + ```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 + value [`builtins.currentSystem`](../expressions/builtins.md) for + the `system` argument. You can override this using `--arg`, e.g., + `nix-env -i pkgname --arg system \"i686-freebsd\"`. (Note that + since the argument is a Nix string literal, you have to escape the + quotes.) + + - `--argstr` *name* *value* + This option is like `--arg`, only the value is not a Nix + expression but a string. So instead of `--arg system + \"i686-linux\"` (the outer quotes are to keep the shell happy) you + can say `--argstr system i686-linux`. + + - `--attr` / `-A` *attrPath* + Select an attribute from the top-level Nix expression being + evaluated. (`nix-env`, `nix-instantiate`, `nix-build` and + `nix-shell` only.) The *attribute path* *attrPath* is a sequence + of attribute names separated by dots. For instance, given a + top-level Nix expression *e*, the attribute path `xorg.xorgserver` + would cause the expression `e.xorg.xorgserver` to be used. See + [`nix-env --install`](nix-env.md#operation---install) for some + concrete examples. + + In addition to attribute names, you can also specify array indices. + For instance, the attribute path `foo.3.bar` selects the `bar` + attribute of the fourth element of the array in the `foo` attribute + of the top-level expression. + + - `--expr` / `-E` + Interpret the command line arguments as a list of Nix expressions to + be parsed and evaluated, rather than as a list of file names of Nix + expressions. (`nix-instantiate`, `nix-build` and `nix-shell` only.) + + For `nix-shell`, this option is commonly used to give you a shell in + which you can build the packages returned by the expression. If you + want to get a shell which contain the *built* packages ready for + use, give your expression to the `nix-shell -p` convenience flag + instead. + + - `-I` *path* + Add a path to the Nix expression search path. This option may be + given multiple times. See the `NIX_PATH` environment variable for + information on the semantics of the Nix search path. Paths added + through `-I` take precedence over `NIX_PATH`. + + - `--option` *name* *value* + Set the Nix configuration option *name* to *value*. This overrides + settings in the Nix configuration file (see nix.conf5). + + - `--repair` + Fix corrupted or missing store paths by redownloading or rebuilding + them. Note that this is slow because it requires computing a + cryptographic hash of the contents of every path in the closure of + the build. Also note the warning under `nix-store --repair-path`. diff --git a/doc/manual/src/command-ref/opt-inst-syn.md b/doc/manual/src/command-ref/opt-inst-syn.md new file mode 100644 index 000000000..1703c40e3 --- /dev/null +++ b/doc/manual/src/command-ref/opt-inst-syn.md @@ -0,0 +1,15 @@ +\--prebuilt-only + +\-b + +\--attr + +\-A + +\--from-expression + +\-E + +\--from-profile + +path diff --git a/doc/manual/src/command-ref/utilities.md b/doc/manual/src/command-ref/utilities.md new file mode 100644 index 000000000..5ba8a02a3 --- /dev/null +++ b/doc/manual/src/command-ref/utilities.md @@ -0,0 +1,3 @@ +# Utilities + +This section lists utilities that you can use when you work with Nix. diff --git a/doc/manual/src/expressions/advanced-attributes.md b/doc/manual/src/expressions/advanced-attributes.md new file mode 100644 index 000000000..31ebadda1 --- /dev/null +++ b/doc/manual/src/expressions/advanced-attributes.md @@ -0,0 +1,249 @@ +# Advanced Attributes + +Derivations can declare some infrequently used optional attributes. + + - `allowedReferences` + The optional attribute `allowedReferences` specifies a list of legal + references (dependencies) of the output of the builder. For example, + + ```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 + dependency on itself, use `"out"` as a list item. This is used in + NixOS to check that generated files such as initial ramdisks for + booting Linux don’t have accidental dependencies on other paths in + the Nix store. + + - `allowedRequisites` + This attribute is similar to `allowedReferences`, but it specifies + the legal requisites of the whole closure, so all the dependencies + recursively. For example, + + ```nix + allowedRequisites = [ foobar ]; + ``` + + enforces that the output of a derivation cannot have any other + runtime dependency than `foobar`, and in addition it enforces that + `foobar` itself doesn't introduce any other dependency itself. + + - `disallowedReferences` + The optional attribute `disallowedReferences` specifies a list of + illegal references (dependencies) of the output of the builder. For + example, + + ```nix + disallowedReferences = [ foo ]; + ``` + + enforces that the output of a derivation cannot have a direct + runtime dependencies on the derivation `foo`. + + - `disallowedRequisites` + This attribute is similar to `disallowedReferences`, but it + specifies illegal requisites for the whole closure, so all the + dependencies recursively. For example, + + ```nix + disallowedRequisites = [ foobar ]; + ``` + + enforces that the output of a derivation cannot have any runtime + dependency on `foobar` or any other derivation depending recursively + on `foobar`. + + - `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: + + ```nix + derivation { + ... + exportReferencesGraph = [ "libfoo-graph" libfoo ]; + }; + ``` + + the references graph of `libfoo` is placed in the file + `libfoo-graph` in the temporary build directory. + + `exportReferencesGraph` is useful for builders that want to do + something with the closure of a store path. Examples include the + builders in NixOS that generate the initial ramdisk for booting + Linux (a `cpio` archive containing the closure of the boot script) + and the ISO-9660 image for the installation CD (which is populated + with a Nix store containing the closure of a bootable NixOS + configuration). + + - `impureEnvVars` + This attribute allows you to specify a list of environment variables + that should be passed from the environment of the calling user to + the builder. Usually, the environment is cleared completely when the + builder is executed, but with this attribute you can allow specific + environment variables to be passed unmodified. For example, + `fetchurl` in Nixpkgs has the line + + ```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. + + This attribute is only allowed in *fixed-output derivations* (see + below), where impurities such as these are okay since (the hash + of) the output is known in advance. It is ignored for all other + derivations. + + > **Warning** + > + > `impureEnvVars` implementation takes environment variables from + > the current builder process. When a daemon is building its + > environmental variables are used. Without the daemon, the + > environmental variables come from the environment of the + > `nix-build`. + + - `outputHash`; `outputHashAlgo`; `outputHashMode` + These attributes declare that the derivation is a so-called + *fixed-output derivation*, which means that a cryptographic hash of + the output is already known in advance. When the build of a + fixed-output derivation finishes, Nix computes the cryptographic + hash of the output and compares it to the hash declared with these + attributes. If there is a mismatch, the build fails. + + The rationale for fixed-output derivations is derivations such as + those produced by the `fetchurl` function. This function downloads a + file from a given URL. To ensure that the downloaded file has not + been modified, the caller must also specify a cryptographic hash of + the file. For example, + + ```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., + + ```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* + would change. For instance, if we were to change the URL of the + Glibc source distribution in Nixpkgs (a package on which almost all + other packages depend) massive rebuilds would be needed. This is + unfortunate for a change which we know cannot have a real effect as + it propagates upwards through the dependency graph. + + For fixed-output derivations, on the other hand, the name of the + output path only depends on the `outputHash*` and `name` attributes, + while all other attributes are ignored for the purpose of computing + the output path. (The `name` attribute is included because it is + part of the path.) + + As an example, here is the (simplified) Nix expression for + `fetchurl`: + + ```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 + `"sha512"`. + + The `outputHashMode` attribute determines how the hash is computed. + It must be one of the following two values: + + - `"flat"` + The output must be a non-executable regular file. If it isn’t, + the build fails. The hash is simply computed over the contents + of that file (so it’s equal to what Unix commands like + `sha256sum` or `sha1sum` produce). + + This is the default. + + - `"recursive"` + The hash is computed over the NAR archive dump of the output + (i.e., the result of [`nix-store + --dump`](../command-ref/nix-store.md#operation---dump)). In + this case, the output can be anything, including a directory + tree. + + The `outputHash` attribute, finally, must be a string containing + the hash in either hexadecimal or base-32 notation. (See the + [`nix-hash` command](../command-ref/nix-hash.md) for information + about converting to and from base-32 notation.) + + - `passAsFile` + 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). + + - `preferLocalBuild` + If this attribute is set to `true` and [distributed building is + enabled](../advanced-topics/distributed-builds.md), then, if + possible, the derivaton will be built locally instead of forwarded + to a remote machine. This is appropriate for trivial builders + where the cost of doing a download or remote build would exceed + the cost of building locally. + + - `allowSubstitutes` + If this attribute is set to `false`, then Nix will always build this + derivation; it will not try to substitute its outputs. This is + useful for very trivial derivations (such as `writeText` in Nixpkgs) + that are cheaper to build than to substitute from a binary cache. + + > **Note** + > + > You need to have a builder configured which satisfies the + > derivation’s `system` attribute, since the derivation cannot be + > substituted. Thus it is usually a good idea to align `system` with + > `builtins.currentSystem` when setting `allowSubstitutes` to + > `false`. For most trivial derivations this should be the case. diff --git a/doc/manual/src/expressions/arguments-variables.md b/doc/manual/src/expressions/arguments-variables.md new file mode 100644 index 000000000..12198c879 --- /dev/null +++ b/doc/manual/src/expressions/arguments-variables.md @@ -0,0 +1,80 @@ +# Arguments and Variables + +The [Nix expression for GNU Hello](expression-syntax.md) is a +function; it is missing some arguments that have to be filled in +somewhere. In the Nix Packages collection this is done in the file +`pkgs/top-level/all-packages.nix`, where all Nix expressions for +packages are imported and called with the appropriate arguments. Here +are some fragments of `all-packages.nix`, with annotations of what +they mean: + +```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 + recursive* set of attributes. That is, the attributes can refer to + each other. This is precisely what we want since we want to “plug” + the various packages into each other. + +2. Here we *import* the Nix expression for GNU Hello. The import + operation just loads and returns the specified Nix expression. In + fact, we could just have put the contents of the Nix expression + for GNU Hello in `all-packages.nix` at this point. That would be + completely equivalent, but it would make `all-packages.nix` rather + bulky. + + Note that we refer to `../applications/misc/hello/ex-1`, not + `../applications/misc/hello/ex-1/default.nix`. When you try to + import a directory, Nix automatically appends `/default.nix` to the + file name. + +3. This is where the actual composition takes place. Here we *call* the + function imported from `../applications/misc/hello/ex-1` with a set + containing the things that the function expects, namely `fetchurl`, + `stdenv`, and `perl`. We use inherit again to use the attributes + defined in the surrounding scope (we could also have written + `fetchurl = fetchurl;`, etc.). + + The result of this function call is an actual derivation that can be + built by Nix (since when we fill in the arguments of the function, + what we get is its body, which is the call to `stdenv.mkDerivation` + in the [Nix expression for GNU Hello](expression-syntax.md)). + + > **Note** + > + > Nixpkgs has a convenience function `callPackage` that imports and + > calls a function, filling in any missing arguments by passing the + > corresponding attribute from the Nixpkgs set, like this: + > + > ```nix + > hello = callPackage ../applications/misc/hello/ex-1 { }; + > ``` + > + > If necessary, you can set or override arguments: + > + > ```nix + > hello = callPackage ../applications/misc/hello/ex-1 { stdenv = myStdenv; }; + > ``` + +4. Likewise, we have to instantiate Perl, `fetchurl`, and the standard + environment. diff --git a/doc/manual/src/expressions/build-script.md b/doc/manual/src/expressions/build-script.md new file mode 100644 index 000000000..b1eacae88 --- /dev/null +++ b/doc/manual/src/expressions/build-script.md @@ -0,0 +1,70 @@ +# Build Script + +Here is the builder referenced from Hello's Nix expression (stored in +`pkgs/applications/misc/hello/ex-1/builder.sh`): + +```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 +steps to elucidate what a builder does. It performs the following steps: + +1. When Nix runs a builder, it initially completely clears the + environment (except for the attributes declared in the derivation). + This is done to prevent undeclared inputs from being used in the + build process. If for example the `PATH` contained `/usr/bin`, then + you might accidentally use `/usr/bin/gcc`. + + So the first step is to set up the environment. This is done by + calling the `setup` script of the standard environment. The + environment variable `stdenv` points to the location of the + standard environment being used. (It wasn't specified explicitly + as an attribute in Hello's Nix expression, but `mkDerivation` adds + it automatically.) + +2. Since Hello needs Perl, we have to make sure that Perl is in the + `PATH`. The `perl` environment variable points to the location of + the Perl package (since it was passed in as an attribute to the + derivation), so `$perl/bin` is the directory containing the Perl + interpreter. + +3. Now we have to unpack the sources. The `src` attribute was bound to + the result of fetching the Hello source tarball from the network, so + the `src` environment variable points to the location in the Nix + store to which the tarball was downloaded. After unpacking, we `cd` + to the resulting source directory. + + The whole build is performed in a temporary directory created in + `/tmp`, by the way. This directory is removed after the builder + finishes, so there is no need to clean up the sources afterwards. + Also, the temporary directory is always newly created, so you don't + have to worry about files from previous builds interfering with the + current build. + +4. GNU Hello is a typical Autoconf-based package, so we first have to + run its `configure` script. In Nix every package is stored in a + separate location in the Nix store, for instance + `/nix/store/9a54ba97fb71b65fda531012d0443ce2-hello-2.1.1`. Nix + computes this path by cryptographically hashing all attributes of + the derivation. The path is passed to the builder through the `out` + environment variable. So here we give `configure` the parameter + `--prefix=$out` to cause Hello to be installed in the expected + location. + +5. Finally we build Hello (`make`) and install it into the location + specified by `out` (`make install`). + +If you are wondering about the absence of error checking on the result +of various commands called in the builder: this is because the shell +script is evaluated with Bash's `-e` option, which causes the script to +be aborted if any command fails without an error check. diff --git a/doc/manual/src/expressions/builtin-constants.md b/doc/manual/src/expressions/builtin-constants.md new file mode 100644 index 000000000..3345a715b --- /dev/null +++ b/doc/manual/src/expressions/builtin-constants.md @@ -0,0 +1,20 @@ +# Built-in Constants + +Here are the constants built into the Nix expression evaluator: + + - `builtins` + The set `builtins` contains all the built-in functions and values. + You can use `builtins` to test for the availability of features in + the Nix installation, e.g., + + ```nix + if builtins ? getEnv then builtins.getEnv "PATH" else "" + ``` + + This allows a Nix expression to fall back gracefully on older Nix + installations that don’t have the desired built-in function. + + - `builtins.currentSystem` + The built-in value `currentSystem` evaluates to the Nix platform + identifier for the Nix installation on which the expression is being + evaluated, such as `"i686-linux"` or `"x86_64-darwin"`. diff --git a/doc/manual/src/expressions/builtins-prefix.md b/doc/manual/src/expressions/builtins-prefix.md new file mode 100644 index 000000000..0f7c3d32f --- /dev/null +++ b/doc/manual/src/expressions/builtins-prefix.md @@ -0,0 +1,15 @@ +# Built-in Functions + +This section lists the functions built into the Nix expression +evaluator. (The built-in function `derivation` is discussed above.) +Some built-ins, such as `derivation`, are always in scope of every Nix +expression; you can just access them right away. But to prevent +polluting the namespace too much, most built-ins are not in +scope. Instead, you can access them through the `builtins` built-in +value, which is a set that contains all built-in functions and values. +For instance, `derivation` is also available as `builtins.derivation`. + + - `derivation` *attrs*; `builtins.derivation` *attrs* + + `derivation` is described in [its own section](derivations.md). + diff --git a/doc/manual/src/expressions/derivations.md b/doc/manual/src/expressions/derivations.md new file mode 100644 index 000000000..d26a33b7f --- /dev/null +++ b/doc/manual/src/expressions/derivations.md @@ -0,0 +1,161 @@ +# Derivations + +The most important built-in function is `derivation`, which is used to +describe a single derivation (a build action). It takes as input a set, +the attributes of which specify the inputs of the build. + + - There must be an attribute named `system` whose value must be a + string specifying a Nix system type, such as `"i686-linux"` or + `"x86_64-darwin"`. (To figure out your system type, run `nix -vv + --version`.) The build can only be performed on a machine and + operating system matching the system type. (Nix can automatically + [forward builds for other + platforms](../advanced-topics/distributed-builds.md) by forwarding + them to other machines.) + + - There must be an attribute named `name` whose value must be a + string. This is used as a symbolic name for the package by + `nix-env`, and it is appended to the output paths of the derivation. + + - There must be an attribute named `builder` that identifies the + program that is executed to perform the build. It can be either a + derivation or a source (a local file reference, e.g., + `./builder.sh`). + + - Every attribute is passed as an environment variable to the builder. + Attribute values are translated to environment variables as follows: + + - Strings and numbers are just passed verbatim. + + - A *path* (e.g., `../foo/sources.tar`) causes the referenced file + to be copied to the store; its location in the store is put in + the environment variable. The idea is that all sources should + reside in the Nix store, since all inputs to a derivation should + reside in the Nix store. + + - A *derivation* causes that derivation to be built prior to the + present derivation; its default output path is put in the + environment variable. + + - Lists of the previous types are also allowed. They are simply + concatenated, separated by spaces. + + - `true` is passed as the string `1`, `false` and `null` are + passed as an empty string. + + - The optional attribute `args` specifies command-line arguments to be + passed to the builder. It should be a list. + + - The optional attribute `outputs` specifies a list of symbolic + outputs of the derivation. By default, a derivation produces a + single output path, denoted as `out`. However, derivations can + produce multiple output paths. This is useful because it allows + outputs to be downloaded or garbage-collected separately. For + instance, imagine a library package that provides a dynamic library, + header files, and documentation. A program that links against the + library doesn’t need the header files and documentation at runtime, + and it doesn’t need the documentation at build time. Thus, the + library package could specify: + + ```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 + + ```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. + + ```nix + buildInputs = [ pkg.lib pkg.headers ]; + ``` + + The first element of `outputs` determines the *default output*. + Thus, you could also write + + ```nix + buildInputs = [ pkg pkg.headers ]; + ``` + + since `pkg` is equivalent to `pkg.lib`. + +The function `mkDerivation` in the Nixpkgs standard environment is a +wrapper around `derivation` that adds a default value for `system` and +always uses Bash as the builder, to which the supplied builder is passed +as a command-line argument. See the Nixpkgs manual for details. + +The builder is executed as follows: + + - A temporary directory is created under the directory specified by + `TMPDIR` (default `/tmp`) where the build will take place. The + current directory is changed to this directory. + + - The environment is cleared and set to the derivation attributes, as + specified above. + + - In addition, the following variables are set: + + - `NIX_BUILD_TOP` contains the path of the temporary directory for + this build. + + - Also, `TMPDIR`, `TEMPDIR`, `TMP`, `TEMP` are set to point to the + temporary directory. This is to prevent the builder from + accidentally writing temporary files anywhere else. Doing so + might cause interference by other processes. + + - `PATH` is set to `/path-not-set` to prevent shells from + initialising it to their built-in default value. + + - `HOME` is set to `/homeless-shelter` to prevent programs from + using `/etc/passwd` or the like to find the user's home + directory, which could cause impurity. Usually, when `HOME` is + set, it is used as the location of the home directory, even if + it points to a non-existent path. + + - `NIX_STORE` is set to the path of the top-level Nix store + directory (typically, `/nix/store`). + + - For each output declared in `outputs`, the corresponding + environment variable is set to point to the intended path in the + Nix store for that output. Each output path is a concatenation + of the cryptographic hash of all build inputs, the `name` + attribute and the output name. (The output name is omitted if + it’s `out`.) + + - If an output path already exists, it is removed. Also, locks are + acquired to prevent multiple Nix instances from performing the same + build at the same time. + + - A log of the combined standard output and error is written to + `/nix/var/log/nix`. + + - The builder is executed with the arguments specified by the + attribute `args`. If it exits with exit code 0, it is considered to + have succeeded. + + - The temporary directory is removed (unless the `-K` option was + specified). + + - If the build was successful, Nix scans each output path for + references to input paths by looking for the hash parts of the input + paths. Since these are potential runtime dependencies, Nix registers + them as dependencies of the output paths. + + - After the build, Nix sets the last-modified timestamp on all files + in the build result to 1 (00:00:01 1/1/1970 UTC), sets the group to + the default group, and sets the mode of the file to 0444 or 0555 + (i.e., read-only, with execute permission enabled if the file was + originally executable). Note that possible `setuid` and `setgid` + bits are cleared. Setuid and setgid programs are not currently + supported by Nix. This is because the Nix archives used in + deployment have no concept of ownership information, and because it + makes the build result dependent on the user performing the build. diff --git a/doc/manual/src/expressions/expression-language.md b/doc/manual/src/expressions/expression-language.md new file mode 100644 index 000000000..267fcb983 --- /dev/null +++ b/doc/manual/src/expressions/expression-language.md @@ -0,0 +1,12 @@ +# Nix Expression Language + +The Nix expression language is a pure, lazy, functional language. Purity +means that operations in the language don't have side-effects (for +instance, there is no variable assignment). Laziness means that +arguments to functions are evaluated only when they are needed. +Functional means that functions are “normal” values that can be passed +around and manipulated in interesting ways. The language is not a +full-featured, general purpose language. Its main job is to describe +packages, compositions of packages, and the variability within packages. + +This section presents the various features of the language. diff --git a/doc/manual/src/expressions/expression-syntax.md b/doc/manual/src/expressions/expression-syntax.md new file mode 100644 index 000000000..2a1306e32 --- /dev/null +++ b/doc/manual/src/expressions/expression-syntax.md @@ -0,0 +1,93 @@ +# Expression Syntax + +Here is a Nix expression for GNU Hello: + +```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 +place each package in a separate directory and call the single Nix +expression in that directory `default.nix`. The file has the following +elements (referenced from the figure by number): + +1. This states that the expression is a *function* that expects to be + called with three arguments: `stdenv`, `fetchurl`, and `perl`. They + are needed to build Hello, but we don't know how to build them here; + that's why they are function arguments. `stdenv` is a package that + is used by almost all Nix Packages packages; it provides a + “standard” environment consisting of the things you would expect + in a basic Unix environment: a C/C++ compiler (GCC, to be precise), + the Bash shell, fundamental Unix tools such as `cp`, `grep`, `tar`, + 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. + +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; }`. + +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 + default builder (which does a `configure; make; make install`, in + essence). Hello is sufficiently simple that the default builder + would suffice, but in this case, we will show an actual builder + for educational purposes. The value `./builder.sh` refers to the + shell script shown in the [next section](build-script.md), + discussed below. + +5. The builder has to know what the sources of the package are. Here, + the attribute `src` is bound to the result of a call to the + `fetchurl` function. Given a URL and a SHA-256 hash of the expected + contents of the file at that URL, this function builds a derivation + that downloads the file and checks its hash. So the sources are a + dependency that like all other dependencies is built before Hello + itself is built. + + Instead of `src` any other name could have been used, and in fact + there can be any number of sources (bound to different attributes). + However, `src` is customary, and it's also expected by the default + builder (which we don't use in this example). + +6. Since the derivation requires Perl, we have to pass the value of the + `perl` function argument to the builder. All attributes in the set + are actually passed as environment variables to the builder, so + declaring an attribute + + ```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 + bit silly, so there is a shorter syntax. The `inherit` keyword + causes the specified attributes to be bound to whatever variables + with the same name happen to be in scope. diff --git a/doc/manual/src/expressions/generic-builder.md b/doc/manual/src/expressions/generic-builder.md new file mode 100644 index 000000000..cf26b5f82 --- /dev/null +++ b/doc/manual/src/expressions/generic-builder.md @@ -0,0 +1,66 @@ +# Generic Builder Syntax + +Recall that the [build script for GNU Hello](build-script.md) looked +something like this: + +```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 +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: + +```bash +buildInputs="$perl" ① + +source $stdenv/setup ② + +genericBuild ③ +``` + +Here is what each line means: + +1. The `buildInputs` variable tells `setup` to use the indicated + packages as “inputs”. This means that if a package provides a `bin` + subdirectory, it's added to `PATH`; if it has a `include` + subdirectory, it's added to GCC's header search path; and so on. + (This is implemented in a modular way: `setup` tries to source the + file `pkg/nix-support/setup-hook` of all dependencies. These “setup + hooks” can then set up whatever environment variables they want; for + instance, the setup hook for Perl sets the `PERL5LIB` environment + variable to contain the `lib/site_perl` directories of all inputs.) + +2. The function `genericBuild` is defined in the file `$stdenv/setup`. + +3. The final step calls the shell function `genericBuild`, which + performs the steps that were done explicitly in the previous build + script. The generic builder is smart enough to figure out whether + to unpack the sources using `gzip`, `bzip2`, etc. It can be + customised in many ways; see the Nixpkgs manual for details. + +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: + +```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 +entirely. diff --git a/doc/manual/src/expressions/language-constructs.md b/doc/manual/src/expressions/language-constructs.md new file mode 100644 index 000000000..cb0169239 --- /dev/null +++ b/doc/manual/src/expressions/language-constructs.md @@ -0,0 +1,350 @@ +# Language Constructs + +## Recursive sets + +Recursive sets are just normal sets, but the attributes can refer to +each other. For example, + +```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 +would be invalid if no such variable exists. That is, in a normal +(non-recursive) set, attributes are not added to the lexical scope; in a +recursive set, they are. + +Recursive sets of course introduce the danger of infinite recursion. For +example, the expression + +```nix +rec { + x = y; + y = x; +}.x +``` + +will crash with an `infinite recursion encountered` error message. + +## Let-expressions + +A let-expression allows you to define local variables for an expression. +For instance, + +```nix +let + x = "foo"; + y = "bar"; +in x + y +``` + +evaluates to `"foobar"`. + +## Inheriting attributes + +When defining a set or in a let-expression it is often convenient to +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, + +```nix +let x = 123; in +{ inherit x; + y = 456; +} +``` + +is equivalent to + +```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`, + +```nix +graphviz = (import ../tools/graphics/graphviz) { + inherit fetchurl stdenv libpng libjpeg expat x11 yacc; + inherit (xlibs) libXaw; +}; + +xlibs = { + libX11 = ...; + libXaw = ...; + ... +} + +libpng = ...; +libjpg = ...; +... +``` + +the set used in the function call to the function defined in +`../tools/graphics/graphviz` inherits a number of variables from the +surrounding scope (`fetchurl` ... `yacc`), but also inherits `libXaw` +(the X Athena Widgets) from the `xlibs` (X11 client-side libraries) set. + +Summarizing the fragment + +```nix +... +inherit x y z; +inherit (src-set) a b c; +... +``` + +is equivalent to + +```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. + +## Functions + +Functions have the following form: + +```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 +three kinds of patterns: + + - If a pattern is a single identifier, then the function matches any + argument. Example: + + ```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., + + ```nix + map (concat "foo") [ "bar" "bla" "abc" ] + ``` + + 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 + + ```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 (`...`): + + ```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, + + ```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`. + + - An `@`-pattern provides a means of referring to the whole value + being matched: + + ```nix + args@{ x, y, z, ... }: z + y + x + args.a + ``` + + but can also be written as: + + ```nix + { x, y, z, ... } @ args: z + y + x + args.a + ``` + + Here `args` is bound to the entire argument, which is further + matched against the pattern `{ x, y, z, + ... }`. `@`-pattern makes mainly sense with an ellipsis(`...`) as + you can access attribute names as `a`, using `args.a`, which was + given as an additional attribute to the function. + + > **Warning** + > + > The `args@` expression is bound to the argument passed to the + > function which means that attributes with defaults that aren't + > explicitly specified in the function call won't cause an + > evaluation error, but won't exist in `args`. + > + > For instance + > + > ```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., + +```nix +let concat = { x, y }: x + y; +in concat { x = "foo"; y = "bar"; } +``` + +## Conditionals + +Conditionals look like this: + +```nix +if e1 then e2 else e3 +``` + +where *e1* is an expression that should evaluate to a Boolean value +(`true` or `false`). + +## Assertions + +Assertions are generally used to check that certain requirements on or +between features and dependencies hold. They look like this: + +```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 +evaluation is aborted and a backtrace is printed. + +Here is a Nix expression for the Subversion package that shows how +assertions can be used:. + +```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: + +1. This assertion states that if Subversion is to have support for + local repositories, then Berkeley DB is needed. So if the Subversion + function is called with the `localServer` argument set to `true` but + the `db4` argument set to `null`, then the evaluation fails. + +2. This is a more subtle condition: if Subversion is built with Apache + (`httpServer`) support, then the Expat library (an XML library) used + by Subversion should be same as the one used by Apache. This is + because in this configuration Subversion code ends up being linked + with Apache code, and if the Expat libraries do not match, a build- + or runtime link error or incompatibility might occur. + +3. This assertion says that in order for Subversion to have SSL support + (so that it can access `https` URLs), an OpenSSL library must be + passed. Additionally, it says that *if* Apache support is enabled, + then Apache's OpenSSL should match Subversion's. (Note that if + Apache support is not enabled, we don't care about Apache's + OpenSSL.) + +4. The conditional here is not really related to assertions, but is + worth pointing out: it ensures that if SSL support is disabled, then + the Subversion derivation is not dependent on OpenSSL, even if a + non-`null` value was passed. This prevents an unnecessary rebuild of + Subversion if OpenSSL changes. + +## With-expressions + +A *with-expression*, + +```nix +with e1; e2 +``` + +introduces the set *e1* into the lexical scope of the expression *e2*. +For instance, + +```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., + +```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. + +The bindings introduced by `with` do not shadow bindings introduced by +other means, e.g. + +```nix +let a = 3; in with { a = 1; }; let a = 4; in with { a = 2; }; ... +``` + +establishes the same scope as + +```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 `/* ... */`. diff --git a/doc/manual/src/expressions/language-operators.md b/doc/manual/src/expressions/language-operators.md new file mode 100644 index 000000000..1d787ffe3 --- /dev/null +++ b/doc/manual/src/expressions/language-operators.md @@ -0,0 +1,29 @@ +# Operators + +The table below lists the operators in the Nix expression language, in +order of precedence (from strongest to weakest binding). + +| Name | Syntax | Associativity | Description | Precedence | +| ------------------------ | ----------------------------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | +| Select | *e* `.` *attrpath* \[ `or` *def* \] | none | Select attribute denoted by the attribute path *attrpath* from set *e*. (An attribute path is a dot-separated list of attribute names.) If the attribute doesn’t exist, return *def* if provided, otherwise abort evaluation. | 1 | +| Application | *e1* *e2* | left | Call function *e1* with argument *e2*. | 2 | +| Arithmetic Negation | `-` *e* | none | Arithmetic negation. | 3 | +| Has Attribute | *e* `?` *attrpath* | none | Test whether set *e* contains the attribute denoted by *attrpath*; return `true` or `false`. | 4 | +| List Concatenation | *e1* `++` *e2* | right | List concatenation. | 5 | +| Multiplication | *e1* `*` *e2*, | left | Arithmetic multiplication. | 6 | +| Division | *e1* `/` *e2* | left | Arithmetic division. | 6 | +| Addition | *e1* `+` *e2* | left | Arithmetic addition. | 7 | +| Subtraction | *e1* `-` *e2* | left | Arithmetic subtraction. | 7 | +| String Concatenation | *string1* `+` *string2* | left | String concatenation. | 7 | +| Not | `!` *e* | none | Boolean negation. | 8 | +| Update | *e1* `//` *e2* | right | Return a set consisting of the attributes in *e1* and *e2* (with the latter taking precedence over the former in case of equally named attributes). | 9 | +| Less Than | *e1* `<` *e2*, | none | Arithmetic comparison. | 10 | +| Less Than or Equal To | *e1* `<=` *e2* | none | Arithmetic comparison. | 10 | +| Greater Than | *e1* `>` *e2* | none | Arithmetic comparison. | 10 | +| Greater Than or Equal To | *e1* `>=` *e2* | none | Arithmetic comparison. | 10 | +| Equality | *e1* `==` *e2* | none | Equality. | 11 | +| Inequality | *e1* `!=` *e2* | none | Inequality. | 11 | +| Logical AND | *e1* `&&` *e2* | left | Logical AND. | 12 | +| Logical OR | *e1* `\|\|` *e2* | left | Logical OR. | 13 | +| Logical Implication | *e1* `->` *e2* | none | Logical implication (equivalent to `!e1 \|\| + e2`). | 14 | diff --git a/doc/manual/src/expressions/language-values.md b/doc/manual/src/expressions/language-values.md new file mode 100644 index 000000000..ce31029cc --- /dev/null +++ b/doc/manual/src/expressions/language-values.md @@ -0,0 +1,244 @@ +# Values + +## Simple Values + +Nix has the following basic data types: + + - *Strings* can be written in three ways. + + The most common way is to enclose the string between double quotes, + e.g., `"foo bar"`. Strings can span multiple lines. The special + characters `"` and `\` and the character sequence `${` must be + escaped by prefixing them with a backslash (`\`). Newlines, carriage + returns and tabs can be written as `\n`, `\r` and `\t`, + respectively. + + You can include the result of an expression into a string by + enclosing it in `${...}`, a feature known as *antiquotation*. The + enclosed expression must evaluate to something that can be coerced + into a string (meaning that it must be a string, a path, or a + derivation). For instance, rather than writing + + ```nix + "--with-freetype2-library=" + freetype + "/lib" + ``` + + (where `freetype` is a derivation), you can instead write the more + natural + + ```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)): + + ```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 + themselves contain strings (e.g., `"-thread"`), some of which in + turn contain expressions (e.g., `${mesa}`). + + The second way to write string literals is as an *indented string*, + which is enclosed between pairs of *double single-quotes*, like so: + + ```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 + number of spaces equal to the minimal indentation of the string as a + whole (disregarding the indentation of empty lines). For instance, + the first and second line are indented two space, while the third + line is indented four spaces. Thus, two spaces are stripped from + each line, so the resulting string is + + ```nix + "This is the first line.\nThis is the second line.\n This is the third line.\n" + ``` + + Note that the whitespace and newline following the opening `''` is + ignored if there is no non-whitespace text on the initial line. + + Antiquotation (`${expr}`) is supported in indented strings. + + Since `${` and `''` have special meaning in indented strings, you + need a way to quote them. `$` can be escaped by prefixing it with + `''` (that is, two single quotes), i.e., `''$`. `''` can be escaped + by prefixing it with `'`, i.e., `'''`. `$` removes any special + meaning from the following `$`. Linefeed, carriage-return and tab + characters can be written as `''\n`, `''\r`, `''\t`, and `''\` + escapes any other character. + + Indented strings are primarily useful in that they allow multi-line + string literals to follow the indentation of the enclosing Nix + expression, and that less escaping is typically necessary for + strings representing languages such as shell scripts and + configuration files because `''` is much less common than `"`. + Example: + + ```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 + is*, without quotes. For instance, the string + `"http://example.org/foo.tar.bz2"` can also be written as + `http://example.org/foo.tar.bz2`. + + - Numbers, which can be *integers* (like `123`) or *floating point* + (like `123.43` or `.27e13`). + + Numbers are type-compatible: pure integer operations will always + return integers, whereas any operation involving at least one + floating point number will have a floating point number as a result. + + - *Paths*, e.g., `/bin/sh` or `./builder.sh`. A path must contain at + least one slash to be recognised as such. For instance, `builder.sh` + is not a path: it's parsed as an expression that selects the + attribute `sh` from the variable `builder`. If the file name is + relative, i.e., if it does not begin with a slash, it is made + absolute at parse time relative to the directory of the Nix + expression that contained it. For instance, if a Nix expression in + `/foo/bar/bla.nix` refers to `../xyzzy/fnord.nix`, the absolute path + is `/foo/xyzzy/fnord.nix`. + + If the first component of a path is a `~`, it is interpreted as if + the rest of the path were relative to the user's home directory. + e.g. `~/foo` would be equivalent to `/home/edolstra/foo` for a user + whose home directory is `/home/edolstra`. + + Paths can also be specified between angle brackets, e.g. + ``. This means that the directories listed in the + environment variable `NIX_PATH` will be searched for the given file + or directory name. + + - *Booleans* with values `true` and `false`. + + - The null value, denoted as `null`. + +## Lists + +Lists are formed by enclosing a whitespace-separated list of values +between square brackets. For example, + +```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., + +```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. + +Note that lists are only lazy in values, and they are strict in length. + +## Sets + +Sets are really the core of the language, since ultimately the Nix +language is all about creating derivations, which are really just sets +of attributes to be passed to build scripts. + +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: + +```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. + +Attributes can be selected from a set using the `.` operator. For +instance, + +```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, + +```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: + +```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: + +```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). + +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: + +```nix +{ ${if foo then "bar" else null} = true; } +``` + +This will evaluate to `{}` if `foo` evaluates to `false`. + +A set that has a `__functor` attribute whose value is callable (i.e. is +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., + +```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 +of object-oriented programming, for example. diff --git a/doc/manual/src/expressions/simple-building-testing.md b/doc/manual/src/expressions/simple-building-testing.md new file mode 100644 index 000000000..6f730a936 --- /dev/null +++ b/doc/manual/src/expressions/simple-building-testing.md @@ -0,0 +1,61 @@ +# Building and Testing + +You can now try to build Hello. Of course, you could do `nix-env -i +hello`, but you may not want to install a possibly broken package just +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: + +```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 +(which also happens to be `hello`) and is unambiguous (there can be +multiple packages with the symbolic name `hello`, but there can be +only one attribute in a set named `hello`). + +`nix-build` registers the `./result` symlink as a garbage collection +root, so unless and until you delete the `./result` symlink, the output +of the build will be safely kept on your system. You can use +`nix-build`’s `-o` switch to give the symlink another name. + +Nix has transactional semantics. Once a build finishes successfully, Nix +makes a note of this in its database: it registers that the path denoted +by `out` is now “valid”. If you try to build the derivation again, Nix +will see that the path is already valid and finish immediately. If a +build fails, either because it returns a non-zero exit code, because Nix +or the builder are killed, or because the machine crashes, then the +output paths will not be registered as valid. If you try to build the +derivation again, Nix will remove the output paths if they exist (e.g., +because the builder died half-way through `make +install`) and try again. Note that there is no “negative caching”: Nix +doesn't remember that a build failed, and so a failed build can always +be repeated. This is because Nix cannot distinguish between permanent +failures (e.g., a compiler error due to a syntax error in the source) +and transient failures (e.g., a disk full condition). + +Nix also performs locking. If you run multiple Nix builds +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: + +```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 +isn’t the case with, say, `make`). diff --git a/doc/manual/src/expressions/simple-expression.md b/doc/manual/src/expressions/simple-expression.md new file mode 100644 index 000000000..857f71b9b --- /dev/null +++ b/doc/manual/src/expressions/simple-expression.md @@ -0,0 +1,23 @@ +# A Simple Nix Expression + +This section shows how to add and test the [GNU Hello +package](http://www.gnu.org/software/hello/hello.html) to the Nix +Packages collection. Hello is a program that prints out the text “Hello, +world\!”. + +To add a package to the Nix Packages collection, you generally need to +do three things: + +1. Write a Nix expression for the package. This is a file that + describes all the inputs involved in building the package, such as + dependencies, sources, and so on. + +2. Write a *builder*. This is a shell script that builds the package + from the inputs. (In fact, it can be written in any language, but + typically it's a `bash` shell script.) + +3. Add the package to the file `pkgs/top-level/all-packages.nix`. The + Nix expression written in the first step is a *function*; it + requires other packages in order to build it. In this step you put + it all together, i.e., you call the function with the right + arguments to build the actual package. diff --git a/doc/manual/src/expressions/writing-nix-expressions.md b/doc/manual/src/expressions/writing-nix-expressions.md new file mode 100644 index 000000000..5664108e7 --- /dev/null +++ b/doc/manual/src/expressions/writing-nix-expressions.md @@ -0,0 +1,12 @@ +This chapter shows you how to write Nix expressions, which instruct Nix +how to build packages. It starts with a simple example (a Nix expression +for GNU Hello), and then moves on to a more in-depth look at the Nix +expression language. + +> **Note** +> +> This chapter is mostly about the Nix expression language. For more +> extensive information on adding packages to the Nix Packages +> collection (such as functions in the standard environment and coding +> conventions), please consult [its +> manual](http://nixos.org/nixpkgs/manual/). diff --git a/doc/manual/figures/user-environments.png b/doc/manual/src/figures/user-environments.png similarity index 100% rename from doc/manual/figures/user-environments.png rename to doc/manual/src/figures/user-environments.png diff --git a/doc/manual/figures/user-environments.sxd b/doc/manual/src/figures/user-environments.sxd similarity index 100% rename from doc/manual/figures/user-environments.sxd rename to doc/manual/src/figures/user-environments.sxd diff --git a/doc/manual/src/glossary.md b/doc/manual/src/glossary.md new file mode 100644 index 000000000..56af9cd85 --- /dev/null +++ b/doc/manual/src/glossary.md @@ -0,0 +1,100 @@ +# Glossary + + - derivation + A description of a build action. The result of a derivation is a + store object. Derivations are typically specified in Nix expressions + using the [`derivation` primitive](expressions/derivations.md). These are + translated into low-level *store derivations* (implicitly by + `nix-env` and `nix-build`, or explicitly by `nix-instantiate`). + + - store + The location in the file system where store objects live. Typically + `/nix/store`. + + - store path + The location in the file system of a store object, i.e., an + immediate child of the Nix store directory. + + - store object + A file that is an immediate child of the Nix store directory. These + can be regular files, but also entire directory trees. Store objects + can be sources (objects copied from outside of the store), + derivation outputs (objects produced by running a build action), or + derivations (files describing a build action). + + - substitute + A substitute is a command invocation stored in the Nix database that + describes how to build a store object, bypassing the normal build + mechanism (i.e., derivations). Typically, the substitute builds the + store object by downloading a pre-built version of the store object + from some server. + + - purity + The assumption that equal Nix derivations when run always produce + the same output. This cannot be guaranteed in general (e.g., a + builder can rely on external inputs such as the network or the + system time) but the Nix model assumes it. + + - Nix expression + A high-level description of software packages and compositions + thereof. Deploying software using Nix entails writing Nix + expressions for your packages. Nix expressions are translated to + derivations that are stored in the Nix store. These derivations can + then be built. + + - reference + A store path `P` is said to have a reference to a store path `Q` if + the store object at `P` contains the path `Q` somewhere. The + *references* of a store path are the set of store paths to which it + has a reference. + + A derivation can reference other derivations and sources (but not + output paths), whereas an output path only references other output + paths. + + - reachable + A store path `Q` is reachable from another store path `P` if `Q` + is in the *closure* of the *references* relation. + + - closure + The closure of a store path is the set of store paths that are + directly or indirectly “reachable” from that store path; that is, + it’s the closure of the path under the *references* relation. For + a package, the closure of its derivation is equivalent to the + build-time dependencies, while the closure of its output path is + equivalent to its runtime dependencies. For correct deployment it + is necessary to deploy whole closures, since otherwise at runtime + files could be missing. The command `nix-store -qR` prints out + closures of store paths. + + As an example, if the store object at path `P` contains a reference + to path `Q`, then `Q` is in the closure of `P`. Further, if `Q` + references `R` then `R` is also in the closure of `P`. + + - output path + A store path produced by a derivation. + + - deriver + The deriver of an *output path* is the store + derivation that built it. + + - validity + A store path is considered *valid* if it exists in the file system, + is listed in the Nix database as being valid, and if all paths in + its closure are also valid. + + - user environment + An automatically generated store object that consists of a set of + symlinks to “active” applications, i.e., other store paths. These + are generated automatically by + [`nix-env`](command-ref/nix-env.md). See *profiles*. + + - profile + A symlink to the current *user environment* of a user, e.g., + `/nix/var/nix/profiles/default`. + + - NAR + A *N*ix *AR*chive. This is a serialisation of a path in the Nix + store. It can contain regular files, directories and symbolic + links. NARs are generated and unpacked using `nix-store --dump` + and `nix-store --restore`. diff --git a/doc/manual/src/hacking.md b/doc/manual/src/hacking.md new file mode 100644 index 000000000..2a1e55e5b --- /dev/null +++ b/doc/manual/src/hacking.md @@ -0,0 +1,77 @@ +# Hacking + +This section provides some notes on how to hack on Nix. To get the +latest version of Nix from GitHub: + +```console +$ git clone https://github.com/NixOS/nix.git +$ cd nix +``` + +To build Nix for the current operating system/architecture use + +```console +$ nix-build +``` + +or if you have a flake-enabled nix: + +```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. + +```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: + +```console +$ nix-shell +``` + +To build Nix itself in this shell: + +```console +[nix-shell]$ ./bootstrap.sh +[nix-shell]$ ./configure $configureFlags --prefix=$(pwd)/outputs/out +[nix-shell]$ make -j $NIX_BUILD_CORES +``` + +To install it in `$(pwd)/outputs` and test it: + +```console +[nix-shell]$ make install +[nix-shell]$ make installcheck -j $NIX_BUILD_CORES +[nix-shell]$ ./outputs/out/bin/nix --version +nix (Nix) 3.0 +``` + +To run a functional test: + +```console +make tests/test-name-should-auto-complete.sh.test +``` + +To run the unit-tests for C++ code: + +``` +make check +``` + +If you have a flakes-enabled Nix you can replace: + +```console +$ nix-shell +``` + +by: + +```console +$ nix develop +``` diff --git a/doc/manual/src/installation/building-source.md b/doc/manual/src/installation/building-source.md new file mode 100644 index 000000000..d21a51a82 --- /dev/null +++ b/doc/manual/src/installation/building-source.md @@ -0,0 +1,38 @@ +# Building Nix from Source + +After unpacking or checking out the Nix sources, issue the following +commands: + +```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: + +```console +$ ./bootstrap.sh +``` + +The installation path can be specified by passing the `--prefix=prefix` +to `configure`. The default installation directory is `/usr/local`. You +can change this to any location you like. You must have write permission +to the *prefix* path. + +Nix keeps its *store* (the place where packages are stored) in +`/nix/store` by default. This can be changed using +`--with-store-dir=path`. + +> **Warning** +> +> It is best *not* to change the Nix store from its default, since doing +> so makes it impossible to use pre-built binaries from the standard +> Nixpkgs channels — that is, all packages will need to be built from +> source. + +Nix keeps state (such as its database and log files) in `/nix/var` by +default. This can be changed using `--localstatedir=path`. diff --git a/doc/manual/src/installation/env-variables.md b/doc/manual/src/installation/env-variables.md new file mode 100644 index 000000000..4a49897e4 --- /dev/null +++ b/doc/manual/src/installation/env-variables.md @@ -0,0 +1,64 @@ +# Environment Variables + +To use Nix, some environment variables should be set. In particular, +`PATH` should contain the directories `prefix/bin` and +`~/.nix-profile/bin`. The first directory contains the Nix tools +themselves, while `~/.nix-profile` is a symbolic link to the current +*user environment* (an automatically generated package consisting of +symlinks to installed packages). The simplest way to set the required +environment variables is to include the file +`prefix/etc/profile.d/nix.sh` in your `~/.profile` (or similar), like +this: + +```bash +source prefix/etc/profile.d/nix.sh +``` + +# `NIX_SSL_CERT_FILE` + +If you need to specify a custom certificate bundle to account for an +HTTPS-intercepting man in the middle proxy, you must specify the path to +the certificate bundle in the environment variable `NIX_SSL_CERT_FILE`. + +If you don't specify a `NIX_SSL_CERT_FILE` manually, Nix will install +and use its own certificate bundle. + +Set the environment variable and install Nix + +```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: + +```bash +export NIX_SSL_CERT_FILE=/etc/ssl/my-certificate-bundle.crt +``` + +> **Note** +> +> You must not add the export and then do the install, as the Nix +> installer will detect the presense of Nix configuration, and abort. + +## `NIX_SSL_CERT_FILE` with macOS and the Nix daemon + +On macOS you must specify the environment variable for the Nix daemon +service, then restart it: + +```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 + +The Nix installer has special handling for these proxy-related +environment variables: `http_proxy`, `https_proxy`, `ftp_proxy`, +`no_proxy`, `HTTP_PROXY`, `HTTPS_PROXY`, `FTP_PROXY`, `NO_PROXY`. + +If any of these variables are set when running the Nix installer, then +the installer will create an override file at +`/etc/systemd/system/nix-daemon.service.d/override.conf` so `nix-daemon` +will use them. diff --git a/doc/manual/src/installation/installation.md b/doc/manual/src/installation/installation.md new file mode 100644 index 000000000..b40c5b95f --- /dev/null +++ b/doc/manual/src/installation/installation.md @@ -0,0 +1,2 @@ +This section describes how to install and configure Nix for first-time +use. diff --git a/doc/manual/src/installation/installing-binary.md b/doc/manual/src/installation/installing-binary.md new file mode 100644 index 000000000..8b8d1d738 --- /dev/null +++ b/doc/manual/src/installation/installing-binary.md @@ -0,0 +1,291 @@ +# Installing a Binary Distribution + +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: + +```console +$ sh <(curl -L https://nixos.org/nix/install) +``` + +If you're using macOS 10.15 (Catalina) or newer, consult [the macOS +installation instructions](#macos-installation) before installing. + +As of Nix 2.1.0, the Nix installer will always default to creating a +single-user installation, however opting in to the multi-user +installation is highly recommended. + +# Single User Installation + +To explicitly select a single-user installation on your system: + +```console +$ sh <(curl -L https://nixos.org/nix/install) --no-daemon +``` + +This will perform a single-user installation of Nix, meaning that `/nix` +is owned by the invoking user. You should run this under your usual user +account, *not* as root. The script will invoke `sudo` to create `/nix` +if it doesn’t already exist. If you don’t have `sudo`, you should +manually create `/nix` first as root, e.g.: + +```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 +`~/.nix-profile/etc/profile.d/nix.sh`. You can set the +`NIX_INSTALLER_NO_MODIFY_PROFILE` environment variable before executing +the install script to disable this behaviour. + +You can uninstall Nix simply by running: + +```console +$ rm -rf /nix +``` + +# Multi User Installation + +The multi-user Nix installation creates system users, and a system +service for the Nix daemon. + + - Linux running systemd, with SELinux disabled + + - macOS + +You can instruct the installer to perform a multi-user installation on +your system: + +```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 +should run this under your usual user account, *not* as root. The script +will invoke `sudo` as needed. + +> **Note** +> +> If you need Nix to use a different group ID or user ID set, you will +> have to download the tarball manually and [edit the install +> script](#installing-from-a-binary-tarball). + +The installer will modify `/etc/bashrc`, and `/etc/zshrc` if they exist. +The installer will first back up these files with a `.backup-before-nix` +extension. The installer will also create `/etc/profile.d/nix.sh`. + +You can uninstall Nix with the following commands: + +```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. + +# macOS Installation + +Starting with macOS 10.15 (Catalina), the root filesystem is read-only. +This means `/nix` can no longer live on your system volume, and that +you'll need a workaround to install Nix. + +The recommended approach, which creates an unencrypted APFS volume for +your Nix store and a "synthetic" empty directory to mount it over at +`/nix`, is least likely to impair Nix or your system. + +> **Note** +> +> With all separate-volume approaches, it's possible something on your +> system (particularly daemons/services and restored apps) may need +> access to your Nix store before the volume is mounted. Adding +> additional encryption makes this more likely. + +If you're using a recent Mac with a [T2 +chip](https://www.apple.com/euro/mac/shared/docs/Apple_T2_Security_Chip_Overview.pdf), +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: + +```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. + +> **Note** +> +> All of the known workarounds have drawbacks, but we hope better +> solutions will be available in the future. Some that we have our eye +> on are: +> +> 1. A true firmlink would enable the Nix store to live on the primary +> data volume without the build problems caused by the symlink +> approach. End users cannot currently create true firmlinks. +> +> 2. If the Nix store volume shared FileVault encryption with the +> primary data volume (probably by using the same volume group and +> role), FileVault encryption could be easily supported by the +> installer without requiring manual setup by each user. + +## Change the Nix store path prefix + +Changing the default prefix for the Nix store is a simple approach which +enables you to leave it on your root volume, where it can take full +advantage of FileVault encryption if enabled. Unfortunately, this +approach also opts your device out of some benefits that are enabled by +using the same prefix across systems: + + - Your system won't be able to take advantage of the binary cache + (unless someone is able to stand up and support duplicate caching + infrastructure), which means you'll spend more time waiting for + builds. + + - It's harder to build and deploy packages to Linux systems. + +It would also possible (and often requested) to just apply this change +ecosystem-wide, but it's an intrusive process that has side effects we +want to avoid for now. + +## Use a separate encrypted volume + +If you like, you can also add encryption to the recommended approach +taken by the installer. You can do this by pre-creating an encrypted +volume before you run the installer--or you can run the installer and +encrypt the volume it creates later. + +In either case, adding encryption to a second volume isn't quite as +simple as enabling FileVault for your boot volume. Before you dive in, +there are a few things to weigh: + +1. The additional volume won't be encrypted with your existing + FileVault key, so you'll need another mechanism to decrypt the + volume. + +2. You can store the password in Keychain to automatically decrypt the + volume on boot--but it'll have to wait on Keychain and may not mount + before your GUI apps restore. If any of your launchd agents or apps + depend on Nix-installed software (for example, if you use a + Nix-installed login shell), the restore may fail or break. + + On a case-by-case basis, you may be able to work around this problem + by using `wait4path` to block execution until your executable is + available. + + It's also possible to decrypt and mount the volume earlier with a + login hook--but this mechanism appears to be deprecated and its + future is unclear. + +3. You can hard-code the password in the clear, so that your store + volume can be decrypted before Keychain is available. + +If you are comfortable navigating these tradeoffs, you can encrypt the +volume with something along the lines of: + +```console +alice$ diskutil apfs enableFileVault /nix -user disk +``` + +## Symlink the Nix store to a custom location + +Another simple approach is using `/etc/synthetic.conf` to symlink the +Nix store to the data volume. This option also enables your store to +share any configured FileVault encryption. Unfortunately, builds that +resolve the symlink may leak the canonical path or even fail. + +Because of these downsides, we can't recommend this approach. + +## Notes on the recommended approach + +This section goes into a little more detail on the recommended approach. +You don't need to understand it to run the installer, but it can serve +as a helpful reference if you run into trouble. + +1. In order to compose user-writable locations into the new read-only + system root, Apple introduced a new concept called `firmlinks`, + which it describes as a "bi-directional wormhole" between two + filesystems. You can see the current firmlinks in + `/usr/share/firmlinks`. Unfortunately, firmlinks aren't (currently?) + user-configurable. + + For special cases like NFS mount points or package manager roots, + [synthetic.conf(5)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man5/synthetic.conf.5.html) + supports limited user-controlled file-creation (of symlinks, and + synthetic empty directories) at `/`. To create a synthetic empty + directory for mounting at `/nix`, add the following line to + `/etc/synthetic.conf` (create it if necessary): + + nix + +2. This configuration is applied at boot time, but you can use + `apfs.util` to trigger creation (not deletion) of new entries + without a reboot: + + ```console + alice$ /System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util -B + ``` + +3. Create the new APFS volume with diskutil: + + ```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: + + # + # Warning - this file should only be modified with vifs(8) + # + # Failure to do so is unsupported and may be destructive. + # + LABEL=Nix\040Store /nix apfs rw,nobrowse + + The nobrowse setting will keep Spotlight from indexing this volume, + and keep it from showing up on your desktop. + +# Installing a pinned Nix version from a URL + +NixOS.org hosts version-specific installation URLs for all Nix versions +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: + +```console +$ sh <(curl -L https://nixos.org/nix/install) +``` + +In the same directory of the install script are sha256 sums, and gpg +signature files. + +# Installing from a binary tarball + +You can also download a binary tarball that contains Nix and all its +dependencies. (This is what the install script at + does automatically.) You should unpack +it somewhere (e.g. in `/tmp`), and then run the script named `install` +inside the binary tarball: + +```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 +file named `install-multi-user`. diff --git a/doc/manual/src/installation/installing-source.md b/doc/manual/src/installation/installing-source.md new file mode 100644 index 000000000..e52d38a03 --- /dev/null +++ b/doc/manual/src/installation/installing-source.md @@ -0,0 +1,4 @@ +# Installing Nix from Source + +If no binary package is available, you can download and compile a source +distribution. diff --git a/doc/manual/src/installation/multi-user.md b/doc/manual/src/installation/multi-user.md new file mode 100644 index 000000000..6920591c4 --- /dev/null +++ b/doc/manual/src/installation/multi-user.md @@ -0,0 +1,77 @@ +# Multi-User Mode + +To allow a Nix store to be shared safely among multiple users, it is +important that users are not able to run builders that modify the Nix +store or database in arbitrary ways, or that interfere with builds +started by other users. If they could do so, they could install a Trojan +horse in some package and compromise the accounts of other users. + +To prevent this, the Nix store and database are owned by some privileged +user (usually `root`) and builders are executed under special user +accounts (usually named `nixbld1`, `nixbld2`, etc.). When a unprivileged +user runs a Nix command, actions that operate on the Nix store (such as +builds) are forwarded to a *Nix daemon* running under the owner of the +Nix store/database that performs the operation. + +> **Note** +> +> Multi-user mode has one important limitation: only root and a set of +> trusted users specified in `nix.conf` can specify arbitrary binary +> caches. So while unprivileged users may install packages from +> arbitrary Nix expressions, they may not get pre-built binaries. + +## Setting up the build users + +The *build users* are the special UIDs under which builds are performed. +They should all be members of the *build users group* `nixbld`. This +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: + +```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 +expect to do many builds at the same time. + +## Running the daemon + +The [Nix daemon](../command-ref/nix-daemon.md) should be started as +follows (as `root`): + +```console +$ nix-daemon +``` + +You’ll want to put that line somewhere in your system’s boot scripts. + +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 + +```console +export NIX_REMOTE=daemon +``` + +into the users’ login scripts. + +## Restricting access + +To limit which users can perform Nix operations, you can use the +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 + +```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 +cannot perform Nix operations. diff --git a/doc/manual/src/installation/nix-security.md b/doc/manual/src/installation/nix-security.md new file mode 100644 index 000000000..1e9036b68 --- /dev/null +++ b/doc/manual/src/installation/nix-security.md @@ -0,0 +1,15 @@ +# Security + +Nix has two basic security models. First, it can be used in “single-user +mode”, which is similar to what most other package management tools do: +there is a single user (typically root) who performs all package +management operations. All other users can then use the installed +packages, but they cannot perform package management operations +themselves. + +Alternatively, you can configure Nix in “multi-user mode”. In this +model, all users can perform package management operations — for +instance, every user can install software without requiring root +privileges. Nix ensures that this is secure. For instance, it’s not +possible for one user to overwrite a package used by another user with a +Trojan horse. diff --git a/doc/manual/src/installation/obtaining-source.md b/doc/manual/src/installation/obtaining-source.md new file mode 100644 index 000000000..0a906e390 --- /dev/null +++ b/doc/manual/src/installation/obtaining-source.md @@ -0,0 +1,18 @@ +# Obtaining a Source Distribution + +The source tarball of the most recent stable release can be downloaded +from the [Nix homepage](http://nixos.org/nix/download.html). You can +also grab the [most recent development +release](http://hydra.nixos.org/job/nix/master/release/latest-finished#tabs-constituents). + +Alternatively, the most recent sources of Nix can be obtained from its +[Git repository](https://github.com/NixOS/nix). For example, the +following command will check out the latest revision into a directory +called `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. diff --git a/doc/manual/src/installation/prerequisites-source.md b/doc/manual/src/installation/prerequisites-source.md new file mode 100644 index 000000000..69b7c5a5e --- /dev/null +++ b/doc/manual/src/installation/prerequisites-source.md @@ -0,0 +1,71 @@ +# Prerequisites + + - GNU Autoconf () and the + autoconf-archive macro collection + (). These are only + needed to run the bootstrap script, and are not necessary if your + source distribution came with a pre-built `./configure` script. + + - GNU Make. + + - Bash Shell. The `./configure` script relies on bashisms, so Bash is + required. + + - A version of GCC or Clang that supports C++17. + + - `pkg-config` to locate dependencies. If your distribution does not + provide it, you can get it from + . + + - The OpenSSL library to calculate cryptographic hashes. If your + distribution does not provide it, you can get it from + . + + - The `libbrotlienc` and `libbrotlidec` libraries to provide + implementation of the Brotli compression algorithm. They are + available for download from the official repository + . + + - The bzip2 compressor program and the `libbz2` library. Thus you must + have bzip2 installed, including development headers and libraries. + If your distribution does not provide these, you can obtain bzip2 + from + . + + - `liblzma`, which is provided by XZ Utils. If your distribution does + not provide this, you can get it from . + + - cURL and its library. If your distribution does not provide it, you + can get it from . + + - The SQLite embedded database library, version 3.6.19 or higher. If + your distribution does not provide it, please install it from + . + + - The [Boehm garbage collector](http://www.hboehm.info/gc/) to reduce + the evaluator’s memory consumption (optional). To enable it, install + `pkgconfig` and the Boehm garbage collector, and pass the flag + `--enable-gc` to `configure`. + + - The `boost` library of version 1.66.0 or higher. It can be obtained + from the official web site . + + - The `editline` library of version 1.14.0 or higher. It can be + obtained from the its repository + . + + - Recent versions of Bison and Flex to build the parser. (This is + because Nix needs GLR support in Bison and reentrancy support in + Flex.) For Bison, you need version 2.6, which can be obtained from + the [GNU FTP server](ftp://alpha.gnu.org/pub/gnu/bison). For Flex, + you need version 2.5.35, which is available on + [SourceForge](http://lex.sourceforge.net/). Slightly older versions + may also work, but ancient versions like the ubiquitous 2.5.4a + won't. Note that these are only required if you modify the parser or + when you are building from the Git repository. + + - The `libseccomp` is used to provide syscall filtering on Linux. This + is an optional dependency and can be disabled passing a + `--disable-seccomp-sandboxing` option to the `configure` script (Not + recommended unless your system doesn't support `libseccomp`). To get + the library, visit . diff --git a/doc/manual/src/installation/single-user.md b/doc/manual/src/installation/single-user.md new file mode 100644 index 000000000..f9a3b26ed --- /dev/null +++ b/doc/manual/src/installation/single-user.md @@ -0,0 +1,9 @@ +# Single-User Mode + +In single-user mode, all Nix operations that access the database in +`prefix/var/nix/db` or modify the Nix store in `prefix/store` must be +performed under the user ID that owns those directories. This is +typically root. (If you install from RPM packages, that’s in fact the +default ownership.) However, on single-user machines, it is often +convenient to `chown` those directories to your normal user account so +that you don’t have to `su` to root all the time. diff --git a/doc/manual/src/installation/supported-platforms.md b/doc/manual/src/installation/supported-platforms.md new file mode 100644 index 000000000..8ef1f0e78 --- /dev/null +++ b/doc/manual/src/installation/supported-platforms.md @@ -0,0 +1,7 @@ +# Supported Platforms + +Nix is currently supported on the following platforms: + + - Linux (i686, x86\_64, aarch64). + + - macOS (x86\_64). diff --git a/doc/manual/src/installation/upgrading.md b/doc/manual/src/installation/upgrading.md new file mode 100644 index 000000000..24efc4681 --- /dev/null +++ b/doc/manual/src/installation/upgrading.md @@ -0,0 +1,14 @@ +# Upgrading Nix + +Multi-user Nix users on macOS can upgrade Nix by running: `sudo -i sh -c +'nix-channel --update && +nix-env -iA nixpkgs.nix && +launchctl remove org.nixos.nix-daemon && +launchctl load /Library/LaunchDaemons/org.nixos.nix-daemon.plist'` + +Single-user installations of Nix should run this: `nix-channel --update; +nix-env -iA nixpkgs.nix nixpkgs.cacert` + +Multi-user Nix users on Linux should run this with sudo: `nix-channel +--update; nix-env -iA nixpkgs.nix nixpkgs.cacert; systemctl +daemon-reload; systemctl restart nix-daemon` diff --git a/doc/manual/src/introduction.md b/doc/manual/src/introduction.md new file mode 100644 index 000000000..f01fe7b38 --- /dev/null +++ b/doc/manual/src/introduction.md @@ -0,0 +1,193 @@ +# Introduction + +Nix is a _purely functional package manager_. This means that it +treats packages like values in purely functional programming languages +such as Haskell — they are built by functions that don’t have +side-effects, and they never change after they have been built. Nix +stores packages in the _Nix store_, usually the directory +`/nix/store`, where each package has its own unique subdirectory such +as + + /nix/store/b6gvzjyb2pg0kjfwrjmg1vfhh54ad73z-firefox-33.1/ + +where `b6gvzjyb2pg0…` is a unique identifier for the package that +captures all its dependencies (it’s a cryptographic hash of the +package’s build dependency graph). This enables many powerful +features. + +## Multiple versions + +You can have multiple versions or variants of a package +installed at the same time. This is especially important when +different applications have dependencies on different versions of the +same package — it prevents the “DLL hell”. Because of the hashing +scheme, different versions of a package end up in different paths in +the Nix store, so they don’t interfere with each other. + +An important consequence is that operations like upgrading or +uninstalling an application cannot break other applications, since +these operations never “destructively” update or delete files that are +used by other packages. + +## Complete dependencies + +Nix helps you make sure that package dependency specifications are +complete. In general, when you’re making a package for a package +management system like RPM, you have to specify for each package what +its dependencies are, but there are no guarantees that this +specification is complete. If you forget a dependency, then the +package will build and work correctly on _your_ machine if you have +the dependency installed, but not on the end user's machine if it's +not there. + +Since Nix on the other hand doesn’t install packages in “global” +locations like `/usr/bin` but in package-specific directories, the +risk of incomplete dependencies is greatly reduced. This is because +tools such as compilers don’t search in per-packages directories such +as `/nix/store/5lbfaxb722zp…-openssl-0.9.8d/include`, so if a package +builds correctly on your system, this is because you specified the +dependency explicitly. This takes care of the build-time dependencies. + +Once a package is built, runtime dependencies are found by scanning +binaries for the hash parts of Nix store paths (such as `r8vvq9kq…`). +This sounds risky, but it works extremely well. + +## Multi-user support + +Nix has multi-user support. This means that non-privileged users can +securely install software. Each user can have a different _profile_, +a set of packages in the Nix store that appear in the user’s `PATH`. +If a user installs a package that another user has already installed +previously, the package won’t be built or downloaded a second time. +At the same time, it is not possible for one user to inject a Trojan +horse into a package that might be used by another user. + +## Atomic upgrades and rollbacks + +Since package management operations never overwrite packages in the +Nix store but just add new versions in different paths, they are +_atomic_. So during a package upgrade, there is no time window in +which the package has some files from the old version and some files +from the new version — which would be bad because a program might well +crash if it’s started during that period. + +And since packages aren’t overwritten, the old versions are still +there after an upgrade. This means that you can _roll back_ to the +old version: + +```console +$ nix-env --upgrade some-packages +$ nix-env --rollback +``` + +## Garbage collection + +When you uninstall a package like this… + +```console +$ nix-env --uninstall firefox +``` + +the package isn’t 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_: + +```console +$ nix-collect-garbage +``` + +This deletes all packages that aren’t in use by any user profile or by +a currently running program. + +## Functional package language + +Packages are built from _Nix expressions_, which is a simple +functional language. A Nix expression describes everything that goes +into a package build action (a “derivation”): other packages, sources, +the build script, environment variables for the build script, etc. +Nix tries very hard to ensure that Nix expressions are +_deterministic_: building a Nix expression twice should yield the same +result. + +Because it’s a functional language, it’s easy to support +building variants of a package: turn the Nix expression into a +function and call it any number of times with the appropriate +arguments. Due to the hashing scheme, variants don’t conflict with +each other in the Nix store. + +## Transparent source/binary deployment + +Nix expressions generally describe how to build a package from +source, so an installation action like + +```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 +compiler) would have to built, at least if they are not already in the +Nix store. This is a _source deployment model_. For most users, +building from source is not very pleasant as it takes far too long. +However, Nix can automatically skip building from source and instead +use a _binary cache_, a web server that provides pre-built +binaries. For instance, when asked to build +`/nix/store/b6gvzjyb2pg0…-firefox-33.1` from source, Nix would first +check if the file `https://cache.nixos.org/b6gvzjyb2pg0….narinfo` +exists, and if so, fetch the pre-built binary referenced from there; +otherwise, it would fall back to building from source. + +## Nix Packages collection + +We provide a large set of Nix expressions containing hundreds of +existing Unix packages, the _Nix Packages collection_ (Nixpkgs). + +## Managing build environments + +Nix is extremely useful for developers as it makes it easy to +automatically set up the build environment for a package. Given a Nix +expression that describes the dependencies of your package, the +command `nix-shell` will build or download those dependencies if +they’re not already in your Nix store, and then start a Bash shell in +which all necessary environment variables (such as compiler search +paths) are set. + +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): + +```console +$ nix-shell '' -A pan +``` + +You’re then dropped into a shell where you can edit, build and test +the package: + +```console +[nix-shell]$ tar xf $src +[nix-shell]$ cd pan-* +[nix-shell]$ ./configure +[nix-shell]$ make +[nix-shell]$ ./pan/gui/pan +``` + +## Portability + +Nix runs on Linux and macOS. + +## NixOS + +NixOS is a Linux distribution based on Nix. It uses Nix not just for +package management but also to manage the system configuration (e.g., +to build configuration files in `/etc`). This means, among other +things, that it is easy to roll back the entire configuration of the +system to an earlier state. Also, users can install software without +root privileges. For more information and downloads, see the [NixOS +homepage](https://nixos.org/). + +## License + +Nix is released under the terms of the [GNU LGPLv2.1 or (at your +option) any later +version](http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html). diff --git a/doc/manual/src/package-management/basic-package-mgmt.md b/doc/manual/src/package-management/basic-package-mgmt.md new file mode 100644 index 000000000..9702a29eb --- /dev/null +++ b/doc/manual/src/package-management/basic-package-mgmt.md @@ -0,0 +1,172 @@ +# Basic Package Management + +The main command for package management is +[`nix-env`](../command-ref/nix-env.md). You can use it to install, +upgrade, and erase packages, and to query what packages are installed +or are available for installation. + +In Nix, different users can have different “views” on the set of +installed applications. That is, there might be lots of applications +present on the system (possibly in many different versions), but users +can have a specific selection of those active — where “active” just +means that it appears in a directory in the user’s `PATH`. Such a view +on the set of installed applications is called a *user environment*, +which is just a directory tree consisting of symlinks to the files of +the active applications. + +Components are installed from a set of *Nix expressions* that tell Nix +how to build those packages, including, if necessary, their +dependencies. There is a collection of Nix expressions called the +Nixpkgs package collection that contains packages ranging from basic +development stuff such as GCC and Glibc, to end-user applications like +Mozilla Firefox. (Nix is however not tied to the Nixpkgs package +collection; you could write your own Nix expressions based on Nixpkgs, +or completely new ones.) + +You can manually download the latest version of Nixpkgs from +. However, it’s much more +convenient to use the Nixpkgs [*channel*](channels.md), since it makes +it easy to stay up to date with new versions of Nixpkgs. Nixpkgs is +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: + +```console +$ nix-channel --add https://nixos.org/channels/nixpkgs-unstable +$ nix-channel --update +``` + +> **Note** +> +> On NixOS, you’re automatically subscribed to a NixOS channel +> corresponding to your NixOS major release (e.g. +> ). A NixOS channel is identical +> to the Nixpkgs channel, except that it contains only Linux binaries +> and is updated only if a set of regression tests succeed. + +You can view the set of available packages in Nixpkgs: + +```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 +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: + +```console +$ nix-env -qaf /path/to/nixpkgs +``` + +where */path/to/nixpkgs* is where you’ve unpacked or checked out +Nixpkgs. + +You can select specific packages by name: + +```console +$ nix-env -qa firefox +firefox-34.0.5 +firefox-with-plugins-34.0.5 +``` + +and using regular expressions: + +```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: + +```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 +present on your system (in which case installing it into your user +environment would be a very quick operation). The last one (`S`) +indicates whether there is a so-called *substitute* for the package, +which is Nix’s mechanism for doing binary deployment. It just means that +Nix knows that it can fetch a pre-built package from somewhere +(typically a network server) instead of building it locally. + +You can install a package using `nix-env -i`. For instance, + +```console +$ nix-env -i subversion +``` + +will install the package called `subversion` (which is, of course, the +[Subversion version management system](http://subversion.tigris.org/)). + +> **Note** +> +> When you ask Nix to install a package, it will first try to get it in +> pre-compiled form from a *binary cache*. By default, Nix will use the +> binary cache ; it contains binaries for most +> packages in Nixpkgs. Only if no binary is available in the binary +> cache, Nix will build the package from source. So if `nix-env +> -i subversion` results in Nix building stuff from source, then either +> the package is not built for your platform by the Nixpkgs build +> servers, or your version of Nixpkgs is too old or too new. For +> instance, if you have a very recent checkout of Nixpkgs, then the +> Nixpkgs build servers may not have had a chance to build everything +> and upload the resulting binaries to . The +> Nixpkgs channel is only updated after all binaries have been uploaded +> to the cache, so if you stick to the Nixpkgs channel (rather than +> using a Git checkout of the Nixpkgs tree), you will get binaries for +> most packages. + +Naturally, packages can also be uninstalled: + +```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: + +```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 +regarding ordering of version numbers (which generally do what you’d +expect of them). To just unconditionally replace Subversion with +whatever version is in the Nix expressions, use `-i` instead of `-u`; +`-i` will remove whatever version is already installed. + +You can also upgrade all packages for which there are newer versions: + +```console +$ nix-env -u +``` + +Sometimes it’s 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 + +```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' +``` diff --git a/doc/manual/src/package-management/binary-cache-substituter.md b/doc/manual/src/package-management/binary-cache-substituter.md new file mode 100644 index 000000000..bdc5038fc --- /dev/null +++ b/doc/manual/src/package-management/binary-cache-substituter.md @@ -0,0 +1,50 @@ +# Serving a Nix store via HTTP + +You can easily share the Nix store of a machine via HTTP. This allows +other machines to fetch store paths from that machine to speed up +installations. It uses the same *binary cache* mechanism that Nix +usually uses to fetch pre-built binaries from . + +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: + +```console +$ nix-env -i nix-serve +``` + +You can then start the server, listening for HTTP connections on +whatever port you like: + +```console +$ nix-serve -p 8080 +``` + +To check whether it works, try the following on the client: + +```console +$ curl http://avalon:8080/nix-cache-info +``` + +which should print something like: + + StoreDir: /nix/store + WantMassQuery: 1 + Priority: 30 + +On the client side, you can tell Nix to use your binary cache using +`--option extra-binary-caches`, e.g.: + +```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 . +Thus, for any path in the closure of Firefox, Nix will first check if +the path is available on the server `avalon` or another binary caches. +If not, it will fall back to building from source. + +You can also tell Nix to always use your binary cache by adding a line +to the `nix.conf` configuration file like this: + + binary-caches = http://avalon:8080/ https://cache.nixos.org/ diff --git a/doc/manual/src/package-management/channels.md b/doc/manual/src/package-management/channels.md new file mode 100644 index 000000000..93c8b41a6 --- /dev/null +++ b/doc/manual/src/package-management/channels.md @@ -0,0 +1,50 @@ +# Channels + +If you want to stay up to date with a set of packages, it’s not very +convenient to manually download the latest set of Nix expressions for +those packages and upgrade using `nix-env`. Fortunately, there’s a +better way: *Nix channels*. + +A Nix channel is just a URL that points to a place that contains a set +of Nix expressions and a manifest. Using the command +[`nix-channel`](../command-ref/nix-channel.md) you can automatically +stay up to date with whatever is available at that URL. + +To see the list of official NixOS channels, visit +. + +You can “subscribe” to a channel using `nix-channel --add`, e.g., + +```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 +is added to the file `~/.nix-channels`, where it is read by subsequent +calls to `nix-channel +--update`.) You can “unsubscribe” using `nix-channel +--remove`: + +```console +$ nix-channel --remove nixpkgs +``` + +To obtain the latest Nix expressions available in a channel, do + +```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 +each channel’s Nix expressions available by default to `nix-env` +operations (via the symlink `~/.nix-defexpr/channels`). Consequently, +you can then say + +```console +$ nix-env -u +``` + +to upgrade all packages in your profile to the latest versions available +in the subscribed channels. diff --git a/doc/manual/src/package-management/copy-closure.md b/doc/manual/src/package-management/copy-closure.md new file mode 100644 index 000000000..d3fac4d76 --- /dev/null +++ b/doc/manual/src/package-management/copy-closure.md @@ -0,0 +1,34 @@ +# Copying Closures via SSH + +The command `nix-copy-closure` copies a Nix store path along with all +its dependencies to or from another machine via the SSH protocol. It +doesn’t copy store paths that are already present on the target machine. +For example, the following command copies Firefox with all its +dependencies: + + $ nix-copy-closure --to alice@itchy.example.org $(type -p firefox) + +See the [manpage for `nix-copy-closure`](../command-ref/nix-copy-closure.md) for details. + +With `nix-store +--export` and `nix-store --import` you can write the closure of a store +path (that is, the path and all its dependencies) to a file, and then +unpack that file into another Nix store. For example, + + $ nix-store --export $(nix-store -qR $(type -p firefox)) > firefox.closure + +writes the closure of Firefox to a file. You can then copy this file to +another machine and install the closure: + + $ nix-store --import < firefox.closure + +Any store paths in the closure that are already present in the target +store are ignored. It is also possible to pipe the export into another +command, e.g. to copy and install a closure directly to/on another +machine: + + $ nix-store --export $(nix-store -qR $(type -p firefox)) | bzip2 | \ + ssh alice@itchy.example.org "bunzip2 | nix-store --import" + +However, `nix-copy-closure` is generally more efficient because it only +copies paths that are not already present in the target Nix store. diff --git a/doc/manual/src/package-management/garbage-collection.md b/doc/manual/src/package-management/garbage-collection.md new file mode 100644 index 000000000..fecb30fd6 --- /dev/null +++ b/doc/manual/src/package-management/garbage-collection.md @@ -0,0 +1,73 @@ +# Garbage Collection + +`nix-env` operations such as upgrades (`-u`) and uninstall (`-e`) never +actually delete packages from the system. All they do (as shown above) +is to create a new user environment that no longer contains symlinks to +the “deleted” packages. + +Of course, since disk space is not infinite, unused packages should be +removed at some point. You can do this by running the Nix garbage +collector. It will remove from the Nix store any package not used +(directly or indirectly) by any generation of any profile. + +Note however that as long as old generations reference a package, it +will not be deleted. After all, we wouldn’t be able to do a rollback +otherwise. So in order for garbage collection to be effective, you +should also delete (some) old generations. Of course, this should only +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: + +```console +$ nix-env --delete-generations old +``` + +Instead of `old` you can also specify a list of generations, e.g., + +```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, + +```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: + +```console +$ nix-store --gc +``` + +The behaviour of the gargage collector is affected by the +`keep-derivations` (default: true) and `keep-outputs` (default: false) +options in the Nix configuration file. The defaults will ensure that all +derivations that are build-time dependencies of garbage collector roots +will be kept and that all output paths that are runtime dependencies +will be kept as well. All other derivations or paths will be collected. +(This is usually what you want, but while you are developing it may make +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: + +```console +$ nix-store --gc --print-dead +``` + +Likewise, the option `--print-live` will show the paths that *won’t* be +deleted. + +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 + +```console +$ nix-collect-garbage -d +``` + +is a quick and easy way to clean up your system. diff --git a/doc/manual/src/package-management/garbage-collector-roots.md b/doc/manual/src/package-management/garbage-collector-roots.md new file mode 100644 index 000000000..30c5b7f8d --- /dev/null +++ b/doc/manual/src/package-management/garbage-collector-roots.md @@ -0,0 +1,18 @@ +# Garbage Collector Roots + +The roots of the garbage collector are all store paths to which there +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: + +```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. + +Subdirectories of `prefix/nix/var/nix/gcroots` are also searched for +symlinks. Symlinks to non-store paths are followed and searched for +roots, but symlinks to non-store paths *inside* the paths reached in +that way are not followed to prevent infinite recursion. diff --git a/doc/manual/src/package-management/package-management.md b/doc/manual/src/package-management/package-management.md new file mode 100644 index 000000000..bd26a09ab --- /dev/null +++ b/doc/manual/src/package-management/package-management.md @@ -0,0 +1,5 @@ +This chapter discusses how to do package management with Nix, i.e., +how to obtain, install, upgrade, and erase packages. This is the +“user’s” perspective of the Nix system — people who want to *create* +packages should consult the [chapter on writing Nix +expressions](../expressions/writing-nix-expressions.md). diff --git a/doc/manual/src/package-management/profiles.md b/doc/manual/src/package-management/profiles.md new file mode 100644 index 000000000..fbbfb7320 --- /dev/null +++ b/doc/manual/src/package-management/profiles.md @@ -0,0 +1,133 @@ +# Profiles + +Profiles and user environments are Nix’s mechanism for implementing the +ability to allow different users to have different configurations, and +to do atomic upgrades and rollbacks. To understand how they work, it’s +useful to know a bit about how Nix works. In Nix, packages are stored in +unique locations in the *Nix store* (typically, `/nix/store`). For +instance, a particular version of the Subversion package might be stored +in a directory +`/nix/store/dpmvp969yhdqs7lm2r1a3gng7pyq6vy4-subversion-1.1.3/`, while +another version might be stored in +`/nix/store/5mq2jcn36ldlmh93yj1n8s9c95pj7c5s-subversion-1.1.2`. The long +strings prefixed to the directory names are cryptographic hashes (to be +precise, 160-bit truncations of SHA-256 hashes encoded in a base-32 +notation) of *all* inputs involved in building the package — sources, +dependencies, compiler flags, and so on. So if two packages differ in +any way, they end up in different locations in the file system, so they +don’t interfere with each other. Here is what a part of a typical Nix +store looks like: + +![](../figures/user-environments.png) + +Of course, you wouldn’t want to type + +```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 +package we want to use, but this is not very convenient since changing +`PATH` doesn’t take effect for already existing processes. The solution +Nix uses is to create directory trees of symlinks to *activated* +packages. These are called *user environments* and they are packages +themselves (though automatically generated by `nix-env`), so they too +reside in the Nix store. For instance, in the figure above, the user +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 + +```console +$ nix-env -i subversion +``` + +on a set of Nix expressions that contained Subversion 1.1.2. + +This doesn’t in itself solve the problem, of course; you wouldn’t want +to type `/nix/store/0c1p5z4kda11...-user-env/bin/svn` either. That’s why +there are symlinks outside of the store that point to the user +environments in the store; for instance, the symlinks `default-42-link` +and `default-43-link` in the example. These are called *generations* +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 + +```console +$ nix-env -i subversion firefox +``` + +on a set of Nix expressions that contained Firefox and a new version of +Subversion. + +Generations are grouped together into *profiles* so that different users +don’t interfere with each other if they don’t want to. For example: + +```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 +`nix-env` operation, a new user environment and generation link are +created based on the current one, and finally the `default` symlink is +made to point at the new generation. This last step is atomic on Unix, +which explains how we can do atomic upgrades. (Note that the +building/installing of new packages doesn’t interfere in any way with +old packages, since they are stored in different locations in the Nix +store.) + +If you find that you want to undo a `nix-env` operation, you can just do + +```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: + +```console +$ nix-env --switch-generation 43 +``` + +which in this example would roll forward to generation 43 again. You can +also see all available generations: + +```console +$ nix-env --list-generations +``` + +You generally wouldn’t have `/nix/var/nix/profiles/some-profile/bin` in +your `PATH`. Rather, there is a symlink `~/.nix-profile` that points to +your current profile. This means that you should put +`~/.nix-profile/bin` in your `PATH` (and indeed, that’s what the +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`: + +```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 doesn’t exist, it will be created +automatically. You should be careful about storing a profile in another +location than the `profiles` directory, since otherwise it might not be +used as a root of the [garbage collector](garbage-collection.md). + +All `nix-env` operations work on the profile pointed to by +`~/.nix-profile`, but you can override this using the `--profile` option +(abbreviation `-p`): + +```console +$ nix-env -p /nix/var/nix/profiles/other-profile -i subversion +``` + +This will *not* change the `~/.nix-profile` symlink. diff --git a/doc/manual/src/package-management/s3-substituter.md b/doc/manual/src/package-management/s3-substituter.md new file mode 100644 index 000000000..a4f4d561f --- /dev/null +++ b/doc/manual/src/package-management/s3-substituter.md @@ -0,0 +1,145 @@ +# Serving a Nix store via S3 + +Nix has built-in support for storing and fetching store paths from +Amazon S3 and S3-compatible services. This uses the same *binary* +cache mechanism that Nix usually uses to fetch prebuilt binaries from +[cache.nixos.org](https://cache.nixos.org/). + +The following options can be specified as URL parameters to the S3 URL: + + - `profile` + The name of the AWS configuration profile to use. By default Nix + will use the `default` profile. + + - `region` + The region of the S3 bucket. `us–east-1` by default. + + If your bucket is not in `us–east-1`, you should always explicitly + specify the region parameter. + + - `endpoint` + The URL to your S3-compatible service, for when not using Amazon S3. + Do not specify this value if you're using Amazon S3. + + > **Note** + > + > This endpoint must support HTTPS and will use path-based + > addressing instead of virtual host based addressing. + + - `scheme` + The scheme used for S3 requests, `https` (default) or `http`. This + option allows you to disable HTTPS for binary caches which don't + support it. + + > **Note** + > + > HTTPS should be used if the cache might contain sensitive + > information. + +In this example we will use the bucket named `example-nix-cache`. + +## Anonymous Reads to your S3-compatible binary cache + +If your binary cache is publicly accessible and does not require +authentication, the simplest and easiest way to use Nix with your S3 +compatible binary cache is to use the HTTP URL for that cache. + +For AWS S3 the binary cache URL for example bucket will be exactly + or +. For S3 compatible binary caches, consult that +cache's documentation. + +Your bucket will need the following bucket policy: + +```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 + +For AWS S3 the binary cache URL for example bucket will be exactly +. + +Nix will use the [default credential provider +chain](https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/credentials.html) +for authenticating requests to Amazon S3. + +Nix supports authenticated reads from Amazon S3 and S3 compatible binary +caches. + +Your bucket will need a bucket policy allowing the desired users to +perform the `s3:GetObject` and `s3:GetBucketLocation` action on all +objects in the bucket. The [anonymous policy given +above](#anonymous-reads-to-your-s3-compatible-binary-cache) can be +updated to have a restricted `Principal` to support this. + +## Authenticated Writes to your S3-compatible binary cache + +Nix support fully supports writing to Amazon S3 and S3 compatible +buckets. The binary cache URL for our example bucket will be +. + +Nix will use the [default credential provider +chain](https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/credentials.html) +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": [ + { + "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: + +```console +$ nix copy nixpkgs.hello \ + --to 's3://example-nix-cache?profile=cache-upload®ion=eu-west-2' +``` + +To upload to an S3-compatible binary cache: + +```console +$ nix copy nixpkgs.hello --to \ + 's3://example-nix-cache?profile=cache-upload&scheme=https&endpoint=minio.example.com' +``` diff --git a/doc/manual/src/package-management/sharing-packages.md b/doc/manual/src/package-management/sharing-packages.md new file mode 100644 index 000000000..846ca6934 --- /dev/null +++ b/doc/manual/src/package-management/sharing-packages.md @@ -0,0 +1,6 @@ +# Sharing Packages Between Machines + +Sometimes you want to copy a package from one machine to another. Or, +you want to install some packages and you know that another machine +already has some or all of those packages or their dependencies. In that +case there are mechanisms to quickly copy packages between machines. diff --git a/doc/manual/src/package-management/ssh-substituter.md b/doc/manual/src/package-management/ssh-substituter.md new file mode 100644 index 000000000..6e5e258bc --- /dev/null +++ b/doc/manual/src/package-management/ssh-substituter.md @@ -0,0 +1,62 @@ +# Serving a Nix store via SSH + +You can tell Nix to automatically fetch needed binaries from a remote +Nix store via SSH. For example, the following installs Firefox, +automatically fetching any store paths in Firefox’s closure if they are +available on the server `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 +will first check if it’s available in the Nix store on `avalon`. If not, +it will fall back to using the binary cache substituter, and then to +building from source. + +> **Note** +> +> The SSH substituter currently does not allow you to enter an SSH +> passphrase interactively. Therefore, you should use `ssh-add` to load +> the decrypted private key into `ssh-agent`. + +You can also copy the closure of some store path, without installing it +into your profile, e.g. + +```console +$ nix-store -r /nix/store/m85bxg…-firefox-34.0.5 --substituters +ssh://alice@avalon +``` + +This is essentially equivalent to doing + +```console +$ nix-copy-closure --from alice@avalon +/nix/store/m85bxg…-firefox-34.0.5 +``` + +You can use SSH’s *forced command* feature to set up a restricted user +account for SSH substituter access, allowing read-only access to the +local Nix store, but nothing more. For example, add the following lines +to `sshd_config` to restrict the user `nix-ssh`: + + Match User nix-ssh + AllowAgentForwarding no + AllowTcpForwarding no + PermitTTY no + PermitTunnel no + X11Forwarding no + ForceCommand nix-store --serve + Match All + +On NixOS, you can accomplish the same by adding the following to your +`configuration.nix`: + +```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. diff --git a/doc/manual/src/quick-start.md b/doc/manual/src/quick-start.md new file mode 100644 index 000000000..71205923b --- /dev/null +++ b/doc/manual/src/quick-start.md @@ -0,0 +1,99 @@ +# Quick Start + +This chapter is for impatient people who don't like reading +documentation. For more in-depth information you are kindly referred +to subsequent chapters. + +1. Install single-user Nix by running the following: + + ```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 + other installation methods, see + [here](installation/installation.md).) + +1. See what installable packages are currently available in the + channel: + + ```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: + + ```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: + + ```console + $ which hello + /home/eelco/.nix-profile/bin/hello + $ hello + Hello, world! + ``` + +1. Uninstall a package: + + ```console + $ nix-env -e hello + ``` + +1. You can also test a package without installing it: + + ```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: + + ```console + [nix-shell:~]$ hello + Hello, world! + + [nix-shell:~]$ exit + + $ hello + hello: command not found + ``` + +1. To keep up-to-date with the channel, do: + + ```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 + numbers). + +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: + + ```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: + + ```console + $ nix-collect-garbage -d + ``` diff --git a/doc/manual/src/release-notes/release-notes.md b/doc/manual/src/release-notes/release-notes.md new file mode 100644 index 000000000..b05d5ee0a --- /dev/null +++ b/doc/manual/src/release-notes/release-notes.md @@ -0,0 +1 @@ +# Nix Release Notes diff --git a/doc/manual/src/release-notes/rl-0.10.1.md b/doc/manual/src/release-notes/rl-0.10.1.md new file mode 100644 index 000000000..e1ed6558a --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.10.1.md @@ -0,0 +1,5 @@ +# Release 0.10.1 (2006-10-11) + +This release fixes two somewhat obscure bugs that occur when evaluating +Nix expressions that are stored inside the Nix store (`NIX-67`). These +do not affect most users. diff --git a/doc/manual/src/release-notes/rl-0.10.md b/doc/manual/src/release-notes/rl-0.10.md new file mode 100644 index 000000000..1301add26 --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.10.md @@ -0,0 +1,212 @@ +# Release 0.10 (2006-10-06) + +> **Note** +> +> This version of Nix uses Berkeley DB 4.4 instead of 4.3. The database +> is upgraded automatically, but you should be careful not to use old +> versions of Nix that still use Berkeley DB 4.3. In particular, if you +> use a Nix installed through Nix, you should run +> +> $ nix-store --clear-substitutes +> +> first. + +> **Warning** +> +> Also, the database schema has changed slighted to fix a performance +> issue (see below). When you run any Nix 0.10 command for the first +> time, the database will be upgraded automatically. This is +> irreversible. + + - `nix-env` usability improvements: + + - An option `--compare-versions` (or `-c`) has been added to + `nix-env + --query` to allow you to compare installed versions of packages + to available versions, or vice versa. An easy way to see if you + are up to date with what’s in your subscribed channels is + `nix-env -qc \*`. + + - `nix-env --query` now takes as arguments a list of package names + about which to show information, just like `--install`, etc.: + for example, `nix-env -q gcc`. Note that to show all + derivations, you need to specify `\*`. + + - `nix-env -i + pkgname` will now install the highest available version of + *pkgname*, rather than installing all available versions (which + would probably give collisions) (`NIX-31`). + + - `nix-env (-i|-u) --dry-run` now shows exactly which missing + paths will be built or substituted. + + - `nix-env -qa --description` shows human-readable descriptions of + packages, provided that they have a `meta.description` attribute + (which most packages in Nixpkgs don’t have yet). + + - New language features: + + - Reference scanning (which happens after each build) is much + faster and takes a constant amount of memory. + + - String interpolation. Expressions like + + "--with-freetype2-library=" + freetype + "/lib" + + can now be written as + + "--with-freetype2-library=${freetype}/lib" + + You can write arbitrary expressions within `${...}`, not just + identifiers. + + - Multi-line string literals. + + - String concatenations can now involve derivations, as in the + example `"--with-freetype2-library=" + + freetype + "/lib"`. This was not previously possible because + we need to register that a derivation that uses such a string is + dependent on `freetype`. The evaluator now properly propagates + this information. Consequently, the subpath operator (`~`) has + been deprecated. + + - Default values of function arguments can now refer to other + function arguments; that is, all arguments are in scope in the + default values (`NIX-45`). + + - Lots of new built-in primitives, such as functions for list + manipulation and integer arithmetic. See the manual for a + complete list. All primops are now available in the set + `builtins`, allowing one to test for the availability of primop + in a backwards-compatible way. + + - Real let-expressions: `let x = ...; + ... z = ...; in ...`. + + - New commands `nix-pack-closure` and `nix-unpack-closure` than can be + used to easily transfer a store path with all its dependencies to + another machine. Very convenient whenever you have some package on + your machine and you want to copy it somewhere else. + + - XML support: + + - `nix-env -q --xml` prints the installed or available packages in + an XML representation for easy processing by other tools. + + - `nix-instantiate --eval-only + --xml` prints an XML representation of the resulting term. (The + new flag `--strict` forces ‘deep’ evaluation of the result, + i.e., list elements and attributes are evaluated recursively.) + + - In Nix expressions, the primop `builtins.toXML` converts a term + to an XML representation. This is primarily useful for passing + structured information to builders. + + - You can now unambiguously specify which derivation to build or + install in `nix-env`, `nix-instantiate` and `nix-build` using the + `--attr` / `-A` flags, which takes an attribute name as argument. + (Unlike symbolic package names such as `subversion-1.4.0`, attribute + names in an attribute set are unique.) For instance, a quick way to + perform a test build of a package in Nixpkgs is `nix-build + pkgs/top-level/all-packages.nix -A + foo`. `nix-env -q + --attr` shows the attribute names corresponding to each derivation. + + - If the top-level Nix expression used by `nix-env`, `nix-instantiate` + or `nix-build` evaluates to a function whose arguments all have + default values, the function will be called automatically. Also, the + new command-line switch `--arg + name + value` can be used to specify function arguments on the command + line. + + - `nix-install-package --url + URL` allows a package to be installed directly from the given URL. + + - Nix now works behind an HTTP proxy server; just set the standard + environment variables `http_proxy`, `https_proxy`, `ftp_proxy` or + `all_proxy` appropriately. Functions such as `fetchurl` in Nixpkgs + also respect these variables. + + - `nix-build -o + symlink` allows the symlink to the build result to be named + something other than `result`. + + - Platform support: + + - Support for 64-bit platforms, provided a [suitably patched ATerm + library](http://bugzilla.sen.cwi.nl:8080/show_bug.cgi?id=606) is + used. Also, files larger than 2 GiB are now supported. + + - Added support for Cygwin (Windows, `i686-cygwin`), Mac OS X on + Intel (`i686-darwin`) and Linux on PowerPC (`powerpc-linux`). + + - Users of SMP and multicore machines will appreciate that the + number of builds to be performed in parallel can now be + specified in the configuration file in the `build-max-jobs` + setting. + + - Garbage collector improvements: + + - Open files (such as running programs) are now used as roots of + the garbage collector. This prevents programs that have been + uninstalled from being garbage collected while they are still + running. The script that detects these additional runtime roots + (`find-runtime-roots.pl`) is inherently system-specific, but it + should work on Linux and on all platforms that have the `lsof` + utility. + + - `nix-store --gc` (a.k.a. `nix-collect-garbage`) prints out the + number of bytes freed on standard output. `nix-store + --gc --print-dead` shows how many bytes would be freed by an + actual garbage collection. + + - `nix-collect-garbage -d` removes all old generations of *all* + profiles before calling the actual garbage collector (`nix-store + --gc`). This is an easy way to get rid of all old packages in + the Nix store. + + - `nix-store` now has an operation `--delete` to delete specific + paths from the Nix store. It won’t delete reachable + (non-garbage) paths unless `--ignore-liveness` is specified. + + - Berkeley DB 4.4’s process registry feature is used to recover from + crashed Nix processes. + + - A performance issue has been fixed with the `referer` table, which + stores the inverse of the `references` table (i.e., it tells you + what store paths refer to a given path). Maintaining this table + could take a quadratic amount of time, as well as a quadratic amount + of Berkeley DB log file space (in particular when running the + garbage collector) (`NIX-23`). + + - Nix now catches the `TERM` and `HUP` signals in addition to the + `INT` signal. So you can now do a `killall + nix-store` without triggering a database recovery. + + - `bsdiff` updated to version 4.3. + + - Substantial performance improvements in expression evaluation and + `nix-env -qa`, all thanks to [Valgrind](http://valgrind.org/). + Memory use has been reduced by a factor 8 or so. Big speedup by + memoisation of path hashing. + + - Lots of bug fixes, notably: + + - Make sure that the garbage collector can run successfully when + the disk is full (`NIX-18`). + + - `nix-env` now locks the profile to prevent races between + concurrent `nix-env` operations on the same profile (`NIX-7`). + + - Removed misleading messages from `nix-env -i` (e.g., + ``installing + `foo'`` followed by ``uninstalling + `foo'``) (`NIX-17`). + + - Nix source distributions are a lot smaller now since we no longer + include a full copy of the Berkeley DB source distribution (but only + the bits we need). + + - Header files are now installed so that external programs can use the + Nix libraries. diff --git a/doc/manual/src/release-notes/rl-0.11.md b/doc/manual/src/release-notes/rl-0.11.md new file mode 100644 index 000000000..d2f4d73aa --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.11.md @@ -0,0 +1,167 @@ +# Release 0.11 (2007-12-31) + +Nix 0.11 has many improvements over the previous stable release. The +most important improvement is secure multi-user support. It also +features many usability enhancements and language extensions, many of +them prompted by NixOS, the purely functional Linux distribution based +on Nix. Here is an (incomplete) list: + + - Secure multi-user support. A single Nix store can now be shared + between multiple (possible untrusted) users. This is an important + feature for NixOS, where it allows non-root users to install + software. The old setuid method for sharing a store between multiple + users has been removed. Details for setting up a multi-user store + can be found in the manual. + + - The new command `nix-copy-closure` gives you an easy and efficient + way to exchange software between machines. It copies the missing + parts of the closure of a set of store path to or from a remote + machine via `ssh`. + + - A new kind of string literal: strings between double single-quotes + (`''`) have indentation “intelligently” removed. This allows large + strings (such as shell scripts or configuration file fragments in + NixOS) to cleanly follow the indentation of the surrounding + expression. It also requires much less escaping, since `''` is less + common in most languages than `"`. + + - `nix-env` `--set` modifies the current generation of a profile so + that it contains exactly the specified derivation, and nothing else. + For example, `nix-env -p /nix/var/nix/profiles/browser --set + firefox` lets the profile named `browser` contain just Firefox. + + - `nix-env` now maintains meta-information about installed packages in + profiles. The meta-information is the contents of the `meta` + attribute of derivations, such as `description` or `homepage`. The + command `nix-env -q --xml + --meta` shows all meta-information. + + - `nix-env` now uses the `meta.priority` attribute of derivations to + resolve filename collisions between packages. Lower priority values + denote a higher priority. For instance, the GCC wrapper package and + the Binutils package in Nixpkgs both have a file `bin/ld`, so + previously if you tried to install both you would get a collision. + Now, on the other hand, the GCC wrapper declares a higher priority + than Binutils, so the former’s `bin/ld` is symlinked in the user + environment. + + - `nix-env -i / -u`: instead of breaking package ties by version, + break them by priority and version number. That is, if there are + multiple packages with the same name, then pick the package with the + highest priority, and only use the version if there are multiple + packages with the same priority. + + This makes it possible to mark specific versions/variant in Nixpkgs + more or less desirable than others. A typical example would be a + beta version of some package (e.g., `gcc-4.2.0rc1`) which should not + be installed even though it is the highest version, except when it + is explicitly selected (e.g., `nix-env -i + gcc-4.2.0rc1`). + + - `nix-env --set-flag` allows meta attributes of installed packages to + be modified. There are several attributes that can be usefully + modified, because they affect the behaviour of `nix-env` or the user + environment build script: + + - `meta.priority` can be changed to resolve filename clashes (see + above). + + - `meta.keep` can be set to `true` to prevent the package from + being upgraded or replaced. Useful if you want to hang on to an + older version of a package. + + - `meta.active` can be set to `false` to “disable” the package. + That is, no symlinks will be generated to the files of the + package, but it remains part of the profile (so it won’t be + garbage-collected). Set it back to `true` to re-enable the + package. + + - `nix-env -q` now has a flag `--prebuilt-only` (`-b`) that causes + `nix-env` to show only those derivations whose output is already in + the Nix store or that can be substituted (i.e., downloaded from + somewhere). In other words, it shows the packages that can be + installed “quickly”, i.e., don’t need to be built from source. The + `-b` flag is also available in `nix-env -i` and `nix-env -u` to + filter out derivations for which no pre-built binary is available. + + - The new option `--argstr` (in `nix-env`, `nix-instantiate` and + `nix-build`) is like `--arg`, except that the value is a string. For + example, `--argstr system + i686-linux` is equivalent to `--arg system + \"i686-linux\"` (note that `--argstr` prevents annoying quoting + around shell arguments). + + - `nix-store` has a new operation `--read-log` (`-l`) `paths` that + shows the build log of the given paths. + + - Nix now uses Berkeley DB 4.5. The database is upgraded + automatically, but you should be careful not to use old versions of + Nix that still use Berkeley DB 4.4. + + - The option `--max-silent-time` (corresponding to the configuration + setting `build-max-silent-time`) allows you to set a timeout on + builds — if a build produces no output on `stdout` or `stderr` for + the given number of seconds, it is terminated. This is useful for + recovering automatically from builds that are stuck in an infinite + loop. + + - `nix-channel`: each subscribed channel is its own attribute in the + top-level expression generated for the channel. This allows + disambiguation (e.g. `nix-env + -i -A nixpkgs_unstable.firefox`). + + - The substitutes table has been removed from the database. This makes + operations such as `nix-pull` and `nix-channel --update` much, much + faster. + + - `nix-pull` now supports bzip2-compressed manifests. This speeds up + channels. + + - `nix-prefetch-url` now has a limited form of caching. This is used + by `nix-channel` to prevent unnecessary downloads when the channel + hasn’t changed. + + - `nix-prefetch-url` now by default computes the SHA-256 hash of the + file instead of the MD5 hash. In calls to `fetchurl` you should pass + the `sha256` attribute instead of `md5`. You can pass either a + hexadecimal or a base-32 encoding of the hash. + + - Nix can now perform builds in an automatically generated “chroot”. + This prevents a builder from accessing stuff outside of the Nix + store, and thus helps ensure purity. This is an experimental + feature. + + - The new command `nix-store + --optimise` reduces Nix store disk space usage by finding identical + files in the store and hard-linking them to each other. It typically + reduces the size of the store by something like 25-35%. + + - `~/.nix-defexpr` can now be a directory, in which case the Nix + expressions in that directory are combined into an attribute set, + with the file names used as the names of the attributes. The command + `nix-env + --import` (which set the `~/.nix-defexpr` symlink) is removed. + + - Derivations can specify the new special attribute + `allowedReferences` to enforce that the references in the output of + a derivation are a subset of a declared set of paths. For example, + if `allowedReferences` is an empty list, then the output must not + have any references. This is used in NixOS to check that generated + files such as initial ramdisks for booting Linux don’t have any + dependencies. + + - The new attribute `exportReferencesGraph` allows builders access to + the references graph of their inputs. This is used in NixOS for + tasks such as generating ISO-9660 images that contain a Nix store + populated with the closure of certain paths. + + - Fixed-output derivations (like `fetchurl`) can define the attribute + `impureEnvVars` to allow external environment variables to be passed + to builders. This is used in Nixpkgs to support proxy configuration, + among other things. + + - Several new built-in functions: `builtins.attrNames`, + `builtins.filterSource`, `builtins.isAttrs`, `builtins.isFunction`, + `builtins.listToAttrs`, `builtins.stringLength`, `builtins.sub`, + `builtins.substring`, `throw`, `builtins.trace`, + `builtins.readFile`. diff --git a/doc/manual/src/release-notes/rl-0.12.md b/doc/manual/src/release-notes/rl-0.12.md new file mode 100644 index 000000000..3a4aba07d --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.12.md @@ -0,0 +1,123 @@ +# Release 0.12 (2008-11-20) + + - Nix no longer uses Berkeley DB to store Nix store metadata. The + principal advantages of the new storage scheme are: it works + properly over decent implementations of NFS (allowing Nix stores to + be shared between multiple machines); no recovery is needed when a + Nix process crashes; no write access is needed for read-only + operations; no more running out of Berkeley DB locks on certain + operations. + + You still need to compile Nix with Berkeley DB support if you want + Nix to automatically convert your old Nix store to the new schema. + If you don’t need this, you can build Nix with the `configure` + option `--disable-old-db-compat`. + + After the automatic conversion to the new schema, you can delete the + old Berkeley DB files: + + $ cd /nix/var/nix/db + $ rm __db* log.* derivers references referrers reserved validpaths DB_CONFIG + + The new metadata is stored in the directories `/nix/var/nix/db/info` + and `/nix/var/nix/db/referrer`. Though the metadata is stored in + human-readable plain-text files, they are not intended to be + human-editable, as Nix is rather strict about the format. + + The new storage schema may or may not require less disk space than + the Berkeley DB environment, mostly depending on the cluster size of + your file system. With 1 KiB clusters (which seems to be the `ext3` + default nowadays) it usually takes up much less space. + + - There is a new substituter that copies paths directly from other + (remote) Nix stores mounted somewhere in the filesystem. For + instance, you can speed up an installation by mounting some remote + Nix store that already has the packages in question via NFS or + `sshfs`. The environment variable `NIX_OTHER_STORES` specifies the + locations of the remote Nix directories, e.g. `/mnt/remote-fs/nix`. + + - New `nix-store` operations `--dump-db` and `--load-db` to dump and + reload the Nix database. + + - The garbage collector has a number of new options to allow only some + of the garbage to be deleted. The option `--max-freed N` tells the + collector to stop after at least *N* bytes have been deleted. The + option `--max-links + N` tells it to stop after the link count on `/nix/store` has dropped + below *N*. This is useful for very large Nix stores on filesystems + with a 32000 subdirectories limit (like `ext3`). The option + `--use-atime` causes store paths to be deleted in order of ascending + last access time. This allows non-recently used stuff to be deleted. + The option `--max-atime time` specifies an upper limit to the last + accessed time of paths that may be deleted. For instance, + + ``` + $ nix-store --gc -v --max-atime $(date +%s -d "2 months ago") + ``` + + deletes everything that hasn’t been accessed in two months. + + - `nix-env` now uses optimistic profile locking when performing an + operation like installing or upgrading, instead of setting an + exclusive lock on the profile. This allows multiple `nix-env -i / -u + / -e` operations on the same profile in parallel. If a `nix-env` + operation sees at the end that the profile was changed in the + meantime by another process, it will just restart. This is generally + cheap because the build results are still in the Nix store. + + - The option `--dry-run` is now supported by `nix-store -r` and + `nix-build`. + + - The information previously shown by `--dry-run` (i.e., which + derivations will be built and which paths will be substituted) is + now always shown by `nix-env`, `nix-store -r` and `nix-build`. The + total download size of substitutable paths is now also shown. For + instance, a build will show something like + + the following derivations will be built: + /nix/store/129sbxnk5n466zg6r1qmq1xjv9zymyy7-activate-configuration.sh.drv + /nix/store/7mzy971rdm8l566ch8hgxaf89x7lr7ik-upstart-jobs.drv + ... + the following paths will be downloaded/copied (30.02 MiB): + /nix/store/4m8pvgy2dcjgppf5b4cj5l6wyshjhalj-samba-3.2.4 + /nix/store/7h1kwcj29ip8vk26rhmx6bfjraxp0g4l-libunwind-0.98.6 + ... + + - Language features: + + - @-patterns as in Haskell. For instance, in a function definition + + f = args @ {x, y, z}: ...; + + `args` refers to the argument as a whole, which is further + pattern-matched against the attribute set pattern `{x, y, z}`. + + - “`...`” (ellipsis) patterns. An attribute set pattern can now + say `...` at the end of the attribute name list to specify that + the function takes *at least* the listed attributes, while + ignoring additional attributes. For instance, + + {stdenv, fetchurl, fuse, ...}: ... + + defines a function that accepts any attribute set that includes + at least the three listed attributes. + + - New primops: `builtins.parseDrvName` (split a package name + string like `"nix-0.12pre12876"` into its name and version + components, e.g. `"nix"` and `"0.12pre12876"`), + `builtins.compareVersions` (compare two version strings using + the same algorithm that `nix-env` uses), `builtins.length` + (efficiently compute the length of a list), `builtins.mul` + (integer multiplication), `builtins.div` (integer division). + + - `nix-prefetch-url` now supports `mirror://` URLs, provided that the + environment variable `NIXPKGS_ALL` points at a Nixpkgs tree. + + - Removed the commands `nix-pack-closure` and `nix-unpack-closure`. + You can do almost the same thing but much more efficiently by doing + `nix-store --export + $(nix-store -qR paths) > closure` and `nix-store --import < + closure`. + + - Lots of bug fixes, including a big performance bug in the handling + of `with`-expressions. diff --git a/doc/manual/src/release-notes/rl-0.13.md b/doc/manual/src/release-notes/rl-0.13.md new file mode 100644 index 000000000..13a60e01c --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.13.md @@ -0,0 +1,55 @@ +# Release 0.13 (2009-11-05) + +This is primarily a bug fix release. It has some new features: + + - Syntactic sugar for writing nested attribute sets. Instead of + + { + foo = { + bar = 123; + xyzzy = true; + }; + a = { b = { c = "d"; }; }; + } + + you can write + + { + foo.bar = 123; + foo.xyzzy = true; + a.b.c = "d"; + } + + This is useful, for instance, in NixOS configuration files. + + - Support for Nix channels generated by Hydra, the Nix-based + continuous build system. (Hydra generates NAR archives on the fly, + so the size and hash of these archives isn’t known in advance.) + + - Support `i686-linux` builds directly on `x86_64-linux` Nix + installations. This is implemented using the `personality()` + syscall, which causes `uname` to return `i686` in child processes. + + - Various improvements to the `chroot` support. Building in a `chroot` + works quite well now. + + - Nix no longer blocks if it tries to build a path and another process + is already building the same path. Instead it tries to build another + buildable path first. This improves parallelism. + + - Support for large (\> 4 GiB) files in NAR archives. + + - Various (performance) improvements to the remote build mechanism. + + - New primops: `builtins.addErrorContext` (to add a string to stack + traces — useful for debugging), `builtins.isBool`, + `builtins.isString`, `builtins.isInt`, `builtins.intersectAttrs`. + + - OpenSolaris support (Sander van der Burg). + + - Stack traces are no longer displayed unless the `--show-trace` + option is used. + + - The scoping rules for `inherit + (e) ...` in recursive attribute sets have changed. The expression + *e* can now refer to the attributes defined in the containing set. diff --git a/doc/manual/src/release-notes/rl-0.14.md b/doc/manual/src/release-notes/rl-0.14.md new file mode 100644 index 000000000..9d58f2072 --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.14.md @@ -0,0 +1,21 @@ +# Release 0.14 (2010-02-04) + +This release has the following improvements: + + - The garbage collector now starts deleting garbage much faster than + before. It no longer determines liveness of all paths in the store, + but does so on demand. + + - Added a new operation, `nix-store --query + --roots`, that shows the garbage collector roots that directly or + indirectly point to the given store paths. + + - Removed support for converting Berkeley DB-based Nix databases to + the new schema. + + - Removed the `--use-atime` and `--max-atime` garbage collector + options. They were not very useful in practice. + + - On Windows, Nix now requires Cygwin 1.7.x. + + - A few bug fixes. diff --git a/doc/manual/src/release-notes/rl-0.15.md b/doc/manual/src/release-notes/rl-0.15.md new file mode 100644 index 000000000..48e2a6f1b --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.15.md @@ -0,0 +1,5 @@ +# Release 0.15 (2010-03-17) + +This is a bug-fix release. Among other things, it fixes building on Mac +OS X (Snow Leopard), and improves the contents of `/etc/passwd` and +`/etc/group` in `chroot` builds. diff --git a/doc/manual/src/release-notes/rl-0.16.md b/doc/manual/src/release-notes/rl-0.16.md new file mode 100644 index 000000000..23ac53786 --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.16.md @@ -0,0 +1,25 @@ +# Release 0.16 (2010-08-17) + +This release has the following improvements: + + - The Nix expression evaluator is now much faster in most cases: + typically, [3 to 8 times compared to the old + implementation](http://www.mail-archive.com/nix-dev@cs.uu.nl/msg04113.html). + It also uses less memory. It no longer depends on the ATerm library. + + - Support for configurable parallelism inside builders. Build scripts + have always had the ability to perform multiple build actions in + parallel (for instance, by running `make -j + 2`), but this was not desirable because the number of actions to be + performed in parallel was not configurable. Nix now has an option + `--cores + N` as well as a configuration setting `build-cores = + N` that causes the environment variable `NIX_BUILD_CORES` to be set + to *N* when the builder is invoked. The builder can use this at its + discretion to perform a parallel build, e.g., by calling `make -j + N`. In Nixpkgs, this can be enabled on a per-package basis by + setting the derivation attribute `enableParallelBuilding` to `true`. + + - `nix-store -q` now supports XML output through the `--xml` flag. + + - Several bug fixes. diff --git a/doc/manual/src/release-notes/rl-0.5.md b/doc/manual/src/release-notes/rl-0.5.md new file mode 100644 index 000000000..5cff2da0b --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.5.md @@ -0,0 +1,3 @@ +# Release 0.5 and earlier + +Please refer to the Subversion commit log messages. diff --git a/doc/manual/src/release-notes/rl-0.6.md b/doc/manual/src/release-notes/rl-0.6.md new file mode 100644 index 000000000..ed2d21583 --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.6.md @@ -0,0 +1,64 @@ +# Release 0.6 (2004-11-14) + + - Rewrite of the normalisation engine. + + - Multiple builds can now be performed in parallel (option `-j`). + + - Distributed builds. Nix can now call a shell script to forward + builds to Nix installations on remote machines, which may or may + not be of the same platform type. + + - Option `--fallback` allows recovery from broken substitutes. + + - Option `--keep-going` causes building of other (unaffected) + derivations to continue if one failed. + + - Improvements to the garbage collector (i.e., it should actually work + now). + + - Setuid Nix installations allow a Nix store to be shared among + multiple users. + + - Substitute registration is much faster now. + + - A utility `nix-build` to build a Nix expression and create a symlink + to the result int the current directory; useful for testing Nix + derivations. + + - Manual updates. + + - `nix-env` changes: + + - Derivations for other platforms are filtered out (which can be + overridden using `--system-filter`). + + - `--install` by default now uninstall previous derivations with + the same name. + + - `--upgrade` allows upgrading to a specific version. + + - New operation `--delete-generations` to remove profile + generations (necessary for effective garbage collection). + + - Nicer output (sorted, columnised). + + - More sensible verbosity levels all around (builder output is now + shown always, unless `-Q` is given). + + - Nix expression language changes: + + - New language construct: `with + E1; + E2` brings all attributes defined in the attribute set *E1* in + scope in *E2*. + + - Added a `map` function. + + - Various new operators (e.g., string concatenation). + + - Expression evaluation is much faster. + + - An Emacs mode for editing Nix expressions (with syntax highlighting + and indentation) has been added. + + - Many bug fixes. diff --git a/doc/manual/src/release-notes/rl-0.7.md b/doc/manual/src/release-notes/rl-0.7.md new file mode 100644 index 000000000..d873fe890 --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.7.md @@ -0,0 +1,21 @@ +# Release 0.7 (2005-01-12) + + - Binary patching. When upgrading components using pre-built binaries + (through nix-pull / nix-channel), Nix can automatically download and + apply binary patches to already installed components instead of full + downloads. Patching is “smart”: if there is a *sequence* of patches + to an installed component, Nix will use it. Patches are currently + generated automatically between Nixpkgs (pre-)releases. + + - Simplifications to the substitute mechanism. + + - Nix-pull now stores downloaded manifests in + `/nix/var/nix/manifests`. + + - Metadata on files in the Nix store is canonicalised after builds: + the last-modified timestamp is set to 0 (00:00:00 1/1/1970), the + mode is set to 0444 or 0555 (readable and possibly executable by + all; setuid/setgid bits are dropped), and the group is set to the + default. This ensures that the result of a build and an installation + through a substitute is the same; and that timestamp dependencies + are revealed. diff --git a/doc/manual/src/release-notes/rl-0.8.1.md b/doc/manual/src/release-notes/rl-0.8.1.md new file mode 100644 index 000000000..7629f81cb --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.8.1.md @@ -0,0 +1,8 @@ +# Release 0.8.1 (2005-04-13) + +This is a bug fix release. + + - Patch downloading was broken. + + - The garbage collector would not delete paths that had references + from invalid (but substitutable) paths. diff --git a/doc/manual/src/release-notes/rl-0.8.md b/doc/manual/src/release-notes/rl-0.8.md new file mode 100644 index 000000000..626c0c92b --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.8.md @@ -0,0 +1,166 @@ +# Release 0.8 (2005-04-11) + +NOTE: the hashing scheme in Nix 0.8 changed (as detailed below). As a +result, `nix-pull` manifests and channels built for Nix 0.7 and below +will not work anymore. However, the Nix expression language has not +changed, so you can still build from source. Also, existing user +environments continue to work. Nix 0.8 will automatically upgrade the +database schema of previous installations when it is first run. + +If you get the error message + + you have an old-style manifest `/nix/var/nix/manifests/[...]'; please + delete it + +you should delete previously downloaded manifests: + + $ rm /nix/var/nix/manifests/* + +If `nix-channel` gives the error message + + manifest `http://catamaran.labs.cs.uu.nl/dist/nix/channels/[channel]/MANIFEST' + is too old (i.e., for Nix <= 0.7) + +then you should unsubscribe from the offending channel (`nix-channel +--remove +URL`; leave out `/MANIFEST`), and subscribe to the same URL, with +`channels` replaced by `channels-v3` (e.g., +). + +Nix 0.8 has the following improvements: + + - The cryptographic hashes used in store paths are now 160 bits long, + but encoded in base-32 so that they are still only 32 characters + long (e.g., + `/nix/store/csw87wag8bqlqk7ipllbwypb14xainap-atk-1.9.0`). (This is + actually a 160 bit truncation of a SHA-256 hash.) + + - Big cleanups and simplifications of the basic store semantics. The + notion of “closure store expressions” is gone (and so is the notion + of “successors”); the file system references of a store path are now + just stored in the database. + + For instance, given any store path, you can query its closure: + + $ nix-store -qR $(which firefox) + ... lots of paths ... + + Also, Nix now remembers for each store path the derivation that + built it (the “deriver”): + + $ nix-store -qR $(which firefox) + /nix/store/4b0jx7vq80l9aqcnkszxhymsf1ffa5jd-firefox-1.0.1.drv + + So to see the build-time dependencies, you can do + + $ nix-store -qR $(nix-store -qd $(which firefox)) + + or, in a nicer format: + + $ nix-store -q --tree $(nix-store -qd $(which firefox)) + + File system references are also stored in reverse. For instance, you + can query all paths that directly or indirectly use a certain Glibc: + + $ nix-store -q --referrers-closure \ + /nix/store/8lz9yc6zgmc0vlqmn2ipcpkjlmbi51vv-glibc-2.3.4 + + - The concept of fixed-output derivations has been formalised. + Previously, functions such as `fetchurl` in Nixpkgs used a hack + (namely, explicitly specifying a store path hash) to prevent changes + to, say, the URL of the file from propagating upwards through the + dependency graph, causing rebuilds of everything. This can now be + done cleanly by specifying the `outputHash` and `outputHashAlgo` + attributes. Nix itself checks that the content of the output has the + specified hash. (This is important for maintaining certain + invariants necessary for future work on secure shared stores.) + + - One-click installation :-) It is now possible to install any + top-level component in Nixpkgs directly, through the web — see, + e.g., . All you + have to do is associate `/nix/bin/nix-install-package` with the MIME + type `application/nix-package` (or the extension `.nixpkg`), and + clicking on a package link will cause it to be installed, with all + appropriate dependencies. If you just want to install some specific + application, this is easier than subscribing to a channel. + + - `nix-store -r + PATHS` now builds all the derivations PATHS in parallel. Previously + it did them sequentially (though exploiting possible parallelism + between subderivations). This is nice for build farms. + + - `nix-channel` has new operations `--list` and `--remove`. + + - New ways of installing components into user environments: + + - Copy from another user environment: + + $ nix-env -i --from-profile .../other-profile firefox + + - Install a store derivation directly (bypassing the Nix + expression language entirely): + + $ nix-env -i /nix/store/z58v41v21xd3...-aterm-2.3.1.drv + + (This is used to implement `nix-install-package`, which is + therefore immune to evolution in the Nix expression language.) + + - Install an already built store path directly: + + $ nix-env -i /nix/store/hsyj5pbn0d9i...-aterm-2.3.1 + + - Install the result of a Nix expression specified as a + command-line argument: + + $ nix-env -f .../i686-linux.nix -i -E 'x: x.firefoxWrapper' + + The difference with the normal installation mode is that `-E` + does not use the `name` attributes of derivations. Therefore, + this can be used to disambiguate multiple derivations with the + same name. + + - A hash of the contents of a store path is now stored in the database + after a successful build. This allows you to check whether store + paths have been tampered with: `nix-store + --verify --check-contents`. + + - Implemented a concurrent garbage collector. It is now always safe to + run the garbage collector, even if other Nix operations are + happening simultaneously. + + However, there can still be GC races if you use `nix-instantiate` + and `nix-store + --realise` directly to build things. To prevent races, use the + `--add-root` flag of those commands. + + - The garbage collector now finally deletes paths in the right order + (i.e., topologically sorted under the “references” relation), thus + making it safe to interrupt the collector without risking a store + that violates the closure invariant. + + - Likewise, the substitute mechanism now downloads files in the right + order, thus preserving the closure invariant at all times. + + - The result of `nix-build` is now registered as a root of the garbage + collector. If the `./result` link is deleted, the GC root disappears + automatically. + + - The behaviour of the garbage collector can be changed globally by + setting options in `/nix/etc/nix/nix.conf`. + + - `gc-keep-derivations` specifies whether deriver links should be + followed when searching for live paths. + + - `gc-keep-outputs` specifies whether outputs of derivations + should be followed when searching for live paths. + + - `env-keep-derivations` specifies whether user environments + should store the paths of derivations when they are added (thus + keeping the derivations alive). + + - New `nix-env` query flags `--drv-path` and `--out-path`. + + - `fetchurl` allows SHA-1 and SHA-256 in addition to MD5. Just specify + the attribute `sha1` or `sha256` instead of `md5`. + + - Manual updates. diff --git a/doc/manual/src/release-notes/rl-0.9.1.md b/doc/manual/src/release-notes/rl-0.9.1.md new file mode 100644 index 000000000..9c20eed1b --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.9.1.md @@ -0,0 +1,4 @@ +# Release 0.9.1 (2005-09-20) + +This bug fix release addresses a problem with the ATerm library when the +`--with-aterm` flag in `configure` was *not* used. diff --git a/doc/manual/src/release-notes/rl-0.9.2.md b/doc/manual/src/release-notes/rl-0.9.2.md new file mode 100644 index 000000000..0caaf28de --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.9.2.md @@ -0,0 +1,11 @@ +# Release 0.9.2 (2005-09-21) + +This bug fix release fixes two problems on Mac OS X: + + - If Nix was linked against statically linked versions of the ATerm or + Berkeley DB library, there would be dynamic link errors at runtime. + + - `nix-pull` and `nix-push` intermittently failed due to race + conditions involving pipes and child processes with error messages + such as `open2: open(GLOB(0x180b2e4), >&=9) failed: Bad + file descriptor at /nix/bin/nix-pull line 77` (issue `NIX-14`). diff --git a/doc/manual/src/release-notes/rl-0.9.md b/doc/manual/src/release-notes/rl-0.9.md new file mode 100644 index 000000000..8c3e1b28e --- /dev/null +++ b/doc/manual/src/release-notes/rl-0.9.md @@ -0,0 +1,72 @@ +# Release 0.9 (2005-09-16) + +NOTE: this version of Nix uses Berkeley DB 4.3 instead of 4.2. The +database is upgraded automatically, but you should be careful not to use +old versions of Nix that still use Berkeley DB 4.2. In particular, if +you use a Nix installed through Nix, you should run + + $ nix-store --clear-substitutes + +first. + + - Unpacking of patch sequences is much faster now since we no longer + do redundant unpacking and repacking of intermediate paths. + + - Nix now uses Berkeley DB 4.3. + + - The `derivation` primitive is lazier. Attributes of dependent + derivations can mutually refer to each other (as long as there are + no data dependencies on the `outPath` and `drvPath` attributes + computed by `derivation`). + + For example, the expression `derivation + attrs` now evaluates to (essentially) + + attrs // { + type = "derivation"; + outPath = derivation! attrs; + drvPath = derivation! attrs; + } + + where `derivation!` is a primop that does the actual derivation + instantiation (i.e., it does what `derivation` used to do). The + advantage is that it allows commands such as `nix-env -qa` and + `nix-env -i` to be much faster since they no longer need to + instantiate all derivations, just the `name` attribute. + + Also, it allows derivations to cyclically reference each other, for + example, + + webServer = derivation { + ... + hostName = "svn.cs.uu.nl"; + services = [svnService]; + }; + + svnService = derivation { + ... + hostName = webServer.hostName; + }; + + Previously, this would yield a black hole (infinite recursion). + + - `nix-build` now defaults to using `./default.nix` if no Nix + expression is specified. + + - `nix-instantiate`, when applied to a Nix expression that evaluates + to a function, will call the function automatically if all its + arguments have defaults. + + - Nix now uses libtool to build dynamic libraries. This reduces the + size of executables. + + - A new list concatenation operator `++`. For example, `[1 2 3] ++ + [4 5 + 6]` evaluates to `[1 2 3 4 5 + 6]`. + + - Some currently undocumented primops to support low-level build + management using Nix (i.e., using Nix as a Make replacement). See + the commit messages for `r3578` and `r3580`. + + - Various bug fixes and performance improvements. diff --git a/doc/manual/src/release-notes/rl-1.0.md b/doc/manual/src/release-notes/rl-1.0.md new file mode 100644 index 000000000..cdb257787 --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.0.md @@ -0,0 +1,68 @@ +# Release 1.0 (2012-05-11) + +There have been numerous improvements and bug fixes since the previous +release. Here are the most significant: + + - Nix can now optionally use the Boehm garbage collector. This + significantly reduces the Nix evaluator’s memory footprint, + especially when evaluating large NixOS system configurations. It can + be enabled using the `--enable-gc` configure option. + + - Nix now uses SQLite for its database. This is faster and more + flexible than the old *ad hoc* format. SQLite is also used to cache + the manifests in `/nix/var/nix/manifests`, resulting in a + significant speedup. + + - Nix now has an search path for expressions. The search path is set + using the environment variable `NIX_PATH` and the `-I` command line + option. In Nix expressions, paths between angle brackets are used to + specify files that must be looked up in the search path. For + instance, the expression `` looks for a file + `nixpkgs/default.nix` relative to every element in the search path. + + - The new command `nix-build --run-env` builds all dependencies of a + derivation, then starts a shell in an environment containing all + variables from the derivation. This is useful for reproducing the + environment of a derivation for development. + + - The new command `nix-store --verify-path` verifies that the contents + of a store path have not changed. + + - The new command `nix-store --print-env` prints out the environment + of a derivation in a format that can be evaluated by a shell. + + - Attribute names can now be arbitrary strings. For instance, you can + write `{ "foo-1.2" = …; "bla bla" = …; }."bla + bla"`. + + - Attribute selection can now provide a default value using the `or` + operator. For instance, the expression `x.y.z or e` evaluates to the + attribute `x.y.z` if it exists, and `e` otherwise. + + - The right-hand side of the `?` operator can now be an attribute + path, e.g., `attrs ? + a.b.c`. + + - On Linux, Nix will now make files in the Nix store immutable on + filesystems that support it. This prevents accidental modification + of files in the store by the root user. + + - Nix has preliminary support for derivations with multiple outputs. + This is useful because it allows parts of a package to be deployed + and garbage-collected separately. For instance, development parts of + a package such as header files or static libraries would typically + not be part of the closure of an application, resulting in reduced + disk usage and installation time. + + - The Nix store garbage collector is faster and holds the global lock + for a shorter amount of time. + + - The option `--timeout` (corresponding to the configuration setting + `build-timeout`) allows you to set an absolute timeout on builds — + if a build runs for more than the given number of seconds, it is + terminated. This is useful for recovering automatically from builds + that are stuck in an infinite loop but keep producing output, and + for which `--max-silent-time` is ineffective. + + - Nix development has moved to GitHub + (). diff --git a/doc/manual/src/release-notes/rl-1.1.md b/doc/manual/src/release-notes/rl-1.1.md new file mode 100644 index 000000000..1e658fe15 --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.1.md @@ -0,0 +1,61 @@ +# Release 1.1 (2012-07-18) + +This release has the following improvements: + + - On Linux, when doing a chroot build, Nix now uses various namespace + features provided by the Linux kernel to improve build isolation. + Namely: + + - The private network namespace ensures that builders cannot talk + to the outside world (or vice versa): each build only sees a + private loopback interface. This also means that two concurrent + builds can listen on the same port (e.g. as part of a test) + without conflicting with each other. + + - The PID namespace causes each build to start as PID 1. Processes + outside of the chroot are not visible to those on the inside. On + the other hand, processes inside the chroot *are* visible from + the outside (though with different PIDs). + + - The IPC namespace prevents the builder from communicating with + outside processes using SysV IPC mechanisms (shared memory, + message queues, semaphores). It also ensures that all IPC + objects are destroyed when the builder exits. + + - The UTS namespace ensures that builders see a hostname of + `localhost` rather than the actual hostname. + + - The private mount namespace was already used by Nix to ensure + that the bind-mounts used to set up the chroot are cleaned up + automatically. + + - Build logs are now compressed using `bzip2`. The command `nix-store + -l` decompresses them on the fly. This can be disabled by setting + the option `build-compress-log` to `false`. + + - The creation of build logs in `/nix/var/log/nix/drvs` can be + disabled by setting the new option `build-keep-log` to `false`. This + is useful, for instance, for Hydra build machines. + + - Nix now reserves some space in `/nix/var/nix/db/reserved` to ensure + that the garbage collector can run successfully if the disk is full. + This is necessary because SQLite transactions fail if the disk is + full. + + - Added a basic `fetchurl` function. This is not intended to replace + the `fetchurl` in Nixpkgs, but is useful for bootstrapping; e.g., it + will allow us to get rid of the bootstrap binaries in the Nixpkgs + source tree and download them instead. You can use it by doing + `import { url = + url; sha256 = + "hash"; }`. (Shea Levy) + + - Improved RPM spec file. (Michel Alexandre Salim) + + - Support for on-demand socket-based activation in the Nix daemon with + `systemd`. + + - Added a manpage for nix.conf5. + + - When using the Nix daemon, the `-s` flag in `nix-env -qa` is now + much faster. diff --git a/doc/manual/src/release-notes/rl-1.10.md b/doc/manual/src/release-notes/rl-1.10.md new file mode 100644 index 000000000..2bb859536 --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.10.md @@ -0,0 +1,31 @@ +# Release 1.10 (2015-09-03) + +This is primarily a bug fix release. It also has a number of new +features: + + - A number of builtin functions have been added to reduce + Nixpkgs/NixOS evaluation time and memory consumption: `all`, `any`, + `concatStringsSep`, `foldl’`, `genList`, `replaceStrings`, `sort`. + + - The garbage collector is more robust when the disk is full. + + - Nix supports a new API for building derivations that doesn’t require + a `.drv` file to be present on disk; it only requires an in-memory + representation of the derivation. This is used by the Hydra + continuous build system to make remote builds more efficient. + + - The function `` now uses a *builtin* builder (i.e. + it doesn’t require starting an external process; the download is + performed by Nix itself). This ensures that derivation paths don’t + change when Nix is upgraded, and obviates the need for ugly hacks to + support chroot execution. + + - `--version -v` now prints some configuration information, in + particular what compile-time optional features are enabled, and the + paths of various directories. + + - Build users have their supplementary groups set correctly. + +This release has contributions from Eelco Dolstra, Guillaume Maudoux, +Iwan Aucamp, Jaka Hudoklin, Kirill Elagin, Ludovic Courtès, Manolis +Ragkousis, Nicolas B. Pierron and Shea Levy. diff --git a/doc/manual/src/release-notes/rl-1.11.10.md b/doc/manual/src/release-notes/rl-1.11.10.md new file mode 100644 index 000000000..d1efe1d0b --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.11.10.md @@ -0,0 +1,21 @@ +# Release 1.11.10 (2017-06-12) + +This release fixes a security bug in Nix’s “build user” build isolation +mechanism. Previously, Nix builders had the ability to create setuid +binaries owned by a `nixbld` user. Such a binary could then be used by +an attacker to assume a `nixbld` identity and interfere with subsequent +builds running under the same UID. + +To prevent this issue, Nix now disallows builders to create setuid and +setgid binaries. On Linux, this is done using a seccomp BPF filter. Note +that this imposes a small performance penalty (e.g. 1% when building GNU +Hello). Using seccomp, we now also prevent the creation of extended +attributes and POSIX ACLs since these cannot be represented in the NAR +format and (in the case of POSIX ACLs) allow bypassing regular Nix store +permissions. On macOS, the restriction is implemented using the existing +sandbox mechanism, which now uses a minimal “allow all except the +creation of setuid/setgid binaries” profile when regular sandboxing is +disabled. On other platforms, the “build user” mechanism is now +disabled. + +Thanks go to Linus Heckemann for discovering and reporting this bug. diff --git a/doc/manual/src/release-notes/rl-1.11.md b/doc/manual/src/release-notes/rl-1.11.md new file mode 100644 index 000000000..fbabdaa2f --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.11.md @@ -0,0 +1,87 @@ +# Release 1.11 (2016-01-19) + +This is primarily a bug fix release. It also has a number of new +features: + + - `nix-prefetch-url` can now download URLs specified in a Nix + expression. For example, + + $ nix-prefetch-url -A hello.src + + will prefetch the file specified by the `fetchurl` call in the + attribute `hello.src` from the Nix expression in the current + directory, and print the cryptographic hash of the resulting file on + stdout. This differs from `nix-build -A + hello.src` in that it doesn't verify the hash, and is thus useful + when you’re updating a Nix expression. + + You can also prefetch the result of functions that unpack a tarball, + such as `fetchFromGitHub`. For example: + + $ nix-prefetch-url --unpack https://github.com/NixOS/patchelf/archive/0.8.tar.gz + + or from a Nix expression: + + $ nix-prefetch-url -A nix-repl.src + + - The builtin function `` now supports downloading + and unpacking NARs. This removes the need to have multiple downloads + in the Nixpkgs stdenv bootstrap process (like a separate busybox + binary for Linux, or curl/mkdir/sh/bzip2 for Darwin). Now all those + files can be combined into a single NAR, optionally compressed using + `xz`. + + - Nix now supports SHA-512 hashes for verifying fixed-output + derivations, and in `builtins.hashString`. + + - The new flag `--option build-repeat + N` will cause every build to be executed *N*+1 times. If the build + output differs between any round, the build is rejected, and the + output paths are not registered as valid. This is primarily useful + to verify build determinism. (We already had a `--check` option to + repeat a previously succeeded build. However, with `--check`, + non-deterministic builds are registered in the DB. Preventing that + is useful for Hydra to ensure that non-deterministic builds don't + end up getting published to the binary cache.) + + - The options `--check` and `--option + build-repeat N`, if they detect a difference between two runs of the + same derivation and `-K` is given, will make the output of the other + run available under `store-path-check`. This makes it easier to + investigate the non-determinism using tools like `diffoscope`, e.g., + + $ nix-build pkgs/stdenv/linux -A stage1.pkgs.zlib --check -K + error: derivation ‘/nix/store/l54i8wlw2265…-zlib-1.2.8.drv’ may not + be deterministic: output ‘/nix/store/11a27shh6n2i…-zlib-1.2.8’ + differs from ‘/nix/store/11a27shh6n2i…-zlib-1.2.8-check’ + + $ diffoscope /nix/store/11a27shh6n2i…-zlib-1.2.8 /nix/store/11a27shh6n2i…-zlib-1.2.8-check + … + ├── lib/libz.a + │ ├── metadata + │ │ @@ -1,15 +1,15 @@ + │ │ -rw-r--r-- 30001/30000 3096 Jan 12 15:20 2016 adler32.o + … + │ │ +rw-r--r-- 30001/30000 3096 Jan 12 15:28 2016 adler32.o + … + + - Improved FreeBSD support. + + - `nix-env -qa --xml --meta` now prints license information. + + - The maximum number of parallel TCP connections that the binary cache + substituter will use has been decreased from 150 to 25. This should + prevent upsetting some broken NAT routers, and also improves + performance. + + - All "chroot"-containing strings got renamed to "sandbox". In + particular, some Nix options got renamed, but the old names are + still accepted as lower-priority aliases. + +This release has contributions from Anders Claesson, Anthony Cowley, +Bjørn Forsman, Brian McKenna, Danny Wilson, davidak, Eelco Dolstra, +Fabian Schmitthenner, FrankHB, Ilya Novoselov, janus, Jim Garrison, John +Ericson, Jude Taylor, Ludovic Courtès, Manuel Jacob, Mathnerd314, Pascal +Wittmann, Peter Simons, Philip Potter, Preston Bennes, Rommel M. +Martinez, Sander van der Burg, Shea Levy, Tim Cuthbertson, Tuomas +Tynkkynen, Utku Demir and Vladimír Čunát. diff --git a/doc/manual/src/release-notes/rl-1.2.md b/doc/manual/src/release-notes/rl-1.2.md new file mode 100644 index 000000000..25b830955 --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.2.md @@ -0,0 +1,97 @@ +# Release 1.2 (2012-12-06) + +This release has the following improvements and changes: + + - Nix has a new binary substituter mechanism: the *binary cache*. A + binary cache contains pre-built binaries of Nix packages. Whenever + Nix wants to build a missing Nix store path, it will check a set of + binary caches to see if any of them has a pre-built binary of that + path. The configuration setting `binary-caches` contains a list of + URLs of binary caches. For instance, doing + + $ nix-env -i thunderbird --option binary-caches http://cache.nixos.org + + will install Thunderbird and its dependencies, using the available + pre-built binaries in . The main advantage + over the old “manifest”-based method of getting pre-built binaries + is that you don’t have to worry about your manifest being in sync + with the Nix expressions you’re installing from; i.e., you don’t + need to run `nix-pull` to update your manifest. It’s also more + scalable because you don’t need to redownload a giant manifest file + every time. + + A Nix channel can provide a binary cache URL that will be used + automatically if you subscribe to that channel. If you use the + Nixpkgs or NixOS channels () you + automatically get the cache . + + Binary caches are created using `nix-push`. For details on the + operation and format of binary caches, see the `nix-push` manpage. + More details are provided in [this nix-dev + posting](https://nixos.org/nix-dev/2012-September/009826.html). + + - Multiple output support should now be usable. A derivation can + declare that it wants to produce multiple store paths by saying + something like + + outputs = [ "lib" "headers" "doc" ]; + + This will cause Nix to pass the intended store path of each output + to the builder through the environment variables `lib`, `headers` + and `doc`. Other packages can refer to a specific output by + referring to `pkg.output`, e.g. + + buildInputs = [ pkg.lib pkg.headers ]; + + If you install a package with multiple outputs using `nix-env`, each + output path will be symlinked into the user environment. + + - Dashes are now valid as part of identifiers and attribute names. + + - The new operation `nix-store --repair-path` allows corrupted or + missing store paths to be repaired by redownloading them. `nix-store + --verify --check-contents + --repair` will scan and repair all paths in the Nix store. + Similarly, `nix-env`, `nix-build`, `nix-instantiate` and `nix-store + --realise` have a `--repair` flag to detect and fix bad paths by + rebuilding or redownloading them. + + - Nix no longer sets the immutable bit on files in the Nix store. + Instead, the recommended way to guard the Nix store against + accidental modification on Linux is to make it a read-only bind + mount, like this: + + $ mount --bind /nix/store /nix/store + $ mount -o remount,ro,bind /nix/store + + Nix will automatically make `/nix/store` writable as needed (using a + private mount namespace) to allow modifications. + + - Store optimisation (replacing identical files in the store with hard + links) can now be done automatically every time a path is added to + the store. This is enabled by setting the configuration option + `auto-optimise-store` to `true` (disabled by default). + + - Nix now supports `xz` compression for NARs in addition to `bzip2`. + It compresses about 30% better on typical archives and decompresses + about twice as fast. + + - Basic Nix expression evaluation profiling: setting the environment + variable `NIX_COUNT_CALLS` to `1` will cause Nix to print how many + times each primop or function was executed. + + - New primops: `concatLists`, `elem`, `elemAt` and `filter`. + + - The command `nix-copy-closure` has a new flag `--use-substitutes` + (`-s`) to download missing paths on the target machine using the + substitute mechanism. + + - The command `nix-worker` has been renamed to `nix-daemon`. Support + for running the Nix worker in “slave” mode has been removed. + + - The `--help` flag of every Nix command now invokes `man`. + + - Chroot builds are now supported on systemd machines. + +This release has contributions from Eelco Dolstra, Florian Friesdorf, +Mats Erik Andersson and Shea Levy. diff --git a/doc/manual/src/release-notes/rl-1.3.md b/doc/manual/src/release-notes/rl-1.3.md new file mode 100644 index 000000000..0c7b48380 --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.3.md @@ -0,0 +1,10 @@ +# Release 1.3 (2013-01-04) + +This is primarily a bug fix release. When this version is first run on +Linux, it removes any immutable bits from the Nix store and increases +the schema version of the Nix store. (The previous release removed +support for setting the immutable bit; this release clears any remaining +immutable bits to make certain operations more efficient.) + +This release has contributions from Eelco Dolstra and Stuart +Pernsteiner. diff --git a/doc/manual/src/release-notes/rl-1.4.md b/doc/manual/src/release-notes/rl-1.4.md new file mode 100644 index 000000000..d23de71ad --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.4.md @@ -0,0 +1,22 @@ +# Release 1.4 (2013-02-26) + +This release fixes a security bug in multi-user operation. It was +possible for derivations to cause the mode of files outside of the Nix +store to be changed to 444 (read-only but world-readable) by creating +hard links to those files +([details](https://github.com/NixOS/nix/commit/5526a282b5b44e9296e61e07d7d2626a79141ac4)). + +There are also the following improvements: + + - New built-in function: `builtins.hashString`. + + - Build logs are now stored in `/nix/var/log/nix/drvs/XX/`, where *XX* + is the first two characters of the derivation. This is useful on + machines that keep a lot of build logs (such as Hydra servers). + + - The function `corepkgs/fetchurl` can now make the downloaded file + executable. This will allow getting rid of all bootstrap binaries in + the Nixpkgs source tree. + + - Language change: The expression `"${./path} + ..."` now evaluates to a string instead of a path. diff --git a/doc/manual/src/release-notes/rl-1.5.1.md b/doc/manual/src/release-notes/rl-1.5.1.md new file mode 100644 index 000000000..72b29518e --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.5.1.md @@ -0,0 +1,4 @@ +# Release 1.5.1 (2013-02-28) + +The bug fix to the bug fix had a bug itself, of course. But this time it +will work for sure\! diff --git a/doc/manual/src/release-notes/rl-1.5.2.md b/doc/manual/src/release-notes/rl-1.5.2.md new file mode 100644 index 000000000..508580554 --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.5.2.md @@ -0,0 +1,4 @@ +# Release 1.5.2 (2013-05-13) + +This is primarily a bug fix release. It has contributions from Eelco +Dolstra, Lluís Batlle i Rossell and Shea Levy. diff --git a/doc/manual/src/release-notes/rl-1.5.md b/doc/manual/src/release-notes/rl-1.5.md new file mode 100644 index 000000000..d2ccf8a5d --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.5.md @@ -0,0 +1,4 @@ +# Release 1.5 (2013-02-27) + +This is a brown paper bag release to fix a regression introduced by the +hard link security fix in 1.4. diff --git a/doc/manual/src/release-notes/rl-1.6.1.md b/doc/manual/src/release-notes/rl-1.6.1.md new file mode 100644 index 000000000..9bb9bb1f8 --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.6.1.md @@ -0,0 +1,32 @@ +# Release 1.6.1 (2013-10-28) + +This is primarily a bug fix release. Changes of interest are: + + - Nix 1.6 accidentally changed the semantics of antiquoted paths in + strings, such as `"${/foo}/bar"`. This release reverts to the Nix + 1.5.3 behaviour. + + - Previously, Nix optimised expressions such as `"${expr}"` to *expr*. + Thus it neither checked whether *expr* could be coerced to a string, + nor applied such coercions. This meant that `"${123}"` evaluatued to + `123`, and `"${./foo}"` evaluated to `./foo` (even though `"${./foo} + "` evaluates to `"/nix/store/hash-foo "`). Nix now checks the type + of antiquoted expressions and applies coercions. + + - Nix now shows the exact position of undefined variables. In + particular, undefined variable errors in a `with` previously didn't + show *any* position information, so this makes it a lot easier to + fix such errors. + + - Undefined variables are now treated consistently. Previously, the + `tryEval` function would catch undefined variables inside a `with` + but not outside. Now `tryEval` never catches undefined variables. + + - Bash completion in `nix-shell` now works correctly. + + - Stack traces are less verbose: they no longer show calls to builtin + functions and only show a single line for each derivation on the + call stack. + + - New built-in function: `builtins.typeOf`, which returns the type of + its argument as a string. diff --git a/doc/manual/src/release-notes/rl-1.6.md b/doc/manual/src/release-notes/rl-1.6.md new file mode 100644 index 000000000..9b83d9274 --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.6.md @@ -0,0 +1,72 @@ +# Release 1.6 (2013-09-10) + +In addition to the usual bug fixes, this release has several new +features: + + - The command `nix-build --run-env` has been renamed to `nix-shell`. + + - `nix-shell` now sources `$stdenv/setup` *inside* the interactive + shell, rather than in a parent shell. This ensures that shell + functions defined by `stdenv` can be used in the interactive shell. + + - `nix-shell` has a new flag `--pure` to clear the environment, so you + get an environment that more closely corresponds to the “real” Nix + build. + + - `nix-shell` now sets the shell prompt (`PS1`) to ensure that Nix + shells are distinguishable from your regular shells. + + - `nix-env` no longer requires a `*` argument to match all packages, + so `nix-env -qa` is equivalent to `nix-env + -qa '*'`. + + - `nix-env -i` has a new flag `--remove-all` (`-r`) to remove all + previous packages from the profile. This makes it easier to do + declarative package management similar to NixOS’s + `environment.systemPackages`. For instance, if you have a + specification `my-packages.nix` like this: + + with import {}; + [ thunderbird + geeqie + ... + ] + + then after any change to this file, you can run: + + $ nix-env -f my-packages.nix -ir + + to update your profile to match the specification. + + - The ‘`with`’ language construct is now more lazy. It only evaluates + its argument if a variable might actually refer to an attribute in + the argument. For instance, this now works: + + let + pkgs = with pkgs; { foo = "old"; bar = foo; } // overrides; + overrides = { foo = "new"; }; + in pkgs.bar + + This evaluates to `"new"`, while previously it gave an “infinite + recursion” error. + + - Nix now has proper integer arithmetic operators. For instance, you + can write `x + y` instead of `builtins.add x y`, or `x < + y` instead of `builtins.lessThan x y`. The comparison operators also + work on strings. + + - On 64-bit systems, Nix integers are now 64 bits rather than 32 bits. + + - When using the Nix daemon, the `nix-daemon` worker process now runs + on the same CPU as the client, on systems that support setting CPU + affinity. This gives a significant speedup on some systems. + + - If a stack overflow occurs in the Nix evaluator, you now get a + proper error message (rather than “Segmentation fault”) on some + systems. + + - In addition to directories, you can now bind-mount regular files in + chroots through the (now misnamed) option `build-chroot-dirs`. + +This release has contributions from Domen Kožar, Eelco Dolstra, Florian +Friesdorf, Gergely Risko, Ivan Kozik, Ludovic Courtès and Shea Levy. diff --git a/doc/manual/src/release-notes/rl-1.7.md b/doc/manual/src/release-notes/rl-1.7.md new file mode 100644 index 000000000..fb18e797d --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.7.md @@ -0,0 +1,140 @@ +# Release 1.7 (2014-04-11) + +In addition to the usual bug fixes, this release has the following new +features: + + - Antiquotation is now allowed inside of quoted attribute names (e.g. + `set."${foo}"`). In the case where the attribute name is just a + single antiquotation, the quotes can be dropped (e.g. the above + example can be written `set.${foo}`). If an attribute name inside of + a set declaration evaluates to `null` (e.g. `{ ${null} = false; }`), + then that attribute is not added to the set. + + - Experimental support for cryptographically signed binary caches. See + [the commit for + details](https://github.com/NixOS/nix/commit/0fdf4da0e979f992db75cc17376e455ddc5a96d8). + + - An experimental new substituter, `download-via-ssh`, that fetches + binaries from remote machines via SSH. Specifying the flags + `--option + use-ssh-substituter true --option ssh-substituter-hosts + user@hostname` will cause Nix to download binaries from the + specified machine, if it has them. + + - `nix-store -r` and `nix-build` have a new flag, `--check`, that + builds a previously built derivation again, and prints an error + message if the output is not exactly the same. This helps to verify + whether a derivation is truly deterministic. For example: + + $ nix-build '' -A patchelf + … + $ nix-build '' -A patchelf --check + … + error: derivation `/nix/store/1ipvxs…-patchelf-0.6' may not be deterministic: + hash mismatch in output `/nix/store/4pc1dm…-patchelf-0.6.drv' + + - The `nix-instantiate` flags `--eval-only` and `--parse-only` have + been renamed to `--eval` and `--parse`, respectively. + + - `nix-instantiate`, `nix-build` and `nix-shell` now have a flag + `--expr` (or `-E`) that allows you to specify the expression to be + evaluated as a command line argument. For instance, `nix-instantiate + --eval -E + '1 + 2'` will print `3`. + + - `nix-shell` improvements: + + - It has a new flag, `--packages` (or `-p`), that sets up a build + environment containing the specified packages from Nixpkgs. For + example, the command + + $ nix-shell -p sqlite xorg.libX11 hello + + will start a shell in which the given packages are present. + + - It now uses `shell.nix` as the default expression, falling back + to `default.nix` if the former doesn’t exist. This makes it + convenient to have a `shell.nix` in your project to set up a + nice development environment. + + - It evaluates the derivation attribute `shellHook`, if set. Since + `stdenv` does not normally execute this hook, it allows you to + do `nix-shell`-specific setup. + + - It preserves the user’s timezone setting. + + - In chroots, Nix now sets up a `/dev` containing only a minimal set + of devices (such as `/dev/null`). Note that it only does this if you + *don’t* have `/dev` listed in your `build-chroot-dirs` setting; + otherwise, it will bind-mount the `/dev` from outside the chroot. + + Similarly, if you don’t have `/dev/pts` listed in + `build-chroot-dirs`, Nix will mount a private `devpts` filesystem on + the chroot’s `/dev/pts`. + + - New built-in function: `builtins.toJSON`, which returns a JSON + representation of a value. + + - `nix-env -q` has a new flag `--json` to print a JSON representation + of the installed or available packages. + + - `nix-env` now supports meta attributes with more complex values, + such as attribute sets. + + - The `-A` flag now allows attribute names with dots in them, e.g. + + $ nix-instantiate --eval '' -A 'config.systemd.units."nscd.service".text' + + - The `--max-freed` option to `nix-store --gc` now accepts a unit + specifier. For example, `nix-store --gc --max-freed + 1G` will free up to 1 gigabyte of disk space. + + - `nix-collect-garbage` has a new flag `--delete-older-than` *N*`d`, + which deletes all user environment generations older than *N* days. + Likewise, `nix-env + --delete-generations` accepts a *N*`d` age limit. + + - Nix now heuristically detects whether a build failure was due to a + disk-full condition. In that case, the build is not flagged as + “permanently failed”. This is mostly useful for Hydra, which needs + to distinguish between permanent and transient build failures. + + - There is a new symbol `__curPos` that expands to an attribute set + containing its file name and line and column numbers, e.g. `{ file = + "foo.nix"; line = 10; + column = 5; }`. There also is a new builtin function, + `unsafeGetAttrPos`, that returns the position of an attribute. This + is used by Nixpkgs to provide location information in error + messages, e.g. + + $ nix-build '' -A libreoffice --argstr system x86_64-darwin + error: the package ‘libreoffice-4.0.5.2’ in ‘.../applications/office/libreoffice/default.nix:263’ + is not supported on ‘x86_64-darwin’ + + - The garbage collector is now more concurrent with other Nix + processes because it releases certain locks earlier. + + - The binary tarball installer has been improved. You can now install + Nix by running: + + $ bash <(curl -L https://nixos.org/nix/install) + + - More evaluation errors include position information. For instance, + selecting a missing attribute will print something like + + error: attribute `nixUnstabl' missing, at /etc/nixos/configurations/misc/eelco/mandark.nix:216:15 + + - The command `nix-setuid-helper` is gone. + + - Nix no longer uses Automake, but instead has a non-recursive, GNU + Make-based build system. + + - All installed libraries now have the prefix `libnix`. In particular, + this gets rid of `libutil`, which could clash with libraries with + the same name from other packages. + + - Nix now requires a compiler that supports C++11. + +This release has contributions from Danny Wilson, Domen Kožar, Eelco +Dolstra, Ian-Woo Kim, Ludovic Courtès, Maxim Ivanov, Petr Rockai, +Ricardo M. Correia and Shea Levy. diff --git a/doc/manual/src/release-notes/rl-1.8.md b/doc/manual/src/release-notes/rl-1.8.md new file mode 100644 index 000000000..59af363e8 --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.8.md @@ -0,0 +1,88 @@ +# Release 1.8 (2014-12-14) + + - Breaking change: to address a race condition, the remote build hook + mechanism now uses `nix-store + --serve` on the remote machine. This requires build slaves to be + updated to Nix 1.8. + + - Nix now uses HTTPS instead of HTTP to access the default binary + cache, `cache.nixos.org`. + + - `nix-env` selectors are now regular expressions. For instance, you + can do + + $ nix-env -qa '.*zip.*' + + to query all packages with a name containing `zip`. + + - `nix-store --read-log` can now fetch remote build logs. If a build + log is not available locally, then ‘nix-store -l’ will now try to + download it from the servers listed in the ‘log-servers’ option in + nix.conf. For instance, if you have the configuration option + + log-servers = http://hydra.nixos.org/log + + then it will try to get logs from `http://hydra.nixos.org/log/base + name of the + store path`. This allows you to do things like: + + $ nix-store -l $(which xterm) + + and get a log even if `xterm` wasn't built locally. + + - New builtin functions: `attrValues`, `deepSeq`, `fromJSON`, + `readDir`, `seq`. + + - `nix-instantiate --eval` now has a `--json` flag to print the + resulting value in JSON format. + + - `nix-copy-closure` now uses `nix-store --serve` on the remote side + to send or receive closures. This fixes a race condition between + `nix-copy-closure` and the garbage collector. + + - Derivations can specify the new special attribute + `allowedRequisites`, which has a similar meaning to + `allowedReferences`. But instead of only enforcing to explicitly + specify the immediate references, it requires the derivation to + specify all the dependencies recursively (hence the name, + requisites) that are used by the resulting output. + + - On Mac OS X, Nix now handles case collisions when importing closures + from case-sensitive file systems. This is mostly useful for running + NixOps on Mac OS X. + + - The Nix daemon has new configuration options `allowed-users` + (specifying the users and groups that are allowed to connect to the + daemon) and `trusted-users` (specifying the users and groups that + can perform privileged operations like specifying untrusted binary + caches). + + - The configuration option `build-cores` now defaults to the number of + available CPU cores. + + - Build users are now used by default when Nix is invoked as root. + This prevents builds from accidentally running as root. + + - Nix now includes systemd units and Upstart jobs. + + - Speed improvements to `nix-store + --optimise`. + + - Language change: the `==` operator now ignores string contexts (the + “dependencies” of a string). + + - Nix now filters out Nix-specific ANSI escape sequences on standard + error. They are supposed to be invisible, but some terminals show + them anyway. + + - Various commands now automatically pipe their output into the pager + as specified by the `PAGER` environment variable. + + - Several improvements to reduce memory consumption in the evaluator. + +This release has contributions from Adam Szkoda, Aristid Breitkreuz, Bob +van der Linden, Charles Strahan, darealshinji, Eelco Dolstra, Gergely +Risko, Joel Taylor, Ludovic Courtès, Marko Durkovic, Mikey Ariel, Paul +Colomiets, Ricardo M. Correia, Ricky Elrod, Robert Helgesson, Rob +Vermaas, Russell O'Connor, Shea Levy, Shell Turner, Sönke Hahn, Steve +Purcell, Vladimír Čunát and Wout Mertens. diff --git a/doc/manual/src/release-notes/rl-1.9.md b/doc/manual/src/release-notes/rl-1.9.md new file mode 100644 index 000000000..92c6af90b --- /dev/null +++ b/doc/manual/src/release-notes/rl-1.9.md @@ -0,0 +1,143 @@ +# Release 1.9 (2015-06-12) + +In addition to the usual bug fixes, this release has the following new +features: + + - Signed binary cache support. You can enable signature checking by + adding the following to `nix.conf`: + + signed-binary-caches = * + binary-cache-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= + + This will prevent Nix from downloading any binary from the cache + that is not signed by one of the keys listed in + `binary-cache-public-keys`. + + Signature checking is only supported if you built Nix with the + `libsodium` package. + + Note that while Nix has had experimental support for signed binary + caches since version 1.7, this release changes the signature format + in a backwards-incompatible way. + + - Automatic downloading of Nix expression tarballs. In various places, + you can now specify the URL of a tarball containing Nix expressions + (such as Nixpkgs), which will be downloaded and unpacked + automatically. For example: + + - In `nix-env`: + + $ nix-env -f https://github.com/NixOS/nixpkgs-channels/archive/nixos-14.12.tar.gz -iA firefox + + This installs Firefox from the latest tested and built revision + of the NixOS 14.12 channel. + + - In `nix-build` and `nix-shell`: + + $ nix-build https://github.com/NixOS/nixpkgs/archive/master.tar.gz -A hello + + This builds GNU Hello from the latest revision of the Nixpkgs + master branch. + + - In the Nix search path (as specified via `NIX_PATH` or `-I`). + For example, to start a shell containing the Pan package from a + specific version of Nixpkgs: + + $ nix-shell -p pan -I nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/8a3eea054838b55aca962c3fbde9c83c102b8bf2.tar.gz + + - In `nixos-rebuild` (on NixOS): + + $ nixos-rebuild test -I nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/nixos-unstable.tar.gz + + - In Nix expressions, via the new builtin function `fetchTarball`: + + with import (fetchTarball https://github.com/NixOS/nixpkgs-channels/archive/nixos-14.12.tar.gz) {}; … + + (This is not allowed in restricted mode.) + + - `nix-shell` improvements: + + - `nix-shell` now has a flag `--run` to execute a command in the + `nix-shell` environment, e.g. `nix-shell --run make`. This is + like the existing `--command` flag, except that it uses a + non-interactive shell (ensuring that hitting Ctrl-C won’t drop + you into the child shell). + + - `nix-shell` can now be used as a `#!`-interpreter. This allows + you to write scripts that dynamically fetch their own + dependencies. For example, here is a Haskell script that, when + invoked, first downloads GHC and the Haskell packages on which + it depends: + + #! /usr/bin/env nix-shell + #! nix-shell -i runghc -p haskellPackages.ghc haskellPackages.HTTP + + import Network.HTTP + + main = do + resp <- Network.HTTP.simpleHTTP (getRequest "http://nixos.org/") + body <- getResponseBody resp + print (take 100 body) + + Of course, the dependencies are cached in the Nix store, so the + second invocation of this script will be much faster. + + - Chroot improvements: + + - Chroot builds are now supported on Mac OS X (using its sandbox + mechanism). + + - If chroots are enabled, they are now used for all derivations, + including fixed-output derivations (such as `fetchurl`). The + latter do have network access, but can no longer access the host + filesystem. If you need the old behaviour, you can set the + option `build-use-chroot` to `relaxed`. + + - On Linux, if chroots are enabled, builds are performed in a + private PID namespace once again. (This functionality was lost + in Nix 1.8.) + + - Store paths listed in `build-chroot-dirs` are now automatically + expanded to their closure. For instance, if you want + `/nix/store/…-bash/bin/sh` mounted in your chroot as `/bin/sh`, + you only need to say `build-chroot-dirs = + /bin/sh=/nix/store/…-bash/bin/sh`; it is no longer necessary to + specify the dependencies of Bash. + + - The new derivation attribute `passAsFile` allows you to specify that + the contents of derivation attributes should be passed via files + rather than environment variables. This is useful if you need to + pass very long strings that exceed the size limit of the + environment. The Nixpkgs function `writeTextFile` uses this. + + - You can now use `~` in Nix file names to refer to your home + directory, e.g. `import + ~/.nixpkgs/config.nix`. + + - Nix has a new option `restrict-eval` that allows limiting what paths + the Nix evaluator has access to. By passing `--option restrict-eval + true` to Nix, the evaluator will throw an exception if an attempt is + made to access any file outside of the Nix search path. This is + primarily intended for Hydra to ensure that a Hydra jobset only + refers to its declared inputs (and is therefore reproducible). + + - `nix-env` now only creates a new “generation” symlink in + `/nix/var/nix/profiles` if something actually changed. + + - The environment variable `NIX_PAGER` can now be set to override + `PAGER`. You can set it to `cat` to disable paging for Nix commands + only. + + - Failing `<...>` lookups now show position information. + + - Improved Boehm GC use: we disabled scanning for interior pointers, + which should reduce the “`Repeated + allocation of very large block`” warnings and associated retention + of memory. + +This release has contributions from aszlig, Benjamin Staffin, Charles +Strahan, Christian Theune, Daniel Hahler, Danylo Hlynskyi Daniel +Peebles, Dan Peebles, Domen Kožar, Eelco Dolstra, Harald van Dijk, Hoang +Xuan Phu, Jaka Hudoklin, Jeff Ramnani, j-keck, Linquize, Luca Bruno, +Michael Merickel, Oliver Dunkl, Rob Vermaas, Rok Garbas, Shea Levy, +Tobias Geerinckx-Rice and William A. Kennington III. diff --git a/doc/manual/src/release-notes/rl-2.0.md b/doc/manual/src/release-notes/rl-2.0.md new file mode 100644 index 000000000..9f6d4aa83 --- /dev/null +++ b/doc/manual/src/release-notes/rl-2.0.md @@ -0,0 +1,558 @@ +# Release 2.0 (2018-02-22) + +The following incompatible changes have been made: + + - The manifest-based substituter mechanism + (`download-using-manifests`) has been + [removed](https://github.com/NixOS/nix/commit/867967265b80946dfe1db72d40324b4f9af988ed). + It has been superseded by the binary cache substituter mechanism + since several years. As a result, the following programs have been + removed: + + - `nix-pull` + + - `nix-generate-patches` + + - `bsdiff` + + - `bspatch` + + - The “copy from other stores” substituter mechanism + (`copy-from-other-stores` and the `NIX_OTHER_STORES` environment + variable) has been removed. It was primarily used by the NixOS + installer to copy available paths from the installation medium. The + replacement is to use a chroot store as a substituter (e.g. + `--substituters /mnt`), or to build into a chroot store (e.g. + `--store /mnt --substituters /`). + + - The command `nix-push` has been removed as part of the effort to + eliminate Nix's dependency on Perl. You can use `nix copy` instead, + e.g. `nix copy + --to file:///tmp/my-binary-cache paths…` + + - The “nested” log output feature (`--log-type + pretty`) has been removed. As a result, `nix-log2xml` was also + removed. + + - OpenSSL-based signing has been + [removed](https://github.com/NixOS/nix/commit/f435f8247553656774dd1b2c88e9de5d59cab203). + This feature was never well-supported. A better alternative is + provided by the `secret-key-files` and `trusted-public-keys` + options. + + - Failed build caching has been + [removed](https://github.com/NixOS/nix/commit/8cffec84859cec8b610a2a22ab0c4d462a9351ff). + This feature was introduced to support the Hydra continuous build + system, but Hydra no longer uses it. + + - `nix-mode.el` has been removed from Nix. It is now [a separate + repository](https://github.com/NixOS/nix-mode) and can be installed + through the MELPA package repository. + +This release has the following new features: + + - It introduces a new command named `nix`, which is intended to + eventually replace all `nix-*` commands with a more consistent and + better designed user interface. It currently provides replacements + for some (but not all) of the functionality provided by `nix-store`, + `nix-build`, `nix-shell -p`, `nix-env -qa`, `nix-instantiate + --eval`, `nix-push` and `nix-copy-closure`. It has the following + major features: + + - Unlike the legacy commands, it has a consistent way to refer to + packages and package-like arguments (like store paths). For + example, the following commands all copy the GNU Hello package + to a remote machine: + + nix copy --to ssh://machine nixpkgs.hello + + nix copy --to ssh://machine /nix/store/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9-hello-2.10 + + nix copy --to ssh://machine '(with import {}; hello)' + + By contrast, `nix-copy-closure` only accepted store paths as + arguments. + + - It is self-documenting: `--help` shows all available + command-line arguments. If `--help` is given after a subcommand, + it shows examples for that subcommand. `nix + --help-config` shows all configuration options. + + - It is much less verbose. By default, it displays a single-line + progress indicator that shows how many packages are left to be + built or downloaded, and (if there are running builds) the most + recent line of builder output. If a build fails, it shows the + last few lines of builder output. The full build log can be + retrieved using `nix + log`. + + - It + [provides](https://github.com/NixOS/nix/commit/b8283773bd64d7da6859ed520ee19867742a03ba) + all `nix.conf` configuration options as command line flags. For + example, instead of `--option + http-connections 100` you can write `--http-connections 100`. + Boolean options can be written as `--foo` or `--no-foo` (e.g. + `--no-auto-optimise-store`). + + - Many subcommands have a `--json` flag to write results to stdout + in JSON format. + + > **Warning** + > + > Please note that the `nix` command is a work in progress and the + > interface is subject to change. + + It provides the following high-level (“porcelain”) subcommands: + + - `nix build` is a replacement for `nix-build`. + + - `nix run` executes a command in an environment in which the + specified packages are available. It is (roughly) a replacement + for `nix-shell + -p`. Unlike that command, it does not execute the command in a + shell, and has a flag (`-c`) that specifies the unquoted command + line to be executed. + + It is particularly useful in conjunction with chroot stores, + allowing Linux users who do not have permission to install Nix + in `/nix/store` to still use binary substitutes that assume + `/nix/store`. For example, + + nix run --store ~/my-nix nixpkgs.hello -c hello --greeting 'Hi everybody!' + + downloads (or if not substitutes are available, builds) the GNU + Hello package into `~/my-nix/nix/store`, then runs `hello` in a + mount namespace where `~/my-nix/nix/store` is mounted onto + `/nix/store`. + + - `nix search` replaces `nix-env + -qa`. It searches the available packages for occurrences of a + search string in the attribute name, package name or + description. Unlike `nix-env -qa`, it has a cache to speed up + subsequent searches. + + - `nix copy` copies paths between arbitrary Nix stores, + generalising `nix-copy-closure` and `nix-push`. + + - `nix repl` replaces the external program `nix-repl`. It provides + an interactive environment for evaluating and building Nix + expressions. Note that it uses `linenoise-ng` instead of GNU + Readline. + + - `nix upgrade-nix` upgrades Nix to the latest stable version. + This requires that Nix is installed in a profile. (Thus it won’t + work on NixOS, or if it’s installed outside of the Nix store.) + + - `nix verify` checks whether store paths are unmodified and/or + “trusted” (see below). It replaces `nix-store --verify` and + `nix-store + --verify-path`. + + - `nix log` shows the build log of a package or path. If the + build log is not available locally, it will try to obtain it + from the configured substituters (such as + [cache.nixos.org](https://cache.nixos.org/), which now + provides build logs). + + - `nix edit` opens the source code of a package in your editor. + + - `nix eval` replaces `nix-instantiate --eval`. + + - `nix + why-depends` shows why one store path has another in its + closure. This is primarily useful to finding the causes of + closure bloat. For example, + + nix why-depends nixpkgs.vlc nixpkgs.libdrm.dev + + shows a chain of files and fragments of file contents that cause + the VLC package to have the “dev” output of `libdrm` in its + closure — an undesirable situation. + + - `nix path-info` shows information about store paths, replacing + `nix-store -q`. A useful feature is the option `--closure-size` + (`-S`). For example, the following command show the closure + sizes of every path in the current NixOS system closure, sorted + by size: + + nix path-info -rS /run/current-system | sort -nk2 + + - `nix optimise-store` replaces `nix-store --optimise`. The main + difference is that it has a progress indicator. + + A number of low-level (“plumbing”) commands are also available: + + - `nix ls-store` and `nix + ls-nar` list the contents of a store path or NAR file. The + former is primarily useful in conjunction with remote stores, + e.g. + + nix ls-store --store https://cache.nixos.org/ -lR /nix/store/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9-hello-2.10 + + lists the contents of path in a binary cache. + + - `nix cat-store` and `nix + cat-nar` allow extracting a file from a store path or NAR file. + + - `nix dump-path` writes the contents of a store path to stdout in + NAR format. This replaces `nix-store --dump`. + + - `nix + show-derivation` displays a store derivation in JSON format. + This is an alternative to `pp-aterm`. + + - `nix + add-to-store` replaces `nix-store + --add`. + + - `nix sign-paths` signs store paths. + + - `nix copy-sigs` copies signatures from one store to another. + + - `nix show-config` shows all configuration options and their + current values. + + - The store abstraction that Nix has had for a long time to support + store access via the Nix daemon has been extended + significantly. In particular, substituters (which used to be + external programs such as `download-from-binary-cache`) are now + subclasses of the abstract `Store` class. This allows many Nix + commands to operate on such store types. For example, `nix + path-info` shows information about paths in your local Nix store, + while `nix path-info --store https://cache.nixos.org/` shows + information about paths in the specified binary cache. Similarly, + `nix-copy-closure`, `nix-push` and substitution are all instances + of the general notion of copying paths between different kinds of + Nix stores. + + Stores are specified using an URI-like syntax, e.g. + or . The following store + types are supported: + + - `LocalStore` (stori URI `local` or an absolute path) and the + misnamed `RemoteStore` (`daemon`) provide access to a local Nix + store, the latter via the Nix daemon. You can use `auto` or the + empty string to auto-select a local or daemon store depending on + whether you have write permission to the Nix store. It is no + longer necessary to set the `NIX_REMOTE` environment variable to + use the Nix daemon. + + As noted above, `LocalStore` now supports chroot builds, + allowing the “physical” location of the Nix store (e.g. + `/home/alice/nix/store`) to differ from its “logical” location + (typically `/nix/store`). This allows non-root users to use Nix + while still getting the benefits from prebuilt binaries from + [cache.nixos.org](https://cache.nixos.org/). + + - `BinaryCacheStore` is the abstract superclass of all binary + cache stores. It supports writing build logs and NAR content + listings in JSON format. + + - `HttpBinaryCacheStore` (`http://`, `https://`) supports binary + caches via HTTP or HTTPS. If the server supports `PUT` requests, + it supports uploading store paths via commands such as `nix + copy`. + + - `LocalBinaryCacheStore` (`file://`) supports binary caches in + the local filesystem. + + - `S3BinaryCacheStore` (`s3://`) supports binary caches stored in + Amazon S3, if enabled at compile time. + + - `LegacySSHStore` (`ssh://`) is used to implement remote builds + and `nix-copy-closure`. + + - `SSHStore` (`ssh-ng://`) supports arbitrary Nix operations on a + remote machine via the same protocol used by `nix-daemon`. + + - Security has been improved in various ways: + + - Nix now stores signatures for local store paths. When paths are + copied between stores (e.g., copied from a binary cache to a + local store), signatures are propagated. + + Locally-built paths are signed automatically using the secret + keys specified by the `secret-key-files` store option. + Secret/public key pairs can be generated using `nix-store + --generate-binary-cache-key`. + + In addition, locally-built store paths are marked as “ultimately + trusted”, but this bit is not propagated when paths are copied + between stores. + + - Content-addressable store paths no longer require signatures — + they can be imported into a store by unprivileged users even if + they lack signatures. + + - The command `nix verify` checks whether the specified paths are + trusted, i.e., have a certain number of trusted signatures, are + ultimately trusted, or are content-addressed. + + - Substitutions from binary caches + [now](https://github.com/NixOS/nix/commit/ecbc3fedd3d5bdc5a0e1a0a51b29062f2874ac8b) + require signatures by default. This was already the case on + NixOS. + + - In Linux sandbox builds, we + [now](https://github.com/NixOS/nix/commit/eba840c8a13b465ace90172ff76a0db2899ab11b) + use `/build` instead of `/tmp` as the temporary build directory. + This fixes potential security problems when a build accidentally + stores its `TMPDIR` in some security-sensitive place, such as an + RPATH. + + - *Pure evaluation mode*. With the `--pure-eval` flag, Nix enables a + variant of the existing restricted evaluation mode that forbids + access to anything that could cause different evaluations of the + same command line arguments to produce a different result. This + includes builtin functions such as `builtins.getEnv`, but more + importantly, *all* filesystem or network access unless a content + hash or commit hash is specified. For example, calls to + `builtins.fetchGit` are only allowed if a `rev` attribute is + specified. + + The goal of this feature is to enable true reproducibility and + traceability of builds (including NixOS system configurations) at + the evaluation level. For example, in the future, `nixos-rebuild` + might build configurations from a Nix expression in a Git repository + in pure mode. That expression might fetch other repositories such as + Nixpkgs via `builtins.fetchGit`. The commit hash of the top-level + repository then uniquely identifies a running system, and, in + conjunction with that repository, allows it to be reproduced or + modified. + + - There are several new features to support binary reproducibility + (i.e. to help ensure that multiple builds of the same derivation + produce exactly the same output). When `enforce-determinism` is set + to `false`, it’s [no + longer](https://github.com/NixOS/nix/commit/8bdf83f936adae6f2c907a6d2541e80d4120f051) + a fatal error if build rounds produce different output. Also, a hook + named `diff-hook` is + [provided](https://github.com/NixOS/nix/commit/9a313469a4bdea2d1e8df24d16289dc2a172a169) + to allow you to run tools such as `diffoscope` when build rounds + produce different output. + + - Configuring remote builds is a lot easier now. Provided you are not + using the Nix daemon, you can now just specify a remote build + machine on the command line, e.g. `--option builders + 'ssh://my-mac x86_64-darwin'`. The environment variable + `NIX_BUILD_HOOK` has been removed and is no longer needed. The + environment variable `NIX_REMOTE_SYSTEMS` is still supported for + compatibility, but it is also possible to specify builders in + `nix.conf` by setting the option `builders = + @path`. + + - If a fixed-output derivation produces a result with an incorrect + hash, the output path is moved to the location corresponding to the + actual hash and registered as valid. Thus, a subsequent build of the + fixed-output derivation with the correct hash is unnecessary. + + - `nix-shell` + [now](https://github.com/NixOS/nix/commit/ea59f39326c8e9dc42dfed4bcbf597fbce58797c) + sets the `IN_NIX_SHELL` environment variable during evaluation and + in the shell itself. This can be used to perform different actions + depending on whether you’re in a Nix shell or in a regular build. + Nixpkgs provides `lib.inNixShell` to check this variable during + evaluation. + + - `NIX_PATH` is now lazy, so URIs in the path are only downloaded if + they are needed for evaluation. + + - You can now use `channel:` as a short-hand for + . For example, + `nix-build channel:nixos-15.09 -A hello` will build the GNU Hello + package from the `nixos-15.09` channel. In the future, this may + use Git to fetch updates more efficiently. + + - When `--no-build-output` is given, the last 10 lines of the build + log will be shown if a build fails. + + - Networking has been improved: + + - HTTP/2 is now supported. This makes binary cache lookups [much + more + efficient](https://github.com/NixOS/nix/commit/90ad02bf626b885a5dd8967894e2eafc953bdf92). + + - We now retry downloads on many HTTP errors, making binary caches + substituters more resilient to temporary failures. + + - HTTP credentials can now be configured via the standard `netrc` + mechanism. + + - If S3 support is enabled at compile time, URIs are + [supported](https://github.com/NixOS/nix/commit/9ff9c3f2f80ba4108e9c945bbfda2c64735f987b) + in all places where Nix allows URIs. + + - Brotli compression is now supported. In particular, + [cache.nixos.org](https://cache.nixos.org/) build logs are now compressed + using Brotli. + + - `nix-env` + [now](https://github.com/NixOS/nix/commit/b0cb11722626e906a73f10dd9a0c9eea29faf43a) + ignores packages with bad derivation names (in particular those + starting with a digit or containing a dot). + + - Many configuration options have been renamed, either because they + were unnecessarily verbose (e.g. `build-use-sandbox` is now just + `sandbox`) or to reflect generalised behaviour (e.g. `binary-caches` + is now `substituters` because it allows arbitrary store URIs). The + old names are still supported for compatibility. + + - The `max-jobs` option can + [now](https://github.com/NixOS/nix/commit/7251d048fa812d2551b7003bc9f13a8f5d4c95a5) + be set to `auto` to use the number of CPUs in the system. + + - Hashes can + [now](https://github.com/NixOS/nix/commit/c0015e87af70f539f24d2aa2bc224a9d8b84276b) + be specified in base-64 format, in addition to base-16 and the + non-standard base-32. + + - `nix-shell` now uses `bashInteractive` from Nixpkgs, rather than the + `bash` command that happens to be in the caller’s `PATH`. This is + especially important on macOS where the `bash` provided by the + system is seriously outdated and cannot execute `stdenv`’s setup + script. + + - Nix can now automatically trigger a garbage collection if free disk + space drops below a certain level during a build. This is configured + using the `min-free` and `max-free` options. + + - `nix-store -q --roots` and `nix-store --gc --print-roots` now show + temporary and in-memory roots. + + - Nix can now be extended with plugins. See the documentation of the + `plugin-files` option for more details. + +The Nix language has the following new features: + + - It supports floating point numbers. They are based on the C++ + `float` type and are supported by the existing numerical operators. + Export and import to and from JSON and XML works, too. + + - Derivation attributes can now reference the outputs of the + derivation using the `placeholder` builtin function. For example, + the attribute + + configureFlags = "--prefix=${placeholder "out"} --includedir=${placeholder "dev"}"; + + will cause the `configureFlags` environment variable to contain the + actual store paths corresponding to the `out` and `dev` outputs. + +The following builtin functions are new or extended: + + - `builtins.fetchGit` allows Git repositories to be fetched at + evaluation time. Thus it differs from the `fetchgit` function in + Nixpkgs, which fetches at build time and cannot be used to fetch Nix + expressions during evaluation. A typical use case is to import + external NixOS modules from your configuration, e.g. + + imports = [ (builtins.fetchGit https://github.com/edolstra/dwarffs + "/module.nix") ]; + + - Similarly, `builtins.fetchMercurial` allows you to fetch Mercurial + repositories. + + - `builtins.path` generalises `builtins.filterSource` and path + literals (e.g. `./foo`). It allows specifying a store path name that + differs from the source path name (e.g. `builtins.path { path = + ./foo; name = "bar"; + }`) and also supports filtering out unwanted files. + + - `builtins.fetchurl` and `builtins.fetchTarball` now support `sha256` + and `name` attributes. + + - `builtins.split` splits a string using a POSIX extended regular + expression as the separator. + + - `builtins.partition` partitions the elements of a list into two + lists, depending on a Boolean predicate. + + - `` now uses the content-addressable tarball cache + at , just like `fetchurl` in Nixpkgs. + (f2682e6e18a76ecbfb8a12c17e3a0ca15c084197) + + - In restricted and pure evaluation mode, builtin functions that + download from the network (such as `fetchGit`) are permitted to + fetch underneath a list of URI prefixes specified in the option + `allowed-uris`. + +The Nix build environment has the following changes: + + - Values such as Booleans, integers, (nested) lists and attribute sets + can + [now](https://github.com/NixOS/nix/commit/6de33a9c675b187437a2e1abbcb290981a89ecb1) + be passed to builders in a non-lossy way. If the special attribute + `__structuredAttrs` is set to `true`, the other derivation + attributes are serialised in JSON format and made available to the + builder via the file `.attrs.json` in the builder’s temporary + directory. This obviates the need for `passAsFile` since JSON files + have no size restrictions, unlike process environments. + + [As a convenience to Bash + builders](https://github.com/NixOS/nix/commit/2d5b1b24bf70a498e4c0b378704cfdb6471cc699), + Nix writes a script named `.attrs.sh` to the builder’s directory + that initialises shell variables corresponding to all attributes + that are representable in Bash. This includes non-nested + (associative) arrays. For example, the attribute `hardening.format = + true` ends up as the Bash associative array element + `${hardening[format]}`. + + - Builders can + [now](https://github.com/NixOS/nix/commit/88e6bb76de5564b3217be9688677d1c89101b2a3) + communicate what build phase they are in by writing messages to the + file descriptor specified in `NIX_LOG_FD`. The current phase is + shown by the `nix` progress indicator. + + - In Linux sandbox builds, we + [now](https://github.com/NixOS/nix/commit/a2d92bb20e82a0957067ede60e91fab256948b41) + provide a default `/bin/sh` (namely `ash` from BusyBox). + + - In structured attribute mode, `exportReferencesGraph` + [exports](https://github.com/NixOS/nix/commit/c2b0d8749f7e77afc1c4b3e8dd36b7ee9720af4a) + extended information about closures in JSON format. In particular, + it includes the sizes and hashes of paths. This is primarily useful + for NixOS image builders. + + - Builds are + [now](https://github.com/NixOS/nix/commit/21948deed99a3295e4d5666e027a6ca42dc00b40) + killed as soon as Nix receives EOF on the builder’s stdout or + stderr. This fixes a bug that allowed builds to hang Nix + indefinitely, regardless of timeouts. + + - The `sandbox-paths` configuration option can now specify optional + paths by appending a `?`, e.g. `/dev/nvidiactl?` will bind-mount + `/dev/nvidiactl` only if it exists. + + - On Linux, builds are now executed in a user namespace with UID 1000 + and GID 100. + +A number of significant internal changes were made: + + - Nix no longer depends on Perl and all Perl components have been + rewritten in C++ or removed. The Perl bindings that used to be part + of Nix have been moved to a separate package, `nix-perl`. + + - All `Store` classes are now thread-safe. `RemoteStore` supports + multiple concurrent connections to the daemon. This is primarily + useful in multi-threaded programs such as `hydra-queue-runner`. + +This release has contributions from Adrien Devresse, Alexander Ried, +Alex Cruice, Alexey Shmalko, AmineChikhaoui, Andy Wingo, Aneesh Agrawal, +Anthony Cowley, Armijn Hemel, aszlig, Ben Gamari, Benjamin Hipple, +Benjamin Staffin, Benno Fünfstück, Bjørn Forsman, Brian McKenna, Charles +Strahan, Chase Adams, Chris Martin, Christian Theune, Chris Warburton, +Daiderd Jordan, Dan Connolly, Daniel Peebles, Dan Peebles, davidak, +David McFarland, Dmitry Kalinkin, Domen Kožar, Eelco Dolstra, Emery +Hemingway, Eric Litak, Eric Wolf, Fabian Schmitthenner, Frederik +Rietdijk, Gabriel Gonzalez, Giorgio Gallo, Graham Christensen, Guillaume +Maudoux, Harmen, Iavael, James Broadhead, James Earl Douglas, Janus +Troelsen, Jeremy Shaw, Joachim Schiele, Joe Hermaszewski, Joel Moberg, +Johannes 'fish' Ziemke, Jörg Thalheim, Jude Taylor, kballou, Keshav +Kini, Kjetil Orbekk, Langston Barrett, Linus Heckemann, Ludovic Courtès, +Manav Rathi, Marc Scholten, Markus Hauck, Matt Audesse, Matthew Bauer, +Matthias Beyer, Matthieu Coudron, N1X, Nathan Zadoks, Neil Mayhew, +Nicolas B. Pierron, Niklas Hambüchen, Nikolay Amiantov, Ole Jørgen +Brønner, Orivej Desh, Peter Simons, Peter Stuart, Pyry Jahkola, regnat, +Renzo Carbonara, Rhys, Robert Vollmert, Scott Olson, Scott R. Parish, +Sergei Trofimovich, Shea Levy, Sheena Artrip, Spencer Baugh, Stefan +Junker, Susan Potter, Thomas Tuegel, Timothy Allen, Tristan Hume, Tuomas +Tynkkynen, tv, Tyson Whitehead, Vladimír Čunát, Will Dietz, wmertens, +Wout Mertens, zimbatm and Zoran Plesivčak. diff --git a/doc/manual/src/release-notes/rl-2.1.md b/doc/manual/src/release-notes/rl-2.1.md new file mode 100644 index 000000000..a9592657b --- /dev/null +++ b/doc/manual/src/release-notes/rl-2.1.md @@ -0,0 +1,49 @@ +# Release 2.1 (2018-09-02) + +This is primarily a bug fix release. It also reduces memory consumption +in certain situations. In addition, it has the following new features: + + - The Nix installer will no longer default to the Multi-User + installation for macOS. You can still instruct the installer to + run in multi-user mode. + + - The Nix installer now supports performing a Multi-User + installation for Linux computers which are running systemd. You + can select a Multi-User installation by passing the `--daemon` + flag to the installer: `sh <(curl -L https://nixos.org/nix/install) + --daemon`. + + The multi-user installer cannot handle systems with SELinux. If + your system has SELinux enabled, you can force the installer to + run in single-user mode. + + - New builtin functions: `builtins.bitAnd`, `builtins.bitOr`, + `builtins.bitXor`, `builtins.fromTOML`, `builtins.concatMap`, + `builtins.mapAttrs`. + + - The S3 binary cache store now supports uploading NARs larger than 5 + GiB. + + - The S3 binary cache store now supports uploading to S3-compatible + services with the `endpoint` option. + + - The flag `--fallback` is no longer required to recover from + disappeared NARs in binary caches. + + - `nix-daemon` now respects `--store`. + + - `nix run` now respects `nix-support/propagated-user-env-packages`. + +This release has contributions from Adrien Devresse, Aleksandr Pashkov, +Alexandre Esteves, Amine Chikhaoui, Andrew Dunham, Asad Saeeduddin, +aszlig, Ben Challenor, Ben Gamari, Benjamin Hipple, Bogdan Seniuc, Corey +O'Connor, Daiderd Jordan, Daniel Peebles, Daniel Poelzleithner, Danylo +Hlynskyi, Dmitry Kalinkin, Domen Kožar, Doug Beardsley, Eelco Dolstra, +Erik Arvstedt, Félix Baylac-Jacqué, Gleb Peregud, Graham Christensen, +Guillaume Maudoux, Ivan Kozik, John Arnold, Justin Humm, Linus +Heckemann, Lorenzo Manacorda, Matthew Justin Bauer, Matthew O'Gorman, +Maximilian Bosch, Michael Bishop, Michael Fiano, Michael Mercier, +Michael Raskin, Michael Weiss, Nicolas Dudebout, Peter Simons, Ryan +Trinkle, Samuel Dionne-Riel, Sean Seefried, Shea Levy, Symphorien Gibol, +Tim Engler, Tim Sears, Tuomas Tynkkynen, volth, Will Dietz, Yorick van +Pelt and zimbatm. diff --git a/doc/manual/src/release-notes/rl-2.2.md b/doc/manual/src/release-notes/rl-2.2.md new file mode 100644 index 000000000..b67d65db7 --- /dev/null +++ b/doc/manual/src/release-notes/rl-2.2.md @@ -0,0 +1,82 @@ +# Release 2.2 (2019-01-11) + +This is primarily a bug fix release. It also has the following changes: + + - In derivations that use structured attributes (i.e. that specify set + the `__structuredAttrs` attribute to `true` to cause all attributes + to be passed to the builder in JSON format), you can now specify + closure checks per output, e.g.: + + outputChecks."out" = { + # The closure of 'out' must not be larger than 256 MiB. + maxClosureSize = 256 * 1024 * 1024; + + # It must not refer to C compiler or to the 'dev' output. + disallowedRequisites = [ stdenv.cc "dev" ]; + }; + + outputChecks."dev" = { + # The 'dev' output must not be larger than 128 KiB. + maxSize = 128 * 1024; + }; + + - The derivation attribute `requiredSystemFeatures` is now enforced + for local builds, and not just to route builds to remote builders. + The supported features of a machine can be specified through the + configuration setting `system-features`. + + By default, `system-features` includes `kvm` if `/dev/kvm` exists. + For compatibility, it also includes the pseudo-features + `nixos-test`, `benchmark` and `big-parallel` which are used by + Nixpkgs to route builds to particular Hydra build machines. + + - Sandbox builds are now enabled by default on Linux. + + - The new command `nix doctor` shows potential issues with your Nix + installation. + + - The `fetchGit` builtin function now uses a caching scheme that puts + different remote repositories in distinct local repositories, rather + than a single shared repository. This may require more disk space + but is faster. + + - The `dirOf` builtin function now works on relative paths. + + - Nix now supports [SRI hashes](https://www.w3.org/TR/SRI/), allowing + the hash algorithm and hash to be specified in a single string. For + example, you can write: + + import { + url = https://nixos.org/releases/nix/nix-2.1.3/nix-2.1.3.tar.xz; + hash = "sha256-XSLa0FjVyADWWhFfkZ2iKTjFDda6mMXjoYMXLRSYQKQ="; + }; + + instead of + + import { + url = https://nixos.org/releases/nix/nix-2.1.3/nix-2.1.3.tar.xz; + sha256 = "5d22dad058d5c800d65a115f919da22938c50dd6ba98c5e3a183172d149840a4"; + }; + + In fixed-output derivations, the `outputHashAlgo` attribute is no + longer mandatory if `outputHash` specifies the hash. + + `nix hash-file` and `nix + hash-path` now print hashes in SRI format by default. They also use + SHA-256 by default instead of SHA-512 because that's what we use + most of the time in Nixpkgs. + + - Integers are now 64 bits on all platforms. + + - The evaluator now prints profiling statistics (enabled via the + `NIX_SHOW_STATS` and `NIX_COUNT_CALLS` environment variables) in + JSON format. + + - The option `--xml` in `nix-store + --query` has been removed. Instead, there now is an option + `--graphml` to output the dependency graph in GraphML format. + + - All `nix-*` commands are now symlinks to `nix`. This saves a bit of + disk space. + + - `nix repl` now uses `libeditline` or `libreadline`. diff --git a/doc/manual/src/release-notes/rl-2.3.md b/doc/manual/src/release-notes/rl-2.3.md new file mode 100644 index 000000000..d1f4e3734 --- /dev/null +++ b/doc/manual/src/release-notes/rl-2.3.md @@ -0,0 +1,44 @@ +# Release 2.3 (2019-09-04) + +This is primarily a bug fix release. However, it makes some incompatible +changes: + + - Nix now uses BSD file locks instead of POSIX file locks. Because of + this, you should not use Nix 2.3 and previous releases at the same + time on a Nix store. + +It also has the following changes: + + - `builtins.fetchGit`'s `ref` argument now allows specifying an + absolute remote ref. Nix will automatically prefix `ref` with + `refs/heads` only if `ref` doesn't already begin with `refs/`. + + - The installer now enables sandboxing by default on Linux when the + system has the necessary kernel support. + + - The `max-jobs` setting now defaults to 1. + + - New builtin functions: `builtins.isPath`, `builtins.hashFile`. + + - The `nix` command has a new `--print-build-logs` (`-L`) flag to + print build log output to stderr, rather than showing the last log + line in the progress bar. To distinguish between concurrent builds, + log lines are prefixed by the name of the package. + + - Builds are now executed in a pseudo-terminal, and the `TERM` + environment variable is set to `xterm-256color`. This allows many + programs (e.g. `gcc`, `clang`, `cmake`) to print colorized log + output. + + - Add `--no-net` convenience flag. This flag disables substituters; + sets the `tarball-ttl` setting to infinity (ensuring that any + previously downloaded files are considered current); and disables + retrying downloads and sets the connection timeout to the minimum. + This flag is enabled automatically if there are no configured + non-loopback network interfaces. + + - Add a `post-build-hook` setting to run a program after a build has + succeeded. + + - Add a `trace-function-calls` setting to log the duration of Nix + function calls to stderr. diff --git a/doc/manual/utils.nix b/doc/manual/utils.nix new file mode 100644 index 000000000..50150bf3e --- /dev/null +++ b/doc/manual/utils.nix @@ -0,0 +1,7 @@ +with builtins; + +{ + splitLines = s: filter (x: !isList x) (split "\n" s); + + concatStrings = concatStringsSep ""; +} diff --git a/flake.lock b/flake.lock new file mode 100644 index 000000000..822a73332 --- /dev/null +++ b/flake.lock @@ -0,0 +1,43 @@ +{ + "nodes": { + "lowdown-src": { + "flake": false, + "locked": { + "lastModified": 1598695561, + "narHash": "sha256-gyH/5j+h/nWw0W8AcR2WKvNBUsiQ7QuxqSJNXAwV+8E=", + "owner": "kristapsdz", + "repo": "lowdown", + "rev": "1705b4a26fbf065d9574dce47a94e8c7c79e052f", + "type": "github" + }, + "original": { + "owner": "kristapsdz", + "repo": "lowdown", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1591633336, + "narHash": "sha256-oVXv4xAnDJB03LvZGbC72vSVlIbbJr8tpjEW5o/Fdek=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "70717a337f7ae4e486ba71a500367cad697e5f09", + "type": "github" + }, + "original": { + "id": "nixpkgs", + "ref": "nixos-20.03-small", + "type": "indirect" + } + }, + "root": { + "inputs": { + "lowdown-src": "lowdown-src", + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 000000000..200417c3e --- /dev/null +++ b/flake.nix @@ -0,0 +1,462 @@ +{ + description = "The purely functional package manager"; + + inputs.nixpkgs.url = "nixpkgs/nixos-20.03-small"; + inputs.lowdown-src = { url = "github:kristapsdz/lowdown"; flake = false; }; + + outputs = { self, nixpkgs, lowdown-src }: + + let + + version = builtins.readFile ./.version + versionSuffix; + versionSuffix = + if officialRelease + then "" + else "pre${builtins.substring 0 8 (self.lastModifiedDate or self.lastModified)}_${self.shortRev or "dirty"}"; + + officialRelease = false; + + systems = [ "x86_64-linux" "i686-linux" "x86_64-darwin" "aarch64-linux" ]; + + forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f system); + + # Memoize nixpkgs for different platforms for efficiency. + nixpkgsFor = forAllSystems (system: + import nixpkgs { + inherit system; + overlays = [ self.overlay ]; + } + ); + + commonDeps = pkgs: with pkgs; rec { + # Use "busybox-sandbox-shell" if present, + # if not (legacy) fallback and hope it's sufficient. + sh = pkgs.busybox-sandbox-shell or (busybox.override { + useMusl = true; + enableStatic = true; + enableMinimal = true; + extraConfig = '' + CONFIG_FEATURE_FANCY_ECHO y + CONFIG_FEATURE_SH_MATH y + CONFIG_FEATURE_SH_MATH_64 y + + CONFIG_ASH y + CONFIG_ASH_OPTIMIZE_FOR_SIZE y + + CONFIG_ASH_ALIAS y + CONFIG_ASH_BASH_COMPAT y + CONFIG_ASH_CMDCMD y + CONFIG_ASH_ECHO y + CONFIG_ASH_GETOPTS y + CONFIG_ASH_INTERNAL_GLOB y + CONFIG_ASH_JOB_CONTROL y + CONFIG_ASH_PRINTF y + CONFIG_ASH_TEST y + ''; + }); + + configureFlags = + lib.optionals stdenv.isLinux [ + "--with-sandbox-shell=${sh}/bin/busybox" + "LDFLAGS=-fuse-ld=gold" + ]; + + buildDeps = + [ bison + flex + mdbook + lowdown + autoconf-archive + autoreconfHook + + curl + bzip2 xz brotli zlib editline + openssl pkgconfig sqlite + libarchive + boost + nlohmann_json + + # Tests + git + mercurial + jq + gmock + ] + ++ lib.optionals stdenv.isLinux [libseccomp utillinuxMinimal] + ++ lib.optional (stdenv.isLinux || stdenv.isDarwin) libsodium + ++ lib.optional (stdenv.isLinux || stdenv.isDarwin) + (aws-sdk-cpp.override { + apis = ["s3" "transfer"]; + customMemoryManagement = false; + }); + + propagatedDeps = + [ (boehmgc.override { enableLargeConfig = true; }) + ]; + + perlDeps = + [ perl + perlPackages.DBDSQLite + ]; + }; + + in { + + # A Nixpkgs overlay that overrides the 'nix' and + # 'nix.perl-bindings' packages. + overlay = final: prev: { + + nix = with final; with commonDeps pkgs; (stdenv.mkDerivation { + name = "nix-${version}"; + + src = self; + + VERSION_SUFFIX = versionSuffix; + + outputs = [ "out" "dev" "doc" ]; + + buildInputs = buildDeps; + + propagatedBuildInputs = propagatedDeps; + + preConfigure = + '' + # Copy libboost_context so we don't get all of Boost in our closure. + # https://github.com/NixOS/nixpkgs/issues/45462 + mkdir -p $out/lib + cp -pd ${boost}/lib/{libboost_context*,libboost_thread*,libboost_system*} $out/lib + rm -f $out/lib/*.a + ${lib.optionalString stdenv.isLinux '' + chmod u+w $out/lib/*.so.* + patchelf --set-rpath $out/lib:${stdenv.cc.cc.lib}/lib $out/lib/libboost_thread.so.* + ''} + ''; + + configureFlags = configureFlags ++ + [ "--sysconfdir=/etc" ]; + + enableParallelBuilding = true; + + makeFlags = "profiledir=$(out)/etc/profile.d PRECOMPILE_HEADERS=1"; + + doCheck = true; + + installFlags = "sysconfdir=$(out)/etc"; + + postInstall = '' + mkdir -p $doc/nix-support + echo "doc manual $doc/share/doc/nix/manual" >> $doc/nix-support/hydra-build-products + ''; + + doInstallCheck = true; + installCheckFlags = "sysconfdir=$(out)/etc"; + + separateDebugInfo = true; + }) // { + + perl-bindings = with final; stdenv.mkDerivation { + name = "nix-perl-${version}"; + + src = self; + + buildInputs = + [ autoconf-archive + autoreconfHook + nix + curl + bzip2 + xz + pkgconfig + pkgs.perl + boost + nlohmann_json + ] + ++ lib.optional (stdenv.isLinux || stdenv.isDarwin) libsodium; + + configureFlags = '' + --with-dbi=${perlPackages.DBI}/${pkgs.perl.libPrefix} + --with-dbd-sqlite=${perlPackages.DBDSQLite}/${pkgs.perl.libPrefix} + ''; + + enableParallelBuilding = true; + + postUnpack = "sourceRoot=$sourceRoot/perl"; + }; + + }; + + lowdown = with final; stdenv.mkDerivation { + name = "lowdown-0.7.1"; + + /* + src = fetchurl { + url = https://kristaps.bsd.lv/lowdown/snapshots/lowdown-0.7.1.tar.gz; + hash = "sha512-1daoAQfYD0LdhK6aFhrSQvadjc5GsSPBZw0fJDb+BEHYMBLjqiUl2A7H8N+l0W4YfGKqbsPYSrCy4vct+7U6FQ=="; + }; + */ + + src = lowdown-src; + + outputs = [ "out" "dev" ]; + + buildInputs = [ which ]; + + configurePhase = + '' + ./configure \ + PREFIX=${placeholder "dev"} \ + BINDIR=${placeholder "out"}/bin + ''; + }; + + }; + + hydraJobs = { + + # Binary package for various platforms. + build = nixpkgs.lib.genAttrs systems (system: nixpkgsFor.${system}.nix); + + # Perl bindings for various platforms. + perlBindings = nixpkgs.lib.genAttrs systems (system: nixpkgsFor.${system}.nix.perl-bindings); + + # Binary tarball for various platforms, containing a Nix store + # with the closure of 'nix' package, and the second half of + # the installation script. + binaryTarball = nixpkgs.lib.genAttrs systems (system: + + with nixpkgsFor.${system}; + + let + installerClosureInfo = closureInfo { rootPaths = [ nix cacert ]; }; + in + + runCommand "nix-binary-tarball-${version}" + { #nativeBuildInputs = lib.optional (system != "aarch64-linux") shellcheck; + meta.description = "Distribution-independent Nix bootstrap binaries for ${system}"; + } + '' + cp ${installerClosureInfo}/registration $TMPDIR/reginfo + substitute ${./scripts/install-nix-from-closure.sh} $TMPDIR/install \ + --subst-var-by nix ${nix} \ + --subst-var-by cacert ${cacert} + + substitute ${./scripts/install-darwin-multi-user.sh} $TMPDIR/install-darwin-multi-user.sh \ + --subst-var-by nix ${nix} \ + --subst-var-by cacert ${cacert} + substitute ${./scripts/install-systemd-multi-user.sh} $TMPDIR/install-systemd-multi-user.sh \ + --subst-var-by nix ${nix} \ + --subst-var-by cacert ${cacert} + substitute ${./scripts/install-multi-user.sh} $TMPDIR/install-multi-user \ + --subst-var-by nix ${nix} \ + --subst-var-by cacert ${cacert} + + if type -p shellcheck; then + # SC1090: Don't worry about not being able to find + # $nix/etc/profile.d/nix.sh + shellcheck --exclude SC1090 $TMPDIR/install + shellcheck $TMPDIR/install-darwin-multi-user.sh + shellcheck $TMPDIR/install-systemd-multi-user.sh + + # SC1091: Don't panic about not being able to source + # /etc/profile + # SC2002: Ignore "useless cat" "error", when loading + # .reginfo, as the cat is a much cleaner + # implementation, even though it is "useless" + # SC2116: Allow ROOT_HOME=$(echo ~root) for resolving + # root's home directory + shellcheck --external-sources \ + --exclude SC1091,SC2002,SC2116 $TMPDIR/install-multi-user + fi + + chmod +x $TMPDIR/install + chmod +x $TMPDIR/install-darwin-multi-user.sh + chmod +x $TMPDIR/install-systemd-multi-user.sh + chmod +x $TMPDIR/install-multi-user + dir=nix-${version}-${system} + fn=$out/$dir.tar.xz + mkdir -p $out/nix-support + echo "file binary-dist $fn" >> $out/nix-support/hydra-build-products + tar cvfJ $fn \ + --owner=0 --group=0 --mode=u+rw,uga+r \ + --absolute-names \ + --hard-dereference \ + --transform "s,$TMPDIR/install,$dir/install," \ + --transform "s,$TMPDIR/reginfo,$dir/.reginfo," \ + --transform "s,$NIX_STORE,$dir/store,S" \ + $TMPDIR/install $TMPDIR/install-darwin-multi-user.sh \ + $TMPDIR/install-systemd-multi-user.sh \ + $TMPDIR/install-multi-user $TMPDIR/reginfo \ + $(cat ${installerClosureInfo}/store-paths) + ''); + + # The first half of the installation script. This is uploaded + # to https://nixos.org/nix/install. It downloads the binary + # tarball for the user's system and calls the second half of the + # installation script. + installerScript = + with nixpkgsFor.x86_64-linux; + runCommand "installer-script" + { buildInputs = [ nix ]; + } + '' + mkdir -p $out/nix-support + + substitute ${./scripts/install.in} $out/install \ + ${pkgs.lib.concatMapStrings + (system: "--replace '@binaryTarball_${system}@' $(nix --experimental-features nix-command hash-file --base16 --type sha256 ${self.hydraJobs.binaryTarball.${system}}/*.tar.xz) ") + [ "x86_64-linux" "i686-linux" "x86_64-darwin" "aarch64-linux" ] + } \ + --replace '@nixVersion@' ${version} + + echo "file installer $out/install" >> $out/nix-support/hydra-build-products + ''; + + # Line coverage analysis. + coverage = + with nixpkgsFor.x86_64-linux; + with commonDeps pkgs; + + releaseTools.coverageAnalysis { + name = "nix-coverage-${version}"; + + src = self; + + enableParallelBuilding = true; + + buildInputs = buildDeps ++ propagatedDeps; + + dontInstall = false; + + doInstallCheck = true; + + lcovFilter = [ "*/boost/*" "*-tab.*" ]; + + # We call `dot', and even though we just use it to + # syntax-check generated dot files, it still requires some + # fonts. So provide those. + FONTCONFIG_FILE = texFunctions.fontsConf; + }; + + # System tests. + tests.remoteBuilds = import ./tests/remote-builds.nix { + system = "x86_64-linux"; + inherit nixpkgs; + inherit (self) overlay; + }; + + tests.nix-copy-closure = import ./tests/nix-copy-closure.nix { + system = "x86_64-linux"; + inherit nixpkgs; + inherit (self) overlay; + }; + + tests.githubFlakes = (import ./tests/github-flakes.nix rec { + system = "x86_64-linux"; + inherit nixpkgs; + inherit (self) overlay; + }); + + tests.setuid = nixpkgs.lib.genAttrs + ["i686-linux" "x86_64-linux"] + (system: + import ./tests/setuid.nix rec { + inherit nixpkgs system; + inherit (self) overlay; + }); + + # Test whether the binary tarball works in an Ubuntu system. + tests.binaryTarball = + with nixpkgsFor.x86_64-linux; + vmTools.runInLinuxImage (runCommand "nix-binary-tarball-test" + { diskImage = vmTools.diskImages.ubuntu1204x86_64; + } + '' + set -x + useradd -m alice + su - alice -c 'tar xf ${self.hydraJobs.binaryTarball.x86_64-linux}/*.tar.*' + mkdir /dest-nix + mount -o bind /dest-nix /nix # Provide a writable /nix. + chown alice /nix + su - alice -c '_NIX_INSTALLER_TEST=1 ./nix-*/install' + su - alice -c 'nix-store --verify' + su - alice -c 'PAGER= nix-store -qR ${self.hydraJobs.build.x86_64-linux}' + + # Check whether 'nix upgrade-nix' works. + cat > /tmp/paths.nix <head_key($dstKey)) { print STDERR "uploading $fn to s3://$releasesBucketName/$dstKey...\n"; - $releasesBucket->add_key_filename($dstKey, $fn) + + my $configuration = (); + $configuration->{content_type} = "application/octet-stream"; + + if ($fn =~ /.sha256|.asc|install/) { + # Text files + $configuration->{content_type} = "text/plain"; + } + + $releasesBucket->add_key_filename($dstKey, $fn, $configuration) or die $releasesBucket->err . ": " . $releasesBucket->errstr; } } @@ -170,15 +179,5 @@ $channelsBucket->add_key( chdir("/home/eelco/Dev/nix-pristine") or die; system("git remote update origin") == 0 or die; system("git tag --force --sign $version $nixRev -m 'Tagging release $version'") == 0 or die; - -# Update the website. -my $siteDir = "/home/eelco/Dev/nixos-homepage-pristine"; - -system("cd $siteDir && git pull") == 0 or die; - -write_file("$siteDir/nix-release.tt", - "[%-\n" . - "latestNixVersion = \"$version\"\n" . - "-%]\n"); - -system("cd $siteDir && git commit -a -m 'Nix $version released'") == 0 or die; +system("git push --tags") == 0 or die; +system("git push --force-with-lease origin $nixRev:refs/heads/latest-release") == 0 or die; diff --git a/misc/bash/completion.sh b/misc/bash/completion.sh new file mode 100644 index 000000000..bc184edd6 --- /dev/null +++ b/misc/bash/completion.sh @@ -0,0 +1,19 @@ +function _complete_nix { + local -a words + local cword cur + _get_comp_words_by_ref -n ':=&' words cword cur + local have_type + while IFS= read -r line; do + if [[ -z $have_type ]]; then + have_type=1 + if [[ $line = filenames ]]; then + compopt -o filenames + fi + else + COMPREPLY+=("$line") + fi + done < <(NIX_GET_COMPLETIONS=$cword "${words[@]}") + __ltrim_colon_completions "$cur" +} + +complete -F _complete_nix nix diff --git a/misc/bash/local.mk b/misc/bash/local.mk new file mode 100644 index 000000000..66235af05 --- /dev/null +++ b/misc/bash/local.mk @@ -0,0 +1 @@ +$(eval $(call install-file-as, $(d)/completion.sh, $(datarootdir)/bash-completion/completions/nix, 0644)) diff --git a/misc/launchd/org.nixos.nix-daemon.plist.in b/misc/launchd/org.nixos.nix-daemon.plist.in index 9f26296a9..c334639e2 100644 --- a/misc/launchd/org.nixos.nix-daemon.plist.in +++ b/misc/launchd/org.nixos.nix-daemon.plist.in @@ -4,6 +4,8 @@ EnvironmentVariables + NIX_SSL_CERT_FILE + /nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt OBJC_DISABLE_INITIALIZE_FORK_SAFETY YES diff --git a/mk/precompiled-headers.mk b/mk/precompiled-headers.mk index 1c0452dc2..cdd3daecd 100644 --- a/mk/precompiled-headers.mk +++ b/mk/precompiled-headers.mk @@ -1,4 +1,4 @@ -PRECOMPILE_HEADERS ?= 1 +PRECOMPILE_HEADERS ?= 0 print-var-help += \ echo " PRECOMPILE_HEADERS ($(PRECOMPILE_HEADERS)): Whether to use precompiled headers to speed up the build"; @@ -10,33 +10,12 @@ $(GCH): precompiled-headers.h @mkdir -p "$(dir $@)" $(trace-gen) $(CXX) -x c++-header -o $@ $< $(GLOBAL_CXXFLAGS) $(GCH_CXXFLAGS) -PCH = $(buildprefix)precompiled-headers.h.pch - -$(PCH): precompiled-headers.h - @rm -f $@ - @mkdir -p "$(dir $@)" - $(trace-gen) $(CXX) -x c++-header -o $@ $< $(GLOBAL_CXXFLAGS) $(GCH_CXXFLAGS) - -clean-files += $(GCH) $(PCH) +clean-files += $(GCH) ifeq ($(PRECOMPILE_HEADERS), 1) - ifeq ($(CXX), g++) + GLOBAL_CXXFLAGS_PCH += -include $(buildprefix)precompiled-headers.h -Winvalid-pch - GLOBAL_CXXFLAGS_PCH += -include $(buildprefix)precompiled-headers.h -Winvalid-pch - - GLOBAL_ORDER_AFTER += $(GCH) - - else ifeq ($(CXX), clang++) - - GLOBAL_CXXFLAGS_PCH += -include-pch $(PCH) -Winvalid-pch - - GLOBAL_ORDER_AFTER += $(PCH) - - else - - $(error Don't know how to precompile headers on $(CXX)) - - endif + GLOBAL_ORDER_AFTER += $(GCH) endif diff --git a/mk/tests.mk b/mk/tests.mk index 2e39bb694..c1e140bac 100644 --- a/mk/tests.mk +++ b/mk/tests.mk @@ -8,7 +8,7 @@ define run-install-test .PHONY: $1.test $1.test: $1 $(test-deps) - @env TEST_NAME=$(notdir $(basename $1)) TESTS_ENVIRONMENT="$(tests-environment)" mk/run_test.sh $1 + @env TEST_NAME=$(notdir $(basename $1)) TESTS_ENVIRONMENT="$(tests-environment)" mk/run_test.sh $1 < /dev/null endef diff --git a/perl/Makefile b/perl/Makefile index 7ddb0cf69..259ed7dc3 100644 --- a/perl/Makefile +++ b/perl/Makefile @@ -1,6 +1,6 @@ makefiles = local.mk -GLOBAL_CXXFLAGS += -g -Wall +GLOBAL_CXXFLAGS += -g -Wall -std=c++17 -include Makefile.config diff --git a/perl/configure.ac b/perl/configure.ac index c3769e142..255744afd 100644 --- a/perl/configure.ac +++ b/perl/configure.ac @@ -70,19 +70,6 @@ PKG_CHECK_MODULES([NIX], [nix-store]) NEED_PROG([NIX], [nix]) -# Get nix configure values -export NIX_REMOTE=daemon -nixbindir=$("$NIX" --experimental-features nix-command eval --raw -f '' nixBinDir) -nixlibexecdir=$("$NIX" --experimental-features nix-command eval --raw -f '' nixLibexecDir) -nixlocalstatedir=$("$NIX" --experimental-features nix-command eval --raw -f '' nixLocalstateDir) -nixsysconfdir=$("$NIX" --experimental-features nix-command eval --raw -f '' nixSysconfDir) -nixstoredir=$("$NIX" --experimental-features nix-command eval --raw -f '' nixStoreDir) -AC_SUBST(nixbindir) -AC_SUBST(nixlibexecdir) -AC_SUBST(nixlocalstatedir) -AC_SUBST(nixsysconfdir) -AC_SUBST(nixstoredir) - # Expand all variables in config.status. test "$prefix" = NONE && prefix=$ac_default_prefix test "$exec_prefix" = NONE && exec_prefix='${prefix}' diff --git a/perl/lib/Nix/Config.pm.in b/perl/lib/Nix/Config.pm.in index bc1749e60..f7c6f2484 100644 --- a/perl/lib/Nix/Config.pm.in +++ b/perl/lib/Nix/Config.pm.in @@ -4,14 +4,8 @@ use MIME::Base64; $version = "@PACKAGE_VERSION@"; -$binDir = $ENV{"NIX_BIN_DIR"} || "@nixbindir@"; -$libexecDir = $ENV{"NIX_LIBEXEC_DIR"} || "@nixlibexecdir@"; -$stateDir = $ENV{"NIX_STATE_DIR"} || "@nixlocalstatedir@/nix"; -$logDir = $ENV{"NIX_LOG_DIR"} || "@nixlocalstatedir@/log/nix"; -$confDir = $ENV{"NIX_CONF_DIR"} || "@nixsysconfdir@/nix"; -$storeDir = $ENV{"NIX_STORE_DIR"} || "@nixstoredir@"; - -$useBindings = 1; +$binDir = Nix::Store::getBinDir; +$storeDir = Nix::Store::getStoreDir; %config = (); diff --git a/perl/lib/Nix/Store.pm b/perl/lib/Nix/Store.pm index d226264d4..179f1dc90 100644 --- a/perl/lib/Nix/Store.pm +++ b/perl/lib/Nix/Store.pm @@ -2,7 +2,6 @@ package Nix::Store; use strict; use warnings; -use Nix::Config; require Exporter; @@ -22,6 +21,7 @@ our @EXPORT = qw( addToStore makeFixedOutputPath derivationFromPath addTempRoot + getBinDir getStoreDir ); our $VERSION = '0.15'; @@ -34,62 +34,8 @@ sub backtick { return $res; } -if ($Nix::Config::useBindings) { - require XSLoader; - XSLoader::load('Nix::Store', $VERSION); -} else { - - # Provide slow fallbacks of some functions on platforms that don't - # support the Perl bindings. - - use File::Temp; - use Fcntl qw/F_SETFD/; - - *hashFile = sub { - my ($algo, $base32, $path) = @_; - my $res = backtick("$Nix::Config::binDir/nix-hash", "--flat", $path, "--type", $algo, $base32 ? "--base32" : ()); - chomp $res; - return $res; - }; - - *hashPath = sub { - my ($algo, $base32, $path) = @_; - my $res = backtick("$Nix::Config::binDir/nix-hash", $path, "--type", $algo, $base32 ? "--base32" : ()); - chomp $res; - return $res; - }; - - *hashString = sub { - my ($algo, $base32, $s) = @_; - my $fh = File::Temp->new(); - print $fh $s; - my $res = backtick("$Nix::Config::binDir/nix-hash", $fh->filename, "--type", $algo, $base32 ? "--base32" : ()); - chomp $res; - return $res; - }; - - *addToStore = sub { - my ($srcPath, $recursive, $algo) = @_; - die "not implemented" if $recursive || $algo ne "sha256"; - my $res = backtick("$Nix::Config::binDir/nix-store", "--add", $srcPath); - chomp $res; - return $res; - }; - - *isValidPath = sub { - my ($path) = @_; - my $res = backtick("$Nix::Config::binDir/nix-store", "--check-validity", "--print-invalid", $path); - chomp $res; - return $res ne $path; - }; - - *queryPathHash = sub { - my ($path) = @_; - my $res = backtick("$Nix::Config::binDir/nix-store", "--query", "--hash", $path); - chomp $res; - return $res; - }; -} +require XSLoader; +XSLoader::load('Nix::Store', $VERSION); 1; __END__ diff --git a/perl/lib/Nix/Store.xs b/perl/lib/Nix/Store.xs index 945ed49c7..599921151 100644 --- a/perl/lib/Nix/Store.xs +++ b/perl/lib/Nix/Store.xs @@ -182,7 +182,7 @@ void importPaths(int fd, int dontCheckSigs) PPCODE: try { FdSource source(fd); - store()->importPaths(source, nullptr, dontCheckSigs ? NoCheckSigs : CheckSigs); + store()->importPaths(source, dontCheckSigs ? NoCheckSigs : CheckSigs); } catch (Error & e) { croak("%s", e.what()); } @@ -224,7 +224,7 @@ SV * hashString(char * algo, int base32, char * s) SV * convertHash(char * algo, char * s, int toBase32) PPCODE: try { - Hash h(s, parseHashType(algo)); + auto h = Hash::parseAny(s, parseHashType(algo)); string s = h.to_string(toBase32 ? Base32 : Base16, false); XPUSHs(sv_2mortal(newSVpv(s.c_str(), 0))); } catch (Error & e) { @@ -285,7 +285,7 @@ SV * addToStore(char * srcPath, int recursive, char * algo) SV * makeFixedOutputPath(int recursive, char * algo, char * hash, char * name) PPCODE: try { - Hash h(hash, parseHashType(algo)); + auto h = Hash::parseAny(hash, parseHashType(algo)); auto method = recursive ? FileIngestionMethod::Recursive : FileIngestionMethod::Flat; auto path = store()->makeFixedOutputPath(method, h, name); XPUSHs(sv_2mortal(newSVpv(store()->printStorePath(path).c_str(), 0))); @@ -303,8 +303,14 @@ SV * derivationFromPath(char * drvPath) hash = newHV(); HV * outputs = newHV(); - for (auto & i : drv.outputs) - hv_store(outputs, i.first.c_str(), i.first.size(), newSVpv(store()->printStorePath(i.second.path).c_str(), 0), 0); + for (auto & i : drv.outputsAndOptPaths(*store())) { + hv_store( + outputs, i.first.c_str(), i.first.size(), + !i.second.second + ? newSV(0) /* null value */ + : newSVpv(store()->printStorePath(*i.second.second).c_str(), 0), + 0); + } hv_stores(hash, "outputs", newRV((SV *) outputs)); AV * inputDrvs = newAV(); @@ -345,3 +351,13 @@ void addTempRoot(char * storePath) } catch (Error & e) { croak("%s", e.what()); } + + +SV * getBinDir() + PPCODE: + XPUSHs(sv_2mortal(newSVpv(settings.nixBinDir.c_str(), 0))); + + +SV * getStoreDir() + PPCODE: + XPUSHs(sv_2mortal(newSVpv(settings.nixStore.c_str(), 0))); diff --git a/precompiled-headers.h b/precompiled-headers.h index 079aa496e..f52f1cab8 100644 --- a/precompiled-headers.h +++ b/precompiled-headers.h @@ -56,3 +56,5 @@ #include #include #include + +#include diff --git a/release-common.nix b/release-common.nix deleted file mode 100644 index 4316c3c23..000000000 --- a/release-common.nix +++ /dev/null @@ -1,82 +0,0 @@ -{ pkgs }: - -with pkgs; - -rec { - # Use "busybox-sandbox-shell" if present, - # if not (legacy) fallback and hope it's sufficient. - sh = pkgs.busybox-sandbox-shell or (busybox.override { - useMusl = true; - enableStatic = true; - enableMinimal = true; - extraConfig = '' - CONFIG_FEATURE_FANCY_ECHO y - CONFIG_FEATURE_SH_MATH y - CONFIG_FEATURE_SH_MATH_64 y - - CONFIG_ASH y - CONFIG_ASH_OPTIMIZE_FOR_SIZE y - - CONFIG_ASH_ALIAS y - CONFIG_ASH_BASH_COMPAT y - CONFIG_ASH_CMDCMD y - CONFIG_ASH_ECHO y - CONFIG_ASH_GETOPTS y - CONFIG_ASH_INTERNAL_GLOB y - CONFIG_ASH_JOB_CONTROL y - CONFIG_ASH_PRINTF y - CONFIG_ASH_TEST y - ''; - }); - - configureFlags = - lib.optionals stdenv.isLinux [ - "--with-sandbox-shell=${sh}/bin/busybox" - ]; - - buildDeps = - [ bison - flex - libxml2 - libxslt - docbook5 - docbook_xsl_ns - autoconf-archive - autoreconfHook - - curl - bzip2 xz brotli zlib editline - openssl pkgconfig sqlite - libarchive - boost - nlohmann_json - - # Tests - git - mercurial - gmock - ] - ++ lib.optionals stdenv.isLinux [libseccomp utillinuxMinimal] - ++ lib.optional (stdenv.isLinux || stdenv.isDarwin) libsodium - ++ lib.optional (stdenv.isLinux || stdenv.isDarwin) - ((aws-sdk-cpp.override { - apis = ["s3" "transfer"]; - customMemoryManagement = false; - }).overrideDerivation (args: { - /* - patches = args.patches or [] ++ [ (fetchpatch { - url = https://github.com/edolstra/aws-sdk-cpp/commit/3e07e1f1aae41b4c8b340735ff9e8c735f0c063f.patch; - sha256 = "1pij0v449p166f9l29x7ppzk8j7g9k9mp15ilh5qxp29c7fnvxy2"; - }) ]; - */ - })); - - propagatedDeps = - [ (boehmgc.override { enableLargeConfig = true; }) - ]; - - perlDeps = - [ perl - perlPackages.DBDSQLite - ]; -} diff --git a/release.nix b/release.nix deleted file mode 100644 index fbf9e4721..000000000 --- a/release.nix +++ /dev/null @@ -1,303 +0,0 @@ -{ nix ? builtins.fetchGit ./. -, nixpkgs ? builtins.fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-20.03-small.tar.gz -, officialRelease ? false -, systems ? [ "x86_64-linux" "i686-linux" "x86_64-darwin" "aarch64-linux" ] -}: - -let - - pkgs = import nixpkgs { system = builtins.currentSystem or "x86_64-linux"; }; - - version = - builtins.readFile ./.version - + (if officialRelease then "" else "pre${toString nix.revCount}_${nix.shortRev}"); - - jobs = rec { - - build = pkgs.lib.genAttrs systems (system: - - let pkgs = import nixpkgs { inherit system; }; in - - with pkgs; - - with import ./release-common.nix { inherit pkgs; }; - - stdenv.mkDerivation { - name = "nix-${version}"; - - src = nix; - - outputs = [ "out" "dev" "doc" ]; - - buildInputs = buildDeps; - - propagatedBuildInputs = propagatedDeps; - - preConfigure = - '' - # Copy libboost_context so we don't get all of Boost in our closure. - # https://github.com/NixOS/nixpkgs/issues/45462 - mkdir -p $out/lib - cp -pd ${boost}/lib/{libboost_context*,libboost_thread*,libboost_system*} $out/lib - rm -f $out/lib/*.a - ${lib.optionalString stdenv.isLinux '' - chmod u+w $out/lib/*.so.* - patchelf --set-rpath $out/lib:${stdenv.cc.cc.lib}/lib $out/lib/libboost_thread.so.* - ''} - - (cd perl; autoreconf --install --force --verbose) - ''; - - configureFlags = configureFlags ++ - [ "--sysconfdir=/etc" ]; - - enableParallelBuilding = true; - - makeFlags = "profiledir=$(out)/etc/profile.d"; - - installFlags = "sysconfdir=$(out)/etc"; - - postInstall = '' - mkdir -p $doc/nix-support - echo "doc manual $doc/share/doc/nix/manual" >> $doc/nix-support/hydra-build-products - ''; - - doCheck = true; - - doInstallCheck = true; - installCheckFlags = "sysconfdir=$(out)/etc"; - - separateDebugInfo = true; - }); - - - perlBindings = pkgs.lib.genAttrs systems (system: - - let pkgs = import nixpkgs { inherit system; }; in with pkgs; - - releaseTools.nixBuild { - name = "nix-perl-${version}"; - - src = nix; - - buildInputs = - [ autoconf-archive - autoreconfHook - jobs.build.${system} - curl - bzip2 - xz - pkgconfig - pkgs.perl - boost - ] - ++ lib.optional (stdenv.isLinux || stdenv.isDarwin) libsodium; - - configureFlags = '' - --with-dbi=${perlPackages.DBI}/${pkgs.perl.libPrefix} - --with-dbd-sqlite=${perlPackages.DBDSQLite}/${pkgs.perl.libPrefix} - ''; - - enableParallelBuilding = true; - - postUnpack = "sourceRoot=$sourceRoot/perl"; - }); - - - binaryTarball = pkgs.lib.genAttrs systems (system: - - with import nixpkgs { inherit system; }; - - let - toplevel = builtins.getAttr system jobs.build; - installerClosureInfo = closureInfo { rootPaths = [ toplevel cacert ]; }; - in - - runCommand "nix-binary-tarball-${version}" - { #nativeBuildInputs = lib.optional (system != "aarch64-linux") shellcheck; - meta.description = "Distribution-independent Nix bootstrap binaries for ${system}"; - } - '' - cp ${installerClosureInfo}/registration $TMPDIR/reginfo - cp ${./scripts/create-darwin-volume.sh} $TMPDIR/create-darwin-volume.sh - substitute ${./scripts/install-nix-from-closure.sh} $TMPDIR/install \ - --subst-var-by nix ${toplevel} \ - --subst-var-by cacert ${cacert} - substitute ${./scripts/install-darwin-multi-user.sh} $TMPDIR/install-darwin-multi-user.sh \ - --subst-var-by nix ${toplevel} \ - --subst-var-by cacert ${cacert} - substitute ${./scripts/install-systemd-multi-user.sh} $TMPDIR/install-systemd-multi-user.sh \ - --subst-var-by nix ${toplevel} \ - --subst-var-by cacert ${cacert} - substitute ${./scripts/install-multi-user.sh} $TMPDIR/install-multi-user \ - --subst-var-by nix ${toplevel} \ - --subst-var-by cacert ${cacert} - - if type -p shellcheck; then - # SC1090: Don't worry about not being able to find - # $nix/etc/profile.d/nix.sh - shellcheck --exclude SC1090 $TMPDIR/install - shellcheck $TMPDIR/create-darwin-volume.sh - shellcheck $TMPDIR/install-darwin-multi-user.sh - shellcheck $TMPDIR/install-systemd-multi-user.sh - - # SC1091: Don't panic about not being able to source - # /etc/profile - # SC2002: Ignore "useless cat" "error", when loading - # .reginfo, as the cat is a much cleaner - # implementation, even though it is "useless" - # SC2116: Allow ROOT_HOME=$(echo ~root) for resolving - # root's home directory - shellcheck --external-sources \ - --exclude SC1091,SC2002,SC2116 $TMPDIR/install-multi-user - fi - - chmod +x $TMPDIR/install - chmod +x $TMPDIR/create-darwin-volume.sh - chmod +x $TMPDIR/install-darwin-multi-user.sh - chmod +x $TMPDIR/install-systemd-multi-user.sh - chmod +x $TMPDIR/install-multi-user - dir=nix-${version}-${system} - fn=$out/$dir.tar.xz - mkdir -p $out/nix-support - echo "file binary-dist $fn" >> $out/nix-support/hydra-build-products - tar cvfJ $fn \ - --owner=0 --group=0 --mode=u+rw,uga+r \ - --absolute-names \ - --hard-dereference \ - --transform "s,$TMPDIR/install,$dir/install," \ - --transform "s,$TMPDIR/create-darwin-volume.sh,$dir/create-darwin-volume.sh," \ - --transform "s,$TMPDIR/reginfo,$dir/.reginfo," \ - --transform "s,$NIX_STORE,$dir/store,S" \ - $TMPDIR/install \ - $TMPDIR/create-darwin-volume.sh \ - $TMPDIR/install-darwin-multi-user.sh \ - $TMPDIR/install-systemd-multi-user.sh \ - $TMPDIR/install-multi-user \ - $TMPDIR/reginfo \ - $(cat ${installerClosureInfo}/store-paths) - ''); - - - coverage = - with pkgs; - - with import ./release-common.nix { inherit pkgs; }; - - releaseTools.coverageAnalysis { - name = "nix-coverage-${version}"; - - src = nix; - - enableParallelBuilding = true; - - buildInputs = buildDeps ++ propagatedDeps; - - dontInstall = false; - - doInstallCheck = true; - - lcovFilter = [ "*/boost/*" "*-tab.*" ]; - - # We call `dot', and even though we just use it to - # syntax-check generated dot files, it still requires some - # fonts. So provide those. - FONTCONFIG_FILE = texFunctions.fontsConf; - - # To test building without precompiled headers. - makeFlagsArray = [ "PRECOMPILE_HEADERS=0" ]; - }; - - - # System tests. - tests.remoteBuilds = (import ./tests/remote-builds.nix rec { - inherit nixpkgs; - nix = build.x86_64-linux; system = "x86_64-linux"; - }); - - tests.nix-copy-closure = (import ./tests/nix-copy-closure.nix rec { - inherit nixpkgs; - nix = build.x86_64-linux; system = "x86_64-linux"; - }); - - tests.setuid = pkgs.lib.genAttrs - ["i686-linux" "x86_64-linux"] - (system: - import ./tests/setuid.nix rec { - inherit nixpkgs; - nix = build.${system}; inherit system; - }); - - tests.binaryTarball = - with import nixpkgs { system = "x86_64-linux"; }; - vmTools.runInLinuxImage (runCommand "nix-binary-tarball-test" - { diskImage = vmTools.diskImages.ubuntu1204x86_64; - } - '' - set -x - useradd -m alice - su - alice -c 'tar xf ${binaryTarball.x86_64-linux}/*.tar.*' - mkdir /dest-nix - mount -o bind /dest-nix /nix # Provide a writable /nix. - chown alice /nix - su - alice -c '_NIX_INSTALLER_TEST=1 ./nix-*/install' - su - alice -c 'nix-store --verify' - su - alice -c 'PAGER= nix-store -qR ${build.x86_64-linux}' - - # Check whether 'nix upgrade-nix' works. - cat > /tmp/paths.nix <> $out/nix-support/hydra-build-products - ''; - - }; - - -in jobs diff --git a/scripts/install-multi-user.sh b/scripts/install-multi-user.sh index 00c9d540b..e5cc4d7ed 100644 --- a/scripts/install-multi-user.sh +++ b/scripts/install-multi-user.sh @@ -37,6 +37,8 @@ readonly PROFILE_NIX_FILE="$NIX_ROOT/var/nix/profiles/default/etc/profile.d/nix- readonly NIX_INSTALLED_NIX="@nix@" readonly NIX_INSTALLED_CACERT="@cacert@" +#readonly NIX_INSTALLED_NIX="/nix/store/j8dbv5w6jl34caywh2ygdy88knx1mdf7-nix-2.3.6" +#readonly NIX_INSTALLED_CACERT="/nix/store/7dxhzymvy330i28ii676fl1pqwcahv2f-nss-cacert-3.49.2" readonly EXTRACTED_NIX_PATH="$(dirname "$0")" readonly ROOT_HOME=$(echo ~root) @@ -69,9 +71,11 @@ uninstall_directions() { subheader "Uninstalling nix:" local step=0 - if poly_service_installed_check; then + if [ -e /run/systemd/system ] && poly_service_installed_check; then step=$((step + 1)) poly_service_uninstall_directions "$step" + else + step=$((step + 1)) fi for profile_target in "${PROFILE_TARGETS[@]}"; do @@ -250,7 +254,9 @@ function finish_success { echo "But fetching the nixpkgs channel failed. (Are you offline?)" echo "To try again later, run \"sudo -i nix-channel --update nixpkgs\"." fi - cat <&2 -elif [ "$(uname -s)" = "Linux" ] && [ -e /run/systemd/system ]; then +elif [ "$(uname -s)" = "Linux" ]; then echo "Note: a multi-user installation is possible. See https://nixos.org/nix/manual/#sect-multi-user-installation" >&2 fi @@ -122,7 +124,7 @@ if [ "$(uname -s)" = "Darwin" ]; then fi if [ "$INSTALL_MODE" = "daemon" ]; then - printf '\e[1;31mSwitching to the Daemon-based Installer\e[0m\n' + printf '\e[1;31mSwitching to the Multi-user Installer\e[0m\n' exec "$self/install-multi-user" exit 0 fi @@ -207,7 +209,7 @@ if [ -z "$NIX_INSTALLER_NO_MODIFY_PROFILE" ]; then if [ -w "$fn" ]; then if ! grep -q "$p" "$fn"; then echo "modifying $fn..." >&2 - echo "if [ -e $p ]; then . $p; fi # added by Nix installer" >> "$fn" + echo -e "\nif [ -e $p ]; then . $p; fi # added by Nix installer" >> "$fn" fi added=1 break @@ -218,7 +220,7 @@ if [ -z "$NIX_INSTALLER_NO_MODIFY_PROFILE" ]; then if [ -w "$fn" ]; then if ! grep -q "$p" "$fn"; then echo "modifying $fn..." >&2 - echo "if [ -e $p ]; then . $p; fi # added by Nix installer" >> "$fn" + echo -e "\nif [ -e $p ]; then . $p; fi # added by Nix installer" >> "$fn" fi added=1 break diff --git a/scripts/install.in b/scripts/install.in index 1d26c4ff0..39fae37e3 100644 --- a/scripts/install.in +++ b/scripts/install.in @@ -10,6 +10,8 @@ oops() { exit 1 } +umask 0022 + tmpDir="$(mktemp -d -t nix-binary-tarball-unpack.XXXXXXXXXX || \ oops "Can't create temporary directory for downloading the Nix binary tarball")" cleanup() { diff --git a/shell.nix b/shell.nix index 17aaa05ed..330df0ab6 100644 --- a/shell.nix +++ b/shell.nix @@ -1,25 +1,3 @@ -{ useClang ? false }: - -with import (builtins.fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-20.03-small.tar.gz) {}; - -with import ./release-common.nix { inherit pkgs; }; - -(if useClang then clangStdenv else stdenv).mkDerivation { - name = "nix"; - - buildInputs = buildDeps ++ propagatedDeps ++ perlDeps; - - inherit configureFlags; - - enableParallelBuilding = true; - - installFlags = "sysconfdir=$(out)/etc"; - - shellHook = - '' - export prefix=$(pwd)/inst - configureFlags+=" --prefix=$prefix" - PKG_CONFIG_PATH=$prefix/lib/pkgconfig:$PKG_CONFIG_PATH - PATH=$prefix/bin:$PATH - ''; -} +(import (fetchTarball https://github.com/edolstra/flake-compat/archive/master.tar.gz) { + src = ./.; +}).shellNix diff --git a/src/build-remote/build-remote.cc b/src/build-remote/build-remote.cc index e07117496..9a0e9f08d 100644 --- a/src/build-remote/build-remote.cc +++ b/src/build-remote/build-remote.cc @@ -33,18 +33,18 @@ std::string escapeUri(std::string uri) static string currentLoad; -static AutoCloseFD openSlotLock(const Machine & m, unsigned long long slot) +static AutoCloseFD openSlotLock(const Machine & m, uint64_t slot) { return openLockFile(fmt("%s/%s-%d", currentLoad, escapeUri(m.storeUri), slot), true); } -static bool allSupportedLocally(const std::set& requiredFeatures) { +static bool allSupportedLocally(Store & store, const std::set& requiredFeatures) { for (auto & feature : requiredFeatures) - if (!settings.systemFeatures.get().count(feature)) return false; + if (!store.systemFeatures.get().count(feature)) return false; return true; } -static int _main(int argc, char * * argv) +static int main_build_remote(int argc, char * * argv) { { logger = makeJSONLogger(*logger); @@ -103,10 +103,10 @@ static int _main(int argc, char * * argv) drvPath = store->parseStorePath(readString(source)); auto requiredFeatures = readStrings>(source); - auto canBuildLocally = amWilling + auto canBuildLocally = amWilling && ( neededSystem == settings.thisSystem || settings.extraPlatforms.get().count(neededSystem) > 0) - && allSupportedLocally(requiredFeatures); + && allSupportedLocally(*store, requiredFeatures); /* Error ignored here, will be caught later */ mkdir(currentLoad.c_str(), 0777); @@ -119,7 +119,7 @@ static int _main(int argc, char * * argv) bool rightType = false; Machine * bestMachine = nullptr; - unsigned long long bestLoad = 0; + uint64_t bestLoad = 0; for (auto & m : machines) { debug("considering building on remote machine '%s'", m.storeUri); @@ -130,8 +130,8 @@ static int _main(int argc, char * * argv) m.mandatoryMet(requiredFeatures)) { rightType = true; AutoCloseFD free; - unsigned long long load = 0; - for (unsigned long long slot = 0; slot < m.maxJobs; ++slot) { + uint64_t load = 0; + for (uint64_t slot = 0; slot < m.maxJobs; ++slot) { auto slotLock = openSlotLock(m, slot); if (lockFile(slotLock.get(), ltWrite, false)) { if (!free) { @@ -170,7 +170,45 @@ static int _main(int argc, char * * argv) if (rightType && !canBuildLocally) std::cerr << "# postpone\n"; else + { + // build the hint template. + string hintstring = "derivation: %s\nrequired (system, features): (%s, %s)"; + hintstring += "\n%s available machines:"; + hintstring += "\n(systems, maxjobs, supportedFeatures, mandatoryFeatures)"; + + for (unsigned int i = 0; i < machines.size(); ++i) { + hintstring += "\n(%s, %s, %s, %s)"; + } + + // add the template values. + string drvstr; + if (drvPath.has_value()) + drvstr = drvPath->to_string(); + else + drvstr = ""; + + auto hint = hintformat(hintstring); + hint + % drvstr + % neededSystem + % concatStringsSep(", ", requiredFeatures) + % machines.size(); + + for (auto & m : machines) { + hint % concatStringsSep>(", ", m.systemTypes) + % m.maxJobs + % concatStringsSep(", ", m.supportedFeatures) + % concatStringsSep(", ", m.mandatoryFeatures); + } + + logErrorInfo(lvlInfo, { + .name = "Remote build", + .description = "Failed to find a machine for remote build!", + .hint = hint + }); + std::cerr << "# decline\n"; + } break; } @@ -186,15 +224,7 @@ static int _main(int argc, char * * argv) Activity act(*logger, lvlTalkative, actUnknown, fmt("connecting to '%s'", bestMachine->storeUri)); - Store::Params storeParams; - if (hasPrefix(bestMachine->storeUri, "ssh://")) { - storeParams["max-connections"] = "1"; - storeParams["log-fd"] = "4"; - if (bestMachine->sshKey != "") - storeParams["ssh-key"] = bestMachine->sshKey; - } - - sshStore = openStore(bestMachine->storeUri, storeParams); + sshStore = bestMachine->openStore(); sshStore->connect(); storeUri = bestMachine->storeUri; @@ -267,4 +297,4 @@ connected: } } -static RegisterLegacyCommand s1("build-remote", _main); +static RegisterLegacyCommand r_build_remote("build-remote", main_build_remote); diff --git a/src/libexpr/common-eval-args.cc b/src/libexpr/common-eval-args.cc index 44baadd53..10c1a6975 100644 --- a/src/libexpr/common-eval-args.cc +++ b/src/libexpr/common-eval-args.cc @@ -4,6 +4,8 @@ #include "util.hh" #include "eval.hh" #include "fetchers.hh" +#include "registry.hh" +#include "flake/flakeref.hh" #include "store-api.hh" namespace nix { @@ -27,10 +29,31 @@ MixEvalArgs::MixEvalArgs() addFlag({ .longName = "include", .shortName = 'I', - .description = "add a path to the list of locations used to look up <...> file names", + .description = "add a path to the list of locations used to look up `<...>` file names", .labels = {"path"}, .handler = {[&](std::string s) { searchPath.push_back(s); }} }); + + addFlag({ + .longName = "impure", + .description = "allow access to mutable paths and repositories", + .handler = {[&]() { + evalSettings.pureEval = false; + }}, + }); + + addFlag({ + .longName = "override-flake", + .description = "override a flake registry value", + .labels = {"original-ref", "resolved-ref"}, + .handler = {[&](std::string _from, std::string _to) { + auto from = parseFlakeRef(_from, absPath(".")); + auto to = parseFlakeRef(_to, absPath(".")); + fetchers::Attrs extraAttrs; + if (to.subdir != "") extraAttrs["dir"] = to.subdir; + fetchers::overrideRegistry(from.input, to.input, extraAttrs); + }} + }); } Bindings * MixEvalArgs::getAutoArgs(EvalState & state) @@ -53,7 +76,7 @@ Path lookupFileArg(EvalState & state, string s) if (isUri(s)) { return state.store->toRealPath( fetchers::downloadTarball( - state.store, resolveUri(s), "source", false).storePath); + state.store, resolveUri(s), "source", false).first.storePath); } else if (s.size() > 2 && s.at(0) == '<' && s.at(s.size() - 1) == '>') { Path p = s.substr(1, s.size() - 2); return state.findFile(p); diff --git a/src/libexpr/eval-cache.cc b/src/libexpr/eval-cache.cc new file mode 100644 index 000000000..381344b40 --- /dev/null +++ b/src/libexpr/eval-cache.cc @@ -0,0 +1,620 @@ +#include "eval-cache.hh" +#include "sqlite.hh" +#include "eval.hh" +#include "eval-inline.hh" +#include "store-api.hh" + +namespace nix::eval_cache { + +static const char * schema = R"sql( +create table if not exists Attributes ( + parent integer not null, + name text, + type integer not null, + value text, + context text, + primary key (parent, name) +); +)sql"; + +struct AttrDb +{ + std::atomic_bool failed{false}; + + struct State + { + SQLite db; + SQLiteStmt insertAttribute; + SQLiteStmt insertAttributeWithContext; + SQLiteStmt queryAttribute; + SQLiteStmt queryAttributes; + std::unique_ptr txn; + }; + + std::unique_ptr> _state; + + AttrDb(const Hash & fingerprint) + : _state(std::make_unique>()) + { + auto state(_state->lock()); + + Path cacheDir = getCacheDir() + "/nix/eval-cache-v2"; + createDirs(cacheDir); + + Path dbPath = cacheDir + "/" + fingerprint.to_string(Base16, false) + ".sqlite"; + + state->db = SQLite(dbPath); + state->db.isCache(); + state->db.exec(schema); + + state->insertAttribute.create(state->db, + "insert or replace into Attributes(parent, name, type, value) values (?, ?, ?, ?)"); + + state->insertAttributeWithContext.create(state->db, + "insert or replace into Attributes(parent, name, type, value, context) values (?, ?, ?, ?, ?)"); + + state->queryAttribute.create(state->db, + "select rowid, type, value, context from Attributes where parent = ? and name = ?"); + + state->queryAttributes.create(state->db, + "select name from Attributes where parent = ?"); + + state->txn = std::make_unique(state->db); + } + + ~AttrDb() + { + try { + auto state(_state->lock()); + if (!failed) + state->txn->commit(); + state->txn.reset(); + } catch (...) { + ignoreException(); + } + } + + template + AttrId doSQLite(F && fun) + { + if (failed) return 0; + try { + return fun(); + } catch (SQLiteError &) { + ignoreException(); + failed = true; + return 0; + } + } + + AttrId setAttrs( + AttrKey key, + const std::vector & attrs) + { + return doSQLite([&]() + { + auto state(_state->lock()); + + state->insertAttribute.use() + (key.first) + (key.second) + (AttrType::FullAttrs) + (0, false).exec(); + + AttrId rowId = state->db.getLastInsertedRowId(); + assert(rowId); + + for (auto & attr : attrs) + state->insertAttribute.use() + (rowId) + (attr) + (AttrType::Placeholder) + (0, false).exec(); + + return rowId; + }); + } + + AttrId setString( + AttrKey key, + std::string_view s, + const char * * context = nullptr) + { + return doSQLite([&]() + { + auto state(_state->lock()); + + if (context) { + std::string ctx; + for (const char * * p = context; *p; ++p) { + if (p != context) ctx.push_back(' '); + ctx.append(*p); + } + state->insertAttributeWithContext.use() + (key.first) + (key.second) + (AttrType::String) + (s) + (ctx).exec(); + } else { + state->insertAttribute.use() + (key.first) + (key.second) + (AttrType::String) + (s).exec(); + } + + return state->db.getLastInsertedRowId(); + }); + } + + AttrId setBool( + AttrKey key, + bool b) + { + return doSQLite([&]() + { + auto state(_state->lock()); + + state->insertAttribute.use() + (key.first) + (key.second) + (AttrType::Bool) + (b ? 1 : 0).exec(); + + return state->db.getLastInsertedRowId(); + }); + } + + AttrId setPlaceholder(AttrKey key) + { + return doSQLite([&]() + { + auto state(_state->lock()); + + state->insertAttribute.use() + (key.first) + (key.second) + (AttrType::Placeholder) + (0, false).exec(); + + return state->db.getLastInsertedRowId(); + }); + } + + AttrId setMissing(AttrKey key) + { + return doSQLite([&]() + { + auto state(_state->lock()); + + state->insertAttribute.use() + (key.first) + (key.second) + (AttrType::Missing) + (0, false).exec(); + + return state->db.getLastInsertedRowId(); + }); + } + + AttrId setMisc(AttrKey key) + { + return doSQLite([&]() + { + auto state(_state->lock()); + + state->insertAttribute.use() + (key.first) + (key.second) + (AttrType::Misc) + (0, false).exec(); + + return state->db.getLastInsertedRowId(); + }); + } + + AttrId setFailed(AttrKey key) + { + return doSQLite([&]() + { + auto state(_state->lock()); + + state->insertAttribute.use() + (key.first) + (key.second) + (AttrType::Failed) + (0, false).exec(); + + return state->db.getLastInsertedRowId(); + }); + } + + std::optional> getAttr( + AttrKey key, + SymbolTable & symbols) + { + auto state(_state->lock()); + + auto queryAttribute(state->queryAttribute.use()(key.first)(key.second)); + if (!queryAttribute.next()) return {}; + + auto rowId = (AttrType) queryAttribute.getInt(0); + auto type = (AttrType) queryAttribute.getInt(1); + + switch (type) { + case AttrType::Placeholder: + return {{rowId, placeholder_t()}}; + case AttrType::FullAttrs: { + // FIXME: expensive, should separate this out. + std::vector attrs; + auto queryAttributes(state->queryAttributes.use()(rowId)); + while (queryAttributes.next()) + attrs.push_back(symbols.create(queryAttributes.getStr(0))); + return {{rowId, attrs}}; + } + case AttrType::String: { + std::vector> context; + if (!queryAttribute.isNull(3)) + for (auto & s : tokenizeString>(queryAttribute.getStr(3), ";")) + context.push_back(decodeContext(s)); + return {{rowId, string_t{queryAttribute.getStr(2), context}}}; + } + case AttrType::Bool: + return {{rowId, queryAttribute.getInt(2) != 0}}; + case AttrType::Missing: + return {{rowId, missing_t()}}; + case AttrType::Misc: + return {{rowId, misc_t()}}; + case AttrType::Failed: + return {{rowId, failed_t()}}; + default: + throw Error("unexpected type in evaluation cache"); + } + } +}; + +static std::shared_ptr makeAttrDb(const Hash & fingerprint) +{ + try { + return std::make_shared(fingerprint); + } catch (SQLiteError &) { + ignoreException(); + return nullptr; + } +} + +EvalCache::EvalCache( + std::optional> useCache, + EvalState & state, + RootLoader rootLoader) + : db(useCache ? makeAttrDb(*useCache) : nullptr) + , state(state) + , rootLoader(rootLoader) +{ +} + +Value * EvalCache::getRootValue() +{ + if (!value) { + debug("getting root value"); + value = allocRootValue(rootLoader()); + } + return *value; +} + +std::shared_ptr EvalCache::getRoot() +{ + return std::make_shared(ref(shared_from_this()), std::nullopt); +} + +AttrCursor::AttrCursor( + ref root, + Parent parent, + Value * value, + std::optional> && cachedValue) + : root(root), parent(parent), cachedValue(std::move(cachedValue)) +{ + if (value) + _value = allocRootValue(value); +} + +AttrKey AttrCursor::getKey() +{ + if (!parent) + return {0, root->state.sEpsilon}; + if (!parent->first->cachedValue) { + parent->first->cachedValue = root->db->getAttr( + parent->first->getKey(), root->state.symbols); + assert(parent->first->cachedValue); + } + return {parent->first->cachedValue->first, parent->second}; +} + +Value & AttrCursor::getValue() +{ + if (!_value) { + if (parent) { + auto & vParent = parent->first->getValue(); + root->state.forceAttrs(vParent); + auto attr = vParent.attrs->get(parent->second); + if (!attr) + throw Error("attribute '%s' is unexpectedly missing", getAttrPathStr()); + _value = allocRootValue(attr->value); + } else + _value = allocRootValue(root->getRootValue()); + } + return **_value; +} + +std::vector AttrCursor::getAttrPath() const +{ + if (parent) { + auto attrPath = parent->first->getAttrPath(); + attrPath.push_back(parent->second); + return attrPath; + } else + return {}; +} + +std::vector AttrCursor::getAttrPath(Symbol name) const +{ + auto attrPath = getAttrPath(); + attrPath.push_back(name); + return attrPath; +} + +std::string AttrCursor::getAttrPathStr() const +{ + return concatStringsSep(".", getAttrPath()); +} + +std::string AttrCursor::getAttrPathStr(Symbol name) const +{ + return concatStringsSep(".", getAttrPath(name)); +} + +Value & AttrCursor::forceValue() +{ + debug("evaluating uncached attribute %s", getAttrPathStr()); + + auto & v = getValue(); + + try { + root->state.forceValue(v); + } catch (EvalError &) { + debug("setting '%s' to failed", getAttrPathStr()); + if (root->db) + cachedValue = {root->db->setFailed(getKey()), failed_t()}; + throw; + } + + if (root->db && (!cachedValue || std::get_if(&cachedValue->second))) { + if (v.type == tString) + cachedValue = {root->db->setString(getKey(), v.string.s, v.string.context), + string_t{v.string.s, {}}}; + else if (v.type == tPath) + cachedValue = {root->db->setString(getKey(), v.path), v.path}; + else if (v.type == tBool) + cachedValue = {root->db->setBool(getKey(), v.boolean), v.boolean}; + else if (v.type == tAttrs) + ; // FIXME: do something? + else + cachedValue = {root->db->setMisc(getKey()), misc_t()}; + } + + return v; +} + +std::shared_ptr AttrCursor::maybeGetAttr(Symbol name, bool forceErrors) +{ + if (root->db) { + if (!cachedValue) + cachedValue = root->db->getAttr(getKey(), root->state.symbols); + + if (cachedValue) { + if (auto attrs = std::get_if>(&cachedValue->second)) { + for (auto & attr : *attrs) + if (attr == name) + return std::make_shared(root, std::make_pair(shared_from_this(), name)); + return nullptr; + } else if (std::get_if(&cachedValue->second)) { + auto attr = root->db->getAttr({cachedValue->first, name}, root->state.symbols); + if (attr) { + if (std::get_if(&attr->second)) + return nullptr; + else if (std::get_if(&attr->second)) { + if (forceErrors) + debug("reevaluating failed cached attribute '%s'"); + else + throw CachedEvalError("cached failure of attribute '%s'", getAttrPathStr(name)); + } else + return std::make_shared(root, + std::make_pair(shared_from_this(), name), nullptr, std::move(attr)); + } + // Incomplete attrset, so need to fall thru and + // evaluate to see whether 'name' exists + } else + return nullptr; + //throw TypeError("'%s' is not an attribute set", getAttrPathStr()); + } + } + + auto & v = forceValue(); + + if (v.type != tAttrs) + return nullptr; + //throw TypeError("'%s' is not an attribute set", getAttrPathStr()); + + auto attr = v.attrs->get(name); + + if (!attr) { + if (root->db) { + if (!cachedValue) + cachedValue = {root->db->setPlaceholder(getKey()), placeholder_t()}; + root->db->setMissing({cachedValue->first, name}); + } + return nullptr; + } + + std::optional> cachedValue2; + if (root->db) { + if (!cachedValue) + cachedValue = {root->db->setPlaceholder(getKey()), placeholder_t()}; + cachedValue2 = {root->db->setPlaceholder({cachedValue->first, name}), placeholder_t()}; + } + + return std::make_shared( + root, std::make_pair(shared_from_this(), name), attr->value, std::move(cachedValue2)); +} + +std::shared_ptr AttrCursor::maybeGetAttr(std::string_view name) +{ + return maybeGetAttr(root->state.symbols.create(name)); +} + +std::shared_ptr AttrCursor::getAttr(Symbol name, bool forceErrors) +{ + auto p = maybeGetAttr(name, forceErrors); + if (!p) + throw Error("attribute '%s' does not exist", getAttrPathStr(name)); + return p; +} + +std::shared_ptr AttrCursor::getAttr(std::string_view name) +{ + return getAttr(root->state.symbols.create(name)); +} + +std::shared_ptr AttrCursor::findAlongAttrPath(const std::vector & attrPath) +{ + auto res = shared_from_this(); + for (auto & attr : attrPath) { + res = res->maybeGetAttr(attr); + if (!res) return {}; + } + return res; +} + +std::string AttrCursor::getString() +{ + if (root->db) { + if (!cachedValue) + cachedValue = root->db->getAttr(getKey(), root->state.symbols); + if (cachedValue && !std::get_if(&cachedValue->second)) { + if (auto s = std::get_if(&cachedValue->second)) { + debug("using cached string attribute '%s'", getAttrPathStr()); + return s->first; + } else + throw TypeError("'%s' is not a string", getAttrPathStr()); + } + } + + auto & v = forceValue(); + + if (v.type != tString && v.type != tPath) + throw TypeError("'%s' is not a string but %s", getAttrPathStr(), showType(v.type)); + + return v.type == tString ? v.string.s : v.path; +} + +string_t AttrCursor::getStringWithContext() +{ + if (root->db) { + if (!cachedValue) + cachedValue = root->db->getAttr(getKey(), root->state.symbols); + if (cachedValue && !std::get_if(&cachedValue->second)) { + if (auto s = std::get_if(&cachedValue->second)) { + debug("using cached string attribute '%s'", getAttrPathStr()); + return *s; + } else + throw TypeError("'%s' is not a string", getAttrPathStr()); + } + } + + auto & v = forceValue(); + + if (v.type == tString) + return {v.string.s, v.getContext()}; + else if (v.type == tPath) + return {v.path, {}}; + else + throw TypeError("'%s' is not a string but %s", getAttrPathStr(), showType(v.type)); +} + +bool AttrCursor::getBool() +{ + if (root->db) { + if (!cachedValue) + cachedValue = root->db->getAttr(getKey(), root->state.symbols); + if (cachedValue && !std::get_if(&cachedValue->second)) { + if (auto b = std::get_if(&cachedValue->second)) { + debug("using cached Boolean attribute '%s'", getAttrPathStr()); + return *b; + } else + throw TypeError("'%s' is not a Boolean", getAttrPathStr()); + } + } + + auto & v = forceValue(); + + if (v.type != tBool) + throw TypeError("'%s' is not a Boolean", getAttrPathStr()); + + return v.boolean; +} + +std::vector AttrCursor::getAttrs() +{ + if (root->db) { + if (!cachedValue) + cachedValue = root->db->getAttr(getKey(), root->state.symbols); + if (cachedValue && !std::get_if(&cachedValue->second)) { + if (auto attrs = std::get_if>(&cachedValue->second)) { + debug("using cached attrset attribute '%s'", getAttrPathStr()); + return *attrs; + } else + throw TypeError("'%s' is not an attribute set", getAttrPathStr()); + } + } + + auto & v = forceValue(); + + if (v.type != tAttrs) + throw TypeError("'%s' is not an attribute set", getAttrPathStr()); + + std::vector attrs; + for (auto & attr : *getValue().attrs) + attrs.push_back(attr.name); + std::sort(attrs.begin(), attrs.end(), [](const Symbol & a, const Symbol & b) { + return (const string &) a < (const string &) b; + }); + + if (root->db) + cachedValue = {root->db->setAttrs(getKey(), attrs), attrs}; + + return attrs; +} + +bool AttrCursor::isDerivation() +{ + auto aType = maybeGetAttr("type"); + return aType && aType->getString() == "derivation"; +} + +StorePath AttrCursor::forceDerivation() +{ + auto aDrvPath = getAttr(root->state.sDrvPath, true); + auto drvPath = root->state.store->parseStorePath(aDrvPath->getString()); + if (!root->state.store->isValidPath(drvPath) && !settings.readOnlyMode) { + /* The eval cache contains 'drvPath', but the actual path has + been garbage-collected. So force it to be regenerated. */ + aDrvPath->forceValue(); + if (!root->state.store->isValidPath(drvPath)) + throw Error("don't know how to recreate store derivation '%s'!", + root->state.store->printStorePath(drvPath)); + } + return drvPath; +} + +} diff --git a/src/libexpr/eval-cache.hh b/src/libexpr/eval-cache.hh new file mode 100644 index 000000000..e23e45c94 --- /dev/null +++ b/src/libexpr/eval-cache.hh @@ -0,0 +1,123 @@ +#pragma once + +#include "sync.hh" +#include "hash.hh" +#include "eval.hh" + +#include +#include + +namespace nix::eval_cache { + +MakeError(CachedEvalError, EvalError); + +struct AttrDb; +class AttrCursor; + +class EvalCache : public std::enable_shared_from_this +{ + friend class AttrCursor; + + std::shared_ptr db; + EvalState & state; + typedef std::function RootLoader; + RootLoader rootLoader; + RootValue value; + + Value * getRootValue(); + +public: + + EvalCache( + std::optional> useCache, + EvalState & state, + RootLoader rootLoader); + + std::shared_ptr getRoot(); +}; + +enum AttrType { + Placeholder = 0, + FullAttrs = 1, + String = 2, + Missing = 3, + Misc = 4, + Failed = 5, + Bool = 6, +}; + +struct placeholder_t {}; +struct missing_t {}; +struct misc_t {}; +struct failed_t {}; +typedef uint64_t AttrId; +typedef std::pair AttrKey; +typedef std::pair>> string_t; + +typedef std::variant< + std::vector, + string_t, + placeholder_t, + missing_t, + misc_t, + failed_t, + bool + > AttrValue; + +class AttrCursor : public std::enable_shared_from_this +{ + friend class EvalCache; + + ref root; + typedef std::optional, Symbol>> Parent; + Parent parent; + RootValue _value; + std::optional> cachedValue; + + AttrKey getKey(); + + Value & getValue(); + +public: + + AttrCursor( + ref root, + Parent parent, + Value * value = nullptr, + std::optional> && cachedValue = {}); + + std::vector getAttrPath() const; + + std::vector getAttrPath(Symbol name) const; + + std::string getAttrPathStr() const; + + std::string getAttrPathStr(Symbol name) const; + + std::shared_ptr maybeGetAttr(Symbol name, bool forceErrors = false); + + std::shared_ptr maybeGetAttr(std::string_view name); + + std::shared_ptr getAttr(Symbol name, bool forceErrors = false); + + std::shared_ptr getAttr(std::string_view name); + + std::shared_ptr findAlongAttrPath(const std::vector & attrPath); + + std::string getString(); + + string_t getStringWithContext(); + + bool getBool(); + + std::vector getAttrs(); + + bool isDerivation(); + + Value & forceValue(); + + /* Force creation of the .drv file in the Nix store. */ + StorePath forceDerivation(); +}; + +} diff --git a/src/libexpr/eval.cc b/src/libexpr/eval.cc index c1a9af9b2..d6366050c 100644 --- a/src/libexpr/eval.cc +++ b/src/libexpr/eval.cc @@ -87,6 +87,7 @@ static void printValue(std::ostream & str, std::set & active, con else if (*i == '\n') str << "\\n"; else if (*i == '\r') str << "\\r"; else if (*i == '\t') str << "\\t"; + else if (*i == '$' && *(i+1) == '{') str << "\\" << *i; else str << *i; str << "\""; break; @@ -199,6 +200,18 @@ string showType(const Value & v) } +bool Value::isTrivial() const +{ + return + type != tApp + && type != tPrimOpApp + && (type != tThunk + || (dynamic_cast(thunk.expr) + && ((ExprAttrs *) thunk.expr)->dynamicAttrs.empty()) + || dynamic_cast(thunk.expr)); +} + + #if HAVE_BOEHMGC /* Called when the Boehm GC runs out of memory. */ static void * oomHandler(size_t requested) @@ -333,12 +346,17 @@ EvalState::EvalState(const Strings & _searchPath, ref store) , sStructuredAttrs(symbols.create("__structuredAttrs")) , sBuilder(symbols.create("builder")) , sArgs(symbols.create("args")) + , sContentAddressed(symbols.create("__contentAddressed")) , sOutputHash(symbols.create("outputHash")) , sOutputHashAlgo(symbols.create("outputHashAlgo")) , sOutputHashMode(symbols.create("outputHashMode")) , sRecurseForDerivations(symbols.create("recurseForDerivations")) + , sDescription(symbols.create("description")) + , sSelf(symbols.create("self")) + , sEpsilon(symbols.create("")) , repair(NoRepair) , store(store) + , regexCache(makeRegexCache()) , baseEnv(allocEnv(128)) , staticBaseEnv(false, 0) { @@ -353,7 +371,11 @@ EvalState::EvalState(const Strings & _searchPath, ref store) for (auto & i : _searchPath) addToSearchPath(i); for (auto & i : evalSettings.nixPath.get()) addToSearchPath(i); } - addToSearchPath("nix=" + canonPath(settings.nixDataDir + "/nix/corepkgs", true)); + + try { + addToSearchPath("nix=" + canonPath(settings.nixDataDir + "/nix/corepkgs", true)); + } catch (Error &) { + } if (evalSettings.restrictEval || evalSettings.pureEval) { allowedPaths = PathSet(); @@ -365,10 +387,14 @@ EvalState::EvalState(const Strings & _searchPath, ref store) auto path = r.second; if (store->isInStore(r.second)) { - StorePathSet closure; - store->computeFSClosure(store->parseStorePath(store->toStorePath(r.second)), closure); - for (auto & path : closure) - allowedPaths->insert(store->printStorePath(path)); + try { + StorePathSet closure; + store->computeFSClosure(store->toStorePath(r.second).first, closure); + for (auto & path : closure) + allowedPaths->insert(store->printStorePath(path)); + } catch (InvalidPath &) { + allowedPaths->insert(r.second); + } } else allowedPaths->insert(r.second); } @@ -493,7 +519,7 @@ Value * EvalState::addPrimOp(const string & name, if (arity == 0) { auto vPrimOp = allocValue(); vPrimOp->type = tPrimOp; - vPrimOp->primOp = new PrimOp(primOp, 1, sym); + vPrimOp->primOp = new PrimOp { .fun = primOp, .arity = 1, .name = sym }; Value v; mkApp(v, *vPrimOp, *vPrimOp); return addConstant(name, v); @@ -501,7 +527,7 @@ Value * EvalState::addPrimOp(const string & name, Value * v = allocValue(); v->type = tPrimOp; - v->primOp = new PrimOp(primOp, arity, sym); + v->primOp = new PrimOp { .fun = primOp, .arity = arity, .name = sym }; staticBaseEnv.vars[symbols.create(name)] = baseEnvDispl; baseEnv.values[baseEnvDispl++] = v; baseEnv.values[0]->attrs->push_back(Attr(sym, v)); @@ -509,12 +535,59 @@ Value * EvalState::addPrimOp(const string & name, } +Value * EvalState::addPrimOp(PrimOp && primOp) +{ + /* Hack to make constants lazy: turn them into a application of + the primop to a dummy value. */ + if (primOp.arity == 0) { + primOp.arity = 1; + auto vPrimOp = allocValue(); + vPrimOp->type = tPrimOp; + vPrimOp->primOp = new PrimOp(std::move(primOp)); + Value v; + mkApp(v, *vPrimOp, *vPrimOp); + return addConstant(primOp.name, v); + } + + Symbol envName = primOp.name; + if (hasPrefix(primOp.name, "__")) + primOp.name = symbols.create(std::string(primOp.name, 2)); + + Value * v = allocValue(); + v->type = tPrimOp; + v->primOp = new PrimOp(std::move(primOp)); + staticBaseEnv.vars[envName] = baseEnvDispl; + baseEnv.values[baseEnvDispl++] = v; + baseEnv.values[0]->attrs->push_back(Attr(primOp.name, v)); + return v; +} + + Value & EvalState::getBuiltin(const string & name) { return *baseEnv.values[0]->attrs->find(symbols.create(name))->value; } +std::optional EvalState::getDoc(Value & v) +{ + if (v.type == tPrimOp || v.type == tPrimOpApp) { + auto v2 = &v; + while (v2->type == tPrimOpApp) + v2 = v2->primOpApp.left; + if (v2->primOp->doc) + return Doc { + .pos = noPos, + .name = v2->primOp->name, + .arity = v2->primOp->arity, + .args = v2->primOp->args, + .doc = v2->primOp->doc, + }; + } + return {}; +} + + /* Every "format" object (even temporary) takes up a few hundred bytes of stack space, which is a real killer in the recursive evaluator. So here are some helper functions for throwing @@ -782,7 +855,7 @@ Value * ExprPath::maybeThunk(EvalState & state, Env & env) } -void EvalState::evalFile(const Path & path_, Value & v) +void EvalState::evalFile(const Path & path_, Value & v, bool mustBeTrivial) { auto path = checkSourcePath(path_); @@ -811,6 +884,11 @@ void EvalState::evalFile(const Path & path_, Value & v) fileParseCache[path2] = e; try { + // Enforce that 'flake.nix' is a direct attrset, not a + // computation. + if (mustBeTrivial && + !(dynamic_cast(e))) + throw Error("file '%s' must be an attribute set", path); eval(e, v); } catch (Error & e) { addErrorTrace(e, "while evaluating the file '%1%':", path2); @@ -1236,10 +1314,10 @@ void EvalState::callFunction(Value & fun, Value & arg, Value & v, const Pos & po try { lambda.body->eval(*this, env2, v); } catch (Error & e) { - addErrorTrace(e, lambda.pos, "while evaluating %s", - (lambda.name.set() - ? "'" + (string) lambda.name + "'" - : "anonymous lambdaction")); + addErrorTrace(e, lambda.pos, "while evaluating %s", + (lambda.name.set() + ? "'" + (string) lambda.name + "'" + : "anonymous lambda")); addErrorTrace(e, pos, "from call site%s", ""); throw; } @@ -1276,14 +1354,25 @@ void EvalState::autoCallFunction(Bindings & args, Value & fun, Value & res) } Value * actualArgs = allocValue(); - mkAttrs(*actualArgs, fun.lambda.fun->formals->formals.size()); + mkAttrs(*actualArgs, std::max(static_cast(fun.lambda.fun->formals->formals.size()), args.size())); - for (auto & i : fun.lambda.fun->formals->formals) { - Bindings::iterator j = args.find(i.name); - if (j != args.end()) - actualArgs->attrs->push_back(*j); - else if (!i.def) - throwTypeError("cannot auto-call a function that has an argument without a default value ('%1%')", i.name); + if (fun.lambda.fun->formals->ellipsis) { + // If the formals have an ellipsis (eg the function accepts extra args) pass + // all available automatic arguments (which includes arguments specified on + // the command line via --arg/--argstr) + for (auto& v : args) { + actualArgs->attrs->push_back(v); + } + } else { + // Otherwise, only pass the arguments that the function accepts + for (auto & i : fun.lambda.fun->formals->formals) { + Bindings::iterator j = args.find(i.name); + if (j != args.end()) { + actualArgs->attrs->push_back(*j); + } else if (!i.def) { + throwTypeError("cannot auto-call a function that has an argument without a default value ('%1%')", i.name); + } + } } actualArgs->attrs->sort(); @@ -1586,6 +1675,18 @@ string EvalState::forceString(Value & v, const Pos & pos) } +/* Decode a context string ‘!!’ into a pair . */ +std::pair decodeContext(std::string_view s) +{ + if (s.at(0) == '!') { + size_t index = s.find("!", 1); + return {std::string(s.substr(index + 1)), std::string(s.substr(1, index - 1))}; + } else + return {s.at(0) == '/' ? std::string(s) : std::string(s.substr(1)), ""}; +} + + void copyContext(const Value & v, PathSet & context) { if (v.string.context) @@ -1594,6 +1695,17 @@ void copyContext(const Value & v, PathSet & context) } +std::vector> Value::getContext() +{ + std::vector> res; + assert(type == tString); + if (string.context) + for (const char * * p = string.context; *p; ++p) + res.push_back(decodeContext(*p)); + return res; +} + + string EvalState::forceString(Value & v, PathSet & context, const Pos & pos) { string s = forceString(v, pos); @@ -1969,7 +2081,7 @@ Strings EvalSettings::getDefaultNixPath() EvalSettings evalSettings; -static GlobalConfig::Register r1(&evalSettings); +static GlobalConfig::Register rEvalSettings(&evalSettings); } diff --git a/src/libexpr/eval.hh b/src/libexpr/eval.hh index 0d52a7f63..0e1f61baa 100644 --- a/src/libexpr/eval.hh +++ b/src/libexpr/eval.hh @@ -4,13 +4,12 @@ #include "value.hh" #include "nixexpr.hh" #include "symbol-table.hh" -#include "hash.hh" #include "config.hh" -#include #include #include #include +#include namespace nix { @@ -30,8 +29,8 @@ struct PrimOp PrimOpFun fun; size_t arity; Symbol name; - PrimOp(PrimOpFun fun, size_t arity, Symbol name) - : fun(fun), arity(arity), name(name) { } + std::vector args; + const char * doc = nullptr; }; @@ -65,6 +64,11 @@ typedef std::list SearchPath; void initGC(); +struct RegexCache; + +std::shared_ptr makeRegexCache(); + + class EvalState { public: @@ -74,8 +78,10 @@ public: sSystem, sOverrides, sOutputs, sOutputName, sIgnoreNulls, sFile, sLine, sColumn, sFunctor, sToString, sRight, sWrong, sStructuredAttrs, sBuilder, sArgs, + sContentAddressed, sOutputHash, sOutputHashAlgo, sOutputHashMode, - sRecurseForDerivations; + sRecurseForDerivations, + sDescription, sSelf, sEpsilon; Symbol sDerivationNix; /* If set, force copying files to the Nix store even if they @@ -90,6 +96,7 @@ public: const ref store; + private: SrcToStore srcToStore; @@ -117,7 +124,7 @@ private: std::unordered_map resolvedPaths; /* Cache used by prim_match(). */ - std::unordered_map regexCache; + std::shared_ptr regexCache; public: @@ -152,8 +159,9 @@ public: Expr * parseStdin(); /* Evaluate an expression read from the given file to normal - form. */ - void evalFile(const Path & path, Value & v); + form. Optionally enforce that the top-level expression is + trivial (i.e. doesn't require arbitrary computation). */ + void evalFile(const Path & path, Value & v, bool mustBeTrivial = false); void resetFileCache(); @@ -238,10 +246,23 @@ private: Value * addPrimOp(const string & name, size_t arity, PrimOpFun primOp); + Value * addPrimOp(PrimOp && primOp); + public: Value & getBuiltin(const string & name); + struct Doc + { + Pos pos; + std::optional name; + size_t arity; + std::vector args; + const char * doc; + }; + + std::optional getDoc(Value & v); + private: inline Value * lookupVar(Env * env, const ExprVar & var, bool noEval); @@ -330,7 +351,7 @@ string showType(const Value & v); /* Decode a context string ‘!!’ into a pair . */ -std::pair decodeContext(const string & s); +std::pair decodeContext(std::string_view s); /* If `path' refers to a directory, then append "/default.nix". */ Path resolveExprPath(Path path); @@ -353,24 +374,60 @@ struct EvalSettings : Config Setting enableNativeCode{this, false, "allow-unsafe-native-code-during-evaluation", "Whether builtin functions that allow executing native code should be enabled."}; - Setting nixPath{this, getDefaultNixPath(), "nix-path", - "List of directories to be searched for <...> file references."}; + Setting nixPath{ + this, getDefaultNixPath(), "nix-path", + "List of directories to be searched for `<...>` file references."}; - Setting restrictEval{this, false, "restrict-eval", - "Whether to restrict file system access to paths in $NIX_PATH, " - "and network access to the URI prefixes listed in 'allowed-uris'."}; + Setting restrictEval{ + this, false, "restrict-eval", + R"( + If set to `true`, the Nix evaluator will not allow access to any + files outside of the Nix search path (as set via the `NIX_PATH` + environment variable or the `-I` option), or to URIs outside of + `allowed-uri`. The default is `false`. + )"}; Setting pureEval{this, false, "pure-eval", "Whether to restrict file system and network access to files specified by cryptographic hash."}; - Setting enableImportFromDerivation{this, true, "allow-import-from-derivation", - "Whether the evaluator allows importing the result of a derivation."}; + Setting enableImportFromDerivation{ + this, true, "allow-import-from-derivation", + R"( + By default, Nix allows you to `import` from a derivation, allowing + building at evaluation time. With this option set to false, Nix will + throw an error when evaluating an expression that uses this feature, + allowing users to ensure their evaluation will not require any + builds to take place. + )"}; Setting allowedUris{this, {}, "allowed-uris", - "Prefixes of URIs that builtin functions such as fetchurl and fetchGit are allowed to fetch."}; + R"( + A list of URI prefixes to which access is allowed in restricted + evaluation mode. For example, when set to + `https://github.com/NixOS`, builtin functions such as `fetchGit` are + allowed to access `https://github.com/NixOS/patchelf.git`. + )"}; Setting traceFunctionCalls{this, false, "trace-function-calls", - "Emit log messages for each function entry and exit at the 'vomit' log level (-vvvv)."}; + R"( + If set to `true`, the Nix evaluator will trace every function call. + Nix will print a log message at the "vomit" level for every function + entrance and function exit. + + function-trace entered undefined position at 1565795816999559622 + function-trace exited undefined position at 1565795816999581277 + function-trace entered /nix/store/.../example.nix:226:41 at 1565795253249935150 + function-trace exited /nix/store/.../example.nix:226:41 at 1565795253249941684 + + The `undefined position` means the function call is a builtin. + + Use the `contrib/stack-collapse.py` script distributed with the Nix + source code to convert the trace logs in to a format suitable for + `flamegraph.pl`. + )"}; + + Setting useEvalCache{this, true, "eval-cache", + "Whether to use the flake evaluation cache."}; }; extern EvalSettings evalSettings; diff --git a/src/libexpr/flake/call-flake.nix b/src/libexpr/flake/call-flake.nix new file mode 100644 index 000000000..932ac5e90 --- /dev/null +++ b/src/libexpr/flake/call-flake.nix @@ -0,0 +1,56 @@ +lockFileStr: rootSrc: rootSubdir: + +let + + lockFile = builtins.fromJSON lockFileStr; + + allNodes = + builtins.mapAttrs + (key: node: + let + + sourceInfo = + if key == lockFile.root + then rootSrc + else fetchTree (node.info or {} // removeAttrs node.locked ["dir"]); + + subdir = if key == lockFile.root then rootSubdir else node.locked.dir or ""; + + flake = import (sourceInfo + (if subdir != "" then "/" else "") + subdir + "/flake.nix"); + + inputs = builtins.mapAttrs + (inputName: inputSpec: allNodes.${resolveInput inputSpec}) + (node.inputs or {}); + + # Resolve a input spec into a node name. An input spec is + # either a node name, or a 'follows' path from the root + # node. + resolveInput = inputSpec: + if builtins.isList inputSpec + then getInputByPath lockFile.root inputSpec + else inputSpec; + + # Follow an input path (e.g. ["dwarffs" "nixpkgs"]) from the + # root node, returning the final node. + getInputByPath = nodeName: path: + if path == [] + then nodeName + else + getInputByPath + # Since this could be a 'follows' input, call resolveInput. + (resolveInput lockFile.nodes.${nodeName}.inputs.${builtins.head path}) + (builtins.tail path); + + outputs = flake.outputs (inputs // { self = result; }); + + result = outputs // sourceInfo // { inherit inputs; inherit outputs; inherit sourceInfo; }; + in + if node.flake or true then + assert builtins.isFunction flake.outputs; + result + else + sourceInfo + ) + lockFile.nodes; + +in allNodes.${lockFile.root} diff --git a/src/libexpr/flake/flake.cc b/src/libexpr/flake/flake.cc new file mode 100644 index 000000000..bae4d65e5 --- /dev/null +++ b/src/libexpr/flake/flake.cc @@ -0,0 +1,608 @@ +#include "flake.hh" +#include "lockfile.hh" +#include "primops.hh" +#include "eval-inline.hh" +#include "store-api.hh" +#include "fetchers.hh" +#include "finally.hh" + +namespace nix { + +using namespace flake; + +namespace flake { + +typedef std::pair FetchedFlake; +typedef std::vector> FlakeCache; + +static std::optional lookupInFlakeCache( + const FlakeCache & flakeCache, + const FlakeRef & flakeRef) +{ + // FIXME: inefficient. + for (auto & i : flakeCache) { + if (flakeRef == i.first) { + debug("mapping '%s' to previously seen input '%s' -> '%s", + flakeRef, i.first, i.second.second); + return i.second; + } + } + + return std::nullopt; +} + +static std::tuple fetchOrSubstituteTree( + EvalState & state, + const FlakeRef & originalRef, + bool allowLookup, + FlakeCache & flakeCache) +{ + auto fetched = lookupInFlakeCache(flakeCache, originalRef); + FlakeRef resolvedRef = originalRef; + + if (!fetched) { + if (originalRef.input.isDirect()) { + fetched.emplace(originalRef.fetchTree(state.store)); + } else { + if (allowLookup) { + resolvedRef = originalRef.resolve(state.store); + auto fetchedResolved = lookupInFlakeCache(flakeCache, originalRef); + if (!fetchedResolved) fetchedResolved.emplace(resolvedRef.fetchTree(state.store)); + flakeCache.push_back({resolvedRef, *fetchedResolved}); + fetched.emplace(*fetchedResolved); + } + else { + throw Error("'%s' is an indirect flake reference, but registry lookups are not allowed", originalRef); + } + } + flakeCache.push_back({originalRef, *fetched}); + } + + auto [tree, lockedRef] = *fetched; + + debug("got tree '%s' from '%s'", + state.store->printStorePath(tree.storePath), lockedRef); + + if (state.allowedPaths) + state.allowedPaths->insert(tree.actualPath); + + assert(!originalRef.input.getNarHash() || tree.storePath == originalRef.input.computeStorePath(*state.store)); + + return {std::move(tree), resolvedRef, lockedRef}; +} + +static void expectType(EvalState & state, ValueType type, + Value & value, const Pos & pos) +{ + if (value.type == tThunk && value.isTrivial()) + state.forceValue(value, pos); + if (value.type != type) + throw Error("expected %s but got %s at %s", + showType(type), showType(value.type), pos); +} + +static std::map parseFlakeInputs( + EvalState & state, Value * value, const Pos & pos); + +static FlakeInput parseFlakeInput(EvalState & state, + const std::string & inputName, Value * value, const Pos & pos) +{ + expectType(state, tAttrs, *value, pos); + + FlakeInput input; + + auto sInputs = state.symbols.create("inputs"); + auto sUrl = state.symbols.create("url"); + auto sFlake = state.symbols.create("flake"); + auto sFollows = state.symbols.create("follows"); + + fetchers::Attrs attrs; + std::optional url; + + for (nix::Attr attr : *(value->attrs)) { + try { + if (attr.name == sUrl) { + expectType(state, tString, *attr.value, *attr.pos); + url = attr.value->string.s; + attrs.emplace("url", *url); + } else if (attr.name == sFlake) { + expectType(state, tBool, *attr.value, *attr.pos); + input.isFlake = attr.value->boolean; + } else if (attr.name == sInputs) { + input.overrides = parseFlakeInputs(state, attr.value, *attr.pos); + } else if (attr.name == sFollows) { + expectType(state, tString, *attr.value, *attr.pos); + input.follows = parseInputPath(attr.value->string.s); + } else { + state.forceValue(*attr.value); + if (attr.value->type == tString) + attrs.emplace(attr.name, attr.value->string.s); + else + throw TypeError("flake input attribute '%s' is %s while a string is expected", + attr.name, showType(*attr.value)); + } + } catch (Error & e) { + e.addTrace(*attr.pos, hintfmt("in flake attribute '%s'", attr.name)); + throw; + } + } + + if (attrs.count("type")) + try { + input.ref = FlakeRef::fromAttrs(attrs); + } catch (Error & e) { + e.addTrace(pos, hintfmt("in flake input")); + throw; + } + else { + attrs.erase("url"); + if (!attrs.empty()) + throw Error("unexpected flake input attribute '%s', at %s", attrs.begin()->first, pos); + if (url) + input.ref = parseFlakeRef(*url, {}, true); + } + + if (!input.follows && !input.ref) + input.ref = FlakeRef::fromAttrs({{"type", "indirect"}, {"id", inputName}}); + + return input; +} + +static std::map parseFlakeInputs( + EvalState & state, Value * value, const Pos & pos) +{ + std::map inputs; + + expectType(state, tAttrs, *value, pos); + + for (nix::Attr & inputAttr : *(*value).attrs) { + inputs.emplace(inputAttr.name, + parseFlakeInput(state, + inputAttr.name, + inputAttr.value, + *inputAttr.pos)); + } + + return inputs; +} + +static Flake getFlake( + EvalState & state, + const FlakeRef & originalRef, + bool allowLookup, + FlakeCache & flakeCache) +{ + auto [sourceInfo, resolvedRef, lockedRef] = fetchOrSubstituteTree( + state, originalRef, allowLookup, flakeCache); + + // Guard against symlink attacks. + auto flakeFile = canonPath(sourceInfo.actualPath + "/" + lockedRef.subdir + "/flake.nix"); + if (!isInDir(flakeFile, sourceInfo.actualPath)) + throw Error("'flake.nix' file of flake '%s' escapes from '%s'", + lockedRef, state.store->printStorePath(sourceInfo.storePath)); + + Flake flake { + .originalRef = originalRef, + .resolvedRef = resolvedRef, + .lockedRef = lockedRef, + .sourceInfo = std::make_shared(std::move(sourceInfo)) + }; + + if (!pathExists(flakeFile)) + throw Error("source tree referenced by '%s' does not contain a '%s/flake.nix' file", lockedRef, lockedRef.subdir); + + Value vInfo; + state.evalFile(flakeFile, vInfo, true); // FIXME: symlink attack + + expectType(state, tAttrs, vInfo, Pos(foFile, state.symbols.create(flakeFile), 0, 0)); + + auto sEdition = state.symbols.create("edition"); // FIXME: remove soon + + if (vInfo.attrs->get(sEdition)) + warn("flake '%s' has deprecated attribute 'edition'", lockedRef); + + if (auto description = vInfo.attrs->get(state.sDescription)) { + expectType(state, tString, *description->value, *description->pos); + flake.description = description->value->string.s; + } + + auto sInputs = state.symbols.create("inputs"); + + if (auto inputs = vInfo.attrs->get(sInputs)) + flake.inputs = parseFlakeInputs(state, inputs->value, *inputs->pos); + + auto sOutputs = state.symbols.create("outputs"); + + if (auto outputs = vInfo.attrs->get(sOutputs)) { + expectType(state, tLambda, *outputs->value, *outputs->pos); + + if (outputs->value->lambda.fun->matchAttrs) { + for (auto & formal : outputs->value->lambda.fun->formals->formals) { + if (formal.name != state.sSelf) + flake.inputs.emplace(formal.name, FlakeInput { + .ref = parseFlakeRef(formal.name) + }); + } + } + + } else + throw Error("flake '%s' lacks attribute 'outputs'", lockedRef); + + for (auto & attr : *vInfo.attrs) { + if (attr.name != sEdition && + attr.name != state.sDescription && + attr.name != sInputs && + attr.name != sOutputs) + throw Error("flake '%s' has an unsupported attribute '%s', at %s", + lockedRef, attr.name, *attr.pos); + } + + return flake; +} + +Flake getFlake(EvalState & state, const FlakeRef & originalRef, bool allowLookup) +{ + FlakeCache flakeCache; + return getFlake(state, originalRef, allowLookup, flakeCache); +} + +/* Compute an in-memory lock file for the specified top-level flake, + and optionally write it to file, if the flake is writable. */ +LockedFlake lockFlake( + EvalState & state, + const FlakeRef & topRef, + const LockFlags & lockFlags) +{ + settings.requireExperimentalFeature("flakes"); + + FlakeCache flakeCache; + + auto flake = getFlake(state, topRef, lockFlags.useRegistries, flakeCache); + + // FIXME: symlink attack + auto oldLockFile = LockFile::read( + flake.sourceInfo->actualPath + "/" + flake.lockedRef.subdir + "/flake.lock"); + + debug("old lock file: %s", oldLockFile); + + // FIXME: check whether all overrides are used. + std::map overrides; + std::set overridesUsed, updatesUsed; + + for (auto & i : lockFlags.inputOverrides) + overrides.insert_or_assign(i.first, FlakeInput { .ref = i.second }); + + LockFile newLockFile; + + std::vector parents; + + std::function node, + const InputPath & inputPathPrefix, + std::shared_ptr oldNode)> + computeLocks; + + computeLocks = [&]( + const FlakeInputs & flakeInputs, + std::shared_ptr node, + const InputPath & inputPathPrefix, + std::shared_ptr oldNode) + { + debug("computing lock file node '%s'", printInputPath(inputPathPrefix)); + + /* Get the overrides (i.e. attributes of the form + 'inputs.nixops.inputs.nixpkgs.url = ...'). */ + // FIXME: check this + for (auto & [id, input] : flake.inputs) { + for (auto & [idOverride, inputOverride] : input.overrides) { + auto inputPath(inputPathPrefix); + inputPath.push_back(id); + inputPath.push_back(idOverride); + overrides.insert_or_assign(inputPath, inputOverride); + } + } + + /* Go over the flake inputs, resolve/fetch them if + necessary (i.e. if they're new or the flakeref changed + from what's in the lock file). */ + for (auto & [id, input2] : flakeInputs) { + auto inputPath(inputPathPrefix); + inputPath.push_back(id); + auto inputPathS = printInputPath(inputPath); + debug("computing input '%s'", inputPathS); + + /* Do we have an override for this input from one of the + ancestors? */ + auto i = overrides.find(inputPath); + bool hasOverride = i != overrides.end(); + if (hasOverride) overridesUsed.insert(inputPath); + auto & input = hasOverride ? i->second : input2; + + /* Resolve 'follows' later (since it may refer to an input + path we haven't processed yet. */ + if (input.follows) { + InputPath target; + if (hasOverride || input.absolute) + /* 'follows' from an override is relative to the + root of the graph. */ + target = *input.follows; + else { + /* Otherwise, it's relative to the current flake. */ + target = inputPathPrefix; + for (auto & i : *input.follows) target.push_back(i); + } + debug("input '%s' follows '%s'", inputPathS, printInputPath(target)); + node->inputs.insert_or_assign(id, target); + continue; + } + + assert(input.ref); + + /* Do we have an entry in the existing lock file? And we + don't have a --update-input flag for this input? */ + std::shared_ptr oldLock; + + updatesUsed.insert(inputPath); + + if (oldNode && !lockFlags.inputUpdates.count(inputPath)) + if (auto oldLock2 = get(oldNode->inputs, id)) + if (auto oldLock3 = std::get_if<0>(&*oldLock2)) + oldLock = *oldLock3; + + if (oldLock + && oldLock->originalRef == *input.ref + && !hasOverride) + { + debug("keeping existing input '%s'", inputPathS); + + /* Copy the input from the old lock since its flakeref + didn't change and there is no override from a + higher level flake. */ + auto childNode = std::make_shared( + oldLock->lockedRef, oldLock->originalRef, oldLock->isFlake); + + node->inputs.insert_or_assign(id, childNode); + + /* If we have an --update-input flag for an input + of this input, then we must fetch the flake to + update it. */ + auto lb = lockFlags.inputUpdates.lower_bound(inputPath); + + auto hasChildUpdate = + lb != lockFlags.inputUpdates.end() + && lb->size() > inputPath.size() + && std::equal(inputPath.begin(), inputPath.end(), lb->begin()); + + if (hasChildUpdate) { + auto inputFlake = getFlake( + state, oldLock->lockedRef, false, flakeCache); + computeLocks(inputFlake.inputs, childNode, inputPath, oldLock); + } else { + /* No need to fetch this flake, we can be + lazy. However there may be new overrides on the + inputs of this flake, so we need to check + those. */ + FlakeInputs fakeInputs; + + for (auto & i : oldLock->inputs) { + if (auto lockedNode = std::get_if<0>(&i.second)) { + fakeInputs.emplace(i.first, FlakeInput { + .ref = (*lockedNode)->originalRef, + .isFlake = (*lockedNode)->isFlake, + }); + } else if (auto follows = std::get_if<1>(&i.second)) { + fakeInputs.emplace(i.first, FlakeInput { + .follows = *follows, + .absolute = true + }); + } + } + + computeLocks(fakeInputs, childNode, inputPath, oldLock); + } + + } else { + /* We need to create a new lock file entry. So fetch + this input. */ + debug("creating new input '%s'", inputPathS); + + if (!lockFlags.allowMutable && !input.ref->input.isImmutable()) + throw Error("cannot update flake input '%s' in pure mode", inputPathS); + + if (input.isFlake) { + auto inputFlake = getFlake(state, *input.ref, lockFlags.useRegistries, flakeCache); + + /* Note: in case of an --override-input, we use + the *original* ref (input2.ref) for the + "original" field, rather than the + override. This ensures that the override isn't + nuked the next time we update the lock + file. That is, overrides are sticky unless you + use --no-write-lock-file. */ + auto childNode = std::make_shared( + inputFlake.lockedRef, input2.ref ? *input2.ref : *input.ref); + + node->inputs.insert_or_assign(id, childNode); + + /* Guard against circular flake imports. */ + for (auto & parent : parents) + if (parent == *input.ref) + throw Error("found circular import of flake '%s'", parent); + parents.push_back(*input.ref); + Finally cleanup([&]() { parents.pop_back(); }); + + /* Recursively process the inputs of this + flake. Also, unless we already have this flake + in the top-level lock file, use this flake's + own lock file. */ + computeLocks( + inputFlake.inputs, childNode, inputPath, + oldLock + ? std::dynamic_pointer_cast(oldLock) + : LockFile::read( + inputFlake.sourceInfo->actualPath + "/" + inputFlake.lockedRef.subdir + "/flake.lock").root); + } + + else { + auto [sourceInfo, resolvedRef, lockedRef] = fetchOrSubstituteTree( + state, *input.ref, lockFlags.useRegistries, flakeCache); + node->inputs.insert_or_assign(id, + std::make_shared(lockedRef, *input.ref, false)); + } + } + } + }; + + computeLocks( + flake.inputs, newLockFile.root, {}, + lockFlags.recreateLockFile ? nullptr : oldLockFile.root); + + for (auto & i : lockFlags.inputOverrides) + if (!overridesUsed.count(i.first)) + warn("the flag '--override-input %s %s' does not match any input", + printInputPath(i.first), i.second); + + for (auto & i : lockFlags.inputUpdates) + if (!updatesUsed.count(i)) + warn("the flag '--update-input %s' does not match any input", printInputPath(i)); + + /* Check 'follows' inputs. */ + newLockFile.check(); + + debug("new lock file: %s", newLockFile); + + /* Check whether we need to / can write the new lock file. */ + if (!(newLockFile == oldLockFile)) { + + auto diff = LockFile::diff(oldLockFile, newLockFile); + + if (lockFlags.writeLockFile) { + if (auto sourcePath = topRef.input.getSourcePath()) { + if (!newLockFile.isImmutable()) { + if (settings.warnDirty) + warn("will not write lock file of flake '%s' because it has a mutable input", topRef); + } else { + if (!lockFlags.updateLockFile) + throw Error("flake '%s' requires lock file changes but they're not allowed due to '--no-update-lock-file'", topRef); + + auto relPath = (topRef.subdir == "" ? "" : topRef.subdir + "/") + "flake.lock"; + + auto path = *sourcePath + "/" + relPath; + + bool lockFileExists = pathExists(path); + + if (lockFileExists) { + auto s = chomp(diff); + if (s.empty()) + warn("updating lock file '%s'", path); + else + warn("updating lock file '%s':\n%s", path, s); + } else + warn("creating lock file '%s'", path); + + newLockFile.write(path); + + topRef.input.markChangedFile( + (topRef.subdir == "" ? "" : topRef.subdir + "/") + "flake.lock", + lockFlags.commitLockFile + ? std::optional(fmt("%s: %s\n\nFlake input changes:\n\n%s", + relPath, lockFileExists ? "Update" : "Add", diff)) + : std::nullopt); + + /* Rewriting the lockfile changed the top-level + repo, so we should re-read it. FIXME: we could + also just clear the 'rev' field... */ + auto prevLockedRef = flake.lockedRef; + FlakeCache dummyCache; + flake = getFlake(state, topRef, lockFlags.useRegistries, dummyCache); + + if (lockFlags.commitLockFile && + flake.lockedRef.input.getRev() && + prevLockedRef.input.getRev() != flake.lockedRef.input.getRev()) + warn("committed new revision '%s'", flake.lockedRef.input.getRev()->gitRev()); + + /* Make sure that we picked up the change, + i.e. the tree should usually be dirty + now. Corner case: we could have reverted from a + dirty to a clean tree! */ + if (flake.lockedRef.input == prevLockedRef.input + && !flake.lockedRef.input.isImmutable()) + throw Error("'%s' did not change after I updated its 'flake.lock' file; is 'flake.lock' under version control?", flake.originalRef); + } + } else + throw Error("cannot write modified lock file of flake '%s' (use '--no-write-lock-file' to ignore)", topRef); + } else + warn("not writing modified lock file of flake '%s':\n%s", topRef, chomp(diff)); + } + + return LockedFlake { .flake = std::move(flake), .lockFile = std::move(newLockFile) }; +} + +void callFlake(EvalState & state, + const LockedFlake & lockedFlake, + Value & vRes) +{ + auto vLocks = state.allocValue(); + auto vRootSrc = state.allocValue(); + auto vRootSubdir = state.allocValue(); + auto vTmp1 = state.allocValue(); + auto vTmp2 = state.allocValue(); + + mkString(*vLocks, lockedFlake.lockFile.to_string()); + + emitTreeAttrs(state, *lockedFlake.flake.sourceInfo, lockedFlake.flake.lockedRef.input, *vRootSrc); + + mkString(*vRootSubdir, lockedFlake.flake.lockedRef.subdir); + + static RootValue vCallFlake = nullptr; + + if (!vCallFlake) { + vCallFlake = allocRootValue(state.allocValue()); + state.eval(state.parseExprFromString( + #include "call-flake.nix.gen.hh" + , "/"), **vCallFlake); + } + + state.callFunction(**vCallFlake, *vLocks, *vTmp1, noPos); + state.callFunction(*vTmp1, *vRootSrc, *vTmp2, noPos); + state.callFunction(*vTmp2, *vRootSubdir, vRes, noPos); +} + +static void prim_getFlake(EvalState & state, const Pos & pos, Value * * args, Value & v) +{ + auto flakeRefS = state.forceStringNoCtx(*args[0], pos); + auto flakeRef = parseFlakeRef(flakeRefS, {}, true); + if (evalSettings.pureEval && !flakeRef.input.isImmutable()) + throw Error("cannot call 'getFlake' on mutable flake reference '%s', at %s (use --impure to override)", flakeRefS, pos); + + callFlake(state, + lockFlake(state, flakeRef, + LockFlags { + .updateLockFile = false, + .useRegistries = !evalSettings.pureEval, + .allowMutable = !evalSettings.pureEval, + }), + v); +} + +static RegisterPrimOp r2("__getFlake", 1, prim_getFlake, "flakes"); + +} + +Fingerprint LockedFlake::getFingerprint() const +{ + // FIXME: as an optimization, if the flake contains a lock file + // and we haven't changed it, then it's sufficient to use + // flake.sourceInfo.storePath for the fingerprint. + return hashString(htSHA256, + fmt("%s;%d;%d;%s", + flake.sourceInfo->storePath.to_string(), + flake.lockedRef.input.getRevCount().value_or(0), + flake.lockedRef.input.getLastModified().value_or(0), + lockFile)); +} + +Flake::~Flake() { } + +} diff --git a/src/libexpr/flake/flake.hh b/src/libexpr/flake/flake.hh new file mode 100644 index 000000000..69c779af8 --- /dev/null +++ b/src/libexpr/flake/flake.hh @@ -0,0 +1,110 @@ +#pragma once + +#include "types.hh" +#include "flakeref.hh" +#include "lockfile.hh" +#include "value.hh" + +namespace nix { + +class EvalState; + +namespace fetchers { struct Tree; } + +namespace flake { + +struct FlakeInput; + +typedef std::map FlakeInputs; + +struct FlakeInput +{ + std::optional ref; + bool isFlake = true; + std::optional follows; + bool absolute = false; // whether 'follows' is relative to the flake root + FlakeInputs overrides; +}; + +struct Flake +{ + FlakeRef originalRef; + FlakeRef resolvedRef; + FlakeRef lockedRef; + std::optional description; + std::shared_ptr sourceInfo; + FlakeInputs inputs; + ~Flake(); +}; + +Flake getFlake(EvalState & state, const FlakeRef & flakeRef, bool allowLookup); + +/* Fingerprint of a locked flake; used as a cache key. */ +typedef Hash Fingerprint; + +struct LockedFlake +{ + Flake flake; + LockFile lockFile; + + Fingerprint getFingerprint() const; +}; + +struct LockFlags +{ + /* Whether to ignore the existing lock file, creating a new one + from scratch. */ + bool recreateLockFile = false; + + /* Whether to update the lock file at all. If set to false, if any + change to the lock file is needed (e.g. when an input has been + added to flake.nix), you get a fatal error. */ + bool updateLockFile = true; + + /* Whether to write the lock file to disk. If set to true, if the + any changes to the lock file are needed and the flake is not + writable (i.e. is not a local Git working tree or similar), you + get a fatal error. If set to false, Nix will use the modified + lock file in memory only, without writing it to disk. */ + bool writeLockFile = true; + + /* Whether to use the registries to lookup indirect flake + references like 'nixpkgs'. */ + bool useRegistries = true; + + /* Whether mutable flake references (i.e. those without a Git + revision or similar) without a corresponding lock are + allowed. Mutable flake references with a lock are always + allowed. */ + bool allowMutable = true; + + /* Whether to commit changes to flake.lock. */ + bool commitLockFile = false; + + /* Flake inputs to be overriden. */ + std::map inputOverrides; + + /* Flake inputs to be updated. This means that any existing lock + for those inputs will be ignored. */ + std::set inputUpdates; +}; + +LockedFlake lockFlake( + EvalState & state, + const FlakeRef & flakeRef, + const LockFlags & lockFlags); + +void callFlake( + EvalState & state, + const LockedFlake & lockedFlake, + Value & v); + +} + +void emitTreeAttrs( + EvalState & state, + const fetchers::Tree & tree, + const fetchers::Input & input, + Value & v, bool emptyRevFallback = false); + +} diff --git a/src/libexpr/flake/flakeref.cc b/src/libexpr/flake/flakeref.cc new file mode 100644 index 000000000..833e8a776 --- /dev/null +++ b/src/libexpr/flake/flakeref.cc @@ -0,0 +1,206 @@ +#include "flakeref.hh" +#include "store-api.hh" +#include "url.hh" +#include "url-parts.hh" +#include "fetchers.hh" +#include "registry.hh" + +namespace nix { + +#if 0 +// 'dir' path elements cannot start with a '.'. We also reject +// potentially dangerous characters like ';'. +const static std::string subDirElemRegex = "(?:[a-zA-Z0-9_-]+[a-zA-Z0-9._-]*)"; +const static std::string subDirRegex = subDirElemRegex + "(?:/" + subDirElemRegex + ")*"; +#endif + +std::string FlakeRef::to_string() const +{ + std::map extraQuery; + if (subdir != "") + extraQuery.insert_or_assign("dir", subdir); + return input.toURLString(extraQuery); +} + +fetchers::Attrs FlakeRef::toAttrs() const +{ + auto attrs = input.toAttrs(); + if (subdir != "") + attrs.emplace("dir", subdir); + return attrs; +} + +std::ostream & operator << (std::ostream & str, const FlakeRef & flakeRef) +{ + str << flakeRef.to_string(); + return str; +} + +bool FlakeRef::operator ==(const FlakeRef & other) const +{ + return input == other.input && subdir == other.subdir; +} + +FlakeRef FlakeRef::resolve(ref store) const +{ + auto [input2, extraAttrs] = lookupInRegistries(store, input); + return FlakeRef(std::move(input2), fetchers::maybeGetStrAttr(extraAttrs, "dir").value_or(subdir)); +} + +FlakeRef parseFlakeRef( + const std::string & url, const std::optional & baseDir, bool allowMissing) +{ + auto [flakeRef, fragment] = parseFlakeRefWithFragment(url, baseDir, allowMissing); + if (fragment != "") + throw Error("unexpected fragment '%s' in flake reference '%s'", fragment, url); + return flakeRef; +} + +std::optional maybeParseFlakeRef( + const std::string & url, const std::optional & baseDir) +{ + try { + return parseFlakeRef(url, baseDir); + } catch (Error &) { + return {}; + } +} + +std::pair parseFlakeRefWithFragment( + const std::string & url, const std::optional & baseDir, bool allowMissing) +{ + using namespace fetchers; + + static std::string fnRegex = "[0-9a-zA-Z-._~!$&'\"()*+,;=]+"; + + static std::regex pathUrlRegex( + "(/?" + fnRegex + "(?:/" + fnRegex + ")*/?)" + + "(?:\\?(" + queryRegex + "))?" + + "(?:#(" + queryRegex + "))?", + std::regex::ECMAScript); + + static std::regex flakeRegex( + "((" + flakeIdRegexS + ")(?:/(?:" + refAndOrRevRegex + "))?)" + + "(?:#(" + queryRegex + "))?", + std::regex::ECMAScript); + + std::smatch match; + + /* Check if 'url' is a flake ID. This is an abbreviated syntax for + 'flake:?ref=&rev='. */ + + if (std::regex_match(url, match, flakeRegex)) { + auto parsedURL = ParsedURL{ + .url = url, + .base = "flake:" + std::string(match[1]), + .scheme = "flake", + .authority = "", + .path = match[1], + }; + + return std::make_pair( + FlakeRef(Input::fromURL(parsedURL), ""), + percentDecode(std::string(match[6]))); + } + + else if (std::regex_match(url, match, pathUrlRegex)) { + std::string path = match[1]; + std::string fragment = percentDecode(std::string(match[3])); + + if (baseDir) { + /* Check if 'url' is a path (either absolute or relative + to 'baseDir'). If so, search upward to the root of the + repo (i.e. the directory containing .git). */ + + path = absPath(path, baseDir, true); + + if (!S_ISDIR(lstat(path).st_mode)) + throw BadURL("path '%s' is not a flake (because it's not a directory)", path); + + if (!allowMissing && !pathExists(path + "/flake.nix")) + throw BadURL("path '%s' is not a flake (because it doesn't contain a 'flake.nix' file)", path); + + auto flakeRoot = path; + std::string subdir; + + while (flakeRoot != "/") { + if (pathExists(flakeRoot + "/.git")) { + auto base = std::string("git+file://") + flakeRoot; + + auto parsedURL = ParsedURL{ + .url = base, // FIXME + .base = base, + .scheme = "git+file", + .authority = "", + .path = flakeRoot, + .query = decodeQuery(match[2]), + }; + + if (subdir != "") { + if (parsedURL.query.count("dir")) + throw Error("flake URL '%s' has an inconsistent 'dir' parameter", url); + parsedURL.query.insert_or_assign("dir", subdir); + } + + if (pathExists(flakeRoot + "/.git/shallow")) + parsedURL.query.insert_or_assign("shallow", "1"); + + return std::make_pair( + FlakeRef(Input::fromURL(parsedURL), get(parsedURL.query, "dir").value_or("")), + fragment); + } + + subdir = std::string(baseNameOf(flakeRoot)) + (subdir.empty() ? "" : "/" + subdir); + flakeRoot = dirOf(flakeRoot); + } + + } else { + if (!hasPrefix(path, "/")) + throw BadURL("flake reference '%s' is not an absolute path", url); + auto query = decodeQuery(match[2]); + path = canonPath(path + "/" + get(query, "dir").value_or("")); + } + + fetchers::Attrs attrs; + attrs.insert_or_assign("type", "path"); + attrs.insert_or_assign("path", path); + + return std::make_pair(FlakeRef(Input::fromAttrs(std::move(attrs)), ""), fragment); + } + + else { + auto parsedURL = parseURL(url); + std::string fragment; + std::swap(fragment, parsedURL.fragment); + return std::make_pair( + FlakeRef(Input::fromURL(parsedURL), get(parsedURL.query, "dir").value_or("")), + fragment); + } +} + +std::optional> maybeParseFlakeRefWithFragment( + const std::string & url, const std::optional & baseDir) +{ + try { + return parseFlakeRefWithFragment(url, baseDir); + } catch (Error & e) { + return {}; + } +} + +FlakeRef FlakeRef::fromAttrs(const fetchers::Attrs & attrs) +{ + auto attrs2(attrs); + attrs2.erase("dir"); + return FlakeRef( + fetchers::Input::fromAttrs(std::move(attrs2)), + fetchers::maybeGetStrAttr(attrs, "dir").value_or("")); +} + +std::pair FlakeRef::fetchTree(ref store) const +{ + auto [tree, lockedInput] = input.fetch(store); + return {std::move(tree), FlakeRef(std::move(lockedInput), subdir)}; +} + +} diff --git a/src/libexpr/flake/flakeref.hh b/src/libexpr/flake/flakeref.hh new file mode 100644 index 000000000..f4eb825a6 --- /dev/null +++ b/src/libexpr/flake/flakeref.hh @@ -0,0 +1,53 @@ +#pragma once + +#include "types.hh" +#include "hash.hh" +#include "fetchers.hh" + +#include + +namespace nix { + +class Store; + +typedef std::string FlakeId; + +struct FlakeRef +{ + fetchers::Input input; + + Path subdir; + + bool operator==(const FlakeRef & other) const; + + FlakeRef(fetchers::Input && input, const Path & subdir) + : input(std::move(input)), subdir(subdir) + { } + + // FIXME: change to operator <<. + std::string to_string() const; + + fetchers::Attrs toAttrs() const; + + FlakeRef resolve(ref store) const; + + static FlakeRef fromAttrs(const fetchers::Attrs & attrs); + + std::pair fetchTree(ref store) const; +}; + +std::ostream & operator << (std::ostream & str, const FlakeRef & flakeRef); + +FlakeRef parseFlakeRef( + const std::string & url, const std::optional & baseDir = {}, bool allowMissing = false); + +std::optional maybeParseFlake( + const std::string & url, const std::optional & baseDir = {}); + +std::pair parseFlakeRefWithFragment( + const std::string & url, const std::optional & baseDir = {}, bool allowMissing = false); + +std::optional> maybeParseFlakeRefWithFragment( + const std::string & url, const std::optional & baseDir = {}); + +} diff --git a/src/libexpr/flake/lockfile.cc b/src/libexpr/flake/lockfile.cc new file mode 100644 index 000000000..bb46e1bb4 --- /dev/null +++ b/src/libexpr/flake/lockfile.cc @@ -0,0 +1,339 @@ +#include "lockfile.hh" +#include "store-api.hh" +#include "url-parts.hh" + +#include + +namespace nix::flake { + +FlakeRef getFlakeRef( + const nlohmann::json & json, + const char * attr, + const char * info) +{ + auto i = json.find(attr); + if (i != json.end()) { + auto attrs = fetchers::jsonToAttrs(*i); + // FIXME: remove when we drop support for version 5. + if (info) { + auto j = json.find(info); + if (j != json.end()) { + for (auto k : fetchers::jsonToAttrs(*j)) + attrs.insert_or_assign(k.first, k.second); + } + } + return FlakeRef::fromAttrs(attrs); + } + + throw Error("attribute '%s' missing in lock file", attr); +} + +LockedNode::LockedNode(const nlohmann::json & json) + : lockedRef(getFlakeRef(json, "locked", "info")) + , originalRef(getFlakeRef(json, "original", nullptr)) + , isFlake(json.find("flake") != json.end() ? (bool) json["flake"] : true) +{ + if (!lockedRef.input.isImmutable()) + throw Error("lockfile contains mutable lock '%s'", attrsToJson(lockedRef.input.toAttrs())); +} + +StorePath LockedNode::computeStorePath(Store & store) const +{ + return lockedRef.input.computeStorePath(store); +} + +std::shared_ptr LockFile::findInput(const InputPath & path) +{ + auto pos = root; + + if (!pos) return {}; + + for (auto & elem : path) { + if (auto i = get(pos->inputs, elem)) { + if (auto node = std::get_if<0>(&*i)) + pos = *node; + else if (auto follows = std::get_if<1>(&*i)) { + pos = findInput(*follows); + if (!pos) return {}; + } + } else + return {}; + } + + return pos; +} + +LockFile::LockFile(const nlohmann::json & json, const Path & path) +{ + auto version = json.value("version", 0); + if (version < 5 || version > 7) + throw Error("lock file '%s' has unsupported version %d", path, version); + + std::unordered_map> nodeMap; + + std::function getInputs; + + getInputs = [&](Node & node, const nlohmann::json & jsonNode) + { + if (jsonNode.find("inputs") == jsonNode.end()) return; + for (auto & i : jsonNode["inputs"].items()) { + if (i.value().is_array()) { + InputPath path; + for (auto & j : i.value()) + path.push_back(j); + node.inputs.insert_or_assign(i.key(), path); + } else { + std::string inputKey = i.value(); + auto k = nodeMap.find(inputKey); + if (k == nodeMap.end()) { + auto jsonNode2 = json["nodes"][inputKey]; + auto input = std::make_shared(jsonNode2); + k = nodeMap.insert_or_assign(inputKey, input).first; + getInputs(*input, jsonNode2); + } + if (auto child = std::dynamic_pointer_cast(k->second)) + node.inputs.insert_or_assign(i.key(), child); + else + // FIXME: replace by follows node + throw Error("lock file contains cycle to root node"); + } + } + }; + + std::string rootKey = json["root"]; + nodeMap.insert_or_assign(rootKey, root); + getInputs(*root, json["nodes"][rootKey]); + + // FIXME: check that there are no cycles in version >= 7. Cycles + // between inputs are only possible using 'follows' indirections. + // Once we drop support for version <= 6, we can simplify the code + // a bit since we don't need to worry about cycles. +} + +nlohmann::json LockFile::toJson() const +{ + nlohmann::json nodes; + std::unordered_map, std::string> nodeKeys; + std::unordered_set keys; + + std::function node)> dumpNode; + + dumpNode = [&](std::string key, std::shared_ptr node) -> std::string + { + auto k = nodeKeys.find(node); + if (k != nodeKeys.end()) + return k->second; + + if (!keys.insert(key).second) { + for (int n = 2; ; ++n) { + auto k = fmt("%s_%d", key, n); + if (keys.insert(k).second) { + key = k; + break; + } + } + } + + nodeKeys.insert_or_assign(node, key); + + auto n = nlohmann::json::object(); + + if (!node->inputs.empty()) { + auto inputs = nlohmann::json::object(); + for (auto & i : node->inputs) { + if (auto child = std::get_if<0>(&i.second)) { + inputs[i.first] = dumpNode(i.first, *child); + } else if (auto follows = std::get_if<1>(&i.second)) { + auto arr = nlohmann::json::array(); + for (auto & x : *follows) + arr.push_back(x); + inputs[i.first] = std::move(arr); + } + } + n["inputs"] = std::move(inputs); + } + + if (auto lockedNode = std::dynamic_pointer_cast(node)) { + n["original"] = fetchers::attrsToJson(lockedNode->originalRef.toAttrs()); + n["locked"] = fetchers::attrsToJson(lockedNode->lockedRef.toAttrs()); + if (!lockedNode->isFlake) n["flake"] = false; + } + + nodes[key] = std::move(n); + + return key; + }; + + nlohmann::json json; + json["version"] = 7; + json["root"] = dumpNode("root", root); + json["nodes"] = std::move(nodes); + + return json; +} + +std::string LockFile::to_string() const +{ + return toJson().dump(2); +} + +LockFile LockFile::read(const Path & path) +{ + if (!pathExists(path)) return LockFile(); + return LockFile(nlohmann::json::parse(readFile(path)), path); +} + +std::ostream & operator <<(std::ostream & stream, const LockFile & lockFile) +{ + stream << lockFile.toJson().dump(2); + return stream; +} + +void LockFile::write(const Path & path) const +{ + createDirs(dirOf(path)); + writeFile(path, fmt("%s\n", *this)); +} + +bool LockFile::isImmutable() const +{ + std::unordered_set> nodes; + + std::function node)> visit; + + visit = [&](std::shared_ptr node) + { + if (!nodes.insert(node).second) return; + for (auto & i : node->inputs) + if (auto child = std::get_if<0>(&i.second)) + visit(*child); + }; + + visit(root); + + for (auto & i : nodes) { + if (i == root) continue; + auto lockedNode = std::dynamic_pointer_cast(i); + if (lockedNode && !lockedNode->lockedRef.input.isImmutable()) return false; + } + + return true; +} + +bool LockFile::operator ==(const LockFile & other) const +{ + // FIXME: slow + return toJson() == other.toJson(); +} + +InputPath parseInputPath(std::string_view s) +{ + InputPath path; + + for (auto & elem : tokenizeString>(s, "/")) { + if (!std::regex_match(elem, flakeIdRegex)) + throw UsageError("invalid flake input path element '%s'", elem); + path.push_back(elem); + } + + return path; +} + +std::map LockFile::getAllInputs() const +{ + std::unordered_set> done; + std::map res; + + std::function node)> recurse; + + recurse = [&](const InputPath & prefix, std::shared_ptr node) + { + if (!done.insert(node).second) return; + + for (auto &[id, input] : node->inputs) { + auto inputPath(prefix); + inputPath.push_back(id); + res.emplace(inputPath, input); + if (auto child = std::get_if<0>(&input)) + recurse(inputPath, *child); + } + }; + + recurse({}, root); + + return res; +} + +std::ostream & operator <<(std::ostream & stream, const Node::Edge & edge) +{ + if (auto node = std::get_if<0>(&edge)) + stream << "'" << (*node)->lockedRef << "'"; + else if (auto follows = std::get_if<1>(&edge)) + stream << fmt("follows '%s'", printInputPath(*follows)); + return stream; +} + +static bool equals(const Node::Edge & e1, const Node::Edge & e2) +{ + if (auto n1 = std::get_if<0>(&e1)) + if (auto n2 = std::get_if<0>(&e2)) + return (*n1)->lockedRef == (*n2)->lockedRef; + if (auto f1 = std::get_if<1>(&e1)) + if (auto f2 = std::get_if<1>(&e2)) + return *f1 == *f2; + return false; +} + +std::string LockFile::diff(const LockFile & oldLocks, const LockFile & newLocks) +{ + auto oldFlat = oldLocks.getAllInputs(); + auto newFlat = newLocks.getAllInputs(); + + auto i = oldFlat.begin(); + auto j = newFlat.begin(); + std::string res; + + while (i != oldFlat.end() || j != newFlat.end()) { + if (j != newFlat.end() && (i == oldFlat.end() || i->first > j->first)) { + res += fmt("* Added '%s': %s\n", printInputPath(j->first), j->second); + ++j; + } else if (i != oldFlat.end() && (j == newFlat.end() || i->first < j->first)) { + res += fmt("* Removed '%s'\n", printInputPath(i->first)); + ++i; + } else { + if (!equals(i->second, j->second)) { + res += fmt("* Updated '%s': %s -> %s\n", + printInputPath(i->first), + i->second, + j->second); + } + ++i; + ++j; + } + } + + return res; +} + +void LockFile::check() +{ + auto inputs = getAllInputs(); + + for (auto & [inputPath, input] : inputs) { + if (auto follows = std::get_if<1>(&input)) { + if (!follows->empty() && !get(inputs, *follows)) + throw Error("input '%s' follows a non-existent input '%s'", + printInputPath(inputPath), + printInputPath(*follows)); + } + } +} + +void check(); + +std::string printInputPath(const InputPath & path) +{ + return concatStringsSep("/", path); +} + +} diff --git a/src/libexpr/flake/lockfile.hh b/src/libexpr/flake/lockfile.hh new file mode 100644 index 000000000..627794d8c --- /dev/null +++ b/src/libexpr/flake/lockfile.hh @@ -0,0 +1,83 @@ +#pragma once + +#include "flakeref.hh" + +#include + +namespace nix { +class Store; +class StorePath; +} + +namespace nix::flake { + +typedef std::vector InputPath; + +struct LockedNode; + +/* A node in the lock file. It has outgoing edges to other nodes (its + inputs). Only the root node has this type; all other nodes have + type LockedNode. */ +struct Node : std::enable_shared_from_this +{ + typedef std::variant, InputPath> Edge; + + std::map inputs; + + virtual ~Node() { } +}; + +/* A non-root node in the lock file. */ +struct LockedNode : Node +{ + FlakeRef lockedRef, originalRef; + bool isFlake = true; + + LockedNode( + const FlakeRef & lockedRef, + const FlakeRef & originalRef, + bool isFlake = true) + : lockedRef(lockedRef), originalRef(originalRef), isFlake(isFlake) + { } + + LockedNode(const nlohmann::json & json); + + StorePath computeStorePath(Store & store) const; +}; + +struct LockFile +{ + std::shared_ptr root = std::make_shared(); + + LockFile() {}; + LockFile(const nlohmann::json & json, const Path & path); + + nlohmann::json toJson() const; + + std::string to_string() const; + + static LockFile read(const Path & path); + + void write(const Path & path) const; + + bool isImmutable() const; + + bool operator ==(const LockFile & other) const; + + std::shared_ptr findInput(const InputPath & path); + + std::map getAllInputs() const; + + static std::string diff(const LockFile & oldLocks, const LockFile & newLocks); + + /* Check that every 'follows' input target exists. */ + void check(); +}; + +std::ostream & operator <<(std::ostream & stream, const LockFile & lockFile); + +InputPath parseInputPath(std::string_view s); + +std::string printInputPath(const InputPath & path); + +} diff --git a/src/libexpr/get-drvs.cc b/src/libexpr/get-drvs.cc index 9055f59a1..91916e8bf 100644 --- a/src/libexpr/get-drvs.cc +++ b/src/libexpr/get-drvs.cc @@ -38,8 +38,11 @@ DrvInfo::DrvInfo(EvalState & state, ref store, const std::string & drvPat auto i = drv.outputs.find(outputName); if (i == drv.outputs.end()) throw Error("derivation '%s' does not have output '%s'", store->printStorePath(drvPath), outputName); + auto & [outputName, output] = *i; - outPath = store->printStorePath(i->second.path); + auto optStorePath = output.path(*store, drv.name, outputName); + if (optStorePath) + outPath = store->printStorePath(*optStorePath); } @@ -77,12 +80,15 @@ string DrvInfo::queryDrvPath() const string DrvInfo::queryOutPath() const { - if (outPath == "" && attrs) { + if (!outPath && attrs) { Bindings::iterator i = attrs->find(state->sOutPath); PathSet context; - outPath = i != attrs->end() ? state->coerceToPath(*i->pos, *i->value, context) : ""; + if (i != attrs->end()) + outPath = state->coerceToPath(*i->pos, *i->value, context); } - return outPath; + if (!outPath) + throw UnimplementedError("CA derivations are not yet supported"); + return *outPath; } diff --git a/src/libexpr/get-drvs.hh b/src/libexpr/get-drvs.hh index d7860fc6a..29bb6a660 100644 --- a/src/libexpr/get-drvs.hh +++ b/src/libexpr/get-drvs.hh @@ -20,7 +20,7 @@ private: mutable string name; mutable string system; mutable string drvPath; - mutable string outPath; + mutable std::optional outPath; mutable string outputName; Outputs outputs; diff --git a/src/libexpr/json-to-value.cc b/src/libexpr/json-to-value.cc index 76e1a26bf..9ca5ac86d 100644 --- a/src/libexpr/json-to-value.cc +++ b/src/libexpr/json-to-value.cc @@ -115,6 +115,14 @@ public: { return handle_value(mkString, val.c_str()); } +#if NLOHMANN_JSON_VERSION_MAJOR >= 3 && NLOHMANN_JSON_VERSION_MINOR >= 8 + bool binary(binary_t&) + { + // This function ought to be unreachable + assert(false); + return true; + } +#endif bool start_object(std::size_t len) { diff --git a/src/libexpr/local.mk b/src/libexpr/local.mk index 9ed39e745..687a8ccda 100644 --- a/src/libexpr/local.mk +++ b/src/libexpr/local.mk @@ -4,7 +4,12 @@ libexpr_NAME = libnixexpr libexpr_DIR := $(d) -libexpr_SOURCES := $(wildcard $(d)/*.cc) $(wildcard $(d)/primops/*.cc) $(d)/lexer-tab.cc $(d)/parser-tab.cc +libexpr_SOURCES := \ + $(wildcard $(d)/*.cc) \ + $(wildcard $(d)/primops/*.cc) \ + $(wildcard $(d)/flake/*.cc) \ + $(d)/lexer-tab.cc \ + $(d)/parser-tab.cc libexpr_CXXFLAGS += -I src/libutil -I src/libstore -I src/libfetchers -I src/libmain -I src/libexpr @@ -34,4 +39,9 @@ dist-files += $(d)/parser-tab.cc $(d)/parser-tab.hh $(d)/lexer-tab.cc $(d)/lexer $(eval $(call install-file-in, $(d)/nix-expr.pc, $(prefix)/lib/pkgconfig, 0644)) -$(d)/primops.cc: $(d)/imported-drv-to-derivation.nix.gen.hh +$(foreach i, $(wildcard src/libexpr/flake/*.hh), \ + $(eval $(call install-file-in, $(i), $(includedir)/nix/flake, 0644))) + +$(d)/primops.cc: $(d)/imported-drv-to-derivation.nix.gen.hh $(d)/primops/derivation.nix.gen.hh + +$(d)/flake/flake.cc: $(d)/flake/call-flake.nix.gen.hh diff --git a/src/libexpr/parser.y b/src/libexpr/parser.y index 878f06c96..a4c84c526 100644 --- a/src/libexpr/parser.y +++ b/src/libexpr/parser.y @@ -614,8 +614,7 @@ Path resolveExprPath(Path path) // Basic cycle/depth limit to avoid infinite loops. if (++followCount >= maxFollow) throw Error("too many symbolic links encountered while traversing the path '%s'", path); - if (lstat(path.c_str(), &st)) - throw SysError("getting status of '%s'", path); + st = lstat(path); if (!S_ISLNK(st.st_mode)) break; path = absPath(readLink(path), dirOf(path)); } @@ -719,7 +718,7 @@ std::pair EvalState::resolveSearchPathElem(const SearchPathEl if (isUri(elem.second)) { try { res = { true, store->toRealPath(fetchers::downloadTarball( - store, resolveUri(elem.second), "source", false).storePath) }; + store, resolveUri(elem.second), "source", false).first.storePath) }; } catch (FileTransferError & e) { logWarning({ .name = "Entry download", diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index dec917b38..2b304aab0 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -30,18 +30,6 @@ namespace nix { *************************************************************/ -/* Decode a context string ‘!!’ into a pair . */ -std::pair decodeContext(const string & s) -{ - if (s.at(0) == '!') { - size_t index = s.find("!", 1); - return std::pair(string(s, index + 1), string(s, 1, index - 1)); - } else - return std::pair(s.at(0) == '/' ? s : string(s, 1), ""); -} - - InvalidPathError::InvalidPathError(const Path & path) : EvalError("path '%s' is not valid", path), path(path) {} @@ -56,16 +44,6 @@ void EvalState::realiseContext(const PathSet & context) throw InvalidPathError(store->printStorePath(ctx)); if (!outputName.empty() && ctx.isDerivation()) { drvs.push_back(StorePathWithOutputs{ctx, {outputName}}); - - /* Add the output of this derivation to the allowed - paths. */ - if (allowedPaths) { - auto drv = store->derivationFromPath(ctx); - DerivationOutputs::iterator i = drv.outputs.find(outputName); - if (i == drv.outputs.end()) - throw Error("derivation '%s' does not have an output named '%s'", ctxS, outputName); - allowedPaths->insert(store->printStorePath(i->second.path)); - } } } @@ -77,19 +55,61 @@ void EvalState::realiseContext(const PathSet & context) /* For performance, prefetch all substitute info. */ StorePathSet willBuild, willSubstitute, unknown; - unsigned long long downloadSize, narSize; + uint64_t downloadSize, narSize; store->queryMissing(drvs, willBuild, willSubstitute, unknown, downloadSize, narSize); store->buildPaths(drvs); + + /* Add the output of this derivations to the allowed + paths. */ + if (allowedPaths) { + for (auto & [drvPath, outputs] : drvs) { + auto outputPaths = store->queryDerivationOutputMap(drvPath); + for (auto & outputName : outputs) { + if (outputPaths.count(outputName) == 0) + throw Error("derivation '%s' does not have an output named '%s'", + store->printStorePath(drvPath), outputName); + allowedPaths->insert(store->printStorePath(outputPaths.at(outputName))); + } + } + } } +/* Add and attribute to the given attribute map from the output name to + the output path, or a placeholder. + + Where possible the path is used, but for floating CA derivations we + may not know it. For sake of determinism we always assume we don't + and instead put in a place holder. In either case, however, the + string context will contain the drv path and output name, so + downstream derivations will have the proper dependency, and in + addition, before building, the placeholder will be rewritten to be + the actual path. + + The 'drv' and 'drvPath' outputs must correspond. */ +static void mkOutputString(EvalState & state, Value & v, + const StorePath & drvPath, const BasicDerivation & drv, + std::pair o) +{ + auto optOutputPath = o.second.path(*state.store, drv.name, o.first); + mkString( + *state.allocAttr(v, state.symbols.create(o.first)), + optOutputPath + ? state.store->printStorePath(*optOutputPath) + /* Downstream we would substitute this for an actual path once + we build the floating CA derivation */ + /* FIXME: we need to depend on the basic derivation, not + derivation */ + : downstreamPlaceholder(*state.store, drvPath, o.first), + {"!" + o.first + "!" + state.store->printStorePath(drvPath)}); +} /* Load and evaluate an expression from path specified by the argument. */ -static void prim_scopedImport(EvalState & state, const Pos & pos, Value * * args, Value & v) +static void import(EvalState & state, const Pos & pos, Value & vPath, Value * vScope, Value & v) { PathSet context; - Path path = state.coerceToPath(pos, *args[1], context); + Path path = state.coerceToPath(pos, vPath, context); try { state.realiseContext(context); @@ -103,8 +123,18 @@ static void prim_scopedImport(EvalState & state, const Pos & pos, Value * * args Path realPath = state.checkSourcePath(state.toRealPath(path, context)); // FIXME - if (state.store->isStorePath(path) && state.store->isValidPath(state.store->parseStorePath(path)) && isDerivation(path)) { - Derivation drv = readDerivation(*state.store, realPath); + auto isValidDerivationInStore = [&]() -> std::optional { + if (!state.store->isStorePath(path)) + return std::nullopt; + auto storePath = state.store->parseStorePath(path); + if (!(state.store->isValidPath(storePath) && isDerivation(path))) + return std::nullopt; + return storePath; + }; + + if (auto optStorePath = isValidDerivationInStore()) { + auto storePath = *optStorePath; + Derivation drv = state.store->readDerivation(storePath); Value & w = *state.allocValue(); state.mkAttrs(w, 3 + drv.outputs.size()); Value * v2 = state.allocAttr(w, state.sDrvPath); @@ -117,8 +147,7 @@ static void prim_scopedImport(EvalState & state, const Pos & pos, Value * * args unsigned int outputs_index = 0; for (const auto & o : drv.outputs) { - v2 = state.allocAttr(w, state.symbols.create(o.first)); - mkString(*v2, state.store->printStorePath(o.second.path), {"!" + o.first + "!" + path}); + mkOutputString(state, w, storePath, drv, o); outputsVal->listElems()[outputs_index] = state.allocValue(); mkString(*(outputsVal->listElems()[outputs_index++]), o.first); } @@ -136,17 +165,18 @@ static void prim_scopedImport(EvalState & state, const Pos & pos, Value * * args mkApp(v, **fun, w); state.forceAttrs(v, pos); } else { - state.forceAttrs(*args[0]); - if (args[0]->attrs->empty()) + if (!vScope) state.evalFile(realPath, v); else { - Env * env = &state.allocEnv(args[0]->attrs->size()); + state.forceAttrs(*vScope); + + Env * env = &state.allocEnv(vScope->attrs->size()); env->up = &state.baseEnv; StaticEnv staticEnv(false, &state.staticBaseEnv); unsigned int displ = 0; - for (auto & attr : *args[0]->attrs) { + for (auto & attr : *vScope->attrs) { staticEnv.vars[attr.name] = displ; env->values[displ++] = attr.value; } @@ -159,6 +189,76 @@ static void prim_scopedImport(EvalState & state, const Pos & pos, Value * * args } } +static RegisterPrimOp primop_scopedImport(RegisterPrimOp::Info { + .name = "scopedImport", + .arity = 2, + .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v) + { + import(state, pos, *args[1], args[0], v); + } +}); + +static RegisterPrimOp primop_import({ + .name = "import", + .args = {"path"}, + .doc = R"( + Load, parse and return the Nix expression in the file *path*. If + *path* is a directory, the file ` default.nix ` in that directory + is loaded. Evaluation aborts if the file doesn’t exist or contains + an incorrect Nix expression. `import` implements Nix’s module + system: you can put any Nix expression (such as a set or a + function) in a separate file, and use it from Nix expressions in + other files. + + > **Note** + > + > Unlike some languages, `import` is a regular function in Nix. + > Paths using the angle bracket syntax (e.g., `import` *\*) + > are [normal path values](language-values.md). + + A Nix expression loaded by `import` must not contain any *free + variables* (identifiers that are not defined in the Nix expression + itself and are not built-in). Therefore, it cannot refer to + variables that are in scope at the call site. For instance, if you + have a calling expression + + ```nix + rec { + x = 123; + y = import ./foo.nix; + } + ``` + + then the following `foo.nix` will give an error: + + ```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: + + ```nix + rec { + x = 123; + y = import ./foo.nix x; + } + ``` + + and + + ```nix + x: x + 456 + ``` + + (The function argument doesn’t have to be called `x` in `foo.nix`; + any name would work.) + )", + .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v) + { + import(state, pos, *args[0], nullptr, v); + } +}); /* Want reasonable symbol names, so extern C */ /* !!! Should we pass the Pos or the file name too? */ @@ -278,6 +378,16 @@ static void prim_typeOf(EvalState & state, const Pos & pos, Value * * args, Valu mkString(v, state.symbols.create(t)); } +static RegisterPrimOp primop_typeOf({ + .name = "__typeOf", + .args = {"e"}, + .doc = R"( + Return a string representing the type of the value *e*, namely + `"int"`, `"bool"`, `"string"`, `"path"`, `"null"`, `"set"`, + `"list"`, `"lambda"` or `"float"`. + )", + .fun = prim_typeOf, +}); /* Determine whether the argument is the null value. */ static void prim_isNull(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -286,6 +396,18 @@ static void prim_isNull(EvalState & state, const Pos & pos, Value * * args, Valu mkBool(v, args[0]->type == tNull); } +static RegisterPrimOp primop_isNull({ + .name = "isNull", + .args = {"e"}, + .doc = R"( + Return `true` if *e* evaluates to `null`, and `false` otherwise. + + > **Warning** + > + > This function is *deprecated*; just write `e == null` instead. + )", + .fun = prim_isNull, +}); /* Determine whether the argument is a function. */ static void prim_isFunction(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -305,6 +427,14 @@ static void prim_isFunction(EvalState & state, const Pos & pos, Value * * args, mkBool(v, res); } +static RegisterPrimOp primop_isFunction({ + .name = "__isFunction", + .args = {"e"}, + .doc = R"( + Return `true` if *e* evaluates to a function, and `false` otherwise. + )", + .fun = prim_isFunction, +}); /* Determine whether the argument is an integer. */ static void prim_isInt(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -313,6 +443,15 @@ static void prim_isInt(EvalState & state, const Pos & pos, Value * * args, Value mkBool(v, args[0]->type == tInt); } +static RegisterPrimOp primop_isInt({ + .name = "__isInt", + .args = {"e"}, + .doc = R"( + Return `true` if *e* evaluates to an integer, and `false` otherwise. + )", + .fun = prim_isInt, +}); + /* Determine whether the argument is a float. */ static void prim_isFloat(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -320,6 +459,15 @@ static void prim_isFloat(EvalState & state, const Pos & pos, Value * * args, Val mkBool(v, args[0]->type == tFloat); } +static RegisterPrimOp primop_isFloat({ + .name = "__isFloat", + .args = {"e"}, + .doc = R"( + Return `true` if *e* evaluates to a float, and `false` otherwise. + )", + .fun = prim_isFloat, +}); + /* Determine whether the argument is a string. */ static void prim_isString(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -327,6 +475,14 @@ static void prim_isString(EvalState & state, const Pos & pos, Value * * args, Va mkBool(v, args[0]->type == tString); } +static RegisterPrimOp primop_isString({ + .name = "__isString", + .args = {"e"}, + .doc = R"( + Return `true` if *e* evaluates to a string, and `false` otherwise. + )", + .fun = prim_isString, +}); /* Determine whether the argument is a Boolean. */ static void prim_isBool(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -335,6 +491,15 @@ static void prim_isBool(EvalState & state, const Pos & pos, Value * * args, Valu mkBool(v, args[0]->type == tBool); } +static RegisterPrimOp primop_isBool({ + .name = "__isBool", + .args = {"e"}, + .doc = R"( + Return `true` if *e* evaluates to a bool, and `false` otherwise. + )", + .fun = prim_isBool, +}); + /* Determine whether the argument is a path. */ static void prim_isPath(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -342,6 +507,15 @@ static void prim_isPath(EvalState & state, const Pos & pos, Value * * args, Valu mkBool(v, args[0]->type == tPath); } +static RegisterPrimOp primop_isPath({ + .name = "__isPath", + .args = {"e"}, + .doc = R"( + Return `true` if *e* evaluates to a path, and `false` otherwise. + )", + .fun = prim_isPath, +}); + struct CompareValues { bool operator () (const Value * v1, const Value * v2) const @@ -447,22 +621,43 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar v.listElems()[n++] = i; } +static RegisterPrimOp primop_genericClosure(RegisterPrimOp::Info { + .name = "__genericClosure", + .arity = 1, + .fun = prim_genericClosure, +}); -static void prim_abort(EvalState & state, const Pos & pos, Value * * args, Value & v) -{ - PathSet context; - string s = state.coerceToString(pos, *args[0], context); - throw Abort("evaluation aborted with the following error message: '%1%'", s); -} - - -static void prim_throw(EvalState & state, const Pos & pos, Value * * args, Value & v) -{ - PathSet context; - string s = state.coerceToString(pos, *args[0], context); - throw ThrownError(s); -} +static RegisterPrimOp primop_abort({ + .name = "abort", + .args = {"s"}, + .doc = R"( + Abort Nix expression evaluation and print the error message *s*. + )", + .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v) + { + PathSet context; + string s = state.coerceToString(pos, *args[0], context); + throw Abort("evaluation aborted with the following error message: '%1%'", s); + } +}); +static RegisterPrimOp primop_throw({ + .name = "throw", + .args = {"s"}, + .doc = R"( + Throw an error message *s*. This usually aborts Nix expression + evaluation, but in `nix-env -qa` and other commands that try to + evaluate a set of derivations to get information about those + derivations, a derivation that throws an error is silently skipped + (which is not the case for `abort`). + )", + .fun = [](EvalState & state, const Pos & pos, Value * * args, Value & v) + { + PathSet context; + string s = state.coerceToString(pos, *args[0], context); + throw ThrownError(s); + } +}); static void prim_addErrorContext(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -476,6 +671,11 @@ static void prim_addErrorContext(EvalState & state, const Pos & pos, Value * * a } } +static RegisterPrimOp primop_addErrorContext(RegisterPrimOp::Info { + .name = "__addErrorContext", + .arity = 2, + .fun = prim_addErrorContext, +}); /* Try evaluating the argument. Success => {success=true; value=something;}, * else => {success=false; value=false;} */ @@ -493,6 +693,22 @@ static void prim_tryEval(EvalState & state, const Pos & pos, Value * * args, Val v.attrs->sort(); } +static RegisterPrimOp primop_tryEval({ + .name = "__tryEval", + .args = {"e"}, + .doc = R"( + 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 + `false`. + )", + .fun = prim_tryEval, +}); /* Return an environment variable. Use with care. */ static void prim_getEnv(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -501,6 +717,22 @@ static void prim_getEnv(EvalState & state, const Pos & pos, Value * * args, Valu mkString(v, evalSettings.restrictEval || evalSettings.pureEval ? "" : getEnv(name).value_or("")); } +static RegisterPrimOp primop_getEnv({ + .name = "__getEnv", + .args = {"s"}, + .doc = R"( + `getEnv` returns the value of the environment variable *s*, or an + empty string if the variable doesn’t exist. This function should be + used with care, as it can introduce all sorts of nasty environment + dependencies in your Nix expression. + + `getEnv` is used in Nix Packages to locate the file + `~/.nixpkgs/config.nix`, which contains user-local settings for Nix + Packages. (That is, it does a `getEnv "HOME"` to locate the user’s + home directory.) + )", + .fun = prim_getEnv, +}); /* Evaluate the first argument, then return the second argument. */ static void prim_seq(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -510,6 +742,15 @@ static void prim_seq(EvalState & state, const Pos & pos, Value * * args, Value & v = *args[1]; } +static RegisterPrimOp primop_seq({ + .name = "__seq", + .args = {"e1", "e2"}, + .doc = R"( + Evaluate *e1*, then evaluate and return *e2*. This ensures that a + computation is strict in the value of *e1*. + )", + .fun = prim_seq, +}); /* Evaluate the first argument deeply (i.e. recursing into lists and attrsets), then return the second argument. */ @@ -520,6 +761,16 @@ static void prim_deepSeq(EvalState & state, const Pos & pos, Value * * args, Val v = *args[1]; } +static RegisterPrimOp primop_deepSeq({ + .name = "__deepSeq", + .args = {"e1", "e2"}, + .doc = R"( + This is like `seq e1 e2`, except that *e1* is evaluated *deeply*: + if it’s a list or set, its elements or attributes are also + evaluated recursively. + )", + .fun = prim_deepSeq, +}); /* Evaluate the first expression and print it on standard error. Then return the second expression. Useful for debugging. */ @@ -534,6 +785,17 @@ static void prim_trace(EvalState & state, const Pos & pos, Value * * args, Value v = *args[1]; } +static RegisterPrimOp primop_trace({ + .name = "__trace", + .args = {"e1", "e2"}, + .doc = R"( + Evaluate *e1* and print its abstract syntax representation on + standard error. Then return *e2*. This function is useful for + debugging. + )", + .fun = prim_trace, +}); + /************************************************************* * Derivations @@ -582,9 +844,11 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * /* Build the derivation expression by processing the attributes. */ Derivation drv; + drv.name = drvName; PathSet context; + bool contentAddressed = false; std::optional outputHash; std::string outputHashAlgo; auto ingestionMethod = FileIngestionMethod::Flat; @@ -641,9 +905,14 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * if (i->value->type == tNull) continue; } + if (i->name == state.sContentAddressed) { + settings.requireExperimentalFeature("ca-derivations"); + contentAddressed = state.forceBool(*i->value, pos); + } + /* The `args' attribute is special: it supplies the command-line arguments to the builder. */ - if (i->name == state.sArgs) { + else if (i->name == state.sArgs) { state.forceList(*i->value, pos); for (unsigned int n = 0; n < i->value->listSize(); ++n) { string s = state.coerceToString(posDrvName, *i->value->listElems()[n], context, true); @@ -696,7 +965,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * } } catch (Error & e) { - e.addTrace(posDrvName, + e.addTrace(posDrvName, "while evaluating the attribute '%1%' of the derivation '%2%'", key, drvName); throw; @@ -763,7 +1032,10 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * }); if (outputHash) { - /* Handle fixed-output derivations. */ + /* Handle fixed-output derivations. + + Ignore `__contentAddressed` because fixed output derivations are + already content addressed. */ if (outputs.size() != 1 || *(outputs.begin()) != "out") throw Error({ .hint = hintfmt("multiple outputs are not supported in fixed-output derivations"), @@ -774,16 +1046,30 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * Hash h = newHashAllowEmpty(*outputHash, ht); auto outPath = state.store->makeFixedOutputPath(ingestionMethod, h, drvName); - if (!jsonObject) drv.env["out"] = state.store->printStorePath(outPath); + drv.env["out"] = state.store->printStorePath(outPath); drv.outputs.insert_or_assign("out", DerivationOutput { - .path = std::move(outPath), - .hash = FixedOutputHash { - .method = ingestionMethod, - .hash = std::move(h), - }, + .output = DerivationOutputCAFixed { + .hash = FixedOutputHash { + .method = ingestionMethod, + .hash = std::move(h), + }, + }, }); } + else if (contentAddressed) { + HashType ht = parseHashType(outputHashAlgo); + for (auto & i : outputs) { + drv.env[i] = hashPlaceholder(i); + drv.outputs.insert_or_assign(i, DerivationOutput { + .output = DerivationOutputCAFloating { + .method = ingestionMethod, + .hashType = std::move(ht), + }, + }); + } + } + else { /* Compute a hash over the "masked" store derivation, which is the final one except that in the list of outputs, the @@ -792,48 +1078,59 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * that changes in the set of output names do get reflected in the hash. */ for (auto & i : outputs) { - if (!jsonObject) drv.env[i] = ""; + drv.env[i] = ""; drv.outputs.insert_or_assign(i, DerivationOutput { - .path = StorePath::dummy, - .hash = std::optional {}, + .output = DerivationOutputInputAddressed { + .path = StorePath::dummy, + }, }); } - Hash h = hashDerivationModulo(*state.store, Derivation(drv), true); + // Regular, non-CA derivation should always return a single hash and not + // hash per output. + Hash h = std::get<0>(hashDerivationModulo(*state.store, Derivation(drv), true)); for (auto & i : outputs) { auto outPath = state.store->makeOutputPath(i, h, drvName); - if (!jsonObject) drv.env[i] = state.store->printStorePath(outPath); + drv.env[i] = state.store->printStorePath(outPath); drv.outputs.insert_or_assign(i, DerivationOutput { - .path = std::move(outPath), - .hash = std::optional(), + .output = DerivationOutputInputAddressed { + .path = std::move(outPath), + }, }); } } /* Write the resulting term into the Nix store directory. */ - auto drvPath = writeDerivation(state.store, drv, drvName, state.repair); + auto drvPath = writeDerivation(*state.store, drv, state.repair); auto drvPathS = state.store->printStorePath(drvPath); printMsg(lvlChatty, "instantiated '%1%' -> '%2%'", drvName, drvPathS); /* Optimisation, but required in read-only mode! because in that case we don't actually write store derivations, so we can't - read them later. */ - drvHashes.insert_or_assign(drvPath, - hashDerivationModulo(*state.store, Derivation(drv), false)); + read them later. + + However, we don't bother doing this for floating CA derivations because + their "hash modulo" is indeterminate until built. */ + if (drv.type() != DerivationType::CAFloating) + drvHashes.insert_or_assign(drvPath, + hashDerivationModulo(*state.store, Derivation(drv), false)); state.mkAttrs(v, 1 + drv.outputs.size()); mkString(*state.allocAttr(v, state.sDrvPath), drvPathS, {"=" + drvPathS}); - for (auto & i : drv.outputs) { - mkString(*state.allocAttr(v, state.symbols.create(i.first)), - state.store->printStorePath(i.second.path), {"!" + i.first + "!" + drvPathS}); - } + for (auto & i : drv.outputs) + mkOutputString(state, v, drvPath, drv, i); v.attrs->sort(); } +static RegisterPrimOp primop_derivationStrict(RegisterPrimOp::Info { + .name = "derivationStrict", + .arity = 1, + .fun = prim_derivationStrict, +}); /* Return a placeholder string for the specified output that will be substituted by the corresponding output path at build time. For @@ -847,6 +1144,17 @@ static void prim_placeholder(EvalState & state, const Pos & pos, Value * * args, mkString(v, hashPlaceholder(state.forceStringNoCtx(*args[0], pos))); } +static RegisterPrimOp primop_placeholder({ + .name = "placeholder", + .args = {"output"}, + .doc = R"( + Return a placeholder string for the specified *output* that will be + substituted by the corresponding output path at build time. Typical + outputs would be `"out"`, `"bin"` or `"dev"`. + )", + .fun = prim_placeholder, +}); + /************************************************************* * Paths @@ -861,6 +1169,15 @@ static void prim_toPath(EvalState & state, const Pos & pos, Value * * args, Valu mkString(v, canonPath(path), context); } +static RegisterPrimOp primop_toPath({ + .name = "__toPath", + .args = {"s"}, + .doc = R"( + **DEPRECATED.** Use `/. + "/path"` to convert a string into an absolute + path. For relative paths, use `./. + "/path"`. + )", + .fun = prim_toPath, +}); /* Allow a valid store path to be used in an expression. This is useful in some generated expressions such as in nix-push, which @@ -872,6 +1189,9 @@ static void prim_toPath(EvalState & state, const Pos & pos, Value * * args, Valu corner cases. */ static void prim_storePath(EvalState & state, const Pos & pos, Value * * args, Value & v) { + if (evalSettings.pureEval) + throw EvalError("builtins.storePath' is not allowed in pure evaluation mode"); + PathSet context; Path path = state.checkSourcePath(state.coerceToPath(pos, *args[0], context)); /* Resolve symlinks in ‘path’, unless ‘path’ itself is a symlink @@ -883,13 +1203,30 @@ static void prim_storePath(EvalState & state, const Pos & pos, Value * * args, V .hint = hintfmt("path '%1%' is not in the Nix store", path), .errPos = pos }); - Path path2 = state.store->toStorePath(path); + auto path2 = state.store->toStorePath(path).first; if (!settings.readOnlyMode) - state.store->ensurePath(state.store->parseStorePath(path2)); - context.insert(path2); + state.store->ensurePath(path2); + context.insert(state.store->printStorePath(path2)); mkString(v, path, context); } +static RegisterPrimOp primop_storePath({ + .name = "__storePath", + .args = {"path"}, + .doc = R"( + This function allows you to define a dependency on an already + existing store path. For example, the derivation attribute `src + = builtins.storePath /nix/store/f1d18v1y…-source` causes the + derivation to depend on the specified path, which must exist or + be substitutable. Note that this differs from a plain path + (e.g. `src = /nix/store/f1d18v1y…-source`) in that the latter + causes the path to be *copied* again to the Nix store, resulting + in a new path (e.g. `/nix/store/ld01dnzc…-source-source`). + + This function is not available in pure evaluation mode. + )", + .fun = prim_storePath, +}); static void prim_pathExists(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -917,6 +1254,15 @@ static void prim_pathExists(EvalState & state, const Pos & pos, Value * * args, } } +static RegisterPrimOp primop_pathExists({ + .name = "__pathExists", + .args = {"path"}, + .doc = R"( + Return `true` if the path *path* exists at evaluation time, and + `false` otherwise. + )", + .fun = prim_pathExists, +}); /* Return the base name of the given string, i.e., everything following the last slash. */ @@ -926,6 +1272,16 @@ static void prim_baseNameOf(EvalState & state, const Pos & pos, Value * * args, mkString(v, baseNameOf(state.coerceToString(pos, *args[0], context, false, false)), context); } +static RegisterPrimOp primop_baseNameOf({ + .name = "baseNameOf", + .args = {"s"}, + .doc = R"( + Return the *base name* of the string *s*, that is, everything + following the final slash in the string. This is similar to the GNU + `basename` command. + )", + .fun = prim_baseNameOf, +}); /* Return the directory of the given path, i.e., everything before the last slash. Return either a path or a string depending on the type @@ -937,6 +1293,16 @@ static void prim_dirOf(EvalState & state, const Pos & pos, Value * * args, Value if (args[0]->type == tPath) mkPath(v, dir.c_str()); else mkString(v, dir, context); } +static RegisterPrimOp primop_dirOf({ + .name = "dirOf", + .args = {"s"}, + .doc = R"( + Return the directory part of the string *s*, that is, everything + before the final slash in the string. This is similar to the GNU + `dirname` command. + )", + .fun = prim_dirOf, +}); /* Return the contents of a file as a string. */ static void prim_readFile(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -957,6 +1323,14 @@ static void prim_readFile(EvalState & state, const Pos & pos, Value * * args, Va mkString(v, s.c_str()); } +static RegisterPrimOp primop_readFile({ + .name = "__readFile", + .args = {"path"}, + .doc = R"( + Return the contents of the file *path* as a string. + )", + .fun = prim_readFile, +}); /* Find a file in the Nix search path. Used to implement paths, which are desugared to 'findFile __nixPath "x"'. */ @@ -1002,6 +1376,12 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va mkPath(v, state.checkSourcePath(state.findFile(searchPath, path, pos)).c_str()); } +static RegisterPrimOp primop_findFile(RegisterPrimOp::Info { + .name = "__findFile", + .arity = 2, + .fun = prim_findFile, +}); + /* Return the cryptographic hash of a file in base-16. */ static void prim_hashFile(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -1019,6 +1399,17 @@ static void prim_hashFile(EvalState & state, const Pos & pos, Value * * args, Va mkString(v, hashFile(*ht, state.checkSourcePath(p)).to_string(Base16, false), context); } +static RegisterPrimOp primop_hashFile({ + .name = "__hashFile", + .args = {"type", "p"}, + .doc = R"( + Return a base-16 representation of the cryptographic hash of the + file at path *p*. The hash algorithm specified by *type* must be one + of `"md5"`, `"sha1"`, `"sha256"` or `"sha512"`. + )", + .fun = prim_hashFile, +}); + /* Read a directory (without . or ..) */ static void prim_readDir(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -1050,6 +1441,25 @@ static void prim_readDir(EvalState & state, const Pos & pos, Value * * args, Val v.attrs->sort(); } +static RegisterPrimOp primop_readDir({ + .name = "__readDir", + .args = {"path"}, + .doc = R"( + 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 + + ```nix + { B = "regular"; C = "directory"; } + ``` + + The possible values for the file type are `"regular"`, + `"directory"`, `"symlink"` and `"unknown"`. + )", + .fun = prim_readDir, +}); + /************************************************************* * Creating files @@ -1067,6 +1477,102 @@ static void prim_toXML(EvalState & state, const Pos & pos, Value * * args, Value mkString(v, out.str(), context); } +static RegisterPrimOp primop_toXML({ + .name = "__toXML", + .args = {"e"}, + .doc = R"( + Return a string containing an XML representation of *e*. The main + application for `toXML` is to communicate information with the + builder in a more structured format than plain environment + variables. + + Here is an example where this is the case: + + ```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" ② + " + + + + + + + + + + + + + "; + + servlets = builtins.toXML [ ③ + { path = "/bugtracker"; war = jira + "/lib/atlassian-jira.war"; } + { path = "/wiki"; war = uberwiki + "/uberwiki.war"; } + ]; + }) + ``` + + The builder is supposed to generate the configuration file for a + [Jetty servlet container](http://jetty.mortbay.org/). A servlet + container contains a number of servlets (`*.war` files) each + exported under a specific URI prefix. So the servlet configuration + is a list of sets containing the `path` and `war` of the servlet + (①). This kind of information is difficult to communicate with the + normal method of passing information through an environment + variable, which just concatenates everything together into a + string (which might just work in this case, but wouldn’t work if + fields are optional or contain lists themselves). Instead the Nix + expression is converted to an XML representation with `toXML`, + which is unambiguous and can easily be processed with the + appropriate tools. For instance, in the example an XSLT stylesheet + (at point ②) is applied to it (at point ①) to generate the XML + configuration file for the Jetty server. The XML representation + produced at point ③ by `toXML` is as follows: + + ```xml + + + + + + + + + + + + + + + + + + + + + + ``` + + Note that we used the `toFile` built-in to write the builder and + the stylesheet “inline” in the Nix expression. The path of the + stylesheet is spliced into the builder using the syntax `xsltproc + ${stylesheet}`. + )", + .fun = prim_toXML, +}); /* Convert the argument (which can be any Nix expression) to a JSON string. Not all Nix expressions can be sensibly or completely @@ -1079,6 +1585,19 @@ static void prim_toJSON(EvalState & state, const Pos & pos, Value * * args, Valu mkString(v, out.str(), context); } +static RegisterPrimOp primop_toJSON({ + .name = "__toJSON", + .args = {"e"}, + .doc = R"( + Return a string containing a JSON representation of *e*. Strings, + integers, floats, booleans, nulls and lists are mapped to their JSON + equivalents. Sets (except derivations) are represented as objects. + Derivations are translated to a JSON string containing the + derivation’s output path. Paths are copied to the store and + represented as a JSON string of the resulting store path. + )", + .fun = prim_toJSON, +}); /* Parse a JSON string to a value. */ static void prim_fromJSON(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -1087,6 +1606,20 @@ static void prim_fromJSON(EvalState & state, const Pos & pos, Value * * args, Va parseJSON(state, s, v); } +static RegisterPrimOp primop_fromJSON({ + .name = "__fromJSON", + .args = {"e"}, + .doc = R"( + Convert a JSON string to a Nix value. For example, + + ```nix + builtins.fromJSON ''{"x": [1, 2, 3], "y": null}'' + ``` + + returns the value `{ x = [ 1 2 3 ]; y = null; }`. + )", + .fun = prim_fromJSON, +}); /* Store a string in the Nix store as a source file that can be used as an input by derivations. */ @@ -1121,9 +1654,86 @@ static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Valu mkString(v, storePath, {storePath}); } +static RegisterPrimOp primop_toFile({ + .name = "__toFile", + .args = {"name", "s"}, + .doc = R"( + Store the string *s* in a file in the Nix store and return its + path. The file has suffix *name*. This file can be used as an + input to derivations. One application is to write builders + “inline”. For instance, the following Nix expression combines the + [Nix expression for GNU Hello](expression-syntax.md) and its + [build script](build-script.md) into one file: + + ```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., + + ```nix + builder = let + configFile = builtins.toFile "foo.conf" " + # This is some dummy configuration file. + ... + "; + in builtins.toFile "builder.sh" " + source $stdenv/setup + ... + cp ${configFile} $out/etc/foo.conf + "; + ``` + + Note that `${configFile}` is an + [antiquotation](language-values.md), so the result of the + expression `configFile` + (i.e., a path like `/nix/store/m7p7jfny445k...-foo.conf`) will be + spliced into the resulting string. + + It is however *not* allowed to have files mutually referring to each + other, like so: + + ```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`. + + It is also not possible to reference the result of a derivation. If + you are using Nixpkgs, the `writeTextFile` function is able to do + that. + )", + .fun = prim_toFile, +}); static void addPath(EvalState & state, const Pos & pos, const string & name, const Path & path_, - Value * filterFun, FileIngestionMethod method, const Hash & expectedHash, Value & v) + Value * filterFun, FileIngestionMethod method, const std::optional expectedHash, Value & v) { const auto path = evalSettings.pureEval && expectedHash ? path_ : @@ -1154,7 +1764,7 @@ static void addPath(EvalState & state, const Pos & pos, const string & name, con std::optional expectedStorePath; if (expectedHash) - expectedStorePath = state.store->makeFixedOutputPath(method, expectedHash, name); + expectedStorePath = state.store->makeFixedOutputPath(method, *expectedHash, name); Path dstPath; if (!expectedHash || !state.store->isValidPath(*expectedStorePath)) { dstPath = state.store->printStorePath(settings.readOnlyMode @@ -1188,9 +1798,51 @@ static void prim_filterSource(EvalState & state, const Pos & pos, Value * * args .errPos = pos }); - addPath(state, pos, std::string(baseNameOf(path)), path, args[0], FileIngestionMethod::Recursive, Hash(), v); + addPath(state, pos, std::string(baseNameOf(path)), path, args[0], FileIngestionMethod::Recursive, std::nullopt, v); } +static RegisterPrimOp primop_filterSource({ + .name = "__filterSource", + .args = {"e1", "e2"}, + .doc = R"( + This function allows you to copy sources into the Nix store while + filtering certain files. For instance, suppose that you want to use + the directory `source-dir` as an input to a Nix expression, e.g. + + ```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 + store. Worse, the contents of those directories may change a lot, + causing lots of spurious rebuilds. With `filterSource` you can + filter out the `.svn` directories: + + ```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 + called for each regular file, directory or symlink in the source + tree *e2*. If the function returns `true`, the file is copied to the + Nix store, otherwise it is omitted. The function is called with two + arguments. The first is the full path of the file. The second is a + string that identifies the type of the file, which is either + `"regular"`, `"directory"`, `"symlink"` or `"unknown"` (for other + kinds of files such as device nodes or fifos — but note that those + cannot be copied to the Nix store, so if the predicate returns + `true` for them, the copy will fail). If you exclude a directory, + the entire corresponding subtree of *e2* will be excluded. + )", + .fun = prim_filterSource, +}); + static void prim_path(EvalState & state, const Pos & pos, Value * * args, Value & v) { state.forceAttrs(*args[0], pos); @@ -1198,7 +1850,7 @@ static void prim_path(EvalState & state, const Pos & pos, Value * * args, Value string name; Value * filterFun = nullptr; auto method = FileIngestionMethod::Recursive; - Hash expectedHash; + std::optional expectedHash; for (auto & attr : *args[0]->attrs) { const string & n(attr.name); @@ -1236,6 +1888,41 @@ static void prim_path(EvalState & state, const Pos & pos, Value * * args, Value addPath(state, pos, name, path, filterFun, method, expectedHash, v); } +static RegisterPrimOp primop_path({ + .name = "__path", + .args = {"args"}, + .doc = R"( + An enrichment of the built-in path type, based on the attributes + present in *args*. All are optional except `path`: + + - path + The underlying path. + + - name + The name of the path when added to the store. This can used to + reference paths that have nix-illegal characters in their names, + like `@`. + + - filter + A function of the type expected by `builtins.filterSource`, + with the same semantics. + + - recursive + When `false`, when `path` is added to the store it is with a + flat hash, rather than a hash of the NAR serialization of the + file. Thus, `path` must refer to a regular file, not a + directory. This allows similar behavior to `fetchurl`. Defaults + to `true`. + + - sha256 + When provided, this is the expected hash of the file at the + path. Evaluation will fail if the hash is incorrect, and + providing a hash allows `builtins.path` to be used even when the + `pure-eval` nix config option is on. + )", + .fun = prim_path, +}); + /************************************************************* * Sets @@ -1258,6 +1945,16 @@ static void prim_attrNames(EvalState & state, const Pos & pos, Value * * args, V [](Value * v1, Value * v2) { return strcmp(v1->string.s, v2->string.s) < 0; }); } +static RegisterPrimOp primop_attrNames({ + .name = "__attrNames", + .args = {"set"}, + .doc = R"( + Return the names of the attributes in the set *set* in an + alphabetically sorted list. For instance, `builtins.attrNames { y + = 1; x = "foo"; }` evaluates to `[ "x" "y" ]`. + )", + .fun = prim_attrNames, +}); /* Return the values of the attributes in a set as a list, in the same order as attrNames. */ @@ -1278,6 +1975,15 @@ static void prim_attrValues(EvalState & state, const Pos & pos, Value * * args, v.listElems()[i] = ((Attr *) v.listElems()[i])->value; } +static RegisterPrimOp primop_attrValues({ + .name = "__attrValues", + .args = {"set"}, + .doc = R"( + Return the values of the attributes in the set *set* in the order + corresponding to the sorted attribute names. + )", + .fun = prim_attrValues, +}); /* Dynamic version of the `.' operator. */ void prim_getAttr(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -1297,9 +2003,20 @@ void prim_getAttr(EvalState & state, const Pos & pos, Value * * args, Value & v) v = *i->value; } +static RegisterPrimOp primop_getAttr({ + .name = "__getAttr", + .args = {"s", "set"}, + .doc = R"( + `getAttr` returns the attribute named *s* from *set*. Evaluation + aborts if the attribute doesn’t exist. This is a dynamic version of + the `.` operator, since *s* is an expression rather than an + identifier. + )", + .fun = prim_getAttr, +}); /* Return position information of the specified attribute. */ -void prim_unsafeGetAttrPos(EvalState & state, const Pos & pos, Value * * args, Value & v) +static void prim_unsafeGetAttrPos(EvalState & state, const Pos & pos, Value * * args, Value & v) { string attr = state.forceStringNoCtx(*args[0], pos); state.forceAttrs(*args[1], pos); @@ -1310,6 +2027,11 @@ void prim_unsafeGetAttrPos(EvalState & state, const Pos & pos, Value * * args, V state.mkPos(v, i->pos); } +static RegisterPrimOp primop_unsafeGetAttrPos(RegisterPrimOp::Info { + .name = "__unsafeGetAttrPos", + .arity = 2, + .fun = prim_unsafeGetAttrPos, +}); /* Dynamic version of the `?' operator. */ static void prim_hasAttr(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -1319,6 +2041,16 @@ static void prim_hasAttr(EvalState & state, const Pos & pos, Value * * args, Val mkBool(v, args[1]->attrs->find(state.symbols.create(attr)) != args[1]->attrs->end()); } +static RegisterPrimOp primop_hasAttr({ + .name = "__hasAttr", + .args = {"s", "set"}, + .doc = R"( + `hasAttr` returns `true` if *set* has an attribute named *s*, and + `false` otherwise. This is a dynamic version of the `?` operator, + since *s* is an expression rather than an identifier. + )", + .fun = prim_hasAttr, +}); /* Determine whether the argument is a set. */ static void prim_isAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -1327,6 +2059,14 @@ static void prim_isAttrs(EvalState & state, const Pos & pos, Value * * args, Val mkBool(v, args[0]->type == tAttrs); } +static RegisterPrimOp primop_isAttrs({ + .name = "__isAttrs", + .args = {"e"}, + .doc = R"( + Return `true` if *e* evaluates to a set, and `false` otherwise. + )", + .fun = prim_isAttrs, +}); static void prim_removeAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -1350,6 +2090,21 @@ static void prim_removeAttrs(EvalState & state, const Pos & pos, Value * * args, } } +static RegisterPrimOp primop_removeAttrs({ + .name = "removeAttrs", + .args = {"set", "list"}, + .doc = R"( + Remove the attributes listed in *list* from *set*. The attributes + don’t have to exist in *set*. For instance, + + ```nix + removeAttrs { x = 1; y = 2; z = 3; } [ "a" "x" "z" ] + ``` + + evaluates to `{ y = 2; }`. + )", + .fun = prim_removeAttrs, +}); /* Builds a set from a list specifying (name, value) pairs. To be precise, a list [{name = "name1"; value = value1;} ... {name = @@ -1391,10 +2146,31 @@ static void prim_listToAttrs(EvalState & state, const Pos & pos, Value * * args, v.attrs->sort(); } +static RegisterPrimOp primop_listToAttrs({ + .name = "__listToAttrs", + .args = {"e"}, + .doc = R"( + Construct a set from a list specifying the names and values of each + attribute. Each element of the list should be a set consisting of a + string-valued attribute `name` specifying the name of the attribute, + and an attribute `value` specifying its value. Example: + + ```nix + builtins.listToAttrs + [ { name = "foo"; value = 123; } + { name = "bar"; value = 456; } + ] + ``` + + evaluates to + + ```nix + { foo = 123; bar = 456; } + ``` + )", + .fun = prim_listToAttrs, +}); -/* Return the right-biased intersection of two sets as1 and as2, - i.e. a set that contains every attribute from as2 that is also a - member of as1. */ static void prim_intersectAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v) { state.forceAttrs(*args[0], pos); @@ -1409,14 +2185,16 @@ static void prim_intersectAttrs(EvalState & state, const Pos & pos, Value * * ar } } +static RegisterPrimOp primop_intersectAttrs({ + .name = "__intersectAttrs", + .args = {"e1", "e2"}, + .doc = R"( + Return a set consisting of the attributes in the set *e2* that also + exist in the set *e1*. + )", + .fun = prim_intersectAttrs, +}); -/* Collect each attribute named `attr' from a list of attribute sets. - Sets that don't contain the named attribute are ignored. - - Example: - catAttrs "a" [{a = 1;} {b = 0;} {a = 2;}] - => [1 2] -*/ static void prim_catAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v) { Symbol attrName = state.symbols.create(state.forceStringNoCtx(*args[0], pos)); @@ -1438,23 +2216,30 @@ static void prim_catAttrs(EvalState & state, const Pos & pos, Value * * args, Va v.listElems()[n] = res[n]; } +static RegisterPrimOp primop_catAttrs({ + .name = "__catAttrs", + .args = {"attr", "list"}, + .doc = R"( + Collect each attribute named *attr* from a list of attribute + sets. Attrsets that don't contain the named attribute are + ignored. For example, -/* Return a set containing the names of the formal arguments expected - by the function `f'. The value of each attribute is a Boolean - denoting whether the corresponding argument has a default value. For instance, + ```nix + builtins.catAttrs "a" [{a = 1;} {b = 0;} {a = 2;}] + ``` - functionArgs ({ x, y ? 123}: ...) - => { x = false; y = true; } + evaluates to `[1 2]`. + )", + .fun = prim_catAttrs, +}); - "Formal argument" here refers to the attributes pattern-matched by - the function. Plain lambdas are not included, e.g. - - functionArgs (x: ...) - => { } -*/ static void prim_functionArgs(EvalState & state, const Pos & pos, Value * * args, Value & v) { state.forceValue(*args[0], pos); + if (args[0]->type == tPrimOpApp || args[0]->type == tPrimOp) { + state.mkAttrs(v, 0); + return; + } if (args[0]->type != tLambda) throw TypeError({ .hint = hintfmt("'functionArgs' requires a function"), @@ -1476,8 +2261,24 @@ static void prim_functionArgs(EvalState & state, const Pos & pos, Value * * args v.attrs->sort(); } +static RegisterPrimOp primop_functionArgs({ + .name = "__functionArgs", + .args = {"f"}, + .doc = R"( + Return a set containing the names of the formal arguments expected + by the function *f*. The value of each attribute is a Boolean + denoting whether the corresponding argument has a default value. For + instance, `functionArgs ({ x, y ? 123}: ...) = { x = false; y = + true; }`. -/* Apply a function to every element of an attribute set. */ + "Formal argument" here refers to the attributes pattern-matched by + the function. Plain lambdas are not included, e.g. `functionArgs (x: + ...) = { }`. + )", + .fun = prim_functionArgs, +}); + +/* */ static void prim_mapAttrs(EvalState & state, const Pos & pos, Value * * args, Value & v) { state.forceAttrs(*args[1], pos); @@ -1493,6 +2294,20 @@ static void prim_mapAttrs(EvalState & state, const Pos & pos, Value * * args, Va } } +static RegisterPrimOp primop_mapAttrs({ + .name = "__mapAttrs", + .args = {"f", "attrset"}, + .doc = R"( + Apply function *f* to every element of *attrset*. For example, + + ```nix + builtins.mapAttrs (name: value: value * 10) { a = 1; b = 2; } + ``` + + evaluates to `{ a = 10; b = 20; }`. + )", + .fun = prim_mapAttrs, +}); /************************************************************* @@ -1507,6 +2322,14 @@ static void prim_isList(EvalState & state, const Pos & pos, Value * * args, Valu mkBool(v, args[0]->isList()); } +static RegisterPrimOp primop_isList({ + .name = "__isList", + .args = {"e"}, + .doc = R"( + Return `true` if *e* evaluates to a list, and `false` otherwise. + )", + .fun = prim_isList, +}); static void elemAt(EvalState & state, const Pos & pos, Value & list, int n, Value & v) { @@ -1520,13 +2343,21 @@ static void elemAt(EvalState & state, const Pos & pos, Value & list, int n, Valu v = *list.listElems()[n]; } - /* Return the n-1'th element of a list. */ static void prim_elemAt(EvalState & state, const Pos & pos, Value * * args, Value & v) { elemAt(state, pos, *args[0], state.forceInt(*args[1], pos), v); } +static RegisterPrimOp primop_elemAt({ + .name = "__elemAt", + .args = {"xs", "n"}, + .doc = R"( + Return element *n* from the list *xs*. Elements are counted starting + from 0. A fatal error occurs if the index is out of bounds. + )", + .fun = prim_elemAt, +}); /* Return the first element of a list. */ static void prim_head(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -1534,6 +2365,16 @@ static void prim_head(EvalState & state, const Pos & pos, Value * * args, Value elemAt(state, pos, *args[0], 0, v); } +static RegisterPrimOp primop_head({ + .name = "__head", + .args = {"list"}, + .doc = R"( + Return the first element of a list; abort evaluation if the argument + isn’t a list or is an empty list. You can test whether a list is + empty by comparing it with `[]`. + )", + .fun = prim_head, +}); /* Return a list consisting of everything but the first element of a list. Warning: this function takes O(n) time, so you probably @@ -1552,6 +2393,21 @@ static void prim_tail(EvalState & state, const Pos & pos, Value * * args, Value v.listElems()[n] = args[0]->listElems()[n + 1]; } +static RegisterPrimOp primop_tail({ + .name = "__tail", + .args = {"list"}, + .doc = R"( + Return the second to last elements of a list; abort evaluation if + the argument isn’t a list or is an empty list. + + > **Warning** + > + > This function should generally be avoided since it's inefficient: + > unlike Haskell's `tail`, it takes O(n) time, so recursing over a + > list by repeatedly calling `tail` takes O(n^2) time. + )", + .fun = prim_tail, +}); /* Apply a function to every element of a list. */ static void prim_map(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -1565,6 +2421,21 @@ static void prim_map(EvalState & state, const Pos & pos, Value * * args, Value & *args[0], *args[1]->listElems()[n]); } +static RegisterPrimOp primop_map({ + .name = "map", + .args = {"f", "list"}, + .doc = R"( + Apply the function *f* to each element in the list *list*. For + example, + + ```nix + map (x: "foo" + x) [ "bar" "bla" "abc" ] + ``` + + evaluates to `[ "foobar" "foobla" "fooabc" ]`. + )", + .fun = prim_map, +}); /* Filter a list using a predicate; that is, return a list containing every element from the list for which the predicate function @@ -1596,6 +2467,15 @@ static void prim_filter(EvalState & state, const Pos & pos, Value * * args, Valu } } +static RegisterPrimOp primop_filter({ + .name = "__filter", + .args = {"f", "list"}, + .doc = R"( + Return a list consisting of the elements of *list* for which the + function *f* returns `true`. + )", + .fun = prim_filter, +}); /* Return true if a list contains a given element. */ static void prim_elem(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -1610,6 +2490,15 @@ static void prim_elem(EvalState & state, const Pos & pos, Value * * args, Value mkBool(v, res); } +static RegisterPrimOp primop_elem({ + .name = "__elem", + .args = {"x", "xs"}, + .doc = R"( + Return `true` if a value equal to *x* occurs in the list *xs*, and + `false` otherwise. + )", + .fun = prim_elem, +}); /* Concatenate a list of lists. */ static void prim_concatLists(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -1618,6 +2507,14 @@ static void prim_concatLists(EvalState & state, const Pos & pos, Value * * args, state.concatLists(v, args[0]->listSize(), args[0]->listElems(), pos); } +static RegisterPrimOp primop_concatLists({ + .name = "__concatLists", + .args = {"lists"}, + .doc = R"( + Concatenate a list of lists into a single list. + )", + .fun = prim_concatLists, +}); /* Return the length of a list. This is an O(1) time operation. */ static void prim_length(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -1626,6 +2523,14 @@ static void prim_length(EvalState & state, const Pos & pos, Value * * args, Valu mkInt(v, args[0]->listSize()); } +static RegisterPrimOp primop_length({ + .name = "__length", + .args = {"e"}, + .doc = R"( + Return the length of the list *e*. + )", + .fun = prim_length, +}); /* Reduce a list by applying a binary operator, from left to right. The operator is applied strictly. */ @@ -1650,6 +2555,18 @@ static void prim_foldlStrict(EvalState & state, const Pos & pos, Value * * args, } } +static RegisterPrimOp primop_foldlStrict({ + .name = "__foldl'", + .args = {"op", "nul", "list"}, + .doc = R"( + 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. + )", + .fun = prim_foldlStrict, +}); static void anyOrAll(bool any, EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -1675,12 +2592,30 @@ static void prim_any(EvalState & state, const Pos & pos, Value * * args, Value & anyOrAll(true, state, pos, args, v); } +static RegisterPrimOp primop_any({ + .name = "__any", + .args = {"pred", "list"}, + .doc = R"( + Return `true` if the function *pred* returns `true` for at least one + element of *list*, and `false` otherwise. + )", + .fun = prim_any, +}); static void prim_all(EvalState & state, const Pos & pos, Value * * args, Value & v) { anyOrAll(false, state, pos, args, v); } +static RegisterPrimOp primop_all({ + .name = "__all", + .args = {"pred", "list"}, + .doc = R"( + Return `true` if the function *pred* returns `true` for all elements + of *list*, and `false` otherwise. + )", + .fun = prim_all, +}); static void prim_genList(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -1701,6 +2636,21 @@ static void prim_genList(EvalState & state, const Pos & pos, Value * * args, Val } } +static RegisterPrimOp primop_genList({ + .name = "__genList", + .args = {"generator", "length"}, + .doc = R"( + Generate list of size *length*, with each element *i* equal to the + value returned by *generator* `i`. For example, + + ```nix + builtins.genList (x: x * x) 5 + ``` + + returns the list `[ 0 1 4 9 16 ]`. + )", + .fun = prim_genList, +}); static void prim_lessThan(EvalState & state, const Pos & pos, Value * * args, Value & v); @@ -1736,6 +2686,26 @@ static void prim_sort(EvalState & state, const Pos & pos, Value * * args, Value std::stable_sort(v.listElems(), v.listElems() + len, comparator); } +static RegisterPrimOp primop_sort({ + .name = "__sort", + .args = {"comparator", "list"}, + .doc = R"( + Return *list* in sorted order. It repeatedly calls the function + *comparator* with two elements. The comparator should return `true` + if the first element is less than the second, and `false` otherwise. + For example, + + ```nix + builtins.sort builtins.lessThan [ 483 249 526 147 42 77 ] + ``` + + produces the list `[ 42 77 147 249 483 526 ]`. + + This is a stable sort: it preserves the relative order of elements + deemed equal by the comparator. + )", + .fun = prim_sort, +}); static void prim_partition(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -1774,9 +2744,29 @@ static void prim_partition(EvalState & state, const Pos & pos, Value * * args, V v.attrs->sort(); } +static RegisterPrimOp primop_partition({ + .name = "__partition", + .args = {"pred", "list"}, + .doc = R"( + Given a predicate function *pred*, this function returns an + attrset containing a list named `right`, containing the elements + in *list* for which *pred* returned `true`, and a list named + `wrong`, containing the elements for which it returned + `false`. For example, + + ```nix + builtins.partition (x: x > 10) [1 23 9 3 42] + ``` + + evaluates to + + ```nix + { right = [ 23 42 ]; wrong = [ 1 9 3 ]; } + ``` + )", + .fun = prim_partition, +}); -/* concatMap = f: list: concatLists (map f list); */ -/* C++-version is to avoid allocating `mkApp', call `f' eagerly */ static void prim_concatMap(EvalState & state, const Pos & pos, Value * * args, Value & v) { state.forceFunction(*args[0], pos); @@ -1803,6 +2793,16 @@ static void prim_concatMap(EvalState & state, const Pos & pos, Value * * args, V } } +static RegisterPrimOp primop_concatMap({ + .name = "__concatMap", + .args = {"f", "list"}, + .doc = R"( + This function is equivalent to `builtins.concatLists (map f list)` + but is more efficient. + )", + .fun = prim_concatMap, +}); + /************************************************************* * Integer arithmetic @@ -1819,6 +2819,14 @@ static void prim_add(EvalState & state, const Pos & pos, Value * * args, Value & mkInt(v, state.forceInt(*args[0], pos) + state.forceInt(*args[1], pos)); } +static RegisterPrimOp primop_add({ + .name = "__add", + .args = {"e1", "e2"}, + .doc = R"( + Return the sum of the numbers *e1* and *e2*. + )", + .fun = prim_add, +}); static void prim_sub(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -1830,6 +2838,14 @@ static void prim_sub(EvalState & state, const Pos & pos, Value * * args, Value & mkInt(v, state.forceInt(*args[0], pos) - state.forceInt(*args[1], pos)); } +static RegisterPrimOp primop_sub({ + .name = "__sub", + .args = {"e1", "e2"}, + .doc = R"( + Return the difference between the numbers *e1* and *e2*. + )", + .fun = prim_sub, +}); static void prim_mul(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -1841,6 +2857,14 @@ static void prim_mul(EvalState & state, const Pos & pos, Value * * args, Value & mkInt(v, state.forceInt(*args[0], pos) * state.forceInt(*args[1], pos)); } +static RegisterPrimOp primop_mul({ + .name = "__mul", + .args = {"e1", "e2"}, + .doc = R"( + Return the product of the numbers *e1* and *e2*. + )", + .fun = prim_mul, +}); static void prim_div(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -1870,21 +2894,57 @@ static void prim_div(EvalState & state, const Pos & pos, Value * * args, Value & } } +static RegisterPrimOp primop_div({ + .name = "__div", + .args = {"e1", "e2"}, + .doc = R"( + Return the quotient of the numbers *e1* and *e2*. + )", + .fun = prim_div, +}); + static void prim_bitAnd(EvalState & state, const Pos & pos, Value * * args, Value & v) { mkInt(v, state.forceInt(*args[0], pos) & state.forceInt(*args[1], pos)); } +static RegisterPrimOp primop_bitAnd({ + .name = "__bitAnd", + .args = {"e1", "e2"}, + .doc = R"( + Return the bitwise AND of the integers *e1* and *e2*. + )", + .fun = prim_bitAnd, +}); + static void prim_bitOr(EvalState & state, const Pos & pos, Value * * args, Value & v) { mkInt(v, state.forceInt(*args[0], pos) | state.forceInt(*args[1], pos)); } +static RegisterPrimOp primop_bitOr({ + .name = "__bitOr", + .args = {"e1", "e2"}, + .doc = R"( + Return the bitwise OR of the integers *e1* and *e2*. + )", + .fun = prim_bitOr, +}); + static void prim_bitXor(EvalState & state, const Pos & pos, Value * * args, Value & v) { mkInt(v, state.forceInt(*args[0], pos) ^ state.forceInt(*args[1], pos)); } +static RegisterPrimOp primop_bitXor({ + .name = "__bitXor", + .args = {"e1", "e2"}, + .doc = R"( + Return the bitwise XOR of the integers *e1* and *e2*. + )", + .fun = prim_bitXor, +}); + static void prim_lessThan(EvalState & state, const Pos & pos, Value * * args, Value & v) { state.forceValue(*args[0], pos); @@ -1893,6 +2953,17 @@ static void prim_lessThan(EvalState & state, const Pos & pos, Value * * args, Va mkBool(v, comp(args[0], args[1])); } +static RegisterPrimOp primop_lessThan({ + .name = "__lessThan", + .args = {"e1", "e2"}, + .doc = R"( + Return `true` if the number *e1* is less than the number *e2*, and + `false` otherwise. Evaluation aborts if either *e1* or *e2* does not + evaluate to a number. + )", + .fun = prim_lessThan, +}); + /************************************************************* * String manipulation @@ -1909,6 +2980,29 @@ static void prim_toString(EvalState & state, const Pos & pos, Value * * args, Va mkString(v, s, context); } +static RegisterPrimOp primop_toString({ + .name = "toString", + .args = {"e"}, + .doc = R"( + Convert the expression *e* to a string. *e* can be: + + - A string (in which case the string is returned unmodified). + + - A path (e.g., `toString /foo/bar` yields `"/foo/bar"`. + + - A set containing `{ __toString = self: ...; }`. + + - An integer. + + - A list, in which case the string representations of its elements + are joined with spaces. + + - A Boolean (`false` yields `""`, `true` yields `"1"`). + + - `null`, which yields the empty string. + )", + .fun = prim_toString, +}); /* `substring start len str' returns the substring of `str' starting at character position `min(start, stringLength str)' inclusive and @@ -1930,6 +3024,25 @@ static void prim_substring(EvalState & state, const Pos & pos, Value * * args, V mkString(v, (unsigned int) start >= s.size() ? "" : string(s, start, len), context); } +static RegisterPrimOp primop_substring({ + .name = "__substring", + .args = {"start", "len", "s"}, + .doc = R"( + Return the substring of *s* from character position *start* + (zero-based) up to but not including *start + len*. If *start* is + greater than the length of the string, an empty string is returned, + and if *start + len* lies beyond the end of the string, only the + substring up to the end of the string is returned. *start* must be + non-negative. For example, + + ```nix + builtins.substring 0 3 "nixos" + ``` + + evaluates to `"nix"`. + )", + .fun = prim_substring, +}); static void prim_stringLength(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -1938,6 +3051,15 @@ static void prim_stringLength(EvalState & state, const Pos & pos, Value * * args mkInt(v, s.size()); } +static RegisterPrimOp primop_stringLength({ + .name = "__stringLength", + .args = {"e"}, + .doc = R"( + Return the length of the string *e*. If *e* is not a string, + evaluation is aborted. + )", + .fun = prim_stringLength, +}); /* Return the cryptographic hash of a string in base-16. */ static void prim_hashString(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -1956,18 +3078,36 @@ static void prim_hashString(EvalState & state, const Pos & pos, Value * * args, mkString(v, hashString(*ht, s).to_string(Base16, false), context); } +static RegisterPrimOp primop_hashString({ + .name = "__hashString", + .args = {"type", "s"}, + .doc = R"( + Return a base-16 representation of the cryptographic hash of string + *s*. The hash algorithm specified by *type* must be one of `"md5"`, + `"sha1"`, `"sha256"` or `"sha512"`. + )", + .fun = prim_hashString, +}); + +struct RegexCache +{ + std::unordered_map cache; +}; + +std::shared_ptr makeRegexCache() +{ + return std::make_shared(); +} -/* Match a regular expression against a string and return either - ‘null’ or a list containing substring matches. */ void prim_match(EvalState & state, const Pos & pos, Value * * args, Value & v) { auto re = state.forceStringNoCtx(*args[0], pos); try { - auto regex = state.regexCache.find(re); - if (regex == state.regexCache.end()) - regex = state.regexCache.emplace(re, std::regex(re, std::regex::extended)).first; + auto regex = state.regexCache->cache.find(re); + if (regex == state.regexCache->cache.end()) + regex = state.regexCache->cache.emplace(re, std::regex(re, std::regex::extended)).first; PathSet context; const std::string str = state.forceString(*args[1], context, pos); @@ -2004,6 +3144,41 @@ void prim_match(EvalState & state, const Pos & pos, Value * * args, Value & v) } } +static RegisterPrimOp primop_match({ + .name = "__match", + .args = {"regex", "str"}, + .doc = R"s( + Returns a list if the [extended POSIX regular + expression](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04) + *regex* matches *str* precisely, otherwise returns `null`. Each item + in the list is a regex group. + + ```nix + builtins.match "ab" "abc" + ``` + + Evaluates to `null`. + + ```nix + builtins.match "abc" "abc" + ``` + + Evaluates to `[ ]`. + + ```nix + builtins.match "a(b)(c)" "abc" + ``` + + Evaluates to `[ "b" "c" ]`. + + ```nix + builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" " FOO " + ``` + + Evaluates to `[ "foo" ]`. + )s", + .fun = prim_match, +}); /* Split a string with a regular expression, and return a list of the non-matching parts interleaved by the lists of the matching groups. */ @@ -2077,8 +3252,44 @@ static void prim_split(EvalState & state, const Pos & pos, Value * * args, Value } } +static RegisterPrimOp primop_split({ + .name = "__split", + .args = {"regex", "str"}, + .doc = R"s( + Returns a list composed of non matched strings interleaved with the + lists of the [extended POSIX regular + expression](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04) + *regex* matches of *str*. Each item in the lists of matched + sequences is a regex group. -static void prim_concatStringSep(EvalState & state, const Pos & pos, Value * * args, Value & v) + ```nix + builtins.split "(a)b" "abc" + ``` + + Evaluates to `[ "" [ "a" ] "c" ]`. + + ```nix + builtins.split "([ac])" "abc" + ``` + + Evaluates to `[ "" [ "a" ] "b" [ "c" ] "" ]`. + + ```nix + builtins.split "(a)|(c)" "abc" + ``` + + Evaluates to `[ "" [ "a" null ] "b" [ null "c" ] "" ]`. + + ```nix + builtins.split "([[:upper:]]+)" " FOO " + ``` + + Evaluates to `[ " " [ "FOO" ] " " ]`. + )s", + .fun = prim_split, +}); + +static void prim_concatStringsSep(EvalState & state, const Pos & pos, Value * * args, Value & v) { PathSet context; @@ -2097,6 +3308,16 @@ static void prim_concatStringSep(EvalState & state, const Pos & pos, Value * * a mkString(v, res, context); } +static RegisterPrimOp primop_concatStringsSep({ + .name = "__concatStringsSep", + .args = {"separator", "list"}, + .doc = R"( + Concatenate a list of strings with a separator between each + element, e.g. `concatStringsSep "/" ["usr" "local" "bin"] == + "usr/local/bin"`. + )", + .fun = prim_concatStringsSep, +}); static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -2156,6 +3377,22 @@ static void prim_replaceStrings(EvalState & state, const Pos & pos, Value * * ar mkString(v, res, context); } +static RegisterPrimOp primop_replaceStrings({ + .name = "__replaceStrings", + .args = {"from", "to", "s"}, + .doc = R"( + Given string *s*, replace every occurrence of the strings in *from* + with the corresponding string in *to*. For example, + + ```nix + builtins.replaceStrings ["oo" "a"] ["a" "i"] "foobar" + ``` + + evaluates to `"fabir"`. + )", + .fun = prim_replaceStrings, +}); + /************************************************************* * Versions @@ -2172,6 +3409,19 @@ static void prim_parseDrvName(EvalState & state, const Pos & pos, Value * * args v.attrs->sort(); } +static RegisterPrimOp primop_parseDrvName({ + .name = "__parseDrvName", + .args = {"s"}, + .doc = R"( + Split the string *s* into a package name and version. The package + name is everything up to but not including the first dash followed + by a digit, and the version is everything following that dash. The + result is returned in a set `{ name, version }`. Thus, + `builtins.parseDrvName "nix-0.12pre12876"` returns `{ name = + "nix"; version = "0.12pre12876"; }`. + )", + .fun = prim_parseDrvName, +}); static void prim_compareVersions(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -2180,6 +3430,18 @@ static void prim_compareVersions(EvalState & state, const Pos & pos, Value * * a mkInt(v, compareVersions(version1, version2)); } +static RegisterPrimOp primop_compareVersions({ + .name = "__compareVersions", + .args = {"s1", "s2"}, + .doc = R"( + Compare two strings representing versions and return `-1` if + version *s1* is older than version *s2*, `0` if they are the same, + and `1` if *s1* is newer than *s2*. The version comparison + algorithm is the same as the one used by [`nix-env + -u`](../command-ref/nix-env.md#operation---upgrade). + )", + .fun = prim_compareVersions, +}); static void prim_splitVersion(EvalState & state, const Pos & pos, Value * * args, Value & v) { @@ -2200,6 +3462,17 @@ static void prim_splitVersion(EvalState & state, const Pos & pos, Value * * args } } +static RegisterPrimOp primop_splitVersion({ + .name = "__splitVersion", + .args = {"s"}, + .doc = R"( + Split a string representing a version into its components, by the + same version splitting logic underlying the version comparison in + [`nix-env -u`](../command-ref/nix-env.md#operation---upgrade). + )", + .fun = prim_splitVersion, +}); + /************************************************************* * Primop registration @@ -2213,7 +3486,20 @@ RegisterPrimOp::RegisterPrimOp(std::string name, size_t arity, PrimOpFun fun, std::optional requiredFeature) { if (!primOps) primOps = new PrimOps; - primOps->push_back({name, arity, fun, requiredFeature}); + primOps->push_back({ + .name = name, + .args = {}, + .arity = arity, + .requiredFeature = std::move(requiredFeature), + .fun = fun + }); +} + + +RegisterPrimOp::RegisterPrimOp(Info && info) +{ + if (!primOps) primOps = new PrimOps; + primOps->push_back(std::move(info)); } @@ -2237,15 +3523,6 @@ void EvalState::createBaseEnv() mkNull(v); addConstant("null", v); - auto vThrow = addPrimOp("throw", 1, prim_throw); - - auto addPurityError = [&](const std::string & name) { - Value * v2 = allocValue(); - mkString(*v2, fmt("'%s' is not allowed in pure evaluation mode", name)); - mkApp(v, *vThrow, *v2); - addConstant(name, v); - }; - if (!evalSettings.pureEval) { mkInt(v, time(0)); addConstant("__currentTime", v); @@ -2270,132 +3547,16 @@ void EvalState::createBaseEnv() addConstant("__langVersion", v); // Miscellaneous - auto vScopedImport = addPrimOp("scopedImport", 2, prim_scopedImport); - Value * v2 = allocValue(); - mkAttrs(*v2, 0); - mkApp(v, *vScopedImport, *v2); - forceValue(v); - addConstant("import", v); if (evalSettings.enableNativeCode) { addPrimOp("__importNative", 2, prim_importNative); addPrimOp("__exec", 1, prim_exec); } - addPrimOp("__typeOf", 1, prim_typeOf); - addPrimOp("isNull", 1, prim_isNull); - addPrimOp("__isFunction", 1, prim_isFunction); - addPrimOp("__isString", 1, prim_isString); - addPrimOp("__isInt", 1, prim_isInt); - addPrimOp("__isFloat", 1, prim_isFloat); - addPrimOp("__isBool", 1, prim_isBool); - addPrimOp("__isPath", 1, prim_isPath); - addPrimOp("__genericClosure", 1, prim_genericClosure); - addPrimOp("abort", 1, prim_abort); - addPrimOp("__addErrorContext", 2, prim_addErrorContext); - addPrimOp("__tryEval", 1, prim_tryEval); - addPrimOp("__getEnv", 1, prim_getEnv); - - // Strictness - addPrimOp("__seq", 2, prim_seq); - addPrimOp("__deepSeq", 2, prim_deepSeq); - - // Debugging - addPrimOp("__trace", 2, prim_trace); - - // Paths - addPrimOp("__toPath", 1, prim_toPath); - if (evalSettings.pureEval) - addPurityError("__storePath"); - else - addPrimOp("__storePath", 1, prim_storePath); - addPrimOp("__pathExists", 1, prim_pathExists); - addPrimOp("baseNameOf", 1, prim_baseNameOf); - addPrimOp("dirOf", 1, prim_dirOf); - addPrimOp("__readFile", 1, prim_readFile); - addPrimOp("__readDir", 1, prim_readDir); - addPrimOp("__findFile", 2, prim_findFile); - addPrimOp("__hashFile", 2, prim_hashFile); - - // Creating files - addPrimOp("__toXML", 1, prim_toXML); - addPrimOp("__toJSON", 1, prim_toJSON); - addPrimOp("__fromJSON", 1, prim_fromJSON); - addPrimOp("__toFile", 2, prim_toFile); - addPrimOp("__filterSource", 2, prim_filterSource); - addPrimOp("__path", 1, prim_path); - - // Sets - addPrimOp("__attrNames", 1, prim_attrNames); - addPrimOp("__attrValues", 1, prim_attrValues); - addPrimOp("__getAttr", 2, prim_getAttr); - addPrimOp("__unsafeGetAttrPos", 2, prim_unsafeGetAttrPos); - addPrimOp("__hasAttr", 2, prim_hasAttr); - addPrimOp("__isAttrs", 1, prim_isAttrs); - addPrimOp("removeAttrs", 2, prim_removeAttrs); - addPrimOp("__listToAttrs", 1, prim_listToAttrs); - addPrimOp("__intersectAttrs", 2, prim_intersectAttrs); - addPrimOp("__catAttrs", 2, prim_catAttrs); - addPrimOp("__functionArgs", 1, prim_functionArgs); - addPrimOp("__mapAttrs", 2, prim_mapAttrs); - - // Lists - addPrimOp("__isList", 1, prim_isList); - addPrimOp("__elemAt", 2, prim_elemAt); - addPrimOp("__head", 1, prim_head); - addPrimOp("__tail", 1, prim_tail); - addPrimOp("map", 2, prim_map); - addPrimOp("__filter", 2, prim_filter); - addPrimOp("__elem", 2, prim_elem); - addPrimOp("__concatLists", 1, prim_concatLists); - addPrimOp("__length", 1, prim_length); - addPrimOp("__foldl'", 3, prim_foldlStrict); - addPrimOp("__any", 2, prim_any); - addPrimOp("__all", 2, prim_all); - addPrimOp("__genList", 2, prim_genList); - addPrimOp("__sort", 2, prim_sort); - addPrimOp("__partition", 2, prim_partition); - addPrimOp("__concatMap", 2, prim_concatMap); - - // Integer arithmetic - addPrimOp("__add", 2, prim_add); - addPrimOp("__sub", 2, prim_sub); - addPrimOp("__mul", 2, prim_mul); - addPrimOp("__div", 2, prim_div); - addPrimOp("__bitAnd", 2, prim_bitAnd); - addPrimOp("__bitOr", 2, prim_bitOr); - addPrimOp("__bitXor", 2, prim_bitXor); - addPrimOp("__lessThan", 2, prim_lessThan); - - // String manipulation - addPrimOp("toString", 1, prim_toString); - addPrimOp("__substring", 3, prim_substring); - addPrimOp("__stringLength", 1, prim_stringLength); - addPrimOp("__hashString", 2, prim_hashString); - addPrimOp("__match", 2, prim_match); - addPrimOp("__split", 2, prim_split); - addPrimOp("__concatStringsSep", 2, prim_concatStringSep); - addPrimOp("__replaceStrings", 3, prim_replaceStrings); - - // Versions - addPrimOp("__parseDrvName", 1, prim_parseDrvName); - addPrimOp("__compareVersions", 2, prim_compareVersions); - addPrimOp("__splitVersion", 1, prim_splitVersion); - - // Derivations - addPrimOp("derivationStrict", 1, prim_derivationStrict); - addPrimOp("placeholder", 1, prim_placeholder); - - /* Add a wrapper around the derivation primop that computes the - `drvPath' and `outPath' attributes lazily. */ - string path = canonPath(settings.nixDataDir + "/nix/corepkgs/derivation.nix", true); - sDerivationNix = symbols.create(path); - evalFile(path, v); - addConstant("derivation", v); /* Add a value containing the current Nix expression search path. */ mkList(v, searchPath.size()); int n = 0; for (auto & i : searchPath) { - v2 = v.listElems()[n++] = allocValue(); + auto v2 = v.listElems()[n++] = allocValue(); mkAttrs(*v2, 2); mkString(*allocAttr(*v2, symbols.create("path")), i.second); mkString(*allocAttr(*v2, symbols.create("prefix")), i.first); @@ -2406,7 +3567,21 @@ void EvalState::createBaseEnv() if (RegisterPrimOp::primOps) for (auto & primOp : *RegisterPrimOp::primOps) if (!primOp.requiredFeature || settings.isExperimentalFeatureEnabled(*primOp.requiredFeature)) - addPrimOp(primOp.name, primOp.arity, primOp.primOp); + addPrimOp({ + .fun = primOp.fun, + .arity = std::max(primOp.args.size(), primOp.arity), + .name = symbols.create(primOp.name), + .args = std::move(primOp.args), + .doc = primOp.doc, + }); + + /* Add a wrapper around the derivation primop that computes the + `drvPath' and `outPath' attributes lazily. */ + sDerivationNix = symbols.create("//builtin/derivation.nix"); + eval(parse( + #include "primops/derivation.nix.gen.hh" + , foFile, sDerivationNix, "/", staticBaseEnv), v); + addConstant("derivation", v); /* Now that we've added all primops, sort the `builtins' set, because attribute lookups expect it to be sorted. */ diff --git a/src/libexpr/primops.hh b/src/libexpr/primops.hh index 75c460ecf..9d42d6539 100644 --- a/src/libexpr/primops.hh +++ b/src/libexpr/primops.hh @@ -1,3 +1,5 @@ +#pragma once + #include "eval.hh" #include @@ -10,9 +12,11 @@ struct RegisterPrimOp struct Info { std::string name; - size_t arity; - PrimOpFun primOp; + std::vector args; + size_t arity = 0; + const char * doc; std::optional requiredFeature; + PrimOpFun fun; }; typedef std::vector PrimOps; @@ -26,6 +30,8 @@ struct RegisterPrimOp size_t arity, PrimOpFun fun, std::optional requiredFeature = {}); + + RegisterPrimOp(Info && info); }; /* These primops are disabled without enableNativeCode, but plugins diff --git a/src/libexpr/primops/context.cc b/src/libexpr/primops/context.cc index dbb93bae6..b570fca31 100644 --- a/src/libexpr/primops/context.cc +++ b/src/libexpr/primops/context.cc @@ -11,7 +11,7 @@ static void prim_unsafeDiscardStringContext(EvalState & state, const Pos & pos, mkString(v, s, PathSet()); } -static RegisterPrimOp r1("__unsafeDiscardStringContext", 1, prim_unsafeDiscardStringContext); +static RegisterPrimOp primop_unsafeDiscardStringContext("__unsafeDiscardStringContext", 1, prim_unsafeDiscardStringContext); static void prim_hasContext(EvalState & state, const Pos & pos, Value * * args, Value & v) @@ -21,7 +21,7 @@ static void prim_hasContext(EvalState & state, const Pos & pos, Value * * args, mkBool(v, !context.empty()); } -static RegisterPrimOp r2("__hasContext", 1, prim_hasContext); +static RegisterPrimOp primop_hasContext("__hasContext", 1, prim_hasContext); /* Sometimes we want to pass a derivation path (i.e. pkg.drvPath) to a @@ -42,7 +42,7 @@ static void prim_unsafeDiscardOutputDependency(EvalState & state, const Pos & po mkString(v, s, context2); } -static RegisterPrimOp r3("__unsafeDiscardOutputDependency", 1, prim_unsafeDiscardOutputDependency); +static RegisterPrimOp primop_unsafeDiscardOutputDependency("__unsafeDiscardOutputDependency", 1, prim_unsafeDiscardOutputDependency); /* Extract the context of a string as a structured Nix value. @@ -127,7 +127,7 @@ static void prim_getContext(EvalState & state, const Pos & pos, Value * * args, v.attrs->sort(); } -static RegisterPrimOp r4("__getContext", 1, prim_getContext); +static RegisterPrimOp primop_getContext("__getContext", 1, prim_getContext); /* Append the given context to a given string. @@ -191,6 +191,6 @@ static void prim_appendContext(EvalState & state, const Pos & pos, Value * * arg mkString(v, orig, context); } -static RegisterPrimOp r5("__appendContext", 2, prim_appendContext); +static RegisterPrimOp primop_appendContext("__appendContext", 2, prim_appendContext); } diff --git a/corepkgs/derivation.nix b/src/libexpr/primops/derivation.nix similarity index 100% rename from corepkgs/derivation.nix rename to src/libexpr/primops/derivation.nix diff --git a/src/libexpr/primops/fetchGit.cc b/src/libexpr/primops/fetchGit.cc deleted file mode 100644 index 36b0db2bd..000000000 --- a/src/libexpr/primops/fetchGit.cc +++ /dev/null @@ -1,91 +0,0 @@ -#include "primops.hh" -#include "eval-inline.hh" -#include "store-api.hh" -#include "hash.hh" -#include "fetchers.hh" -#include "url.hh" - -namespace nix { - -static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Value & v) -{ - std::string url; - std::optional ref; - std::optional rev; - std::string name = "source"; - bool fetchSubmodules = false; - PathSet context; - - state.forceValue(*args[0]); - - if (args[0]->type == tAttrs) { - - state.forceAttrs(*args[0], pos); - - for (auto & attr : *args[0]->attrs) { - string n(attr.name); - if (n == "url") - url = state.coerceToString(*attr.pos, *attr.value, context, false, false); - else if (n == "ref") - ref = state.forceStringNoCtx(*attr.value, *attr.pos); - else if (n == "rev") - rev = Hash(state.forceStringNoCtx(*attr.value, *attr.pos), htSHA1); - else if (n == "name") - name = state.forceStringNoCtx(*attr.value, *attr.pos); - else if (n == "submodules") - fetchSubmodules = state.forceBool(*attr.value, *attr.pos); - else - throw EvalError({ - .hint = hintfmt("unsupported argument '%s' to 'fetchGit'", attr.name), - .errPos = *attr.pos - }); - } - - if (url.empty()) - throw EvalError({ - .hint = hintfmt("'url' argument required"), - .errPos = pos - }); - - } else - url = state.coerceToString(pos, *args[0], context, false, false); - - // FIXME: git externals probably can be used to bypass the URI - // whitelist. Ah well. - state.checkURI(url); - - if (evalSettings.pureEval && !rev) - throw Error("in pure evaluation mode, 'fetchGit' requires a Git revision"); - - fetchers::Attrs attrs; - attrs.insert_or_assign("type", "git"); - attrs.insert_or_assign("url", url.find("://") != std::string::npos ? url : "file://" + url); - if (ref) attrs.insert_or_assign("ref", *ref); - if (rev) attrs.insert_or_assign("rev", rev->gitRev()); - if (fetchSubmodules) attrs.insert_or_assign("submodules", true); - auto input = fetchers::inputFromAttrs(attrs); - - // FIXME: use name? - auto [tree, input2] = input->fetchTree(state.store); - - state.mkAttrs(v, 8); - auto storePath = state.store->printStorePath(tree.storePath); - mkString(*state.allocAttr(v, state.sOutPath), storePath, PathSet({storePath})); - // Backward compatibility: set 'rev' to - // 0000000000000000000000000000000000000000 for a dirty tree. - auto rev2 = input2->getRev().value_or(Hash(htSHA1)); - mkString(*state.allocAttr(v, state.symbols.create("rev")), rev2.gitRev()); - mkString(*state.allocAttr(v, state.symbols.create("shortRev")), rev2.gitShortRev()); - // Backward compatibility: set 'revCount' to 0 for a dirty tree. - mkInt(*state.allocAttr(v, state.symbols.create("revCount")), - tree.info.revCount.value_or(0)); - mkBool(*state.allocAttr(v, state.symbols.create("submodules")), fetchSubmodules); - v.attrs->sort(); - - if (state.allowedPaths) - state.allowedPaths->insert(tree.actualPath); -} - -static RegisterPrimOp r("fetchGit", 1, prim_fetchGit); - -} diff --git a/src/libexpr/primops/fetchMercurial.cc b/src/libexpr/primops/fetchMercurial.cc index 59166b777..a77035c16 100644 --- a/src/libexpr/primops/fetchMercurial.cc +++ b/src/libexpr/primops/fetchMercurial.cc @@ -3,8 +3,7 @@ #include "store-api.hh" #include "fetchers.hh" #include "url.hh" - -#include +#include "url-parts.hh" namespace nix { @@ -31,7 +30,7 @@ static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * ar // be both a revision or a branch/tag name. auto value = state.forceStringNoCtx(*attr.value, *attr.pos); if (std::regex_match(value, revRegex)) - rev = Hash(value, htSHA1); + rev = Hash::parseAny(value, htSHA1); else ref = value; } @@ -65,29 +64,29 @@ static void prim_fetchMercurial(EvalState & state, const Pos & pos, Value * * ar attrs.insert_or_assign("url", url.find("://") != std::string::npos ? url : "file://" + url); if (ref) attrs.insert_or_assign("ref", *ref); if (rev) attrs.insert_or_assign("rev", rev->gitRev()); - auto input = fetchers::inputFromAttrs(attrs); + auto input = fetchers::Input::fromAttrs(std::move(attrs)); // FIXME: use name - auto [tree, input2] = input->fetchTree(state.store); + auto [tree, input2] = input.fetch(state.store); state.mkAttrs(v, 8); auto storePath = state.store->printStorePath(tree.storePath); mkString(*state.allocAttr(v, state.sOutPath), storePath, PathSet({storePath})); - if (input2->getRef()) - mkString(*state.allocAttr(v, state.symbols.create("branch")), *input2->getRef()); + if (input2.getRef()) + mkString(*state.allocAttr(v, state.symbols.create("branch")), *input2.getRef()); // Backward compatibility: set 'rev' to // 0000000000000000000000000000000000000000 for a dirty tree. - auto rev2 = input2->getRev().value_or(Hash(htSHA1)); + auto rev2 = input2.getRev().value_or(Hash(htSHA1)); mkString(*state.allocAttr(v, state.symbols.create("rev")), rev2.gitRev()); mkString(*state.allocAttr(v, state.symbols.create("shortRev")), std::string(rev2.gitRev(), 0, 12)); - if (tree.info.revCount) - mkInt(*state.allocAttr(v, state.symbols.create("revCount")), *tree.info.revCount); + if (auto revCount = input2.getRevCount()) + mkInt(*state.allocAttr(v, state.symbols.create("revCount")), *revCount); v.attrs->sort(); if (state.allowedPaths) state.allowedPaths->insert(tree.actualPath); } -static RegisterPrimOp r("fetchMercurial", 1, prim_fetchMercurial); +static RegisterPrimOp r_fetchMercurial("fetchMercurial", 1, prim_fetchMercurial); } diff --git a/src/libexpr/primops/fetchTree.cc b/src/libexpr/primops/fetchTree.cc index 01d6ad8b0..7cd4d0fbf 100644 --- a/src/libexpr/primops/fetchTree.cc +++ b/src/libexpr/primops/fetchTree.cc @@ -3,6 +3,7 @@ #include "store-api.hh" #include "fetchers.hh" #include "filetransfer.hh" +#include "registry.hh" #include #include @@ -12,39 +13,73 @@ namespace nix { void emitTreeAttrs( EvalState & state, const fetchers::Tree & tree, - std::shared_ptr input, - Value & v) + const fetchers::Input & input, + Value & v, + bool emptyRevFallback) { + assert(input.isImmutable()); + state.mkAttrs(v, 8); auto storePath = state.store->printStorePath(tree.storePath); mkString(*state.allocAttr(v, state.sOutPath), storePath, PathSet({storePath})); - assert(tree.info.narHash); - mkString(*state.allocAttr(v, state.symbols.create("narHash")), - tree.info.narHash.to_string(SRI, true)); + // FIXME: support arbitrary input attributes. - if (input->getRev()) { - mkString(*state.allocAttr(v, state.symbols.create("rev")), input->getRev()->gitRev()); - mkString(*state.allocAttr(v, state.symbols.create("shortRev")), input->getRev()->gitShortRev()); + auto narHash = input.getNarHash(); + assert(narHash); + mkString(*state.allocAttr(v, state.symbols.create("narHash")), + narHash->to_string(SRI, true)); + + if (auto rev = input.getRev()) { + mkString(*state.allocAttr(v, state.symbols.create("rev")), rev->gitRev()); + mkString(*state.allocAttr(v, state.symbols.create("shortRev")), rev->gitShortRev()); + } else if (emptyRevFallback) { + // Backwards compat for `builtins.fetchGit`: dirty repos return an empty sha1 as rev + auto emptyHash = Hash(htSHA1); + mkString(*state.allocAttr(v, state.symbols.create("rev")), emptyHash.gitRev()); + mkString(*state.allocAttr(v, state.symbols.create("shortRev")), emptyHash.gitRev()); } - if (tree.info.revCount) - mkInt(*state.allocAttr(v, state.symbols.create("revCount")), *tree.info.revCount); + if (input.getType() == "git") + mkBool(*state.allocAttr(v, state.symbols.create("submodules")), maybeGetBoolAttr(input.attrs, "submodules").value_or(false)); - if (tree.info.lastModified) - mkString(*state.allocAttr(v, state.symbols.create("lastModified")), - fmt("%s", std::put_time(std::gmtime(&*tree.info.lastModified), "%Y%m%d%H%M%S"))); + if (auto revCount = input.getRevCount()) + mkInt(*state.allocAttr(v, state.symbols.create("revCount")), *revCount); + else if (emptyRevFallback) + mkInt(*state.allocAttr(v, state.symbols.create("revCount")), 0); + + if (auto lastModified = input.getLastModified()) { + mkInt(*state.allocAttr(v, state.symbols.create("lastModified")), *lastModified); + mkString(*state.allocAttr(v, state.symbols.create("lastModifiedDate")), + fmt("%s", std::put_time(std::gmtime(&*lastModified), "%Y%m%d%H%M%S"))); + } v.attrs->sort(); } -static void prim_fetchTree(EvalState & state, const Pos & pos, Value * * args, Value & v) +std::string fixURI(std::string uri, EvalState &state) { - settings.requireExperimentalFeature("flakes"); + state.checkURI(uri); + return uri.find("://") != std::string::npos ? uri : "file://" + uri; +} - std::shared_ptr input; +void addURI(EvalState &state, fetchers::Attrs &attrs, Symbol name, std::string v) +{ + string n(name); + attrs.emplace(name, n == "url" ? fixURI(v, state) : v); +} + +static void fetchTree( + EvalState &state, + const Pos &pos, + Value **args, + Value &v, + const std::optional type, + bool emptyRevFallback = false +) { + fetchers::Input input; PathSet context; state.forceValue(*args[0]); @@ -56,38 +91,68 @@ static void prim_fetchTree(EvalState & state, const Pos & pos, Value * * args, V for (auto & attr : *args[0]->attrs) { state.forceValue(*attr.value); - if (attr.value->type == tString) - attrs.emplace(attr.name, attr.value->string.s); + if (attr.value->type == tPath || attr.value->type == tString) + addURI( + state, + attrs, + attr.name, + state.coerceToString(*attr.pos, *attr.value, context, false, false) + ); + else if (attr.value->type == tString) + addURI(state, attrs, attr.name, attr.value->string.s); else if (attr.value->type == tBool) - attrs.emplace(attr.name, attr.value->boolean); + attrs.emplace(attr.name, fetchers::Explicit{attr.value->boolean}); + else if (attr.value->type == tInt) + attrs.emplace(attr.name, attr.value->integer); else - throw TypeError("fetchTree argument '%s' is %s while a string or Boolean is expected", + throw TypeError("fetchTree argument '%s' is %s while a string, Boolean or integer is expected", attr.name, showType(*attr.value)); } + if (type) + attrs.emplace("type", type.value()); + if (!attrs.count("type")) throw Error({ .hint = hintfmt("attribute 'type' is missing in call to 'fetchTree'"), .errPos = pos }); - input = fetchers::inputFromAttrs(attrs); - } else - input = fetchers::inputFromURL(state.coerceToString(pos, *args[0], context, false, false)); + input = fetchers::Input::fromAttrs(std::move(attrs)); + } else { + auto url = fixURI(state.coerceToString(pos, *args[0], context, false, false), state); - if (evalSettings.pureEval && !input->isImmutable()) - throw Error("in pure evaluation mode, 'fetchTree' requires an immutable input"); + if (type == "git") { + fetchers::Attrs attrs; + attrs.emplace("type", "git"); + attrs.emplace("url", url); + input = fetchers::Input::fromAttrs(std::move(attrs)); + } else { + input = fetchers::Input::fromURL(url); + } + } - // FIXME: use fetchOrSubstituteTree - auto [tree, input2] = input->fetchTree(state.store); + if (!evalSettings.pureEval && !input.isDirect()) + input = lookupInRegistries(state.store, input).first; + + if (evalSettings.pureEval && !input.isImmutable()) + throw Error("in pure evaluation mode, 'fetchTree' requires an immutable input, at %s", pos); + + auto [tree, input2] = input.fetch(state.store); if (state.allowedPaths) state.allowedPaths->insert(tree.actualPath); - emitTreeAttrs(state, tree, input2, v); + emitTreeAttrs(state, tree, input2, v, emptyRevFallback); } -static RegisterPrimOp r("fetchTree", 1, prim_fetchTree); +static void prim_fetchTree(EvalState & state, const Pos & pos, Value * * args, Value & v) +{ + settings.requireExperimentalFeature("flakes"); + fetchTree(state, pos, args, v, std::nullopt); +} + +static RegisterPrimOp primop_fetchTree("fetchTree", 1, prim_fetchTree); static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, const string & who, bool unpack, std::string name) @@ -136,7 +201,7 @@ static void fetch(EvalState & state, const Pos & pos, Value * * args, Value & v, auto storePath = unpack - ? fetchers::downloadTarball(state.store, *url, name, (bool) expectedHash).storePath + ? fetchers::downloadTarball(state.store, *url, name, (bool) expectedHash).first.storePath : fetchers::downloadFile(state.store, *url, name, (bool) expectedHash).storePath; auto path = state.store->toRealPath(storePath); @@ -161,12 +226,187 @@ static void prim_fetchurl(EvalState & state, const Pos & pos, Value * * args, Va fetch(state, pos, args, v, "fetchurl", false, ""); } +static RegisterPrimOp primop_fetchurl({ + .name = "__fetchurl", + .args = {"url"}, + .doc = R"( + Download the specified URL and return the path of the downloaded + file. This function is not available if [restricted evaluation + mode](../command-ref/conf-file.md) is enabled. + )", + .fun = prim_fetchurl, +}); + static void prim_fetchTarball(EvalState & state, const Pos & pos, Value * * args, Value & v) { fetch(state, pos, args, v, "fetchTarball", true, "source"); } -static RegisterPrimOp r2("__fetchurl", 1, prim_fetchurl); -static RegisterPrimOp r3("fetchTarball", 1, prim_fetchTarball); +static RegisterPrimOp primop_fetchTarball({ + .name = "fetchTarball", + .args = {"args"}, + .doc = R"( + Download the specified URL, unpack it and return the path of the + unpacked tree. The file must be a tape archive (`.tar`) compressed + with `gzip`, `bzip2` or `xz`. The top-level path component of the + files in the tarball is removed, so it is best if the tarball + contains a single directory at top level. The typical use of the + function is to obtain external Nix expression dependencies, such as + a particular version of Nixpkgs, e.g. + + ```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 + timeout either on the command line with `--option tarball-ttl number + 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. + + 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. + + ```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. + )", + .fun = prim_fetchTarball, +}); + +static void prim_fetchGit(EvalState &state, const Pos &pos, Value **args, Value &v) +{ + fetchTree(state, pos, args, v, "git", true); +} + +static RegisterPrimOp primop_fetchGit({ + .name = "fetchGit", + .args = {"args"}, + .doc = R"( + Fetch a path from git. *args* can be a URL, in which case the HEAD + of the repo at that URL is fetched. Otherwise, it can be an + attribute with the following attributes (all except `url` optional): + + - url + The URL of the repo. + + - name + The name of the directory the repo should be exported to in the + store. Defaults to the basename of the URL. + + - rev + The git revision to fetch. Defaults to the tip of `ref`. + + - ref + The git ref to look for the requested revision under. This is + often a branch or tag name. Defaults to `HEAD`. + + By default, the `ref` value is prefixed with `refs/heads/`. As + of Nix 2.3.0 Nix will not prefix `refs/heads/` if `ref` starts + with `refs/`. + + - submodules + A Boolean parameter that specifies whether submodules should be + checked out. Defaults to `false`. + + Here are some examples of how to use `fetchGit`. + + - To fetch a private repository over SSH: + + ```nix + builtins.fetchGit { + url = "git@github.com:my-secret/repository.git"; + ref = "master"; + rev = "adab8b916a45068c044658c4158d81878f9ed1c3"; + } + ``` + + - To fetch an arbitrary reference: + + ```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 + name in the `ref` attribute. + + However, if the revision you're looking for is in a future + branch for the non-default branch you will need to specify the + the `ref` attribute as well. + + ```nix + builtins.fetchGit { + url = "https://github.com/nixos/nix.git"; + rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452"; + ref = "1.11-maintenance"; + } + ``` + + > **Note** + > + > It is nice to always specify the branch which a revision + > belongs to. Without the branch being specified, the fetcher + > might fail if the default branch changes. Additionally, it can + > be confusing to try a commit from a non-default branch and see + > the fetch fail. If the branch is specified the fault is much + > more obvious. + + - If the revision you're looking for is in the default branch of + the git repository you may omit the `ref` attribute. + + ```nix + builtins.fetchGit { + url = "https://github.com/nixos/nix.git"; + rev = "841fcbd04755c7a2865c51c1e2d3b045976b7452"; + } + ``` + + - To fetch a specific tag: + + ```nix + builtins.fetchGit { + url = "https://github.com/nixos/nix.git"; + ref = "refs/tags/1.9"; + } + ``` + + - To fetch the latest version of a remote branch: + + ```nix + builtins.fetchGit { + url = "ssh://git@github.com/nixos/nix.git"; + ref = "master"; + } + ``` + + > **Note** + > + > Nix will refetch the branch in accordance with + > the option `tarball-ttl`. + + > **Note** + > + > This behavior is disabled in *Pure evaluation mode*. + )", + .fun = prim_fetchGit, +}); } diff --git a/src/libexpr/primops/fromTOML.cc b/src/libexpr/primops/fromTOML.cc index b00827a4b..77bff44ae 100644 --- a/src/libexpr/primops/fromTOML.cc +++ b/src/libexpr/primops/fromTOML.cc @@ -88,6 +88,6 @@ static void prim_fromTOML(EvalState & state, const Pos & pos, Value * * args, Va } } -static RegisterPrimOp r("fromTOML", 1, prim_fromTOML); +static RegisterPrimOp primop_fromTOML("fromTOML", 1, prim_fromTOML); } diff --git a/src/libexpr/symbol-table.hh b/src/libexpr/symbol-table.hh index 7ba5e1c14..4eb6dac81 100644 --- a/src/libexpr/symbol-table.hh +++ b/src/libexpr/symbol-table.hh @@ -28,6 +28,12 @@ public: return s == s2.s; } + // FIXME: remove + bool operator == (std::string_view s2) const + { + return s->compare(s2) == 0; + } + bool operator != (const Symbol & s2) const { return s != s2.s; @@ -68,9 +74,10 @@ private: Symbols symbols; public: - Symbol create(const string & s) + Symbol create(std::string_view s) { - std::pair res = symbols.insert(s); + // FIXME: avoid allocation if 's' already exists in the symbol table. + std::pair res = symbols.emplace(std::string(s)); return Symbol(&*res.first); } diff --git a/src/libexpr/value.hh b/src/libexpr/value.hh index 71025824e..fe11bb2ed 100644 --- a/src/libexpr/value.hh +++ b/src/libexpr/value.hh @@ -166,6 +166,13 @@ struct Value { return type == tList1 ? 1 : type == tList2 ? 2 : bigList.size; } + + /* Check whether forcing this value requires a trivial amount of + computation. In particular, function applications are + non-trivial. */ + bool isTrivial() const; + + std::vector> getContext(); }; diff --git a/src/libfetchers/attrs.cc b/src/libfetchers/attrs.cc index feb0a6085..1e59faa73 100644 --- a/src/libfetchers/attrs.cc +++ b/src/libfetchers/attrs.cc @@ -27,7 +27,7 @@ nlohmann::json attrsToJson(const Attrs & attrs) { nlohmann::json json; for (auto & attr : attrs) { - if (auto v = std::get_if(&attr.second)) { + if (auto v = std::get_if(&attr.second)) { json[attr.first] = *v; } else if (auto v = std::get_if(&attr.second)) { json[attr.first] = *v; @@ -55,16 +55,16 @@ std::string getStrAttr(const Attrs & attrs, const std::string & name) return *s; } -std::optional maybeGetIntAttr(const Attrs & attrs, const std::string & name) +std::optional maybeGetIntAttr(const Attrs & attrs, const std::string & name) { auto i = attrs.find(name); if (i == attrs.end()) return {}; - if (auto v = std::get_if(&i->second)) + if (auto v = std::get_if(&i->second)) return *v; throw Error("input attribute '%s' is not an integer", name); } -int64_t getIntAttr(const Attrs & attrs, const std::string & name) +uint64_t getIntAttr(const Attrs & attrs, const std::string & name) { auto s = maybeGetIntAttr(attrs, name); if (!s) @@ -76,8 +76,8 @@ std::optional maybeGetBoolAttr(const Attrs & attrs, const std::string & na { auto i = attrs.find(name); if (i == attrs.end()) return {}; - if (auto v = std::get_if(&i->second)) - return *v; + if (auto v = std::get_if>(&i->second)) + return v->t; throw Error("input attribute '%s' is not a Boolean", name); } @@ -93,7 +93,7 @@ std::map attrsToQuery(const Attrs & attrs) { std::map query; for (auto & attr : attrs) { - if (auto v = std::get_if(&attr.second)) { + if (auto v = std::get_if(&attr.second)) { query.insert_or_assign(attr.first, fmt("%d", *v)); } else if (auto v = std::get_if(&attr.second)) { query.insert_or_assign(attr.first, *v); diff --git a/src/libfetchers/attrs.hh b/src/libfetchers/attrs.hh index d6e0ae000..4b4630c80 100644 --- a/src/libfetchers/attrs.hh +++ b/src/libfetchers/attrs.hh @@ -13,9 +13,14 @@ namespace nix::fetchers { template struct Explicit { T t; + + bool operator ==(const Explicit & other) const + { + return t == other.t; + } }; -typedef std::variant> Attr; +typedef std::variant> Attr; typedef std::map Attrs; Attrs jsonToAttrs(const nlohmann::json & json); @@ -26,9 +31,9 @@ std::optional maybeGetStrAttr(const Attrs & attrs, const std::strin std::string getStrAttr(const Attrs & attrs, const std::string & name); -std::optional maybeGetIntAttr(const Attrs & attrs, const std::string & name); +std::optional maybeGetIntAttr(const Attrs & attrs, const std::string & name); -int64_t getIntAttr(const Attrs & attrs, const std::string & name); +uint64_t getIntAttr(const Attrs & attrs, const std::string & name); std::optional maybeGetBoolAttr(const Attrs & attrs, const std::string & name); diff --git a/src/libfetchers/fetchers.cc b/src/libfetchers/fetchers.cc index 9174c3de4..49851f7bc 100644 --- a/src/libfetchers/fetchers.cc +++ b/src/libfetchers/fetchers.cc @@ -5,71 +5,276 @@ namespace nix::fetchers { -std::unique_ptr>> inputSchemes = nullptr; +std::unique_ptr>> inputSchemes = nullptr; -void registerInputScheme(std::unique_ptr && inputScheme) +void registerInputScheme(std::shared_ptr && inputScheme) { - if (!inputSchemes) inputSchemes = std::make_unique>>(); + if (!inputSchemes) inputSchemes = std::make_unique>>(); inputSchemes->push_back(std::move(inputScheme)); } -std::unique_ptr inputFromURL(const ParsedURL & url) +Input Input::fromURL(const std::string & url) +{ + return fromURL(parseURL(url)); +} + +static void fixupInput(Input & input) +{ + // Check common attributes. + input.getType(); + input.getRef(); + if (input.getRev()) + input.immutable = true; + input.getRevCount(); + input.getLastModified(); + if (input.getNarHash()) + input.immutable = true; +} + +Input Input::fromURL(const ParsedURL & url) { for (auto & inputScheme : *inputSchemes) { auto res = inputScheme->inputFromURL(url); - if (res) return res; + if (res) { + res->scheme = inputScheme; + fixupInput(*res); + return std::move(*res); + } } + throw Error("input '%s' is unsupported", url.url); } -std::unique_ptr inputFromURL(const std::string & url) +Input Input::fromAttrs(Attrs && attrs) { - return inputFromURL(parseURL(url)); -} - -std::unique_ptr inputFromAttrs(const Attrs & attrs) -{ - auto attrs2(attrs); - attrs2.erase("narHash"); for (auto & inputScheme : *inputSchemes) { - auto res = inputScheme->inputFromAttrs(attrs2); + auto res = inputScheme->inputFromAttrs(attrs); if (res) { - if (auto narHash = maybeGetStrAttr(attrs, "narHash")) - // FIXME: require SRI hash. - res->narHash = newHashAllowEmpty(*narHash, {}); - return res; + res->scheme = inputScheme; + fixupInput(*res); + return std::move(*res); } } - throw Error("input '%s' is unsupported", attrsToJson(attrs)); + + Input input; + input.attrs = attrs; + fixupInput(input); + return input; +} + +ParsedURL Input::toURL() const +{ + if (!scheme) + throw Error("cannot show unsupported input '%s'", attrsToJson(attrs)); + return scheme->toURL(*this); +} + +std::string Input::toURLString(const std::map & extraQuery) const +{ + auto url = toURL(); + for (auto & attr : extraQuery) + url.query.insert(attr); + return url.to_string(); +} + +std::string Input::to_string() const +{ + return toURL().to_string(); } Attrs Input::toAttrs() const { - auto attrs = toAttrsInternal(); - if (narHash) - attrs.emplace("narHash", narHash->to_string(SRI, true)); - attrs.emplace("type", type()); return attrs; } -std::pair> Input::fetchTree(ref store) const +bool Input::hasAllInfo() const { - auto [tree, input] = fetchTreeInternal(store); + return getNarHash() && scheme && scheme->hasAllInfo(*this); +} + +bool Input::operator ==(const Input & other) const +{ + return attrs == other.attrs; +} + +bool Input::contains(const Input & other) const +{ + if (*this == other) return true; + auto other2(other); + other2.attrs.erase("ref"); + other2.attrs.erase("rev"); + if (*this == other2) return true; + return false; +} + +std::pair Input::fetch(ref store) const +{ + if (!scheme) + throw Error("cannot fetch unsupported input '%s'", attrsToJson(toAttrs())); + + /* The tree may already be in the Nix store, or it could be + substituted (which is often faster than fetching from the + original source). So check that. */ + if (hasAllInfo()) { + try { + auto storePath = computeStorePath(*store); + + store->ensurePath(storePath); + + debug("using substituted/cached input '%s' in '%s'", + to_string(), store->printStorePath(storePath)); + + auto actualPath = store->toRealPath(storePath); + + return {fetchers::Tree(std::move(actualPath), std::move(storePath)), *this}; + } catch (Error & e) { + debug("substitution of input '%s' failed: %s", to_string(), e.what()); + } + } + + auto [tree, input] = scheme->fetch(store, *this); if (tree.actualPath == "") tree.actualPath = store->toRealPath(tree.storePath); - if (!tree.info.narHash) - tree.info.narHash = store->queryPathInfo(tree.storePath)->narHash; + auto narHash = store->queryPathInfo(tree.storePath)->narHash; + input.attrs.insert_or_assign("narHash", narHash.to_string(SRI, true)); - if (input->narHash) - assert(input->narHash == tree.info.narHash); + if (auto prevNarHash = getNarHash()) { + if (narHash != *prevNarHash) + throw Error((unsigned int) 102, "NAR hash mismatch in input '%s' (%s), expected '%s', got '%s'", + to_string(), tree.actualPath, prevNarHash->to_string(SRI, true), narHash.to_string(SRI, true)); + } - if (narHash && narHash != input->narHash) - throw Error("NAR hash mismatch in input '%s' (%s), expected '%s', got '%s'", - to_string(), tree.actualPath, narHash->to_string(SRI, true), input->narHash->to_string(SRI, true)); + if (auto prevLastModified = getLastModified()) { + if (input.getLastModified() != prevLastModified) + throw Error("'lastModified' attribute mismatch in input '%s', expected %d", + input.to_string(), *prevLastModified); + } + + if (auto prevRevCount = getRevCount()) { + if (input.getRevCount() != prevRevCount) + throw Error("'revCount' attribute mismatch in input '%s', expected %d", + input.to_string(), *prevRevCount); + } + + input.immutable = true; + + assert(input.hasAllInfo()); return {std::move(tree), input}; } +Input Input::applyOverrides( + std::optional ref, + std::optional rev) const +{ + if (!scheme) return *this; + return scheme->applyOverrides(*this, ref, rev); +} + +void Input::clone(const Path & destDir) const +{ + assert(scheme); + scheme->clone(*this, destDir); +} + +std::optional Input::getSourcePath() const +{ + assert(scheme); + return scheme->getSourcePath(*this); +} + +void Input::markChangedFile( + std::string_view file, + std::optional commitMsg) const +{ + assert(scheme); + return scheme->markChangedFile(*this, file, commitMsg); +} + +StorePath Input::computeStorePath(Store & store) const +{ + auto narHash = getNarHash(); + if (!narHash) + throw Error("cannot compute store path for mutable input '%s'", to_string()); + return store.makeFixedOutputPath(FileIngestionMethod::Recursive, *narHash, "source"); +} + +std::string Input::getType() const +{ + return getStrAttr(attrs, "type"); +} + +std::optional Input::getNarHash() const +{ + if (auto s = maybeGetStrAttr(attrs, "narHash")) { + auto hash = s->empty() ? Hash(htSHA256) : Hash::parseSRI(*s); + if (hash.type != htSHA256) + throw UsageError("narHash must use SHA-256"); + return hash; + } + return {}; +} + +std::optional Input::getRef() const +{ + if (auto s = maybeGetStrAttr(attrs, "ref")) + return *s; + return {}; +} + +std::optional Input::getRev() const +{ + if (auto s = maybeGetStrAttr(attrs, "rev")) + return Hash::parseAny(*s, htSHA1); + return {}; +} + +std::optional Input::getRevCount() const +{ + if (auto n = maybeGetIntAttr(attrs, "revCount")) + return *n; + return {}; +} + +std::optional Input::getLastModified() const +{ + if (auto n = maybeGetIntAttr(attrs, "lastModified")) + return *n; + return {}; +} + +ParsedURL InputScheme::toURL(const Input & input) +{ + throw Error("don't know how to convert input '%s' to a URL", attrsToJson(input.attrs)); +} + +Input InputScheme::applyOverrides( + const Input & input, + std::optional ref, + std::optional rev) +{ + if (ref) + throw Error("don't know how to set branch/tag name of input '%s' to '%s'", input.to_string(), *ref); + if (rev) + throw Error("don't know how to set revision of input '%s' to '%s'", input.to_string(), rev->gitRev()); + return input; +} + +std::optional InputScheme::getSourcePath(const Input & input) +{ + return {}; +} + +void InputScheme::markChangedFile(const Input & input, std::string_view file, std::optional commitMsg) +{ + assert(false); +} + +void InputScheme::clone(const Input & input, const Path & destDir) +{ + throw Error("do not know how to clone input '%s'", input.to_string()); +} + } diff --git a/src/libfetchers/fetchers.hh b/src/libfetchers/fetchers.hh index 59a58ae67..e8ae59143 100644 --- a/src/libfetchers/fetchers.hh +++ b/src/libfetchers/fetchers.hh @@ -3,7 +3,6 @@ #include "types.hh" #include "hash.hh" #include "path.hh" -#include "tree-info.hh" #include "attrs.hh" #include "url.hh" @@ -13,73 +12,106 @@ namespace nix { class Store; } namespace nix::fetchers { -struct Input; - struct Tree { Path actualPath; StorePath storePath; - TreeInfo info; + Tree(Path && actualPath, StorePath && storePath) : actualPath(actualPath), storePath(std::move(storePath)) {} }; -struct Input : std::enable_shared_from_this +struct InputScheme; + +struct Input { - std::optional narHash; // FIXME: implement + friend struct InputScheme; - virtual std::string type() const = 0; + std::shared_ptr scheme; // note: can be null + Attrs attrs; + bool immutable = false; + bool direct = true; - virtual ~Input() { } +public: + static Input fromURL(const std::string & url); - virtual bool operator ==(const Input & other) const { return false; } + static Input fromURL(const ParsedURL & url); - /* Check whether this is a "direct" input, that is, not - one that goes through a registry. */ - virtual bool isDirect() const { return true; } + static Input fromAttrs(Attrs && attrs); - /* Check whether this is an "immutable" input, that is, - one that contains a commit hash or content hash. */ - virtual bool isImmutable() const { return (bool) narHash; } + ParsedURL toURL() const; - virtual bool contains(const Input & other) const { return false; } + std::string toURLString(const std::map & extraQuery = {}) const; - virtual std::optional getRef() const { return {}; } - - virtual std::optional getRev() const { return {}; } - - virtual ParsedURL toURL() const = 0; - - std::string to_string() const - { - return toURL().to_string(); - } + std::string to_string() const; Attrs toAttrs() const; - std::pair> fetchTree(ref store) const; + /* Check whether this is a "direct" input, that is, not + one that goes through a registry. */ + bool isDirect() const { return direct; } -private: + /* Check whether this is an "immutable" input, that is, + one that contains a commit hash or content hash. */ + bool isImmutable() const { return immutable; } - virtual std::pair> fetchTreeInternal(ref store) const = 0; + bool hasAllInfo() const; - virtual Attrs toAttrsInternal() const = 0; + bool operator ==(const Input & other) const; + + bool contains(const Input & other) const; + + std::pair fetch(ref store) const; + + Input applyOverrides( + std::optional ref, + std::optional rev) const; + + void clone(const Path & destDir) const; + + std::optional getSourcePath() const; + + void markChangedFile( + std::string_view file, + std::optional commitMsg) const; + + StorePath computeStorePath(Store & store) const; + + // Convenience functions for common attributes. + std::string getType() const; + std::optional getNarHash() const; + std::optional getRef() const; + std::optional getRev() const; + std::optional getRevCount() const; + std::optional getLastModified() const; }; struct InputScheme { - virtual ~InputScheme() { } + virtual ~InputScheme() + { } - virtual std::unique_ptr inputFromURL(const ParsedURL & url) = 0; + virtual std::optional inputFromURL(const ParsedURL & url) = 0; - virtual std::unique_ptr inputFromAttrs(const Attrs & attrs) = 0; + virtual std::optional inputFromAttrs(const Attrs & attrs) = 0; + + virtual ParsedURL toURL(const Input & input); + + virtual bool hasAllInfo(const Input & input) = 0; + + virtual Input applyOverrides( + const Input & input, + std::optional ref, + std::optional rev); + + virtual void clone(const Input & input, const Path & destDir); + + virtual std::optional getSourcePath(const Input & input); + + virtual void markChangedFile(const Input & input, std::string_view file, std::optional commitMsg); + + virtual std::pair fetch(ref store, const Input & input) = 0; }; -std::unique_ptr inputFromURL(const ParsedURL & url); - -std::unique_ptr inputFromURL(const std::string & url); - -std::unique_ptr inputFromAttrs(const Attrs & attrs); - -void registerInputScheme(std::unique_ptr && fetcher); +void registerInputScheme(std::shared_ptr && fetcher); struct DownloadFileResult { @@ -92,12 +124,14 @@ DownloadFileResult downloadFile( ref store, const std::string & url, const std::string & name, - bool immutable); + bool immutable, + const Headers & headers = {}); -Tree downloadTarball( +std::pair downloadTarball( ref store, const std::string & url, const std::string & name, - bool immutable); + bool immutable, + const Headers & headers = {}); } diff --git a/src/libfetchers/git.cc b/src/libfetchers/git.cc index 75ce5ee8b..a6411b02b 100644 --- a/src/libfetchers/git.cc +++ b/src/libfetchers/git.cc @@ -3,6 +3,7 @@ #include "globals.hh" #include "tarfile.hh" #include "store-api.hh" +#include "url-parts.hh" #include @@ -22,80 +23,152 @@ static bool isNotDotGitDirectory(const Path & path) return not std::regex_match(path, gitDirRegex); } -struct GitInput : Input +struct GitInputScheme : InputScheme { - ParsedURL url; - std::optional ref; - std::optional rev; - bool shallow = false; - bool submodules = false; - - GitInput(const ParsedURL & url) : url(url) - { } - - std::string type() const override { return "git"; } - - bool operator ==(const Input & other) const override + std::optional inputFromURL(const ParsedURL & url) override { - auto other2 = dynamic_cast(&other); - return - other2 - && url == other2->url - && rev == other2->rev - && ref == other2->ref; - } + if (url.scheme != "git" && + url.scheme != "git+http" && + url.scheme != "git+https" && + url.scheme != "git+ssh" && + url.scheme != "git+file") return {}; - bool isImmutable() const override - { - return (bool) rev || narHash; - } + auto url2(url); + if (hasPrefix(url2.scheme, "git+")) url2.scheme = std::string(url2.scheme, 4); + url2.query.clear(); - std::optional getRef() const override { return ref; } - - std::optional getRev() const override { return rev; } - - ParsedURL toURL() const override - { - ParsedURL url2(url); - if (url2.scheme != "git") url2.scheme = "git+" + url2.scheme; - if (rev) url2.query.insert_or_assign("rev", rev->gitRev()); - if (ref) url2.query.insert_or_assign("ref", *ref); - if (shallow) url2.query.insert_or_assign("shallow", "1"); - return url2; - } - - Attrs toAttrsInternal() const override - { Attrs attrs; - attrs.emplace("url", url.to_string()); - if (ref) - attrs.emplace("ref", *ref); - if (rev) - attrs.emplace("rev", rev->gitRev()); - if (shallow) - attrs.emplace("shallow", true); - if (submodules) - attrs.emplace("submodules", true); - return attrs; + attrs.emplace("type", "git"); + + for (auto &[name, value] : url.query) { + if (name == "rev" || name == "ref") + attrs.emplace(name, value); + else if (name == "shallow") + attrs.emplace(name, Explicit { value == "1" }); + else + url2.query.emplace(name, value); + } + + attrs.emplace("url", url2.to_string()); + + return inputFromAttrs(attrs); } - std::pair getActualUrl() const + std::optional inputFromAttrs(const Attrs & attrs) override + { + if (maybeGetStrAttr(attrs, "type") != "git") return {}; + + for (auto & [name, value] : attrs) + if (name != "type" && name != "url" && name != "ref" && name != "rev" && name != "shallow" && name != "submodules" && name != "lastModified" && name != "revCount" && name != "narHash") + throw Error("unsupported Git input attribute '%s'", name); + + parseURL(getStrAttr(attrs, "url")); + maybeGetBoolAttr(attrs, "shallow"); + maybeGetBoolAttr(attrs, "submodules"); + + if (auto ref = maybeGetStrAttr(attrs, "ref")) { + if (std::regex_search(*ref, badGitRefRegex)) + throw BadURL("invalid Git branch/tag name '%s'", *ref); + } + + Input input; + input.attrs = attrs; + return input; + } + + ParsedURL toURL(const Input & input) override + { + auto url = parseURL(getStrAttr(input.attrs, "url")); + if (url.scheme != "git") url.scheme = "git+" + url.scheme; + if (auto rev = input.getRev()) url.query.insert_or_assign("rev", rev->gitRev()); + if (auto ref = input.getRef()) url.query.insert_or_assign("ref", *ref); + if (maybeGetBoolAttr(input.attrs, "shallow").value_or(false)) + url.query.insert_or_assign("shallow", "1"); + return url; + } + + bool hasAllInfo(const Input & input) override + { + bool maybeDirty = !input.getRef(); + bool shallow = maybeGetBoolAttr(input.attrs, "shallow").value_or(false); + return + maybeGetIntAttr(input.attrs, "lastModified") + && (shallow || maybeDirty || maybeGetIntAttr(input.attrs, "revCount")); + } + + Input applyOverrides( + const Input & input, + std::optional ref, + std::optional rev) override + { + auto res(input); + if (rev) res.attrs.insert_or_assign("rev", rev->gitRev()); + if (ref) res.attrs.insert_or_assign("ref", *ref); + if (!res.getRef() && res.getRev()) + throw Error("Git input '%s' has a commit hash but no branch/tag name", res.to_string()); + return res; + } + + void clone(const Input & input, const Path & destDir) override + { + auto [isLocal, actualUrl] = getActualUrl(input); + + Strings args = {"clone"}; + + args.push_back(actualUrl); + + if (auto ref = input.getRef()) { + args.push_back("--branch"); + args.push_back(*ref); + } + + if (input.getRev()) throw UnimplementedError("cloning a specific revision is not implemented"); + + args.push_back(destDir); + + runProgram("git", true, args); + } + + std::optional getSourcePath(const Input & input) override + { + auto url = parseURL(getStrAttr(input.attrs, "url")); + if (url.scheme == "file" && !input.getRef() && !input.getRev()) + return url.path; + return {}; + } + + void markChangedFile(const Input & input, std::string_view file, std::optional commitMsg) override + { + auto sourcePath = getSourcePath(input); + assert(sourcePath); + + runProgram("git", true, + { "-C", *sourcePath, "add", "--force", "--intent-to-add", "--", std::string(file) }); + + if (commitMsg) + runProgram("git", true, + { "-C", *sourcePath, "commit", std::string(file), "-m", *commitMsg }); + } + + std::pair getActualUrl(const Input & input) const { // Don't clone file:// URIs (but otherwise treat them the // same as remote URIs, i.e. don't use the working tree or // HEAD). static bool forceHttp = getEnv("_NIX_FORCE_HTTP") == "1"; // for testing + auto url = parseURL(getStrAttr(input.attrs, "url")); bool isLocal = url.scheme == "file" && !forceHttp; return {isLocal, isLocal ? url.path : url.base}; } - std::pair> fetchTreeInternal(nix::ref store) const override + std::pair fetch(ref store, const Input & _input) override { auto name = "source"; - auto input = std::make_shared(*this); + Input input(_input); - assert(!rev || rev->type == htSHA1); + bool shallow = maybeGetBoolAttr(input.attrs, "shallow").value_or(false); + bool submodules = maybeGetBoolAttr(input.attrs, "submodules").value_or(false); std::string cacheType = "git"; if (shallow) cacheType += "-shallow"; @@ -106,39 +179,35 @@ struct GitInput : Input return Attrs({ {"type", cacheType}, {"name", name}, - {"rev", input->rev->gitRev()}, + {"rev", input.getRev()->gitRev()}, }); }; auto makeResult = [&](const Attrs & infoAttrs, StorePath && storePath) - -> std::pair> + -> std::pair { - assert(input->rev); - assert(!rev || rev == input->rev); + assert(input.getRev()); + assert(!_input.getRev() || _input.getRev() == input.getRev()); + if (!shallow) + input.attrs.insert_or_assign("revCount", getIntAttr(infoAttrs, "revCount")); + input.attrs.insert_or_assign("lastModified", getIntAttr(infoAttrs, "lastModified")); return { - Tree { - .actualPath = store->toRealPath(storePath), - .storePath = std::move(storePath), - .info = TreeInfo { - .revCount = shallow ? std::nullopt : std::optional(getIntAttr(infoAttrs, "revCount")), - .lastModified = getIntAttr(infoAttrs, "lastModified"), - }, - }, + Tree(store->toRealPath(storePath), std::move(storePath)), input }; }; - if (rev) { + if (input.getRev()) { if (auto res = getCache()->lookup(store, getImmutableAttrs())) return makeResult(res->first, std::move(res->second)); } - auto [isLocal, actualUrl_] = getActualUrl(); + auto [isLocal, actualUrl_] = getActualUrl(input); auto actualUrl = actualUrl_; // work around clang bug // If this is a local directory and no ref or revision is // given, then allow the use of an unclean working tree. - if (!input->ref && !input->rev && isLocal) { + if (!input.getRef() && !input.getRev() && isLocal) { bool clean = false; /* Check whether this repo has any commits. There are @@ -197,44 +266,44 @@ struct GitInput : Input auto storePath = store->addToStore("source", actualUrl, FileIngestionMethod::Recursive, htSHA256, filter); - auto tree = Tree { - .actualPath = store->printStorePath(storePath), - .storePath = std::move(storePath), - .info = TreeInfo { - // FIXME: maybe we should use the timestamp of the last - // modified dirty file? - .lastModified = haveCommits ? std::stoull(runProgram("git", true, { "-C", actualUrl, "log", "-1", "--format=%ct", "HEAD" })) : 0, - } - }; + // FIXME: maybe we should use the timestamp of the last + // modified dirty file? + input.attrs.insert_or_assign( + "lastModified", + haveCommits ? std::stoull(runProgram("git", true, { "-C", actualUrl, "log", "-1", "--format=%ct", "--no-show-signature", "HEAD" })) : 0); - return {std::move(tree), input}; + return { + Tree(store->printStorePath(storePath), std::move(storePath)), + input + }; } } - if (!input->ref) input->ref = isLocal ? readHead(actualUrl) : "master"; + if (!input.getRef()) input.attrs.insert_or_assign("ref", isLocal ? readHead(actualUrl) : "master"); Attrs mutableAttrs({ {"type", cacheType}, {"name", name}, {"url", actualUrl}, - {"ref", *input->ref}, + {"ref", *input.getRef()}, }); Path repoDir; if (isLocal) { - if (!input->rev) - input->rev = Hash(chomp(runProgram("git", true, { "-C", actualUrl, "rev-parse", *input->ref })), htSHA1); + if (!input.getRev()) + input.attrs.insert_or_assign("rev", + Hash::parseAny(chomp(runProgram("git", true, { "-C", actualUrl, "rev-parse", *input.getRef() })), htSHA1).gitRev()); repoDir = actualUrl; } else { if (auto res = getCache()->lookup(store, mutableAttrs)) { - auto rev2 = Hash(getStrAttr(res->first, "rev"), htSHA1); - if (!rev || rev == rev2) { - input->rev = rev2; + auto rev2 = Hash::parseAny(getStrAttr(res->first, "rev"), htSHA1); + if (!input.getRev() || input.getRev() == rev2) { + input.attrs.insert_or_assign("rev", rev2.gitRev()); return makeResult(res->first, std::move(res->second)); } } @@ -248,18 +317,18 @@ struct GitInput : Input } Path localRefFile = - input->ref->compare(0, 5, "refs/") == 0 - ? cacheDir + "/" + *input->ref - : cacheDir + "/refs/heads/" + *input->ref; + input.getRef()->compare(0, 5, "refs/") == 0 + ? cacheDir + "/" + *input.getRef() + : cacheDir + "/refs/heads/" + *input.getRef(); bool doFetch; time_t now = time(0); /* If a rev was specified, we need to fetch if it's not in the repo. */ - if (input->rev) { + if (input.getRev()) { try { - runProgram("git", true, { "-C", repoDir, "cat-file", "-e", input->rev->gitRev() }); + runProgram("git", true, { "-C", repoDir, "cat-file", "-e", input.getRev()->gitRev() }); doFetch = false; } catch (ExecError & e) { if (WIFEXITED(e.status)) { @@ -282,9 +351,10 @@ struct GitInput : Input // FIXME: git stderr messes up our progress indicator, so // we're using --quiet for now. Should process its stderr. try { - auto fetchRef = input->ref->compare(0, 5, "refs/") == 0 - ? *input->ref - : "refs/heads/" + *input->ref; + auto ref = input.getRef(); + auto fetchRef = ref->compare(0, 5, "refs/") == 0 + ? *ref + : "refs/heads/" + *ref; runProgram("git", true, { "-C", repoDir, "fetch", "--quiet", "--force", "--", actualUrl, fmt("%s:%s", fetchRef, fetchRef) }); } catch (Error & e) { if (!pathExists(localRefFile)) throw; @@ -300,8 +370,8 @@ struct GitInput : Input utimes(localRefFile.c_str(), times); } - if (!input->rev) - input->rev = Hash(chomp(readFile(localRefFile)), htSHA1); + if (!input.getRev()) + input.attrs.insert_or_assign("rev", Hash::parseAny(chomp(readFile(localRefFile)), htSHA1).gitRev()); } bool isShallow = chomp(runProgram("git", true, { "-C", repoDir, "rev-parse", "--is-shallow-repository" })) == "true"; @@ -311,7 +381,7 @@ struct GitInput : Input // FIXME: check whether rev is an ancestor of ref. - printTalkative("using revision %s of repo '%s'", input->rev->gitRev(), actualUrl); + printTalkative("using revision %s of repo '%s'", input.getRev()->gitRev(), actualUrl); /* Now that we know the ref, check again whether we have it in the store. */ @@ -333,7 +403,7 @@ struct GitInput : Input runProgram("git", true, { "-C", tmpDir, "fetch", "--quiet", "--force", "--update-head-ok", "--", repoDir, "refs/*:refs/*" }); - runProgram("git", true, { "-C", tmpDir, "checkout", "--quiet", input->rev->gitRev() }); + runProgram("git", true, { "-C", tmpDir, "checkout", "--quiet", input.getRev()->gitRev() }); runProgram("git", true, { "-C", tmpDir, "remote", "add", "origin", actualUrl }); runProgram("git", true, { "-C", tmpDir, "submodule", "--quiet", "update", "--init", "--recursive" }); @@ -342,7 +412,7 @@ struct GitInput : Input // FIXME: should pipe this, or find some better way to extract a // revision. auto source = sinkToSource([&](Sink & sink) { - RunOptions gitOptions("git", { "-C", repoDir, "archive", input->rev->gitRev() }); + RunOptions gitOptions("git", { "-C", repoDir, "archive", input.getRev()->gitRev() }); gitOptions.standardOut = &sink; runProgram2(gitOptions); }); @@ -352,18 +422,18 @@ struct GitInput : Input auto storePath = store->addToStore(name, tmpDir, FileIngestionMethod::Recursive, htSHA256, filter); - auto lastModified = std::stoull(runProgram("git", true, { "-C", repoDir, "log", "-1", "--format=%ct", input->rev->gitRev() })); + auto lastModified = std::stoull(runProgram("git", true, { "-C", repoDir, "log", "-1", "--format=%ct", "--no-show-signature", input.getRev()->gitRev() })); Attrs infoAttrs({ - {"rev", input->rev->gitRev()}, + {"rev", input.getRev()->gitRev()}, {"lastModified", lastModified}, }); if (!shallow) infoAttrs.insert_or_assign("revCount", - std::stoull(runProgram("git", true, { "-C", repoDir, "rev-list", "--count", input->rev->gitRev() }))); + std::stoull(runProgram("git", true, { "-C", repoDir, "rev-list", "--count", input.getRev()->gitRev() }))); - if (!this->rev) + if (!_input.getRev()) getCache()->add( store, mutableAttrs, @@ -382,60 +452,6 @@ struct GitInput : Input } }; -struct GitInputScheme : InputScheme -{ - std::unique_ptr inputFromURL(const ParsedURL & url) override - { - if (url.scheme != "git" && - url.scheme != "git+http" && - url.scheme != "git+https" && - url.scheme != "git+ssh" && - url.scheme != "git+file") return nullptr; - - auto url2(url); - if (hasPrefix(url2.scheme, "git+")) url2.scheme = std::string(url2.scheme, 4); - url2.query.clear(); - - Attrs attrs; - attrs.emplace("type", "git"); - - for (auto &[name, value] : url.query) { - if (name == "rev" || name == "ref") - attrs.emplace(name, value); - else - url2.query.emplace(name, value); - } - - attrs.emplace("url", url2.to_string()); - - return inputFromAttrs(attrs); - } - - std::unique_ptr inputFromAttrs(const Attrs & attrs) override - { - if (maybeGetStrAttr(attrs, "type") != "git") return {}; - - for (auto & [name, value] : attrs) - if (name != "type" && name != "url" && name != "ref" && name != "rev" && name != "shallow" && name != "submodules") - throw Error("unsupported Git input attribute '%s'", name); - - auto input = std::make_unique(parseURL(getStrAttr(attrs, "url"))); - if (auto ref = maybeGetStrAttr(attrs, "ref")) { - if (std::regex_search(*ref, badGitRefRegex)) - throw BadURL("invalid Git branch/tag name '%s'", *ref); - input->ref = *ref; - } - if (auto rev = maybeGetStrAttr(attrs, "rev")) - input->rev = Hash(*rev, htSHA1); - - input->shallow = maybeGetBoolAttr(attrs, "shallow").value_or(false); - - input->submodules = maybeGetBoolAttr(attrs, "submodules").value_or(false); - - return input; - } -}; - -static auto r1 = OnStartup([] { registerInputScheme(std::make_unique()); }); +static auto rGitInputScheme = OnStartup([] { registerInputScheme(std::make_unique()); }); } diff --git a/src/libfetchers/github.cc b/src/libfetchers/github.cc index 0bee1d6b3..92ff224f7 100644 --- a/src/libfetchers/github.cc +++ b/src/libfetchers/github.cc @@ -3,86 +3,180 @@ #include "fetchers.hh" #include "globals.hh" #include "store-api.hh" +#include "types.hh" +#include "url-parts.hh" +#include #include namespace nix::fetchers { -std::regex ownerRegex("[a-zA-Z][a-zA-Z0-9_-]*", std::regex::ECMAScript); -std::regex repoRegex("[a-zA-Z][a-zA-Z0-9_-]*", std::regex::ECMAScript); - -struct GitHubInput : Input +struct DownloadUrl { - std::string owner; - std::string repo; - std::optional ref; - std::optional rev; + std::string url; + Headers headers; +}; - std::string type() const override { return "github"; } +// A github or gitlab host +const static std::string hostRegexS = "[a-zA-Z0-9.]*"; // FIXME: check +std::regex hostRegex(hostRegexS, std::regex::ECMAScript); - bool operator ==(const Input & other) const override +struct GitArchiveInputScheme : InputScheme +{ + virtual std::string type() = 0; + + virtual std::optional> accessHeaderFromToken(const std::string & token) const = 0; + + std::optional inputFromURL(const ParsedURL & url) override { - auto other2 = dynamic_cast(&other); - return - other2 - && owner == other2->owner - && repo == other2->repo - && rev == other2->rev - && ref == other2->ref; + if (url.scheme != type()) return {}; + + auto path = tokenizeString>(url.path, "/"); + + std::optional rev; + std::optional ref; + std::optional host_url; + + if (path.size() == 2) { + } else if (path.size() == 3) { + if (std::regex_match(path[2], revRegex)) + rev = Hash::parseAny(path[2], htSHA1); + else if (std::regex_match(path[2], refRegex)) + ref = path[2]; + else + throw BadURL("in URL '%s', '%s' is not a commit hash or branch/tag name", url.url, path[2]); + } else + throw BadURL("URL '%s' is invalid", url.url); + + for (auto &[name, value] : url.query) { + if (name == "rev") { + if (rev) + throw BadURL("URL '%s' contains multiple commit hashes", url.url); + rev = Hash::parseAny(value, htSHA1); + } + else if (name == "ref") { + if (!std::regex_match(value, refRegex)) + throw BadURL("URL '%s' contains an invalid branch/tag name", url.url); + if (ref) + throw BadURL("URL '%s' contains multiple branch/tag names", url.url); + ref = value; + } + else if (name == "host") { + if (!std::regex_match(value, hostRegex)) + throw BadURL("URL '%s' contains an invalid instance host", url.url); + host_url = value; + } + // FIXME: barf on unsupported attributes + } + + if (ref && rev) + throw BadURL("URL '%s' contains both a commit hash and a branch/tag name %s %s", url.url, *ref, rev->gitRev()); + + Input input; + input.attrs.insert_or_assign("type", type()); + input.attrs.insert_or_assign("owner", path[0]); + input.attrs.insert_or_assign("repo", path[1]); + if (rev) input.attrs.insert_or_assign("rev", rev->gitRev()); + if (ref) input.attrs.insert_or_assign("ref", *ref); + if (host_url) input.attrs.insert_or_assign("host", *host_url); + + return input; } - bool isImmutable() const override + std::optional inputFromAttrs(const Attrs & attrs) override { - return (bool) rev || narHash; + if (maybeGetStrAttr(attrs, "type") != type()) return {}; + + for (auto & [name, value] : attrs) + if (name != "type" && name != "owner" && name != "repo" && name != "ref" && name != "rev" && name != "narHash" && name != "lastModified" && name != "host") + throw Error("unsupported input attribute '%s'", name); + + getStrAttr(attrs, "owner"); + getStrAttr(attrs, "repo"); + + Input input; + input.attrs = attrs; + return input; } - std::optional getRef() const override { return ref; } - - std::optional getRev() const override { return rev; } - - ParsedURL toURL() const override + ParsedURL toURL(const Input & input) override { + auto owner = getStrAttr(input.attrs, "owner"); + auto repo = getStrAttr(input.attrs, "repo"); + auto ref = input.getRef(); + auto rev = input.getRev(); auto path = owner + "/" + repo; assert(!(ref && rev)); if (ref) path += "/" + *ref; if (rev) path += "/" + rev->to_string(Base16, false); return ParsedURL { - .scheme = "github", + .scheme = type(), .path = path, }; } - Attrs toAttrsInternal() const override + bool hasAllInfo(const Input & input) override { - Attrs attrs; - attrs.emplace("owner", owner); - attrs.emplace("repo", repo); - if (ref) - attrs.emplace("ref", *ref); - if (rev) - attrs.emplace("rev", rev->gitRev()); - return attrs; + return input.getRev() && maybeGetIntAttr(input.attrs, "lastModified"); } - std::pair> fetchTreeInternal(nix::ref store) const override + Input applyOverrides( + const Input & _input, + std::optional ref, + std::optional rev) override { - auto rev = this->rev; - auto ref = this->ref.value_or("master"); - - if (!rev) { - auto url = fmt("https://api.github.com/repos/%s/%s/commits/%s", - owner, repo, ref); - auto json = nlohmann::json::parse( - readFile( - store->toRealPath( - downloadFile(store, url, "source", false).storePath))); - rev = Hash(std::string { json["sha"] }, htSHA1); - debug("HEAD revision for '%s' is %s", url, rev->gitRev()); + auto input(_input); + if (rev && ref) + throw BadURL("cannot apply both a commit hash (%s) and a branch/tag name ('%s') to input '%s'", + rev->gitRev(), *ref, input.to_string()); + if (rev) { + input.attrs.insert_or_assign("rev", rev->gitRev()); + input.attrs.erase("ref"); } + if (ref) { + input.attrs.insert_or_assign("ref", *ref); + input.attrs.erase("rev"); + } + return input; + } - auto input = std::make_shared(*this); - input->ref = {}; - input->rev = *rev; + std::optional getAccessToken(const std::string & host) const + { + auto tokens = settings.accessTokens.get(); + if (auto token = get(tokens, host)) + return *token; + return {}; + } + + Headers makeHeadersWithAuthTokens(const std::string & host) const + { + Headers headers; + auto accessToken = getAccessToken(host); + if (accessToken) { + auto hdr = accessHeaderFromToken(*accessToken); + if (hdr) + headers.push_back(*hdr); + else + warn("Unrecognized access token for host '%s'", host); + } + return headers; + } + + virtual Hash getRevFromRef(nix::ref store, const Input & input) const = 0; + + virtual DownloadUrl getDownloadUrl(const Input & input) const = 0; + + std::pair fetch(ref store, const Input & _input) override + { + Input input(_input); + + if (!maybeGetStrAttr(input.attrs, "ref")) input.attrs.insert_or_assign("ref", "HEAD"); + + auto rev = input.getRev(); + if (!rev) rev = getRevFromRef(store, input); + + input.attrs.erase("ref"); + input.attrs.insert_or_assign("rev", rev->gitRev()); Attrs immutableAttrs({ {"type", "git-tarball"}, @@ -90,36 +184,25 @@ struct GitHubInput : Input }); if (auto res = getCache()->lookup(store, immutableAttrs)) { + input.attrs.insert_or_assign("lastModified", getIntAttr(res->first, "lastModified")); return { - Tree{ - .actualPath = store->toRealPath(res->second), - .storePath = std::move(res->second), - .info = TreeInfo { - .lastModified = getIntAttr(res->first, "lastModified"), - }, - }, + Tree(store->toRealPath(res->second), std::move(res->second)), input }; } - // FIXME: use regular /archive URLs instead? api.github.com - // might have stricter rate limits. + auto url = getDownloadUrl(input); - auto url = fmt("https://api.github.com/repos/%s/%s/tarball/%s", - owner, repo, rev->to_string(Base16, false)); + auto [tree, lastModified] = downloadTarball(store, url.url, "source", true, url.headers); - std::string accessToken = settings.githubAccessToken.get(); - if (accessToken != "") - url += "?access_token=" + accessToken; - - auto tree = downloadTarball(store, url, "source", true); + input.attrs.insert_or_assign("lastModified", lastModified); getCache()->add( store, immutableAttrs, { {"rev", rev->gitRev()}, - {"lastModified", *tree.info.lastModified} + {"lastModified", lastModified} }, tree.storePath, true); @@ -128,68 +211,130 @@ struct GitHubInput : Input } }; -struct GitHubInputScheme : InputScheme +struct GitHubInputScheme : GitArchiveInputScheme { - std::unique_ptr inputFromURL(const ParsedURL & url) override + std::string type() override { return "github"; } + + std::optional> accessHeaderFromToken(const std::string & token) const override { - if (url.scheme != "github") return nullptr; - - auto path = tokenizeString>(url.path, "/"); - auto input = std::make_unique(); - - if (path.size() == 2) { - } else if (path.size() == 3) { - if (std::regex_match(path[2], revRegex)) - input->rev = Hash(path[2], htSHA1); - else if (std::regex_match(path[2], refRegex)) - input->ref = path[2]; - else - throw BadURL("in GitHub URL '%s', '%s' is not a commit hash or branch/tag name", url.url, path[2]); - } else - throw BadURL("GitHub URL '%s' is invalid", url.url); - - for (auto &[name, value] : url.query) { - if (name == "rev") { - if (input->rev) - throw BadURL("GitHub URL '%s' contains multiple commit hashes", url.url); - input->rev = Hash(value, htSHA1); - } - else if (name == "ref") { - if (!std::regex_match(value, refRegex)) - throw BadURL("GitHub URL '%s' contains an invalid branch/tag name", url.url); - if (input->ref) - throw BadURL("GitHub URL '%s' contains multiple branch/tag names", url.url); - input->ref = value; - } - } - - if (input->ref && input->rev) - throw BadURL("GitHub URL '%s' contains both a commit hash and a branch/tag name", url.url); - - input->owner = path[0]; - input->repo = path[1]; - - return input; + // Github supports PAT/OAuth2 tokens and HTTP Basic + // Authentication. The former simply specifies the token, the + // latter can use the token as the password. Only the first + // is used here. See + // https://developer.github.com/v3/#authentication and + // https://docs.github.com/en/developers/apps/authorizing-oath-apps + return std::pair("Authorization", fmt("token %s", token)); } - std::unique_ptr inputFromAttrs(const Attrs & attrs) override + Hash getRevFromRef(nix::ref store, const Input & input) const override { - if (maybeGetStrAttr(attrs, "type") != "github") return {}; + auto host = maybeGetStrAttr(input.attrs, "host").value_or("github.com"); + auto url = fmt("https://api.%s/repos/%s/%s/commits/%s", // FIXME: check + host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"), *input.getRef()); - for (auto & [name, value] : attrs) - if (name != "type" && name != "owner" && name != "repo" && name != "ref" && name != "rev") - throw Error("unsupported GitHub input attribute '%s'", name); + Headers headers = makeHeadersWithAuthTokens(host); - auto input = std::make_unique(); - input->owner = getStrAttr(attrs, "owner"); - input->repo = getStrAttr(attrs, "repo"); - input->ref = maybeGetStrAttr(attrs, "ref"); - if (auto rev = maybeGetStrAttr(attrs, "rev")) - input->rev = Hash(*rev, htSHA1); - return input; + auto json = nlohmann::json::parse( + readFile( + store->toRealPath( + downloadFile(store, url, "source", false, headers).storePath))); + auto rev = Hash::parseAny(std::string { json["sha"] }, htSHA1); + debug("HEAD revision for '%s' is %s", url, rev.gitRev()); + return rev; + } + + DownloadUrl getDownloadUrl(const Input & input) const override + { + // FIXME: use regular /archive URLs instead? api.github.com + // might have stricter rate limits. + auto host = maybeGetStrAttr(input.attrs, "host").value_or("github.com"); + auto url = fmt("https://api.%s/repos/%s/%s/tarball/%s", // FIXME: check if this is correct for self hosted instances + host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"), + input.getRev()->to_string(Base16, false)); + + Headers headers = makeHeadersWithAuthTokens(host); + return DownloadUrl { url, headers }; + } + + void clone(const Input & input, const Path & destDir) override + { + auto host = maybeGetStrAttr(input.attrs, "host").value_or("github.com"); + Input::fromURL(fmt("git+ssh://git@%s/%s/%s.git", + host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"))) + .applyOverrides(input.getRef().value_or("HEAD"), input.getRev()) + .clone(destDir); } }; -static auto r1 = OnStartup([] { registerInputScheme(std::make_unique()); }); +struct GitLabInputScheme : GitArchiveInputScheme +{ + std::string type() override { return "gitlab"; } + + std::optional> accessHeaderFromToken(const std::string & token) const override + { + // Gitlab supports 4 kinds of authorization, two of which are + // relevant here: OAuth2 and PAT (Private Access Token). The + // user can indicate which token is used by specifying the + // token as :, where type is "OAuth2" or "PAT". + // If the is unrecognized, this will fall back to + // treating this simply has :. See + // https://docs.gitlab.com/12.10/ee/api/README.html#authentication + auto fldsplit = token.find_first_of(':'); + // n.b. C++20 would allow: if (token.starts_with("OAuth2:")) ... + if ("OAuth2" == token.substr(0, fldsplit)) + return std::make_pair("Authorization", fmt("Bearer %s", token.substr(fldsplit+1))); + if ("PAT" == token.substr(0, fldsplit)) + return std::make_pair("Private-token", token.substr(fldsplit+1)); + warn("Unrecognized GitLab token type %s", token.substr(0, fldsplit)); + return std::nullopt; + } + + Hash getRevFromRef(nix::ref store, const Input & input) const override + { + auto host = maybeGetStrAttr(input.attrs, "host").value_or("gitlab.com"); + // See rate limiting note below + auto url = fmt("https://%s/api/v4/projects/%s%%2F%s/repository/commits?ref_name=%s", + host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"), *input.getRef()); + + Headers headers = makeHeadersWithAuthTokens(host); + + auto json = nlohmann::json::parse( + readFile( + store->toRealPath( + downloadFile(store, url, "source", false, headers).storePath))); + auto rev = Hash::parseAny(std::string(json[0]["id"]), htSHA1); + debug("HEAD revision for '%s' is %s", url, rev.gitRev()); + return rev; + } + + DownloadUrl getDownloadUrl(const Input & input) const override + { + // This endpoint has a rate limit threshold that may be + // server-specific and vary based whether the user is + // authenticated via an accessToken or not, but the usual rate + // is 10 reqs/sec/ip-addr. See + // https://docs.gitlab.com/ee/user/gitlab_com/index.html#gitlabcom-specific-rate-limits + auto host = maybeGetStrAttr(input.attrs, "host").value_or("gitlab.com"); + auto url = fmt("https://%s/api/v4/projects/%s%%2F%s/repository/archive.tar.gz?sha=%s", + host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"), + input.getRev()->to_string(Base16, false)); + + Headers headers = makeHeadersWithAuthTokens(host); + return DownloadUrl { url, headers }; + } + + void clone(const Input & input, const Path & destDir) override + { + auto host = maybeGetStrAttr(input.attrs, "host").value_or("gitlab.com"); + // FIXME: get username somewhere + Input::fromURL(fmt("git+ssh://git@%s/%s/%s.git", + host, getStrAttr(input.attrs, "owner"), getStrAttr(input.attrs, "repo"))) + .applyOverrides(input.getRef().value_or("HEAD"), input.getRev()) + .clone(destDir); + } +}; + +static auto rGitHubInputScheme = OnStartup([] { registerInputScheme(std::make_unique()); }); +static auto rGitLabInputScheme = OnStartup([] { registerInputScheme(std::make_unique()); }); } diff --git a/src/libfetchers/indirect.cc b/src/libfetchers/indirect.cc new file mode 100644 index 000000000..10e59919a --- /dev/null +++ b/src/libfetchers/indirect.cc @@ -0,0 +1,105 @@ +#include "fetchers.hh" +#include "url-parts.hh" + +namespace nix::fetchers { + +std::regex flakeRegex("[a-zA-Z][a-zA-Z0-9_-]*", std::regex::ECMAScript); + +struct IndirectInputScheme : InputScheme +{ + std::optional inputFromURL(const ParsedURL & url) override + { + if (url.scheme != "flake") return {}; + + auto path = tokenizeString>(url.path, "/"); + + std::optional rev; + std::optional ref; + + if (path.size() == 1) { + } else if (path.size() == 2) { + if (std::regex_match(path[1], revRegex)) + rev = Hash::parseAny(path[1], htSHA1); + else if (std::regex_match(path[1], refRegex)) + ref = path[1]; + else + throw BadURL("in flake URL '%s', '%s' is not a commit hash or branch/tag name", url.url, path[1]); + } else if (path.size() == 3) { + if (!std::regex_match(path[1], refRegex)) + throw BadURL("in flake URL '%s', '%s' is not a branch/tag name", url.url, path[1]); + ref = path[1]; + if (!std::regex_match(path[2], revRegex)) + throw BadURL("in flake URL '%s', '%s' is not a commit hash", url.url, path[2]); + rev = Hash::parseAny(path[2], htSHA1); + } else + throw BadURL("GitHub URL '%s' is invalid", url.url); + + std::string id = path[0]; + if (!std::regex_match(id, flakeRegex)) + throw BadURL("'%s' is not a valid flake ID", id); + + // FIXME: forbid query params? + + Input input; + input.direct = false; + input.attrs.insert_or_assign("type", "indirect"); + input.attrs.insert_or_assign("id", id); + if (rev) input.attrs.insert_or_assign("rev", rev->gitRev()); + if (ref) input.attrs.insert_or_assign("ref", *ref); + + return input; + } + + std::optional inputFromAttrs(const Attrs & attrs) override + { + if (maybeGetStrAttr(attrs, "type") != "indirect") return {}; + + for (auto & [name, value] : attrs) + if (name != "type" && name != "id" && name != "ref" && name != "rev" && name != "narHash") + throw Error("unsupported indirect input attribute '%s'", name); + + auto id = getStrAttr(attrs, "id"); + if (!std::regex_match(id, flakeRegex)) + throw BadURL("'%s' is not a valid flake ID", id); + + Input input; + input.direct = false; + input.attrs = attrs; + return input; + } + + ParsedURL toURL(const Input & input) override + { + ParsedURL url; + url.scheme = "flake"; + url.path = getStrAttr(input.attrs, "id"); + if (auto ref = input.getRef()) { url.path += '/'; url.path += *ref; }; + if (auto rev = input.getRev()) { url.path += '/'; url.path += rev->gitRev(); }; + return url; + } + + bool hasAllInfo(const Input & input) override + { + return false; + } + + Input applyOverrides( + const Input & _input, + std::optional ref, + std::optional rev) override + { + auto input(_input); + if (rev) input.attrs.insert_or_assign("rev", rev->gitRev()); + if (ref) input.attrs.insert_or_assign("ref", *ref); + return input; + } + + std::pair fetch(ref store, const Input & input) override + { + throw Error("indirect input '%s' cannot be fetched directly", input.to_string()); + } +}; + +static auto rIndirectInputScheme = OnStartup([] { registerInputScheme(std::make_unique()); }); + +} diff --git a/src/libfetchers/mercurial.cc b/src/libfetchers/mercurial.cc index 2e0d4bf4d..7d3d52751 100644 --- a/src/libfetchers/mercurial.cc +++ b/src/libfetchers/mercurial.cc @@ -3,6 +3,7 @@ #include "globals.hh" #include "tarfile.hh" #include "store-api.hh" +#include "url-parts.hh" #include @@ -10,76 +11,124 @@ using namespace std::string_literals; namespace nix::fetchers { -struct MercurialInput : Input +struct MercurialInputScheme : InputScheme { - ParsedURL url; - std::optional ref; - std::optional rev; - - MercurialInput(const ParsedURL & url) : url(url) - { } - - std::string type() const override { return "hg"; } - - bool operator ==(const Input & other) const override + std::optional inputFromURL(const ParsedURL & url) override { - auto other2 = dynamic_cast(&other); - return - other2 - && url == other2->url - && rev == other2->rev - && ref == other2->ref; + if (url.scheme != "hg+http" && + url.scheme != "hg+https" && + url.scheme != "hg+ssh" && + url.scheme != "hg+file") return {}; + + auto url2(url); + url2.scheme = std::string(url2.scheme, 3); + url2.query.clear(); + + Attrs attrs; + attrs.emplace("type", "hg"); + + for (auto &[name, value] : url.query) { + if (name == "rev" || name == "ref") + attrs.emplace(name, value); + else + url2.query.emplace(name, value); + } + + attrs.emplace("url", url2.to_string()); + + return inputFromAttrs(attrs); } - bool isImmutable() const override + std::optional inputFromAttrs(const Attrs & attrs) override { - return (bool) rev || narHash; + if (maybeGetStrAttr(attrs, "type") != "hg") return {}; + + for (auto & [name, value] : attrs) + if (name != "type" && name != "url" && name != "ref" && name != "rev" && name != "revCount" && name != "narHash") + throw Error("unsupported Mercurial input attribute '%s'", name); + + parseURL(getStrAttr(attrs, "url")); + + if (auto ref = maybeGetStrAttr(attrs, "ref")) { + if (!std::regex_match(*ref, refRegex)) + throw BadURL("invalid Mercurial branch/tag name '%s'", *ref); + } + + Input input; + input.attrs = attrs; + return input; } - std::optional getRef() const override { return ref; } - - std::optional getRev() const override { return rev; } - - ParsedURL toURL() const override + ParsedURL toURL(const Input & input) override { - ParsedURL url2(url); - url2.scheme = "hg+" + url2.scheme; - if (rev) url2.query.insert_or_assign("rev", rev->gitRev()); - if (ref) url2.query.insert_or_assign("ref", *ref); + auto url = parseURL(getStrAttr(input.attrs, "url")); + url.scheme = "hg+" + url.scheme; + if (auto rev = input.getRev()) url.query.insert_or_assign("rev", rev->gitRev()); + if (auto ref = input.getRef()) url.query.insert_or_assign("ref", *ref); return url; } - Attrs toAttrsInternal() const override + bool hasAllInfo(const Input & input) override { - Attrs attrs; - attrs.emplace("url", url.to_string()); - if (ref) - attrs.emplace("ref", *ref); - if (rev) - attrs.emplace("rev", rev->gitRev()); - return attrs; + // FIXME: ugly, need to distinguish between dirty and clean + // default trees. + return input.getRef() == "default" || maybeGetIntAttr(input.attrs, "revCount"); } - std::pair getActualUrl() const + Input applyOverrides( + const Input & input, + std::optional ref, + std::optional rev) override { + auto res(input); + if (rev) res.attrs.insert_or_assign("rev", rev->gitRev()); + if (ref) res.attrs.insert_or_assign("ref", *ref); + return res; + } + + std::optional getSourcePath(const Input & input) override + { + auto url = parseURL(getStrAttr(input.attrs, "url")); + if (url.scheme == "file" && !input.getRef() && !input.getRev()) + return url.path; + return {}; + } + + void markChangedFile(const Input & input, std::string_view file, std::optional commitMsg) override + { + auto sourcePath = getSourcePath(input); + assert(sourcePath); + + // FIXME: shut up if file is already tracked. + runProgram("hg", true, + { "add", *sourcePath + "/" + std::string(file) }); + + if (commitMsg) + runProgram("hg", true, + { "commit", *sourcePath + "/" + std::string(file), "-m", *commitMsg }); + } + + std::pair getActualUrl(const Input & input) const + { + auto url = parseURL(getStrAttr(input.attrs, "url")); bool isLocal = url.scheme == "file"; return {isLocal, isLocal ? url.path : url.base}; } - std::pair> fetchTreeInternal(nix::ref store) const override + std::pair fetch(ref store, const Input & _input) override { auto name = "source"; - auto input = std::make_shared(*this); + Input input(_input); - auto [isLocal, actualUrl_] = getActualUrl(); + auto [isLocal, actualUrl_] = getActualUrl(input); auto actualUrl = actualUrl_; // work around clang bug // FIXME: return lastModified. // FIXME: don't clone local repositories. - if (!input->ref && !input->rev && isLocal && pathExists(actualUrl + "/.hg")) { + if (!input.getRef() && !input.getRev() && isLocal && pathExists(actualUrl + "/.hg")) { bool clean = runProgram("hg", true, { "status", "-R", actualUrl, "--modified", "--added", "--removed" }) == ""; @@ -94,7 +143,7 @@ struct MercurialInput : Input if (settings.warnDirty) warn("Mercurial tree '%s' is unclean", actualUrl); - input->ref = chomp(runProgram("hg", true, { "branch", "-R", actualUrl })); + input.attrs.insert_or_assign("ref", chomp(runProgram("hg", true, { "branch", "-R", actualUrl }))); auto files = tokenizeString>( runProgram("hg", true, { "status", "-R", actualUrl, "--clean", "--modified", "--added", "--no-status", "--print0" }), "\0"s); @@ -116,60 +165,54 @@ struct MercurialInput : Input auto storePath = store->addToStore("source", actualUrl, FileIngestionMethod::Recursive, htSHA256, filter); - return {Tree { - .actualPath = store->printStorePath(storePath), - .storePath = std::move(storePath), - }, input}; + return { + Tree(store->printStorePath(storePath), std::move(storePath)), + input + }; } } - if (!input->ref) input->ref = "default"; + if (!input.getRef()) input.attrs.insert_or_assign("ref", "default"); auto getImmutableAttrs = [&]() { return Attrs({ {"type", "hg"}, {"name", name}, - {"rev", input->rev->gitRev()}, + {"rev", input.getRev()->gitRev()}, }); }; auto makeResult = [&](const Attrs & infoAttrs, StorePath && storePath) - -> std::pair> + -> std::pair { - assert(input->rev); - assert(!rev || rev == input->rev); + assert(input.getRev()); + assert(!_input.getRev() || _input.getRev() == input.getRev()); + input.attrs.insert_or_assign("revCount", getIntAttr(infoAttrs, "revCount")); return { - Tree{ - .actualPath = store->toRealPath(storePath), - .storePath = std::move(storePath), - .info = TreeInfo { - .revCount = getIntAttr(infoAttrs, "revCount"), - }, - }, + Tree(store->toRealPath(storePath), std::move(storePath)), input }; }; - if (input->rev) { + if (input.getRev()) { if (auto res = getCache()->lookup(store, getImmutableAttrs())) return makeResult(res->first, std::move(res->second)); } - assert(input->rev || input->ref); - auto revOrRef = input->rev ? input->rev->gitRev() : *input->ref; + auto revOrRef = input.getRev() ? input.getRev()->gitRev() : *input.getRef(); Attrs mutableAttrs({ {"type", "hg"}, {"name", name}, {"url", actualUrl}, - {"ref", *input->ref}, + {"ref", *input.getRef()}, }); if (auto res = getCache()->lookup(store, mutableAttrs)) { - auto rev2 = Hash(getStrAttr(res->first, "rev"), htSHA1); - if (!rev || rev == rev2) { - input->rev = rev2; + auto rev2 = Hash::parseAny(getStrAttr(res->first, "rev"), htSHA1); + if (!input.getRev() || input.getRev() == rev2) { + input.attrs.insert_or_assign("rev", rev2.gitRev()); return makeResult(res->first, std::move(res->second)); } } @@ -178,10 +221,10 @@ struct MercurialInput : Input /* If this is a commit hash that we already have, we don't have to pull again. */ - if (!(input->rev + if (!(input.getRev() && pathExists(cacheDir) && runProgram( - RunOptions("hg", { "log", "-R", cacheDir, "-r", input->rev->gitRev(), "--template", "1" }) + RunOptions("hg", { "log", "-R", cacheDir, "-r", input.getRev()->gitRev(), "--template", "1" }) .killStderr(true)).second == "1")) { Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Mercurial repository '%s'", actualUrl)); @@ -210,9 +253,9 @@ struct MercurialInput : Input runProgram("hg", true, { "log", "-R", cacheDir, "-r", revOrRef, "--template", "{node} {rev} {branch}" })); assert(tokens.size() == 3); - input->rev = Hash(tokens[0], htSHA1); + input.attrs.insert_or_assign("rev", Hash::parseAny(tokens[0], htSHA1).gitRev()); auto revCount = std::stoull(tokens[1]); - input->ref = tokens[2]; + input.attrs.insert_or_assign("ref", tokens[2]); if (auto res = getCache()->lookup(store, getImmutableAttrs())) return makeResult(res->first, std::move(res->second)); @@ -220,18 +263,18 @@ struct MercurialInput : Input Path tmpDir = createTempDir(); AutoDelete delTmpDir(tmpDir, true); - runProgram("hg", true, { "archive", "-R", cacheDir, "-r", input->rev->gitRev(), tmpDir }); + runProgram("hg", true, { "archive", "-R", cacheDir, "-r", input.getRev()->gitRev(), tmpDir }); deletePath(tmpDir + "/.hg_archival.txt"); auto storePath = store->addToStore(name, tmpDir); Attrs infoAttrs({ - {"rev", input->rev->gitRev()}, + {"rev", input.getRev()->gitRev()}, {"revCount", (int64_t) revCount}, }); - if (!this->rev) + if (!_input.getRev()) getCache()->add( store, mutableAttrs, @@ -250,54 +293,6 @@ struct MercurialInput : Input } }; -struct MercurialInputScheme : InputScheme -{ - std::unique_ptr inputFromURL(const ParsedURL & url) override - { - if (url.scheme != "hg+http" && - url.scheme != "hg+https" && - url.scheme != "hg+ssh" && - url.scheme != "hg+file") return nullptr; - - auto url2(url); - url2.scheme = std::string(url2.scheme, 3); - url2.query.clear(); - - Attrs attrs; - attrs.emplace("type", "hg"); - - for (auto &[name, value] : url.query) { - if (name == "rev" || name == "ref") - attrs.emplace(name, value); - else - url2.query.emplace(name, value); - } - - attrs.emplace("url", url2.to_string()); - - return inputFromAttrs(attrs); - } - - std::unique_ptr inputFromAttrs(const Attrs & attrs) override - { - if (maybeGetStrAttr(attrs, "type") != "hg") return {}; - - for (auto & [name, value] : attrs) - if (name != "type" && name != "url" && name != "ref" && name != "rev") - throw Error("unsupported Mercurial input attribute '%s'", name); - - auto input = std::make_unique(parseURL(getStrAttr(attrs, "url"))); - if (auto ref = maybeGetStrAttr(attrs, "ref")) { - if (!std::regex_match(*ref, refRegex)) - throw BadURL("invalid Mercurial branch/tag name '%s'", *ref); - input->ref = *ref; - } - if (auto rev = maybeGetStrAttr(attrs, "rev")) - input->rev = Hash(*rev, htSHA1); - return input; - } -}; - -static auto r1 = OnStartup([] { registerInputScheme(std::make_unique()); }); +static auto rMercurialInputScheme = OnStartup([] { registerInputScheme(std::make_unique()); }); } diff --git a/src/libfetchers/path.cc b/src/libfetchers/path.cc index ba2cc192e..bcb904c0d 100644 --- a/src/libfetchers/path.cc +++ b/src/libfetchers/path.cc @@ -3,65 +3,86 @@ namespace nix::fetchers { -struct PathInput : Input +struct PathInputScheme : InputScheme { - Path path; - - /* Allow the user to pass in "fake" tree info attributes. This is - useful for making a pinned tree work the same as the repository - from which is exported - (e.g. path:/nix/store/...-source?lastModified=1585388205&rev=b0c285...). */ - std::optional rev; - std::optional revCount; - std::optional lastModified; - - std::string type() const override { return "path"; } - - std::optional getRev() const override { return rev; } - - bool operator ==(const Input & other) const override + std::optional inputFromURL(const ParsedURL & url) override { - auto other2 = dynamic_cast(&other); - return - other2 - && path == other2->path - && rev == other2->rev - && revCount == other2->revCount - && lastModified == other2->lastModified; + if (url.scheme != "path") return {}; + + if (url.authority && *url.authority != "") + throw Error("path URL '%s' should not have an authority ('%s')", url.url, *url.authority); + + Input input; + input.attrs.insert_or_assign("type", "path"); + input.attrs.insert_or_assign("path", url.path); + + for (auto & [name, value] : url.query) + if (name == "rev" || name == "narHash") + input.attrs.insert_or_assign(name, value); + else if (name == "revCount" || name == "lastModified") { + uint64_t n; + if (!string2Int(value, n)) + throw Error("path URL '%s' has invalid parameter '%s'", url.to_string(), name); + input.attrs.insert_or_assign(name, n); + } + else + throw Error("path URL '%s' has unsupported parameter '%s'", url.to_string(), name); + + return input; } - bool isImmutable() const override + std::optional inputFromAttrs(const Attrs & attrs) override { - return (bool) narHash; + if (maybeGetStrAttr(attrs, "type") != "path") return {}; + + getStrAttr(attrs, "path"); + + for (auto & [name, value] : attrs) + /* Allow the user to pass in "fake" tree info + attributes. This is useful for making a pinned tree + work the same as the repository from which is exported + (e.g. path:/nix/store/...-source?lastModified=1585388205&rev=b0c285...). */ + if (name == "type" || name == "rev" || name == "revCount" || name == "lastModified" || name == "narHash" || name == "path") + // checked in Input::fromAttrs + ; + else + throw Error("unsupported path input attribute '%s'", name); + + Input input; + input.attrs = attrs; + return input; } - ParsedURL toURL() const override + ParsedURL toURL(const Input & input) override { - auto query = attrsToQuery(toAttrsInternal()); + auto query = attrsToQuery(input.attrs); query.erase("path"); + query.erase("type"); return ParsedURL { .scheme = "path", - .path = path, + .path = getStrAttr(input.attrs, "path"), .query = query, }; } - Attrs toAttrsInternal() const override + bool hasAllInfo(const Input & input) override { - Attrs attrs; - attrs.emplace("path", path); - if (rev) - attrs.emplace("rev", rev->gitRev()); - if (revCount) - attrs.emplace("revCount", *revCount); - if (lastModified) - attrs.emplace("lastModified", *lastModified); - return attrs; + return true; } - std::pair> fetchTreeInternal(nix::ref store) const override + std::optional getSourcePath(const Input & input) override { - auto input = std::make_shared(*this); + return getStrAttr(input.attrs, "path"); + } + + void markChangedFile(const Input & input, std::string_view file, std::optional commitMsg) override + { + // nothing to do + } + + std::pair fetch(ref store, const Input & input) override + { + auto path = getStrAttr(input.attrs, "path"); // FIXME: check whether access to 'path' is allowed. @@ -74,75 +95,13 @@ struct PathInput : Input // FIXME: try to substitute storePath. storePath = store->addToStore("source", path); - return - { - Tree { - .actualPath = store->toRealPath(*storePath), - .storePath = std::move(*storePath), - .info = TreeInfo { - .revCount = revCount, - .lastModified = lastModified - } - }, - input - }; - } - -}; - -struct PathInputScheme : InputScheme -{ - std::unique_ptr inputFromURL(const ParsedURL & url) override - { - if (url.scheme != "path") return nullptr; - - auto input = std::make_unique(); - input->path = url.path; - - for (auto & [name, value] : url.query) - if (name == "rev") - input->rev = Hash(value, htSHA1); - else if (name == "revCount") { - uint64_t revCount; - if (!string2Int(value, revCount)) - throw Error("path URL '%s' has invalid parameter '%s'", url.to_string(), name); - input->revCount = revCount; - } - else if (name == "lastModified") { - time_t lastModified; - if (!string2Int(value, lastModified)) - throw Error("path URL '%s' has invalid parameter '%s'", url.to_string(), name); - input->lastModified = lastModified; - } - else - throw Error("path URL '%s' has unsupported parameter '%s'", url.to_string(), name); - - return input; - } - - std::unique_ptr inputFromAttrs(const Attrs & attrs) override - { - if (maybeGetStrAttr(attrs, "type") != "path") return {}; - - auto input = std::make_unique(); - input->path = getStrAttr(attrs, "path"); - - for (auto & [name, value] : attrs) - if (name == "rev") - input->rev = Hash(getStrAttr(attrs, "rev"), htSHA1); - else if (name == "revCount") - input->revCount = getIntAttr(attrs, "revCount"); - else if (name == "lastModified") - input->lastModified = getIntAttr(attrs, "lastModified"); - else if (name == "type" || name == "path") - ; - else - throw Error("unsupported path input attribute '%s'", name); - - return input; + return { + Tree(store->toRealPath(*storePath), std::move(*storePath)), + input + }; } }; -static auto r1 = OnStartup([] { registerInputScheme(std::make_unique()); }); +static auto rPathInputScheme = OnStartup([] { registerInputScheme(std::make_unique()); }); } diff --git a/src/libfetchers/registry.cc b/src/libfetchers/registry.cc new file mode 100644 index 000000000..4367ee810 --- /dev/null +++ b/src/libfetchers/registry.cc @@ -0,0 +1,212 @@ +#include "registry.hh" +#include "fetchers.hh" +#include "util.hh" +#include "globals.hh" +#include "store-api.hh" + +#include + +namespace nix::fetchers { + +std::shared_ptr Registry::read( + const Path & path, RegistryType type) +{ + auto registry = std::make_shared(type); + + if (!pathExists(path)) + return std::make_shared(type); + + try { + + auto json = nlohmann::json::parse(readFile(path)); + + auto version = json.value("version", 0); + + if (version == 2) { + for (auto & i : json["flakes"]) { + auto toAttrs = jsonToAttrs(i["to"]); + Attrs extraAttrs; + auto j = toAttrs.find("dir"); + if (j != toAttrs.end()) { + extraAttrs.insert(*j); + toAttrs.erase(j); + } + auto exact = i.find("exact"); + registry->entries.push_back( + Entry { + .from = Input::fromAttrs(jsonToAttrs(i["from"])), + .to = Input::fromAttrs(std::move(toAttrs)), + .extraAttrs = extraAttrs, + .exact = exact != i.end() && exact.value() + }); + } + } + + else + throw Error("flake registry '%s' has unsupported version %d", path, version); + + } catch (nlohmann::json::exception & e) { + warn("cannot parse flake registry '%s': %s", path, e.what()); + } catch (Error & e) { + warn("cannot read flake registry '%s': %s", path, e.what()); + } + + return registry; +} + +void Registry::write(const Path & path) +{ + nlohmann::json arr; + for (auto & entry : entries) { + nlohmann::json obj; + obj["from"] = attrsToJson(entry.from.toAttrs()); + obj["to"] = attrsToJson(entry.to.toAttrs()); + if (!entry.extraAttrs.empty()) + obj["to"].update(attrsToJson(entry.extraAttrs)); + if (entry.exact) + obj["exact"] = true; + arr.emplace_back(std::move(obj)); + } + + nlohmann::json json; + json["version"] = 2; + json["flakes"] = std::move(arr); + + createDirs(dirOf(path)); + writeFile(path, json.dump(2)); +} + +void Registry::add( + const Input & from, + const Input & to, + const Attrs & extraAttrs) +{ + entries.emplace_back( + Entry { + .from = from, + .to = to, + .extraAttrs = extraAttrs + }); +} + +void Registry::remove(const Input & input) +{ + // FIXME: use C++20 std::erase. + for (auto i = entries.begin(); i != entries.end(); ) + if (i->from == input) + i = entries.erase(i); + else + ++i; +} + +static Path getSystemRegistryPath() +{ + return settings.nixConfDir + "/registry.json"; +} + +static std::shared_ptr getSystemRegistry() +{ + static auto systemRegistry = + Registry::read(getSystemRegistryPath(), Registry::System); + return systemRegistry; +} + +Path getUserRegistryPath() +{ + return getHome() + "/.config/nix/registry.json"; +} + +std::shared_ptr getUserRegistry() +{ + static auto userRegistry = + Registry::read(getUserRegistryPath(), Registry::User); + return userRegistry; +} + +static std::shared_ptr flagRegistry = + std::make_shared(Registry::Flag); + +std::shared_ptr getFlagRegistry() +{ + return flagRegistry; +} + +void overrideRegistry( + const Input & from, + const Input & to, + const Attrs & extraAttrs) +{ + flagRegistry->add(from, to, extraAttrs); +} + +static std::shared_ptr getGlobalRegistry(ref store) +{ + static auto reg = [&]() { + auto path = settings.flakeRegistry.get(); + + if (!hasPrefix(path, "/")) { + auto storePath = downloadFile(store, path, "flake-registry.json", false).storePath; + if (auto store2 = store.dynamic_pointer_cast()) + store2->addPermRoot(storePath, getCacheDir() + "/nix/flake-registry.json"); + path = store->toRealPath(storePath); + } + + return Registry::read(path, Registry::Global); + }(); + + return reg; +} + +Registries getRegistries(ref store) +{ + Registries registries; + registries.push_back(getFlagRegistry()); + registries.push_back(getUserRegistry()); + registries.push_back(getSystemRegistry()); + registries.push_back(getGlobalRegistry(store)); + return registries; +} + +std::pair lookupInRegistries( + ref store, + const Input & _input) +{ + Attrs extraAttrs; + int n = 0; + Input input(_input); + + restart: + + n++; + if (n > 100) throw Error("cycle detected in flake registry for '%s'", input.to_string()); + + for (auto & registry : getRegistries(store)) { + // FIXME: O(n) + for (auto & entry : registry->entries) { + if (entry.exact) { + if (entry.from == input) { + input = entry.to; + extraAttrs = entry.extraAttrs; + goto restart; + } + } else { + if (entry.from.contains(input)) { + input = entry.to.applyOverrides( + !entry.from.getRef() && input.getRef() ? input.getRef() : std::optional(), + !entry.from.getRev() && input.getRev() ? input.getRev() : std::optional()); + extraAttrs = entry.extraAttrs; + goto restart; + } + } + } + } + + if (!input.isDirect()) + throw Error("cannot find flake '%s' in the flake registries", input.to_string()); + + debug("looked up '%s' -> '%s'", _input.to_string(), input.to_string()); + + return {input, extraAttrs}; +} + +} diff --git a/src/libfetchers/registry.hh b/src/libfetchers/registry.hh new file mode 100644 index 000000000..1077af020 --- /dev/null +++ b/src/libfetchers/registry.hh @@ -0,0 +1,64 @@ +#pragma once + +#include "types.hh" +#include "fetchers.hh" + +namespace nix { class Store; } + +namespace nix::fetchers { + +struct Registry +{ + enum RegistryType { + Flag = 0, + User = 1, + System = 2, + Global = 3, + }; + + RegistryType type; + + struct Entry + { + Input from, to; + Attrs extraAttrs; + bool exact = false; + }; + + std::vector entries; + + Registry(RegistryType type) + : type(type) + { } + + static std::shared_ptr read( + const Path & path, RegistryType type); + + void write(const Path & path); + + void add( + const Input & from, + const Input & to, + const Attrs & extraAttrs); + + void remove(const Input & input); +}; + +typedef std::vector> Registries; + +std::shared_ptr getUserRegistry(); + +Path getUserRegistryPath(); + +Registries getRegistries(ref store); + +void overrideRegistry( + const Input & from, + const Input & to, + const Attrs & extraAttrs); + +std::pair lookupInRegistries( + ref store, + const Input & input); + +} diff --git a/src/libfetchers/tarball.cc b/src/libfetchers/tarball.cc index f5356f0af..8c0f20475 100644 --- a/src/libfetchers/tarball.cc +++ b/src/libfetchers/tarball.cc @@ -5,6 +5,7 @@ #include "store-api.hh" #include "archive.hh" #include "tarfile.hh" +#include "types.hh" namespace nix::fetchers { @@ -12,7 +13,8 @@ DownloadFileResult downloadFile( ref store, const std::string & url, const std::string & name, - bool immutable) + bool immutable, + const Headers & headers) { // FIXME: check store @@ -37,6 +39,7 @@ DownloadFileResult downloadFile( return useCached(); FileTransferRequest request(url); + request.headers = headers; if (cached) request.expectedETag = getStrAttr(cached->infoAttrs, "etag"); FileTransferResult res; @@ -67,8 +70,10 @@ DownloadFileResult downloadFile( StringSink sink; dumpString(*res.data, sink); auto hash = hashString(htSHA256, *res.data); - ValidPathInfo info(store->makeFixedOutputPath(FileIngestionMethod::Flat, hash, name)); - info.narHash = hashString(htSHA256, *sink.s); + ValidPathInfo info { + store->makeFixedOutputPath(FileIngestionMethod::Flat, hash, name), + hashString(htSHA256, *sink.s), + }; info.narSize = sink.s->size(); info.ca = FixedOutputHash { .method = FileIngestionMethod::Flat, @@ -105,11 +110,12 @@ DownloadFileResult downloadFile( }; } -Tree downloadTarball( +std::pair downloadTarball( ref store, const std::string & url, const std::string & name, - bool immutable) + bool immutable, + const Headers & headers) { Attrs inAttrs({ {"type", "tarball"}, @@ -120,15 +126,12 @@ Tree downloadTarball( auto cached = getCache()->lookupExpired(store, inAttrs); if (cached && !cached->expired) - return Tree { - .actualPath = store->toRealPath(cached->storePath), - .storePath = std::move(cached->storePath), - .info = TreeInfo { - .lastModified = getIntAttr(cached->infoAttrs, "lastModified"), - }, + return { + Tree(store->toRealPath(cached->storePath), std::move(cached->storePath)), + getIntAttr(cached->infoAttrs, "lastModified") }; - auto res = downloadFile(store, url, name, immutable); + auto res = downloadFile(store, url, name, immutable, headers); std::optional unpackedStorePath; time_t lastModified; @@ -160,119 +163,74 @@ Tree downloadTarball( *unpackedStorePath, immutable); - return Tree { - .actualPath = store->toRealPath(*unpackedStorePath), - .storePath = std::move(*unpackedStorePath), - .info = TreeInfo { - .lastModified = lastModified, - }, + return { + Tree(store->toRealPath(*unpackedStorePath), std::move(*unpackedStorePath)), + lastModified, }; } -struct TarballInput : Input -{ - ParsedURL url; - std::optional hash; - - TarballInput(const ParsedURL & url) : url(url) - { } - - std::string type() const override { return "tarball"; } - - bool operator ==(const Input & other) const override - { - auto other2 = dynamic_cast(&other); - return - other2 - && to_string() == other2->to_string() - && hash == other2->hash; - } - - bool isImmutable() const override - { - return hash || narHash; - } - - ParsedURL toURL() const override - { - auto url2(url); - // NAR hashes are preferred over file hashes since tar/zip files - // don't have a canonical representation. - if (narHash) - url2.query.insert_or_assign("narHash", narHash->to_string(SRI, true)); - else if (hash) - url2.query.insert_or_assign("hash", hash->to_string(SRI, true)); - return url2; - } - - Attrs toAttrsInternal() const override - { - Attrs attrs; - attrs.emplace("url", url.to_string()); - if (hash) - attrs.emplace("hash", hash->to_string(SRI, true)); - return attrs; - } - - std::pair> fetchTreeInternal(nix::ref store) const override - { - auto tree = downloadTarball(store, url.to_string(), "source", false); - - auto input = std::make_shared(*this); - input->narHash = store->queryPathInfo(tree.storePath)->narHash; - - return {std::move(tree), input}; - } -}; - struct TarballInputScheme : InputScheme { - std::unique_ptr inputFromURL(const ParsedURL & url) override + std::optional inputFromURL(const ParsedURL & url) override { - if (url.scheme != "file" && url.scheme != "http" && url.scheme != "https") return nullptr; + if (url.scheme != "file" && url.scheme != "http" && url.scheme != "https") return {}; if (!hasSuffix(url.path, ".zip") && !hasSuffix(url.path, ".tar") && !hasSuffix(url.path, ".tar.gz") && !hasSuffix(url.path, ".tar.xz") && !hasSuffix(url.path, ".tar.bz2")) - return nullptr; - - auto input = std::make_unique(url); - - auto hash = input->url.query.find("hash"); - if (hash != input->url.query.end()) { - // FIXME: require SRI hash. - input->hash = Hash(hash->second); - input->url.query.erase(hash); - } - - auto narHash = input->url.query.find("narHash"); - if (narHash != input->url.query.end()) { - // FIXME: require SRI hash. - input->narHash = Hash(narHash->second); - input->url.query.erase(narHash); - } + return {}; + Input input; + input.attrs.insert_or_assign("type", "tarball"); + input.attrs.insert_or_assign("url", url.to_string()); + auto narHash = url.query.find("narHash"); + if (narHash != url.query.end()) + input.attrs.insert_or_assign("narHash", narHash->second); return input; } - std::unique_ptr inputFromAttrs(const Attrs & attrs) override + std::optional inputFromAttrs(const Attrs & attrs) override { if (maybeGetStrAttr(attrs, "type") != "tarball") return {}; for (auto & [name, value] : attrs) - if (name != "type" && name != "url" && name != "hash") + if (name != "type" && name != "url" && /* name != "hash" && */ name != "narHash") throw Error("unsupported tarball input attribute '%s'", name); - auto input = std::make_unique(parseURL(getStrAttr(attrs, "url"))); - if (auto hash = maybeGetStrAttr(attrs, "hash")) - input->hash = newHashAllowEmpty(*hash, {}); - + Input input; + input.attrs = attrs; + //input.immutable = (bool) maybeGetStrAttr(input.attrs, "hash"); return input; } + + ParsedURL toURL(const Input & input) override + { + auto url = parseURL(getStrAttr(input.attrs, "url")); + // NAR hashes are preferred over file hashes since tar/zip files + // don't have a canonical representation. + if (auto narHash = input.getNarHash()) + url.query.insert_or_assign("narHash", narHash->to_string(SRI, true)); + /* + else if (auto hash = maybeGetStrAttr(input.attrs, "hash")) + url.query.insert_or_assign("hash", Hash(*hash).to_string(SRI, true)); + */ + return url; + } + + bool hasAllInfo(const Input & input) override + { + return true; + } + + std::pair fetch(ref store, const Input & input) override + { + auto tree = downloadTarball(store, getStrAttr(input.attrs, "url"), "source", false).first; + return {std::move(tree), input}; + } }; -static auto r1 = OnStartup([] { registerInputScheme(std::make_unique()); }); +static auto rTarballInputScheme = OnStartup([] { registerInputScheme(std::make_unique()); }); } diff --git a/src/libfetchers/tree-info.cc b/src/libfetchers/tree-info.cc deleted file mode 100644 index b2d8cfc8d..000000000 --- a/src/libfetchers/tree-info.cc +++ /dev/null @@ -1,14 +0,0 @@ -#include "tree-info.hh" -#include "store-api.hh" - -#include - -namespace nix::fetchers { - -StorePath TreeInfo::computeStorePath(Store & store) const -{ - assert(narHash); - return store.makeFixedOutputPath(FileIngestionMethod::Recursive, narHash, "source"); -} - -} diff --git a/src/libfetchers/tree-info.hh b/src/libfetchers/tree-info.hh deleted file mode 100644 index 2c7347281..000000000 --- a/src/libfetchers/tree-info.hh +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include "path.hh" -#include "hash.hh" - -#include - -namespace nix { class Store; } - -namespace nix::fetchers { - -struct TreeInfo -{ - Hash narHash; - std::optional revCount; - std::optional lastModified; - - bool operator ==(const TreeInfo & other) const - { - return - narHash == other.narHash - && revCount == other.revCount - && lastModified == other.lastModified; - } - - StorePath computeStorePath(Store & store) const; -}; - -} diff --git a/src/libmain/common-args.cc b/src/libmain/common-args.cc index 051668e53..3411e2d7a 100644 --- a/src/libmain/common-args.cc +++ b/src/libmain/common-args.cc @@ -28,21 +28,31 @@ MixCommonArgs::MixCommonArgs(const string & programName) addFlag({ .longName = "option", - .description = "set a Nix configuration option (overriding nix.conf)", + .description = "set a Nix configuration option (overriding `nix.conf`)", .labels = {"name", "value"}, .handler = {[](std::string name, std::string value) { try { globalConfig.set(name, value); } catch (UsageError & e) { - warn(e.what()); + if (!completions) + warn(e.what()); } }}, + .completer = [](size_t index, std::string_view prefix) { + if (index == 0) { + std::map settings; + globalConfig.getSettings(settings); + for (auto & s : settings) + if (hasPrefix(s.first, prefix)) + completions->insert(s.first); + } + } }); addFlag({ .longName = "log-format", - .description = "format of log output; \"raw\", \"internal-json\", \"bar\" " - "or \"bar-with-logs\"", + .description = "format of log output; `raw`, `internal-json`, `bar` " + "or `bar-with-logs`", .labels = {"format"}, .handler = {[](std::string format) { setLogFormat(format); }}, }); diff --git a/src/libmain/loggers.cc b/src/libmain/loggers.cc index fa18f991d..0a7291780 100644 --- a/src/libmain/loggers.cc +++ b/src/libmain/loggers.cc @@ -1,12 +1,13 @@ #include "loggers.hh" #include "progress-bar.hh" +#include "util.hh" namespace nix { LogFormat defaultLogFormat = LogFormat::raw; LogFormat parseLogFormat(const std::string & logFormatStr) { - if (logFormatStr == "raw") + if (logFormatStr == "raw" || getEnv("NIX_GET_COMPLETIONS")) return LogFormat::raw; else if (logFormatStr == "raw-with-logs") return LogFormat::rawWithLogs; diff --git a/src/libmain/progress-bar.cc b/src/libmain/progress-bar.cc index 3f7d99a1d..07b45b3b5 100644 --- a/src/libmain/progress-bar.cc +++ b/src/libmain/progress-bar.cc @@ -256,7 +256,7 @@ public: } else if (type == resBuildLogLine || type == resPostBuildLogLine) { - auto lastLine = trim(getS(fields, 0)); + auto lastLine = chomp(getS(fields, 0)); if (!lastLine.empty()) { auto i = state->its.find(act); assert(i != state->its.end()); @@ -362,7 +362,7 @@ public: auto width = getWindowSize().second; if (width <= 0) width = std::numeric_limits::max(); - writeToStderr("\r" + filterANSIEscapes(line, false, width) + "\e[K"); + writeToStderr("\r" + filterANSIEscapes(line, false, width) + ANSI_NORMAL + "\e[K"); } std::string getStatus(State & state) diff --git a/src/libmain/shared.cc b/src/libmain/shared.cc index 52718c231..2247aeca4 100644 --- a/src/libmain/shared.cc +++ b/src/libmain/shared.cc @@ -36,7 +36,7 @@ void printGCWarning() void printMissing(ref store, const std::vector & paths, Verbosity lvl) { - unsigned long long downloadSize, narSize; + uint64_t downloadSize, narSize; StorePathSet willBuild, willSubstitute, unknown; store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); printMissing(store, willBuild, willSubstitute, unknown, downloadSize, narSize, lvl); @@ -45,7 +45,7 @@ void printMissing(ref store, const std::vector & pa void printMissing(ref store, const StorePathSet & willBuild, const StorePathSet & willSubstitute, const StorePathSet & unknown, - unsigned long long downloadSize, unsigned long long narSize, Verbosity lvl) + uint64_t downloadSize, uint64_t narSize, Verbosity lvl) { if (!willBuild.empty()) { if (willBuild.size() == 1) @@ -277,6 +277,8 @@ void printVersion(const string & programName) #if HAVE_SODIUM cfg.push_back("signed-caches"); #endif + std::cout << "System type: " << settings.thisSystem << "\n"; + std::cout << "Additional system types: " << concatStringsSep(", ", settings.extraPlatforms.get()) << "\n"; std::cout << "Features: " << concatStringsSep(", ", cfg) << "\n"; std::cout << "System configuration file: " << settings.nixConfDir + "/nix.conf" << "\n"; std::cout << "User configuration files: " << @@ -384,18 +386,12 @@ RunPager::~RunPager() } -string showBytes(unsigned long long bytes) -{ - return (format("%.2f MiB") % (bytes / (1024.0 * 1024.0))).str(); -} - - PrintFreed::~PrintFreed() { if (show) - std::cout << format("%1% store paths deleted, %2% freed\n") - % results.paths.size() - % showBytes(results.bytesFreed); + std::cout << fmt("%d store paths deleted, %s freed\n", + results.paths.size(), + showBytes(results.bytesFreed)); } Exit::~Exit() { } diff --git a/src/libmain/shared.hh b/src/libmain/shared.hh index f558247c0..ffae5d796 100644 --- a/src/libmain/shared.hh +++ b/src/libmain/shared.hh @@ -47,7 +47,7 @@ void printMissing( void printMissing(ref store, const StorePathSet & willBuild, const StorePathSet & willSubstitute, const StorePathSet & unknown, - unsigned long long downloadSize, unsigned long long narSize, Verbosity lvl = lvlInfo); + uint64_t downloadSize, uint64_t narSize, Verbosity lvl = lvlInfo); string getArg(const string & opt, Strings::iterator & i, const Strings::iterator & end); @@ -110,7 +110,7 @@ extern volatile ::sig_atomic_t blockInt; /* GC helpers. */ -string showBytes(unsigned long long bytes); +string showBytes(uint64_t bytes); struct GCResults; diff --git a/src/libstore/binary-cache-store.cc b/src/libstore/binary-cache-store.cc index 9f52ddafa..f6224d6a0 100644 --- a/src/libstore/binary-cache-store.cc +++ b/src/libstore/binary-cache-store.cc @@ -11,17 +11,20 @@ #include "nar-accessor.hh" #include "json.hh" #include "thread-pool.hh" +#include "callback.hh" #include #include #include +#include #include namespace nix { BinaryCacheStore::BinaryCacheStore(const Params & params) - : Store(params) + : BinaryCacheStoreConfig(params) + , Store(params) { if (secretKeyFile != "") secretKey = std::unique_ptr(new SecretKey(readFile(secretKeyFile))); @@ -57,6 +60,13 @@ void BinaryCacheStore::init() } } +void BinaryCacheStore::upsertFile(const std::string & path, + std::string && data, + const std::string & mimeType) +{ + upsertFile(path, std::make_shared(std::move(data)), mimeType); +} + void BinaryCacheStore::getFile(const std::string & path, Callback> callback) noexcept { @@ -113,13 +123,71 @@ void BinaryCacheStore::writeNarInfo(ref narInfo) diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr(narInfo)); } -void BinaryCacheStore::addToStore(const ValidPathInfo & info, Source & narSource, - RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr accessor) +AutoCloseFD openFile(const Path & path) { - // FIXME: See if we can use the original source to reduce memory usage. - auto nar = make_ref(narSource.drain()); + auto fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (!fd) + throw SysError("opening file '%1%'", path); + return fd; +} - if (!repair && isValidPath(info.path)) return; +struct FileSource : FdSource +{ + AutoCloseFD fd2; + + FileSource(const Path & path) + : fd2(openFile(path)) + { + fd = fd2.get(); + } +}; + +ref BinaryCacheStore::addToStoreCommon( + Source & narSource, RepairFlag repair, CheckSigsFlag checkSigs, + std::function mkInfo) +{ + auto [fdTemp, fnTemp] = createTempFile(); + + AutoDelete autoDelete(fnTemp); + + auto now1 = std::chrono::steady_clock::now(); + + /* Read the NAR simultaneously into a CompressionSink+FileSink (to + write the compressed NAR to disk), into a HashSink (to get the + NAR hash), and into a NarAccessor (to get the NAR listing). */ + HashSink fileHashSink { htSHA256 }; + std::shared_ptr narAccessor; + HashSink narHashSink { htSHA256 }; + { + FdSink fileSink(fdTemp.get()); + TeeSink teeSinkCompressed { fileSink, fileHashSink }; + auto compressionSink = makeCompressionSink(compression, teeSinkCompressed); + TeeSink teeSinkUncompressed { *compressionSink, narHashSink }; + TeeSource teeSource { narSource, teeSinkUncompressed }; + narAccessor = makeNarAccessor(teeSource); + compressionSink->finish(); + fileSink.flush(); + } + + auto now2 = std::chrono::steady_clock::now(); + + auto info = mkInfo(narHashSink.finish()); + auto narInfo = make_ref(info); + narInfo->compression = compression; + auto [fileHash, fileSize] = fileHashSink.finish(); + narInfo->fileHash = fileHash; + narInfo->fileSize = fileSize; + narInfo->url = "nar/" + narInfo->fileHash->to_string(Base32, false) + ".nar" + + (compression == "xz" ? ".xz" : + compression == "bzip2" ? ".bz2" : + compression == "br" ? ".br" : + ""); + + auto duration = std::chrono::duration_cast(now2 - now1).count(); + printMsg(lvlTalkative, "copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache", + printStorePath(narInfo->path), info.narSize, + ((1.0 - (double) fileSize / info.narSize) * 100.0), + duration); /* Verify that all references are valid. This may do some .narinfo reads, but typically they'll already be cached. */ @@ -132,23 +200,6 @@ void BinaryCacheStore::addToStore(const ValidPathInfo & info, Source & narSource printStorePath(info.path), printStorePath(ref)); } - assert(nar->compare(0, narMagic.size(), narMagic) == 0); - - auto narInfo = make_ref(info); - - narInfo->narSize = nar->size(); - narInfo->narHash = hashString(htSHA256, *nar); - - if (info.narHash && info.narHash != narInfo->narHash) - throw Error("refusing to copy corrupted path '%1%' to binary cache", printStorePath(info.path)); - - auto accessor_ = std::dynamic_pointer_cast(accessor); - - auto narAccessor = makeNarAccessor(nar); - - if (accessor_) - accessor_->addToCache(printStorePath(info.path), *nar, narAccessor); - /* Optionally write a JSON file containing a listing of the contents of the NAR. */ if (writeNARListing) { @@ -160,33 +211,13 @@ void BinaryCacheStore::addToStore(const ValidPathInfo & info, Source & narSource { auto res = jsonRoot.placeholder("root"); - listNar(res, narAccessor, "", true); + listNar(res, ref(narAccessor), "", true); } } - upsertFile(std::string(info.path.to_string()) + ".ls", jsonOut.str(), "application/json"); + upsertFile(std::string(info.path.hashPart()) + ".ls", jsonOut.str(), "application/json"); } - /* Compress the NAR. */ - narInfo->compression = compression; - auto now1 = std::chrono::steady_clock::now(); - auto narCompressed = compress(compression, *nar, parallelCompression); - auto now2 = std::chrono::steady_clock::now(); - narInfo->fileHash = hashString(htSHA256, *narCompressed); - narInfo->fileSize = narCompressed->size(); - - auto duration = std::chrono::duration_cast(now2 - now1).count(); - printMsg(lvlTalkative, "copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache", - printStorePath(narInfo->path), narInfo->narSize, - ((1.0 - (double) narCompressed->size() / nar->size()) * 100.0), - duration); - - narInfo->url = "nar/" + narInfo->fileHash.to_string(Base32, false) + ".nar" - + (compression == "xz" ? ".xz" : - compression == "bzip2" ? ".bz2" : - compression == "br" ? ".br" : - ""); - /* Optionally maintain an index of DWARF debug info files consisting of JSON files named 'debuginfo/' that specify the NAR file and member containing the debug info. */ @@ -247,12 +278,14 @@ void BinaryCacheStore::addToStore(const ValidPathInfo & info, Source & narSource /* Atomically write the NAR file. */ if (repair || !fileExists(narInfo->url)) { stats.narWrite++; - upsertFile(narInfo->url, *narCompressed, "application/x-nix-nar"); + upsertFile(narInfo->url, + std::make_shared(fnTemp, std::ios_base::in | std::ios_base::binary), + "application/x-nix-nar"); } else stats.narWriteAverted++; - stats.narWriteBytes += nar->size(); - stats.narWriteCompressedBytes += narCompressed->size(); + stats.narWriteBytes += info.narSize; + stats.narWriteCompressedBytes += fileSize; stats.narWriteCompressionTimeMs += duration; /* Atomically write the NAR info file.*/ @@ -261,6 +294,41 @@ void BinaryCacheStore::addToStore(const ValidPathInfo & info, Source & narSource writeNarInfo(narInfo); stats.narInfoWrite++; + + return narInfo; +} + +void BinaryCacheStore::addToStore(const ValidPathInfo & info, Source & narSource, + RepairFlag repair, CheckSigsFlag checkSigs) +{ + if (!repair && isValidPath(info.path)) { + // FIXME: copyNAR -> null sink + narSource.drain(); + return; + } + + addToStoreCommon(narSource, repair, checkSigs, {[&](HashResult nar) { + /* FIXME reinstate these, once we can correctly do hash modulo sink as + needed. We need to throw here in case we uploaded a corrupted store path. */ + // assert(info.narHash == nar.first); + // assert(info.narSize == nar.second); + return info; + }}); +} + +StorePath BinaryCacheStore::addToStoreFromDump(Source & dump, const string & name, + FileIngestionMethod method, HashType hashAlgo, RepairFlag repair) +{ + if (method != FileIngestionMethod::Recursive || hashAlgo != htSHA256) + unsupported("addToStoreFromDump"); + return addToStoreCommon(dump, repair, CheckSigs, [&](HashResult nar) { + ValidPathInfo info { + makeFixedOutputPath(method, nar.first, name), + nar.first, + }; + info.narSize = nar.second; + return info; + })->path; } bool BinaryCacheStore::isValidPathUncached(const StorePath & storePath) @@ -275,14 +343,10 @@ void BinaryCacheStore::narFromPath(const StorePath & storePath, Sink & sink) { auto info = queryPathInfo(storePath).cast(); - uint64_t narSize = 0; + LengthSink narSize; + TeeSink tee { sink, narSize }; - LambdaSink wrapperSink([&](const unsigned char * data, size_t len) { - sink(data, len); - narSize += len; - }); - - auto decompressor = makeDecompressionSink(info->compression, wrapperSink); + auto decompressor = makeDecompressionSink(info->compression, tee); try { getFile(info->url, *decompressor); @@ -294,7 +358,7 @@ void BinaryCacheStore::narFromPath(const StorePath & storePath, Sink & sink) stats.narRead++; //stats.narReadCompressedBytes += nar->size(); // FIXME - stats.narReadBytes += narSize; + stats.narReadBytes += narSize.length; } void BinaryCacheStore::queryPathInfoUncached(const StorePath & storePath, @@ -332,44 +396,52 @@ void BinaryCacheStore::queryPathInfoUncached(const StorePath & storePath, StorePath BinaryCacheStore::addToStore(const string & name, const Path & srcPath, FileIngestionMethod method, HashType hashAlgo, PathFilter & filter, RepairFlag repair) { - // FIXME: some cut&paste from LocalStore::addToStore(). + /* FIXME: Make BinaryCacheStore::addToStoreCommon support + non-recursive+sha256 so we can just use the default + implementation of this method in terms of addToStoreFromDump. */ - /* Read the whole path into memory. This is not a very scalable - method for very large paths, but `copyPath' is mainly used for - small files. */ - StringSink sink; - Hash h; + HashSink sink { hashAlgo }; if (method == FileIngestionMethod::Recursive) { dumpPath(srcPath, sink, filter); - h = hashString(hashAlgo, *sink.s); } else { - auto s = readFile(srcPath); - dumpString(s, sink); - h = hashString(hashAlgo, s); + readFile(srcPath, sink); } + auto h = sink.finish().first; - ValidPathInfo info(makeFixedOutputPath(method, h, name)); - - auto source = StringSource { *sink.s }; - addToStore(info, source, repair, CheckSigs, nullptr); - - return std::move(info.path); + auto source = sinkToSource([&](Sink & sink) { + dumpPath(srcPath, sink, filter); + }); + return addToStoreCommon(*source, repair, CheckSigs, [&](HashResult nar) { + ValidPathInfo info { + makeFixedOutputPath(method, h, name), + nar.first, + }; + info.narSize = nar.second; + info.ca = FixedOutputHash { + .method = method, + .hash = h, + }; + return info; + })->path; } StorePath BinaryCacheStore::addTextToStore(const string & name, const string & s, const StorePathSet & references, RepairFlag repair) { - ValidPathInfo info(computeStorePathForText(name, s, references)); - info.references = references; + auto textHash = hashString(htSHA256, s); + auto path = makeTextPath(name, textHash, references); - if (repair || !isValidPath(info.path)) { - StringSink sink; - dumpString(s, sink); - auto source = StringSource { *sink.s }; - addToStore(info, source, repair, CheckSigs, nullptr); - } + if (!repair && isValidPath(path)) + return path; - return std::move(info.path); + auto source = StringSource { s }; + return addToStoreCommon(source, repair, CheckSigs, [&](HashResult nar) { + ValidPathInfo info { path, nar.first }; + info.narSize = nar.second; + info.ca = TextHash { textHash }; + info.references = references; + return info; + })->path; } ref BinaryCacheStore::getFSAccessor() diff --git a/src/libstore/binary-cache-store.hh b/src/libstore/binary-cache-store.hh index 52ef8aa7a..5224d7ec8 100644 --- a/src/libstore/binary-cache-store.hh +++ b/src/libstore/binary-cache-store.hh @@ -11,17 +11,21 @@ namespace nix { struct NarInfo; -class BinaryCacheStore : public Store +struct BinaryCacheStoreConfig : virtual StoreConfig { -public: + using StoreConfig::StoreConfig; - const Setting compression{this, "xz", "compression", "NAR compression method ('xz', 'bzip2', or 'none')"}; - const Setting writeNARListing{this, false, "write-nar-listing", "whether to write a JSON file listing the files in each NAR"}; - const Setting writeDebugInfo{this, false, "index-debug-info", "whether to index DWARF debug info files by build ID"}; - const Setting secretKeyFile{this, "", "secret-key", "path to secret key used to sign the binary cache"}; - const Setting localNarCache{this, "", "local-nar-cache", "path to a local cache of NARs"}; - const Setting parallelCompression{this, false, "parallel-compression", + const Setting compression{(StoreConfig*) this, "xz", "compression", "NAR compression method ('xz', 'bzip2', or 'none')"}; + const Setting writeNARListing{(StoreConfig*) this, false, "write-nar-listing", "whether to write a JSON file listing the files in each NAR"}; + const Setting writeDebugInfo{(StoreConfig*) this, false, "index-debug-info", "whether to index DWARF debug info files by build ID"}; + const Setting secretKeyFile{(StoreConfig*) this, "", "secret-key", "path to secret key used to sign the binary cache"}; + const Setting localNarCache{(StoreConfig*) this, "", "local-nar-cache", "path to a local cache of NARs"}; + const Setting parallelCompression{(StoreConfig*) this, false, "parallel-compression", "enable multi-threading compression, available for xz only currently"}; +}; + +class BinaryCacheStore : public Store, public virtual BinaryCacheStoreConfig +{ private: @@ -36,9 +40,13 @@ public: virtual bool fileExists(const std::string & path) = 0; virtual void upsertFile(const std::string & path, - const std::string & data, + std::shared_ptr> istream, const std::string & mimeType) = 0; + void upsertFile(const std::string & path, + std::string && data, + const std::string & mimeType); + /* Note: subclasses must implement at least one of the two following getFile() methods. */ @@ -54,7 +62,7 @@ public: public: - virtual void init(); + virtual void init() override; private: @@ -64,6 +72,10 @@ private: void writeNarInfo(ref narInfo); + ref addToStoreCommon( + Source & narSource, RepairFlag repair, CheckSigsFlag checkSigs, + std::function mkInfo); + public: bool isValidPathUncached(const StorePath & path) override; @@ -75,8 +87,10 @@ public: { unsupported("queryPathFromHashPart"); } void addToStore(const ValidPathInfo & info, Source & narSource, - RepairFlag repair, CheckSigsFlag checkSigs, - std::shared_ptr accessor) override; + RepairFlag repair, CheckSigsFlag checkSigs) override; + + StorePath addToStoreFromDump(Source & dump, const string & name, + FileIngestionMethod method, HashType hashAlgo, RepairFlag repair) override; StorePath addToStore(const string & name, const Path & srcPath, FileIngestionMethod method, HashType hashAlgo, diff --git a/src/libstore/build.cc b/src/libstore/build.cc index e927a65f0..4c88504c4 100644 --- a/src/libstore/build.cc +++ b/src/libstore/build.cc @@ -17,6 +17,8 @@ #include "daemon.hh" #include "worker-protocol.hh" #include "user-lock.hh" +#include "topo-sort.hh" +#include "callback.hh" #include #include @@ -295,10 +297,22 @@ public: ~Worker(); /* Make a goal (with caching). */ - GoalPtr makeDerivationGoal(const StorePath & drvPath, const StringSet & wantedOutputs, BuildMode buildMode = bmNormal); - std::shared_ptr makeBasicDerivationGoal(const StorePath & drvPath, - const BasicDerivation & drv, BuildMode buildMode = bmNormal); - GoalPtr makeSubstitutionGoal(const StorePath & storePath, RepairFlag repair = NoRepair); + + /* derivation goal */ +private: + std::shared_ptr makeDerivationGoalCommon( + const StorePath & drvPath, const StringSet & wantedOutputs, + std::function()> mkDrvGoal); +public: + std::shared_ptr makeDerivationGoal( + const StorePath & drvPath, + const StringSet & wantedOutputs, BuildMode buildMode = bmNormal); + std::shared_ptr makeBasicDerivationGoal( + const StorePath & drvPath, const BasicDerivation & drv, + const StringSet & wantedOutputs, BuildMode buildMode = bmNormal); + + /* substitution goal */ + GoalPtr makeSubstitutionGoal(const StorePath & storePath, RepairFlag repair = NoRepair, std::optional ca = std::nullopt); /* Remove a dead goal. */ void removeGoal(GoalPtr goal); @@ -606,6 +620,33 @@ typedef enum {rpAccept, rpDecline, rpPostpone} HookReply; class SubstitutionGoal; +/* Unless we are repairing, we don't both to test validity and just assume it, + so the choices are `Absent` or `Valid`. */ +enum struct PathStatus { + Corrupt, + Absent, + Valid, +}; + +struct InitialOutputStatus { + StorePath path; + PathStatus status; + /* Valid in the store, and additionally non-corrupt if we are repairing */ + bool isValid() const { + return status == PathStatus::Valid; + } + /* Merely present, allowed to be corrupt */ + bool isPresent() const { + return status == PathStatus::Corrupt + || status == PathStatus::Valid; + } +}; + +struct InitialOutput { + bool wanted; + std::optional known; +}; + class DerivationGoal : public Goal { private: @@ -633,19 +674,14 @@ private: /* The remainder is state held during the build. */ - /* Locks on the output paths. */ + /* Locks on (fixed) output paths. */ PathLocks outputLocks; /* All input paths (that is, the union of FS closures of the immediate input paths). */ StorePathSet inputPaths; - /* Outputs that are already valid. If we're repairing, these are - the outputs that are valid *and* not corrupt. */ - StorePathSet validPaths; - - /* Outputs that are corrupt or not valid. */ - StorePathSet missingPaths; + std::map initialOutputs; /* User selected for running the builder. */ std::unique_ptr buildUser; @@ -702,8 +738,8 @@ private: /* RAII object to delete the chroot directory. */ std::shared_ptr autoDelChroot; - /* Whether this is a fixed-output derivation. */ - bool fixedOutput; + /* The sort of derivation we are building. */ + DerivationType derivationType; /* Whether to run the build in a private network namespace. */ bool privateNetwork = false; @@ -735,6 +771,31 @@ private: typedef map RedirectedOutputs; RedirectedOutputs redirectedOutputs; + /* The outputs paths used during the build. + + - Input-addressed derivations or fixed content-addressed outputs are + sometimes built when some of their outputs already exist, and can not + be hidden via sandboxing. We use temporary locations instead and + rewrite after the build. Otherwise the regular predetermined paths are + put here. + + - Floating content-addressed derivations do not know their final build + output paths until the outputs are hashed, so random locations are + used, and then renamed. The randomness helps guard against hidden + self-references. + */ + OutputPathMap scratchOutputs; + + /* The final output paths of the build. + + - For input-addressed derivations, always the precomputed paths + + - For content-addressed derivations, calcuated from whatever the hash + ends up being. (Note that fixed outputs derivations that produce the + "wrong" output still install that data under its true content-address.) + */ + OutputPathMap finalOutputs; + BuildMode buildMode; /* If we're repairing without a chroot, there may be outputs that @@ -796,10 +857,12 @@ private: friend struct RestrictedStore; public: - DerivationGoal(const StorePath & drvPath, const StringSet & wantedOutputs, - Worker & worker, BuildMode buildMode = bmNormal); + DerivationGoal(const StorePath & drvPath, + const StringSet & wantedOutputs, Worker & worker, + BuildMode buildMode = bmNormal); DerivationGoal(const StorePath & drvPath, const BasicDerivation & drv, - Worker & worker, BuildMode buildMode = bmNormal); + const StringSet & wantedOutputs, Worker & worker, + BuildMode buildMode = bmNormal); ~DerivationGoal(); /* Whether we need to perform hash rewriting if there are valid output paths. */ @@ -833,13 +896,16 @@ private: void getDerivation(); void loadDerivation(); void haveDerivation(); - void outputsSubstituted(); + void outputsSubstitutionTried(); + void gaveUpOnSubstitution(); void closureRepaired(); void inputsRealised(); void tryToBuild(); void tryLocalBuild(); void buildDone(); + void resolvedFinished(); + /* Is the build hook willing to perform the build? */ HookReply tryBuildHook(); @@ -894,13 +960,27 @@ private: void handleEOF(int fd) override; void flushLine(); + /* Wrappers around the corresponding Store methods that first consult the + derivation. This is currently needed because when there is no drv file + there also is no DB entry. */ + std::map> queryPartialDerivationOutputMap(); + OutputPathMap queryDerivationOutputMap(); + /* Return the set of (in)valid paths. */ - StorePathSet checkPathValidity(bool returnValid, bool checkHash); + void checkPathValidity(); /* Forcibly kill the child process, if any. */ void killChild(); - void addHashRewrite(const StorePath & path); + /* Create alternative path calculated from but distinct from the + input, so we can avoid overwriting outputs (or other store paths) + that already exist. */ + StorePath makeFallbackPath(const StorePath & path); + /* Make a path to another based on the output name along with the + derivation hash. */ + /* FIXME add option to randomize, so we can audit whether our + rewrites caught everything */ + StorePath makeFallbackPath(std::string_view outputName); void repairClosure(); @@ -917,8 +997,8 @@ private: const Path DerivationGoal::homeDir = "/homeless-shelter"; -DerivationGoal::DerivationGoal(const StorePath & drvPath, const StringSet & wantedOutputs, - Worker & worker, BuildMode buildMode) +DerivationGoal::DerivationGoal(const StorePath & drvPath, + const StringSet & wantedOutputs, Worker & worker, BuildMode buildMode) : Goal(worker) , useDerivation(true) , drvPath(drvPath) @@ -926,7 +1006,9 @@ DerivationGoal::DerivationGoal(const StorePath & drvPath, const StringSet & want , buildMode(buildMode) { state = &DerivationGoal::getDerivation; - name = fmt("building of '%s'", worker.store.printStorePath(this->drvPath)); + name = fmt( + "building of '%s' from .drv file", + StorePathWithOutputs { drvPath, wantedOutputs }.to_string(worker.store)); trace("created"); mcExpectedBuilds = std::make_unique>(worker.expectedBuilds); @@ -935,15 +1017,18 @@ DerivationGoal::DerivationGoal(const StorePath & drvPath, const StringSet & want DerivationGoal::DerivationGoal(const StorePath & drvPath, const BasicDerivation & drv, - Worker & worker, BuildMode buildMode) + const StringSet & wantedOutputs, Worker & worker, BuildMode buildMode) : Goal(worker) , useDerivation(false) , drvPath(drvPath) + , wantedOutputs(wantedOutputs) , buildMode(buildMode) { this->drv = std::make_unique(BasicDerivation(drv)); state = &DerivationGoal::haveDerivation; - name = fmt("building of %s", worker.store.showPaths(drv.outputPaths())); + name = fmt( + "building of '%s' from in-memory derivation", + StorePathWithOutputs { drvPath, drv.outputNames() }.to_string(worker.store)); trace("created"); mcExpectedBuilds = std::make_unique>(worker.expectedBuilds); @@ -1075,43 +1160,60 @@ void DerivationGoal::haveDerivation() { trace("have derivation"); + if (drv->type() == DerivationType::CAFloating) + settings.requireExperimentalFeature("ca-derivations"); + retrySubstitution = false; - for (auto & i : drv->outputs) - worker.store.addTempRoot(i.second.path); + for (auto & i : drv->outputsAndOptPaths(worker.store)) + if (i.second.second) + worker.store.addTempRoot(*i.second.second); /* Check what outputs paths are not already valid. */ - auto invalidOutputs = checkPathValidity(false, buildMode == bmRepair); + checkPathValidity(); + bool allValid = true; + for (auto & [_, status] : initialOutputs) { + if (!status.wanted) continue; + if (!status.known || !status.known->isValid()) { + allValid = false; + break; + } + } /* If they are all valid, then we're done. */ - if (invalidOutputs.size() == 0 && buildMode == bmNormal) { + if (allValid && buildMode == bmNormal) { done(BuildResult::AlreadyValid); return; } parsedDrv = std::make_unique(drvPath, *drv); - if (parsedDrv->contentAddressed()) { - settings.requireExperimentalFeature("ca-derivations"); - throw Error("ca-derivations isn't implemented yet"); - } - /* We are first going to try to create the invalid output paths through substitutes. If that doesn't work, we'll build them. */ if (settings.useSubstitutes && parsedDrv->substitutesAllowed()) - for (auto & i : invalidOutputs) - addWaitee(worker.makeSubstitutionGoal(i, buildMode == bmRepair ? Repair : NoRepair)); + for (auto & [_, status] : initialOutputs) { + if (!status.wanted) continue; + if (!status.known) { + warn("do not know how to query for unknown floating content-addressed derivation output yet"); + /* Nothing to wait for; tail call */ + return DerivationGoal::gaveUpOnSubstitution(); + } + addWaitee(worker.makeSubstitutionGoal( + status.known->path, + buildMode == bmRepair ? Repair : NoRepair, + getDerivationCA(*drv))); + } if (waitees.empty()) /* to prevent hang (no wake-up event) */ - outputsSubstituted(); + outputsSubstitutionTried(); else - state = &DerivationGoal::outputsSubstituted; + state = &DerivationGoal::outputsSubstitutionTried; } -void DerivationGoal::outputsSubstituted() +void DerivationGoal::outputsSubstitutionTried() { trace("all outputs substituted (maybe)"); @@ -1135,7 +1237,14 @@ void DerivationGoal::outputsSubstituted() return; } - auto nrInvalid = checkPathValidity(false, buildMode == bmRepair).size(); + checkPathValidity(); + size_t nrInvalid = 0; + for (auto & [_, status] : initialOutputs) { + if (!status.wanted) continue; + if (!status.known || !status.known->isValid()) + nrInvalid++; + } + if (buildMode == bmNormal && nrInvalid == 0) { done(BuildResult::Substituted); return; @@ -1148,9 +1257,14 @@ void DerivationGoal::outputsSubstituted() throw Error("some outputs of '%s' are not valid, so checking is not possible", worker.store.printStorePath(drvPath)); - /* Otherwise, at least one of the output paths could not be - produced using a substitute. So we have to build instead. */ + /* Nothing to wait for; tail call */ + gaveUpOnSubstitution(); +} +/* At least one of the output paths could not be + produced using a substitute. So we have to build instead. */ +void DerivationGoal::gaveUpOnSubstitution() +{ /* Make sure checkPathValidity() from now on checks all outputs. */ wantedOutputs.clear(); @@ -1183,15 +1297,16 @@ void DerivationGoal::repairClosure() that produced those outputs. */ /* Get the output closure. */ + auto outputs = queryDerivationOutputMap(); StorePathSet outputClosure; - for (auto & i : drv->outputs) { + for (auto & i : outputs) { if (!wantOutput(i.first, wantedOutputs)) continue; - worker.store.computeFSClosure(i.second.path, outputClosure); + worker.store.computeFSClosure(i.second, outputClosure); } /* Filter out our own outputs (which we have already checked). */ - for (auto & i : drv->outputs) - outputClosure.erase(i.second.path); + for (auto & i : outputs) + outputClosure.erase(i.second); /* Get all dependencies of this derivation so that we know which derivation is responsible for which path in the output @@ -1201,9 +1316,10 @@ void DerivationGoal::repairClosure() std::map outputsToDrv; for (auto & i : inputClosure) if (i.isDerivation()) { - Derivation drv = worker.store.derivationFromPath(i); - for (auto & j : drv.outputs) - outputsToDrv.insert_or_assign(j.second.path, i); + auto depOutputs = worker.store.queryPartialDerivationOutputMap(i); + for (auto & j : depOutputs) + if (j.second) + outputsToDrv.insert_or_assign(*j.second, i); } /* Check each path (slow!). */ @@ -1265,35 +1381,72 @@ void DerivationGoal::inputsRealised() /* Determine the full set of input paths. */ /* First, the input derivations. */ - if (useDerivation) - for (auto & i : dynamic_cast(drv.get())->inputDrvs) { + if (useDerivation) { + auto & fullDrv = *dynamic_cast(drv.get()); + + if (!fullDrv.inputDrvs.empty() && fullDrv.type() == DerivationType::CAFloating) { + /* We are be able to resolve this derivation based on the + now-known results of dependencies. If so, we become a stub goal + aliasing that resolved derivation goal */ + std::optional attempt = fullDrv.tryResolve(worker.store); + assert(attempt); + Derivation drvResolved { *std::move(attempt) }; + + auto pathResolved = writeDerivation(worker.store, drvResolved); + /* Add to memotable to speed up downstream goal's queries with the + original derivation. */ + drvPathResolutions.lock()->insert_or_assign(drvPath, pathResolved); + + auto msg = fmt("Resolved derivation: '%s' -> '%s'", + worker.store.printStorePath(drvPath), + worker.store.printStorePath(pathResolved)); + act = std::make_unique(*logger, lvlInfo, actBuildWaiting, msg, + Logger::Fields { + worker.store.printStorePath(drvPath), + worker.store.printStorePath(pathResolved), + }); + + auto resolvedGoal = worker.makeDerivationGoal( + pathResolved, wantedOutputs, buildMode); + addWaitee(resolvedGoal); + + state = &DerivationGoal::resolvedFinished; + return; + } + + for (auto & [depDrvPath, wantedDepOutputs] : fullDrv.inputDrvs) { /* Add the relevant output closures of the input derivation `i' as input paths. Only add the closures of output paths that are specified as inputs. */ - assert(worker.store.isValidPath(i.first)); - Derivation inDrv = worker.store.derivationFromPath(i.first); - for (auto & j : i.second) { - auto k = inDrv.outputs.find(j); - if (k != inDrv.outputs.end()) - worker.store.computeFSClosure(k->second.path, inputPaths); - else + assert(worker.store.isValidPath(drvPath)); + auto outputs = worker.store.queryPartialDerivationOutputMap(depDrvPath); + for (auto & j : wantedDepOutputs) { + if (outputs.count(j) > 0) { + auto optRealizedInput = outputs.at(j); + if (!optRealizedInput) + throw Error( + "derivation '%s' requires output '%s' from input derivation '%s', which is supposedly realized already, yet we still don't know what path corresponds to that output", + worker.store.printStorePath(drvPath), j, worker.store.printStorePath(drvPath)); + worker.store.computeFSClosure(*optRealizedInput, inputPaths); + } else throw Error( "derivation '%s' requires non-existent output '%s' from input derivation '%s'", - worker.store.printStorePath(drvPath), j, worker.store.printStorePath(i.first)); + worker.store.printStorePath(drvPath), j, worker.store.printStorePath(drvPath)); } } + } /* Second, the input sources. */ worker.store.computeFSClosure(drv->inputSrcs, inputPaths); debug("added input paths %s", worker.store.showPaths(inputPaths)); - /* Is this a fixed-output derivation? */ - fixedOutput = drv->isFixedOutput(); + /* What type of derivation are we building? */ + derivationType = drv->type(); /* Don't repeat fixed-output derivations since they're already verified by their output hash.*/ - nrRounds = fixedOutput ? 1 : settings.buildRepeat + 1; + nrRounds = derivationIsFixed(derivationType) ? 1 : settings.buildRepeat + 1; /* Okay, try to build. Note that here we don't wait for a build slot to become available, since we don't need one if there is a @@ -1324,14 +1477,18 @@ void DerivationGoal::tryToBuild() { trace("trying to build"); - /* Obtain locks on all output paths. The locks are automatically - released when we exit this function or Nix crashes. If we - can't acquire the lock, then continue; hopefully some other - goal can start a build, and if not, the main loop will sleep a - few seconds and then retry this goal. */ + /* Obtain locks on all output paths, if the paths are known a priori. + + The locks are automatically released when we exit this function or Nix + crashes. If we can't acquire the lock, then continue; hopefully some + other goal can start a build, and if not, the main loop will sleep a few + seconds and then retry this goal. */ PathSet lockFiles; - for (auto & outPath : drv->outputPaths()) - lockFiles.insert(worker.store.Store::toRealPath(outPath)); + /* FIXME: Should lock something like the drv itself so we don't build same + CA drv concurrently */ + for (auto & i : drv->outputsAndOptPaths(worker.store)) + if (i.second.second) + lockFiles.insert(worker.store.Store::toRealPath(*i.second.second)); if (!outputLocks.lockPaths(lockFiles, "", false)) { if (!actLock) @@ -1350,32 +1507,36 @@ void DerivationGoal::tryToBuild() omitted, but that would be less efficient.) Note that since we now hold the locks on the output paths, no other process can build this derivation, so no further checks are necessary. */ - validPaths = checkPathValidity(true, buildMode == bmRepair); - if (buildMode != bmCheck && validPaths.size() == drv->outputs.size()) { + checkPathValidity(); + bool allValid = true; + for (auto & [_, status] : initialOutputs) { + if (!status.wanted) continue; + if (!status.known || !status.known->isValid()) { + allValid = false; + break; + } + } + if (buildMode != bmCheck && allValid) { debug("skipping build of derivation '%s', someone beat us to it", worker.store.printStorePath(drvPath)); outputLocks.setDeletion(true); done(BuildResult::AlreadyValid); return; } - missingPaths = drv->outputPaths(); - if (buildMode != bmCheck) - for (auto & i : validPaths) missingPaths.erase(i); - /* If any of the outputs already exist but are not valid, delete them. */ - for (auto & i : drv->outputs) { - if (worker.store.isValidPath(i.second.path)) continue; - debug("removing invalid path '%s'", worker.store.printStorePath(i.second.path)); - deletePath(worker.store.Store::toRealPath(i.second.path)); + for (auto & [_, status] : initialOutputs) { + if (!status.known || status.known->isValid()) continue; + auto storePath = status.known->path; + debug("removing invalid path '%s'", worker.store.printStorePath(status.known->path)); + deletePath(worker.store.Store::toRealPath(storePath)); } /* Don't do a remote build if the derivation has the attribute `preferLocalBuild' set. Also, check and repair modes are only supported for local builds. */ - bool buildLocally = buildMode != bmNormal || parsedDrv->willBuildLocally(); + bool buildLocally = buildMode != bmNormal || parsedDrv->willBuildLocally(worker.store); - /* Is the build hook willing to accept this job? */ if (!buildLocally) { switch (tryBuildHook()) { case rpAccept: @@ -1403,6 +1564,13 @@ void DerivationGoal::tryToBuild() actLock.reset(); + state = &DerivationGoal::tryLocalBuild; + worker.wakeUp(shared_from_this()); +} + +void DerivationGoal::tryLocalBuild() { + bool buildLocally = buildMode != bmNormal || parsedDrv->willBuildLocally(worker.store); + /* Make sure that we are allowed to start a build. If this derivation prefers to be done locally, do it even if maxBuildJobs is 0. */ @@ -1413,13 +1581,6 @@ void DerivationGoal::tryToBuild() return; } - state = &DerivationGoal::tryLocalBuild; - worker.wakeUp(shared_from_this()); -} - - -void DerivationGoal::tryLocalBuild() { - if (useBuildUsers()) { if (!buildUser) buildUser = acquireUserLock(); @@ -1460,7 +1621,34 @@ void DerivationGoal::tryLocalBuild() { } -void replaceValidPath(const Path & storePath, const Path tmpPath) +static void chmod_(const Path & path, mode_t mode) +{ + if (chmod(path.c_str(), mode) == -1) + throw SysError("setting permissions on '%s'", path); +} + + +/* Move/rename path 'src' to 'dst'. Temporarily make 'src' writable if + it's a directory and we're not root (to be able to update the + directory's parent link ".."). */ +static void movePath(const Path & src, const Path & dst) +{ + auto st = lstat(src); + + bool changePerm = (geteuid() && S_ISDIR(st.st_mode) && !(st.st_mode & S_IWUSR)); + + if (changePerm) + chmod_(src, st.st_mode | S_IWUSR); + + if (rename(src.c_str(), dst.c_str())) + throw SysError("renaming '%1%' to '%2%'", src, dst); + + if (changePerm) + chmod_(dst, st.st_mode); +} + + +void replaceValidPath(const Path & storePath, const Path & tmpPath) { /* We can't atomically replace storePath (the original) with tmpPath (the replacement), so we have to move it out of the @@ -1468,11 +1656,20 @@ void replaceValidPath(const Path & storePath, const Path tmpPath) we're repairing (say) Glibc, we end up with a broken system. */ Path oldPath = (format("%1%.old-%2%-%3%") % storePath % getpid() % random()).str(); if (pathExists(storePath)) - rename(storePath.c_str(), oldPath.c_str()); - if (rename(tmpPath.c_str(), storePath.c_str()) == -1) { - rename(oldPath.c_str(), storePath.c_str()); // attempt to recover - throw SysError("moving '%s' to '%s'", tmpPath, storePath); + movePath(storePath, oldPath); + + try { + movePath(tmpPath, storePath); + } catch (...) { + try { + // attempt to recover + movePath(oldPath, storePath); + } catch (...) { + ignoreException(); + } + throw; } + deletePath(oldPath); } @@ -1538,13 +1735,13 @@ void DerivationGoal::buildDone() So instead, check if the disk is (nearly) full now. If so, we don't mark this build as a permanent failure. */ #if HAVE_STATVFS - unsigned long long required = 8ULL * 1024 * 1024; // FIXME: make configurable + uint64_t required = 8ULL * 1024 * 1024; // FIXME: make configurable struct statvfs st; if (statvfs(worker.store.realStoreDir.c_str(), &st) == 0 && - (unsigned long long) st.f_bavail * st.f_bsize < required) + (uint64_t) st.f_bavail * st.f_bsize < required) diskFull = true; if (statvfs(tmpDir.c_str(), &st) == 0 && - (unsigned long long) st.f_bavail * st.f_bsize < required) + (uint64_t) st.f_bavail * st.f_bsize < required) diskFull = true; #endif @@ -1553,8 +1750,10 @@ void DerivationGoal::buildDone() /* Move paths out of the chroot for easier debugging of build failures. */ if (useChroot && buildMode == bmNormal) - for (auto & i : missingPaths) { - auto p = worker.store.printStorePath(i); + for (auto & [_, status] : initialOutputs) { + if (!status.known) continue; + if (buildMode != bmCheck && status.known->isValid()) continue; + auto p = worker.store.printStorePath(status.known->path); if (pathExists(chrootRootDir + p)) rename((chrootRootDir + p).c_str(), p.c_str()); } @@ -1584,7 +1783,10 @@ void DerivationGoal::buildDone() fmt("running post-build-hook '%s'", settings.postBuildHook), Logger::Fields{worker.store.printStorePath(drvPath)}); PushActivity pact(act.id); - auto outputPaths = drv->outputPaths(); + StorePathSet outputPaths; + for (auto i : drv->outputs) { + outputPaths.insert(finalOutputs.at(i.first)); + } std::map hookEnvironment = getEnv(); hookEnvironment.emplace("DRV_PATH", worker.store.printStorePath(drvPath)); @@ -1675,7 +1877,7 @@ void DerivationGoal::buildDone() st = dynamic_cast(&e) ? BuildResult::NotDeterministic : statusOk(status) ? BuildResult::OutputRejected : - fixedOutput || diskFull ? BuildResult::TransientFailure : + derivationIsImpure(derivationType) || diskFull ? BuildResult::TransientFailure : BuildResult::PermanentFailure; } @@ -1686,6 +1888,9 @@ void DerivationGoal::buildDone() done(BuildResult::Built); } +void DerivationGoal::resolvedFinished() { + done(BuildResult::Built); +} HookReply DerivationGoal::tryBuildHook() { @@ -1756,11 +1961,19 @@ HookReply DerivationGoal::tryBuildHook() /* Tell the hook all the inputs that have to be copied to the remote system. */ - writeStorePaths(worker.store, hook->sink, inputPaths); + worker_proto::write(worker.store, hook->sink, inputPaths); /* Tell the hooks the missing outputs that have to be copied back from the remote system. */ - writeStorePaths(worker.store, hook->sink, missingPaths); + { + StorePathSet missingPaths; + for (auto & [_, status] : initialOutputs) { + if (!status.known) continue; + if (buildMode != bmCheck && status.known->isValid()) continue; + missingPaths.insert(status.known->path); + } + worker_proto::write(worker.store, hook->sink, missingPaths); + } hook->sink = FdSink(); hook->toHook.writeSide = -1; @@ -1777,13 +1990,6 @@ HookReply DerivationGoal::tryBuildHook() } -static void chmod_(const Path & path, mode_t mode) -{ - if (chmod(path.c_str(), mode) == -1) - throw SysError("setting permissions on '%s'", path); -} - - int childEntry(void * arg) { ((DerivationGoal *) arg)->runChild(); @@ -1811,8 +2017,15 @@ StorePathSet DerivationGoal::exportReferences(const StorePathSet & storePaths) for (auto & j : paths2) { if (j.isDerivation()) { Derivation drv = worker.store.derivationFromPath(j); - for (auto & k : drv.outputs) - worker.store.computeFSClosure(k.second.path, paths); + for (auto & k : drv.outputsAndOptPaths(worker.store)) { + if (!k.second.second) + /* FIXME: I am confused why we are calling + `computeFSClosure` on the output path, rather than + derivation itself. That doesn't seem right to me, so I + won't try to implemented this for CA derivations. */ + throw UnimplementedError("exportReferences on CA derivations is not yet implemented"); + worker.store.computeFSClosure(*k.second.second, paths); + } } } @@ -1843,7 +2056,7 @@ void linkOrCopy(const Path & from, const Path & to) file (e.g. 32000 of ext3), which is quite possible after a 'nix-store --optimise'. FIXME: actually, why don't we just bind-mount in this case? - + It can also fail with EPERM in BeegFS v7 and earlier versions which don't allow hard-links to other directories */ if (errno != EMLINK && errno != EPERM) @@ -1856,13 +2069,13 @@ void linkOrCopy(const Path & from, const Path & to) void DerivationGoal::startBuilder() { /* Right platform? */ - if (!parsedDrv->canBuildLocally()) + if (!parsedDrv->canBuildLocally(worker.store)) throw Error("a '%s' with features {%s} is required to build '%s', but I am a '%s' with features {%s}", drv->platform, concatStringsSep(", ", parsedDrv->getRequiredSystemFeatures()), worker.store.printStorePath(drvPath), settings.thisSystem, - concatStringsSep(", ", settings.systemFeatures)); + concatStringsSep(", ", worker.store.systemFeatures)); if (drv->isBuiltin()) preloadNSS(); @@ -1888,7 +2101,7 @@ void DerivationGoal::startBuilder() else if (settings.sandboxMode == smDisabled) useChroot = false; else if (settings.sandboxMode == smRelaxed) - useChroot = !fixedOutput && !noChroot; + useChroot = !(derivationIsImpure(derivationType)) && !noChroot; } if (worker.store.storeDir != worker.store.realStoreDir) { @@ -1905,9 +2118,64 @@ void DerivationGoal::startBuilder() chownToBuilder(tmpDir); - /* Substitute output placeholders with the actual output paths. */ - for (auto & output : drv->outputs) - inputRewrites[hashPlaceholder(output.first)] = worker.store.printStorePath(output.second.path); + for (auto & [outputName, status] : initialOutputs) { + /* Set scratch path we'll actually use during the build. + + If we're not doing a chroot build, but we have some valid + output paths. Since we can't just overwrite or delete + them, we have to do hash rewriting: i.e. in the + environment/arguments passed to the build, we replace the + hashes of the valid outputs with unique dummy strings; + after the build, we discard the redirected outputs + corresponding to the valid outputs, and rewrite the + contents of the new outputs to replace the dummy strings + with the actual hashes. */ + auto scratchPath = + !status.known + ? makeFallbackPath(outputName) + : !needsHashRewrite() + /* Can always use original path in sandbox */ + ? status.known->path + : !status.known->isPresent() + /* If path doesn't yet exist can just use it */ + ? status.known->path + : buildMode != bmRepair && !status.known->isValid() + /* If we aren't repairing we'll delete a corrupted path, so we + can use original path */ + ? status.known->path + : /* If we are repairing or the path is totally valid, we'll need + to use a temporary path */ + makeFallbackPath(status.known->path); + scratchOutputs.insert_or_assign(outputName, scratchPath); + + /* A non-removed corrupted path needs to be stored here, too */ + if (buildMode == bmRepair && !status.known->isValid()) + redirectedBadOutputs.insert(status.known->path); + + /* Substitute output placeholders with the scratch output paths. + We'll use during the build. */ + inputRewrites[hashPlaceholder(outputName)] = worker.store.printStorePath(scratchPath); + + /* Additional tasks if we know the final path a priori. */ + if (!status.known) continue; + auto fixedFinalPath = status.known->path; + + /* Additional tasks if the final and scratch are both known and + differ. */ + if (fixedFinalPath == scratchPath) continue; + + /* Ensure scratch path is ours to use. */ + deletePath(worker.store.printStorePath(scratchPath)); + + /* Rewrite and unrewrite paths */ + { + std::string h1 { fixedFinalPath.hashPart() }; + std::string h2 { scratchPath.hashPart() }; + inputRewrites[h1] = h2; + } + + redirectedOutputs.insert_or_assign(std::move(fixedFinalPath), std::move(scratchPath)); + } /* Construct the environment passed to the builder. */ initEnv(); @@ -1933,7 +2201,10 @@ void DerivationGoal::startBuilder() if (!std::regex_match(fileName, regex)) throw Error("invalid file name '%s' in 'exportReferencesGraph'", fileName); - auto storePath = worker.store.parseStorePath(*i++); + auto storePathS = *i++; + if (!worker.store.isInStore(storePathS)) + throw BuildError("'exportReferencesGraph' contains a non-store path '%1%'", storePathS); + auto storePath = worker.store.toStorePath(storePathS).first; /* Write closure info to . */ writeFile(tmpDir + "/" + fileName, @@ -1975,10 +2246,11 @@ void DerivationGoal::startBuilder() for (auto & i : dirsInChroot) try { if (worker.store.isInStore(i.second.source)) - worker.store.computeFSClosure(worker.store.parseStorePath(worker.store.toStorePath(i.second.source)), closure); + worker.store.computeFSClosure(worker.store.toStorePath(i.second.source).first, closure); } catch (InvalidPath & e) { } catch (Error & e) { - throw Error("while processing 'sandbox-paths': %s", e.what()); + e.addTrace({}, "while processing 'sandbox-paths'"); + throw; } for (auto & i : closure) { auto p = worker.store.printStorePath(i); @@ -2065,7 +2337,7 @@ void DerivationGoal::startBuilder() "nogroup:x:65534:\n") % sandboxGid).str()); /* Create /etc/hosts with localhost entry. */ - if (!fixedOutput) + if (!(derivationIsImpure(derivationType))) writeFile(chrootRootDir + "/etc/hosts", "127.0.0.1 localhost\n::1 localhost\n"); /* Make the closure of the inputs available in the chroot, @@ -2085,10 +2357,7 @@ void DerivationGoal::startBuilder() for (auto & i : inputPaths) { auto p = worker.store.printStorePath(i); Path r = worker.store.toRealPath(p); - struct stat st; - if (lstat(r.c_str(), &st)) - throw SysError("getting attributes of path '%s'", p); - if (S_ISDIR(st.st_mode)) + if (S_ISDIR(lstat(r).st_mode)) dirsInChroot.insert_or_assign(p, r); else linkOrCopy(r, chrootRootDir + p); @@ -2099,8 +2368,15 @@ void DerivationGoal::startBuilder() rebuilding a path that is in settings.dirsInChroot (typically the dependencies of /bin/sh). Throw them out. */ - for (auto & i : drv->outputs) - dirsInChroot.erase(worker.store.printStorePath(i.second.path)); + for (auto & i : drv->outputsAndOptPaths(worker.store)) { + /* If the name isn't known a priori (i.e. floating + content-addressed derivation), the temporary location we use + should be fresh. Freshness means it is impossible that the path + is already in the sandbox, so we don't need to worry about + removing it. */ + if (i.second.second) + dirsInChroot.erase(worker.store.printStorePath(*i.second.second)); + } if (useSystemdCgroup) { settings.requireExperimentalFeature("systemd-cgroup"); @@ -2130,33 +2406,8 @@ void DerivationGoal::startBuilder() throw Error("feature 'systemd-cgroup' is only supported in sandboxed builds"); } - if (needsHashRewrite()) { - - if (pathExists(homeDir)) - throw Error("home directory '%1%' exists; please remove it to assure purity of builds without sandboxing", homeDir); - - /* We're not doing a chroot build, but we have some valid - output paths. Since we can't just overwrite or delete - them, we have to do hash rewriting: i.e. in the - environment/arguments passed to the build, we replace the - hashes of the valid outputs with unique dummy strings; - after the build, we discard the redirected outputs - corresponding to the valid outputs, and rewrite the - contents of the new outputs to replace the dummy strings - with the actual hashes. */ - if (validPaths.size() > 0) - for (auto & i : validPaths) - addHashRewrite(i); - - /* If we're repairing, then we don't want to delete the - corrupt outputs in advance. So rewrite them as well. */ - if (buildMode == bmRepair) - for (auto & i : missingPaths) - if (worker.store.isValidPath(i) && pathExists(worker.store.printStorePath(i))) { - addHashRewrite(i); - redirectedBadOutputs.insert(i); - } - } + if (needsHashRewrite() && pathExists(homeDir)) + throw Error("home directory '%1%' exists; please remove it to assure purity of builds without sandboxing", homeDir); if (useChroot && settings.preBuildHook != "" && dynamic_cast(drv.get())) { printMsg(lvlChatty, format("executing pre-build hook '%1%'") @@ -2293,7 +2544,7 @@ void DerivationGoal::startBuilder() us. */ - if (!fixedOutput) + if (!(derivationIsImpure(derivationType))) privateNetwork = true; userNamespaceSync.create(); @@ -2358,6 +2609,12 @@ void DerivationGoal::startBuilder() userNamespaceSync.readSide = -1; + /* Close the write side to prevent runChild() from hanging + reading from this. */ + Finally cleanup([&]() { + userNamespaceSync.writeSide = -1; + }); + pid_t tmp; if (!string2Int(readLine(builderOut.readSide.get()), tmp)) abort(); pid = tmp; @@ -2392,7 +2649,6 @@ void DerivationGoal::startBuilder() /* Signal the builder that we've updated its user namespace. */ writeFull(userNamespaceSync.writeSide.get(), "1"); - userNamespaceSync.writeSide = -1; } else #endif @@ -2412,9 +2668,12 @@ void DerivationGoal::startBuilder() /* Check if setting up the build environment failed. */ while (true) { string msg = readLine(builderOut.readSide.get()); + if (string(msg, 0, 1) == "\2") break; if (string(msg, 0, 1) == "\1") { - if (msg.size() == 1) break; - throw Error(string(msg, 1)); + FdSource source(builderOut.readSide.get()); + auto ex = readError(source); + ex.addTrace({}, "while setting up the build environment"); + throw ex; } debug(msg); } @@ -2502,7 +2761,7 @@ void DerivationGoal::initEnv() derivation, tell the builder, so that for instance `fetchurl' can skip checking the output. On older Nixes, this environment variable won't be set, so `fetchurl' will do the check. */ - if (fixedOutput) env["NIX_OUTPUT_CHECKED"] = "1"; + if (derivationIsFixed(derivationType)) env["NIX_OUTPUT_CHECKED"] = "1"; /* *Only* if this is a fixed-output derivation, propagate the values of the environment variables specified in the @@ -2513,7 +2772,7 @@ void DerivationGoal::initEnv() to the builder is generally impure, but the output of fixed-output derivations is by definition pure (since we already know the cryptographic hash of the output). */ - if (fixedOutput) { + if (derivationIsImpure(derivationType)) { for (auto & i : parsedDrv->getStringsAttr("impureEnvVars").value_or(Strings())) env[i] = getEnv(i).value_or(""); } @@ -2540,8 +2799,11 @@ void DerivationGoal::writeStructuredAttrs() /* Add an "outputs" object containing the output paths. */ nlohmann::json outputs; - for (auto & i : drv->outputs) - outputs[i.first] = rewriteStrings(worker.store.printStorePath(i.second.path), inputRewrites); + for (auto & i : drv->outputs) { + /* The placeholder must have a rewrite, so we use it to cover both the + cases where we know or don't know the output path ahead of time. */ + outputs[i.first] = rewriteStrings(hashPlaceholder(i.first), inputRewrites); + } json["outputs"] = outputs; /* Handle exportReferencesGraph. */ @@ -2634,18 +2896,23 @@ void DerivationGoal::writeStructuredAttrs() chownToBuilder(tmpDir + "/.attrs.sh"); } +struct RestrictedStoreConfig : LocalFSStoreConfig +{ + using LocalFSStoreConfig::LocalFSStoreConfig; + const std::string name() { return "Restricted Store"; } +}; /* A wrapper around LocalStore that only allows building/querying of paths that are in the input closures of the build or were added via recursive Nix calls. */ -struct RestrictedStore : public LocalFSStore +struct RestrictedStore : public LocalFSStore, public virtual RestrictedStoreConfig { ref next; DerivationGoal & goal; RestrictedStore(const Params & params, ref next, DerivationGoal & goal) - : Store(params), LocalFSStore(params), next(next), goal(goal) + : StoreConfig(params), Store(params), LocalFSStore(params), next(next), goal(goal) { } Path getRealStoreDir() override @@ -2684,8 +2951,12 @@ struct RestrictedStore : public LocalFSStore void queryReferrers(const StorePath & path, StorePathSet & referrers) override { } - OutputPathMap queryDerivationOutputMap(const StorePath & path) override - { throw Error("queryDerivationOutputMap"); } + std::map> queryPartialDerivationOutputMap(const StorePath & path) override + { + if (!goal.isAllowed(path)) + throw InvalidPath("cannot query output map for unknown path '%s' in recursive Nix", printStorePath(path)); + return next->queryPartialDerivationOutputMap(path); + } std::optional queryPathFromHashPart(const std::string & hashPart) override { throw Error("queryPathFromHashPart"); } @@ -2696,21 +2967,12 @@ struct RestrictedStore : public LocalFSStore { throw Error("addToStore"); } void addToStore(const ValidPathInfo & info, Source & narSource, - RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs, - std::shared_ptr accessor = 0) override + RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs) override { - next->addToStore(info, narSource, repair, checkSigs, accessor); + next->addToStore(info, narSource, repair, checkSigs); goal.addDependency(info.path); } - StorePath addToStoreFromDump(const string & dump, const string & name, - FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, RepairFlag repair = NoRepair) override - { - auto path = next->addToStoreFromDump(dump, name, method, hashAlgo, repair); - goal.addDependency(path); - return path; - } - StorePath addTextToStore(const string & name, const string & s, const StorePathSet & references, RepairFlag repair = NoRepair) override { @@ -2740,19 +3002,20 @@ struct RestrictedStore : public LocalFSStore StorePathSet newPaths; for (auto & path : paths) { - if (path.path.isDerivation()) { - if (!goal.isAllowed(path.path)) - throw InvalidPath("cannot build unknown path '%s' in recursive Nix", printStorePath(path.path)); - auto drv = derivationFromPath(path.path); - for (auto & output : drv.outputs) - if (wantOutput(output.first, path.outputs)) - newPaths.insert(output.second.path); - } else if (!goal.isAllowed(path.path)) + if (!goal.isAllowed(path.path)) throw InvalidPath("cannot build unknown path '%s' in recursive Nix", printStorePath(path.path)); } next->buildPaths(paths, buildMode); + for (auto & path : paths) { + if (!path.path.isDerivation()) continue; + auto outputs = next->queryDerivationOutputMap(path.path); + for (auto & output : outputs) + if (wantOutput(output.first, path.outputs)) + newPaths.insert(output.second); + } + StorePathSet closure; next->computeFSClosure(newPaths, closure); for (auto & path : closure) @@ -2780,7 +3043,7 @@ struct RestrictedStore : public LocalFSStore void queryMissing(const std::vector & targets, StorePathSet & willBuild, StorePathSet & willSubstitute, StorePathSet & unknown, - unsigned long long & downloadSize, unsigned long long & narSize) override + uint64_t & downloadSize, uint64_t & narSize) override { /* This is slightly impure since it leaks information to the client about what paths will be built/substituted or are @@ -2849,7 +3112,8 @@ void DerivationGoal::startDaemon() FdSink to(remote.get()); try { daemon::processConnection(store, from, to, - daemon::NotTrusted, daemon::Recursive, "nobody", 65535); + daemon::NotTrusted, daemon::Recursive, + [&](Store & store) { store.createUser("nobody", 65535); }); debug("terminated daemon connection"); } catch (SysError &) { ignoreException(); @@ -2903,9 +3167,7 @@ void DerivationGoal::addDependency(const StorePath & path) if (pathExists(target)) throw Error("store path '%s' already exists in the sandbox", worker.store.printStorePath(path)); - struct stat st; - if (lstat(source.c_str(), &st)) - throw SysError("getting attributes of path '%s'", source); + auto st = lstat(source); if (S_ISDIR(st.st_mode)) { @@ -3108,7 +3370,7 @@ void DerivationGoal::runChild() createDirs(chrootRootDir + "/dev/shm"); createDirs(chrootRootDir + "/dev/pts"); ss.push_back("/dev/full"); - if (settings.systemFeatures.get().count("kvm") && pathExists("/dev/kvm")) + if (worker.store.systemFeatures.get().count("kvm") && pathExists("/dev/kvm")) ss.push_back("/dev/kvm"); ss.push_back("/dev/null"); ss.push_back("/dev/random"); @@ -3124,7 +3386,7 @@ void DerivationGoal::runChild() /* Fixed-output derivations typically need to access the network, so give them access to /etc/resolv.conf and so on. */ - if (fixedOutput) { + if (derivationIsImpure(derivationType)) { ss.push_back("/etc/resolv.conf"); // Only use nss functions to resolve hosts and @@ -3378,17 +3640,13 @@ void DerivationGoal::runChild() sandboxProfile += "(import \"sandbox-defaults.sb\")\n"; - if (fixedOutput) + if (derivationIsImpure(derivationType)) sandboxProfile += "(import \"sandbox-network.sb\")\n"; - /* Our rwx outputs */ + /* Add the output paths we'll use at build-time to the chroot */ sandboxProfile += "(allow file-read* file-write* process-exec\n"; - for (auto & i : missingPaths) - sandboxProfile += fmt("\t(subpath \"%s\")\n", worker.store.printStorePath(i)); - - /* Also add redirected outputs to the chroot */ - for (auto & i : redirectedOutputs) - sandboxProfile += fmt("\t(subpath \"%s\")\n", worker.store.printStorePath(i.second)); + for (auto & [_, path] : scratchOutputs) + sandboxProfile += fmt("\t(subpath \"%s\")\n", worker.store.printStorePath(path)); sandboxProfile += ")\n"; @@ -3474,7 +3732,7 @@ void DerivationGoal::runChild() args.push_back(rewriteStrings(i, inputRewrites)); /* Indicate that we managed to set up the build environment. */ - writeFull(STDERR_FILENO, string("\1\n")); + writeFull(STDERR_FILENO, string("\2\n")); /* Execute the program. This should not return. */ if (drv->isBuiltin()) { @@ -3495,7 +3753,7 @@ void DerivationGoal::runChild() throw Error("unsupported builtin function '%1%'", string(drv->builder, 8)); _exit(0); } catch (std::exception & e) { - writeFull(STDERR_FILENO, "error: " + string(e.what()) + "\n"); + writeFull(STDERR_FILENO, e.what() + std::string("\n")); _exit(1); } } @@ -3504,62 +3762,31 @@ void DerivationGoal::runChild() throw SysError("executing '%1%'", drv->builder); - } catch (std::exception & e) { - writeFull(STDERR_FILENO, "\1while setting up the build environment: " + string(e.what()) + "\n"); + } catch (Error & e) { + writeFull(STDERR_FILENO, "\1\n"); + FdSink sink(STDERR_FILENO); + sink << e; + sink.flush(); _exit(1); } } -/* Parse a list of reference specifiers. Each element must either be - a store path, or the symbolic name of the output of the derivation - (such as `out'). */ -StorePathSet parseReferenceSpecifiers(Store & store, const BasicDerivation & drv, const Strings & paths) -{ - StorePathSet result; - for (auto & i : paths) { - if (store.isStorePath(i)) - result.insert(store.parseStorePath(i)); - else if (drv.outputs.count(i)) - result.insert(drv.outputs.find(i)->second.path); - else throw BuildError("derivation contains an illegal reference specifier '%s'", i); - } - return result; -} - - -static void moveCheckToStore(const Path & src, const Path & dst) -{ - /* For the rename of directory to succeed, we must be running as root or - the directory must be made temporarily writable (to update the - directory's parent link ".."). */ - struct stat st; - if (lstat(src.c_str(), &st) == -1) { - throw SysError("getting attributes of path '%1%'", src); - } - - bool changePerm = (geteuid() && S_ISDIR(st.st_mode) && !(st.st_mode & S_IWUSR)); - - if (changePerm) - chmod_(src, st.st_mode | S_IWUSR); - - if (rename(src.c_str(), dst.c_str())) - throw SysError("renaming '%1%' to '%2%'", src, dst); - - if (changePerm) - chmod_(dst, st.st_mode); -} - - void DerivationGoal::registerOutputs() { /* When using a build hook, the build hook can register the output as valid (by doing `nix-store --import'). If so we don't have - to do anything here. */ + to do anything here. + + We can only early return when the outputs are known a priori. For + floating content-addressed derivations this isn't the case. + */ if (hook) { bool allValid = true; - for (auto & i : drv->outputs) - if (!worker.store.isValidPath(i.second.path)) allValid = false; + for (auto & i : drv->outputsAndOptPaths(worker.store)) { + if (!i.second.second || !worker.store.isValidPath(*i.second.second)) + allValid = false; + } if (allValid) return; } @@ -3580,47 +3807,51 @@ void DerivationGoal::registerOutputs() Nix calls. */ StorePathSet referenceablePaths; for (auto & p : inputPaths) referenceablePaths.insert(p); - for (auto & i : drv->outputs) referenceablePaths.insert(i.second.path); + for (auto & i : scratchOutputs) referenceablePaths.insert(i.second); for (auto & p : addedPaths) referenceablePaths.insert(p); - /* Check whether the output paths were created, and grep each - output path to determine what other paths it references. Also make all - output paths read-only. */ - for (auto & i : drv->outputs) { - auto path = worker.store.printStorePath(i.second.path); - if (!missingPaths.count(i.second.path)) continue; + /* FIXME `needsHashRewrite` should probably be removed and we get to the + real reason why we aren't using the chroot dir */ + auto toRealPathChroot = [&](const Path & p) -> Path { + return useChroot && !needsHashRewrite() + ? chrootRootDir + p + : worker.store.toRealPath(p); + }; - Path actualPath = path; - if (needsHashRewrite()) { - auto r = redirectedOutputs.find(i.second.path); - if (r != redirectedOutputs.end()) { - auto redirected = worker.store.Store::toRealPath(r->second); - if (buildMode == bmRepair - && redirectedBadOutputs.count(i.second.path) - && pathExists(redirected)) - replaceValidPath(path, redirected); - if (buildMode == bmCheck) - actualPath = redirected; - } - } else if (useChroot) { - actualPath = chrootRootDir + path; - if (pathExists(actualPath)) { - /* Move output paths from the chroot to the Nix store. */ - if (buildMode == bmRepair) - replaceValidPath(path, actualPath); - else - if (buildMode != bmCheck && rename(actualPath.c_str(), worker.store.toRealPath(path).c_str()) == -1) - throw SysError("moving build output '%1%' from the sandbox to the Nix store", path); - } - if (buildMode != bmCheck) actualPath = worker.store.toRealPath(path); + /* Check whether the output paths were created, and make all + output paths read-only. Then get the references of each output (that we + might need to register), so we can topologically sort them. For the ones + that are most definitely already installed, we just store their final + name so we can also use it in rewrites. */ + StringSet outputsToSort; + struct AlreadyRegistered { StorePath path; }; + struct PerhapsNeedToRegister { StorePathSet refs; }; + std::map> outputReferencesIfUnregistered; + std::map outputStats; + for (auto & [outputName, _] : drv->outputs) { + auto actualPath = toRealPathChroot(worker.store.printStorePath(scratchOutputs.at(outputName))); + + outputsToSort.insert(outputName); + + /* Updated wanted info to remove the outputs we definitely don't need to register */ + auto & initialInfo = initialOutputs.at(outputName); + + /* Don't register if already valid, and not checking */ + initialInfo.wanted = buildMode == bmCheck + || !(initialInfo.known && initialInfo.known->isValid()); + if (!initialInfo.wanted) { + outputReferencesIfUnregistered.insert_or_assign( + outputName, + AlreadyRegistered { .path = initialInfo.known->path }); + continue; } struct stat st; if (lstat(actualPath.c_str(), &st) == -1) { if (errno == ENOENT) throw BuildError( - "builder for '%s' failed to produce output path '%s'", - worker.store.printStorePath(drvPath), path); + "builder for '%s' failed to produce output path for output '%s' at '%s'", + worker.store.printStorePath(drvPath), outputName, actualPath); throw SysError("getting attributes of path '%s'", actualPath); } @@ -3631,140 +3862,296 @@ void DerivationGoal::registerOutputs() user. */ if ((!S_ISLNK(st.st_mode) && (st.st_mode & (S_IWGRP | S_IWOTH))) || (buildUser && st.st_uid != buildUser->getUID())) - throw BuildError("suspicious ownership or permission on '%1%'; rejecting this build output", path); + throw BuildError( + "suspicious ownership or permission on '%s' for output '%s'; rejecting this build output", + actualPath, outputName); #endif - /* Apply hash rewriting if necessary. */ - bool rewritten = false; - if (!outputRewrites.empty()) { - logWarning({ - .name = "Rewriting hashes", - .hint = hintfmt("rewriting hashes in '%1%'; cross fingers", path) - }); + /* Canonicalise first. This ensures that the path we're + rewriting doesn't contain a hard link to /etc/shadow or + something like that. */ + canonicalisePathMetaData( + actualPath, + buildUser ? std::optional(buildUser->getUIDRange()) : std::nullopt, + inodesSeen); - /* Canonicalise first. This ensures that the path we're - rewriting doesn't contain a hard link to /etc/shadow or - something like that. */ - canonicalisePathMetaData( - actualPath, - buildUser ? std::optional(buildUser->getUIDRange()) : std::nullopt, - inodesSeen); + debug("scanning for references for output '%s' in temp location '%s'", outputName, actualPath); - /* FIXME: this is in-memory. */ - StringSink sink; - dumpPath(actualPath, sink); - deletePath(actualPath); - sink.s = make_ref(rewriteStrings(*sink.s, outputRewrites)); - StringSource source(*sink.s); - restorePath(actualPath, source); + /* Pass blank Sink as we are not ready to hash data at this stage. */ + NullSink blank; + auto references = worker.store.parseStorePathSet( + scanForReferences(blank, actualPath, worker.store.printStorePathSet(referenceablePaths))); - rewritten = true; - } + outputReferencesIfUnregistered.insert_or_assign( + outputName, + PerhapsNeedToRegister { .refs = references }); + outputStats.insert_or_assign(outputName, std::move(st)); + } - /* Check that fixed-output derivations produced the right - outputs (i.e., the content hash should match the specified - hash). */ - std::optional ca; + auto sortedOutputNames = topoSort(outputsToSort, + {[&](const std::string & name) { + return std::visit(overloaded { + /* Since we'll use the already installed versions of these, we + can treat them as leaves and ignore any references they + have. */ + [&](AlreadyRegistered _) { return StringSet {}; }, + [&](PerhapsNeedToRegister refs) { + StringSet referencedOutputs; + /* FIXME build inverted map up front so no quadratic waste here */ + for (auto & r : refs.refs) + for (auto & [o, p] : scratchOutputs) + if (r == p) + referencedOutputs.insert(o); + return referencedOutputs; + }, + }, outputReferencesIfUnregistered.at(name)); + }}, + {[&](const std::string & path, const std::string & parent) { + // TODO with more -vvvv also show the temporary paths for manual inspection. + return BuildError( + "cycle detected in build of '%s' in the references of output '%s' from output '%s'", + worker.store.printStorePath(drvPath), path, parent); + }}); - if (fixedOutput) { + std::reverse(sortedOutputNames.begin(), sortedOutputNames.end()); - if (i.second.hash->method == FileIngestionMethod::Flat) { + for (auto & outputName : sortedOutputNames) { + auto output = drv->outputs.at(outputName); + auto & scratchPath = scratchOutputs.at(outputName); + auto actualPath = toRealPathChroot(worker.store.printStorePath(scratchPath)); + + auto finish = [&](StorePath finalStorePath) { + /* Store the final path */ + finalOutputs.insert_or_assign(outputName, finalStorePath); + /* The rewrite rule will be used in downstream outputs that refer to + use. This is why the topological sort is essential to do first + before this for loop. */ + if (scratchPath != finalStorePath) + outputRewrites[std::string { scratchPath.hashPart() }] = std::string { finalStorePath.hashPart() }; + }; + + std::optional referencesOpt = std::visit(overloaded { + [&](AlreadyRegistered skippedFinalPath) -> std::optional { + finish(skippedFinalPath.path); + return std::nullopt; + }, + [&](PerhapsNeedToRegister r) -> std::optional { + return r.refs; + }, + }, outputReferencesIfUnregistered.at(outputName)); + + if (!referencesOpt) + continue; + auto references = *referencesOpt; + + auto rewriteOutput = [&]() { + /* Apply hash rewriting if necessary. */ + if (!outputRewrites.empty()) { + logWarning({ + .name = "Rewriting hashes", + .hint = hintfmt("rewriting hashes in '%1%'; cross fingers", actualPath), + }); + + /* FIXME: this is in-memory. */ + StringSink sink; + dumpPath(actualPath, sink); + deletePath(actualPath); + sink.s = make_ref(rewriteStrings(*sink.s, outputRewrites)); + StringSource source(*sink.s); + restorePath(actualPath, source); + + /* FIXME: set proper permissions in restorePath() so + we don't have to do another traversal. */ + canonicalisePathMetaData(actualPath, {}, inodesSeen); + } + }; + + auto rewriteRefs = [&]() -> std::pair { + /* In the CA case, we need the rewritten refs to calculate the + final path, therefore we look for a *non-rewritten + self-reference, and use a bool rather try to solve the + computationally intractable fixed point. */ + std::pair res { + false, + {}, + }; + for (auto & r : references) { + auto name = r.name(); + auto origHash = std::string { r.hashPart() }; + if (r == scratchPath) + res.first = true; + else if (outputRewrites.count(origHash) == 0) + res.second.insert(r); + else { + std::string newRef = outputRewrites.at(origHash); + newRef += '-'; + newRef += name; + res.second.insert(StorePath { newRef }); + } + } + return res; + }; + + auto newInfoFromCA = [&](const DerivationOutputCAFloating outputHash) -> ValidPathInfo { + auto & st = outputStats.at(outputName); + if (outputHash.method == FileIngestionMethod::Flat) { /* The output path should be a regular file without execute permission. */ if (!S_ISREG(st.st_mode) || (st.st_mode & S_IXUSR) != 0) throw BuildError( "output path '%1%' should be a non-executable regular file " "since recursive hashing is not enabled (outputHashMode=flat)", - path); + actualPath); } - - /* Check the hash. In hash mode, move the path produced by - the derivation to its content-addressed location. */ - Hash h2 = i.second.hash->method == FileIngestionMethod::Recursive - ? hashPath(*i.second.hash->hash.type, actualPath).first - : hashFile(*i.second.hash->hash.type, actualPath); - - auto dest = worker.store.makeFixedOutputPath(i.second.hash->method, h2, i.second.path.name()); - - if (i.second.hash->hash != h2) { - - /* Throw an error after registering the path as - valid. */ - worker.hashMismatch = true; - delayedException = std::make_exception_ptr( - BuildError("hash mismatch in fixed-output derivation '%s':\n wanted: %s\n got: %s", - worker.store.printStorePath(dest), - i.second.hash->hash.to_string(SRI, true), - h2.to_string(SRI, true))); - - Path actualDest = worker.store.Store::toRealPath(dest); - - if (worker.store.isValidPath(dest)) - std::rethrow_exception(delayedException); - - if (actualPath != actualDest) { - PathLocks outputLocks({actualDest}); - deletePath(actualDest); - if (rename(actualPath.c_str(), actualDest.c_str()) == -1) - throw SysError("moving '%s' to '%s'", actualPath, worker.store.printStorePath(dest)); - } - - path = worker.store.printStorePath(dest); - actualPath = actualDest; + rewriteOutput(); + /* FIXME optimize and deduplicate with addToStore */ + std::string oldHashPart { scratchPath.hashPart() }; + HashModuloSink caSink { outputHash.hashType, oldHashPart }; + switch (outputHash.method) { + case FileIngestionMethod::Recursive: + dumpPath(actualPath, caSink); + break; + case FileIngestionMethod::Flat: + readFile(actualPath, caSink); + break; } - else - assert(worker.store.parseStorePath(path) == dest); - - ca = FixedOutputHash { - .method = i.second.hash->method, - .hash = h2, + auto got = caSink.finish().first; + auto refs = rewriteRefs(); + HashModuloSink narSink { htSHA256, oldHashPart }; + dumpPath(actualPath, narSink); + auto narHashAndSize = narSink.finish(); + ValidPathInfo newInfo0 { + worker.store.makeFixedOutputPath( + outputHash.method, + got, + outputPathName(drv->name, outputName), + refs.second, + refs.first), + narHashAndSize.first, }; + newInfo0.narSize = narHashAndSize.second; + newInfo0.ca = FixedOutputHash { + .method = outputHash.method, + .hash = got, + }; + newInfo0.references = refs.second; + if (refs.first) + newInfo0.references.insert(newInfo0.path); + + assert(newInfo0.ca); + return newInfo0; + }; + + ValidPathInfo newInfo = std::visit(overloaded { + [&](DerivationOutputInputAddressed output) { + /* input-addressed case */ + auto requiredFinalPath = output.path; + /* Preemptively add rewrite rule for final hash, as that is + what the NAR hash will use rather than normalized-self references */ + if (scratchPath != requiredFinalPath) + outputRewrites.insert_or_assign( + std::string { scratchPath.hashPart() }, + std::string { requiredFinalPath.hashPart() }); + rewriteOutput(); + auto narHashAndSize = hashPath(htSHA256, actualPath); + ValidPathInfo newInfo0 { requiredFinalPath, narHashAndSize.first }; + newInfo0.narSize = narHashAndSize.second; + auto refs = rewriteRefs(); + newInfo0.references = refs.second; + if (refs.first) + newInfo0.references.insert(newInfo0.path); + return newInfo0; + }, + [&](DerivationOutputCAFixed dof) { + auto newInfo0 = newInfoFromCA(DerivationOutputCAFloating { + .method = dof.hash.method, + .hashType = dof.hash.hash.type, + }); + + /* Check wanted hash */ + Hash & wanted = dof.hash.hash; + assert(newInfo0.ca); + auto got = getContentAddressHash(*newInfo0.ca); + if (wanted != got) { + /* Throw an error after registering the path as + valid. */ + worker.hashMismatch = true; + delayedException = std::make_exception_ptr( + BuildError("hash mismatch in fixed-output derivation '%s':\n wanted: %s\n got: %s", + worker.store.printStorePath(drvPath), + wanted.to_string(SRI, true), + got.to_string(SRI, true))); + } + return newInfo0; + }, + [&](DerivationOutputCAFloating dof) { + return newInfoFromCA(dof); + }, + }, output.output); + + /* Calculate where we'll move the output files. In the checking case we + will leave leave them where they are, for now, rather than move to + their usual "final destination" */ + auto finalDestPath = worker.store.printStorePath(newInfo.path); + + /* Lock final output path, if not already locked. This happens with + floating CA derivations and hash-mismatching fixed-output + derivations. */ + PathLocks dynamicOutputLock; + auto optFixedPath = output.path(worker.store, drv->name, outputName); + if (!optFixedPath || + worker.store.printStorePath(*optFixedPath) != finalDestPath) + { + assert(newInfo.ca); + dynamicOutputLock.lockPaths({worker.store.toRealPath(finalDestPath)}); } - /* Get rid of all weird permissions. This also checks that - all files are owned by the build user, if applicable. */ - canonicalisePathMetaData(actualPath, - buildUser && !rewritten - ? std::optional(buildUser->getUIDRange()) - : std::nullopt, - inodesSeen); - - /* For this output path, find the references to other paths - contained in it. Compute the SHA-256 NAR hash at the same - time. The hash is stored in the database so that we can - verify later on whether nobody has messed with the store. */ - debug("scanning for references inside '%1%'", path); - HashResult hash; - auto references = worker.store.parseStorePathSet(scanForReferences(actualPath, worker.store.printStorePathSet(referenceablePaths), hash)); + /* Move files, if needed */ + if (worker.store.toRealPath(finalDestPath) != actualPath) { + if (buildMode == bmRepair) { + /* Path already exists, need to replace it */ + replaceValidPath(worker.store.toRealPath(finalDestPath), actualPath); + actualPath = worker.store.toRealPath(finalDestPath); + } else if (buildMode == bmCheck) { + /* Path already exists, and we want to compare, so we leave out + new path in place. */ + } else if (worker.store.isValidPath(newInfo.path)) { + /* Path already exists because CA path produced by something + else. No moving needed. */ + assert(newInfo.ca); + } else { + auto destPath = worker.store.toRealPath(finalDestPath); + movePath(actualPath, destPath); + actualPath = destPath; + } + } if (buildMode == bmCheck) { - if (!worker.store.isValidPath(worker.store.parseStorePath(path))) continue; - ValidPathInfo info(*worker.store.queryPathInfo(worker.store.parseStorePath(path))); - if (hash.first != info.narHash) { + if (!worker.store.isValidPath(newInfo.path)) continue; + ValidPathInfo oldInfo(*worker.store.queryPathInfo(newInfo.path)); + if (newInfo.narHash != oldInfo.narHash) { worker.checkMismatch = true; if (settings.runDiffHook || settings.keepFailed) { - Path dst = worker.store.toRealPath(path + checkSuffix); + auto dst = worker.store.toRealPath(finalDestPath + checkSuffix); deletePath(dst); - moveCheckToStore(actualPath, dst); + movePath(actualPath, dst); handleDiffHook( buildUser ? buildUser->getUID() : getuid(), buildUser ? buildUser->getGID() : getgid(), - path, dst, worker.store.printStorePath(drvPath), tmpDir); + finalDestPath, dst, worker.store.printStorePath(drvPath), tmpDir); throw NotDeterministic("derivation '%s' may not be deterministic: output '%s' differs from '%s'", - worker.store.printStorePath(drvPath), worker.store.toRealPath(path), dst); + worker.store.printStorePath(drvPath), worker.store.toRealPath(finalDestPath), dst); } else throw NotDeterministic("derivation '%s' may not be deterministic: output '%s' differs", - worker.store.printStorePath(drvPath), worker.store.toRealPath(path)); + worker.store.printStorePath(drvPath), worker.store.toRealPath(finalDestPath)); } /* Since we verified the build, it's now ultimately trusted. */ - if (!info.ultimate) { - info.ultimate = true; - worker.store.signPathInfo(info); - ValidPathInfos infos; - infos.push_back(std::move(info)); - worker.store.registerValidPaths(infos); + if (!oldInfo.ultimate) { + oldInfo.ultimate = true; + worker.store.signPathInfo(oldInfo); + worker.store.registerValidPaths({ std::move(oldInfo) }); } continue; @@ -3781,24 +4168,22 @@ void DerivationGoal::registerOutputs() if (curRound == nrRounds) { worker.store.optimisePath(actualPath); // FIXME: combine with scanForReferences() - worker.markContentsGood(worker.store.parseStorePath(path)); + worker.markContentsGood(newInfo.path); } - ValidPathInfo info(worker.store.parseStorePath(path)); - info.narHash = hash.first; - info.narSize = hash.second; - info.references = std::move(references); - info.deriver = drvPath; - info.ultimate = true; - info.ca = ca; - worker.store.signPathInfo(info); + newInfo.deriver = drvPath; + newInfo.ultimate = true; + worker.store.signPathInfo(newInfo); - if (!info.references.empty()) { - // FIXME don't we have an experimental feature for fixed output with references? - info.ca = {}; - } + finish(newInfo.path); - infos.emplace(i.first, std::move(info)); + /* If it's a CA path, register it right away. This is necessary if it + isn't statically known so that we can safely unlock the path before + the next iteration */ + if (newInfo.ca) + worker.store.registerValidPaths({newInfo}); + + infos.emplace(outputName, std::move(newInfo)); } if (buildMode == bmCheck) return; @@ -3841,8 +4226,8 @@ void DerivationGoal::registerOutputs() /* If this is the first round of several, then move the output out of the way. */ if (nrRounds > 1 && curRound == 1 && curRound < nrRounds && keepPreviousRound) { - for (auto & i : drv->outputs) { - auto path = worker.store.printStorePath(i.second.path); + for (auto & [_, outputStorePath] : finalOutputs) { + auto path = worker.store.printStorePath(outputStorePath); Path prev = path + checkSuffix; deletePath(prev); Path dst = path + checkSuffix; @@ -3859,8 +4244,8 @@ void DerivationGoal::registerOutputs() /* Remove the .check directories if we're done. FIXME: keep them if the result was not determistic? */ if (curRound == nrRounds) { - for (auto & i : drv->outputs) { - Path prev = worker.store.printStorePath(i.second.path) + checkSuffix; + for (auto & [_, outputStorePath] : finalOutputs) { + Path prev = worker.store.printStorePath(outputStorePath) + checkSuffix; deletePath(prev); } } @@ -3870,7 +4255,9 @@ void DerivationGoal::registerOutputs() outputs, this will fail. */ { ValidPathInfos infos2; - for (auto & i : infos) infos2.push_back(i.second); + for (auto & [outputName, newInfo] : infos) { + infos2.push_back(newInfo); + } worker.store.registerValidPaths(infos2); } @@ -3878,6 +4265,27 @@ void DerivationGoal::registerOutputs() exception now that we have registered the output as valid. */ if (delayedException) std::rethrow_exception(delayedException); + + /* If we made it this far, we are sure the output matches the derivation + (since the delayedException would be a fixed output CA mismatch). That + means it's safe to link the derivation to the output hash. We must do + that for floating CA derivations, which otherwise couldn't be cached, + but it's fine to do in all cases. */ + bool isCaFloating = drv->type() == DerivationType::CAFloating; + + auto drvPathResolved = drvPath; + if (!useDerivation && isCaFloating) { + /* Once a floating CA derivations reaches this point, it + must already be resolved, so we don't bother trying to + downcast drv to get would would just be an empty + inputDrvs field. */ + Derivation drv2 { *drv }; + drvPathResolved = writeDerivation(worker.store, drv2); + } + + if (useDerivation || isCaFloating) + for (auto & [outputName, newInfo] : infos) + worker.store.linkDeriverToPath(drvPathResolved, outputName, newInfo.path); } @@ -3946,7 +4354,17 @@ void DerivationGoal::checkOutputs(const std::map & outputs) { if (!value) return; - auto spec = parseReferenceSpecifiers(worker.store, *drv, *value); + /* Parse a list of reference specifiers. Each element must + either be a store path, or the symbolic name of the output + of the derivation (such as `out'). */ + StorePathSet spec; + for (auto & i : *value) { + if (worker.store.isStorePath(i)) + spec.insert(worker.store.parseStorePath(i)); + else if (finalOutputs.count(i)) + spec.insert(finalOutputs.at(i)); + else throw BuildError("derivation contains an illegal reference specifier '%s'", i); + } auto used = recursive ? getClosure(info.path).first @@ -4155,31 +4573,67 @@ void DerivationGoal::flushLine() } -StorePathSet DerivationGoal::checkPathValidity(bool returnValid, bool checkHash) +std::map> DerivationGoal::queryPartialDerivationOutputMap() { - StorePathSet result; - for (auto & i : drv->outputs) { - if (!wantOutput(i.first, wantedOutputs)) continue; - bool good = - worker.store.isValidPath(i.second.path) && - (!checkHash || worker.pathContentsGood(i.second.path)); - if (good == returnValid) result.insert(i.second.path); + if (!useDerivation || drv->type() != DerivationType::CAFloating) { + std::map> res; + for (auto & [name, output] : drv->outputs) + res.insert_or_assign(name, output.path(worker.store, drv->name, name)); + return res; + } else { + return worker.store.queryPartialDerivationOutputMap(drvPath); + } +} + +OutputPathMap DerivationGoal::queryDerivationOutputMap() +{ + if (!useDerivation || drv->type() != DerivationType::CAFloating) { + OutputPathMap res; + for (auto & [name, output] : drv->outputsAndOptPaths(worker.store)) + res.insert_or_assign(name, *output.second); + return res; + } else { + return worker.store.queryDerivationOutputMap(drvPath); } - return result; } -void DerivationGoal::addHashRewrite(const StorePath & path) +void DerivationGoal::checkPathValidity() { - auto h1 = std::string(((std::string_view) path.to_string()).substr(0, 32)); - auto p = worker.store.makeStorePath( + bool checkHash = buildMode == bmRepair; + for (auto & i : queryPartialDerivationOutputMap()) { + InitialOutput info { + .wanted = wantOutput(i.first, wantedOutputs), + }; + if (i.second) { + auto outputPath = *i.second; + info.known = { + .path = outputPath, + .status = !worker.store.isValidPath(outputPath) + ? PathStatus::Absent + : !checkHash || worker.pathContentsGood(outputPath) + ? PathStatus::Valid + : PathStatus::Corrupt, + }; + } + initialOutputs.insert_or_assign(i.first, info); + } +} + + +StorePath DerivationGoal::makeFallbackPath(std::string_view outputName) +{ + return worker.store.makeStorePath( + "rewrite:" + std::string(drvPath.to_string()) + ":name:" + std::string(outputName), + Hash(htSHA256), outputPathName(drv->name, outputName)); +} + + +StorePath DerivationGoal::makeFallbackPath(const StorePath & path) +{ + return worker.store.makeStorePath( "rewrite:" + std::string(drvPath.to_string()) + ":" + std::string(path.to_string()), Hash(htSHA256), path.name()); - auto h2 = std::string(((std::string_view) p.to_string()).substr(0, 32)); - deletePath(worker.store.printStorePath(p)); - inputRewrites[h1] = h2; - outputRewrites[h2] = h1; - redirectedOutputs.insert_or_assign(path, std::move(p)); } @@ -4220,6 +4674,10 @@ private: /* The store path that should be realised through a substitute. */ StorePath storePath; + /* The path the substituter refers to the path as. This will be + * different when the stores have different names. */ + std::optional subPath; + /* The remaining substituters. */ std::list> subs; @@ -4253,8 +4711,11 @@ private: typedef void (SubstitutionGoal::*GoalState)(); GoalState state; + /* Content address for recomputing store path */ + std::optional ca; + public: - SubstitutionGoal(const StorePath & storePath, Worker & worker, RepairFlag repair = NoRepair); + SubstitutionGoal(const StorePath & storePath, Worker & worker, RepairFlag repair = NoRepair, std::optional ca = std::nullopt); ~SubstitutionGoal(); void timedOut(Error && ex) override { abort(); }; @@ -4284,10 +4745,11 @@ public: }; -SubstitutionGoal::SubstitutionGoal(const StorePath & storePath, Worker & worker, RepairFlag repair) +SubstitutionGoal::SubstitutionGoal(const StorePath & storePath, Worker & worker, RepairFlag repair, std::optional ca) : Goal(worker) , storePath(storePath) , repair(repair) + , ca(ca) { state = &SubstitutionGoal::init; name = fmt("substitution of '%s'", worker.store.printStorePath(this->storePath)); @@ -4362,14 +4824,18 @@ void SubstitutionGoal::tryNext() sub = subs.front(); subs.pop_front(); - if (sub->storeDir != worker.store.storeDir) { + if (ca) { + subPath = sub->makeFixedOutputPathFromCA(storePath.name(), *ca); + if (sub->storeDir == worker.store.storeDir) + assert(subPath == storePath); + } else if (sub->storeDir != worker.store.storeDir) { tryNext(); return; } try { // FIXME: make async - info = sub->queryPathInfo(storePath); + info = sub->queryPathInfo(subPath ? *subPath : storePath); } catch (InvalidPath &) { tryNext(); return; @@ -4388,6 +4854,19 @@ void SubstitutionGoal::tryNext() throw; } + if (info->path != storePath) { + if (info->isContentAddressed(*sub) && info->references.empty()) { + auto info2 = std::make_shared(*info); + info2->path = storePath; + info = info2; + } else { + printError("asked '%s' for '%s' but got '%s'", + sub->getUri(), worker.store.printStorePath(storePath), sub->printStorePath(info->path)); + tryNext(); + return; + } + } + /* Update the total expected download size. */ auto narInfo = std::dynamic_pointer_cast(info); @@ -4477,7 +4956,7 @@ void SubstitutionGoal::tryToRun() PushActivity pact(act.id); copyStorePath(ref(sub), ref(worker.store.shared_from_this()), - storePath, repair, sub->isTrusted ? NoCheckSigs : CheckSigs); + subPath ? *subPath : storePath, repair, sub->isTrusted ? NoCheckSigs : CheckSigs); promise.set_value(); } catch (...) { @@ -4587,35 +5066,52 @@ Worker::~Worker() } -GoalPtr Worker::makeDerivationGoal(const StorePath & path, +std::shared_ptr Worker::makeDerivationGoalCommon( + const StorePath & drvPath, + const StringSet & wantedOutputs, + std::function()> mkDrvGoal) +{ + WeakGoalPtr & abstract_goal_weak = derivationGoals[drvPath]; + GoalPtr abstract_goal = abstract_goal_weak.lock(); // FIXME + std::shared_ptr goal; + if (!abstract_goal) { + goal = mkDrvGoal(); + abstract_goal_weak = goal; + wakeUp(goal); + } else { + goal = std::dynamic_pointer_cast(abstract_goal); + assert(goal); + goal->addWantedOutputs(wantedOutputs); + } + return goal; +} + + +std::shared_ptr Worker::makeDerivationGoal(const StorePath & drvPath, const StringSet & wantedOutputs, BuildMode buildMode) { - GoalPtr goal = derivationGoals[path].lock(); // FIXME - if (!goal) { - goal = std::make_shared(path, wantedOutputs, *this, buildMode); - derivationGoals.insert_or_assign(path, goal); - wakeUp(goal); - } else - (dynamic_cast(goal.get()))->addWantedOutputs(wantedOutputs); - return goal; + return makeDerivationGoalCommon(drvPath, wantedOutputs, [&]() { + return std::make_shared(drvPath, wantedOutputs, *this, buildMode); + }); } std::shared_ptr Worker::makeBasicDerivationGoal(const StorePath & drvPath, - const BasicDerivation & drv, BuildMode buildMode) + const BasicDerivation & drv, const StringSet & wantedOutputs, BuildMode buildMode) { - auto goal = std::make_shared(drvPath, drv, *this, buildMode); - wakeUp(goal); - return goal; + return makeDerivationGoalCommon(drvPath, wantedOutputs, [&]() { + return std::make_shared(drvPath, drv, wantedOutputs, *this, buildMode); + }); } -GoalPtr Worker::makeSubstitutionGoal(const StorePath & path, RepairFlag repair) +GoalPtr Worker::makeSubstitutionGoal(const StorePath & path, RepairFlag repair, std::optional ca) { - GoalPtr goal = substitutionGoals[path].lock(); // FIXME + WeakGoalPtr & goal_weak = substitutionGoals[path]; + GoalPtr goal = goal_weak.lock(); // FIXME if (!goal) { - goal = std::make_shared(path, *this, repair); - substitutionGoals.insert_or_assign(path, goal); + goal = std::make_shared(path, *this, repair, ca); + goal_weak = goal; wakeUp(goal); } return goal; @@ -4771,8 +5267,17 @@ void Worker::run(const Goals & _topGoals) waitForInput(); else { if (awake.empty() && 0 == settings.maxBuildJobs) - throw Error("unable to start any build; either increase '--max-jobs' " - "or enable remote builds"); + { + if (getMachines().empty()) + throw Error("unable to start any build; either increase '--max-jobs' " + "or enable remote builds." + "\nhttps://nixos.org/nix/manual/#chap-distributed-builds"); + else + throw Error("unable to start any build; remote machines may not have " + "all required system features." + "\nhttps://nixos.org/nix/manual/#chap-distributed-builds"); + + } assert(!awake.empty()); } } @@ -4866,7 +5371,7 @@ void Worker::waitForInput() std::vector buffer(4096); for (auto & k : fds2) { if (pollStatus.at(fdToPollStatus.at(k)).revents) { - ssize_t rd = read(k, buffer.data(), buffer.size()); + ssize_t rd = ::read(k, buffer.data(), buffer.size()); // FIXME: is there a cleaner way to handle pt close // than EIO? Is this even standard? if (rd == 0 || (rd == -1 && errno == EIO)) { @@ -4956,7 +5461,7 @@ bool Worker::pathContentsGood(const StorePath & path) if (!pathExists(store.printStorePath(path))) res = false; else { - HashResult current = hashPath(*info->narHash.type, store.printStorePath(path)); + HashResult current = hashPath(info->narHash.type, store.printStorePath(path)); Hash nullHash(htSHA256); res = info->narHash == nullHash || info->narHash == current.first; } @@ -4982,7 +5487,7 @@ void Worker::markContentsGood(const StorePath & path) static void primeCache(Store & store, const std::vector & paths) { StorePathSet willBuild, willSubstitute, unknown; - unsigned long long downloadSize, narSize; + uint64_t downloadSize, narSize; store.queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); if (!willBuild.empty() && 0 == settings.maxBuildJobs && getMachines().empty()) @@ -5037,7 +5542,7 @@ BuildResult LocalStore::buildDerivation(const StorePath & drvPath, const BasicDe BuildMode buildMode) { Worker worker(*this); - auto goal = worker.makeBasicDerivationGoal(drvPath, drv, buildMode); + auto goal = worker.makeBasicDerivationGoal(drvPath, drv, {}, buildMode); BuildResult result; diff --git a/src/libstore/builtins/buildenv.hh b/src/libstore/builtins/buildenv.hh index 0a37459b0..73c0f5f7f 100644 --- a/src/libstore/builtins/buildenv.hh +++ b/src/libstore/builtins/buildenv.hh @@ -9,7 +9,7 @@ struct Package { Path path; bool active; int priority; - Package(Path path, bool active, int priority) : path{path}, active{active}, priority{priority} {} + Package(const Path & path, bool active, int priority) : path{path}, active{active}, priority{priority} {} }; typedef std::vector Packages; diff --git a/src/libstore/builtins/fetchurl.cc b/src/libstore/builtins/fetchurl.cc index e630cf6f1..4fb5d8a06 100644 --- a/src/libstore/builtins/fetchurl.cc +++ b/src/libstore/builtins/fetchurl.cc @@ -58,17 +58,14 @@ void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData) } }; - /* We always have one output, and if it's a fixed-output derivation (as - checked below) it must be the only output */ - auto & output = drv.outputs.begin()->second; - /* Try the hashed mirrors first. */ - if (output.hash && output.hash->method == FileIngestionMethod::Flat) + if (getAttr("outputHashMode") == "flat") for (auto hashedMirror : settings.hashedMirrors.get()) try { if (!hasSuffix(hashedMirror, "/")) hashedMirror += '/'; - auto & h = output.hash->hash; - fetch(hashedMirror + printHashType(*h.type) + "/" + h.to_string(Base16, false)); + std::optional ht = parseHashTypeOpt(getAttr("outputHashAlgo")); + Hash h = newHashAllowEmpty(getAttr("outputHash"), ht); + fetch(hashedMirror + printHashType(h.type) + "/" + h.to_string(Base16, false)); return; } catch (Error & e) { debug(e.what()); diff --git a/src/libstore/cgroup.cc b/src/libstore/cgroup.cc index 9e5e937df..0ae45e46d 100644 --- a/src/libstore/cgroup.cc +++ b/src/libstore/cgroup.cc @@ -4,7 +4,10 @@ #include "util.hh" #include +#include +#include #include +#include #include diff --git a/src/libstore/content-address.cc b/src/libstore/content-address.cc index 3d753836f..90a3ad1f5 100644 --- a/src/libstore/content-address.cc +++ b/src/libstore/content-address.cc @@ -1,12 +1,16 @@ +#include "args.hh" #include "content-address.hh" +#include "split.hh" namespace nix { -std::string FixedOutputHash::printMethodAlgo() const { - return makeFileIngestionPrefix(method) + printHashType(*hash.type); +std::string FixedOutputHash::printMethodAlgo() const +{ + return makeFileIngestionPrefix(method) + printHashType(hash.type); } -std::string makeFileIngestionPrefix(const FileIngestionMethod m) { +std::string makeFileIngestionPrefix(const FileIngestionMethod m) +{ switch (m) { case FileIngestionMethod::Flat: return ""; @@ -24,11 +28,8 @@ std::string makeFixedOutputCA(FileIngestionMethod method, const Hash & hash) + hash.to_string(Base32, true); } -// FIXME Put this somewhere? -template struct overloaded : Ts... { using Ts::operator()...; }; -template overloaded(Ts...) -> overloaded; - -std::string renderContentAddress(ContentAddress ca) { +std::string renderContentAddress(ContentAddress ca) +{ return std::visit(overloaded { [](TextHash th) { return "text:" + th.hash.to_string(Base32, true); @@ -39,47 +40,110 @@ std::string renderContentAddress(ContentAddress ca) { }, ca); } -ContentAddress parseContentAddress(std::string_view rawCa) { - auto prefixSeparator = rawCa.find(':'); - if (prefixSeparator != string::npos) { - auto prefix = string(rawCa, 0, prefixSeparator); - if (prefix == "text") { - auto hashTypeAndHash = rawCa.substr(prefixSeparator+1, string::npos); - Hash hash = Hash(string(hashTypeAndHash)); - if (*hash.type != htSHA256) { - throw Error("parseContentAddress: the text hash should have type SHA256"); - } - return TextHash { hash }; - } else if (prefix == "fixed") { - // This has to be an inverse of makeFixedOutputCA - auto methodAndHash = rawCa.substr(prefixSeparator+1, string::npos); - if (methodAndHash.substr(0,2) == "r:") { - std::string_view hashRaw = methodAndHash.substr(2,string::npos); - return FixedOutputHash { - .method = FileIngestionMethod::Recursive, - .hash = Hash(string(hashRaw)), - }; - } else { - std::string_view hashRaw = methodAndHash; - return FixedOutputHash { - .method = FileIngestionMethod::Flat, - .hash = Hash(string(hashRaw)), - }; - } - } else { - throw Error("parseContentAddress: format not recognized; has to be text or fixed"); +std::string renderContentAddressMethod(ContentAddressMethod cam) +{ + return std::visit(overloaded { + [](TextHashMethod &th) { + return std::string{"text:"} + printHashType(htSHA256); + }, + [](FixedOutputHashMethod &fshm) { + return "fixed:" + makeFileIngestionPrefix(fshm.fileIngestionMethod) + printHashType(fshm.hashType); } - } else { - throw Error("Not a content address because it lacks an appropriate prefix"); + }, cam); +} + +/* + Parses content address strings up to the hash. + */ +static ContentAddressMethod parseContentAddressMethodPrefix(std::string_view & rest) +{ + std::string_view wholeInput { rest }; + + std::string_view prefix; + { + auto optPrefix = splitPrefixTo(rest, ':'); + if (!optPrefix) + throw UsageError("not a content address because it is not in the form ':': %s", wholeInput); + prefix = *optPrefix; } + + auto parseHashType_ = [&](){ + auto hashTypeRaw = splitPrefixTo(rest, ':'); + if (!hashTypeRaw) + throw UsageError("content address hash must be in form ':', but found: %s", wholeInput); + HashType hashType = parseHashType(*hashTypeRaw); + return std::move(hashType); + }; + + // Switch on prefix + if (prefix == "text") { + // No parsing of the ingestion method, "text" only support flat. + HashType hashType = parseHashType_(); + if (hashType != htSHA256) + throw Error("text content address hash should use %s, but instead uses %s", + printHashType(htSHA256), printHashType(hashType)); + return TextHashMethod {}; + } else if (prefix == "fixed") { + // Parse method + auto method = FileIngestionMethod::Flat; + if (splitPrefix(rest, "r:")) + method = FileIngestionMethod::Recursive; + HashType hashType = parseHashType_(); + return FixedOutputHashMethod { + .fileIngestionMethod = method, + .hashType = std::move(hashType), + }; + } else + throw UsageError("content address prefix '%s' is unrecognized. Recogonized prefixes are 'text' or 'fixed'", prefix); +} + +ContentAddress parseContentAddress(std::string_view rawCa) { + auto rest = rawCa; + + ContentAddressMethod caMethod = parseContentAddressMethodPrefix(rest); + + return std::visit( + overloaded { + [&](TextHashMethod thm) { + return ContentAddress(TextHash { + .hash = Hash::parseNonSRIUnprefixed(rest, htSHA256) + }); + }, + [&](FixedOutputHashMethod fohMethod) { + return ContentAddress(FixedOutputHash { + .method = fohMethod.fileIngestionMethod, + .hash = Hash::parseNonSRIUnprefixed(rest, std::move(fohMethod.hashType)), + }); + }, + }, caMethod); +} + +ContentAddressMethod parseContentAddressMethod(std::string_view caMethod) +{ + std::string_view asPrefix {std::string{caMethod} + ":"}; + return parseContentAddressMethodPrefix(asPrefix); +} + +std::optional parseContentAddressOpt(std::string_view rawCaOpt) +{ + return rawCaOpt == "" ? std::optional() : parseContentAddress(rawCaOpt); }; -std::optional parseContentAddressOpt(std::string_view rawCaOpt) { - return rawCaOpt == "" ? std::optional {} : parseContentAddress(rawCaOpt); -}; - -std::string renderContentAddress(std::optional ca) { +std::string renderContentAddress(std::optional ca) +{ return ca ? renderContentAddress(*ca) : ""; } +Hash getContentAddressHash(const ContentAddress & ca) +{ + return std::visit(overloaded { + [](TextHash th) { + return th.hash; + }, + [](FixedOutputHash fsh) { + return fsh.hash; + } + }, ca); +} + } diff --git a/src/libstore/content-address.hh b/src/libstore/content-address.hh index ba4797f5b..f6a6f5140 100644 --- a/src/libstore/content-address.hh +++ b/src/libstore/content-address.hh @@ -53,4 +53,25 @@ ContentAddress parseContentAddress(std::string_view rawCa); std::optional parseContentAddressOpt(std::string_view rawCaOpt); +Hash getContentAddressHash(const ContentAddress & ca); + +/* + We only have one way to hash text with references, so this is single-value + type is only useful in std::variant. +*/ +struct TextHashMethod { }; +struct FixedOutputHashMethod { + FileIngestionMethod fileIngestionMethod; + HashType hashType; +}; + +typedef std::variant< + TextHashMethod, + FixedOutputHashMethod + > ContentAddressMethod; + +ContentAddressMethod parseContentAddressMethod(std::string_view rawCaMethod); + +std::string renderContentAddressMethod(ContentAddressMethod caMethod); + } diff --git a/src/libstore/daemon.cc b/src/libstore/daemon.cc index a8fb62e0a..99d8add92 100644 --- a/src/libstore/daemon.cc +++ b/src/libstore/daemon.cc @@ -2,7 +2,6 @@ #include "monitor-fd.hh" #include "worker-protocol.hh" #include "store-api.hh" -#include "local-store.hh" #include "finally.hh" #include "affinity.hh" #include "archive.hh" @@ -81,12 +80,12 @@ struct TunnelLogger : public Logger showErrorInfo(oss, ei, false); StringSink buf; - buf << STDERR_NEXT << oss.str() << "\n"; + buf << STDERR_NEXT << oss.str(); enqueueMsg(*buf.s); } /* startWork() means that we're starting an operation for which we - want to send out stderr to the client. */ + want to send out stderr to the client. */ void startWork() { auto state(state_.lock()); @@ -102,17 +101,20 @@ struct TunnelLogger : public Logger /* stopWork() means that we're done; stop sending stderr to the client. */ - void stopWork(bool success = true, const string & msg = "", unsigned int status = 0) + void stopWork(const Error * ex = nullptr) { auto state(state_.lock()); state->canSendStderr = false; - if (success) + if (!ex) to << STDERR_LAST; else { - to << STDERR_ERROR << msg; - if (status != 0) to << status; + if (GET_PROTOCOL_MINOR(clientVersion) >= 26) { + to << STDERR_ERROR << *ex; + } else { + to << STDERR_ERROR << ex->what() << ex->status; + } } } @@ -173,31 +175,6 @@ struct TunnelSource : BufferedSource } }; -/* If the NAR archive contains a single file at top-level, then save - the contents of the file to `s'. Otherwise barf. */ -struct RetrieveRegularNARSink : ParseSink -{ - bool regular; - string s; - - RetrieveRegularNARSink() : regular(true) { } - - void createDirectory(const Path & path) - { - regular = false; - } - - void receiveContents(unsigned char * data, unsigned int len) - { - s.append((const char *) data, len); - } - - void createSymlink(const Path & path, const string & target) - { - regular = false; - } -}; - struct ClientSettings { bool keepFailed; @@ -257,7 +234,7 @@ struct ClientSettings else if (setSubstituters(settings.extraSubstituters)) ; else - warn("ignoring the user-specified setting '%s', because it is a restricted setting and you are not a trusted user", name); + debug("ignoring the client-specified setting '%s', because it is a restricted setting and you are not a trusted user", name); } catch (UsageError & e) { warn(e.what()); } @@ -265,6 +242,23 @@ struct ClientSettings } }; +static void writeValidPathInfo( + ref store, + unsigned int clientVersion, + Sink & to, + std::shared_ptr info) +{ + to << (info->deriver ? store->printStorePath(*info->deriver) : "") + << info->narHash.to_string(Base16, false); + worker_proto::write(*store, to, info->references); + to << info->registrationTime << info->narSize; + if (GET_PROTOCOL_MINOR(clientVersion) >= 16) { + to << info->ultimate + << info->sigs + << renderContentAddress(info->ca); + } +} + static void performOp(TunnelLogger * logger, ref store, TrustedFlag trusted, RecursiveFlag recursive, unsigned int clientVersion, Source & from, BufferedSink & to, unsigned int op) @@ -281,11 +275,11 @@ static void performOp(TunnelLogger * logger, ref store, } case wopQueryValidPaths: { - auto paths = readStorePaths(*store, from); + auto paths = worker_proto::read(*store, from, Phantom {}); logger->startWork(); auto res = store->queryValidPaths(paths); logger->stopWork(); - writeStorePaths(*store, to, res); + worker_proto::write(*store, to, res); break; } @@ -301,11 +295,11 @@ static void performOp(TunnelLogger * logger, ref store, } case wopQuerySubstitutablePaths: { - auto paths = readStorePaths(*store, from); + auto paths = worker_proto::read(*store, from, Phantom {}); logger->startWork(); auto res = store->querySubstitutablePaths(paths); logger->stopWork(); - writeStorePaths(*store, to, res); + worker_proto::write(*store, to, res); break; } @@ -334,7 +328,7 @@ static void performOp(TunnelLogger * logger, ref store, paths = store->queryValidDerivers(path); else paths = store->queryDerivationOutputs(path); logger->stopWork(); - writeStorePaths(*store, to, paths); + worker_proto::write(*store, to, paths); break; } @@ -350,9 +344,9 @@ static void performOp(TunnelLogger * logger, ref store, case wopQueryDerivationOutputMap: { auto path = store->parseStorePath(readString(from)); logger->startWork(); - OutputPathMap outputs = store->queryDerivationOutputMap(path); + auto outputs = store->queryPartialDerivationOutputMap(path); logger->stopWork(); - writeOutputPathMap(*store, to, outputs); + worker_proto::write(*store, to, outputs); break; } @@ -375,52 +369,90 @@ static void performOp(TunnelLogger * logger, ref store, } case wopAddToStore: { - std::string s, baseName; - FileIngestionMethod method; - { - bool fixed; uint8_t recursive; - from >> baseName >> fixed /* obsolete */ >> recursive >> s; - if (recursive > (uint8_t) FileIngestionMethod::Recursive) - throw Error("unsupported FileIngestionMethod with value of %i; you may need to upgrade nix-daemon", recursive); - method = FileIngestionMethod { recursive }; - /* Compatibility hack. */ - if (!fixed) { - s = "sha256"; - method = FileIngestionMethod::Recursive; + if (GET_PROTOCOL_MINOR(clientVersion) >= 25) { + auto name = readString(from); + auto camStr = readString(from); + auto refs = worker_proto::read(*store, from, Phantom {}); + bool repairBool; + from >> repairBool; + auto repair = RepairFlag{repairBool}; + + logger->startWork(); + auto pathInfo = [&]() { + // NB: FramedSource must be out of scope before logger->stopWork(); + ContentAddressMethod contentAddressMethod = parseContentAddressMethod(camStr); + FramedSource source(from); + // TODO this is essentially RemoteStore::addCAToStore. Move it up to Store. + return std::visit(overloaded { + [&](TextHashMethod &_) { + // We could stream this by changing Store + std::string contents = source.drain(); + auto path = store->addTextToStore(name, contents, refs, repair); + return store->queryPathInfo(path); + }, + [&](FixedOutputHashMethod &fohm) { + if (!refs.empty()) + throw UnimplementedError("cannot yet have refs with flat or nar-hashed data"); + auto path = store->addToStoreFromDump(source, name, fohm.fileIngestionMethod, fohm.hashType, repair); + return store->queryPathInfo(path); + }, + }, contentAddressMethod); + }(); + logger->stopWork(); + + to << store->printStorePath(pathInfo->path); + writeValidPathInfo(store, clientVersion, to, pathInfo); + + } else { + HashType hashAlgo; + std::string baseName; + FileIngestionMethod method; + { + bool fixed; + uint8_t recursive; + std::string hashAlgoRaw; + from >> baseName >> fixed /* obsolete */ >> recursive >> hashAlgoRaw; + if (recursive > (uint8_t) FileIngestionMethod::Recursive) + throw Error("unsupported FileIngestionMethod with value of %i; you may need to upgrade nix-daemon", recursive); + method = FileIngestionMethod { recursive }; + /* Compatibility hack. */ + if (!fixed) { + hashAlgoRaw = "sha256"; + method = FileIngestionMethod::Recursive; + } + hashAlgo = parseHashType(hashAlgoRaw); } + + StringSink saved; + TeeSource savedNARSource(from, saved); + RetrieveRegularNARSink savedRegular { saved }; + + if (method == FileIngestionMethod::Recursive) { + /* Get the entire NAR dump from the client and save it to + a string so that we can pass it to + addToStoreFromDump(). */ + ParseSink sink; /* null sink; just parse the NAR */ + parseDump(sink, savedNARSource); + } else + parseDump(savedRegular, from); + + logger->startWork(); + if (!savedRegular.regular) throw Error("regular file expected"); + + // FIXME: try to stream directly from `from`. + StringSource dumpSource { *saved.s }; + auto path = store->addToStoreFromDump(dumpSource, baseName, method, hashAlgo); + logger->stopWork(); + + to << store->printStorePath(path); } - HashType hashAlgo = parseHashType(s); - - TeeSource savedNAR(from); - RetrieveRegularNARSink savedRegular; - - if (method == FileIngestionMethod::Recursive) { - /* Get the entire NAR dump from the client and save it to - a string so that we can pass it to - addToStoreFromDump(). */ - ParseSink sink; /* null sink; just parse the NAR */ - parseDump(sink, savedNAR); - } else - parseDump(savedRegular, from); - - logger->startWork(); - if (!savedRegular.regular) throw Error("regular file expected"); - - auto path = store->addToStoreFromDump( - method == FileIngestionMethod::Recursive ? *savedNAR.data : savedRegular.s, - baseName, - method, - hashAlgo); - logger->stopWork(); - - to << store->printStorePath(path); break; } case wopAddTextToStore: { string suffix = readString(from); string s = readString(from); - auto refs = readStorePaths(*store, from); + auto refs = worker_proto::read(*store, from, Phantom {}); logger->startWork(); auto path = store->addTextToStore(suffix, s, refs, NoRepair); logger->stopWork(); @@ -442,7 +474,7 @@ static void performOp(TunnelLogger * logger, ref store, case wopImportPaths: { logger->startWork(); TunnelSource source(from, to); - auto paths = store->importPaths(source, nullptr, + auto paths = store->importPaths(source, trusted ? NoCheckSigs : CheckSigs); logger->stopWork(); Strings paths2; @@ -474,11 +506,63 @@ static void performOp(TunnelLogger * logger, ref store, case wopBuildDerivation: { auto drvPath = store->parseStorePath(readString(from)); BasicDerivation drv; - readDerivation(from, *store, drv); + readDerivation(from, *store, drv, Derivation::nameFromPath(drvPath)); BuildMode buildMode = (BuildMode) readInt(from); logger->startWork(); - if (!trusted) - throw Error("you are not privileged to build derivations"); + + /* Content-addressed derivations are trustless because their output paths + are verified by their content alone, so any derivation is free to + try to produce such a path. + + Input-addressed derivation output paths, however, are calculated + from the derivation closure that produced them---even knowing the + root derivation is not enough. That the output data actually came + from those derivations is fundamentally unverifiable, but the daemon + trusts itself on that matter. The question instead is whether the + submitted plan has rights to the output paths it wants to fill, and + at least the derivation closure proves that. + + It would have been nice if input-address algorithm merely depended + on the build time closure, rather than depending on the derivation + closure. That would mean input-addressed paths used at build time + would just be trusted and not need their own evidence. This is in + fact fine as the same guarantees would hold *inductively*: either + the remote builder has those paths and already trusts them, or it + needs to build them too and thus their evidence must be provided in + turn. The advantage of this variant algorithm is that the evidence + for input-addressed paths which the remote builder already has + doesn't need to be sent again. + + That said, now that we have floating CA derivations, it is better + that people just migrate to those which also solve this problem, and + others. It's the same migration difficulty with strictly more + benefit. + + Lastly, do note that when we parse fixed-output content-addressed + derivations, we throw out the precomputed output paths and just + store the hashes, so there aren't two competing sources of truth an + attacker could exploit. */ + if (drv.type() == DerivationType::InputAddressed && !trusted) + throw Error("you are not privileged to build input-addressed derivations"); + + /* Make sure that the non-input-addressed derivations that got this far + are in fact content-addressed if we don't trust them. */ + assert(derivationIsCA(drv.type()) || trusted); + + /* Recompute the derivation path when we cannot trust the original. */ + if (!trusted) { + /* Recomputing the derivation path for input-address derivations + makes it harder to audit them after the fact, since we need the + original not-necessarily-resolved derivation to verify the drv + derivation as adequate claim to the input-addressed output + paths. */ + assert(derivationIsCA(drv.type())); + + Derivation drv2; + static_cast(drv2) = drv; + drvPath = writeDerivation(*store, Derivation { drv2 }); + } + auto res = store->buildDerivation(drvPath, drv, buildMode); logger->stopWork(); to << res.status << res.errorMsg; @@ -541,7 +625,7 @@ static void performOp(TunnelLogger * logger, ref store, case wopCollectGarbage: { GCOptions options; options.action = (GCOptions::GCAction) readInt(from); - options.pathsToDelete = readStorePaths(*store, from); + options.pathsToDelete = worker_proto::read(*store, from, Phantom {}); from >> options.ignoreLiveness >> options.maxFreed; // obsolete fields readInt(from); @@ -602,7 +686,7 @@ static void performOp(TunnelLogger * logger, ref store, auto path = store->parseStorePath(readString(from)); logger->startWork(); SubstitutablePathInfos infos; - store->querySubstitutablePathInfos({path}, infos); + store->querySubstitutablePathInfos({{path, std::nullopt}}, infos); logger->stopWork(); auto i = infos.find(path); if (i == infos.end()) @@ -610,7 +694,7 @@ static void performOp(TunnelLogger * logger, ref store, else { to << 1 << (i->second.deriver ? store->printStorePath(*i->second.deriver) : ""); - writeStorePaths(*store, to, i->second.references); + worker_proto::write(*store, to, i->second.references); to << i->second.downloadSize << i->second.narSize; } @@ -618,16 +702,22 @@ static void performOp(TunnelLogger * logger, ref store, } case wopQuerySubstitutablePathInfos: { - auto paths = readStorePaths(*store, from); - logger->startWork(); SubstitutablePathInfos infos; - store->querySubstitutablePathInfos(paths, infos); + StorePathCAMap pathsMap = {}; + if (GET_PROTOCOL_MINOR(clientVersion) < 22) { + auto paths = worker_proto::read(*store, from, Phantom {}); + for (auto & path : paths) + pathsMap.emplace(path, std::nullopt); + } else + pathsMap = worker_proto::read(*store, from, Phantom {}); + logger->startWork(); + store->querySubstitutablePathInfos(pathsMap, infos); logger->stopWork(); to << infos.size(); for (auto & i : infos) { to << store->printStorePath(i.first) << (i.second.deriver ? store->printStorePath(*i.second.deriver) : ""); - writeStorePaths(*store, to, i.second.references); + worker_proto::write(*store, to, i.second.references); to << i.second.downloadSize << i.second.narSize; } break; @@ -637,7 +727,7 @@ static void performOp(TunnelLogger * logger, ref store, logger->startWork(); auto paths = store->queryAllValidPaths(); logger->stopWork(); - writeStorePaths(*store, to, paths); + worker_proto::write(*store, to, paths); break; } @@ -654,15 +744,7 @@ static void performOp(TunnelLogger * logger, ref store, if (info) { if (GET_PROTOCOL_MINOR(clientVersion) >= 17) to << 1; - to << (info->deriver ? store->printStorePath(*info->deriver) : "") - << info->narHash.to_string(Base16, false); - writeStorePaths(*store, to, info->references); - to << info->registrationTime << info->narSize; - if (GET_PROTOCOL_MINOR(clientVersion) >= 16) { - to << info->ultimate - << info->sigs - << renderContentAddress(info->ca); - } + writeValidPathInfo(store, clientVersion, to, info); } else { assert(GET_PROTOCOL_MINOR(clientVersion) >= 17); to << 0; @@ -705,18 +787,19 @@ static void performOp(TunnelLogger * logger, ref store, auto path = store->parseStorePath(readString(from)); logger->startWork(); logger->stopWork(); - dumpPath(store->printStorePath(path), to); + dumpPath(store->toRealPath(path), to); break; } case wopAddToStoreNar: { bool repair, dontCheckSigs; - ValidPathInfo info(store->parseStorePath(readString(from))); + auto path = store->parseStorePath(readString(from)); auto deriver = readString(from); + auto narHash = Hash::parseAny(readString(from), htSHA256); + ValidPathInfo info { path, narHash }; if (deriver != "") info.deriver = store->parseStorePath(deriver); - info.narHash = Hash(readString(from), htSHA256); - info.references = readStorePaths(*store, from); + info.references = worker_proto::read(*store, from, Phantom {}); from >> info.registrationTime >> info.narSize >> info.ultimate; info.sigs = readStrings(from); info.ca = parseContentAddressOpt(readString(from)); @@ -726,24 +809,37 @@ static void performOp(TunnelLogger * logger, ref store, if (!trusted) info.ultimate = false; - std::string saved; - std::unique_ptr source; - if (GET_PROTOCOL_MINOR(clientVersion) >= 21) - source = std::make_unique(from, to); - else { - TeeSink tee(from); - parseDump(tee, tee.source); - saved = std::move(*tee.source.data); - source = std::make_unique(saved); + if (GET_PROTOCOL_MINOR(clientVersion) >= 23) { + logger->startWork(); + { + FramedSource source(from); + store->addToStore(info, source, (RepairFlag) repair, + dontCheckSigs ? NoCheckSigs : CheckSigs); + } + logger->stopWork(); } - logger->startWork(); + else { + std::unique_ptr source; + if (GET_PROTOCOL_MINOR(clientVersion) >= 21) + source = std::make_unique(from, to); + else { + StringSink saved; + TeeSource tee { from, saved }; + ParseSink ether; + parseDump(ether, tee); + source = std::make_unique(std::move(*saved.s)); + } - // FIXME: race if addToStore doesn't read source? - store->addToStore(info, *source, (RepairFlag) repair, - dontCheckSigs ? NoCheckSigs : CheckSigs, nullptr); + logger->startWork(); + + // FIXME: race if addToStore doesn't read source? + store->addToStore(info, *source, (RepairFlag) repair, + dontCheckSigs ? NoCheckSigs : CheckSigs); + + logger->stopWork(); + } - logger->stopWork(); break; } @@ -753,12 +849,12 @@ static void performOp(TunnelLogger * logger, ref store, targets.push_back(store->parsePathWithOutputs(s)); logger->startWork(); StorePathSet willBuild, willSubstitute, unknown; - unsigned long long downloadSize, narSize; + uint64_t downloadSize, narSize; store->queryMissing(targets, willBuild, willSubstitute, unknown, downloadSize, narSize); logger->stopWork(); - writeStorePaths(*store, to, willBuild); - writeStorePaths(*store, to, willSubstitute); - writeStorePaths(*store, to, unknown); + worker_proto::write(*store, to, willBuild); + worker_proto::write(*store, to, willSubstitute); + worker_proto::write(*store, to, unknown); to << downloadSize << narSize; break; } @@ -774,8 +870,7 @@ void processConnection( FdSink & to, TrustedFlag trusted, RecursiveFlag recursive, - const std::string & userName, - uid_t userId) + std::function authHook) { auto monitor = !recursive ? std::make_unique(from.fd) : nullptr; @@ -816,15 +911,7 @@ void processConnection( /* If we can't accept clientVersion, then throw an error *here* (not above). */ - -#if 0 - /* Prevent users from doing something very dangerous. */ - if (geteuid() == 0 && - querySetting("build-users-group", "") == "") - throw Error("if you run 'nix-daemon' as root, then you MUST set 'build-users-group'!"); -#endif - - store->createUser(userName, userId); + authHook(*store); tunnelLogger->stopWork(); to.flush(); @@ -851,10 +938,11 @@ void processConnection( during addTextToStore() / importPath(). If that happens, just send the error message and exit. */ bool errorAllowed = tunnelLogger->state_.lock()->canSendStderr; - tunnelLogger->stopWork(false, e.msg(), e.status); + tunnelLogger->stopWork(&e); if (!errorAllowed) throw; } catch (std::bad_alloc & e) { - tunnelLogger->stopWork(false, "Nix daemon out of memory", 1); + auto ex = Error("Nix daemon out of memory"); + tunnelLogger->stopWork(&ex); throw; } @@ -863,8 +951,13 @@ void processConnection( assert(!tunnelLogger->state_.lock()->canSendStderr); }; + } catch (Error & e) { + tunnelLogger->stopWork(&e); + to.flush(); + return; } catch (std::exception & e) { - tunnelLogger->stopWork(false, e.what(), 1); + auto ex = Error(e.what()); + tunnelLogger->stopWork(&ex); to.flush(); return; } diff --git a/src/libstore/daemon.hh b/src/libstore/daemon.hh index 266932013..67755d54e 100644 --- a/src/libstore/daemon.hh +++ b/src/libstore/daemon.hh @@ -1,3 +1,5 @@ +#pragma once + #include "serialise.hh" #include "store-api.hh" @@ -12,7 +14,10 @@ void processConnection( FdSink & to, TrustedFlag trusted, RecursiveFlag recursive, - const std::string & userName, - uid_t userId); + /* Arbitrary hook to check authorization / initialize user data / whatever + after the protocol has been negotiated. The idea is that this function + and everything it calls doesn't know about this stuff, and the + `nix-daemon` handles that instead. */ + std::function authHook); } diff --git a/src/libstore/derivations.cc b/src/libstore/derivations.cc index 42551ef6b..07b4e772b 100644 --- a/src/libstore/derivations.cc +++ b/src/libstore/derivations.cc @@ -4,16 +4,61 @@ #include "util.hh" #include "worker-protocol.hh" #include "fs-accessor.hh" -#include "istringstream_nocopy.hh" namespace nix { -const StorePath & BasicDerivation::findOutput(const string & id) const +std::optional DerivationOutput::path(const Store & store, std::string_view drvName, std::string_view outputName) const { - auto i = outputs.find(id); - if (i == outputs.end()) - throw Error("derivation has no output '%s'", id); - return i->second.path; + return std::visit(overloaded { + [](DerivationOutputInputAddressed doi) -> std::optional { + return { doi.path }; + }, + [&](DerivationOutputCAFixed dof) -> std::optional { + return { + dof.path(store, drvName, outputName) + }; + }, + [](DerivationOutputCAFloating dof) -> std::optional { + return std::nullopt; + }, + }, output); +} + + +StorePath DerivationOutputCAFixed::path(const Store & store, std::string_view drvName, std::string_view outputName) const { + return store.makeFixedOutputPath( + hash.method, hash.hash, + outputPathName(drvName, outputName)); +} + + +bool derivationIsCA(DerivationType dt) { + switch (dt) { + case DerivationType::InputAddressed: return false; + case DerivationType::CAFixed: return true; + case DerivationType::CAFloating: return true; + }; + // Since enums can have non-variant values, but making a `default:` would + // disable exhaustiveness warnings. + assert(false); +} + +bool derivationIsFixed(DerivationType dt) { + switch (dt) { + case DerivationType::InputAddressed: return false; + case DerivationType::CAFixed: return true; + case DerivationType::CAFloating: return false; + }; + assert(false); +} + +bool derivationIsImpure(DerivationType dt) { + switch (dt) { + case DerivationType::InputAddressed: return false; + case DerivationType::CAFixed: return true; + case DerivationType::CAFloating: return false; + }; + assert(false); } @@ -23,8 +68,8 @@ bool BasicDerivation::isBuiltin() const } -StorePath writeDerivation(ref store, - const Derivation & drv, std::string_view name, RepairFlag repair) +StorePath writeDerivation(Store & store, + const Derivation & drv, RepairFlag repair, bool readOnly) { auto references = drv.inputSrcs; for (auto & i : drv.inputDrvs) @@ -32,11 +77,11 @@ StorePath writeDerivation(ref store, /* Note that the outputs of a derivation are *not* references (that can be missing (of course) and should not necessarily be held during a garbage collection). */ - auto suffix = std::string(name) + drvExtension; - auto contents = drv.unparse(*store, false); - return settings.readOnlyMode - ? store->computeStorePathForText(suffix, contents, references) - : store->addTextToStore(suffix, contents, references, repair); + auto suffix = std::string(drv.name) + drvExtension; + auto contents = drv.unparse(store, false); + return readOnly || settings.readOnlyMode + ? store.computeStorePathForText(suffix, contents, references) + : store.addTextToStore(suffix, contents, references, repair); } @@ -68,12 +113,15 @@ static string parseString(std::istream & str) return res; } +static void validatePath(std::string_view s) { + if (s.size() == 0 || s[0] != '/') + throw FormatError("bad path '%1%' in derivation", s); +} static Path parsePath(std::istream & str) { - string s = parseString(str); - if (s.size() == 0 || s[0] != '/') - throw FormatError("bad path '%1%' in derivation", s); + auto s = parseString(str); + validatePath(s); return s; } @@ -101,38 +149,63 @@ static StringSet parseStrings(std::istream & str, bool arePaths) } -static DerivationOutput parseDerivationOutput(const Store & store, istringstream_nocopy & str) +static DerivationOutput parseDerivationOutput(const Store & store, + std::string_view pathS, std::string_view hashAlgo, std::string_view hash) { - expect(str, ","); auto path = store.parseStorePath(parsePath(str)); - expect(str, ","); auto hashAlgo = parseString(str); - expect(str, ","); const auto hash = parseString(str); - expect(str, ")"); - - std::optional fsh; if (hashAlgo != "") { auto method = FileIngestionMethod::Flat; if (string(hashAlgo, 0, 2) == "r:") { method = FileIngestionMethod::Recursive; - hashAlgo = string(hashAlgo, 2); + hashAlgo = hashAlgo.substr(2); } - const HashType hashType = parseHashType(hashAlgo); - fsh = FixedOutputHash { - .method = std::move(method), - .hash = Hash(hash, hashType), + const auto hashType = parseHashType(hashAlgo); + if (hash != "") { + validatePath(pathS); + return DerivationOutput { + .output = DerivationOutputCAFixed { + .hash = FixedOutputHash { + .method = std::move(method), + .hash = Hash::parseNonSRIUnprefixed(hash, hashType), + }, + }, + }; + } else { + settings.requireExperimentalFeature("ca-derivations"); + assert(pathS == ""); + return DerivationOutput { + .output = DerivationOutputCAFloating { + .method = std::move(method), + .hashType = std::move(hashType), + }, + }; + } + } else { + validatePath(pathS); + return DerivationOutput { + .output = DerivationOutputInputAddressed { + .path = store.parseStorePath(pathS), + } }; } +} - return DerivationOutput { - .path = std::move(path), - .hash = std::move(fsh), - }; +static DerivationOutput parseDerivationOutput(const Store & store, std::istringstream & str) +{ + expect(str, ","); const auto pathS = parseString(str); + expect(str, ","); const auto hashAlgo = parseString(str); + expect(str, ","); const auto hash = parseString(str); + expect(str, ")"); + + return parseDerivationOutput(store, pathS, hashAlgo, hash); } -static Derivation parseDerivation(const Store & store, const string & s) +Derivation parseDerivation(const Store & store, std::string && s, std::string_view name) { Derivation drv; - istringstream_nocopy str(s); + drv.name = name; + + std::istringstream str(std::move(s)); expect(str, "Derive(["); /* Parse the list of outputs. */ @@ -175,34 +248,6 @@ static Derivation parseDerivation(const Store & store, const string & s) } -Derivation readDerivation(const Store & store, const Path & drvPath) -{ - try { - return parseDerivation(store, readFile(drvPath)); - } catch (FormatError & e) { - throw Error("error parsing derivation '%1%': %2%", drvPath, e.msg()); - } -} - - -Derivation Store::derivationFromPath(const StorePath & drvPath) -{ - ensurePath(drvPath); - return readDerivation(drvPath); -} - - -Derivation Store::readDerivation(const StorePath & drvPath) -{ - auto accessor = getFSAccessor(); - try { - return parseDerivation(*this, accessor->readFile(printStorePath(drvPath))); - } catch (FormatError & e) { - throw Error("error parsing derivation '%s': %s", printStorePath(drvPath), e.msg()); - } -} - - static void printString(string & res, std::string_view s) { char buf[s.size() * 2 + 2]; @@ -264,10 +309,23 @@ string Derivation::unparse(const Store & store, bool maskOutputs, for (auto & i : outputs) { if (first) first = false; else s += ','; s += '('; printUnquotedString(s, i.first); - s += ','; printUnquotedString(s, maskOutputs ? "" : store.printStorePath(i.second.path)); - s += ','; printUnquotedString(s, i.second.hash ? i.second.hash->printMethodAlgo() : ""); - s += ','; printUnquotedString(s, - i.second.hash ? i.second.hash->hash.to_string(Base16, false) : ""); + std::visit(overloaded { + [&](DerivationOutputInputAddressed doi) { + s += ','; printUnquotedString(s, maskOutputs ? "" : store.printStorePath(doi.path)); + s += ','; printUnquotedString(s, ""); + s += ','; printUnquotedString(s, ""); + }, + [&](DerivationOutputCAFixed dof) { + s += ','; printUnquotedString(s, maskOutputs ? "" : store.printStorePath(dof.path(store, name, i.first))); + s += ','; printUnquotedString(s, dof.hash.printMethodAlgo()); + s += ','; printUnquotedString(s, dof.hash.hash.to_string(Base16, false)); + }, + [&](DerivationOutputCAFloating dof) { + s += ','; printUnquotedString(s, ""); + s += ','; printUnquotedString(s, makeFileIngestionPrefix(dof.method) + printHashType(dof.hashType)); + s += ','; printUnquotedString(s, ""); + }, + }, i.second.output); s += ')'; } @@ -319,59 +377,144 @@ bool isDerivation(const string & fileName) } -bool BasicDerivation::isFixedOutput() const +std::string outputPathName(std::string_view drvName, std::string_view outputName) { + std::string res { drvName }; + if (outputName != "out") { + res += "-"; + res += outputName; + } + return res; +} + + +DerivationType BasicDerivation::type() const { - return outputs.size() == 1 && - outputs.begin()->first == "out" && - outputs.begin()->second.hash; + std::set inputAddressedOutputs, fixedCAOutputs, floatingCAOutputs; + std::optional floatingHashType; + for (auto & i : outputs) { + std::visit(overloaded { + [&](DerivationOutputInputAddressed _) { + inputAddressedOutputs.insert(i.first); + }, + [&](DerivationOutputCAFixed _) { + fixedCAOutputs.insert(i.first); + }, + [&](DerivationOutputCAFloating dof) { + floatingCAOutputs.insert(i.first); + if (!floatingHashType) { + floatingHashType = dof.hashType; + } else { + if (*floatingHashType != dof.hashType) + throw Error("All floating outputs must use the same hash type"); + } + }, + }, i.second.output); + } + + if (inputAddressedOutputs.empty() && fixedCAOutputs.empty() && floatingCAOutputs.empty()) { + throw Error("Must have at least one output"); + } else if (! inputAddressedOutputs.empty() && fixedCAOutputs.empty() && floatingCAOutputs.empty()) { + return DerivationType::InputAddressed; + } else if (inputAddressedOutputs.empty() && ! fixedCAOutputs.empty() && floatingCAOutputs.empty()) { + if (fixedCAOutputs.size() > 1) + // FIXME: Experimental feature? + throw Error("Only one fixed output is allowed for now"); + if (*fixedCAOutputs.begin() != "out") + throw Error("Single fixed output must be named \"out\""); + return DerivationType::CAFixed; + } else if (inputAddressedOutputs.empty() && fixedCAOutputs.empty() && ! floatingCAOutputs.empty()) { + return DerivationType::CAFloating; + } else { + throw Error("Can't mix derivation output types"); + } } DrvHashes drvHashes; +/* pathDerivationModulo and hashDerivationModulo are mutually recursive + */ -/* Returns the hash of a derivation modulo fixed-output - subderivations. A fixed-output derivation is a derivation with one - output (`out') for which an expected hash and hash algorithm are - specified (using the `outputHash' and `outputHashAlgo' - attributes). We don't want changes to such derivations to - propagate upwards through the dependency graph, changing output - paths everywhere. +/* Look up the derivation by value and memoize the + `hashDerivationModulo` call. + */ +static const DrvHashModulo & pathDerivationModulo(Store & store, const StorePath & drvPath) +{ + auto h = drvHashes.find(drvPath); + if (h == drvHashes.end()) { + assert(store.isValidPath(drvPath)); + // Cache it + h = drvHashes.insert_or_assign( + drvPath, + hashDerivationModulo( + store, + store.readDerivation(drvPath), + false)).first; + } + return h->second; +} - For instance, if we change the url in a call to the `fetchurl' - function, we do not want to rebuild everything depending on it - (after all, (the hash of) the file being downloaded is unchanged). - So the *output paths* should not change. On the other hand, the - *derivation paths* should change to reflect the new dependency - graph. +/* See the header for interface details. These are the implementation details. - That's what this function does: it returns a hash which is just the - hash of the derivation ATerm, except that any input derivation - paths have been replaced by the result of a recursive call to this - function, and that for fixed-output derivations we return a hash of - its output path. */ -Hash hashDerivationModulo(Store & store, const Derivation & drv, bool maskOutputs) + For fixed-output derivations, each hash in the map is not the + corresponding output's content hash, but a hash of that hash along + with other constant data. The key point is that the value is a pure + function of the output's contents, and there are no preimage attacks + either spoofing an output's contents for a derivation, or + spoofing a derivation for an output's contents. + + For regular derivations, it looks up each subderivation from its hash + and recurs. If the subderivation is also regular, it simply + substitutes the derivation path with its hash. If the subderivation + is fixed-output, however, it takes each output hash and pretends it + is a derivation hash producing a single "out" output. This is so we + don't leak the provenance of fixed outputs, reducing pointless cache + misses as the build itself won't know this. + */ +DrvHashModulo hashDerivationModulo(Store & store, const Derivation & drv, bool maskOutputs) { /* Return a fixed hash for fixed-output derivations. */ - if (drv.isFixedOutput()) { - DerivationOutputs::const_iterator i = drv.outputs.begin(); - return hashString(htSHA256, "fixed:out:" - + i->second.hash->printMethodAlgo() + ":" - + i->second.hash->hash.to_string(Base16, false) + ":" - + store.printStorePath(i->second.path)); + switch (drv.type()) { + case DerivationType::CAFloating: + throw Error("Regular input-addressed derivations are not yet allowed to depend on CA derivations"); + case DerivationType::CAFixed: { + std::map outputHashes; + for (const auto & i : drv.outputs) { + auto & dof = std::get(i.second.output); + auto hash = hashString(htSHA256, "fixed:out:" + + dof.hash.printMethodAlgo() + ":" + + dof.hash.hash.to_string(Base16, false) + ":" + + store.printStorePath(dof.path(store, drv.name, i.first))); + outputHashes.insert_or_assign(i.first, std::move(hash)); + } + return outputHashes; + } + case DerivationType::InputAddressed: + break; } /* For other derivations, replace the inputs paths with recursive - calls to this function.*/ + calls to this function. */ std::map inputs2; for (auto & i : drv.inputDrvs) { - auto h = drvHashes.find(i.first); - if (h == drvHashes.end()) { - assert(store.isValidPath(i.first)); - h = drvHashes.insert_or_assign(i.first, hashDerivationModulo(store, - store.readDerivation(i.first), false)).first; - } - inputs2.insert_or_assign(h->second.to_string(Base16, false), i.second); + const auto & res = pathDerivationModulo(store, i.first); + std::visit(overloaded { + // Regular non-CA derivation, replace derivation + [&](Hash drvHash) { + inputs2.insert_or_assign(drvHash.to_string(Base16, false), i.second); + }, + // CA derivation's output hashes + [&](CaOutputHashes outputHashes) { + std::set justOut = { "out" }; + for (auto & output : i.second) { + /* Put each one in with a single "out" output.. */ + const auto h = outputHashes.at(output); + inputs2.insert_or_assign( + h.to_string(Base16, false), + justOut); + } + }, + }, res); } return hashString(htSHA256, drv.unparse(store, maskOutputs, &inputs2)); @@ -392,38 +535,13 @@ bool wantOutput(const string & output, const std::set & wanted) } -StorePathSet BasicDerivation::outputPaths() const -{ - StorePathSet paths; - for (auto & i : outputs) - paths.insert(i.second.path); - return paths; -} - static DerivationOutput readDerivationOutput(Source & in, const Store & store) { - auto path = store.parseStorePath(readString(in)); - auto hashAlgo = readString(in); - auto hash = readString(in); + const auto pathS = readString(in); + const auto hashAlgo = readString(in); + const auto hash = readString(in); - std::optional fsh; - if (hashAlgo != "") { - auto method = FileIngestionMethod::Flat; - if (string(hashAlgo, 0, 2) == "r:") { - method = FileIngestionMethod::Recursive; - hashAlgo = string(hashAlgo, 2); - } - auto hashType = parseHashType(hashAlgo); - fsh = FixedOutputHash { - .method = std::move(method), - .hash = Hash(hash, hashType), - }; - } - - return DerivationOutput { - .path = std::move(path), - .hash = std::move(fsh), - }; + return parseDerivationOutput(store, pathS, hashAlgo, hash); } StringSet BasicDerivation::outputNames() const @@ -434,9 +552,30 @@ StringSet BasicDerivation::outputNames() const return names; } +DerivationOutputsAndOptPaths BasicDerivation::outputsAndOptPaths(const Store & store) const { + DerivationOutputsAndOptPaths outsAndOptPaths; + for (auto output : outputs) + outsAndOptPaths.insert(std::make_pair( + output.first, + std::make_pair(output.second, output.second.path(store, name, output.first)) + ) + ); + return outsAndOptPaths; +} -Source & readDerivation(Source & in, const Store & store, BasicDerivation & drv) +std::string_view BasicDerivation::nameFromPath(const StorePath & drvPath) { + auto nameWithSuffix = drvPath.name(); + constexpr std::string_view extension = ".drv"; + assert(hasSuffix(nameWithSuffix, extension)); + nameWithSuffix.remove_suffix(extension.size()); + return nameWithSuffix; +} + + +Source & readDerivation(Source & in, const Store & store, BasicDerivation & drv, std::string_view name) { + drv.name = name; + drv.outputs.clear(); auto nr = readNum(in); for (size_t n = 0; n < nr; n++) { @@ -445,7 +584,7 @@ Source & readDerivation(Source & in, const Store & store, BasicDerivation & drv) drv.outputs.emplace(std::move(name), std::move(output)); } - drv.inputSrcs = readStorePaths(store, in); + drv.inputSrcs = worker_proto::read(store, in, Phantom {}); in >> drv.platform >> drv.builder; drv.args = readStrings(in); @@ -464,16 +603,26 @@ void writeDerivation(Sink & out, const Store & store, const BasicDerivation & dr { out << drv.outputs.size(); for (auto & i : drv.outputs) { - out << i.first - << store.printStorePath(i.second.path); - if (i.second.hash) { - out << i.second.hash->printMethodAlgo() - << i.second.hash->hash.to_string(Base16, false); - } else { - out << "" << ""; - } + out << i.first; + std::visit(overloaded { + [&](DerivationOutputInputAddressed doi) { + out << store.printStorePath(doi.path) + << "" + << ""; + }, + [&](DerivationOutputCAFixed dof) { + out << store.printStorePath(dof.path(store, drv.name, i.first)) + << dof.hash.printMethodAlgo() + << dof.hash.hash.to_string(Base16, false); + }, + [&](DerivationOutputCAFloating dof) { + out << "" + << (makeFileIngestionPrefix(dof.method) + printHashType(dof.hashType)) + << ""; + }, + }, i.second.output); } - writeStorePaths(store, out, drv.inputSrcs); + worker_proto::write(store, out, drv.inputSrcs); out << drv.platform << drv.builder << drv.args; out << drv.env.size(); for (auto & i : drv.env) @@ -487,5 +636,65 @@ std::string hashPlaceholder(const std::string & outputName) return "/" + hashString(htSHA256, "nix-output:" + outputName).to_string(Base32, false); } +std::string downstreamPlaceholder(const Store & store, const StorePath & drvPath, std::string_view outputName) +{ + auto drvNameWithExtension = drvPath.name(); + auto drvName = drvNameWithExtension.substr(0, drvNameWithExtension.size() - 4); + auto clearText = "nix-upstream-output:" + std::string { drvPath.hashPart() } + ":" + outputPathName(drvName, outputName); + return "/" + hashString(htSHA256, clearText).to_string(Base32, false); +} + + +// N.B. Outputs are left unchanged +static void rewriteDerivation(Store & store, BasicDerivation & drv, const StringMap & rewrites) { + + debug("Rewriting the derivation"); + + for (auto &rewrite: rewrites) { + debug("rewriting %s as %s", rewrite.first, rewrite.second); + } + + drv.builder = rewriteStrings(drv.builder, rewrites); + for (auto & arg: drv.args) { + arg = rewriteStrings(arg, rewrites); + } + + StringPairs newEnv; + for (auto & envVar: drv.env) { + auto envName = rewriteStrings(envVar.first, rewrites); + auto envValue = rewriteStrings(envVar.second, rewrites); + newEnv.emplace(envName, envValue); + } + drv.env = newEnv; +} + + +Sync drvPathResolutions; + +std::optional Derivation::tryResolve(Store & store) { + BasicDerivation resolved { *this }; + + // Input paths that we'll want to rewrite in the derivation + StringMap inputRewrites; + + for (auto & input : inputDrvs) { + auto inputDrvOutputs = store.queryPartialDerivationOutputMap(input.first); + StringSet newOutputNames; + for (auto & outputName : input.second) { + auto actualPathOpt = inputDrvOutputs.at(outputName); + if (!actualPathOpt) + return std::nullopt; + auto actualPath = *actualPathOpt; + inputRewrites.emplace( + downstreamPlaceholder(store, input.first, outputName), + store.printStorePath(actualPath)); + resolved.inputSrcs.insert(std::move(actualPath)); + } + } + + rewriteDerivation(store, resolved, inputRewrites); + + return resolved; +} } diff --git a/src/libstore/derivations.hh b/src/libstore/derivations.hh index 68c53c1ff..d48266774 100644 --- a/src/libstore/derivations.hh +++ b/src/libstore/derivations.hh @@ -4,8 +4,10 @@ #include "types.hh" #include "hash.hh" #include "content-address.hh" +#include "sync.hh" #include +#include namespace nix { @@ -13,20 +15,82 @@ namespace nix { /* Abstract syntax of derivations. */ +/* The traditional non-fixed-output derivation type. */ +struct DerivationOutputInputAddressed +{ + /* Will need to become `std::optional` once input-addressed + derivations are allowed to depend on cont-addressed derivations */ + StorePath path; +}; + +/* Fixed-output derivations, whose output paths are content addressed + according to that fixed output. */ +struct DerivationOutputCAFixed +{ + FixedOutputHash hash; /* hash used for expected hash computation */ + StorePath path(const Store & store, std::string_view drvName, std::string_view outputName) const; +}; + +/* Floating-output derivations, whose output paths are content addressed, but + not fixed, and so are dynamically calculated from whatever the output ends + up being. */ +struct DerivationOutputCAFloating +{ + /* information used for expected hash computation */ + FileIngestionMethod method; + HashType hashType; +}; + struct DerivationOutput { - StorePath path; - std::optional hash; /* hash used for expected hash computation */ + std::variant< + DerivationOutputInputAddressed, + DerivationOutputCAFixed, + DerivationOutputCAFloating + > output; + std::optional hashAlgoOpt(const Store & store) const; + /* Note, when you use this function you should make sure that you're passing + the right derivation name. When in doubt, you should use the safer + interface provided by BasicDerivation::outputsAndOptPaths */ + std::optional path(const Store & store, std::string_view drvName, std::string_view outputName) const; }; typedef std::map DerivationOutputs; +/* These are analogues to the previous DerivationOutputs data type, but they + also contains, for each output, the (optional) store path in which it would + be written. To calculate values of these types, see the corresponding + functions in BasicDerivation */ +typedef std::map> + DerivationOutputsAndPaths; +typedef std::map>> + DerivationOutputsAndOptPaths; + /* For inputs that are sub-derivations, we specify exactly which output IDs we are interested in. */ typedef std::map DerivationInputs; typedef std::map StringPairs; +enum struct DerivationType : uint8_t { + InputAddressed, + CAFixed, + CAFloating, +}; + +/* Do the outputs of the derivation have paths calculated from their content, + or from the derivation itself? */ +bool derivationIsCA(DerivationType); + +/* Is the content of the outputs fixed a-priori via a hash? Never true for + non-CA derivations. */ +bool derivationIsFixed(DerivationType); + +/* Is the derivation impure and needs to access non-deterministic resources, or + pure and can be sandboxed? Note that whether or not we actually sandbox the + derivation is controlled separately. Never true for non-CA derivations. */ +bool derivationIsImpure(DerivationType); + struct BasicDerivation { DerivationOutputs outputs; /* keyed on symbolic IDs */ @@ -35,24 +99,25 @@ struct BasicDerivation Path builder; Strings args; StringPairs env; + std::string name; - BasicDerivation() { } + BasicDerivation() = default; virtual ~BasicDerivation() { }; - /* Return the path corresponding to the output identifier `id' in - the given derivation. */ - const StorePath & findOutput(const std::string & id) const; - bool isBuiltin() const; /* Return true iff this is a fixed-output derivation. */ - bool isFixedOutput() const; - - /* Return the output paths of a derivation. */ - StorePathSet outputPaths() const; + DerivationType type() const; /* Return the output names of a derivation. */ StringSet outputNames() const; + + /* Calculates the maps that contains all the DerivationOutputs, but + augmented with knowledge of the Store paths they would be written + into. */ + DerivationOutputsAndOptPaths outputsAndOptPaths(const Store & store) const; + + static std::string_view nameFromPath(const StorePath & storePath); }; struct Derivation : BasicDerivation @@ -63,7 +128,17 @@ struct Derivation : BasicDerivation std::string unparse(const Store & store, bool maskOutputs, std::map * actualInputs = nullptr) const; - Derivation() { } + /* Return the underlying basic derivation but with these changes: + + 1. Input drvs are emptied, but the outputs of them that were used are + added directly to input sources. + + 2. Input placeholders are replaced with realized input store paths. */ + std::optional tryResolve(Store & store); + + Derivation() = default; + Derivation(const BasicDerivation & bd) : BasicDerivation(bd) { } + Derivation(BasicDerivation && bd) : BasicDerivation(std::move(bd)) { } }; @@ -72,30 +147,96 @@ class Store; enum RepairFlag : bool { NoRepair = false, Repair = true }; /* Write a derivation to the Nix store, and return its path. */ -StorePath writeDerivation(ref store, - const Derivation & drv, std::string_view name, RepairFlag repair = NoRepair); +StorePath writeDerivation(Store & store, + const Derivation & drv, + RepairFlag repair = NoRepair, + bool readOnly = false); /* Read a derivation from a file. */ -Derivation readDerivation(const Store & store, const Path & drvPath); +Derivation parseDerivation(const Store & store, std::string && s, std::string_view name); // FIXME: remove bool isDerivation(const string & fileName); -Hash hashDerivationModulo(Store & store, const Derivation & drv, bool maskOutputs); +/* Calculate the name that will be used for the store path for this + output. + + This is usually -, but is just when + the output name is "out". */ +std::string outputPathName(std::string_view drvName, std::string_view outputName); + +// known CA drv's output hashes, current just for fixed-output derivations +// whose output hashes are always known since they are fixed up-front. +typedef std::map CaOutputHashes; + +typedef std::variant< + Hash, // regular DRV normalized hash + CaOutputHashes +> DrvHashModulo; + +/* Returns hashes with the details of fixed-output subderivations + expunged. + + A fixed-output derivation is a derivation whose outputs have a + specified content hash and hash algorithm. (Currently they must have + exactly one output (`out'), which is specified using the `outputHash' + and `outputHashAlgo' attributes, but the algorithm doesn't assume + this.) We don't want changes to such derivations to propagate upwards + through the dependency graph, changing output paths everywhere. + + For instance, if we change the url in a call to the `fetchurl' + function, we do not want to rebuild everything depending on it---after + all, (the hash of) the file being downloaded is unchanged. So the + *output paths* should not change. On the other hand, the *derivation + paths* should change to reflect the new dependency graph. + + For fixed-output derivations, this returns a map from the name of + each output to its hash, unique up to the output's contents. + + For regular derivations, it returns a single hash of the derivation + ATerm, after subderivations have been likewise expunged from that + derivation. + */ +DrvHashModulo hashDerivationModulo(Store & store, const Derivation & drv, bool maskOutputs); /* Memoisation of hashDerivationModulo(). */ -typedef std::map DrvHashes; +typedef std::map DrvHashes; extern DrvHashes drvHashes; // FIXME: global, not thread-safe +/* Memoisation of `readDerivation(..).resove()`. */ +typedef std::map< + StorePath, + std::optional +> DrvPathResolutions; + +// FIXME: global, though at least thread-safe. +// FIXME: arguably overlaps with hashDerivationModulo memo table. +extern Sync drvPathResolutions; + bool wantOutput(const string & output, const std::set & wanted); struct Source; struct Sink; -Source & readDerivation(Source & in, const Store & store, BasicDerivation & drv); +Source & readDerivation(Source & in, const Store & store, BasicDerivation & drv, std::string_view name); void writeDerivation(Sink & out, const Store & store, const BasicDerivation & drv); +/* This creates an opaque and almost certainly unique string + deterministically from the output name. + + It is used as a placeholder to allow derivations to refer to their + own outputs without needing to use the hash of a derivation in + itself, making the hash near-impossible to calculate. */ std::string hashPlaceholder(const std::string & outputName); +/* This creates an opaque and almost certainly unique string + deterministically from a derivation path and output name. + + It is used as a placeholder to allow derivations to refer to + content-addressed paths whose content --- and thus the path + themselves --- isn't yet known. This occurs when a derivation has a + dependency which is a CA derivation. */ +std::string downstreamPlaceholder(const Store & store, const StorePath & drvPath, std::string_view outputName); + } diff --git a/src/libstore/dummy-store.cc b/src/libstore/dummy-store.cc new file mode 100644 index 000000000..98b745c3a --- /dev/null +++ b/src/libstore/dummy-store.cc @@ -0,0 +1,67 @@ +#include "store-api.hh" +#include "callback.hh" + +namespace nix { + +struct DummyStoreConfig : virtual StoreConfig { + using StoreConfig::StoreConfig; + + const std::string name() override { return "Dummy Store"; } +}; + +struct DummyStore : public Store, public virtual DummyStoreConfig +{ + DummyStore(const std::string scheme, const std::string uri, const Params & params) + : DummyStore(params) + { } + + DummyStore(const Params & params) + : StoreConfig(params) + , Store(params) + { } + + string getUri() override + { + return *uriSchemes().begin(); + } + + void queryPathInfoUncached(const StorePath & path, + Callback> callback) noexcept override + { + callback(nullptr); + } + + static std::set uriSchemes() { + return {"dummy"}; + } + + std::optional queryPathFromHashPart(const std::string & hashPart) override + { unsupported("queryPathFromHashPart"); } + + void addToStore(const ValidPathInfo & info, Source & source, + RepairFlag repair, CheckSigsFlag checkSigs) override + { unsupported("addToStore"); } + + StorePath addToStore(const string & name, const Path & srcPath, + FileIngestionMethod method, HashType hashAlgo, + PathFilter & filter, RepairFlag repair) override + { unsupported("addToStore"); } + + StorePath addTextToStore(const string & name, const string & s, + const StorePathSet & references, RepairFlag repair) override + { unsupported("addTextToStore"); } + + void narFromPath(const StorePath & path, Sink & sink) override + { unsupported("narFromPath"); } + + void ensurePath(const StorePath & path) override + { unsupported("ensurePath"); } + + BuildResult buildDerivation(const StorePath & drvPath, const BasicDerivation & drv, + BuildMode buildMode) override + { unsupported("buildDerivation"); } +}; + +static RegisterStoreImplementation regDummyStore; + +} diff --git a/src/libstore/export-import.cc b/src/libstore/export-import.cc index 57b7e9590..02c839520 100644 --- a/src/libstore/export-import.cc +++ b/src/libstore/export-import.cc @@ -7,24 +7,6 @@ namespace nix { -struct HashAndWriteSink : Sink -{ - Sink & writeSink; - HashSink hashSink; - HashAndWriteSink(Sink & writeSink) : writeSink(writeSink), hashSink(htSHA256) - { - } - virtual void operator () (const unsigned char * data, size_t len) - { - writeSink(data, len); - hashSink(data, len); - } - Hash currentHash() - { - return hashSink.currentHash().first; - } -}; - void Store::exportPaths(const StorePathSet & paths, Sink & sink) { auto sorted = topoSortPaths(paths); @@ -47,28 +29,29 @@ void Store::exportPath(const StorePath & path, Sink & sink) { auto info = queryPathInfo(path); - HashAndWriteSink hashAndWriteSink(sink); + HashSink hashSink(htSHA256); + TeeSink teeSink(sink, hashSink); - narFromPath(path, hashAndWriteSink); + narFromPath(path, teeSink); /* Refuse to export paths that have changed. This prevents filesystem corruption from spreading to other machines. Don't complain if the stored hash is zero (unknown). */ - Hash hash = hashAndWriteSink.currentHash(); - if (hash != info->narHash && info->narHash != Hash(*info->narHash.type)) + Hash hash = hashSink.currentHash().first; + if (hash != info->narHash && info->narHash != Hash(info->narHash.type)) throw Error("hash of path '%s' has changed from '%s' to '%s'!", printStorePath(path), info->narHash.to_string(Base32, true), hash.to_string(Base32, true)); - hashAndWriteSink + teeSink << exportMagic << printStorePath(path); - writeStorePaths(*this, hashAndWriteSink, info->references); - hashAndWriteSink + worker_proto::write(*this, teeSink, info->references); + teeSink << (info->deriver ? printStorePath(*info->deriver) : "") << 0; } -StorePaths Store::importPaths(Source & source, std::shared_ptr accessor, CheckSigsFlag checkSigs) +StorePaths Store::importPaths(Source & source, CheckSigsFlag checkSigs) { StorePaths res; while (true) { @@ -77,33 +60,36 @@ StorePaths Store::importPaths(Source & source, std::shared_ptr acces if (n != 1) throw Error("input doesn't look like something created by 'nix-store --export'"); /* Extract the NAR from the source. */ - TeeSink tee(source); - parseDump(tee, tee.source); + StringSink saved; + TeeSource tee { source, saved }; + ParseSink ether; + parseDump(ether, tee); uint32_t magic = readInt(source); if (magic != exportMagic) throw Error("Nix archive cannot be imported; wrong format"); - ValidPathInfo info(parseStorePath(readString(source))); + auto path = parseStorePath(readString(source)); //Activity act(*logger, lvlInfo, format("importing path '%s'") % info.path); - info.references = readStorePaths(*this, source); - + auto references = worker_proto::read(*this, source, Phantom {}); auto deriver = readString(source); + auto narHash = hashString(htSHA256, *saved.s); + + ValidPathInfo info { path, narHash }; if (deriver != "") info.deriver = parseStorePath(deriver); - - info.narHash = hashString(htSHA256, *tee.source.data); - info.narSize = tee.source.data->size(); + info.references = references; + info.narSize = saved.s->size(); // Ignore optional legacy signature. if (readInt(source) == 1) readString(source); // Can't use underlying source, which would have been exhausted - auto source = StringSource { *tee.source.data }; - addToStore(info, source, NoRepair, checkSigs, accessor); + auto source = StringSource { *saved.s }; + addToStore(info, source, NoRepair, checkSigs); res.push_back(info.path); } diff --git a/src/libstore/filetransfer.cc b/src/libstore/filetransfer.cc index 531b85af8..c2c65af05 100644 --- a/src/libstore/filetransfer.cc +++ b/src/libstore/filetransfer.cc @@ -5,6 +5,7 @@ #include "s3.hh" #include "compression.hh" #include "finally.hh" +#include "callback.hh" #ifdef ENABLE_S3 #include @@ -22,6 +23,7 @@ #include #include #include +#include using namespace std::string_literals; @@ -29,7 +31,7 @@ namespace nix { FileTransferSettings fileTransferSettings; -static GlobalConfig::Register r1(&fileTransferSettings); +static GlobalConfig::Register rFileTransferSettings(&fileTransferSettings); std::string resolveUri(const std::string & uri) { @@ -56,7 +58,7 @@ struct curlFileTransfer : public FileTransfer Callback callback; CURL * req = 0; bool active = false; // whether the handle has been added to the multi object - std::string status; + std::string statusMsg; unsigned int attempt = 0; @@ -111,6 +113,9 @@ struct curlFileTransfer : public FileTransfer requestHeaders = curl_slist_append(requestHeaders, ("If-None-Match: " + request.expectedETag).c_str()); if (!request.mimeType.empty()) requestHeaders = curl_slist_append(requestHeaders, ("Content-Type: " + request.mimeType).c_str()); + for (auto it = request.headers.begin(); it != request.headers.end(); ++it){ + requestHeaders = curl_slist_append(requestHeaders, fmt("%s: %s", it->first, it->second).c_str()); + } } ~TransferItem() @@ -123,7 +128,7 @@ struct curlFileTransfer : public FileTransfer if (requestHeaders) curl_slist_free_all(requestHeaders); try { if (!done) - fail(FileTransferError(Interrupted, "download of '%s' was interrupted", request.uri)); + fail(FileTransferError(Interrupted, nullptr, "download of '%s' was interrupted", request.uri)); } catch (...) { ignoreException(); } @@ -144,6 +149,7 @@ struct curlFileTransfer : public FileTransfer LambdaSink finalSink; std::shared_ptr decompressionSink; + std::optional errorSink; std::exception_ptr writeException; @@ -153,9 +159,19 @@ struct curlFileTransfer : public FileTransfer size_t realSize = size * nmemb; result.bodySize += realSize; - if (!decompressionSink) + if (!decompressionSink) { decompressionSink = makeDecompressionSink(encoding, finalSink); + if (! successfulStatuses.count(getHTTPStatus())) { + // In this case we want to construct a TeeSink, to keep + // the response around (which we figure won't be big + // like an actual download should be) to improve error + // messages. + errorSink = StringSink { }; + } + } + if (errorSink) + (*errorSink)((unsigned char *) contents, realSize); (*decompressionSink)((unsigned char *) contents, realSize); return realSize; @@ -175,12 +191,13 @@ struct curlFileTransfer : public FileTransfer size_t realSize = size * nmemb; std::string line((char *) contents, realSize); printMsg(lvlVomit, format("got header for '%s': %s") % request.uri % trim(line)); - if (line.compare(0, 5, "HTTP/") == 0) { // new response starts + static std::regex statusLine("HTTP/[^ ]+ +[0-9]+(.*)", std::regex::extended | std::regex::icase); + std::smatch match; + if (std::regex_match(line, match, statusLine)) { result.etag = ""; - auto ss = tokenizeString>(line, " "); - status = ss.size() >= 2 ? ss[1] : ""; result.data = std::make_shared(); result.bodySize = 0; + statusMsg = trim(match[1]); acceptRanges = false; encoding = ""; } else { @@ -194,7 +211,9 @@ struct curlFileTransfer : public FileTransfer the expected ETag on a 200 response, then shut down the connection because we already have the data. */ - if (result.etag == request.expectedETag && status == "200") { + long httpStatus = 0; + curl_easy_getinfo(req, CURLINFO_RESPONSE_CODE, &httpStatus); + if (result.etag == request.expectedETag && httpStatus == 200) { debug(format("shutting down on 200 HTTP response with expected ETag")); return 0; } @@ -408,16 +427,21 @@ struct curlFileTransfer : public FileTransfer attempt++; + std::shared_ptr response; + if (errorSink) + response = errorSink->s; auto exc = code == CURLE_ABORTED_BY_CALLBACK && _isInterrupted - ? FileTransferError(Interrupted, fmt("%s of '%s' was interrupted", request.verb(), request.uri)) + ? FileTransferError(Interrupted, response, "%s of '%s' was interrupted", request.verb(), request.uri) : httpStatus != 0 ? FileTransferError(err, - fmt("unable to %s '%s': HTTP error %d", - request.verb(), request.uri, httpStatus) + response, + fmt("unable to %s '%s': HTTP error %d ('%s')", + request.verb(), request.uri, httpStatus, statusMsg) + (code == CURLE_OK ? "" : fmt(" (curl error: %s)", curl_easy_strerror(code))) ) : FileTransferError(err, + response, fmt("unable to %s '%s': %s (%d)", request.verb(), request.uri, curl_easy_strerror(code), code)); @@ -675,7 +699,7 @@ struct curlFileTransfer : public FileTransfer auto s3Res = s3Helper.getObject(bucketName, key); FileTransferResult res; if (!s3Res.data) - throw FileTransferError(NotFound, fmt("S3 object '%s' does not exist", request.uri)); + throw FileTransferError(NotFound, nullptr, "S3 object '%s' does not exist", request.uri); res.data = s3Res.data; callback(std::move(res)); #else @@ -820,6 +844,21 @@ void FileTransfer::download(FileTransferRequest && request, Sink & sink) } } +template +FileTransferError::FileTransferError(FileTransfer::Error error, std::shared_ptr response, const Args & ... args) + : Error(args...), error(error), response(response) +{ + const auto hf = hintfmt(args...); + // FIXME: Due to https://github.com/NixOS/nix/issues/3841 we don't know how + // to print different messages for different verbosity levels. For now + // we add some heuristics for detecting when we want to show the response. + if (response && (response->size() < 1024 || response->find("") != string::npos)) { + err.hint = hintfmt("%1%\n\nresponse body:\n\n%2%", normaltxt(hf.str()), *response); + } else { + err.hint = hf; + } +} + bool isUri(const string & s) { if (s.compare(0, 8, "channel:") == 0) return true; diff --git a/src/libstore/filetransfer.hh b/src/libstore/filetransfer.hh index 11dca2fe0..c89c51a21 100644 --- a/src/libstore/filetransfer.hh +++ b/src/libstore/filetransfer.hh @@ -17,15 +17,30 @@ struct FileTransferSettings : Config Setting userAgentSuffix{this, "", "user-agent-suffix", "String appended to the user agent in HTTP requests."}; - Setting httpConnections{this, 25, "http-connections", - "Number of parallel HTTP connections.", + Setting httpConnections{ + this, 25, "http-connections", + R"( + The maximum number of parallel TCP connections used to fetch + files from binary caches and by other downloads. It defaults + to 25. 0 means no limit. + )", {"binary-caches-parallel-connections"}}; - Setting connectTimeout{this, 0, "connect-timeout", - "Timeout for connecting to servers during downloads. 0 means use curl's builtin default."}; + Setting connectTimeout{ + this, 0, "connect-timeout", + R"( + The timeout (in seconds) for establishing connections in the + binary cache substituter. It corresponds to `curl`’s + `--connect-timeout` option. + )"}; - Setting stalledDownloadTimeout{this, 300, "stalled-download-timeout", - "Timeout (in seconds) for receiving data from servers during download. Nix cancels idle downloads after this timeout's duration."}; + Setting stalledDownloadTimeout{ + this, 300, "stalled-download-timeout", + R"( + The timeout (in seconds) for receiving data from servers + during download. Nix cancels idle downloads after this + timeout's duration. + )"}; Setting tries{this, 5, "download-attempts", "How often Nix will attempt to download a file before giving up."}; @@ -36,6 +51,7 @@ extern FileTransferSettings fileTransferSettings; struct FileTransferRequest { std::string uri; + Headers headers; std::string expectedETag; bool verifyTLS = true; bool head = false; @@ -103,10 +119,12 @@ class FileTransferError : public Error { public: FileTransfer::Error error; + std::shared_ptr response; // intentionally optional + template - FileTransferError(FileTransfer::Error error, const Args & ... args) - : Error(args...), error(error) - { } + FileTransferError(FileTransfer::Error error, std::shared_ptr response, const Args & ... args); + + virtual const char* sname() const override { return "FileTransferError"; } }; bool isUri(const string & s); diff --git a/src/libstore/gc.cc b/src/libstore/gc.cc index 57fb20845..518a357ef 100644 --- a/src/libstore/gc.cc +++ b/src/libstore/gc.cc @@ -85,8 +85,7 @@ void LocalStore::addIndirectRoot(const Path & path) } -Path LocalFSStore::addPermRoot(const StorePath & storePath, - const Path & _gcRoot, bool indirect, bool allowOutsideRootsDir) +Path LocalFSStore::addPermRoot(const StorePath & storePath, const Path & _gcRoot) { Path gcRoot(canonPath(_gcRoot)); @@ -95,47 +94,12 @@ Path LocalFSStore::addPermRoot(const StorePath & storePath, "creating a garbage collector root (%1%) in the Nix store is forbidden " "(are you running nix-build inside the store?)", gcRoot); - if (indirect) { - /* Don't clobber the link if it already exists and doesn't - point to the Nix store. */ - if (pathExists(gcRoot) && (!isLink(gcRoot) || !isInStore(readLink(gcRoot)))) - throw Error("cannot create symlink '%1%'; already exists", gcRoot); - makeSymlink(gcRoot, printStorePath(storePath)); - addIndirectRoot(gcRoot); - } - - else { - if (!allowOutsideRootsDir) { - Path rootsDir = canonPath((format("%1%/%2%") % stateDir % gcRootsDir).str()); - - if (string(gcRoot, 0, rootsDir.size() + 1) != rootsDir + "/") - throw Error( - "path '%1%' is not a valid garbage collector root; " - "it's not in the directory '%2%'", - gcRoot, rootsDir); - } - - if (baseNameOf(gcRoot) == std::string(storePath.to_string())) - writeFile(gcRoot, ""); - else - makeSymlink(gcRoot, printStorePath(storePath)); - } - - /* Check that the root can be found by the garbage collector. - !!! This can be very slow on machines that have many roots. - Instead of reading all the roots, it would be more efficient to - check if the root is in a directory in or linked from the - gcroots directory. */ - if (settings.checkRootReachability) { - auto roots = findRoots(false); - if (roots[storePath].count(gcRoot) == 0) - logWarning({ - .name = "GC root", - .hint = hintfmt("warning: '%1%' is not in a directory where the garbage collector looks for roots; " - "therefore, '%2%' might be removed by the garbage collector", - gcRoot, printStorePath(storePath)) - }); - } + /* Don't clobber the link if it already exists and doesn't + point to the Nix store. */ + if (pathExists(gcRoot) && (!isLink(gcRoot) || !isInStore(readLink(gcRoot)))) + throw Error("cannot create symlink '%1%'; already exists", gcRoot); + makeSymlink(gcRoot, printStorePath(storePath)); + addIndirectRoot(gcRoot); /* Grab the global GC root, causing us to block while a GC is in progress. This prevents the set of permanent roots from @@ -262,11 +226,13 @@ void LocalStore::findTempRoots(FDs & fds, Roots & tempRoots, bool censor) void LocalStore::findRoots(const Path & path, unsigned char type, Roots & roots) { auto foundRoot = [&](const Path & path, const Path & target) { - auto storePath = maybeParseStorePath(toStorePath(target)); - if (storePath && isValidPath(*storePath)) - roots[std::move(*storePath)].emplace(path); - else - printInfo("skipping invalid root from '%1%' to '%2%'", path, target); + try { + auto storePath = toStorePath(target).first; + if (isValidPath(storePath)) + roots[std::move(storePath)].emplace(path); + else + printInfo("skipping invalid root from '%1%' to '%2%'", path, target); + } catch (BadStorePath &) { } }; try { @@ -472,15 +438,15 @@ void LocalStore::findRuntimeRoots(Roots & roots, bool censor) for (auto & [target, links] : unchecked) { if (!isInStore(target)) continue; - Path pathS = toStorePath(target); - if (!isStorePath(pathS)) continue; - auto path = parseStorePath(pathS); - if (!isValidPath(path)) continue; - debug("got additional root '%1%'", pathS); - if (censor) - roots[path].insert(censored); - else - roots[path].insert(links.begin(), links.end()); + try { + auto path = toStorePath(target).first; + if (!isValidPath(path)) continue; + debug("got additional root '%1%'", printStorePath(path)); + if (censor) + roots[path].insert(censored); + else + roots[path].insert(links.begin(), links.end()); + } catch (BadStorePath &) { } } } @@ -498,7 +464,7 @@ struct LocalStore::GCState StorePathSet alive; bool gcKeepOutputs; bool gcKeepDerivations; - unsigned long long bytesInvalidated; + uint64_t bytesInvalidated; bool moveToTrash = true; bool shouldDelete; GCState(const GCOptions & options, GCResults & results) @@ -516,7 +482,7 @@ bool LocalStore::isActiveTempFile(const GCState & state, void LocalStore::deleteGarbage(GCState & state, const Path & path) { - unsigned long long bytesFreed; + uint64_t bytesFreed; deletePath(path, bytesFreed); state.results.bytesFreed += bytesFreed; } @@ -526,7 +492,7 @@ void LocalStore::deletePathRecursive(GCState & state, const Path & path) { checkInterrupt(); - unsigned long long size = 0; + uint64_t size = 0; auto storePath = maybeParseStorePath(path); if (storePath && isValidPath(*storePath)) { @@ -608,9 +574,12 @@ bool LocalStore::canReachRoot(GCState & state, StorePathSet & visited, const Sto /* If keep-derivations is set and this is a derivation, then don't delete the derivation if any of the outputs are alive. */ if (state.gcKeepDerivations && path.isDerivation()) { - for (auto & i : queryDerivationOutputs(path)) - if (isValidPath(i) && queryPathInfo(i)->deriver == path) - incoming.insert(i); + for (auto & [name, maybeOutPath] : queryPartialDerivationOutputMap(path)) + if (maybeOutPath && + isValidPath(*maybeOutPath) && + queryPathInfo(*maybeOutPath)->deriver == path + ) + incoming.insert(*maybeOutPath); } /* If keep-outputs is set, then don't delete this path if there @@ -685,7 +654,7 @@ void LocalStore::removeUnusedLinks(const GCState & state) AutoCloseDir dir(opendir(linksDir.c_str())); if (!dir) throw SysError("opening directory '%1%'", linksDir); - long long actualSize = 0, unsharedSize = 0; + int64_t actualSize = 0, unsharedSize = 0; struct dirent * dirent; while (errno = 0, dirent = readdir(dir.get())) { @@ -694,9 +663,7 @@ void LocalStore::removeUnusedLinks(const GCState & state) if (name == "." || name == "..") continue; Path path = linksDir + "/" + name; - struct stat st; - if (lstat(path.c_str(), &st) == -1) - throw SysError("statting '%1%'", path); + auto st = lstat(path); if (st.st_nlink != 1) { actualSize += st.st_size; @@ -715,10 +682,10 @@ void LocalStore::removeUnusedLinks(const GCState & state) struct stat st; if (stat(linksDir.c_str(), &st) == -1) throw SysError("statting '%1%'", linksDir); - long long overhead = st.st_blocks * 512ULL; + auto overhead = st.st_blocks * 512ULL; - printInfo(format("note: currently hard linking saves %.2f MiB") - % ((unsharedSize - actualSize - overhead) / (1024.0 * 1024.0))); + printInfo("note: currently hard linking saves %.2f MiB", + ((unsharedSize - actualSize - overhead) / (1024.0 * 1024.0))); } diff --git a/src/libstore/globals.cc b/src/libstore/globals.cc index 683fa5196..1238dc530 100644 --- a/src/libstore/globals.cc +++ b/src/libstore/globals.cc @@ -2,6 +2,7 @@ #include "util.hh" #include "archive.hh" #include "args.hh" +#include "abstract-setting-to-json.hh" #include #include @@ -9,6 +10,8 @@ #include #include +#include + namespace nix { @@ -22,7 +25,7 @@ namespace nix { Settings settings; -static GlobalConfig::Register r1(&settings); +static GlobalConfig::Register rSettings(&settings); Settings::Settings() : nixPrefix(NIX_PREFIX) @@ -39,6 +42,7 @@ Settings::Settings() { buildUsersGroup = getuid() == 0 ? "nixbld" : ""; lockCPU = getEnv("NIX_AFFINITY_HACK") == "1"; + allowSymlinkedStore = getEnv("NIX_IGNORE_SYMLINK_STORE") == "1"; caFile = getEnv("NIX_SSL_CERT_FILE").value_or(getEnv("SSL_CERT_FILE").value_or("")); if (caFile == "") { @@ -144,6 +148,12 @@ bool Settings::isWSL1() const string nixVersion = PACKAGE_VERSION; +NLOHMANN_JSON_SERIALIZE_ENUM(SandboxMode, { + {SandboxMode::smEnabled, true}, + {SandboxMode::smRelaxed, "relaxed"}, + {SandboxMode::smDisabled, false}, +}); + template<> void BaseSetting::set(const std::string & str) { if (str == "true") value = smEnabled; @@ -160,11 +170,6 @@ template<> std::string BaseSetting::to_string() const else abort(); } -template<> void BaseSetting::toJSON(JSONPlaceholder & out) -{ - AbstractSetting::toJSON(out); -} - template<> void BaseSetting::convertToArg(Args & args, const std::string & category) { args.addFlag({ diff --git a/src/libstore/globals.hh b/src/libstore/globals.hh index 5cf73c7b4..aa1fbdeb7 100644 --- a/src/libstore/globals.hh +++ b/src/libstore/globals.hh @@ -80,73 +80,178 @@ public: Setting keepGoing{this, false, "keep-going", "Whether to keep building derivations when another build fails."}; - Setting tryFallback{this, false, "fallback", - "Whether to fall back to building when substitution fails.", + Setting tryFallback{ + this, false, "fallback", + R"( + If set to `true`, Nix will fall back to building from source if a + binary substitute fails. This is equivalent to the `--fallback` + flag. The default is `false`. + )", {"build-fallback"}}; /* Whether to show build log output in real time. */ bool verboseBuild = true; Setting logLines{this, 10, "log-lines", - "If verbose-build is false, the number of lines of the tail of " + "If `verbose-build` is false, the number of lines of the tail of " "the log to show if a build fails."}; - MaxBuildJobsSetting maxBuildJobs{this, 1, "max-jobs", - "Maximum number of parallel build jobs. \"auto\" means use number of cores.", + MaxBuildJobsSetting maxBuildJobs{ + this, 1, "max-jobs", + R"( + This option defines the maximum number of jobs that Nix will try to + build in parallel. The default is `1`. The special value `auto` + causes Nix to use the number of CPUs in your system. `0` is useful + when using remote builders to prevent any local builds (except for + `preferLocalBuild` derivation attribute which executes locally + regardless). It can be overridden using the `--max-jobs` (`-j`) + command line switch. + )", {"build-max-jobs"}}; - Setting buildCores{this, getDefaultCores(), "cores", - "Number of CPU cores to utilize in parallel within a build, " - "i.e. by passing this number to Make via '-j'. 0 means that the " - "number of actual CPU cores on the local host ought to be " - "auto-detected.", {"build-cores"}}; + Setting buildCores{ + this, getDefaultCores(), "cores", + R"( + Sets the value of the `NIX_BUILD_CORES` environment variable in the + invocation of builders. Builders can use this variable at their + discretion to control the maximum amount of parallelism. For + instance, in Nixpkgs, if the derivation attribute + `enableParallelBuilding` is set to `true`, the builder passes the + `-jN` flag to GNU Make. It can be overridden using the `--cores` + command line switch and defaults to `1`. The value `0` means that + the builder should use all available CPU cores in the system. + )", + {"build-cores"}}; /* Read-only mode. Don't copy stuff to the store, don't change the database. */ bool readOnlyMode = false; - Setting thisSystem{this, SYSTEM, "system", - "The canonical Nix system name."}; + Setting thisSystem{ + this, SYSTEM, "system", + R"( + This option specifies the canonical Nix system name of the current + installation, such as `i686-linux` or `x86_64-darwin`. Nix can only + build derivations whose `system` attribute equals the value + specified here. In general, it never makes sense to modify this + value from its default, since you can use it to ‘lie’ about the + platform you are building on (e.g., perform a Mac OS build on a + Linux machine; the result would obviously be wrong). It only makes + sense if the Nix binaries can run on multiple platforms, e.g., + ‘universal binaries’ that run on `x86_64-linux` and `i686-linux`. - Setting maxSilentTime{this, 0, "max-silent-time", - "The maximum time in seconds that a builer can go without " - "producing any output on stdout/stderr before it is killed. " - "0 means infinity.", + It defaults to the canonical Nix system name detected by `configure` + at build time. + )"}; + + Setting maxSilentTime{ + this, 0, "max-silent-time", + R"( + This option defines the maximum number of seconds that a builder can + go without producing any data on standard output or standard error. + This is useful (for instance in an automated build system) to catch + builds that are stuck in an infinite loop, or to catch remote builds + that are hanging due to network problems. It can be overridden using + the `--max-silent-time` command line switch. + + The value `0` means that there is no timeout. This is also the + default. + )", {"build-max-silent-time"}}; - Setting buildTimeout{this, 0, "timeout", - "The maximum duration in seconds that a builder can run. " - "0 means infinity.", {"build-timeout"}}; + Setting buildTimeout{ + this, 0, "timeout", + R"( + This option defines the maximum number of seconds that a builder can + run. This is useful (for instance in an automated build system) to + catch builds that are stuck in an infinite loop but keep writing to + their standard output or standard error. It can be overridden using + the `--timeout` command line switch. + + The value `0` means that there is no timeout. This is also the + default. + )", + {"build-timeout"}}; PathSetting buildHook{this, true, nixLibexecDir + "/nix/build-remote", "build-hook", "The path of the helper program that executes builds to remote machines."}; - Setting builders{this, "@" + nixConfDir + "/machines", "builders", - "A semicolon-separated list of build machines, in the format of nix.machines."}; + Setting builders{ + this, "@" + nixConfDir + "/machines", "builders", + "A semicolon-separated list of build machines, in the format of `nix.machines`."}; - Setting buildersUseSubstitutes{this, false, "builders-use-substitutes", - "Whether build machines should use their own substitutes for obtaining " - "build dependencies if possible, rather than waiting for this host to " - "upload them."}; + Setting buildersUseSubstitutes{ + this, false, "builders-use-substitutes", + R"( + If set to `true`, Nix will instruct remote build machines to use + their own binary substitutes if available. In practical terms, this + means that remote hosts will fetch as many build dependencies as + possible from their own substitutes (e.g, from `cache.nixos.org`), + instead of waiting for this host to upload them all. This can + drastically reduce build times if the network connection between + this computer and the remote build host is slow. + )"}; Setting reservedSize{this, 8 * 1024 * 1024, "gc-reserved-space", "Amount of reserved disk space for the garbage collector."}; - Setting fsyncMetadata{this, true, "fsync-metadata", - "Whether SQLite should use fsync()."}; + Setting fsyncMetadata{ + this, true, "fsync-metadata", + R"( + If set to `true`, changes to the Nix store metadata (in + `/nix/var/nix/db`) are synchronously flushed to disk. This improves + robustness in case of system crashes, but reduces performance. The + default is `true`. + )"}; Setting useSQLiteWAL{this, !isWSL1(), "use-sqlite-wal", "Whether SQLite should use WAL mode."}; Setting syncBeforeRegistering{this, false, "sync-before-registering", - "Whether to call sync() before registering a path as valid."}; + "Whether to call `sync()` before registering a path as valid."}; - Setting useSubstitutes{this, true, "substitute", - "Whether to use substitutes.", + Setting useSubstitutes{ + this, true, "substitute", + R"( + If set to `true` (default), Nix will use binary substitutes if + available. This option can be disabled to force building from + source. + )", {"build-use-substitutes"}}; - Setting buildUsersGroup{this, "", "build-users-group", - "The Unix group that contains the build users."}; + Setting buildUsersGroup{ + this, "", "build-users-group", + R"( + This options specifies the Unix group containing the Nix build user + accounts. In multi-user Nix installations, builds should not be + performed by the Nix account since that would allow users to + arbitrarily modify the Nix store and database by supplying specially + crafted builders; and they cannot be performed by the calling user + since that would allow him/her to influence the build result. + + Therefore, if this option is non-empty and specifies a valid group, + builds will be performed under the user accounts that are a member + of the group specified here (as listed in `/etc/group`). Those user + accounts should not be used for any other purpose\! + + Nix will never run two builds under the same user account at the + same time. This is to prevent an obvious security hole: a malicious + user writing a Nix expression that modifies the build result of a + legitimate Nix expression being built by another user. Therefore it + is good to have as many Nix build user accounts as you can spare. + (Remember: uids are cheap.) + + The build users should have permission to create files in the Nix + store, but not delete them. Therefore, `/nix/store` should be owned + by the Nix account, its group should be the group specified here, + and its mode should be `1775`. + + If the build users group is empty, builds will be performed under + the uid of the Nix process (that is, the uid of the caller if + `NIX_REMOTE` is empty, the uid under which the Nix daemon runs if + `NIX_REMOTE` is `daemon`). Obviously, this should not be used in + multi-user settings with untrusted users. + )"}; #if __linux__ Setting autoAllocateUids{this, false, "auto-allocate-uids", @@ -165,17 +270,32 @@ public: "Whether to impersonate a Linux 2.6 machine on newer kernels.", {"build-impersonate-linux-26"}}; - Setting keepLog{this, true, "keep-build-log", - "Whether to store build logs.", + Setting keepLog{ + this, true, "keep-build-log", + R"( + 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`. + )", {"build-keep-log"}}; - Setting compressLog{this, true, "compress-build-log", - "Whether to compress logs.", + Setting compressLog{ + this, true, "compress-build-log", + R"( + If set to `true` (the default), build logs written to + `/nix/var/log/nix/drvs` will be compressed on the fly using bzip2. + Otherwise, they will not be compressed. + )", {"build-compress-log"}}; - Setting maxLogSize{this, 0, "max-build-log-size", - "Maximum number of bytes a builder can write to stdout/stderr " - "before being killed (0 means no limit).", + Setting maxLogSize{ + this, 0, "max-build-log-size", + R"( + This option defines the maximum number of bytes that a builder can + write to its stdout/stderr. If the builder exceeds this limit, it’s + killed. A value of `0` (the default) means that there is no limit. + )", {"build-max-log-size"}}; /* When buildRepeat > 0 and verboseBuild == true, whether to print @@ -186,57 +306,156 @@ public: Setting pollInterval{this, 5, "build-poll-interval", "How often (in seconds) to poll for locks."}; - Setting checkRootReachability{this, false, "gc-check-reachability", - "Whether to check if new GC roots can in fact be found by the " - "garbage collector."}; + Setting gcKeepOutputs{ + this, false, "keep-outputs", + R"( + If `true`, the garbage collector will keep the outputs of + non-garbage derivations. If `false` (default), outputs will be + deleted unless they are GC roots themselves (or reachable from other + roots). - Setting gcKeepOutputs{this, false, "keep-outputs", - "Whether the garbage collector should keep outputs of live derivations.", + In general, outputs must be registered as roots separately. However, + even if the output of a derivation is registered as a root, the + collector will still delete store paths that are used only at build + time (e.g., the C compiler, or source tarballs downloaded from the + network). To prevent it from doing so, set this option to `true`. + )", {"gc-keep-outputs"}}; - Setting gcKeepDerivations{this, true, "keep-derivations", - "Whether the garbage collector should keep derivers of live paths.", + Setting gcKeepDerivations{ + this, true, "keep-derivations", + R"( + If `true` (default), the garbage collector will keep the derivations + from which non-garbage store paths were built. If `false`, they will + be deleted unless explicitly registered as a root (or reachable from + other roots). + + Keeping derivation around is useful for querying and traceability + (e.g., it allows you to ask with what dependencies or options a + store path was built), so by default this option is on. Turn it off + to save a bit of disk space (or a lot if `keep-outputs` is also + turned on). + )", {"gc-keep-derivations"}}; - Setting autoOptimiseStore{this, false, "auto-optimise-store", - "Whether to automatically replace files with identical contents with hard links."}; + Setting autoOptimiseStore{ + this, false, "auto-optimise-store", + R"( + 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. + )"}; - Setting envKeepDerivations{this, false, "keep-env-derivations", - "Whether to add derivations as a dependency of user environments " - "(to prevent them from being GCed).", + Setting envKeepDerivations{ + this, false, "keep-env-derivations", + R"( + If `false` (default), derivations are not stored in Nix user + environments. That is, the derivations of any build-time-only + dependencies may be garbage-collected. + + If `true`, when you add a Nix derivation to a user environment, the + path of the derivation is stored in the user environment. Thus, the + derivation will not be garbage-collected until the user environment + generation is deleted (`nix-env --delete-generations`). To prevent + build-time-only dependencies from being collected, you should also + turn on `keep-outputs`. + + The difference between this option and `keep-derivations` is that + this one is “sticky”: it applies to any user environment created + while this option was enabled, while `keep-derivations` only applies + at the moment the garbage collector is run. + )", {"env-keep-derivations"}}; /* Whether to lock the Nix client and worker to the same CPU. */ bool lockCPU; - Setting sandboxMode{this, + Setting sandboxMode{ + this, #if __linux__ smEnabled #else smDisabled #endif , "sandbox", - "Whether to enable sandboxed builds. Can be \"true\", \"false\" or \"relaxed\".", + R"( + If set to `true`, builds will be performed in a *sandboxed + environment*, i.e., they’re isolated from the normal file system + hierarchy and will only see their dependencies in the Nix store, + the temporary build directory, private versions of `/proc`, + `/dev`, `/dev/shm` and `/dev/pts` (on Linux), and the paths + configured with the `sandbox-paths` option. This is useful to + prevent undeclared dependencies on files in directories such as + `/usr/bin`. In addition, on Linux, builds run in private PID, + mount, network, IPC and UTS namespaces to isolate them from other + processes in the system (except that fixed-output derivations do + not run in private network namespace to ensure they can access the + network). + + Currently, sandboxing only work on Linux and macOS. The use of a + sandbox requires that Nix is run as root (so you should use the + “build users” feature to perform the actual builds under different + users than root). + + If this option is set to `relaxed`, then fixed-output derivations + and derivations that have the `__noChroot` attribute set to `true` + do not run in sandboxes. + + The default is `true` on Linux and `false` on all other platforms. + )", {"build-use-chroot", "build-use-sandbox"}}; - Setting sandboxPaths{this, {}, "sandbox-paths", - "The paths to make available inside the build sandbox.", + Setting sandboxPaths{ + this, {}, "sandbox-paths", + R"( + A list of paths bind-mounted into Nix sandbox environments. You can + use the syntax `target=source` to mount a path in a different + location in the sandbox; for instance, `/bin=/nix-bin` will mount + the path `/nix-bin` as `/bin` inside the sandbox. If *source* is + followed by `?`, then it is not an error if *source* does not exist; + for example, `/dev/nvidiactl?` specifies that `/dev/nvidiactl` will + only be mounted in the sandbox if it exists in the host filesystem. + + Depending on how Nix was built, the default value for this option + may be empty or provide `/bin/sh` as a bind-mount of `bash`. + )", {"build-chroot-dirs", "build-sandbox-paths"}}; Setting sandboxFallback{this, true, "sandbox-fallback", "Whether to disable sandboxing when the kernel doesn't allow it."}; - Setting extraSandboxPaths{this, {}, "extra-sandbox-paths", - "Additional paths to make available inside the build sandbox.", + Setting extraSandboxPaths{ + this, {}, "extra-sandbox-paths", + R"( + A list of additional paths appended to `sandbox-paths`. Useful if + you want to extend its default value. + )", {"build-extra-chroot-dirs", "build-extra-sandbox-paths"}}; - Setting buildRepeat{this, 0, "repeat", - "The number of times to repeat a build in order to verify determinism.", + Setting buildRepeat{ + this, 0, "repeat", + R"( + How many times to repeat builds to check whether they are + deterministic. The default value is 0. If the value is non-zero, + every build is repeated the specified number of times. If the + contents of any of the runs differs from the previous ones and + `enforce-determinism` is true, the build is rejected and the + resulting store paths are not registered as “valid” in Nix’s + database. + )", {"build-repeat"}}; #if __linux__ - Setting sandboxShmSize{this, "50%", "sandbox-dev-shm-size", - "The size of /dev/shm in the build sandbox."}; + Setting sandboxShmSize{ + this, "50%", "sandbox-dev-shm-size", + R"( + This option determines the maximum size of the `tmpfs` filesystem + mounted on `/dev/shm` in Linux sandboxes. For the format, see the + description of the `size` option of `tmpfs` in mount8. The default + is `50%`. + )"}; Setting sandboxBuildDir{this, "/build", "sandbox-build-dir", "The build directory inside the sandbox."}; @@ -250,121 +469,457 @@ public: "Whether to log Darwin sandbox access violations to the system log."}; #endif - Setting runDiffHook{this, false, "run-diff-hook", - "Whether to run the program specified by the diff-hook setting " - "repeated builds produce a different result. Typically used to " - "plug in diffoscope."}; + Setting runDiffHook{ + this, false, "run-diff-hook", + R"( + If true, enable the execution of the `diff-hook` program. - PathSetting diffHook{this, true, "", "diff-hook", - "A program that prints out the differences between the two paths " - "specified on its command line."}; + When using the Nix daemon, `run-diff-hook` must be set in the + `nix.conf` configuration file, and cannot be passed at the command + line. + )"}; - Setting enforceDeterminism{this, true, "enforce-determinism", - "Whether to fail if repeated builds produce different output."}; + PathSetting diffHook{ + this, true, "", "diff-hook", + R"( + Absolute path to an executable capable of diffing build + results. The hook is executed if `run-diff-hook` is true, and the + output of a build is known to not be the same. This program is not + executed to determine if two results are the same. - Setting trustedPublicKeys{this, + 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 built. + + The diff hook program receives three parameters: + + 1. A path to the previous build's results + + 2. A path to the current build's results + + 3. The path to the build's derivation + + 4. The path to the build's scratch directory. This directory will + exist only if the build was run with `--keep-failed`. + + The stderr and stdout output from the diff hook will not be + displayed to the user. Instead, it will print to the nix-daemon's + log. + + When using the Nix daemon, `diff-hook` must be set in the `nix.conf` + configuration file, and cannot be passed at the command line. + )"}; + + Setting enforceDeterminism{ + this, true, "enforce-determinism", + "Whether to fail if repeated builds produce different output. See `repeat`."}; + + Setting trustedPublicKeys{ + this, {"cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="}, "trusted-public-keys", - "Trusted public keys for secure substitution.", + R"( + 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: + `cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= + hydra.nixos.org-1:CNHJZBh9K4tP3EKF6FkkgeVYsS3ohTl+oS0Qa8bezVs=`. + )", {"binary-cache-public-keys"}}; - Setting secretKeyFiles{this, {}, "secret-key-files", - "Secret keys with which to sign local builds."}; + Setting secretKeyFiles{ + this, {}, "secret-key-files", + R"( + 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`. + )"}; - Setting tarballTtl{this, 60 * 60, "tarball-ttl", - "How long downloaded files are considered up-to-date."}; + Setting tarballTtl{ + this, 60 * 60, "tarball-ttl", + R"( + The number of seconds a downloaded tarball is considered fresh. If + the cached tarball is stale, Nix will check whether it is still up + to date using the ETag header. Nix will download a new version if + the ETag header is unsupported, or the cached ETag doesn't match. - Setting requireSigs{this, true, "require-sigs", - "Whether to check that any non-content-addressed path added to the " - "Nix store has a valid signature (that is, one signed using a key " - "listed in 'trusted-public-keys'."}; + Setting the TTL to `0` forces Nix to always check if the tarball is + up to date. - Setting extraPlatforms{this, + Nix caches tarballs in `$XDG_CACHE_HOME/nix/tarballs`. + + Files fetched via `NIX_PATH`, `fetchGit`, `fetchMercurial`, + `fetchTarball`, and `fetchurl` respect this TTL. + )"}; + + Setting requireSigs{ + this, true, "require-sigs", + R"( + If set to `true` (the default), any non-content-addressed path added + or copied to the Nix store (e.g. when substituting from a binary + cache) must have a valid signature, that is, be signed using one of + the keys listed in `trusted-public-keys` or `secret-key-files`. Set + to `false` to disable signature checking. + )"}; + + Setting extraPlatforms{ + this, std::string{SYSTEM} == "x86_64-linux" && !isWSL1() ? StringSet{"i686-linux"} : StringSet{}, "extra-platforms", - "Additional platforms that can be built on the local system. " - "These may be supported natively (e.g. armv7 on some aarch64 CPUs " - "or using hacks like qemu-user."}; + R"( + Platforms other than the native one which this machine is capable of + building for. This can be useful for supporting additional + architectures on compatible machines: i686-linux can be built on + x86\_64-linux machines (and the default for this setting reflects + this); armv7 is backwards-compatible with armv6 and armv5tel; some + aarch64 machines can also natively run 32-bit ARM code; and + qemu-user may be used to support non-native platforms (though this + may be slow and buggy). Most values for this are not enabled by + default because build systems will often misdetect the target + platform and generate incompatible code, so you may wish to + cross-check the results of using this option against proper + natively-built versions of your derivations. + )"}; - Setting systemFeatures{this, getDefaultSystemFeatures(), + Setting systemFeatures{ + this, getDefaultSystemFeatures(), "system-features", - "Optional features that this system implements (like \"kvm\")."}; + R"( + A set of system “features” supported by this machine, e.g. `kvm`. + Derivations can express a dependency on such features through the + derivation attribute `requiredSystemFeatures`. For example, the + attribute - Setting substituters{this, + requiredSystemFeatures = [ "kvm" ]; + + ensures that the derivation can only be built on a machine with the + `kvm` feature. + + This setting by default includes `kvm` if `/dev/kvm` is accessible, + and the pseudo-features `nixos-test`, `benchmark` and `big-parallel` + that are used in Nixpkgs to route builds to specific machines. + )"}; + + Setting substituters{ + this, nixStore == "/nix/store" ? Strings{"https://cache.nixos.org/"} : Strings(), "substituters", - "The URIs of substituters (such as https://cache.nixos.org/).", + R"( + A list of URLs of substituters, separated by whitespace. The default + is `https://cache.nixos.org`. + )", {"binary-caches"}}; // FIXME: provide a way to add to option values. - Setting extraSubstituters{this, {}, "extra-substituters", - "Additional URIs of substituters.", + Setting extraSubstituters{ + this, {}, "extra-substituters", + R"( + Additional binary caches appended to those specified in + `substituters`. When used by unprivileged users, untrusted + substituters (i.e. those not listed in `trusted-substituters`) are + silently ignored. + )", {"extra-binary-caches"}}; - Setting trustedSubstituters{this, {}, "trusted-substituters", - "Disabled substituters that may be enabled via the substituters option by untrusted users.", + Setting trustedSubstituters{ + this, {}, "trusted-substituters", + R"( + 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`. + )", {"trusted-binary-caches"}}; - Setting trustedUsers{this, {"root"}, "trusted-users", - "Which users or groups are trusted to ask the daemon to do unsafe things."}; + Setting trustedUsers{ + this, {"root"}, "trusted-users", + R"( + A list of names of users (separated by whitespace) that have + additional rights when connecting to the Nix daemon, such as the + ability to specify additional binary caches, or to import unsigned + NARs. You can also specify groups by prefixing them with `@`; for + instance, `@wheel` means all users in the `wheel` group. The default + is `root`. - Setting ttlNegativeNarInfoCache{this, 3600, "narinfo-cache-negative-ttl", - "The TTL in seconds for negative lookups in the disk cache i.e binary cache lookups that " - "return an invalid path result"}; + > **Warning** + > + > Adding a user to `trusted-users` is essentially equivalent to + > giving that user root access to the system. For example, the user + > can set `sandbox-paths` and thereby obtain read access to + > directories that are otherwise inacessible to them. + )"}; - Setting ttlPositiveNarInfoCache{this, 30 * 24 * 3600, "narinfo-cache-positive-ttl", - "The TTL in seconds for positive lookups in the disk cache i.e binary cache lookups that " - "return a valid path result."}; + Setting ttlNegativeNarInfoCache{ + this, 3600, "narinfo-cache-negative-ttl", + R"( + The TTL in seconds for negative lookups. If a store path is queried + from a substituter but was not found, there will be a negative + lookup cached in the local disk cache database for the specified + duration. + )"}; + + Setting ttlPositiveNarInfoCache{ + this, 30 * 24 * 3600, "narinfo-cache-positive-ttl", + R"( + The TTL in seconds for positive lookups. If a store path is queried + from a substituter, the result of the query will be cached in the + local disk cache database including some of the NAR metadata. The + default TTL is a month, setting a shorter TTL for positive lookups + can be useful for binary caches that have frequent garbage + collection, in which case having a more frequent cache invalidation + would prevent trying to pull the path again and failing with a hash + mismatch if the build isn't reproducible. + )"}; /* ?Who we trust to use the daemon in safe ways */ - Setting allowedUsers{this, {"*"}, "allowed-users", - "Which users or groups are allowed to connect to the daemon."}; + Setting allowedUsers{ + this, {"*"}, "allowed-users", + R"( + A list of names of users (separated by whitespace) that are allowed + to connect to the Nix daemon. As with the `trusted-users` option, + you can specify groups by prefixing them with `@`. Also, you can + allow all users by specifying `*`. The default is `*`. + + Note that trusted users are always allowed to connect. + )"}; Setting printMissing{this, true, "print-missing", "Whether to print what paths need to be built or downloaded."}; - Setting preBuildHook{this, "", - "pre-build-hook", - "A program to run just before a build to set derivation-specific build settings."}; + Setting preBuildHook{ + this, "", "pre-build-hook", + R"( + If set, the path to a program that can set extra derivation-specific + settings for this system. This is used for settings that can't be + captured by the derivation model itself and are too variable between + different versions of the same system to be hard-coded into nix. - Setting postBuildHook{this, "", "post-build-hook", - "A program to run just after each successful build."}; + The hook is passed the derivation path and, if sandboxes are + enabled, the sandbox directory. It can then modify the sandbox and + send a series of commands to modify various settings to stdout. The + currently recognized commands are: - Setting netrcFile{this, fmt("%s/%s", nixConfDir, "netrc"), "netrc-file", - "Path to the netrc file used to obtain usernames/passwords for downloads."}; + - `extra-sandbox-paths` + Pass a list of files and directories to be included in the + sandbox for this build. One entry per line, terminated by an + empty line. Entries have the same format as `sandbox-paths`. + )"}; + + Setting postBuildHook{ + this, "", "post-build-hook", + R"( + Optional. The path to a program to execute after each build. + + This option is only settable in the global `nix.conf`, or on the + command line by trusted users. + + When using the nix-daemon, the daemon executes the hook as `root`. + If the nix-daemon is not involved, the hook runs as the user + executing the nix-build. + + - The hook executes after an evaluation-time build. + + - The hook does not execute on substituted paths. + + - The hook's output always goes to the user's terminal. + + - If the hook fails, the build succeeds but no further builds + execute. + + - The hook executes synchronously, and blocks other builds from + progressing while it runs. + + The program executes with no arguments. The program's environment + contains the following environment variables: + + - `DRV_PATH` + The derivation for the built paths. + + Example: + `/nix/store/5nihn1a7pa8b25l9zafqaqibznlvvp3f-bash-4.4-p23.drv` + + - `OUT_PATHS` + Output paths of the built derivation, separated by a space + character. + + Example: + `/nix/store/zf5lbh336mnzf1nlswdn11g4n2m8zh3g-bash-4.4-p23-dev + /nix/store/rjxwxwv1fpn9wa2x5ssk5phzwlcv4mna-bash-4.4-p23-doc + /nix/store/6bqvbzjkcp9695dq0dpl5y43nvy37pq1-bash-4.4-p23-info + /nix/store/r7fng3kk3vlpdlh2idnrbn37vh4imlj2-bash-4.4-p23-man + /nix/store/xfghy8ixrhz3kyy6p724iv3cxji088dx-bash-4.4-p23`. + )"}; + + Setting netrcFile{ + this, fmt("%s/%s", nixConfDir, "netrc"), "netrc-file", + R"( + If set to an absolute path to a `netrc` file, Nix will use the HTTP + authentication credentials in this file when trying to download from + a remote host through HTTP or HTTPS. Defaults to + `$NIX_CONF_DIR/netrc`. + + The `netrc` file consists of a list of accounts in the following + format: + + machine my-machine + login my-username + password my-password + + For the exact syntax, see [the `curl` + documentation](https://ec.haxx.se/usingcurl-netrc.html). + + > **Note** + > + > This must be an absolute path, and `~` is not resolved. For + > example, `~/.netrc` won't resolve to your home directory's + > `.netrc`. + )"}; /* Path to the SSL CA file used */ Path caFile; #if __linux__ - Setting filterSyscalls{this, true, "filter-syscalls", - "Whether to prevent certain dangerous system calls, such as " - "creation of setuid/setgid files or adding ACLs or extended " - "attributes. Only disable this if you're aware of the " - "security implications."}; + Setting filterSyscalls{ + this, true, "filter-syscalls", + R"( + Whether to prevent certain dangerous system calls, such as + creation of setuid/setgid files or adding ACLs or extended + attributes. Only disable this if you're aware of the + security implications. + )"}; - Setting allowNewPrivileges{this, false, "allow-new-privileges", - "Whether builders can acquire new privileges by calling programs with " - "setuid/setgid bits or with file capabilities."}; + Setting allowNewPrivileges{ + this, false, "allow-new-privileges", + R"( + (Linux-specific.) By default, builders on Linux cannot acquire new + privileges by calling setuid/setgid programs or programs that have + file capabilities. For example, programs such as `sudo` or `ping` + will fail. (Note that in sandbox builds, no such programs are + available unless you bind-mount them into the sandbox via the + `sandbox-paths` option.) You can allow the use of such programs by + enabling this option. This is impure and usually undesirable, but + may be useful in certain scenarios (e.g. to spin up containers or + set up userspace network interfaces in tests). + )"}; #endif - Setting hashedMirrors{this, {"http://tarballs.nixos.org/"}, "hashed-mirrors", - "A list of servers used by builtins.fetchurl to fetch files by hash."}; + Setting hashedMirrors{ + this, {}, "hashed-mirrors", + R"( + A list of web servers used by `builtins.fetchurl` to obtain files by + hash. The default is `http://tarballs.nixos.org/`. Given a hash type + *ht* and a base-16 hash *h*, Nix will try to download the file from + *hashed-mirror*/*ht*/*h*. This allows files to be downloaded even if + they have disappeared from their original URI. For example, given + the default mirror `http://tarballs.nixos.org/`, when building the + derivation - Setting minFree{this, 0, "min-free", - "Automatically run the garbage collector when free disk space drops below the specified amount."}; + ```nix + builtins.fetchurl { + url = "https://example.org/foo-1.2.3.tar.xz"; + sha256 = "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"; + } + ``` - Setting maxFree{this, std::numeric_limits::max(), "max-free", - "Stop deleting garbage when free disk space is above the specified amount."}; + Nix will attempt to download this file from + `http://tarballs.nixos.org/sha256/2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae` + first. If it is not available there, if will try the original URI. + )"}; + + Setting minFree{ + this, 0, "min-free", + R"( + When free disk space in `/nix/store` drops below `min-free` during a + build, Nix performs a garbage-collection until `max-free` bytes are + available or there is no more garbage. A value of `0` (the default) + disables this feature. + )"}; + + Setting maxFree{ + this, std::numeric_limits::max(), "max-free", + R"( + When a garbage collection is triggered by the `min-free` option, it + stops as soon as `max-free` bytes are available. The default is + infinity (i.e. delete all garbage). + )"}; Setting minFreeCheckInterval{this, 5, "min-free-check-interval", "Number of seconds between checking free disk space."}; - Setting pluginFiles{this, {}, "plugin-files", - "Plugins to dynamically load at nix initialization time."}; + Setting pluginFiles{ + this, {}, "plugin-files", + R"( + A list of plugin files to be loaded by Nix. Each of these files will + be dlopened by Nix, allowing them to affect execution through static + initialization. In particular, these plugins may construct static + instances of RegisterPrimOp to add new primops or constants to the + expression language, RegisterStoreImplementation to add new store + implementations, RegisterCommand to add new subcommands to the `nix` + command, and RegisterSetting to add new nix config settings. See the + constructors for those types for more details. - Setting githubAccessToken{this, "", "github-access-token", - "GitHub access token to get access to GitHub data through the GitHub API for github:<..> flakes."}; + Since these files are loaded into the same address space as Nix + itself, they must be DSOs compatible with the instance of Nix + running at the time (i.e. compiled against the same headers, not + linked to any incompatible libraries). They should not be linked to + any Nix libs directly, as those will be available already at load + time. + + If an entry in the list is a directory, all files in the directory + are loaded as plugins (non-recursively). + )"}; + + Setting accessTokens{this, {}, "access-tokens", + R"( + Access tokens used to access protected GitHub, GitLab, or + other locations requiring token-based authentication. + + Access tokens are specified as a string made up of + space-separated `host=token` values. The specific token + used is selected by matching the `host` portion against the + "host" specification of the input. The actual use of the + `token` value is determined by the type of resource being + accessed: + + * Github: the token value is the OAUTH-TOKEN string obtained + as the Personal Access Token from the Github server (see + https://docs.github.com/en/developers/apps/authorizing-oath-apps). + + * Gitlab: the token value is either the OAuth2 token or the + Personal Access Token (these are different types tokens + for gitlab, see + https://docs.gitlab.com/12.10/ee/api/README.html#authentication). + The `token` value should be `type:tokenstring` where + `type` is either `OAuth2` or `PAT` to indicate which type + of token is being specified. + + Example `~/.config/nix/nix.conf`: + + ``` + access-tokens = "github.com=23ac...b289 gitlab.mycompany.com=PAT:A123Bp_Cd..EfG gitlab.com=OAuth2:1jklw3jk" + ``` + + Example `~/code/flake.nix`: + + ```nix + input.foo = { + type = "gitlab"; + host = "gitlab.mycompany.com"; + owner = "mycompany"; + repo = "pro"; + }; + ``` + + This example specifies three tokens, one each for accessing + github.com, gitlab.mycompany.com, and sourceforge.net. + + The `input.foo` uses the "gitlab" fetcher, which might + requires specifying the token type along with the token + value. + )"}; Setting experimentalFeatures{this, {}, "experimental-features", "Experimental Nix features to enable."}; @@ -378,6 +933,25 @@ public: Setting warnDirty{this, true, "warn-dirty", "Whether to warn about dirty Git/Mercurial trees."}; + + Setting narBufferSize{this, 32 * 1024 * 1024, "nar-buffer-size", + "Maximum size of NARs before spilling them to disk."}; + + Setting flakeRegistry{this, "https://github.com/NixOS/flake-registry/raw/master/flake-registry.json", "flake-registry", + "Path or URI of the global flake registry."}; + + Setting allowSymlinkedStore{ + this, false, "allow-symlinked-store", + R"( + If set to `true`, Nix will stop complaining if the store directory + (typically /nix/store) contains symlink components. + + This risks making some builds "impure" because builders sometimes + "canonicalise" paths by resolving all symlink components. Problems + occur if those builds are then deployed to machines where /nix/store + resolves to a different location from that of the build machine. You + can enable this setting if you are sure you're not going to do that. + )"}; }; diff --git a/src/libstore/http-binary-cache-store.cc b/src/libstore/http-binary-cache-store.cc index 451a64785..9d2a89f96 100644 --- a/src/libstore/http-binary-cache-store.cc +++ b/src/libstore/http-binary-cache-store.cc @@ -2,12 +2,20 @@ #include "filetransfer.hh" #include "globals.hh" #include "nar-info-disk-cache.hh" +#include "callback.hh" namespace nix { MakeError(UploadToHTTP, Error); -class HttpBinaryCacheStore : public BinaryCacheStore +struct HttpBinaryCacheStoreConfig : virtual BinaryCacheStoreConfig +{ + using BinaryCacheStoreConfig::BinaryCacheStoreConfig; + + const std::string name() override { return "Http Binary Cache Store"; } +}; + +class HttpBinaryCacheStore : public BinaryCacheStore, public HttpBinaryCacheStoreConfig { private: @@ -24,9 +32,12 @@ private: public: HttpBinaryCacheStore( - const Params & params, const Path & _cacheUri) - : BinaryCacheStore(params) - , cacheUri(_cacheUri) + const std::string & scheme, + const Path & _cacheUri, + const Params & params) + : StoreConfig(params) + , BinaryCacheStore(params) + , cacheUri(scheme + "://" + _cacheUri) { if (cacheUri.back() == '/') cacheUri.pop_back(); @@ -55,6 +66,14 @@ public: } } + static std::set uriSchemes() + { + static bool forceHttp = getEnv("_NIX_FORCE_HTTP") == "1"; + auto ret = std::set({"http", "https"}); + if (forceHttp) ret.insert("file"); + return ret; + } + protected: void maybeDisable() @@ -85,7 +104,7 @@ protected: checkEnabled(); try { - FileTransferRequest request(cacheUri + "/" + path); + FileTransferRequest request(makeRequest(path)); request.head = true; getFileTransfer()->download(request); return true; @@ -100,11 +119,11 @@ protected: } void upsertFile(const std::string & path, - const std::string & data, + std::shared_ptr> istream, const std::string & mimeType) override { - auto req = FileTransferRequest(cacheUri + "/" + path); - req.data = std::make_shared(data); // FIXME: inefficient + auto req = makeRequest(path); + req.data = std::make_shared(StreamToSourceAdapter(istream).drain()); req.mimeType = mimeType; try { getFileTransfer()->upload(req); @@ -115,8 +134,11 @@ protected: FileTransferRequest makeRequest(const std::string & path) { - FileTransferRequest request(cacheUri + "/" + path); - return request; + return FileTransferRequest( + hasPrefix(path, "https://") || hasPrefix(path, "http://") || hasPrefix(path, "file://") + ? path + : cacheUri + "/" + path); + } void getFile(const std::string & path, Sink & sink) override @@ -159,18 +181,6 @@ protected: }; -static RegisterStoreImplementation regStore([]( - const std::string & uri, const Store::Params & params) - -> std::shared_ptr -{ - static bool forceHttp = getEnv("_NIX_FORCE_HTTP") == "1"; - if (std::string(uri, 0, 7) != "http://" && - std::string(uri, 0, 8) != "https://" && - (!forceHttp || std::string(uri, 0, 7) != "file://")) - return 0; - auto store = std::make_shared(params, uri); - store->init(); - return store; -}); +static RegisterStoreImplementation regHttpBinaryCacheStore; } diff --git a/src/libstore/legacy-ssh-store.cc b/src/libstore/legacy-ssh-store.cc index 5657aa593..467169ce8 100644 --- a/src/libstore/legacy-ssh-store.cc +++ b/src/libstore/legacy-ssh-store.cc @@ -6,21 +6,28 @@ #include "worker-protocol.hh" #include "ssh.hh" #include "derivations.hh" +#include "callback.hh" namespace nix { -static std::string uriScheme = "ssh://"; - -struct LegacySSHStore : public Store +struct LegacySSHStoreConfig : virtual StoreConfig { - const Setting maxConnections{this, 1, "max-connections", "maximum number of concurrent SSH connections"}; - const Setting sshKey{this, "", "ssh-key", "path to an SSH private key"}; - const Setting compress{this, false, "compress", "whether to compress the connection"}; - const Setting remoteProgram{this, "nix-store", "remote-program", "path to the nix-store executable on the remote system"}; - const Setting remoteStore{this, "", "remote-store", "URI of the store on the remote system"}; + using StoreConfig::StoreConfig; + const Setting maxConnections{(StoreConfig*) this, 1, "max-connections", "maximum number of concurrent SSH connections"}; + const Setting sshKey{(StoreConfig*) this, "", "ssh-key", "path to an SSH private key"}; + const Setting compress{(StoreConfig*) this, false, "compress", "whether to compress the connection"}; + const Setting remoteProgram{(StoreConfig*) this, "nix-store", "remote-program", "path to the nix-store executable on the remote system"}; + const Setting remoteStore{(StoreConfig*) this, "", "remote-store", "URI of the store on the remote system"}; + const std::string name() override { return "Legacy SSH Store"; } +}; + +struct LegacySSHStore : public Store, public virtual LegacySSHStoreConfig +{ // Hack for getting remote build log output. - const Setting logFD{this, -1, "log-fd", "file descriptor to which SSH's stderr is connected"}; + // Intentionally not in `LegacySSHStoreConfig` so that it doesn't appear in + // the documentation + const Setting logFD{(StoreConfig*) this, -1, "log-fd", "file descriptor to which SSH's stderr is connected"}; struct Connection { @@ -37,8 +44,11 @@ struct LegacySSHStore : public Store SSHMaster master; - LegacySSHStore(const string & host, const Params & params) - : Store(params) + static std::set uriSchemes() { return {"ssh"}; } + + LegacySSHStore(const string & scheme, const string & host, const Params & params) + : StoreConfig(params) + , Store(params) , host(host) , connections(make_ref>( std::max(1, (int) maxConnections), @@ -84,7 +94,7 @@ struct LegacySSHStore : public Store string getUri() override { - return uriScheme + host; + return *uriSchemes().begin() + "://" + host; } void queryPathInfoUncached(const StorePath & path, @@ -93,6 +103,9 @@ struct LegacySSHStore : public Store try { auto conn(connections->get()); + /* No longer support missing NAR hash */ + assert(GET_PROTOCOL_MINOR(conn->remoteVersion) >= 4); + debug("querying remote host '%s' for info on '%s'", host, printStorePath(path)); conn->to << cmdQueryPathInfos << PathSet{printStorePath(path)}; @@ -100,23 +113,27 @@ struct LegacySSHStore : public Store auto p = readString(conn->from); if (p.empty()) return callback(nullptr); - auto info = std::make_shared(parseStorePath(p)); - assert(path == info->path); + auto path2 = parseStorePath(p); + assert(path == path2); + /* Hash will be set below. FIXME construct ValidPathInfo at end. */ + auto info = std::make_shared(path, Hash::dummy); PathSet references; auto deriver = readString(conn->from); if (deriver != "") info->deriver = parseStorePath(deriver); - info->references = readStorePaths(*this, conn->from); + info->references = worker_proto::read(*this, conn->from, Phantom {}); readLongLong(conn->from); // download size info->narSize = readLongLong(conn->from); - if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 4) { + { auto s = readString(conn->from); - info->narHash = s.empty() ? Hash() : Hash(s); - info->ca = parseContentAddressOpt(readString(conn->from)); - info->sigs = readStrings(conn->from); + if (s == "") + throw Error("NAR hash is now mandatory"); + info->narHash = Hash::parseAnyPrefixed(s); } + info->ca = parseContentAddressOpt(readString(conn->from)); + info->sigs = readStrings(conn->from); auto s = readString(conn->from); assert(s == ""); @@ -126,8 +143,7 @@ struct LegacySSHStore : public Store } void addToStore(const ValidPathInfo & info, Source & source, - RepairFlag repair, CheckSigsFlag checkSigs, - std::shared_ptr accessor) override + RepairFlag repair, CheckSigsFlag checkSigs) override { debug("adding path '%s' to remote host '%s'", printStorePath(info.path), host); @@ -140,7 +156,7 @@ struct LegacySSHStore : public Store << printStorePath(info.path) << (info.deriver ? printStorePath(*info.deriver) : "") << info.narHash.to_string(Base16, false); - writeStorePaths(*this, conn->to, info.references); + worker_proto::write(*this, conn->to, info.references); conn->to << info.registrationTime << info.narSize @@ -169,7 +185,7 @@ struct LegacySSHStore : public Store conn->to << exportMagic << printStorePath(info.path); - writeStorePaths(*this, conn->to, info.references); + worker_proto::write(*this, conn->to, info.references); conn->to << (info.deriver ? printStorePath(*info.deriver) : "") << 0 @@ -203,6 +219,24 @@ struct LegacySSHStore : public Store const StorePathSet & references, RepairFlag repair) override { unsupported("addTextToStore"); } +private: + + void putBuildSettings(Connection & conn) + { + conn.to + << settings.maxSilentTime + << settings.buildTimeout; + if (GET_PROTOCOL_MINOR(conn.remoteVersion) >= 2) + conn.to + << settings.maxLogSize; + if (GET_PROTOCOL_MINOR(conn.remoteVersion) >= 3) + conn.to + << settings.buildRepeat + << settings.enforceDeterminism; + } + +public: + BuildResult buildDerivation(const StorePath & drvPath, const BasicDerivation & drv, BuildMode buildMode) override { @@ -212,16 +246,8 @@ struct LegacySSHStore : public Store << cmdBuildDerivation << printStorePath(drvPath); writeDerivation(conn->to, *this, drv); - conn->to - << settings.maxSilentTime - << settings.buildTimeout; - if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 2) - conn->to - << settings.maxLogSize; - if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 3) - conn->to - << settings.buildRepeat - << settings.enforceDeterminism; + + putBuildSettings(*conn); conn->to.flush(); @@ -235,6 +261,29 @@ struct LegacySSHStore : public Store return status; } + void buildPaths(const std::vector & drvPaths, BuildMode buildMode) override + { + auto conn(connections->get()); + + conn->to << cmdBuildPaths; + Strings ss; + for (auto & p : drvPaths) + ss.push_back(p.to_string(*this)); + conn->to << ss; + + putBuildSettings(*conn); + + conn->to.flush(); + + BuildResult result; + result.status = (BuildResult::Status) readInt(conn->from); + + if (!result.success()) { + conn->from >> result.errorMsg; + throw Error(result.status, result.errorMsg); + } + } + void ensurePath(const StorePath & path) override { unsupported("ensurePath"); } @@ -252,10 +301,10 @@ struct LegacySSHStore : public Store conn->to << cmdQueryClosure << includeOutputs; - writeStorePaths(*this, conn->to, paths); + worker_proto::write(*this, conn->to, paths); conn->to.flush(); - for (auto & i : readStorePaths(*this, conn->from)) + for (auto & i : worker_proto::read(*this, conn->from, Phantom {})) out.insert(i); } @@ -268,10 +317,10 @@ struct LegacySSHStore : public Store << cmdQueryValidPaths << false // lock << maybeSubstitute; - writeStorePaths(*this, conn->to, paths); + worker_proto::write(*this, conn->to, paths); conn->to.flush(); - return readStorePaths(*this, conn->from); + return worker_proto::read(*this, conn->from, Phantom {}); } void connect() override @@ -286,12 +335,6 @@ struct LegacySSHStore : public Store } }; -static RegisterStoreImplementation regStore([]( - const std::string & uri, const Store::Params & params) - -> std::shared_ptr -{ - if (std::string(uri, 0, uriScheme.size()) != uriScheme) return 0; - return std::make_shared(std::string(uri, uriScheme.size()), params); -}); +static RegisterStoreImplementation regLegacySSHStore; } diff --git a/src/libstore/local-binary-cache-store.cc b/src/libstore/local-binary-cache-store.cc index 48aca478c..7d979c5c2 100644 --- a/src/libstore/local-binary-cache-store.cc +++ b/src/libstore/local-binary-cache-store.cc @@ -4,7 +4,14 @@ namespace nix { -class LocalBinaryCacheStore : public BinaryCacheStore +struct LocalBinaryCacheStoreConfig : virtual BinaryCacheStoreConfig +{ + using BinaryCacheStoreConfig::BinaryCacheStoreConfig; + + const std::string name() override { return "Local Binary Cache Store"; } +}; + +class LocalBinaryCacheStore : public BinaryCacheStore, public virtual LocalBinaryCacheStoreConfig { private: @@ -13,8 +20,11 @@ private: public: LocalBinaryCacheStore( - const Params & params, const Path & binaryCacheDir) - : BinaryCacheStore(params) + const std::string scheme, + const Path & binaryCacheDir, + const Params & params) + : StoreConfig(params) + , BinaryCacheStore(params) , binaryCacheDir(binaryCacheDir) { } @@ -26,13 +36,25 @@ public: return "file://" + binaryCacheDir; } + static std::set uriSchemes(); + protected: bool fileExists(const std::string & path) override; void upsertFile(const std::string & path, - const std::string & data, - const std::string & mimeType) override; + std::shared_ptr> istream, + const std::string & mimeType) override + { + auto path2 = binaryCacheDir + "/" + path; + Path tmp = path2 + ".tmp." + std::to_string(getpid()); + AutoDelete del(tmp, false); + StreamToSourceAdapter source(istream); + writeFile(tmp, source); + if (rename(tmp.c_str(), path2.c_str())) + throw SysError("renaming '%1%' to '%2%'", tmp, path2); + del.cancel(); + } void getFile(const std::string & path, Sink & sink) override { @@ -52,7 +74,9 @@ protected: if (entry.name.size() != 40 || !hasSuffix(entry.name, ".narinfo")) continue; - paths.insert(parseStorePath(storeDir + "/" + entry.name.substr(0, entry.name.size() - 8))); + paths.insert(parseStorePath( + storeDir + "/" + entry.name.substr(0, entry.name.size() - 8) + + "-" + MissingName)); } return paths; @@ -68,38 +92,19 @@ void LocalBinaryCacheStore::init() BinaryCacheStore::init(); } -static void atomicWrite(const Path & path, const std::string & s) -{ - Path tmp = path + ".tmp." + std::to_string(getpid()); - AutoDelete del(tmp, false); - writeFile(tmp, s); - if (rename(tmp.c_str(), path.c_str())) - throw SysError("renaming '%1%' to '%2%'", tmp, path); - del.cancel(); -} - bool LocalBinaryCacheStore::fileExists(const std::string & path) { return pathExists(binaryCacheDir + "/" + path); } -void LocalBinaryCacheStore::upsertFile(const std::string & path, - const std::string & data, - const std::string & mimeType) +std::set LocalBinaryCacheStore::uriSchemes() { - atomicWrite(binaryCacheDir + "/" + path, data); + if (getEnv("_NIX_FORCE_HTTP_BINARY_CACHE_STORE") == "1") + return {}; + else + return {"file"}; } -static RegisterStoreImplementation regStore([]( - const std::string & uri, const Store::Params & params) - -> std::shared_ptr -{ - if (getEnv("_NIX_FORCE_HTTP_BINARY_CACHE_STORE") == "1" || - std::string(uri, 0, 7) != "file://") - return 0; - auto store = std::make_shared(params, std::string(uri, 7)); - store->init(); - return store; -}); +static RegisterStoreImplementation regLocalBinaryCacheStore; } diff --git a/src/libstore/local-fs-store.cc b/src/libstore/local-fs-store.cc index dd96d2578..2f1d9663a 100644 --- a/src/libstore/local-fs-store.cc +++ b/src/libstore/local-fs-store.cc @@ -20,9 +20,9 @@ struct LocalStoreAccessor : public FSAccessor Path toRealPath(const Path & path) { - Path storePath = store->toStorePath(path); - if (!store->isValidPath(store->parseStorePath(storePath))) - throw InvalidPath("path '%1%' is not a valid store path", storePath); + auto storePath = store->toStorePath(path).first; + if (!store->isValidPath(storePath)) + throw InvalidPath("path '%1%' is not a valid store path", store->printStorePath(storePath)); return store->getRealStoreDir() + std::string(path, store->storeDir.size()); } diff --git a/src/libstore/local-store.cc b/src/libstore/local-store.cc index 80ebe903f..6a5f13996 100644 --- a/src/libstore/local-store.cc +++ b/src/libstore/local-store.cc @@ -6,6 +6,7 @@ #include "derivations.hh" #include "nar-info.hh" #include "references.hh" +#include "callback.hh" #include #include @@ -42,7 +43,8 @@ namespace nix { LocalStore::LocalStore(const Params & params) - : Store(params) + : StoreConfig(params) + , Store(params) , LocalFSStore(params) , realStoreDir_{this, false, rootDir != "" ? rootDir + "/nix/store" : storeDir, "real", "physical path to the Nix store"} @@ -108,12 +110,11 @@ LocalStore::LocalStore(const Params & params) } /* Ensure that the store and its parents are not symlinks. */ - if (getEnv("NIX_IGNORE_SYMLINK_STORE") != "1") { + if (!settings.allowSymlinkedStore) { Path path = realStoreDir; struct stat st; while (path != "/") { - if (lstat(path.c_str(), &st)) - throw SysError("getting status of '%1%'", path); + st = lstat(path); if (S_ISLNK(st.st_mode)) throw Error( "the path '%1%' is a symlink; " @@ -417,10 +418,7 @@ static void canonicaliseTimestampAndPermissions(const Path & path, const struct void canonicaliseTimestampAndPermissions(const Path & path) { - struct stat st; - if (lstat(path.c_str(), &st)) - throw SysError("getting attributes of path '%1%'", path); - canonicaliseTimestampAndPermissions(path, st); + canonicaliseTimestampAndPermissions(path, lstat(path)); } @@ -441,9 +439,7 @@ static void canonicalisePathMetaData_( } #endif - struct stat st; - if (lstat(path.c_str(), &st)) - throw SysError("getting attributes of path '%1%'", path); + auto st = lstat(path); /* Really make sure that the path is of a supported type. */ if (!(S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode))) @@ -479,8 +475,7 @@ static void canonicalisePathMetaData_( ensure that we don't fail on hard links within the same build (i.e. "touch $out/foo; ln $out/foo $out/bar"). */ if (uidRange && (st.st_uid < uidRange->first || st.st_uid > uidRange->second)) { - assert(!S_ISDIR(st.st_mode)); - if (inodesSeen.find(Inode(st.st_dev, st.st_ino)) == inodesSeen.end()) + if (S_ISDIR(st.st_mode) || !inodesSeen.count(Inode(st.st_dev, st.st_ino))) throw BuildError("invalid ownership on file '%1%'", path); mode_t mode = st.st_mode & ~S_IFMT; assert(S_ISLNK(st.st_mode) || (st.st_uid == geteuid() && (mode == 0444 || mode == 0555) && st.st_mtime == mtimeStore)); @@ -526,9 +521,7 @@ void canonicalisePathMetaData( /* On platforms that don't have lchown(), the top-level path can't be a symlink, since we can't change its ownership. */ - struct stat st; - if (lstat(path.c_str(), &st)) - throw SysError("getting attributes of path '%1%'", path); + auto st = lstat(path); if (st.st_uid != geteuid()) { assert(S_ISLNK(st.st_mode)); @@ -551,11 +544,8 @@ void LocalStore::checkDerivationOutputs(const StorePath & drvPath, const Derivat std::string drvName(drvPath.name()); drvName = string(drvName, 0, drvName.size() - drvExtension.size()); - auto check = [&](const StorePath & expected, const StorePath & actual, const std::string & varName) + auto envHasRightPath = [&](const StorePath & actual, const std::string & varName) { - if (actual != expected) - throw Error("derivation '%s' has incorrect output '%s', should be '%s'", - printStorePath(drvPath), printStorePath(actual), printStorePath(expected)); auto j = drv.env.find(varName); if (j == drv.env.end() || parseStorePath(j->second) != actual) throw Error("derivation '%s' has incorrect environment variable '%s', should be '%s'", @@ -563,24 +553,54 @@ void LocalStore::checkDerivationOutputs(const StorePath & drvPath, const Derivat }; - if (drv.isFixedOutput()) { - DerivationOutputs::const_iterator out = drv.outputs.find("out"); - if (out == drv.outputs.end()) - throw Error("derivation '%s' does not have an output named 'out'", printStorePath(drvPath)); + // Don't need the answer, but do this anyways to assert is proper + // combination. The code below is more general and naturally allows + // combinations that are currently prohibited. + drv.type(); - check( - makeFixedOutputPath( - out->second.hash->method, - out->second.hash->hash, - drvName), - out->second.path, "out"); + std::optional h; + for (auto & i : drv.outputs) { + std::visit(overloaded { + [&](DerivationOutputInputAddressed doia) { + if (!h) { + // somewhat expensive so we do lazily + auto temp = hashDerivationModulo(*this, drv, true); + h = std::get(temp); + } + StorePath recomputed = makeOutputPath(i.first, *h, drvName); + if (doia.path != recomputed) + throw Error("derivation '%s' has incorrect output '%s', should be '%s'", + printStorePath(drvPath), printStorePath(doia.path), printStorePath(recomputed)); + envHasRightPath(doia.path, i.first); + }, + [&](DerivationOutputCAFixed dof) { + StorePath path = makeFixedOutputPath(dof.hash.method, dof.hash.hash, drvName); + envHasRightPath(path, i.first); + }, + [&](DerivationOutputCAFloating _) { + /* Nothing to check */ + }, + }, i.second.output); } +} + + +void LocalStore::linkDeriverToPath(const StorePath & deriver, const string & outputName, const StorePath & output) +{ + auto state(_state.lock()); + return linkDeriverToPath(*state, queryValidPathId(*state, deriver), outputName, output); +} + +void LocalStore::linkDeriverToPath(State & state, uint64_t deriver, const string & outputName, const StorePath & output) +{ + retrySQLite([&]() { + state.stmtAddDerivationOutput.use() + (deriver) + (outputName) + (printStorePath(output)) + .exec(); + }); - else { - Hash h = hashDerivationModulo(*this, drv, true); - for (auto & i : drv.outputs) - check(makeOutputPath(i.first, h, drvName), i.second.path, i.first); - } } @@ -601,7 +621,7 @@ uint64_t LocalStore::addValidPath(State & state, (concatStringsSep(" ", info.sigs), !info.sigs.empty()) (renderContentAddress(info.ca), (bool) info.ca) .exec(); - uint64_t id = sqlite3_last_insert_rowid(state.db); + uint64_t id = state.db.getLastInsertedRowId(); /* If this is a derivation, then store the derivation outputs in the database. This is useful for the garbage collector: it can @@ -617,12 +637,11 @@ uint64_t LocalStore::addValidPath(State & state, registration above is undone. */ if (checkOutputs) checkDerivationOutputs(info.path, drv); - for (auto & i : drv.outputs) { - state.stmtAddDerivationOutput.use() - (id) - (i.first) - (printStorePath(i.second.path)) - .exec(); + for (auto & i : drv.outputsAndOptPaths(*this)) { + /* Floating CA derivations have indeterminate output paths until + they are built, so don't register anything in that case */ + if (i.second.second) + linkDeriverToPath(state, id, i.first, *i.second.second); } } @@ -640,25 +659,28 @@ void LocalStore::queryPathInfoUncached(const StorePath & path, Callback> callback) noexcept { try { - auto info = std::make_shared(path); - callback(retrySQLite>([&]() { auto state(_state.lock()); /* Get the path info. */ - auto useQueryPathInfo(state->stmtQueryPathInfo.use()(printStorePath(info->path))); + auto useQueryPathInfo(state->stmtQueryPathInfo.use()(printStorePath(path))); if (!useQueryPathInfo.next()) return std::shared_ptr(); - info->id = useQueryPathInfo.getInt(0); + auto id = useQueryPathInfo.getInt(0); + auto narHash = Hash::dummy; try { - info->narHash = Hash(useQueryPathInfo.getStr(1)); + narHash = Hash::parseAnyPrefixed(useQueryPathInfo.getStr(1)); } catch (BadHash & e) { - throw Error("in valid-path entry for '%s': %s", printStorePath(path), e.what()); + throw Error("invalid-path entry for '%s': %s", printStorePath(path), e.what()); } + auto info = std::make_shared(path, narHash); + + info->id = id; + info->registrationTime = useQueryPathInfo.getInt(2); auto s = (const char *) sqlite3_column_text(state->stmtQueryPathInfo, 3); @@ -706,7 +728,7 @@ uint64_t LocalStore::queryValidPathId(State & state, const StorePath & path) { auto use(state.stmtQueryPathInfo.use()(printStorePath(path))); if (!use.next()) - throw Error("path '%s' is not valid", printStorePath(path)); + throw InvalidPath("path '%s' is not valid", printStorePath(path)); return use.getInt(0); } @@ -781,17 +803,61 @@ StorePathSet LocalStore::queryValidDerivers(const StorePath & path) } -OutputPathMap LocalStore::queryDerivationOutputMap(const StorePath & path) +std::map> LocalStore::queryPartialDerivationOutputMap(const StorePath & path_) { - return retrySQLite([&]() { + auto path = path_; + std::map> outputs; + Derivation drv = readDerivation(path); + for (auto & [outName, _] : drv.outputs) { + outputs.insert_or_assign(outName, std::nullopt); + } + bool haveCached = false; + { + auto resolutions = drvPathResolutions.lock(); + auto resolvedPathOptIter = resolutions->find(path); + if (resolvedPathOptIter != resolutions->end()) { + auto & [_, resolvedPathOpt] = *resolvedPathOptIter; + if (resolvedPathOpt) + path = *resolvedPathOpt; + haveCached = true; + } + } + /* can't just use else-if instead of `!haveCached` because we need to unlock + `drvPathResolutions` before it is locked in `Derivation::resolve`. */ + if (!haveCached && drv.type() == DerivationType::CAFloating) { + /* Try resolve drv and use that path instead. */ + auto attempt = drv.tryResolve(*this); + if (!attempt) + /* If we cannot resolve the derivation, we cannot have any path + assigned so we return the map of all std::nullopts. */ + return outputs; + /* Just compute store path */ + auto pathResolved = writeDerivation(*this, *std::move(attempt), NoRepair, true); + /* Store in memo table. */ + /* FIXME: memo logic should not be local-store specific, should have + wrapper-method instead. */ + drvPathResolutions.lock()->insert_or_assign(path, pathResolved); + path = std::move(pathResolved); + } + return retrySQLite>>([&]() { auto state(_state.lock()); - auto useQueryDerivationOutputs(state->stmtQueryDerivationOutputs.use() - (queryValidPathId(*state, path))); + uint64_t drvId; + try { + drvId = queryValidPathId(*state, path); + } catch (InvalidPath &) { + /* FIXME? if the derivation doesn't exist, we cannot have a mapping + for it. */ + return outputs; + } + + auto useQueryDerivationOutputs { + state->stmtQueryDerivationOutputs.use() + (drvId) + }; - OutputPathMap outputs; while (useQueryDerivationOutputs.next()) - outputs.emplace( + outputs.insert_or_assign( useQueryDerivationOutputs.getStr(0), parseStorePath(useQueryDerivationOutputs.getStr(1)) ); @@ -853,20 +919,32 @@ StorePathSet LocalStore::querySubstitutablePaths(const StorePathSet & paths) } -void LocalStore::querySubstitutablePathInfos(const StorePathSet & paths, - SubstitutablePathInfos & infos) +void LocalStore::querySubstitutablePathInfos(const StorePathCAMap & paths, SubstitutablePathInfos & infos) { if (!settings.useSubstitutes) return; for (auto & sub : getDefaultSubstituters()) { - if (sub->storeDir != storeDir) continue; for (auto & path : paths) { - if (infos.count(path)) continue; - debug("checking substituter '%s' for path '%s'", sub->getUri(), printStorePath(path)); + auto subPath(path.first); + + // recompute store path so that we can use a different store root + if (path.second) { + subPath = makeFixedOutputPathFromCA(path.first.name(), *path.second); + if (sub->storeDir == storeDir) + assert(subPath == path.first); + if (subPath != path.first) + debug("replaced path '%s' with '%s' for substituter '%s'", printStorePath(path.first), sub->printStorePath(subPath), sub->getUri()); + } else if (sub->storeDir != storeDir) continue; + + debug("checking substituter '%s' for path '%s'", sub->getUri(), sub->printStorePath(subPath)); try { - auto info = sub->queryPathInfo(path); + auto info = sub->queryPathInfo(subPath); + + if (sub->storeDir != storeDir && !(info->isContentAddressed(*sub) && info->references.empty())) + continue; + auto narInfo = std::dynamic_pointer_cast( std::shared_ptr(info)); - infos.insert_or_assign(path, SubstitutablePathInfo{ + infos.insert_or_assign(path.first, SubstitutablePathInfo{ info->deriver, info->references, narInfo ? narInfo->fileSize : 0, @@ -969,11 +1047,8 @@ const PublicKeys & LocalStore::getPublicKeys() void LocalStore::addToStore(const ValidPathInfo & info, Source & source, - RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr accessor) + RepairFlag repair, CheckSigsFlag checkSigs) { - if (!info.narHash) - throw Error("cannot add path '%s' because it lacks a hash", printStorePath(info.path)); - if (requireSigs && checkSigs && !info.checkSignatures(*this, getPublicKeys())) throw Error("cannot add path '%s' because it lacks a valid signature", printStorePath(info.path)); @@ -983,7 +1058,7 @@ void LocalStore::addToStore(const ValidPathInfo & info, Source & source, PathLocks outputLock; - Path realPath = realStoreDir + "/" + std::string(info.path.to_string()); + auto realPath = Store::toRealPath(info.path); /* Lock the output path. But don't lock if we're being called from a build hook (whose parent process already acquired a @@ -1008,11 +1083,7 @@ void LocalStore::addToStore(const ValidPathInfo & info, Source & source, else hashSink = std::make_unique(htSHA256, std::string(info.path.hashPart())); - LambdaSource wrapperSource([&](unsigned char * data, size_t len) -> size_t { - size_t n = source.read(data, len); - (*hashSink)(data, n); - return n; - }); + TeeSource wrapperSource { source, *hashSink }; restorePath(realPath, wrapperSource); @@ -1040,12 +1111,64 @@ void LocalStore::addToStore(const ValidPathInfo & info, Source & source, } -StorePath LocalStore::addToStoreFromDump(const string & dump, const string & name, +StorePath LocalStore::addToStoreFromDump(Source & source0, const string & name, FileIngestionMethod method, HashType hashAlgo, RepairFlag repair) { - Hash h = hashString(hashAlgo, dump); + /* For computing the store path. */ + auto hashSink = std::make_unique(hashAlgo); + TeeSource source { source0, *hashSink }; - auto dstPath = makeFixedOutputPath(method, h, name); + /* Read the source path into memory, but only if it's up to + narBufferSize bytes. If it's larger, write it to a temporary + location in the Nix store. If the subsequently computed + destination store path is already valid, we just delete the + temporary path. Otherwise, we move it to the destination store + path. */ + bool inMemory = false; + + std::string dump; + + /* Fill out buffer, and decide whether we are working strictly in + memory based on whether we break out because the buffer is full + or the original source is empty */ + while (dump.size() < settings.narBufferSize) { + auto oldSize = dump.size(); + constexpr size_t chunkSize = 65536; + auto want = std::min(chunkSize, settings.narBufferSize - oldSize); + dump.resize(oldSize + want); + auto got = 0; + try { + got = source.read((uint8_t *) dump.data() + oldSize, want); + } catch (EndOfFile &) { + inMemory = true; + break; + } + dump.resize(oldSize + got); + } + + std::unique_ptr delTempDir; + Path tempPath; + + if (!inMemory) { + /* Drain what we pulled so far, and then keep on pulling */ + StringSource dumpSource { dump }; + ChainSource bothSource { dumpSource, source }; + + auto tempDir = createTempDir(realStoreDir, "add"); + delTempDir = std::make_unique(tempDir); + tempPath = tempDir + "/x"; + + if (method == FileIngestionMethod::Recursive) + restorePath(tempPath, bothSource); + else + writeFile(tempPath, bothSource); + + dump.clear(); + } + + auto [hash, size] = hashSink->finish(); + + auto dstPath = makeFixedOutputPath(method, hash, name); addTempRoot(dstPath); @@ -1054,8 +1177,7 @@ StorePath LocalStore::addToStoreFromDump(const string & dump, const string & nam /* The first check above is an optimisation to prevent unnecessary lock acquisition. */ - Path realPath = realStoreDir + "/"; - realPath += dstPath.to_string(); + auto realPath = Store::toRealPath(dstPath); PathLocks outputLock({realPath}); @@ -1065,31 +1187,35 @@ StorePath LocalStore::addToStoreFromDump(const string & dump, const string & nam autoGC(); - if (method == FileIngestionMethod::Recursive) { - StringSource source(dump); - restorePath(realPath, source); - } else - writeFile(realPath, dump); + if (inMemory) { + StringSource dumpSource { dump }; + /* Restore from the NAR in memory. */ + if (method == FileIngestionMethod::Recursive) + restorePath(realPath, dumpSource); + else + writeFile(realPath, dumpSource); + } else { + /* Move the temporary path we restored above. */ + if (rename(tempPath.c_str(), realPath.c_str())) + throw Error("renaming '%s' to '%s'", tempPath, realPath); + } - canonicalisePathMetaData(realPath, {}); + /* For computing the nar hash. In recursive SHA-256 mode, this + is the same as the store hash, so no need to do it again. */ + auto narHash = std::pair { hash, size }; + if (method != FileIngestionMethod::Recursive || hashAlgo != htSHA256) { + HashSink narSink { htSHA256 }; + dumpPath(realPath, narSink); + narHash = narSink.finish(); + } - /* Register the SHA-256 hash of the NAR serialisation of - the path in the database. We may just have computed it - above (if called with recursive == true and hashAlgo == - sha256); otherwise, compute it here. */ - HashResult hash; - if (method == FileIngestionMethod::Recursive) { - hash.first = hashAlgo == htSHA256 ? h : hashString(htSHA256, dump); - hash.second = dump.size(); - } else - hash = hashPath(htSHA256, realPath); + canonicalisePathMetaData(realPath, {}); // FIXME: merge into restorePath - optimisePath(realPath); // FIXME: combine with hashPath() + optimisePath(realPath); - ValidPathInfo info(dstPath); - info.narHash = hash.first; - info.narSize = hash.second; - info.ca = FixedOutputHash { .method = method, .hash = h }; + ValidPathInfo info { dstPath, narHash.first }; + info.narSize = narHash.second; + info.ca = FixedOutputHash { .method = method, .hash = hash }; registerValidPath(info); } @@ -1100,24 +1226,6 @@ StorePath LocalStore::addToStoreFromDump(const string & dump, const string & nam } -StorePath LocalStore::addToStore(const string & name, const Path & _srcPath, - FileIngestionMethod method, HashType hashAlgo, PathFilter & filter, RepairFlag repair) -{ - Path srcPath(absPath(_srcPath)); - - /* Read the whole path into memory. This is not a very scalable - method for very large paths, but `copyPath' is mainly used for - small files. */ - StringSink sink; - if (method == FileIngestionMethod::Recursive) - dumpPath(srcPath, sink, filter); - else - sink.s = make_ref(readFile(srcPath)); - - return addToStoreFromDump(*sink.s, name, method, hashAlgo, repair); -} - - StorePath LocalStore::addTextToStore(const string & name, const string & s, const StorePathSet & references, RepairFlag repair) { @@ -1128,8 +1236,7 @@ StorePath LocalStore::addTextToStore(const string & name, const string & s, if (repair || !isValidPath(dstPath)) { - Path realPath = realStoreDir + "/"; - realPath += dstPath.to_string(); + auto realPath = Store::toRealPath(dstPath); PathLocks outputLock({realPath}); @@ -1149,8 +1256,7 @@ StorePath LocalStore::addTextToStore(const string & name, const string & s, optimisePath(realPath); - ValidPathInfo info(dstPath); - info.narHash = narHash; + ValidPathInfo info { dstPath, narHash }; info.narSize = sink.s->size(); info.references = references; info.ca = TextHash { .hash = hash }; @@ -1265,9 +1371,9 @@ bool LocalStore::verifyStore(bool checkContents, RepairFlag repair) std::unique_ptr hashSink; if (!info->ca || !info->references.count(info->path)) - hashSink = std::make_unique(*info->narHash.type); + hashSink = std::make_unique(info->narHash.type); else - hashSink = std::make_unique(*info->narHash.type, std::string(info->path.hashPart())); + hashSink = std::make_unique(info->narHash.type, std::string(info->path.hashPart())); dumpPath(Store::toRealPath(i), *hashSink); auto current = hashSink->finish(); @@ -1387,7 +1493,7 @@ static void makeMutable(const Path & path) { checkInterrupt(); - struct stat st = lstat(path); + auto st = lstat(path); if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode)) return; diff --git a/src/libstore/local-store.hh b/src/libstore/local-store.hh index 79b415875..118c7149b 100644 --- a/src/libstore/local-store.hh +++ b/src/libstore/local-store.hh @@ -23,18 +23,26 @@ namespace nix { const int nixSchemaVersion = 10; -struct Derivation; - - struct OptimiseStats { unsigned long filesLinked = 0; - unsigned long long bytesFreed = 0; - unsigned long long blocksFreed = 0; + uint64_t bytesFreed = 0; + uint64_t blocksFreed = 0; +}; + +struct LocalStoreConfig : virtual LocalFSStoreConfig +{ + using LocalFSStoreConfig::LocalFSStoreConfig; + + Setting requireSigs{(StoreConfig*) this, + settings.requireSigs, + "require-sigs", "whether store paths should have a trusted signature on import"}; + + const std::string name() override { return "Local Store"; } }; -class LocalStore : public LocalFSStore +class LocalStore : public LocalFSStore, public virtual LocalStoreConfig { private: @@ -98,10 +106,6 @@ public: private: - Setting requireSigs{(Store*) this, - settings.requireSigs, - "require-sigs", "whether store paths should have a trusted signature on import"}; - const PublicKeys & getPublicKeys(); public: @@ -133,29 +137,20 @@ public: StorePathSet queryValidDerivers(const StorePath & path) override; - OutputPathMap queryDerivationOutputMap(const StorePath & path) override; + std::map> queryPartialDerivationOutputMap(const StorePath & path) override; std::optional queryPathFromHashPart(const std::string & hashPart) override; StorePathSet querySubstitutablePaths(const StorePathSet & paths) override; - void querySubstitutablePathInfos(const StorePathSet & paths, + void querySubstitutablePathInfos(const StorePathCAMap & paths, SubstitutablePathInfos & infos) override; void addToStore(const ValidPathInfo & info, Source & source, - RepairFlag repair, CheckSigsFlag checkSigs, - std::shared_ptr accessor) override; + RepairFlag repair, CheckSigsFlag checkSigs) override; - StorePath addToStore(const string & name, const Path & srcPath, - FileIngestionMethod method, HashType hashAlgo, - PathFilter & filter, RepairFlag repair) override; - - /* Like addToStore(), but the contents of the path are contained - in `dump', which is either a NAR serialisation (if recursive == - true) or simply the contents of a regular file (if recursive == - false). */ - StorePath addToStoreFromDump(const string & dump, const string & name, - FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, RepairFlag repair = NoRepair) override; + StorePath addToStoreFromDump(Source & dump, const string & name, + FileIngestionMethod method, HashType hashAlgo, RepairFlag repair) override; StorePath addTextToStore(const string & name, const string & s, const StorePathSet & references, RepairFlag repair) override; @@ -291,6 +286,11 @@ private: specified by the ‘secret-key-files’ option. */ void signPathInfo(ValidPathInfo & info); + /* Register the store path 'output' as the output named 'outputName' of + derivation 'deriver'. */ + void linkDeriverToPath(const StorePath & deriver, const string & outputName, const StorePath & output); + void linkDeriverToPath(State & state, uint64_t deriver, const string & outputName, const StorePath & output); + Path getRealStoreDir() override { return realStoreDir; } void createUser(const std::string & userName, uid_t userId) override; diff --git a/src/libstore/local.mk b/src/libstore/local.mk index aec4ed493..d266c8efe 100644 --- a/src/libstore/local.mk +++ b/src/libstore/local.mk @@ -61,3 +61,6 @@ $(d)/build.cc: clean-files += $(d)/schema.sql.gen.hh $(eval $(call install-file-in, $(d)/nix-store.pc, $(prefix)/lib/pkgconfig, 0644)) + +$(foreach i, $(wildcard src/libstore/builtins/*.hh), \ + $(eval $(call install-file-in, $(i), $(includedir)/nix/builtins, 0644))) diff --git a/src/libstore/machines.cc b/src/libstore/machines.cc index f848582da..7db2556f4 100644 --- a/src/libstore/machines.cc +++ b/src/libstore/machines.cc @@ -1,6 +1,7 @@ #include "machines.hh" #include "util.hh" #include "globals.hh" +#include "store-api.hh" #include @@ -48,6 +49,29 @@ bool Machine::mandatoryMet(const std::set & features) const { }); } +ref Machine::openStore() const { + Store::Params storeParams; + if (hasPrefix(storeUri, "ssh://")) { + storeParams["max-connections"] = "1"; + storeParams["log-fd"] = "4"; + if (sshKey != "") + storeParams["ssh-key"] = sshKey; + } + { + auto & fs = storeParams["system-features"]; + auto append = [&](auto feats) { + for (auto & f : feats) { + if (fs.size() > 0) fs += ' '; + fs += f; + } + }; + append(supportedFeatures); + append(mandatoryFeatures); + } + + return nix::openStore(storeUri, storeParams); +} + void parseMachines(const std::string & s, Machines & machines) { for (auto line : tokenizeString>(s, "\n;")) { diff --git a/src/libstore/machines.hh b/src/libstore/machines.hh index de92eb924..341d9bd97 100644 --- a/src/libstore/machines.hh +++ b/src/libstore/machines.hh @@ -4,6 +4,8 @@ namespace nix { +class Store; + struct Machine { const string storeUri; @@ -28,6 +30,8 @@ struct Machine { decltype(supportedFeatures) supportedFeatures, decltype(mandatoryFeatures) mandatoryFeatures, decltype(sshPublicHostKey) sshPublicHostKey); + + ref openStore() const; }; typedef std::vector Machines; diff --git a/src/libstore/misc.cc b/src/libstore/misc.cc index e68edb38c..ad4dccef9 100644 --- a/src/libstore/misc.cc +++ b/src/libstore/misc.cc @@ -4,7 +4,8 @@ #include "local-store.hh" #include "store-api.hh" #include "thread-pool.hh" - +#include "topo-sort.hh" +#include "callback.hh" namespace nix { @@ -108,9 +109,19 @@ void Store::computeFSClosure(const StorePath & startPath, } +std::optional getDerivationCA(const BasicDerivation & drv) +{ + auto out = drv.outputs.find("out"); + if (out != drv.outputs.end()) { + if (auto v = std::get_if(&out->second.output)) + return v->hash; + } + return std::nullopt; +} + void Store::queryMissing(const std::vector & targets, StorePathSet & willBuild_, StorePathSet & willSubstitute_, StorePathSet & unknown_, - unsigned long long & downloadSize_, unsigned long long & narSize_) + uint64_t & downloadSize_, uint64_t & narSize_) { Activity act(*logger, lvlDebug, actUnknown, "querying info about missing paths"); @@ -122,8 +133,8 @@ void Store::queryMissing(const std::vector & targets, { std::unordered_set done; StorePathSet & unknown, & willSubstitute, & willBuild; - unsigned long long & downloadSize; - unsigned long long & narSize; + uint64_t & downloadSize; + uint64_t & narSize; }; struct DrvState @@ -157,7 +168,7 @@ void Store::queryMissing(const std::vector & targets, auto outPath = parseStorePath(outPathS); SubstitutablePathInfos infos; - querySubstitutablePathInfos({outPath}, infos); + querySubstitutablePathInfos({{outPath, getDerivationCA(*drv)}}, infos); if (infos.empty()) { drvState_->lock()->done = true; @@ -192,17 +203,24 @@ void Store::queryMissing(const std::vector & targets, return; } + PathSet invalid; + /* true for regular derivations, and CA derivations for which we + have a trust mapping for all wanted outputs. */ + auto knownOutputPaths = true; + for (auto & [outputName, pathOpt] : queryPartialDerivationOutputMap(path.path)) { + if (!pathOpt) { + knownOutputPaths = false; + break; + } + if (wantOutput(outputName, path.outputs) && !isValidPath(*pathOpt)) + invalid.insert(printStorePath(*pathOpt)); + } + if (knownOutputPaths && invalid.empty()) return; + auto drv = make_ref(derivationFromPath(path.path)); ParsedDerivation parsedDrv(StorePath(path.path), *drv); - PathSet invalid; - for (auto & j : drv->outputs) - if (wantOutput(j.first, path.outputs) - && !isValidPath(j.second.path)) - invalid.insert(printStorePath(j.second.path)); - if (invalid.empty()) return; - - if (settings.useSubstitutes && parsedDrv.substitutesAllowed()) { + if (knownOutputPaths && settings.useSubstitutes && parsedDrv.substitutesAllowed()) { auto drvState = make_ref>(DrvState(invalid.size())); for (auto & output : invalid) pool.enqueue(std::bind(checkOutput, printStorePath(path.path), drv, output, drvState)); @@ -214,7 +232,7 @@ void Store::queryMissing(const std::vector & targets, if (isValidPath(path.path)) return; SubstitutablePathInfos infos; - querySubstitutablePathInfos({path.path}, infos); + querySubstitutablePathInfos({{path.path, std::nullopt}}, infos); if (infos.empty()) { auto state(state_.lock()); @@ -246,41 +264,21 @@ void Store::queryMissing(const std::vector & targets, StorePaths Store::topoSortPaths(const StorePathSet & paths) { - StorePaths sorted; - StorePathSet visited, parents; - - std::function dfsVisit; - - dfsVisit = [&](const StorePath & path, const StorePath * parent) { - if (parents.count(path)) - throw BuildError("cycle detected in the references of '%s' from '%s'", - printStorePath(path), printStorePath(*parent)); - - if (!visited.insert(path).second) return; - parents.insert(path); - - StorePathSet references; - try { - references = queryPathInfo(path)->references; - } catch (InvalidPath &) { - } - - for (auto & i : references) - /* Don't traverse into paths that don't exist. That can - happen due to substitutes for non-existent paths. */ - if (i != path && paths.count(i)) - dfsVisit(i, &path); - - sorted.push_back(path); - parents.erase(path); - }; - - for (auto & i : paths) - dfsVisit(i, nullptr); - - std::reverse(sorted.begin(), sorted.end()); - - return sorted; + return topoSort(paths, + {[&](const StorePath & path) { + StorePathSet references; + try { + references = queryPathInfo(path)->references; + } catch (InvalidPath &) { + } + return references; + }}, + {[&](const StorePath & path, const StorePath & parent) { + return BuildError( + "cycle detected in the references of '%s' from '%s'", + printStorePath(path), + printStorePath(parent)); + }}); } diff --git a/src/libstore/names.cc b/src/libstore/names.cc index d1c8a6101..41e28dc99 100644 --- a/src/libstore/names.cc +++ b/src/libstore/names.cc @@ -1,10 +1,18 @@ #include "names.hh" #include "util.hh" +#include + namespace nix { +struct Regex +{ + std::regex regex; +}; + + DrvName::DrvName() { name = ""; @@ -30,11 +38,18 @@ DrvName::DrvName(std::string_view s) : hits(0) } +DrvName::~DrvName() +{ } + + bool DrvName::matches(DrvName & n) { if (name != "*") { - if (!regex) regex = std::unique_ptr(new std::regex(name, std::regex::extended)); - if (!std::regex_match(n.name, *regex)) return false; + if (!regex) { + regex = std::make_unique(); + regex->regex = std::regex(name, std::regex::extended); + } + if (!std::regex_match(n.name, regex->regex)) return false; } if (version != "" && version != n.version) return false; return true; @@ -99,7 +114,7 @@ DrvNames drvNamesFromArgs(const Strings & opArgs) { DrvNames result; for (auto & i : opArgs) - result.push_back(DrvName(i)); + result.emplace_back(i); return result; } diff --git a/src/libstore/names.hh b/src/libstore/names.hh index 00e14b8c7..bc62aac93 100644 --- a/src/libstore/names.hh +++ b/src/libstore/names.hh @@ -3,10 +3,11 @@ #include #include "types.hh" -#include namespace nix { +struct Regex; + struct DrvName { string fullName; @@ -16,10 +17,12 @@ struct DrvName DrvName(); DrvName(std::string_view s); + ~DrvName(); + bool matches(DrvName & n); private: - std::unique_ptr regex; + std::unique_ptr regex; }; typedef list DrvNames; diff --git a/src/libstore/nar-accessor.cc b/src/libstore/nar-accessor.cc index ca663d837..a9efdd0b6 100644 --- a/src/libstore/nar-accessor.cc +++ b/src/libstore/nar-accessor.cc @@ -18,7 +18,7 @@ struct NarMember /* If this is a regular file, position of the contents of this file in the NAR. */ - size_t start = 0, size = 0; + uint64_t start = 0, size = 0; std::string target; @@ -34,20 +34,23 @@ struct NarAccessor : public FSAccessor NarMember root; - struct NarIndexer : ParseSink, StringSource + struct NarIndexer : ParseSink, Source { NarAccessor & acc; + Source & source; std::stack parents; - std::string currentStart; bool isExec = false; - NarIndexer(NarAccessor & acc, const std::string & nar) - : StringSource(nar), acc(acc) + uint64_t pos = 0; + + NarIndexer(NarAccessor & acc, Source & source) + : acc(acc), source(source) { } - void createMember(const Path & path, NarMember member) { + void createMember(const Path & path, NarMember member) + { size_t level = std::count(path.begin(), path.end(), '/'); while (parents.size() > level) parents.pop(); @@ -77,33 +80,40 @@ struct NarAccessor : public FSAccessor parents.top()->isExecutable = true; } - void preallocateContents(unsigned long long size) override + void preallocateContents(uint64_t size) override { - currentStart = string(s, pos, 16); - assert(size <= std::numeric_limits::max()); - parents.top()->size = (size_t)size; + assert(size <= std::numeric_limits::max()); + parents.top()->size = (uint64_t) size; parents.top()->start = pos; } - void receiveContents(unsigned char * data, unsigned int len) override - { - // Sanity check - if (!currentStart.empty()) { - assert(len < 16 || currentStart == string((char *) data, 16)); - currentStart.clear(); - } - } + void receiveContents(unsigned char * data, size_t len) override + { } void createSymlink(const Path & path, const string & target) override { createMember(path, NarMember{FSAccessor::Type::tSymlink, false, 0, 0, target}); } + + size_t read(unsigned char * data, size_t len) override + { + auto n = source.read(data, len); + pos += n; + return n; + } }; NarAccessor(ref nar) : nar(nar) { - NarIndexer indexer(*this, *nar); + StringSource source(*nar); + NarIndexer indexer(*this, source); + parseDump(indexer, indexer); + } + + NarAccessor(Source & source) + { + NarIndexer indexer(*this, source); parseDump(indexer, indexer); } @@ -219,6 +229,11 @@ ref makeNarAccessor(ref nar) return make_ref(nar); } +ref makeNarAccessor(Source & source) +{ + return make_ref(source); +} + ref makeLazyNarAccessor(const std::string & listing, GetNarBytes getNarBytes) { diff --git a/src/libstore/nar-accessor.hh b/src/libstore/nar-accessor.hh index 2871199de..8af1272f6 100644 --- a/src/libstore/nar-accessor.hh +++ b/src/libstore/nar-accessor.hh @@ -6,10 +6,14 @@ namespace nix { +struct Source; + /* Return an object that provides access to the contents of a NAR file. */ ref makeNarAccessor(ref nar); +ref makeNarAccessor(Source & source); + /* Create a NAR accessor from a NAR listing (in the format produced by listNar()). The callback getNarBytes(offset, length) is used by the readFile() method of the accessor to get the contents of files diff --git a/src/libstore/nar-info-disk-cache.cc b/src/libstore/nar-info-disk-cache.cc index 012dea6ea..8541cc51f 100644 --- a/src/libstore/nar-info-disk-cache.cc +++ b/src/libstore/nar-info-disk-cache.cc @@ -189,13 +189,14 @@ public: return {oInvalid, 0}; auto namePart = queryNAR.getStr(1); - auto narInfo = make_ref(StorePath(hashPart + "-" + namePart)); + auto narInfo = make_ref( + StorePath(hashPart + "-" + namePart), + Hash::parseAnyPrefixed(queryNAR.getStr(6))); narInfo->url = queryNAR.getStr(2); narInfo->compression = queryNAR.getStr(3); if (!queryNAR.isNull(4)) - narInfo->fileHash = Hash(queryNAR.getStr(4)); + narInfo->fileHash = Hash::parseAnyPrefixed(queryNAR.getStr(4)); narInfo->fileSize = queryNAR.getInt(5); - narInfo->narHash = Hash(queryNAR.getStr(6)); narInfo->narSize = queryNAR.getInt(7); for (auto & r : tokenizeString(queryNAR.getStr(8), " ")) narInfo->references.insert(StorePath(r)); @@ -230,7 +231,7 @@ public: (std::string(info->path.name())) (narInfo ? narInfo->url : "", narInfo != 0) (narInfo ? narInfo->compression : "", narInfo != 0) - (narInfo && narInfo->fileHash ? narInfo->fileHash.to_string(Base32, true) : "", narInfo && narInfo->fileHash) + (narInfo && narInfo->fileHash ? narInfo->fileHash->to_string(Base32, true) : "", narInfo && narInfo->fileHash) (narInfo ? narInfo->fileSize : 0, narInfo != 0 && narInfo->fileSize) (info->narHash.to_string(Base32, true)) (info->narSize) diff --git a/src/libstore/nar-info.cc b/src/libstore/nar-info.cc index 04550ed97..3454f34bb 100644 --- a/src/libstore/nar-info.cc +++ b/src/libstore/nar-info.cc @@ -1,36 +1,37 @@ #include "globals.hh" #include "nar-info.hh" +#include "store-api.hh" namespace nix { NarInfo::NarInfo(const Store & store, const std::string & s, const std::string & whence) - : ValidPathInfo(StorePath(StorePath::dummy)) // FIXME: hack + : ValidPathInfo(StorePath(StorePath::dummy), Hash(Hash::dummy)) // FIXME: hack { auto corrupt = [&]() { - throw Error("NAR info file '%1%' is corrupt", whence); + return Error("NAR info file '%1%' is corrupt", whence); }; auto parseHashField = [&](const string & s) { try { - return Hash(s); + return Hash::parseAnyPrefixed(s); } catch (BadHash &) { - corrupt(); - return Hash(); // never reached + throw corrupt(); } }; bool havePath = false; + bool haveNarHash = false; size_t pos = 0; while (pos < s.size()) { size_t colon = s.find(':', pos); - if (colon == std::string::npos) corrupt(); + if (colon == std::string::npos) throw corrupt(); std::string name(s, pos, colon - pos); size_t eol = s.find('\n', colon + 2); - if (eol == std::string::npos) corrupt(); + if (eol == std::string::npos) throw corrupt(); std::string value(s, colon + 2, eol - colon - 2); @@ -45,16 +46,18 @@ NarInfo::NarInfo(const Store & store, const std::string & s, const std::string & else if (name == "FileHash") fileHash = parseHashField(value); else if (name == "FileSize") { - if (!string2Int(value, fileSize)) corrupt(); + if (!string2Int(value, fileSize)) throw corrupt(); } - else if (name == "NarHash") + else if (name == "NarHash") { narHash = parseHashField(value); + haveNarHash = true; + } else if (name == "NarSize") { - if (!string2Int(value, narSize)) corrupt(); + if (!string2Int(value, narSize)) throw corrupt(); } else if (name == "References") { auto refs = tokenizeString(value, " "); - if (!references.empty()) corrupt(); + if (!references.empty()) throw corrupt(); for (auto & r : refs) references.insert(StorePath(r)); } @@ -67,7 +70,7 @@ NarInfo::NarInfo(const Store & store, const std::string & s, const std::string & else if (name == "Sig") sigs.insert(value); else if (name == "CA") { - if (ca) corrupt(); + if (ca) throw corrupt(); // FIXME: allow blank ca or require skipping field? ca = parseContentAddressOpt(value); } @@ -77,7 +80,7 @@ NarInfo::NarInfo(const Store & store, const std::string & s, const std::string & if (compression == "") compression = "bzip2"; - if (!havePath || url.empty() || narSize == 0 || !narHash) corrupt(); + if (!havePath || !haveNarHash || url.empty() || narSize == 0) throw corrupt(); } std::string NarInfo::to_string(const Store & store) const @@ -87,8 +90,8 @@ std::string NarInfo::to_string(const Store & store) const res += "URL: " + url + "\n"; assert(compression != ""); res += "Compression: " + compression + "\n"; - assert(fileHash.type == htSHA256); - res += "FileHash: " + fileHash.to_string(Base32, true) + "\n"; + assert(fileHash && fileHash->type == htSHA256); + res += "FileHash: " + fileHash->to_string(Base32, true) + "\n"; res += "FileSize: " + std::to_string(fileSize) + "\n"; assert(narHash.type == htSHA256); res += "NarHash: " + narHash.to_string(Base32, true) + "\n"; diff --git a/src/libstore/nar-info.hh b/src/libstore/nar-info.hh index 373c33427..39ced76e5 100644 --- a/src/libstore/nar-info.hh +++ b/src/libstore/nar-info.hh @@ -2,20 +2,22 @@ #include "types.hh" #include "hash.hh" -#include "store-api.hh" +#include "path-info.hh" namespace nix { +class Store; + struct NarInfo : ValidPathInfo { std::string url; std::string compression; - Hash fileHash; + std::optional fileHash; uint64_t fileSize = 0; std::string system; NarInfo() = delete; - NarInfo(StorePath && path) : ValidPathInfo(std::move(path)) { } + NarInfo(StorePath && path, Hash narHash) : ValidPathInfo(std::move(path), narHash) { } NarInfo(const ValidPathInfo & info) : ValidPathInfo(info) { } NarInfo(const Store & store, const std::string & s, const std::string & whence); diff --git a/src/libstore/optimise-store.cc b/src/libstore/optimise-store.cc index b2b2412a3..a0d482ddf 100644 --- a/src/libstore/optimise-store.cc +++ b/src/libstore/optimise-store.cc @@ -17,9 +17,7 @@ namespace nix { static void makeWritable(const Path & path) { - struct stat st; - if (lstat(path.c_str(), &st)) - throw SysError("getting attributes of path '%1%'", path); + auto st = lstat(path); if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1) throw SysError("changing writability of '%1%'", path); } @@ -94,9 +92,7 @@ void LocalStore::optimisePath_(Activity * act, OptimiseStats & stats, { checkInterrupt(); - struct stat st; - if (lstat(path.c_str(), &st)) - throw SysError("getting attributes of path '%1%'", path); + auto st = lstat(path); #if __APPLE__ /* HFS/macOS has some undocumented security feature disabling hardlinking for @@ -187,9 +183,7 @@ void LocalStore::optimisePath_(Activity * act, OptimiseStats & stats, /* Yes! We've seen a file with the same contents. Replace the current file with a hard link to that file. */ - struct stat stLink; - if (lstat(linkPath.c_str(), &stLink)) - throw SysError("getting attributes of path '%1%'", linkPath); + auto stLink = lstat(linkPath); if (st.st_ino == stLink.st_ino) { debug(format("'%1%' is already linked to '%2%'") % path % linkPath); @@ -282,21 +276,15 @@ void LocalStore::optimiseStore(OptimiseStats & stats) } } -static string showBytes(unsigned long long bytes) -{ - return (format("%.2f MiB") % (bytes / (1024.0 * 1024.0))).str(); -} - void LocalStore::optimiseStore() { OptimiseStats stats; optimiseStore(stats); - printInfo( - format("%1% freed by hard-linking %2% files") - % showBytes(stats.bytesFreed) - % stats.filesLinked); + printInfo("%s freed by hard-linking %d files", + showBytes(stats.bytesFreed), + stats.filesLinked); } void LocalStore::optimisePath(const Path & path) diff --git a/src/libstore/parsed-derivations.cc b/src/libstore/parsed-derivations.cc index c7797b730..e7b7202d4 100644 --- a/src/libstore/parsed-derivations.cc +++ b/src/libstore/parsed-derivations.cc @@ -94,7 +94,7 @@ StringSet ParsedDerivation::getRequiredSystemFeatures() const return res; } -bool ParsedDerivation::canBuildLocally() const +bool ParsedDerivation::canBuildLocally(Store & localStore) const { if (drv.platform != settings.thisSystem.get() && !settings.extraPlatforms.get().count(drv.platform) @@ -102,14 +102,14 @@ bool ParsedDerivation::canBuildLocally() const return false; for (auto & feature : getRequiredSystemFeatures()) - if (!settings.systemFeatures.get().count(feature)) return false; + if (!localStore.systemFeatures.get().count(feature)) return false; return true; } -bool ParsedDerivation::willBuildLocally() const +bool ParsedDerivation::willBuildLocally(Store & localStore) const { - return getBoolAttr("preferLocalBuild") && canBuildLocally(); + return getBoolAttr("preferLocalBuild") && canBuildLocally(localStore); } bool ParsedDerivation::substitutesAllowed() const @@ -117,9 +117,4 @@ bool ParsedDerivation::substitutesAllowed() const return getBoolAttr("allowSubstitutes", true); } -bool ParsedDerivation::contentAddressed() const -{ - return getBoolAttr("__contentAddressed", false); -} - } diff --git a/src/libstore/parsed-derivations.hh b/src/libstore/parsed-derivations.hh index 0b8e8d031..c9fbe68c4 100644 --- a/src/libstore/parsed-derivations.hh +++ b/src/libstore/parsed-derivations.hh @@ -1,3 +1,5 @@ +#pragma once + #include "store-api.hh" #include @@ -29,13 +31,11 @@ public: StringSet getRequiredSystemFeatures() const; - bool canBuildLocally() const; + bool canBuildLocally(Store & localStore) const; - bool willBuildLocally() const; + bool willBuildLocally(Store & localStore) const; bool substitutesAllowed() const; - - bool contentAddressed() const; }; } diff --git a/src/libstore/path-info.hh b/src/libstore/path-info.hh new file mode 100644 index 000000000..8ff5c466e --- /dev/null +++ b/src/libstore/path-info.hh @@ -0,0 +1,112 @@ +#pragma once + +#include "crypto.hh" +#include "path.hh" +#include "hash.hh" +#include "content-address.hh" + +#include +#include + +namespace nix { + + +class Store; + + +struct SubstitutablePathInfo +{ + std::optional deriver; + StorePathSet references; + uint64_t downloadSize; /* 0 = unknown or inapplicable */ + uint64_t narSize; /* 0 = unknown */ +}; + +typedef std::map SubstitutablePathInfos; + + +struct ValidPathInfo +{ + StorePath path; + std::optional deriver; + // TODO document this + Hash narHash; + StorePathSet references; + time_t registrationTime = 0; + uint64_t narSize = 0; // 0 = unknown + uint64_t id; // internal use only + + /* Whether the path is ultimately trusted, that is, it's a + derivation output that was built locally. */ + bool ultimate = false; + + StringSet sigs; // note: not necessarily verified + + /* If non-empty, an assertion that the path is content-addressed, + i.e., that the store path is computed from a cryptographic hash + of the contents of the path, plus some other bits of data like + the "name" part of the path. Such a path doesn't need + signatures, since we don't have to trust anybody's claim that + the path is the output of a particular derivation. (In the + extensional store model, we have to trust that the *contents* + of an output path of a derivation were actually produced by + that derivation. In the intensional model, we have to trust + that a particular output path was produced by a derivation; the + path then implies the contents.) + + Ideally, the content-addressability assertion would just be a Boolean, + and the store path would be computed from the name component, ‘narHash’ + and ‘references’. However, we support many types of content addresses. + */ + std::optional ca; + + bool operator == (const ValidPathInfo & i) const + { + return + path == i.path + && narHash == i.narHash + && references == i.references; + } + + /* Return a fingerprint of the store path to be used in binary + cache signatures. It contains the store path, the base-32 + SHA-256 hash of the NAR serialisation of the path, the size of + the NAR, and the sorted references. The size field is strictly + speaking superfluous, but might prevent endless/excessive data + attacks. */ + std::string fingerprint(const Store & store) const; + + void sign(const Store & store, const SecretKey & secretKey); + + /* Return true iff the path is verifiably content-addressed. */ + bool isContentAddressed(const Store & store) const; + + /* Functions to view references + hasSelfReference as one set, mainly for + compatibility's sake. */ + StorePathSet referencesPossiblyToSelf() const; + void insertReferencePossiblyToSelf(StorePath && ref); + void setReferencesPossiblyToSelf(StorePathSet && refs); + + static const size_t maxSigs = std::numeric_limits::max(); + + /* Return the number of signatures on this .narinfo that were + produced by one of the specified keys, or maxSigs if the path + is content-addressed. */ + size_t checkSignatures(const Store & store, const PublicKeys & publicKeys) const; + + /* Verify a single signature. */ + bool checkSignature(const Store & store, const PublicKeys & publicKeys, const std::string & sig) const; + + Strings shortRefs() const; + + ValidPathInfo(const ValidPathInfo & other) = default; + + ValidPathInfo(StorePath && path, Hash narHash) : path(std::move(path)), narHash(narHash) { }; + ValidPathInfo(const StorePath & path, Hash narHash) : path(path), narHash(narHash) { }; + + virtual ~ValidPathInfo() { } +}; + +typedef list ValidPathInfos; + +} diff --git a/src/libstore/path.cc b/src/libstore/path.cc index b3d8ce95c..dc9dc3897 100644 --- a/src/libstore/path.cc +++ b/src/libstore/path.cc @@ -2,8 +2,6 @@ namespace nix { -MakeError(BadStorePath, Error); - static void checkName(std::string_view path, std::string_view name) { if (name.empty()) diff --git a/src/libstore/path.hh b/src/libstore/path.hh index e43a8b50c..b03a0f69d 100644 --- a/src/libstore/path.hh +++ b/src/libstore/path.hh @@ -64,6 +64,8 @@ typedef std::set StorePathSet; typedef std::vector StorePaths; typedef std::map OutputPathMap; +typedef std::map> StorePathCAMap; + /* Extension of derivations in the Nix store. */ const std::string drvExtension = ".drv"; diff --git a/src/libstore/profiles.cc b/src/libstore/profiles.cc index 6cfe393a4..c3809bad7 100644 --- a/src/libstore/profiles.cc +++ b/src/libstore/profiles.cc @@ -12,30 +12,24 @@ namespace nix { -static bool cmpGensByNumber(const Generation & a, const Generation & b) -{ - return a.number < b.number; -} - - /* Parse a generation name of the format `--link'. */ -static int parseName(const string & profileName, const string & name) +static std::optional parseName(const string & profileName, const string & name) { - if (string(name, 0, profileName.size() + 1) != profileName + "-") return -1; + if (string(name, 0, profileName.size() + 1) != profileName + "-") return {}; string s = string(name, profileName.size() + 1); string::size_type p = s.find("-link"); - if (p == string::npos) return -1; - int n; + if (p == string::npos) return {}; + unsigned int n; if (string2Int(string(s, 0, p), n) && n >= 0) return n; else - return -1; + return {}; } -Generations findGenerations(Path profile, int & curGen) +std::pair> findGenerations(Path profile) { Generations gens; @@ -43,30 +37,31 @@ Generations findGenerations(Path profile, int & curGen) auto profileName = std::string(baseNameOf(profile)); for (auto & i : readDirectory(profileDir)) { - int n; - if ((n = parseName(profileName, i.name)) != -1) { - Generation gen; - gen.path = profileDir + "/" + i.name; - gen.number = n; - struct stat st; - if (lstat(gen.path.c_str(), &st) != 0) - throw SysError("statting '%1%'", gen.path); - gen.creationTime = st.st_mtime; - gens.push_back(gen); + if (auto n = parseName(profileName, i.name)) { + auto path = profileDir + "/" + i.name; + gens.push_back({ + .number = *n, + .path = path, + .creationTime = lstat(path).st_mtime + }); } } - gens.sort(cmpGensByNumber); + gens.sort([](const Generation & a, const Generation & b) + { + return a.number < b.number; + }); - curGen = pathExists(profile) + return { + gens, + pathExists(profile) ? parseName(profileName, readLink(profile)) - : -1; - - return gens; + : std::nullopt + }; } -static void makeName(const Path & profile, unsigned int num, +static void makeName(const Path & profile, GenerationNumber num, Path & outLink) { Path prefix = (format("%1%-%2%") % profile % num).str(); @@ -74,18 +69,17 @@ static void makeName(const Path & profile, unsigned int num, } -Path createGeneration(ref store, Path profile, Path outPath) +Path createGeneration(ref store, Path profile, StorePath outPath) { /* The new generation number should be higher than old the previous ones. */ - int dummy; - Generations gens = findGenerations(profile, dummy); + auto [gens, dummy] = findGenerations(profile); - unsigned int num; + GenerationNumber num; if (gens.size() > 0) { Generation last = gens.back(); - if (readLink(last.path) == outPath) { + if (readLink(last.path) == store->printStorePath(outPath)) { /* We only create a new generation symlink if it differs from the last one. @@ -108,7 +102,7 @@ Path createGeneration(ref store, Path profile, Path outPath) user environment etc. we've just built. */ Path generation; makeName(profile, num + 1, generation); - store->addPermRoot(store->parseStorePath(outPath), generation, false, true); + store->addPermRoot(outPath, generation); return generation; } @@ -121,7 +115,7 @@ static void removeFile(const Path & path) } -void deleteGeneration(const Path & profile, unsigned int gen) +void deleteGeneration(const Path & profile, GenerationNumber gen) { Path generation; makeName(profile, gen, generation); @@ -129,7 +123,7 @@ void deleteGeneration(const Path & profile, unsigned int gen) } -static void deleteGeneration2(const Path & profile, unsigned int gen, bool dryRun) +static void deleteGeneration2(const Path & profile, GenerationNumber gen, bool dryRun) { if (dryRun) printInfo(format("would remove generation %1%") % gen); @@ -140,31 +134,29 @@ static void deleteGeneration2(const Path & profile, unsigned int gen, bool dryRu } -void deleteGenerations(const Path & profile, const std::set & gensToDelete, bool dryRun) +void deleteGenerations(const Path & profile, const std::set & gensToDelete, bool dryRun) { PathLocks lock; lockProfile(lock, profile); - int curGen; - Generations gens = findGenerations(profile, curGen); + auto [gens, curGen] = findGenerations(profile); - if (gensToDelete.find(curGen) != gensToDelete.end()) + if (gensToDelete.count(*curGen)) throw Error("cannot delete current generation of profile %1%'", profile); for (auto & i : gens) { - if (gensToDelete.find(i.number) == gensToDelete.end()) continue; + if (!gensToDelete.count(i.number)) continue; deleteGeneration2(profile, i.number, dryRun); } } -void deleteGenerationsGreaterThan(const Path & profile, int max, bool dryRun) +void deleteGenerationsGreaterThan(const Path & profile, GenerationNumber max, bool dryRun) { PathLocks lock; lockProfile(lock, profile); - int curGen; bool fromCurGen = false; - Generations gens = findGenerations(profile, curGen); + auto [gens, curGen] = findGenerations(profile); for (auto i = gens.rbegin(); i != gens.rend(); ++i) { if (i->number == curGen) { fromCurGen = true; @@ -186,8 +178,7 @@ void deleteOldGenerations(const Path & profile, bool dryRun) PathLocks lock; lockProfile(lock, profile); - int curGen; - Generations gens = findGenerations(profile, curGen); + auto [gens, curGen] = findGenerations(profile); for (auto & i : gens) if (i.number != curGen) @@ -200,8 +191,7 @@ void deleteGenerationsOlderThan(const Path & profile, time_t t, bool dryRun) PathLocks lock; lockProfile(lock, profile); - int curGen; - Generations gens = findGenerations(profile, curGen); + auto [gens, curGen] = findGenerations(profile); bool canDelete = false; for (auto i = gens.rbegin(); i != gens.rend(); ++i) diff --git a/src/libstore/profiles.hh b/src/libstore/profiles.hh index 78645d8b6..be55a65d4 100644 --- a/src/libstore/profiles.hh +++ b/src/libstore/profiles.hh @@ -8,38 +8,35 @@ namespace nix { +class StorePath; + + +typedef unsigned int GenerationNumber; struct Generation { - int number; + GenerationNumber number; Path path; time_t creationTime; - Generation() - { - number = -1; - } - operator bool() const - { - return number != -1; - } }; -typedef list Generations; +typedef std::list Generations; /* Returns the list of currently present generations for the specified - profile, sorted by generation number. */ -Generations findGenerations(Path profile, int & curGen); + profile, sorted by generation number. Also returns the number of + the current generation. */ +std::pair> findGenerations(Path profile); class LocalFSStore; -Path createGeneration(ref store, Path profile, Path outPath); +Path createGeneration(ref store, Path profile, StorePath outPath); -void deleteGeneration(const Path & profile, unsigned int gen); +void deleteGeneration(const Path & profile, GenerationNumber gen); -void deleteGenerations(const Path & profile, const std::set & gensToDelete, bool dryRun); +void deleteGenerations(const Path & profile, const std::set & gensToDelete, bool dryRun); -void deleteGenerationsGreaterThan(const Path & profile, const int max, bool dryRun); +void deleteGenerationsGreaterThan(const Path & profile, GenerationNumber max, bool dryRun); void deleteOldGenerations(const Path & profile, bool dryRun); diff --git a/src/libstore/references.cc b/src/libstore/references.cc index a10d536a3..d2096cb49 100644 --- a/src/libstore/references.cc +++ b/src/libstore/references.cc @@ -48,13 +48,12 @@ static void search(const unsigned char * s, size_t len, struct RefScanSink : Sink { - HashSink hashSink; StringSet hashes; StringSet seen; string tail; - RefScanSink() : hashSink(htSHA256) { } + RefScanSink() { } void operator () (const unsigned char * data, size_t len); }; @@ -62,8 +61,6 @@ struct RefScanSink : Sink void RefScanSink::operator () (const unsigned char * data, size_t len) { - hashSink(data, len); - /* It's possible that a reference spans the previous and current fragment, so search in the concatenation of the tail of the previous fragment and the start of the current fragment. */ @@ -79,10 +76,20 @@ void RefScanSink::operator () (const unsigned char * data, size_t len) } -PathSet scanForReferences(const string & path, - const PathSet & refs, HashResult & hash) +std::pair scanForReferences(const string & path, + const PathSet & refs) { - RefScanSink sink; + HashSink hashSink { htSHA256 }; + auto found = scanForReferences(hashSink, path, refs); + auto hash = hashSink.finish(); + return std::pair(found, hash); +} + +PathSet scanForReferences(Sink & toTee, + const string & path, const PathSet & refs) +{ + RefScanSink refsSink; + TeeSink sink { refsSink, toTee }; std::map backMap; /* For efficiency (and a higher hit rate), just search for the @@ -97,7 +104,7 @@ PathSet scanForReferences(const string & path, assert(s.size() == refLength); assert(backMap.find(s) == backMap.end()); // parseHash(htSHA256, s); - sink.hashes.insert(s); + refsSink.hashes.insert(s); backMap[s] = i; } @@ -106,14 +113,12 @@ PathSet scanForReferences(const string & path, /* Map the hashes found back to their store paths. */ PathSet found; - for (auto & i : sink.seen) { + for (auto & i : refsSink.seen) { std::map::iterator j; if ((j = backMap.find(i)) == backMap.end()) abort(); found.insert(j->second); } - hash = sink.hashSink.finish(); - return found; } diff --git a/src/libstore/references.hh b/src/libstore/references.hh index c38bdd720..c2efd095c 100644 --- a/src/libstore/references.hh +++ b/src/libstore/references.hh @@ -5,8 +5,9 @@ namespace nix { -PathSet scanForReferences(const Path & path, const PathSet & refs, - HashResult & hash); +std::pair scanForReferences(const Path & path, const PathSet & refs); + +PathSet scanForReferences(Sink & toTee, const Path & path, const PathSet & refs); struct RewritingSink : Sink { diff --git a/src/libstore/remote-fs-accessor.cc b/src/libstore/remote-fs-accessor.cc index bd698d781..2d02a181b 100644 --- a/src/libstore/remote-fs-accessor.cc +++ b/src/libstore/remote-fs-accessor.cc @@ -16,26 +16,26 @@ RemoteFSAccessor::RemoteFSAccessor(ref store, const Path & cacheDir) createDirs(cacheDir); } -Path RemoteFSAccessor::makeCacheFile(const Path & storePath, const std::string & ext) +Path RemoteFSAccessor::makeCacheFile(std::string_view hashPart, const std::string & ext) { assert(cacheDir != ""); - return fmt("%s/%s.%s", cacheDir, store->parseStorePath(storePath).hashPart(), ext); + return fmt("%s/%s.%s", cacheDir, hashPart, ext); } -void RemoteFSAccessor::addToCache(const Path & storePath, const std::string & nar, +void RemoteFSAccessor::addToCache(std::string_view hashPart, const std::string & nar, ref narAccessor) { - nars.emplace(storePath, narAccessor); + nars.emplace(hashPart, narAccessor); if (cacheDir != "") { try { std::ostringstream str; JSONPlaceholder jsonRoot(str); listNar(jsonRoot, narAccessor, "", true); - writeFile(makeCacheFile(storePath, "ls"), str.str()); + writeFile(makeCacheFile(hashPart, "ls"), str.str()); /* FIXME: do this asynchronously. */ - writeFile(makeCacheFile(storePath, "nar"), nar); + writeFile(makeCacheFile(hashPart, "nar"), nar); } catch (...) { ignoreException(); @@ -47,23 +47,22 @@ std::pair, Path> RemoteFSAccessor::fetch(const Path & path_) { auto path = canonPath(path_); - auto storePath = store->toStorePath(path); - std::string restPath = std::string(path, storePath.size()); + auto [storePath, restPath] = store->toStorePath(path); - if (!store->isValidPath(store->parseStorePath(storePath))) - throw InvalidPath("path '%1%' is not a valid store path", storePath); + if (!store->isValidPath(storePath)) + throw InvalidPath("path '%1%' is not a valid store path", store->printStorePath(storePath)); - auto i = nars.find(storePath); + auto i = nars.find(std::string(storePath.hashPart())); if (i != nars.end()) return {i->second, restPath}; StringSink sink; std::string listing; Path cacheFile; - if (cacheDir != "" && pathExists(cacheFile = makeCacheFile(storePath, "nar"))) { + if (cacheDir != "" && pathExists(cacheFile = makeCacheFile(storePath.hashPart(), "nar"))) { try { - listing = nix::readFile(makeCacheFile(storePath, "ls")); + listing = nix::readFile(makeCacheFile(storePath.hashPart(), "ls")); auto narAccessor = makeLazyNarAccessor(listing, [cacheFile](uint64_t offset, uint64_t length) { @@ -81,7 +80,7 @@ std::pair, Path> RemoteFSAccessor::fetch(const Path & path_) return buf; }); - nars.emplace(storePath, narAccessor); + nars.emplace(storePath.hashPart(), narAccessor); return {narAccessor, restPath}; } catch (SysError &) { } @@ -90,15 +89,15 @@ std::pair, Path> RemoteFSAccessor::fetch(const Path & path_) *sink.s = nix::readFile(cacheFile); auto narAccessor = makeNarAccessor(sink.s); - nars.emplace(storePath, narAccessor); + nars.emplace(storePath.hashPart(), narAccessor); return {narAccessor, restPath}; } catch (SysError &) { } } - store->narFromPath(store->parseStorePath(storePath), sink); + store->narFromPath(storePath, sink); auto narAccessor = makeNarAccessor(sink.s); - addToCache(storePath, *sink.s, narAccessor); + addToCache(storePath.hashPart(), *sink.s, narAccessor); return {narAccessor, restPath}; } diff --git a/src/libstore/remote-fs-accessor.hh b/src/libstore/remote-fs-accessor.hh index 4afb3be95..347cf5764 100644 --- a/src/libstore/remote-fs-accessor.hh +++ b/src/libstore/remote-fs-accessor.hh @@ -10,7 +10,7 @@ class RemoteFSAccessor : public FSAccessor { ref store; - std::map> nars; + std::map> nars; Path cacheDir; @@ -18,9 +18,9 @@ class RemoteFSAccessor : public FSAccessor friend class BinaryCacheStore; - Path makeCacheFile(const Path & storePath, const std::string & ext); + Path makeCacheFile(std::string_view hashPart, const std::string & ext); - void addToCache(const Path & storePath, const std::string & nar, + void addToCache(std::string_view hashPart, const std::string & nar, ref narAccessor); public: diff --git a/src/libstore/remote-store.cc b/src/libstore/remote-store.cc index 118aadf7e..23b1942ce 100644 --- a/src/libstore/remote-store.cc +++ b/src/libstore/remote-store.cc @@ -1,5 +1,6 @@ #include "serialise.hh" #include "util.hh" +#include "remote-fs-accessor.hh" #include "remote-store.hh" #include "worker-protocol.hh" #include "archive.hh" @@ -9,6 +10,7 @@ #include "pool.hh" #include "finally.hh" #include "logging.hh" +#include "callback.hh" #include #include @@ -22,53 +24,82 @@ namespace nix { +namespace worker_proto { -template<> StorePathSet readStorePaths(const Store & store, Source & from) +std::string read(const Store & store, Source & from, Phantom _) { - StorePathSet paths; - for (auto & i : readStrings(from)) - paths.insert(store.parseStorePath(i)); - return paths; + return readString(from); +} + +void write(const Store & store, Sink & out, const std::string & str) +{ + out << str; } -void writeStorePaths(const Store & store, Sink & out, const StorePathSet & paths) +StorePath read(const Store & store, Source & from, Phantom _) { - out << paths.size(); - for (auto & i : paths) - out << store.printStorePath(i); + return store.parseStorePath(readString(from)); } -std::map readOutputPathMap(const Store & store, Source & from) +void write(const Store & store, Sink & out, const StorePath & storePath) { - std::map pathMap; - auto rawInput = readStrings(from); - if (rawInput.size() % 2) - throw Error("got an odd number of elements from the daemon when trying to read a output path map"); - auto curInput = rawInput.begin(); - while (curInput != rawInput.end()) { - auto thisKey = *curInput++; - auto thisValue = *curInput++; - pathMap.emplace(thisKey, store.parseStorePath(thisValue)); - } - return pathMap; + out << store.printStorePath(storePath); } -void writeOutputPathMap(const Store & store, Sink & out, const std::map & pathMap) + +ContentAddress read(const Store & store, Source & from, Phantom _) { - out << 2*pathMap.size(); - for (auto & i : pathMap) { - out << i.first; - out << store.printStorePath(i.second); - } + return parseContentAddress(readString(from)); } +void write(const Store & store, Sink & out, const ContentAddress & ca) +{ + out << renderContentAddress(ca); +} + + +std::optional read(const Store & store, Source & from, Phantom> _) +{ + auto s = readString(from); + return s == "" ? std::optional {} : store.parseStorePath(s); +} + +void write(const Store & store, Sink & out, const std::optional & storePathOpt) +{ + out << (storePathOpt ? store.printStorePath(*storePathOpt) : ""); +} + + +std::optional read(const Store & store, Source & from, Phantom> _) +{ + return parseContentAddressOpt(readString(from)); +} + +void write(const Store & store, Sink & out, const std::optional & caOpt) +{ + out << (caOpt ? renderContentAddress(*caOpt) : ""); +} + +} + + /* TODO: Separate these store impls into different files, give them better names */ RemoteStore::RemoteStore(const Params & params) : Store(params) + , RemoteStoreConfig(params) , connections(make_ref>( std::max(1, (int) maxConnections), - [this]() { return openConnectionWrapper(); }, + [this]() { + auto conn = openConnectionWrapper(); + try { + initConnection(*conn); + } catch (...) { + failed = true; + throw; + } + return conn; + }, [this](const ref & r) { return r->to.good() @@ -95,19 +126,21 @@ ref RemoteStore::openConnectionWrapper() UDSRemoteStore::UDSRemoteStore(const Params & params) - : Store(params) + : StoreConfig(params) + , Store(params) , LocalFSStore(params) , RemoteStore(params) { } -UDSRemoteStore::UDSRemoteStore(std::string socket_path, const Params & params) - : Store(params) - , LocalFSStore(params) - , RemoteStore(params) - , path(socket_path) +UDSRemoteStore::UDSRemoteStore( + const std::string scheme, + std::string socket_path, + const Params & params) + : UDSRemoteStore(params) { + path.emplace(socket_path); } @@ -151,8 +184,6 @@ ref UDSRemoteStore::openConnection() conn->startTime = std::chrono::steady_clock::now(); - initConnection(*conn); - return conn; } @@ -260,14 +291,16 @@ struct ConnectionHandle RemoteStore::Connection * operator -> () { return &*handle; } - void processStderr(Sink * sink = 0, Source * source = 0) + void processStderr(Sink * sink = 0, Source * source = 0, bool flush = true) { - auto ex = handle->processStderr(sink, source); + auto ex = handle->processStderr(sink, source, flush); if (ex) { daemonException = true; std::rethrow_exception(ex); } } + + void withFramedSink(std::function fun); }; @@ -296,9 +329,9 @@ StorePathSet RemoteStore::queryValidPaths(const StorePathSet & paths, Substitute return res; } else { conn->to << wopQueryValidPaths; - writeStorePaths(*this, conn->to, paths); + worker_proto::write(*this, conn->to, paths); conn.processStderr(); - return readStorePaths(*this, conn->from); + return worker_proto::read(*this, conn->from, Phantom {}); } } @@ -308,7 +341,7 @@ StorePathSet RemoteStore::queryAllValidPaths() auto conn(getConnection()); conn->to << wopQueryAllValidPaths; conn.processStderr(); - return readStorePaths(*this, conn->from); + return worker_proto::read(*this, conn->from, Phantom {}); } @@ -325,41 +358,46 @@ StorePathSet RemoteStore::querySubstitutablePaths(const StorePathSet & paths) return res; } else { conn->to << wopQuerySubstitutablePaths; - writeStorePaths(*this, conn->to, paths); + worker_proto::write(*this, conn->to, paths); conn.processStderr(); - return readStorePaths(*this, conn->from); + return worker_proto::read(*this, conn->from, Phantom {}); } } -void RemoteStore::querySubstitutablePathInfos(const StorePathSet & paths, - SubstitutablePathInfos & infos) +void RemoteStore::querySubstitutablePathInfos(const StorePathCAMap & pathsMap, SubstitutablePathInfos & infos) { - if (paths.empty()) return; + if (pathsMap.empty()) return; auto conn(getConnection()); if (GET_PROTOCOL_MINOR(conn->daemonVersion) < 12) { - for (auto & i : paths) { + for (auto & i : pathsMap) { SubstitutablePathInfo info; - conn->to << wopQuerySubstitutablePathInfo << printStorePath(i); + conn->to << wopQuerySubstitutablePathInfo << printStorePath(i.first); conn.processStderr(); unsigned int reply = readInt(conn->from); if (reply == 0) continue; auto deriver = readString(conn->from); if (deriver != "") info.deriver = parseStorePath(deriver); - info.references = readStorePaths(*this, conn->from); + info.references = worker_proto::read(*this, conn->from, Phantom {}); info.downloadSize = readLongLong(conn->from); info.narSize = readLongLong(conn->from); - infos.insert_or_assign(i, std::move(info)); + infos.insert_or_assign(i.first, std::move(info)); } } else { conn->to << wopQuerySubstitutablePathInfos; - writeStorePaths(*this, conn->to, paths); + if (GET_PROTOCOL_MINOR(conn->daemonVersion) < 22) { + StorePathSet paths; + for (auto & path : pathsMap) + paths.insert(path.first); + worker_proto::write(*this, conn->to, paths); + } else + worker_proto::write(*this, conn->to, pathsMap); conn.processStderr(); size_t count = readNum(conn->from); for (size_t n = 0; n < count; n++) { @@ -367,7 +405,7 @@ void RemoteStore::querySubstitutablePathInfos(const StorePathSet & paths, auto deriver = readString(conn->from); if (deriver != "") info.deriver = parseStorePath(deriver); - info.references = readStorePaths(*this, conn->from); + info.references = worker_proto::read(*this, conn->from, Phantom {}); info.downloadSize = readLongLong(conn->from); info.narSize = readLongLong(conn->from); } @@ -376,11 +414,28 @@ void RemoteStore::querySubstitutablePathInfos(const StorePathSet & paths, } +ref RemoteStore::readValidPathInfo(ConnectionHandle & conn, const StorePath & path) +{ + auto deriver = readString(conn->from); + auto narHash = Hash::parseAny(readString(conn->from), htSHA256); + auto info = make_ref(path, narHash); + if (deriver != "") info->deriver = parseStorePath(deriver); + info->references = worker_proto::read(*this, conn->from, Phantom {}); + conn->from >> info->registrationTime >> info->narSize; + if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 16) { + conn->from >> info->ultimate; + info->sigs = readStrings(conn->from); + info->ca = parseContentAddressOpt(readString(conn->from)); + } + return info; +} + + void RemoteStore::queryPathInfoUncached(const StorePath & path, Callback> callback) noexcept { try { - std::shared_ptr info; + std::shared_ptr info; { auto conn(getConnection()); conn->to << wopQueryPathInfo << printStorePath(path); @@ -396,17 +451,7 @@ void RemoteStore::queryPathInfoUncached(const StorePath & path, bool valid; conn->from >> valid; if (!valid) throw InvalidPath("path '%s' is not valid", printStorePath(path)); } - info = std::make_shared(StorePath(path)); - auto deriver = readString(conn->from); - if (deriver != "") info->deriver = parseStorePath(deriver); - info->narHash = Hash(readString(conn->from), htSHA256); - info->references = readStorePaths(*this, conn->from); - conn->from >> info->registrationTime >> info->narSize; - if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 16) { - conn->from >> info->ultimate; - info->sigs = readStrings(conn->from); - info->ca = parseContentAddressOpt(readString(conn->from)); - } + info = readValidPathInfo(conn, path); } callback(std::move(info)); } catch (...) { callback.rethrow(); } @@ -419,7 +464,7 @@ void RemoteStore::queryReferrers(const StorePath & path, auto conn(getConnection()); conn->to << wopQueryReferrers << printStorePath(path); conn.processStderr(); - for (auto & i : readStorePaths(*this, conn->from)) + for (auto & i : worker_proto::read(*this, conn->from, Phantom {})) referrers.insert(i); } @@ -429,7 +474,7 @@ StorePathSet RemoteStore::queryValidDerivers(const StorePath & path) auto conn(getConnection()); conn->to << wopQueryValidDerivers << printStorePath(path); conn.processStderr(); - return readStorePaths(*this, conn->from); + return worker_proto::read(*this, conn->from, Phantom {}); } @@ -441,17 +486,32 @@ StorePathSet RemoteStore::queryDerivationOutputs(const StorePath & path) } conn->to << wopQueryDerivationOutputs << printStorePath(path); conn.processStderr(); - return readStorePaths(*this, conn->from); + return worker_proto::read(*this, conn->from, Phantom {}); } -OutputPathMap RemoteStore::queryDerivationOutputMap(const StorePath & path) +std::map> RemoteStore::queryPartialDerivationOutputMap(const StorePath & path) { - auto conn(getConnection()); - conn->to << wopQueryDerivationOutputMap << printStorePath(path); - conn.processStderr(); - return readOutputPathMap(*this, conn->from); - + if (GET_PROTOCOL_MINOR(getProtocol()) >= 0x16) { + auto conn(getConnection()); + conn->to << wopQueryDerivationOutputMap << printStorePath(path); + conn.processStderr(); + return worker_proto::read(*this, conn->from, Phantom>> {}); + } else { + // Fallback for old daemon versions. + // For floating-CA derivations (and their co-dependencies) this is an + // under-approximation as it only returns the paths that can be inferred + // from the derivation itself (and not the ones that are known because + // the have been built), but as old stores don't handle floating-CA + // derivations this shouldn't matter + auto derivation = readDerivation(path); + auto outputsWithOptPaths = derivation.outputsAndOptPaths(*this); + std::map> ret; + for (auto & [outputName, outputAndPath] : outputsWithOptPaths) { + ret.emplace(outputName, outputAndPath.second); + } + return ret; + } } std::optional RemoteStore::queryPathFromHashPart(const std::string & hashPart) @@ -465,8 +525,95 @@ std::optional RemoteStore::queryPathFromHashPart(const std::string & } +ref RemoteStore::addCAToStore( + Source & dump, + const string & name, + ContentAddressMethod caMethod, + const StorePathSet & references, + RepairFlag repair) +{ + std::optional conn_(getConnection()); + auto & conn = *conn_; + + if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 25) { + + conn->to + << wopAddToStore + << name + << renderContentAddressMethod(caMethod); + worker_proto::write(*this, conn->to, references); + conn->to << repair; + + conn.withFramedSink([&](Sink & sink) { + dump.drainInto(sink); + }); + + auto path = parseStorePath(readString(conn->from)); + return readValidPathInfo(conn, path); + } + else { + if (repair) throw Error("repairing is not supported when building through the Nix daemon protocol < 1.25"); + + std::visit(overloaded { + [&](TextHashMethod thm) -> void { + std::string s = dump.drain(); + conn->to << wopAddTextToStore << name << s; + worker_proto::write(*this, conn->to, references); + conn.processStderr(); + }, + [&](FixedOutputHashMethod fohm) -> void { + conn->to + << wopAddToStore + << name + << ((fohm.hashType == htSHA256 && fohm.fileIngestionMethod == FileIngestionMethod::Recursive) ? 0 : 1) /* backwards compatibility hack */ + << (fohm.fileIngestionMethod == FileIngestionMethod::Recursive ? 1 : 0) + << printHashType(fohm.hashType); + + try { + conn->to.written = 0; + conn->to.warn = true; + connections->incCapacity(); + { + Finally cleanup([&]() { connections->decCapacity(); }); + if (fohm.fileIngestionMethod == FileIngestionMethod::Recursive) { + dump.drainInto(conn->to); + } else { + std::string contents = dump.drain(); + dumpString(contents, conn->to); + } + } + conn->to.warn = false; + conn.processStderr(); + } catch (SysError & e) { + /* Daemon closed while we were sending the path. Probably OOM + or I/O error. */ + if (e.errNo == EPIPE) + try { + conn.processStderr(); + } catch (EndOfFile & e) { } + throw; + } + + } + }, caMethod); + auto path = parseStorePath(readString(conn->from)); + // Release our connection to prevent a deadlock in queryPathInfo(). + conn_.reset(); + return queryPathInfo(path); + } +} + + +StorePath RemoteStore::addToStoreFromDump(Source & dump, const string & name, + FileIngestionMethod method, HashType hashType, RepairFlag repair) +{ + StorePathSet references; + return addCAToStore(dump, name, FixedOutputHashMethod{ .fileIngestionMethod = method, .hashType = hashType }, references, repair)->path; +} + + void RemoteStore::addToStore(const ValidPathInfo & info, Source & source, - RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr accessor) + RepairFlag repair, CheckSigsFlag checkSigs) { auto conn(getConnection()); @@ -480,7 +627,7 @@ void RemoteStore::addToStore(const ValidPathInfo & info, Source & source, sink << exportMagic << printStorePath(info.path); - writeStorePaths(*this, sink, info.references); + worker_proto::write(*this, sink, info.references); sink << (info.deriver ? printStorePath(*info.deriver) : "") << 0 // == no legacy signature @@ -490,7 +637,7 @@ void RemoteStore::addToStore(const ValidPathInfo & info, Source & source, conn.processStderr(0, source2.get()); - auto importedPaths = readStorePaths(*this, conn->from); + auto importedPaths = worker_proto::read(*this, conn->from, Phantom {}); assert(importedPaths.size() <= 1); } @@ -499,68 +646,30 @@ void RemoteStore::addToStore(const ValidPathInfo & info, Source & source, << printStorePath(info.path) << (info.deriver ? printStorePath(*info.deriver) : "") << info.narHash.to_string(Base16, false); - writeStorePaths(*this, conn->to, info.references); + worker_proto::write(*this, conn->to, info.references); conn->to << info.registrationTime << info.narSize << info.ultimate << info.sigs << renderContentAddress(info.ca) << repair << !checkSigs; - bool tunnel = GET_PROTOCOL_MINOR(conn->daemonVersion) >= 21; - if (!tunnel) copyNAR(source, conn->to); - conn.processStderr(0, tunnel ? &source : nullptr); - } -} - -StorePath RemoteStore::addToStore(const string & name, const Path & _srcPath, - FileIngestionMethod method, HashType hashAlgo, PathFilter & filter, RepairFlag repair) -{ - if (repair) throw Error("repairing is not supported when building through the Nix daemon"); - - auto conn(getConnection()); - - Path srcPath(absPath(_srcPath)); - - conn->to - << wopAddToStore - << name - << ((hashAlgo == htSHA256 && method == FileIngestionMethod::Recursive) ? 0 : 1) /* backwards compatibility hack */ - << (method == FileIngestionMethod::Recursive ? 1 : 0) - << printHashType(hashAlgo); - - try { - conn->to.written = 0; - conn->to.warn = true; - connections->incCapacity(); - { - Finally cleanup([&]() { connections->decCapacity(); }); - dumpPath(srcPath, conn->to, filter); + if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 23) { + conn.withFramedSink([&](Sink & sink) { + copyNAR(source, sink); + }); + } else if (GET_PROTOCOL_MINOR(conn->daemonVersion) >= 21) { + conn.processStderr(0, &source); + } else { + copyNAR(source, conn->to); + conn.processStderr(0, nullptr); } - conn->to.warn = false; - conn.processStderr(); - } catch (SysError & e) { - /* Daemon closed while we were sending the path. Probably OOM - or I/O error. */ - if (e.errNo == EPIPE) - try { - conn.processStderr(); - } catch (EndOfFile & e) { } - throw; } - - return parseStorePath(readString(conn->from)); } StorePath RemoteStore::addTextToStore(const string & name, const string & s, const StorePathSet & references, RepairFlag repair) { - if (repair) throw Error("repairing is not supported when building through the Nix daemon"); - - auto conn(getConnection()); - conn->to << wopAddTextToStore << name << s; - writeStorePaths(*this, conn->to, references); - - conn.processStderr(); - return parseStorePath(readString(conn->from)); + StringSource source(s); + return addCAToStore(source, name, TextHashMethod{}, references, repair)->path; } @@ -659,7 +768,7 @@ void RemoteStore::collectGarbage(const GCOptions & options, GCResults & results) conn->to << wopCollectGarbage << options.action; - writeStorePaths(*this, conn->to, options.pathsToDelete); + worker_proto::write(*this, conn->to, options.pathsToDelete); conn->to << options.ignoreLiveness << options.maxFreed /* removed options */ @@ -707,7 +816,7 @@ void RemoteStore::addSignatures(const StorePath & storePath, const StringSet & s void RemoteStore::queryMissing(const std::vector & targets, StorePathSet & willBuild, StorePathSet & willSubstitute, StorePathSet & unknown, - unsigned long long & downloadSize, unsigned long long & narSize) + uint64_t & downloadSize, uint64_t & narSize) { { auto conn(getConnection()); @@ -721,9 +830,9 @@ void RemoteStore::queryMissing(const std::vector & targets ss.push_back(p.to_string(*this)); conn->to << ss; conn.processStderr(); - willBuild = readStorePaths(*this, conn->from); - willSubstitute = readStorePaths(*this, conn->from); - unknown = readStorePaths(*this, conn->from); + willBuild = worker_proto::read(*this, conn->from, Phantom {}); + willSubstitute = worker_proto::read(*this, conn->from, Phantom {}); + unknown = worker_proto::read(*this, conn->from, Phantom {}); conn->from >> downloadSize >> narSize; return; } @@ -762,6 +871,18 @@ RemoteStore::Connection::~Connection() } } +void RemoteStore::narFromPath(const StorePath & path, Sink & sink) +{ + auto conn(connections->get()); + conn->to << wopNarFromPath << printStorePath(path); + conn->processStderr(); + copyNAR(conn->from, sink); +} + +ref RemoteStore::getFSAccessor() +{ + return make_ref(ref(shared_from_this())); +} static Logger::Fields readFields(Source & from) { @@ -780,9 +901,10 @@ static Logger::Fields readFields(Source & from) } -std::exception_ptr RemoteStore::Connection::processStderr(Sink * sink, Source * source) +std::exception_ptr RemoteStore::Connection::processStderr(Sink * sink, Source * source, bool flush) { - to.flush(); + if (flush) + to.flush(); while (true) { @@ -803,9 +925,13 @@ std::exception_ptr RemoteStore::Connection::processStderr(Sink * sink, Source * } else if (msg == STDERR_ERROR) { - string error = readString(from); - unsigned int status = readInt(from); - return std::make_exception_ptr(Error(status, error)); + if (GET_PROTOCOL_MINOR(daemonVersion) >= 26) { + return std::make_exception_ptr(readError(from)); + } else { + string error = readString(from); + unsigned int status = readInt(from); + return std::make_exception_ptr(Error(status, error)); + } } else if (msg == STDERR_NEXT) @@ -843,14 +969,49 @@ std::exception_ptr RemoteStore::Connection::processStderr(Sink * sink, Source * return nullptr; } -static std::string uriScheme = "unix://"; - -static RegisterStoreImplementation regStore([]( - const std::string & uri, const Store::Params & params) - -> std::shared_ptr +void ConnectionHandle::withFramedSink(std::function fun) { - if (std::string(uri, 0, uriScheme.size()) != uriScheme) return 0; - return std::make_shared(std::string(uri, uriScheme.size()), params); -}); + (*this)->to.flush(); + + std::exception_ptr ex; + + /* Handle log messages / exceptions from the remote on a + separate thread. */ + std::thread stderrThread([&]() + { + try { + processStderr(nullptr, nullptr, false); + } catch (...) { + ex = std::current_exception(); + } + }); + + Finally joinStderrThread([&]() + { + if (stderrThread.joinable()) { + stderrThread.join(); + if (ex) { + try { + std::rethrow_exception(ex); + } catch (...) { + ignoreException(); + } + } + } + }); + + { + FramedSink sink((*this)->to, ex); + fun(sink); + sink.flush(); + } + + stderrThread.join(); + if (ex) + std::rethrow_exception(ex); + +} + +static RegisterStoreImplementation regUDSRemoteStore; } diff --git a/src/libstore/remote-store.hh b/src/libstore/remote-store.hh index fb2052752..ec04be985 100644 --- a/src/libstore/remote-store.hh +++ b/src/libstore/remote-store.hh @@ -16,19 +16,23 @@ struct FdSource; template class Pool; struct ConnectionHandle; +struct RemoteStoreConfig : virtual StoreConfig +{ + using StoreConfig::StoreConfig; + + const Setting maxConnections{(StoreConfig*) this, 1, + "max-connections", "maximum number of concurrent connections to the Nix daemon"}; + + const Setting maxConnectionAge{(StoreConfig*) this, std::numeric_limits::max(), + "max-connection-age", "number of seconds to reuse a connection"}; +}; /* FIXME: RemoteStore is a misnomer - should be something like DaemonStore. */ -class RemoteStore : public virtual Store +class RemoteStore : public virtual Store, public virtual RemoteStoreConfig { public: - const Setting maxConnections{(Store*) this, 1, - "max-connections", "maximum number of concurrent connections to the Nix daemon"}; - - const Setting maxConnectionAge{(Store*) this, std::numeric_limits::max(), - "max-connection-age", "number of seconds to reuse a connection"}; - virtual bool sameMachine() = 0; RemoteStore(const Params & params); @@ -51,21 +55,28 @@ public: StorePathSet queryDerivationOutputs(const StorePath & path) override; - OutputPathMap queryDerivationOutputMap(const StorePath & path) override; + std::map> queryPartialDerivationOutputMap(const StorePath & path) override; std::optional queryPathFromHashPart(const std::string & hashPart) override; StorePathSet querySubstitutablePaths(const StorePathSet & paths) override; - void querySubstitutablePathInfos(const StorePathSet & paths, + void querySubstitutablePathInfos(const StorePathCAMap & paths, SubstitutablePathInfos & infos) override; - void addToStore(const ValidPathInfo & info, Source & nar, - RepairFlag repair, CheckSigsFlag checkSigs, - std::shared_ptr accessor) override; + /* Add a content-addressable store path. `dump` will be drained. */ + ref addCAToStore( + Source & dump, + const string & name, + ContentAddressMethod caMethod, + const StorePathSet & references, + RepairFlag repair); - StorePath addToStore(const string & name, const Path & srcPath, - FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, - PathFilter & filter = defaultPathFilter, RepairFlag repair = NoRepair) override; + /* Add a content-addressable store path. Does not support references. `dump` will be drained. */ + StorePath addToStoreFromDump(Source & dump, const string & name, + FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, RepairFlag repair = NoRepair) override; + + void addToStore(const ValidPathInfo & info, Source & nar, + RepairFlag repair, CheckSigsFlag checkSigs) override; StorePath addTextToStore(const string & name, const string & s, const StorePathSet & references, RepairFlag repair) override; @@ -95,7 +106,7 @@ public: void queryMissing(const std::vector & targets, StorePathSet & willBuild, StorePathSet & willSubstitute, StorePathSet & unknown, - unsigned long long & downloadSize, unsigned long long & narSize) override; + uint64_t & downloadSize, uint64_t & narSize) override; void connect() override; @@ -103,8 +114,6 @@ public: void flushBadConnections(); -protected: - struct Connection { AutoCloseFD fd; @@ -115,11 +124,13 @@ protected: virtual ~Connection(); - std::exception_ptr processStderr(Sink * sink = 0, Source * source = 0); + std::exception_ptr processStderr(Sink * sink = 0, Source * source = 0, bool flush = true); }; ref openConnectionWrapper(); +protected: + virtual ref openConnection() = 0; void initConnection(Connection & conn); @@ -132,24 +143,56 @@ protected: friend struct ConnectionHandle; + virtual ref getFSAccessor() override; + + virtual void narFromPath(const StorePath & path, Sink & sink) override; + + ref readValidPathInfo(ConnectionHandle & conn, const StorePath & path); + private: std::atomic_bool failed{false}; }; -class UDSRemoteStore : public LocalFSStore, public RemoteStore +struct UDSRemoteStoreConfig : virtual LocalFSStoreConfig, virtual RemoteStoreConfig +{ + UDSRemoteStoreConfig(const Store::Params & params) + : StoreConfig(params) + , LocalFSStoreConfig(params) + , RemoteStoreConfig(params) + { + } + + UDSRemoteStoreConfig() + : UDSRemoteStoreConfig(Store::Params({})) + { + } + + const std::string name() override { return "Local Daemon Store"; } +}; + +class UDSRemoteStore : public LocalFSStore, public RemoteStore, public virtual UDSRemoteStoreConfig { public: UDSRemoteStore(const Params & params); - UDSRemoteStore(std::string path, const Params & params); + UDSRemoteStore(const std::string scheme, std::string path, const Params & params); std::string getUri() override; + static std::set uriSchemes() + { return {"unix"}; } + bool sameMachine() override { return true; } + ref getFSAccessor() override + { return LocalFSStore::getFSAccessor(); } + + void narFromPath(const StorePath & path, Sink & sink) override + { LocalFSStore::narFromPath(path, sink); } + private: ref openConnection() override; diff --git a/src/libstore/s3-binary-cache-store.cc b/src/libstore/s3-binary-cache-store.cc index 427dd48ce..552c4aac7 100644 --- a/src/libstore/s3-binary-cache-store.cc +++ b/src/libstore/s3-binary-cache-store.cc @@ -7,7 +7,6 @@ #include "globals.hh" #include "compression.hh" #include "filetransfer.hh" -#include "istringstream_nocopy.hh" #include #include @@ -173,20 +172,26 @@ S3Helper::FileTransferResult S3Helper::getObject( return res; } -struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore +struct S3BinaryCacheStoreConfig : virtual BinaryCacheStoreConfig { - const Setting profile{this, "", "profile", "The name of the AWS configuration profile to use."}; - const Setting region{this, Aws::Region::US_EAST_1, "region", {"aws-region"}}; - const Setting scheme{this, "", "scheme", "The scheme to use for S3 requests, https by default."}; - const Setting endpoint{this, "", "endpoint", "An optional override of the endpoint to use when talking to S3."}; - const Setting narinfoCompression{this, "", "narinfo-compression", "compression method for .narinfo files"}; - const Setting lsCompression{this, "", "ls-compression", "compression method for .ls files"}; - const Setting logCompression{this, "", "log-compression", "compression method for log/* files"}; + using BinaryCacheStoreConfig::BinaryCacheStoreConfig; + const Setting profile{(StoreConfig*) this, "", "profile", "The name of the AWS configuration profile to use."}; + const Setting region{(StoreConfig*) this, Aws::Region::US_EAST_1, "region", {"aws-region"}}; + const Setting scheme{(StoreConfig*) this, "", "scheme", "The scheme to use for S3 requests, https by default."}; + const Setting endpoint{(StoreConfig*) this, "", "endpoint", "An optional override of the endpoint to use when talking to S3."}; + const Setting narinfoCompression{(StoreConfig*) this, "", "narinfo-compression", "compression method for .narinfo files"}; + const Setting lsCompression{(StoreConfig*) this, "", "ls-compression", "compression method for .ls files"}; + const Setting logCompression{(StoreConfig*) this, "", "log-compression", "compression method for log/* files"}; const Setting multipartUpload{ - this, false, "multipart-upload", "whether to use multi-part uploads"}; + (StoreConfig*) this, false, "multipart-upload", "whether to use multi-part uploads"}; const Setting bufferSize{ - this, 5 * 1024 * 1024, "buffer-size", "size (in bytes) of each part in multi-part uploads"}; + (StoreConfig*) this, 5 * 1024 * 1024, "buffer-size", "size (in bytes) of each part in multi-part uploads"}; + const std::string name() override { return "S3 Binary Cache Store"; } +}; + +struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore, virtual S3BinaryCacheStoreConfig +{ std::string bucketName; Stats stats; @@ -194,8 +199,11 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore S3Helper s3Helper; S3BinaryCacheStoreImpl( - const Params & params, const std::string & bucketName) - : S3BinaryCacheStore(params) + const std::string & scheme, + const std::string & bucketName, + const Params & params) + : StoreConfig(params) + , S3BinaryCacheStore(params) , bucketName(bucketName) , s3Helper(profile, region, scheme, endpoint) { @@ -262,11 +270,14 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore std::shared_ptr transferManager; std::once_flag transferManagerCreated; - void uploadFile(const std::string & path, const std::string & data, + void uploadFile(const std::string & path, + std::shared_ptr> istream, const std::string & mimeType, const std::string & contentEncoding) { - auto stream = std::make_shared(data); + istream->seekg(0, istream->end); + auto size = istream->tellg(); + istream->seekg(0, istream->beg); auto maxThreads = std::thread::hardware_concurrency(); @@ -307,7 +318,7 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore std::shared_ptr transferHandle = transferManager->UploadFile( - stream, bucketName, path, mimeType, + istream, bucketName, path, mimeType, Aws::Map(), nullptr /*, contentEncoding */); @@ -333,9 +344,7 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore if (contentEncoding != "") request.SetContentEncoding(contentEncoding); - auto stream = std::make_shared(data); - - request.SetBody(stream); + request.SetBody(istream); auto result = checkAws(fmt("AWS error uploading '%s'", path), s3Helper.client->PutObject(request)); @@ -347,25 +356,32 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore std::chrono::duration_cast(now2 - now1) .count(); - printInfo(format("uploaded 's3://%1%/%2%' (%3% bytes) in %4% ms") % - bucketName % path % data.size() % duration); + printInfo("uploaded 's3://%s/%s' (%d bytes) in %d ms", + bucketName, path, size, duration); stats.putTimeMs += duration; - stats.putBytes += data.size(); + stats.putBytes += std::max(size, (decltype(size)) 0); stats.put++; } - void upsertFile(const std::string & path, const std::string & data, + void upsertFile(const std::string & path, + std::shared_ptr> istream, const std::string & mimeType) override { + auto compress = [&](std::string compression) + { + auto compressed = nix::compress(compression, StreamToSourceAdapter(istream).drain()); + return std::make_shared(std::move(*compressed)); + }; + if (narinfoCompression != "" && hasSuffix(path, ".narinfo")) - uploadFile(path, *compress(narinfoCompression, data), mimeType, narinfoCompression); + uploadFile(path, compress(narinfoCompression), mimeType, narinfoCompression); else if (lsCompression != "" && hasSuffix(path, ".ls")) - uploadFile(path, *compress(lsCompression, data), mimeType, lsCompression); + uploadFile(path, compress(lsCompression), mimeType, lsCompression); else if (logCompression != "" && hasPrefix(path, "log/")) - uploadFile(path, *compress(logCompression, data), mimeType, logCompression); + uploadFile(path, compress(logCompression), mimeType, logCompression); else - uploadFile(path, data, mimeType, ""); + uploadFile(path, istream, mimeType, ""); } void getFile(const std::string & path, Sink & sink) override @@ -410,7 +426,7 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore for (auto object : contents) { auto & key = object.GetKey(); if (key.size() != 40 || !hasSuffix(key, ".narinfo")) continue; - paths.insert(parseStorePath(storeDir + "/" + key.substr(0, key.size() - 8) + "-unknown")); + paths.insert(parseStorePath(storeDir + "/" + key.substr(0, key.size() - 8) + "-" + MissingName)); } marker = res.GetNextMarker(); @@ -419,17 +435,11 @@ struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore return paths; } + static std::set uriSchemes() { return {"s3"}; } + }; -static RegisterStoreImplementation regStore([]( - const std::string & uri, const Store::Params & params) - -> std::shared_ptr -{ - if (std::string(uri, 0, 5) != "s3://") return 0; - auto store = std::make_shared(params, std::string(uri, 5)); - store->init(); - return store; -}); +static RegisterStoreImplementation regS3BinaryCacheStore; } diff --git a/src/libstore/sqlite.cc b/src/libstore/sqlite.cc index 76c822c4e..31a1f0cac 100644 --- a/src/libstore/sqlite.cc +++ b/src/libstore/sqlite.cc @@ -61,6 +61,11 @@ void SQLite::exec(const std::string & stmt) }); } +uint64_t SQLite::getLastInsertedRowId() +{ + return sqlite3_last_insert_rowid(db); +} + void SQLiteStmt::create(sqlite3 * db, const string & sql) { checkInterrupt(); @@ -95,10 +100,10 @@ SQLiteStmt::Use::~Use() sqlite3_reset(stmt); } -SQLiteStmt::Use & SQLiteStmt::Use::operator () (const std::string & value, bool notNull) +SQLiteStmt::Use & SQLiteStmt::Use::operator () (std::string_view value, bool notNull) { if (notNull) { - if (sqlite3_bind_text(stmt, curArg++, value.c_str(), -1, SQLITE_TRANSIENT) != SQLITE_OK) + if (sqlite3_bind_text(stmt, curArg++, value.data(), -1, SQLITE_TRANSIENT) != SQLITE_OK) throwSQLiteError(stmt.db, "binding argument"); } else bind(); diff --git a/src/libstore/sqlite.hh b/src/libstore/sqlite.hh index dd81ab051..99f0d56ce 100644 --- a/src/libstore/sqlite.hh +++ b/src/libstore/sqlite.hh @@ -26,6 +26,8 @@ struct SQLite void isCache(); void exec(const std::string & stmt); + + uint64_t getLastInsertedRowId(); }; /* RAII wrapper to create and destroy SQLite prepared statements. */ @@ -54,7 +56,7 @@ struct SQLiteStmt ~Use(); /* Bind the next parameter. */ - Use & operator () (const std::string & value, bool notNull = true); + Use & operator () (std::string_view value, bool notNull = true); Use & operator () (const unsigned char * data, size_t len, bool notNull = true); Use & operator () (int64_t value, bool notNull = true); Use & bind(); // null diff --git a/src/libstore/ssh-store.cc b/src/libstore/ssh-store.cc index caae6b596..08d0bd565 100644 --- a/src/libstore/ssh-store.cc +++ b/src/libstore/ssh-store.cc @@ -8,19 +8,25 @@ namespace nix { -static std::string uriScheme = "ssh-ng://"; +struct SSHStoreConfig : virtual RemoteStoreConfig +{ + using RemoteStoreConfig::RemoteStoreConfig; -class SSHStore : public RemoteStore + const Setting sshKey{(StoreConfig*) this, "", "ssh-key", "path to an SSH private key"}; + const Setting compress{(StoreConfig*) this, false, "compress", "whether to compress the connection"}; + const Setting remoteProgram{(StoreConfig*) this, "nix-daemon", "remote-program", "path to the nix-daemon executable on the remote system"}; + const Setting remoteStore{(StoreConfig*) this, "", "remote-store", "URI of the store on the remote system"}; + + const std::string name() override { return "SSH Store"; } +}; + +class SSHStore : public virtual RemoteStore, public virtual SSHStoreConfig { public: - const Setting sshKey{(Store*) this, "", "ssh-key", "path to an SSH private key"}; - const Setting compress{(Store*) this, false, "compress", "whether to compress the connection"}; - const Setting remoteProgram{(Store*) this, "nix-daemon", "remote-program", "path to the nix-daemon executable on the remote system"}; - const Setting remoteStore{(Store*) this, "", "remote-store", "URI of the store on the remote system"}; - - SSHStore(const std::string & host, const Params & params) - : Store(params) + SSHStore(const std::string & scheme, const std::string & host, const Params & params) + : StoreConfig(params) + , Store(params) , RemoteStore(params) , host(host) , master( @@ -32,18 +38,16 @@ public: { } + static std::set uriSchemes() { return {"ssh-ng"}; } + std::string getUri() override { - return uriScheme + host; + return *uriSchemes().begin() + "://" + host; } bool sameMachine() override { return false; } - void narFromPath(const StorePath & path, Sink & sink) override; - - ref getFSAccessor() override; - private: struct Connection : RemoteStore::Connection @@ -68,19 +72,6 @@ private: }; }; -void SSHStore::narFromPath(const StorePath & path, Sink & sink) -{ - auto conn(connections->get()); - conn->to << wopNarFromPath << printStorePath(path); - conn->processStderr(); - copyNAR(conn->from, sink); -} - -ref SSHStore::getFSAccessor() -{ - return make_ref(ref(shared_from_this())); -} - ref SSHStore::openConnection() { auto conn = make_ref(); @@ -89,16 +80,9 @@ ref SSHStore::openConnection() + (remoteStore.get() == "" ? "" : " --store " + shellEscape(remoteStore.get()))); conn->to = FdSink(conn->sshConn->in.get()); conn->from = FdSource(conn->sshConn->out.get()); - initConnection(*conn); return conn; } -static RegisterStoreImplementation regStore([]( - const std::string & uri, const Store::Params & params) - -> std::shared_ptr -{ - if (std::string(uri, 0, uriScheme.size()) != uriScheme) return 0; - return std::make_shared(std::string(uri, uriScheme.size()), params); -}); +static RegisterStoreImplementation regSSHStore; } diff --git a/src/libstore/store-api.cc b/src/libstore/store-api.cc index c0a8bc9f6..1bbc74db8 100644 --- a/src/libstore/store-api.cc +++ b/src/libstore/store-api.cc @@ -1,15 +1,14 @@ #include "crypto.hh" +#include "fs-accessor.hh" #include "globals.hh" #include "store-api.hh" #include "util.hh" #include "nar-info-disk-cache.hh" #include "thread-pool.hh" #include "json.hh" -#include "derivations.hh" #include "url.hh" - -#include - +#include "archive.hh" +#include "callback.hh" namespace nix { @@ -20,15 +19,15 @@ bool Store::isInStore(const Path & path) const } -Path Store::toStorePath(const Path & path) const +std::pair Store::toStorePath(const Path & path) const { if (!isInStore(path)) throw Error("path '%1%' is not in the Nix store", path); Path::size_type slash = path.find('/', storeDir.size() + 1); if (slash == Path::npos) - return path; + return {parseStorePath(path), ""}; else - return Path(path, 0, slash); + return {parseStorePath(std::string_view(path).substr(0, slash)), path.substr(slash)}; } @@ -41,14 +40,14 @@ Path Store::followLinksToStore(std::string_view _path) const path = absPath(target, dirOf(path)); } if (!isInStore(path)) - throw NotInStore("path '%1%' is not in the Nix store", path); + throw BadStorePath("path '%1%' is not in the Nix store", path); return path; } StorePath Store::followLinksToStorePath(std::string_view path) const { - return parseStorePath(toStorePath(followLinksToStore(path))); + return toStorePath(followLinksToStore(path)).first; } @@ -139,21 +138,28 @@ StorePathWithOutputs Store::followLinksToStorePathWithOutputs(std::string_view p */ -StorePath Store::makeStorePath(const string & type, - const Hash & hash, std::string_view name) const +StorePath Store::makeStorePath(std::string_view type, + std::string_view hash, std::string_view name) const { /* e.g., "source:sha256:1abc...:/nix/store:foo.tar.gz" */ - string s = type + ":" + hash.to_string(Base16, true) + ":" + storeDir + ":" + std::string(name); + string s = std::string { type } + ":" + std::string { hash } + + ":" + storeDir + ":" + std::string { name }; auto h = compressHash(hashString(htSHA256, s), 20); return StorePath(h, name); } -StorePath Store::makeOutputPath(const string & id, +StorePath Store::makeStorePath(std::string_view type, const Hash & hash, std::string_view name) const { - return makeStorePath("output:" + id, hash, - std::string(name) + (id == "out" ? "" : "-" + id)); + return makeStorePath(type, hash.to_string(Base16, true), name); +} + + +StorePath Store::makeOutputPath(std::string_view id, + const Hash & hash, std::string_view name) const +{ + return makeStorePath("output:" + std::string { id }, hash, outputPathName(name, id)); } @@ -192,6 +198,19 @@ StorePath Store::makeFixedOutputPath( } } +StorePath Store::makeFixedOutputPathFromCA(std::string_view name, ContentAddress ca, + const StorePathSet & references, bool hasSelfReference) const +{ + // New template + return std::visit(overloaded { + [&](TextHash th) { + return makeTextPath(name, th.hash, references); + }, + [&](FixedOutputHash fsh) { + return makeFixedOutputPath(fsh.method, fsh.hash, name, references, hasSelfReference); + } + }, ca); +} StorePath Store::makeTextPath(std::string_view name, const Hash & hash, const StorePathSet & references) const @@ -221,8 +240,111 @@ StorePath Store::computeStorePathForText(const string & name, const string & s, } +StorePath Store::addToStore(const string & name, const Path & _srcPath, + FileIngestionMethod method, HashType hashAlgo, PathFilter & filter, RepairFlag repair) +{ + Path srcPath(absPath(_srcPath)); + auto source = sinkToSource([&](Sink & sink) { + if (method == FileIngestionMethod::Recursive) + dumpPath(srcPath, sink, filter); + else + readFile(srcPath, sink); + }); + return addToStoreFromDump(*source, name, method, hashAlgo, repair); +} + + +/* +The aim of this function is to compute in one pass the correct ValidPathInfo for +the files that we are trying to add to the store. To accomplish that in one +pass, given the different kind of inputs that we can take (normal nar archives, +nar archives with non SHA-256 hashes, and flat files), we set up a net of sinks +and aliases. Also, since the dataflow is obfuscated by this, we include here a +graphviz diagram: + +digraph graphname { + node [shape=box] + fileSource -> narSink + narSink [style=dashed] + narSink -> unsualHashTee [style = dashed, label = "Recursive && !SHA-256"] + narSink -> narHashSink [style = dashed, label = "else"] + unsualHashTee -> narHashSink + unsualHashTee -> caHashSink + fileSource -> parseSink + parseSink [style=dashed] + parseSink-> fileSink [style = dashed, label = "Flat"] + parseSink -> blank [style = dashed, label = "Recursive"] + fileSink -> caHashSink +} +*/ +ValidPathInfo Store::addToStoreSlow(std::string_view name, const Path & srcPath, + FileIngestionMethod method, HashType hashAlgo, + std::optional expectedCAHash) +{ + HashSink narHashSink { htSHA256 }; + HashSink caHashSink { hashAlgo }; + + /* Note that fileSink and unusualHashTee must be mutually exclusive, since + they both write to caHashSink. Note that that requisite is currently true + because the former is only used in the flat case. */ + RetrieveRegularNARSink fileSink { caHashSink }; + TeeSink unusualHashTee { narHashSink, caHashSink }; + + auto & narSink = method == FileIngestionMethod::Recursive && hashAlgo != htSHA256 + ? static_cast(unusualHashTee) + : narHashSink; + + /* Functionally, this means that fileSource will yield the content of + srcPath. The fact that we use scratchpadSink as a temporary buffer here + is an implementation detail. */ + auto fileSource = sinkToSource([&](Sink & scratchpadSink) { + dumpPath(srcPath, scratchpadSink); + }); + + /* tapped provides the same data as fileSource, but we also write all the + information to narSink. */ + TeeSource tapped { *fileSource, narSink }; + + ParseSink blank; + auto & parseSink = method == FileIngestionMethod::Flat + ? fileSink + : blank; + + /* The information that flows from tapped (besides being replicated in + narSink), is now put in parseSink. */ + parseDump(parseSink, tapped); + + /* We extract the result of the computation from the sink by calling + finish. */ + auto [narHash, narSize] = narHashSink.finish(); + + auto hash = method == FileIngestionMethod::Recursive && hashAlgo == htSHA256 + ? narHash + : caHashSink.finish().first; + + if (expectedCAHash && expectedCAHash != hash) + throw Error("hash mismatch for '%s'", srcPath); + + ValidPathInfo info { + makeFixedOutputPath(method, hash, name), + narHash, + }; + info.narSize = narSize; + info.ca = FixedOutputHash { .method = method, .hash = hash }; + + if (!isValidPath(info.path)) { + auto source = sinkToSource([&](Sink & scratchpadSink) { + dumpPath(srcPath, scratchpadSink); + }); + addToStore(info, *source); + } + + return info; +} + + Store::Store(const Params & params) - : Config(params) + : StoreConfig(params) , state({(size_t) pathInfoCacheSize}) { } @@ -242,6 +364,17 @@ bool Store::PathInfoCacheValue::isKnownNow() return std::chrono::steady_clock::now() < time_point + ttl; } +OutputPathMap Store::queryDerivationOutputMap(const StorePath & path) { + auto resp = queryPartialDerivationOutputMap(path); + OutputPathMap result; + for (auto & [outName, optOutPath] : resp) { + if (!optOutPath) + throw Error("output '%s' has no store path mapped to it", outName); + result.insert_or_assign(outName, *optOutPath); + } + return result; +} + StorePathSet Store::queryDerivationOutputs(const StorePath & path) { auto outputMap = this->queryDerivationOutputMap(path); @@ -316,6 +449,14 @@ ref Store::queryPathInfo(const StorePath & storePath) } +static bool goodStorePath(const StorePath & expected, const StorePath & actual) +{ + return + expected.hashPart() == actual.hashPart() + && (expected.name() == Store::MissingName || expected.name() == actual.name()); +} + + void Store::queryPathInfo(const StorePath & storePath, Callback> callback) noexcept { @@ -343,7 +484,7 @@ void Store::queryPathInfo(const StorePath & storePath, state_->pathInfoCache.upsert(hashPart, res.first == NarInfoDiskCache::oInvalid ? PathInfoCacheValue{} : PathInfoCacheValue{ .value = res.second }); if (res.first == NarInfoDiskCache::oInvalid || - res.second->path != storePath) + !goodStorePath(storePath, res.second->path)) throw InvalidPath("path '%s' is not valid", printStorePath(storePath)); } return callback(ref(res.second)); @@ -355,7 +496,7 @@ void Store::queryPathInfo(const StorePath & storePath, auto callbackPtr = std::make_shared(std::move(callback)); queryPathInfoUncached(storePath, - {[this, storePath{printStorePath(storePath)}, hashPart, callbackPtr](std::future> fut) { + {[this, storePathS{printStorePath(storePath)}, hashPart, callbackPtr](std::future> fut) { try { auto info = fut.get(); @@ -368,9 +509,11 @@ void Store::queryPathInfo(const StorePath & storePath, state_->pathInfoCache.upsert(hashPart, PathInfoCacheValue { .value = info }); } - if (!info || info->path != parseStorePath(storePath)) { + auto storePath = parseStorePath(storePathS); + + if (!info || !goodStorePath(storePath, info->path)) { stats.narInfoMissing++; - throw InvalidPath("path '%s' is not valid", storePath); + throw InvalidPath("path '%s' is not valid", storePathS); } (*callbackPtr)(ref(info)); @@ -515,7 +658,7 @@ void Store::pathInfoToJSON(JSONPlaceholder & jsonOut, const StorePathSet & store if (!narInfo->url.empty()) jsonPath.attr("url", narInfo->url); if (narInfo->fileHash) - jsonPath.attr("downloadHash", narInfo->fileHash.to_string(Base32, true)); + jsonPath.attr("downloadHash", narInfo->fileHash->to_string(hashBase, true)); if (narInfo->fileSize) jsonPath.attr("downloadSize", narInfo->fileSize); if (showClosureSize) @@ -591,18 +734,13 @@ void copyStorePath(ref srcStore, ref dstStore, uint64_t total = 0; - if (!info->narHash) { - StringSink sink; - srcStore->narFromPath({storePath}, sink); + // recompute store path on the chance dstStore does it differently + if (info->ca && info->references.empty()) { auto info2 = make_ref(*info); - info2->narHash = hashString(htSHA256, *sink.s); - if (!info->narSize) info2->narSize = sink.s->size(); - if (info->ultimate) info2->ultimate = false; + info2->path = dstStore->makeFixedOutputPathFromCA(info->path.name(), *info->ca); + if (dstStore->storeDir == srcStore->storeDir) + assert(info->path == info2->path); info = info2; - - StringSource source(*sink.s); - dstStore->addToStore(*info, source, repair, checkSigs); - return; } if (info->ultimate) { @@ -612,12 +750,12 @@ void copyStorePath(ref srcStore, ref dstStore, } auto source = sinkToSource([&](Sink & sink) { - LambdaSink wrapperSink([&](const unsigned char * data, size_t len) { - sink(data, len); + LambdaSink progressSink([&](const unsigned char * data, size_t len) { total += len; act.progress(total, info->narSize); }); - srcStore->narFromPath(storePath, wrapperSink); + TeeSink tee { sink, progressSink }; + srcStore->narFromPath(storePath, tee); }, [&]() { throw EndOfFile("NAR for '%s' fetched from '%s' is incomplete", srcStore->printStorePath(storePath), srcStore->getUri()); }); @@ -626,16 +764,20 @@ void copyStorePath(ref srcStore, ref dstStore, } -void copyPaths(ref srcStore, ref dstStore, const StorePathSet & storePaths, +std::map copyPaths(ref srcStore, ref dstStore, const StorePathSet & storePaths, RepairFlag repair, CheckSigsFlag checkSigs, SubstituteFlag substitute) { auto valid = dstStore->queryValidPaths(storePaths, substitute); - PathSet missing; + StorePathSet missing; for (auto & path : storePaths) - if (!valid.count(path)) missing.insert(srcStore->printStorePath(path)); + if (!valid.count(path)) missing.insert(path); - if (missing.empty()) return; + std::map pathsMap; + for (auto & path : storePaths) + pathsMap.insert_or_assign(path, path); + + if (missing.empty()) return pathsMap; Activity act(*logger, lvlInfo, actCopyPaths, fmt("copying %d paths", missing.size())); @@ -650,30 +792,49 @@ void copyPaths(ref srcStore, ref dstStore, const StorePathSet & st ThreadPool pool; - processGraph(pool, - PathSet(missing.begin(), missing.end()), + processGraph(pool, + StorePathSet(missing.begin(), missing.end()), - [&](const Path & storePath) { - if (dstStore->isValidPath(dstStore->parseStorePath(storePath))) { + [&](const StorePath & storePath) { + auto info = srcStore->queryPathInfo(storePath); + auto storePathForDst = storePath; + if (info->ca && info->references.empty()) { + storePathForDst = dstStore->makeFixedOutputPathFromCA(storePath.name(), *info->ca); + if (dstStore->storeDir == srcStore->storeDir) + assert(storePathForDst == storePath); + if (storePathForDst != storePath) + debug("replaced path '%s' to '%s' for substituter '%s'", srcStore->printStorePath(storePath), dstStore->printStorePath(storePathForDst), dstStore->getUri()); + } + pathsMap.insert_or_assign(storePath, storePathForDst); + + if (dstStore->isValidPath(storePath)) { nrDone++; showProgress(); - return PathSet(); + return StorePathSet(); } - auto info = srcStore->queryPathInfo(srcStore->parseStorePath(storePath)); - bytesExpected += info->narSize; act.setExpected(actCopyPath, bytesExpected); - return srcStore->printStorePathSet(info->references); + return info->references; }, - [&](const Path & storePathS) { + [&](const StorePath & storePath) { checkInterrupt(); - auto storePath = dstStore->parseStorePath(storePathS); + auto info = srcStore->queryPathInfo(storePath); - if (!dstStore->isValidPath(storePath)) { + auto storePathForDst = storePath; + if (info->ca && info->references.empty()) { + storePathForDst = dstStore->makeFixedOutputPathFromCA(storePath.name(), *info->ca); + if (dstStore->storeDir == srcStore->storeDir) + assert(storePathForDst == storePath); + if (storePathForDst != storePath) + debug("replaced path '%s' to '%s' for substituter '%s'", srcStore->printStorePath(storePath), dstStore->printStorePath(storePathForDst), dstStore->getUri()); + } + pathsMap.insert_or_assign(storePath, storePathForDst); + + if (!dstStore->isValidPath(storePathForDst)) { MaintainCount mc(nrRunning); showProgress(); try { @@ -682,7 +843,7 @@ void copyPaths(ref srcStore, ref dstStore, const StorePathSet & st nrFailed++; if (!settings.keepGoing) throw e; - logger->log(lvlError, fmt("could not copy %s: %s", storePathS, e.what())); + logger->log(lvlError, fmt("could not copy %s: %s", dstStore->printStorePath(storePath), e.what())); showProgress(); return; } @@ -691,6 +852,8 @@ void copyPaths(ref srcStore, ref dstStore, const StorePathSet & st nrDone++; showProgress(); }); + + return pathsMap; } @@ -704,19 +867,22 @@ void copyClosure(ref srcStore, ref dstStore, } -std::optional decodeValidPathInfo(const Store & store, std::istream & str, bool hashGiven) +std::optional decodeValidPathInfo(const Store & store, std::istream & str, std::optional hashGiven) { std::string path; getline(str, path); if (str.eof()) { return {}; } - ValidPathInfo info(store.parseStorePath(path)); - if (hashGiven) { + if (!hashGiven) { string s; getline(str, s); - info.narHash = Hash(s, htSHA256); + auto narHash = Hash::parseAny(s, htSHA256); getline(str, s); - if (!string2Int(s, info.narSize)) throw Error("number expected"); + uint64_t narSize; + if (!string2Int(s, narSize)) throw Error("number expected"); + hashGiven = { narHash, narSize }; } + ValidPathInfo info(store.parseStorePath(path), hashGiven->first); + info.narSize = hashGiven->second; std::string deriver; getline(str, deriver); if (deriver != "") info.deriver = store.parseStorePath(deriver); @@ -751,8 +917,8 @@ string showPaths(const PathSet & paths) std::string ValidPathInfo::fingerprint(const Store & store) const { - if (narSize == 0 || !narHash) - throw Error("cannot calculate fingerprint of path '%s' because its size/hash is not known", + if (narSize == 0) + throw Error("cannot calculate fingerprint of path '%s' because its size is not known", store.printStorePath(path)); return "1;" + store.printStorePath(path) + ";" @@ -767,10 +933,6 @@ void ValidPathInfo::sign(const Store & store, const SecretKey & secretKey) sigs.insert(secretKey.signDetached(fingerprint(store))); } -// FIXME Put this somewhere? -template struct overloaded : Ts... { using Ts::operator()...; }; -template overloaded(Ts...) -> overloaded; - bool ValidPathInfo::isContentAddressed(const Store & store) const { if (! ca) return false; @@ -826,6 +988,25 @@ Strings ValidPathInfo::shortRefs() const } +Derivation Store::derivationFromPath(const StorePath & drvPath) +{ + ensurePath(drvPath); + return readDerivation(drvPath); +} + + +Derivation Store::readDerivation(const StorePath & drvPath) +{ + auto accessor = getFSAccessor(); + try { + return parseDerivation(*this, + accessor->readFile(printStorePath(drvPath)), + Derivation::nameFromPath(drvPath)); + } catch (FormatError & e) { + throw Error("error parsing derivation '%s': %s", printStorePath(drvPath), e.msg()); + } +} + } @@ -835,9 +1016,6 @@ Strings ValidPathInfo::shortRefs() const namespace nix { - -RegisterStoreImplementation::Implementations * RegisterStoreImplementation::implementations = 0; - /* Split URI into protocol+hierarchy part and its parameter set. */ std::pair splitUriAndParams(const std::string & uri_) { @@ -851,63 +1029,72 @@ std::pair splitUriAndParams(const std::string & uri_ return {uri, params}; } +static bool isNonUriPath(const std::string & spec) { + return + // is not a URL + spec.find("://") == std::string::npos + // Has at least one path separator, and so isn't a single word that + // might be special like "auto" + && spec.find("/") != std::string::npos; +} + +std::shared_ptr openFromNonUri(const std::string & uri, const Store::Params & params) +{ + if (uri == "" || uri == "auto") { + auto stateDir = get(params, "state").value_or(settings.nixStateDir); + if (access(stateDir.c_str(), R_OK | W_OK) == 0) + return std::make_shared(params); + else if (pathExists(settings.nixDaemonSocketFile)) + return std::make_shared(params); + else + return std::make_shared(params); + } else if (uri == "daemon") { + return std::make_shared(params); + } else if (uri == "local") { + return std::make_shared(params); + } else if (isNonUriPath(uri)) { + Store::Params params2 = params; + params2["root"] = absPath(uri); + return std::make_shared(params2); + } else { + return nullptr; + } +} + ref openStore(const std::string & uri_, const Store::Params & extraParams) { - auto [uri, uriParams] = splitUriAndParams(uri_); auto params = extraParams; - params.insert(uriParams.begin(), uriParams.end()); + try { + auto parsedUri = parseURL(uri_); + params.insert(parsedUri.query.begin(), parsedUri.query.end()); - for (auto fun : *RegisterStoreImplementation::implementations) { - auto store = fun(uri, params); - if (store) { + auto baseURI = parsedUri.authority.value_or("") + parsedUri.path; + + for (auto implem : *Implementations::registered) { + if (implem.uriSchemes.count(parsedUri.scheme)) { + auto store = implem.create(parsedUri.scheme, baseURI, params); + if (store) { + store->init(); + store->warnUnknownSettings(); + return ref(store); + } + } + } + } + catch (BadURL &) { + auto [uri, uriParams] = splitUriAndParams(uri_); + params.insert(uriParams.begin(), uriParams.end()); + + if (auto store = openFromNonUri(uri, params)) { store->warnUnknownSettings(); return ref(store); } } - throw Error("don't know how to open Nix store '%s'", uri); + throw Error("don't know how to open Nix store '%s'", uri_); } - -StoreType getStoreType(const std::string & uri, const std::string & stateDir) -{ - if (uri == "daemon") { - return tDaemon; - } else if (uri == "local" || hasPrefix(uri, "/")) { - return tLocal; - } else if (uri == "" || uri == "auto") { - if (access(stateDir.c_str(), R_OK | W_OK) == 0) - return tLocal; - else if (pathExists(settings.nixDaemonSocketFile)) - return tDaemon; - else - return tLocal; - } else { - return tOther; - } -} - - -static RegisterStoreImplementation regStore([]( - const std::string & uri, const Store::Params & params) - -> std::shared_ptr -{ - switch (getStoreType(uri, get(params, "state").value_or(settings.nixStateDir))) { - case tDaemon: - return std::shared_ptr(std::make_shared(params)); - case tLocal: { - Store::Params params2 = params; - if (hasPrefix(uri, "/")) - params2["root"] = uri; - return std::shared_ptr(std::make_shared(params2)); - } - default: - return nullptr; - } -}); - - std::list> getDefaultSubstituters() { static auto stores([]() { @@ -940,5 +1127,6 @@ std::list> getDefaultSubstituters() return stores; } +std::vector * Implementations::registered = 0; } diff --git a/src/libstore/store-api.hh b/src/libstore/store-api.hh index b122e05d6..450c0f554 100644 --- a/src/libstore/store-api.hh +++ b/src/libstore/store-api.hh @@ -4,12 +4,12 @@ #include "hash.hh" #include "content-address.hh" #include "serialise.hh" -#include "crypto.hh" #include "lru-cache.hh" #include "sync.hh" #include "globals.hh" #include "config.hh" #include "derivations.hh" +#include "path-info.hh" #include #include @@ -24,6 +24,31 @@ namespace nix { +/** + * About the class hierarchy of the store implementations: + * + * Each store type `Foo` consists of two classes: + * + * 1. A class `FooConfig : virtual StoreConfig` that contains the configuration + * for the store + * + * It should only contain members of type `const Setting` (or subclasses + * of it) and inherit the constructors of `StoreConfig` + * (`using StoreConfig::StoreConfig`). + * + * 2. A class `Foo : virtual Store, virtual FooConfig` that contains the + * implementation of the store. + * + * This class is expected to have a constructor `Foo(const Params & params)` + * that calls `StoreConfig(params)` (otherwise you're gonna encounter an + * `assertion failure` when trying to instantiate it). + * + * You can then register the new store using: + * + * ``` + * cpp static RegisterStoreImplementation regStore; + * ``` + */ MakeError(SubstError, Error); MakeError(BuildError, Error); // denotes a permanent build failure @@ -31,8 +56,9 @@ MakeError(InvalidPath, Error); MakeError(Unsupported, Error); MakeError(SubstituteGone, Error); MakeError(SubstituterDisabled, Error); -MakeError(NotInStore, Error); +MakeError(BadStorePath, Error); +MakeError(InvalidStoreURI, Error); class FSAccessor; class NarInfoDiskCache; @@ -85,7 +111,7 @@ struct GCOptions StorePathSet pathsToDelete; /* Stop after at least `maxFreed' bytes have been freed. */ - unsigned long long maxFreed{std::numeric_limits::max()}; + uint64_t maxFreed{std::numeric_limits::max()}; }; @@ -97,98 +123,10 @@ struct GCResults /* For `gcReturnDead', `gcDeleteDead' and `gcDeleteSpecific', the number of bytes that would be or was freed. */ - unsigned long long bytesFreed = 0; + uint64_t bytesFreed = 0; }; -struct SubstitutablePathInfo -{ - std::optional deriver; - StorePathSet references; - unsigned long long downloadSize; /* 0 = unknown or inapplicable */ - unsigned long long narSize; /* 0 = unknown */ -}; - -typedef std::map SubstitutablePathInfos; - -struct ValidPathInfo -{ - StorePath path; - std::optional deriver; - Hash narHash; - StorePathSet references; - time_t registrationTime = 0; - uint64_t narSize = 0; // 0 = unknown - uint64_t id; // internal use only - - /* Whether the path is ultimately trusted, that is, it's a - derivation output that was built locally. */ - bool ultimate = false; - - StringSet sigs; // note: not necessarily verified - - /* If non-empty, an assertion that the path is content-addressed, - i.e., that the store path is computed from a cryptographic hash - of the contents of the path, plus some other bits of data like - the "name" part of the path. Such a path doesn't need - signatures, since we don't have to trust anybody's claim that - the path is the output of a particular derivation. (In the - extensional store model, we have to trust that the *contents* - of an output path of a derivation were actually produced by - that derivation. In the intensional model, we have to trust - that a particular output path was produced by a derivation; the - path then implies the contents.) - - Ideally, the content-addressability assertion would just be a Boolean, - and the store path would be computed from the name component, ‘narHash’ - and ‘references’. However, we support many types of content addresses. - */ - std::optional ca; - - bool operator == (const ValidPathInfo & i) const - { - return - path == i.path - && narHash == i.narHash - && references == i.references; - } - - /* Return a fingerprint of the store path to be used in binary - cache signatures. It contains the store path, the base-32 - SHA-256 hash of the NAR serialisation of the path, the size of - the NAR, and the sorted references. The size field is strictly - speaking superfluous, but might prevent endless/excessive data - attacks. */ - std::string fingerprint(const Store & store) const; - - void sign(const Store & store, const SecretKey & secretKey); - - /* Return true iff the path is verifiably content-addressed. */ - bool isContentAddressed(const Store & store) const; - - static const size_t maxSigs = std::numeric_limits::max(); - - /* Return the number of signatures on this .narinfo that were - produced by one of the specified keys, or maxSigs if the path - is content-addressed. */ - size_t checkSignatures(const Store & store, const PublicKeys & publicKeys) const; - - /* Verify a single signature. */ - bool checkSignature(const Store & store, const PublicKeys & publicKeys, const std::string & sig) const; - - Strings shortRefs() const; - - ValidPathInfo(const ValidPathInfo & other) = default; - - ValidPathInfo(StorePath && path) : path(std::move(path)) { }; - ValidPathInfo(const StorePath & path) : path(path) { }; - - virtual ~ValidPathInfo() { } -}; - -typedef list ValidPathInfos; - - enum BuildMode { bmNormal, bmRepair, bmCheck }; @@ -232,12 +170,33 @@ struct BuildResult } }; - -class Store : public std::enable_shared_from_this, public Config +struct StoreConfig : public Config { -public: + using Config::Config; - typedef std::map Params; + /** + * When constructing a store implementation, we pass in a map `params` of + * parameters that's supposed to initialize the associated config. + * To do that, we must use the `StoreConfig(StringMap & params)` + * constructor, so we'd like to `delete` its default constructor to enforce + * it. + * + * However, actually deleting it means that all the subclasses of + * `StoreConfig` will have their default constructor deleted (because it's + * supposed to call the deleted default constructor of `StoreConfig`). But + * because we're always using virtual inheritance, the constructors of + * child classes will never implicitely call this one, so deleting it will + * be more painful than anything else. + * + * So we `assert(false)` here to ensure at runtime that the right + * constructor is always called without having to redefine a custom + * constructor for each `*Config` class. + */ + StoreConfig() { assert(false); } + + virtual ~StoreConfig() { } + + virtual const std::string name() = 0; const PathSetting storeDir_{this, false, settings.nixStore, "store", "path to the Nix store"}; @@ -251,6 +210,18 @@ public: Setting wantMassQuery{this, false, "want-mass-query", "whether this substituter can be queried efficiently for path validity"}; + Setting systemFeatures{this, settings.systemFeatures, + "system-features", + "Optional features that the system this store builds on implements (like \"kvm\")."}; + +}; + +class Store : public std::enable_shared_from_this, public virtual StoreConfig +{ +public: + + typedef std::map Params; + protected: struct PathInfoCacheValue { @@ -284,6 +255,11 @@ protected: Store(const Params & params); public: + /** + * Perform any necessary effectful operation to make the store up and + * running + */ + virtual void init() {}; virtual ~Store() { } @@ -317,9 +293,9 @@ public: the Nix store. */ bool isStorePath(std::string_view path) const; - /* Chop off the parts after the top-level store name, e.g., - /nix/store/abcd-foo/bar => /nix/store/abcd-foo. */ - Path toStorePath(const Path & path) const; + /* Split a path like /nix/store/-/ into + /nix/store/- and /. */ + std::pair toStorePath(const Path & path) const; /* Follow symlinks until we end up with a path in the Nix store. */ Path followLinksToStore(std::string_view path) const; @@ -331,10 +307,12 @@ public: StorePathWithOutputs followLinksToStorePathWithOutputs(std::string_view path) const; /* Constructs a unique store path name. */ - StorePath makeStorePath(const string & type, + StorePath makeStorePath(std::string_view type, + std::string_view hash, std::string_view name) const; + StorePath makeStorePath(std::string_view type, const Hash & hash, std::string_view name) const; - StorePath makeOutputPath(const string & id, + StorePath makeOutputPath(std::string_view id, const Hash & hash, std::string_view name) const; StorePath makeFixedOutputPath(FileIngestionMethod method, @@ -343,7 +321,11 @@ public: bool hasSelfReference = false) const; StorePath makeTextPath(std::string_view name, const Hash & hash, - const StorePathSet & references) const; + const StorePathSet & references = {}) const; + + StorePath makeFixedOutputPathFromCA(std::string_view name, ContentAddress ca, + const StorePathSet & references = {}, + bool hasSelfReference = false) const; /* This is the preparatory part of addToStore(); it computes the store path to which srcPath is to be copied. Returns the store @@ -384,13 +366,16 @@ public: SubstituteFlag maybeSubstitute = NoSubstitute); /* Query the set of all valid paths. Note that for some store - backends, the name part of store paths may be omitted - (i.e. you'll get /nix/store/ rather than + backends, the name part of store paths may be replaced by 'x' + (i.e. you'll get /nix/store/-x rather than /nix/store/-). Use queryPathInfo() to obtain the - full store path. */ + full store path. FIXME: should return a set of + std::variant to get rid of this hack. */ virtual StorePathSet queryAllValidPaths() { unsupported("queryAllValidPaths"); } + constexpr static const char * MissingName = "x"; + /* Query information about a valid path. It is permitted to omit the name part of the store path. */ ref queryPathInfo(const StorePath & path); @@ -420,9 +405,15 @@ public: /* Query the outputs of the derivation denoted by `path'. */ virtual StorePathSet queryDerivationOutputs(const StorePath & path); - /* Query the mapping outputName=>outputPath for the given derivation */ - virtual OutputPathMap queryDerivationOutputMap(const StorePath & path) - { unsupported("queryDerivationOutputMap"); } + /* Query the mapping outputName => outputPath for the given derivation. All + outputs are mentioned so ones mising the mapping are mapped to + `std::nullopt`. */ + virtual std::map> queryPartialDerivationOutputMap(const StorePath & path) + { unsupported("queryPartialDerivationOutputMap"); } + + /* Query the mapping outputName=>outputPath for the given derivation. + Assume every output has a mapping and throw an exception otherwise. */ + OutputPathMap queryDerivationOutputMap(const StorePath & path); /* Query the full store path given the hash part of a valid store path, or empty if the path doesn't exist. */ @@ -432,15 +423,15 @@ public: virtual StorePathSet querySubstitutablePaths(const StorePathSet & paths) { return {}; }; /* Query substitute info (i.e. references, derivers and download - sizes) of a set of paths. If a path does not have substitute - info, it's omitted from the resulting ‘infos’ map. */ - virtual void querySubstitutablePathInfos(const StorePathSet & paths, + sizes) of a map of paths to their optional ca values. If a path + does not have substitute info, it's omitted from the resulting + ‘infos’ map. */ + virtual void querySubstitutablePathInfos(const StorePathCAMap & paths, SubstitutablePathInfos & infos) { return; }; /* Import a path into the store. */ virtual void addToStore(const ValidPathInfo & info, Source & narSource, - RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs, - std::shared_ptr accessor = 0) = 0; + RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs) = 0; /* Copy the contents of a path to the store and register the validity the resulting path. The resulting path is returned. @@ -448,14 +439,24 @@ public: libutil/archive.hh). */ virtual StorePath addToStore(const string & name, const Path & srcPath, FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, - PathFilter & filter = defaultPathFilter, RepairFlag repair = NoRepair) = 0; + PathFilter & filter = defaultPathFilter, RepairFlag repair = NoRepair); + /* Copy the contents of a path to the store and register the + validity the resulting path, using a constant amount of + memory. */ + ValidPathInfo addToStoreSlow(std::string_view name, const Path & srcPath, + FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, + std::optional expectedCAHash = {}); + + /* Like addToStore(), but the contents of the path are contained + in `dump', which is either a NAR serialisation (if recursive == + true) or simply the contents of a regular file (if recursive == + false). + `dump` may be drained */ // FIXME: remove? - virtual StorePath addToStoreFromDump(const string & dump, const string & name, + virtual StorePath addToStoreFromDump(Source & dump, const string & name, FileIngestionMethod method = FileIngestionMethod::Recursive, HashType hashAlgo = htSHA256, RepairFlag repair = NoRepair) - { - throw Error("addToStoreFromDump() is not supported by this store"); - } + { unsupported("addToStoreFromDump"); } /* Like addToStore, but the contents written to the output path is a regular file containing the given string. */ @@ -478,8 +479,38 @@ public: BuildMode buildMode = bmNormal); /* Build a single non-materialized derivation (i.e. not from an - on-disk .drv file). Note that ‘drvPath’ is only used for - informational purposes. */ + on-disk .drv file). + + ‘drvPath’ is used to deduplicate worker goals so it is imperative that + is correct. That said, it doesn't literally need to be store path that + would be calculated from writing this derivation to the store: it is OK + if it instead is that of a Derivation which would resolve to this (by + taking the outputs of it's input derivations and adding them as input + sources) such that the build time referenceable-paths are the same. + + In the input-addressed case, we usually *do* use an "original" + unresolved derivations's path, as that is what will be used in the + `buildPaths` case. Also, the input-addressed output paths are verified + only by that contents of that specific unresolved derivation, so it is + nice to keep that information around so if the original derivation is + ever obtained later, it can be verified whether the trusted user in fact + used the proper output path. + + In the content-addressed case, we want to always use the + resolved drv path calculated from the provided derivation. This serves + two purposes: + + - It keeps the operation trustless, by ruling out a maliciously + invalid drv path corresponding to a non-resolution-equivalent + derivation. + + - For the floating case in particular, it ensures that the derivation + to output mapping respects the resolution equivalence relation, so + one cannot choose different resolution-equivalent derivations to + subvert dependency coherence (i.e. the property that one doesn't end + up with multiple different versions of dependencies without + explicitly choosing to allow it). + */ virtual BuildResult buildDerivation(const StorePath & drvPath, const BasicDerivation & drv, BuildMode buildMode = bmNormal) = 0; @@ -516,7 +547,7 @@ public: - The collector isn't running, or it's just started but hasn't acquired the GC lock yet. In that case we get and release the lock right away, then exit. The collector scans the - permanent root and sees our's. + permanent root and sees ours. In either case the permanent root is seen by the collector. */ virtual void syncWithGC() { }; @@ -600,7 +631,7 @@ public: that will be substituted. */ virtual void queryMissing(const std::vector & targets, StorePathSet & willBuild, StorePathSet & willSubstitute, StorePathSet & unknown, - unsigned long long & downloadSize, unsigned long long & narSize); + uint64_t & downloadSize, uint64_t & narSize); /* Sort a set of paths topologically under the references relation. If p refers to q, then p precedes q in this list. */ @@ -616,8 +647,7 @@ public: the Nix store. Optionally, the contents of the NARs are preloaded into the specified FS accessor to speed up subsequent access. */ - StorePaths importPaths(Source & source, std::shared_ptr accessor, - CheckSigsFlag checkSigs = CheckSigs); + StorePaths importPaths(Source & source, CheckSigsFlag checkSigs = CheckSigs); struct Stats { @@ -685,22 +715,25 @@ protected: }; - -class LocalFSStore : public virtual Store +struct LocalFSStoreConfig : virtual StoreConfig { -public: - - // FIXME: the (Store*) cast works around a bug in gcc that causes + using StoreConfig::StoreConfig; + // FIXME: the (StoreConfig*) cast works around a bug in gcc that causes // it to omit the call to the Setting constructor. Clang works fine // either way. - const PathSetting rootDir{(Store*) this, true, "", + const PathSetting rootDir{(StoreConfig*) this, true, "", "root", "directory prefixed to all other paths"}; - const PathSetting stateDir{(Store*) this, false, + const PathSetting stateDir{(StoreConfig*) this, false, rootDir != "" ? rootDir + "/nix/var/nix" : settings.nixStateDir, "state", "directory where Nix will store state"}; - const PathSetting logDir{(Store*) this, false, + const PathSetting logDir{(StoreConfig*) this, false, rootDir != "" ? rootDir + "/nix/var/log/nix" : settings.nixLogDir, "log", "directory where Nix will store state"}; +}; + +class LocalFSStore : public virtual Store, public virtual LocalFSStoreConfig +{ +public: const static string drvsLogDir; @@ -710,8 +743,7 @@ public: ref getFSAccessor() override; /* Register a permanent GC root. */ - Path addPermRoot(const StorePath & storePath, - const Path & gcRoot, bool indirect, bool allowOutsideRootsDir = false); + Path addPermRoot(const StorePath & storePath, const Path & gcRoot); virtual Path getRealStoreDir() { return storeDir; } @@ -731,11 +763,13 @@ void copyStorePath(ref srcStore, ref dstStore, /* Copy store paths from one store to another. The paths may be copied - in parallel. They are copied in a topologically sorted order - (i.e. if A is a reference of B, then A is copied before B), but - the set of store paths is not automatically closed; use - copyClosure() for that. */ -void copyPaths(ref srcStore, ref dstStore, const StorePathSet & storePaths, + in parallel. They are copied in a topologically sorted order (i.e. + if A is a reference of B, then A is copied before B), but the set + of store paths is not automatically closed; use copyClosure() for + that. Returns a map of what each path was copied to the dstStore + as. */ +std::map copyPaths(ref srcStore, ref dstStore, + const StorePathSet & storePaths, RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs, SubstituteFlag substitute = NoSubstitute); @@ -788,37 +822,48 @@ ref openStore(const std::string & uri = settings.storeUri.get(), const Store::Params & extraParams = Store::Params()); -enum StoreType { - tDaemon, - tLocal, - tOther -}; - - -StoreType getStoreType(const std::string & uri = settings.storeUri.get(), - const std::string & stateDir = settings.nixStateDir); - /* Return the default substituter stores, defined by the ‘substituters’ option and various legacy options. */ std::list> getDefaultSubstituters(); - -/* Store implementation registration. */ -typedef std::function( - const std::string & uri, const Store::Params & params)> OpenStore; - -struct RegisterStoreImplementation +struct StoreFactory { - typedef std::vector Implementations; - static Implementations * implementations; + std::set uriSchemes; + std::function (const std::string & scheme, const std::string & uri, const Store::Params & params)> create; + std::function ()> getConfig; +}; - RegisterStoreImplementation(OpenStore fun) +struct Implementations +{ + static std::vector * registered; + + template + static void add() { - if (!implementations) implementations = new Implementations; - implementations->push_back(fun); + if (!registered) registered = new std::vector(); + StoreFactory factory{ + .uriSchemes = T::uriSchemes(), + .create = + ([](const std::string & scheme, const std::string & uri, const Store::Params & params) + -> std::shared_ptr + { return std::make_shared(scheme, uri, params); }), + .getConfig = + ([]() + -> std::shared_ptr + { return std::make_shared(StringMap({})); }) + }; + registered->push_back(factory); } }; +template +struct RegisterStoreImplementation +{ + RegisterStoreImplementation() + { + Implementations::add(); + } +}; /* Display a set of paths in human-readable form (i.e., between quotes @@ -829,9 +874,11 @@ string showPaths(const PathSet & paths); std::optional decodeValidPathInfo( const Store & store, std::istream & str, - bool hashGiven = false); + std::optional hashGiven = std::nullopt); /* Split URI into protocol+hierarchy part and its parameter set. */ std::pair splitUriAndParams(const std::string & uri); +std::optional getDerivationCA(const BasicDerivation & drv); + } diff --git a/src/libstore/user-lock.cc b/src/libstore/user-lock.cc index fb2a45f48..704bb4ad0 100644 --- a/src/libstore/user-lock.cc +++ b/src/libstore/user-lock.cc @@ -3,6 +3,9 @@ #include "pathlocks.hh" #include "cgroup.hh" +#include +#include + namespace nix { struct SimpleUserLock : UserLock diff --git a/src/libstore/worker-protocol.hh b/src/libstore/worker-protocol.hh index 8b538f6da..b3705578e 100644 --- a/src/libstore/worker-protocol.hh +++ b/src/libstore/worker-protocol.hh @@ -6,7 +6,7 @@ namespace nix { #define WORKER_MAGIC_1 0x6e697863 #define WORKER_MAGIC_2 0x6478696f -#define PROTOCOL_VERSION 0x116 +#define PROTOCOL_VERSION 0x11a #define GET_PROTOCOL_MAJOR(x) ((x) & 0xff00) #define GET_PROTOCOL_MINOR(x) ((x) & 0x00ff) @@ -18,7 +18,7 @@ typedef enum { wopQueryReferences = 5, // obsolete wopQueryReferrers = 6, wopAddToStore = 7, - wopAddTextToStore = 8, + wopAddTextToStore = 8, // obsolete since 1.25, Nix 3.0. Use wopAddToStore wopBuildPaths = 9, wopEnsurePath = 10, wopAddTempRoot = 11, @@ -66,10 +66,89 @@ typedef enum { class Store; struct Source; -template T readStorePaths(const Store & store, Source & from); +/* To guide overloading */ +template +struct Phantom {}; -void writeStorePaths(const Store & store, Sink & out, const StorePathSet & paths); -void writeOutputPathMap(const Store & store, Sink & out, const OutputPathMap & paths); +namespace worker_proto { +/* FIXME maybe move more stuff inside here */ + +#define MAKE_WORKER_PROTO(TEMPLATE, T) \ + TEMPLATE T read(const Store & store, Source & from, Phantom< T > _); \ + TEMPLATE void write(const Store & store, Sink & out, const T & str) + +MAKE_WORKER_PROTO(, std::string); +MAKE_WORKER_PROTO(, StorePath); +MAKE_WORKER_PROTO(, ContentAddress); + +MAKE_WORKER_PROTO(template, std::set); + +#define X_ template +#define Y_ std::map +MAKE_WORKER_PROTO(X_, Y_); +#undef X_ +#undef Y_ + +/* These use the empty string for the null case, relying on the fact + that the underlying types never serialize to the empty string. + + We do this instead of a generic std::optional instance because + ordinal tags (0 or 1, here) are a bit of a compatability hazard. For + the same reason, we don't have a std::variant instances (ordinal + tags 0...n). + + We could the generic instances and then these as specializations for + compatability, but that's proven a bit finnicky, and also makes the + worker protocol harder to implement in other languages where such + specializations may not be allowed. + */ +MAKE_WORKER_PROTO(, std::optional); +MAKE_WORKER_PROTO(, std::optional); + +template +std::set read(const Store & store, Source & from, Phantom> _) +{ + std::set resSet; + auto size = readNum(from); + while (size--) { + resSet.insert(read(store, from, Phantom {})); + } + return resSet; +} + +template +void write(const Store & store, Sink & out, const std::set & resSet) +{ + out << resSet.size(); + for (auto & key : resSet) { + write(store, out, key); + } +} + +template +std::map read(const Store & store, Source & from, Phantom> _) +{ + std::map resMap; + auto size = readNum(from); + while (size--) { + auto k = read(store, from, Phantom {}); + auto v = read(store, from, Phantom {}); + resMap.insert_or_assign(std::move(k), std::move(v)); + } + return resMap; +} + +template +void write(const Store & store, Sink & out, const std::map & resMap) +{ + out << resMap.size(); + for (auto & i : resMap) { + write(store, out, i.first); + write(store, out, i.second); + } +} + +} } diff --git a/src/libutil/abstract-setting-to-json.hh b/src/libutil/abstract-setting-to-json.hh new file mode 100644 index 000000000..b3fbc84f7 --- /dev/null +++ b/src/libutil/abstract-setting-to-json.hh @@ -0,0 +1,15 @@ +#pragma once + +#include +#include "config.hh" + +namespace nix { +template +std::map BaseSetting::toJSONObject() +{ + auto obj = AbstractSetting::toJSONObject(); + obj.emplace("value", value); + obj.emplace("defaultValue", defaultValue); + return obj; +} +} diff --git a/src/libutil/ansicolor.hh b/src/libutil/ansicolor.hh index a38c2d798..ae741f867 100644 --- a/src/libutil/ansicolor.hh +++ b/src/libutil/ansicolor.hh @@ -11,7 +11,7 @@ namespace nix { #define ANSI_GREEN "\e[32;1m" #define ANSI_YELLOW "\e[33;1m" #define ANSI_BLUE "\e[34;1m" -#define ANSI_MAGENTA "\e[35m;1m" -#define ANSI_CYAN "\e[36m;1m" +#define ANSI_MAGENTA "\e[35;1m" +#define ANSI_CYAN "\e[36;1m" } diff --git a/src/libutil/archive.cc b/src/libutil/archive.cc index 51c88537e..f1479329f 100644 --- a/src/libutil/archive.cc +++ b/src/libutil/archive.cc @@ -27,11 +27,13 @@ struct ArchiveSettings : Config #endif "use-case-hack", "Whether to enable a Darwin-specific hack for dealing with file name collisions."}; + Setting preallocateContents{this, true, "preallocate-contents", + "Whether to preallocate files when writing objects with known size."}; }; static ArchiveSettings archiveSettings; -static GlobalConfig::Register r1(&archiveSettings); +static GlobalConfig::Register rArchiveSettings(&archiveSettings); const std::string narVersionMagic1 = "nix-archive-1"; @@ -66,9 +68,7 @@ static void dump(const Path & path, Sink & sink, PathFilter & filter) { checkInterrupt(); - struct stat st; - if (lstat(path.c_str(), &st)) - throw SysError("getting attributes of path '%1%'", path); + auto st = lstat(path); sink << "("; @@ -150,17 +150,17 @@ static void skipGeneric(Source & source) static void parseContents(ParseSink & sink, Source & source, const Path & path) { - unsigned long long size = readLongLong(source); + uint64_t size = readLongLong(source); sink.preallocateContents(size); - unsigned long long left = size; + uint64_t left = size; std::vector buf(65536); while (left) { checkInterrupt(); auto n = buf.size(); - if ((unsigned long long)n > left) n = left; + if ((uint64_t)n > left) n = left; source(buf.data(), n); sink.receiveContents(buf.data(), n); left -= n; @@ -323,8 +323,11 @@ struct RestoreSink : ParseSink throw SysError("fchmod"); } - void preallocateContents(unsigned long long len) + void preallocateContents(uint64_t len) { + if (!archiveSettings.preallocateContents) + return; + #if HAVE_POSIX_FALLOCATE if (len) { errno = posix_fallocate(fd.get(), 0, len); @@ -338,7 +341,7 @@ struct RestoreSink : ParseSink #endif } - void receiveContents(unsigned char * data, unsigned int len) + void receiveContents(unsigned char * data, size_t len) { writeFull(fd.get(), data, len); } @@ -366,11 +369,7 @@ void copyNAR(Source & source, Sink & sink) ParseSink parseSink; /* null sink; just parse the NAR */ - LambdaSource wrapper([&](unsigned char * data, size_t len) { - auto n = source.read(data, len); - sink(data, n); - return n; - }); + TeeSource wrapper { source, sink }; parseDump(parseSink, wrapper); } diff --git a/src/libutil/archive.hh b/src/libutil/archive.hh index 768fe2536..5665732d2 100644 --- a/src/libutil/archive.hh +++ b/src/libutil/archive.hh @@ -57,17 +57,35 @@ struct ParseSink virtual void createRegularFile(const Path & path) { }; virtual void isExecutable() { }; - virtual void preallocateContents(unsigned long long size) { }; - virtual void receiveContents(unsigned char * data, unsigned int len) { }; + virtual void preallocateContents(uint64_t size) { }; + virtual void receiveContents(unsigned char * data, size_t len) { }; virtual void createSymlink(const Path & path, const string & target) { }; }; -struct TeeSink : ParseSink +/* If the NAR archive contains a single file at top-level, then save + the contents of the file to `s'. Otherwise barf. */ +struct RetrieveRegularNARSink : ParseSink { - TeeSource source; + bool regular = true; + Sink & sink; - TeeSink(Source & source) : source(source) { } + RetrieveRegularNARSink(Sink & sink) : sink(sink) { } + + void createDirectory(const Path & path) + { + regular = false; + } + + void receiveContents(unsigned char * data, size_t len) + { + sink(data, len); + } + + void createSymlink(const Path & path, const string & target) + { + regular = false; + } }; void parseDump(ParseSink & sink, Source & source); diff --git a/src/libutil/args.cc b/src/libutil/args.cc index 1f0e4f803..2760b830b 100644 --- a/src/libutil/args.cc +++ b/src/libutil/args.cc @@ -1,6 +1,10 @@ #include "args.hh" #include "hash.hh" +#include + +#include + namespace nix { void Args::addFlag(Flag && flag_) @@ -13,6 +17,20 @@ void Args::addFlag(Flag && flag_) if (flag->shortName) shortFlags[flag->shortName] = flag; } +bool pathCompletions = false; +std::shared_ptr> completions; + +std::string completionMarker = "___COMPLETE___"; + +std::optional needsCompletion(std::string_view s) +{ + if (!completions) return {}; + auto i = s.find(completionMarker); + if (i != std::string::npos) + return std::string(s.begin(), i); + return {}; +} + void Args::parseCmdline(const Strings & _cmdline) { Strings pendingArgs; @@ -20,6 +38,14 @@ void Args::parseCmdline(const Strings & _cmdline) Strings cmdline(_cmdline); + if (auto s = getEnv("NIX_GET_COMPLETIONS")) { + size_t n = std::stoi(*s); + assert(n > 0 && n <= cmdline.size()); + *std::next(cmdline.begin(), n - 1) += completionMarker; + completions = std::make_shared(); + verbosity = lvlError; + } + for (auto pos = cmdline.begin(); pos != cmdline.end(); ) { auto arg = *pos; @@ -63,7 +89,7 @@ void Args::printHelp(const string & programName, std::ostream & out) for (auto & exp : expectedArgs) { std::cout << renderLabels({exp.label}); // FIXME: handle arity > 1 - if (exp.arity == 0) std::cout << "..."; + if (exp.handler.arity == ArityAny) std::cout << "..."; if (exp.optional) std::cout << "?"; } std::cout << "\n"; @@ -99,18 +125,32 @@ bool Args::processFlag(Strings::iterator & pos, Strings::iterator end) auto process = [&](const std::string & name, const Flag & flag) -> bool { ++pos; std::vector args; + bool anyCompleted = false; for (size_t n = 0 ; n < flag.handler.arity; ++n) { if (pos == end) { if (flag.handler.arity == ArityAny) break; throw UsageError("flag '%s' requires %d argument(s)", name, flag.handler.arity); } + if (flag.completer) + if (auto prefix = needsCompletion(*pos)) { + anyCompleted = true; + flag.completer(n, *prefix); + } args.push_back(*pos++); } - flag.handler.fun(std::move(args)); + if (!anyCompleted) + flag.handler.fun(std::move(args)); return true; }; if (string(*pos, 0, 2) == "--") { + if (auto prefix = needsCompletion(*pos)) { + for (auto & [name, flag] : longFlags) { + if (!hiddenCategories.count(flag->category) + && hasPrefix(name, std::string(*prefix, 2))) + completions->insert("--" + name); + } + } auto i = longFlags.find(string(*pos, 2)); if (i == longFlags.end()) return false; return process("--" + i->first, *i->second); @@ -123,6 +163,14 @@ bool Args::processFlag(Strings::iterator & pos, Strings::iterator end) return process(std::string("-") + c, *i->second); } + if (auto prefix = needsCompletion(*pos)) { + if (prefix == "-") { + completions->insert("--"); + for (auto & [flag, _] : shortFlags) + completions->insert(std::string("-") + flag); + } + } + return false; } @@ -138,12 +186,17 @@ bool Args::processArgs(const Strings & args, bool finish) bool res = false; - if ((exp.arity == 0 && finish) || - (exp.arity > 0 && args.size() == exp.arity)) + if ((exp.handler.arity == ArityAny && finish) || + (exp.handler.arity != ArityAny && args.size() == exp.handler.arity)) { std::vector ss; - for (auto & s : args) ss.push_back(s); - exp.handler(std::move(ss)); + for (const auto &[n, s] : enumerate(args)) { + ss.push_back(s); + if (exp.completer) + if (auto prefix = needsCompletion(s)) + exp.completer(n, *prefix); + } + exp.handler.fun(ss); expectedArgs.pop_front(); res = true; } @@ -154,6 +207,50 @@ bool Args::processArgs(const Strings & args, bool finish) return res; } +nlohmann::json Args::toJSON() +{ + auto flags = nlohmann::json::object(); + + for (auto & [name, flag] : longFlags) { + auto j = nlohmann::json::object(); + if (flag->shortName) + j["shortName"] = std::string(1, flag->shortName); + if (flag->description != "") + j["description"] = flag->description; + if (flag->category != "") + j["category"] = flag->category; + if (flag->handler.arity != ArityAny) + j["arity"] = flag->handler.arity; + if (!flag->labels.empty()) + j["labels"] = flag->labels; + flags[name] = std::move(j); + } + + auto args = nlohmann::json::array(); + + for (auto & arg : expectedArgs) { + auto j = nlohmann::json::object(); + j["label"] = arg.label; + j["optional"] = arg.optional; + if (arg.handler.arity != ArityAny) + j["arity"] = arg.handler.arity; + args.push_back(std::move(j)); + } + + auto res = nlohmann::json::object(); + res["description"] = description(); + res["flags"] = std::move(flags); + res["args"] = std::move(args); + return res; +} + +static void hashTypeCompleter(size_t index, std::string_view prefix) +{ + for (auto & type : hashTypes) + if (hasPrefix(type, prefix)) + completions->insert(type); +} + Args::Flag Args::Flag::mkHashTypeFlag(std::string && longName, HashType * ht) { return Flag { @@ -162,7 +259,8 @@ Args::Flag Args::Flag::mkHashTypeFlag(std::string && longName, HashType * ht) .labels = {"hash-algo"}, .handler = {[ht](std::string s) { *ht = parseHashType(s); - }} + }}, + .completer = hashTypeCompleter }; } @@ -174,10 +272,42 @@ Args::Flag Args::Flag::mkHashTypeOptFlag(std::string && longName, std::optional< .labels = {"hash-algo"}, .handler = {[oht](std::string s) { *oht = std::optional { parseHashType(s) }; - }} + }}, + .completer = hashTypeCompleter }; } +static void _completePath(std::string_view prefix, bool onlyDirs) +{ + pathCompletions = true; + glob_t globbuf; + int flags = GLOB_NOESCAPE | GLOB_TILDE; + #ifdef GLOB_ONLYDIR + if (onlyDirs) + flags |= GLOB_ONLYDIR; + #endif + if (glob((std::string(prefix) + "*").c_str(), flags, nullptr, &globbuf) == 0) { + for (size_t i = 0; i < globbuf.gl_pathc; ++i) { + if (onlyDirs) { + auto st = lstat(globbuf.gl_pathv[i]); + if (!S_ISDIR(st.st_mode)) continue; + } + completions->insert(globbuf.gl_pathv[i]); + } + globfree(&globbuf); + } +} + +void completePath(size_t, std::string_view prefix) +{ + _completePath(prefix, false); +} + +void completeDir(size_t, std::string_view prefix) +{ + _completePath(prefix, true); +} + Strings argvToStrings(int argc, char * * argv) { Strings args; @@ -222,21 +352,47 @@ void Command::printHelp(const string & programName, std::ostream & out) } } +nlohmann::json Command::toJSON() +{ + auto exs = nlohmann::json::array(); + + for (auto & example : examples()) { + auto ex = nlohmann::json::object(); + ex["description"] = example.description; + ex["command"] = chomp(stripIndentation(example.command)); + exs.push_back(std::move(ex)); + } + + auto res = Args::toJSON(); + res["examples"] = std::move(exs); + auto s = doc(); + if (s != "") res.emplace("doc", stripIndentation(s)); + return res; +} + MultiCommand::MultiCommand(const Commands & commands) : commands(commands) { - expectedArgs.push_back(ExpectedArg{"command", 1, true, [=](std::vector ss) { - assert(!command); - auto cmd = ss[0]; - if (auto alias = get(deprecatedAliases, cmd)) { - warn("'%s' is a deprecated alias for '%s'", cmd, *alias); - cmd = *alias; - } - auto i = commands.find(cmd); - if (i == commands.end()) - throw UsageError("'%s' is not a recognised command", cmd); - command = {cmd, i->second()}; - }}); + expectArgs({ + .label = "subcommand", + .optional = true, + .handler = {[=](std::string s) { + assert(!command); + if (auto alias = get(deprecatedAliases, s)) { + warn("'%s' is a deprecated alias for '%s'", s, *alias); + s = *alias; + } + if (auto prefix = needsCompletion(s)) { + for (auto & [name, command] : commands) + if (hasPrefix(name, *prefix)) + completions->insert(name); + } + auto i = commands.find(s); + if (i == commands.end()) + throw UsageError("'%s' is not a recognised command", s); + command = {s, i->second()}; + }} + }); categories[Command::catDefault] = "Available commands"; } @@ -288,4 +444,20 @@ bool MultiCommand::processArgs(const Strings & args, bool finish) return Args::processArgs(args, finish); } +nlohmann::json MultiCommand::toJSON() +{ + auto cmds = nlohmann::json::object(); + + for (auto & [name, commandFun] : commands) { + auto command = commandFun(); + auto j = command->toJSON(); + j["category"] = categories[command->category()]; + cmds[name] = std::move(j); + } + + auto res = Args::toJSON(); + res["commands"] = std::move(cmds); + return res; +} + } diff --git a/src/libutil/args.hh b/src/libutil/args.hh index 433d26bba..f41242e17 100644 --- a/src/libutil/args.hh +++ b/src/libutil/args.hh @@ -4,12 +4,12 @@ #include #include +#include + #include "util.hh" namespace nix { -MakeError(UsageError, Error); - enum HashType : char; class Args @@ -22,67 +22,74 @@ public: virtual void printHelp(const string & programName, std::ostream & out); + /* Return a short one-line description of the command. */ virtual std::string description() { return ""; } protected: static const size_t ArityAny = std::numeric_limits::max(); + struct Handler + { + std::function)> fun; + size_t arity; + + Handler() {} + + Handler(std::function)> && fun) + : fun(std::move(fun)) + , arity(ArityAny) + { } + + Handler(std::function && handler) + : fun([handler{std::move(handler)}](std::vector) { handler(); }) + , arity(0) + { } + + Handler(std::function && handler) + : fun([handler{std::move(handler)}](std::vector ss) { + handler(std::move(ss[0])); + }) + , arity(1) + { } + + Handler(std::function && handler) + : fun([handler{std::move(handler)}](std::vector ss) { + handler(std::move(ss[0]), std::move(ss[1])); + }) + , arity(2) + { } + + Handler(std::vector * dest) + : fun([=](std::vector ss) { *dest = ss; }) + , arity(ArityAny) + { } + + template + Handler(T * dest) + : fun([=](std::vector ss) { *dest = ss[0]; }) + , arity(1) + { } + + template + Handler(T * dest, const T & val) + : fun([=](std::vector ss) { *dest = val; }) + , arity(0) + { } + }; + /* Flags. */ struct Flag { typedef std::shared_ptr ptr; - struct Handler - { - std::function)> fun; - size_t arity; - - Handler() {} - - Handler(std::function)> && fun) - : fun(std::move(fun)) - , arity(ArityAny) - { } - - Handler(std::function && handler) - : fun([handler{std::move(handler)}](std::vector) { handler(); }) - , arity(0) - { } - - Handler(std::function && handler) - : fun([handler{std::move(handler)}](std::vector ss) { - handler(std::move(ss[0])); - }) - , arity(1) - { } - - Handler(std::function && handler) - : fun([handler{std::move(handler)}](std::vector ss) { - handler(std::move(ss[0]), std::move(ss[1])); - }) - , arity(2) - { } - - template - Handler(T * dest) - : fun([=](std::vector ss) { *dest = ss[0]; }) - , arity(1) - { } - - template - Handler(T * dest, const T & val) - : fun([=](std::vector ss) { *dest = val; }) - , arity(0) - { } - }; - std::string longName; char shortName = 0; std::string description; std::string category; Strings labels; Handler handler; + std::function completer; static Flag mkHashTypeFlag(std::string && longName, HashType * ht); static Flag mkHashTypeOptFlag(std::string && longName, std::optional * oht); @@ -99,9 +106,9 @@ protected: struct ExpectedArg { std::string label; - size_t arity; // 0 = any - bool optional; - std::function)> handler; + bool optional = false; + Handler handler; + std::function completer; }; std::list expectedArgs; @@ -175,22 +182,32 @@ public: }); } + void expectArgs(ExpectedArg && arg) + { + expectedArgs.emplace_back(std::move(arg)); + } + /* Expect a string argument. */ void expectArg(const std::string & label, string * dest, bool optional = false) { - expectedArgs.push_back(ExpectedArg{label, 1, optional, [=](std::vector ss) { - *dest = ss[0]; - }}); + expectArgs({ + .label = label, + .optional = optional, + .handler = {dest} + }); } /* Expect 0 or more arguments. */ void expectArgs(const std::string & label, std::vector * dest) { - expectedArgs.push_back(ExpectedArg{label, 0, false, [=](std::vector ss) { - *dest = std::move(ss); - }}); + expectArgs({ + .label = label, + .handler = {dest} + }); } + virtual nlohmann::json toJSON(); + friend class MultiCommand; }; @@ -205,6 +222,9 @@ struct Command : virtual Args virtual void prepare() { }; virtual void run() = 0; + /* Return documentation about this command, in Markdown format. */ + virtual std::string doc() { return ""; } + struct Example { std::string description; @@ -222,6 +242,8 @@ struct Command : virtual Args virtual Category category() { return catDefault; } void printHelp(const string & programName, std::ostream & out) override; + + nlohmann::json toJSON() override; }; typedef std::map()>> Commands; @@ -247,6 +269,8 @@ public: bool processFlag(Strings::iterator & pos, Strings::iterator end) override; bool processArgs(const Strings & args, bool finish) override; + + nlohmann::json toJSON() override; }; Strings argvToStrings(int argc, char * * argv); @@ -259,4 +283,13 @@ typedef std::vector> Table2; void printTable(std::ostream & out, const Table2 & table); +extern std::shared_ptr> completions; +extern bool pathCompletions; + +std::optional needsCompletion(std::string_view s); + +void completePath(size_t, std::string_view prefix); + +void completeDir(size_t, std::string_view prefix); + } diff --git a/src/libutil/callback.hh b/src/libutil/callback.hh new file mode 100644 index 000000000..ef31794be --- /dev/null +++ b/src/libutil/callback.hh @@ -0,0 +1,46 @@ +#pragma once + +#include +#include + +namespace nix { + +/* A callback is a wrapper around a lambda that accepts a valid of + type T or an exception. (We abuse std::future to pass the value or + exception.) */ +template +class Callback +{ + std::function)> fun; + std::atomic_flag done = ATOMIC_FLAG_INIT; + +public: + + Callback(std::function)> fun) : fun(fun) { } + + Callback(Callback && callback) : fun(std::move(callback.fun)) + { + auto prev = callback.done.test_and_set(); + if (prev) done.test_and_set(); + } + + void operator()(T && t) noexcept + { + auto prev = done.test_and_set(); + assert(!prev); + std::promise promise; + promise.set_value(std::move(t)); + fun(promise.get_future()); + } + + void rethrow(const std::exception_ptr & exc = std::current_exception()) noexcept + { + auto prev = done.test_and_set(); + assert(!prev); + std::promise promise; + promise.set_exception(exc); + fun(promise.get_future()); + } +}; + +} diff --git a/src/libutil/config.cc b/src/libutil/config.cc index 8fc700a2b..521733025 100644 --- a/src/libutil/config.cc +++ b/src/libutil/config.cc @@ -1,6 +1,8 @@ #include "config.hh" #include "args.hh" -#include "json.hh" +#include "abstract-setting-to-json.hh" + +#include namespace nix { @@ -131,15 +133,14 @@ void Config::resetOverriden() s.second.setting->overriden = false; } -void Config::toJSON(JSONObject & out) +nlohmann::json Config::toJSON() { + auto res = nlohmann::json::object(); for (auto & s : _settings) if (!s.second.isAlias) { - JSONObject out2(out.object(s.first)); - out2.attr("description", s.second.setting->description); - JSONPlaceholder out3(out2.placeholder("value")); - s.second.setting->toJSON(out3); + res.emplace(s.first, s.second.setting->toJSON()); } + return res; } void Config::convertToArgs(Args & args, const std::string & category) @@ -153,7 +154,7 @@ AbstractSetting::AbstractSetting( const std::string & name, const std::string & description, const std::set & aliases) - : name(name), description(description), aliases(aliases) + : name(name), description(stripIndentation(description)), aliases(aliases) { } @@ -162,21 +163,23 @@ void AbstractSetting::setDefault(const std::string & str) if (!overriden) set(str); } -void AbstractSetting::toJSON(JSONPlaceholder & out) +nlohmann::json AbstractSetting::toJSON() { - out.write(to_string()); + return nlohmann::json(toJSONObject()); +} + +std::map AbstractSetting::toJSONObject() +{ + std::map obj; + obj.emplace("description", description); + obj.emplace("aliases", aliases); + return obj; } void AbstractSetting::convertToArg(Args & args, const std::string & category) { } -template -void BaseSetting::toJSON(JSONPlaceholder & out) -{ - out.write(value); -} - template void BaseSetting::convertToArg(Args & args, const std::string & category) { @@ -255,13 +258,6 @@ template<> std::string BaseSetting::to_string() const return concatStringsSep(" ", value); } -template<> void BaseSetting::toJSON(JSONPlaceholder & out) -{ - JSONList list(out.list()); - for (auto & s : value) - list.elem(s); -} - template<> void BaseSetting::set(const std::string & str) { value = tokenizeString(str); @@ -272,11 +268,24 @@ template<> std::string BaseSetting::to_string() const return concatStringsSep(" ", value); } -template<> void BaseSetting::toJSON(JSONPlaceholder & out) +template<> void BaseSetting::set(const std::string & str) { - JSONList list(out.list()); - for (auto & s : value) - list.elem(s); + auto kvpairs = tokenizeString(str); + for (auto & s : kvpairs) + { + auto eq = s.find_first_of('='); + if (std::string::npos != eq) + value.emplace(std::string(s, 0, eq), std::string(s, eq + 1)); + // else ignored + } +} + +template<> std::string BaseSetting::to_string() const +{ + Strings kvstrs; + std::transform(value.begin(), value.end(), back_inserter(kvstrs), + [&](auto kvpair){ return kvpair.first + "=" + kvpair.second; }); + return concatStringsSep(" ", kvstrs); } template class BaseSetting; @@ -289,6 +298,7 @@ template class BaseSetting; template class BaseSetting; template class BaseSetting; template class BaseSetting; +template class BaseSetting; void PathSetting::set(const std::string & str) { @@ -323,10 +333,12 @@ void GlobalConfig::resetOverriden() config->resetOverriden(); } -void GlobalConfig::toJSON(JSONObject & out) +nlohmann::json GlobalConfig::toJSON() { + auto res = nlohmann::json::object(); for (auto & config : *configRegistrations) - config->toJSON(out); + res.update(config->toJSON()); + return res; } void GlobalConfig::convertToArgs(Args & args, const std::string & category) diff --git a/src/libutil/config.hh b/src/libutil/config.hh index 66073546e..1f5f4e7b9 100644 --- a/src/libutil/config.hh +++ b/src/libutil/config.hh @@ -4,6 +4,8 @@ #include "types.hh" +#include + #pragma once namespace nix { @@ -42,8 +44,6 @@ namespace nix { class Args; class AbstractSetting; -class JSONPlaceholder; -class JSONObject; class AbstractConfig { @@ -97,7 +97,7 @@ public: * Outputs all settings to JSON * - out: JSONObject to write the configuration to */ - virtual void toJSON(JSONObject & out) = 0; + virtual nlohmann::json toJSON() = 0; /** * Converts settings to `Args` to be used on the command line interface @@ -167,7 +167,7 @@ public: void resetOverriden() override; - void toJSON(JSONObject & out) override; + nlohmann::json toJSON() override; void convertToArgs(Args & args, const std::string & category) override; }; @@ -206,7 +206,9 @@ protected: virtual std::string to_string() const = 0; - virtual void toJSON(JSONPlaceholder & out); + nlohmann::json toJSON(); + + virtual std::map toJSONObject(); virtual void convertToArg(Args & args, const std::string & category); @@ -220,6 +222,7 @@ class BaseSetting : public AbstractSetting protected: T value; + const T defaultValue; public: @@ -229,6 +232,7 @@ public: const std::set & aliases = {}) : AbstractSetting(name, description, aliases) , value(def) + , defaultValue(def) { } operator const T &() const { return value; } @@ -251,7 +255,7 @@ public: void convertToArg(Args & args, const std::string & category) override; - void toJSON(JSONPlaceholder & out) override; + std::map toJSONObject() override; }; template @@ -319,7 +323,7 @@ struct GlobalConfig : public AbstractConfig void resetOverriden() override; - void toJSON(JSONObject & out) override; + nlohmann::json toJSON() override; void convertToArgs(Args & args, const std::string & category) override; diff --git a/src/libutil/error.cc b/src/libutil/error.cc index a4ee7afc2..803a72953 100644 --- a/src/libutil/error.cc +++ b/src/libutil/error.cc @@ -11,13 +11,13 @@ const std::string nativeSystem = SYSTEM; BaseError & BaseError::addTrace(std::optional e, hintformat hint) { - err.traces.push_front(Trace { .pos = e, .hint = hint}); + err.traces.push_front(Trace { .pos = e, .hint = hint }); return *this; } // c++ std::exception descendants must have a 'const char* what()' function. // This stringifies the error and caches it for use by what(), or similarly by msg(). -const string& BaseError::calcWhat() const +const string & BaseError::calcWhat() const { if (what_.has_value()) return *what_; @@ -34,12 +34,12 @@ const string& BaseError::calcWhat() const std::optional ErrorInfo::programName = std::nullopt; -std::ostream& operator<<(std::ostream &os, const hintformat &hf) +std::ostream & operator<<(std::ostream & os, const hintformat & hf) { return os << hf.str(); } -string showErrPos(const ErrPos &errPos) +string showErrPos(const ErrPos & errPos) { if (errPos.line > 0) { if (errPos.column > 0) { @@ -53,7 +53,7 @@ string showErrPos(const ErrPos &errPos) } } -std::optional getCodeLines(const ErrPos &errPos) +std::optional getCodeLines(const ErrPos & errPos) { if (errPos.line <= 0) return std::nullopt; @@ -92,13 +92,13 @@ std::optional getCodeLines(const ErrPos &errPos) return loc; } } - catch (EndOfFile &eof) { + catch (EndOfFile & eof) { if (loc.errLineOfCode.has_value()) return loc; else return std::nullopt; } - catch (std::exception &e) { + catch (std::exception & e) { printError("error reading nix file: %s\n%s", errPos.file, e.what()); return std::nullopt; } @@ -137,10 +137,10 @@ std::optional getCodeLines(const ErrPos &errPos) } // print lines of code to the ostream, indicating the error column. -void printCodeLines(std::ostream &out, - const string &prefix, - const ErrPos &errPos, - const LinesOfCode &loc) +void printCodeLines(std::ostream & out, + const string & prefix, + const ErrPos & errPos, + const LinesOfCode & loc) { // previous line of code. if (loc.prevLineOfCode.has_value()) { @@ -186,7 +186,7 @@ void printCodeLines(std::ostream &out, } } -void printAtPos(const string &prefix, const ErrPos &pos, std::ostream &out) +void printAtPos(const string & prefix, const ErrPos & pos, std::ostream & out) { if (pos) { @@ -212,7 +212,7 @@ void printAtPos(const string &prefix, const ErrPos &pos, std::ostream &out) } } -std::ostream& showErrorInfo(std::ostream &out, const ErrorInfo &einfo, bool showTrace) +std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool showTrace) { auto errwidth = std::max(getWindowSize().second, 20); string prefix = ""; @@ -355,26 +355,21 @@ std::ostream& showErrorInfo(std::ostream &out, const ErrorInfo &einfo, bool show for (auto iter = einfo.traces.rbegin(); iter != einfo.traces.rend(); ++iter) { - try { + out << std::endl << prefix; + out << ANSI_BLUE << "trace: " << ANSI_NORMAL << iter->hint.str(); + + if (iter->pos.has_value() && (*iter->pos)) { + auto pos = iter->pos.value(); out << std::endl << prefix; - out << ANSI_BLUE << "trace: " << ANSI_NORMAL << iter->hint.str(); + printAtPos(prefix, pos, out); - nl = true; - if (*iter->pos) { - auto pos = iter->pos.value(); + auto loc = getCodeLines(pos); + if (loc.has_value()) + { + out << std::endl << prefix; + printCodeLines(out, prefix, pos, *loc); out << std::endl << prefix; - - printAtPos(prefix, pos, out); - auto loc = getCodeLines(pos); - if (loc.has_value()) - { - out << std::endl << prefix; - printCodeLines(out, prefix, pos, *loc); - out << std::endl << prefix; - } } - } catch(const std::bad_optional_access& e) { - out << iter->hint.str() << std::endl; } } } diff --git a/src/libutil/error.hh b/src/libutil/error.hh index 1b0fb43b8..d1b6d82bb 100644 --- a/src/libutil/error.hh +++ b/src/libutil/error.hh @@ -1,8 +1,8 @@ #pragma once - #include "ref.hh" #include "types.hh" +#include "fmt.hh" #include #include @@ -10,7 +10,9 @@ #include #include -#include "fmt.hh" +#include +#include +#include /* Before 4.7, gcc's std::exception uses empty throw() specifiers for * its (virtual) destructor and what() in c++11 mode, in violation of spec @@ -105,7 +107,7 @@ struct Trace { struct ErrorInfo { Verbosity level; string name; - string description; + string description; // FIXME: remove? it seems to be barely used std::optional hint; std::optional errPos; std::list traces; @@ -167,7 +169,7 @@ public: #endif const string & msg() const { return calcWhat(); } - const ErrorInfo & info() { calcWhat(); return err; } + const ErrorInfo & info() const { calcWhat(); return err; } template BaseError & addTrace(std::optional e, const string &fs, const Args & ... args) @@ -189,6 +191,8 @@ public: } MakeError(Error, BaseError); +MakeError(UsageError, Error); +MakeError(UnimplementedError, Error); class SysError : public Error { diff --git a/src/libutil/fmt.hh b/src/libutil/fmt.hh index a39de041f..85c0e9429 100644 --- a/src/libutil/fmt.hh +++ b/src/libutil/fmt.hh @@ -1,7 +1,6 @@ #pragma once #include -#include #include #include "ansicolor.hh" @@ -77,11 +76,11 @@ template struct yellowtxt { yellowtxt(const T &s) : value(s) {} - const T &value; + const T & value; }; template -std::ostream& operator<<(std::ostream &out, const yellowtxt &y) +std::ostream & operator<<(std::ostream & out, const yellowtxt & y) { return out << ANSI_YELLOW << y.value << ANSI_NORMAL; } @@ -89,12 +88,12 @@ std::ostream& operator<<(std::ostream &out, const yellowtxt &y) template struct normaltxt { - normaltxt(const T &s) : value(s) {} - const T &value; + normaltxt(const T & s) : value(s) {} + const T & value; }; template -std::ostream& operator<<(std::ostream &out, const normaltxt &y) +std::ostream & operator<<(std::ostream & out, const normaltxt & y) { return out << ANSI_NORMAL << y.value; } @@ -102,26 +101,30 @@ std::ostream& operator<<(std::ostream &out, const normaltxt &y) class hintformat { public: - hintformat(const string &format) :fmt(format) + hintformat(const string & format) : fmt(format) { - fmt.exceptions(boost::io::all_error_bits ^ + fmt.exceptions(boost::io::all_error_bits ^ boost::io::too_many_args_bit ^ boost::io::too_few_args_bit); } - hintformat(const hintformat &hf) - : fmt(hf.fmt) - {} + hintformat(const hintformat & hf) + : fmt(hf.fmt) + { } + + hintformat(format && fmt) + : fmt(std::move(fmt)) + { } template - hintformat& operator%(const T &value) + hintformat & operator%(const T & value) { fmt % yellowtxt(value); return *this; } template - hintformat& operator%(const normaltxt &value) + hintformat & operator%(const normaltxt & value) { fmt % value.value; return *this; @@ -136,7 +139,7 @@ private: format fmt; }; -std::ostream& operator<<(std::ostream &os, const hintformat &hf); +std::ostream & operator<<(std::ostream & os, const hintformat & hf); template inline hintformat hintfmt(const std::string & fs, const Args & ... args) diff --git a/src/libutil/hash.cc b/src/libutil/hash.cc index 1a3e7c5d8..4a94f0dfd 100644 --- a/src/libutil/hash.cc +++ b/src/libutil/hash.cc @@ -7,8 +7,8 @@ #include "args.hh" #include "hash.hh" #include "archive.hh" +#include "split.hh" #include "util.hh" -#include "istringstream_nocopy.hh" #include #include @@ -17,15 +17,23 @@ namespace nix { -void Hash::init() -{ - assert(type); - switch (*type) { - case htMD5: hashSize = md5HashSize; break; - case htSHA1: hashSize = sha1HashSize; break; - case htSHA256: hashSize = sha256HashSize; break; - case htSHA512: hashSize = sha512HashSize; break; +static size_t regularHashSize(HashType type) { + switch (type) { + case htMD5: return md5HashSize; + case htSHA1: return sha1HashSize; + case htSHA256: return sha256HashSize; + case htSHA512: return sha512HashSize; } + abort(); +} + + +std::set hashTypes = { "md5", "sha1", "sha256", "sha512" }; + + +Hash::Hash(HashType type) : type(type) +{ + hashSize = regularHashSize(type); assert(hashSize <= maxHashSize); memset(hash, 0, maxHashSize); } @@ -106,17 +114,11 @@ string printHash16or32(const Hash & hash) } -HashType assertInitHashType(const Hash & h) -{ - assert(h.type); - return *h.type; -} - std::string Hash::to_string(Base base, bool includeType) const { std::string s; if (base == SRI || includeType) { - s += printHashType(assertInitHashType(*this)); + s += printHashType(type); s += base == SRI ? '-' : ':'; } switch (base) { @@ -134,63 +136,103 @@ std::string Hash::to_string(Base base, bool includeType) const return s; } -Hash::Hash(std::string_view s, HashType type) : Hash(s, std::optional { type }) { } -Hash::Hash(std::string_view s) : Hash(s, std::optional{}) { } +Hash Hash::dummy(htSHA256); -Hash::Hash(std::string_view s, std::optional type) - : type(type) -{ - size_t pos = 0; +Hash Hash::parseSRI(std::string_view original) { + auto rest = original; + + // Parse the has type before the separater, if there was one. + auto hashRaw = splitPrefixTo(rest, '-'); + if (!hashRaw) + throw BadHash("hash '%s' is not SRI", original); + HashType parsedType = parseHashType(*hashRaw); + + return Hash(rest, parsedType, true); +} + +// Mutates the string to eliminate the prefixes when found +static std::pair, bool> getParsedTypeAndSRI(std::string_view & rest) { bool isSRI = false; - auto sep = s.find(':'); - if (sep == string::npos) { - sep = s.find('-'); - if (sep != string::npos) { - isSRI = true; - } else if (! type) - throw BadHash("hash '%s' does not include a type", s); + // Parse the has type before the separater, if there was one. + std::optional optParsedType; + { + auto hashRaw = splitPrefixTo(rest, ':'); + + if (!hashRaw) { + hashRaw = splitPrefixTo(rest, '-'); + if (hashRaw) + isSRI = true; + } + if (hashRaw) + optParsedType = parseHashType(*hashRaw); } - if (sep != string::npos) { - string hts = string(s, 0, sep); - this->type = parseHashType(hts); - if (!this->type) - throw BadHash("unknown hash type '%s'", hts); - if (type && type != this->type) - throw BadHash("hash '%s' should have type '%s'", s, printHashType(*type)); - pos = sep + 1; - } + return {optParsedType, isSRI}; +} - init(); +Hash Hash::parseAnyPrefixed(std::string_view original) +{ + auto rest = original; + auto [optParsedType, isSRI] = getParsedTypeAndSRI(rest); - size_t size = s.size() - pos; + // Either the string or user must provide the type, if they both do they + // must agree. + if (!optParsedType) + throw BadHash("hash '%s' does not include a type", rest); - if (!isSRI && size == base16Len()) { + return Hash(rest, *optParsedType, isSRI); +} + +Hash Hash::parseAny(std::string_view original, std::optional optType) +{ + auto rest = original; + auto [optParsedType, isSRI] = getParsedTypeAndSRI(rest); + + // Either the string or user must provide the type, if they both do they + // must agree. + if (!optParsedType && !optType) + throw BadHash("hash '%s' does not include a type, nor is the type otherwise known from context.", rest); + else if (optParsedType && optType && *optParsedType != *optType) + throw BadHash("hash '%s' should have type '%s'", original, printHashType(*optType)); + + HashType hashType = optParsedType ? *optParsedType : *optType; + return Hash(rest, hashType, isSRI); +} + +Hash Hash::parseNonSRIUnprefixed(std::string_view s, HashType type) +{ + return Hash(s, type, false); +} + +Hash::Hash(std::string_view rest, HashType type, bool isSRI) + : Hash(type) +{ + if (!isSRI && rest.size() == base16Len()) { auto parseHexDigit = [&](char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - 'A' + 10; if (c >= 'a' && c <= 'f') return c - 'a' + 10; - throw BadHash("invalid base-16 hash '%s'", s); + throw BadHash("invalid base-16 hash '%s'", rest); }; for (unsigned int i = 0; i < hashSize; i++) { hash[i] = - parseHexDigit(s[pos + i * 2]) << 4 - | parseHexDigit(s[pos + i * 2 + 1]); + parseHexDigit(rest[i * 2]) << 4 + | parseHexDigit(rest[i * 2 + 1]); } } - else if (!isSRI && size == base32Len()) { + else if (!isSRI && rest.size() == base32Len()) { - for (unsigned int n = 0; n < size; ++n) { - char c = s[pos + size - n - 1]; + for (unsigned int n = 0; n < rest.size(); ++n) { + char c = rest[rest.size() - n - 1]; unsigned char digit; for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */ if (base32Chars[digit] == c) break; if (digit >= 32) - throw BadHash("invalid base-32 hash '%s'", s); + throw BadHash("invalid base-32 hash '%s'", rest); unsigned int b = n * 5; unsigned int i = b / 8; unsigned int j = b % 8; @@ -200,21 +242,21 @@ Hash::Hash(std::string_view s, std::optional type) hash[i + 1] |= digit >> (8 - j); } else { if (digit >> (8 - j)) - throw BadHash("invalid base-32 hash '%s'", s); + throw BadHash("invalid base-32 hash '%s'", rest); } } } - else if (isSRI || size == base64Len()) { - auto d = base64Decode(s.substr(pos)); + else if (isSRI || rest.size() == base64Len()) { + auto d = base64Decode(rest); if (d.size() != hashSize) - throw BadHash("invalid %s hash '%s'", isSRI ? "SRI" : "base-64", s); + throw BadHash("invalid %s hash '%s'", isSRI ? "SRI" : "base-64", rest); assert(hashSize); memcpy(hash, d.data(), hashSize); } else - throw BadHash("hash '%s' has wrong length for hash type '%s'", s, printHashType(*type)); + throw BadHash("hash '%s' has wrong length for hash type '%s'", rest, printHashType(this->type)); } Hash newHashAllowEmpty(std::string hashStr, std::optional ht) @@ -226,7 +268,7 @@ Hash newHashAllowEmpty(std::string hashStr, std::optional ht) warn("found empty hash, assuming '%s'", h.to_string(SRI, true)); return h; } else - return Hash(hashStr, ht); + return Hash::parseAny(hashStr, ht); } @@ -267,7 +309,7 @@ static void finish(HashType ht, Ctx & ctx, unsigned char * hash) } -Hash hashString(HashType ht, const string & s) +Hash hashString(HashType ht, std::string_view s) { Ctx ctx; Hash hash(ht); @@ -334,7 +376,7 @@ HashResult hashPath( Hash compressHash(const Hash & hash, unsigned int newSize) { - Hash h; + Hash h(hash.type); h.hashSize = newSize; for (unsigned int i = 0; i < hash.hashSize; ++i) h.hash[i % newSize] ^= hash.hash[i]; @@ -342,7 +384,7 @@ Hash compressHash(const Hash & hash, unsigned int newSize) } -std::optional parseHashTypeOpt(const string & s) +std::optional parseHashTypeOpt(std::string_view s) { if (s == "md5") return htMD5; else if (s == "sha1") return htSHA1; @@ -351,7 +393,7 @@ std::optional parseHashTypeOpt(const string & s) else return std::optional {}; } -HashType parseHashType(const string & s) +HashType parseHashType(std::string_view s) { auto opt_h = parseHashTypeOpt(s); if (opt_h) diff --git a/src/libutil/hash.hh b/src/libutil/hash.hh index 23259dced..6d6eb70ca 100644 --- a/src/libutil/hash.hh +++ b/src/libutil/hash.hh @@ -18,6 +18,8 @@ const int sha1HashSize = 20; const int sha256HashSize = 32; const int sha512HashSize = 64; +extern std::set hashTypes; + extern const string base32Chars; enum Base : int { Base64, Base32, Base16, SRI }; @@ -25,34 +27,38 @@ enum Base : int { Base64, Base32, Base16, SRI }; struct Hash { - static const unsigned int maxHashSize = 64; - unsigned int hashSize = 0; - unsigned char hash[maxHashSize] = {}; + constexpr static size_t maxHashSize = 64; + size_t hashSize = 0; + uint8_t hash[maxHashSize] = {}; - std::optional type = {}; - - /* Create an unset hash object. */ - Hash() { }; + HashType type; /* Create a zero-filled hash object. */ - Hash(HashType type) : type(type) { init(); }; + Hash(HashType type); - /* Initialize the hash from a string representation, in the format + /* Parse the hash from a string representation in the format "[:]" or "-" (a Subresource Integrity hash expression). If the 'type' argument is not present, then the hash type must be specified in the string. */ - Hash(std::string_view s, std::optional type); - // type must be provided - Hash(std::string_view s, HashType type); - // hash type must be part of string - Hash(std::string_view s); + static Hash parseAny(std::string_view s, std::optional type); - void init(); + /* Parse a hash from a string representation like the above, except the + type prefix is mandatory is there is no separate arguement. */ + static Hash parseAnyPrefixed(std::string_view s); - /* Check whether a hash is set. */ - operator bool () const { return (bool) type; } + /* Parse a plain hash that musst not have any prefix indicating the type. + The type is passed in to disambiguate. */ + static Hash parseNonSRIUnprefixed(std::string_view s, HashType type); + static Hash parseSRI(std::string_view original); + +private: + /* The type must be provided, the string view must not include + prefix. `isSRI` helps disambigate the various base-* encodings. */ + Hash(std::string_view s, HashType type, bool isSRI); + +public: /* Check whether two hash are equal. */ bool operator == (const Hash & h2) const; @@ -96,6 +102,8 @@ struct Hash assert(type == htSHA1); return std::string(to_string(Base16, false), 0, 7); } + + static Hash dummy; }; /* Helper that defaults empty hashes to the 0 hash. */ @@ -105,14 +113,14 @@ Hash newHashAllowEmpty(std::string hashStr, std::optional ht); string printHash16or32(const Hash & hash); /* Compute the hash of the given string. */ -Hash hashString(HashType ht, const string & s); +Hash hashString(HashType ht, std::string_view s); /* Compute the hash of the given file. */ Hash hashFile(HashType ht, const Path & path); /* Compute the hash of the given path. The hash is defined as (essentially) hashString(ht, dumpPath(path)). */ -typedef std::pair HashResult; +typedef std::pair HashResult; HashResult hashPath(HashType ht, const Path & path, PathFilter & filter = defaultPathFilter); @@ -121,9 +129,10 @@ HashResult hashPath(HashType ht, const Path & path, Hash compressHash(const Hash & hash, unsigned int newSize); /* Parse a string representing a hash type. */ -HashType parseHashType(const string & s); +HashType parseHashType(std::string_view s); + /* Will return nothing on parse error */ -std::optional parseHashTypeOpt(const string & s); +std::optional parseHashTypeOpt(std::string_view s); /* And the reverse. */ string printHashType(HashType ht); @@ -141,7 +150,7 @@ class HashSink : public BufferedSink, public AbstractHashSink private: HashType ht; Ctx * ctx; - unsigned long long bytes; + uint64_t bytes; public: HashSink(HashType ht); diff --git a/src/libutil/istringstream_nocopy.hh b/src/libutil/istringstream_nocopy.hh deleted file mode 100644 index f7beac578..000000000 --- a/src/libutil/istringstream_nocopy.hh +++ /dev/null @@ -1,92 +0,0 @@ -/* This file provides a variant of std::istringstream that doesn't - copy its string argument. This is useful for large strings. The - caller must ensure that the string object is not destroyed while - it's referenced by this object. */ - -#pragma once - -#include -#include - -template , class Allocator = std::allocator> -class basic_istringbuf_nocopy : public std::basic_streambuf -{ -public: - typedef std::basic_string string_type; - - typedef typename std::basic_streambuf::off_type off_type; - - typedef typename std::basic_streambuf::pos_type pos_type; - - typedef typename std::basic_streambuf::int_type int_type; - - typedef typename std::basic_streambuf::traits_type traits_type; - -private: - const string_type & s; - - off_type off; - -public: - basic_istringbuf_nocopy(const string_type & s) : s{s}, off{0} - { - } - -private: - pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) - { - if (which & std::ios_base::in) { - this->off = dir == std::ios_base::beg - ? off - : (dir == std::ios_base::end - ? s.size() + off - : this->off + off); - } - return pos_type(this->off); - } - - pos_type seekpos(pos_type pos, std::ios_base::openmode which) - { - return seekoff(pos, std::ios_base::beg, which); - } - - std::streamsize showmanyc() - { - return s.size() - off; - } - - int_type underflow() - { - if (typename string_type::size_type(off) == s.size()) - return traits_type::eof(); - return traits_type::to_int_type(s[off]); - } - - int_type uflow() - { - if (typename string_type::size_type(off) == s.size()) - return traits_type::eof(); - return traits_type::to_int_type(s[off++]); - } - - int_type pbackfail(int_type ch) - { - if (off == 0 || (ch != traits_type::eof() && ch != s[off - 1])) - return traits_type::eof(); - - return traits_type::to_int_type(s[--off]); - } - -}; - -template , class Allocator = std::allocator> -class basic_istringstream_nocopy : public std::basic_iostream -{ - typedef basic_istringbuf_nocopy buf_type; - buf_type buf; -public: - basic_istringstream_nocopy(const typename buf_type::string_type & s) : - std::basic_iostream(&buf), buf(s) {}; -}; - -typedef basic_istringstream_nocopy istringstream_nocopy; diff --git a/src/libutil/logging.cc b/src/libutil/logging.cc index 90c6afe81..8a6752e22 100644 --- a/src/libutil/logging.cc +++ b/src/libutil/logging.cc @@ -10,7 +10,7 @@ namespace nix { LoggerSettings loggerSettings; -static GlobalConfig::Register r1(&loggerSettings); +static GlobalConfig::Register rLoggerSettings(&loggerSettings); static thread_local ActivityId curActivity = 0; @@ -81,7 +81,6 @@ public: log(ei.level, oss.str()); } - void startActivity(ActivityId act, Verbosity lvl, ActivityType type, const std::string & s, const Fields & fields, ActivityId parent) @@ -185,6 +184,33 @@ struct JSONLogger : Logger { json["action"] = "msg"; json["level"] = ei.level; json["msg"] = oss.str(); + json["raw_msg"] = ei.hint->str(); + + if (ei.errPos.has_value() && (*ei.errPos)) { + json["line"] = ei.errPos->line; + json["column"] = ei.errPos->column; + json["file"] = ei.errPos->file; + } else { + json["line"] = nullptr; + json["column"] = nullptr; + json["file"] = nullptr; + } + + if (loggerSettings.showTrace.get() && !ei.traces.empty()) { + nlohmann::json traces = nlohmann::json::array(); + for (auto iter = ei.traces.rbegin(); iter != ei.traces.rend(); ++iter) { + nlohmann::json stackFrame; + stackFrame["raw_msg"] = iter->hint.str(); + if (iter->pos.has_value() && (*iter->pos)) { + stackFrame["line"] = iter->pos->line; + stackFrame["column"] = iter->pos->column; + stackFrame["file"] = iter->pos->file; + } + traces.push_back(stackFrame); + } + + json["trace"] = traces; + } write(json); } diff --git a/src/libutil/logging.hh b/src/libutil/logging.hh index 09619aac6..63cb2b268 100644 --- a/src/libutil/logging.hh +++ b/src/libutil/logging.hh @@ -37,10 +37,12 @@ typedef uint64_t ActivityId; struct LoggerSettings : Config { - Setting showTrace{this, - false, - "show-trace", - "Whether to show a stack trace on evaluation errors."}; + Setting showTrace{ + this, false, "show-trace", + R"( + Where Nix should print out a stack trace in case of Nix + expression evaluation errors. + )"}; }; extern LoggerSettings loggerSettings; diff --git a/src/libutil/serialise.cc b/src/libutil/serialise.cc index c8b71188f..5c9f6f901 100644 --- a/src/libutil/serialise.cc +++ b/src/libutil/serialise.cc @@ -93,7 +93,7 @@ void Source::operator () (unsigned char * data, size_t len) } -std::string Source::drain() +void Source::drainInto(Sink & sink) { std::string s; std::vector buf(8192); @@ -101,12 +101,19 @@ std::string Source::drain() size_t n; try { n = read(buf.data(), buf.size()); - s.append((char *) buf.data(), n); + sink(buf.data(), n); } catch (EndOfFile &) { break; } } - return s; +} + + +std::string Source::drain() +{ + StringSink s; + drainInto(s); + return *s.s; } @@ -259,6 +266,24 @@ Sink & operator << (Sink & sink, const StringSet & s) return sink; } +Sink & operator << (Sink & sink, const Error & ex) +{ + auto info = ex.info(); + sink + << "Error" + << info.level + << info.name + << info.description + << (info.hint ? info.hint->str() : "") + << 0 // FIXME: info.errPos + << info.traces.size(); + for (auto & trace : info.traces) { + sink << 0; // FIXME: trace.pos + sink << trace.hint.str(); + } + return sink; +} + void readPadding(size_t len, Source & source) { @@ -312,6 +337,30 @@ template Paths readStrings(Source & source); template PathSet readStrings(Source & source); +Error readError(Source & source) +{ + auto type = readString(source); + assert(type == "Error"); + ErrorInfo info; + info.level = (Verbosity) readInt(source); + info.name = readString(source); + info.description = readString(source); + auto hint = readString(source); + if (hint != "") info.hint = hintformat(std::move(format("%s") % hint)); + auto havePos = readNum(source); + assert(havePos == 0); + auto nrTraces = readNum(source); + for (size_t i = 0; i < nrTraces; ++i) { + havePos = readNum(source); + assert(havePos == 0); + info.traces.push_back(Trace { + .hint = hintformat(std::move(format("%s") % readString(source))) + }); + } + return Error(std::move(info)); +} + + void StringSink::operator () (const unsigned char * data, size_t len) { static bool warned = false; @@ -322,5 +371,18 @@ void StringSink::operator () (const unsigned char * data, size_t len) s->append((const char *) data, len); } +size_t ChainSource::read(unsigned char * data, size_t len) +{ + if (useSecond) { + return source2.read(data, len); + } else { + try { + return source1.read(data, len); + } catch (EndOfFile &) { + useSecond = true; + return this->read(data, len); + } + } +} } diff --git a/src/libutil/serialise.hh b/src/libutil/serialise.hh index a04118512..d7fe0b81e 100644 --- a/src/libutil/serialise.hh +++ b/src/libutil/serialise.hh @@ -22,8 +22,15 @@ struct Sink } }; +/* Just throws away data. */ +struct NullSink : Sink +{ + void operator () (const unsigned char * data, size_t len) override + { } +}; -/* A buffered abstract sink. */ +/* A buffered abstract sink. Warning: a BufferedSink should not be + used from multiple threads concurrently. */ struct BufferedSink : virtual Sink { size_t bufSize, bufPos; @@ -62,11 +69,14 @@ struct Source virtual bool good() { return true; } + void drainInto(Sink & sink); + std::string drain(); }; -/* A buffered abstract source. */ +/* A buffered abstract source. Warning: a BufferedSource should not be + used from multiple threads concurrently. */ struct BufferedSource : Source { size_t bufSize, bufPosIn, bufPosOut; @@ -166,17 +176,30 @@ struct StringSource : Source }; -/* Adapter class of a Source that saves all data read to `s'. */ +/* A sink that writes all incoming data to two other sinks. */ +struct TeeSink : Sink +{ + Sink & sink1, & sink2; + TeeSink(Sink & sink1, Sink & sink2) : sink1(sink1), sink2(sink2) { } + virtual void operator () (const unsigned char * data, size_t len) + { + sink1(data, len); + sink2(data, len); + } +}; + + +/* Adapter class of a Source that saves all data read to a sink. */ struct TeeSource : Source { Source & orig; - ref data; - TeeSource(Source & orig) - : orig(orig), data(make_ref()) { } + Sink & sink; + TeeSource(Source & orig, Sink & sink) + : orig(orig), sink(sink) { } size_t read(unsigned char * data, size_t len) { size_t n = orig.read(data, len); - this->data->append((const char *) data, n); + sink(data, n); return n; } }; @@ -212,6 +235,17 @@ struct SizedSource : Source } }; +/* A sink that that just counts the number of bytes given to it */ +struct LengthSink : Sink +{ + uint64_t length = 0; + + virtual void operator () (const unsigned char * _, size_t len) + { + length += len; + } +}; + /* Convert a function into a sink. */ struct LambdaSink : Sink { @@ -243,6 +277,19 @@ struct LambdaSource : Source } }; +/* Chain two sources together so after the first is exhausted, the second is + used */ +struct ChainSource : Source +{ + Source & source1, & source2; + bool useSecond = false; + ChainSource(Source & s1, Source & s2) + : source1(s1), source2(s2) + { } + + size_t read(unsigned char * data, size_t len) override; +}; + /* Convert a function that feeds data into a Sink into a Source. The Source executes the function as a coroutine. */ @@ -274,6 +321,7 @@ inline Sink & operator << (Sink & sink, uint64_t n) Sink & operator << (Sink & sink, const string & s); Sink & operator << (Sink & sink, const Strings & s); Sink & operator << (Sink & sink, const StringSet & s); +Sink & operator << (Sink & in, const Error & ex); MakeError(SerialisationError, Error); @@ -286,16 +334,16 @@ T readNum(Source & source) source(buf, sizeof(buf)); uint64_t n = - ((unsigned long long) buf[0]) | - ((unsigned long long) buf[1] << 8) | - ((unsigned long long) buf[2] << 16) | - ((unsigned long long) buf[3] << 24) | - ((unsigned long long) buf[4] << 32) | - ((unsigned long long) buf[5] << 40) | - ((unsigned long long) buf[6] << 48) | - ((unsigned long long) buf[7] << 56); + ((uint64_t) buf[0]) | + ((uint64_t) buf[1] << 8) | + ((uint64_t) buf[2] << 16) | + ((uint64_t) buf[3] << 24) | + ((uint64_t) buf[4] << 32) | + ((uint64_t) buf[5] << 40) | + ((uint64_t) buf[6] << 48) | + ((uint64_t) buf[7] << 56); - if (n > std::numeric_limits::max()) + if (n > (uint64_t)std::numeric_limits::max()) throw SerialisationError("serialised integer %d is too large for type '%s'", n, typeid(T).name()); return (T) n; @@ -335,5 +383,119 @@ Source & operator >> (Source & in, bool & b) return in; } +Error readError(Source & source); + + +/* An adapter that converts a std::basic_istream into a source. */ +struct StreamToSourceAdapter : Source +{ + std::shared_ptr> istream; + + StreamToSourceAdapter(std::shared_ptr> istream) + : istream(istream) + { } + + size_t read(unsigned char * data, size_t len) override + { + if (!istream->read((char *) data, len)) { + if (istream->eof()) { + if (istream->gcount() == 0) + throw EndOfFile("end of file"); + } else + throw Error("I/O error in StreamToSourceAdapter"); + } + return istream->gcount(); + } +}; + + +/* A source that reads a distinct format of concatenated chunks back into its + logical form, in order to guarantee a known state to the original stream, + even in the event of errors. + + Use with FramedSink, which also allows the logical stream to be terminated + in the event of an exception. +*/ +struct FramedSource : Source +{ + Source & from; + bool eof = false; + std::vector pending; + size_t pos = 0; + + FramedSource(Source & from) : from(from) + { } + + ~FramedSource() + { + if (!eof) { + while (true) { + auto n = readInt(from); + if (!n) break; + std::vector data(n); + from(data.data(), n); + } + } + } + + size_t read(unsigned char * data, size_t len) override + { + if (eof) throw EndOfFile("reached end of FramedSource"); + + if (pos >= pending.size()) { + size_t len = readInt(from); + if (!len) { + eof = true; + return 0; + } + pending = std::vector(len); + pos = 0; + from(pending.data(), len); + } + + auto n = std::min(len, pending.size() - pos); + memcpy(data, pending.data() + pos, n); + pos += n; + return n; + } +}; + +/* Write as chunks in the format expected by FramedSource. + + The exception_ptr reference can be used to terminate the stream when you + detect that an error has occurred on the remote end. +*/ +struct FramedSink : nix::BufferedSink +{ + BufferedSink & to; + std::exception_ptr & ex; + + FramedSink(BufferedSink & to, std::exception_ptr & ex) : to(to), ex(ex) + { } + + ~FramedSink() + { + try { + to << 0; + to.flush(); + } catch (...) { + ignoreException(); + } + } + + void write(const unsigned char * data, size_t len) override + { + /* Don't send more data if the remote has + encountered an error. */ + if (ex) { + auto ex2 = ex; + ex = nullptr; + std::rethrow_exception(ex2); + } + to << len; + to(data, len); + }; +}; + } diff --git a/src/libutil/split.hh b/src/libutil/split.hh new file mode 100644 index 000000000..87a23b13e --- /dev/null +++ b/src/libutil/split.hh @@ -0,0 +1,33 @@ +#pragma once + +#include +#include + +#include "util.hh" + +namespace nix { + +// If `separator` is found, we return the portion of the string before the +// separator, and modify the string argument to contain only the part after the +// separator. Otherwise, we return `std::nullopt`, and we leave the argument +// string alone. +static inline std::optional splitPrefixTo(std::string_view & string, char separator) { + auto sepInstance = string.find(separator); + + if (sepInstance != std::string_view::npos) { + auto prefix = string.substr(0, sepInstance); + string.remove_prefix(sepInstance+1); + return prefix; + } + + return std::nullopt; +} + +static inline bool splitPrefix(std::string_view & string, std::string_view prefix) { + bool res = hasPrefix(string, prefix); + if (res) + string.remove_prefix(prefix.length()); + return res; +} + +} diff --git a/src/libutil/tests/config.cc b/src/libutil/tests/config.cc index 74c59fd31..c7777a21f 100644 --- a/src/libutil/tests/config.cc +++ b/src/libutil/tests/config.cc @@ -1,9 +1,9 @@ -#include "json.hh" #include "config.hh" #include "args.hh" #include #include +#include namespace nix { @@ -33,7 +33,7 @@ namespace nix { const auto iter = settings.find("name-of-the-setting"); ASSERT_NE(iter, settings.end()); ASSERT_EQ(iter->second.value, ""); - ASSERT_EQ(iter->second.description, "description"); + ASSERT_EQ(iter->second.description, "description\n"); } TEST(Config, getDefinedOverridenSettingNotSet) { @@ -59,7 +59,7 @@ namespace nix { const auto iter = settings.find("name-of-the-setting"); ASSERT_NE(iter, settings.end()); ASSERT_EQ(iter->second.value, "value"); - ASSERT_EQ(iter->second.description, "description"); + ASSERT_EQ(iter->second.description, "description\n"); } TEST(Config, getDefinedSettingSet2) { @@ -73,7 +73,7 @@ namespace nix { const auto e = settings.find("name-of-the-setting"); ASSERT_NE(e, settings.end()); ASSERT_EQ(e->second.value, "value"); - ASSERT_EQ(e->second.description, "description"); + ASSERT_EQ(e->second.description, "description\n"); } TEST(Config, addSetting) { @@ -152,29 +152,16 @@ namespace nix { } TEST(Config, toJSONOnEmptyConfig) { - std::stringstream out; - { // Scoped to force the destructor of JSONObject to write the final `}` - JSONObject obj(out); - Config config; - config.toJSON(obj); - } - - ASSERT_EQ(out.str(), "{}"); + ASSERT_EQ(Config().toJSON().dump(), "{}"); } TEST(Config, toJSONOnNonEmptyConfig) { - std::stringstream out; - { // Scoped to force the destructor of JSONObject to write the final `}` - JSONObject obj(out); + Config config; + std::map settings; + Setting setting{&config, "", "name-of-the-setting", "description"}; + setting.assign("value"); - Config config; - std::map settings; - Setting setting{&config, "", "name-of-the-setting", "description"}; - setting.assign("value"); - - config.toJSON(obj); - } - ASSERT_EQ(out.str(), R"#({"name-of-the-setting":{"description":"description","value":"value"}})#"); + ASSERT_EQ(config.toJSON().dump(), R"#({"name-of-the-setting":{"aliases":[],"defaultValue":"","description":"description\n","value":"value"}})#"); } TEST(Config, setSettingAlias) { diff --git a/src/libutil/tests/logging.cc b/src/libutil/tests/logging.cc index ef22e9966..7e53f17c6 100644 --- a/src/libutil/tests/logging.cc +++ b/src/libutil/tests/logging.cc @@ -34,6 +34,24 @@ namespace nix { } } + TEST(logEI, jsonOutput) { + SymbolTable testTable; + auto problem_file = testTable.create("random.nix"); + testing::internal::CaptureStderr(); + + makeJSONLogger(*logger)->logEI({ + .name = "error name", + .description = "error without any code lines.", + .hint = hintfmt("this hint has %1% templated %2%!!", + "yellow", + "values"), + .errPos = Pos(foFile, problem_file, 02, 13) + }); + + auto str = testing::internal::GetCapturedStderr(); + ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- SysError --- error-unit-test\x1B[0m\nopening file '\x1B[33;1mrandom.nix\x1B[0m': \x1B[33;1mNo such file or directory\x1B[0m\n@nix {\"action\":\"msg\",\"column\":13,\"file\":\"random.nix\",\"level\":0,\"line\":2,\"msg\":\"\\u001b[31;1merror:\\u001b[0m\\u001b[34;1m --- error name --- error-unit-test\\u001b[0m\\n\\u001b[34;1mat: \\u001b[33;1m(2:13)\\u001b[34;1m in file: \\u001b[0mrandom.nix\\n\\nerror without any code lines.\\n\\nthis hint has \\u001b[33;1myellow\\u001b[0m templated \\u001b[33;1mvalues\\u001b[0m!!\",\"raw_msg\":\"this hint has \\u001b[33;1myellow\\u001b[0m templated \\u001b[33;1mvalues\\u001b[0m!!\"}\n"); + } + TEST(logEI, appendingHintsToPreviousError) { MakeError(TestError, Error); @@ -251,18 +269,19 @@ namespace nix { TEST(addTrace, showTracesWithShowTrace) { SymbolTable testTable; auto problem_file = testTable.create(test_file); - auto oneliner_file = testTable.create(one_liner); + auto invalidfilename = testTable.create("invalid filename"); auto e = AssertionError(ErrorInfo { .name = "wat", - .description = "a well-known problem occurred", + .description = "show-traces", .hint = hintfmt("it has been %1% days since our last error", "zero"), .errPos = Pos(foString, problem_file, 2, 13), }); e.addTrace(Pos(foStdin, oneliner_file, 1, 19), "while trying to compute %1%", 42); e.addTrace(std::nullopt, "while doing something without a %1%", "pos"); + e.addTrace(Pos(foFile, invalidfilename, 100, 1), "missing %s", "nix file"); testing::internal::CaptureStderr(); @@ -271,24 +290,25 @@ namespace nix { logError(e.info()); auto str = testing::internal::GetCapturedStderr(); - ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- AssertionError --- error-unit-test\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(2:13)\x1B[34;1m from string\x1B[0m\n\na well-known problem occurred\n\n 1| previous line of code\n 2| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n 3| next line of code\n\nit has been \x1B[33;1mzero\x1B[0m days since our last error\n\x1B[34;1m---- show-trace ----\x1B[0m\n\x1B[34;1mtrace: \x1B[0mwhile trying to compute \x1B[33;1m42\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(1:19)\x1B[34;1m from stdin\x1B[0m\n\n 1| this is the other problem line of code\n | \x1B[31;1m^\x1B[0m\n\n\x1B[34;1mtrace: \x1B[0mwhile doing something without a \x1B[33;1mpos\x1B[0m\n"); + ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- SysError --- error-unit-test\x1B[0m\nopening file '\x1B[33;1minvalid filename\x1B[0m': \x1B[33;1mNo such file or directory\x1B[0m\n\x1B[31;1merror:\x1B[0m\x1B[34;1m --- AssertionError --- error-unit-test\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(2:13)\x1B[34;1m from string\x1B[0m\n\nshow-traces\n\n 1| previous line of code\n 2| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n 3| next line of code\n\nit has been \x1B[33;1mzero\x1B[0m days since our last error\n\x1B[34;1m---- show-trace ----\x1B[0m\n\x1B[34;1mtrace: \x1B[0mwhile trying to compute \x1B[33;1m42\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(1:19)\x1B[34;1m from stdin\x1B[0m\n\n 1| this is the other problem line of code\n | \x1B[31;1m^\x1B[0m\n\n\x1B[34;1mtrace: \x1B[0mwhile doing something without a \x1B[33;1mpos\x1B[0m\n\x1B[34;1mtrace: \x1B[0mmissing \x1B[33;1mnix file\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(100:1)\x1B[34;1m in file: \x1B[0minvalid filename\n"); } TEST(addTrace, hideTracesWithoutShowTrace) { SymbolTable testTable; auto problem_file = testTable.create(test_file); - auto oneliner_file = testTable.create(one_liner); + auto invalidfilename = testTable.create("invalid filename"); auto e = AssertionError(ErrorInfo { .name = "wat", - .description = "a well-known problem occurred", + .description = "hide traces", .hint = hintfmt("it has been %1% days since our last error", "zero"), .errPos = Pos(foString, problem_file, 2, 13), }); e.addTrace(Pos(foStdin, oneliner_file, 1, 19), "while trying to compute %1%", 42); e.addTrace(std::nullopt, "while doing something without a %1%", "pos"); + e.addTrace(Pos(foFile, invalidfilename, 100, 1), "missing %s", "nix file"); testing::internal::CaptureStderr(); @@ -297,9 +317,10 @@ namespace nix { logError(e.info()); auto str = testing::internal::GetCapturedStderr(); - ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- AssertionError --- error-unit-test\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(2:13)\x1B[34;1m from string\x1B[0m\n\na well-known problem occurred\n\n 1| previous line of code\n 2| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n 3| next line of code\n\nit has been \x1B[33;1mzero\x1B[0m days since our last error\n"); + ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- AssertionError --- error-unit-test\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(2:13)\x1B[34;1m from string\x1B[0m\n\nhide traces\n\n 1| previous line of code\n 2| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n 3| next line of code\n\nit has been \x1B[33;1mzero\x1B[0m days since our last error\n"); } + /* ---------------------------------------------------------------------------- * hintfmt * --------------------------------------------------------------------------*/ diff --git a/src/libutil/topo-sort.hh b/src/libutil/topo-sort.hh new file mode 100644 index 000000000..7418be5e0 --- /dev/null +++ b/src/libutil/topo-sort.hh @@ -0,0 +1,42 @@ +#pragma once + +#include "error.hh" + +namespace nix { + +template +std::vector topoSort(std::set items, + std::function(const T &)> getChildren, + std::function makeCycleError) +{ + std::vector sorted; + std::set visited, parents; + + std::function dfsVisit; + + dfsVisit = [&](const T & path, const T * parent) { + if (parents.count(path)) throw makeCycleError(path, *parent); + + if (!visited.insert(path).second) return; + parents.insert(path); + + std::set references = getChildren(path); + + for (auto & i : references) + /* Don't traverse into items that don't exist in our starting set. */ + if (i != path && items.count(i)) + dfsVisit(i, &path); + + sorted.push_back(path); + parents.erase(path); + }; + + for (auto & i : items) + dfsVisit(i, nullptr); + + std::reverse(sorted.begin(), sorted.end()); + + return sorted; +} + +} diff --git a/src/libutil/types.hh b/src/libutil/types.hh index 3af485fa0..55d02bcf9 100644 --- a/src/libutil/types.hh +++ b/src/libutil/types.hh @@ -24,6 +24,8 @@ typedef string Path; typedef list Paths; typedef set PathSet; +typedef vector> Headers; + /* Helper class to run code at startup. */ template struct OnStartup diff --git a/src/libutil/url-parts.hh b/src/libutil/url-parts.hh new file mode 100644 index 000000000..68be15cb0 --- /dev/null +++ b/src/libutil/url-parts.hh @@ -0,0 +1,44 @@ +#pragma once + +#include +#include + +namespace nix { + +// URI stuff. +const static std::string pctEncoded = "(?:%[0-9a-fA-F][0-9a-fA-F])"; +const static std::string schemeRegex = "(?:[a-z][a-z0-9+.-]*)"; +const static std::string ipv6AddressRegex = "(?:\\[[0-9a-fA-F:]+\\])"; +const static std::string unreservedRegex = "(?:[a-zA-Z0-9-._~])"; +const static std::string subdelimsRegex = "(?:[!$&'\"()*+,;=])"; +const static std::string hostnameRegex = "(?:(?:" + unreservedRegex + "|" + pctEncoded + "|" + subdelimsRegex + ")*)"; +const static std::string hostRegex = "(?:" + ipv6AddressRegex + "|" + hostnameRegex + ")"; +const static std::string userRegex = "(?:(?:" + unreservedRegex + "|" + pctEncoded + "|" + subdelimsRegex + "|:)*)"; +const static std::string authorityRegex = "(?:" + userRegex + "@)?" + hostRegex + "(?::[0-9]+)?"; +const static std::string pcharRegex = "(?:" + unreservedRegex + "|" + pctEncoded + "|" + subdelimsRegex + "|[:@])"; +const static std::string queryRegex = "(?:" + pcharRegex + "|[/? \"])*"; +const static std::string segmentRegex = "(?:" + pcharRegex + "+)"; +const static std::string absPathRegex = "(?:(?:/" + segmentRegex + ")*/?)"; +const static std::string pathRegex = "(?:" + segmentRegex + "(?:/" + segmentRegex + ")*/?)"; + +// A Git ref (i.e. branch or tag name). +const static std::string refRegexS = "[a-zA-Z0-9][a-zA-Z0-9_.-]*"; // FIXME: check +extern std::regex refRegex; + +// Instead of defining what a good Git Ref is, we define what a bad Git Ref is +// This is because of the definition of a ref in refs.c in https://github.com/git/git +// See tests/fetchGitRefs.sh for the full definition +const static std::string badGitRefRegexS = "//|^[./]|/\\.|\\.\\.|[[:cntrl:][:space:]:?^~\[]|\\\\|\\*|\\.lock$|\\.lock/|@\\{|[/.]$|^@$|^$"; +extern std::regex badGitRefRegex; + +// A Git revision (a SHA-1 commit hash). +const static std::string revRegexS = "[0-9a-fA-F]{40}"; +extern std::regex revRegex; + +// A ref or revision, or a ref followed by a revision. +const static std::string refAndOrRevRegex = "(?:(" + revRegexS + ")|(?:(" + refRegexS + ")(?:/(" + revRegexS + "))?))"; + +const static std::string flakeIdRegexS = "[a-zA-Z][a-zA-Z0-9_-]*"; +extern std::regex flakeIdRegex; + +} diff --git a/src/libutil/url.cc b/src/libutil/url.cc index 88c09eef9..c1bab866c 100644 --- a/src/libutil/url.cc +++ b/src/libutil/url.cc @@ -1,4 +1,5 @@ #include "url.hh" +#include "url-parts.hh" #include "util.hh" namespace nix { diff --git a/src/libutil/url.hh b/src/libutil/url.hh index 2ef88ef2a..6e77142e3 100644 --- a/src/libutil/url.hh +++ b/src/libutil/url.hh @@ -2,8 +2,6 @@ #include "error.hh" -#include - namespace nix { struct ParsedURL @@ -29,40 +27,4 @@ std::map decodeQuery(const std::string & query); ParsedURL parseURL(const std::string & url); -// URI stuff. -const static std::string pctEncoded = "(?:%[0-9a-fA-F][0-9a-fA-F])"; -const static std::string schemeRegex = "(?:[a-z+]+)"; -const static std::string ipv6AddressRegex = "(?:\\[[0-9a-fA-F:]+\\])"; -const static std::string unreservedRegex = "(?:[a-zA-Z0-9-._~])"; -const static std::string subdelimsRegex = "(?:[!$&'\"()*+,;=])"; -const static std::string hostnameRegex = "(?:(?:" + unreservedRegex + "|" + pctEncoded + "|" + subdelimsRegex + ")*)"; -const static std::string hostRegex = "(?:" + ipv6AddressRegex + "|" + hostnameRegex + ")"; -const static std::string userRegex = "(?:(?:" + unreservedRegex + "|" + pctEncoded + "|" + subdelimsRegex + "|:)*)"; -const static std::string authorityRegex = "(?:" + userRegex + "@)?" + hostRegex + "(?::[0-9]+)?"; -const static std::string pcharRegex = "(?:" + unreservedRegex + "|" + pctEncoded + "|" + subdelimsRegex + "|[:@])"; -const static std::string queryRegex = "(?:" + pcharRegex + "|[/? \"])*"; -const static std::string segmentRegex = "(?:" + pcharRegex + "+)"; -const static std::string absPathRegex = "(?:(?:/" + segmentRegex + ")*/?)"; -const static std::string pathRegex = "(?:" + segmentRegex + "(?:/" + segmentRegex + ")*/?)"; - -// A Git ref (i.e. branch or tag name). -const static std::string refRegexS = "[a-zA-Z0-9][a-zA-Z0-9_.-]*"; // FIXME: check -extern std::regex refRegex; - -// Instead of defining what a good Git Ref is, we define what a bad Git Ref is -// This is because of the definition of a ref in refs.c in https://github.com/git/git -// See tests/fetchGitRefs.sh for the full definition -const static std::string badGitRefRegexS = "//|^[./]|/\\.|\\.\\.|[[:cntrl:][:space:]:?^~\[]|\\\\|\\*|\\.lock$|\\.lock/|@\\{|[/.]$|^@$|^$"; -extern std::regex badGitRefRegex; - -// A Git revision (a SHA-1 commit hash). -const static std::string revRegexS = "[0-9a-fA-F]{40}"; -extern std::regex revRegex; - -// A ref or revision, or a ref followed by a revision. -const static std::string refAndOrRevRegex = "(?:(" + revRegexS + ")|(?:(" + refRegexS + ")(?:/(" + revRegexS + "))?))"; - -const static std::string flakeIdRegexS = "[a-zA-Z][a-zA-Z0-9_-]*"; -extern std::regex flakeIdRegex; - } diff --git a/src/libutil/util.cc b/src/libutil/util.cc index 1268b146a..f07e99885 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -79,7 +80,7 @@ void replaceEnv(std::map newEnv) } -Path absPath(Path path, std::optional dir) +Path absPath(Path path, std::optional dir, bool resolveSymlinks) { if (path[0] != '/') { if (!dir) { @@ -100,7 +101,7 @@ Path absPath(Path path, std::optional dir) } path = *dir + "/" + path; } - return canonPath(path); + return canonPath(path, resolveSymlinks); } @@ -345,7 +346,6 @@ void writeFile(const Path & path, Source & source, mode_t mode) } } - string readLine(int fd) { string s; @@ -374,7 +374,7 @@ void writeLine(int fd, string s) } -static void _deletePath(int parentfd, const Path & path, unsigned long long & bytesFreed) +static void _deletePath(int parentfd, const Path & path, uint64_t & bytesFreed) { checkInterrupt(); @@ -414,7 +414,7 @@ static void _deletePath(int parentfd, const Path & path, unsigned long long & by } } -static void _deletePath(const Path & path, unsigned long long & bytesFreed) +static void _deletePath(const Path & path, uint64_t & bytesFreed) { Path dir = dirOf(path); if (dir == "") @@ -435,12 +435,12 @@ static void _deletePath(const Path & path, unsigned long long & bytesFreed) void deletePath(const Path & path) { - unsigned long long dummy; + uint64_t dummy; deletePath(path, dummy); } -void deletePath(const Path & path, unsigned long long & bytesFreed) +void deletePath(const Path & path, uint64_t & bytesFreed) { //Activity act(*logger, lvlDebug, format("recursively deleting path '%1%'") % path); bytesFreed = 0; @@ -494,6 +494,7 @@ std::pair createTempFile(const Path & prefix) { Path tmpl(getEnv("TMPDIR").value_or("/tmp") + "/" + prefix + ".XXXXXX"); // Strictly speaking, this is UB, but who cares... + // FIXME: use O_TMPFILE. AutoCloseFD fd(mkstemp((char *) tmpl.c_str())); if (!fd) throw SysError("creating temporary file '%s'", tmpl); @@ -581,20 +582,31 @@ Paths createDirs(const Path & path) } -void createSymlink(const Path & target, const Path & link) +void createSymlink(const Path & target, const Path & link, + std::optional mtime) { if (symlink(target.c_str(), link.c_str())) throw SysError("creating symlink from '%1%' to '%2%'", link, target); + if (mtime) { + struct timeval times[2]; + times[0].tv_sec = *mtime; + times[0].tv_usec = 0; + times[1].tv_sec = *mtime; + times[1].tv_usec = 0; + if (lutimes(link.c_str(), times)) + throw SysError("setting time of symlink '%s'", link); + } } -void replaceSymlink(const Path & target, const Path & link) +void replaceSymlink(const Path & target, const Path & link, + std::optional mtime) { for (unsigned int n = 0; true; n++) { Path tmp = canonPath(fmt("%s/.%d_%s", dirOf(link), n, baseNameOf(link))); try { - createSymlink(target, tmp); + createSymlink(target, tmp, mtime); } catch (SysError & e) { if (e.errNo == EEXIST) continue; throw; @@ -1006,12 +1018,14 @@ std::vector stringsToCharPtrs(const Strings & ss) return res; } - +// Output = "standard out" output stream string runProgram(Path program, bool searchPath, const Strings & args, const std::optional & input) { RunOptions opts(program, args); opts.searchPath = searchPath; + // This allows you to refer to a program with a pathname relative to the + // PATH variable. opts.input = input; auto res = runProgram(opts); @@ -1022,6 +1036,7 @@ string runProgram(Path program, bool searchPath, const Strings & args, return res.second; } +// Output = error code + "standard out" output stream std::pair runProgram(const RunOptions & options_) { RunOptions options(options_); @@ -1094,6 +1109,8 @@ void runProgram2(const RunOptions & options) if (options.searchPath) execvp(options.program.c_str(), stringsToCharPtrs(args_).data()); + // This allows you to refer to a program with a pathname relative + // to the PATH variable. else execv(options.program.c_str(), stringsToCharPtrs(args_).data()); @@ -1433,7 +1450,7 @@ string base64Decode(std::string_view s) char digit = decode[(unsigned char) c]; if (digit == -1) - throw Error("invalid character in Base64 string"); + throw Error("invalid character in Base64 string: '%c'", c); bits += 6; d = d << 6 | digit; @@ -1447,6 +1464,47 @@ string base64Decode(std::string_view s) } +std::string stripIndentation(std::string_view s) +{ + size_t minIndent = 10000; + size_t curIndent = 0; + bool atStartOfLine = true; + + for (auto & c : s) { + if (atStartOfLine && c == ' ') + curIndent++; + else if (c == '\n') { + if (atStartOfLine) + minIndent = std::max(minIndent, curIndent); + curIndent = 0; + atStartOfLine = true; + } else { + if (atStartOfLine) { + minIndent = std::min(minIndent, curIndent); + atStartOfLine = false; + } + } + } + + std::string res; + + size_t pos = 0; + while (pos < s.size()) { + auto eol = s.find('\n', pos); + if (eol == s.npos) eol = s.size(); + if (eol - pos > minIndent) + res.append(s.substr(pos + minIndent, eol - pos - minIndent)); + res.push_back('\n'); + pos = eol + 1; + } + + return res; +} + + +////////////////////////////////////////////////////////////////////// + + static Sync> windowSize{{0, 0}}; @@ -1565,7 +1623,7 @@ AutoCloseFD createUnixDomainSocket(const Path & path, mode_t mode) struct sockaddr_un addr; addr.sun_family = AF_UNIX; - if (path.size() >= sizeof(addr.sun_path)) + if (path.size() + 1 >= sizeof(addr.sun_path)) throw Error("socket path '%1%' is too long", path); strcpy(addr.sun_path, path.c_str()); @@ -1583,4 +1641,11 @@ AutoCloseFD createUnixDomainSocket(const Path & path, mode_t mode) return fdSocket; } + +string showBytes(uint64_t bytes) +{ + return fmt("%.2f MiB", bytes / (1024.0 * 1024.0)); +} + + } diff --git a/src/libutil/util.hh b/src/libutil/util.hh index 3641daaec..129d59a97 100644 --- a/src/libutil/util.hh +++ b/src/libutil/util.hh @@ -12,13 +12,9 @@ #include #include -#include -#include #include #include #include -#include -#include #ifndef HAVE_STRUCT_DIRENT_D_TYPE #define DT_UNKNOWN 0 @@ -49,7 +45,9 @@ void clearEnv(); /* Return an absolutized path, resolving paths relative to the specified directory, or the current directory otherwise. The path is also canonicalised. */ -Path absPath(Path path, std::optional dir = {}); +Path absPath(Path path, + std::optional dir = {}, + bool resolveSymlinks = false); /* Canonicalise a path by removing all `.' or `..' components and double or trailing slashes. Optionally resolves all symlink @@ -123,7 +121,7 @@ void writeLine(int fd, string s); second variant returns the number of bytes and blocks freed. */ void deletePath(const Path & path); -void deletePath(const Path & path, unsigned long long & bytesFreed); +void deletePath(const Path & path, uint64_t & bytesFreed); std::string getUserName(); @@ -147,10 +145,12 @@ Path getDataDir(); Paths createDirs(const Path & path); /* Create a symlink. */ -void createSymlink(const Path & target, const Path & link); +void createSymlink(const Path & target, const Path & link, + std::optional mtime = {}); /* Atomically create or replace a symlink. */ -void replaceSymlink(const Path & target, const Path & link); +void replaceSymlink(const Path & target, const Path & link, + std::optional mtime = {}); /* Wrappers arount read()/write() that read/write exactly the @@ -460,6 +460,12 @@ string base64Encode(std::string_view s); string base64Decode(std::string_view s); +/* Remove common leading whitespace from the lines in the string + 's'. For example, if every line is indented by at least 3 spaces, + then we remove 3 spaces from the start of every line. */ +std::string stripIndentation(std::string_view s); + + /* Get a value for the specified key from an associate container. */ template std::optional get(const T & map, const typename T::key_type & key) @@ -470,43 +476,8 @@ std::optional get(const T & map, const typename T::key_ } -/* A callback is a wrapper around a lambda that accepts a valid of - type T or an exception. (We abuse std::future to pass the value or - exception.) */ template -class Callback -{ - std::function)> fun; - std::atomic_flag done = ATOMIC_FLAG_INIT; - -public: - - Callback(std::function)> fun) : fun(fun) { } - - Callback(Callback && callback) : fun(std::move(callback.fun)) - { - auto prev = callback.done.test_and_set(); - if (prev) done.test_and_set(); - } - - void operator()(T && t) noexcept - { - auto prev = done.test_and_set(); - assert(!prev); - std::promise promise; - promise.set_value(std::move(t)); - fun(promise.get_future()); - } - - void rethrow(const std::exception_ptr & exc = std::current_exception()) noexcept - { - auto prev = done.test_and_set(); - assert(!prev); - std::promise promise; - promise.set_exception(exc); - fun(promise.get_future()); - } -}; +class Callback; /* Start a thread that handles various signals. Also block those signals @@ -597,4 +568,12 @@ constexpr auto enumerate(T && iterable) } +// C++17 std::visit boilerplate +template struct overloaded : Ts... { using Ts::operator()...; }; +template overloaded(Ts...) -> overloaded; + + +std::string showBytes(uint64_t bytes); + + } diff --git a/src/nix-build/nix-build.cc b/src/nix-build/nix-build.cc index f77de56ea..a79b1086b 100755 --- a/src/nix-build/nix-build.cc +++ b/src/nix-build/nix-build.cc @@ -67,7 +67,7 @@ std::vector shellwords(const string & s) return res; } -static void _main(int argc, char * * argv) +static void main_nix_build(int argc, char * * argv) { auto dryRun = false; auto runEnv = std::regex_search(argv[0], std::regex("nix-shell$")); @@ -98,8 +98,8 @@ static void _main(int argc, char * * argv) // List of environment variables kept for --pure std::set keepVars{ - "HOME", "USER", "LOGNAME", "DISPLAY", "PATH", "TERM", - "IN_NIX_SHELL", "TZ", "PAGER", "NIX_BUILD_SHELL", "SHLVL", + "HOME", "USER", "LOGNAME", "DISPLAY", "PATH", "TERM", "IN_NIX_SHELL", + "NIX_SHELL_PRESERVE_PROMPT", "TZ", "PAGER", "NIX_BUILD_SHELL", "SHLVL", "http_proxy", "https_proxy", "ftp_proxy", "all_proxy", "no_proxy" }; @@ -174,7 +174,7 @@ static void _main(int argc, char * * argv) else if (*arg == "--run-env") // obsolete runEnv = true; - else if (*arg == "--command" || *arg == "--run") { + else if (runEnv && (*arg == "--command" || *arg == "--run")) { if (*arg == "--run") interactive = false; envCommand = getArg(*arg, arg, end) + "\nexit"; @@ -192,7 +192,7 @@ static void _main(int argc, char * * argv) else if (*arg == "--pure") pure = true; else if (*arg == "--impure") pure = false; - else if (*arg == "--packages" || *arg == "-p") + else if (runEnv && (*arg == "--packages" || *arg == "-p")) packages = true; else if (inShebang && *arg == "-i") { @@ -325,7 +325,7 @@ static void _main(int argc, char * * argv) auto buildPaths = [&](const std::vector & paths) { /* Note: we do this even when !printMissing to efficiently fetch binary cache data. */ - unsigned long long downloadSize, narSize; + uint64_t downloadSize, narSize; StorePathSet willBuild, willSubstitute, unknown; store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); @@ -446,7 +446,7 @@ static void _main(int argc, char * * argv) "PATH=%4%:\"$PATH\"; " "SHELL=%5%; " "set +e; " - R"s([ -n "$PS1" ] && PS1='\n\[\033[1;32m\][nix-shell:\w]\$\[\033[0m\] '; )s" + R"s([ -n "$PS1" -a -z "$NIX_SHELL_PRESERVE_PROMPT" ] && PS1='\n\[\033[1;32m\][nix-shell:\w]\$\[\033[0m\] '; )s" "if [ \"$(type -t runHook)\" = function ]; then runHook shellHook; fi; " "unset NIX_ENFORCE_PURITY; " "shopt -u nullglob; " @@ -487,52 +487,58 @@ static void _main(int argc, char * * argv) std::vector pathsToBuild; - std::map drvPrefixes; - std::map resultSymlinks; - std::vector outPaths; + std::map> drvMap; for (auto & drvInfo : drvs) { - auto drvPath = drvInfo.queryDrvPath(); - auto outPath = drvInfo.queryOutPath(); + auto drvPath = store->parseStorePath(drvInfo.queryDrvPath()); auto outputName = drvInfo.queryOutputName(); if (outputName == "") - throw Error("derivation '%s' lacks an 'outputName' attribute", drvPath); + throw Error("derivation '%s' lacks an 'outputName' attribute", store->printStorePath(drvPath)); - pathsToBuild.push_back({store->parseStorePath(drvPath), {outputName}}); + pathsToBuild.push_back({drvPath, {outputName}}); - std::string drvPrefix; - auto i = drvPrefixes.find(drvPath); - if (i != drvPrefixes.end()) - drvPrefix = i->second; + auto i = drvMap.find(drvPath); + if (i != drvMap.end()) + i->second.second.insert(outputName); else { - drvPrefix = outLink; - if (drvPrefixes.size()) - drvPrefix += fmt("-%d", drvPrefixes.size() + 1); - drvPrefixes[drvPath] = drvPrefix; + drvMap[drvPath] = {drvMap.size(), {outputName}}; } - - std::string symlink = drvPrefix; - if (outputName != "out") symlink += "-" + outputName; - - resultSymlinks[symlink] = outPath; - outPaths.push_back(outPath); } buildPaths(pathsToBuild); if (dryRun) return; - for (auto & symlink : resultSymlinks) - if (auto store2 = store.dynamic_pointer_cast()) - store2->addPermRoot(store->parseStorePath(symlink.second), absPath(symlink.first), true); + std::vector outPaths; + + for (auto & [drvPath, info] : drvMap) { + auto & [counter, wantedOutputs] = info; + std::string drvPrefix = outLink; + if (counter) + drvPrefix += fmt("-%d", counter + 1); + + auto builtOutputs = store->queryDerivationOutputMap(drvPath); + + for (auto & outputName : wantedOutputs) { + auto outputPath = builtOutputs.at(outputName); + + if (auto store2 = store.dynamic_pointer_cast()) { + std::string symlink = drvPrefix; + if (outputName != "out") symlink += "-" + outputName; + store2->addPermRoot(outputPath, absPath(symlink)); + } + + outPaths.push_back(outputPath); + } + } logger->stop(); for (auto & path : outPaths) - std::cout << path << '\n'; + std::cout << store->printStorePath(path) << '\n'; } } -static RegisterLegacyCommand s1("nix-build", _main); -static RegisterLegacyCommand s2("nix-shell", _main); +static RegisterLegacyCommand r_nix_build("nix-build", main_nix_build); +static RegisterLegacyCommand r_nix_shell("nix-shell", main_nix_build); diff --git a/src/nix-channel/nix-channel.cc b/src/nix-channel/nix-channel.cc index 3ccf620c9..309970df6 100755 --- a/src/nix-channel/nix-channel.cc +++ b/src/nix-channel/nix-channel.cc @@ -76,6 +76,13 @@ static void update(const StringSet & channelNames) auto store = openStore(); + auto [fd, unpackChannelPath] = createTempFile(); + writeFull(fd.get(), + #include "unpack-channel.nix.gen.hh" + ); + fd = -1; + AutoDelete del(unpackChannelPath, false); + // Download each channel. Strings exprs; for (const auto & channel : channels) { @@ -104,7 +111,7 @@ static void update(const StringSet & channelNames) bool unpacked = false; if (std::regex_search(filename, std::regex("\\.tar\\.(gz|bz2|xz)$"))) { - runProgram(settings.nixBinDir + "/nix-build", false, { "--no-out-link", "--expr", "import " + runProgram(settings.nixBinDir + "/nix-build", false, { "--no-out-link", "--expr", "import " + unpackChannelPath + "{ name = \"" + cname + "\"; channelName = \"" + name + "\"; src = builtins.storePath \"" + filename + "\"; }" }); unpacked = true; } @@ -125,7 +132,7 @@ static void update(const StringSet & channelNames) // Unpack the channel tarballs into the Nix store and install them // into the channels profile. std::cerr << "unpacking channels...\n"; - Strings envArgs{ "--profile", profile, "--file", "", "--install", "--from-expression" }; + Strings envArgs{ "--profile", profile, "--file", unpackChannelPath, "--install", "--from-expression" }; for (auto & expr : exprs) envArgs.push_back(std::move(expr)); envArgs.push_back("--quiet"); @@ -146,7 +153,7 @@ static void update(const StringSet & channelNames) replaceSymlink(profile, channelLink); } -static int _main(int argc, char ** argv) +static int main_nix_channel(int argc, char ** argv) { { // Figure out the name of the `.nix-channels' file to use @@ -243,4 +250,4 @@ static int _main(int argc, char ** argv) } } -static RegisterLegacyCommand s1("nix-channel", _main); +static RegisterLegacyCommand r_nix_channel("nix-channel", main_nix_channel); diff --git a/corepkgs/unpack-channel.nix b/src/nix-channel/unpack-channel.nix similarity index 100% rename from corepkgs/unpack-channel.nix rename to src/nix-channel/unpack-channel.nix diff --git a/src/nix-collect-garbage/nix-collect-garbage.cc b/src/nix-collect-garbage/nix-collect-garbage.cc index aa5ada3a6..57092b887 100644 --- a/src/nix-collect-garbage/nix-collect-garbage.cc +++ b/src/nix-collect-garbage/nix-collect-garbage.cc @@ -49,7 +49,7 @@ void removeOldGenerations(std::string dir) } } -static int _main(int argc, char * * argv) +static int main_nix_collect_garbage(int argc, char * * argv) { { bool removeOld = false; @@ -67,10 +67,8 @@ static int _main(int argc, char * * argv) deleteOlderThan = getArg(*arg, arg, end); } else if (*arg == "--dry-run") dryRun = true; - else if (*arg == "--max-freed") { - long long maxFreed = getIntArg(*arg, arg, end, true); - options.maxFreed = maxFreed >= 0 ? maxFreed : 0; - } + else if (*arg == "--max-freed") + options.maxFreed = std::max(getIntArg(*arg, arg, end, true), (int64_t) 0); else return false; return true; @@ -94,4 +92,4 @@ static int _main(int argc, char * * argv) } } -static RegisterLegacyCommand s1("nix-collect-garbage", _main); +static RegisterLegacyCommand r_nix_collect_garbage("nix-collect-garbage", main_nix_collect_garbage); diff --git a/src/nix-copy-closure/nix-copy-closure.cc b/src/nix-copy-closure/nix-copy-closure.cc index b10184718..10990f7b5 100755 --- a/src/nix-copy-closure/nix-copy-closure.cc +++ b/src/nix-copy-closure/nix-copy-closure.cc @@ -4,7 +4,7 @@ using namespace nix; -static int _main(int argc, char ** argv) +static int main_nix_copy_closure(int argc, char ** argv) { { auto gzip = false; @@ -65,4 +65,4 @@ static int _main(int argc, char ** argv) } } -static RegisterLegacyCommand s1("nix-copy-closure", _main); +static RegisterLegacyCommand r_nix_copy_closure("nix-copy-closure", main_nix_copy_closure); diff --git a/src/nix-daemon/nix-daemon.cc b/src/nix-daemon/nix-daemon.cc index bcb86cbce..fc6195cf0 100644 --- a/src/nix-daemon/nix-daemon.cc +++ b/src/nix-daemon/nix-daemon.cc @@ -1,5 +1,6 @@ #include "shared.hh" #include "local-store.hh" +#include "remote-store.hh" #include "util.hh" #include "serialise.hh" #include "archive.hh" @@ -239,7 +240,15 @@ static void daemonLoop(char * * argv) // Handle the connection. FdSource from(remote.get()); FdSink to(remote.get()); - processConnection(openUncachedStore(), from, to, trusted, NotRecursive, user, peer.uid); + processConnection(openUncachedStore(), from, to, trusted, NotRecursive, [&](Store & store) { +#if 0 + /* Prevent users from doing something very dangerous. */ + if (geteuid() == 0 && + querySetting("build-users-group", "") == "") + throw Error("if you run 'nix-daemon' as root, then you MUST set 'build-users-group'!"); +#endif + store.createUser(user, peer.uid); + }); exit(0); }, options); @@ -256,7 +265,7 @@ static void daemonLoop(char * * argv) } -static int _main(int argc, char * * argv) +static int main_nix_daemon(int argc, char * * argv) { { auto stdio = false; @@ -277,44 +286,28 @@ static int _main(int argc, char * * argv) initPlugins(); if (stdio) { - if (getStoreType() == tDaemon) { - // Forward on this connection to the real daemon - auto socketPath = settings.nixDaemonSocketFile; - auto s = socket(PF_UNIX, SOCK_STREAM, 0); - if (s == -1) - throw SysError("creating Unix domain socket"); + if (auto store = openUncachedStore().dynamic_pointer_cast()) { + auto conn = store->openConnectionWrapper(); + int from = conn->from.fd; + int to = conn->to.fd; - auto socketDir = dirOf(socketPath); - if (chdir(socketDir.c_str()) == -1) - throw SysError("changing to socket directory '%1%'", socketDir); - - auto socketName = std::string(baseNameOf(socketPath)); - auto addr = sockaddr_un{}; - addr.sun_family = AF_UNIX; - if (socketName.size() + 1 >= sizeof(addr.sun_path)) - throw Error("socket name %1% is too long", socketName); - strcpy(addr.sun_path, socketName.c_str()); - - if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) == -1) - throw SysError("cannot connect to daemon at %1%", socketPath); - - auto nfds = (s > STDIN_FILENO ? s : STDIN_FILENO) + 1; + auto nfds = std::max(from, STDIN_FILENO) + 1; while (true) { fd_set fds; FD_ZERO(&fds); - FD_SET(s, &fds); + FD_SET(from, &fds); FD_SET(STDIN_FILENO, &fds); if (select(nfds, &fds, nullptr, nullptr, nullptr) == -1) throw SysError("waiting for data from client or server"); - if (FD_ISSET(s, &fds)) { - auto res = splice(s, nullptr, STDOUT_FILENO, nullptr, SSIZE_MAX, SPLICE_F_MOVE); + if (FD_ISSET(from, &fds)) { + auto res = splice(from, nullptr, STDOUT_FILENO, nullptr, SSIZE_MAX, SPLICE_F_MOVE); if (res == -1) throw SysError("splicing data from daemon socket to stdout"); else if (res == 0) throw EndOfFile("unexpected EOF from daemon socket"); } if (FD_ISSET(STDIN_FILENO, &fds)) { - auto res = splice(STDIN_FILENO, nullptr, s, nullptr, SSIZE_MAX, SPLICE_F_MOVE); + auto res = splice(STDIN_FILENO, nullptr, to, nullptr, SSIZE_MAX, SPLICE_F_MOVE); if (res == -1) throw SysError("splicing data from stdin to daemon socket"); else if (res == 0) @@ -324,7 +317,10 @@ static int _main(int argc, char * * argv) } else { FdSource from(STDIN_FILENO); FdSink to(STDOUT_FILENO); - processConnection(openUncachedStore(), from, to, Trusted, NotRecursive, "root", 0); + /* Auth hook is empty because in this mode we blindly trust the + standard streams. Limitting access to thoses is explicitly + not `nix-daemon`'s responsibility. */ + processConnection(openUncachedStore(), from, to, Trusted, NotRecursive, [&](Store & _){}); } } else { daemonLoop(argv); @@ -334,4 +330,4 @@ static int _main(int argc, char * * argv) } } -static RegisterLegacyCommand s1("nix-daemon", _main); +static RegisterLegacyCommand r_nix_daemon("nix-daemon", main_nix_daemon); diff --git a/src/nix-env/nix-env.cc b/src/nix-env/nix-env.cc index c992b7d74..e6667e7f5 100644 --- a/src/nix-env/nix-env.cc +++ b/src/nix-env/nix-env.cc @@ -230,7 +230,7 @@ static DrvInfos filterBySelector(EvalState & state, const DrvInfos & allElems, { DrvNames selectors = drvNamesFromArgs(args); if (selectors.empty()) - selectors.push_back(DrvName("*")); + selectors.emplace_back("*"); DrvInfos elems; set done; @@ -381,7 +381,8 @@ static void queryInstSources(EvalState & state, if (path.isDerivation()) { elem.setDrvPath(state.store->printStorePath(path)); - elem.setOutPath(state.store->printStorePath(state.store->derivationFromPath(path).findOutput("out"))); + auto outputs = state.store->queryDerivationOutputMap(path); + elem.setOutPath(state.store->printStorePath(outputs.at("out"))); if (name.size() >= drvExtension.size() && string(name, name.size() - drvExtension.size()) == drvExtension) name = string(name, 0, name.size() - drvExtension.size()); @@ -707,7 +708,9 @@ static void opSet(Globals & globals, Strings opFlags, Strings opArgs) } debug(format("switching to new user environment")); - Path generation = createGeneration(ref(store2), globals.profile, drv.queryOutPath()); + Path generation = createGeneration( + ref(store2), globals.profile, + store2->parseStorePath(drv.queryOutPath())); switchLink(globals.profile, generation); } @@ -1208,18 +1211,17 @@ static void opSwitchProfile(Globals & globals, Strings opFlags, Strings opArgs) } -static const int prevGen = -2; +static constexpr GenerationNumber prevGen = std::numeric_limits::max(); -static void switchGeneration(Globals & globals, int dstGen) +static void switchGeneration(Globals & globals, GenerationNumber dstGen) { PathLocks lock; lockProfile(lock, globals.profile); - int curGen; - Generations gens = findGenerations(globals.profile, curGen); + auto [gens, curGen] = findGenerations(globals.profile); - Generation dst; + std::optional dst; for (auto & i : gens) if ((dstGen == prevGen && i.number < curGen) || (dstGen >= 0 && i.number == dstGen)) @@ -1227,18 +1229,16 @@ static void switchGeneration(Globals & globals, int dstGen) if (!dst) { if (dstGen == prevGen) - throw Error("no generation older than the current (%1%) exists", - curGen); + throw Error("no generation older than the current (%1%) exists", curGen.value_or(0)); else throw Error("generation %1% does not exist", dstGen); } - printInfo(format("switching from generation %1% to %2%") - % curGen % dst.number); + printInfo("switching from generation %1% to %2%", curGen.value_or(0), dst->number); if (globals.dryRun) return; - switchLink(globals.profile, dst.path); + switchLink(globals.profile, dst->path); } @@ -1249,7 +1249,7 @@ static void opSwitchGeneration(Globals & globals, Strings opFlags, Strings opArg if (opArgs.size() != 1) throw UsageError("exactly one argument expected"); - int dstGen; + GenerationNumber dstGen; if (!string2Int(opArgs.front(), dstGen)) throw UsageError("expected a generation number"); @@ -1278,8 +1278,7 @@ static void opListGenerations(Globals & globals, Strings opFlags, Strings opArgs PathLocks lock; lockProfile(lock, globals.profile); - int curGen; - Generations gens = findGenerations(globals.profile, curGen); + auto [gens, curGen] = findGenerations(globals.profile); RunPager pager; @@ -1308,14 +1307,14 @@ static void opDeleteGenerations(Globals & globals, Strings opFlags, Strings opAr if(opArgs.front().size() < 2) throw Error("invalid number of generations ‘%1%’", opArgs.front()); string str_max = string(opArgs.front(), 1, opArgs.front().size()); - int max; + GenerationNumber max; if (!string2Int(str_max, max) || max == 0) throw Error("invalid number of generations to keep ‘%1%’", opArgs.front()); deleteGenerationsGreaterThan(globals.profile, max, globals.dryRun); } else { - std::set gens; + std::set gens; for (auto & i : opArgs) { - unsigned int n; + GenerationNumber n; if (!string2Int(i, n)) throw UsageError("invalid generation number '%1%'", i); gens.insert(n); @@ -1331,7 +1330,7 @@ static void opVersion(Globals & globals, Strings opFlags, Strings opArgs) } -static int _main(int argc, char * * argv) +static int main_nix_env(int argc, char * * argv) { { Strings opFlags, opArgs; @@ -1461,4 +1460,4 @@ static int _main(int argc, char * * argv) } } -static RegisterLegacyCommand s1("nix-env", _main); +static RegisterLegacyCommand r_nix_env("nix-env", main_nix_env); diff --git a/src/nix-env/user-env.cc b/src/nix-env/user-env.cc index 8e7f09e12..8c6c8af05 100644 --- a/src/nix-env/user-env.cc +++ b/src/nix-env/user-env.cc @@ -151,7 +151,8 @@ bool createUserEnv(EvalState & state, DrvInfos & elems, } debug(format("switching to new user environment")); - Path generation = createGeneration(ref(store2), profile, topLevelOut); + Path generation = createGeneration(ref(store2), profile, + store2->parseStorePath(topLevelOut)); switchLink(profile, generation); } diff --git a/src/nix-instantiate/nix-instantiate.cc b/src/nix-instantiate/nix-instantiate.cc index bf353677a..18a0049a6 100644 --- a/src/nix-instantiate/nix-instantiate.cc +++ b/src/nix-instantiate/nix-instantiate.cc @@ -20,7 +20,6 @@ using namespace nix; static Path gcRoot; static int rootNr = 0; -static bool indirectRoot = false; enum OutputKind { okPlain, okXML, okJSON }; @@ -71,11 +70,11 @@ void processExpr(EvalState & state, const Strings & attrPaths, if (gcRoot == "") printGCWarning(); else { - Path rootName = indirectRoot ? absPath(gcRoot) : gcRoot; + Path rootName = absPath(gcRoot); if (++rootNr > 1) rootName += "-" + std::to_string(rootNr); auto store2 = state.store.dynamic_pointer_cast(); if (store2) - drvPath = store2->addPermRoot(store2->parseStorePath(drvPath), rootName, indirectRoot); + drvPath = store2->addPermRoot(store2->parseStorePath(drvPath), rootName); } std::cout << fmt("%s%s\n", drvPath, (outputName != "out" ? "!" + outputName : "")); } @@ -84,7 +83,7 @@ void processExpr(EvalState & state, const Strings & attrPaths, } -static int _main(int argc, char * * argv) +static int main_nix_instantiate(int argc, char * * argv) { { Strings files; @@ -127,7 +126,7 @@ static int _main(int argc, char * * argv) else if (*arg == "--add-root") gcRoot = getArg(*arg, arg, end); else if (*arg == "--indirect") - indirectRoot = true; + ; else if (*arg == "--xml") outputKind = okXML; else if (*arg == "--json") @@ -193,4 +192,4 @@ static int _main(int argc, char * * argv) } } -static RegisterLegacyCommand s1("nix-instantiate", _main); +static RegisterLegacyCommand r_nix_instantiate("nix-instantiate", main_nix_instantiate); diff --git a/src/nix-prefetch-url/nix-prefetch-url.cc b/src/nix-prefetch-url/nix-prefetch-url.cc index 40b05a2f3..3bdee55a7 100644 --- a/src/nix-prefetch-url/nix-prefetch-url.cc +++ b/src/nix-prefetch-url/nix-prefetch-url.cc @@ -48,7 +48,7 @@ string resolveMirrorUri(EvalState & state, string uri) } -static int _main(int argc, char * * argv) +static int main_nix_prefetch_url(int argc, char * * argv) { { HashType ht = htSHA256; @@ -57,6 +57,7 @@ static int _main(int argc, char * * argv) bool fromExpr = false; string attrPath; bool unpack = false; + bool executable = false; string name; struct MyArgs : LegacyArgs, MixEvalArgs @@ -81,6 +82,8 @@ static int _main(int argc, char * * argv) } else if (*arg == "--unpack") unpack = true; + else if (*arg == "--executable") + executable = true; else if (*arg == "--name") name = getArg(*arg, arg, end); else if (*arg != "" && arg->at(0) == '-') @@ -153,14 +156,15 @@ static int _main(int argc, char * * argv) /* If an expected hash is given, the file may already exist in the store. */ - Hash hash, expectedHash(ht); + std::optional expectedHash; + Hash hash(ht); std::optional storePath; if (args.size() == 2) { - expectedHash = Hash(args[1], ht); + expectedHash = Hash::parseAny(args[1], ht); const auto recursive = unpack ? FileIngestionMethod::Recursive : FileIngestionMethod::Flat; - storePath = store->makeFixedOutputPath(recursive, expectedHash, name); + storePath = store->makeFixedOutputPath(recursive, *expectedHash, name); if (store->isValidPath(*storePath)) - hash = expectedHash; + hash = *expectedHash; else storePath.reset(); } @@ -174,7 +178,11 @@ static int _main(int argc, char * * argv) /* Download the file. */ { - AutoCloseFD fd = open(tmpFile.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0600); + auto mode = 0600; + if (executable) + mode = 0700; + + AutoCloseFD fd = open(tmpFile.c_str(), O_WRONLY | O_CREAT | O_EXCL, mode); if (!fd) throw SysError("creating temporary file '%s'", tmpFile); FdSink sink(fd.get()); @@ -200,22 +208,12 @@ static int _main(int argc, char * * argv) tmpFile = unpacked; } - /* FIXME: inefficient; addToStore() will also hash - this. */ - hash = unpack ? hashPath(ht, tmpFile).first : hashFile(ht, tmpFile); + const auto method = unpack || executable ? FileIngestionMethod::Recursive : FileIngestionMethod::Flat; - if (expectedHash != Hash(ht) && expectedHash != hash) - throw Error("hash mismatch for '%1%'", uri); - - const auto recursive = unpack ? FileIngestionMethod::Recursive : FileIngestionMethod::Flat; - - /* Copy the file to the Nix store. FIXME: if RemoteStore - implemented addToStoreFromDump() and downloadFile() - supported a sink, we could stream the download directly - into the Nix store. */ - storePath = store->addToStore(name, tmpFile, recursive, ht); - - assert(*storePath == store->makeFixedOutputPath(recursive, hash, name)); + auto info = store->addToStoreSlow(name, tmpFile, method, ht, expectedHash); + storePath = info.path; + assert(info.ca); + hash = getContentAddressHash(*info.ca); } stopProgressBar(); @@ -231,4 +229,4 @@ static int _main(int argc, char * * argv) } } -static RegisterLegacyCommand s1("nix-prefetch-url", _main); +static RegisterLegacyCommand r_nix_prefetch_url("nix-prefetch-url", main_nix_prefetch_url); diff --git a/src/nix-store/nix-store.cc b/src/nix-store/nix-store.cc index b948380bb..70927925d 100644 --- a/src/nix-store/nix-store.cc +++ b/src/nix-store/nix-store.cc @@ -24,6 +24,9 @@ #endif +namespace nix_store { + + using namespace nix; using std::cin; using std::cout; @@ -34,7 +37,6 @@ typedef void (* Operation) (Strings opFlags, Strings opArgs); static Path gcRoot; static int rootNr = 0; -static bool indirectRoot = false; static bool noOutput = false; static std::shared_ptr store; @@ -65,6 +67,7 @@ static PathSet realisePath(StorePathWithOutputs path, bool build = true) if (path.path.isDerivation()) { if (build) store->buildPaths({path}); + auto outputPaths = store->queryDerivationOutputMap(path.path); Derivation drv = store->derivationFromPath(path.path); rootNr++; @@ -77,7 +80,8 @@ static PathSet realisePath(StorePathWithOutputs path, bool build = true) if (i == drv.outputs.end()) throw Error("derivation '%s' does not have an output named '%s'", store2->printStorePath(path.path), j); - auto outPath = store2->printStorePath(i->second.path); + auto outPath = outputPaths.at(i->first); + auto retPath = store->printStorePath(outPath); if (store2) { if (gcRoot == "") printGCWarning(); @@ -85,10 +89,10 @@ static PathSet realisePath(StorePathWithOutputs path, bool build = true) Path rootName = gcRoot; if (rootNr > 1) rootName += "-" + std::to_string(rootNr); if (i->first != "out") rootName += "-" + i->first; - outPath = store2->addPermRoot(store->parseStorePath(outPath), rootName, indirectRoot); + retPath = store2->addPermRoot(outPath, rootName); } } - outputs.insert(outPath); + outputs.insert(retPath); } return outputs; } @@ -104,7 +108,7 @@ static PathSet realisePath(StorePathWithOutputs path, bool build = true) Path rootName = gcRoot; rootNr++; if (rootNr > 1) rootName += "-" + std::to_string(rootNr); - return {store2->addPermRoot(path.path, rootName, indirectRoot)}; + return {store2->addPermRoot(path.path, rootName)}; } } return {store->printStorePath(path.path)}; @@ -130,7 +134,7 @@ static void opRealise(Strings opFlags, Strings opArgs) for (auto & i : opArgs) paths.push_back(store->followLinksToStorePathWithOutputs(i)); - unsigned long long downloadSize, narSize; + uint64_t downloadSize, narSize; StorePathSet willBuild, willSubstitute, unknown; store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); @@ -174,10 +178,10 @@ static void opAdd(Strings opFlags, Strings opArgs) store. */ static void opAddFixed(Strings opFlags, Strings opArgs) { - auto recursive = FileIngestionMethod::Flat; + auto method = FileIngestionMethod::Flat; for (auto & i : opFlags) - if (i == "--recursive") recursive = FileIngestionMethod::Recursive; + if (i == "--recursive") method = FileIngestionMethod::Recursive; else throw UsageError("unknown flag '%1%'", i); if (opArgs.empty()) @@ -187,7 +191,7 @@ static void opAddFixed(Strings opFlags, Strings opArgs) opArgs.pop_front(); for (auto & i : opArgs) - cout << fmt("%s\n", store->printStorePath(store->addToStore(std::string(baseNameOf(i)), i, recursive, hashAlgo))); + std::cout << fmt("%s\n", store->printStorePath(store->addToStoreSlow(baseNameOf(i), i, method, hashAlgo).path)); } @@ -208,7 +212,7 @@ static void opPrintFixedPath(Strings opFlags, Strings opArgs) string hash = *i++; string name = *i++; - cout << fmt("%s\n", store->printStorePath(store->makeFixedOutputPath(recursive, Hash(hash, hashAlgo), name))); + cout << fmt("%s\n", store->printStorePath(store->makeFixedOutputPath(recursive, Hash::parseAny(hash, hashAlgo), name))); } @@ -218,8 +222,13 @@ static StorePathSet maybeUseOutputs(const StorePath & storePath, bool useOutput, if (useOutput && storePath.isDerivation()) { auto drv = store->derivationFromPath(storePath); StorePathSet outputs; - for (auto & i : drv.outputs) - outputs.insert(i.second.path); + if (forceRealise) + return store->queryDerivationOutputs(storePath); + for (auto & i : drv.outputsAndOptPaths(*store)) { + if (!i.second.second) + throw UsageError("Cannot use output path of floating content-addressed derivation until we know what it is (e.g. by building it)"); + outputs.insert(*i.second.second); + } return outputs; } else return {storePath}; @@ -309,11 +318,9 @@ static void opQuery(Strings opFlags, Strings opArgs) case qOutputs: { for (auto & i : opArgs) { - auto i2 = store->followLinksToStorePath(i); - if (forceRealise) realisePath({i2}); - Derivation drv = store->derivationFromPath(i2); - for (auto & j : drv.outputs) - cout << fmt("%1%\n", store->printStorePath(j.second.path)); + auto outputs = maybeUseOutputs(store->followLinksToStorePath(i), true, forceRealise); + for (auto & outputPath : outputs) + cout << fmt("%1%\n", store->printStorePath(outputPath)); } break; } @@ -495,7 +502,10 @@ static void registerValidity(bool reregister, bool hashGiven, bool canonicalise) ValidPathInfos infos; while (1) { - auto info = decodeValidPathInfo(*store, cin, hashGiven); + // We use a dummy value because we'll set it below. FIXME be correct by + // construction and avoid dummy value. + auto hashResultOpt = !hashGiven ? std::optional { {Hash::dummy, -1} } : std::nullopt; + auto info = decodeValidPathInfo(*store, cin, hashResultOpt); if (!info) break; if (!store->isValidPath(info->path) || reregister) { /* !!! races */ @@ -572,10 +582,8 @@ static void opGC(Strings opFlags, Strings opArgs) if (*i == "--print-roots") printRoots = true; else if (*i == "--print-live") options.action = GCOptions::gcReturnLive; else if (*i == "--print-dead") options.action = GCOptions::gcReturnDead; - else if (*i == "--max-freed") { - long long maxFreed = getIntArg(*i, i, opFlags.end(), true); - options.maxFreed = maxFreed >= 0 ? maxFreed : 0; - } + else if (*i == "--max-freed") + options.maxFreed = std::max(getIntArg(*i, i, opFlags.end(), true), (int64_t) 0); else throw UsageError("bad sub-operation '%1%' in GC", *i); if (!opArgs.empty()) throw UsageError("no arguments expected"); @@ -671,7 +679,7 @@ static void opImport(Strings opFlags, Strings opArgs) if (!opArgs.empty()) throw UsageError("no arguments expected"); FdSource source(STDIN_FILENO); - auto paths = store->importPaths(source, nullptr, NoCheckSigs); + auto paths = store->importPaths(source, NoCheckSigs); for (auto & i : paths) cout << fmt("%s\n", store->printStorePath(i)) << std::flush; @@ -725,7 +733,7 @@ static void opVerifyPath(Strings opFlags, Strings opArgs) auto path = store->followLinksToStorePath(i); printMsg(lvlTalkative, "checking path '%s'...", store->printStorePath(path)); auto info = store->queryPathInfo(path); - HashSink sink(*info->narHash.type); + HashSink sink(info->narHash.type); store->narFromPath(path, sink); auto current = sink.finish(); if (current.first != info->narHash) { @@ -817,7 +825,7 @@ static void opServe(Strings opFlags, Strings opArgs) case cmdQueryValidPaths: { bool lock = readInt(in); bool substitute = readInt(in); - auto paths = readStorePaths(*store, in); + auto paths = worker_proto::read(*store, in, Phantom {}); if (lock && writeAllowed) for (auto & path : paths) store->addTempRoot(path); @@ -831,7 +839,7 @@ static void opServe(Strings opFlags, Strings opArgs) for (auto & path : paths) if (!path.isDerivation()) paths2.push_back({path}); - unsigned long long downloadSize, narSize; + uint64_t downloadSize, narSize; StorePathSet willBuild, willSubstitute, unknown; store->queryMissing(paths2, willBuild, willSubstitute, unknown, downloadSize, narSize); @@ -847,24 +855,26 @@ static void opServe(Strings opFlags, Strings opArgs) } } - writeStorePaths(*store, out, store->queryValidPaths(paths)); + worker_proto::write(*store, out, store->queryValidPaths(paths)); break; } case cmdQueryPathInfos: { - auto paths = readStorePaths(*store, in); + auto paths = worker_proto::read(*store, in, Phantom {}); // !!! Maybe we want a queryPathInfos? for (auto & i : paths) { try { auto info = store->queryPathInfo(i); out << store->printStorePath(info->path) << (info->deriver ? store->printStorePath(*info->deriver) : ""); - writeStorePaths(*store, out, info->references); + worker_proto::write(*store, out, info->references); // !!! Maybe we want compression? out << info->narSize // downloadSize << info->narSize; if (GET_PROTOCOL_MINOR(clientVersion) >= 4) - out << (info->narHash ? info->narHash.to_string(Base32, true) : "") << renderContentAddress(info->ca) << info->sigs; + out << info->narHash.to_string(Base32, true) + << renderContentAddress(info->ca) + << info->sigs; } catch (InvalidPath &) { } } @@ -878,14 +888,14 @@ static void opServe(Strings opFlags, Strings opArgs) case cmdImportPaths: { if (!writeAllowed) throw Error("importing paths is not allowed"); - store->importPaths(in, nullptr, NoCheckSigs); // FIXME: should we skip sig checking? + store->importPaths(in, NoCheckSigs); // FIXME: should we skip sig checking? out << 1; // indicate success break; } case cmdExportPaths: { readInt(in); // obsolete - store->exportPaths(readStorePaths(*store, in), out); + store->exportPaths(worker_proto::read(*store, in, Phantom {}), out); break; } @@ -914,9 +924,9 @@ static void opServe(Strings opFlags, Strings opArgs) if (!writeAllowed) throw Error("building paths is not allowed"); - auto drvPath = store->parseStorePath(readString(in)); // informational only + auto drvPath = store->parseStorePath(readString(in)); BasicDerivation drv; - readDerivation(in, *store, drv); + readDerivation(in, *store, drv, Derivation::nameFromPath(drvPath)); getBuildSettings(); @@ -934,9 +944,9 @@ static void opServe(Strings opFlags, Strings opArgs) case cmdQueryClosure: { bool includeOutputs = readInt(in); StorePathSet closure; - store->computeFSClosure(readStorePaths(*store, in), + store->computeFSClosure(worker_proto::read(*store, in, Phantom {}), closure, false, includeOutputs); - writeStorePaths(*store, out, closure); + worker_proto::write(*store, out, closure); break; } @@ -944,12 +954,14 @@ static void opServe(Strings opFlags, Strings opArgs) if (!writeAllowed) throw Error("importing paths is not allowed"); auto path = readString(in); - ValidPathInfo info(store->parseStorePath(path)); auto deriver = readString(in); + ValidPathInfo info { + store->parseStorePath(path), + Hash::parseAny(readString(in), htSHA256), + }; if (deriver != "") info.deriver = store->parseStorePath(deriver); - info.narHash = Hash(readString(in), htSHA256); - info.references = readStorePaths(*store, in); + info.references = worker_proto::read(*store, in, Phantom {}); in >> info.registrationTime >> info.narSize >> info.ultimate; info.sigs = readStrings(in); info.ca = parseContentAddressOpt(readString(in)); @@ -1016,7 +1028,7 @@ static void opVersion(Strings opFlags, Strings opArgs) /* Scan the arguments; find the operation, set global flags, put all other flags in a list, and put all other arguments in another list. */ -static int _main(int argc, char * * argv) +static int main_nix_store(int argc, char * * argv) { { Strings opFlags, opArgs; @@ -1080,7 +1092,7 @@ static int _main(int argc, char * * argv) else if (*arg == "--add-root") gcRoot = absPath(getArg(*arg, arg, end)); else if (*arg == "--indirect") - indirectRoot = true; + ; else if (*arg == "--no-output") noOutput = true; else if (*arg != "" && arg->at(0) == '-') { @@ -1112,4 +1124,6 @@ static int _main(int argc, char * * argv) } } -static RegisterLegacyCommand s1("nix-store", _main); +static RegisterLegacyCommand r_nix_store("nix-store", main_nix_store); + +} diff --git a/src/nix/add-to-store.cc b/src/nix/add-to-store.cc index f9d6de16e..7fe87d757 100644 --- a/src/nix/add-to-store.cc +++ b/src/nix/add-to-store.cc @@ -9,6 +9,7 @@ struct CmdAddToStore : MixDryRun, StoreCommand { Path path; std::optional namePart; + FileIngestionMethod ingestionMethod = FileIngestionMethod::Recursive; CmdAddToStore() { @@ -21,6 +22,13 @@ struct CmdAddToStore : MixDryRun, StoreCommand .labels = {"name"}, .handler = {&namePart}, }); + + addFlag({ + .longName = "flat", + .shortName = 0, + .description = "add flat file to the Nix store", + .handler = {&ingestionMethod, FileIngestionMethod::Flat}, + }); } std::string description() override @@ -28,6 +36,14 @@ struct CmdAddToStore : MixDryRun, StoreCommand return "add a path to the Nix store"; } + std::string doc() override + { + return R"( + Copy the file or directory *path* to the Nix store, and + print the resulting store path on standard output. + )"; + } + Examples examples() override { return { @@ -45,12 +61,21 @@ struct CmdAddToStore : MixDryRun, StoreCommand auto narHash = hashString(htSHA256, *sink.s); - ValidPathInfo info(store->makeFixedOutputPath(FileIngestionMethod::Recursive, narHash, *namePart)); - info.narHash = narHash; + Hash hash = narHash; + if (ingestionMethod == FileIngestionMethod::Flat) { + HashSink hsink(htSHA256); + readFile(path, hsink); + hash = hsink.finish().first; + } + + ValidPathInfo info { + store->makeFixedOutputPath(ingestionMethod, hash, *namePart), + narHash, + }; info.narSize = sink.s->size(); info.ca = std::optional { FixedOutputHash { - .method = FileIngestionMethod::Recursive, - .hash = info.narHash, + .method = ingestionMethod, + .hash = hash, } }; if (!dryRun) { @@ -62,4 +87,4 @@ struct CmdAddToStore : MixDryRun, StoreCommand } }; -static auto r1 = registerCommand("add-to-store"); +static auto rCmdAddToStore = registerCommand("add-to-store"); diff --git a/src/nix/app.cc b/src/nix/app.cc new file mode 100644 index 000000000..80acbf658 --- /dev/null +++ b/src/nix/app.cc @@ -0,0 +1,46 @@ +#include "installables.hh" +#include "store-api.hh" +#include "eval-inline.hh" +#include "eval-cache.hh" +#include "names.hh" + +namespace nix { + +App Installable::toApp(EvalState & state) +{ + auto [cursor, attrPath] = getCursor(state); + + auto type = cursor->getAttr("type")->getString(); + + if (type == "app") { + auto [program, context] = cursor->getAttr("program")->getStringWithContext(); + + if (!state.store->isInStore(program)) + throw Error("app program '%s' is not in the Nix store", program); + + std::vector context2; + for (auto & [path, name] : context) + context2.push_back({state.store->parseStorePath(path), {name}}); + + return App { + .context = std::move(context2), + .program = program, + }; + } + + else if (type == "derivation") { + auto drvPath = cursor->forceDerivation(); + auto outPath = cursor->getAttr(state.sOutPath)->getString(); + auto outputName = cursor->getAttr(state.sOutputName)->getString(); + auto name = cursor->getAttr(state.sName)->getString(); + return App { + .context = { { drvPath, {outputName} } }, + .program = outPath + "/bin/" + DrvName(name).name, + }; + } + + else + throw Error("attribute '%s' has unsupported type '%s'", attrPath, type); +} + +} diff --git a/src/nix/build.cc b/src/nix/build.cc index 850e09ce8..d85a482db 100644 --- a/src/nix/build.cc +++ b/src/nix/build.cc @@ -1,3 +1,4 @@ +#include "eval.hh" #include "command.hh" #include "common-args.hh" #include "shared.hh" @@ -8,6 +9,7 @@ using namespace nix; struct CmdBuild : InstallablesCommand, MixDryRun, MixProfile { Path outLink = "result"; + BuildMode buildMode = bmNormal; CmdBuild() { @@ -17,6 +19,7 @@ struct CmdBuild : InstallablesCommand, MixDryRun, MixProfile .description = "path of the symlink to the build result", .labels = {"path"}, .handler = {&outLink}, + .completer = completePath }); addFlag({ @@ -24,6 +27,12 @@ struct CmdBuild : InstallablesCommand, MixDryRun, MixProfile .description = "do not create a symlink to the build result", .handler = {&outLink, Path("")}, }); + + addFlag({ + .longName = "rebuild", + .description = "rebuild an already built package and compare the result to the existing store paths", + .handler = {&buildMode, bmCheck}, + }); } std::string description() override @@ -44,31 +53,39 @@ struct CmdBuild : InstallablesCommand, MixDryRun, MixProfile }, Example{ "To make a profile point at GNU Hello:", - "nix build --profile /tmp/profile nixpkgs.hello" + "nix build --profile /tmp/profile nixpkgs#hello" }, }; } void run(ref store) override { - auto buildables = build(store, dryRun ? DryRun : Build, installables); + auto buildables = build(store, dryRun ? Realise::Nothing : Realise::Outputs, installables, buildMode); if (dryRun) return; - if (outLink != "") { - for (size_t i = 0; i < buildables.size(); ++i) { - for (auto & output : buildables[i].outputs) - if (auto store2 = store.dynamic_pointer_cast()) { - std::string symlink = outLink; - if (i) symlink += fmt("-%d", i); - if (output.first != "out") symlink += fmt("-%s", output.first); - store2->addPermRoot(output.second, absPath(symlink), true); - } - } - } + if (outLink != "") + if (auto store2 = store.dynamic_pointer_cast()) + for (size_t i = 0; i < buildables.size(); ++i) + std::visit(overloaded { + [&](BuildableOpaque bo) { + std::string symlink = outLink; + if (i) symlink += fmt("-%d", i); + store2->addPermRoot(bo.path, absPath(symlink)); + }, + [&](BuildableFromDrv bfd) { + auto builtOutputs = store->queryDerivationOutputMap(bfd.drvPath); + for (auto & output : builtOutputs) { + std::string symlink = outLink; + if (i) symlink += fmt("-%d", i); + if (output.first != "out") symlink += fmt("-%s", output.first); + store2->addPermRoot(output.second, absPath(symlink)); + } + }, + }, buildables[i]); updateProfile(buildables); } }; -static auto r1 = registerCommand("build"); +static auto rCmdBuild = registerCommand("build"); diff --git a/src/nix/bundle.cc b/src/nix/bundle.cc new file mode 100644 index 000000000..fc41da9e4 --- /dev/null +++ b/src/nix/bundle.cc @@ -0,0 +1,129 @@ +#include "command.hh" +#include "common-args.hh" +#include "shared.hh" +#include "store-api.hh" +#include "fs-accessor.hh" + +using namespace nix; + +struct CmdBundle : InstallableCommand +{ + std::string bundler = "github:matthewbauer/nix-bundle"; + std::optional outLink; + + CmdBundle() + { + addFlag({ + .longName = "bundler", + .description = "use custom bundler", + .labels = {"flake-url"}, + .handler = {&bundler}, + .completer = {[&](size_t, std::string_view prefix) { + completeFlakeRef(getStore(), prefix); + }} + }); + + addFlag({ + .longName = "out-link", + .shortName = 'o', + .description = "path of the symlink to the build result", + .labels = {"path"}, + .handler = {&outLink}, + .completer = completePath + }); + } + + std::string description() override + { + return "bundle an application so that it works outside of the Nix store"; + } + + Examples examples() override + { + return { + Example{ + "To bundle Hello:", + "nix bundle hello" + }, + }; + } + + Category category() override { return catSecondary; } + + Strings getDefaultFlakeAttrPaths() override + { + Strings res{"defaultApp." + settings.thisSystem.get()}; + for (auto & s : SourceExprCommand::getDefaultFlakeAttrPaths()) + res.push_back(s); + return res; + } + + Strings getDefaultFlakeAttrPathPrefixes() override + { + Strings res{"apps." + settings.thisSystem.get() + ".", "packages"}; + for (auto & s : SourceExprCommand::getDefaultFlakeAttrPathPrefixes()) + res.push_back(s); + return res; + } + + void run(ref store) override + { + auto evalState = getEvalState(); + + auto app = installable->toApp(*evalState); + store->buildPaths(app.context); + + auto [bundlerFlakeRef, bundlerName] = parseFlakeRefWithFragment(bundler, absPath(".")); + const flake::LockFlags lockFlags{ .writeLockFile = false }; + auto bundler = InstallableFlake( + evalState, std::move(bundlerFlakeRef), + Strings{bundlerName == "" ? "defaultBundler" : bundlerName}, + Strings({"bundlers."}), lockFlags); + + Value * arg = evalState->allocValue(); + evalState->mkAttrs(*arg, 2); + + PathSet context; + for (auto & i : app.context) + context.insert("=" + store->printStorePath(i.path)); + mkString(*evalState->allocAttr(*arg, evalState->symbols.create("program")), app.program, context); + + mkString(*evalState->allocAttr(*arg, evalState->symbols.create("system")), settings.thisSystem.get()); + + arg->attrs->sort(); + + auto vRes = evalState->allocValue(); + evalState->callFunction(*bundler.toValue(*evalState).first, *arg, *vRes, noPos); + + if (!evalState->isDerivation(*vRes)) + throw Error("the bundler '%s' does not produce a derivation", bundler.what()); + + auto attr1 = vRes->attrs->get(evalState->sDrvPath); + if (!attr1) + throw Error("the bundler '%s' does not produce a derivation", bundler.what()); + + PathSet context2; + StorePath drvPath = store->parseStorePath(evalState->coerceToPath(*attr1->pos, *attr1->value, context2)); + + auto attr2 = vRes->attrs->get(evalState->sOutPath); + if (!attr2) + throw Error("the bundler '%s' does not produce a derivation", bundler.what()); + + StorePath outPath = store->parseStorePath(evalState->coerceToPath(*attr2->pos, *attr2->value, context2)); + + store->buildPaths({{drvPath}}); + + auto outPathS = store->printStorePath(outPath); + + auto info = store->queryPathInfo(outPath); + if (!info->references.empty()) + throw Error("'%s' has references; a bundler must not leave any references", outPathS); + + if (!outLink) + outLink = baseNameOf(app.program); + + store.dynamic_pointer_cast()->addPermRoot(outPath, absPath(*outLink)); + } +}; + +static auto r2 = registerCommand("bundle"); diff --git a/src/nix/cat.cc b/src/nix/cat.cc index c82819af8..eef172cfc 100644 --- a/src/nix/cat.cc +++ b/src/nix/cat.cc @@ -25,7 +25,11 @@ struct CmdCatStore : StoreCommand, MixCat { CmdCatStore() { - expectArg("path", &path); + expectArgs({ + .label = "path", + .handler = {&path}, + .completer = completePath + }); } std::string description() override @@ -47,7 +51,11 @@ struct CmdCatNar : StoreCommand, MixCat CmdCatNar() { - expectArg("nar", &narPath); + expectArgs({ + .label = "nar", + .handler = {&narPath}, + .completer = completePath + }); expectArg("path", &path); } @@ -64,5 +72,5 @@ struct CmdCatNar : StoreCommand, MixCat } }; -static auto r1 = registerCommand("cat-store"); -static auto r2 = registerCommand("cat-nar"); +static auto rCmdCatStore = registerCommand("cat-store"); +static auto rCmdCatNar = registerCommand("cat-nar"); diff --git a/src/nix/command.cc b/src/nix/command.cc index 3651a9e9c..ba7de9fdd 100644 --- a/src/nix/command.cc +++ b/src/nix/command.cc @@ -4,12 +4,25 @@ #include "nixexpr.hh" #include "profiles.hh" +#include + extern char * * environ __attribute__((weak)); namespace nix { Commands * RegisterCommand::commands = nullptr; +void NixMultiCommand::printHelp(const string & programName, std::ostream & out) +{ + MultiCommand::printHelp(programName, out); +} + +nlohmann::json NixMultiCommand::toJSON() +{ + // FIXME: use Command::toJSON() as well. + return MultiCommand::toJSON(); +} + StoreCommand::StoreCommand() { } @@ -63,7 +76,7 @@ void StorePathsCommand::run(ref store) } else { - for (auto & p : toStorePaths(store, realiseMode, installables)) + for (auto & p : toStorePaths(store, realiseMode, operateOn, installables)) storePaths.push_back(p); if (recursive) { @@ -80,7 +93,7 @@ void StorePathsCommand::run(ref store) void StorePathCommand::run(ref store) { - auto storePaths = toStorePaths(store, NoBuild, installables); + auto storePaths = toStorePaths(store, Realise::Nothing, operateOn, installables); if (storePaths.size() != 1) throw UsageError("this command requires exactly one store path"); @@ -108,6 +121,7 @@ MixProfile::MixProfile() .description = "profile to update", .labels = {"path"}, .handler = {&profile}, + .completer = completePath }); } @@ -120,27 +134,35 @@ void MixProfile::updateProfile(const StorePath & storePath) switchLink(profile2, createGeneration( ref(store), - profile2, store->printStorePath(storePath))); + profile2, storePath)); } void MixProfile::updateProfile(const Buildables & buildables) { if (!profile) return; - std::optional result; + std::vector result; for (auto & buildable : buildables) { - for (auto & output : buildable.outputs) { - if (result) - throw Error("'--profile' requires that the arguments produce a single store path, but there are multiple"); - result = output.second; - } + std::visit(overloaded { + [&](BuildableOpaque bo) { + result.push_back(bo.path); + }, + [&](BuildableFromDrv bfd) { + for (auto & output : bfd.outputs) { + /* Output path should be known because we just tried to + build it. */ + assert(output.second); + result.push_back(*output.second); + } + }, + }, buildable); } - if (!result) - throw Error("'--profile' requires that the arguments produce a single store path, but there are none"); + if (result.size() != 1) + throw Error("'--profile' requires that the arguments produce a single store path, but there are %d", result.size()); - updateProfile(*result); + updateProfile(result[0]); } MixDefaultProfile::MixDefaultProfile() diff --git a/src/nix/command.hh b/src/nix/command.hh index 959d5f19d..d60c8aeb6 100644 --- a/src/nix/command.hh +++ b/src/nix/command.hh @@ -4,16 +4,30 @@ #include "args.hh" #include "common-eval-args.hh" #include "path.hh" -#include "eval.hh" +#include "flake/lockfile.hh" +#include "store-api.hh" + +#include namespace nix { extern std::string programPath; +class EvalState; +struct Pos; +class Store; + static constexpr Command::Category catSecondary = 100; static constexpr Command::Category catUtility = 101; static constexpr Command::Category catNixInstallation = 102; +struct NixMultiCommand : virtual MultiCommand, virtual Command +{ + void printHelp(const string & programName, std::ostream & out) override; + + nlohmann::json toJSON() override; +}; + /* A command that requires a Nix store. */ struct StoreCommand : virtual Command { @@ -27,28 +41,64 @@ private: std::shared_ptr _store; }; -struct SourceExprCommand : virtual StoreCommand, MixEvalArgs +struct EvalCommand : virtual StoreCommand, MixEvalArgs { - Path file; + ref getEvalState(); + + std::shared_ptr evalState; +}; + +struct MixFlakeOptions : virtual Args, EvalCommand +{ + flake::LockFlags lockFlags; + + MixFlakeOptions(); + + virtual std::optional getFlakeRefForCompletion() + { return {}; } +}; + +/* How to handle derivations in commands that operate on store paths. */ +enum class OperateOn { + /* Operate on the output path. */ + Output, + /* Operate on the .drv path. */ + Derivation +}; + +struct SourceExprCommand : virtual Args, MixFlakeOptions +{ + std::optional file; + std::optional expr; + + // FIXME: move this; not all commands (e.g. 'nix run') use it. + OperateOn operateOn = OperateOn::Output; SourceExprCommand(); - /* Return a value representing the Nix expression from which we - are installing. This is either the file specified by ‘--file’, - or an attribute set constructed from $NIX_PATH, e.g. ‘{ nixpkgs - = import ...; bla = import ...; }’. */ - Value * getSourceExpr(EvalState & state); + std::vector> parseInstallables( + ref store, std::vector ss); - ref getEvalState(); + std::shared_ptr parseInstallable( + ref store, const std::string & installable); -private: + virtual Strings getDefaultFlakeAttrPaths(); - std::shared_ptr evalState; + virtual Strings getDefaultFlakeAttrPathPrefixes(); - RootValue vSourceExpr; + void completeInstallable(std::string_view prefix); }; -enum RealiseMode { Build, NoBuild, DryRun }; +enum class Realise { + /* Build the derivation. Postcondition: the + derivation outputs exist. */ + Outputs, + /* Don't build the derivation. Postcondition: the store derivation + exists. */ + Derivation, + /* Evaluate in dry-run mode. Postcondition: nothing. */ + Nothing +}; /* A command that operates on a list of "installables", which can be store paths, attribute paths, Nix expressions, etc. */ @@ -56,15 +106,14 @@ struct InstallablesCommand : virtual Args, SourceExprCommand { std::vector> installables; - InstallablesCommand() - { - expectArgs("installables", &_installables); - } + InstallablesCommand(); void prepare() override; virtual bool useDefaultInstallables() { return true; } + std::optional getFlakeRefForCompletion() override; + private: std::vector _installables; @@ -75,16 +124,18 @@ struct InstallableCommand : virtual Args, SourceExprCommand { std::shared_ptr installable; - InstallableCommand() - { - expectArg("installable", &_installable); - } + InstallableCommand(); void prepare() override; + std::optional getFlakeRefForCompletion() override + { + return parseFlakeRef(_installable, absPath(".")); + } + private: - std::string _installable; + std::string _installable{"."}; }; /* A command that operates on zero or more store paths. */ @@ -97,7 +148,7 @@ private: protected: - RealiseMode realiseMode = NoBuild; + Realise realiseMode = Realise::Derivation; public: @@ -141,17 +192,15 @@ static RegisterCommand registerCommand(const std::string & name) return RegisterCommand(name, [](){ return make_ref(); }); } -std::shared_ptr parseInstallable( - SourceExprCommand & cmd, ref store, const std::string & installable, - bool useDefaultInstallables); +Buildables build(ref store, Realise mode, + std::vector> installables, BuildMode bMode = bmNormal); -Buildables build(ref store, RealiseMode mode, +std::set toStorePaths(ref store, + Realise mode, OperateOn operateOn, std::vector> installables); -std::set toStorePaths(ref store, RealiseMode mode, - std::vector> installables); - -StorePath toStorePath(ref store, RealiseMode mode, +StorePath toStorePath(ref store, + Realise mode, OperateOn operateOn, std::shared_ptr installable); std::set toDerivations(ref store, @@ -194,4 +243,19 @@ struct MixEnvironment : virtual Args { void setEnviron(); }; +void completeFlakeRef(ref store, std::string_view prefix); + +void completeFlakeRefWithFragment( + ref evalState, + flake::LockFlags lockFlags, + Strings attrPathPrefixes, + const Strings & defaultFlakeAttrPaths, + std::string_view prefix); + +void printClosureDiff( + ref store, + const StorePath & beforePath, + const StorePath & afterPath, + std::string_view indent); + } diff --git a/src/nix/copy.cc b/src/nix/copy.cc index 64099f476..cb31aac8f 100644 --- a/src/nix/copy.cc +++ b/src/nix/copy.cc @@ -45,6 +45,8 @@ struct CmdCopy : StorePathsCommand .description = "whether to try substitutes on the destination store (only supported by SSH)", .handler = {&substitute, Substitute}, }); + + realiseMode = Realise::Outputs; } std::string description() override @@ -70,11 +72,11 @@ struct CmdCopy : StorePathsCommand #ifdef ENABLE_S3 Example{ "To copy Hello to an S3 binary cache:", - "nix copy --to s3://my-bucket?region=eu-west-1 nixpkgs.hello" + "nix copy --to s3://my-bucket?region=eu-west-1 nixpkgs#hello" }, Example{ "To copy Hello to an S3-compatible binary cache:", - "nix copy --to s3://my-bucket?region=eu-west-1&endpoint=example.com nixpkgs.hello" + "nix copy --to s3://my-bucket?region=eu-west-1&endpoint=example.com nixpkgs#hello" }, #endif }; @@ -87,11 +89,16 @@ struct CmdCopy : StorePathsCommand return srcUri.empty() ? StoreCommand::createStore() : openStore(srcUri); } - void run(ref srcStore, StorePaths storePaths) override + void run(ref store) override { if (srcUri.empty() && dstUri.empty()) throw UsageError("you must pass '--from' and/or '--to'"); + StorePathsCommand::run(store); + } + + void run(ref srcStore, StorePaths storePaths) override + { ref dstStore = dstUri.empty() ? openStore() : openStore(dstUri); copyPaths(srcStore, dstStore, StorePathSet(storePaths.begin(), storePaths.end()), @@ -99,4 +106,4 @@ struct CmdCopy : StorePathsCommand } }; -static auto r1 = registerCommand("copy"); +static auto rCmdCopy = registerCommand("copy"); diff --git a/src/nix/describe-stores.cc b/src/nix/describe-stores.cc new file mode 100644 index 000000000..1dd384c0e --- /dev/null +++ b/src/nix/describe-stores.cc @@ -0,0 +1,44 @@ +#include "command.hh" +#include "common-args.hh" +#include "shared.hh" +#include "store-api.hh" + +#include + +using namespace nix; + +struct CmdDescribeStores : Command, MixJSON +{ + std::string description() override + { + return "show registered store types and their available options"; + } + + Category category() override { return catUtility; } + + void run() override + { + auto res = nlohmann::json::object(); + for (auto & implem : *Implementations::registered) { + auto storeConfig = implem.getConfig(); + auto storeName = storeConfig->name(); + res[storeName] = storeConfig->toJSON(); + } + if (json) { + std::cout << res; + } else { + for (auto & [storeName, storeConfig] : res.items()) { + std::cout << "## " << storeName << std::endl << std::endl; + for (auto & [optionName, optionDesc] : storeConfig.items()) { + std::cout << "### " << optionName << std::endl << std::endl; + std::cout << optionDesc["description"].get() << std::endl; + std::cout << "default: " << optionDesc["defaultValue"] << std::endl <("describe-stores"); diff --git a/src/nix/develop.cc b/src/nix/develop.cc index eb93f56fc..a46ea39b6 100644 --- a/src/nix/develop.cc +++ b/src/nix/develop.cc @@ -15,7 +15,7 @@ struct Var { bool exported = true; bool associative = false; - std::string value; // quoted string or array + std::string quoted; // quoted string or array }; struct BuildEnvironment @@ -68,22 +68,22 @@ BuildEnvironment readEnvironment(const Path & path) std::smatch match; - if (std::regex_search(pos, file.cend(), match, declareRegex)) { + if (std::regex_search(pos, file.cend(), match, declareRegex, std::regex_constants::match_continuous)) { pos = match[0].second; exported.insert(match[1]); } - else if (std::regex_search(pos, file.cend(), match, varRegex)) { + else if (std::regex_search(pos, file.cend(), match, varRegex, std::regex_constants::match_continuous)) { pos = match[0].second; - res.env.insert({match[1], Var { .exported = exported.count(match[1]) > 0, .value = match[2] }}); + res.env.insert({match[1], Var { .exported = exported.count(match[1]) > 0, .quoted = match[2] }}); } - else if (std::regex_search(pos, file.cend(), match, assocArrayRegex)) { + else if (std::regex_search(pos, file.cend(), match, assocArrayRegex, std::regex_constants::match_continuous)) { pos = match[0].second; - res.env.insert({match[1], Var { .associative = true, .value = match[2] }}); + res.env.insert({match[1], Var { .associative = true, .quoted = match[2] }}); } - else if (std::regex_search(pos, file.cend(), match, functionRegex)) { + else if (std::regex_search(pos, file.cend(), match, functionRegex, std::regex_constants::match_continuous)) { res.bashFunctions = std::string(pos, file.cend()); break; } @@ -92,6 +92,8 @@ BuildEnvironment readEnvironment(const Path & path) path, file.substr(pos - file.cbegin(), 60)); } + res.env.erase("__output"); + return res; } @@ -124,27 +126,36 @@ StorePath getDerivationEnvironment(ref store, const StorePath & drvPath) /* Rehash and write the derivation. FIXME: would be nice to use 'buildDerivation', but that's privileged. */ - auto drvName = std::string(drvPath.name()); - assert(hasSuffix(drvName, ".drv")); - drvName.resize(drvName.size() - 4); - drvName += "-env"; - for (auto & output : drv.outputs) - drv.env.erase(output.first); - drv.env["out"] = ""; - drv.env["outputs"] = "out"; + drv.name += "-env"; + for (auto & output : drv.outputs) { + output.second = { .output = DerivationOutputInputAddressed { .path = StorePath::dummy } }; + drv.env[output.first] = ""; + } drv.inputSrcs.insert(std::move(getEnvShPath)); - Hash h = hashDerivationModulo(*store, drv, true); - auto shellOutPath = store->makeOutputPath("out", h, drvName); - drv.outputs.insert_or_assign("out", DerivationOutput { .path = shellOutPath }); - drv.env["out"] = store->printStorePath(shellOutPath); - auto shellDrvPath2 = writeDerivation(store, drv, drvName); + Hash h = std::get<0>(hashDerivationModulo(*store, drv, true)); + + for (auto & output : drv.outputs) { + auto outPath = store->makeOutputPath(output.first, h, drv.name); + output.second = { .output = DerivationOutputInputAddressed { .path = outPath } }; + drv.env[output.first] = store->printStorePath(outPath); + } + + auto shellDrvPath = writeDerivation(*store, drv); /* Build the derivation. */ - store->buildPaths({{shellDrvPath2}}); + store->buildPaths({{shellDrvPath}}); - assert(store->isValidPath(shellOutPath)); + for (auto & [_0, outputAndOptPath] : drv.outputsAndOptPaths(*store)) { + auto & [_1, optPath] = outputAndOptPath; + assert(optPath); + auto & outPath = *optPath; + assert(store->isValidPath(outPath)); + auto outPathS = store->toRealPath(outPath); + if (lstat(outPathS).st_size) + return outPath; + } - return shellOutPath; + throw Error("get-env.sh failed to produce an environment"); } struct Common : InstallableCommand, MixProfile @@ -170,8 +181,12 @@ struct Common : InstallableCommand, MixProfile "UID", }; - void makeRcScript(const BuildEnvironment & buildEnvironment, std::ostream & out) + std::string makeRcScript( + const BuildEnvironment & buildEnvironment, + const Path & outputsDir = absPath(".") + "/outputs") { + std::ostringstream out; + out << "unset shellHook\n"; out << "nix_saved_PATH=\"$PATH\"\n"; @@ -179,9 +194,9 @@ struct Common : InstallableCommand, MixProfile for (auto & i : buildEnvironment.env) { if (!ignoreVars.count(i.first) && !hasPrefix(i.first, "BASH_")) { if (i.second.associative) - out << fmt("declare -A %s=(%s)\n", i.first, i.second.value); + out << fmt("declare -A %s=(%s)\n", i.first, i.second.quoted); else { - out << fmt("%s=%s\n", i.first, i.second.value); + out << fmt("%s=%s\n", i.first, i.second.quoted); if (i.second.exported) out << fmt("export %s\n", i.first); } @@ -192,13 +207,31 @@ struct Common : InstallableCommand, MixProfile out << buildEnvironment.bashFunctions << "\n"; - // FIXME: set outputs - out << "export NIX_BUILD_TOP=\"$(mktemp -d --tmpdir nix-shell.XXXXXX)\"\n"; for (auto & i : {"TMP", "TMPDIR", "TEMP", "TEMPDIR"}) out << fmt("export %s=\"$NIX_BUILD_TOP\"\n", i); out << "eval \"$shellHook\"\n"; + + /* Substitute occurrences of output paths. */ + auto outputs = buildEnvironment.env.find("outputs"); + assert(outputs != buildEnvironment.env.end()); + + // FIXME: properly unquote 'outputs'. + StringMap rewrites; + for (auto & outputName : tokenizeString>(replaceStrings(outputs->second.quoted, "'", ""))) { + auto from = buildEnvironment.env.find(outputName); + assert(from != buildEnvironment.env.end()); + // FIXME: unquote + rewrites.insert({from->second.quoted, outputsDir + "/" + outputName}); + } + + return rewriteStrings(out.str(), rewrites); + } + + Strings getDefaultFlakeAttrPaths() override + { + return {"devShell." + settings.thisSystem.get(), "defaultPackage." + settings.thisSystem.get()}; } StorePath getShellOutPath(ref store) @@ -234,19 +267,57 @@ struct Common : InstallableCommand, MixProfile struct CmdDevelop : Common, MixEnvironment { std::vector command; + std::optional phase; CmdDevelop() { addFlag({ .longName = "command", .shortName = 'c', - .description = "command and arguments to be executed insted of an interactive shell", + .description = "command and arguments to be executed instead of an interactive shell", .labels = {"command", "args"}, .handler = {[&](std::vector ss) { if (ss.empty()) throw UsageError("--command requires at least one argument"); command = ss; }} }); + + addFlag({ + .longName = "phase", + .description = "phase to run (e.g. `build` or `configure`)", + .labels = {"phase-name"}, + .handler = {&phase}, + }); + + addFlag({ + .longName = "configure", + .description = "run the configure phase", + .handler = {&phase, {"configure"}}, + }); + + addFlag({ + .longName = "build", + .description = "run the build phase", + .handler = {&phase, {"build"}}, + }); + + addFlag({ + .longName = "check", + .description = "run the check phase", + .handler = {&phase, {"check"}}, + }); + + addFlag({ + .longName = "install", + .description = "run the install phase", + .handler = {&phase, {"install"}}, + }); + + addFlag({ + .longName = "installcheck", + .description = "run the installcheck phase", + .handler = {&phase, {"installCheck"}}, + }); } std::string description() override @@ -259,11 +330,15 @@ struct CmdDevelop : Common, MixEnvironment return { Example{ "To get the build environment of GNU hello:", - "nix develop nixpkgs.hello" + "nix develop nixpkgs#hello" + }, + Example{ + "To get the build environment of the default package of flake in the current directory:", + "nix develop" }, Example{ "To store the build environment in a profile:", - "nix develop --profile /tmp/my-shell nixpkgs.hello" + "nix develop --profile /tmp/my-shell nixpkgs#hello" }, Example{ "To use a build environment previously recorded in a profile:", @@ -278,28 +353,56 @@ struct CmdDevelop : Common, MixEnvironment auto [rcFileFd, rcFilePath] = createTempFile("nix-shell"); - std::ostringstream ss; - makeRcScript(buildEnvironment, ss); + auto script = makeRcScript(buildEnvironment); - ss << fmt("rm -f '%s'\n", rcFilePath); + if (verbosity >= lvlDebug) + script += "set -x\n"; - if (!command.empty()) { + script += fmt("rm -f '%s'\n", rcFilePath); + + if (phase) { + if (!command.empty()) + throw UsageError("you cannot use both '--command' and '--phase'"); + // FIXME: foundMakefile is set by buildPhase, need to get + // rid of that. + script += fmt("foundMakefile=1\n"); + script += fmt("runHook %1%Phase\n", *phase); + script += fmt("exit 0\n", *phase); + } + + else if (!command.empty()) { std::vector args; for (auto s : command) args.push_back(shellEscape(s)); - ss << fmt("exec %s\n", concatStringsSep(" ", args)); + script += fmt("exec %s\n", concatStringsSep(" ", args)); } - writeFull(rcFileFd.get(), ss.str()); + writeFull(rcFileFd.get(), script); stopProgressBar(); - auto shell = getEnv("SHELL").value_or("bash"); - setEnviron(); // prevent garbage collection until shell exits setenv("NIX_GCROOT", gcroot.data(), 1); + Path shell = "bash"; + + try { + auto state = getEvalState(); + + auto bashInstallable = std::make_shared( + state, + installable->nixpkgsFlakeRef(), + Strings{"bashInteractive"}, + Strings{"legacyPackages." + settings.thisSystem.get() + "."}, + lockFlags); + + shell = state->store->printStorePath( + toStorePath(state->store, Realise::Outputs, OperateOn::Output, bashInstallable)) + "/bin/bash"; + } catch (Error &) { + ignoreException(); + } + auto args = Strings{std::string(baseNameOf(shell)), "--rcfile", rcFilePath}; restoreAffinity(); @@ -323,7 +426,7 @@ struct CmdPrintDevEnv : Common return { Example{ "To apply the build environment of GNU hello to the current shell:", - ". <(nix print-dev-env nixpkgs.hello)" + ". <(nix print-dev-env nixpkgs#hello)" }, }; } @@ -336,9 +439,9 @@ struct CmdPrintDevEnv : Common stopProgressBar(); - makeRcScript(buildEnvironment, std::cout); + std::cout << makeRcScript(buildEnvironment); } }; -static auto r1 = registerCommand("print-dev-env"); -static auto r2 = registerCommand("develop"); +static auto rCmdPrintDevEnv = registerCommand("print-dev-env"); +static auto rCmdDevelop = registerCommand("develop"); diff --git a/src/nix/diff-closures.cc b/src/nix/diff-closures.cc new file mode 100644 index 000000000..30e7b20e1 --- /dev/null +++ b/src/nix/diff-closures.cc @@ -0,0 +1,146 @@ +#include "command.hh" +#include "shared.hh" +#include "store-api.hh" +#include "common-args.hh" +#include "names.hh" + +#include + +namespace nix { + +struct Info +{ + std::string outputName; +}; + +// name -> version -> store paths +typedef std::map>> GroupedPaths; + +GroupedPaths getClosureInfo(ref store, const StorePath & toplevel) +{ + StorePathSet closure; + store->computeFSClosure({toplevel}, closure); + + GroupedPaths groupedPaths; + + for (auto & path : closure) { + /* Strip the output name. Unfortunately this is ambiguous (we + can't distinguish between output names like "bin" and + version suffixes like "unstable"). */ + static std::regex regex("(.*)-([a-z]+|lib32|lib64)"); + std::smatch match; + std::string name(path.name()); + std::string outputName; + if (std::regex_match(name, match, regex)) { + name = match[1]; + outputName = match[2]; + } + + DrvName drvName(name); + groupedPaths[drvName.name][drvName.version].emplace(path, Info { .outputName = outputName }); + } + + return groupedPaths; +} + +std::string showVersions(const std::set & versions) +{ + if (versions.empty()) return "∅"; + std::set versions2; + for (auto & version : versions) + versions2.insert(version.empty() ? "ε" : version); + return concatStringsSep(", ", versions2); +} + +void printClosureDiff( + ref store, + const StorePath & beforePath, + const StorePath & afterPath, + std::string_view indent) +{ + auto beforeClosure = getClosureInfo(store, beforePath); + auto afterClosure = getClosureInfo(store, afterPath); + + std::set allNames; + for (auto & [name, _] : beforeClosure) allNames.insert(name); + for (auto & [name, _] : afterClosure) allNames.insert(name); + + for (auto & name : allNames) { + auto & beforeVersions = beforeClosure[name]; + auto & afterVersions = afterClosure[name]; + + auto totalSize = [&](const std::map> & versions) + { + uint64_t sum = 0; + for (auto & [_, paths] : versions) + for (auto & [path, _] : paths) + sum += store->queryPathInfo(path)->narSize; + return sum; + }; + + auto beforeSize = totalSize(beforeVersions); + auto afterSize = totalSize(afterVersions); + auto sizeDelta = (int64_t) afterSize - (int64_t) beforeSize; + auto showDelta = std::abs(sizeDelta) >= 8 * 1024; + + std::set removed, unchanged; + for (auto & [version, _] : beforeVersions) + if (!afterVersions.count(version)) removed.insert(version); else unchanged.insert(version); + + std::set added; + for (auto & [version, _] : afterVersions) + if (!beforeVersions.count(version)) added.insert(version); + + if (showDelta || !removed.empty() || !added.empty()) { + std::vector items; + if (!removed.empty() || !added.empty()) + items.push_back(fmt("%s → %s", showVersions(removed), showVersions(added))); + if (showDelta) + items.push_back(fmt("%s%+.1f KiB" ANSI_NORMAL, sizeDelta > 0 ? ANSI_RED : ANSI_GREEN, sizeDelta / 1024.0)); + std::cout << fmt("%s%s: %s\n", indent, name, concatStringsSep(", ", items)); + } + } +} + +} + +using namespace nix; + +struct CmdDiffClosures : SourceExprCommand +{ + std::string _before, _after; + + CmdDiffClosures() + { + expectArg("before", &_before); + expectArg("after", &_after); + } + + std::string description() override + { + return "show what packages and versions were added and removed between two closures"; + } + + Category category() override { return catSecondary; } + + Examples examples() override + { + return { + { + "To show what got added and removed between two versions of the NixOS system profile:", + "nix diff-closures /nix/var/nix/profiles/system-655-link /nix/var/nix/profiles/system-658-link", + }, + }; + } + + void run(ref store) override + { + auto before = parseInstallable(store, _before); + auto beforePath = toStorePath(store, Realise::Outputs, operateOn, before); + auto after = parseInstallable(store, _after); + auto afterPath = toStorePath(store, Realise::Outputs, operateOn, after); + printClosureDiff(store, beforePath, afterPath, ""); + } +}; + +static auto rCmdDiffClosures = registerCommand("diff-closures"); diff --git a/src/nix/doctor.cc b/src/nix/doctor.cc index 82e92cdd0..4588ac05e 100644 --- a/src/nix/doctor.cc +++ b/src/nix/doctor.cc @@ -49,9 +49,7 @@ struct CmdDoctor : StoreCommand { logger->log("Running checks against store uri: " + store->getUri()); - auto type = getStoreType(); - - if (type < tOther) { + if (store.dynamic_pointer_cast()) { success &= checkNixInPath(); success &= checkProfileRoots(store); } @@ -133,4 +131,4 @@ struct CmdDoctor : StoreCommand } }; -static auto r1 = registerCommand("doctor"); +static auto rCmdDoctor = registerCommand("doctor"); diff --git a/src/nix/dump-path.cc b/src/nix/dump-path.cc index e1de71bf8..6fd197531 100644 --- a/src/nix/dump-path.cc +++ b/src/nix/dump-path.cc @@ -30,4 +30,4 @@ struct CmdDumpPath : StorePathCommand } }; -static auto r1 = registerCommand("dump-path"); +static auto rDumpPath = registerCommand("dump-path"); diff --git a/src/nix/edit.cc b/src/nix/edit.cc index 067d3a973..51c16f5a9 100644 --- a/src/nix/edit.cc +++ b/src/nix/edit.cc @@ -20,7 +20,7 @@ struct CmdEdit : InstallableCommand return { Example{ "To open the Nix expression of the GNU Hello package:", - "nix edit nixpkgs.hello" + "nix edit nixpkgs#hello" }, }; } @@ -45,6 +45,7 @@ struct CmdEdit : InstallableCommand auto args = editorFor(pos); + restoreSignals(); execvp(args.front().c_str(), stringsToCharPtrs(args).data()); std::string command; @@ -53,4 +54,4 @@ struct CmdEdit : InstallableCommand } }; -static auto r1 = registerCommand("edit"); +static auto rCmdEdit = registerCommand("edit"); diff --git a/src/nix/eval.cc b/src/nix/eval.cc index 26e98ac2a..43ce46546 100644 --- a/src/nix/eval.cc +++ b/src/nix/eval.cc @@ -12,10 +12,18 @@ using namespace nix; struct CmdEval : MixJSON, InstallableCommand { bool raw = false; + std::optional apply; CmdEval() { mkFlag(0, "raw", "print strings unquoted", &raw); + + addFlag({ + .longName = "apply", + .description = "apply a function to each argument", + .labels = {"expr"}, + .handler = {&apply}, + }); } std::string description() override @@ -26,21 +34,25 @@ struct CmdEval : MixJSON, InstallableCommand Examples examples() override { return { - Example{ + { "To evaluate a Nix expression given on the command line:", - "nix eval '(1 + 2)'" + "nix eval --expr '1 + 2'" }, - Example{ + { "To evaluate a Nix expression from a file or URI:", - "nix eval -f channel:nixos-17.09 hello.name" + "nix eval -f ./my-nixpkgs hello.name" }, - Example{ + { "To get the current version of Nixpkgs:", - "nix eval --raw nixpkgs.lib.version" + "nix eval --raw nixpkgs#lib.version" }, - Example{ + { "To print the store path of the Hello package:", - "nix eval --raw nixpkgs.hello" + "nix eval --raw nixpkgs#hello" + }, + { + "To get a list of checks in the 'nix' flake:", + "nix eval nix#checks.x86_64-linux --apply builtins.attrNames" }, }; } @@ -57,6 +69,14 @@ struct CmdEval : MixJSON, InstallableCommand auto v = installable->toValue(*state).first; PathSet context; + if (apply) { + auto vApply = state->allocValue(); + state->eval(state->parseExprFromString(*apply, absPath(".")), *vApply); + auto vRes = state->allocValue(); + state->callFunction(*vApply, *v, *vRes, noPos); + v = vRes; + } + if (raw) { stopProgressBar(); std::cout << state->coerceToString(noPos, *v, context); @@ -70,4 +90,4 @@ struct CmdEval : MixJSON, InstallableCommand } }; -static auto r1 = registerCommand("eval"); +static auto rCmdEval = registerCommand("eval"); diff --git a/src/nix/flake.cc b/src/nix/flake.cc new file mode 100644 index 000000000..d45f13029 --- /dev/null +++ b/src/nix/flake.cc @@ -0,0 +1,968 @@ +#include "command.hh" +#include "common-args.hh" +#include "shared.hh" +#include "eval.hh" +#include "eval-inline.hh" +#include "flake/flake.hh" +#include "get-drvs.hh" +#include "store-api.hh" +#include "derivations.hh" +#include "attr-path.hh" +#include "fetchers.hh" +#include "registry.hh" +#include "json.hh" +#include "eval-cache.hh" + +#include +#include +#include + +using namespace nix; +using namespace nix::flake; + +class FlakeCommand : virtual Args, public MixFlakeOptions +{ + std::string flakeUrl = "."; + +public: + + FlakeCommand() + { + expectArgs({ + .label = "flake-url", + .optional = true, + .handler = {&flakeUrl}, + .completer = {[&](size_t, std::string_view prefix) { + completeFlakeRef(getStore(), prefix); + }} + }); + } + + FlakeRef getFlakeRef() + { + return parseFlakeRef(flakeUrl, absPath(".")); //FIXME + } + + Flake getFlake() + { + auto evalState = getEvalState(); + return flake::getFlake(*evalState, getFlakeRef(), lockFlags.useRegistries); + } + + LockedFlake lockFlake() + { + return flake::lockFlake(*getEvalState(), getFlakeRef(), lockFlags); + } + + std::optional getFlakeRefForCompletion() override + { + return getFlakeRef(); + } +}; + +static void printFlakeInfo(const Store & store, const Flake & flake) +{ + logger->stdout("Resolved URL: %s", flake.resolvedRef.to_string()); + logger->stdout("Locked URL: %s", flake.lockedRef.to_string()); + if (flake.description) + logger->stdout("Description: %s", *flake.description); + logger->stdout("Path: %s", store.printStorePath(flake.sourceInfo->storePath)); + if (auto rev = flake.lockedRef.input.getRev()) + logger->stdout("Revision: %s", rev->to_string(Base16, false)); + if (auto revCount = flake.lockedRef.input.getRevCount()) + logger->stdout("Revisions: %s", *revCount); + if (auto lastModified = flake.lockedRef.input.getLastModified()) + logger->stdout("Last modified: %s", + std::put_time(std::localtime(&*lastModified), "%F %T")); +} + +static nlohmann::json flakeToJson(const Store & store, const Flake & flake) +{ + nlohmann::json j; + if (flake.description) + j["description"] = *flake.description; + j["originalUrl"] = flake.originalRef.to_string(); + j["original"] = attrsToJson(flake.originalRef.toAttrs()); + j["resolvedUrl"] = flake.resolvedRef.to_string(); + j["resolved"] = attrsToJson(flake.resolvedRef.toAttrs()); + j["url"] = flake.lockedRef.to_string(); // FIXME: rename to lockedUrl + j["locked"] = attrsToJson(flake.lockedRef.toAttrs()); + if (auto rev = flake.lockedRef.input.getRev()) + j["revision"] = rev->to_string(Base16, false); + if (auto revCount = flake.lockedRef.input.getRevCount()) + j["revCount"] = *revCount; + if (auto lastModified = flake.lockedRef.input.getLastModified()) + j["lastModified"] = *lastModified; + j["path"] = store.printStorePath(flake.sourceInfo->storePath); + return j; +} + +struct CmdFlakeUpdate : FlakeCommand +{ + std::string description() override + { + return "update flake lock file"; + } + + void run(nix::ref store) override + { + /* Use --refresh by default for 'nix flake update'. */ + settings.tarballTtl = 0; + + lockFlake(); + } +}; + +static void enumerateOutputs(EvalState & state, Value & vFlake, + std::function callback) +{ + state.forceAttrs(vFlake); + + auto aOutputs = vFlake.attrs->get(state.symbols.create("outputs")); + assert(aOutputs); + + state.forceAttrs(*aOutputs->value); + + for (auto & attr : *aOutputs->value->attrs) + callback(attr.name, *attr.value, *attr.pos); +} + +struct CmdFlakeInfo : FlakeCommand, MixJSON +{ + std::string description() override + { + return "list info about a given flake"; + } + + void run(nix::ref store) override + { + auto flake = getFlake(); + + if (json) { + auto json = flakeToJson(*store, flake); + logger->stdout("%s", json.dump()); + } else + printFlakeInfo(*store, flake); + } +}; + +struct CmdFlakeListInputs : FlakeCommand, MixJSON +{ + std::string description() override + { + return "list flake inputs"; + } + + void run(nix::ref store) override + { + auto flake = lockFlake(); + + if (json) + logger->stdout("%s", flake.lockFile.toJson()); + else { + logger->stdout("%s", flake.flake.lockedRef); + + std::unordered_set> visited; + + std::function recurse; + + recurse = [&](const Node & node, const std::string & prefix) + { + for (const auto & [i, input] : enumerate(node.inputs)) { + bool last = i + 1 == node.inputs.size(); + + if (auto lockedNode = std::get_if<0>(&input.second)) { + logger->stdout("%s" ANSI_BOLD "%s" ANSI_NORMAL ": %s", + prefix + (last ? treeLast : treeConn), input.first, + *lockedNode ? (*lockedNode)->lockedRef : flake.flake.lockedRef); + + bool firstVisit = visited.insert(*lockedNode).second; + + if (firstVisit) recurse(**lockedNode, prefix + (last ? treeNull : treeLine)); + } else if (auto follows = std::get_if<1>(&input.second)) { + logger->stdout("%s" ANSI_BOLD "%s" ANSI_NORMAL " follows input '%s'", + prefix + (last ? treeLast : treeConn), input.first, + printInputPath(*follows)); + } + } + }; + + visited.insert(flake.lockFile.root); + recurse(*flake.lockFile.root, ""); + } + } +}; + +struct CmdFlakeCheck : FlakeCommand +{ + bool build = true; + + CmdFlakeCheck() + { + addFlag({ + .longName = "no-build", + .description = "do not build checks", + .handler = {&build, false} + }); + } + + std::string description() override + { + return "check whether the flake evaluates and run its tests"; + } + + void run(nix::ref store) override + { + settings.readOnlyMode = !build; + + auto state = getEvalState(); + auto flake = lockFlake(); + + // FIXME: rewrite to use EvalCache. + + auto checkSystemName = [&](const std::string & system, const Pos & pos) { + // FIXME: what's the format of "system"? + if (system.find('-') == std::string::npos) + throw Error("'%s' is not a valid system type, at %s", system, pos); + }; + + auto checkDerivation = [&](const std::string & attrPath, Value & v, const Pos & pos) { + try { + auto drvInfo = getDerivation(*state, v, false); + if (!drvInfo) + throw Error("flake attribute '%s' is not a derivation", attrPath); + // FIXME: check meta attributes + return store->parseStorePath(drvInfo->queryDrvPath()); + } catch (Error & e) { + e.addTrace(pos, hintfmt("while checking the derivation '%s'", attrPath)); + throw; + } + }; + + std::vector drvPaths; + + auto checkApp = [&](const std::string & attrPath, Value & v, const Pos & pos) { + try { + #if 0 + // FIXME + auto app = App(*state, v); + for (auto & i : app.context) { + auto [drvPathS, outputName] = decodeContext(i); + store->parseStorePath(drvPathS); + } + #endif + } catch (Error & e) { + e.addTrace(pos, hintfmt("while checking the app definition '%s'", attrPath)); + throw; + } + }; + + auto checkOverlay = [&](const std::string & attrPath, Value & v, const Pos & pos) { + try { + state->forceValue(v, pos); + if (v.type != tLambda || v.lambda.fun->matchAttrs || std::string(v.lambda.fun->arg) != "final") + throw Error("overlay does not take an argument named 'final'"); + auto body = dynamic_cast(v.lambda.fun->body); + if (!body || body->matchAttrs || std::string(body->arg) != "prev") + throw Error("overlay does not take an argument named 'prev'"); + // FIXME: if we have a 'nixpkgs' input, use it to + // evaluate the overlay. + } catch (Error & e) { + e.addTrace(pos, hintfmt("while checking the overlay '%s'", attrPath)); + throw; + } + }; + + auto checkModule = [&](const std::string & attrPath, Value & v, const Pos & pos) { + try { + state->forceValue(v, pos); + if (v.type == tLambda) { + if (!v.lambda.fun->matchAttrs || !v.lambda.fun->formals->ellipsis) + throw Error("module must match an open attribute set ('{ config, ... }')"); + } else if (v.type == tAttrs) { + for (auto & attr : *v.attrs) + try { + state->forceValue(*attr.value, *attr.pos); + } catch (Error & e) { + e.addTrace(*attr.pos, hintfmt("while evaluating the option '%s'", attr.name)); + throw; + } + } else + throw Error("module must be a function or an attribute set"); + // FIXME: if we have a 'nixpkgs' input, use it to + // check the module. + } catch (Error & e) { + e.addTrace(pos, hintfmt("while checking the NixOS module '%s'", attrPath)); + throw; + } + }; + + std::function checkHydraJobs; + + checkHydraJobs = [&](const std::string & attrPath, Value & v, const Pos & pos) { + try { + state->forceAttrs(v, pos); + + if (state->isDerivation(v)) + throw Error("jobset should not be a derivation at top-level"); + + for (auto & attr : *v.attrs) { + state->forceAttrs(*attr.value, *attr.pos); + if (!state->isDerivation(*attr.value)) + checkHydraJobs(attrPath + "." + (std::string) attr.name, + *attr.value, *attr.pos); + } + + } catch (Error & e) { + e.addTrace(pos, hintfmt("while checking the Hydra jobset '%s'", attrPath)); + throw; + } + }; + + auto checkNixOSConfiguration = [&](const std::string & attrPath, Value & v, const Pos & pos) { + try { + Activity act(*logger, lvlChatty, actUnknown, + fmt("checking NixOS configuration '%s'", attrPath)); + Bindings & bindings(*state->allocBindings(0)); + auto vToplevel = findAlongAttrPath(*state, "config.system.build.toplevel", bindings, v).first; + state->forceAttrs(*vToplevel, pos); + if (!state->isDerivation(*vToplevel)) + throw Error("attribute 'config.system.build.toplevel' is not a derivation"); + } catch (Error & e) { + e.addTrace(pos, hintfmt("while checking the NixOS configuration '%s'", attrPath)); + throw; + } + }; + + auto checkTemplate = [&](const std::string & attrPath, Value & v, const Pos & pos) { + try { + Activity act(*logger, lvlChatty, actUnknown, + fmt("checking template '%s'", attrPath)); + + state->forceAttrs(v, pos); + + if (auto attr = v.attrs->get(state->symbols.create("path"))) { + if (attr->name == state->symbols.create("path")) { + PathSet context; + auto path = state->coerceToPath(*attr->pos, *attr->value, context); + if (!store->isInStore(path)) + throw Error("template '%s' has a bad 'path' attribute"); + // TODO: recursively check the flake in 'path'. + } + } else + throw Error("template '%s' lacks attribute 'path'", attrPath); + + if (auto attr = v.attrs->get(state->symbols.create("description"))) + state->forceStringNoCtx(*attr->value, *attr->pos); + else + throw Error("template '%s' lacks attribute 'description'", attrPath); + + for (auto & attr : *v.attrs) { + std::string name(attr.name); + if (name != "path" && name != "description") + throw Error("template '%s' has unsupported attribute '%s'", attrPath, name); + } + } catch (Error & e) { + e.addTrace(pos, hintfmt("while checking the template '%s'", attrPath)); + throw; + } + }; + + auto checkBundler = [&](const std::string & attrPath, Value & v, const Pos & pos) { + try { + state->forceValue(v, pos); + if (v.type != tLambda) + throw Error("bundler must be a function"); + if (!v.lambda.fun->formals || + v.lambda.fun->formals->argNames.find(state->symbols.create("program")) == v.lambda.fun->formals->argNames.end() || + v.lambda.fun->formals->argNames.find(state->symbols.create("system")) == v.lambda.fun->formals->argNames.end()) + throw Error("bundler must take formal arguments 'program' and 'system'"); + } catch (Error & e) { + e.addTrace(pos, hintfmt("while checking the template '%s'", attrPath)); + throw; + } + }; + + { + Activity act(*logger, lvlInfo, actUnknown, "evaluating flake"); + + auto vFlake = state->allocValue(); + flake::callFlake(*state, flake, *vFlake); + + enumerateOutputs(*state, + *vFlake, + [&](const std::string & name, Value & vOutput, const Pos & pos) { + Activity act(*logger, lvlChatty, actUnknown, + fmt("checking flake output '%s'", name)); + + try { + state->forceValue(vOutput, pos); + + if (name == "checks") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) { + checkSystemName(attr.name, *attr.pos); + state->forceAttrs(*attr.value, *attr.pos); + for (auto & attr2 : *attr.value->attrs) { + auto drvPath = checkDerivation( + fmt("%s.%s.%s", name, attr.name, attr2.name), + *attr2.value, *attr2.pos); + if ((std::string) attr.name == settings.thisSystem.get()) + drvPaths.push_back({drvPath}); + } + } + } + + else if (name == "packages") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) { + checkSystemName(attr.name, *attr.pos); + state->forceAttrs(*attr.value, *attr.pos); + for (auto & attr2 : *attr.value->attrs) + checkDerivation( + fmt("%s.%s.%s", name, attr.name, attr2.name), + *attr2.value, *attr2.pos); + } + } + + else if (name == "apps") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) { + checkSystemName(attr.name, *attr.pos); + state->forceAttrs(*attr.value, *attr.pos); + for (auto & attr2 : *attr.value->attrs) + checkApp( + fmt("%s.%s.%s", name, attr.name, attr2.name), + *attr2.value, *attr2.pos); + } + } + + else if (name == "defaultPackage" || name == "devShell") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) { + checkSystemName(attr.name, *attr.pos); + checkDerivation( + fmt("%s.%s", name, attr.name), + *attr.value, *attr.pos); + } + } + + else if (name == "defaultApp") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) { + checkSystemName(attr.name, *attr.pos); + checkApp( + fmt("%s.%s", name, attr.name), + *attr.value, *attr.pos); + } + } + + else if (name == "legacyPackages") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) { + checkSystemName(attr.name, *attr.pos); + // FIXME: do getDerivations? + } + } + + else if (name == "overlay") + checkOverlay(name, vOutput, pos); + + else if (name == "overlays") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) + checkOverlay(fmt("%s.%s", name, attr.name), + *attr.value, *attr.pos); + } + + else if (name == "nixosModule") + checkModule(name, vOutput, pos); + + else if (name == "nixosModules") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) + checkModule(fmt("%s.%s", name, attr.name), + *attr.value, *attr.pos); + } + + else if (name == "nixosConfigurations") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) + checkNixOSConfiguration(fmt("%s.%s", name, attr.name), + *attr.value, *attr.pos); + } + + else if (name == "hydraJobs") + checkHydraJobs(name, vOutput, pos); + + else if (name == "defaultTemplate") + checkTemplate(name, vOutput, pos); + + else if (name == "templates") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) + checkTemplate(fmt("%s.%s", name, attr.name), + *attr.value, *attr.pos); + } + + else if (name == "defaultBundler") + checkBundler(name, vOutput, pos); + + else if (name == "bundlers") { + state->forceAttrs(vOutput, pos); + for (auto & attr : *vOutput.attrs) + checkBundler(fmt("%s.%s", name, attr.name), + *attr.value, *attr.pos); + } + + else + warn("unknown flake output '%s'", name); + + } catch (Error & e) { + e.addTrace(pos, hintfmt("while checking flake output '%s'", name)); + throw; + } + }); + } + + if (build && !drvPaths.empty()) { + Activity act(*logger, lvlInfo, actUnknown, "running flake checks"); + store->buildPaths(drvPaths); + } + } +}; + +struct CmdFlakeInitCommon : virtual Args, EvalCommand +{ + std::string templateUrl = "templates"; + Path destDir; + + const Strings attrsPathPrefixes{"templates."}; + const LockFlags lockFlags{ .writeLockFile = false }; + + CmdFlakeInitCommon() + { + addFlag({ + .longName = "template", + .shortName = 't', + .description = "the template to use", + .labels = {"template"}, + .handler = {&templateUrl}, + .completer = {[&](size_t, std::string_view prefix) { + completeFlakeRefWithFragment( + getEvalState(), + lockFlags, + attrsPathPrefixes, + {"defaultTemplate"}, + prefix); + }} + }); + } + + void run(nix::ref store) override + { + auto flakeDir = absPath(destDir); + + auto evalState = getEvalState(); + + auto [templateFlakeRef, templateName] = parseFlakeRefWithFragment(templateUrl, absPath(".")); + + auto installable = InstallableFlake( + evalState, std::move(templateFlakeRef), + Strings{templateName == "" ? "defaultTemplate" : templateName}, + Strings(attrsPathPrefixes), lockFlags); + + auto [cursor, attrPath] = installable.getCursor(*evalState); + + auto templateDir = cursor->getAttr("path")->getString(); + + assert(store->isInStore(templateDir)); + + std::vector files; + + std::function copyDir; + copyDir = [&](const Path & from, const Path & to) + { + createDirs(to); + + for (auto & entry : readDirectory(from)) { + auto from2 = from + "/" + entry.name; + auto to2 = to + "/" + entry.name; + auto st = lstat(from2); + if (S_ISDIR(st.st_mode)) + copyDir(from2, to2); + else if (S_ISREG(st.st_mode)) { + auto contents = readFile(from2); + if (pathExists(to2)) { + auto contents2 = readFile(to2); + if (contents != contents2) + throw Error("refusing to overwrite existing file '%s'", to2); + } else + writeFile(to2, contents); + } + else if (S_ISLNK(st.st_mode)) { + auto target = readLink(from2); + if (pathExists(to2)) { + if (readLink(to2) != target) + throw Error("refusing to overwrite existing symlink '%s'", to2); + } else + createSymlink(target, to2); + } + else + throw Error("file '%s' has unsupported type", from2); + files.push_back(to2); + } + }; + + copyDir(templateDir, flakeDir); + + if (pathExists(flakeDir + "/.git")) { + Strings args = { "-C", flakeDir, "add", "--intent-to-add", "--force", "--" }; + for (auto & s : files) args.push_back(s); + runProgram("git", true, args); + } + } +}; + +struct CmdFlakeInit : CmdFlakeInitCommon +{ + std::string description() override + { + return "create a flake in the current directory from a template"; + } + + Examples examples() override + { + return { + Example{ + "To create a flake using the default template:", + "nix flake init" + }, + Example{ + "To see available templates:", + "nix flake show templates" + }, + Example{ + "To create a flake from a specific template:", + "nix flake init -t templates#nixos-container" + }, + }; + } + + CmdFlakeInit() + { + destDir = "."; + } +}; + +struct CmdFlakeNew : CmdFlakeInitCommon +{ + std::string description() override + { + return "create a flake in the specified directory from a template"; + } + + CmdFlakeNew() + { + expectArgs({ + .label = "dest-dir", + .handler = {&destDir}, + .completer = completePath + }); + } +}; + +struct CmdFlakeClone : FlakeCommand +{ + Path destDir; + + std::string description() override + { + return "clone flake repository"; + } + + CmdFlakeClone() + { + addFlag({ + .longName = "dest", + .shortName = 'f', + .description = "destination path", + .labels = {"path"}, + .handler = {&destDir} + }); + } + + void run(nix::ref store) override + { + if (destDir.empty()) + throw Error("missing flag '--dest'"); + + getFlakeRef().resolve(store).input.clone(destDir); + } +}; + +struct CmdFlakeArchive : FlakeCommand, MixJSON, MixDryRun +{ + std::string dstUri; + + CmdFlakeArchive() + { + addFlag({ + .longName = "to", + .description = "URI of the destination Nix store", + .labels = {"store-uri"}, + .handler = {&dstUri} + }); + } + + std::string description() override + { + return "copy a flake and all its inputs to a store"; + } + + Examples examples() override + { + return { + Example{ + "To copy the dwarffs flake and its dependencies to a binary cache:", + "nix flake archive --to file:///tmp/my-cache dwarffs" + }, + Example{ + "To fetch the dwarffs flake and its dependencies to the local Nix store:", + "nix flake archive dwarffs" + }, + Example{ + "To print the store paths of the flake sources of NixOps without fetching them:", + "nix flake archive --json --dry-run nixops" + }, + }; + } + + void run(nix::ref store) override + { + auto flake = lockFlake(); + + auto jsonRoot = json ? std::optional(std::cout) : std::nullopt; + + StorePathSet sources; + + sources.insert(flake.flake.sourceInfo->storePath); + if (jsonRoot) + jsonRoot->attr("path", store->printStorePath(flake.flake.sourceInfo->storePath)); + + // FIXME: use graph output, handle cycles. + std::function & jsonObj)> traverse; + traverse = [&](const Node & node, std::optional & jsonObj) + { + auto jsonObj2 = jsonObj ? jsonObj->object("inputs") : std::optional(); + for (auto & [inputName, input] : node.inputs) { + if (auto inputNode = std::get_if<0>(&input)) { + auto jsonObj3 = jsonObj2 ? jsonObj2->object(inputName) : std::optional(); + auto storePath = + dryRun + ? (*inputNode)->lockedRef.input.computeStorePath(*store) + : (*inputNode)->lockedRef.input.fetch(store).first.storePath; + if (jsonObj3) + jsonObj3->attr("path", store->printStorePath(storePath)); + sources.insert(std::move(storePath)); + traverse(**inputNode, jsonObj3); + } + } + }; + + traverse(*flake.lockFile.root, jsonRoot); + + if (!dryRun && !dstUri.empty()) { + ref dstStore = dstUri.empty() ? openStore() : openStore(dstUri); + copyPaths(store, dstStore, sources); + } + } +}; + +struct CmdFlakeShow : FlakeCommand +{ + bool showLegacy = false; + + CmdFlakeShow() + { + addFlag({ + .longName = "legacy", + .description = "show the contents of the 'legacyPackages' output", + .handler = {&showLegacy, true} + }); + } + + std::string description() override + { + return "show the outputs provided by a flake"; + } + + void run(nix::ref store) override + { + auto state = getEvalState(); + auto flake = std::make_shared(lockFlake()); + + std::function & attrPath, const std::string & headerPrefix, const std::string & nextPrefix)> visit; + + visit = [&](eval_cache::AttrCursor & visitor, const std::vector & attrPath, const std::string & headerPrefix, const std::string & nextPrefix) + { + Activity act(*logger, lvlInfo, actUnknown, + fmt("evaluating '%s'", concatStringsSep(".", attrPath))); + try { + auto recurse = [&]() + { + logger->stdout("%s", headerPrefix); + auto attrs = visitor.getAttrs(); + for (const auto & [i, attr] : enumerate(attrs)) { + bool last = i + 1 == attrs.size(); + auto visitor2 = visitor.getAttr(attr); + auto attrPath2(attrPath); + attrPath2.push_back(attr); + visit(*visitor2, attrPath2, + fmt(ANSI_GREEN "%s%s" ANSI_NORMAL ANSI_BOLD "%s" ANSI_NORMAL, nextPrefix, last ? treeLast : treeConn, attr), + nextPrefix + (last ? treeNull : treeLine)); + } + }; + + auto showDerivation = [&]() + { + auto name = visitor.getAttr(state->sName)->getString(); + + /* + std::string description; + + if (auto aMeta = visitor.maybeGetAttr("meta")) { + if (auto aDescription = aMeta->maybeGetAttr("description")) + description = aDescription->getString(); + } + */ + + logger->stdout("%s: %s '%s'", + headerPrefix, + attrPath.size() == 2 && attrPath[0] == "devShell" ? "development environment" : + attrPath.size() == 3 && attrPath[0] == "checks" ? "derivation" : + attrPath.size() >= 1 && attrPath[0] == "hydraJobs" ? "derivation" : + "package", + name); + }; + + if (attrPath.size() == 0 + || (attrPath.size() == 1 && ( + attrPath[0] == "defaultPackage" + || attrPath[0] == "devShell" + || attrPath[0] == "nixosConfigurations" + || attrPath[0] == "nixosModules" + || attrPath[0] == "defaultApp" + || attrPath[0] == "templates")) + || ((attrPath.size() == 1 || attrPath.size() == 2) + && (attrPath[0] == "checks" + || attrPath[0] == "packages" + || attrPath[0] == "apps")) + ) + { + recurse(); + } + + else if ( + (attrPath.size() == 2 && (attrPath[0] == "defaultPackage" || attrPath[0] == "devShell")) + || (attrPath.size() == 3 && (attrPath[0] == "checks" || attrPath[0] == "packages")) + ) + { + if (visitor.isDerivation()) + showDerivation(); + else + throw Error("expected a derivation"); + } + + else if (attrPath.size() > 0 && attrPath[0] == "hydraJobs") { + if (visitor.isDerivation()) + showDerivation(); + else + recurse(); + } + + else if (attrPath.size() > 0 && attrPath[0] == "legacyPackages") { + if (attrPath.size() == 1) + recurse(); + else if (!showLegacy) + logger->stdout("%s: " ANSI_YELLOW "omitted" ANSI_NORMAL " (use '--legacy' to show)", headerPrefix); + else { + if (visitor.isDerivation()) + showDerivation(); + else if (attrPath.size() <= 2) + // FIXME: handle recurseIntoAttrs + recurse(); + } + } + + else if ( + (attrPath.size() == 2 && attrPath[0] == "defaultApp") || + (attrPath.size() == 3 && attrPath[0] == "apps")) + { + auto aType = visitor.maybeGetAttr("type"); + if (!aType || aType->getString() != "app") + throw EvalError("not an app definition"); + logger->stdout("%s: app", headerPrefix); + } + + else if ( + (attrPath.size() == 1 && attrPath[0] == "defaultTemplate") || + (attrPath.size() == 2 && attrPath[0] == "templates")) + { + auto description = visitor.getAttr("description")->getString(); + logger->stdout("%s: template: " ANSI_BOLD "%s" ANSI_NORMAL, headerPrefix, description); + } + + else { + logger->stdout("%s: %s", + headerPrefix, + attrPath.size() == 1 && attrPath[0] == "overlay" ? "Nixpkgs overlay" : + attrPath.size() == 2 && attrPath[0] == "nixosConfigurations" ? "NixOS configuration" : + attrPath.size() == 2 && attrPath[0] == "nixosModules" ? "NixOS module" : + ANSI_YELLOW "unknown" ANSI_NORMAL); + } + } catch (EvalError & e) { + if (!(attrPath.size() > 0 && attrPath[0] == "legacyPackages")) + throw; + } + }; + + auto cache = openEvalCache(*state, flake); + + visit(*cache->getRoot(), {}, fmt(ANSI_BOLD "%s" ANSI_NORMAL, flake->flake.lockedRef), ""); + } +}; + +struct CmdFlake : NixMultiCommand +{ + CmdFlake() + : MultiCommand({ + {"update", []() { return make_ref(); }}, + {"info", []() { return make_ref(); }}, + {"list-inputs", []() { return make_ref(); }}, + {"check", []() { return make_ref(); }}, + {"init", []() { return make_ref(); }}, + {"new", []() { return make_ref(); }}, + {"clone", []() { return make_ref(); }}, + {"archive", []() { return make_ref(); }}, + {"show", []() { return make_ref(); }}, + }) + { + } + + std::string description() override + { + return "manage Nix flakes"; + } + + void run() override + { + if (!command) + throw UsageError("'nix flake' requires a sub-command."); + settings.requireExperimentalFeature("flakes"); + command->second->prepare(); + command->second->run(); + } +}; + +static auto rCmdFlake = registerCommand("flake"); diff --git a/src/nix/get-env.sh b/src/nix/get-env.sh index a25ec43a9..091c0f573 100644 --- a/src/nix/get-env.sh +++ b/src/nix/get-env.sh @@ -1,9 +1,19 @@ set -e if [ -e .attrs.sh ]; then source .attrs.sh; fi + export IN_NIX_SHELL=impure export dontAddDisableDepTrack=1 + if [[ -n $stdenv ]]; then source $stdenv/setup fi -export > $out -set >> $out + +for __output in $outputs; do + if [[ -z $__done ]]; then + export > ${!__output} + set >> ${!__output} + __done=1 + else + echo -n >> ${!__output} + fi +done diff --git a/src/nix/hash.cc b/src/nix/hash.cc index b97c6d21f..1d23bb0e2 100644 --- a/src/nix/hash.cc +++ b/src/nix/hash.cc @@ -31,7 +31,11 @@ struct CmdHash : Command .labels({"modulus"}) .dest(&modulus); #endif - expectArgs("paths", &paths); + expectArgs({ + .label = "paths", + .handler = {&paths}, + .completer = completePath + }); } std::string description() override @@ -40,6 +44,7 @@ struct CmdHash : Command switch (mode) { case FileIngestionMethod::Flat: d = "print cryptographic hash of a regular file"; + break; case FileIngestionMethod::Recursive: d = "print cryptographic hash of the NAR serialisation of a path"; }; @@ -74,8 +79,8 @@ struct CmdHash : Command } }; -static RegisterCommand r1("hash-file", [](){ return make_ref(FileIngestionMethod::Flat); }); -static RegisterCommand r2("hash-path", [](){ return make_ref(FileIngestionMethod::Recursive); }); +static RegisterCommand rCmdHashFile("hash-file", [](){ return make_ref(FileIngestionMethod::Flat); }); +static RegisterCommand rCmdHashPath("hash-path", [](){ return make_ref(FileIngestionMethod::Recursive); }); struct CmdToBase : Command { @@ -103,14 +108,14 @@ struct CmdToBase : Command void run() override { for (auto s : args) - logger->stdout(Hash(s, ht).to_string(base, base == SRI)); + logger->stdout(Hash::parseAny(s, ht).to_string(base, base == SRI)); } }; -static RegisterCommand r3("to-base16", [](){ return make_ref(Base16); }); -static RegisterCommand r4("to-base32", [](){ return make_ref(Base32); }); -static RegisterCommand r5("to-base64", [](){ return make_ref(Base64); }); -static RegisterCommand r6("to-sri", [](){ return make_ref(SRI); }); +static RegisterCommand rCmdToBase16("to-base16", [](){ return make_ref(Base16); }); +static RegisterCommand rCmdToBase32("to-base32", [](){ return make_ref(Base32); }); +static RegisterCommand rCmdToBase64("to-base64", [](){ return make_ref(Base64); }); +static RegisterCommand rCmdToSRI("to-sri", [](){ return make_ref(SRI); }); /* Legacy nix-hash command. */ static int compatNixHash(int argc, char * * argv) @@ -162,4 +167,4 @@ static int compatNixHash(int argc, char * * argv) return 0; } -static RegisterLegacyCommand s1("nix-hash", compatNixHash); +static RegisterLegacyCommand r_nix_hash("nix-hash", compatNixHash); diff --git a/src/nix/installables.cc b/src/nix/installables.cc index 708a0dc88..9bf6b7caa 100644 --- a/src/nix/installables.cc +++ b/src/nix/installables.cc @@ -1,3 +1,4 @@ +#include "installables.hh" #include "command.hh" #include "attr-path.hh" #include "common-eval-args.hh" @@ -7,80 +8,261 @@ #include "get-drvs.hh" #include "store-api.hh" #include "shared.hh" +#include "flake/flake.hh" +#include "eval-cache.hh" +#include "url.hh" +#include "registry.hh" #include +#include namespace nix { +void completeFlakeInputPath( + ref evalState, + const FlakeRef & flakeRef, + std::string_view prefix) +{ + auto flake = flake::getFlake(*evalState, flakeRef, true); + for (auto & input : flake.inputs) + if (hasPrefix(input.first, prefix)) + completions->insert(input.first); +} + +MixFlakeOptions::MixFlakeOptions() +{ + addFlag({ + .longName = "recreate-lock-file", + .description = "recreate lock file from scratch", + .handler = {&lockFlags.recreateLockFile, true} + }); + + addFlag({ + .longName = "no-update-lock-file", + .description = "do not allow any updates to the lock file", + .handler = {&lockFlags.updateLockFile, false} + }); + + addFlag({ + .longName = "no-write-lock-file", + .description = "do not write the newly generated lock file", + .handler = {&lockFlags.writeLockFile, false} + }); + + addFlag({ + .longName = "no-registries", + .description = "don't use flake registries", + .handler = {&lockFlags.useRegistries, false} + }); + + addFlag({ + .longName = "commit-lock-file", + .description = "commit changes to the lock file", + .handler = {&lockFlags.commitLockFile, true} + }); + + addFlag({ + .longName = "update-input", + .description = "update a specific flake input", + .labels = {"input-path"}, + .handler = {[&](std::string s) { + lockFlags.inputUpdates.insert(flake::parseInputPath(s)); + }}, + .completer = {[&](size_t, std::string_view prefix) { + if (auto flakeRef = getFlakeRefForCompletion()) + completeFlakeInputPath(getEvalState(), *flakeRef, prefix); + }} + }); + + addFlag({ + .longName = "override-input", + .description = "override a specific flake input (e.g. `dwarffs/nixpkgs`)", + .labels = {"input-path", "flake-url"}, + .handler = {[&](std::string inputPath, std::string flakeRef) { + lockFlags.inputOverrides.insert_or_assign( + flake::parseInputPath(inputPath), + parseFlakeRef(flakeRef, absPath("."))); + }} + }); + + addFlag({ + .longName = "inputs-from", + .description = "use the inputs of the specified flake as registry entries", + .labels = {"flake-url"}, + .handler = {[&](std::string flakeRef) { + auto evalState = getEvalState(); + auto flake = flake::lockFlake( + *evalState, + parseFlakeRef(flakeRef, absPath(".")), + { .writeLockFile = false }); + for (auto & [inputName, input] : flake.lockFile.root->inputs) { + auto input2 = flake.lockFile.findInput({inputName}); // resolve 'follows' nodes + if (auto input3 = std::dynamic_pointer_cast(input2)) { + overrideRegistry( + fetchers::Input::fromAttrs({{"type","indirect"}, {"id", inputName}}), + input3->lockedRef.input, + {}); + } + } + }}, + .completer = {[&](size_t, std::string_view prefix) { + completeFlakeRef(getEvalState()->store, prefix); + }} + }); +} SourceExprCommand::SourceExprCommand() { addFlag({ .longName = "file", .shortName = 'f', - .description = "evaluate FILE rather than the default", + .description = "evaluate *file* rather than the default", .labels = {"file"}, - .handler = {&file} + .handler = {&file}, + .completer = completePath + }); + + addFlag({ + .longName ="expr", + .description = "evaluate attributes from *expr*", + .labels = {"expr"}, + .handler = {&expr} + }); + + addFlag({ + .longName ="derivation", + .description = "operate on the store derivation rather than its outputs", + .handler = {&operateOn, OperateOn::Derivation}, }); } -Value * SourceExprCommand::getSourceExpr(EvalState & state) +Strings SourceExprCommand::getDefaultFlakeAttrPaths() { - if (vSourceExpr) return *vSourceExpr; - - auto sToplevel = state.symbols.create("_toplevel"); - - vSourceExpr = allocRootValue(state.allocValue()); - - if (file != "") - state.evalFile(lookupFileArg(state, file), **vSourceExpr); - - else { - - /* Construct the installation source from $NIX_PATH. */ - - auto searchPath = state.getSearchPath(); - - state.mkAttrs(**vSourceExpr, 1024); - - mkBool(*state.allocAttr(**vSourceExpr, sToplevel), true); - - std::unordered_set seen; - - auto addEntry = [&](const std::string & name) { - if (name == "") return; - if (!seen.insert(name).second) return; - Value * v1 = state.allocValue(); - mkPrimOpApp(*v1, state.getBuiltin("findFile"), state.getBuiltin("nixPath")); - Value * v2 = state.allocValue(); - mkApp(*v2, *v1, mkString(*state.allocValue(), name)); - mkApp(*state.allocAttr(**vSourceExpr, state.symbols.create(name)), - state.getBuiltin("import"), *v2); - }; - - for (auto & i : searchPath) - /* Hack to handle channels. */ - if (i.first.empty() && pathExists(i.second + "/manifest.nix")) { - for (auto & j : readDirectory(i.second)) - if (j.name != "manifest.nix" - && pathExists(fmt("%s/%s/default.nix", i.second, j.name))) - addEntry(j.name); - } else - addEntry(i.first); - - (*vSourceExpr)->attrs->sort(); - } - - return *vSourceExpr; + return {"defaultPackage." + settings.thisSystem.get()}; } -ref SourceExprCommand::getEvalState() +Strings SourceExprCommand::getDefaultFlakeAttrPathPrefixes() +{ + return { + // As a convenience, look for the attribute in + // 'outputs.packages'. + "packages." + settings.thisSystem.get() + ".", + // As a temporary hack until Nixpkgs is properly converted + // to provide a clean 'packages' set, look in 'legacyPackages'. + "legacyPackages." + settings.thisSystem.get() + "." + }; +} + +void SourceExprCommand::completeInstallable(std::string_view prefix) +{ + if (file) return; // FIXME + + completeFlakeRefWithFragment( + getEvalState(), + lockFlags, + getDefaultFlakeAttrPathPrefixes(), + getDefaultFlakeAttrPaths(), + prefix); +} + +void completeFlakeRefWithFragment( + ref evalState, + flake::LockFlags lockFlags, + Strings attrPathPrefixes, + const Strings & defaultFlakeAttrPaths, + std::string_view prefix) +{ + /* Look for flake output attributes that match the + prefix. */ + try { + auto hash = prefix.find('#'); + if (hash != std::string::npos) { + auto fragment = prefix.substr(hash + 1); + auto flakeRefS = std::string(prefix.substr(0, hash)); + // FIXME: do tilde expansion. + auto flakeRef = parseFlakeRef(flakeRefS, absPath(".")); + + auto evalCache = openEvalCache(*evalState, + std::make_shared(lockFlake(*evalState, flakeRef, lockFlags))); + + auto root = evalCache->getRoot(); + + /* Complete 'fragment' relative to all the + attrpath prefixes as well as the root of the + flake. */ + attrPathPrefixes.push_back(""); + + for (auto & attrPathPrefixS : attrPathPrefixes) { + auto attrPathPrefix = parseAttrPath(*evalState, attrPathPrefixS); + auto attrPathS = attrPathPrefixS + std::string(fragment); + auto attrPath = parseAttrPath(*evalState, attrPathS); + + std::string lastAttr; + if (!attrPath.empty() && !hasSuffix(attrPathS, ".")) { + lastAttr = attrPath.back(); + attrPath.pop_back(); + } + + auto attr = root->findAlongAttrPath(attrPath); + if (!attr) continue; + + for (auto & attr2 : attr->getAttrs()) { + if (hasPrefix(attr2, lastAttr)) { + auto attrPath2 = attr->getAttrPath(attr2); + /* Strip the attrpath prefix. */ + attrPath2.erase(attrPath2.begin(), attrPath2.begin() + attrPathPrefix.size()); + completions->insert(flakeRefS + "#" + concatStringsSep(".", attrPath2)); + } + } + } + + /* And add an empty completion for the default + attrpaths. */ + if (fragment.empty()) { + for (auto & attrPath : defaultFlakeAttrPaths) { + auto attr = root->findAlongAttrPath(parseAttrPath(*evalState, attrPath)); + if (!attr) continue; + completions->insert(flakeRefS + "#"); + } + } + } + } catch (Error & e) { + warn(e.msg()); + } + + completeFlakeRef(evalState->store, prefix); +} + +ref EvalCommand::getEvalState() { if (!evalState) evalState = std::make_shared(searchPath, getStore()); return ref(evalState); } +void completeFlakeRef(ref store, std::string_view prefix) +{ + if (prefix == "") + completions->insert("."); + + completeDir(0, prefix); + + /* Look for registry entries that match the prefix. */ + for (auto & registry : fetchers::getRegistries(store)) { + for (auto & entry : registry->entries) { + auto from = entry.from.to_string(); + if (!hasPrefix(prefix, "flake:") && hasPrefix(from, "flake:")) { + std::string from2(from, 6); + if (hasPrefix(from2, prefix)) + completions->insert(from2); + } else { + if (hasPrefix(from, prefix)) + completions->insert(from); + } + } + } +} + Buildable Installable::toBuildable() { auto buildables = toBuildables(); @@ -89,27 +271,54 @@ Buildable Installable::toBuildable() return std::move(buildables[0]); } +std::vector, std::string>> +Installable::getCursors(EvalState & state) +{ + auto evalCache = + std::make_shared(std::nullopt, state, + [&]() { return toValue(state).first; }); + return {{evalCache->getRoot(), ""}}; +} + +std::pair, std::string> +Installable::getCursor(EvalState & state) +{ + auto cursors = getCursors(state); + if (cursors.empty()) + throw Error("cannot find flake attribute '%s'", what()); + return cursors[0]; +} + struct InstallableStorePath : Installable { ref store; StorePath storePath; - InstallableStorePath(ref store, const Path & storePath) - : store(store), storePath(store->parseStorePath(storePath)) { } + InstallableStorePath(ref store, StorePath && storePath) + : store(store), storePath(std::move(storePath)) { } std::string what() override { return store->printStorePath(storePath); } Buildables toBuildables() override { - std::map outputs; - outputs.insert_or_assign("out", storePath); - Buildable b{ - .drvPath = storePath.isDerivation() ? storePath : std::optional(), - .outputs = std::move(outputs) - }; - Buildables bs; - bs.push_back(std::move(b)); - return bs; + if (storePath.isDerivation()) { + std::map> outputs; + auto drv = store->readDerivation(storePath); + for (auto & [name, output] : drv.outputsAndOptPaths(*store)) + outputs.emplace(name, output.second); + return { + BuildableFromDrv { + .drvPath = storePath, + .outputs = std::move(outputs) + } + }; + } else { + return { + BuildableOpaque { + .path = storePath, + } + }; + } } std::optional getStorePath() override @@ -118,146 +327,309 @@ struct InstallableStorePath : Installable } }; -struct InstallableValue : Installable +Buildables InstallableValue::toBuildables() { - SourceExprCommand & cmd; + Buildables res; - InstallableValue(SourceExprCommand & cmd) : cmd(cmd) { } + std::map>> drvsToOutputs; - Buildables toBuildables() override - { - auto state = cmd.getEvalState(); - - auto v = toValue(*state).first; - - Bindings & autoArgs = *cmd.getAutoArgs(*state); - - DrvInfos drvs; - getDerivations(*state, *v, "", autoArgs, drvs, false); - - Buildables res; - - StorePathSet drvPaths; - - for (auto & drv : drvs) { - Buildable b{.drvPath = state->store->parseStorePath(drv.queryDrvPath())}; - drvPaths.insert(*b.drvPath); - - auto outputName = drv.queryOutputName(); - if (outputName == "") - throw Error("derivation '%s' lacks an 'outputName' attribute", state->store->printStorePath(*b.drvPath)); - - b.outputs.emplace(outputName, state->store->parseStorePath(drv.queryOutPath())); - - res.push_back(std::move(b)); - } - - // Hack to recognize .all: if all drvs have the same drvPath, - // merge the buildables. - if (drvPaths.size() == 1) { - Buildable b{.drvPath = *drvPaths.begin()}; - for (auto & b2 : res) - for (auto & output : b2.outputs) - b.outputs.insert_or_assign(output.first, output.second); - Buildables bs; - bs.push_back(std::move(b)); - return bs; - } else - return res; + // Group by derivation, helps with .all in particular + for (auto & drv : toDerivations()) { + auto outputName = drv.outputName; + if (outputName == "") + throw Error("derivation '%s' lacks an 'outputName' attribute", state->store->printStorePath(drv.drvPath)); + drvsToOutputs[drv.drvPath].insert_or_assign(outputName, drv.outPath); } -}; -struct InstallableExpr : InstallableValue -{ - std::string text; + for (auto & i : drvsToOutputs) + res.push_back(BuildableFromDrv { i.first, i.second }); - InstallableExpr(SourceExprCommand & cmd, const std::string & text) - : InstallableValue(cmd), text(text) { } - - std::string what() override { return text; } - - std::pair toValue(EvalState & state) override - { - auto v = state.allocValue(); - state.eval(state.parseExprFromString(text, absPath(".")), *v); - return {v, noPos}; - } -}; + return res; +} struct InstallableAttrPath : InstallableValue { + SourceExprCommand & cmd; + RootValue v; std::string attrPath; - InstallableAttrPath(SourceExprCommand & cmd, const std::string & attrPath) - : InstallableValue(cmd), attrPath(attrPath) + InstallableAttrPath(ref state, SourceExprCommand & cmd, Value * v, const std::string & attrPath) + : InstallableValue(state), cmd(cmd), v(allocRootValue(v)), attrPath(attrPath) { } std::string what() override { return attrPath; } std::pair toValue(EvalState & state) override { - auto source = cmd.getSourceExpr(state); - - Bindings & autoArgs = *cmd.getAutoArgs(state); - - auto v = findAlongAttrPath(state, attrPath, autoArgs, *source).first; - state.forceValue(*v); - - return {v, noPos}; + auto [vRes, pos] = findAlongAttrPath(state, attrPath, *cmd.getAutoArgs(state), **v); + state.forceValue(*vRes); + return {vRes, pos}; } + + virtual std::vector toDerivations() override; }; -// FIXME: extend -std::string attrRegex = R"([A-Za-z_][A-Za-z0-9-_+]*)"; -static std::regex attrPathRegex(fmt(R"(%1%(\.%1%)*)", attrRegex)); +std::vector InstallableAttrPath::toDerivations() +{ + auto v = toValue(*state).first; -static std::vector> parseInstallables( - SourceExprCommand & cmd, ref store, std::vector ss, bool useDefaultInstallables) + Bindings & autoArgs = *cmd.getAutoArgs(*state); + + DrvInfos drvInfos; + getDerivations(*state, *v, "", autoArgs, drvInfos, false); + + std::vector res; + for (auto & drvInfo : drvInfos) { + res.push_back({ + state->store->parseStorePath(drvInfo.queryDrvPath()), + state->store->parseStorePath(drvInfo.queryOutPath()), + drvInfo.queryOutputName() + }); + } + + return res; +} + +std::vector InstallableFlake::getActualAttrPaths() +{ + std::vector res; + + for (auto & prefix : prefixes) + res.push_back(prefix + *attrPaths.begin()); + + for (auto & s : attrPaths) + res.push_back(s); + + return res; +} + +Value * InstallableFlake::getFlakeOutputs(EvalState & state, const flake::LockedFlake & lockedFlake) +{ + auto vFlake = state.allocValue(); + + callFlake(state, lockedFlake, *vFlake); + + auto aOutputs = vFlake->attrs->get(state.symbols.create("outputs")); + assert(aOutputs); + + state.forceValue(*aOutputs->value); + + return aOutputs->value; +} + +ref openEvalCache( + EvalState & state, + std::shared_ptr lockedFlake) +{ + auto fingerprint = lockedFlake->getFingerprint(); + return make_ref( + evalSettings.useEvalCache && evalSettings.pureEval + ? std::optional { std::cref(fingerprint) } + : std::nullopt, + state, + [&state, lockedFlake]() + { + /* For testing whether the evaluation cache is + complete. */ + if (getEnv("NIX_ALLOW_EVAL").value_or("1") == "0") + throw Error("not everything is cached, but evaluation is not allowed"); + + auto vFlake = state.allocValue(); + flake::callFlake(state, *lockedFlake, *vFlake); + + state.forceAttrs(*vFlake); + + auto aOutputs = vFlake->attrs->get(state.symbols.create("outputs")); + assert(aOutputs); + + return aOutputs->value; + }); +} + +static std::string showAttrPaths(const std::vector & paths) +{ + std::string s; + for (const auto & [n, i] : enumerate(paths)) { + if (n > 0) s += n + 1 == paths.size() ? " or " : ", "; + s += '\''; s += i; s += '\''; + } + return s; +} + +std::tuple InstallableFlake::toDerivation() +{ + auto lockedFlake = getLockedFlake(); + + auto cache = openEvalCache(*state, lockedFlake); + auto root = cache->getRoot(); + + for (auto & attrPath : getActualAttrPaths()) { + auto attr = root->findAlongAttrPath(parseAttrPath(*state, attrPath)); + if (!attr) continue; + + if (!attr->isDerivation()) + throw Error("flake output attribute '%s' is not a derivation", attrPath); + + auto drvPath = attr->forceDerivation(); + + auto drvInfo = DerivationInfo{ + std::move(drvPath), + state->store->parseStorePath(attr->getAttr(state->sOutPath)->getString()), + attr->getAttr(state->sOutputName)->getString() + }; + + return {attrPath, lockedFlake->flake.lockedRef, std::move(drvInfo)}; + } + + throw Error("flake '%s' does not provide attribute %s", + flakeRef, showAttrPaths(getActualAttrPaths())); +} + +std::vector InstallableFlake::toDerivations() +{ + std::vector res; + res.push_back(std::get<2>(toDerivation())); + return res; +} + +std::pair InstallableFlake::toValue(EvalState & state) +{ + auto lockedFlake = getLockedFlake(); + + auto vOutputs = getFlakeOutputs(state, *lockedFlake); + + auto emptyArgs = state.allocBindings(0); + + for (auto & attrPath : getActualAttrPaths()) { + try { + auto [v, pos] = findAlongAttrPath(state, attrPath, *emptyArgs, *vOutputs); + state.forceValue(*v); + return {v, pos}; + } catch (AttrPathNotFound & e) { + } + } + + throw Error("flake '%s' does not provide attribute %s", + flakeRef, showAttrPaths(getActualAttrPaths())); +} + +std::vector, std::string>> +InstallableFlake::getCursors(EvalState & state) +{ + auto evalCache = openEvalCache(state, + std::make_shared(lockFlake(state, flakeRef, lockFlags))); + + auto root = evalCache->getRoot(); + + std::vector, std::string>> res; + + for (auto & attrPath : getActualAttrPaths()) { + auto attr = root->findAlongAttrPath(parseAttrPath(state, attrPath)); + if (attr) res.push_back({attr, attrPath}); + } + + return res; +} + +std::shared_ptr InstallableFlake::getLockedFlake() const +{ + if (!_lockedFlake) + _lockedFlake = std::make_shared(lockFlake(*state, flakeRef, lockFlags)); + return _lockedFlake; +} + +FlakeRef InstallableFlake::nixpkgsFlakeRef() const +{ + auto lockedFlake = getLockedFlake(); + + if (auto nixpkgsInput = lockedFlake->lockFile.findInput({"nixpkgs"})) { + if (auto lockedNode = std::dynamic_pointer_cast(nixpkgsInput)) { + debug("using nixpkgs flake '%s'", lockedNode->lockedRef); + return std::move(lockedNode->lockedRef); + } + } + + return Installable::nixpkgsFlakeRef(); +} + +std::vector> SourceExprCommand::parseInstallables( + ref store, std::vector ss) { std::vector> result; - if (ss.empty() && useDefaultInstallables) { - if (cmd.file == "") - cmd.file = "."; - ss = {""}; - } + if (file || expr) { + if (file && expr) + throw UsageError("'--file' and '--expr' are exclusive"); - for (auto & s : ss) { + // FIXME: backward compatibility hack + if (file) evalSettings.pureEval = false; - if (s.compare(0, 1, "(") == 0) - result.push_back(std::make_shared(cmd, s)); + auto state = getEvalState(); + auto vFile = state->allocValue(); - else if (s.find("/") != std::string::npos) { - - auto path = store->toStorePath(store->followLinksToStore(s)); - - if (store->isStorePath(path)) - result.push_back(std::make_shared(store, path)); + if (file) + state->evalFile(lookupFileArg(*state, *file), *vFile); + else { + auto e = state->parseExprFromString(*expr, absPath(".")); + state->eval(e, *vFile); } - else if (s == "" || std::regex_match(s, attrPathRegex)) - result.push_back(std::make_shared(cmd, s)); + for (auto & s : ss) + result.push_back(std::make_shared(state, *this, vFile, s == "." ? "" : s)); - else - throw UsageError("don't know what to do with argument '%s'", s); + } else { + + for (auto & s : ss) { + std::exception_ptr ex; + + try { + auto [flakeRef, fragment] = parseFlakeRefWithFragment(s, absPath(".")); + result.push_back(std::make_shared( + getEvalState(), std::move(flakeRef), + fragment == "" ? getDefaultFlakeAttrPaths() : Strings{fragment}, + getDefaultFlakeAttrPathPrefixes(), lockFlags)); + continue; + } catch (...) { + ex = std::current_exception(); + } + + if (s.find('/') != std::string::npos) { + try { + result.push_back(std::make_shared(store, store->followLinksToStorePath(s))); + continue; + } catch (BadStorePath &) { + } catch (...) { + if (!ex) + ex = std::current_exception(); + } + } + + std::rethrow_exception(ex); + + /* + throw Error( + pathExists(s) + ? "path '%s' is not a flake or a store path" + : "don't know how to handle argument '%s'", s); + */ + } } return result; } -std::shared_ptr parseInstallable( - SourceExprCommand & cmd, ref store, const std::string & installable, - bool useDefaultInstallables) +std::shared_ptr SourceExprCommand::parseInstallable( + ref store, const std::string & installable) { - auto installables = parseInstallables(cmd, store, {installable}, false); + auto installables = parseInstallables(store, {installable}); assert(installables.size() == 1); return installables.front(); } -Buildables build(ref store, RealiseMode mode, - std::vector> installables) +Buildables build(ref store, Realise mode, + std::vector> installables, BuildMode bMode) { - if (mode != Build) + if (mode == Realise::Nothing) settings.readOnlyMode = true; Buildables buildables; @@ -266,45 +638,70 @@ Buildables build(ref store, RealiseMode mode, for (auto & i : installables) { for (auto & b : i->toBuildables()) { - if (b.drvPath) { - StringSet outputNames; - for (auto & output : b.outputs) - outputNames.insert(output.first); - pathsToBuild.push_back({*b.drvPath, outputNames}); - } else - for (auto & output : b.outputs) - pathsToBuild.push_back({output.second}); + std::visit(overloaded { + [&](BuildableOpaque bo) { + pathsToBuild.push_back({bo.path}); + }, + [&](BuildableFromDrv bfd) { + StringSet outputNames; + for (auto & output : bfd.outputs) + outputNames.insert(output.first); + pathsToBuild.push_back({bfd.drvPath, outputNames}); + }, + }, b); buildables.push_back(std::move(b)); } } - if (mode == DryRun) + if (mode == Realise::Nothing) printMissing(store, pathsToBuild, lvlError); - else if (mode == Build) - store->buildPaths(pathsToBuild); + else if (mode == Realise::Outputs) + store->buildPaths(pathsToBuild, bMode); return buildables; } -StorePathSet toStorePaths(ref store, RealiseMode mode, +StorePathSet toStorePaths(ref store, + Realise mode, OperateOn operateOn, std::vector> installables) { StorePathSet outPaths; - for (auto & b : build(store, mode, installables)) - for (auto & output : b.outputs) - outPaths.insert(output.second); + if (operateOn == OperateOn::Output) { + for (auto & b : build(store, mode, installables)) + std::visit(overloaded { + [&](BuildableOpaque bo) { + outPaths.insert(bo.path); + }, + [&](BuildableFromDrv bfd) { + for (auto & output : bfd.outputs) { + if (!output.second) + throw Error("Cannot operate on output of unbuilt CA drv"); + outPaths.insert(*output.second); + } + }, + }, b); + } else { + if (mode == Realise::Nothing) + settings.readOnlyMode = true; + + for (auto & i : installables) + for (auto & b : i->toBuildables()) + if (auto bfd = std::get_if(&b)) + outPaths.insert(bfd->drvPath); + } return outPaths; } -StorePath toStorePath(ref store, RealiseMode mode, +StorePath toStorePath(ref store, + Realise mode, OperateOn operateOn, std::shared_ptr installable) { - auto paths = toStorePaths(store, mode, {installable}); + auto paths = toStorePaths(store, mode, operateOn, {installable}); if (paths.size() != 1) - throw Error("argument '%s' should evaluate to one store path", installable->what()); + throw Error("argument '%s' should evaluate to one store path", installable->what()); return *paths.begin(); } @@ -315,32 +712,70 @@ StorePathSet toDerivations(ref store, StorePathSet drvPaths; for (auto & i : installables) - for (auto & b : i->toBuildables()) { - if (!b.drvPath) { - if (!useDeriver) - throw Error("argument '%s' did not evaluate to a derivation", i->what()); - for (auto & output : b.outputs) { - auto derivers = store->queryValidDerivers(output.second); + for (auto & b : i->toBuildables()) + std::visit(overloaded { + [&](BuildableOpaque bo) { + if (!useDeriver) + throw Error("argument '%s' did not evaluate to a derivation", i->what()); + auto derivers = store->queryValidDerivers(bo.path); if (derivers.empty()) throw Error("'%s' does not have a known deriver", i->what()); // FIXME: use all derivers? drvPaths.insert(*derivers.begin()); - } - } else - drvPaths.insert(*b.drvPath); - } + }, + [&](BuildableFromDrv bfd) { + drvPaths.insert(bfd.drvPath); + }, + }, b); return drvPaths; } +InstallablesCommand::InstallablesCommand() +{ + expectArgs({ + .label = "installables", + .handler = {&_installables}, + .completer = {[&](size_t, std::string_view prefix) { + completeInstallable(prefix); + }} + }); +} + void InstallablesCommand::prepare() { - installables = parseInstallables(*this, getStore(), _installables, useDefaultInstallables()); + if (_installables.empty() && useDefaultInstallables()) + // FIXME: commands like "nix install" should not have a + // default, probably. + _installables.push_back("."); + installables = parseInstallables(getStore(), _installables); +} + +std::optional InstallablesCommand::getFlakeRefForCompletion() +{ + if (_installables.empty()) { + if (useDefaultInstallables()) + return parseFlakeRef(".", absPath(".")); + return {}; + } + return parseFlakeRef(_installables.front(), absPath(".")); +} + +InstallableCommand::InstallableCommand() +{ + expectArgs({ + .label = "installable", + .optional = true, + .handler = {&_installable}, + .completer = {[&](size_t, std::string_view prefix) { + completeInstallable(prefix); + }} + }); } void InstallableCommand::prepare() { - installable = parseInstallable(*this, getStore(), _installable, false); + installable = parseInstallable(getStore(), _installable); } } diff --git a/src/nix/installables.hh b/src/nix/installables.hh index 503984220..c7c2f8981 100644 --- a/src/nix/installables.hh +++ b/src/nix/installables.hh @@ -3,32 +3,52 @@ #include "util.hh" #include "path.hh" #include "eval.hh" +#include "flake/flake.hh" #include namespace nix { -struct Buildable -{ - std::optional drvPath; - std::map outputs; +struct DrvInfo; +struct SourceExprCommand; + +namespace eval_cache { class EvalCache; class AttrCursor; } + +struct BuildableOpaque { + StorePath path; }; +struct BuildableFromDrv { + StorePath drvPath; + std::map> outputs; +}; + +typedef std::variant< + BuildableOpaque, + BuildableFromDrv +> Buildable; + typedef std::vector Buildables; +struct App +{ + std::vector context; + Path program; + // FIXME: add args, sandbox settings, metadata, ... +}; + struct Installable { virtual ~Installable() { } virtual std::string what() = 0; - virtual Buildables toBuildables() - { - throw Error("argument '%s' cannot be built", what()); - } + virtual Buildables toBuildables() = 0; Buildable toBuildable(); + App toApp(EvalState & state); + virtual std::pair toValue(EvalState & state) { throw Error("argument '%s' cannot be evaluated", what()); @@ -40,6 +60,73 @@ struct Installable { return {}; } + + virtual std::vector, std::string>> + getCursors(EvalState & state); + + std::pair, std::string> + getCursor(EvalState & state); + + virtual FlakeRef nixpkgsFlakeRef() const + { + return FlakeRef::fromAttrs({{"type","indirect"}, {"id", "nixpkgs"}}); + } }; +struct InstallableValue : Installable +{ + ref state; + + InstallableValue(ref state) : state(state) {} + + struct DerivationInfo + { + StorePath drvPath; + std::optional outPath; + std::string outputName; + }; + + virtual std::vector toDerivations() = 0; + + Buildables toBuildables() override; +}; + +struct InstallableFlake : InstallableValue +{ + FlakeRef flakeRef; + Strings attrPaths; + Strings prefixes; + const flake::LockFlags & lockFlags; + mutable std::shared_ptr _lockedFlake; + + InstallableFlake(ref state, FlakeRef && flakeRef, + Strings && attrPaths, Strings && prefixes, const flake::LockFlags & lockFlags) + : InstallableValue(state), flakeRef(flakeRef), attrPaths(attrPaths), + prefixes(prefixes), lockFlags(lockFlags) + { } + + std::string what() override { return flakeRef.to_string() + "#" + *attrPaths.begin(); } + + std::vector getActualAttrPaths(); + + Value * getFlakeOutputs(EvalState & state, const flake::LockedFlake & lockedFlake); + + std::tuple toDerivation(); + + std::vector toDerivations() override; + + std::pair toValue(EvalState & state) override; + + std::vector, std::string>> + getCursors(EvalState & state) override; + + std::shared_ptr getLockedFlake() const; + + FlakeRef nixpkgsFlakeRef() const override; +}; + +ref openEvalCache( + EvalState & state, + std::shared_ptr lockedFlake); + } diff --git a/src/nix/local.mk b/src/nix/local.mk index b057b7cc6..f37b73384 100644 --- a/src/nix/local.mk +++ b/src/nix/local.mk @@ -19,7 +19,7 @@ nix_CXXFLAGS += -I src/libutil -I src/libstore -I src/libfetchers -I src/libexpr nix_LIBS = libexpr libmain libfetchers libstore libutil -nix_LDFLAGS = -pthread $(SODIUM_LIBS) $(EDITLINE_LIBS) $(BOOST_LDFLAGS) -lboost_context -lboost_thread -lboost_system +nix_LDFLAGS = -pthread $(SODIUM_LIBS) $(EDITLINE_LIBS) $(BOOST_LDFLAGS) -llowdown $(foreach name, \ nix-build nix-channel nix-collect-garbage nix-copy-closure nix-daemon nix-env nix-hash nix-instantiate nix-prefetch-url nix-shell nix-store, \ @@ -29,3 +29,5 @@ $(eval $(call install-symlink, $(bindir)/nix, $(libexecdir)/nix/build-remote)) src/nix-env/user-env.cc: src/nix-env/buildenv.nix.gen.hh src/nix/develop.cc: src/nix/get-env.sh.gen.hh + +src/nix-channel/nix-channel.cc: src/nix-channel/unpack-channel.nix.gen.hh diff --git a/src/nix/log.cc b/src/nix/log.cc index 3fe22f6c2..33a3053f5 100644 --- a/src/nix/log.cc +++ b/src/nix/log.cc @@ -18,7 +18,7 @@ struct CmdLog : InstallableCommand return { Example{ "To get the build log of GNU Hello:", - "nix log nixpkgs.hello" + "nix log nixpkgs#hello" }, Example{ "To get the build log of a specific path:", @@ -26,7 +26,7 @@ struct CmdLog : InstallableCommand }, Example{ "To get a build log from a specific binary cache:", - "nix log --store https://cache.nixos.org nixpkgs.hello" + "nix log --store https://cache.nixos.org nixpkgs#hello" }, }; } @@ -45,11 +45,14 @@ struct CmdLog : InstallableCommand RunPager pager; for (auto & sub : subs) { - auto log = b.drvPath ? sub->getBuildLog(*b.drvPath) : nullptr; - for (auto & output : b.outputs) { - if (log) break; - log = sub->getBuildLog(output.second); - } + auto log = std::visit(overloaded { + [&](BuildableOpaque bo) { + return sub->getBuildLog(bo.path); + }, + [&](BuildableFromDrv bfd) { + return sub->getBuildLog(bfd.drvPath); + }, + }, b); if (!log) continue; stopProgressBar(); printInfo("got build log for '%s' from '%s'", installable->what(), sub->getUri()); @@ -61,4 +64,4 @@ struct CmdLog : InstallableCommand } }; -static auto r1 = registerCommand("log"); +static auto rCmdLog = registerCommand("log"); diff --git a/src/nix/ls.cc b/src/nix/ls.cc index d2157f2d4..baca54431 100644 --- a/src/nix/ls.cc +++ b/src/nix/ls.cc @@ -85,7 +85,11 @@ struct CmdLsStore : StoreCommand, MixLs { CmdLsStore() { - expectArg("path", &path); + expectArgs({ + .label = "path", + .handler = {&path}, + .completer = completePath + }); } Examples examples() override @@ -117,7 +121,11 @@ struct CmdLsNar : Command, MixLs CmdLsNar() { - expectArg("nar", &narPath); + expectArgs({ + .label = "nar", + .handler = {&narPath}, + .completer = completePath + }); expectArg("path", &path); } @@ -144,5 +152,5 @@ struct CmdLsNar : Command, MixLs } }; -static auto r1 = registerCommand("ls-store"); -static auto r2 = registerCommand("ls-nar"); +static auto rCmdLsStore = registerCommand("ls-store"); +static auto rCmdLsNar = registerCommand("ls-nar"); diff --git a/src/nix/main.cc b/src/nix/main.cc index 203901168..1e9e07bc0 100644 --- a/src/nix/main.cc +++ b/src/nix/main.cc @@ -7,7 +7,6 @@ #include "legacy.hh" #include "shared.hh" #include "store-api.hh" -#include "progress-bar.hh" #include "filetransfer.hh" #include "finally.hh" #include "loggers.hh" @@ -18,6 +17,8 @@ #include #include +#include + extern std::string chrootHelperName; void chrootHelper(int argc, char * * argv); @@ -69,7 +70,7 @@ struct NixArgs : virtual MultiCommand, virtual MixCommonArgs addFlag({ .longName = "help", .description = "show usage information", - .handler = {[&]() { showHelpAndExit(); }}, + .handler = {[&]() { if (!completions) showHelpAndExit(); }}, }); addFlag({ @@ -97,7 +98,7 @@ struct NixArgs : virtual MultiCommand, virtual MixCommonArgs addFlag({ .longName = "version", .description = "show version information", - .handler = {[&]() { printVersion(programName); }}, + .handler = {[&]() { if (!completions) printVersion(programName); }}, }); addFlag({ @@ -141,6 +142,11 @@ struct NixArgs : virtual MultiCommand, virtual MixCommonArgs printHelp(programName, std::cout); throw Exit(); } + + std::string description() override + { + return "a tool for reproducible and declarative configuration management"; + } }; void mainWrapped(int argc, char * * argv) @@ -165,6 +171,7 @@ void mainWrapped(int argc, char * * argv) verbosity = lvlWarn; settings.verboseBuild = false; + evalSettings.pureEval = true; setLogFormat("bar"); @@ -172,7 +179,46 @@ void mainWrapped(int argc, char * * argv) NixArgs args; - args.parseCmdline(argvToStrings(argc, argv)); + if (argc == 2 && std::string(argv[1]) == "__dump-args") { + std::cout << args.toJSON().dump() << "\n"; + return; + } + + if (argc == 2 && std::string(argv[1]) == "__dump-builtins") { + evalSettings.pureEval = false; + EvalState state({}, openStore("dummy://")); + auto res = nlohmann::json::object(); + auto builtins = state.baseEnv.values[0]->attrs; + for (auto & builtin : *builtins) { + auto b = nlohmann::json::object(); + if (builtin.value->type != tPrimOp) continue; + auto primOp = builtin.value->primOp; + if (!primOp->doc) continue; + b["arity"] = primOp->arity; + b["args"] = primOp->args; + b["doc"] = trim(stripIndentation(primOp->doc)); + res[(std::string) builtin.name] = std::move(b); + } + std::cout << res.dump() << "\n"; + return; + } + + Finally printCompletions([&]() + { + if (completions) { + std::cout << (pathCompletions ? "filenames\n" : "no-filenames\n"); + for (auto & s : *completions) + std::cout << s << "\n"; + } + }); + + try { + args.parseCmdline(argvToStrings(argc, argv)); + } catch (UsageError &) { + if (!completions) throw; + } + + if (completions) return; initPlugins(); diff --git a/src/nix/make-content-addressable.cc b/src/nix/make-content-addressable.cc index fb36fc410..df3ec5194 100644 --- a/src/nix/make-content-addressable.cc +++ b/src/nix/make-content-addressable.cc @@ -10,7 +10,7 @@ struct CmdMakeContentAddressable : StorePathsCommand, MixJSON { CmdMakeContentAddressable() { - realiseMode = Build; + realiseMode = Realise::Outputs; } std::string description() override @@ -23,7 +23,7 @@ struct CmdMakeContentAddressable : StorePathsCommand, MixJSON return { Example{ "To create a content-addressable representation of GNU Hello (but not its dependencies):", - "nix make-content-addressable nixpkgs.hello" + "nix make-content-addressable nixpkgs#hello" }, Example{ "To compute a content-addressable representation of the current NixOS system closure:", @@ -77,10 +77,12 @@ struct CmdMakeContentAddressable : StorePathsCommand, MixJSON auto narHash = hashModuloSink.finish().first; - ValidPathInfo info(store->makeFixedOutputPath(FileIngestionMethod::Recursive, narHash, path.name(), references, hasSelfReference)); + ValidPathInfo info { + store->makeFixedOutputPath(FileIngestionMethod::Recursive, narHash, path.name(), references, hasSelfReference), + narHash, + }; info.references = std::move(references); if (hasSelfReference) info.references.insert(info.path); - info.narHash = narHash; info.narSize = sink.s->size(); info.ca = FixedOutputHash { .method = FileIngestionMethod::Recursive, @@ -106,4 +108,4 @@ struct CmdMakeContentAddressable : StorePathsCommand, MixJSON } }; -static auto r1 = registerCommand("make-content-addressable"); +static auto rCmdMakeContentAddressable = registerCommand("make-content-addressable"); diff --git a/src/nix/markdown.cc b/src/nix/markdown.cc new file mode 100644 index 000000000..40788a42f --- /dev/null +++ b/src/nix/markdown.cc @@ -0,0 +1,50 @@ +#include "markdown.hh" +#include "util.hh" +#include "finally.hh" + +#include +extern "C" { +#include +} + +namespace nix { + +std::string renderMarkdownToTerminal(std::string_view markdown) +{ + struct lowdown_opts opts { + .type = LOWDOWN_TERM, + .maxdepth = 20, + .cols = std::min(getWindowSize().second, (unsigned short) 80), + .hmargin = 0, + .vmargin = 0, + .feat = LOWDOWN_COMMONMARK | LOWDOWN_FENCED | LOWDOWN_DEFLIST | LOWDOWN_TABLES, + .oflags = 0, + }; + + auto doc = lowdown_doc_new(&opts); + if (!doc) + throw Error("cannot allocate Markdown document"); + Finally freeDoc([&]() { lowdown_doc_free(doc); }); + + size_t maxn = 0; + auto node = lowdown_doc_parse(doc, &maxn, markdown.data(), markdown.size()); + if (!node) + throw Error("cannot parse Markdown document"); + Finally freeNode([&]() { lowdown_node_free(node); }); + + auto renderer = lowdown_term_new(&opts); + if (!renderer) + throw Error("cannot allocate Markdown renderer"); + Finally freeRenderer([&]() { lowdown_term_free(renderer); }); + + auto buf = lowdown_buf_new(16384); + if (!buf) + throw Error("cannot allocate Markdown output buffer"); + Finally freeBuffer([&]() { lowdown_buf_free(buf); }); + + lowdown_term_rndr(buf, nullptr, renderer, node); + + return std::string(buf->data, buf->size); +} + +} diff --git a/src/nix/markdown.hh b/src/nix/markdown.hh new file mode 100644 index 000000000..78320fcf5 --- /dev/null +++ b/src/nix/markdown.hh @@ -0,0 +1,7 @@ +#include "types.hh" + +namespace nix { + +std::string renderMarkdownToTerminal(std::string_view markdown); + +} diff --git a/src/nix/optimise-store.cc b/src/nix/optimise-store.cc index b45951879..51a7a9756 100644 --- a/src/nix/optimise-store.cc +++ b/src/nix/optimise-store.cc @@ -31,4 +31,4 @@ struct CmdOptimiseStore : StoreCommand } }; -static auto r1 = registerCommand("optimise-store"); +static auto rCmdOptimiseStore = registerCommand("optimise-store"); diff --git a/src/nix/path-info.cc b/src/nix/path-info.cc index b89a44f83..63cf885f9 100644 --- a/src/nix/path-info.cc +++ b/src/nix/path-info.cc @@ -40,7 +40,7 @@ struct CmdPathInfo : StorePathsCommand, MixJSON }, Example{ "To show a package's closure size and all its dependencies with human readable sizes:", - "nix path-info -rsSh nixpkgs.rust" + "nix path-info -rsSh nixpkgs#rust" }, Example{ "To check the existence of a path in a binary cache:", @@ -61,7 +61,7 @@ struct CmdPathInfo : StorePathsCommand, MixJSON }; } - void printSize(unsigned long long value) + void printSize(uint64_t value) { if (!humanReadable) { std::cout << fmt("\t%11d", value); @@ -127,4 +127,4 @@ struct CmdPathInfo : StorePathsCommand, MixJSON } }; -static auto r1 = registerCommand("path-info"); +static auto rCmdPathInfo = registerCommand("path-info"); diff --git a/src/nix/ping-store.cc b/src/nix/ping-store.cc index 127397a29..8db78d591 100644 --- a/src/nix/ping-store.cc +++ b/src/nix/ping-store.cc @@ -29,4 +29,4 @@ struct CmdPingStore : StoreCommand } }; -static auto r1 = registerCommand("ping-store"); +static auto rCmdPingStore = registerCommand("ping-store"); diff --git a/src/nix/profile.cc b/src/nix/profile.cc new file mode 100644 index 000000000..01aef2f9b --- /dev/null +++ b/src/nix/profile.cc @@ -0,0 +1,470 @@ +#include "command.hh" +#include "common-args.hh" +#include "shared.hh" +#include "store-api.hh" +#include "derivations.hh" +#include "archive.hh" +#include "builtins/buildenv.hh" +#include "flake/flakeref.hh" +#include "../nix-env/user-env.hh" +#include "profiles.hh" + +#include +#include + +using namespace nix; + +struct ProfileElementSource +{ + FlakeRef originalRef; + // FIXME: record original attrpath. + FlakeRef resolvedRef; + std::string attrPath; + // FIXME: output names +}; + +struct ProfileElement +{ + StorePathSet storePaths; + std::optional source; + bool active = true; + // FIXME: priority +}; + +struct ProfileManifest +{ + std::vector elements; + + ProfileManifest() { } + + ProfileManifest(EvalState & state, const Path & profile) + { + auto manifestPath = profile + "/manifest.json"; + + if (pathExists(manifestPath)) { + auto json = nlohmann::json::parse(readFile(manifestPath)); + + auto version = json.value("version", 0); + if (version != 1) + throw Error("profile manifest '%s' has unsupported version %d", manifestPath, version); + + for (auto & e : json["elements"]) { + ProfileElement element; + for (auto & p : e["storePaths"]) + element.storePaths.insert(state.store->parseStorePath((std::string) p)); + element.active = e["active"]; + if (e.value("uri", "") != "") { + element.source = ProfileElementSource{ + parseFlakeRef(e["originalUri"]), + parseFlakeRef(e["uri"]), + e["attrPath"] + }; + } + elements.emplace_back(std::move(element)); + } + } + + else if (pathExists(profile + "/manifest.nix")) { + // FIXME: needed because of pure mode; ugly. + if (state.allowedPaths) { + state.allowedPaths->insert(state.store->followLinksToStore(profile)); + state.allowedPaths->insert(state.store->followLinksToStore(profile + "/manifest.nix")); + } + + auto drvInfos = queryInstalled(state, state.store->followLinksToStore(profile)); + + for (auto & drvInfo : drvInfos) { + ProfileElement element; + element.storePaths = {state.store->parseStorePath(drvInfo.queryOutPath())}; + elements.emplace_back(std::move(element)); + } + } + } + + std::string toJSON(Store & store) const + { + auto array = nlohmann::json::array(); + for (auto & element : elements) { + auto paths = nlohmann::json::array(); + for (auto & path : element.storePaths) + paths.push_back(store.printStorePath(path)); + nlohmann::json obj; + obj["storePaths"] = paths; + obj["active"] = element.active; + if (element.source) { + obj["originalUri"] = element.source->originalRef.to_string(); + obj["uri"] = element.source->resolvedRef.to_string(); + obj["attrPath"] = element.source->attrPath; + } + array.push_back(obj); + } + nlohmann::json json; + json["version"] = 1; + json["elements"] = array; + return json.dump(); + } + + StorePath build(ref store) + { + auto tempDir = createTempDir(); + + StorePathSet references; + + Packages pkgs; + for (auto & element : elements) { + for (auto & path : element.storePaths) { + if (element.active) + pkgs.emplace_back(store->printStorePath(path), true, 5); + references.insert(path); + } + } + + buildProfile(tempDir, std::move(pkgs)); + + writeFile(tempDir + "/manifest.json", toJSON(*store)); + + /* Add the symlink tree to the store. */ + StringSink sink; + dumpPath(tempDir, sink); + + auto narHash = hashString(htSHA256, *sink.s); + + ValidPathInfo info { + store->makeFixedOutputPath(FileIngestionMethod::Recursive, narHash, "profile", references), + narHash, + }; + info.references = std::move(references); + info.narSize = sink.s->size(); + info.ca = FixedOutputHash { .method = FileIngestionMethod::Recursive, .hash = info.narHash }; + + auto source = StringSource { *sink.s }; + store->addToStore(info, source); + + return std::move(info.path); + } +}; + +struct CmdProfileInstall : InstallablesCommand, MixDefaultProfile +{ + std::string description() override + { + return "install a package into a profile"; + } + + Examples examples() override + { + return { + Example{ + "To install a package from Nixpkgs:", + "nix profile install nixpkgs#hello" + }, + Example{ + "To install a package from a specific branch of Nixpkgs:", + "nix profile install nixpkgs/release-19.09#hello" + }, + Example{ + "To install a package from a specific revision of Nixpkgs:", + "nix profile install nixpkgs/1028bb33859f8dfad7f98e1c8d185f3d1aaa7340#hello" + }, + }; + } + + void run(ref store) override + { + ProfileManifest manifest(*getEvalState(), *profile); + + std::vector pathsToBuild; + + for (auto & installable : installables) { + if (auto installable2 = std::dynamic_pointer_cast(installable)) { + auto [attrPath, resolvedRef, drv] = installable2->toDerivation(); + + ProfileElement element; + if (!drv.outPath) + throw UnimplementedError("CA derivations are not yet supported by 'nix profile'"); + element.storePaths = {*drv.outPath}; // FIXME + element.source = ProfileElementSource{ + installable2->flakeRef, + resolvedRef, + attrPath, + }; + + pathsToBuild.push_back({drv.drvPath, StringSet{"out"}}); // FIXME + + manifest.elements.emplace_back(std::move(element)); + } else + throw UnimplementedError("'nix profile install' does not support argument '%s'", installable->what()); + } + + store->buildPaths(pathsToBuild); + + updateProfile(manifest.build(store)); + } +}; + +class MixProfileElementMatchers : virtual Args +{ + std::vector _matchers; + +public: + + MixProfileElementMatchers() + { + expectArgs("elements", &_matchers); + } + + typedef std::variant Matcher; + + std::vector getMatchers(ref store) + { + std::vector res; + + for (auto & s : _matchers) { + size_t n; + if (string2Int(s, n)) + res.push_back(n); + else if (store->isStorePath(s)) + res.push_back(s); + else + res.push_back(std::regex(s, std::regex::extended | std::regex::icase)); + } + + return res; + } + + bool matches(const Store & store, const ProfileElement & element, size_t pos, const std::vector & matchers) + { + for (auto & matcher : matchers) { + if (auto n = std::get_if(&matcher)) { + if (*n == pos) return true; + } else if (auto path = std::get_if(&matcher)) { + if (element.storePaths.count(store.parseStorePath(*path))) return true; + } else if (auto regex = std::get_if(&matcher)) { + if (element.source + && std::regex_match(element.source->attrPath, *regex)) + return true; + } + } + + return false; + } +}; + +struct CmdProfileRemove : virtual EvalCommand, MixDefaultProfile, MixProfileElementMatchers +{ + std::string description() override + { + return "remove packages from a profile"; + } + + Examples examples() override + { + return { + Example{ + "To remove a package by attribute path:", + "nix profile remove packages.x86_64-linux.hello" + }, + Example{ + "To remove all packages:", + "nix profile remove '.*'" + }, + Example{ + "To remove a package by store path:", + "nix profile remove /nix/store/rr3y0c6zyk7kjjl8y19s4lsrhn4aiq1z-hello-2.10" + }, + Example{ + "To remove a package by position:", + "nix profile remove 3" + }, + }; + } + + void run(ref store) override + { + ProfileManifest oldManifest(*getEvalState(), *profile); + + auto matchers = getMatchers(store); + + ProfileManifest newManifest; + + for (size_t i = 0; i < oldManifest.elements.size(); ++i) { + auto & element(oldManifest.elements[i]); + if (!matches(*store, element, i, matchers)) + newManifest.elements.push_back(std::move(element)); + } + + // FIXME: warn about unused matchers? + + printInfo("removed %d packages, kept %d packages", + oldManifest.elements.size() - newManifest.elements.size(), + newManifest.elements.size()); + + updateProfile(newManifest.build(store)); + } +}; + +struct CmdProfileUpgrade : virtual SourceExprCommand, MixDefaultProfile, MixProfileElementMatchers +{ + std::string description() override + { + return "upgrade packages using their most recent flake"; + } + + Examples examples() override + { + return { + Example{ + "To upgrade all packages that were installed using a mutable flake reference:", + "nix profile upgrade '.*'" + }, + Example{ + "To upgrade a specific package:", + "nix profile upgrade packages.x86_64-linux.hello" + }, + }; + } + + void run(ref store) override + { + ProfileManifest manifest(*getEvalState(), *profile); + + auto matchers = getMatchers(store); + + // FIXME: code duplication + std::vector pathsToBuild; + + for (size_t i = 0; i < manifest.elements.size(); ++i) { + auto & element(manifest.elements[i]); + if (element.source + && !element.source->originalRef.input.isImmutable() + && matches(*store, element, i, matchers)) + { + Activity act(*logger, lvlChatty, actUnknown, + fmt("checking '%s' for updates", element.source->attrPath)); + + InstallableFlake installable(getEvalState(), FlakeRef(element.source->originalRef), {element.source->attrPath}, {}, lockFlags); + + auto [attrPath, resolvedRef, drv] = installable.toDerivation(); + + if (element.source->resolvedRef == resolvedRef) continue; + + printInfo("upgrading '%s' from flake '%s' to '%s'", + element.source->attrPath, element.source->resolvedRef, resolvedRef); + + if (!drv.outPath) + throw UnimplementedError("CA derivations are not yet supported by 'nix profile'"); + element.storePaths = {*drv.outPath}; // FIXME + element.source = ProfileElementSource{ + installable.flakeRef, + resolvedRef, + attrPath, + }; + + pathsToBuild.push_back({drv.drvPath, StringSet{"out"}}); // FIXME + } + } + + store->buildPaths(pathsToBuild); + + updateProfile(manifest.build(store)); + } +}; + +struct CmdProfileInfo : virtual EvalCommand, virtual StoreCommand, MixDefaultProfile +{ + std::string description() override + { + return "list installed packages"; + } + + Examples examples() override + { + return { + Example{ + "To show what packages are installed in the default profile:", + "nix profile info" + }, + }; + } + + void run(ref store) override + { + ProfileManifest manifest(*getEvalState(), *profile); + + for (size_t i = 0; i < manifest.elements.size(); ++i) { + auto & element(manifest.elements[i]); + logger->stdout("%d %s %s %s", i, + element.source ? element.source->originalRef.to_string() + "#" + element.source->attrPath : "-", + element.source ? element.source->resolvedRef.to_string() + "#" + element.source->attrPath : "-", + concatStringsSep(" ", store->printStorePathSet(element.storePaths))); + } + } +}; + +struct CmdProfileDiffClosures : virtual StoreCommand, MixDefaultProfile +{ + std::string description() override + { + return "show the closure difference between each generation of a profile"; + } + + Examples examples() override + { + return { + Example{ + "To show what changed between each generation of the NixOS system profile:", + "nix profile diff-closure --profile /nix/var/nix/profiles/system" + }, + }; + } + + void run(ref store) override + { + auto [gens, curGen] = findGenerations(*profile); + + std::optional prevGen; + bool first = true; + + for (auto & gen : gens) { + if (prevGen) { + if (!first) std::cout << "\n"; + first = false; + std::cout << fmt("Generation %d -> %d:\n", prevGen->number, gen.number); + printClosureDiff(store, + store->followLinksToStorePath(prevGen->path), + store->followLinksToStorePath(gen.path), + " "); + } + + prevGen = gen; + } + } +}; + +struct CmdProfile : NixMultiCommand +{ + CmdProfile() + : MultiCommand({ + {"install", []() { return make_ref(); }}, + {"remove", []() { return make_ref(); }}, + {"upgrade", []() { return make_ref(); }}, + {"info", []() { return make_ref(); }}, + {"diff-closures", []() { return make_ref(); }}, + }) + { } + + std::string description() override + { + return "manage Nix profiles"; + } + + void run() override + { + if (!command) + throw UsageError("'nix profile' requires a sub-command."); + command->second->prepare(); + command->second->run(); + } +}; + +static auto rCmdProfile = registerCommand("profile"); diff --git a/src/nix/registry.cc b/src/nix/registry.cc new file mode 100644 index 000000000..8e8983ad0 --- /dev/null +++ b/src/nix/registry.cc @@ -0,0 +1,146 @@ +#include "command.hh" +#include "common-args.hh" +#include "shared.hh" +#include "eval.hh" +#include "flake/flake.hh" +#include "store-api.hh" +#include "fetchers.hh" +#include "registry.hh" + +using namespace nix; +using namespace nix::flake; + +struct CmdRegistryList : StoreCommand +{ + std::string description() override + { + return "list available Nix flakes"; + } + + void run(nix::ref store) override + { + using namespace fetchers; + + auto registries = getRegistries(store); + + for (auto & registry : registries) { + for (auto & entry : registry->entries) { + // FIXME: format nicely + logger->stdout("%s %s %s", + registry->type == Registry::Flag ? "flags " : + registry->type == Registry::User ? "user " : + registry->type == Registry::System ? "system" : + "global", + entry.from.toURLString(), + entry.to.toURLString(attrsToQuery(entry.extraAttrs))); + } + } + } +}; + +struct CmdRegistryAdd : MixEvalArgs, Command +{ + std::string fromUrl, toUrl; + + std::string description() override + { + return "add/replace flake in user flake registry"; + } + + CmdRegistryAdd() + { + expectArg("from-url", &fromUrl); + expectArg("to-url", &toUrl); + } + + void run() override + { + auto fromRef = parseFlakeRef(fromUrl); + auto toRef = parseFlakeRef(toUrl); + fetchers::Attrs extraAttrs; + if (toRef.subdir != "") extraAttrs["dir"] = toRef.subdir; + auto userRegistry = fetchers::getUserRegistry(); + userRegistry->remove(fromRef.input); + userRegistry->add(fromRef.input, toRef.input, extraAttrs); + userRegistry->write(fetchers::getUserRegistryPath()); + } +}; + +struct CmdRegistryRemove : virtual Args, MixEvalArgs, Command +{ + std::string url; + + std::string description() override + { + return "remove flake from user flake registry"; + } + + CmdRegistryRemove() + { + expectArg("url", &url); + } + + void run() override + { + auto userRegistry = fetchers::getUserRegistry(); + userRegistry->remove(parseFlakeRef(url).input); + userRegistry->write(fetchers::getUserRegistryPath()); + } +}; + +struct CmdRegistryPin : virtual Args, EvalCommand +{ + std::string url; + + std::string description() override + { + return "pin a flake to its current version in user flake registry"; + } + + CmdRegistryPin() + { + expectArg("url", &url); + } + + void run(nix::ref store) override + { + auto ref = parseFlakeRef(url); + auto userRegistry = fetchers::getUserRegistry(); + userRegistry->remove(ref.input); + auto [tree, resolved] = ref.resolve(store).input.fetch(store); + fetchers::Attrs extraAttrs; + if (ref.subdir != "") extraAttrs["dir"] = ref.subdir; + userRegistry->add(ref.input, resolved, extraAttrs); + userRegistry->write(fetchers::getUserRegistryPath()); + } +}; + +struct CmdRegistry : virtual NixMultiCommand +{ + CmdRegistry() + : MultiCommand({ + {"list", []() { return make_ref(); }}, + {"add", []() { return make_ref(); }}, + {"remove", []() { return make_ref(); }}, + {"pin", []() { return make_ref(); }}, + }) + { + } + + std::string description() override + { + return "manage the flake registry"; + } + + Category category() override { return catSecondary; } + + void run() override + { + if (!command) + throw UsageError("'nix registry' requires a sub-command."); + command->second->prepare(); + command->second->run(); + } +}; + +static auto rCmdRegistry = registerCommand("registry"); diff --git a/src/nix/repl.cc b/src/nix/repl.cc index fdacf604b..9ff386b1d 100644 --- a/src/nix/repl.cc +++ b/src/nix/repl.cc @@ -32,13 +32,19 @@ extern "C" { #include "globals.hh" #include "command.hh" #include "finally.hh" +#include "markdown.hh" +#if HAVE_BOEHMGC #define GC_INCLUDE_NEW #include +#endif namespace nix { -struct NixRepl : gc +struct NixRepl + #if HAVE_BOEHMGC + : gc + #endif { string curDir; std::unique_ptr state; @@ -59,7 +65,7 @@ struct NixRepl : gc void mainLoop(const std::vector & files); StringSet completePrefix(string prefix); bool getLine(string & input, const std::string &prompt); - Path getDerivationPath(Value & v); + StorePath getDerivationPath(Value & v); bool processLine(string line); void loadFile(const Path & path); void initEnv(); @@ -370,13 +376,16 @@ bool isVarName(const string & s) } -Path NixRepl::getDerivationPath(Value & v) { +StorePath NixRepl::getDerivationPath(Value & v) { auto drvInfo = getDerivation(*state, v, false); if (!drvInfo) throw Error("expression does not evaluate to a derivation, so I can't build it"); - Path drvPath = drvInfo->queryDrvPath(); - if (drvPath == "" || !state->store->isValidPath(state->store->parseStorePath(drvPath))) - throw Error("expression did not evaluate to a valid derivation"); + Path drvPathRaw = drvInfo->queryDrvPath(); + if (drvPathRaw == "") + throw Error("expression did not evaluate to a valid derivation (no drv path)"); + StorePath drvPath = state->store->parseStorePath(drvPathRaw); + if (!state->store->isValidPath(drvPath)) + throw Error("expression did not evaluate to a valid derivation (invalid drv path)"); return drvPath; } @@ -411,7 +420,8 @@ bool NixRepl::processLine(string line) << " :r Reload all files\n" << " :s Build dependencies of derivation, then start nix-shell\n" << " :t Describe result of evaluation\n" - << " :u Build derivation, then start nix-shell\n"; + << " :u Build derivation, then start nix-shell\n" + << " :doc Show documentation of a builtin function\n"; } else if (command == ":a" || command == ":add") { @@ -469,29 +479,30 @@ bool NixRepl::processLine(string line) evalString("drv: (import {}).runCommand \"shell\" { buildInputs = [ drv ]; } \"\"", f); state->callFunction(f, v, result, Pos()); - Path drvPath = getDerivationPath(result); - runProgram(settings.nixBinDir + "/nix-shell", Strings{drvPath}); + StorePath drvPath = getDerivationPath(result); + runProgram(settings.nixBinDir + "/nix-shell", Strings{state->store->printStorePath(drvPath)}); } else if (command == ":b" || command == ":i" || command == ":s") { Value v; evalString(arg, v); - Path drvPath = getDerivationPath(v); + StorePath drvPath = getDerivationPath(v); + Path drvPathRaw = state->store->printStorePath(drvPath); if (command == ":b") { /* We could do the build in this process using buildPaths(), but doing it in a child makes it easier to recover from problems / SIGINT. */ - if (runProgram(settings.nixBinDir + "/nix", Strings{"build", "--no-link", drvPath}) == 0) { - auto drv = readDerivation(*state->store, drvPath); + if (runProgram(settings.nixBinDir + "/nix", Strings{"build", "--no-link", drvPathRaw}) == 0) { + auto drv = state->store->readDerivation(drvPath); std::cout << std::endl << "this derivation produced the following outputs:" << std::endl; - for (auto & i : drv.outputs) - std::cout << fmt(" %s -> %s\n", i.first, state->store->printStorePath(i.second.path)); + for (auto & i : drv.outputsAndOptPaths(*state->store)) + std::cout << fmt(" %s -> %s\n", i.first, state->store->printStorePath(*i.second.second)); } } else if (command == ":i") { - runProgram(settings.nixBinDir + "/nix-env", Strings{"-i", drvPath}); + runProgram(settings.nixBinDir + "/nix-env", Strings{"-i", drvPathRaw}); } else { - runProgram(settings.nixBinDir + "/nix-shell", Strings{drvPath}); + runProgram(settings.nixBinDir + "/nix-shell", Strings{drvPathRaw}); } } @@ -504,6 +515,29 @@ bool NixRepl::processLine(string line) else if (command == ":q" || command == ":quit") return false; + else if (command == ":doc") { + Value v; + evalString(arg, v); + if (auto doc = state->getDoc(v)) { + std::string markdown; + + if (!doc->args.empty() && doc->name) { + auto args = doc->args; + for (auto & arg : args) + arg = "*" + arg + "*"; + + markdown += + "**Synopsis:** `builtins." + (std::string) (*doc->name) + "` " + + concatStringsSep(" ", args) + "\n\n"; + } + + markdown += trim(stripIndentation(doc->doc)); + + std::cout << renderMarkdownToTerminal(markdown); + } else + throw Error("value does not have documentation"); + } + else if (command != "") throw Error("unknown command '%1%'", command); @@ -760,7 +794,11 @@ struct CmdRepl : StoreCommand, MixEvalArgs CmdRepl() { - expectArgs("files", &files); + expectArgs({ + .label = "files", + .handler = {&files}, + .completer = completePath + }); } std::string description() override @@ -773,19 +811,20 @@ struct CmdRepl : StoreCommand, MixEvalArgs return { Example{ "Display all special commands within the REPL:", - "nix repl\n nix-repl> :?" + "nix repl\nnix-repl> :?" } }; } void run(ref store) override { + evalSettings.pureEval = false; auto repl = std::make_unique(searchPath, openStore()); repl->autoArgs = getAutoArgs(*repl->state); repl->mainLoop(files); } }; -static auto r1 = registerCommand("repl"); +static auto rCmdRepl = registerCommand("repl"); } diff --git a/src/nix/run.cc b/src/nix/run.cc index 321ee1d11..790784382 100644 --- a/src/nix/run.cc +++ b/src/nix/run.cc @@ -84,31 +84,30 @@ struct CmdShell : InstallablesCommand, RunCommon, MixEnvironment { return { Example{ - "To start a shell providing GNU Hello from NixOS 17.03:", - "nix shell -f channel:nixos-17.03 hello" + "To start a shell providing GNU Hello from NixOS 20.03:", + "nix shell nixpkgs/nixos-20.03#hello" }, Example{ "To start a shell providing youtube-dl from your 'nixpkgs' channel:", - "nix shell nixpkgs.youtube-dl" + "nix shell nixpkgs#youtube-dl" }, Example{ "To run GNU Hello:", - "nix shell nixpkgs.hello -c hello --greeting 'Hi everybody!'" + "nix shell nixpkgs#hello -c hello --greeting 'Hi everybody!'" }, Example{ "To run GNU Hello in a chroot store:", - "nix shell --store ~/my-nix nixpkgs.hello -c hello" + "nix shell --store ~/my-nix nixpkgs#hello -c hello" }, }; } void run(ref store) override { - auto outPaths = toStorePaths(store, Build, installables); + auto outPaths = toStorePaths(store, Realise::Outputs, OperateOn::Output, installables); auto accessor = store->getFSAccessor(); - std::unordered_set done; std::queue todo; for (auto & path : outPaths) todo.push(path); @@ -141,7 +140,76 @@ struct CmdShell : InstallablesCommand, RunCommon, MixEnvironment } }; -static auto r1 = registerCommand("shell"); +static auto rCmdShell = registerCommand("shell"); + +struct CmdRun : InstallableCommand, RunCommon +{ + std::vector args; + + CmdRun() + { + expectArgs({ + .label = "args", + .handler = {&args}, + .completer = completePath + }); + } + + std::string description() override + { + return "run a Nix application"; + } + + Examples examples() override + { + return { + Example{ + "To run Blender:", + "nix run blender-bin" + }, + Example{ + "To run vim from nixpkgs:", + "nix run nixpkgs#vim" + }, + Example{ + "To run vim from nixpkgs with arguments:", + "nix run nixpkgs#vim -- --help" + }, + }; + } + + Strings getDefaultFlakeAttrPaths() override + { + Strings res{"defaultApp." + settings.thisSystem.get()}; + for (auto & s : SourceExprCommand::getDefaultFlakeAttrPaths()) + res.push_back(s); + return res; + } + + Strings getDefaultFlakeAttrPathPrefixes() override + { + Strings res{"apps." + settings.thisSystem.get() + ".", "packages"}; + for (auto & s : SourceExprCommand::getDefaultFlakeAttrPathPrefixes()) + res.push_back(s); + return res; + } + + void run(ref store) override + { + auto state = getEvalState(); + + auto app = installable->toApp(*state); + + state->store->buildPaths(app.context); + + Strings allArgs{app.program}; + for (auto & i : args) allArgs.push_back(i); + + runProgram(store, app.program, allArgs); + } +}; + +static auto rCmdRun = registerCommand("run"); void chrootHelper(int argc, char * * argv) { diff --git a/src/nix/search.cc b/src/nix/search.cc index 93c3f3f83..d4326dc84 100644 --- a/src/nix/search.cc +++ b/src/nix/search.cc @@ -6,8 +6,9 @@ #include "get-drvs.hh" #include "common-args.hh" #include "json.hh" -#include "json-to-value.hh" #include "shared.hh" +#include "eval-cache.hh" +#include "attr-path.hh" #include #include @@ -25,33 +26,17 @@ std::string hilite(const std::string & s, const std::smatch & m, std::string pos m.empty() ? s : std::string(m.prefix()) - + ANSI_RED + std::string(m.str()) + postfix + + ANSI_GREEN + std::string(m.str()) + postfix + std::string(m.suffix()); } -struct CmdSearch : SourceExprCommand, MixJSON +struct CmdSearch : InstallableCommand, MixJSON { std::vector res; - bool writeCache = true; - bool useCache = true; - CmdSearch() { expectArgs("regex", &res); - - addFlag({ - .longName = "update-cache", - .shortName = 'u', - .description = "update the package search cache", - .handler = {[&]() { writeCache = true; useCache = false; }} - }); - - addFlag({ - .longName = "no-cache", - .description = "do not use or update the package search cache", - .handler = {[&]() { writeCache = false; useCache = false; }} - }); } std::string description() override @@ -63,24 +48,32 @@ struct CmdSearch : SourceExprCommand, MixJSON { return { Example{ - "To show all available packages:", + "To show all packages in the flake in the current directory:", "nix search" }, Example{ - "To show any packages containing 'blender' in its name or description:", - "nix search blender" + "To show packages in the 'nixpkgs' flake containing 'blender' in its name or description:", + "nix search nixpkgs blender" }, Example{ "To search for Firefox or Chromium:", - "nix search 'firefox|chromium'" + "nix search nixpkgs 'firefox|chromium'" }, Example{ - "To search for git and frontend or gui:", - "nix search git 'frontend|gui'" + "To search for packages containing 'git' and either 'frontend' or 'gui':", + "nix search nixpkgs git 'frontend|gui'" } }; } + Strings getDefaultFlakeAttrPaths() override + { + return { + "packages." + settings.thisSystem.get() + ".", + "legacyPackages." + settings.thisSystem.get() + "." + }; + } + void run(ref store) override { settings.readOnlyMode = true; @@ -88,190 +81,108 @@ struct CmdSearch : SourceExprCommand, MixJSON // Empty search string should match all packages // Use "^" here instead of ".*" due to differences in resulting highlighting // (see #1893 -- libc++ claims empty search string is not in POSIX grammar) - if (res.empty()) { + if (res.empty()) res.push_back("^"); - } std::vector regexes; regexes.reserve(res.size()); - for (auto &re : res) { + for (auto & re : res) regexes.push_back(std::regex(re, std::regex::extended | std::regex::icase)); - } auto state = getEvalState(); auto jsonOut = json ? std::make_unique(std::cout) : nullptr; - auto sToplevel = state->symbols.create("_toplevel"); - auto sRecurse = state->symbols.create("recurseForDerivations"); + uint64_t results = 0; - bool fromCache = false; - - std::map results; - - std::function doExpr; - - doExpr = [&](Value * v, std::string attrPath, bool toplevel, JSONObject * cache) { - debug("at attribute '%s'", attrPath); + std::function & attrPath)> visit; + visit = [&](eval_cache::AttrCursor & cursor, const std::vector & attrPath) + { + Activity act(*logger, lvlInfo, actUnknown, + fmt("evaluating '%s'", concatStringsSep(".", attrPath))); try { - uint found = 0; + auto recurse = [&]() + { + for (const auto & attr : cursor.getAttrs()) { + auto cursor2 = cursor.getAttr(attr); + auto attrPath2(attrPath); + attrPath2.push_back(attr); + visit(*cursor2, attrPath2); + } + }; - state->forceValue(*v); + if (cursor.isDerivation()) { + size_t found = 0; - if (v->type == tLambda && toplevel) { - Value * v2 = state->allocValue(); - state->autoCallFunction(*state->allocBindings(1), *v, *v2); - v = v2; - state->forceValue(*v); - } + DrvName name(cursor.getAttr("name")->getString()); - if (state->isDerivation(*v)) { + auto aMeta = cursor.maybeGetAttr("meta"); + auto aDescription = aMeta ? aMeta->maybeGetAttr("description") : nullptr; + auto description = aDescription ? aDescription->getString() : ""; + std::replace(description.begin(), description.end(), '\n', ' '); + auto attrPath2 = concatStringsSep(".", attrPath); - DrvInfo drv(*state, attrPath, v->attrs); - std::string description; std::smatch attrPathMatch; std::smatch descriptionMatch; std::smatch nameMatch; - std::string name; - DrvName parsed(drv.queryName()); - - for (auto ®ex : regexes) { - std::regex_search(attrPath, attrPathMatch, regex); - - name = parsed.name; - std::regex_search(name, nameMatch, regex); - - description = drv.queryMetaString("description"); - std::replace(description.begin(), description.end(), '\n', ' '); + for (auto & regex : regexes) { + std::regex_search(attrPath2, attrPathMatch, regex); + std::regex_search(name.name, nameMatch, regex); std::regex_search(description, descriptionMatch, regex); - if (!attrPathMatch.empty() || !nameMatch.empty() || !descriptionMatch.empty()) - { found++; - } } if (found == res.size()) { + results++; if (json) { - - auto jsonElem = jsonOut->object(attrPath); - - jsonElem.attr("pkgName", parsed.name); - jsonElem.attr("version", parsed.version); + auto jsonElem = jsonOut->object(attrPath2); + jsonElem.attr("pname", name.name); + jsonElem.attr("version", name.version); jsonElem.attr("description", description); - } else { - auto name = hilite(parsed.name, nameMatch, "\e[0;2m") - + std::string(parsed.fullName, parsed.name.length()); - results[attrPath] = fmt( - "* %s (%s)\n %s\n", - wrap("\e[0;1m", hilite(attrPath, attrPathMatch, "\e[0;1m")), - wrap("\e[0;2m", hilite(name, nameMatch, "\e[0;2m")), - hilite(description, descriptionMatch, ANSI_NORMAL)); - } - } - - if (cache) { - cache->attr("type", "derivation"); - cache->attr("name", drv.queryName()); - cache->attr("system", drv.querySystem()); - if (description != "") { - auto meta(cache->object("meta")); - meta.attr("description", description); + auto name2 = hilite(name.name, nameMatch, "\e[0;2m"); + if (results > 1) logger->stdout(""); + logger->stdout( + "* %s%s", + wrap("\e[0;1m", hilite(attrPath2, attrPathMatch, "\e[0;1m")), + name.version != "" ? " (" + name.version + ")" : ""); + if (description != "") + logger->stdout( + " %s", hilite(description, descriptionMatch, ANSI_NORMAL)); } } } - else if (v->type == tAttrs) { + else if ( + attrPath.size() == 0 + || (attrPath[0] == "legacyPackages" && attrPath.size() <= 2) + || (attrPath[0] == "packages" && attrPath.size() <= 2)) + recurse(); - if (!toplevel) { - auto attrs = v->attrs; - Bindings::iterator j = attrs->find(sRecurse); - if (j == attrs->end() || !state->forceBool(*j->value, *j->pos)) { - debug("skip attribute '%s'", attrPath); - return; - } - } - - bool toplevel2 = false; - if (!fromCache) { - Bindings::iterator j = v->attrs->find(sToplevel); - toplevel2 = j != v->attrs->end() && state->forceBool(*j->value, *j->pos); - } - - for (auto & i : *v->attrs) { - auto cache2 = - cache ? std::make_unique(cache->object(i.name)) : nullptr; - doExpr(i.value, - attrPath == "" ? (std::string) i.name : attrPath + "." + (std::string) i.name, - toplevel2 || fromCache, cache2 ? cache2.get() : nullptr); - } + else if (attrPath[0] == "legacyPackages" && attrPath.size() > 2) { + auto attr = cursor.maybeGetAttr(state->sRecurseForDerivations); + if (attr && attr->getBool()) + recurse(); } - } catch (AssertionError & e) { - } catch (Error & e) { - if (!toplevel) { - e.addTrace(std::nullopt, "While evaluating the attribute '%s'", attrPath); + } catch (EvalError & e) { + if (!(attrPath.size() > 0 && attrPath[0] == "legacyPackages")) throw; - } } }; - Path jsonCacheFileName = getCacheDir() + "/nix/package-search.json"; + for (auto & [cursor, prefix] : installable->getCursors(*state)) + visit(*cursor, parseAttrPath(*state, prefix)); - if (useCache && pathExists(jsonCacheFileName)) { - - warn("using cached results; pass '-u' to update the cache"); - - Value vRoot; - parseJSON(*state, readFile(jsonCacheFileName), vRoot); - - fromCache = true; - - doExpr(&vRoot, "", true, nullptr); - } - - else { - createDirs(dirOf(jsonCacheFileName)); - - Path tmpFile = fmt("%s.tmp.%d", jsonCacheFileName, getpid()); - - std::ofstream jsonCacheFile; - - try { - // iostream considered harmful - jsonCacheFile.exceptions(std::ofstream::failbit); - jsonCacheFile.open(tmpFile); - - auto cache = writeCache ? std::make_unique(jsonCacheFile, false) : nullptr; - - doExpr(getSourceExpr(*state), "", true, cache.get()); - - } catch (std::exception &) { - /* Fun fact: catching std::ios::failure does not work - due to C++11 ABI shenanigans. - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145 */ - if (!jsonCacheFile) - throw Error("error writing to %s", tmpFile); - throw; - } - - if (writeCache && rename(tmpFile.c_str(), jsonCacheFileName.c_str()) == -1) - throw SysError("cannot rename '%s' to '%s'", tmpFile, jsonCacheFileName); - } - - if (!json && results.size() == 0) + if (!json && !results) throw Error("no results for the given search term(s)!"); - - RunPager pager; - for (auto el : results) std::cout << el.second << "\n"; - } }; -static auto r1 = registerCommand("search"); +static auto rCmdSearch = registerCommand("search"); diff --git a/src/nix/show-config.cc b/src/nix/show-config.cc index 4fd8886de..1ef54a33a 100644 --- a/src/nix/show-config.cc +++ b/src/nix/show-config.cc @@ -2,7 +2,8 @@ #include "common-args.hh" #include "shared.hh" #include "store-api.hh" -#include "json.hh" + +#include using namespace nix; @@ -19,8 +20,7 @@ struct CmdShowConfig : Command, MixJSON { if (json) { // FIXME: use appropriate JSON types (bool, ints, etc). - JSONObject jsonObj(std::cout); - globalConfig.toJSON(jsonObj); + logger->stdout("%s", globalConfig.toJSON().dump()); } else { std::map settings; globalConfig.getSettings(settings); @@ -30,4 +30,4 @@ struct CmdShowConfig : Command, MixJSON } }; -static auto r1 = registerCommand("show-config"); +static auto rShowConfig = registerCommand("show-config"); diff --git a/src/nix/show-derivation.cc b/src/nix/show-derivation.cc index 5d77cfdca..2542537d3 100644 --- a/src/nix/show-derivation.cc +++ b/src/nix/show-derivation.cc @@ -33,7 +33,7 @@ struct CmdShowDerivation : InstallablesCommand return { Example{ "To show the store derivation that results from evaluating the Hello package:", - "nix show-derivation nixpkgs.hello" + "nix show-derivation nixpkgs#hello" }, Example{ "To show the full derivation graph (if available) that produced your NixOS system:", @@ -67,13 +67,22 @@ struct CmdShowDerivation : InstallablesCommand { auto outputsObj(drvObj.object("outputs")); - for (auto & output : drv.outputs) { - auto outputObj(outputsObj.object(output.first)); - outputObj.attr("path", store->printStorePath(output.second.path)); - if (output.second.hash) { - outputObj.attr("hashAlgo", output.second.hash->printMethodAlgo()); - outputObj.attr("hash", output.second.hash->hash.to_string(Base16, false)); - } + for (auto & [_outputName, output] : drv.outputs) { + auto & outputName = _outputName; // work around clang bug + auto outputObj { outputsObj.object(outputName) }; + std::visit(overloaded { + [&](DerivationOutputInputAddressed doi) { + outputObj.attr("path", store->printStorePath(doi.path)); + }, + [&](DerivationOutputCAFixed dof) { + outputObj.attr("path", store->printStorePath(dof.path(*store, drv.name, outputName))); + outputObj.attr("hashAlgo", dof.hash.printMethodAlgo()); + outputObj.attr("hash", dof.hash.hash.to_string(Base16, false)); + }, + [&](DerivationOutputCAFloating dof) { + outputObj.attr("hashAlgo", makeFileIngestionPrefix(dof.method) + printHashType(dof.hashType)); + }, + }, output.output); } } @@ -114,4 +123,4 @@ struct CmdShowDerivation : InstallablesCommand } }; -static auto r1 = registerCommand("show-derivation"); +static auto rCmdShowDerivation = registerCommand("show-derivation"); diff --git a/src/nix/sigs.cc b/src/nix/sigs.cc index 6c9b9a792..44916c77f 100644 --- a/src/nix/sigs.cc +++ b/src/nix/sigs.cc @@ -92,7 +92,7 @@ struct CmdCopySigs : StorePathsCommand } }; -static auto r1 = registerCommand("copy-sigs"); +static auto rCmdCopySigs = registerCommand("copy-sigs"); struct CmdSignPaths : StorePathsCommand { @@ -105,7 +105,8 @@ struct CmdSignPaths : StorePathsCommand .shortName = 'k', .description = "file containing the secret signing key", .labels = {"file"}, - .handler = {&secretKeyFile} + .handler = {&secretKeyFile}, + .completer = completePath }); } @@ -143,4 +144,4 @@ struct CmdSignPaths : StorePathsCommand } }; -static auto r2 = registerCommand("sign-paths"); +static auto rCmdSignPaths = registerCommand("sign-paths"); diff --git a/src/nix/upgrade-nix.cc b/src/nix/upgrade-nix.cc index a880bdae0..66ecc5b34 100644 --- a/src/nix/upgrade-nix.cc +++ b/src/nix/upgrade-nix.cc @@ -158,4 +158,4 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand } }; -static auto r1 = registerCommand("upgrade-nix"); +static auto rCmdUpgradeNix = registerCommand("upgrade-nix"); diff --git a/src/nix/verify.cc b/src/nix/verify.cc index bb5e4529b..ec7333d03 100644 --- a/src/nix/verify.cc +++ b/src/nix/verify.cc @@ -77,20 +77,23 @@ struct CmdVerify : StorePathsCommand try { checkInterrupt(); - Activity act2(*logger, lvlInfo, actUnknown, fmt("checking '%s'", storePath)); - MaintainCount> mcActive(active); update(); auto info = store->queryPathInfo(store->parseStorePath(storePath)); + // Note: info->path can be different from storePath + // for binary cache stores when using --all (since we + // can't enumerate names efficiently). + Activity act2(*logger, lvlInfo, actUnknown, fmt("checking '%s'", store->printStorePath(info->path))); + if (!noContents) { std::unique_ptr hashSink; if (!info->ca) - hashSink = std::make_unique(*info->narHash.type); + hashSink = std::make_unique(info->narHash.type); else - hashSink = std::make_unique(*info->narHash.type, std::string(info->path.hashPart())); + hashSink = std::make_unique(info->narHash.type, std::string(info->path.hashPart())); store->narFromPath(info->path, *hashSink); @@ -186,4 +189,4 @@ struct CmdVerify : StorePathsCommand } }; -static auto r1 = registerCommand("verify"); +static auto rCmdVerify = registerCommand("verify"); diff --git a/src/nix/why-depends.cc b/src/nix/why-depends.cc index 167c974ee..63bf087e6 100644 --- a/src/nix/why-depends.cc +++ b/src/nix/why-depends.cc @@ -55,15 +55,15 @@ struct CmdWhyDepends : SourceExprCommand return { Example{ "To show one path through the dependency graph leading from Hello to Glibc:", - "nix why-depends nixpkgs.hello nixpkgs.glibc" + "nix why-depends nixpkgs#hello nixpkgs#glibc" }, Example{ "To show all files and paths in the dependency graph leading from Thunderbird to libX11:", - "nix why-depends --all nixpkgs.thunderbird nixpkgs.xorg.libX11" + "nix why-depends --all nixpkgs#thunderbird nixpkgs#xorg.libX11" }, Example{ "To show why Glibc depends on itself:", - "nix why-depends nixpkgs.glibc nixpkgs.glibc" + "nix why-depends nixpkgs#glibc nixpkgs#glibc" }, }; } @@ -72,17 +72,19 @@ struct CmdWhyDepends : SourceExprCommand void run(ref store) override { - auto package = parseInstallable(*this, store, _package, false); - auto packagePath = toStorePath(store, Build, package); - auto dependency = parseInstallable(*this, store, _dependency, false); - auto dependencyPath = toStorePath(store, NoBuild, dependency); + auto package = parseInstallable(store, _package); + auto packagePath = toStorePath(store, Realise::Outputs, operateOn, package); + auto dependency = parseInstallable(store, _dependency); + auto dependencyPath = toStorePath(store, Realise::Derivation, operateOn, dependency); auto dependencyPathHash = dependencyPath.hashPart(); StorePathSet closure; store->computeFSClosure({packagePath}, closure, false, false); if (!closure.count(dependencyPath)) { - printError("'%s' does not depend on '%s'", package->what(), dependency->what()); + printError("'%s' does not depend on '%s'", + store->printStorePath(packagePath), + store->printStorePath(dependencyPath)); return; } @@ -106,7 +108,11 @@ struct CmdWhyDepends : SourceExprCommand std::map graph; for (auto & path : closure) - graph.emplace(path, Node { .path = path, .refs = store->queryPathInfo(path)->references }); + graph.emplace(path, Node { + .path = path, + .refs = store->queryPathInfo(path)->references, + .dist = path == dependencyPath ? 0 : inf + }); // Transpose the graph. for (auto & node : graph) @@ -115,8 +121,6 @@ struct CmdWhyDepends : SourceExprCommand /* Run Dijkstra's shortest path algorithm to get the distance of every path in the closure to 'dependency'. */ - graph.emplace(dependencyPath, Node { .path = dependencyPath, .dist = 0 }); - std::priority_queue queue; queue.push(&graph.at(dependencyPath)); @@ -259,4 +263,4 @@ struct CmdWhyDepends : SourceExprCommand } }; -static auto r1 = registerCommand("why-depends"); +static auto rCmdWhyDepends = registerCommand("why-depends"); diff --git a/src/resolve-system-dependencies/resolve-system-dependencies.cc b/src/resolve-system-dependencies/resolve-system-dependencies.cc index 434ad80a6..d30227e4e 100644 --- a/src/resolve-system-dependencies/resolve-system-dependencies.cc +++ b/src/resolve-system-dependencies/resolve-system-dependencies.cc @@ -111,11 +111,7 @@ std::set runResolver(const Path & filename) bool isSymlink(const Path & path) { - struct stat st; - if (lstat(path.c_str(), &st) == -1) - throw SysError("getting attributes of path '%1%'", path); - - return S_ISLNK(st.st_mode); + return S_ISLNK(lstat(path).st_mode); } Path resolveSymlink(const Path & path) diff --git a/tests/binary-cache.sh b/tests/binary-cache.sh index 17b63d978..fe4ddec8d 100644 --- a/tests/binary-cache.sh +++ b/tests/binary-cache.sh @@ -182,3 +182,60 @@ clearCacheCache nix-store -r $outPath --substituters "file://$cacheDir2 file://$cacheDir" --trusted-public-keys "$publicKey" fi # HAVE_LIBSODIUM + + +unset _NIX_FORCE_HTTP + + +# Test 'nix verify --all' on a binary cache. +nix verify -vvvvv --all --store file://$cacheDir --no-trust + + +# Test local NAR caching. +narCache=$TEST_ROOT/nar-cache +rm -rf $narCache +mkdir $narCache + +[[ $(nix cat-store --store "file://$cacheDir?local-nar-cache=$narCache" $outPath/foobar) = FOOBAR ]] + +rm -rfv "$cacheDir/nar" + +[[ $(nix cat-store --store "file://$cacheDir?local-nar-cache=$narCache" $outPath/foobar) = FOOBAR ]] + +(! nix cat-store --store file://$cacheDir $outPath/foobar) + + +# Test NAR listing generation. +clearCache + +outPath=$(nix-build --no-out-link -E ' + with import ./config.nix; + mkDerivation { + name = "nar-listing"; + buildCommand = "mkdir $out; echo foo > $out/bar; ln -s xyzzy $out/link"; + } +') + +nix copy --to file://$cacheDir?write-nar-listing=1 $outPath + +diff -u \ + <(jq -S < $cacheDir/$(basename $outPath | cut -c1-32).ls) \ + <(echo '{"version":1,"root":{"type":"directory","entries":{"bar":{"type":"regular","size":4,"narOffset":232},"link":{"type":"symlink","target":"xyzzy"}}}}' | jq -S) + + +# Test debug info index generation. +clearCache + +outPath=$(nix-build --no-out-link -E ' + with import ./config.nix; + mkDerivation { + name = "debug-info"; + buildCommand = "mkdir -p $out/lib/debug/.build-id/02; echo foo > $out/lib/debug/.build-id/02/623eda209c26a59b1a8638ff7752f6b945c26b.debug"; + } +') + +nix copy --to "file://$cacheDir?index-debug-info=1&compression=none" $outPath + +diff -u \ + <(cat $cacheDir/debuginfo/02623eda209c26a59b1a8638ff7752f6b945c26b.debug | jq -S) \ + <(echo '{"archive":"../nar/100vxs724qr46phz8m24iswmg9p3785hsyagz0kchf6q6gf06sw6.nar","member":"lib/debug/.build-id/02/623eda209c26a59b1a8638ff7752f6b945c26b.debug"}' | jq -S) diff --git a/tests/build-hook-ca.nix b/tests/build-hook-ca.nix new file mode 100644 index 000000000..98db473fc --- /dev/null +++ b/tests/build-hook-ca.nix @@ -0,0 +1,45 @@ +{ busybox }: + +with import ./config.nix; + +let + + mkDerivation = args: + derivation ({ + inherit system; + builder = busybox; + args = ["sh" "-e" args.builder or (builtins.toFile "builder-${args.name}.sh" "if [ -e .attrs.sh ]; then source .attrs.sh; fi; eval \"$buildCommand\"")]; + outputHashMode = "recursive"; + outputHashAlgo = "sha256"; + } // removeAttrs args ["builder" "meta"]) + // { meta = args.meta or {}; }; + + input1 = mkDerivation { + shell = busybox; + name = "build-remote-input-1"; + buildCommand = "echo FOO > $out"; + requiredSystemFeatures = ["foo"]; + outputHash = "sha256-FePFYIlMuycIXPZbWi7LGEiMmZSX9FMbaQenWBzm1Sc="; + }; + + input2 = mkDerivation { + shell = busybox; + name = "build-remote-input-2"; + buildCommand = "echo BAR > $out"; + requiredSystemFeatures = ["bar"]; + outputHash = "sha256-XArauVH91AVwP9hBBQNlkX9ccuPpSYx9o0zeIHb6e+Q="; + }; + +in + + mkDerivation { + shell = busybox; + name = "build-remote"; + buildCommand = + '' + read x < ${input1} + read y < ${input2} + echo "$x $y" > $out + ''; + outputHash = "sha256-3YGhlOfbGUm9hiPn2teXXTT8M1NEpDFvfXkxMaJRld0="; + } diff --git a/tests/build-hook.nix b/tests/build-hook.nix index a19c10dde..eb16676f0 100644 --- a/tests/build-hook.nix +++ b/tests/build-hook.nix @@ -23,6 +23,17 @@ let shell = busybox; name = "build-remote-input-2"; buildCommand = "echo BAR > $out"; + requiredSystemFeatures = ["bar"]; + }; + + input3 = mkDerivation { + shell = busybox; + name = "build-remote-input-3"; + buildCommand = '' + read x < ${input2} + echo $x BAZ > $out + ''; + requiredSystemFeatures = ["baz"]; }; in @@ -33,7 +44,7 @@ in buildCommand = '' read x < ${input1} - read y < ${input2} - echo $x$y > $out + read y < ${input3} + echo "$x $y" > $out ''; } diff --git a/tests/build-remote-content-addressed-fixed.sh b/tests/build-remote-content-addressed-fixed.sh new file mode 100644 index 000000000..1408a19d5 --- /dev/null +++ b/tests/build-remote-content-addressed-fixed.sh @@ -0,0 +1,5 @@ +source common.sh + +file=build-hook-ca.nix + +source build-remote.sh diff --git a/tests/build-remote-input-addressed.sh b/tests/build-remote-input-addressed.sh new file mode 100644 index 000000000..b34caa061 --- /dev/null +++ b/tests/build-remote-input-addressed.sh @@ -0,0 +1,5 @@ +source common.sh + +file=build-hook.nix + +source build-remote.sh diff --git a/tests/build-remote.sh b/tests/build-remote.sh index 4dfb753e1..ca6d1de09 100644 --- a/tests/build-remote.sh +++ b/tests/build-remote.sh @@ -1,31 +1,47 @@ -source common.sh - -clearStore - if ! canUseSandbox; then exit; fi if ! [[ $busybox =~ busybox ]]; then exit; fi -chmod -R u+w $TEST_ROOT/machine0 || true -chmod -R u+w $TEST_ROOT/machine1 || true -chmod -R u+w $TEST_ROOT/machine2 || true -rm -rf $TEST_ROOT/machine0 $TEST_ROOT/machine1 $TEST_ROOT/machine2 -rm -f $TEST_ROOT/result - unset NIX_STORE_DIR unset NIX_STATE_DIR +function join_by { local d=$1; shift; echo -n "$1"; shift; printf "%s" "${@/#/$d}"; } + +builders=( + # system-features will automatically be added to the outer URL, but not inner + # remote-store URL. + "ssh://localhost?remote-store=$TEST_ROOT/machine1?system-features=foo - - 1 1 foo" + "$TEST_ROOT/machine2 - - 1 1 bar" + "ssh-ng://localhost?remote-store=$TEST_ROOT/machine3?system-features=baz - - 1 1 baz" +) + # Note: ssh://localhost bypasses ssh, directly invoking nix-store as a # child process. This allows us to test LegacySSHStore::buildDerivation(). -nix build -L -v -f build-hook.nix -o $TEST_ROOT/result --max-jobs 0 \ +# ssh-ng://... likewise allows us to test RemoteStore::buildDerivation(). +nix build -L -v -f $file -o $TEST_ROOT/result --max-jobs 0 \ --arg busybox $busybox \ --store $TEST_ROOT/machine0 \ - --builders "ssh://localhost?remote-store=$TEST_ROOT/machine1; $TEST_ROOT/machine2 - - 1 1 foo" \ - --system-features foo + --builders "$(join_by '; ' "${builders[@]}")" outPath=$(readlink -f $TEST_ROOT/result) -cat $TEST_ROOT/machine0/$outPath | grep FOOBAR +grep 'FOO BAR BAZ' $TEST_ROOT/machine0/$outPath -# Ensure that input1 was built on store2 due to the required feature. -(! nix path-info --store $TEST_ROOT/machine1 --all | grep builder-build-remote-input-1.sh) -nix path-info --store $TEST_ROOT/machine2 --all | grep builder-build-remote-input-1.sh +set -o pipefail + +# Ensure that input1 was built on store1 due to the required feature. +nix path-info --store $TEST_ROOT/machine1 --all \ + | grep builder-build-remote-input-1.sh \ + | grep -v builder-build-remote-input-2.sh \ + | grep -v builder-build-remote-input-3.sh + +# Ensure that input2 was built on store2 due to the required feature. +nix path-info --store $TEST_ROOT/machine2 --all \ + | grep -v builder-build-remote-input-1.sh \ + | grep builder-build-remote-input-2.sh \ + | grep -v builder-build-remote-input-3.sh + +# Ensure that input3 was built on store3 due to the required feature. +nix path-info --store $TEST_ROOT/machine3 --all \ + | grep -v builder-build-remote-input-1.sh \ + | grep -v builder-build-remote-input-2.sh \ + | grep builder-build-remote-input-3.sh diff --git a/tests/check.sh b/tests/check.sh index 5f25d04cb..5f4997e28 100644 --- a/tests/check.sh +++ b/tests/check.sh @@ -61,30 +61,30 @@ nix-build check.nix -A nondeterministic --no-out-link --repeat 1 2> $TEST_ROOT/l [ "$status" = "1" ] grep 'differs from previous round' $TEST_ROOT/log -path=$(nix-build check.nix -A fetchurl --no-out-link --hashed-mirrors '') +path=$(nix-build check.nix -A fetchurl --no-out-link) chmod +w $path echo foo > $path chmod -w $path -nix-build check.nix -A fetchurl --no-out-link --check --hashed-mirrors '' +nix-build check.nix -A fetchurl --no-out-link --check # Note: "check" doesn't repair anything, it just compares to the hash stored in the database. [[ $(cat $path) = foo ]] -nix-build check.nix -A fetchurl --no-out-link --repair --hashed-mirrors '' +nix-build check.nix -A fetchurl --no-out-link --repair [[ $(cat $path) != foo ]] -nix-build check.nix -A hashmismatch --no-out-link --hashed-mirrors '' || status=$? +nix-build check.nix -A hashmismatch --no-out-link || status=$? [ "$status" = "102" ] echo -n > ./dummy -nix-build check.nix -A hashmismatch --no-out-link --hashed-mirrors '' +nix-build check.nix -A hashmismatch --no-out-link echo 'Hello World' > ./dummy -nix-build check.nix -A hashmismatch --no-out-link --check --hashed-mirrors '' || status=$? +nix-build check.nix -A hashmismatch --no-out-link --check || status=$? [ "$status" = "102" ] # Multiple failures with --keep-going nix-build check.nix -A nondeterministic --no-out-link -nix-build check.nix -A nondeterministic -A hashmismatch --no-out-link --check --keep-going --hashed-mirrors '' || status=$? +nix-build check.nix -A nondeterministic -A hashmismatch --no-out-link --check --keep-going || status=$? [ "$status" = "110" ] diff --git a/tests/common.sh.in b/tests/common.sh.in index 308126094..5e00d64f1 100644 --- a/tests/common.sh.in +++ b/tests/common.sh.in @@ -32,7 +32,6 @@ export PATH=@bindir@:$PATH coreutils=@coreutils@ export dot=@dot@ -export xmllint="@xmllint@" export SHELL="@bash@" export PAGER=cat export HAVE_SODIUM="@HAVE_SODIUM@" diff --git a/tests/content-addressed.nix b/tests/content-addressed.nix new file mode 100644 index 000000000..3dcf916c3 --- /dev/null +++ b/tests/content-addressed.nix @@ -0,0 +1,54 @@ +with import ./config.nix; + +{ seed ? 0 }: +# A simple content-addressed derivation. +# The derivation can be arbitrarily modified by passing a different `seed`, +# but the output will always be the same +rec { + rootLegacy = mkDerivation { + name = "simple-input-addressed"; + buildCommand = '' + set -x + echo "Building a legacy derivation" + mkdir -p $out + echo "Hello World" > $out/hello + ''; + }; + rootCA = mkDerivation { + name = "dependent"; + outputs = [ "out" "dev" ]; + buildCommand = '' + echo "building a CA derivation" + echo "The seed is ${toString seed}" + mkdir -p $out + echo ${rootLegacy}/hello > $out/dep + # test symlink at root + ln -s $out $dev + ''; + __contentAddressed = true; + outputHashMode = "recursive"; + outputHashAlgo = "sha256"; + }; + dependentCA = mkDerivation { + name = "dependent"; + buildCommand = '' + echo "building a dependent derivation" + mkdir -p $out + echo ${rootCA}/hello > $out/dep + ''; + __contentAddressed = true; + outputHashMode = "recursive"; + outputHashAlgo = "sha256"; + }; + transitivelyDependentCA = mkDerivation { + name = "transitively-dependent"; + buildCommand = '' + echo "building transitively-dependent" + cat ${dependentCA}/dep + echo ${dependentCA} > $out + ''; + __contentAddressed = true; + outputHashMode = "recursive"; + outputHashAlgo = "sha256"; + }; +} diff --git a/tests/content-addressed.sh b/tests/content-addressed.sh new file mode 100644 index 000000000..61ec03fe3 --- /dev/null +++ b/tests/content-addressed.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash + +source common.sh + +drv=$(nix-instantiate --experimental-features ca-derivations ./content-addressed.nix -A rootCA --arg seed 1) +nix --experimental-features 'nix-command ca-derivations' show-derivation --derivation "$drv" --arg seed 1 + +testDerivation () { + local derivationPath=$1 + local commonArgs=("--experimental-features" "ca-derivations" "./content-addressed.nix" "-A" "$derivationPath" "--no-out-link") + local out1 out2 + out1=$(nix-build "${commonArgs[@]}" --arg seed 1) + out2=$(nix-build "${commonArgs[@]}" --arg seed 2 "${secondSeedArgs[@]}") + test "$out1" == "$out2" +} + +testDerivation rootCA +# The seed only changes the root derivation, and not it's output, so the +# dependent derivations should only need to be built once. +secondSeedArgs=(-j0) +# Don't directly build depenentCA, that way we'll make sure we dodn't rely on +# dependent derivations always being already built. +#testDerivation dependentCA +testDerivation transitivelyDependentCA + +nix-instantiate --experimental-features ca-derivations ./content-addressed.nix -A rootCA --arg seed 5 +nix-collect-garbage --experimental-features ca-derivations --option keep-derivations true diff --git a/tests/describe-stores.sh b/tests/describe-stores.sh new file mode 100644 index 000000000..3fea61483 --- /dev/null +++ b/tests/describe-stores.sh @@ -0,0 +1,8 @@ +source common.sh + +# Query an arbitrary value in `nix describe-stores --json`'s output just to +# check that it has the right structure +[[ $(nix --experimental-features 'nix-command flakes' describe-stores --json | jq '.["SSH Store"]["compress"]["defaultValue"]') == false ]] + +# Ensure that the output of `nix describe-stores` isn't empty +[[ -n $(nix --experimental-features 'nix-command flakes' describe-stores) ]] diff --git a/tests/fetchGit.sh b/tests/fetchGit.sh index d9c9874f5..cedd796f7 100644 --- a/tests/fetchGit.sh +++ b/tests/fetchGit.sh @@ -31,44 +31,46 @@ rev2=$(git -C $repo rev-parse HEAD) # Fetch a worktree unset _NIX_FORCE_HTTP -path0=$(nix eval --raw "(builtins.fetchGit file://$TEST_ROOT/worktree).outPath") +path0=$(nix eval --impure --raw --expr "(builtins.fetchGit file://$TEST_ROOT/worktree).outPath") +path0_=$(nix eval --impure --raw --expr "(builtins.fetchTree { type = \"git\"; url = file://$TEST_ROOT/worktree; }).outPath") +[[ $path0 = $path0_ ]] export _NIX_FORCE_HTTP=1 [[ $(tail -n 1 $path0/hello) = "hello" ]] # Fetch the default branch. -path=$(nix eval --raw "(builtins.fetchGit file://$repo).outPath") +path=$(nix eval --impure --raw --expr "(builtins.fetchGit file://$repo).outPath") [[ $(cat $path/hello) = world ]] # In pure eval mode, fetchGit without a revision should fail. -[[ $(nix eval --raw "(builtins.readFile (fetchGit file://$repo + \"/hello\"))") = world ]] -(! nix eval --pure-eval --raw "(builtins.readFile (fetchGit file://$repo + \"/hello\"))") +[[ $(nix eval --impure --raw --expr "builtins.readFile (fetchGit file://$repo + \"/hello\")") = world ]] +(! nix eval --raw --expr "builtins.readFile (fetchGit file://$repo + \"/hello\")") # Fetch using an explicit revision hash. -path2=$(nix eval --raw "(builtins.fetchGit { url = file://$repo; rev = \"$rev2\"; }).outPath") +path2=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$repo; rev = \"$rev2\"; }).outPath") [[ $path = $path2 ]] # In pure eval mode, fetchGit with a revision should succeed. -[[ $(nix eval --pure-eval --raw "(builtins.readFile (fetchGit { url = file://$repo; rev = \"$rev2\"; } + \"/hello\"))") = world ]] +[[ $(nix eval --raw --expr "builtins.readFile (fetchGit { url = file://$repo; rev = \"$rev2\"; } + \"/hello\")") = world ]] # Fetch again. This should be cached. mv $repo ${repo}-tmp -path2=$(nix eval --raw "(builtins.fetchGit file://$repo).outPath") +path2=$(nix eval --impure --raw --expr "(builtins.fetchGit file://$repo).outPath") [[ $path = $path2 ]] -[[ $(nix eval "(builtins.fetchGit file://$repo).revCount") = 2 ]] -[[ $(nix eval --raw "(builtins.fetchGit file://$repo).rev") = $rev2 ]] +[[ $(nix eval --impure --expr "(builtins.fetchGit file://$repo).revCount") = 2 ]] +[[ $(nix eval --impure --raw --expr "(builtins.fetchGit file://$repo).rev") = $rev2 ]] # Fetching with a explicit hash should succeed. -path2=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchGit { url = file://$repo; rev = \"$rev2\"; }).outPath") +path2=$(nix eval --refresh --raw --expr "(builtins.fetchGit { url = file://$repo; rev = \"$rev2\"; }).outPath") [[ $path = $path2 ]] -path2=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchGit { url = file://$repo; rev = \"$rev1\"; }).outPath") +path2=$(nix eval --refresh --raw --expr "(builtins.fetchGit { url = file://$repo; rev = \"$rev1\"; }).outPath") [[ $(cat $path2/hello) = utrecht ]] mv ${repo}-tmp $repo # Using a clean working tree should produce the same result. -path2=$(nix eval --raw "(builtins.fetchGit $repo).outPath") +path2=$(nix eval --impure --raw --expr "(builtins.fetchGit $repo).outPath") [[ $path = $path2 ]] # Using an unclean tree should yield the tracked but uncommitted changes. @@ -80,59 +82,65 @@ git -C $repo add dir1/foo git -C $repo rm hello unset _NIX_FORCE_HTTP -path2=$(nix eval --raw "(builtins.fetchGit $repo).outPath") +path2=$(nix eval --impure --raw --expr "(builtins.fetchGit $repo).outPath") [ ! -e $path2/hello ] [ ! -e $path2/bar ] [ ! -e $path2/dir2/bar ] [ ! -e $path2/.git ] [[ $(cat $path2/dir1/foo) = foo ]] -[[ $(nix eval --raw "(builtins.fetchGit $repo).rev") = 0000000000000000000000000000000000000000 ]] +[[ $(nix eval --impure --raw --expr "(builtins.fetchGit $repo).rev") = 0000000000000000000000000000000000000000 ]] # ... unless we're using an explicit ref or rev. -path3=$(nix eval --raw "(builtins.fetchGit { url = $repo; ref = \"master\"; }).outPath") +path3=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = $repo; ref = \"master\"; }).outPath") [[ $path = $path3 ]] -path3=$(nix eval --raw "(builtins.fetchGit { url = $repo; rev = \"$rev2\"; }).outPath") +path3=$(nix eval --raw --expr "(builtins.fetchGit { url = $repo; rev = \"$rev2\"; }).outPath") [[ $path = $path3 ]] # Committing should not affect the store path. git -C $repo commit -m 'Bla3' -a -path4=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchGit file://$repo).outPath") +path4=$(nix eval --impure --refresh --raw --expr "(builtins.fetchGit file://$repo).outPath") [[ $path2 = $path4 ]] +nix eval --impure --raw --expr "(builtins.fetchGit { url = $repo; rev = \"$rev2\"; narHash = \"sha256-B5yIPHhEm0eysJKEsO7nqxprh9vcblFxpJG11gXJus1=\"; }).outPath" || status=$? +[[ "$status" = "102" ]] + +path5=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = $repo; rev = \"$rev2\"; narHash = \"sha256-Hr8g6AqANb3xqX28eu1XnjK/3ab8Gv6TJSnkb1LezG9=\"; }).outPath") +[[ $path = $path5 ]] + # tarball-ttl should be ignored if we specify a rev echo delft > $repo/hello git -C $repo add hello git -C $repo commit -m 'Bla4' rev3=$(git -C $repo rev-parse HEAD) -nix eval --tarball-ttl 3600 "(builtins.fetchGit { url = $repo; rev = \"$rev3\"; })" >/dev/null +nix eval --tarball-ttl 3600 --expr "builtins.fetchGit { url = $repo; rev = \"$rev3\"; }" >/dev/null # Update 'path' to reflect latest master -path=$(nix eval --raw "(builtins.fetchGit file://$repo).outPath") +path=$(nix eval --impure --raw --expr "(builtins.fetchGit file://$repo).outPath") # Check behavior when non-master branch is used git -C $repo checkout $rev2 -b dev echo dev > $repo/hello # File URI uses dirty tree unless specified otherwise -path2=$(nix eval --raw "(builtins.fetchGit file://$repo).outPath") +path2=$(nix eval --impure --raw --expr "(builtins.fetchGit file://$repo).outPath") [ $(cat $path2/hello) = dev ] # Using local path with branch other than 'master' should work when clean or dirty -path3=$(nix eval --raw "(builtins.fetchGit $repo).outPath") +path3=$(nix eval --impure --raw --expr "(builtins.fetchGit $repo).outPath") # (check dirty-tree handling was used) -[[ $(nix eval --raw "(builtins.fetchGit $repo).rev") = 0000000000000000000000000000000000000000 ]] +[[ $(nix eval --impure --raw --expr "(builtins.fetchGit $repo).rev") = 0000000000000000000000000000000000000000 ]] # Committing shouldn't change store path, or switch to using 'master' git -C $repo commit -m 'Bla5' -a -path4=$(nix eval --raw "(builtins.fetchGit $repo).outPath") +path4=$(nix eval --impure --raw --expr "(builtins.fetchGit $repo).outPath") [[ $(cat $path4/hello) = dev ]] [[ $path3 = $path4 ]] # Confirm same as 'dev' branch -path5=$(nix eval --raw "(builtins.fetchGit { url = $repo; ref = \"dev\"; }).outPath") +path5=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = $repo; ref = \"dev\"; }).outPath") [[ $path3 = $path5 ]] @@ -141,19 +149,18 @@ rm -rf $TEST_HOME/.cache/nix # Try again, but without 'git' on PATH. This should fail. NIX=$(command -v nix) -# This should fail -(! PATH= $NIX eval --raw "(builtins.fetchGit { url = $repo; ref = \"dev\"; }).outPath" ) +(! PATH= $NIX eval --impure --raw --expr "(builtins.fetchGit { url = $repo; ref = \"dev\"; }).outPath" ) # Try again, with 'git' available. This should work. -path5=$(nix eval --raw "(builtins.fetchGit { url = $repo; ref = \"dev\"; }).outPath") +path5=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = $repo; ref = \"dev\"; }).outPath") [[ $path3 = $path5 ]] # Fetching a shallow repo shouldn't work by default, because we can't # return a revCount. git clone --depth 1 file://$repo $TEST_ROOT/shallow -(! nix eval --raw "(builtins.fetchGit { url = $TEST_ROOT/shallow; ref = \"dev\"; }).outPath") +(! nix eval --impure --raw --expr "(builtins.fetchGit { url = $TEST_ROOT/shallow; ref = \"dev\"; }).outPath") # But you can request a shallow clone, which won't return a revCount. -path6=$(nix eval --raw "(builtins.fetchTree { type = \"git\"; url = \"file://$TEST_ROOT/shallow\"; ref = \"dev\"; shallow = true; }).outPath") +path6=$(nix eval --impure --raw --expr "(builtins.fetchTree { type = \"git\"; url = \"file://$TEST_ROOT/shallow\"; ref = \"dev\"; shallow = true; }).outPath") [[ $path3 = $path6 ]] -[[ $(nix eval "(builtins.fetchTree { type = \"git\"; url = \"file://$TEST_ROOT/shallow\"; ref = \"dev\"; shallow = true; }).revCount or 123") == 123 ]] +[[ $(nix eval --impure --expr "(builtins.fetchTree { type = \"git\"; url = \"file://$TEST_ROOT/shallow\"; ref = \"dev\"; shallow = true; }).revCount or 123") == 123 ]] diff --git a/tests/fetchGitRefs.sh b/tests/fetchGitRefs.sh index 23934698e..52926040b 100644 --- a/tests/fetchGitRefs.sh +++ b/tests/fetchGitRefs.sh @@ -19,7 +19,7 @@ echo utrecht > "$repo"/hello git -C "$repo" add hello git -C "$repo" commit -m 'Bla1' -path=$(nix eval --raw "(builtins.fetchGit { url = $repo; ref = \"master\"; }).outPath") +path=$(nix eval --raw --impure --expr "(builtins.fetchGit { url = $repo; ref = \"master\"; }).outPath") # Test various combinations of ref names # (taken from the git project) @@ -42,7 +42,7 @@ valid_ref() { { set +x; printf >&2 '\n>>>>>>>>>> valid_ref %s\b <<<<<<<<<<\n' $(printf %s "$1" | sed -n -e l); set -x; } git check-ref-format --branch "$1" >/dev/null git -C "$repo" branch "$1" master >/dev/null - path1=$(nix eval --raw "(builtins.fetchGit { url = $repo; ref = ''$1''; }).outPath") + path1=$(nix eval --raw --impure --expr "(builtins.fetchGit { url = $repo; ref = ''$1''; }).outPath") [[ $path1 = $path ]] git -C "$repo" branch -D "$1" >/dev/null } @@ -56,7 +56,7 @@ invalid_ref() { else (! git check-ref-format --branch "$1" >/dev/null 2>&1) fi - nix --debug eval --raw "(builtins.fetchGit { url = $repo; ref = ''$1''; }).outPath" 2>&1 | grep 'invalid Git branch/tag name' >/dev/null + nix --debug eval --raw --impure --expr "(builtins.fetchGit { url = $repo; ref = ''$1''; }).outPath" 2>&1 | grep 'invalid Git branch/tag name' >/dev/null } diff --git a/tests/fetchGitSubmodules.sh b/tests/fetchGitSubmodules.sh index 4c2c13f1a..5f104355f 100644 --- a/tests/fetchGitSubmodules.sh +++ b/tests/fetchGitSubmodules.sh @@ -38,18 +38,18 @@ git -C $rootRepo commit -m "Add submodule" rev=$(git -C $rootRepo rev-parse HEAD) -r1=$(nix eval --raw "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; }).outPath") -r2=$(nix eval --raw "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; submodules = false; }).outPath") -r3=$(nix eval --raw "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; submodules = true; }).outPath") +r1=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; }).outPath") +r2=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; submodules = false; }).outPath") +r3=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; submodules = true; }).outPath") [[ $r1 == $r2 ]] [[ $r2 != $r3 ]] -r4=$(nix eval --raw "(builtins.fetchGit { url = file://$rootRepo; ref = \"master\"; rev = \"$rev\"; }).outPath") -r5=$(nix eval --raw "(builtins.fetchGit { url = file://$rootRepo; ref = \"master\"; rev = \"$rev\"; submodules = false; }).outPath") -r6=$(nix eval --raw "(builtins.fetchGit { url = file://$rootRepo; ref = \"master\"; rev = \"$rev\"; submodules = true; }).outPath") -r7=$(nix eval --raw "(builtins.fetchGit { url = $rootRepo; ref = \"master\"; rev = \"$rev\"; submodules = true; }).outPath") -r8=$(nix eval --raw "(builtins.fetchGit { url = $rootRepo; rev = \"$rev\"; submodules = true; }).outPath") +r4=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$rootRepo; ref = \"master\"; rev = \"$rev\"; }).outPath") +r5=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$rootRepo; ref = \"master\"; rev = \"$rev\"; submodules = false; }).outPath") +r6=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$rootRepo; ref = \"master\"; rev = \"$rev\"; submodules = true; }).outPath") +r7=$(nix eval --raw --expr "(builtins.fetchGit { url = $rootRepo; ref = \"master\"; rev = \"$rev\"; submodules = true; }).outPath") +r8=$(nix eval --raw --expr "(builtins.fetchGit { url = $rootRepo; rev = \"$rev\"; submodules = true; }).outPath") [[ $r1 == $r4 ]] [[ $r4 == $r5 ]] @@ -57,19 +57,19 @@ r8=$(nix eval --raw "(builtins.fetchGit { url = $rootRepo; rev = \"$rev\"; submo [[ $r6 == $r7 ]] [[ $r7 == $r8 ]] -have_submodules=$(nix eval "(builtins.fetchGit { url = $rootRepo; rev = \"$rev\"; }).submodules") +have_submodules=$(nix eval --expr "(builtins.fetchGit { url = $rootRepo; rev = \"$rev\"; }).submodules") [[ $have_submodules == false ]] -have_submodules=$(nix eval "(builtins.fetchGit { url = $rootRepo; rev = \"$rev\"; submodules = false; }).submodules") +have_submodules=$(nix eval --expr "(builtins.fetchGit { url = $rootRepo; rev = \"$rev\"; submodules = false; }).submodules") [[ $have_submodules == false ]] -have_submodules=$(nix eval "(builtins.fetchGit { url = $rootRepo; rev = \"$rev\"; submodules = true; }).submodules") +have_submodules=$(nix eval --expr "(builtins.fetchGit { url = $rootRepo; rev = \"$rev\"; submodules = true; }).submodules") [[ $have_submodules == true ]] -pathWithoutSubmodules=$(nix eval --raw "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; }).outPath") -pathWithSubmodules=$(nix eval --raw "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; submodules = true; }).outPath") -pathWithSubmodulesAgain=$(nix eval --raw "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; submodules = true; }).outPath") -pathWithSubmodulesAgainWithRef=$(nix eval --raw "(builtins.fetchGit { url = file://$rootRepo; ref = \"master\"; rev = \"$rev\"; submodules = true; }).outPath") +pathWithoutSubmodules=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; }).outPath") +pathWithSubmodules=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; submodules = true; }).outPath") +pathWithSubmodulesAgain=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$rootRepo; rev = \"$rev\"; submodules = true; }).outPath") +pathWithSubmodulesAgainWithRef=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$rootRepo; ref = \"master\"; rev = \"$rev\"; submodules = true; }).outPath") # The resulting store path cannot be the same. [[ $pathWithoutSubmodules != $pathWithSubmodules ]] @@ -91,7 +91,7 @@ test "$(find "$pathWithSubmodules" -name .git)" = "" # Git repos without submodules can be fetched with submodules = true. subRev=$(git -C $subRepo rev-parse HEAD) -noSubmoduleRepoBaseline=$(nix eval --raw "(builtins.fetchGit { url = file://$subRepo; rev = \"$subRev\"; }).outPath") -noSubmoduleRepo=$(nix eval --raw "(builtins.fetchGit { url = file://$subRepo; rev = \"$subRev\"; submodules = true; }).outPath") +noSubmoduleRepoBaseline=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$subRepo; rev = \"$subRev\"; }).outPath") +noSubmoduleRepo=$(nix eval --raw --expr "(builtins.fetchGit { url = file://$subRepo; rev = \"$subRev\"; submodules = true; }).outPath") [[ $noSubmoduleRepoBaseline == $noSubmoduleRepo ]] diff --git a/tests/fetchMercurial.sh b/tests/fetchMercurial.sh index 4088dbd39..af8ef8d5b 100644 --- a/tests/fetchMercurial.sh +++ b/tests/fetchMercurial.sh @@ -9,7 +9,7 @@ clearStore repo=$TEST_ROOT/hg -rm -rf $repo ${repo}-tmp $TEST_HOME/.cache/nix/hg +rm -rf $repo ${repo}-tmp $TEST_HOME/.cache/nix hg init $repo echo '[ui]' >> $repo/.hg/hgrc @@ -26,43 +26,43 @@ hg commit --cwd $repo -m 'Bla2' rev2=$(hg log --cwd $repo -r tip --template '{node}') # Fetch the default branch. -path=$(nix eval --raw "(builtins.fetchMercurial file://$repo).outPath") +path=$(nix eval --impure --raw --expr "(builtins.fetchMercurial file://$repo).outPath") [[ $(cat $path/hello) = world ]] # In pure eval mode, fetchGit without a revision should fail. -[[ $(nix eval --raw "(builtins.readFile (fetchMercurial file://$repo + \"/hello\"))") = world ]] -(! nix eval --pure-eval --raw "(builtins.readFile (fetchMercurial file://$repo + \"/hello\"))") +[[ $(nix eval --impure --raw --expr "(builtins.readFile (fetchMercurial file://$repo + \"/hello\"))") = world ]] +(! nix eval --raw --expr "builtins.readFile (fetchMercurial file://$repo + \"/hello\")") # Fetch using an explicit revision hash. -path2=$(nix eval --raw "(builtins.fetchMercurial { url = file://$repo; rev = \"$rev2\"; }).outPath") +path2=$(nix eval --impure --raw --expr "(builtins.fetchMercurial { url = file://$repo; rev = \"$rev2\"; }).outPath") [[ $path = $path2 ]] # In pure eval mode, fetchGit with a revision should succeed. -[[ $(nix eval --pure-eval --raw "(builtins.readFile (fetchMercurial { url = file://$repo; rev = \"$rev2\"; } + \"/hello\"))") = world ]] +[[ $(nix eval --raw --expr "builtins.readFile (fetchMercurial { url = file://$repo; rev = \"$rev2\"; } + \"/hello\")") = world ]] # Fetch again. This should be cached. mv $repo ${repo}-tmp -path2=$(nix eval --raw "(builtins.fetchMercurial file://$repo).outPath") +path2=$(nix eval --impure --raw --expr "(builtins.fetchMercurial file://$repo).outPath") [[ $path = $path2 ]] -[[ $(nix eval --raw "(builtins.fetchMercurial file://$repo).branch") = default ]] -[[ $(nix eval "(builtins.fetchMercurial file://$repo).revCount") = 1 ]] -[[ $(nix eval --raw "(builtins.fetchMercurial file://$repo).rev") = $rev2 ]] +[[ $(nix eval --impure --raw --expr "(builtins.fetchMercurial file://$repo).branch") = default ]] +[[ $(nix eval --impure --expr "(builtins.fetchMercurial file://$repo).revCount") = 1 ]] +[[ $(nix eval --impure --raw --expr "(builtins.fetchMercurial file://$repo).rev") = $rev2 ]] # But with TTL 0, it should fail. -(! nix eval --tarball-ttl 0 "(builtins.fetchMercurial file://$repo)") +(! nix eval --impure --refresh --expr "builtins.fetchMercurial file://$repo") # Fetching with a explicit hash should succeed. -path2=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchMercurial { url = file://$repo; rev = \"$rev2\"; }).outPath") +path2=$(nix eval --refresh --raw --expr "(builtins.fetchMercurial { url = file://$repo; rev = \"$rev2\"; }).outPath") [[ $path = $path2 ]] -path2=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchMercurial { url = file://$repo; rev = \"$rev1\"; }).outPath") +path2=$(nix eval --refresh --raw --expr "(builtins.fetchMercurial { url = file://$repo; rev = \"$rev1\"; }).outPath") [[ $(cat $path2/hello) = utrecht ]] mv ${repo}-tmp $repo # Using a clean working tree should produce the same result. -path2=$(nix eval --raw "(builtins.fetchMercurial $repo).outPath") +path2=$(nix eval --impure --raw --expr "(builtins.fetchMercurial $repo).outPath") [[ $path = $path2 ]] # Using an unclean tree should yield the tracked but uncommitted changes. @@ -73,21 +73,21 @@ echo bar > $repo/dir2/bar hg add --cwd $repo dir1/foo hg rm --cwd $repo hello -path2=$(nix eval --raw "(builtins.fetchMercurial $repo).outPath") +path2=$(nix eval --impure --raw --expr "(builtins.fetchMercurial $repo).outPath") [ ! -e $path2/hello ] [ ! -e $path2/bar ] [ ! -e $path2/dir2/bar ] [ ! -e $path2/.hg ] [[ $(cat $path2/dir1/foo) = foo ]] -[[ $(nix eval --raw "(builtins.fetchMercurial $repo).rev") = 0000000000000000000000000000000000000000 ]] +[[ $(nix eval --impure --raw --expr "(builtins.fetchMercurial $repo).rev") = 0000000000000000000000000000000000000000 ]] -# ... unless we're using an explicit rev. -path3=$(nix eval --raw "(builtins.fetchMercurial { url = $repo; rev = \"default\"; }).outPath") +# ... unless we're using an explicit ref. +path3=$(nix eval --impure --raw --expr "(builtins.fetchMercurial { url = $repo; rev = \"default\"; }).outPath") [[ $path = $path3 ]] # Committing should not affect the store path. hg commit --cwd $repo -m 'Bla3' -path4=$(nix eval --tarball-ttl 0 --raw "(builtins.fetchMercurial file://$repo).outPath") +path4=$(nix eval --impure --refresh --raw --expr "(builtins.fetchMercurial file://$repo).outPath") [[ $path2 = $path4 ]] diff --git a/tests/fetchurl.sh b/tests/fetchurl.sh index 2535651b0..0f2044342 100644 --- a/tests/fetchurl.sh +++ b/tests/fetchurl.sh @@ -5,7 +5,7 @@ clearStore # Test fetching a flat file. hash=$(nix-hash --flat --type sha256 ./fetchurl.sh) -outPath=$(nix-build '' --argstr url file://$(pwd)/fetchurl.sh --argstr sha256 $hash --no-out-link --hashed-mirrors '') +outPath=$(nix-build '' --argstr url file://$(pwd)/fetchurl.sh --argstr sha256 $hash --no-out-link) cmp $outPath fetchurl.sh @@ -14,7 +14,7 @@ clearStore hash=$(nix hash-file --type sha512 --base64 ./fetchurl.sh) -outPath=$(nix-build '' --argstr url file://$(pwd)/fetchurl.sh --argstr sha512 $hash --no-out-link --hashed-mirrors '') +outPath=$(nix-build '' --argstr url file://$(pwd)/fetchurl.sh --argstr sha512 $hash --no-out-link) cmp $outPath fetchurl.sh @@ -25,26 +25,24 @@ hash=$(nix hash-file ./fetchurl.sh) [[ $hash =~ ^sha256- ]] -outPath=$(nix-build '' --argstr url file://$(pwd)/fetchurl.sh --argstr hash $hash --no-out-link --hashed-mirrors '') +outPath=$(nix-build '' --argstr url file://$(pwd)/fetchurl.sh --argstr hash $hash --no-out-link) cmp $outPath fetchurl.sh -# Test the hashed mirror feature. +# Test that we can substitute from a different store dir. clearStore -hash=$(nix hash-file --type sha512 --base64 ./fetchurl.sh) -hash32=$(nix hash-file --type sha512 --base16 ./fetchurl.sh) +other_store=file://$TEST_ROOT/other_store?store=/fnord/store -mirror=$TEST_ROOT/hashed-mirror -rm -rf $mirror -mkdir -p $mirror/sha512 -ln -s $(pwd)/fetchurl.sh $mirror/sha512/$hash32 +hash=$(nix hash-file --type sha256 --base16 ./fetchurl.sh) -outPath=$(nix-build '' --argstr url file:///no-such-dir/fetchurl.sh --argstr sha512 $hash --no-out-link --hashed-mirrors "file://$mirror") +storePath=$(nix --store $other_store add-to-store --flat ./fetchurl.sh) + +outPath=$(nix-build '' --argstr url file:///no-such-dir/fetchurl.sh --argstr sha256 $hash --no-out-link --substituters $other_store) # Test hashed mirrors with an SRI hash. -nix-build '' --argstr url file:///no-such-dir/fetchurl.sh --argstr hash $(nix to-sri --type sha512 $hash) \ - --argstr name bla --no-out-link --hashed-mirrors "file://$mirror" +nix-build '' --argstr url file:///no-such-dir/fetchurl.sh --argstr hash $(nix to-sri --type sha256 $hash) \ + --no-out-link --substituters $other_store # Test unpacking a NAR. rm -rf $TEST_ROOT/archive diff --git a/tests/filter-source.sh b/tests/filter-source.sh index 1f8dceee5..ba34d2eac 100644 --- a/tests/filter-source.sh +++ b/tests/filter-source.sh @@ -10,10 +10,16 @@ touch $TEST_ROOT/filterin/bak touch $TEST_ROOT/filterin/bla.c.bak ln -s xyzzy $TEST_ROOT/filterin/link -nix-build ./filter-source.nix -o $TEST_ROOT/filterout +checkFilter() { + test ! -e $1/foo/bar + test -e $1/xyzzy + test -e $1/bak + test ! -e $1/bla.c.bak + test ! -L $1/link +} -test ! -e $TEST_ROOT/filterout/foo/bar -test -e $TEST_ROOT/filterout/xyzzy -test -e $TEST_ROOT/filterout/bak -test ! -e $TEST_ROOT/filterout/bla.c.bak -test ! -L $TEST_ROOT/filterout/link +nix-build ./filter-source.nix -o $TEST_ROOT/filterout1 +checkFilter $TEST_ROOT/filterout1 + +nix-build ./path.nix -o $TEST_ROOT/filterout2 +checkFilter $TEST_ROOT/filterout2 diff --git a/tests/flakes.sh b/tests/flakes.sh new file mode 100644 index 000000000..5aec563ac --- /dev/null +++ b/tests/flakes.sh @@ -0,0 +1,718 @@ +source common.sh + +if [[ -z $(type -p git) ]]; then + echo "Git not installed; skipping flake tests" + exit 99 +fi + +if [[ -z $(type -p hg) ]]; then + echo "Mercurial not installed; skipping flake tests" + exit 99 +fi + +clearStore +rm -rf $TEST_HOME/.cache $TEST_HOME/.config + +registry=$TEST_ROOT/registry.json + +flake1Dir=$TEST_ROOT/flake1 +flake2Dir=$TEST_ROOT/flake2 +flake3Dir=$TEST_ROOT/flake3 +flake5Dir=$TEST_ROOT/flake5 +flake6Dir=$TEST_ROOT/flake6 +flake7Dir=$TEST_ROOT/flake7 +templatesDir=$TEST_ROOT/templates +nonFlakeDir=$TEST_ROOT/nonFlake +flakeA=$TEST_ROOT/flakeA +flakeB=$TEST_ROOT/flakeB + +for repo in $flake1Dir $flake2Dir $flake3Dir $flake7Dir $templatesDir $nonFlakeDir $flakeA $flakeB; do + rm -rf $repo $repo.tmp + mkdir $repo + git -C $repo init + git -C $repo config user.email "foobar@example.com" + git -C $repo config user.name "Foobar" +done + +cat > $flake1Dir/flake.nix < $flake2Dir/flake.nix < $flake3Dir/flake.nix < $nonFlakeDir/README.md < $registry <> $flake1Dir/flake.nix +git -C $flake1Dir commit -a -m 'Foo' +hash2=$(nix flake info flake1 --json --refresh | jq -r .revision) +[[ $hash1 != $hash2 ]] + +# Test 'nix build' on a flake. +nix build -o $TEST_ROOT/result flake1#foo +[[ -e $TEST_ROOT/result/hello ]] + +# Test defaultPackage. +nix build -o $TEST_ROOT/result flake1 +[[ -e $TEST_ROOT/result/hello ]] + +nix build -o $TEST_ROOT/result $flake1Dir +nix build -o $TEST_ROOT/result git+file://$flake1Dir + +# Check that store symlinks inside a flake are not interpreted as flakes. +nix build -o $flake1Dir/result git+file://$flake1Dir +nix path-info $flake1Dir/result + +# 'getFlake' on a mutable flakeref should fail in pure mode, but succeed in impure mode. +(! nix build -o $TEST_ROOT/result --expr "(builtins.getFlake \"$flake1Dir\").defaultPackage.$system") +nix build -o $TEST_ROOT/result --expr "(builtins.getFlake \"$flake1Dir\").defaultPackage.$system" --impure + +# 'getFlake' on an immutable flakeref should succeed even in pure mode. +nix build -o $TEST_ROOT/result --expr "(builtins.getFlake \"git+file://$flake1Dir?rev=$hash2\").defaultPackage.$system" + +# Building a flake with an unlocked dependency should fail in pure mode. +(! nix build -o $TEST_ROOT/result flake2#bar --no-registries) +(! nix eval --expr "builtins.getFlake \"$flake2Dir\"") + +# But should succeed in impure mode. +(! nix build -o $TEST_ROOT/result flake2#bar --impure) +nix build -o $TEST_ROOT/result flake2#bar --impure --no-write-lock-file + +# Building a local flake with an unlocked dependency should fail with --no-update-lock-file. +nix build -o $TEST_ROOT/result $flake2Dir#bar --no-update-lock-file 2>&1 | grep 'requires lock file changes' + +# But it should succeed without that flag. +nix build -o $TEST_ROOT/result $flake2Dir#bar --no-write-lock-file +nix build -o $TEST_ROOT/result $flake2Dir#bar --no-update-lock-file 2>&1 | grep 'requires lock file changes' +nix build -o $TEST_ROOT/result $flake2Dir#bar --commit-lock-file +[[ -e $flake2Dir/flake.lock ]] +[[ -z $(git -C $flake2Dir diff master) ]] + +# Rerunning the build should not change the lockfile. +nix build -o $TEST_ROOT/result $flake2Dir#bar +[[ -z $(git -C $flake2Dir diff master) ]] + +# Building with a lockfile should not require a fetch of the registry. +nix build -o $TEST_ROOT/result --flake-registry file:///no-registry.json $flake2Dir#bar --refresh +nix build -o $TEST_ROOT/result --no-registries $flake2Dir#bar --refresh + +# Updating the flake should not change the lockfile. +nix flake update $flake2Dir +[[ -z $(git -C $flake2Dir diff master) ]] + +# Now we should be able to build the flake in pure mode. +nix build -o $TEST_ROOT/result flake2#bar + +# Or without a registry. +nix build -o $TEST_ROOT/result --no-registries git+file://$flake2Dir#bar --refresh + +# Test whether indirect dependencies work. +nix build -o $TEST_ROOT/result $flake3Dir#xyzzy +git -C $flake3Dir add flake.lock + +# Add dependency to flake3. +rm $flake3Dir/flake.nix + +cat > $flake3Dir/flake.nix < $flake3Dir/flake.nix < \$out + ''; + }; + }; +} +EOF + +cp ./config.nix $flake3Dir + +git -C $flake3Dir add flake.nix config.nix +git -C $flake3Dir commit -m 'Add nonFlakeInputs' + +# Check whether `nix build` works with a lockfile which is missing a +# nonFlakeInputs. +nix build -o $TEST_ROOT/result $flake3Dir#sth --commit-lock-file + +nix build -o $TEST_ROOT/result flake3#fnord +[[ $(cat $TEST_ROOT/result) = FNORD ]] + +# Check whether flake input fetching is lazy: flake3#sth does not +# depend on flake2, so this shouldn't fail. +rm -rf $TEST_HOME/.cache +clearStore +mv $flake2Dir $flake2Dir.tmp +mv $nonFlakeDir $nonFlakeDir.tmp +nix build -o $TEST_ROOT/result flake3#sth +(! nix build -o $TEST_ROOT/result flake3#xyzzy) +(! nix build -o $TEST_ROOT/result flake3#fnord) +mv $flake2Dir.tmp $flake2Dir +mv $nonFlakeDir.tmp $nonFlakeDir +nix build -o $TEST_ROOT/result flake3#xyzzy flake3#fnord + +# Test doing multiple `lookupFlake`s +nix build -o $TEST_ROOT/result flake4#xyzzy + +# Test 'nix flake update' and --override-flake. +nix flake update $flake3Dir +[[ -z $(git -C $flake3Dir diff master) ]] + +nix flake update $flake3Dir --recreate-lock-file --override-flake flake2 nixpkgs +[[ ! -z $(git -C $flake3Dir diff master) ]] + +# Make branch "removeXyzzy" where flake3 doesn't have xyzzy anymore +git -C $flake3Dir checkout -b removeXyzzy +rm $flake3Dir/flake.nix + +cat > $flake3Dir/flake.nix < \$out + ''; + }; + }; +} +EOF +nix flake update $flake3Dir +git -C $flake3Dir add flake.nix flake.lock +git -C $flake3Dir commit -m 'Remove packages.xyzzy' +git -C $flake3Dir checkout master + +# Test whether fuzzy-matching works for registry entries. +(! nix build -o $TEST_ROOT/result flake4/removeXyzzy#xyzzy) +nix build -o $TEST_ROOT/result flake4/removeXyzzy#sth + +# Testing the nix CLI +nix registry add flake1 flake3 +[[ $(nix registry list | wc -l) == 8 ]] +nix registry pin flake1 +[[ $(nix registry list | wc -l) == 8 ]] +nix registry remove flake1 +[[ $(nix registry list | wc -l) == 7 ]] + +# Test 'nix flake init'. +cat > $templatesDir/flake.nix < $templatesDir/trivial/flake.nix < $flake3Dir/flake.nix < $flake3Dir/flake.nix < $flake3Dir/flake.nix < $flake3Dir/flake.nix < $flake3Dir/flake.nix < $flake3Dir/flake.nix < $flake3Dir/flake.nix < $flake3Dir/flake.nix < $flake3Dir/flake.nix < $flake3Dir/flake.nix < $flake3Dir/flake.nix < $flake5Dir/flake.nix <&1 | grep 'NAR hash mismatch' + +# Test --override-input. +git -C $flake3Dir reset --hard +nix flake update $flake3Dir --override-input flake2/flake1 flake5 -vvvvv +[[ $(jq .nodes.flake1_2.locked.url $flake3Dir/flake.lock) =~ flake5 ]] + +nix flake update $flake3Dir --override-input flake2/flake1 flake1 +[[ $(jq -r .nodes.flake1_2.locked.rev $flake3Dir/flake.lock) =~ $hash2 ]] + +nix flake update $flake3Dir --override-input flake2/flake1 flake1/master/$hash1 +[[ $(jq -r .nodes.flake1_2.locked.rev $flake3Dir/flake.lock) =~ $hash1 ]] + +# Test --update-input. +nix flake update $flake3Dir +[[ $(jq -r .nodes.flake1_2.locked.rev $flake3Dir/flake.lock) = $hash1 ]] + +nix flake update $flake3Dir --update-input flake2/flake1 +[[ $(jq -r .nodes.flake1_2.locked.rev $flake3Dir/flake.lock) =~ $hash2 ]] + +# Test 'nix flake list-inputs'. +[[ $(nix flake list-inputs $flake3Dir | wc -l) == 5 ]] +nix flake list-inputs $flake3Dir --json | jq . + +# Test circular flake dependencies. +cat > $flakeA/flake.nix < $flakeB/flake.nix < $out/commits/HEAD + ''; + +in + +makeTest ( + +{ + + nodes = + { # Impersonate github.com and api.github.com. + github = + { config, pkgs, ... }: + { networking.firewall.allowedTCPPorts = [ 80 443 ]; + + services.httpd.enable = true; + services.httpd.adminAddr = "foo@example.org"; + services.httpd.extraConfig = '' + ErrorLog syslog:local6 + ''; + services.httpd.virtualHosts."github.com" = + { forceSSL = true; + sslServerKey = "${cert}/server.key"; + sslServerCert = "${cert}/server.crt"; + servedDirs = + [ { urlPath = "/NixOS/flake-registry/raw/master"; + dir = registry; + } + ]; + }; + services.httpd.virtualHosts."api.github.com" = + { forceSSL = true; + sslServerKey = "${cert}/server.key"; + sslServerCert = "${cert}/server.crt"; + servedDirs = + [ { urlPath = "/repos/NixOS/nixpkgs"; + dir = api; + } + ]; + }; + }; + + client = + { config, lib, pkgs, nodes, ... }: + { virtualisation.writableStore = true; + virtualisation.diskSize = 2048; + virtualisation.pathsInNixDB = [ pkgs.hello pkgs.fuse ]; + virtualisation.memorySize = 4096; + nix.binaryCaches = lib.mkForce [ ]; + nix.extraOptions = "experimental-features = nix-command flakes"; + environment.systemPackages = [ pkgs.jq ]; + networking.hosts.${(builtins.head nodes.github.config.networking.interfaces.eth1.ipv4.addresses).address} = + [ "github.com" "api.github.com" "raw.githubusercontent.com" ]; + security.pki.certificateFiles = [ "${cert}/ca.crt" ]; + }; + }; + + testScript = { nodes }: + '' + use POSIX qw(strftime); + + startAll; + + $github->waitForUnit("httpd.service"); + + $client->succeed("curl -v https://github.com/ >&2"); + + $client->succeed("nix registry list | grep nixpkgs"); + + $client->succeed("nix flake info nixpkgs --json | jq -r .revision") eq "${nixpkgs.rev}\n" + or die "revision mismatch"; + + $client->succeed("nix registry pin nixpkgs"); + + $client->succeed("nix flake info nixpkgs --tarball-ttl 0 >&2"); + + # Shut down the web server. The flake should be cached on the client. + $github->succeed("systemctl stop httpd.service"); + + my $date = $client->succeed("nix flake info nixpkgs --json | jq -M .lastModified"); + strftime("%Y%m%d%H%M%S", gmtime($date)) eq "${nixpkgs.lastModifiedDate}" or die "time mismatch"; + + $client->succeed("nix build nixpkgs#hello"); + + # The build shouldn't fail even with --tarball-ttl 0 (the server + # being down should not be a fatal error). + $client->succeed("nix build nixpkgs#fuse --tarball-ttl 0"); + ''; + +}) diff --git a/tests/init.sh b/tests/init.sh index 0c2c0e170..f9ced6b0d 100644 --- a/tests/init.sh +++ b/tests/init.sh @@ -19,6 +19,7 @@ keep-derivations = false sandbox = false experimental-features = nix-command flakes gc-reserved-space = 0 +flake-registry = $TEST_ROOT/registry.json include nix.conf.extra EOF diff --git a/tests/install-darwin.sh b/tests/install-darwin.sh index 9933eba94..7e44e54c4 100755 --- a/tests/install-darwin.sh +++ b/tests/install-darwin.sh @@ -53,7 +53,7 @@ trap finish EXIT # First setup Nix cleanup -curl -o install https://nixos.org/nix/install +curl -L -o install https://nixos.org/nix/install yes | bash ./install verify diff --git a/tests/lang.sh b/tests/lang.sh index c797a2a74..61bb444ba 100644 --- a/tests/lang.sh +++ b/tests/lang.sh @@ -1,6 +1,7 @@ source common.sh export TEST_VAR=foo # for eval-okay-getenv.nix +export NIX_REMOTE=dummy:// nix-instantiate --eval -E 'builtins.trace "Hello" 123' 2>&1 | grep -q Hello (! nix-instantiate --show-trace --eval -E 'builtins.addErrorContext "Hello" 123' 2>&1 | grep -q Hello) diff --git a/tests/lang/eval-okay-ind-string.exp b/tests/lang/eval-okay-ind-string.exp index 9cf4bd2ee..7862331fa 100644 --- a/tests/lang/eval-okay-ind-string.exp +++ b/tests/lang/eval-okay-ind-string.exp @@ -1 +1 @@ -"This is an indented multi-line string\nliteral. An amount of whitespace at\nthe start of each line matching the minimum\nindentation of all lines in the string\nliteral together will be removed. Thus,\nin this case four spaces will be\nstripped from each line, even though\n THIS LINE is indented six spaces.\n\nAlso, empty lines don't count in the\ndetermination of the indentation level (the\nprevious empty line has indentation 0, but\nit doesn't matter).\nIf the string starts with whitespace\n followed by a newline, it's stripped, but\n that's not the case here. Two spaces are\n stripped because of the \" \" at the start. \nThis line is indented\na bit further.\nAnti-quotations, like so, are\nalso allowed.\n The \\ is not special here.\n' can be followed by any character except another ', e.g. 'x'.\nLikewise for $, e.g. $$ or $varName.\nBut ' followed by ' is special, as is $ followed by {.\nIf you want them, use anti-quotations: '', ${.\n Tabs are not interpreted as whitespace (since we can't guess\n what tab settings are intended), so don't use them.\n\tThis line starts with a space and a tab, so only one\n space will be stripped from each line.\nAlso note that if the last line (just before the closing ' ')\nconsists only of whitespace, it's ignored. But here there is\nsome non-whitespace stuff, so the line isn't removed. \nThis shows a hacky way to preserve an empty line after the start.\nBut there's no reason to do so: you could just repeat the empty\nline.\n Similarly you can force an indentation level,\n in this case to 2 spaces. This works because the anti-quote\n is significant (not whitespace).\nstart on network-interfaces\n\nstart script\n\n rm -f /var/run/opengl-driver\n ln -sf 123 /var/run/opengl-driver\n\n rm -f /var/log/slim.log\n \nend script\n\nenv SLIM_CFGFILE=abc\nenv SLIM_THEMESDIR=def\nenv FONTCONFIG_FILE=/etc/fonts/fonts.conf \t\t\t\t# !!! cleanup\nenv XKB_BINDIR=foo/bin \t\t\t\t# Needed for the Xkb extension.\nenv LD_LIBRARY_PATH=libX11/lib:libXext/lib:/usr/lib/ # related to xorg-sys-opengl - needed to load libglx for (AI)GLX support (for compiz)\n\nenv XORG_DRI_DRIVER_PATH=nvidiaDrivers/X11R6/lib/modules/drivers/ \n\nexec slim/bin/slim\nEscaping of ' followed by ': ''\nEscaping of $ followed by {: ${\nAnd finally to interpret \\n etc. as in a string: \n, \r, \t.\nfoo\n'bla'\nbar\ncut -d $'\\t' -f 1\nending dollar $$\n" +"This is an indented multi-line string\nliteral. An amount of whitespace at\nthe start of each line matching the minimum\nindentation of all lines in the string\nliteral together will be removed. Thus,\nin this case four spaces will be\nstripped from each line, even though\n THIS LINE is indented six spaces.\n\nAlso, empty lines don't count in the\ndetermination of the indentation level (the\nprevious empty line has indentation 0, but\nit doesn't matter).\nIf the string starts with whitespace\n followed by a newline, it's stripped, but\n that's not the case here. Two spaces are\n stripped because of the \" \" at the start. \nThis line is indented\na bit further.\nAnti-quotations, like so, are\nalso allowed.\n The \\ is not special here.\n' can be followed by any character except another ', e.g. 'x'.\nLikewise for $, e.g. $$ or $varName.\nBut ' followed by ' is special, as is $ followed by {.\nIf you want them, use anti-quotations: '', \${.\n Tabs are not interpreted as whitespace (since we can't guess\n what tab settings are intended), so don't use them.\n\tThis line starts with a space and a tab, so only one\n space will be stripped from each line.\nAlso note that if the last line (just before the closing ' ')\nconsists only of whitespace, it's ignored. But here there is\nsome non-whitespace stuff, so the line isn't removed. \nThis shows a hacky way to preserve an empty line after the start.\nBut there's no reason to do so: you could just repeat the empty\nline.\n Similarly you can force an indentation level,\n in this case to 2 spaces. This works because the anti-quote\n is significant (not whitespace).\nstart on network-interfaces\n\nstart script\n\n rm -f /var/run/opengl-driver\n ln -sf 123 /var/run/opengl-driver\n\n rm -f /var/log/slim.log\n \nend script\n\nenv SLIM_CFGFILE=abc\nenv SLIM_THEMESDIR=def\nenv FONTCONFIG_FILE=/etc/fonts/fonts.conf \t\t\t\t# !!! cleanup\nenv XKB_BINDIR=foo/bin \t\t\t\t# Needed for the Xkb extension.\nenv LD_LIBRARY_PATH=libX11/lib:libXext/lib:/usr/lib/ # related to xorg-sys-opengl - needed to load libglx for (AI)GLX support (for compiz)\n\nenv XORG_DRI_DRIVER_PATH=nvidiaDrivers/X11R6/lib/modules/drivers/ \n\nexec slim/bin/slim\nEscaping of ' followed by ': ''\nEscaping of $ followed by {: \${\nAnd finally to interpret \\n etc. as in a string: \n, \r, \t.\nfoo\n'bla'\nbar\ncut -d $'\\t' -f 1\nending dollar $$\n" diff --git a/tests/local-store.sh b/tests/local-store.sh new file mode 100644 index 000000000..4ec3d64b0 --- /dev/null +++ b/tests/local-store.sh @@ -0,0 +1,20 @@ +source common.sh + +cd $TEST_ROOT + +echo example > example.txt +mkdir -p ./x + +NIX_STORE_DIR=$TEST_ROOT/x + +CORRECT_PATH=$(nix-store --store ./x --add example.txt) + +PATH1=$(nix path-info --store ./x $CORRECT_PATH) +[ $CORRECT_PATH == $PATH1 ] + +PATH2=$(nix path-info --store "$PWD/x" $CORRECT_PATH) +[ $CORRECT_PATH == $PATH2 ] + +# FIXME we could also test the query parameter version: +# PATH3=$(nix path-info --store "local?store=$PWD/x" $CORRECT_PATH) +# [ $CORRECT_PATH == $PATH3 ] diff --git a/tests/local.mk b/tests/local.mk index f3ac330d8..a1929f96d 100644 --- a/tests/local.mk +++ b/tests/local.mk @@ -1,12 +1,12 @@ nix_tests = \ - init.sh hash.sh lang.sh add.sh simple.sh dependencies.sh \ + hash.sh lang.sh add.sh simple.sh dependencies.sh \ config.sh \ gc.sh \ gc-concurrent.sh \ gc-auto.sh \ referrers.sh user-envs.sh logging.sh nix-build.sh misc.sh fixed.sh \ gc-runtime.sh check-refs.sh filter-source.sh \ - remote-store.sh export.sh export-graph.sh \ + local-store.sh remote-store.sh export.sh export-graph.sh \ timeout.sh secure-drv-outputs.sh nix-channel.sh \ multiple-outputs.sh import-derivation.sh fetchurl.sh optimise-store.sh \ binary-cache.sh nix-profile.sh repair.sh dump-db.sh case-hack.sh \ @@ -14,7 +14,8 @@ nix_tests = \ placeholders.sh nix-shell.sh \ linux-sandbox.sh \ build-dry.sh \ - build-remote.sh \ + build-remote-input-addressed.sh \ + ssh-relay.sh \ nar-access.sh \ structured-attrs.sh \ fetchGit.sh \ @@ -31,13 +32,17 @@ nix_tests = \ nix-copy-ssh.sh \ post-hook.sh \ function-trace.sh \ - recursive.sh + recursive.sh \ + describe-stores.sh \ + flakes.sh \ + content-addressed.sh # parallel.sh + # build-remote-content-addressed-fixed.sh \ install-tests += $(foreach x, $(nix_tests), tests/$(x)) tests-environment = NIX_REMOTE= $(bash) -e -clean-files += $(d)/common.sh +clean-files += $(d)/common.sh $(d)/config.nix test-deps += tests/common.sh tests/config.nix tests/plugins/libplugintest.$(SO_EXT) diff --git a/tests/multiple-outputs.nix b/tests/multiple-outputs.nix index 4a9010d18..b915493f7 100644 --- a/tests/multiple-outputs.nix +++ b/tests/multiple-outputs.nix @@ -2,6 +2,21 @@ with import ./config.nix; rec { + # Want to ensure that "out" doesn't get a suffix on it's path. + nameCheck = mkDerivation { + name = "multiple-outputs-a"; + outputs = [ "out" "dev" ]; + builder = builtins.toFile "builder.sh" + '' + mkdir $first $second + test -z $all + echo "first" > $first/file + echo "second" > $second/file + ln -s $first $second/link + ''; + helloString = "Hello, world!"; + }; + a = mkDerivation { name = "multiple-outputs-a"; outputs = [ "first" "second" ]; diff --git a/tests/multiple-outputs.sh b/tests/multiple-outputs.sh index bedbc39a4..7a6ec181d 100644 --- a/tests/multiple-outputs.sh +++ b/tests/multiple-outputs.sh @@ -4,6 +4,12 @@ clearStore rm -f $TEST_ROOT/result* +# Test whether the output names match our expectations +outPath=$(nix-instantiate multiple-outputs.nix --eval -A nameCheck.out.outPath) +[ "$(echo "$outPath" | sed -E 's_^".*/[^-/]*-([^/]*)"$_\1_')" = "multiple-outputs-a" ] +outPath=$(nix-instantiate multiple-outputs.nix --eval -A nameCheck.dev.outPath) +[ "$(echo "$outPath" | sed -E 's_^".*/[^-/]*-([^/]*)"$_\1_')" = "multiple-outputs-a-dev" ] + # Test whether read-only evaluation works when referring to the # ‘drvPath’ attribute. echo "evaluating c..." diff --git a/tests/nar-access.sh b/tests/nar-access.sh index 553d6ca89..88b997ca6 100644 --- a/tests/nar-access.sh +++ b/tests/nar-access.sh @@ -26,12 +26,24 @@ nix cat-store $storePath/foo/baz > baz.cat-nar diff -u baz.cat-nar $storePath/foo/baz # Test --json. -[[ $(nix ls-nar --json $narFile /) = '{"type":"directory","entries":{"foo":{},"foo-x":{},"qux":{},"zyx":{}}}' ]] -[[ $(nix ls-nar --json -R $narFile /foo) = '{"type":"directory","entries":{"bar":{"type":"regular","size":0,"narOffset":368},"baz":{"type":"regular","size":0,"narOffset":552},"data":{"type":"regular","size":58,"narOffset":736}}}' ]] -[[ $(nix ls-nar --json -R $narFile /foo/bar) = '{"type":"regular","size":0,"narOffset":368}' ]] -[[ $(nix ls-store --json $storePath) = '{"type":"directory","entries":{"foo":{},"foo-x":{},"qux":{},"zyx":{}}}' ]] -[[ $(nix ls-store --json -R $storePath/foo) = '{"type":"directory","entries":{"bar":{"type":"regular","size":0},"baz":{"type":"regular","size":0},"data":{"type":"regular","size":58}}}' ]] -[[ $(nix ls-store --json -R $storePath/foo/bar) = '{"type":"regular","size":0}' ]] +diff -u \ + <(nix ls-nar --json $narFile / | jq -S) \ + <(echo '{"type":"directory","entries":{"foo":{},"foo-x":{},"qux":{},"zyx":{}}}' | jq -S) +diff -u \ + <(nix ls-nar --json -R $narFile /foo | jq -S) \ + <(echo '{"type":"directory","entries":{"bar":{"type":"regular","size":0,"narOffset":368},"baz":{"type":"regular","size":0,"narOffset":552},"data":{"type":"regular","size":58,"narOffset":736}}}' | jq -S) +diff -u \ + <(nix ls-nar --json -R $narFile /foo/bar | jq -S) \ + <(echo '{"type":"regular","size":0,"narOffset":368}' | jq -S) +diff -u \ + <(nix ls-store --json $storePath | jq -S) \ + <(echo '{"type":"directory","entries":{"foo":{},"foo-x":{},"qux":{},"zyx":{}}}' | jq -S) +diff -u \ + <(nix ls-store --json -R $storePath/foo | jq -S) \ + <(echo '{"type":"directory","entries":{"bar":{"type":"regular","size":0},"baz":{"type":"regular","size":0},"data":{"type":"regular","size":58}}}' | jq -S) +diff -u \ + <(nix ls-store --json -R $storePath/foo/bar| jq -S) \ + <(echo '{"type":"regular","size":0}' | jq -S) # Test missing files. nix ls-store --json -R $storePath/xyzzy 2>&1 | grep 'does not exist in NAR' diff --git a/tests/nix-build.sh b/tests/nix-build.sh index 0eb599608..3123c6da3 100644 --- a/tests/nix-build.sh +++ b/tests/nix-build.sh @@ -24,5 +24,5 @@ outPath2=$(nix-build $(nix-instantiate dependencies.nix) --no-out-link) outPath2=$(nix-build $(nix-instantiate dependencies.nix)!out --no-out-link) [[ $outPath = $outPath2 ]] -outPath2=$(nix-store -r $(nix-instantiate --indirect --add-root $TEST_ROOT/indirect dependencies.nix)!out) +outPath2=$(nix-store -r $(nix-instantiate --add-root $TEST_ROOT/indirect dependencies.nix)!out) [[ $outPath = $outPath2 ]] diff --git a/tests/nix-channel.sh b/tests/nix-channel.sh index 49c68981a..63c0f97ba 100644 --- a/tests/nix-channel.sh +++ b/tests/nix-channel.sh @@ -28,9 +28,6 @@ nix-channel --update # Do a query. nix-env -qa \* --meta --xml --out-path > $TEST_ROOT/meta.xml -if [ "$xmllint" != false ]; then - $xmllint --noout $TEST_ROOT/meta.xml || fail "malformed XML" -fi grep -q 'meta.*description.*Random test package' $TEST_ROOT/meta.xml grep -q 'item.*attrPath="foo".*name="dependencies-top"' $TEST_ROOT/meta.xml @@ -47,9 +44,6 @@ nix-channel --update # Do a query. nix-env -qa \* --meta --xml --out-path > $TEST_ROOT/meta.xml -if [ "$xmllint" != false ]; then - $xmllint --noout $TEST_ROOT/meta.xml || fail "malformed XML" -fi grep -q 'meta.*description.*Random test package' $TEST_ROOT/meta.xml grep -q 'item.*attrPath="foo".*name="dependencies-top"' $TEST_ROOT/meta.xml diff --git a/tests/nix-copy-closure.nix b/tests/nix-copy-closure.nix index bb5db7410..9c9d119b7 100644 --- a/tests/nix-copy-closure.nix +++ b/tests/nix-copy-closure.nix @@ -1,8 +1,11 @@ # Test ‘nix-copy-closure’. -{ nixpkgs, system, nix }: +{ nixpkgs, system, overlay }: -with import (nixpkgs + "/nixos/lib/testing.nix") { inherit system; }; +with import (nixpkgs + "/nixos/lib/testing.nix") { + inherit system; + extraConfigurations = [ { nixpkgs.overlays = [ overlay ]; } ]; +}; makeTest (let pkgA = pkgs.cowsay; pkgB = pkgs.wget; pkgC = pkgs.hello; in { @@ -11,7 +14,6 @@ makeTest (let pkgA = pkgs.cowsay; pkgB = pkgs.wget; pkgC = pkgs.hello; in { { config, lib, pkgs, ... }: { virtualisation.writableStore = true; virtualisation.pathsInNixDB = [ pkgA ]; - nix.package = nix; nix.binaryCaches = lib.mkForce [ ]; }; @@ -20,7 +22,6 @@ makeTest (let pkgA = pkgs.cowsay; pkgB = pkgs.wget; pkgC = pkgs.hello; in { { services.openssh.enable = true; virtualisation.writableStore = true; virtualisation.pathsInNixDB = [ pkgB pkgC ]; - nix.package = nix; }; }; diff --git a/tests/nix-shell.sh b/tests/nix-shell.sh index 650904057..1228bb04f 100644 --- a/tests/nix-shell.sh +++ b/tests/nix-shell.sh @@ -27,12 +27,12 @@ output=$(nix-shell --pure --keep SELECTED_IMPURE_VAR shell.nix -A shellDrv --run # Test nix-shell on a .drv symlink # Legacy: absolute path and .drv extension required -nix-instantiate shell.nix -A shellDrv --indirect --add-root $TEST_ROOT/shell.drv +nix-instantiate shell.nix -A shellDrv --add-root $TEST_ROOT/shell.drv [[ $(nix-shell --pure $TEST_ROOT/shell.drv --run \ 'echo "$IMPURE_VAR - $VAR_FROM_STDENV_SETUP - $VAR_FROM_NIX"') = " - foo - bar" ]] # New behaviour: just needs to resolve to a derivation in the store -nix-instantiate shell.nix -A shellDrv --indirect --add-root $TEST_ROOT/shell +nix-instantiate shell.nix -A shellDrv --add-root $TEST_ROOT/shell [[ $(nix-shell --pure $TEST_ROOT/shell --run \ 'echo "$IMPURE_VAR - $VAR_FROM_STDENV_SETUP - $VAR_FROM_NIX"') = " - foo - bar" ]] diff --git a/tests/path.nix b/tests/path.nix new file mode 100644 index 000000000..883c3c41b --- /dev/null +++ b/tests/path.nix @@ -0,0 +1,14 @@ +with import ./config.nix; + +mkDerivation { + name = "filter"; + builder = builtins.toFile "builder" "ln -s $input $out"; + input = + builtins.path { + path = ((builtins.getEnv "TEST_ROOT") + "/filterin"); + filter = path: type: + type != "symlink" + && baseNameOf path != "foo" + && !((import ./lang/lib.nix).hasSuffix ".bak" (baseNameOf path)); + }; +} diff --git a/tests/plugins.sh b/tests/plugins.sh index 4b1baeddc..50bfaf7e9 100644 --- a/tests/plugins.sh +++ b/tests/plugins.sh @@ -2,6 +2,6 @@ source common.sh set -o pipefail -res=$(nix eval '(builtins.anotherNull)' --option setting-set true --option plugin-files $PWD/plugins/libplugintest*) +res=$(nix eval --expr builtins.anotherNull --option setting-set true --option plugin-files $PWD/plugins/libplugintest*) [ "$res"x = "nullx" ] diff --git a/tests/pure-eval.sh b/tests/pure-eval.sh index 49c856448..43a765997 100644 --- a/tests/pure-eval.sh +++ b/tests/pure-eval.sh @@ -2,17 +2,17 @@ source common.sh clearStore -nix eval --pure-eval '(assert 1 + 2 == 3; true)' +nix eval --expr 'assert 1 + 2 == 3; true' -[[ $(nix eval '(builtins.readFile ./pure-eval.sh)') =~ clearStore ]] +[[ $(nix eval --impure --expr 'builtins.readFile ./pure-eval.sh') =~ clearStore ]] -(! nix eval --pure-eval '(builtins.readFile ./pure-eval.sh)') +(! nix eval --expr 'builtins.readFile ./pure-eval.sh') -(! nix eval --pure-eval '(builtins.currentTime)') -(! nix eval --pure-eval '(builtins.currentSystem)') +(! nix eval --expr builtins.currentTime) +(! nix eval --expr builtins.currentSystem) (! nix-instantiate --pure-eval ./simple.nix) -[[ $(nix eval "((import (builtins.fetchurl { url = file://$(pwd)/pure-eval.nix; })).x)") == 123 ]] -(! nix eval --pure-eval "((import (builtins.fetchurl { url = file://$(pwd)/pure-eval.nix; })).x)") -nix eval --pure-eval "((import (builtins.fetchurl { url = file://$(pwd)/pure-eval.nix; sha256 = \"$(nix hash-file pure-eval.nix --type sha256)\"; })).x)" +[[ $(nix eval --impure --expr "(import (builtins.fetchurl { url = file://$(pwd)/pure-eval.nix; })).x") == 123 ]] +(! nix eval --expr "(import (builtins.fetchurl { url = file://$(pwd)/pure-eval.nix; })).x") +nix eval --expr "(import (builtins.fetchurl { url = file://$(pwd)/pure-eval.nix; sha256 = \"$(nix hash-file pure-eval.nix --type sha256)\"; })).x" diff --git a/tests/recursive.sh b/tests/recursive.sh index 2d4f83895..80a178cc7 100644 --- a/tests/recursive.sh +++ b/tests/recursive.sh @@ -9,9 +9,8 @@ rm -f $TEST_ROOT/result export unreachable=$(nix add-to-store ./recursive.sh) -nix --experimental-features 'nix-command recursive-nix' build -o $TEST_ROOT/result -L '( +NIX_BIN_DIR=$(dirname $(type -p nix)) nix --experimental-features 'nix-command recursive-nix' build -o $TEST_ROOT/result -L --impure --expr ' with import ./config.nix; - with import ; mkDerivation { name = "recursive"; dummy = builtins.toFile "dummy" "bla bla"; @@ -24,9 +23,10 @@ nix --experimental-features 'nix-command recursive-nix' build -o $TEST_ROOT/resu buildCommand = '\'\'' mkdir $out - PATH=${nixBinDir}:$PATH opts="--experimental-features nix-command" + PATH=${builtins.getEnv "NIX_BIN_DIR"}:$PATH + # Check that we can query/build paths in our input closure. nix $opts path-info $dummy nix $opts build $dummy @@ -49,7 +49,7 @@ nix --experimental-features 'nix-command recursive-nix' build -o $TEST_ROOT/resu [[ $(nix $opts path-info --all | wc -l) -eq 3 ]] # Build a derivation. - nix $opts build -L '\''( + nix $opts build -L --impure --expr '\'' derivation { name = "inner1"; builder = builtins.getEnv "SHELL"; @@ -57,13 +57,13 @@ nix --experimental-features 'nix-command recursive-nix' build -o $TEST_ROOT/resu fnord = builtins.toFile "fnord" "fnord"; args = [ "-c" "echo $fnord blaat > $out" ]; } - )'\'' + '\'' [[ $(nix $opts path-info --json ./result) =~ fnord ]] ln -s $(nix $opts path-info ./result) $out/inner1 '\'\''; - }) + } ' [[ $(cat $TEST_ROOT/result/inner1) =~ blaat ]] diff --git a/tests/remote-builds.nix b/tests/remote-builds.nix index 18d490830..153956619 100644 --- a/tests/remote-builds.nix +++ b/tests/remote-builds.nix @@ -1,8 +1,11 @@ # Test Nix's remote build feature. -{ nixpkgs, system, nix }: +{ nixpkgs, system, overlay }: -with import (nixpkgs + "/nixos/lib/testing.nix") { inherit system; }; +with import (nixpkgs + "/nixos/lib/testing.nix") { + inherit system; + extraConfigurations = [ { nixpkgs.overlays = [ overlay ]; } ]; +}; makeTest ( @@ -13,7 +16,6 @@ let { config, pkgs, ... }: { services.openssh.enable = true; virtualisation.writableStore = true; - nix.package = nix; nix.useSandbox = true; }; @@ -59,7 +61,6 @@ in ]; virtualisation.writableStore = true; virtualisation.pathsInNixDB = [ config.system.build.extraUtils ]; - nix.package = nix; nix.binaryCaches = lib.mkForce [ ]; programs.ssh.extraConfig = "ConnectTimeout 30"; }; diff --git a/tests/remote-store.sh b/tests/remote-store.sh index 4cc73465a..3a61946f9 100644 --- a/tests/remote-store.sh +++ b/tests/remote-store.sh @@ -2,6 +2,9 @@ source common.sh clearStore +# Ensure "fake ssh" remote store works just as legacy fake ssh would. +nix --store ssh-ng://localhost?remote-store=$TEST_ROOT/other-store doctor + startDaemon storeCleared=1 NIX_REMOTE_=$NIX_REMOTE $SHELL ./user-envs.sh diff --git a/tests/repair.sh b/tests/repair.sh index ec7ad5dca..ba019028d 100644 --- a/tests/repair.sh +++ b/tests/repair.sh @@ -13,14 +13,14 @@ hash=$(nix-hash $path2) chmod u+w $path2 touch $path2/bad -if nix-store --verify --check-contents -v; then - echo "nix-store --verify succeeded unexpectedly" >&2 - exit 1 -fi +(! nix-store --verify --check-contents -v) # The path can be repaired by rebuilding the derivation. nix-store --verify --check-contents --repair +(! [ -e $path2/bad ]) +(! [ -w $path2 ]) + nix-store --verify-path $path2 # Re-corrupt and delete the deriver. Now --verify --repair should @@ -30,10 +30,7 @@ touch $path2/bad nix-store --delete $(nix-store -qd $path2) -if nix-store --verify --check-contents --repair; then - echo "nix-store --verify --repair succeeded unexpectedly" >&2 - exit 1 -fi +(! nix-store --verify --check-contents --repair) nix-build dependencies.nix -o $TEST_ROOT/result --repair diff --git a/tests/restricted.sh b/tests/restricted.sh index e02becc60..242b901dd 100644 --- a/tests/restricted.sh +++ b/tests/restricted.sh @@ -17,18 +17,18 @@ nix-instantiate --restrict-eval --eval -E 'builtins.readDir ../src/nix-channel' (! nix-instantiate --restrict-eval --eval -E 'let __nixPath = [ { prefix = "foo"; path = ./.; } ]; in ') nix-instantiate --restrict-eval --eval -E 'let __nixPath = [ { prefix = "foo"; path = ./.; } ]; in ' -I src=. -p=$(nix eval --raw "(builtins.fetchurl file://$(pwd)/restricted.sh)" --restrict-eval --allowed-uris "file://$(pwd)") +p=$(nix eval --raw --expr "builtins.fetchurl file://$(pwd)/restricted.sh" --impure --restrict-eval --allowed-uris "file://$(pwd)") cmp $p restricted.sh -(! nix eval --raw "(builtins.fetchurl file://$(pwd)/restricted.sh)" --restrict-eval) +(! nix eval --raw --expr "builtins.fetchurl file://$(pwd)/restricted.sh" --impure --restrict-eval) -(! nix eval --raw "(builtins.fetchurl file://$(pwd)/restricted.sh)" --restrict-eval --allowed-uris "file://$(pwd)/restricted.sh/") +(! nix eval --raw --expr "builtins.fetchurl file://$(pwd)/restricted.sh" --impure --restrict-eval --allowed-uris "file://$(pwd)/restricted.sh/") -nix eval --raw "(builtins.fetchurl file://$(pwd)/restricted.sh)" --restrict-eval --allowed-uris "file://$(pwd)/restricted.sh" +nix eval --raw --expr "builtins.fetchurl file://$(pwd)/restricted.sh" --impure --restrict-eval --allowed-uris "file://$(pwd)/restricted.sh" -(! nix eval --raw "(builtins.fetchurl https://github.com/NixOS/patchelf/archive/master.tar.gz)" --restrict-eval) -(! nix eval --raw "(builtins.fetchTarball https://github.com/NixOS/patchelf/archive/master.tar.gz)" --restrict-eval) -(! nix eval --raw "(fetchGit git://github.com/NixOS/patchelf.git)" --restrict-eval) +(! nix eval --raw --expr "builtins.fetchurl https://github.com/NixOS/patchelf/archive/master.tar.gz" --impure --restrict-eval) +(! nix eval --raw --expr "builtins.fetchTarball https://github.com/NixOS/patchelf/archive/master.tar.gz" --impure --restrict-eval) +(! nix eval --raw --expr "fetchGit git://github.com/NixOS/patchelf.git" --impure --restrict-eval) ln -sfn $(pwd)/restricted.nix $TEST_ROOT/restricted.nix [[ $(nix-instantiate --eval $TEST_ROOT/restricted.nix) == 3 ]] @@ -37,7 +37,7 @@ ln -sfn $(pwd)/restricted.nix $TEST_ROOT/restricted.nix (! nix-instantiate --eval --restrict-eval $TEST_ROOT/restricted.nix -I .) nix-instantiate --eval --restrict-eval $TEST_ROOT/restricted.nix -I $TEST_ROOT -I . -[[ $(nix eval --raw --restrict-eval -I . '(builtins.readFile "${import ./simple.nix}/hello")') == 'Hello World!' ]] +[[ $(nix eval --raw --impure --restrict-eval -I . --expr 'builtins.readFile "${import ./simple.nix}/hello"') == 'Hello World!' ]] # Check whether we can leak symlink information through directory traversal. traverseDir="$(pwd)/restricted-traverse-me" @@ -45,7 +45,7 @@ ln -sfn "$(pwd)/restricted-secret" "$(pwd)/restricted-innocent" mkdir -p "$traverseDir" goUp="..$(echo "$traverseDir" | sed -e 's,[^/]\+,..,g')" output="$(nix eval --raw --restrict-eval -I "$traverseDir" \ - "(builtins.readFile \"$traverseDir/$goUp$(pwd)/restricted-innocent\")" \ + --expr "builtins.readFile \"$traverseDir/$goUp$(pwd)/restricted-innocent\"" \ 2>&1 || :)" echo "$output" | grep "is forbidden" ! echo "$output" | grep -F restricted-secret diff --git a/tests/search.sh b/tests/search.sh index 14da3127b..ee3261687 100644 --- a/tests/search.sh +++ b/tests/search.sh @@ -3,41 +3,23 @@ source common.sh clearStore clearCache -# No packages -(( $(NIX_PATH= nix search -u|wc -l) == 0 )) - -# Haven't updated cache, still nothing -(( $(nix search -f search.nix hello|wc -l) == 0 )) -(( $(nix search -f search.nix |wc -l) == 0 )) - -# Update cache, search should work -(( $(nix search -f search.nix -u hello|wc -l) > 0 )) - -# Use cache -(( $(nix search -f search.nix foo|wc -l) > 0 )) -(( $(nix search foo|wc -l) > 0 )) - -# Test --no-cache works -# No results from cache -(( $(nix search --no-cache foo |wc -l) == 0 )) -# Does find results from file pointed at -(( $(nix search -f search.nix --no-cache foo |wc -l) > 0 )) +(( $(nix search -f search.nix '' hello | wc -l) > 0 )) # Check descriptions are searched -(( $(nix search broken | wc -l) > 0 )) +(( $(nix search -f search.nix '' broken | wc -l) > 0 )) # Check search that matches nothing -(( $(nix search nosuchpackageexists | wc -l) == 0 )) +(( $(nix search -f search.nix '' nosuchpackageexists | wc -l) == 0 )) # Search for multiple arguments -(( $(nix search hello empty | wc -l) == 3 )) +(( $(nix search -f search.nix '' hello empty | wc -l) == 2 )) # Multiple arguments will not exist -(( $(nix search hello broken | wc -l) == 0 )) +(( $(nix search -f search.nix '' hello broken | wc -l) == 0 )) ## Search expressions # Check that empty search string matches all -nix search|grep -q foo -nix search|grep -q bar -nix search|grep -q hello +nix search -f search.nix '' |grep -q foo +nix search -f search.nix '' |grep -q bar +nix search -f search.nix '' |grep -q hello diff --git a/tests/setuid.nix b/tests/setuid.nix index 63d3c05cb..6f2f7d392 100644 --- a/tests/setuid.nix +++ b/tests/setuid.nix @@ -1,15 +1,17 @@ # Verify that Linux builds cannot create setuid or setgid binaries. -{ nixpkgs, system, nix }: +{ nixpkgs, system, overlay }: -with import (nixpkgs + "/nixos/lib/testing.nix") { inherit system; }; +with import (nixpkgs + "/nixos/lib/testing.nix") { + inherit system; + extraConfigurations = [ { nixpkgs.overlays = [ overlay ]; } ]; +}; makeTest { machine = { config, lib, pkgs, ... }: { virtualisation.writableStore = true; - nix.package = nix; nix.binaryCaches = lib.mkForce [ ]; nix.nixPath = [ "nixpkgs=${lib.cleanSource pkgs.path}" ]; virtualisation.pathsInNixDB = [ pkgs.stdenv pkgs.pkgsi686Linux.stdenv ]; diff --git a/tests/shell.nix b/tests/shell.nix index 6cb4f082b..6ce59b416 100644 --- a/tests/shell.nix +++ b/tests/shell.nix @@ -24,6 +24,7 @@ let pkgs = rec { VAR_FROM_NIX = "bar"; TEST_inNixShell = if inNixShell then "true" else "false"; inherit stdenv; + outputs = ["dev" "out"]; }; # Used by nix-shell -p diff --git a/tests/simple.sh b/tests/simple.sh index 37631b648..15bd2bd16 100644 --- a/tests/simple.sh +++ b/tests/simple.sh @@ -10,13 +10,15 @@ outPath=$(nix-store -rvv "$drvPath") echo "output path is $outPath" +(! [ -w $outPath ]) + text=$(cat "$outPath"/hello) if test "$text" != "Hello World!"; then exit 1; fi # Directed delete: $outPath is not reachable from a root, so it should # be deleteable. nix-store --delete $outPath -if test -e $outPath/hello; then false; fi +(! [ -e $outPath/hello ]) outPath="$(NIX_REMOTE=local?store=/foo\&real=$TEST_ROOT/real-store nix-instantiate --readonly-mode hash-check.nix)" if test "$outPath" != "/foo/lfy1s6ca46rm5r6w4gg9hc0axiakjcnm-dependencies.drv"; then diff --git a/tests/ssh-relay.sh b/tests/ssh-relay.sh new file mode 100644 index 000000000..dce50974b --- /dev/null +++ b/tests/ssh-relay.sh @@ -0,0 +1,16 @@ +source common.sh + +echo foo > $TEST_ROOT/hello.sh + +ssh_localhost=ssh://localhost +remote_store=?remote-store=$ssh_localhost + +store=$ssh_localhost + +store+=$remote_store +store+=$remote_store +store+=$remote_store + +out=$(nix add-to-store --store "$store" $TEST_ROOT/hello.sh) + +[ foo = $(< $out) ] diff --git a/tests/tarball.sh b/tests/tarball.sh index b3ec16d40..fe65a22e4 100644 --- a/tests/tarball.sh +++ b/tests/tarball.sh @@ -17,7 +17,7 @@ test_tarball() { local compressor="$2" tarball=$TEST_ROOT/tarball.tar$ext - (cd $TEST_ROOT && tar c tarball) | $compressor > $tarball + (cd $TEST_ROOT && tar cf - tarball) | $compressor > $tarball nix-env -f file://$tarball -qa --out-path | grep -q dependencies @@ -27,10 +27,13 @@ test_tarball() { nix-build -o $TEST_ROOT/result -E "import (fetchTarball file://$tarball)" - nix-build --experimental-features flakes -o $TEST_ROOT/result -E "import (fetchTree file://$tarball)" - nix-build --experimental-features flakes -o $TEST_ROOT/result -E "import (fetchTree { type = \"tarball\"; url = file://$tarball; })" - nix-build --experimental-features flakes -o $TEST_ROOT/result -E "import (fetchTree { type = \"tarball\"; url = file://$tarball; narHash = \"$hash\"; })" - nix-build --experimental-features flakes -o $TEST_ROOT/result -E "import (fetchTree { type = \"tarball\"; url = file://$tarball; narHash = \"sha256-xdKv2pq/IiwLSnBBJXW8hNowI4MrdZfW+SYqDQs7Tzc=\"; })" 2>&1 | grep 'NAR hash mismatch in input' + nix-build -o $TEST_ROOT/result -E "import (fetchTree file://$tarball)" + nix-build -o $TEST_ROOT/result -E "import (fetchTree { type = \"tarball\"; url = file://$tarball; })" + nix-build -o $TEST_ROOT/result -E "import (fetchTree { type = \"tarball\"; url = file://$tarball; narHash = \"$hash\"; })" + nix-build -o $TEST_ROOT/result -E "import (fetchTree { type = \"tarball\"; url = file://$tarball; narHash = \"sha256-xdKv2pq/IiwLSnBBJXW8hNowI4MrdZfW+SYqDQs7Tzc=\"; })" 2>&1 | grep 'NAR hash mismatch in input' + + nix-instantiate --strict --eval -E "!((import (fetchTree { type = \"tarball\"; url = file://$tarball; narHash = \"$hash\"; })) ? submodules)" >&2 + nix-instantiate --strict --eval -E "!((import (fetchTree { type = \"tarball\"; url = file://$tarball; narHash = \"$hash\"; })) ? submodules)" 2>&1 | grep 'true' nix-instantiate --eval -E '1 + 2' -I fnord=file://no-such-tarball.tar$ext nix-instantiate --eval -E 'with ; 1 + 2' -I fnord=file://no-such-tarball$ext diff --git a/tests/user-envs.nix b/tests/user-envs.nix index 1aa410cc9..43eff1a68 100644 --- a/tests/user-envs.nix +++ b/tests/user-envs.nix @@ -13,7 +13,7 @@ let builder = ./user-envs.builder.sh; } // { meta = { - description = "A silly test package"; + description = "A silly test package with some \${escaped anti-quotation} in it"; }; });