diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e2e07da2..cb97fd211 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -128,7 +128,7 @@ jobs: - run: exec bash -c "nix-channel --update && nix-env -iA nixpkgs.hello && hello" docker_push_image: - needs: [check_secrets, tests] + needs: [check_secrets, tests, vm_tests] permissions: contents: read packages: write @@ -194,7 +194,13 @@ jobs: - uses: actions/checkout@v4 - uses: DeterminateSystems/nix-installer-action@main - uses: DeterminateSystems/magic-nix-cache-action@main - - run: nix build -L .#hydraJobs.tests.githubFlakes .#hydraJobs.tests.tarballFlakes .#hydraJobs.tests.functional_user + - run: | + nix build -L \ + .#hydraJobs.tests.functional_user \ + .#hydraJobs.tests.githubFlakes \ + .#hydraJobs.tests.nix-docker \ + .#hydraJobs.tests.tarballFlakes \ + ; flake_regressions: needs: vm_tests @@ -214,4 +220,4 @@ jobs: path: flake-regressions/tests - uses: DeterminateSystems/nix-installer-action@main - uses: DeterminateSystems/magic-nix-cache-action@main - - run: nix build --out-link ./new-nix && PATH=$(pwd)/new-nix/bin:$PATH scripts/flake-regressions.sh + - run: nix build --out-link ./new-nix && PATH=$(pwd)/new-nix/bin:$PATH MAX_FLAKES=25 flake-regressions/eval-all.sh diff --git a/.gitignore b/.gitignore index 11a80ab5b..de1183977 100644 --- a/.gitignore +++ b/.gitignore @@ -102,9 +102,6 @@ perl/Makefile.config /tests/functional/restricted-innocent /tests/functional/shell /tests/functional/shell.drv -/tests/functional/config.nix -/tests/functional/ca/config.nix -/tests/functional/dyn-drv/config.nix /tests/functional/repl-result-out /tests/functional/debugger-test-out /tests/functional/test-libstoreconsumer/test-libstoreconsumer diff --git a/.version b/.version index 5c18f9195..7a25c70f9 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -2.25.0 +2.26.0 diff --git a/Makefile b/Makefile deleted file mode 100644 index 4d70be0e8..000000000 --- a/Makefile +++ /dev/null @@ -1,128 +0,0 @@ -# External build directory support - -include mk/build-dir.mk - --include $(buildprefix)Makefile.config -clean-files += $(buildprefix)Makefile.config - -# List makefiles - -include mk/platform.mk - -ifeq ($(ENABLE_BUILD), yes) -makefiles = \ - mk/precompiled-headers.mk \ - local.mk \ - src/libutil/local.mk \ - src/libstore/local.mk \ - src/libfetchers/local.mk \ - src/libmain/local.mk \ - src/libexpr/local.mk \ - src/libflake/local.mk \ - src/libcmd/local.mk \ - src/nix/local.mk \ - src/libutil-c/local.mk \ - src/libstore-c/local.mk \ - src/libexpr-c/local.mk - -ifdef HOST_UNIX -makefiles += \ - scripts/local.mk \ - maintainers/local.mk \ - misc/bash/local.mk \ - misc/fish/local.mk \ - misc/zsh/local.mk \ - misc/systemd/local.mk \ - misc/launchd/local.mk \ - misc/upstart/local.mk -endif -endif - -ifeq ($(ENABLE_UNIT_TESTS), yes) -makefiles += \ - src/libutil-tests/local.mk \ - src/libutil-test-support/local.mk \ - src/libstore-tests/local.mk \ - src/libstore-test-support/local.mk \ - src/libfetchers-tests/local.mk \ - src/libexpr-tests/local.mk \ - src/libexpr-test-support/local.mk \ - src/libflake-tests/local.mk -endif - -ifeq ($(ENABLE_FUNCTIONAL_TESTS), yes) -ifdef HOST_UNIX -makefiles += \ - tests/functional/local.mk \ - tests/functional/flakes/local.mk \ - tests/functional/ca/local.mk \ - tests/functional/git-hashing/local.mk \ - tests/functional/dyn-drv/local.mk \ - tests/functional/local-overlay-store/local.mk \ - tests/functional/test-libstoreconsumer/local.mk \ - tests/functional/plugins/local.mk -endif -endif - -# Some makefiles require access to built programs and must be included late. -makefiles-late = - -ifeq ($(ENABLE_DOC_GEN), yes) -makefiles-late += doc/manual/local.mk -endif - -# Miscellaneous global Flags - -OPTIMIZE = 1 - -ifeq ($(OPTIMIZE), 1) - GLOBAL_CXXFLAGS += -O3 $(CXXLTO) - GLOBAL_LDFLAGS += $(CXXLTO) -else - GLOBAL_CXXFLAGS += -O0 -U_FORTIFY_SOURCE - unexport NIX_HARDENING_ENABLE -endif - -ifdef HOST_WINDOWS - # Windows DLLs are stricter about symbol visibility than Unix shared - # objects --- see https://gcc.gnu.org/wiki/Visibility for details. - # This is a temporary sledgehammer to export everything like on Unix, - # and not detail with this yet. - # - # TODO do not do this, and instead do fine-grained export annotations. - GLOBAL_LDFLAGS += -Wl,--export-all-symbols -endif - -GLOBAL_CXXFLAGS += -g -Wall -Wdeprecated-copy -Wignored-qualifiers -Wimplicit-fallthrough -Werror=unused-result -Werror=suggest-override -include $(buildprefix)config.h -std=c++2a -I src - -# Include the main lib, causing rules to be defined - -include mk/lib.mk - -# Fallback stub rules for better UX when things are disabled -# -# These must be defined after `mk/lib.mk`. Otherwise the first rule -# incorrectly becomes the default target. - -ifneq ($(ENABLE_UNIT_TESTS), yes) -.PHONY: check -check: - @echo "Unit tests are disabled. Configure without '--disable-unit-tests', or avoid calling 'make check'." - @exit 1 -endif - -ifneq ($(ENABLE_FUNCTIONAL_TESTS), yes) -.PHONY: installcheck -installcheck: - @echo "Functional tests are disabled. Configure without '--disable-functional-tests', or avoid calling 'make installcheck'." - @exit 1 -endif - -# Documentation fallback stub rules. - -ifneq ($(ENABLE_DOC_GEN), yes) -.PHONY: manual-html manpages -manual-html manpages: - @echo "Generated docs are disabled. Configure without '--disable-doc-gen', or avoid calling 'make manpages' and 'make manual-html'." - @exit 1 -endif diff --git a/Makefile.config.in b/Makefile.config.in deleted file mode 100644 index 3100d2073..000000000 --- a/Makefile.config.in +++ /dev/null @@ -1,54 +0,0 @@ -AR = @AR@ -BDW_GC_LIBS = @BDW_GC_LIBS@ -BOOST_LDFLAGS = @BOOST_LDFLAGS@ -BUILD_SHARED_LIBS = @BUILD_SHARED_LIBS@ -CC = @CC@ -CFLAGS = @CFLAGS@ -CXX = @CXX@ -CXXFLAGS = @CXXFLAGS@ -CXXLTO = @CXXLTO@ -EDITLINE_LIBS = @EDITLINE_LIBS@ -ENABLE_BUILD = @ENABLE_BUILD@ -ENABLE_DOC_GEN = @ENABLE_DOC_GEN@ -ENABLE_FUNCTIONAL_TESTS = @ENABLE_FUNCTIONAL_TESTS@ -ENABLE_S3 = @ENABLE_S3@ -ENABLE_UNIT_TESTS = @ENABLE_UNIT_TESTS@ -GTEST_LIBS = @GTEST_LIBS@ -HAVE_LIBCPUID = @HAVE_LIBCPUID@ -HAVE_SECCOMP = @HAVE_SECCOMP@ -HOST_OS = @host_os@ -INSTALL_UNIT_TESTS = @INSTALL_UNIT_TESTS@ -LDFLAGS = @LDFLAGS@ -LIBARCHIVE_LIBS = @LIBARCHIVE_LIBS@ -LIBBROTLI_LIBS = @LIBBROTLI_LIBS@ -LIBCURL_LIBS = @LIBCURL_LIBS@ -LIBGIT2_LIBS = @LIBGIT2_LIBS@ -LIBSECCOMP_LIBS = @LIBSECCOMP_LIBS@ -LOWDOWN_LIBS = @LOWDOWN_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@ -bindir = @bindir@ -checkbindir = @checkbindir@ -checklibdir = @checklibdir@ -datadir = @datadir@ -datarootdir = @datarootdir@ -docdir = @docdir@ -embedded_sandbox_shell = @embedded_sandbox_shell@ -exec_prefix = @exec_prefix@ -includedir = @includedir@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localstatedir = @localstatedir@ -lsof = @lsof@ -mandir = @mandir@ -pkglibdir = $(libdir)/$(PACKAGE_NAME) -prefix = @prefix@ -sandbox_shell = @sandbox_shell@ -storedir = @storedir@ -sysconfdir = @sysconfdir@ -system = @system@ diff --git a/build-utils-meson/libatomic/meson.build b/build-utils-meson/libatomic/meson.build new file mode 100644 index 000000000..d16d23817 --- /dev/null +++ b/build-utils-meson/libatomic/meson.build @@ -0,0 +1,8 @@ + +# Check if -latomic is needed +# This is needed for std::atomic on some platforms +# We did not manage to test this reliably on all platforms, so we hardcode +# it for now. +if host_machine.cpu_family() == 'arm' + deps_other += cxx.find_library('atomic') +endif diff --git a/build-utils-meson/windows-version/meson.build b/build-utils-meson/windows-version/meson.build new file mode 100644 index 000000000..3a008e5df --- /dev/null +++ b/build-utils-meson/windows-version/meson.build @@ -0,0 +1,6 @@ +if host_machine.system() == 'windows' + # https://learn.microsoft.com/en-us/cpp/porting/modifying-winver-and-win32-winnt?view=msvc-170 + # #define _WIN32_WINNT_WIN8 0x0602 + # We currently don't use any API which requires higher than this. + add_project_arguments([ '-D_WIN32_WINNT=0x0602' ], language: 'cpp') +endif diff --git a/config/install-sh b/config/install-sh deleted file mode 100755 index 377bb8687..000000000 --- a/config/install-sh +++ /dev/null @@ -1,527 +0,0 @@ -#!/bin/sh -# install - install a program, script, or datafile - -scriptversion=2011-11-20.07; # UTC - -# This originates from X11R5 (mit/util/scripts/install.sh), which was -# later released in X11R6 (xc/config/util/install.sh) with the -# following copyright and license. -# -# Copyright (C) 1994 X Consortium -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN -# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- -# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -# Except as contained in this notice, the name of the X Consortium shall not -# be used in advertising or otherwise to promote the sale, use or other deal- -# ings in this Software without prior written authorization from the X Consor- -# tium. -# -# -# FSF changes to this file are in the public domain. -# -# Calling this script install-sh is preferred over install.sh, to prevent -# 'make' implicit rules from creating a file called install from it -# when there is no Makefile. -# -# This script is compatible with the BSD install script, but was written -# from scratch. - -nl=' -' -IFS=" "" $nl" - -# set DOITPROG to echo to test this script - -# Don't use :- since 4.3BSD and earlier shells don't like it. -doit=${DOITPROG-} -if test -z "$doit"; then - doit_exec=exec -else - doit_exec=$doit -fi - -# Put in absolute file names if you don't have them in your path; -# or use environment vars. - -chgrpprog=${CHGRPPROG-chgrp} -chmodprog=${CHMODPROG-chmod} -chownprog=${CHOWNPROG-chown} -cmpprog=${CMPPROG-cmp} -cpprog=${CPPROG-cp} -mkdirprog=${MKDIRPROG-mkdir} -mvprog=${MVPROG-mv} -rmprog=${RMPROG-rm} -stripprog=${STRIPPROG-strip} - -posix_glob='?' -initialize_posix_glob=' - test "$posix_glob" != "?" || { - if (set -f) 2>/dev/null; then - posix_glob= - else - posix_glob=: - fi - } -' - -posix_mkdir= - -# Desired mode of installed file. -mode=0755 - -chgrpcmd= -chmodcmd=$chmodprog -chowncmd= -mvcmd=$mvprog -rmcmd="$rmprog -f" -stripcmd= - -src= -dst= -dir_arg= -dst_arg= - -copy_on_change=false -no_target_directory= - -usage="\ -Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE - or: $0 [OPTION]... SRCFILES... DIRECTORY - or: $0 [OPTION]... -t DIRECTORY SRCFILES... - or: $0 [OPTION]... -d DIRECTORIES... - -In the 1st form, copy SRCFILE to DSTFILE. -In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. -In the 4th, create DIRECTORIES. - -Options: - --help display this help and exit. - --version display version info and exit. - - -c (ignored) - -C install only if different (preserve the last data modification time) - -d create directories instead of installing files. - -g GROUP $chgrpprog installed files to GROUP. - -m MODE $chmodprog installed files to MODE. - -o USER $chownprog installed files to USER. - -s $stripprog installed files. - -t DIRECTORY install into DIRECTORY. - -T report an error if DSTFILE is a directory. - -Environment variables override the default commands: - CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG - RMPROG STRIPPROG -" - -while test $# -ne 0; do - case $1 in - -c) ;; - - -C) copy_on_change=true;; - - -d) dir_arg=true;; - - -g) chgrpcmd="$chgrpprog $2" - shift;; - - --help) echo "$usage"; exit $?;; - - -m) mode=$2 - case $mode in - *' '* | *' '* | *' -'* | *'*'* | *'?'* | *'['*) - echo "$0: invalid mode: $mode" >&2 - exit 1;; - esac - shift;; - - -o) chowncmd="$chownprog $2" - shift;; - - -s) stripcmd=$stripprog;; - - -t) dst_arg=$2 - # Protect names problematic for 'test' and other utilities. - case $dst_arg in - -* | [=\(\)!]) dst_arg=./$dst_arg;; - esac - shift;; - - -T) no_target_directory=true;; - - --version) echo "$0 $scriptversion"; exit $?;; - - --) shift - break;; - - -*) echo "$0: invalid option: $1" >&2 - exit 1;; - - *) break;; - esac - shift -done - -if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then - # When -d is used, all remaining arguments are directories to create. - # When -t is used, the destination is already specified. - # Otherwise, the last argument is the destination. Remove it from $@. - for arg - do - if test -n "$dst_arg"; then - # $@ is not empty: it contains at least $arg. - set fnord "$@" "$dst_arg" - shift # fnord - fi - shift # arg - dst_arg=$arg - # Protect names problematic for 'test' and other utilities. - case $dst_arg in - -* | [=\(\)!]) dst_arg=./$dst_arg;; - esac - done -fi - -if test $# -eq 0; then - if test -z "$dir_arg"; then - echo "$0: no input file specified." >&2 - exit 1 - fi - # It's OK to call 'install-sh -d' without argument. - # This can happen when creating conditional directories. - exit 0 -fi - -if test -z "$dir_arg"; then - do_exit='(exit $ret); exit $ret' - trap "ret=129; $do_exit" 1 - trap "ret=130; $do_exit" 2 - trap "ret=141; $do_exit" 13 - trap "ret=143; $do_exit" 15 - - # Set umask so as not to create temps with too-generous modes. - # However, 'strip' requires both read and write access to temps. - case $mode in - # Optimize common cases. - *644) cp_umask=133;; - *755) cp_umask=22;; - - *[0-7]) - if test -z "$stripcmd"; then - u_plus_rw= - else - u_plus_rw='% 200' - fi - cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; - *) - if test -z "$stripcmd"; then - u_plus_rw= - else - u_plus_rw=,u+rw - fi - cp_umask=$mode$u_plus_rw;; - esac -fi - -for src -do - # Protect names problematic for 'test' and other utilities. - case $src in - -* | [=\(\)!]) src=./$src;; - esac - - if test -n "$dir_arg"; then - dst=$src - dstdir=$dst - test -d "$dstdir" - dstdir_status=$? - else - - # Waiting for this to be detected by the "$cpprog $src $dsttmp" command - # might cause directories to be created, which would be especially bad - # if $src (and thus $dsttmp) contains '*'. - if test ! -f "$src" && test ! -d "$src"; then - echo "$0: $src does not exist." >&2 - exit 1 - fi - - if test -z "$dst_arg"; then - echo "$0: no destination specified." >&2 - exit 1 - fi - dst=$dst_arg - - # If destination is a directory, append the input filename; won't work - # if double slashes aren't ignored. - if test -d "$dst"; then - if test -n "$no_target_directory"; then - echo "$0: $dst_arg: Is a directory" >&2 - exit 1 - fi - dstdir=$dst - dst=$dstdir/`basename "$src"` - dstdir_status=0 - else - # Prefer dirname, but fall back on a substitute if dirname fails. - dstdir=` - (dirname "$dst") 2>/dev/null || - expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$dst" : 'X\(//\)[^/]' \| \ - X"$dst" : 'X\(//\)$' \| \ - X"$dst" : 'X\(/\)' \| . 2>/dev/null || - echo X"$dst" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q' - ` - - test -d "$dstdir" - dstdir_status=$? - fi - fi - - obsolete_mkdir_used=false - - if test $dstdir_status != 0; then - case $posix_mkdir in - '') - # Create intermediate dirs using mode 755 as modified by the umask. - # This is like FreeBSD 'install' as of 1997-10-28. - umask=`umask` - case $stripcmd.$umask in - # Optimize common cases. - *[2367][2367]) mkdir_umask=$umask;; - .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; - - *[0-7]) - mkdir_umask=`expr $umask + 22 \ - - $umask % 100 % 40 + $umask % 20 \ - - $umask % 10 % 4 + $umask % 2 - `;; - *) mkdir_umask=$umask,go-w;; - esac - - # With -d, create the new directory with the user-specified mode. - # Otherwise, rely on $mkdir_umask. - if test -n "$dir_arg"; then - mkdir_mode=-m$mode - else - mkdir_mode= - fi - - posix_mkdir=false - case $umask in - *[123567][0-7][0-7]) - # POSIX mkdir -p sets u+wx bits regardless of umask, which - # is incompatible with FreeBSD 'install' when (umask & 300) != 0. - ;; - *) - tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ - trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 - - if (umask $mkdir_umask && - exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 - then - if test -z "$dir_arg" || { - # Check for POSIX incompatibilities with -m. - # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or - # other-writable bit of parent directory when it shouldn't. - # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. - ls_ld_tmpdir=`ls -ld "$tmpdir"` - case $ls_ld_tmpdir in - d????-?r-*) different_mode=700;; - d????-?--*) different_mode=755;; - *) false;; - esac && - $mkdirprog -m$different_mode -p -- "$tmpdir" && { - ls_ld_tmpdir_1=`ls -ld "$tmpdir"` - test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" - } - } - then posix_mkdir=: - fi - rmdir "$tmpdir/d" "$tmpdir" - else - # Remove any dirs left behind by ancient mkdir implementations. - rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null - fi - trap '' 0;; - esac;; - esac - - if - $posix_mkdir && ( - umask $mkdir_umask && - $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" - ) - then : - else - - # The umask is ridiculous, or mkdir does not conform to POSIX, - # or it failed possibly due to a race condition. Create the - # directory the slow way, step by step, checking for races as we go. - - case $dstdir in - /*) prefix='/';; - [-=\(\)!]*) prefix='./';; - *) prefix='';; - esac - - eval "$initialize_posix_glob" - - oIFS=$IFS - IFS=/ - $posix_glob set -f - set fnord $dstdir - shift - $posix_glob set +f - IFS=$oIFS - - prefixes= - - for d - do - test X"$d" = X && continue - - prefix=$prefix$d - if test -d "$prefix"; then - prefixes= - else - if $posix_mkdir; then - (umask=$mkdir_umask && - $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break - # Don't fail if two instances are running concurrently. - test -d "$prefix" || exit 1 - else - case $prefix in - *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; - *) qprefix=$prefix;; - esac - prefixes="$prefixes '$qprefix'" - fi - fi - prefix=$prefix/ - done - - if test -n "$prefixes"; then - # Don't fail if two instances are running concurrently. - (umask $mkdir_umask && - eval "\$doit_exec \$mkdirprog $prefixes") || - test -d "$dstdir" || exit 1 - obsolete_mkdir_used=true - fi - fi - fi - - if test -n "$dir_arg"; then - { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && - { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && - { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || - test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 - else - - # Make a couple of temp file names in the proper directory. - dsttmp=$dstdir/_inst.$$_ - rmtmp=$dstdir/_rm.$$_ - - # Trap to clean up those temp files at exit. - trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 - - # Copy the file name to the temp name. - (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && - - # and set any options; do chmod last to preserve setuid bits. - # - # If any of these fail, we abort the whole thing. If we want to - # ignore errors from any of these, just make sure not to ignore - # errors from the above "$doit $cpprog $src $dsttmp" command. - # - { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && - { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && - { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && - { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && - - # If -C, don't bother to copy if it wouldn't change the file. - if $copy_on_change && - old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && - new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && - - eval "$initialize_posix_glob" && - $posix_glob set -f && - set X $old && old=:$2:$4:$5:$6 && - set X $new && new=:$2:$4:$5:$6 && - $posix_glob set +f && - - test "$old" = "$new" && - $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 - then - rm -f "$dsttmp" - else - # Rename the file to the real destination. - $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || - - # The rename failed, perhaps because mv can't rename something else - # to itself, or perhaps because mv is so ancient that it does not - # support -f. - { - # Now remove or move aside any old file at destination location. - # We try this two ways since rm can't unlink itself on some - # systems and the destination file might be busy for other - # reasons. In this case, the final cleanup might fail but the new - # file should still install successfully. - { - test ! -f "$dst" || - $doit $rmcmd -f "$dst" 2>/dev/null || - { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && - { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } - } || - { echo "$0: cannot unlink or rename $dst" >&2 - (exit 1); exit 1 - } - } && - - # Now rename the file to the real destination. - $doit $mvcmd "$dsttmp" "$dst" - } - fi || exit 1 - - trap '' 0 - fi -done - -# Local variables: -# eval: (add-hook 'write-file-hooks 'time-stamp) -# time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" -# time-stamp-time-zone: "UTC" -# time-stamp-end: "; # UTC" -# End: diff --git a/configure.ac b/configure.ac deleted file mode 100644 index 4df5c80f0..000000000 --- a/configure.ac +++ /dev/null @@ -1,456 +0,0 @@ -AC_INIT([nix],[m4_esyscmd(bash -c "echo -n $(cat ./.version)$VERSION_SUFFIX")]) -AC_CONFIG_MACRO_DIRS([m4]) -AC_CONFIG_SRCDIR(README.md) -AC_CONFIG_AUX_DIR(config) - -AC_PROG_SED - -# Construct a Nix system name (like "i686-linux"): -# https://www.gnu.org/software/autoconf/manual/html_node/Canonicalizing.html#index-AC_005fCANONICAL_005fHOST-1 -# The inital value is produced by the `config/config.guess` script: -# upstream: https://git.savannah.gnu.org/cgit/config.git/tree/config.guess -# It has the following form, which is not documented anywhere: -# --[][-] -# If `./configure` is passed any of the `--host`, `--build`, `--target` options, the value comes from `config/config.sub` instead: -# upstream: https://git.savannah.gnu.org/cgit/config.git/tree/config.sub -AC_CANONICAL_HOST -AC_MSG_CHECKING([for the canonical Nix system name]) - -AC_ARG_WITH(system, AS_HELP_STRING([--with-system=SYSTEM],[Platform identifier (e.g., `i686-linux').]), - [system=$withval], - [case "$host_cpu" in - i*86) - machine_name="i686";; - amd64) - machine_name="x86_64";; - armv6|armv7) - machine_name="${host_cpu}l";; - *) - machine_name="$host_cpu";; - esac - - case "$host_os" in - linux-gnu*|linux-musl*) - # For backward compatibility, strip the `-gnu' part. - system="$machine_name-linux";; - *) - # Strip the version number from names such as `gnu0.3', - # `darwin10.2.0', etc. - system="$machine_name-`echo $host_os | "$SED" -e's/@<:@0-9.@:>@*$//g'`";; - esac]) - -AC_MSG_RESULT($system) -AC_SUBST(system) -AC_DEFINE_UNQUOTED(SYSTEM, ["$system"], [platform identifier ('cpu-os')]) - - -# State should be stored in /nix/var, unless the user overrides it explicitly. -test "$localstatedir" = '${prefix}/var' && localstatedir=/nix/var - -# Assign a default value to C{,XX}FLAGS as the default configure script sets them -# to -O2 otherwise, which we don't want to have hardcoded -CFLAGS=${CFLAGS-""} -CXXFLAGS=${CXXFLAGS-""} - -AC_PROG_CC -AC_PROG_CXX -AC_PROG_CPP - -AC_CHECK_TOOL([AR], [ar]) - -# Use 64-bit file system calls so that we can support files > 2 GiB. -AC_SYS_LARGEFILE - - -# OS-specific stuff. -case "$host_os" in - solaris*) - # Solaris requires -lsocket -lnsl for network functions - LDFLAGS="-lsocket -lnsl $LDFLAGS" - ;; - darwin*) - # Need to link to libsandbox. - LDFLAGS="-lsandbox $LDFLAGS" - ;; -esac - - -ENSURE_NO_GCC_BUG_80431 - - -# Check for pubsetbuf. -AC_MSG_CHECKING([for pubsetbuf]) -AC_LANG_PUSH(C++) -AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include -using namespace std; -static char buf[1024];]], - [[cerr.rdbuf()->pubsetbuf(buf, sizeof(buf));]])], - [AC_MSG_RESULT(yes) AC_DEFINE(HAVE_PUBSETBUF, 1, [Whether pubsetbuf is available.])], - AC_MSG_RESULT(no)) -AC_LANG_POP(C++) - - -AC_CHECK_FUNCS([statvfs pipe2 close_range]) - - -# Check for lutimes and utimensat, optionally used for changing the -# mtime of symlinks. -AC_CHECK_DECLS([AT_SYMLINK_NOFOLLOW], [], [], [[#include ]]) -AC_CHECK_FUNCS([lutimes utimensat]) - - -# Check whether the store optimiser can optimise symlinks. -AC_MSG_CHECKING([whether it is possible to create a link to a symlink]) -ln -s bla tmp_link -if ln tmp_link tmp_link2 2> /dev/null; then - AC_MSG_RESULT(yes) - AC_DEFINE(CAN_LINK_SYMLINK, 1, [Whether link() works on symlinks.]) -else - AC_MSG_RESULT(no) -fi -rm -f tmp_link tmp_link2 - - -# Check for . -AC_LANG_PUSH(C++) -AC_CHECK_HEADERS([locale]) -AC_LANG_POP(C++) - - -AC_DEFUN([NEED_PROG], -[ -AC_PATH_PROG($1, $2) -if test -z "$$1"; then - AC_MSG_ERROR([$2 is required]) -fi -]) - -NEED_PROG(bash, bash) -AC_PATH_PROG(flex, flex, false) -AC_PATH_PROG(bison, bison, false) -AC_PATH_PROG(dot, dot) -AC_PATH_PROG(lsof, lsof, lsof) - - -AC_SUBST(coreutils, [$(dirname $(type -p cat))]) - - -AC_ARG_WITH(store-dir, AS_HELP_STRING([--with-store-dir=PATH],[path of the Nix store (defaults to /nix/store)]), - storedir=$withval, storedir='/nix/store') -AC_SUBST(storedir) - - -# Running the functional tests without building Nix is useful for testing -# different pre-built versions of Nix against each other. -AC_ARG_ENABLE(build, AS_HELP_STRING([--disable-build],[Do not build nix]), - ENABLE_BUILD=$enableval, ENABLE_BUILD=yes) -AC_SUBST(ENABLE_BUILD) - -# Building without unit tests is useful for bootstrapping with a smaller footprint -# or running the tests in a separate derivation. Otherwise, we do compile and -# run them. - -AC_ARG_ENABLE(unit-tests, AS_HELP_STRING([--disable-unit-tests],[Do not build the tests]), - ENABLE_UNIT_TESTS=$enableval, ENABLE_UNIT_TESTS=$ENABLE_BUILD) -AC_SUBST(ENABLE_UNIT_TESTS) - -AS_IF( - [test "$ENABLE_BUILD" == "no" && test "$ENABLE_UNIT_TESTS" == "yes"], - [AC_MSG_ERROR([Cannot enable unit tests when building overall is disabled. Please do not pass '--enable-unit-tests' or do not pass '--disable-build'.])]) - -AC_ARG_ENABLE(functional-tests, AS_HELP_STRING([--disable-functional-tests],[Do not build the tests]), - ENABLE_FUNCTIONAL_TESTS=$enableval, ENABLE_FUNCTIONAL_TESTS=yes) -AC_SUBST(ENABLE_FUNCTIONAL_TESTS) - -# documentation generation switch -AC_ARG_ENABLE(doc-gen, AS_HELP_STRING([--disable-doc-gen],[disable documentation generation]), - ENABLE_DOC_GEN=$enableval, ENABLE_DOC_GEN=$ENABLE_BUILD) -AC_SUBST(ENABLE_DOC_GEN) - -AS_IF( - [test "$ENABLE_BUILD" == "no" && test "$ENABLE_DOC_GEN" == "yes"], - [AC_MSG_ERROR([Cannot enable generated docs when building overall is disabled. Please do not pass '--enable-doc-gen' or do not pass '--disable-build'.])]) - -AS_IF( - [test "$ENABLE_FUNCTIONAL_TESTS" == "yes" || test "$ENABLE_DOC_GEN" == "yes"], - [NEED_PROG(jq, jq)]) - -AS_IF( - [test "$ENABLE_DOC_GEN" == "yes"], - [NEED_PROG(man, man)]) - -AS_IF([test "$ENABLE_BUILD" == "yes"],[ - -# Look for boost, a required dependency. -# Note that AX_BOOST_BASE only exports *CPP* BOOST_CPPFLAGS, no CXX flags, -# and CPPFLAGS are not passed to the C++ compiler automatically. -# Thus we append the returned CPPFLAGS to the CXXFLAGS here. -AX_BOOST_BASE([1.66], [CXXFLAGS="$BOOST_CPPFLAGS $CXXFLAGS"], [AC_MSG_ERROR([Nix requires boost.])]) -# For unknown reasons, setting this directly in the ACTION-IF-FOUND above -# ends up with LDFLAGS being empty, so we set it afterwards. -LDFLAGS="$BOOST_LDFLAGS $LDFLAGS" - -# On some platforms, new-style atomics need a helper library -AC_MSG_CHECKING(whether -latomic is needed) -AC_LINK_IFELSE([AC_LANG_SOURCE([[ -#include -uint64_t v; -int main() { - return (int)__atomic_load_n(&v, __ATOMIC_ACQUIRE); -}]])], GCC_ATOMIC_BUILTINS_NEED_LIBATOMIC=no, GCC_ATOMIC_BUILTINS_NEED_LIBATOMIC=yes) -AC_MSG_RESULT($GCC_ATOMIC_BUILTINS_NEED_LIBATOMIC) -if test "x$GCC_ATOMIC_BUILTINS_NEED_LIBATOMIC" = xyes; then - LDFLAGS="-latomic $LDFLAGS" -fi - -AC_ARG_ENABLE(install-unit-tests, AS_HELP_STRING([--enable-install-unit-tests],[Install the unit tests for running later (default no)]), - INSTALL_UNIT_TESTS=$enableval, INSTALL_UNIT_TESTS=no) -AC_SUBST(INSTALL_UNIT_TESTS) - -AC_ARG_WITH(check-bin-dir, AS_HELP_STRING([--with-check-bin-dir=PATH],[path to install unit tests for running later (defaults to $libexecdir/nix)]), - checkbindir=$withval, checkbindir=$libexecdir/nix) -AC_SUBST(checkbindir) - -AC_ARG_WITH(check-lib-dir, AS_HELP_STRING([--with-check-lib-dir=PATH],[path to install unit tests for running later (defaults to $libdir)]), - checklibdir=$withval, checklibdir=$libdir) -AC_SUBST(checklibdir) - -# LTO is currently broken with clang for unknown reasons; ld segfaults in the llvm plugin -AC_ARG_ENABLE(lto, AS_HELP_STRING([--enable-lto],[Enable LTO (only supported with GCC) [default=no]]), - lto=$enableval, lto=no) -if test "$lto" = yes; then - if $CXX --version | grep -q GCC; then - AC_SUBST(CXXLTO, [-flto=jobserver]) - else - echo "error: LTO is only supported with GCC at the moment" >&2 - exit 1 - fi -else - AC_SUBST(CXXLTO, [""]) -fi - -PKG_PROG_PKG_CONFIG - -AC_ARG_ENABLE(shared, AS_HELP_STRING([--enable-shared],[Build shared libraries for Nix [default=yes]]), - shared=$enableval, shared=yes) -if test "$shared" = yes; then - AC_SUBST(BUILD_SHARED_LIBS, 1, [Whether to build shared libraries.]) -else - AC_SUBST(BUILD_SHARED_LIBS, 0, [Whether to build shared libraries.]) - PKG_CONFIG="$PKG_CONFIG --static" -fi - -# Look for OpenSSL, a required dependency. FIXME: this is only (maybe) -# used by S3BinaryCacheStore. -PKG_CHECK_MODULES([OPENSSL], [libcrypto >= 1.1.1], [CXXFLAGS="$OPENSSL_CFLAGS $CXXFLAGS"]) - - -# Look for libarchive. -PKG_CHECK_MODULES([LIBARCHIVE], [libarchive >= 3.1.2], [CXXFLAGS="$LIBARCHIVE_CFLAGS $CXXFLAGS"]) -# Workaround until https://github.com/libarchive/libarchive/issues/1446 is fixed -if test "$shared" != yes; then - LIBARCHIVE_LIBS+=' -lz' -fi - -# Look for SQLite, a required dependency. -PKG_CHECK_MODULES([SQLITE3], [sqlite3 >= 3.6.19], [CXXFLAGS="$SQLITE3_CFLAGS $CXXFLAGS"]) - -# Look for libcurl, a required dependency. -PKG_CHECK_MODULES([LIBCURL], [libcurl], [CXXFLAGS="$LIBCURL_CFLAGS $CXXFLAGS"]) - -# Look for editline or readline, a required dependency. -# The the libeditline.pc file was added only in libeditline >= 1.15.2, -# see https://github.com/troglobit/editline/commit/0a8f2ef4203c3a4a4726b9dd1336869cd0da8607, -# Older versions are no longer supported. -AC_ARG_WITH( - [readline-flavor], - AS_HELP_STRING([--with-readline-flavor],[Which library to use for nice line editting with the Nix language REPL" [default=editline]]), - [readline_flavor=$withval], - [readline_flavor=editline]) -AS_CASE(["$readline_flavor"], - [editline], [ - readline_flavor_pc=libeditline - ], - [readline], [ - readline_flavor_pc=readline - AC_DEFINE([USE_READLINE], [1], [Use readline instead of editline]) - ], - [AC_MSG_ERROR([bad value "$readline_flavor" for --with-readline-flavor, must be one of: editline, readline])]) -PKG_CHECK_MODULES([EDITLINE], [$readline_flavor_pc], [CXXFLAGS="$EDITLINE_CFLAGS $CXXFLAGS"]) - -# Look for libsodium. -PKG_CHECK_MODULES([SODIUM], [libsodium], [CXXFLAGS="$SODIUM_CFLAGS $CXXFLAGS"]) - -# Look for libbrotli{enc,dec}. -PKG_CHECK_MODULES([LIBBROTLI], [libbrotlienc libbrotlidec], [CXXFLAGS="$LIBBROTLI_CFLAGS $CXXFLAGS"]) - -# Look for libcpuid. -have_libcpuid= -if test "$machine_name" = "x86_64"; then - AC_ARG_ENABLE([cpuid], - AS_HELP_STRING([--disable-cpuid], [Do not determine microarchitecture levels with libcpuid (relevant to x86_64 only)])) - if test "x$enable_cpuid" != "xno"; then - PKG_CHECK_MODULES([LIBCPUID], [libcpuid], - [CXXFLAGS="$LIBCPUID_CFLAGS $CXXFLAGS" - have_libcpuid=1 - AC_DEFINE([HAVE_LIBCPUID], [1], [Use libcpuid])] - ) - fi -fi -AC_SUBST(HAVE_LIBCPUID, [$have_libcpuid]) - - -# Look for libseccomp, required for Linux sandboxing. -case "$host_os" in - linux*) - AC_ARG_ENABLE([seccomp-sandboxing], - AS_HELP_STRING([--disable-seccomp-sandboxing],[Don't build support for seccomp sandboxing (only recommended if your arch doesn't support libseccomp yet!) - ])) - if test "x$enable_seccomp_sandboxing" != "xno"; then - PKG_CHECK_MODULES([LIBSECCOMP], [libseccomp], - [CXXFLAGS="$LIBSECCOMP_CFLAGS $CXXFLAGS" CFLAGS="$LIBSECCOMP_CFLAGS $CFLAGS"]) - have_seccomp=1 - AC_DEFINE([HAVE_SECCOMP], [1], [Whether seccomp is available and should be used for sandboxing.]) - AC_COMPILE_IFELSE([ - AC_LANG_SOURCE([[ - #include - #ifndef __SNR_fchmodat2 - # error "Missing support for fchmodat2" - #endif - ]]) - ], [], [ - echo "libseccomp is missing __SNR_fchmodat2. Please provide libseccomp 2.5.5 or later" - exit 1 - ]) - else - have_seccomp= - fi - ;; - *) - have_seccomp= - ;; -esac -AC_SUBST(HAVE_SECCOMP, [$have_seccomp]) - -# Optional dependencies for better normalizing file system data -AC_CHECK_HEADERS([sys/xattr.h]) -AS_IF([test "$ac_cv_header_sys_xattr_h" = "yes"],[ - AC_CHECK_FUNCS([llistxattr lremovexattr]) - AS_IF([test "$ac_cv_func_llistxattr" = "yes" && test "$ac_cv_func_lremovexattr" = "yes"],[ - AC_DEFINE([HAVE_ACL_SUPPORT], [1], [Define if we can manipulate file system Access Control Lists]) - ]) -]) - -# Look for aws-cpp-sdk-s3. -AC_LANG_PUSH(C++) -AC_CHECK_HEADERS([aws/s3/S3Client.h], - [AC_DEFINE([ENABLE_S3], [1], [Whether to enable S3 support via aws-sdk-cpp.]) enable_s3=1], - [AC_DEFINE([ENABLE_S3], [0], [Whether to enable S3 support via aws-sdk-cpp.]) enable_s3=]) -AC_SUBST(ENABLE_S3, [$enable_s3]) -AC_LANG_POP(C++) - - -# Whether to use the Boehm garbage collector. -AC_ARG_ENABLE(gc, AS_HELP_STRING([--enable-gc],[enable garbage collection in the Nix expression evaluator (requires Boehm GC) [default=yes]]), - gc=$enableval, gc=yes) -if test "$gc" = yes; then - PKG_CHECK_MODULES([BDW_GC], [bdw-gc]) - CXXFLAGS="$BDW_GC_CFLAGS $CXXFLAGS" - AC_DEFINE(HAVE_BOEHMGC, 1, [Whether to use the Boehm garbage collector.]) - - # See `fixupBoehmStackPointer`, for the integration between Boehm GC - # and Boost coroutines. - old_CFLAGS="$CFLAGS" - # Temporary set `-pthread` just for the next check - CFLAGS="$CFLAGS -pthread" - AC_CHECK_FUNCS([pthread_attr_get_np pthread_getattr_np]) - CFLAGS="$old_CFLAGS" -fi - -AS_IF([test "$ENABLE_UNIT_TESTS" == "yes"],[ - -# Look for gtest. -PKG_CHECK_MODULES([GTEST], [gtest_main gmock_main]) - -# Look for rapidcheck. -PKG_CHECK_MODULES([RAPIDCHECK], [rapidcheck rapidcheck_gtest]) - -]) - -# Look for nlohmann/json. -PKG_CHECK_MODULES([NLOHMANN_JSON], [nlohmann_json >= 3.9]) - - -# Look for lowdown library. -AC_ARG_ENABLE([markdown], AS_HELP_STRING([--enable-markdown], [Enable Markdown rendering in the Nix binary (requires lowdown) [default=auto]]), - enable_markdown=$enableval, enable_markdown=auto) -AS_CASE(["$enable_markdown"], - [yes | auto], [ - PKG_CHECK_MODULES([LOWDOWN], [lowdown >= 0.9.0], [ - CXXFLAGS="$LOWDOWN_CFLAGS $CXXFLAGS" - have_lowdown=1 - AC_DEFINE(HAVE_LOWDOWN, 1, [Whether lowdown is available and should be used for Markdown rendering.]) - ], [ - AS_IF([test "x$enable_markdown" == "xyes"], [AC_MSG_ERROR([--enable-markdown was specified, but lowdown was not found.])]) - ]) - ], - [no], [have_lowdown=], - [AC_MSG_ERROR([bad value "$enable_markdown" for --enable-markdown, must be one of: yes, no, auto])]) - - -# Look for libgit2. -PKG_CHECK_MODULES([LIBGIT2], [libgit2]) - - -# Look for toml11, a required dependency. -AC_LANG_PUSH(C++) -AC_CHECK_HEADER([toml.hpp], [], [AC_MSG_ERROR([toml11 is not found.])]) -AC_LANG_POP(C++) - -# Setuid installations. -AC_CHECK_FUNCS([setresuid setreuid lchown]) - - -# Nice to have, but not essential. -AC_CHECK_FUNCS([strsignal posix_fallocate sysconf]) - - -AC_ARG_WITH(sandbox-shell, AS_HELP_STRING([--with-sandbox-shell=PATH],[path of a statically-linked shell to use as /bin/sh in sandboxes]), - sandbox_shell=$withval) -AC_SUBST(sandbox_shell) -if test ${cross_compiling:-no} = no && ! test -z ${sandbox_shell+x}; then - AC_MSG_CHECKING([whether sandbox-shell has the standalone feature]) - # busybox shell sometimes allows executing other busybox applets, - # even if they are not in the path, breaking our sandbox - if PATH= $sandbox_shell -c "busybox" 2>&1 | grep -qv "not found"; then - AC_MSG_RESULT(enabled) - AC_MSG_ERROR([Please disable busybox FEATURE_SH_STANDALONE]) - else - AC_MSG_RESULT(disabled) - fi -fi - -AC_ARG_ENABLE(embedded-sandbox-shell, AS_HELP_STRING([--enable-embedded-sandbox-shell],[include the sandbox shell in the Nix binary [default=no]]), - embedded_sandbox_shell=$enableval, embedded_sandbox_shell=no) -AC_SUBST(embedded_sandbox_shell) -if test "$embedded_sandbox_shell" = yes; then - AC_DEFINE(HAVE_EMBEDDED_SANDBOX_SHELL, 1, [Include the sandbox shell in the Nix binary.]) -fi - -]) - - -# Expand all variables in config.status. -test "$prefix" = NONE && prefix=$ac_default_prefix -test "$exec_prefix" = NONE && exec_prefix='${prefix}' -for name in $ac_subst_vars; do - declare $name="$(eval echo "${!name}")" - declare $name="$(eval echo "${!name}")" - declare $name="$(eval echo "${!name}")" -done - -rm -f Makefile.config - -AC_CONFIG_HEADERS([config.h]) -AC_CONFIG_FILES([]) -AC_OUTPUT diff --git a/doc/manual/local.mk b/doc/manual/local.mk deleted file mode 100644 index 36cccc506..000000000 --- a/doc/manual/local.mk +++ /dev/null @@ -1,236 +0,0 @@ -# The version of Nix used to generate the doc. Can also be -# `$(nix_INSTALL_PATH)` or just `nix` (to grap ambient from the `PATH`), -# if one prefers. -doc_nix = $(nix_PATH) - -MANUAL_SRCS := \ - $(call rwildcard, $(d)/source, *.md) \ - $(call rwildcard, $(d)/source, */*.md) - -man-pages := $(foreach n, \ - nix-env.1 nix-store.1 \ - nix-build.1 nix-shell.1 nix-instantiate.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 \ - nix-profiles.5 \ -, $(d)/$(n)) - -# man pages for subcommands -# convert from `$(d)/source/command-ref/nix-{1}/{2}.md` to `$(d)/nix-{1}-{2}.1` -# FIXME: unify with how nix3-cli man pages are generated -man-pages += $(foreach subcommand, \ - $(filter-out %opt-common.md %env-common.md, $(wildcard $(d)/source/command-ref/nix-*/*.md)), \ - $(d)/$(subst /,-,$(subst $(d)/source/command-ref/,,$(subst .md,.1,$(subcommand))))) - -clean-files += $(d)/*.1 $(d)/*.5 $(d)/*.8 - -# Provide a dummy environment for nix, so that it will not access files outside the macOS sandbox. -# Set cores to 0 because otherwise `nix config show` resolves the cores based on the current machine -dummy-env = env -i \ - HOME=/dummy \ - NIX_CONF_DIR=/dummy \ - NIX_SSL_CERT_FILE=/dummy/no-ca-bundle.crt \ - NIX_STATE_DIR=/dummy \ - NIX_CONFIG='cores = 0' - -nix-eval = $(dummy-env) $(doc_nix) eval --experimental-features nix-command -I nix=doc/manual --store dummy:// --impure --raw - -# re-implement mdBook's include directive to make it usable for terminal output and for proper @docroot@ substitution -define process-includes - while read -r line; do \ - set -euo pipefail; \ - filename="$$(dirname $(1))/$$(sed 's/{{#include \(.*\)}}/\1/'<<< $$line)"; \ - test -f "$$filename" || ( echo "#include-d file '$$filename' does not exist." >&2; exit 1; ); \ - matchline="$$(sed 's|/|\\/|g' <<< $$line)"; \ - sed -i "/$$matchline/r $$filename" $(2); \ - sed -i "s/$$matchline//" $(2); \ - done < <(grep '{{#include' $(1)) -endef - -$(d)/nix-env-%.1: $(d)/source/command-ref/nix-env/%.md - @printf "Title: %s\n\n" "$(subst nix-env-,nix-env --,$$(basename "$@" .1))" > $^.tmp - $(render-subcommand) - -$(d)/nix-store-%.1: $(d)/source/command-ref/nix-store/%.md - @printf -- 'Title: %s\n\n' "$(subst nix-store-,nix-store --,$$(basename "$@" .1))" > $^.tmp - $(render-subcommand) - -# FIXME: there surely is some more deduplication to be achieved here with even darker Make magic -define render-subcommand - @cat $^ >> $^.tmp - @$(call process-includes,$^,$^.tmp) - $(trace-gen) lowdown -sT man --nroff-nolinks -M section=1 $^.tmp -o $@ - @# fix up `lowdown`'s automatic escaping of `--` - @# https://github.com/kristapsdz/lowdown/blob/edca6ce6d5336efb147321a43c47a698de41bb7c/entity.c#L202 - @sed -i 's/\e\[u2013\]/--/' $@ - @rm $^.tmp -endef - - -$(d)/%.1: $(d)/source/command-ref/%.md - @printf "Title: %s\n\n" "$$(basename $@ .1)" > $^.tmp - @cat $^ >> $^.tmp - @$(call process-includes,$^,$^.tmp) - $(trace-gen) lowdown -sT man --nroff-nolinks -M section=1 $^.tmp -o $@ - @rm $^.tmp - -$(d)/%.8: $(d)/source/command-ref/%.md - @printf "Title: %s\n\n" "$$(basename $@ .8)" > $^.tmp - @cat $^ >> $^.tmp - $(trace-gen) lowdown -sT man --nroff-nolinks -M section=8 $^.tmp -o $@ - @rm $^.tmp - -$(d)/nix.conf.5: $(d)/source/command-ref/conf-file.md - @printf "Title: %s\n\n" "$$(basename $@ .5)" > $^.tmp - @cat $^ >> $^.tmp - @$(call process-includes,$^,$^.tmp) - $(trace-gen) lowdown -sT man --nroff-nolinks -M section=5 $^.tmp -o $@ - @rm $^.tmp - -$(d)/nix-profiles.5: $(d)/source/command-ref/files/profiles.md - @printf "Title: %s\n\n" "$$(basename $@ .5)" > $^.tmp - @cat $^ >> $^.tmp - $(trace-gen) lowdown -sT man --nroff-nolinks -M section=5 $^.tmp -o $@ - @rm $^.tmp - -$(d)/source/SUMMARY.md: $(d)/source/SUMMARY.md.in $(d)/source/SUMMARY-rl-next.md $(d)/source/store/types $(d)/source/command-ref/new-cli $(d)/source/development/experimental-feature-descriptions.md - @cp $< $@ - @$(call process-includes,$@,$@) - -$(d)/source/store/types: $(d)/nix.json $(d)/utils.nix $(d)/generate-store-info.nix $(d)/generate-store-types.nix $(d)/source/store/types/index.md.in $(doc_nix) - @# FIXME: build out of tree! - @rm -rf $@.tmp - $(trace-gen) $(nix-eval) --write-to $@.tmp --expr 'import doc/manual/generate-store-types.nix (builtins.fromJSON (builtins.readFile $<)).stores' - @# do not destroy existing contents - @mv $@.tmp/* $@/ - -$(d)/source/command-ref/new-cli: $(d)/nix.json $(d)/utils.nix $(d)/generate-manpage.nix $(d)/generate-settings.nix $(d)/generate-store-info.nix $(doc_nix) - @rm -rf $@ $@.tmp - $(trace-gen) $(nix-eval) --write-to $@.tmp --expr 'import doc/manual/generate-manpage.nix true (builtins.readFile $<)' - @mv $@.tmp $@ - -$(d)/source/command-ref/conf-file.md: $(d)/conf-file.json $(d)/utils.nix $(d)/generate-settings.nix $(d)/source/command-ref/conf-file-prefix.md $(d)/source/command-ref/experimental-features-shortlist.md $(doc_nix) - @cat doc/manual/source/command-ref/conf-file-prefix.md > $@.tmp - $(trace-gen) $(nix-eval) --expr 'import doc/manual/generate-settings.nix { prefix = "conf"; } (builtins.fromJSON (builtins.readFile $<))' >> $@.tmp; - @mv $@.tmp $@ - -$(d)/nix.json: $(doc_nix) - $(trace-gen) $(dummy-env) $(doc_nix) __dump-cli > $@.tmp - @mv $@.tmp $@ - -$(d)/conf-file.json: $(doc_nix) - $(trace-gen) $(dummy-env) $(doc_nix) config show --json --experimental-features nix-command > $@.tmp - @mv $@.tmp $@ - -$(d)/source/development/experimental-feature-descriptions.md: $(d)/xp-features.json $(d)/utils.nix $(d)/generate-xp-features.nix $(doc_nix) - @rm -rf $@ $@.tmp - $(trace-gen) $(nix-eval) --write-to $@.tmp --expr 'import doc/manual/generate-xp-features.nix (builtins.fromJSON (builtins.readFile $<))' - @mv $@.tmp $@ - -$(d)/source/command-ref/experimental-features-shortlist.md: $(d)/xp-features.json $(d)/utils.nix $(d)/generate-xp-features-shortlist.nix $(doc_nix) - @rm -rf $@ $@.tmp - $(trace-gen) $(nix-eval) --write-to $@.tmp --expr 'import doc/manual/generate-xp-features-shortlist.nix (builtins.fromJSON (builtins.readFile $<))' - @mv $@.tmp $@ - -$(d)/xp-features.json: $(doc_nix) - $(trace-gen) $(dummy-env) $(doc_nix) __dump-xp-features > $@.tmp - @mv $@.tmp $@ - -$(d)/source/language/builtins.md: $(d)/language.json $(d)/generate-builtins.nix $(d)/source/language/builtins-prefix.md $(doc_nix) - @cat doc/manual/source/language/builtins-prefix.md > $@.tmp - $(trace-gen) $(nix-eval) --expr 'import doc/manual/generate-builtins.nix (builtins.fromJSON (builtins.readFile $<))' >> $@.tmp; - @cat doc/manual/source/language/builtins-suffix.md >> $@.tmp - @mv $@.tmp $@ - -$(d)/language.json: $(doc_nix) - $(trace-gen) $(dummy-env) $(doc_nix) __dump-language > $@.tmp - @mv $@.tmp $@ - -# Generate "Upcoming release" notes (or clear it and remove from menu) -$(d)/source/release-notes/rl-next.md: $(d)/rl-next $(d)/rl-next/* - @if type -p changelog-d > /dev/null; then \ - echo " GEN " $@; \ - changelog-d doc/manual/rl-next > $@; \ - else \ - echo " NULL " $@; \ - true > $@; \ - fi - -$(d)/source/SUMMARY-rl-next.md: $(d)/source/release-notes/rl-next.md - $(trace-gen) true - @if [ -s $< ]; then \ - echo ' - [Upcoming release](release-notes/rl-next.md)' > $@; \ - else \ - true > $@; \ - fi - -# Generate the HTML manual. -.PHONY: manual-html -manual-html: $(docdir)/manual/index.html - -# Open the built HTML manual in the default browser. -manual-html-open: $(docdir)/manual/index.html - @echo " OPEN " $<; \ - xdg-open $< \ - || open $< \ - || { \ - echo "Could not open the manual in a browser. Please open '$<'" >&2; \ - false; \ - } -install: $(docdir)/manual/index.html - -# Generate 'nix' manpages. -.PHONY: manpages -manpages: $(mandir)/man1/nix3-manpages -install: $(mandir)/man1/nix3-manpages -man: doc/manual/generated/man1/nix3-manpages -all: doc/manual/generated/man1/nix3-manpages - -# FIXME: unify with how the other man pages are generated. -# this one works differently and does not use any of the amenities provided by `/mk/lib.mk`. -$(mandir)/man1/nix3-manpages: doc/manual/generated/man1/nix3-manpages - @mkdir -p $(DESTDIR)$$(dirname $@) - $(trace-install) install -m 0644 $$(dirname $<)/* $(DESTDIR)$$(dirname $@) - -doc/manual/generated/man1/nix3-manpages: $(d)/source/command-ref/new-cli - @mkdir -p $(DESTDIR)$$(dirname $@) - $(trace-gen) for i in doc/manual/source/command-ref/new-cli/*.md; do \ - name=$$(basename $$i .md); \ - tmpFile=$$(mktemp); \ - if [[ $$name = SUMMARY ]]; then continue; fi; \ - printf "Title: %s\n\n" "$$name" > $$tmpFile; \ - cat $$i >> $$tmpFile; \ - lowdown -sT man --nroff-nolinks -M section=1 $$tmpFile -o $(DESTDIR)$$(dirname $@)/$$name.1; \ - rm $$tmpFile; \ - done - @touch $@ - -# the `! -name 'documentation.md'` filter excludes the one place where -# `@docroot@` is to be preserved for documenting the mechanism -# FIXME: maybe contributing guides should live right next to the code -# instead of in the manual -$(docdir)/manual/index.html: $(MANUAL_SRCS) $(d)/book.toml $(d)/anchors.jq $(d)/custom.css $(d)/source/SUMMARY.md $(d)/source/store/types $(d)/source/command-ref/new-cli $(d)/source/development/experimental-feature-descriptions.md $(d)/source/command-ref/conf-file.md $(d)/source/language/builtins.md $(d)/source/release-notes/rl-next.md $(d)/source/figures $(d)/source/favicon.png $(d)/source/favicon.svg - $(trace-gen) \ - tmp="$$(mktemp -d)"; \ - cp -r doc/manual "$$tmp"; \ - find "$$tmp" -name '*.md' | while read -r file; do \ - $(call process-includes,$$file,$$file); \ - done; \ - find "$$tmp" -name '*.md' ! -name 'documentation.md' | while read -r file; do \ - docroot="$$(realpath --relative-to="$$(dirname "$$file")" $$tmp/manual/source)"; \ - sed -i "s,@docroot@,$$docroot,g" "$$file"; \ - done; \ - set -euo pipefail; \ - ( \ - cd "$$tmp/manual"; \ - RUST_LOG=warn \ - MDBOOK_SUBSTITUTE_SEARCH=$(d)/source \ - mdbook build -d $(DESTDIR)$(docdir)/manual.tmp 2>&1 \ - | { grep -Fv "because fragment resolution isn't implemented" || :; } \ - ); \ - rm -rf "$$tmp/manual" - @rm -rf $(DESTDIR)$(docdir)/manual - @mv $(DESTDIR)$(docdir)/manual.tmp/html $(DESTDIR)$(docdir)/manual - @rm -rf $(DESTDIR)$(docdir)/manual.tmp diff --git a/doc/manual/rl-next/add-nix-state-home.md b/doc/manual/rl-next/add-nix-state-home.md deleted file mode 100644 index bbfdd5d38..000000000 --- a/doc/manual/rl-next/add-nix-state-home.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -synopsis: Use envvars NIX_CACHE_HOME, NIX_CONFIG_HOME, NIX_DATA_HOME, NIX_STATE_HOME if defined -prs: [11351] ---- - -Added new environment variables: - -- `NIX_CACHE_HOME` -- `NIX_CONFIG_HOME` -- `NIX_DATA_HOME` -- `NIX_STATE_HOME` - -Each, if defined, takes precedence over the corresponding [XDG environment variable](@docroot@/command-ref/env-common.md#xdg-base-directories). -This provides more fine-grained control over where Nix looks for files, and allows to have a stand-alone Nix environment, which only uses files in a specific directory, and doesn't interfere with the user environment. diff --git a/doc/manual/rl-next/ban-integer-overflow.md b/doc/manual/rl-next/ban-integer-overflow.md deleted file mode 100644 index 0e553af76..000000000 --- a/doc/manual/rl-next/ban-integer-overflow.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -synopsis: Define integer overflow in the Nix language as an error -issues: [10968] -prs: [11188] ---- - -Previously, integer overflow in the Nix language invoked C++ level signed overflow, which was undefined behaviour, but *usually* manifested as wrapping around on overflow. - -Since prior to the public release of Lix, Lix had C++ signed overflow defined to crash the process and nobody noticed this having accidentally removed overflow from the Nix language for three months until it was caught by fiddling around. -Given the significant body of actual Nix code that has been evaluated by Lix in that time, it does not appear that nixpkgs or much of importance depends on integer overflow, so it appears safe to turn into an error. - -Some other overflows were fixed: -- `builtins.fromJSON` of values greater than the maximum representable value in a signed 64-bit integer will generate an error. -- `nixConfig` in flakes will no longer accept negative values for configuration options. - -Integer overflow now looks like the following: - -``` -$ nix eval --expr '9223372036854775807 + 1' -error: integer overflow in adding 9223372036854775807 + 1 -``` diff --git a/doc/manual/rl-next/build-hook-default.md b/doc/manual/rl-next/build-hook-default.md deleted file mode 100644 index f13537983..000000000 --- a/doc/manual/rl-next/build-hook-default.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -synopsis: |- - The `build-hook` setting's default is less useful when using `libnixstore` as a library -prs: -- 11178 ---- - -*This is an obscure issue that only affects usage of the `libnixstore` library outside of the Nix executable.* - -As part the ongoing [rewrite of the build system](https://github.com/NixOS/nix/issues/2503) to use [Meson](https://mesonbuild.com/), we are also switching to packaging individual Nix components separately (and building them in separate derivations). -This means that when building `libnixstore` we do not know where the Nix binaries will be installed --- `libnixstore` doesn't know about downstream consumers like the Nix binaries at all. - -*This is also unrelated to the _`post`_-`build-hook`*, which is often used for pushing to a cache.* - -This has a small adverse affect on remote building --- the `build-remote` executable that is specified from the [`build-hook`](@docroot@/command-ref/conf-file.md#conf-build-hook) setting will not be gotten from the (presumed) installation location, but instead looked up on the `PATH`. -This means that other applications linking `libnixstore` that wish to use remote building must arrange for the `nix` command to be on the PATH (or manually overriding `build-hook`) in order for that to work. - -Long term we don't envision this being a downside, because we plan to [get rid of `build-remote` and the build hook setting entirely](https://github.com/NixOS/nix/issues/1221). -There should simply be no need to have an extra, intermediate layer of remote-procedure-calling when we want to connect to a remote builder. -The build hook protocol did in principle support custom ways of remote building, but that can also be accomplished with a custom service for the ssh or daemon/ssh-ng protocols, or with a custom [store type](@docroot@/store/types/index.md) i.e. `Store` subclass. - -The Perl bindings no longer expose `getBinDir` either, since the underlying C++ libraries those bindings wrap no longer know the location of installed binaries as described above. diff --git a/doc/manual/rl-next/filesystem-errors.md b/doc/manual/rl-next/filesystem-errors.md deleted file mode 100644 index 2d5b26228..000000000 --- a/doc/manual/rl-next/filesystem-errors.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -synopsis: wrap filesystem exceptions more correctly -issues: [] -prs: [11378] ---- - - -With the switch to `std::filesystem` in different places, Nix started to throw `std::filesystem::filesystem_error` in many places instead of its own exceptions. - -This lead to no longer generating error traces, for example when listing a non-existing directory, and can also lead to crashes inside the Nix REPL. - -This version catches these types of exception correctly and wrap them into Nix's own exeception type. - -Author: [**@Mic92**](https://github.com/Mic92) diff --git a/doc/manual/rl-next/fsync-store-paths.md b/doc/manual/rl-next/fsync-store-paths.md deleted file mode 100644 index 0e9e7f7f2..000000000 --- a/doc/manual/rl-next/fsync-store-paths.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -synopsis: Add setting `fsync-store-paths` -issues: [1218] -prs: [7126] ---- - -Nix now has a setting `fsync-store-paths` that ensures that new store paths are durably written to disk before they are registered as "valid" in Nix's database. This can prevent Nix store corruption if the system crashes or there is a power loss. This setting defaults to `false`. - -Author: [**@squalus**](https://github.com/squalus) diff --git a/doc/manual/rl-next/nix-flake-show-description.md b/doc/manual/rl-next/nix-flake-show-description.md deleted file mode 100644 index 7feb08483..000000000 --- a/doc/manual/rl-next/nix-flake-show-description.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -synopsis: Show package descriptions with `nix flake show` -issues: [10977] -prs: [10980] ---- - -`nix flake show` will now display a package's `meta.description` if it exists. If the description does not fit in the terminal it will be truncated to fit the terminal width. If the size of the terminal width is unknown the description will be capped at 80 characters. - -``` -$ nix flake show -└───packages - └───x86_64-linux - ├───builderImage: package 'docker-image-ara-builder-image.tar.gz' - 'Docker image hosting the nix build environment' - └───runnerImage: package 'docker-image-gitlab-runner.tar.gz' - 'Docker image hosting the gitlab-runner executable' -``` - -In a narrower terminal: - -``` -$ nix flake show -└───packages - └───x86_64-linux - ├───builderImage: package 'docker-image-ara-builder-image.tar.gz' - 'Docker image hosting the nix b... - └───runnerImage: package 'docker-image-gitlab-runner.tar.gz' - 'Docker image hosting the gitlab-run... -``` diff --git a/doc/manual/rl-next/nix-fmt-default-argument.md b/doc/manual/rl-next/nix-fmt-default-argument.md deleted file mode 100644 index 54161ab30..000000000 --- a/doc/manual/rl-next/nix-fmt-default-argument.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -synopsis: Removing the default argument passed to the `nix fmt` formatter -issues: [] -prs: [11438] ---- - -The underlying formatter no longer receives the ". " default argument when `nix fmt` is called with no arguments. - -This change was necessary as the formatter wasn't able to distinguish between -a user wanting to format the current folder with `nix fmt .` or the generic -`nix fmt`. - -The default behaviour is now the responsibility of the formatter itself, and -allows tools such as treefmt to format the whole tree instead of only the -current directory and below. - -Author: [**@zimbatm**](https://github.com/zimbatm) diff --git a/doc/manual/rl-next/no-flake-substitution.md b/doc/manual/rl-next/no-flake-substitution.md deleted file mode 100644 index 67ec58750..000000000 --- a/doc/manual/rl-next/no-flake-substitution.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -synopsis: Flakes are no longer substituted -prs: [10612] ---- - -Nix will no longer attempt to substitute the source code of flakes from a binary cache. This functionality was broken because it could lead to different evaluation results depending on whether the flake was available in the binary cache, or even depending on whether the flake was already in the local store. - -Author: [**@edolstra**](https://github.com/edolstra) diff --git a/doc/manual/rl-next/verify-tls.md b/doc/manual/rl-next/verify-tls.md deleted file mode 100644 index afc689f46..000000000 --- a/doc/manual/rl-next/verify-tls.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -synopsis: "`` uses TLS verification" -prs: [11585] ---- - -Previously `` did not do TLS verification. This was because the Nix sandbox in the past did not have access to TLS certificates, and Nix checks the hash of the fetched file anyway. However, this can expose authentication data from `netrc` and URLs to man-in-the-middle attackers. In addition, Nix now in some cases (such as when using impure derivations) does *not* check the hash. Therefore we have now enabled TLS verification. This means that downloads by `` will now fail if you're fetching from a HTTPS server that does not have a valid certificate. - -`` is also known as the builtin derivation builder `builtin:fetchurl`. It's not to be confused with the evaluation-time function `builtins.fetchurl`, which was not affected by this issue. diff --git a/doc/manual/source/SUMMARY.md.in b/doc/manual/source/SUMMARY.md.in index d7c312ae7..244bf582d 100644 --- a/doc/manual/source/SUMMARY.md.in +++ b/doc/manual/source/SUMMARY.md.in @@ -130,6 +130,7 @@ - [Contributing](development/contributing.md) - [Releases](release-notes/index.md) {{#include ./SUMMARY-rl-next.md}} + - [Release 2.25 (2024-11-07)](release-notes/rl-2.25.md) - [Release 2.24 (2024-07-31)](release-notes/rl-2.24.md) - [Release 2.23 (2024-06-03)](release-notes/rl-2.23.md) - [Release 2.22 (2024-04-23)](release-notes/rl-2.22.md) diff --git a/doc/manual/source/command-ref/nix-collect-garbage.md b/doc/manual/source/command-ref/nix-collect-garbage.md index 2136d28e9..bd05f2816 100644 --- a/doc/manual/source/command-ref/nix-collect-garbage.md +++ b/doc/manual/source/command-ref/nix-collect-garbage.md @@ -36,7 +36,7 @@ Instead, it looks in a few locations, and acts on all profiles it finds there: > > Not stable; subject to change > - > Do not rely on this functionality; it just exists for migration purposes and is may change in the future. + > Do not rely on this functionality; it just exists for migration purposes and may change in the future. > These deprecated paths remain a private implementation detail of Nix. `$NIX_STATE_DIR/profiles` and `$NIX_STATE_DIR/profiles/per-user`. diff --git a/doc/manual/source/development/building.md b/doc/manual/source/development/building.md index dbf080296..409294682 100644 --- a/doc/manual/source/development/building.md +++ b/doc/manual/source/development/building.md @@ -35,20 +35,20 @@ To build Nix itself in this shell: ```console [nix-shell]$ mesonFlags+=" --prefix=$(pwd)/outputs/out" -[nix-shell]$ dontAddPrefix=1 mesonConfigurePhase -[nix-shell]$ ninjaBuildPhase +[nix-shell]$ dontAddPrefix=1 configurePhase +[nix-shell]$ buildPhase ``` To test it: ```console -[nix-shell]$ mesonCheckPhase +[nix-shell]$ checkPhase ``` To install it in `$(pwd)/outputs`: ```console -[nix-shell]$ ninjaInstallPhase +[nix-shell]$ installPhase [nix-shell]$ ./outputs/out/bin/nix --version nix (Nix) 2.12 ``` @@ -90,20 +90,20 @@ $ nix develop .#native-clangStdenvPackages To build Nix itself in this shell: ```console -[nix-shell]$ mesonConfigurePhase -[nix-shell]$ ninjaBuildPhase +[nix-shell]$ configurePhase +[nix-shell]$ buildPhase ``` To test it: ```console -[nix-shell]$ mesonCheckPhase +[nix-shell]$ checkPhase ``` To install it in `$(pwd)/outputs`: ```console -[nix-shell]$ ninjaInstallPhase +[nix-shell]$ installPhase [nix-shell]$ nix --version nix (Nix) 2.12 ``` @@ -167,7 +167,7 @@ It is useful to perform multiple cross and native builds on the same source tree for example to ensure that better support for one platform doesn't break the build for another. Meson thankfully makes this very easy by confining all build products to the build directory --- one simple shares the source directory between multiple build directories, each of which contains the build for Nix to a different platform. -Nixpkgs's `mesonConfigurePhase` always chooses `build` in the current directory as the name and location of the build. +Nixpkgs's `configurePhase` always chooses `build` in the current directory as the name and location of the build. This makes having multiple build directories slightly more inconvenient. The good news is that Meson/Ninja seem to cope well with relocating the build directory after it is created. @@ -176,13 +176,13 @@ Here's how to do that 1. Configure as usual ```bash - mesonConfigurePhase + configurePhase ``` 2. Rename the build directory ```bash - cd .. # since `mesonConfigurePhase` cd'd inside + cd .. # since `configurePhase` cd'd inside mv build build-linux # or whatever name we want cd build-linux ``` @@ -190,7 +190,7 @@ Here's how to do that 3. Build as usual ```bash - ninjaBuildPhase + buildPhase ``` > **N.B.** diff --git a/doc/manual/source/development/documentation.md b/doc/manual/source/development/documentation.md index d51373e7b..2e188f232 100644 --- a/doc/manual/source/development/documentation.md +++ b/doc/manual/source/development/documentation.md @@ -203,7 +203,7 @@ $ xdg-open ./result/share/doc/nix/internal-api/html/index.html or inside `nix-shell` or `nix develop`: ```console -$ mesonConfigurePhase +$ configurePhase $ ninja src/internal-api-docs/html $ xdg-open src/internal-api-docs/html/index.html ``` @@ -224,7 +224,7 @@ $ xdg-open ./result/share/doc/nix/external-api/html/index.html or inside `nix-shell` or `nix develop`: ``` -$ mesonConfigurePhase +$ configurePhase $ ninja src/external-api-docs/html $ xdg-open src/external-api-docs/html/index.html ``` diff --git a/doc/manual/source/development/testing.md b/doc/manual/source/development/testing.md index 9d228fd16..30aa7d0d5 100644 --- a/doc/manual/source/development/testing.md +++ b/doc/manual/source/development/testing.md @@ -29,7 +29,7 @@ The unit tests are defined using the [googletest] and [rapidcheck] frameworks. > ``` > src > ├── libexpr -> │ ├── local.mk +> │ ├── meson.build > │ ├── value/context.hh > │ ├── value/context.cc > │ … @@ -37,25 +37,24 @@ The unit tests are defined using the [googletest] and [rapidcheck] frameworks. > ├── tests > │ │ > │ … -> │ └── unit -> │ ├── libutil -> │ │ ├── local.mk -> │ │ … -> │ │ └── data -> │ │ ├── git/tree.txt -> │ │ … -> │ │ -> │ ├── libexpr-support -> │ │ ├── local.mk -> │ │ └── tests -> │ │ ├── value/context.hh -> │ │ ├── value/context.cc -> │ │ … -> │ │ -> │ ├── libexpr -> │ … ├── local.mk -> │ ├── value/context.cc -> │ … +> │ ├── libutil-tests +> │ │ ├── meson.build +> │ │ … +> │ │ └── data +> │ │ ├── git/tree.txt +> │ │ … +> │ │ +> │ ├── libexpr-test-support +> │ │ ├── meson.build +> │ │ └── tests +> │ │ ├── value/context.hh +> │ │ ├── value/context.cc +> │ │ … +> │ │ +> │ ├── libexpr-tests +> │ … ├── meson.build +> │ ├── value/context.cc +> │ … > … > ``` @@ -128,7 +127,7 @@ On other platforms they wouldn't be run at all. ## Functional tests -The functional tests reside under the `tests/functional` directory and are listed in `tests/functional/local.mk`. +The functional tests reside under the `tests/functional` directory and are listed in `tests/functional/meson.build`. Each test is a bash script. Functional tests are run during `installCheck` in the `nix` package build, as well as separately from the build, in VM tests. @@ -138,7 +137,7 @@ Functional tests are run during `installCheck` in the `nix` package build, as we The whole test suite (functional and unit tests) can be run with: ```shell-session -$ mesonCheckPhase +$ checkPhase ``` ### Grouping tests diff --git a/doc/manual/source/installation/installing-docker.md b/doc/manual/source/installation/installing-docker.md index 6f77d6a57..9354c1a72 100644 --- a/doc/manual/source/installation/installing-docker.md +++ b/doc/manual/source/installation/installing-docker.md @@ -57,3 +57,21 @@ $ nix build ./\#hydraJobs.dockerImage.x86_64-linux $ docker load -i ./result/image.tar.gz $ docker run -ti nix:2.5pre20211105 ``` + +# Docker image with non-root Nix + +If you would like to run Nix in a container under a user other than `root`, +you can build an image with a non-root single-user installation of Nix +by specifying the `uid`, `gid`, `uname`, and `gname` arguments to `docker.nix`: + +```console +$ nix build --file docker.nix \ + --arg uid 1000 \ + --arg gid 1000 \ + --argstr uname user \ + --argstr gname user \ + --argstr name nix-user \ + --out-link nix-user.tar.gz +$ docker load -i nix-user.tar.gz +$ docker run -ti nix-user +``` diff --git a/doc/manual/source/release-notes/rl-2.25.md b/doc/manual/source/release-notes/rl-2.25.md new file mode 100644 index 000000000..29e3e509c --- /dev/null +++ b/doc/manual/source/release-notes/rl-2.25.md @@ -0,0 +1,144 @@ +# Release 2.25.0 (2024-11-07) + +- New environment variables to override XDG locations [#11351](https://github.com/NixOS/nix/pull/11351) + + Added new environment variables: + + - `NIX_CACHE_HOME` + - `NIX_CONFIG_HOME` + - `NIX_DATA_HOME` + - `NIX_STATE_HOME` + + Each, if defined, takes precedence over the corresponding [XDG environment variable](@docroot@/command-ref/env-common.md#xdg-base-directories). + This provides more fine-grained control over where Nix looks for files. It allows having a stand-alone Nix environment that only uses files in a specific directory and that doesn't interfere with the user environment. + +- Define integer overflow in the Nix language as an error [#10968](https://github.com/NixOS/nix/issues/10968) [#11188](https://github.com/NixOS/nix/pull/11188) + + Previously, integer overflow in the Nix language invoked C++ level signed overflow, which manifested as wrapping around on overflow. It now looks like this: + + ``` + $ nix eval --expr '9223372036854775807 + 1' + error: integer overflow in adding 9223372036854775807 + 1 + ``` + + Some other overflows were fixed: + - `builtins.fromJSON` of values greater than the maximum representable value in a signed 64-bit integer will generate an error. + - `nixConfig` in flakes will no longer accept negative values for configuration options. + +- The `build-hook` setting no longer has a useful default when using `libnixstore` as a library [#11178](https://github.com/NixOS/nix/pull/11178) + + *This is an obscure issue that only affects usage of the `libnixstore` library outside of the Nix executable. It is unrelated to the `post-build-hook` settings, which is often used for pushing to a cache.* + + As part the ongoing [rewrite of the build system](https://github.com/NixOS/nix/issues/2503) to use [Meson](https://mesonbuild.com/), we are also switching to packaging individual Nix components separately (and building them in separate derivations). + This means that when building `libnixstore` we do not know where the Nix binaries will be installed --- `libnixstore` doesn't know about downstream consumers like the Nix binaries at all. + + This has a small adverse affect on remote building --- the `build-remote` executable that is specified from the [`build-hook`](@docroot@/command-ref/conf-file.md#conf-build-hook) setting will not be gotten from the (presumed) installation location, but instead looked up on the `PATH`. + This means that other applications linking `libnixstore` that wish to use remote building must arrange for the `nix` command to be on the PATH (or manually overriding `build-hook`) in order for that to work. + + Long term we don't envision this being a downside, because we plan to [get rid of `build-remote` and the build hook setting entirely](https://github.com/NixOS/nix/issues/1221). + There should simply be no need to have an extra, intermediate layer of remote-procedure-calling when we want to connect to a remote builder. + The build hook protocol did in principle support custom ways of remote building, but that can also be accomplished with a custom service for the ssh or daemon/ssh-ng protocols, or with a custom [store type](@docroot@/store/types/index.md) i.e. `Store` subclass. + + The Perl bindings no longer expose `getBinDir` either, since the underlying C++ libraries those bindings wrap no longer know the location of installed binaries as described above. + +- Wrap filesystem exceptions more correctly [#11378](https://github.com/NixOS/nix/pull/11378) + + With the switch to `std::filesystem` in different places, Nix started to throw `std::filesystem::filesystem_error` in many places instead of its own exceptions. + As a result, Nix no longer generated error traces when (for example) listing a non-existing directory. It could also lead to crashes inside the Nix REPL. + + This version catches these types of exception correctly and wraps them into Nix's own exception type. + + Author: [**@Mic92**](https://github.com/Mic92) + +- Add setting `fsync-store-paths` [#1218](https://github.com/NixOS/nix/issues/1218) [#7126](https://github.com/NixOS/nix/pull/7126) + + Nix now has a setting `fsync-store-paths` that ensures that new store paths are durably written to disk before they are registered as "valid" in Nix's database. This can prevent Nix store corruption if the system crashes or there is a power loss. This setting defaults to `false`. + + Author: [**@squalus**](https://github.com/squalus) + +- Removing the default argument passed to the `nix fmt` formatter [#11438](https://github.com/NixOS/nix/pull/11438) + + The underlying formatter no longer receives the "." default argument when `nix fmt` is called with no arguments. + + This change was necessary as the formatter wasn't able to distinguish between + a user wanting to format the current folder with `nix fmt .` or the generic + `nix fmt`. + + The default behavior is now the responsibility of the formatter itself, and + allows tools such as `treefmt` to format the whole tree instead of only the + current directory and below. + + Author: [**@zimbatm**](https://github.com/zimbatm) + +- `` uses TLS verification [#11585](https://github.com/NixOS/nix/pull/11585) + + Previously `` did not do TLS verification. This was because the Nix sandbox in the past did not have access to TLS certificates, and Nix checks the hash of the fetched file anyway. However, this can expose authentication data from `netrc` and URLs to man-in-the-middle attackers. In addition, Nix now in some cases (such as when using impure derivations) does *not* check the hash. Therefore we have now enabled TLS verification. This means that downloads by `` will now fail if you're fetching from a HTTPS server that does not have a valid certificate. + + `` is also known as the builtin derivation builder `builtin:fetchurl`. It's not to be confused with the evaluation-time function `builtins.fetchurl`, which was not affected by this issue. + + +# Contributors + +This release was made possible by the following 58 contributors: + +- 1444 [**(@0x5a4)**](https://github.com/0x5a4) +- Adrian Hesketh [**(@a-h)**](https://github.com/a-h) +- Aleksana [**(@Aleksanaa)**](https://github.com/Aleksanaa) +- Alyssa Ross [**(@alyssais)**](https://github.com/alyssais) +- Andrew Marshall [**(@amarshall)**](https://github.com/amarshall) +- Artemis Tosini [**(@artemist)**](https://github.com/artemist) +- Artturin [**(@Artturin)**](https://github.com/Artturin) +- Bjørn Forsman [**(@bjornfor)**](https://github.com/bjornfor) +- Brian McGee [**(@brianmcgee)**](https://github.com/brianmcgee) +- Brian McKenna [**(@puffnfresh)**](https://github.com/puffnfresh) +- Bryan Honof [**(@bryanhonof)**](https://github.com/bryanhonof) +- Cole Helbling [**(@cole-h)**](https://github.com/cole-h) +- Eelco Dolstra [**(@edolstra)**](https://github.com/edolstra) +- Eman Resu [**(@llakala)**](https://github.com/llakala) +- Emery Hemingway [**(@ehmry)**](https://github.com/ehmry) +- Emil Petersen [**(@leetemil)**](https://github.com/leetemil) +- Emily [**(@emilazy)**](https://github.com/emilazy) +- Geoffrey Thomas [**(@geofft)**](https://github.com/geofft) +- Gerg-L [**(@Gerg-L)**](https://github.com/Gerg-L) +- Ivan Tkachev +- Jacek Galowicz [**(@tfc)**](https://github.com/tfc) +- Jan Hrcek [**(@jhrcek)**](https://github.com/jhrcek) +- Jason Yundt [**(@Jayman2000)**](https://github.com/Jayman2000) +- Jeremy Kerfs [**(@jkerfs)**](https://github.com/jkerfs) +- Jeremy Kolb [**(@kjeremy)**](https://github.com/kjeremy) +- John Ericson [**(@Ericson2314)**](https://github.com/Ericson2314) +- Jonas Chevalier [**(@zimbatm)**](https://github.com/zimbatm) +- Jordan Justen [**(@jljusten)**](https://github.com/jljusten) +- Josh Heinrichs [**(@joshheinrichs-shopify)**](https://github.com/joshheinrichs-shopify) +- Jörg Thalheim [**(@Mic92)**](https://github.com/Mic92) +- Kevin Cox [**(@kevincox)**](https://github.com/kevincox) +- Michael Gallagher [**(@mjgallag)**](https://github.com/mjgallag) +- Michael [**(@michaelvanstraten)**](https://github.com/michaelvanstraten) +- Nikodem Rabuliński [**(@nrabulinski)**](https://github.com/nrabulinski) +- Noam Yorav-Raphael [**(@noamraph)**](https://github.com/noamraph) +- Onni Hakala [**(@onnimonni)**](https://github.com/onnimonni) +- Parker Hoyes [**(@parkerhoyes)**](https://github.com/parkerhoyes) +- Philipp Otterbein +- Pol Dellaiera [**(@drupol)**](https://github.com/drupol) +- Robert Hensing [**(@roberth)**](https://github.com/roberth) +- Ryan Hendrickson [**(@rhendric)**](https://github.com/rhendric) +- Sandro [**(@SuperSandro2000)**](https://github.com/SuperSandro2000) +- Seggy Umboh [**(@secobarbital)**](https://github.com/secobarbital) +- Sergei Zimmerman [**(@xokdvium)**](https://github.com/xokdvium) +- Shivaraj B H [**(@shivaraj-bh)**](https://github.com/shivaraj-bh) +- Siddhant Kumar [**(@siddhantk232)**](https://github.com/siddhantk232) +- Tim [**(@Jaculabilis)**](https://github.com/Jaculabilis) +- Tom Bereknyei +- Travis A. Everett [**(@abathur)**](https://github.com/abathur) +- Valentin Gagarin [**(@fricklerhandwerk)**](https://github.com/fricklerhandwerk) +- Vinayak Kaushik [**(@VinayakKaushikDH)**](https://github.com/VinayakKaushikDH) +- Yann Hamdaoui [**(@yannham)**](https://github.com/yannham) +- Yuriy Taraday [**(@YorikSar)**](https://github.com/YorikSar) +- bryango [**(@bryango)**](https://github.com/bryango) +- emhamm [**(@emhamm)**](https://github.com/emhamm) +- jade [**(@lf-)**](https://github.com/lf-) +- kenji [**(@a-kenji)**](https://github.com/a-kenji) +- pennae [**(@pennae)**](https://github.com/pennae) +- puckipedia [**(@puckipedia)**](https://github.com/puckipedia) +- squalus [**(@squalus)**](https://github.com/squalus) +- tomberek [**(@tomberek)**](https://github.com/tomberek) diff --git a/docker.nix b/docker.nix index bd16b71cd..19479e57c 100644 --- a/docker.nix +++ b/docker.nix @@ -9,6 +9,10 @@ , maxLayers ? 100 , nixConf ? {} , flake-registry ? null +, uid ? 0 +, gid ? 0 +, uname ? "root" +, gname ? "root" }: let defaultPkgs = with pkgs; [ @@ -50,6 +54,15 @@ let description = "Unprivileged account (don't use!)"; }; + } // lib.optionalAttrs (uid != 0) { + "${uname}" = { + uid = uid; + shell = "${pkgs.bashInteractive}/bin/bash"; + home = "/home/${uname}"; + gid = gid; + groups = [ "${gname}" ]; + description = "Nix user"; + }; } // lib.listToAttrs ( map ( @@ -70,6 +83,8 @@ let root.gid = 0; nixbld.gid = 30000; nobody.gid = 65534; + } // lib.optionalAttrs (gid != 0) { + "${gname}".gid = gid; }; userToPasswd = ( @@ -150,6 +165,8 @@ let in "${n} = ${vStr}") (defaultNixConf // nixConf))) + "\n"; + userHome = if uid == 0 then "/root" else "/home/${uname}"; + baseSystem = let nixpkgs = pkgs.path; @@ -237,26 +254,26 @@ let mkdir -p $out/etc/nix cat $nixConfContentsPath > $out/etc/nix/nix.conf - mkdir -p $out/root - mkdir -p $out/nix/var/nix/profiles/per-user/root + mkdir -p $out${userHome} + mkdir -p $out/nix/var/nix/profiles/per-user/${uname} ln -s ${profile} $out/nix/var/nix/profiles/default-1-link ln -s $out/nix/var/nix/profiles/default-1-link $out/nix/var/nix/profiles/default - ln -s /nix/var/nix/profiles/default $out/root/.nix-profile + ln -s /nix/var/nix/profiles/default $out${userHome}/.nix-profile - ln -s ${channel} $out/nix/var/nix/profiles/per-user/root/channels-1-link - ln -s $out/nix/var/nix/profiles/per-user/root/channels-1-link $out/nix/var/nix/profiles/per-user/root/channels + ln -s ${channel} $out/nix/var/nix/profiles/per-user/${uname}/channels-1-link + ln -s $out/nix/var/nix/profiles/per-user/${uname}/channels-1-link $out/nix/var/nix/profiles/per-user/${uname}/channels - mkdir -p $out/root/.nix-defexpr - ln -s $out/nix/var/nix/profiles/per-user/root/channels $out/root/.nix-defexpr/channels - echo "${channelURL} ${channelName}" > $out/root/.nix-channels + mkdir -p $out${userHome}/.nix-defexpr + ln -s $out/nix/var/nix/profiles/per-user/${uname}/channels $out${userHome}/.nix-defexpr/channels + echo "${channelURL} ${channelName}" > $out${userHome}/.nix-channels mkdir -p $out/bin $out/usr/bin ln -s ${pkgs.coreutils}/bin/env $out/usr/bin/env ln -s ${pkgs.bashInteractive}/bin/bash $out/bin/sh '' + (lib.optionalString (flake-registry-path != null) '' - nixCacheDir="/root/.cache/nix" + nixCacheDir="${userHome}/.cache/nix" mkdir -p $out$nixCacheDir globalFlakeRegistryPath="$nixCacheDir/flake-registry.json" ln -s ${flake-registry-path} $out$globalFlakeRegistryPath @@ -268,7 +285,7 @@ let in pkgs.dockerTools.buildLayeredImageWithNixDb { - inherit name tag maxLayers; + inherit name tag maxLayers uid gid uname gname; contents = [ baseSystem ]; @@ -279,25 +296,28 @@ pkgs.dockerTools.buildLayeredImageWithNixDb { fakeRootCommands = '' chmod 1777 tmp chmod 1777 var/tmp + chown -R ${toString uid}:${toString gid} .${userHome} + chown -R ${toString uid}:${toString gid} nix ''; config = { - Cmd = [ "/root/.nix-profile/bin/bash" ]; + Cmd = [ "${userHome}/.nix-profile/bin/bash" ]; + User = "${toString uid}:${toString gid}"; Env = [ - "USER=root" + "USER=${uname}" "PATH=${lib.concatStringsSep ":" [ - "/root/.nix-profile/bin" + "${userHome}/.nix-profile/bin" "/nix/var/nix/profiles/default/bin" "/nix/var/nix/profiles/default/sbin" ]}" "MANPATH=${lib.concatStringsSep ":" [ - "/root/.nix-profile/share/man" + "${userHome}/.nix-profile/share/man" "/nix/var/nix/profiles/default/share/man" ]}" "SSL_CERT_FILE=/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt" "GIT_SSL_CAINFO=/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt" "NIX_SSL_CERT_FILE=/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt" - "NIX_PATH=/nix/var/nix/profiles/per-user/root/channels:/root/.nix-defexpr/channels" + "NIX_PATH=/nix/var/nix/profiles/per-user/${uname}/channels:${userHome}/.nix-defexpr/channels" ]; }; diff --git a/flake.nix b/flake.nix index 303779c2b..06025e3b7 100644 --- a/flake.nix +++ b/flake.nix @@ -137,7 +137,7 @@ pkgs = final; }); - nix = final.nixComponents.nix; + nix = final.nixComponents.nix-cli; # See https://github.com/NixOS/nixpkgs/pull/214409 # Remove when fixed in this flake's nixpkgs @@ -189,7 +189,6 @@ # system, we should reenable this. #perlBindings = self.hydraJobs.perlBindings.${system}; } - /* # Add "passthru" tests // flatMapAttrs ({ "" = nixpkgsFor.${system}.native; @@ -211,7 +210,6 @@ "${nixpkgsPrefix}nix-functional-tests" = nixpkgs.nixComponents.nix-functional-tests; } ) - */ // devFlake.checks.${system} or {} ); @@ -220,7 +218,9 @@ # for which we don't apply the full build matrix such as cross or static. inherit (nixpkgsFor.${system}.native) changelog-d; - default = self.packages.${system}.nix-ng; + default = self.packages.${system}.nix; + # TODO probably should be `nix-cli` + nix = self.packages.${system}.nix-everything; nix-manual = nixpkgsFor.${system}.native.nixComponents.nix-manual; nix-internal-api-docs = nixpkgsFor.${system}.native.nixComponents.nix-internal-api-docs; nix-external-api-docs = nixpkgsFor.${system}.native.nixComponents.nix-external-api-docs; @@ -228,7 +228,6 @@ # We need to flatten recursive attribute sets of derivations to pass `flake check`. // flatMapAttrs { # Components we'll iterate over in the upcoming lambda - "nix" = { }; "nix-util" = { }; "nix-util-c" = { }; "nix-util-test-support" = { }; @@ -257,10 +256,11 @@ "nix-cli" = { }; + "nix-everything" = { }; + "nix-functional-tests" = { supportsCross = false; }; "nix-perl-bindings" = { supportsCross = false; }; - "nix-ng" = { }; } (pkgName: { supportsCross ? true }: { # These attributes go right into `packages.`. @@ -294,109 +294,24 @@ }); devShells = let - makeShell = pkgs: stdenv: (pkgs.nix.override { inherit stdenv; forDevShell = true; }).overrideAttrs (attrs: - let - buildCanExecuteHost = stdenv.buildPlatform.canExecute stdenv.hostPlatform; - modular = devFlake.getSystem stdenv.buildPlatform.system; - transformFlag = prefix: flag: - assert builtins.isString flag; - let - rest = builtins.substring 2 (builtins.stringLength flag) flag; - in - "-D${prefix}:${rest}"; - havePerl = stdenv.buildPlatform == stdenv.hostPlatform && stdenv.hostPlatform.isUnix; - ignoreCrossFile = flags: builtins.filter (flag: !(lib.strings.hasInfix "cross-file" flag)) flags; - in { - pname = "shell-for-" + attrs.pname; - - # Remove the version suffix to avoid unnecessary attempts to substitute in nix develop - version = lib.fileContents ./.version; - name = attrs.pname; - - installFlags = "sysconfdir=$(out)/etc"; - shellHook = '' - PATH=$prefix/bin:$PATH - unset PYTHONPATH - export MANPATH=$out/share/man:$MANPATH - - # Make bash completion work. - XDG_DATA_DIRS+=:$out/share - ''; - - # We use this shell with the local checkout, not unpackPhase. - src = null; - - env = { - # Needed for Meson to find Boost. - # https://github.com/NixOS/nixpkgs/issues/86131. - BOOST_INCLUDEDIR = "${lib.getDev pkgs.nixDependencies.boost}/include"; - BOOST_LIBRARYDIR = "${lib.getLib pkgs.nixDependencies.boost}/lib"; - # For `make format`, to work without installing pre-commit - _NIX_PRE_COMMIT_HOOKS_CONFIG = - "${(pkgs.formats.yaml { }).generate "pre-commit-config.yaml" modular.pre-commit.settings.rawConfig}"; - }; - - mesonFlags = - map (transformFlag "libutil") (ignoreCrossFile pkgs.nixComponents.nix-util.mesonFlags) - ++ map (transformFlag "libstore") (ignoreCrossFile pkgs.nixComponents.nix-store.mesonFlags) - ++ map (transformFlag "libfetchers") (ignoreCrossFile pkgs.nixComponents.nix-fetchers.mesonFlags) - ++ lib.optionals havePerl (map (transformFlag "perl") (ignoreCrossFile pkgs.nixComponents.nix-perl-bindings.mesonFlags)) - ++ map (transformFlag "libexpr") (ignoreCrossFile pkgs.nixComponents.nix-expr.mesonFlags) - ++ map (transformFlag "libcmd") (ignoreCrossFile pkgs.nixComponents.nix-cmd.mesonFlags) - ; - - nativeBuildInputs = attrs.nativeBuildInputs or [] - ++ pkgs.nixComponents.nix-util.nativeBuildInputs - ++ pkgs.nixComponents.nix-store.nativeBuildInputs - ++ pkgs.nixComponents.nix-fetchers.nativeBuildInputs - ++ lib.optionals havePerl pkgs.nixComponents.nix-perl-bindings.nativeBuildInputs - ++ lib.optionals buildCanExecuteHost pkgs.nixComponents.nix-manual.externalNativeBuildInputs - ++ pkgs.nixComponents.nix-internal-api-docs.nativeBuildInputs - ++ pkgs.nixComponents.nix-external-api-docs.nativeBuildInputs - ++ pkgs.nixComponents.nix-functional-tests.externalNativeBuildInputs - ++ lib.optional - (!buildCanExecuteHost - # Hack around https://github.com/nixos/nixpkgs/commit/bf7ad8cfbfa102a90463433e2c5027573b462479 - && !(stdenv.hostPlatform.isWindows && stdenv.buildPlatform.isDarwin) - && stdenv.hostPlatform.emulatorAvailable pkgs.buildPackages - && lib.meta.availableOn stdenv.buildPlatform (stdenv.hostPlatform.emulator pkgs.buildPackages)) - pkgs.buildPackages.mesonEmulatorHook - ++ [ - pkgs.buildPackages.cmake - pkgs.buildPackages.shellcheck - pkgs.buildPackages.changelog-d - modular.pre-commit.settings.package - (pkgs.writeScriptBin "pre-commit-hooks-install" - modular.pre-commit.settings.installationScript) - ] - # TODO: Remove the darwin check once - # https://github.com/NixOS/nixpkgs/pull/291814 is available - ++ lib.optional (stdenv.cc.isClang && !stdenv.buildPlatform.isDarwin) pkgs.buildPackages.bear - ++ lib.optional (stdenv.cc.isClang && stdenv.hostPlatform == stdenv.buildPlatform) (lib.hiPrio pkgs.buildPackages.clang-tools); - - buildInputs = attrs.buildInputs or [] - ++ [ - pkgs.gtest - pkgs.rapidcheck - ] - ++ lib.optional havePerl pkgs.perl - ; - }); - in + makeShell = import ./packaging/dev-shell.nix { inherit lib devFlake; }; + prefixAttrs = prefix: lib.concatMapAttrs (k: v: { "${prefix}-${k}" = v; }); + in forAllSystems (system: - let - makeShells = prefix: pkgs: - lib.mapAttrs' - (k: v: lib.nameValuePair "${prefix}-${k}" v) - (forAllStdenvs (stdenvName: makeShell pkgs pkgs.${stdenvName})); - in - (makeShells "native" nixpkgsFor.${system}.native) // - (lib.optionalAttrs (!nixpkgsFor.${system}.native.stdenv.isDarwin) - (makeShells "static" nixpkgsFor.${system}.static) // - (forAllCrossSystems (crossSystem: let pkgs = nixpkgsFor.${system}.cross.${crossSystem}; in makeShell pkgs pkgs.stdenv))) // - { - default = self.devShells.${system}.native-stdenvPackages; - } + prefixAttrs "native" (forAllStdenvs (stdenvName: makeShell { + pkgs = nixpkgsFor.${system}.stdenvs."${stdenvName}Packages"; + })) // + lib.optionalAttrs (!nixpkgsFor.${system}.native.stdenv.isDarwin) ( + prefixAttrs "static" (forAllStdenvs (stdenvName: makeShell { + pkgs = nixpkgsFor.${system}.stdenvs."${stdenvName}Packages".pkgsStatic; + })) // + prefixAttrs "cross" (forAllCrossSystems (crossSystem: makeShell { + pkgs = nixpkgsFor.${system}.cross.${crossSystem}; + })) + ) // + { + default = self.devShells.${system}.native-stdenvPackages; + } ); }; } diff --git a/local.mk b/local.mk deleted file mode 100644 index b27c7031e..000000000 --- a/local.mk +++ /dev/null @@ -1,15 +0,0 @@ -GLOBAL_CXXFLAGS += -Wno-deprecated-declarations -Werror=switch -# Allow switch-enum to be overridden for files that do not support it, usually because of dependency headers. -ERROR_SWITCH_ENUM = -Werror=switch-enum - -$(foreach i, config.h $(wildcard src/lib*/*.hh) $(filter-out %_internal.h, $(wildcard src/lib*c/*.h)), \ - $(eval $(call install-file-in, $(i), $(includedir)/nix, 0644))) - -ifdef HOST_UNIX - $(foreach i, $(wildcard src/lib*/unix/*.hh), \ - $(eval $(call install-file-in, $(i), $(includedir)/nix, 0644))) -endif - -$(GCH): src/libutil/util.hh config.h - -GCH_CXXFLAGS = $(INCLUDE_libutil) diff --git a/m4/ax_cxx_compile_stdcxx.m4 b/m4/ax_cxx_compile_stdcxx.m4 deleted file mode 100644 index 43087b2e6..000000000 --- a/m4/ax_cxx_compile_stdcxx.m4 +++ /dev/null @@ -1,951 +0,0 @@ -# =========================================================================== -# https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx.html -# =========================================================================== -# -# SYNOPSIS -# -# AX_CXX_COMPILE_STDCXX(VERSION, [ext|noext], [mandatory|optional]) -# -# DESCRIPTION -# -# Check for baseline language coverage in the compiler for the specified -# version of the C++ standard. If necessary, add switches to CXX and -# CXXCPP to enable support. VERSION may be '11' (for the C++11 standard) -# or '14' (for the C++14 standard). -# -# The second argument, if specified, indicates whether you insist on an -# extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. -# -std=c++11). If neither is specified, you get whatever works, with -# preference for an extended mode. -# -# The third argument, if specified 'mandatory' or if left unspecified, -# indicates that baseline support for the specified C++ standard is -# required and that the macro should error out if no mode with that -# support is found. If specified 'optional', then configuration proceeds -# regardless, after defining HAVE_CXX${VERSION} if and only if a -# supporting mode is found. -# -# LICENSE -# -# Copyright (c) 2008 Benjamin Kosnik -# Copyright (c) 2012 Zack Weinberg -# Copyright (c) 2013 Roy Stogner -# Copyright (c) 2014, 2015 Google Inc.; contributed by Alexey Sokolov -# Copyright (c) 2015 Paul Norman -# Copyright (c) 2015 Moritz Klammler -# Copyright (c) 2016, 2018 Krzesimir Nowak -# Copyright (c) 2019 Enji Cooper -# -# Copying and distribution of this file, with or without modification, are -# permitted in any medium without royalty provided the copyright notice -# and this notice are preserved. This file is offered as-is, without any -# warranty. - -#serial 11 - -dnl This macro is based on the code from the AX_CXX_COMPILE_STDCXX_11 macro -dnl (serial version number 13). - -AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl - m4_if([$1], [11], [ax_cxx_compile_alternatives="11 0x"], - [$1], [14], [ax_cxx_compile_alternatives="14 1y"], - [$1], [17], [ax_cxx_compile_alternatives="17 1z"], - [m4_fatal([invalid first argument `$1' to AX_CXX_COMPILE_STDCXX])])dnl - m4_if([$2], [], [], - [$2], [ext], [], - [$2], [noext], [], - [m4_fatal([invalid second argument `$2' to AX_CXX_COMPILE_STDCXX])])dnl - m4_if([$3], [], [ax_cxx_compile_cxx$1_required=true], - [$3], [mandatory], [ax_cxx_compile_cxx$1_required=true], - [$3], [optional], [ax_cxx_compile_cxx$1_required=false], - [m4_fatal([invalid third argument `$3' to AX_CXX_COMPILE_STDCXX])]) - AC_LANG_PUSH([C++])dnl - ac_success=no - - m4_if([$2], [noext], [], [dnl - if test x$ac_success = xno; then - for alternative in ${ax_cxx_compile_alternatives}; do - switch="-std=gnu++${alternative}" - cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) - AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, - $cachevar, - [ac_save_CXX="$CXX" - CXX="$CXX $switch" - AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], - [eval $cachevar=yes], - [eval $cachevar=no]) - CXX="$ac_save_CXX"]) - if eval test x\$$cachevar = xyes; then - CXX="$CXX $switch" - if test -n "$CXXCPP" ; then - CXXCPP="$CXXCPP $switch" - fi - ac_success=yes - break - fi - done - fi]) - - m4_if([$2], [ext], [], [dnl - if test x$ac_success = xno; then - dnl HP's aCC needs +std=c++11 according to: - dnl http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/PDF_Release_Notes/769149-001.pdf - dnl Cray's crayCC needs "-h std=c++11" - for alternative in ${ax_cxx_compile_alternatives}; do - for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do - cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) - AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, - $cachevar, - [ac_save_CXX="$CXX" - CXX="$CXX $switch" - AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], - [eval $cachevar=yes], - [eval $cachevar=no]) - CXX="$ac_save_CXX"]) - if eval test x\$$cachevar = xyes; then - CXX="$CXX $switch" - if test -n "$CXXCPP" ; then - CXXCPP="$CXXCPP $switch" - fi - ac_success=yes - break - fi - done - if test x$ac_success = xyes; then - break - fi - done - fi]) - AC_LANG_POP([C++]) - if test x$ax_cxx_compile_cxx$1_required = xtrue; then - if test x$ac_success = xno; then - AC_MSG_ERROR([*** A compiler with support for C++$1 language features is required.]) - fi - fi - if test x$ac_success = xno; then - HAVE_CXX$1=0 - AC_MSG_NOTICE([No compiler with C++$1 support was found]) - else - HAVE_CXX$1=1 - AC_DEFINE(HAVE_CXX$1,1, - [define if the compiler supports basic C++$1 syntax]) - fi - AC_SUBST(HAVE_CXX$1) -]) - - -dnl Test body for checking C++11 support - -m4_define([_AX_CXX_COMPILE_STDCXX_testbody_11], - _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 -) - - -dnl Test body for checking C++14 support - -m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14], - _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 - _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 -) - -m4_define([_AX_CXX_COMPILE_STDCXX_testbody_17], - _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 - _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 - _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 -) - -dnl Tests for new features in C++11 - -m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[ - -// If the compiler admits that it is not ready for C++11, why torture it? -// Hopefully, this will speed up the test. - -#ifndef __cplusplus - -#error "This is not a C++ compiler" - -#elif __cplusplus < 201103L - -#error "This is not a C++11 compiler" - -#else - -namespace cxx11 -{ - - namespace test_static_assert - { - - template - struct check - { - static_assert(sizeof(int) <= sizeof(T), "not big enough"); - }; - - } - - namespace test_final_override - { - - struct Base - { - virtual ~Base() {} - virtual void f() {} - }; - - struct Derived : public Base - { - virtual ~Derived() override {} - virtual void f() override {} - }; - - } - - namespace test_double_right_angle_brackets - { - - template < typename T > - struct check {}; - - typedef check single_type; - typedef check> double_type; - typedef check>> triple_type; - typedef check>>> quadruple_type; - - } - - namespace test_decltype - { - - int - f() - { - int a = 1; - decltype(a) b = 2; - return a + b; - } - - } - - namespace test_type_deduction - { - - template < typename T1, typename T2 > - struct is_same - { - static const bool value = false; - }; - - template < typename T > - struct is_same - { - static const bool value = true; - }; - - template < typename T1, typename T2 > - auto - add(T1 a1, T2 a2) -> decltype(a1 + a2) - { - return a1 + a2; - } - - int - test(const int c, volatile int v) - { - static_assert(is_same::value == true, ""); - static_assert(is_same::value == false, ""); - static_assert(is_same::value == false, ""); - auto ac = c; - auto av = v; - auto sumi = ac + av + 'x'; - auto sumf = ac + av + 1.0; - static_assert(is_same::value == true, ""); - static_assert(is_same::value == true, ""); - static_assert(is_same::value == true, ""); - static_assert(is_same::value == false, ""); - static_assert(is_same::value == true, ""); - return (sumf > 0.0) ? sumi : add(c, v); - } - - } - - namespace test_noexcept - { - - int f() { return 0; } - int g() noexcept { return 0; } - - static_assert(noexcept(f()) == false, ""); - static_assert(noexcept(g()) == true, ""); - - } - - namespace test_constexpr - { - - template < typename CharT > - unsigned long constexpr - strlen_c_r(const CharT *const s, const unsigned long acc) noexcept - { - return *s ? strlen_c_r(s + 1, acc + 1) : acc; - } - - template < typename CharT > - unsigned long constexpr - strlen_c(const CharT *const s) noexcept - { - return strlen_c_r(s, 0UL); - } - - static_assert(strlen_c("") == 0UL, ""); - static_assert(strlen_c("1") == 1UL, ""); - static_assert(strlen_c("example") == 7UL, ""); - static_assert(strlen_c("another\0example") == 7UL, ""); - - } - - namespace test_rvalue_references - { - - template < int N > - struct answer - { - static constexpr int value = N; - }; - - answer<1> f(int&) { return answer<1>(); } - answer<2> f(const int&) { return answer<2>(); } - answer<3> f(int&&) { return answer<3>(); } - - void - test() - { - int i = 0; - const int c = 0; - static_assert(decltype(f(i))::value == 1, ""); - static_assert(decltype(f(c))::value == 2, ""); - static_assert(decltype(f(0))::value == 3, ""); - } - - } - - namespace test_uniform_initialization - { - - struct test - { - static const int zero {}; - static const int one {1}; - }; - - static_assert(test::zero == 0, ""); - static_assert(test::one == 1, ""); - - } - - namespace test_lambdas - { - - void - test1() - { - auto lambda1 = [](){}; - auto lambda2 = lambda1; - lambda1(); - lambda2(); - } - - int - test2() - { - auto a = [](int i, int j){ return i + j; }(1, 2); - auto b = []() -> int { return '0'; }(); - auto c = [=](){ return a + b; }(); - auto d = [&](){ return c; }(); - auto e = [a, &b](int x) mutable { - const auto identity = [](int y){ return y; }; - for (auto i = 0; i < a; ++i) - a += b--; - return x + identity(a + b); - }(0); - return a + b + c + d + e; - } - - int - test3() - { - const auto nullary = [](){ return 0; }; - const auto unary = [](int x){ return x; }; - using nullary_t = decltype(nullary); - using unary_t = decltype(unary); - const auto higher1st = [](nullary_t f){ return f(); }; - const auto higher2nd = [unary](nullary_t f1){ - return [unary, f1](unary_t f2){ return f2(unary(f1())); }; - }; - return higher1st(nullary) + higher2nd(nullary)(unary); - } - - } - - namespace test_variadic_templates - { - - template - struct sum; - - template - struct sum - { - static constexpr auto value = N0 + sum::value; - }; - - template <> - struct sum<> - { - static constexpr auto value = 0; - }; - - static_assert(sum<>::value == 0, ""); - static_assert(sum<1>::value == 1, ""); - static_assert(sum<23>::value == 23, ""); - static_assert(sum<1, 2>::value == 3, ""); - static_assert(sum<5, 5, 11>::value == 21, ""); - static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, ""); - - } - - // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae - // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function - // because of this. - namespace test_template_alias_sfinae - { - - struct foo {}; - - template - using member = typename T::member_type; - - template - void func(...) {} - - template - void func(member*) {} - - void test(); - - void test() { func(0); } - - } - -} // namespace cxx11 - -#endif // __cplusplus >= 201103L - -]]) - - -dnl Tests for new features in C++14 - -m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_14], [[ - -// If the compiler admits that it is not ready for C++14, why torture it? -// Hopefully, this will speed up the test. - -#ifndef __cplusplus - -#error "This is not a C++ compiler" - -#elif __cplusplus < 201402L - -#error "This is not a C++14 compiler" - -#else - -namespace cxx14 -{ - - namespace test_polymorphic_lambdas - { - - int - test() - { - const auto lambda = [](auto&&... args){ - const auto istiny = [](auto x){ - return (sizeof(x) == 1UL) ? 1 : 0; - }; - const int aretiny[] = { istiny(args)... }; - return aretiny[0]; - }; - return lambda(1, 1L, 1.0f, '1'); - } - - } - - namespace test_binary_literals - { - - constexpr auto ivii = 0b0000000000101010; - static_assert(ivii == 42, "wrong value"); - - } - - namespace test_generalized_constexpr - { - - template < typename CharT > - constexpr unsigned long - strlen_c(const CharT *const s) noexcept - { - auto length = 0UL; - for (auto p = s; *p; ++p) - ++length; - return length; - } - - static_assert(strlen_c("") == 0UL, ""); - static_assert(strlen_c("x") == 1UL, ""); - static_assert(strlen_c("test") == 4UL, ""); - static_assert(strlen_c("another\0test") == 7UL, ""); - - } - - namespace test_lambda_init_capture - { - - int - test() - { - auto x = 0; - const auto lambda1 = [a = x](int b){ return a + b; }; - const auto lambda2 = [a = lambda1(x)](){ return a; }; - return lambda2(); - } - - } - - namespace test_digit_separators - { - - constexpr auto ten_million = 100'000'000; - static_assert(ten_million == 100000000, ""); - - } - - namespace test_return_type_deduction - { - - auto f(int& x) { return x; } - decltype(auto) g(int& x) { return x; } - - template < typename T1, typename T2 > - struct is_same - { - static constexpr auto value = false; - }; - - template < typename T > - struct is_same - { - static constexpr auto value = true; - }; - - int - test() - { - auto x = 0; - static_assert(is_same::value, ""); - static_assert(is_same::value, ""); - return x; - } - - } - -} // namespace cxx14 - -#endif // __cplusplus >= 201402L - -]]) - - -dnl Tests for new features in C++17 - -m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_17], [[ - -// If the compiler admits that it is not ready for C++17, why torture it? -// Hopefully, this will speed up the test. - -#ifndef __cplusplus - -#error "This is not a C++ compiler" - -#elif __cplusplus < 201703L - -#error "This is not a C++17 compiler" - -#else - -#include -#include -#include - -namespace cxx17 -{ - - namespace test_constexpr_lambdas - { - - constexpr int foo = [](){return 42;}(); - - } - - namespace test::nested_namespace::definitions - { - - } - - namespace test_fold_expression - { - - template - int multiply(Args... args) - { - return (args * ... * 1); - } - - template - bool all(Args... args) - { - return (args && ...); - } - - } - - namespace test_extended_static_assert - { - - static_assert (true); - - } - - namespace test_auto_brace_init_list - { - - auto foo = {5}; - auto bar {5}; - - static_assert(std::is_same, decltype(foo)>::value); - static_assert(std::is_same::value); - } - - namespace test_typename_in_template_template_parameter - { - - template typename X> struct D; - - } - - namespace test_fallthrough_nodiscard_maybe_unused_attributes - { - - int f1() - { - return 42; - } - - [[nodiscard]] int f2() - { - [[maybe_unused]] auto unused = f1(); - - switch (f1()) - { - case 17: - f1(); - [[fallthrough]]; - case 42: - f1(); - } - return f1(); - } - - } - - namespace test_extended_aggregate_initialization - { - - struct base1 - { - int b1, b2 = 42; - }; - - struct base2 - { - base2() { - b3 = 42; - } - int b3; - }; - - struct derived : base1, base2 - { - int d; - }; - - derived d1 {{1, 2}, {}, 4}; // full initialization - derived d2 {{}, {}, 4}; // value-initialized bases - - } - - namespace test_general_range_based_for_loop - { - - struct iter - { - int i; - - int& operator* () - { - return i; - } - - const int& operator* () const - { - return i; - } - - iter& operator++() - { - ++i; - return *this; - } - }; - - struct sentinel - { - int i; - }; - - bool operator== (const iter& i, const sentinel& s) - { - return i.i == s.i; - } - - bool operator!= (const iter& i, const sentinel& s) - { - return !(i == s); - } - - struct range - { - iter begin() const - { - return {0}; - } - - sentinel end() const - { - return {5}; - } - }; - - void f() - { - range r {}; - - for (auto i : r) - { - [[maybe_unused]] auto v = i; - } - } - - } - - namespace test_lambda_capture_asterisk_this_by_value - { - - struct t - { - int i; - int foo() - { - return [*this]() - { - return i; - }(); - } - }; - - } - - namespace test_enum_class_construction - { - - enum class byte : unsigned char - {}; - - byte foo {42}; - - } - - namespace test_constexpr_if - { - - template - int f () - { - if constexpr(cond) - { - return 13; - } - else - { - return 42; - } - } - - } - - namespace test_selection_statement_with_initializer - { - - int f() - { - return 13; - } - - int f2() - { - if (auto i = f(); i > 0) - { - return 3; - } - - switch (auto i = f(); i + 4) - { - case 17: - return 2; - - default: - return 1; - } - } - - } - - namespace test_template_argument_deduction_for_class_templates - { - - template - struct pair - { - pair (T1 p1, T2 p2) - : m1 {p1}, - m2 {p2} - {} - - T1 m1; - T2 m2; - }; - - void f() - { - [[maybe_unused]] auto p = pair{13, 42u}; - } - - } - - namespace test_non_type_auto_template_parameters - { - - template - struct B - {}; - - B<5> b1; - B<'a'> b2; - - } - - namespace test_structured_bindings - { - - int arr[2] = { 1, 2 }; - std::pair pr = { 1, 2 }; - - auto f1() -> int(&)[2] - { - return arr; - } - - auto f2() -> std::pair& - { - return pr; - } - - struct S - { - int x1 : 2; - volatile double y1; - }; - - S f3() - { - return {}; - } - - auto [ x1, y1 ] = f1(); - auto& [ xr1, yr1 ] = f1(); - auto [ x2, y2 ] = f2(); - auto& [ xr2, yr2 ] = f2(); - const auto [ x3, y3 ] = f3(); - - } - - namespace test_exception_spec_type_system - { - - struct Good {}; - struct Bad {}; - - void g1() noexcept; - void g2(); - - template - Bad - f(T*, T*); - - template - Good - f(T1*, T2*); - - static_assert (std::is_same_v); - - } - - namespace test_inline_variables - { - - template void f(T) - {} - - template inline T g(T) - { - return T{}; - } - - template<> inline void f<>(int) - {} - - template<> int g<>(int) - { - return 5; - } - - } - -} // namespace cxx17 - -#endif // __cplusplus < 201703L - -]]) diff --git a/m4/ax_cxx_compile_stdcxx_17.m4 b/m4/ax_cxx_compile_stdcxx_17.m4 deleted file mode 100644 index a68341717..000000000 --- a/m4/ax_cxx_compile_stdcxx_17.m4 +++ /dev/null @@ -1,35 +0,0 @@ -# ============================================================================= -# https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx_17.html -# ============================================================================= -# -# SYNOPSIS -# -# AX_CXX_COMPILE_STDCXX_17([ext|noext], [mandatory|optional]) -# -# DESCRIPTION -# -# Check for baseline language coverage in the compiler for the C++17 -# standard; if necessary, add switches to CXX and CXXCPP to enable -# support. -# -# This macro is a convenience alias for calling the AX_CXX_COMPILE_STDCXX -# macro with the version set to C++17. The two optional arguments are -# forwarded literally as the second and third argument respectively. -# Please see the documentation for the AX_CXX_COMPILE_STDCXX macro for -# more information. If you want to use this macro, you also need to -# download the ax_cxx_compile_stdcxx.m4 file. -# -# LICENSE -# -# Copyright (c) 2015 Moritz Klammler -# Copyright (c) 2016 Krzesimir Nowak -# -# Copying and distribution of this file, with or without modification, are -# permitted in any medium without royalty provided the copyright notice -# and this notice are preserved. This file is offered as-is, without any -# warranty. - -#serial 2 - -AX_REQUIRE_DEFINED([AX_CXX_COMPILE_STDCXX]) -AC_DEFUN([AX_CXX_COMPILE_STDCXX_17], [AX_CXX_COMPILE_STDCXX([17], [$1], [$2])]) diff --git a/maintainers/data/release-credits-email-to-handle.json b/maintainers/data/release-credits-email-to-handle.json index cddc1a6e7..d7a238ebd 100644 --- a/maintainers/data/release-credits-email-to-handle.json +++ b/maintainers/data/release-credits-email-to-handle.json @@ -48,5 +48,55 @@ "delroth@gmail.com": "delroth", "enno@nerdworks.de": "elohmeier", "mjbauer95@gmail.com": "matthewbauer", - "MostAwesomeDude@gmail.com": "MostAwesomeDude" + "MostAwesomeDude@gmail.com": "MostAwesomeDude", + "145775305+xokdvium@users.noreply.github.com": "xokdvium", + "bryanhonof@gmail.com": "bryanhonof", + "50352631+michaelvanstraten@users.noreply.github.com": "michaelvanstraten", + "bjorn.forsman@gmail.com": "bjornfor", + "pol.dellaiera@protonmail.com": "drupol", + "tim.vanbaak@gmail.com": "Jaculabilis", + "leetemil@users.noreply.github.com": "leetemil", + "a-h@users.noreply.github.com": "a-h", + "me@artem.ist": "artemist", + "puck@puckipedia.com": "puckipedia", + "marian.hammer@meetwise.com": "emhamm", + "78693624+llakala@users.noreply.github.com": "llakala", + "itkachev@hyperad.tech": null, + "geofft@ldpreload.com": "geofft", + "onni@flaky.build": "onnimonni", + "jacek@galowicz.de": "tfc", + "potterbein@blockstream.com": null, + "49699333+dependabot[bot]@users.noreply.github.com": "dependabot[bot]", + "112626461+VinayakKaushikDH@users.noreply.github.com": "VinayakKaushikDH", + "kevincox@kevincox.ca": "kevincox", + "yann.hamdaoui@tweag.io": "yannham", + "GregLeyda@proton.me": "Gerg-L", + "jljusten@gmail.com": "jljusten", + "josh.heinrichs@shopify.com": "joshheinrichs-shopify", + "jason@jasonyundt.email": "Jayman2000", + "noamraph@gmail.com": "noamraph", + "nikodem@rabulinski.com": "nrabulinski", + "78693624+quatquatt@users.noreply.github.com": "llakala", + "yuriy.taraday@tweag.io": "YorikSar", + "travis.a.everett@gmail.com": "abathur", + "Artturin@artturin.com": "Artturin", + "zimbatm@zimbatm.com": "zimbatm", + "contact@parkerhoyes.com": "parkerhoyes", + "kjeremy@gmail.com": "kjeremy", + "jkerfs@users.noreply.github.com": "jkerfs", + "sandro.jaeckel@gmail.com": "SuperSandro2000", + "hi@alyssa.is": "alyssais", + "2716069+jhrcek@users.noreply.github.com": "jhrcek", + "seggy.umboh@coupa.com": "secobarbital", + "hello@emily.moe": "emilazy", + "ehmry@posteo.net": "ehmry", + "me@aleksana.moe": "Aleksanaa", + "tom@floxdev.com": null, + "sbh69840@gmail.com": "shivaraj-bh", + "mjgallag@gmail.com": "mjgallag", + "bryango@users.noreply.github.com": "bryango", + "aks.kenji@protonmail.com": "a-kenji", + "54070204+0x5a4@users.noreply.github.com": "0x5a4", + "brian@bmcgee.ie": "brianmcgee", + "squalus@squalus.net": "squalus" } \ No newline at end of file diff --git a/maintainers/data/release-credits-handle-to-name.json b/maintainers/data/release-credits-handle-to-name.json index abf9ed05b..765771668 100644 --- a/maintainers/data/release-credits-handle-to-name.json +++ b/maintainers/data/release-credits-handle-to-name.json @@ -41,5 +41,50 @@ "winterqt": "Winter", "GoldsteinE": "Max \u201cGoldstein\u201d Siling", "pennae": null, - "MostAwesomeDude": "Corbin Simpson" + "MostAwesomeDude": "Corbin Simpson", + "VinayakKaushikDH": "Vinayak Kaushik", + "leetemil": "Emil Petersen", + "michaelvanstraten": "Michael", + "parkerhoyes": "Parker Hoyes", + "a-h": "Adrian Hesketh", + "a-kenji": "kenji", + "geofft": "Geoffrey Thomas", + "bryango": null, + "tfc": "Jacek Galowicz", + "brianmcgee": "Brian McGee", + "Gerg-L": null, + "secobarbital": "Seggy Umboh", + "bjornfor": "Bj\u00f8rn Forsman", + "dependabot[bot]": null, + "xokdvium": "Sergei Zimmerman", + "kevincox": "Kevin Cox", + "Jayman2000": "Jason Yundt", + "Artturin": "Artturin", + "0x5a4": "1444", + "llakala": "Eman Resu", + "nrabulinski": "Nikodem Rabuli\u0144ski", + "shivaraj-bh": "Shivaraj B H", + "yannham": "Yann Hamdaoui", + "jkerfs": "Jeremy Kerfs", + "drupol": "Pol Dellaiera", + "onnimonni": "Onni Hakala", + "joshheinrichs-shopify": "Josh Heinrichs", + "puckipedia": null, + "abathur": "Travis A. Everett", + "alyssais": "Alyssa Ross", + "noamraph": "Noam Yorav-Raphael", + "squalus": null, + "emhamm": null, + "mjgallag": "Michael Gallagher", + "jljusten": "Jordan Justen", + "ehmry": "Emery Hemingway", + "jhrcek": "Jan Hrcek", + "Jaculabilis": "Tim", + "bryanhonof": "Bryan Honof", + "zimbatm": "Jonas Chevalier", + "SuperSandro2000": "Sandro", + "Aleksanaa": "Aleksana", + "YorikSar": "Yuriy Taraday", + "kjeremy": "Jeremy Kolb", + "artemist": "Artemis Tosini" } \ No newline at end of file diff --git a/maintainers/local.mk b/maintainers/local.mk deleted file mode 100644 index e81517eda..000000000 --- a/maintainers/local.mk +++ /dev/null @@ -1,8 +0,0 @@ - -.PHONY: format -print-top-help += echo ' format: Format source code' - -# This uses the cached .pre-commit-hooks.yaml file -fmt_script := $(d)/format.sh -format: - @$(fmt_script) diff --git a/maintainers/onboarding.md b/maintainers/onboarding.md index e750bd8a7..d7491db16 100644 --- a/maintainers/onboarding.md +++ b/maintainers/onboarding.md @@ -4,3 +4,4 @@ - https://github.com/NixOS/nixos-homepage/ - https://github.com/orgs/NixOS/teams/nix-team - Matrix room +- Team member should subscribe to notifications for the [Nix development category on Discourse](https://discourse.nixos.org/c/dev/nix/50) diff --git a/meson.build b/meson.build index d68db0a0d..8985b631e 100644 --- a/meson.build +++ b/meson.build @@ -22,10 +22,12 @@ subproject('libcmd') subproject('nix') # Docs -subproject('internal-api-docs') -subproject('external-api-docs') -if not meson.is_cross_build() - subproject('nix-manual') +if get_option('doc-gen') + subproject('internal-api-docs') + subproject('external-api-docs') + if not meson.is_cross_build() + subproject('nix-manual') + endif endif # External C wrapper libraries @@ -35,17 +37,19 @@ subproject('libexpr-c') subproject('libmain-c') # Language Bindings -if not meson.is_cross_build() +if get_option('bindings') and not meson.is_cross_build() subproject('perl') endif # Testing -subproject('libutil-test-support') -subproject('libutil-tests') -subproject('libstore-test-support') -subproject('libstore-tests') -subproject('libfetchers-tests') -subproject('libexpr-test-support') -subproject('libexpr-tests') -subproject('libflake-tests') +if get_option('unit-tests') + subproject('libutil-test-support') + subproject('libutil-tests') + subproject('libstore-test-support') + subproject('libstore-tests') + subproject('libfetchers-tests') + subproject('libexpr-test-support') + subproject('libexpr-tests') + subproject('libflake-tests') +endif subproject('nix-functional-tests') diff --git a/meson.options b/meson.options new file mode 100644 index 000000000..329fe06bf --- /dev/null +++ b/meson.options @@ -0,0 +1,13 @@ +# vim: filetype=meson + +option('doc-gen', type : 'boolean', value : false, + description : 'Generate documentation', +) + +option('unit-tests', type : 'boolean', value : true, + description : 'Build unit tests', +) + +option('bindings', type : 'boolean', value : true, + description : 'Build language bindings (e.g. Perl)', +) diff --git a/misc/bash/local.mk b/misc/bash/local.mk deleted file mode 100644 index 66235af05..000000000 --- a/misc/bash/local.mk +++ /dev/null @@ -1 +0,0 @@ -$(eval $(call install-file-as, $(d)/completion.sh, $(datarootdir)/bash-completion/completions/nix, 0644)) diff --git a/misc/fish/local.mk b/misc/fish/local.mk deleted file mode 100644 index ece899fc3..000000000 --- a/misc/fish/local.mk +++ /dev/null @@ -1 +0,0 @@ -$(eval $(call install-file-as, $(d)/completion.fish, $(datarootdir)/fish/vendor_completions.d/nix.fish, 0644)) diff --git a/misc/launchd/local.mk b/misc/launchd/local.mk deleted file mode 100644 index a39188fe6..000000000 --- a/misc/launchd/local.mk +++ /dev/null @@ -1,5 +0,0 @@ -ifdef HOST_DARWIN - - $(eval $(call install-data-in, $(d)/org.nixos.nix-daemon.plist, $(prefix)/Library/LaunchDaemons)) - -endif diff --git a/misc/systemd/local.mk b/misc/systemd/local.mk deleted file mode 100644 index 76121a0f9..000000000 --- a/misc/systemd/local.mk +++ /dev/null @@ -1,8 +0,0 @@ -ifdef HOST_LINUX - - $(foreach n, nix-daemon.socket nix-daemon.service, $(eval $(call install-file-in, $(d)/$(n), $(prefix)/lib/systemd/system, 0644))) - $(foreach n, nix-daemon.conf, $(eval $(call install-file-in, $(d)/$(n), $(prefix)/lib/tmpfiles.d, 0644))) - - clean-files += $(d)/nix-daemon.socket $(d)/nix-daemon.service $(d)/nix-daemon.conf - -endif diff --git a/misc/upstart/local.mk b/misc/upstart/local.mk deleted file mode 100644 index 2fbfb29b9..000000000 --- a/misc/upstart/local.mk +++ /dev/null @@ -1,7 +0,0 @@ -ifdef HOST_LINUX - - $(foreach n, nix-daemon.conf, $(eval $(call install-file-in, $(d)/$(n), $(sysconfdir)/init, 0644))) - - clean-files += $(d)/nix-daemon.conf - -endif diff --git a/misc/zsh/local.mk b/misc/zsh/local.mk deleted file mode 100644 index 0b4e294fb..000000000 --- a/misc/zsh/local.mk +++ /dev/null @@ -1,2 +0,0 @@ -$(eval $(call install-file-as, $(d)/completion.zsh, $(datarootdir)/zsh/site-functions/_nix, 0644)) -$(eval $(call install-file-as, $(d)/run-help-nix, $(datarootdir)/zsh/site-functions/run-help-nix, 0644)) diff --git a/mk/build-dir.mk b/mk/build-dir.mk deleted file mode 100644 index 02f4cae60..000000000 --- a/mk/build-dir.mk +++ /dev/null @@ -1,10 +0,0 @@ -# Initialise support for build directories. -builddir ?= - -ifdef builddir - buildprefix = $(builddir)/ - buildprefixrel = $(builddir) -else - buildprefix = - buildprefixrel = . -endif diff --git a/mk/clean.mk b/mk/clean.mk deleted file mode 100644 index ce9afb3b0..000000000 --- a/mk/clean.mk +++ /dev/null @@ -1,11 +0,0 @@ -clean-files := - -clean: - $(suppress) rm -fv -- $(clean-files) - -dryclean: - @for i in $(clean-files); do if [ -e $$i ]; then echo $$i; fi; done | sort - -print-top-help += \ - echo " clean: Delete generated files"; \ - echo " dryclean: Show what files would be deleted by 'make clean'"; diff --git a/mk/common-test.sh b/mk/common-test.sh deleted file mode 100644 index dd899e869..000000000 --- a/mk/common-test.sh +++ /dev/null @@ -1,31 +0,0 @@ -# shellcheck shell=bash - -# Remove overall test dir (at most one of the two should match) and -# remove file extension. - -test_name=$(echo -n "${test?must be defined by caller (test runner)}" | sed \ - -e "s|^src/[^/]*-test/data/||" \ - -e "s|^tests/functional/||" \ - -e "s|\.sh$||" \ - ) - -# Layer violation, but I am not inclined to care too much, as this code -# is about to be deleted. -src_dir=$(realpath tests/functional) - -# shellcheck disable=SC2016 -TESTS_ENVIRONMENT=( - "TEST_NAME=$test_name" - 'NIX_REMOTE=' - 'PS4=+(${BASH_SOURCE[0]-$0}:$LINENO) ' - "_NIX_TEST_SOURCE_DIR=${src_dir}" - "_NIX_TEST_BUILD_DIR=${src_dir}" -) - -unset src_dir - -read -r -a bash <<< "${BASH:-/usr/bin/env bash}" - -run () { - cd "$(dirname "$1")" && env "${TESTS_ENVIRONMENT[@]}" "${bash[@]}" -x -e -u -o pipefail "$(basename "$1")" -} diff --git a/mk/compilation-database.mk b/mk/compilation-database.mk deleted file mode 100644 index f69dc0de0..000000000 --- a/mk/compilation-database.mk +++ /dev/null @@ -1,11 +0,0 @@ -compile-commands-json-files := - -define write-compile-commands - _srcs := $$(sort $$(foreach src, $$($(1)_SOURCES), $$(src))) - - $(1)_COMPILE_COMMANDS_JSON := $$(addprefix $(buildprefix), $$(addsuffix .compile_commands.json, $$(basename $$(_srcs)))) - - compile-commands-json-files += $$($(1)_COMPILE_COMMANDS_JSON) - - clean-files += $$($(1)_COMPILE_COMMANDS_JSON) -endef diff --git a/mk/cxx-big-literal.mk b/mk/cxx-big-literal.mk deleted file mode 100644 index d64a171c8..000000000 --- a/mk/cxx-big-literal.mk +++ /dev/null @@ -1,5 +0,0 @@ -%.gen.hh: % - @echo 'R"__NIX_STR(' >> $@.tmp - $(trace-gen) cat $< >> $@.tmp - @echo ')__NIX_STR"' >> $@.tmp - @mv $@.tmp $@ diff --git a/mk/debug-test.sh b/mk/debug-test.sh deleted file mode 100755 index 0dd4406c3..000000000 --- a/mk/debug-test.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -set -eu -o pipefail - -test=$1 - -dir="$(dirname "${BASH_SOURCE[0]}")" -source "$dir/common-test.sh" - -run "$test" diff --git a/mk/functions.mk b/mk/functions.mk deleted file mode 100644 index c48775db8..000000000 --- a/mk/functions.mk +++ /dev/null @@ -1,14 +0,0 @@ -# Utility function for recursively finding files, e.g. -# ‘$(call rwildcard, path/to/dir, *.c *.h)’. -rwildcard=$(foreach d,$(wildcard $1*),$(call rwildcard,$d/,$2) $(filter $(subst *,%,$2),$d)) - -# Given a file name, produce the corresponding dependency file -# (e.g. ‘foo/bar.o’ becomes ‘foo/.bar.o.dep’). -filename-to-dep = $(dir $1).$(notdir $1).dep - -# Return the full path to a program by looking it up in $PATH, or the -# empty string if not found. -find-program = $(shell for i in $$(IFS=: ; echo $$PATH); do p=$$i/$(strip $1); if [ -e $$p ]; then echo $$p; break; fi; done) - -# Ensure that the given string ends in a single slash. -add-trailing-slash = $(patsubst %/,%,$(1))/ diff --git a/mk/install-dirs.mk b/mk/install-dirs.mk deleted file mode 100644 index 732b0d6fc..000000000 --- a/mk/install-dirs.mk +++ /dev/null @@ -1,11 +0,0 @@ -# Default installation paths. -prefix ?= /usr/local -libdir ?= $(prefix)/lib -bindir ?= $(prefix)/bin -libexecdir ?= $(prefix)/libexec -datadir ?= $(prefix)/share -localstatedir ?= $(prefix)/var -sysconfdir ?= $(prefix)/etc -mandir ?= $(prefix)/share/man - -DESTDIR ?= diff --git a/mk/install.mk b/mk/install.mk deleted file mode 100644 index dad0fd853..000000000 --- a/mk/install.mk +++ /dev/null @@ -1,62 +0,0 @@ -# Add a rule for creating $(1) as a directory. This template may be -# called multiple times for the same directory. -define create-dir - _i := $$(call add-trailing-slash, $(DESTDIR)$$(strip $(1))) - ifndef $$(_i)_SEEN - $$(_i)_SEEN = 1 - $$(_i): - $$(trace-mkdir) install -d "$$@" - endif -endef - - -# Add a rule for installing file $(1) as file $(2) with mode $(3). -# The directory containing $(2) will be created automatically. -define install-file-as - - _i := $(DESTDIR)$$(strip $(2)) - - install: $$(_i) - - $$(_i): $(1) | $$(dir $$(_i)) - $$(trace-install) install -m $(3) $(1) "$$@" - - $$(eval $$(call create-dir, $$(dir $(2)))) - -endef - - -# Add a rule for installing file $(1) in directory $(2) with mode -# $(3). The directory will be created automatically. -define install-file-in - $$(eval $$(call install-file-as,$(1),$(2)/$$(notdir $(1)),$(3))) -endef - - -define install-program-in - $$(eval $$(call install-file-in,$(1),$(2),0755)) -endef - - -define install-data-in - $$(eval $$(call install-file-in,$(1),$(2),0644)) -endef - - -# Install a symlink from $(2) to $(1). Note that $(1) need not exist. -define install-symlink - - _i := $(DESTDIR)$$(strip $(2)) - - install: $$(_i) - - $$(_i): | $$(dir $$(_i)) - $$(trace-install) ln -sfn $(1) "$$@" - - $$(eval $$(call create-dir, $$(dir $(2)))) - -endef - - -print-top-help += \ - echo " install: Install into \$$(prefix) (currently set to '$(prefix)')"; diff --git a/mk/lib.mk b/mk/lib.mk deleted file mode 100644 index 1e7af6ad5..000000000 --- a/mk/lib.mk +++ /dev/null @@ -1,159 +0,0 @@ -default: all - - -# Get rid of default suffixes. FIXME: is this a good idea? -.SUFFIXES: - - -# Initialise some variables. -bin-scripts := -noinst-scripts := -man-pages := -install-tests := -install-tests-groups := - -include mk/platform.mk - -# Hack to define a literal space. -space := -space += - - -# Hack to define a literal newline. -define newline - - -endef - - -# Pass -fPIC if we're building dynamic libraries. -BUILD_SHARED_LIBS ?= 1 - -ifeq ($(BUILD_SHARED_LIBS), 1) - ifdef HOST_CYGWIN - GLOBAL_CFLAGS += -U__STRICT_ANSI__ -D_GNU_SOURCE - GLOBAL_CXXFLAGS += -U__STRICT_ANSI__ -D_GNU_SOURCE - else - GLOBAL_CFLAGS += -fPIC - GLOBAL_CXXFLAGS += -fPIC - endif - ifndef HOST_DARWIN - ifndef HOST_SOLARIS - ifndef HOST_FREEBSD - GLOBAL_LDFLAGS += -Wl,--no-copy-dt-needed-entries - endif - endif - endif - SET_RPATH_TO_LIBS ?= 1 -endif - -# Pass -g if we want debug info. -BUILD_DEBUG ?= 1 - -ifeq ($(BUILD_DEBUG), 1) - GLOBAL_CFLAGS += -g - GLOBAL_CXXFLAGS += -g -endif - - -include mk/build-dir.mk -include mk/install-dirs.mk -include mk/functions.mk -include mk/tracing.mk -include mk/clean.mk -include mk/install.mk -include mk/libraries.mk -include mk/programs.mk -include mk/patterns.mk -include mk/templates.mk -include mk/cxx-big-literal.mk -include mk/tests.mk -include mk/compilation-database.mk - - -# Include all sub-Makefiles. -define include-sub-makefile - d := $$(patsubst %/,%,$$(dir $(1))) - include $(1) -endef - -$(foreach mf, $(makefiles), $(eval $(call include-sub-makefile,$(mf)))) - - -# Instantiate stuff. -$(foreach lib, $(libraries), $(eval $(call build-library,$(lib)))) -$(foreach prog, $(programs), $(eval $(call build-program,$(prog)))) -$(foreach script, $(bin-scripts), $(eval $(call install-program-in,$(script),$(bindir)))) -$(foreach script, $(bin-scripts), $(eval programs-list += $(script))) -$(foreach script, $(noinst-scripts), $(eval programs-list += $(script))) -$(foreach template, $(template-files), $(eval $(call instantiate-template,$(template)))) -$(foreach test, $(install-tests), \ - $(eval $(call run-test,$(test))) \ - $(eval installcheck: $(test).test)) -$(foreach test-group, $(install-tests-groups), \ - $(eval $(call run-test-group,$(test-group))) \ - $(eval installcheck: $(test-group).test-group) \ - $(foreach test, $($(test-group)-tests), \ - $(eval $(call run-test,$(test))) \ - $(eval $(test-group).test-group: $(test).test))) - -# Compilation database. -$(foreach lib, $(libraries), $(eval $(call write-compile-commands,$(lib)))) -$(foreach prog, $(programs), $(eval $(call write-compile-commands,$(prog)))) - -compile_commands.json: $(compile-commands-json-files) - @jq --slurp '.' $^ >$@ - -# Include makefiles requiring built programs. -$(foreach mf, $(makefiles-late), $(eval $(call include-sub-makefile,$(mf)))) - - -$(foreach file, $(man-pages), $(eval $(call install-data-in, $(file), $(mandir)/man$(patsubst .%,%,$(suffix $(file)))))) - - -.PHONY: default all man help - -all: $(programs-list) $(libs-list) $(man-pages) - -man: $(man-pages) - - -help: - @echo "The following targets are available:" - @echo "" - @echo " default: Build default targets" -ifdef man-pages - @echo " man: Generate manual pages" -endif - @$(print-top-help) -ifdef programs-list - @echo "" - @echo "The following programs can be built:" - @echo "" - @for i in $(programs-list); do echo " $$i"; done -endif -ifdef libs-list - @echo "" - @echo "The following libraries can be built:" - @echo "" - @for i in $(libs-list); do echo " $$i"; done -endif -ifdef install-tests-groups - @echo "" - @echo "The following groups of functional tests can be run:" - @echo "" - @for i in $(install-tests-groups); do echo " $$i.test-group"; done - @echo "" - @echo "(installcheck includes tests in test groups too.)" -endif - @echo "" - @echo "The following variables control the build:" - @echo "" - @echo " BUILD_SHARED_LIBS ($(BUILD_SHARED_LIBS)): Whether to build shared libraries" - @echo " BUILD_DEBUG ($(BUILD_DEBUG)): Whether to include debug symbols" - @echo " CC ($(CC)): C compiler to be used" - @echo " CFLAGS: Flags for the C compiler" - @echo " CXX ($(CXX)): C++ compiler to be used" - @echo " CXXFLAGS: Flags for the C++ compiler" - @echo " CPPFLAGS: C preprocessor flags, used for both CC and CXX" - @$(print-var-help) diff --git a/mk/libraries.mk b/mk/libraries.mk deleted file mode 100644 index a7848ba35..000000000 --- a/mk/libraries.mk +++ /dev/null @@ -1,173 +0,0 @@ -libs-list := - -ifdef HOST_DARWIN - SO_EXT = dylib -else - ifdef HOST_WINDOWS - SO_EXT = dll - else - SO_EXT = so - endif -endif - -ifdef HOST_UNIX - THREAD_LDFLAGS = -pthread -else - THREAD_LDFLAGS = -endif - -# Build a library with symbolic name $(1). The library is defined by -# various variables prefixed by ‘$(1)_’: -# -# - $(1)_NAME: the name of the library (e.g. ‘libfoo’); defaults to -# $(1). -# -# - $(1)_DIR: the directory where the (non-installed) library will be -# placed. -# -# - $(1)_SOURCES: the source files of the library. -# -# - $(1)_CFLAGS: additional C compiler flags. -# -# - $(1)_CXXFLAGS: additional C++ compiler flags. -# -# - $(1)_ORDER_AFTER: a set of targets on which the object files of -# this libraries will have an order-only dependency. -# -# - $(1)_LIBS: the symbolic names of other libraries on which this -# library depends. -# -# - $(1)_ALLOW_UNDEFINED: if set, the library is allowed to have -# undefined symbols. Has no effect for static libraries. -# -# - $(1)_LDFLAGS: additional linker flags. -# -# - $(1)_LDFLAGS_PROPAGATED: additional linker flags, also propagated -# to the linking of programs/libraries that use this library. -# -# - $(1)_FORCE_INSTALL: if defined, the library will be installed even -# if it's not needed (i.e. dynamically linked) by a program. -# -# - $(1)_INSTALL_DIR: the directory where the library will be -# installed. Defaults to $(libdir). -# -# - $(1)_EXCLUDE_FROM_LIBRARY_LIST: if defined, the library will not -# be automatically marked as a dependency of the top-level all -# target andwill not be listed in the make help output. This is -# useful for libraries built solely for testing, for example. -# -# - BUILD_SHARED_LIBS: if equal to ‘1’, a dynamic library will be -# built, otherwise a static library. -define build-library - $(1)_NAME ?= $(1) - _d := $(buildprefix)$$(strip $$($(1)_DIR)) - _srcs := $$(sort $$(foreach src, $$($(1)_SOURCES), $$(src))) - $(1)_OBJS := $$(addprefix $(buildprefix), $$(addsuffix .o, $$(basename $$(_srcs)))) - _libs := $$(foreach lib, $$($(1)_LIBS), $$($$(lib)_PATH)) - - ifdef HOST_WINDOWS - $(1)_INSTALL_DIR ?= $$(bindir) - else - $(1)_INSTALL_DIR ?= $$(libdir) - endif - - $(1)_LDFLAGS_USE := - $(1)_LDFLAGS_USE_INSTALLED := - $(1)_LIB_CLOSURE := $(1) - - $$(eval $$(call create-dir, $$(_d))) - - ifeq ($(BUILD_SHARED_LIBS), 1) - - ifdef $(1)_ALLOW_UNDEFINED - ifdef HOST_DARWIN - $(1)_LDFLAGS += -undefined suppress -flat_namespace - endif - else - ifndef HOST_DARWIN - ifndef HOST_WINDOWS - ifndef HOST_OPENBSD - $(1)_LDFLAGS += -Wl,-z,defs - endif - endif - endif - endif - - ifndef HOST_DARWIN - $(1)_LDFLAGS += -Wl,-soname=$$($(1)_NAME).$(SO_EXT) - endif - - $(1)_PATH := $$(_d)/$$($(1)_NAME).$(SO_EXT) - - $$($(1)_PATH): $$($(1)_OBJS) $$(_libs) | $$(_d)/ - +$$(trace-ld) $(CXX) -o $$(abspath $$@) -shared $$(LDFLAGS) $$(GLOBAL_LDFLAGS) $$($(1)_OBJS) $$($(1)_LDFLAGS) $$($(1)_LDFLAGS_PROPAGATED) $$(foreach lib, $$($(1)_LIBS), $$($$(lib)_LDFLAGS_USE)) $$($(1)_LDFLAGS_UNINSTALLED) - - ifndef HOST_DARWIN - $(1)_LDFLAGS_USE += -Wl,-rpath,$$(abspath $$(_d)) - endif - $(1)_LDFLAGS_USE += -L$$(_d) -l$$(patsubst lib%,%,$$(strip $$($(1)_NAME))) - - $(1)_INSTALL_PATH := $(DESTDIR)$$($(1)_INSTALL_DIR)/$$($(1)_NAME).$(SO_EXT) - - _libs_final := $$(foreach lib, $$($(1)_LIBS), $$($$(lib)_INSTALL_PATH)) - - $$(eval $$(call create-dir, $$($(1)_INSTALL_DIR))) - - $$($(1)_INSTALL_PATH): $$($(1)_OBJS) $$(_libs_final) | $(DESTDIR)$$($(1)_INSTALL_DIR)/ - +$$(trace-ld) $(CXX) -o $$@ -shared $$(LDFLAGS) $$(GLOBAL_LDFLAGS) $$($(1)_OBJS) $$($(1)_LDFLAGS) $$($(1)_LDFLAGS_PROPAGATED) $$(foreach lib, $$($(1)_LIBS), $$($$(lib)_LDFLAGS_USE_INSTALLED)) - - $(1)_LDFLAGS_USE_INSTALLED += -L$$(DESTDIR)$$($(1)_INSTALL_DIR) -l$$(patsubst lib%,%,$$(strip $$($(1)_NAME))) - ifndef HOST_DARWIN - ifeq ($(SET_RPATH_TO_LIBS), 1) - $(1)_LDFLAGS_USE_INSTALLED += -Wl,-rpath,$$($(1)_INSTALL_DIR) - else - $(1)_LDFLAGS_USE_INSTALLED += -Wl,-rpath-link,$$($(1)_INSTALL_DIR) - endif - endif - - ifdef $(1)_FORCE_INSTALL - install: $$($(1)_INSTALL_PATH) - endif - - else - - $(1)_PATH := $$(_d)/$$($(1)_NAME).a - - $$($(1)_PATH): $$($(1)_OBJS) | $$(_d)/ - $$(trace-ld) $(LD) $$(ifndef $(HOST_DARWIN),-U) -r -o $$(_d)/$$($(1)_NAME).o $$^ - $$(trace-ar) $(AR) crs $$@ $$(_d)/$$($(1)_NAME).o - - $(1)_LDFLAGS_USE += $$($(1)_PATH) $$($(1)_LDFLAGS) $$(foreach lib, $$($(1)_LIBS), $$($$(lib)_LDFLAGS_USE)) - - $(1)_INSTALL_PATH := $$(libdir)/$$($(1)_NAME).a - - $(1)_LIB_CLOSURE += $$($(1)_LIBS) - - endif - - $(1)_LDFLAGS_USE += $$($(1)_LDFLAGS_PROPAGATED) - $(1)_LDFLAGS_USE_INSTALLED += $$($(1)_LDFLAGS_PROPAGATED) - - # Propagate CFLAGS and CXXFLAGS to the individual object files. - $$(foreach obj, $$($(1)_OBJS), $$(eval $$(obj)_CFLAGS=$$($(1)_CFLAGS))) - $$(foreach obj, $$($(1)_OBJS), $$(eval $$(obj)_CXXFLAGS=$$($(1)_CXXFLAGS))) - - # Make each object file depend on the common dependencies. - $$(foreach obj, $$($(1)_OBJS), $$(eval $$(obj): $$($(1)_COMMON_DEPS) $$(GLOBAL_COMMON_DEPS))) - - # Make each object file have order-only dependencies on the common - # order-only dependencies. This includes the order-only dependencies - # of libraries we're depending on. - $(1)_ORDER_AFTER_CLOSED = $$($(1)_ORDER_AFTER) $$(foreach lib, $$($(1)_LIBS), $$($$(lib)_ORDER_AFTER_CLOSED)) - - $$(foreach obj, $$($(1)_OBJS), $$(eval $$(obj): | $$($(1)_ORDER_AFTER_CLOSED) $$(GLOBAL_ORDER_AFTER))) - - # Include .dep files, if they exist. - $(1)_DEPS := $$(foreach fn, $$($(1)_OBJS), $$(call filename-to-dep, $$(fn))) - -include $$($(1)_DEPS) - - ifndef $(1)_EXCLUDE_FROM_LIBRARY_LIST - libs-list += $$($(1)_PATH) - endif - clean-files += $$(_d)/*.a $$(_d)/*.$(SO_EXT) $$(_d)/*.o $$(_d)/.*.dep $$($(1)_DEPS) $$($(1)_OBJS) -endef diff --git a/mk/patterns.mk b/mk/patterns.mk deleted file mode 100644 index 4caa2039e..000000000 --- a/mk/patterns.mk +++ /dev/null @@ -1,41 +0,0 @@ - -# These are the complete command lines we use to compile C and C++ files. -# - $< is the source file. -# - $1 is the object file to create. -CC_CMD=$(CC) -o $1 -c $< $(CPPFLAGS) $(GLOBAL_CFLAGS) $(CFLAGS) $($1_CFLAGS) -MMD -MF $(call filename-to-dep,$1) -MP -CXX_CMD=$(CXX) -o $1 -c $< $(CPPFLAGS) $(GLOBAL_CXXFLAGS_PCH) $(GLOBAL_CXXFLAGS) $(CXXFLAGS) $($1_CXXFLAGS) $(ERROR_SWITCH_ENUM) -MMD -MF $(call filename-to-dep,$1) -MP - -# We use COMPILE_COMMANDS_JSON_CMD to turn a compilation command (like CC_CMD -# or CXX_CMD above) into a comple_commands.json file. We rely on bash native -# word splitting to define the positional arguments. -# - $< is the source file being compiled. -COMPILE_COMMANDS_JSON_CMD=jq --null-input '{ directory: $$ENV.PWD, file: "$<", arguments: $$ARGS.positional }' --args -- - - -$(buildprefix)%.o: %.cc - @mkdir -p "$(dir $@)" - $(trace-cxx) $(call CXX_CMD,$@) - -$(buildprefix)%.o: %.cpp - @mkdir -p "$(dir $@)" - $(trace-cxx) $(call CXX_CMD,$@) - -$(buildprefix)%.o: %.c - @mkdir -p "$(dir $@)" - $(trace-cc) $(call CC_CMD,$@) - -# In the following we need to replace the .compile_commands.json extension in $@ with .o -# to make the object file. This is needed because CC_CMD and CXX_CMD do further expansions -# based on the object file name (i.e. *_CXXFLAGS and filename-to-dep). - -$(buildprefix)%.compile_commands.json: %.cc - @mkdir -p "$(dir $@)" - $(trace-jq) $(COMPILE_COMMANDS_JSON_CMD) $(call CXX_CMD,$(@:.compile_commands.json=.o)) > $@ - -$(buildprefix)%.compile_commands.json: %.cpp - @mkdir -p "$(dir $@)" - $(trace-jq) $(COMPILE_COMMANDS_JSON_CMD) $(call CXX_CMD,$(@:.compile_commands.json=.o)) > $@ - -$(buildprefix)%.compile_commands.json: %.c - @mkdir -p "$(dir $@)" - $(trace-jq) $(COMPILE_COMMANDS_JSON_CMD) $(call CC_CMD,$(@:.compile_commands.json=.o)) > $@ diff --git a/mk/platform.mk b/mk/platform.mk deleted file mode 100644 index 3c4fff780..000000000 --- a/mk/platform.mk +++ /dev/null @@ -1,40 +0,0 @@ -ifdef HOST_OS - HOST_KERNEL = $(firstword $(subst -, ,$(HOST_OS))) - ifeq ($(patsubst mingw%,,$(HOST_KERNEL)),) - HOST_MINGW = 1 - HOST_WINDOWS = 1 - endif - ifeq ($(HOST_KERNEL), cygwin) - HOST_CYGWIN = 1 - HOST_WINDOWS = 1 - HOST_UNIX = 1 - endif - ifeq ($(patsubst darwin%,,$(HOST_KERNEL)),) - HOST_DARWIN = 1 - HOST_UNIX = 1 - endif - ifeq ($(patsubst freebsd%,,$(HOST_KERNEL)),) - HOST_FREEBSD = 1 - HOST_UNIX = 1 - endif - ifeq ($(patsubst netbsd%,,$(HOST_KERNEL)),) - HOST_NETBSD = 1 - HOST_UNIX = 1 - endif - ifeq ($(patsubst openbsd%,,$(HOST_KERNEL)),) - HOST_OPENBSD = 1 - HOST_UNIX = 1 - endif - ifeq ($(HOST_KERNEL), linux) - HOST_LINUX = 1 - HOST_UNIX = 1 - endif - ifeq ($(patsubst solaris%,,$(HOST_KERNEL)),) - HOST_SOLARIS = 1 - HOST_UNIX = 1 - endif - ifeq ($(HOST_KERNEL), gnu) - HOST_HURD = 1 - HOST_UNIX = 1 - endif -endif diff --git a/mk/precompiled-headers.mk b/mk/precompiled-headers.mk deleted file mode 100644 index f2803eb79..000000000 --- a/mk/precompiled-headers.mk +++ /dev/null @@ -1,21 +0,0 @@ -PRECOMPILE_HEADERS ?= 0 - -print-var-help += \ - echo " PRECOMPILE_HEADERS ($(PRECOMPILE_HEADERS)): Whether to use precompiled headers to speed up the build"; - -GCH = $(buildprefix)precompiled-headers.h.gch - -$(GCH): precompiled-headers.h - @rm -f $@ - @mkdir -p "$(dir $@)" - $(trace-gen) $(CXX) -c -x c++-header -o $@ $< $(GLOBAL_CXXFLAGS) $(GCH_CXXFLAGS) - -clean-files += $(GCH) - -ifeq ($(PRECOMPILE_HEADERS), 1) - - GLOBAL_CXXFLAGS_PCH += -include $(buildprefix)precompiled-headers.h -Winvalid-pch - - GLOBAL_ORDER_AFTER += $(GCH) - -endif diff --git a/mk/programs.mk b/mk/programs.mk deleted file mode 100644 index 623caaf55..000000000 --- a/mk/programs.mk +++ /dev/null @@ -1,98 +0,0 @@ -programs-list := - -ifdef HOST_WINDOWS - EXE_EXT = .exe -else - EXE_EXT = -endif - -# Build a program with symbolic name $(1). The program is defined by -# various variables prefixed by ‘$(1)_’: -# -# - $(1)_NAME: the name of the program (e.g. ‘foo’); defaults to -# $(1). -# -# - $(1)_DIR: the directory where the (non-installed) program will be -# placed. -# -# - $(1)_SOURCES: the source files of the program. -# -# - $(1)_CFLAGS: additional C compiler flags. -# -# - $(1)_CXXFLAGS: additional C++ compiler flags. -# -# - $(1)_ORDER_AFTER: a set of targets on which the object files of -# this program will have an order-only dependency. -# -# - $(1)_LIBS: the symbolic names of libraries on which this program -# depends. -# -# - $(1)_LDFLAGS: additional linker flags. -# -# - $(1)_INSTALL_DIR: the directory where the program will be -# installed; defaults to $(bindir). -define build-program - $(1)_NAME ?= $(1) - _d := $(buildprefix)$$($(1)_DIR) - _srcs := $$(sort $$(foreach src, $$($(1)_SOURCES), $$(src))) - $(1)_OBJS := $$(addprefix $(buildprefix), $$(addsuffix .o, $$(basename $$(_srcs)))) - _libs := $$(foreach lib, $$($(1)_LIBS), $$(foreach lib2, $$($$(lib)_LIB_CLOSURE), $$($$(lib2)_PATH))) - $(1)_PATH := $$(_d)/$$($(1)_NAME)$(EXE_EXT) - - $$(eval $$(call create-dir, $$(_d))) - - $$($(1)_PATH): $$($(1)_OBJS) $$(_libs) | $$(_d)/ - +$$(trace-ld) $(CXX) -o $$@ $$(LDFLAGS) $$(GLOBAL_LDFLAGS) $$($(1)_OBJS) $$($(1)_LDFLAGS) $$(foreach lib, $$($(1)_LIBS), $$($$(lib)_LDFLAGS_USE)) - - $(1)_INSTALL_DIR ?= $$(bindir) - - ifdef $(1)_INSTALL_DIR - - $(1)_INSTALL_PATH := $$($(1)_INSTALL_DIR)/$$($(1)_NAME)$(EXE_EXT) - - $$(eval $$(call create-dir, $$($(1)_INSTALL_DIR))) - - install: $(DESTDIR)$$($(1)_INSTALL_PATH) - - ifeq ($(BUILD_SHARED_LIBS), 1) - - _libs_final := $$(foreach lib, $$($(1)_LIBS), $$($$(lib)_INSTALL_PATH)) - - $(DESTDIR)$$($(1)_INSTALL_PATH): $$($(1)_OBJS) $$(_libs_final) | $(DESTDIR)$$($(1)_INSTALL_DIR)/ - +$$(trace-ld) $(CXX) -o $$@ $$(LDFLAGS) $$(GLOBAL_LDFLAGS) $$($(1)_OBJS) $$($(1)_LDFLAGS) $$(foreach lib, $$($(1)_LIBS), $$($$(lib)_LDFLAGS_USE_INSTALLED)) - - else - - $(DESTDIR)$$($(1)_INSTALL_PATH): $$($(1)_PATH) | $(DESTDIR)$$($(1)_INSTALL_DIR)/ - +$$(trace-install) install -t $(DESTDIR)$$($(1)_INSTALL_DIR) $$< - - endif - endif - - # Propagate CFLAGS and CXXFLAGS to the individual object files. - $$(foreach obj, $$($(1)_OBJS), $$(eval $$(obj)_CFLAGS=$$($(1)_CFLAGS))) - $$(foreach obj, $$($(1)_OBJS), $$(eval $$(obj)_CXXFLAGS=$$($(1)_CXXFLAGS))) - - # Make each object file depend on the common dependencies. - $$(foreach obj, $$($(1)_OBJS), $$(eval $$(obj): $$($(1)_COMMON_DEPS) $$(GLOBAL_COMMON_DEPS))) - - # Make each object file have order-only dependencies on the common - # order-only dependencies. This includes the order-only dependencies - # of libraries we're depending on. - $(1)_ORDER_AFTER_CLOSED = $$($(1)_ORDER_AFTER) $$(foreach lib, $$($(1)_LIBS), $$($$(lib)_ORDER_AFTER_CLOSED)) - - $$(foreach obj, $$($(1)_OBJS), $$(eval $$(obj): | $$($(1)_ORDER_AFTER_CLOSED) $$(GLOBAL_ORDER_AFTER))) - - # Include .dep files, if they exist. - $(1)_DEPS := $$(foreach fn, $$($(1)_OBJS), $$(call filename-to-dep, $$(fn))) - -include $$($(1)_DEPS) - - programs-list += $$($(1)_PATH) - clean-files += $$($(1)_PATH) $$(_d)/*.o $$(_d)/.*.dep $$($(1)_DEPS) $$($(1)_OBJS) - - # Phony target to run this program (typically as a dependency of 'check'). - .PHONY: $(1)_RUN - $(1)_RUN: $$($(1)_PATH) - $(trace-test) $$($(1)_ENV) $$($(1)_PATH) - -endef diff --git a/mk/run-test.sh b/mk/run-test.sh deleted file mode 100755 index 7f9f1d5f8..000000000 --- a/mk/run-test.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash - -set -eu -o pipefail - -red="" -green="" -yellow="" -normal="" - -test=$1 - -dir="$(dirname "${BASH_SOURCE[0]}")" -source "$dir/common-test.sh" - -post_run_msg="ran test $test..." -if [ -t 1 ]; then - red="" - green="" - yellow="" - normal="" -fi - -run_test () { - log="$(run "$test" 2>&1)" && status=0 || status=$? -} - -run_test - -if [[ "$status" = 0 ]]; then - echo "$post_run_msg [${green}PASS$normal]" -elif [[ "$status" = 77 ]]; then - echo "$post_run_msg [${yellow}SKIP$normal]" -else - echo "$post_run_msg [${red}FAIL$normal]" - # shellcheck disable=SC2001 - echo "$log" | sed 's/^/ /' - exit "$status" -fi diff --git a/mk/templates.mk b/mk/templates.mk deleted file mode 100644 index d5dae61c7..000000000 --- a/mk/templates.mk +++ /dev/null @@ -1,19 +0,0 @@ -template-files := - -# Create the file $(1) from $(1).in by running config.status (which -# substitutes all ‘@var@’ variables set by the configure script). -define instantiate-template - - clean-files += $(1) - -endef - -ifneq ($(MAKECMDGOALS), clean) - -$(buildprefix)%.h: %.h.in $(buildprefix)config.status - $(trace-gen) rm -f $@ && cd $(buildprefixrel) && ./config.status --quiet --header=$(@:$(buildprefix)%=%) - -$(buildprefix)%: %.in $(buildprefix)config.status - $(trace-gen) rm -f $@ && cd $(buildprefixrel) && ./config.status --quiet --file=$(@:$(buildprefix)%=%) - -endif diff --git a/mk/tests.mk b/mk/tests.mk deleted file mode 100644 index 0a10f6d3b..000000000 --- a/mk/tests.mk +++ /dev/null @@ -1,30 +0,0 @@ -# Run program $1 as part of ‘make installcheck’. - -test-deps = - -define run-bash - - .PHONY: $1 - $1: $2 - @env BASH=$(bash) $(bash) $3 < /dev/null - -endef - -define run-test - - $(eval $(call run-bash,$1.test,$1 $(test-deps),mk/run-test.sh $1)) - $(eval $(call run-bash,$1.test-debug,$1 $(test-deps),mk/debug-test.sh $1)) - -endef - -define run-test-group - - .PHONY: $1.test-group - -endef - -.PHONY: check installcheck - -print-top-help += \ - echo " check: Run unit tests"; \ - echo " installcheck: Run functional tests"; diff --git a/mk/tracing.mk b/mk/tracing.mk deleted file mode 100644 index 09db1e617..000000000 --- a/mk/tracing.mk +++ /dev/null @@ -1,18 +0,0 @@ -V ?= 0 - -ifeq ($(V), 0) - - trace-gen = @echo " GEN " $@; - trace-cc = @echo " CC " $@; - trace-cxx = @echo " CXX " $@; - trace-ld = @echo " LD " $@; - trace-ar = @echo " AR " $@; - trace-install = @echo " INST " $@; - trace-mkdir = @echo " MKDIR " $@; - trace-test = @echo " TEST " $@; - trace-sh = @echo " SH " $@; - trace-jq = @echo " JQ " $@; - - suppress = @ - -endif diff --git a/package.nix b/package.nix deleted file mode 100644 index 8cbe325e9..000000000 --- a/package.nix +++ /dev/null @@ -1,366 +0,0 @@ -{ lib -, stdenv -, releaseTools -, autoconf-archive -, autoreconfHook -, aws-sdk-cpp -, boehmgc -, nlohmann_json -, bison -, boost -, brotli -, bzip2 -, curl -, editline -, readline -, flex -, git -, gtest -, jq -, libarchive -, libcpuid -, libgit2 -, libseccomp -, libsodium -, man -, darwin -, lowdown -, mdbook -, mdbook-linkcheck -, mercurial -, openssh -, openssl -, pkg-config -, rapidcheck -, sqlite -, toml11 -, unixtools -, xz - -, busybox-sandbox-shell ? null - -# Configuration Options -#: -# This probably seems like too many degrees of freedom, but it -# faithfully reflects how the underlying configure + make build system -# work. The top-level flake.nix will choose useful combinations of these -# options to CI. - -, pname ? "nix" - -, version -, versionSuffix - -# Whether to build Nix. Useful to skip for tasks like testing existing pre-built versions of Nix -, doBuild ? true - -# Run the unit tests as part of the build. See `installUnitTests` for an -# alternative to this. -, doCheck ? __forDefaults.canRunInstalled - -# Run the functional tests as part of the build. -, doInstallCheck ? test-client != null || __forDefaults.canRunInstalled - -# Check test coverage of Nix. Probably want to use with at least -# one of `doCHeck` or `doInstallCheck` enabled. -, withCoverageChecks ? false - -# Whether to build the regular manual -, enableManual ? __forDefaults.canRunInstalled - -# Whether to use garbage collection for the Nix language evaluator. -# -# If it is disabled, we just leak memory, but this is not as bad as it -# sounds so long as evaluation just takes places within short-lived -# processes. (When the process exits, the memory is reclaimed; it is -# only leaked *within* the process.) -# -# Temporarily disabled on Windows because the `GC_throw_bad_alloc` -# symbol is missing during linking. -# -# Disabled on OpenBSD because of missing `_data_start` symbol while linking -, enableGC ? !stdenv.hostPlatform.isWindows && !stdenv.hostPlatform.isOpenBSD - -# Whether to enable Markdown rendering in the Nix binary. -, enableMarkdown ? !stdenv.hostPlatform.isWindows - -# Which interactive line editor library to use for Nix's repl. -# -# Currently supported choices are: -# -# - editline (default) -# - readline -, readlineFlavor ? if stdenv.hostPlatform.isWindows then "readline" else "editline" - -# Whether to install unit tests. This is useful when cross compiling -# since we cannot run them natively during the build, but can do so -# later. -, installUnitTests ? doBuild && !__forDefaults.canExecuteHost - -# For running the functional tests against a pre-built Nix. Probably -# want to use in conjunction with `doBuild = false;`. -, test-daemon ? null -, test-client ? null - -# Avoid setting things that would interfere with a functioning devShell -, forDevShell ? false - -# Not a real argument, just the only way to approximate let-binding some -# stuff for argument defaults. -, __forDefaults ? { - canExecuteHost = stdenv.buildPlatform.canExecute stdenv.hostPlatform; - canRunInstalled = doBuild && __forDefaults.canExecuteHost; - } -}: - -let - inherit (lib) fileset; - - # selected attributes with defaults, will be used to define some - # things which should instead be gotten via `finalAttrs` in order to - # work with overriding. - attrs = { - inherit doBuild doCheck doInstallCheck; - }; - - mkDerivation = - if withCoverageChecks - then - # TODO support `finalAttrs` args function in - # `releaseTools.coverageAnalysis`. - argsFun: - releaseTools.coverageAnalysis (let args = argsFun args; in args) - else stdenv.mkDerivation; -in - -mkDerivation (finalAttrs: let - - inherit (finalAttrs) - doCheck - doInstallCheck - ; - - doBuild = !finalAttrs.dontBuild; - - # Either running the unit tests during the build, or installing them - # to be run later, requiresthe unit tests to be built. - buildUnitTests = doCheck || installUnitTests; - -in { - inherit pname version; - - src = - let - baseFiles = fileset.fileFilter (f: f.name != ".gitignore") ./.; - in - fileset.toSource { - root = ./.; - fileset = fileset.intersection baseFiles (fileset.unions ([ - # For configure - ./.version - ./configure.ac - ./m4 - # TODO: do we really need README.md? It doesn't seem used in the build. - ./README.md - # This could be put behind a conditional - ./maintainers/local.mk - # For make, regardless of what we are building - ./local.mk - ./Makefile - ./Makefile.config.in - ./mk - (fileset.fileFilter (f: lib.strings.hasPrefix "nix-profile" f.name) ./scripts) - ] ++ lib.optionals doBuild [ - ./doc - ./misc - ./precompiled-headers.h - (fileset.difference ./src ./src/perl) - ./COPYING - ./scripts/local.mk - ] ++ lib.optionals enableManual [ - ./doc/manual - ] ++ lib.optionals doInstallCheck [ - ./tests/functional - ])); - }; - - VERSION_SUFFIX = versionSuffix; - - outputs = [ "out" ] - ++ lib.optional doBuild "dev" - # If we are doing just build or just docs, the one thing will use - # "out". We only need additional outputs if we are doing both. - ++ lib.optional (doBuild && enableManual) "doc" - ++ lib.optional installUnitTests "check" - ++ lib.optional doCheck "testresults" - ; - - nativeBuildInputs = [ - autoconf-archive - autoreconfHook - pkg-config - ] ++ lib.optionals doBuild [ - bison - flex - ] ++ lib.optionals enableManual [ - (lib.getBin lowdown) - mdbook - mdbook-linkcheck - ] ++ lib.optionals doInstallCheck [ - git - mercurial - openssh - ] ++ lib.optionals (doInstallCheck || enableManual) [ - jq # Also for custom mdBook preprocessor. - ] ++ lib.optionals enableManual [ - man - ] ++ lib.optional stdenv.hostPlatform.isStatic unixtools.hexdump - ; - - buildInputs = lib.optionals doBuild ( - [ - brotli - bzip2 - curl - libarchive - libgit2 - libsodium - openssl - sqlite - toml11 - xz - ({ inherit readline editline; }.${readlineFlavor}) - ] ++ lib.optionals enableMarkdown [ - lowdown - ] ++ lib.optionals buildUnitTests [ - gtest - rapidcheck - ] ++ lib.optional stdenv.isLinux libseccomp - ++ lib.optional stdenv.hostPlatform.isDarwin darwin.apple_sdk.libs.sandbox - ++ lib.optional stdenv.hostPlatform.isx86_64 libcpuid - # There have been issues building these dependencies - ++ lib.optional (stdenv.hostPlatform == stdenv.buildPlatform && (stdenv.isLinux || stdenv.isDarwin)) - aws-sdk-cpp - ); - - propagatedBuildInputs = lib.optionals doBuild ([ - boost - nlohmann_json - ] ++ lib.optional enableGC boehmgc - ); - - dontBuild = !attrs.doBuild; - doCheck = attrs.doCheck; - - configureFlags = [ - (lib.enableFeature doBuild "build") - (lib.enableFeature buildUnitTests "unit-tests") - (lib.enableFeature doInstallCheck "functional-tests") - (lib.enableFeature enableManual "doc-gen") - (lib.enableFeature enableGC "gc") - (lib.enableFeature enableMarkdown "markdown") - (lib.enableFeature installUnitTests "install-unit-tests") - (lib.withFeatureAs true "readline-flavor" readlineFlavor) - ] ++ lib.optionals (!forDevShell) [ - "--sysconfdir=/etc" - ] ++ lib.optionals installUnitTests [ - "--with-check-bin-dir=${builtins.placeholder "check"}/bin" - "--with-check-lib-dir=${builtins.placeholder "check"}/lib" - ] ++ lib.optionals (doBuild) [ - "--with-boost=${boost}/lib" - ] ++ lib.optionals (doBuild && stdenv.isLinux) [ - "--with-sandbox-shell=${busybox-sandbox-shell}/bin/busybox" - ] ++ lib.optional (doBuild && stdenv.isLinux && !(stdenv.hostPlatform.isStatic && stdenv.system == "aarch64-linux")) - "LDFLAGS=-fuse-ld=gold" - ++ lib.optional (doBuild && stdenv.hostPlatform.isStatic) "--enable-embedded-sandbox-shell" - ; - - enableParallelBuilding = true; - - makeFlags = "profiledir=$(out)/etc/profile.d PRECOMPILE_HEADERS=1"; - - preCheck = '' - mkdir $testresults - ''; - - installTargets = lib.optional doBuild "install"; - - installFlags = "sysconfdir=$(out)/etc"; - - # In this case we are probably just running tests, and so there isn't - # anything to install, we just make an empty directory to signify tests - # succeeded. - installPhase = if finalAttrs.installTargets != [] then null else '' - mkdir -p $out - ''; - - postInstall = lib.optionalString doBuild ( - lib.optionalString stdenv.hostPlatform.isStatic '' - mkdir -p $out/nix-support - echo "file binary-dist $out/bin/nix" >> $out/nix-support/hydra-build-products - '' - ) + lib.optionalString enableManual '' - mkdir -p ''${!outputDoc}/nix-support - echo "doc manual ''${!outputDoc}/share/doc/nix/manual" >> ''${!outputDoc}/nix-support/hydra-build-products - ''; - - # So the check output gets links for DLLs in the out output. - preFixup = lib.optionalString (stdenv.hostPlatform.isWindows && builtins.elem "check" finalAttrs.outputs) '' - ln -s "$check/lib/"*.dll "$check/bin" - ln -s "$out/bin/"*.dll "$check/bin" - ''; - - doInstallCheck = attrs.doInstallCheck; - - installCheckFlags = "sysconfdir=$(out)/etc"; - # Work around buggy detection in stdenv. - installCheckTarget = "installcheck"; - - # Work around weird bug where it doesn't think there is a Makefile. - installCheckPhase = if (!doBuild && doInstallCheck) then '' - runHook preInstallCheck - mkdir -p src/nix-channel - make installcheck -j$NIX_BUILD_CORES -l$NIX_BUILD_CORES - '' else null; - - # Needed for tests if we are not doing a build, but testing existing - # built Nix. - preInstallCheck = - lib.optionalString (! doBuild) '' - mkdir -p src/nix-channel - ''; - - separateDebugInfo = !stdenv.hostPlatform.isStatic; - - # TODO Always true after https://github.com/NixOS/nixpkgs/issues/318564 - strictDeps = !withCoverageChecks; - - hardeningDisable = lib.optional stdenv.hostPlatform.isStatic "pie"; - - meta = { - platforms = lib.platforms.unix ++ lib.platforms.windows; - mainProgram = "nix"; - broken = !(lib.all (a: a) [ - # We cannot run or install unit tests if we don't build them or - # Nix proper (which they depend on). - (installUnitTests -> doBuild) - (doCheck -> doBuild) - # The build process for the manual currently requires extracting - # data from the Nix executable we are trying to document. - (enableManual -> doBuild) - ]); - }; - -} // lib.optionalAttrs withCoverageChecks { - lcovFilter = [ "*/boost/*" "*-tab.*" ]; - - hardeningDisable = ["fortify"]; - - NIX_CFLAGS_COMPILE = "-DCOVERAGE=1"; - - dontInstall = false; -} // lib.optionalAttrs (test-daemon != null) { - NIX_DAEMON_PACKAGE = test-daemon; -} // lib.optionalAttrs (test-client != null) { - NIX_CLIENT_PACKAGE = test-client; -}) diff --git a/packaging/components.nix b/packaging/components.nix index 5cc0be784..c29e04ae9 100644 --- a/packaging/components.nix +++ b/packaging/components.nix @@ -25,11 +25,6 @@ in version = baseVersion + versionSuffix; inherit versionSuffix; - nix = callPackage ../package.nix { - version = fineVersion; - versionSuffix = fineVersionSuffix; - }; - nix-util = callPackage ../src/libutil/package.nix { }; nix-util-c = callPackage ../src/libutil-c/package.nix { }; nix-util-test-support = callPackage ../src/libutil-test-support/package.nix { }; @@ -66,6 +61,5 @@ in nix-perl-bindings = callPackage ../src/perl/package.nix { }; - # Will replace `nix` once the old build system is gone. - nix-ng = callPackage ../packaging/everything.nix { }; + nix-everything = callPackage ../packaging/everything.nix { }; } diff --git a/packaging/dependencies.nix b/packaging/dependencies.nix index 13766f2c0..a8005ce16 100644 --- a/packaging/dependencies.nix +++ b/packaging/dependencies.nix @@ -70,6 +70,9 @@ let pkgs.buildPackages.meson pkgs.buildPackages.ninja ] ++ prevAttrs.nativeBuildInputs or []; + mesonCheckFlags = prevAttrs.mesonCheckFlags or [] ++ [ + "--print-errorlogs" + ]; }; mesonBuildLayer = finalAttrs: prevAttrs: diff --git a/packaging/dev-shell.nix b/packaging/dev-shell.nix new file mode 100644 index 000000000..30ac518d5 --- /dev/null +++ b/packaging/dev-shell.nix @@ -0,0 +1,128 @@ +{ lib, devFlake }: + +{ pkgs }: + +pkgs.nixComponents.nix-util.overrideAttrs (attrs: + +let + stdenv = pkgs.nixDependencies.stdenv; + buildCanExecuteHost = stdenv.buildPlatform.canExecute stdenv.hostPlatform; + modular = devFlake.getSystem stdenv.buildPlatform.system; + transformFlag = prefix: flag: + assert builtins.isString flag; + let + rest = builtins.substring 2 (builtins.stringLength flag) flag; + in + "-D${prefix}:${rest}"; + havePerl = stdenv.buildPlatform == stdenv.hostPlatform && stdenv.hostPlatform.isUnix; + ignoreCrossFile = flags: builtins.filter (flag: !(lib.strings.hasInfix "cross-file" flag)) flags; +in { + pname = "shell-for-" + attrs.pname; + + # Remove the version suffix to avoid unnecessary attempts to substitute in nix develop + version = lib.fileContents ../.version; + name = attrs.pname; + + installFlags = "sysconfdir=$(out)/etc"; + shellHook = '' + PATH=$prefix/bin:$PATH + unset PYTHONPATH + export MANPATH=$out/share/man:$MANPATH + + # Make bash completion work. + XDG_DATA_DIRS+=:$out/share + + # Make the default phases do the right thing. + # FIXME: this wouldn't be needed if the ninja package set buildPhase() instead of $buildPhase. + # FIXME: mesonConfigurePhase shouldn't cd to the build directory. It would be better to pass '-C ' to ninja. + + cdToBuildDir() { + if [[ ! -e build.ninja ]]; then + cd build + fi + } + + configurePhase() { + mesonConfigurePhase + } + + buildPhase() { + cdToBuildDir + ninjaBuildPhase + } + + checkPhase() { + cdToBuildDir + mesonCheckPhase + } + + installPhase() { + cdToBuildDir + ninjaInstallPhase + } + ''; + + # We use this shell with the local checkout, not unpackPhase. + src = null; + + env = { + # Needed for Meson to find Boost. + # https://github.com/NixOS/nixpkgs/issues/86131. + BOOST_INCLUDEDIR = "${lib.getDev pkgs.nixDependencies.boost}/include"; + BOOST_LIBRARYDIR = "${lib.getLib pkgs.nixDependencies.boost}/lib"; + # For `make format`, to work without installing pre-commit + _NIX_PRE_COMMIT_HOOKS_CONFIG = + "${(pkgs.formats.yaml { }).generate "pre-commit-config.yaml" modular.pre-commit.settings.rawConfig}"; + }; + + mesonFlags = + map (transformFlag "libutil") (ignoreCrossFile pkgs.nixComponents.nix-util.mesonFlags) + ++ map (transformFlag "libstore") (ignoreCrossFile pkgs.nixComponents.nix-store.mesonFlags) + ++ map (transformFlag "libfetchers") (ignoreCrossFile pkgs.nixComponents.nix-fetchers.mesonFlags) + ++ lib.optionals havePerl (map (transformFlag "perl") (ignoreCrossFile pkgs.nixComponents.nix-perl-bindings.mesonFlags)) + ++ map (transformFlag "libexpr") (ignoreCrossFile pkgs.nixComponents.nix-expr.mesonFlags) + ++ map (transformFlag "libcmd") (ignoreCrossFile pkgs.nixComponents.nix-cmd.mesonFlags) + ; + + nativeBuildInputs = attrs.nativeBuildInputs or [] + ++ pkgs.nixComponents.nix-util.nativeBuildInputs + ++ pkgs.nixComponents.nix-store.nativeBuildInputs + ++ pkgs.nixComponents.nix-fetchers.nativeBuildInputs + ++ pkgs.nixComponents.nix-expr.nativeBuildInputs + ++ lib.optionals havePerl pkgs.nixComponents.nix-perl-bindings.nativeBuildInputs + ++ lib.optionals buildCanExecuteHost pkgs.nixComponents.nix-manual.externalNativeBuildInputs + ++ pkgs.nixComponents.nix-internal-api-docs.nativeBuildInputs + ++ pkgs.nixComponents.nix-external-api-docs.nativeBuildInputs + ++ pkgs.nixComponents.nix-functional-tests.externalNativeBuildInputs + ++ lib.optional + (!buildCanExecuteHost + # Hack around https://github.com/nixos/nixpkgs/commit/bf7ad8cfbfa102a90463433e2c5027573b462479 + && !(stdenv.hostPlatform.isWindows && stdenv.buildPlatform.isDarwin) + && stdenv.hostPlatform.emulatorAvailable pkgs.buildPackages + && lib.meta.availableOn stdenv.buildPlatform (stdenv.hostPlatform.emulator pkgs.buildPackages)) + pkgs.buildPackages.mesonEmulatorHook + ++ [ + pkgs.buildPackages.cmake + pkgs.buildPackages.shellcheck + pkgs.buildPackages.changelog-d + modular.pre-commit.settings.package + (pkgs.writeScriptBin "pre-commit-hooks-install" + modular.pre-commit.settings.installationScript) + ] + # TODO: Remove the darwin check once + # https://github.com/NixOS/nixpkgs/pull/291814 is available + ++ lib.optional (stdenv.cc.isClang && !stdenv.buildPlatform.isDarwin) pkgs.buildPackages.bear + ++ lib.optional (stdenv.cc.isClang && stdenv.hostPlatform == stdenv.buildPlatform) (lib.hiPrio pkgs.buildPackages.clang-tools); + + buildInputs = attrs.buildInputs or [] + ++ pkgs.nixComponents.nix-util.buildInputs + ++ pkgs.nixComponents.nix-store.buildInputs + ++ pkgs.nixComponents.nix-store-tests.externalBuildInputs + ++ pkgs.nixComponents.nix-fetchers.buildInputs + ++ pkgs.nixComponents.nix-expr.buildInputs + ++ pkgs.nixComponents.nix-expr.externalPropagatedBuildInputs + ++ pkgs.nixComponents.nix-cmd.buildInputs + ++ lib.optionals havePerl pkgs.nixComponents.nix-perl-bindings.externalBuildInputs + ++ lib.optional havePerl pkgs.perl + ; +}) diff --git a/packaging/everything.nix b/packaging/everything.nix index ae2f93da0..b09b9d2a9 100644 --- a/packaging/everything.nix +++ b/packaging/everything.nix @@ -5,12 +5,10 @@ nix-util, nix-util-c, - nix-util-test-support, nix-util-tests, nix-store, nix-store-c, - nix-store-test-support, nix-store-tests, nix-fetchers, @@ -18,7 +16,6 @@ nix-expr, nix-expr-c, - nix-expr-test-support, nix-expr-tests, nix-flake, @@ -38,45 +35,80 @@ nix-external-api-docs, nix-perl-bindings, + + testers, + runCommand, }: +let + dev = stdenv.mkDerivation (finalAttrs: { + name = "nix-${nix-cli.version}-dev"; + pname = "nix"; + version = nix-cli.version; + dontUnpack = true; + dontBuild = true; + libs = map lib.getDev [ + nix-cmd + nix-expr + nix-expr-c + nix-fetchers + nix-flake + nix-main + nix-main-c + nix-store + nix-store-c + nix-util + nix-util-c + nix-perl-bindings + ]; + installPhase = '' + mkdir -p $out/nix-support + echo $libs >> $out/nix-support/propagated-build-inputs + ''; + passthru = { + tests = { + pkg-config = + testers.hasPkgConfigModules { + package = finalAttrs.finalPackage; + }; + }; + + # If we were to fully emulate output selection here, we'd confuse the Nix CLIs, + # because they rely on `drvPath`. + dev = finalAttrs.finalPackage.out; + + libs = throw "`nix.dev.libs` is not meant to be used; use `nix.libs` instead."; + }; + meta = { + pkgConfigModules = [ + "nix-cmd" + "nix-expr" + "nix-expr-c" + "nix-fetchers" + "nix-flake" + "nix-main" + "nix-main-c" + "nix-store" + "nix-store-c" + "nix-util" + "nix-util-c" + ]; + }; + }); + devdoc = buildEnv { + name = "nix-${nix-cli.version}-devdoc"; + paths = [ + nix-internal-api-docs + nix-external-api-docs + ]; + }; + +in (buildEnv { name = "nix-${nix-cli.version}"; paths = [ - nix-util - nix-util-c - nix-util-test-support - nix-util-tests - - nix-store - nix-store-c - nix-store-test-support - nix-store-tests - - nix-fetchers - nix-fetchers-tests - - nix-expr - nix-expr-c - nix-expr-test-support - nix-expr-tests - - nix-flake - nix-flake-tests - - nix-main - nix-main-c - - nix-cmd - nix-cli - - nix-manual - nix-internal-api-docs - nix-external-api-docs - - ] ++ lib.optionals (stdenv.buildPlatform.canExecute stdenv.hostPlatform) [ - nix-perl-bindings + nix-manual.man ]; meta.mainProgram = "nix"; @@ -85,16 +117,31 @@ doInstallCheck = true; checkInputs = [ - # Actually run the unit tests too + # Make sure the unit tests have passed nix-util-tests.tests.run nix-store-tests.tests.run nix-expr-tests.tests.run + nix-fetchers-tests.tests.run nix-flake-tests.tests.run - ]; + + # dev bundle is ok + # (checkInputs must be empty paths??) + (runCommand "check-pkg-config" { checked = dev.tests.pkg-config; } "mkdir $out") + ] ++ + (if stdenv.buildPlatform.canExecute stdenv.hostPlatform + then [ + # TODO: add perl.tests + nix-perl-bindings + ] + else [ + nix-perl-bindings + ]); installCheckInputs = [ nix-functional-tests ]; passthru = prevAttrs.passthru // { + inherit (nix-cli) version; + /** These are the libraries that are part of the Nix project. They are used by the Nix CLI and other tools. @@ -126,5 +173,26 @@ nix-main-c ; }; + + tests = prevAttrs.passthru.tests or {} // { + # TODO: create a proper fixpoint and: + # pkg-config = + # testers.hasPkgConfigModules { + # package = finalPackage; + # }; + }; + + /** + A derivation referencing the `dev` outputs of the Nix libraries. + */ + inherit dev; + inherit devdoc; + doc = nix-manual; + outputs = [ "out" "dev" "devdoc" "doc" ]; + all = lib.attrValues (lib.genAttrs finalAttrs.passthru.outputs (outName: finalAttrs.finalPackage.${outName})); + }; + meta = prevAttrs.meta // { + description = "The Nix package manager"; + pkgConfigModules = dev.meta.pkgConfigModules; }; }) diff --git a/packaging/hydra.nix b/packaging/hydra.nix index cba1b2583..81406a249 100644 --- a/packaging/hydra.nix +++ b/packaging/hydra.nix @@ -16,32 +16,23 @@ let inherit tarballs; }; - testNixVersions = pkgs: client: daemon: - pkgs.nixComponents.callPackage ../package.nix { + testNixVersions = pkgs: daemon: + pkgs.nixComponents.nix-functional-tests.override { pname = "nix-tests" + lib.optionalString (lib.versionAtLeast daemon.version "2.4pre20211005" && - lib.versionAtLeast client.version "2.4pre20211005") - "-${client.version}-against-${daemon.version}"; + lib.versionAtLeast pkgs.nix.version "2.4pre20211005") + "-${pkgs.nix.version}-against-${daemon.version}"; - test-client = client; test-daemon = daemon; - - doBuild = false; - - # This could be more accurate, but a shorter version will match the - # fine version with rev. This functionality is already covered in - # the normal test, so it's fine. - version = pkgs.nixComponents.version; - versionSuffix = pkgs.nixComponents.versionSuffix; }; # Technically we could just return `pkgs.nixComponents`, but for Hydra it's # convention to transpose it, and to transpose it efficiently, we need to # enumerate them manually, so that we don't evaluate unnecessary package sets. forAllPackages = lib.genAttrs [ - "nix" + "nix-everything" "nix-util" "nix-util-c" "nix-util-test-support" @@ -63,7 +54,6 @@ let "nix-cmd" "nix-cli" "nix-functional-tests" - "nix-ng" ]; in { @@ -71,7 +61,9 @@ in build = forAllPackages (pkgName: forAllSystems (system: nixpkgsFor.${system}.native.nixComponents.${pkgName})); - shellInputs = forAllSystems (system: self.devShells.${system}.default.inputDerivation); + shellInputs = removeAttrs + (forAllSystems (system: self.devShells.${system}.default.inputDerivation)) + [ "i686-linux" ]; buildStatic = forAllPackages (pkgName: lib.genAttrs linux64BitSystems (system: nixpkgsFor.${system}.static.nixComponents.${pkgName})); @@ -82,20 +74,28 @@ in (forAllCrossSystems (crossSystem: lib.genAttrs [ "x86_64-linux" ] (system: nixpkgsFor.${system}.cross.${crossSystem}.nixComponents.${pkgName})))); - buildNoGc = forAllSystems (system: - self.packages.${system}.nix.override { enableGC = false; } - ); + buildNoGc = let + components = forAllSystems (system: + nixpkgsFor.${system}.native.nixComponents.overrideScope (self: super: { + nix-expr = super.nix-expr.override { enableGC = false; }; + }) + ); + in forAllPackages (pkgName: forAllSystems (system: components.${system}.${pkgName})); buildNoTests = forAllSystems (system: nixpkgsFor.${system}.native.nixComponents.nix-cli); # Toggles some settings for better coverage. Windows needs these # library combinations, and Debian build Nix with GNU readline too. - buildReadlineNoMarkdown = forAllSystems (system: - self.packages.${system}.nix.override { - enableMarkdown = false; - readlineFlavor = "readline"; - } - ); + buildReadlineNoMarkdown = let + components = forAllSystems (system: + nixpkgsFor.${system}.native.nixComponents.overrideScope (self: super: { + nix-cmd = super.nix-cmd.override { + enableMarkdown = false; + readlineFlavor = "readline"; + }; + }) + ); + in forAllPackages (pkgName: forAllSystems (system: components.${system}.${pkgName})); # Perl bindings for various platforms. perlBindings = forAllSystems (system: nixpkgsFor.${system}.native.nixComponents.nix-perl-bindings); @@ -140,11 +140,11 @@ in # docker image with Nix inside dockerImage = lib.genAttrs linux64BitSystems (system: self.packages.${system}.dockerImage); - # Line coverage analysis. - coverage = nixpkgsFor.x86_64-linux.native.nix.override { - pname = "nix-coverage"; - withCoverageChecks = true; - }; + # # Line coverage analysis. + # coverage = nixpkgsFor.x86_64-linux.native.nix.override { + # pname = "nix-coverage"; + # withCoverageChecks = true; + # }; # Nix's manual manual = nixpkgsFor.x86_64-linux.native.nixComponents.nix-manual; @@ -181,7 +181,7 @@ in import (nixpkgs + "/lib/tests/test-with-nix.nix") { lib = nixpkgsFor.${system}.native.lib; - nix = self.packages.${system}.nix; + nix = self.packages.${system}.nix-cli; pkgs = nixpkgsFor.${system}.native; } ); @@ -196,15 +196,15 @@ in let pkgs = nixpkgsFor.${system}.native; in pkgs.runCommand "install-tests" { - againstSelf = testNixVersions pkgs pkgs.nix pkgs.pkgs.nix; + againstSelf = testNixVersions pkgs pkgs.nix; againstCurrentLatest = # FIXME: temporarily disable this on macOS because of #3605. if system == "x86_64-linux" - then testNixVersions pkgs pkgs.nix pkgs.nixVersions.latest + then testNixVersions pkgs pkgs.nixVersions.latest else null; # Disabled because the latest stable version doesn't handle # `NIX_DAEMON_SOCKET_PATH` which is required for the tests to work - # againstLatestStable = testNixVersions pkgs pkgs.nix pkgs.nixStable; + # againstLatestStable = testNixVersions pkgs pkgs.nixStable; } "touch $out"); installerTests = import ../tests/installer { diff --git a/scripts/flake-regressions.sh b/scripts/flake-regressions.sh deleted file mode 100755 index d76531134..000000000 --- a/scripts/flake-regressions.sh +++ /dev/null @@ -1,27 +0,0 @@ -#! /usr/bin/env bash - -set -e - -echo "Nix version:" -nix --version - -cd flake-regressions - -status=0 - -flakes=$(find tests -mindepth 3 -maxdepth 3 -type d -not -path '*/.*' | sort | head -n25) - -echo "Running flake tests..." - -for flake in $flakes; do - - if ! REGENERATE=0 ./eval-flake.sh "$flake"; then - status=1 - echo "❌ $flake" - else - echo "✅ $flake" - fi - -done - -exit "$status" diff --git a/scripts/local.mk b/scripts/local.mk deleted file mode 100644 index 46255e432..000000000 --- a/scripts/local.mk +++ /dev/null @@ -1,13 +0,0 @@ -nix_noinst_scripts := \ - $(d)/nix-profile.sh - -noinst-scripts += $(nix_noinst_scripts) - -profiledir = $(sysconfdir)/profile.d - -$(eval $(call install-file-as, $(d)/nix-profile.sh, $(profiledir)/nix.sh, 0644)) -$(eval $(call install-file-as, $(d)/nix-profile.fish, $(profiledir)/nix.fish, 0644)) -$(eval $(call install-file-as, $(d)/nix-profile-daemon.sh, $(profiledir)/nix-daemon.sh, 0644)) -$(eval $(call install-file-as, $(d)/nix-profile-daemon.fish, $(profiledir)/nix-daemon.fish, 0644)) - -clean-files += $(nix_noinst_scripts) diff --git a/src/external-api-docs/doxygen.cfg.in b/src/external-api-docs/doxygen.cfg.in index 7ae4c83df..8e235dae5 100644 --- a/src/external-api-docs/doxygen.cfg.in +++ b/src/external-api-docs/doxygen.cfg.in @@ -41,7 +41,7 @@ INPUT = \ @src@/src/libutil-c \ @src@/src/libexpr-c \ @src@/src/libstore-c \ - @src@/doc/external-api/README.md + @src@/src/external-api-docs/README.md FILE_PATTERNS = nix_api_*.h *.md @@ -55,6 +55,8 @@ EXCLUDE_PATTERNS = *_internal.h GENERATE_TREEVIEW = YES OPTIMIZE_OUTPUT_FOR_C = YES -USE_MDFILE_AS_MAINPAGE = doc/external-api/README.md +USE_MDFILE_AS_MAINPAGE = @src@/src/external-api-docs/README.md +WARN_IF_UNDOCUMENTED = NO +WARN_IF_INCOMPLETE_DOC = NO QUIET = YES diff --git a/src/internal-api-docs/doxygen.cfg.in b/src/internal-api-docs/doxygen.cfg.in index bf4c42d11..950497ca3 100644 --- a/src/internal-api-docs/doxygen.cfg.in +++ b/src/internal-api-docs/doxygen.cfg.in @@ -43,8 +43,8 @@ INPUT = \ @src@/libexpr/flake \ @src@/libexpr-tests \ @src@/libexpr-tests/value \ - @src@/libexpr-test-support/test \ - @src@/libexpr-test-support/test/value \ + @src@/libexpr-test-support/tests \ + @src@/libexpr-test-support/tests/value \ @src@/libexpr/value \ @src@/libfetchers \ @src@/libmain \ @@ -52,10 +52,11 @@ INPUT = \ @src@/libstore/build \ @src@/libstore/builtins \ @src@/libstore-tests \ - @src@/libstore-test-support/test \ + @src@/libstore-test-support/tests \ @src@/libutil \ + @src@/libutil/args \ @src@/libutil-tests \ - @src@/libutil-test-support/test \ + @src@/libutil-test-support/tests \ @src@/nix \ @src@/nix-env \ @src@/nix-store @@ -83,7 +84,9 @@ EXPAND_ONLY_PREDEF = YES # RECURSIVE has no effect here. # This tag requires that the tag SEARCH_INCLUDES is set to YES. -INCLUDE_PATH = +INCLUDE_PATH = \ + @BUILD_ROOT@/src/libexpr/libnixexpr.so.p \ + @BUILD_ROOT@/src/nix/nix.p \ # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this # tag can be used to specify a list of macro names that should be expanded. The @@ -96,7 +99,18 @@ EXPAND_AS_DEFINED = \ DECLARE_COMMON_SERIALISER \ DECLARE_WORKER_SERIALISER \ DECLARE_SERVE_SERIALISER \ - LENGTH_PREFIXED_PROTO_HELPER + LENGTH_PREFIXED_PROTO_HELPER \ + LENGTH_PREFIXED_PROTO_HELPER_X \ + WORKER_USE_LENGTH_PREFIX_SERIALISER \ + WORKER_USE_LENGTH_PREFIX_SERIALISER_COMMA \ + SERVE_USE_LENGTH_PREFIX_SERIALISER \ + SERVE_USE_LENGTH_PREFIX_SERIALISER_COMMA \ + COMMON_METHODS \ + JSON_IMPL \ + MakeBinOp + +PREDEFINED = DOXYGEN_SKIP WARN_IF_UNDOCUMENTED = NO +WARN_IF_INCOMPLETE_DOC = NO QUIET = YES diff --git a/src/internal-api-docs/meson.build b/src/internal-api-docs/meson.build index 54eb7e5dd..c0426621e 100644 --- a/src/internal-api-docs/meson.build +++ b/src/internal-api-docs/meson.build @@ -12,6 +12,7 @@ doxygen_cfg = configure_file( configuration : { 'PROJECT_NUMBER': meson.project_version(), 'OUTPUT_DIRECTORY' : meson.current_build_dir(), + 'BUILD_ROOT' : meson.build_root(), 'src' : fs.parent(fs.parent(meson.project_source_root())) / 'src', }, ) diff --git a/src/libcmd/common-eval-args.cc b/src/libcmd/common-eval-args.cc index ccbf957d9..de967e3fe 100644 --- a/src/libcmd/common-eval-args.cc +++ b/src/libcmd/common-eval-args.cc @@ -29,13 +29,13 @@ EvalSettings evalSettings { { { "flake", - [](ref store, std::string_view rest) { + [](EvalState & state, std::string_view rest) { experimentalFeatureSettings.require(Xp::Flakes); // FIXME `parseFlakeRef` should take a `std::string_view`. auto flakeRef = parseFlakeRef(fetchSettings, std::string { rest }, {}, true, false); debug("fetching flake search path element '%s''", rest); - auto storePath = flakeRef.resolve(store).fetchTree(store).first; - return store->toRealPath(storePath); + auto storePath = flakeRef.resolve(state.store).fetchTree(state.store).first; + return state.rootPath(state.store->toRealPath(storePath)); }, }, }, diff --git a/src/libcmd/installable-derived-path.cc b/src/libcmd/installable-derived-path.cc index 4d1f83a1c..abacd7350 100644 --- a/src/libcmd/installable-derived-path.cc +++ b/src/libcmd/installable-derived-path.cc @@ -32,16 +32,6 @@ InstallableDerivedPath InstallableDerivedPath::parse( // store path. [&](const ExtendedOutputsSpec::Default &) -> DerivedPath { auto storePath = store->followLinksToStorePath(prefix); - // Remove this prior to stabilizing the new CLI. - if (storePath.isDerivation()) { - auto oldDerivedPath = DerivedPath::Built { - .drvPath = makeConstantStorePathRef(storePath), - .outputs = OutputsSpec::All { }, - }; - warn( - "The interpretation of store paths arguments ending in `.drv` recently changed. If this command is now failing try again with '%s'", - oldDerivedPath.to_string(*store)); - }; return DerivedPath::Opaque { .path = std::move(storePath), }; diff --git a/src/libcmd/installable-flake.hh b/src/libcmd/installable-flake.hh index 8e0a232ef..212403dd4 100644 --- a/src/libcmd/installable-flake.hh +++ b/src/libcmd/installable-flake.hh @@ -26,7 +26,7 @@ struct ExtraPathInfoFlake : ExtraPathInfoValue Flake flake; ExtraPathInfoFlake(Value && v, Flake && f) - : ExtraPathInfoValue(std::move(v)), flake(f) + : ExtraPathInfoValue(std::move(v)), flake(std::move(f)) { } }; diff --git a/src/libcmd/installable-value.hh b/src/libcmd/installable-value.hh index 60207cd23..4b6dbd306 100644 --- a/src/libcmd/installable-value.hh +++ b/src/libcmd/installable-value.hh @@ -59,7 +59,7 @@ struct ExtraPathInfoValue : ExtraPathInfo Value value; ExtraPathInfoValue(Value && v) - : value(v) + : value(std::move(v)) { } virtual ~ExtraPathInfoValue() = default; diff --git a/src/libcmd/installables.cc b/src/libcmd/installables.cc index 86d26f6c4..f2b27af7c 100644 --- a/src/libcmd/installables.cc +++ b/src/libcmd/installables.cc @@ -857,6 +857,7 @@ std::vector RawInstallablesCommand::getFlakeRefsForCompletion() { applyDefaultInstallables(rawInstallables); std::vector res; + res.reserve(rawInstallables.size()); for (auto i : rawInstallables) res.push_back(parseFlakeRefWithFragment( fetchSettings, diff --git a/src/libcmd/local.mk b/src/libcmd/local.mk deleted file mode 100644 index a270333f4..000000000 --- a/src/libcmd/local.mk +++ /dev/null @@ -1,15 +0,0 @@ -libraries += libcmd - -libcmd_NAME = libnixcmd - -libcmd_DIR := $(d) - -libcmd_SOURCES := $(wildcard $(d)/*.cc) - -libcmd_CXXFLAGS += $(INCLUDE_libutil) $(INCLUDE_libstore) $(INCLUDE_libfetchers) $(INCLUDE_libexpr) $(INCLUDE_libflake) $(INCLUDE_libmain) - -libcmd_LDFLAGS = $(EDITLINE_LIBS) $(LOWDOWN_LIBS) $(THREAD_LDFLAGS) - -libcmd_LIBS = libutil libstore libfetchers libflake libexpr libmain - -$(eval $(call install-file-in, $(buildprefix)$(d)/nix-cmd.pc, $(libdir)/pkgconfig, 0644)) diff --git a/src/libcmd/nix-cmd.pc.in b/src/libcmd/nix-cmd.pc.in deleted file mode 100644 index 39575f222..000000000 --- a/src/libcmd/nix-cmd.pc.in +++ /dev/null @@ -1,9 +0,0 @@ -prefix=@prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: Nix -Description: Nix Package Manager -Version: @PACKAGE_VERSION@ -Libs: -L${libdir} -lnixcmd -Cflags: -I${includedir}/nix -std=c++2a diff --git a/src/libexpr-c/local.mk b/src/libexpr-c/local.mk deleted file mode 100644 index 227a4095b..000000000 --- a/src/libexpr-c/local.mk +++ /dev/null @@ -1,25 +0,0 @@ -libraries += libexprc - -libexprc_NAME = libnixexprc - -libexprc_DIR := $(d) - -libexprc_SOURCES := \ - $(wildcard $(d)/*.cc) \ - -# Not just for this library itself, but also for downstream libraries using this library - -INCLUDE_libexprc := -I $(d) -libexprc_CXXFLAGS += $(INCLUDE_libutil) $(INCLUDE_libutilc) \ - $(INCLUDE_libfetchers) \ - $(INCLUDE_libstore) $(INCLUDE_libstorec) \ - $(INCLUDE_libexpr) $(INCLUDE_libexprc) - -libexprc_LIBS = libutil libutilc libstore libstorec libfetchers libexpr - -libexprc_LDFLAGS += $(THREAD_LDFLAGS) - -$(eval $(call install-file-in, $(d)/nix-expr-c.pc, $(libdir)/pkgconfig, 0644)) - -libexprc_FORCE_INSTALL := 1 - diff --git a/src/libexpr-c/meson.build b/src/libexpr-c/meson.build index 6db5b83b8..4160f0d5a 100644 --- a/src/libexpr-c/meson.build +++ b/src/libexpr-c/meson.build @@ -75,6 +75,7 @@ headers = [config_h] + files( headers += files('nix_api_expr_internal.h') subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') this_library = library( 'nixexprc', diff --git a/src/libexpr-c/nix-expr-c.pc.in b/src/libexpr-c/nix-expr-c.pc.in deleted file mode 100644 index 06897064d..000000000 --- a/src/libexpr-c/nix-expr-c.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: Nix -Description: Nix Language Evaluator - C API -Version: @PACKAGE_VERSION@ -Requires: nix-store-c -Libs: -L${libdir} -lnixexprc -Cflags: -I${includedir}/nix diff --git a/src/libexpr-c/nix_api_expr.cc b/src/libexpr-c/nix_api_expr.cc index 333e99460..6144a7986 100644 --- a/src/libexpr-c/nix_api_expr.cc +++ b/src/libexpr-c/nix_api_expr.cc @@ -67,7 +67,7 @@ nix_err nix_value_call_multi(nix_c_context * context, EvalState * state, nix_val if (context) context->last_err_code = NIX_OK; try { - state->state.callFunction(fn->value, nargs, (nix::Value * *)args, value->value, nix::noPos); + state->state.callFunction(fn->value, {(nix::Value * *) args, nargs}, value->value, nix::noPos); state->state.forceValue(value->value, nix::noPos); } NIXC_CATCH_ERRS diff --git a/src/libexpr-c/nix_api_expr.h b/src/libexpr-c/nix_api_expr.h index 1764b49f3..e680f5ff1 100644 --- a/src/libexpr-c/nix_api_expr.h +++ b/src/libexpr-c/nix_api_expr.h @@ -129,7 +129,7 @@ nix_err nix_value_call_multi( * @param[in] state The state of the evaluation. * @param[out] value The result of the function call. * @param[in] fn The Nix function to call. - * @param[in] args The arguments to pass to the function. + * @param[in] ... The arguments to pass to the function. * * @see nix_value_call_multi */ diff --git a/src/libexpr-c/nix_api_value.h b/src/libexpr-c/nix_api_value.h index 044f68c9e..8a0813ebe 100644 --- a/src/libexpr-c/nix_api_value.h +++ b/src/libexpr-c/nix_api_value.h @@ -77,8 +77,7 @@ typedef struct ExternalValue ExternalValue; */ typedef struct nix_realised_string nix_realised_string; -/** @defgroup primops - * @brief Create your own primops +/** @defgroup primops Adding primops * @{ */ /** @brief Function pointer for primops @@ -252,7 +251,7 @@ int64_t nix_get_int(nix_c_context * context, const nix_value * value); * @param[in] value Nix value to inspect * @return reference to external, NULL in case of error */ -ExternalValue * nix_get_external(nix_c_context * context, nix_value *); +ExternalValue * nix_get_external(nix_c_context * context, nix_value * value); /** @brief Get the ix'th element of a list * @@ -423,7 +422,7 @@ nix_list_builder_insert(nix_c_context * context, ListBuilder * list_builder, uns /** @brief Free a list builder * * Does not fail. - * @param[in] builder the builder to free + * @param[in] list_builder The builder to free. */ void nix_list_builder_free(ListBuilder * list_builder); diff --git a/src/libexpr-test-support/local.mk b/src/libexpr-test-support/local.mk deleted file mode 100644 index 0501de33c..000000000 --- a/src/libexpr-test-support/local.mk +++ /dev/null @@ -1,23 +0,0 @@ -libraries += libexpr-test-support - -libexpr-test-support_NAME = libnixexpr-test-support - -libexpr-test-support_DIR := $(d) - -ifeq ($(INSTALL_UNIT_TESTS), yes) - libexpr-test-support_INSTALL_DIR := $(checklibdir) -else - libexpr-test-support_INSTALL_DIR := -endif - -libexpr-test-support_SOURCES := \ - $(wildcard $(d)/tests/*.cc) \ - $(wildcard $(d)/tests/value/*.cc) - -libexpr-test-support_CXXFLAGS += $(libexpr-tests_EXTRA_INCLUDES) - -libexpr-test-support_LIBS = \ - libstore-test-support libutil-test-support \ - libexpr libstore libutil - -libexpr-test-support_LDFLAGS := $(THREAD_LDFLAGS) -lrapidcheck diff --git a/src/libexpr-test-support/meson.build b/src/libexpr-test-support/meson.build index 4f50478aa..b9e7f390d 100644 --- a/src/libexpr-test-support/meson.build +++ b/src/libexpr-test-support/meson.build @@ -56,6 +56,7 @@ headers = files( ) subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') this_library = library( 'nix-expr-test-support', diff --git a/src/libexpr-test-support/tests/libexpr.hh b/src/libexpr-test-support/tests/libexpr.hh index 045607e87..095ea1d0e 100644 --- a/src/libexpr-test-support/tests/libexpr.hh +++ b/src/libexpr-test-support/tests/libexpr.hh @@ -40,6 +40,12 @@ namespace nix { return v; } + Value * maybeThunk(std::string input, bool forceValue = true) { + Expr * e = state.parseExprFromString(input, state.rootPath(CanonPath::root)); + assert(e); + return e->maybeThunk(state, state.baseEnv); + } + Symbol createSymbol(const char * value) { return state.symbols.create(value); } diff --git a/src/libexpr-tests/eval.cc b/src/libexpr-tests/eval.cc index 93d3f658f..61f6be0db 100644 --- a/src/libexpr-tests/eval.cc +++ b/src/libexpr-tests/eval.cc @@ -138,4 +138,27 @@ TEST(nix_isAllowedURI, non_scheme_colon) { ASSERT_FALSE(isAllowedURI("https://foo/bar:baz", allowed)); } -} // namespace nix \ No newline at end of file +class EvalStateTest : public LibExprTest {}; + +TEST_F(EvalStateTest, getBuiltins_ok) { + auto evaled = maybeThunk("builtins"); + auto & builtins = state.getBuiltins(); + ASSERT_TRUE(builtins.type() == nAttrs); + ASSERT_EQ(evaled, &builtins); +} + +TEST_F(EvalStateTest, getBuiltin_ok) { + auto & builtin = state.getBuiltin("toString"); + ASSERT_TRUE(builtin.type() == nFunction); + // FIXME + // auto evaled = maybeThunk("builtins.toString"); + // ASSERT_EQ(evaled, &builtin); + auto & builtin2 = state.getBuiltin("true"); + ASSERT_EQ(state.forceBool(builtin2, noPos, "in unit test"), true); +} + +TEST_F(EvalStateTest, getBuiltin_fail) { + ASSERT_THROW(state.getBuiltin("nonexistent"), EvalError); +} + +} // namespace nix diff --git a/src/libexpr-tests/local.mk b/src/libexpr-tests/local.mk deleted file mode 100644 index 79583a9ee..000000000 --- a/src/libexpr-tests/local.mk +++ /dev/null @@ -1,45 +0,0 @@ -check: libexpr-tests_RUN - -programs += libexpr-tests - -libexpr-tests_NAME := libnixexpr-tests - -libexpr-tests_ENV := _NIX_TEST_UNIT_DATA=$(d)/data GTEST_OUTPUT=xml:$$testresults/libexpr-tests.xml - -libexpr-tests_DIR := $(d) - -ifeq ($(INSTALL_UNIT_TESTS), yes) - libexpr-tests_INSTALL_DIR := $(checkbindir) -else - libexpr-tests_INSTALL_DIR := -endif - -libexpr-tests_SOURCES := \ - $(wildcard $(d)/*.cc) \ - $(wildcard $(d)/value/*.cc) \ - $(wildcard $(d)/flake/*.cc) - -libexpr-tests_EXTRA_INCLUDES = \ - -I src/libexpr-test-support \ - -I src/libstore-test-support \ - -I src/libutil-test-support \ - $(INCLUDE_libexpr) \ - $(INCLUDE_libexprc) \ - $(INCLUDE_libfetchers) \ - $(INCLUDE_libstore) \ - $(INCLUDE_libstorec) \ - $(INCLUDE_libutil) \ - $(INCLUDE_libutilc) - -libexpr-tests_CXXFLAGS += $(libexpr-tests_EXTRA_INCLUDES) - -libexpr-tests_LIBS = \ - libexpr-test-support libstore-test-support libutil-test-support \ - libexpr libexprc libfetchers libstore libstorec libutil libutilc - -libexpr-tests_LDFLAGS := -lrapidcheck $(GTEST_LIBS) -lgmock - -ifdef HOST_WINDOWS - # Increase the default reserved stack size to 65 MB so Nix doesn't run out of space - libexpr-tests_LDFLAGS += -Wl,--stack,$(shell echo $$((65 * 1024 * 1024))) -endif diff --git a/src/libexpr-tests/meson.build b/src/libexpr-tests/meson.build index 21c321334..5a5c9f1d4 100644 --- a/src/libexpr-tests/meson.build +++ b/src/libexpr-tests/meson.build @@ -28,6 +28,7 @@ subdir('build-utils-meson/subprojects') subdir('build-utils-meson/threads') subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') rapidcheck = dependency('rapidcheck') deps_private += rapidcheck diff --git a/src/libexpr/call-flake.nix b/src/libexpr/call-flake.nix index a411564df..a008346e5 100644 --- a/src/libexpr/call-flake.nix +++ b/src/libexpr/call-flake.nix @@ -10,6 +10,9 @@ lockFileStr: # unlocked trees. overrides: +# This is `prim_fetchFinalTree`. +fetchTreeFinal: + let lockFile = builtins.fromJSON lockFileStr; @@ -44,7 +47,8 @@ let overrides.${key}.sourceInfo else # FIXME: remove obsolete node.info. - fetchTree (node.info or {} // removeAttrs node.locked ["dir"]); + # Note: lock file entries are always final. + fetchTreeFinal (node.info or {} // removeAttrs node.locked ["dir"]); subdir = overrides.${key}.dir or node.locked.dir or ""; diff --git a/src/libexpr/eval-inline.hh b/src/libexpr/eval-inline.hh index d5ce238b2..631c0f396 100644 --- a/src/libexpr/eval-inline.hh +++ b/src/libexpr/eval-inline.hh @@ -87,11 +87,15 @@ void EvalState::forceValue(Value & v, const PosIdx pos) { if (v.isThunk()) { Env * env = v.payload.thunk.env; + assert(env || v.isBlackhole()); Expr * expr = v.payload.thunk.expr; try { v.mkBlackhole(); //checkInterrupt(); - expr->eval(*this, *env, v); + if (env) [[likely]] + expr->eval(*this, *env, v); + else + ExprBlackHole::throwInfiniteRecursionError(*this, v); } catch (...) { v.mkThunk(env, expr); tryFixupBlackHolePos(v, pos); diff --git a/src/libexpr/eval-settings.hh b/src/libexpr/eval-settings.hh index 115e3ee50..a8fcce539 100644 --- a/src/libexpr/eval-settings.hh +++ b/src/libexpr/eval-settings.hh @@ -3,10 +3,11 @@ #include "config.hh" #include "ref.hh" +#include "source-path.hh" namespace nix { -class Store; +class EvalState; struct EvalSettings : Config { @@ -18,11 +19,8 @@ struct EvalSettings : Config * * The return value is (a) whether the entry was valid, and, if so, * what does it map to. - * - * @todo Return (`std::optional` of) `SourceAccssor` or something - * more structured instead of mere `std::string`? */ - using LookupPathHook = std::optional(ref store, std::string_view); + using LookupPathHook = std::optional(EvalState & state, std::string_view); /** * Map from "scheme" to a `LookupPathHook`. diff --git a/src/libexpr/eval.cc b/src/libexpr/eval.cc index e4937735b..05f58957e 100644 --- a/src/libexpr/eval.cc +++ b/src/libexpr/eval.cc @@ -448,7 +448,7 @@ void EvalState::addConstant(const std::string & name, Value * v, Constant info) /* Install value the base environment. */ staticBaseEnv->vars.emplace_back(symbols.create(name), baseEnvDispl); baseEnv.values[baseEnvDispl++] = v; - baseEnv.values[0]->payload.attrs->push_back(Attr(symbols.create(name2), v)); + getBuiltins().payload.attrs->push_back(Attr(symbols.create(name2), v)); } } @@ -510,16 +510,32 @@ Value * EvalState::addPrimOp(PrimOp && primOp) Value * v = allocValue(); v->mkPrimOp(new PrimOp(primOp)); - staticBaseEnv->vars.emplace_back(envName, baseEnvDispl); - baseEnv.values[baseEnvDispl++] = v; - baseEnv.values[0]->payload.attrs->push_back(Attr(symbols.create(primOp.name), v)); + + if (primOp.internal) + internalPrimOps.emplace(primOp.name, v); + else { + staticBaseEnv->vars.emplace_back(envName, baseEnvDispl); + baseEnv.values[baseEnvDispl++] = v; + getBuiltins().payload.attrs->push_back(Attr(symbols.create(primOp.name), v)); + } + return v; } +Value & EvalState::getBuiltins() +{ + return *baseEnv.values[0]; +} + + Value & EvalState::getBuiltin(const std::string & name) { - return *baseEnv.values[0]->attrs()->find(symbols.create(name))->value; + auto it = getBuiltins().attrs()->get(symbols.create(name)); + if (it) + return *it->value; + else + error("builtin '%1%' not found", name).debugThrow(); } @@ -582,14 +598,14 @@ std::optional EvalState::getDoc(Value & v) if (isFunctor(v)) { try { Value & functor = *v.attrs()->find(sFunctor)->value; - Value * vp = &v; + Value * vp[] = {&v}; Value partiallyApplied; // The first paramater is not user-provided, and may be // handled by code that is opaque to the user, like lib.const = x: y: y; // So preferably we show docs that are relevant to the // "partially applied" function returned by e.g. `const`. // We apply the first argument: - callFunction(functor, 1, &vp, partiallyApplied, noPos); + callFunction(functor, vp, partiallyApplied, noPos); auto _level = addCallDepth(noPos); return getDoc(partiallyApplied); } @@ -1454,7 +1470,7 @@ void ExprLambda::eval(EvalState & state, Env & env, Value & v) v.mkLambda(&env, this); } -void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & vRes, const PosIdx pos) +void EvalState::callFunction(Value & fun, std::span args, Value & vRes, const PosIdx pos) { auto _level = addCallDepth(pos); @@ -1469,16 +1485,16 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & auto makeAppChain = [&]() { vRes = vCur; - for (size_t i = 0; i < nrArgs; ++i) { + for (auto arg : args) { auto fun2 = allocValue(); *fun2 = vRes; - vRes.mkPrimOpApp(fun2, args[i]); + vRes.mkPrimOpApp(fun2, arg); } }; const Attr * functor; - while (nrArgs > 0) { + while (args.size() > 0) { if (vCur.isLambda()) { @@ -1581,15 +1597,14 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & throw; } - nrArgs--; - args += 1; + args = args.subspan(1); } else if (vCur.isPrimOp()) { size_t argsLeft = vCur.primOp()->arity; - if (nrArgs < argsLeft) { + if (args.size() < argsLeft) { /* We don't have enough arguments, so create a tPrimOpApp chain. */ makeAppChain(); return; @@ -1601,15 +1616,14 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & if (countCalls) primOpCalls[fn->name]++; try { - fn->fun(*this, vCur.determinePos(noPos), args, vCur); + fn->fun(*this, vCur.determinePos(noPos), args.data(), vCur); } catch (Error & e) { if (fn->addTrace) addErrorTrace(e, pos, "while calling the '%1%' builtin", fn->name); throw; } - nrArgs -= argsLeft; - args += argsLeft; + args = args.subspan(argsLeft); } } @@ -1625,7 +1639,7 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & auto arity = primOp->primOp()->arity; auto argsLeft = arity - argsDone; - if (nrArgs < argsLeft) { + if (args.size() < argsLeft) { /* We still don't have enough arguments, so extend the tPrimOpApp chain. */ makeAppChain(); return; @@ -1657,8 +1671,7 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & throw; } - nrArgs -= argsLeft; - args += argsLeft; + args = args.subspan(argsLeft); } } @@ -1669,13 +1682,12 @@ void EvalState::callFunction(Value & fun, size_t nrArgs, Value * * args, Value & Value * args2[] = {allocValue(), args[0]}; *args2[0] = vCur; try { - callFunction(*functor->value, 2, args2, vCur, functor->pos); + callFunction(*functor->value, args2, vCur, functor->pos); } catch (Error & e) { e.addTrace(positions[pos], "while calling a functor (an attribute set with a '__functor' attribute)"); throw; } - nrArgs--; - args++; + args = args.subspan(1); } else @@ -1718,7 +1730,7 @@ void ExprCall::eval(EvalState & state, Env & env, Value & v) for (size_t i = 0; i < args.size(); ++i) vArgs[i] = args[i]->maybeThunk(state, env); - state.callFunction(vFun, args.size(), vArgs.data(), v, pos); + state.callFunction(vFun, vArgs, v, pos); } @@ -1730,7 +1742,7 @@ void EvalState::incrFunctionCall(ExprLambda * fun) } -void EvalState::autoCallFunction(Bindings & args, Value & fun, Value & res) +void EvalState::autoCallFunction(const Bindings & args, Value & fun, Value & res) { auto pos = fun.determinePos(noPos); @@ -2040,9 +2052,12 @@ void ExprPos::eval(EvalState & state, Env & env, Value & v) state.mkPos(v, pos); } - -void ExprBlackHole::eval(EvalState & state, Env & env, Value & v) +void ExprBlackHole::eval(EvalState & state, [[maybe_unused]] Env & env, Value & v) { + throwInfiniteRecursionError(state, v); +} + +[[gnu::noinline]] [[noreturn]] void ExprBlackHole::throwInfiniteRecursionError(EvalState & state, Value &v) { state.error("infinite recursion encountered") .atPos(v.determinePos(noPos)) .debugThrow(); @@ -3023,8 +3038,8 @@ SourcePath EvalState::findFile(const LookupPath & lookupPath, const std::string_ if (!rOpt) continue; auto r = *rOpt; - Path res = suffix == "" ? r : concatStrings(r, "/", suffix); - if (pathExists(res)) return rootPath(CanonPath(canonPath(res))); + auto res = (r / CanonPath(suffix)).resolveSymlinks(); + if (res.pathExists()) return res; } if (hasPrefix(path, "nix/")) @@ -3039,13 +3054,13 @@ SourcePath EvalState::findFile(const LookupPath & lookupPath, const std::string_ } -std::optional EvalState::resolveLookupPathPath(const LookupPath::Path & value0, bool initAccessControl) +std::optional EvalState::resolveLookupPathPath(const LookupPath::Path & value0, bool initAccessControl) { auto & value = value0.s; auto i = lookupPathResolved.find(value); if (i != lookupPathResolved.end()) return i->second; - auto finish = [&](std::string res) { + auto finish = [&](SourcePath res) { debug("resolved search path element '%s' to '%s'", value, res); lookupPathResolved.emplace(value, res); return res; @@ -3058,7 +3073,7 @@ std::optional EvalState::resolveLookupPathPath(const LookupPath::Pa fetchSettings, EvalSettings::resolvePseudoUrl(value)); auto storePath = fetchToStore(*store, SourcePath(accessor), FetchMode::Copy); - return finish(store->toRealPath(storePath)); + return finish(rootPath(store->toRealPath(storePath))); } catch (Error & e) { logWarning({ .msg = HintFmt("Nix search path entry '%1%' cannot be downloaded, ignoring", value) @@ -3070,29 +3085,29 @@ std::optional EvalState::resolveLookupPathPath(const LookupPath::Pa auto scheme = value.substr(0, colPos); auto rest = value.substr(colPos + 1); if (auto * hook = get(settings.lookupPathHooks, scheme)) { - auto res = (*hook)(store, rest); + auto res = (*hook)(*this, rest); if (res) return finish(std::move(*res)); } } { - auto path = absPath(value); + auto path = rootPath(value); /* Allow access to paths in the search path. */ if (initAccessControl) { - allowPath(path); - if (store->isInStore(path)) { + allowPath(path.path.abs()); + if (store->isInStore(path.path.abs())) { try { StorePathSet closure; - store->computeFSClosure(store->toStorePath(path).first, closure); + store->computeFSClosure(store->toStorePath(path.path.abs()).first, closure); for (auto & p : closure) allowPath(p); } catch (InvalidPath &) { } } } - if (pathExists(path)) + if (path.pathExists()) return finish(std::move(path)); else { logWarning({ @@ -3103,7 +3118,6 @@ std::optional EvalState::resolveLookupPathPath(const LookupPath::Pa debug("failed to resolve search path element '%s'", value); return std::nullopt; - } diff --git a/src/libexpr/eval.hh b/src/libexpr/eval.hh index f7ed6be83..3ac3c8a8a 100644 --- a/src/libexpr/eval.hh +++ b/src/libexpr/eval.hh @@ -91,7 +91,7 @@ struct PrimOp const char * doc = nullptr; /** - * Add a trace item, `while calling the '' builtin` + * Add a trace item, while calling the `` builtin. * * This is used to remove the redundant item for `builtins.addErrorContext`. */ @@ -107,6 +107,11 @@ struct PrimOp */ std::optional experimentalFeature; + /** + * If true, this primop is not exposed to the user. + */ + bool internal = false; + /** * Validity check to be performed by functions that introduce primops, * such as RegisterPrimOp() and Value::mkPrimOp(). @@ -342,7 +347,7 @@ private: LookupPath lookupPath; - std::map> lookupPathResolved; + std::map> lookupPathResolved; /** * Cache used by prim_match(). @@ -447,9 +452,9 @@ public: * * If the specified search path element is a URI, download it. * - * If it is not found, return `std::nullopt` + * If it is not found, return `std::nullopt`. */ - std::optional resolveLookupPathPath( + std::optional resolveLookupPathPath( const LookupPath::Path & elem, bool initAccessControl = false); @@ -591,6 +596,11 @@ public: */ std::shared_ptr staticBaseEnv; // !!! should be private + /** + * Internal primops not exposed to the user. + */ + std::unordered_map, std::equal_to, traceable_allocator>> internalPrimOps; + /** * Name and documentation about every constant. * @@ -613,8 +623,19 @@ private: public: + /** + * Retrieve a specific builtin, equivalent to evaluating `builtins.${name}`. + * @param name The attribute name of the builtin to retrieve. + * @throws EvalError if the builtin does not exist. + */ Value & getBuiltin(const std::string & name); + /** + * Retrieve the `builtins` attrset, equivalent to evaluating the reference `builtins`. + * Always returns an attribute set value. + */ + Value & getBuiltins(); + struct Doc { Pos pos; @@ -680,20 +701,19 @@ public: bool isFunctor(Value & fun); - // FIXME: use std::span - void callFunction(Value & fun, size_t nrArgs, Value * * args, Value & vRes, const PosIdx pos); + void callFunction(Value & fun, std::span args, Value & vRes, const PosIdx pos); void callFunction(Value & fun, Value & arg, Value & vRes, const PosIdx pos) { Value * args[] = {&arg}; - callFunction(fun, 1, args, vRes, pos); + callFunction(fun, args, vRes, pos); } /** * Automatically call a function for which each argument has a * default value or has a binding in the `args` map. */ - void autoCallFunction(Bindings & args, Value & fun, Value & res); + void autoCallFunction(const Bindings & args, Value & fun, Value & res); /** * Allocation primitives. @@ -799,7 +819,6 @@ public: bool callPathFilter( Value * filterFun, const SourcePath & path, - std::string_view pathArg, PosIdx pos); DocComment getDocCommentForPos(PosIdx pos); diff --git a/src/libexpr/local.mk b/src/libexpr/local.mk deleted file mode 100644 index 68518e184..000000000 --- a/src/libexpr/local.mk +++ /dev/null @@ -1,50 +0,0 @@ -libraries += libexpr - -libexpr_NAME = libnixexpr - -libexpr_DIR := $(d) - -libexpr_SOURCES := \ - $(wildcard $(d)/*.cc) \ - $(wildcard $(d)/value/*.cc) \ - $(wildcard $(d)/primops/*.cc) \ - $(d)/lexer-tab.cc \ - $(d)/parser-tab.cc -# Not just for this library itself, but also for downstream libraries using this library - -INCLUDE_libexpr := -I $(d) - -libexpr_CXXFLAGS += \ - $(INCLUDE_libutil) $(INCLUDE_libstore) $(INCLUDE_libfetchers) $(INCLUDE_libexpr) \ - -DGC_THREADS - -libexpr_LIBS = libutil libstore libfetchers - -libexpr_LDFLAGS += -lboost_context $(THREAD_LDFLAGS) -ifdef HOST_LINUX - libexpr_LDFLAGS += -ldl -endif - -# The dependency on libgc must be propagated (i.e. meaning that -# programs/libraries that use libexpr must explicitly pass -lgc), -# because inline functions in libexpr's header files call libgc. -libexpr_LDFLAGS_PROPAGATED = $(BDW_GC_LIBS) - -libexpr_ORDER_AFTER := $(d)/parser-tab.cc $(d)/parser-tab.hh $(d)/lexer-tab.cc $(d)/lexer-tab.hh - -$(d)/parser-tab.cc $(d)/parser-tab.hh: $(d)/parser.y - $(trace-gen) bison -v -o $(libexpr_DIR)/parser-tab.cc $< -d - -$(d)/lexer-tab.cc $(d)/lexer-tab.hh: $(d)/lexer.l - $(trace-gen) flex --outfile $(libexpr_DIR)/lexer-tab.cc --header-file=$(libexpr_DIR)/lexer-tab.hh $< - -clean-files += $(d)/parser-tab.cc $(d)/parser-tab.hh $(d)/lexer-tab.cc $(d)/lexer-tab.hh - -$(eval $(call install-file-in, $(buildprefix)$(d)/nix-expr.pc, $(libdir)/pkgconfig, 0644)) - -$(foreach i, $(wildcard src/libexpr/value/*.hh), \ - $(eval $(call install-file-in, $(i), $(includedir)/nix/value, 0644))) - -$(d)/primops.cc: $(d)/imported-drv-to-derivation.nix.gen.hh - -$(d)/eval.cc: $(d)/primops/derivation.nix.gen.hh $(d)/fetchurl.nix.gen.hh $(d)/call-flake.nix.gen.hh diff --git a/src/libexpr/nix-expr.pc.in b/src/libexpr/nix-expr.pc.in deleted file mode 100644 index 60ffb5dba..000000000 --- a/src/libexpr/nix-expr.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: Nix -Description: Nix Package Manager -Version: @PACKAGE_VERSION@ -Requires: nix-store bdw-gc -Libs: -L${libdir} -lnixexpr -Cflags: -I${includedir}/nix -std=c++2a diff --git a/src/libexpr/nixexpr.hh b/src/libexpr/nixexpr.hh index bdf4e214a..2950ff1fd 100644 --- a/src/libexpr/nixexpr.hh +++ b/src/libexpr/nixexpr.hh @@ -206,7 +206,7 @@ struct ExprSelect : Expr /** * Evaluate the `a.b.c` part of `a.b.c.d`. This exists mostly for the purpose of :doc in the repl. * - * @param[out] v The attribute set that should contain the last attribute name (if it exists). + * @param[out] attrs The attribute set that should contain the last attribute name (if it exists). * @return The last attribute name in `attrPath` * * @note This does *not* evaluate the final attribute, and does not fail if that's the only attribute that does not exist. @@ -468,6 +468,7 @@ struct ExprBlackHole : Expr void show(const SymbolTable & symbols, std::ostream & str) const override {} void eval(EvalState & state, Env & env, Value & v) override; void bindVars(EvalState & es, const std::shared_ptr & env) override {} + [[noreturn]] static void throwInfiniteRecursionError(EvalState & state, Value & v); }; extern ExprBlackHole eBlackHole; diff --git a/src/libexpr/package.nix b/src/libexpr/package.nix index ca1f8bf21..d97e7f3a8 100644 --- a/src/libexpr/package.nix +++ b/src/libexpr/package.nix @@ -71,6 +71,10 @@ mkMesonLibrary (finalAttrs: { nix-util nix-store nix-fetchers + ] ++ finalAttrs.passthru.externalPropagatedBuildInputs; + + # Hack for sake of the dev shell + passthru.externalPropagatedBuildInputs = [ boost nlohmann_json ] ++ lib.optional enableGC boehmgc; diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index 84aa6bac9..53bfce6c5 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -91,6 +91,7 @@ StringMap EvalState::realiseContext(const NixStringContext & context, StorePathS /* Build/substitute the context. */ std::vector buildReqs; + buildReqs.reserve(drvs.size()); for (auto & d : drvs) buildReqs.emplace_back(DerivedPath { d }); buildStore->buildPaths(buildReqs, bmNormal, store); @@ -723,7 +724,7 @@ static void prim_genericClosure(EvalState & state, const PosIdx pos, Value * * a /* Call the `operator' function with `e' as argument. */ Value newElements; - state.callFunction(*op->value, 1, &e, newElements, noPos); + state.callFunction(*op->value, {&e, 1}, newElements, noPos); state.forceList(newElements, noPos, "while evaluating the return value of the `operator` passed to builtins.genericClosure"); /* Add the values returned by the operator to the work set. */ @@ -1602,7 +1603,8 @@ static RegisterPrimOp primop_placeholder({ *************************************************************/ -/* Convert the argument to a path. !!! obsolete? */ +/* Convert the argument to a path and then to a string (confusing, + eh?). !!! obsolete? */ static void prim_toPath(EvalState & state, const PosIdx pos, Value * * args, Value & v) { NixStringContext context; @@ -2436,7 +2438,6 @@ static RegisterPrimOp primop_toFile({ bool EvalState::callPathFilter( Value * filterFun, const SourcePath & path, - std::string_view pathArg, PosIdx pos) { auto st = path.lstat(); @@ -2444,12 +2445,12 @@ bool EvalState::callPathFilter( /* Call the filter function. The first argument is the path, the second is a string indicating the type of the file. */ Value arg1; - arg1.mkString(pathArg); + arg1.mkString(path.path.abs()); // assert that type is not "unknown" Value * args []{&arg1, fileTypeToString(*this, st.type)}; Value res; - callFunction(*filterFun, 2, args, res, pos); + callFunction(*filterFun, args, res, pos); return forceBool(res, pos, "while evaluating the return value of the path filter function"); } @@ -2487,7 +2488,7 @@ static void addPath( if (filterFun) filter = std::make_unique([&](const Path & p) { auto p2 = CanonPath(p); - return state.callPathFilter(filterFun, {path.accessor, p2}, p2.abs(), pos); + return state.callPathFilter(filterFun, {path.accessor, p2}, pos); }); std::optional expectedStorePath; @@ -2613,13 +2614,13 @@ static void prim_path(EvalState & state, const PosIdx pos, Value * * args, Value expectedHash = newHashAllowEmpty(state.forceStringNoCtx(*attr.value, attr.pos, "while evaluating the `sha256` attribute passed to builtins.path"), HashAlgorithm::SHA256); else state.error( - "unsupported argument '%1%' to 'addPath'", + "unsupported argument '%1%' to 'builtins.path'", state.symbols[attr.name] ).atPos(attr.pos).debugThrow(); } if (!path) state.error( - "missing required 'path' attribute in the first argument to builtins.path" + "missing required 'path' attribute in the first argument to 'builtins.path'" ).atPos(pos).debugThrow(); if (name.empty()) name = path->baseName(); @@ -3486,7 +3487,7 @@ static void prim_foldlStrict(EvalState & state, const PosIdx pos, Value * * args for (auto [n, elem] : enumerate(args[2]->listItems())) { Value * vs []{vCur, elem}; vCur = n == args[2]->listSize() - 1 ? &v : state.allocValue(); - state.callFunction(*args[0], 2, vs, *vCur, pos); + state.callFunction(*args[0], vs, *vCur, pos); } state.forceValue(v, pos); } else { @@ -3636,7 +3637,7 @@ static void prim_sort(EvalState & state, const PosIdx pos, Value * * args, Value Value * vs[] = {a, b}; Value vBool; - state.callFunction(*args[0], 2, vs, vBool, noPos); + state.callFunction(*args[0], vs, vBool, noPos); return state.forceBool(vBool, pos, "while evaluating the return value of the sorting function passed to builtins.sort"); }; @@ -4936,7 +4937,7 @@ void EvalState::createBaseEnv() /* Now that we've added all primops, sort the `builtins' set, because attribute lookups expect it to be sorted. */ - baseEnv.values[0]->payload.attrs->sort(); + getBuiltins().payload.attrs->sort(); staticBaseEnv->sort(); diff --git a/src/libexpr/primops/fetchTree.cc b/src/libexpr/primops/fetchTree.cc index d2266e2bc..c207da8ad 100644 --- a/src/libexpr/primops/fetchTree.cc +++ b/src/libexpr/primops/fetchTree.cc @@ -78,6 +78,7 @@ struct FetchTreeParams { bool emptyRevFallback = false; bool allowNameArgument = false; bool isFetchGit = false; + bool isFinal = false; }; static void fetchTree( @@ -195,6 +196,13 @@ static void fetchTree( state.checkURI(input.toURLString()); + if (params.isFinal) { + input.attrs.insert_or_assign("__final", Explicit(true)); + } else { + if (input.isFinal()) + throw Error("input '%s' is not allowed to use the '__final' attribute", input.to_string()); + } + auto [storePath, input2] = input.fetchToStore(state.store); state.allowPath(storePath); @@ -431,6 +439,18 @@ static RegisterPrimOp primop_fetchTree({ .experimentalFeature = Xp::FetchTree, }); +void prim_fetchFinalTree(EvalState & state, const PosIdx pos, Value * * args, Value & v) +{ + fetchTree(state, pos, args, v, {.isFinal = true}); +} + +static RegisterPrimOp primop_fetchFinalTree({ + .name = "fetchFinalTree", + .args = {"input"}, + .fun = prim_fetchFinalTree, + .internal = true, +}); + static void fetch(EvalState & state, const PosIdx pos, Value * * args, Value & v, const std::string & who, bool unpack, std::string name) { diff --git a/src/libexpr/value.hh b/src/libexpr/value.hh index 0ffe74dab..d98161488 100644 --- a/src/libexpr/value.hh +++ b/src/libexpr/value.hh @@ -141,7 +141,9 @@ public: Value * * elems; ListBuilder(EvalState & state, size_t size); - ListBuilder(ListBuilder && x) + // NOTE: Can be noexcept because we are just copying integral values and + // raw pointers. + ListBuilder(ListBuilder && x) noexcept : size(x.size) , inlineElems{x.inlineElems[0], x.inlineElems[1]} , elems(size <= 2 ? inlineElems : x.elems) diff --git a/src/libexpr/value/context.hh b/src/libexpr/value/context.hh index 7f23cd3a4..d6791c6e4 100644 --- a/src/libexpr/value/context.hh +++ b/src/libexpr/value/context.hh @@ -28,7 +28,7 @@ struct NixStringContextElem { /** * Plain opaque path to some store object. * - * Encoded as just the path: ‘’. + * Encoded as just the path: ``. */ using Opaque = SingleDerivedPath::Opaque; @@ -39,7 +39,7 @@ struct NixStringContextElem { * also all outputs of all derivations in that closure (including the * root derivation). * - * Encoded in the form ‘=’. + * Encoded in the form `=`. */ struct DrvDeep { StorePath drvPath; @@ -50,7 +50,7 @@ struct NixStringContextElem { /** * Derivation output. * - * Encoded in the form ‘!!’. + * Encoded in the form `!!`. */ using Built = SingleDerivedPath::Built; @@ -68,9 +68,9 @@ struct NixStringContextElem { /** * Decode a context string, one of: - * - ‘’ - * - ‘=’ - * - ‘!!’ + * - `` + * - `=` + * - `!!` * * @param xpSettings Stop-gap to avoid globals during unit tests. */ diff --git a/src/libfetchers-tests/local.mk b/src/libfetchers-tests/local.mk deleted file mode 100644 index 5c90f1fc7..000000000 --- a/src/libfetchers-tests/local.mk +++ /dev/null @@ -1,37 +0,0 @@ -check: libfetchers-tests_RUN - -programs += libfetchers-tests - -libfetchers-tests_NAME = libnixfetchers-tests - -libfetchers-tests_ENV := _NIX_TEST_UNIT_DATA=$(d)/data GTEST_OUTPUT=xml:$$testresults/libfetchers-tests.xml - -libfetchers-tests_DIR := $(d) - -ifeq ($(INSTALL_UNIT_TESTS), yes) - libfetchers-tests_INSTALL_DIR := $(checkbindir) -else - libfetchers-tests_INSTALL_DIR := -endif - -libfetchers-tests_SOURCES := $(wildcard $(d)/*.cc) - -libfetchers-tests_EXTRA_INCLUDES = \ - -I src/libstore-test-support \ - -I src/libutil-test-support \ - $(INCLUDE_libfetchers) \ - $(INCLUDE_libstore) \ - $(INCLUDE_libutil) - -libfetchers-tests_CXXFLAGS += $(libfetchers-tests_EXTRA_INCLUDES) - -libfetchers-tests_LIBS = \ - libstore-test-support libutil-test-support \ - libfetchers libstore libutil - -libfetchers-tests_LDFLAGS := -lrapidcheck $(GTEST_LIBS) $(LIBGIT2_LIBS) - -ifdef HOST_WINDOWS - # Increase the default reserved stack size to 65 MB so Nix doesn't run out of space - libfetchers-tests_LDFLAGS += -Wl,--stack,$(shell echo $$((65 * 1024 * 1024))) -endif diff --git a/src/libfetchers-tests/meson.build b/src/libfetchers-tests/meson.build index dc9818e27..d948dbad6 100644 --- a/src/libfetchers-tests/meson.build +++ b/src/libfetchers-tests/meson.build @@ -27,6 +27,7 @@ subdir('build-utils-meson/subprojects') subdir('build-utils-meson/threads') subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') rapidcheck = dependency('rapidcheck') deps_private += rapidcheck diff --git a/src/libfetchers/fetch-to-store.cc b/src/libfetchers/fetch-to-store.cc index 65aa72a6c..fe347a59d 100644 --- a/src/libfetchers/fetch-to-store.cc +++ b/src/libfetchers/fetch-to-store.cc @@ -44,6 +44,8 @@ StorePath fetchToStore( : store.addToStore( name, path, method, HashAlgorithm::SHA256, {}, filter2, repair); + debug(mode == FetchMode::DryRun ? "hashed '%s'" : "copied '%s' to '%s'", path, store.printStorePath(storePath)); + if (cacheKey && mode == FetchMode::Copy) fetchers::getCache()->upsert(*cacheKey, store, {}, storePath); diff --git a/src/libfetchers/fetchers.cc b/src/libfetchers/fetchers.cc index b07e8cb6e..e15a460d0 100644 --- a/src/libfetchers/fetchers.cc +++ b/src/libfetchers/fetchers.cc @@ -3,6 +3,7 @@ #include "source-path.hh" #include "fetch-to-store.hh" #include "json-utils.hh" +#include "store-path-accessor.hh" #include @@ -100,7 +101,7 @@ Input Input::fromAttrs(const Settings & settings, Attrs && attrs) auto allowedAttrs = inputScheme->allowedAttrs(); for (auto & [name, _] : attrs) - if (name != "type" && allowedAttrs.count(name) == 0) + if (name != "type" && name != "__final" && allowedAttrs.count(name) == 0) throw Error("input attribute '%s' not supported by scheme '%s'", name, schemeName); auto res = inputScheme->inputFromAttrs(settings, attrs); @@ -145,6 +146,11 @@ bool Input::isLocked() const return scheme && scheme->isLocked(*this); } +bool Input::isFinal() const +{ + return maybeGetBoolAttr(attrs, "__final").value_or(false); +} + Attrs Input::toAttrs() const { return attrs; @@ -172,16 +178,24 @@ std::pair Input::fetchToStore(ref store) const auto [storePath, input] = [&]() -> std::pair { try { - auto [accessor, final] = getAccessorUnchecked(store); + auto [accessor, result] = getAccessorUnchecked(store); - auto storePath = nix::fetchToStore(*store, SourcePath(accessor), FetchMode::Copy, final.getName()); + auto storePath = nix::fetchToStore(*store, SourcePath(accessor), FetchMode::Copy, result.getName()); auto narHash = store->queryPathInfo(storePath)->narHash; - final.attrs.insert_or_assign("narHash", narHash.to_string(HashFormat::SRI, true)); + result.attrs.insert_or_assign("narHash", narHash.to_string(HashFormat::SRI, true)); - scheme->checkLocks(*this, final); + // FIXME: we would like to mark inputs as final in + // getAccessorUnchecked(), but then we can't add + // narHash. Or maybe narHash should be excluded from the + // concept of "final" inputs? + result.attrs.insert_or_assign("__final", Explicit(true)); - return {storePath, final}; + assert(result.isFinal()); + + checkLocks(*this, result); + + return {storePath, result}; } catch (Error & e) { e.addTrace({}, "while fetching the input '%s'", to_string()); throw; @@ -191,13 +205,40 @@ std::pair Input::fetchToStore(ref store) const return {std::move(storePath), input}; } -void InputScheme::checkLocks(const Input & specified, const Input & final) const +void Input::checkLocks(Input specified, Input & result) { + /* If the original input is final, then we just return the + original attributes, dropping any new fields returned by the + fetcher. However, any fields that are in both the specified and + result input must be identical. */ + if (specified.isFinal()) { + + /* Backwards compatibility hack: we had some lock files in the + past that 'narHash' fields with incorrect base-64 + formatting (lacking the trailing '=', e.g. 'sha256-ri...Mw' + instead of ''sha256-ri...Mw='). So fix that. */ + if (auto prevNarHash = specified.getNarHash()) + specified.attrs.insert_or_assign("narHash", prevNarHash->to_string(HashFormat::SRI, true)); + + for (auto & field : specified.attrs) { + auto field2 = result.attrs.find(field.first); + if (field2 != result.attrs.end() && field.second != field2->second) + throw Error("mismatch in field '%s' of input '%s', got '%s'", + field.first, + attrsToJSON(specified.attrs), + attrsToJSON(result.attrs)); + } + + result.attrs = specified.attrs; + + return; + } + if (auto prevNarHash = specified.getNarHash()) { - if (final.getNarHash() != prevNarHash) { - if (final.getNarHash()) + if (result.getNarHash() != prevNarHash) { + if (result.getNarHash()) throw Error((unsigned int) 102, "NAR hash mismatch in input '%s', expected '%s' but got '%s'", - specified.to_string(), prevNarHash->to_string(HashFormat::SRI, true), final.getNarHash()->to_string(HashFormat::SRI, true)); + specified.to_string(), prevNarHash->to_string(HashFormat::SRI, true), result.getNarHash()->to_string(HashFormat::SRI, true)); else throw Error((unsigned int) 102, "NAR hash mismatch in input '%s', expected '%s' but got none", specified.to_string(), prevNarHash->to_string(HashFormat::SRI, true)); @@ -205,32 +246,32 @@ void InputScheme::checkLocks(const Input & specified, const Input & final) const } if (auto prevLastModified = specified.getLastModified()) { - if (final.getLastModified() != prevLastModified) - throw Error("'lastModified' attribute mismatch in input '%s', expected %d", - final.to_string(), *prevLastModified); + if (result.getLastModified() != prevLastModified) + throw Error("'lastModified' attribute mismatch in input '%s', expected %d, got %d", + result.to_string(), *prevLastModified, result.getLastModified().value_or(-1)); } if (auto prevRev = specified.getRev()) { - if (final.getRev() != prevRev) + if (result.getRev() != prevRev) throw Error("'rev' attribute mismatch in input '%s', expected %s", - final.to_string(), prevRev->gitRev()); + result.to_string(), prevRev->gitRev()); } if (auto prevRevCount = specified.getRevCount()) { - if (final.getRevCount() != prevRevCount) + if (result.getRevCount() != prevRevCount) throw Error("'revCount' attribute mismatch in input '%s', expected %d", - final.to_string(), *prevRevCount); + result.to_string(), *prevRevCount); } } std::pair, Input> Input::getAccessor(ref store) const { try { - auto [accessor, final] = getAccessorUnchecked(store); + auto [accessor, result] = getAccessorUnchecked(store); - scheme->checkLocks(*this, final); + checkLocks(*this, result); - return {accessor, std::move(final)}; + return {accessor, std::move(result)}; } catch (Error & e) { e.addTrace({}, "while fetching the input '%s'", to_string()); throw; @@ -244,12 +285,42 @@ std::pair, Input> Input::getAccessorUnchecked(ref sto if (!scheme) throw Error("cannot fetch unsupported input '%s'", attrsToJSON(toAttrs())); - auto [accessor, final] = scheme->getAccessor(store, *this); + /* 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. We only do this for final + inputs, otherwise there is a risk that we don't return the + same attributes (like `lastModified`) that the "real" fetcher + would return. + + FIXME: add a setting to disable this. + FIXME: substituting may be slower than fetching normally, + e.g. for fetchers like Git that are incremental! + */ + if (isFinal() && getNarHash()) { + try { + auto storePath = computeStorePath(*store); + + store->ensurePath(storePath); + + debug("using substituted/cached input '%s' in '%s'", + to_string(), store->printStorePath(storePath)); + + auto accessor = makeStorePathAccessor(store, storePath); + + accessor->fingerprint = scheme->getFingerprint(store, *this); + + return {accessor, *this}; + } catch (Error & e) { + debug("substitution of input '%s' failed: %s", to_string(), e.what()); + } + } + + auto [accessor, result] = scheme->getAccessor(store, *this); assert(!accessor->fingerprint); - accessor->fingerprint = scheme->getFingerprint(store, final); + accessor->fingerprint = scheme->getFingerprint(store, result); - return {accessor, std::move(final)}; + return {accessor, std::move(result)}; } Input Input::applyOverrides( @@ -404,7 +475,10 @@ namespace nlohmann { using namespace nix; -fetchers::PublicKey adl_serializer::from_json(const json & json) { +#ifndef DOXYGEN_SKIP + +fetchers::PublicKey adl_serializer::from_json(const json & json) +{ fetchers::PublicKey res = { }; if (auto type = optionalValueAt(json, "type")) res.type = getString(*type); @@ -414,9 +488,12 @@ fetchers::PublicKey adl_serializer::from_json(const json & return res; } -void adl_serializer::to_json(json & json, fetchers::PublicKey p) { +void adl_serializer::to_json(json & json, fetchers::PublicKey p) +{ json["type"] = p.type; json["key"] = p.key; } +#endif + } diff --git a/src/libfetchers/fetchers.hh b/src/libfetchers/fetchers.hh index a5f9bdcc6..b28ec4568 100644 --- a/src/libfetchers/fetchers.hh +++ b/src/libfetchers/fetchers.hh @@ -78,17 +78,30 @@ public: Attrs toAttrs() const; /** - * Check whether this is a "direct" input, that is, not + * Return whether this is a "direct" input, that is, not * one that goes through a registry. */ bool isDirect() const; /** - * Check whether this is a "locked" input, that is, - * one that contains a commit hash or content hash. + * Return whether this is a "locked" input, that is, it has + * attributes like a Git revision or NAR hash that uniquely + * identify its contents. */ bool isLocked() const; + /** + * Return whether this is a "final" input, meaning that fetching + * it will not add, remove or change any attributes. (See + * `checkLocks()` for the semantics.) Only "final" inputs can be + * substituted from a binary cache. + * + * The "final" state is denoted by the presence of an attribute + * `__final = true`. This attribute is currently undocumented and + * for internal use only. + */ + bool isFinal() const; + bool operator ==(const Input & other) const noexcept; bool contains(const Input & other) const; @@ -99,6 +112,19 @@ public: */ std::pair fetchToStore(ref store) const; + /** + * Check the locking attributes in `result` against + * `specified`. E.g. if `specified` has a `rev` attribute, then + * `result` must have the same `rev` attribute. Throw an exception + * if there is a mismatch. + * + * If `specified` is marked final (i.e. has the `__final` + * attribute), then the intersection of attributes in `specified` + * and `result` must be equal, and `final.attrs` is set to + * `specified.attrs` (i.e. we discard any new attributes). + */ + static void checkLocks(Input specified, Input & result); + /** * Return a `SourceAccessor` that allows access to files in the * input without copying it to the store. Also return a possibly @@ -144,6 +170,10 @@ public: /** * For locked inputs, return a string that uniquely specifies the * content of the input (typically a commit hash or content hash). + * + * Only known-equivalent inputs should return the same fingerprint. + * + * This is not a stable identifier between Nix versions, but not guaranteed to change either. */ std::optional getFingerprint(ref store) const; }; @@ -215,31 +245,11 @@ struct InputScheme virtual bool isDirect(const Input & input) const { return true; } - /** - * A sufficiently unique string that can be used as a cache key to identify the `input`. - * - * Only known-equivalent inputs should return the same fingerprint. - * - * This is not a stable identifier between Nix versions, but not guaranteed to change either. - */ virtual std::optional getFingerprint(ref store, const Input & input) const { return std::nullopt; } - /** - * Return `true` if this input is considered "locked", i.e. it has - * attributes like a Git revision or NAR hash that uniquely - * identify its contents. - */ virtual bool isLocked(const Input & input) const { return false; } - - /** - * Check the locking attributes in `final` against - * `specified`. E.g. if `specified` has a `rev` attribute, then - * `final` must have the same `rev` attribute. Throw an exception - * if there is a mismatch. - */ - virtual void checkLocks(const Input & specified, const Input & final) const; }; void registerInputScheme(std::shared_ptr && fetcher); diff --git a/src/libfetchers/git-utils.cc b/src/libfetchers/git-utils.cc index 95ee33089..74e68fe12 100644 --- a/src/libfetchers/git-utils.cc +++ b/src/libfetchers/git-utils.cc @@ -217,8 +217,12 @@ static void initRepoAtomically(std::filesystem::path &path, bool bare) { try { std::filesystem::rename(tmpDir, path); } catch (std::filesystem::filesystem_error & e) { - if (e.code() == std::errc::file_exists) // Someone might race us to create the repository. + // Someone may race us to create the repository. + if (e.code() == std::errc::file_exists + // `path` may be attempted to be deleted by s::f::rename, in which case the code is: + || e.code() == std::errc::directory_not_empty) { return; + } else throw SysError("moving temporary git repository from %s to %s", tmpDir, path); } diff --git a/src/libfetchers/local.mk b/src/libfetchers/local.mk deleted file mode 100644 index e229a0993..000000000 --- a/src/libfetchers/local.mk +++ /dev/null @@ -1,17 +0,0 @@ -libraries += libfetchers - -libfetchers_NAME = libnixfetchers - -libfetchers_DIR := $(d) - -libfetchers_SOURCES := $(wildcard $(d)/*.cc) - -# Not just for this library itself, but also for downstream libraries using this library - -INCLUDE_libfetchers := -I $(d) - -libfetchers_CXXFLAGS += $(INCLUDE_libutil) $(INCLUDE_libstore) $(INCLUDE_libfetchers) - -libfetchers_LDFLAGS += $(THREAD_LDFLAGS) $(LIBGIT2_LIBS) -larchive - -libfetchers_LIBS = libutil libstore diff --git a/src/libfetchers/meson.build b/src/libfetchers/meson.build index d4f202796..ff638578d 100644 --- a/src/libfetchers/meson.build +++ b/src/libfetchers/meson.build @@ -52,15 +52,15 @@ sources = files( 'fetch-to-store.cc', 'fetchers.cc', 'filtering-source-accessor.cc', - 'git.cc', 'git-utils.cc', + 'git.cc', 'github.cc', 'indirect.cc', 'mercurial.cc', 'mounted-source-accessor.cc', 'path.cc', - 'store-path-accessor.cc', 'registry.cc', + 'store-path-accessor.cc', 'tarball.cc', ) @@ -71,10 +71,10 @@ headers = files( 'cache.hh', 'fetch-settings.hh', 'fetch-to-store.hh', + 'fetchers.hh', 'filtering-source-accessor.hh', 'git-utils.hh', 'mounted-source-accessor.hh', - 'fetchers.hh', 'registry.hh', 'store-path-accessor.hh', 'tarball.hh', diff --git a/src/libfetchers/path.cc b/src/libfetchers/path.cc index fe1534aba..246b68c3a 100644 --- a/src/libfetchers/path.cc +++ b/src/libfetchers/path.cc @@ -72,6 +72,7 @@ struct PathInputScheme : InputScheme auto query = attrsToQuery(input.attrs); query.erase("path"); query.erase("type"); + query.erase("__final"); return ParsedURL { .scheme = "path", .path = getStrAttr(input.attrs, "path"), diff --git a/src/libflake-tests/local.mk b/src/libflake-tests/local.mk deleted file mode 100644 index 8599b43f6..000000000 --- a/src/libflake-tests/local.mk +++ /dev/null @@ -1,43 +0,0 @@ -check: libflake-tests_RUN - -programs += libflake-tests - -libflake-tests_NAME := libnixflake-tests - -libflake-tests_ENV := _NIX_TEST_UNIT_DATA=$(d)/data GTEST_OUTPUT=xml:$$testresults/libflake-tests.xml - -libflake-tests_DIR := $(d) - -ifeq ($(INSTALL_UNIT_TESTS), yes) - libflake-tests_INSTALL_DIR := $(checkbindir) -else - libflake-tests_INSTALL_DIR := -endif - -libflake-tests_SOURCES := \ - $(wildcard $(d)/*.cc) \ - $(wildcard $(d)/value/*.cc) \ - $(wildcard $(d)/flake/*.cc) - -libflake-tests_EXTRA_INCLUDES = \ - -I src/libflake-test-support \ - -I src/libstore-test-support \ - -I src/libutil-test-support \ - $(INCLUDE_libflake) \ - $(INCLUDE_libexpr) \ - $(INCLUDE_libfetchers) \ - $(INCLUDE_libstore) \ - $(INCLUDE_libutil) \ - -libflake-tests_CXXFLAGS += $(libflake-tests_EXTRA_INCLUDES) - -libflake-tests_LIBS = \ - libexpr-test-support libstore-test-support libutil-test-support \ - libflake libexpr libfetchers libstore libutil - -libflake-tests_LDFLAGS := -lrapidcheck $(GTEST_LIBS) -lgmock - -ifdef HOST_WINDOWS - # Increase the default reserved stack size to 65 MB so Nix doesn't run out of space - libflake-tests_LDFLAGS += -Wl,--stack,$(shell echo $$((65 * 1024 * 1024))) -endif diff --git a/src/libflake-tests/meson.build b/src/libflake-tests/meson.build index c022d7f41..592a7493b 100644 --- a/src/libflake-tests/meson.build +++ b/src/libflake-tests/meson.build @@ -27,6 +27,7 @@ subdir('build-utils-meson/subprojects') subdir('build-utils-meson/threads') subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') rapidcheck = dependency('rapidcheck') deps_private += rapidcheck diff --git a/src/libflake/flake/flake.cc b/src/libflake/flake/flake.cc index d18e01464..19b622a34 100644 --- a/src/libflake/flake/flake.cc +++ b/src/libflake/flake/flake.cc @@ -85,7 +85,6 @@ static void forceTrivialValue(EvalState & state, Value & value, const PosIdx pos state.forceValue(value, pos); } - static void expectType(EvalState & state, ValueType type, Value & value, const PosIdx pos) { @@ -810,12 +809,14 @@ void callFlake(EvalState & state, auto vCallFlake = state.allocValue(); state.evalFile(state.callFlakeInternal, *vCallFlake); - auto vTmp1 = state.allocValue(); auto vLocks = state.allocValue(); vLocks->mkString(lockFileStr); - state.callFunction(*vCallFlake, *vLocks, *vTmp1, noPos); - state.callFunction(*vTmp1, vOverrides, vRes, noPos); + auto vFetchFinalTree = get(state.internalPrimOps, "fetchFinalTree"); + assert(vFetchFinalTree); + + Value * args[] = {vLocks, &vOverrides, *vFetchFinalTree}; + state.callFunction(*vCallFlake, args, vRes, noPos); } void initLib(const Settings & settings) diff --git a/src/libflake/flake/flake.hh b/src/libflake/flake/flake.hh index 496e18673..cc2bea76e 100644 --- a/src/libflake/flake/flake.hh +++ b/src/libflake/flake/flake.hh @@ -234,4 +234,11 @@ void emitTreeAttrs( bool emptyRevFallback = false, bool forceDirty = false); +/** + * An internal builtin similar to `fetchTree`, except that it + * always treats the input as final (i.e. no attributes can be + * added/removed/changed). + */ +void prim_fetchFinalTree(EvalState & state, const PosIdx pos, Value * * args, Value & v); + } diff --git a/src/libflake/flake/lockfile.cc b/src/libflake/flake/lockfile.cc index 70b60716f..668ed165f 100644 --- a/src/libflake/flake/lockfile.cc +++ b/src/libflake/flake/lockfile.cc @@ -46,6 +46,10 @@ LockedNode::LockedNode( if (!lockedRef.input.isLocked()) throw Error("lock file contains unlocked input '%s'", fetchers::attrsToJSON(lockedRef.input.toAttrs())); + + // For backward compatibility, lock file entries are implicitly final. + assert(!lockedRef.input.attrs.contains("__final")); + lockedRef.input.attrs.insert_or_assign("__final", Explicit(true)); } StorePath LockedNode::computeStorePath(Store & store) const @@ -53,7 +57,6 @@ StorePath LockedNode::computeStorePath(Store & store) const return lockedRef.input.computeStorePath(store); } - static std::shared_ptr doFind(const ref & root, const InputPath & path, std::vector & visited) { auto pos = root; @@ -191,6 +194,11 @@ std::pair LockFile::toJSON() const if (auto lockedNode = node.dynamic_pointer_cast()) { n["original"] = fetchers::attrsToJSON(lockedNode->originalRef.toAttrs()); n["locked"] = fetchers::attrsToJSON(lockedNode->lockedRef.toAttrs()); + /* For backward compatibility, omit the "__final" + attribute. We never allow non-final inputs in lock files + anyway. */ + assert(lockedNode->lockedRef.input.isFinal()); + n["locked"].erase("__final"); if (!lockedNode->isFlake) n["flake"] = false; } @@ -239,7 +247,7 @@ std::optional LockFile::isUnlocked() const for (auto & i : nodes) { if (i == ref(root)) continue; auto node = i.dynamic_pointer_cast(); - if (node && !node->lockedRef.input.isLocked()) + if (node && (!node->lockedRef.input.isLocked() || !node->lockedRef.input.isFinal())) return node->lockedRef; } diff --git a/src/libflake/flake/lockfile.hh b/src/libflake/flake/lockfile.hh index 841931c11..a2711a516 100644 --- a/src/libflake/flake/lockfile.hh +++ b/src/libflake/flake/lockfile.hh @@ -68,8 +68,8 @@ struct LockFile std::pair to_string() const; /** - * Check whether this lock file has any unlocked inputs. If so, - * return one. + * Check whether this lock file has any unlocked or non-final + * inputs. If so, return one. */ std::optional isUnlocked() const; diff --git a/src/libflake/flake/nix-flake.pc.in b/src/libflake/flake/nix-flake.pc.in deleted file mode 100644 index 10c52f5e9..000000000 --- a/src/libflake/flake/nix-flake.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: Nix -Description: Nix Package Manager -Version: @PACKAGE_VERSION@ -Requires: nix-util nix-store nix-expr -Libs: -L${libdir} -lnixflake -Cflags: -I${includedir}/nix -std=c++2a diff --git a/src/libflake/local.mk b/src/libflake/local.mk deleted file mode 100644 index 5e604ef3a..000000000 --- a/src/libflake/local.mk +++ /dev/null @@ -1,22 +0,0 @@ -libraries += libflake - -libflake_NAME = libnixflake - -libflake_DIR := $(d) - -libflake_SOURCES := $(wildcard $(d)/*.cc $(d)/flake/*.cc) - -# Not just for this library itself, but also for downstream libraries using this library - -INCLUDE_libflake := -I $(d) - -libflake_CXXFLAGS += $(INCLUDE_libutil) $(INCLUDE_libstore) $(INCLUDE_libfetchers) $(INCLUDE_libexpr) $(INCLUDE_libflake) - -libflake_LDFLAGS += $(THREAD_LDFLAGS) - -libflake_LIBS = libutil libstore libfetchers libexpr - -$(eval $(call install-file-in, $(buildprefix)$(d)/flake/nix-flake.pc, $(libdir)/pkgconfig, 0644)) - -$(foreach i, $(wildcard src/libflake/flake/*.hh), \ - $(eval $(call install-file-in, $(i), $(includedir)/nix/flake, 0644))) diff --git a/src/libmain-c/meson.build b/src/libmain-c/meson.build index 345382712..0ec0e3f6d 100644 --- a/src/libmain-c/meson.build +++ b/src/libmain-c/meson.build @@ -68,6 +68,7 @@ headers = [config_h] + files( ) subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') this_library = library( 'nixmainc', diff --git a/src/libmain/common-args.cc b/src/libmain/common-args.cc index 768b2177c..13d358623 100644 --- a/src/libmain/common-args.cc +++ b/src/libmain/common-args.cc @@ -17,7 +17,9 @@ MixCommonArgs::MixCommonArgs(const std::string & programName) .shortName = 'v', .description = "Increase the logging verbosity level.", .category = loggingCategory, - .handler = {[]() { verbosity = (Verbosity) (verbosity + 1); }}, + .handler = {[]() { + verbosity = (Verbosity) std::min>(verbosity + 1, lvlVomit); + }}, }); addFlag({ diff --git a/src/libmain/local.mk b/src/libmain/local.mk deleted file mode 100644 index d41c49dd7..000000000 --- a/src/libmain/local.mk +++ /dev/null @@ -1,22 +0,0 @@ -libraries += libmain - -libmain_NAME = libnixmain - -libmain_DIR := $(d) - -libmain_SOURCES := $(wildcard $(d)/*.cc) -ifdef HOST_UNIX - libmain_SOURCES += $(wildcard $(d)/unix/*.cc) -endif - -INCLUDE_libmain := -I $(d) - -libmain_CXXFLAGS += $(INCLUDE_libutil) $(INCLUDE_libstore) $(INCLUDE_libmain) - -libmain_LDFLAGS += $(OPENSSL_LIBS) - -libmain_LIBS = libstore libutil - -libmain_ALLOW_UNDEFINED = 1 - -$(eval $(call install-file-in, $(buildprefix)$(d)/nix-main.pc, $(libdir)/pkgconfig, 0644)) diff --git a/src/libmain/nix-main.pc.in b/src/libmain/nix-main.pc.in deleted file mode 100644 index fb3ead6fa..000000000 --- a/src/libmain/nix-main.pc.in +++ /dev/null @@ -1,9 +0,0 @@ -prefix=@prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: Nix -Description: Nix Package Manager -Version: @PACKAGE_VERSION@ -Libs: -L${libdir} -lnixmain -Cflags: -I${includedir}/nix -std=c++2a diff --git a/src/libmain/progress-bar.cc b/src/libmain/progress-bar.cc index 22f890f7d..fa0b73ebe 100644 --- a/src/libmain/progress-bar.cc +++ b/src/libmain/progress-bar.cc @@ -543,7 +543,7 @@ public: auto state(state_.lock()); if (!state->active) return {}; std::cerr << fmt("\r\e[K%s ", msg); - auto s = trim(readLine(STDIN_FILENO)); + auto s = trim(readLine(getStandardInput(), true)); if (s.size() != 1) return {}; draw(*state); return s[0]; diff --git a/src/libstore-c/local.mk b/src/libstore-c/local.mk deleted file mode 100644 index 5e3eff06a..000000000 --- a/src/libstore-c/local.mk +++ /dev/null @@ -1,21 +0,0 @@ -libraries += libstorec - -libstorec_NAME = libnixstorec - -libstorec_DIR := $(d) - -libstorec_SOURCES := $(wildcard $(d)/*.cc) - -libstorec_LIBS = libutil libstore libutilc - -libstorec_LDFLAGS += $(THREAD_LDFLAGS) - -# Not just for this library itself, but also for downstream libraries using this library - -INCLUDE_libstorec := -I $(d) -libstorec_CXXFLAGS += $(INCLUDE_libutil) $(INCLUDE_libutilc) \ - $(INCLUDE_libstore) $(INCLUDE_libstorec) - -$(eval $(call install-file-in, $(d)/nix-store-c.pc, $(libdir)/pkgconfig, 0644)) - -libstorec_FORCE_INSTALL := 1 diff --git a/src/libstore-c/meson.build b/src/libstore-c/meson.build index 4bfd944c6..d4f86eeff 100644 --- a/src/libstore-c/meson.build +++ b/src/libstore-c/meson.build @@ -67,6 +67,7 @@ headers = [config_h] + files( headers += files('nix_api_store_internal.h') subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') this_library = library( 'nixstorec', diff --git a/src/libstore-c/nix-store-c.pc.in b/src/libstore-c/nix-store-c.pc.in deleted file mode 100644 index de3c7b4c6..000000000 --- a/src/libstore-c/nix-store-c.pc.in +++ /dev/null @@ -1,9 +0,0 @@ -prefix=@prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: Nix -Description: Nix Store - C API -Version: @PACKAGE_VERSION@ -Libs: -L${libdir} -lnixstorec -lnixutilc -Cflags: -I${includedir}/nix diff --git a/src/libstore-c/nix_api_store.h b/src/libstore-c/nix_api_store.h index 93208cb7c..282ccc285 100644 --- a/src/libstore-c/nix_api_store.h +++ b/src/libstore-c/nix_api_store.h @@ -166,7 +166,7 @@ nix_store_get_version(nix_c_context * context, Store * store, nix_get_string_cal * * @param[out] context Optional, stores error information * @param[in] srcStore nix source store reference - * @param[in] srcStore nix destination store reference + * @param[in] dstStore nix destination store reference * @param[in] path Path to copy */ nix_err nix_store_copy_closure(nix_c_context * context, Store * srcStore, Store * dstStore, StorePath * path); diff --git a/src/libstore-test-support/local.mk b/src/libstore-test-support/local.mk deleted file mode 100644 index 56dedd825..000000000 --- a/src/libstore-test-support/local.mk +++ /dev/null @@ -1,21 +0,0 @@ -libraries += libstore-test-support - -libstore-test-support_NAME = libnixstore-test-support - -libstore-test-support_DIR := $(d) - -ifeq ($(INSTALL_UNIT_TESTS), yes) - libstore-test-support_INSTALL_DIR := $(checklibdir) -else - libstore-test-support_INSTALL_DIR := -endif - -libstore-test-support_SOURCES := $(wildcard $(d)/tests/*.cc) - -libstore-test-support_CXXFLAGS += $(libstore-tests_EXTRA_INCLUDES) - -libstore-test-support_LIBS = \ - libutil-test-support \ - libstore libutil - -libstore-test-support_LDFLAGS := $(THREAD_LDFLAGS) -lrapidcheck diff --git a/src/libstore-test-support/meson.build b/src/libstore-test-support/meson.build index f09d26a31..98ec9882e 100644 --- a/src/libstore-test-support/meson.build +++ b/src/libstore-test-support/meson.build @@ -58,6 +58,7 @@ headers = files( ) subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') this_library = library( 'nix-store-test-support', diff --git a/src/libstore-test-support/tests/derived-path.cc b/src/libstore-test-support/tests/derived-path.cc index 091706dba..078615bbd 100644 --- a/src/libstore-test-support/tests/derived-path.cc +++ b/src/libstore-test-support/tests/derived-path.cc @@ -7,7 +7,7 @@ namespace rc { using namespace nix; -Gen Arbitrary::arbitrary() +Gen Arbitrary::arbitrary() { return gen::just(DerivedPath::Opaque { .path = *gen::arbitrary(), diff --git a/src/libstore-tests/local.mk b/src/libstore-tests/local.mk deleted file mode 100644 index b565ff0be..000000000 --- a/src/libstore-tests/local.mk +++ /dev/null @@ -1,38 +0,0 @@ -check: libstore-tests_RUN - -programs += libstore-tests - -libstore-tests_NAME = libnixstore-tests - -libstore-tests_ENV := _NIX_TEST_UNIT_DATA=$(d)/data GTEST_OUTPUT=xml:$$testresults/libstore-tests.xml - -libstore-tests_DIR := $(d) - -ifeq ($(INSTALL_UNIT_TESTS), yes) - libstore-tests_INSTALL_DIR := $(checkbindir) -else - libstore-tests_INSTALL_DIR := -endif - -libstore-tests_SOURCES := $(wildcard $(d)/*.cc) - -libstore-tests_EXTRA_INCLUDES = \ - -I src/libstore-test-support \ - -I src/libutil-test-support \ - $(INCLUDE_libstore) \ - $(INCLUDE_libstorec) \ - $(INCLUDE_libutil) \ - $(INCLUDE_libutilc) - -libstore-tests_CXXFLAGS += $(libstore-tests_EXTRA_INCLUDES) - -libstore-tests_LIBS = \ - libstore-test-support libutil-test-support \ - libstore libstorec libutil libutilc - -libstore-tests_LDFLAGS := -lrapidcheck $(GTEST_LIBS) - -ifdef HOST_WINDOWS - # Increase the default reserved stack size to 65 MB so Nix doesn't run out of space - libstore-tests_LDFLAGS += -Wl,--stack,$(shell echo $$((65 * 1024 * 1024))) -endif diff --git a/src/libstore-tests/meson.build b/src/libstore-tests/meson.build index 3b36cd62f..f4f67d73a 100644 --- a/src/libstore-tests/meson.build +++ b/src/libstore-tests/meson.build @@ -28,6 +28,7 @@ subdir('build-utils-meson/subprojects') subdir('build-utils-meson/threads') subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') sqlite = dependency('sqlite3', 'sqlite', version : '>=3.6.19') deps_private += sqlite diff --git a/src/libstore-tests/package.nix b/src/libstore-tests/package.nix index 5b2fd108b..3704d8c5c 100644 --- a/src/libstore-tests/package.nix +++ b/src/libstore-tests/package.nix @@ -38,15 +38,19 @@ mkMesonExecutable (finalAttrs: { (fileset.fileFilter (file: file.hasExt "hh") ./.) ]; - buildInputs = [ - nix-store - nix-store-c - nix-store-test-support + # Hack for sake of the dev shell + passthru.externalBuildInputs = [ sqlite rapidcheck gtest ]; + buildInputs = finalAttrs.passthru.externalBuildInputs ++ [ + nix-store + nix-store-c + nix-store-test-support + ]; + preConfigure = # "Inline" .version so it's not a symlink, and includes the suffix. # Do the meson utils, without modification. diff --git a/src/libstore-tests/serve-protocol.cc b/src/libstore-tests/serve-protocol.cc index 2505c5a9a..3dbbf3879 100644 --- a/src/libstore-tests/serve-protocol.cc +++ b/src/libstore-tests/serve-protocol.cc @@ -38,6 +38,8 @@ VERSIONED_CHARACTERIZATION_TEST( "oh no \0\0\0 what was that!", })) +#ifndef DOXYGEN_SKIP + VERSIONED_CHARACTERIZATION_TEST( ServeProtoTest, storePath, @@ -84,6 +86,8 @@ VERSIONED_CHARACTERIZATION_TEST( }, })) +#endif + VERSIONED_CHARACTERIZATION_TEST( ServeProtoTest, realisation, @@ -459,21 +463,14 @@ TEST_F(ServeProtoTest, handshake_client_truncated_replay_throws) CharacterizationTest::readTest("handshake-to-client", [&](std::string toClientLog) { for (size_t len = 0; len < toClientLog.size(); ++len) { NullBufferedSink nullSink; - StringSource in { - // truncate - toClientLog.substr(0, len) - }; + auto substring = toClientLog.substr(0, len); + StringSource in{substring}; if (len < 8) { EXPECT_THROW( - ServeProto::BasicClientConnection::handshake( - nullSink, in, defaultVersion, "blah"), - EndOfFile); + ServeProto::BasicClientConnection::handshake(nullSink, in, defaultVersion, "blah"), EndOfFile); } else { // Not sure why cannot keep on checking for `EndOfFile`. - EXPECT_THROW( - ServeProto::BasicClientConnection::handshake( - nullSink, in, defaultVersion, "blah"), - Error); + EXPECT_THROW(ServeProto::BasicClientConnection::handshake(nullSink, in, defaultVersion, "blah"), Error); } } }); diff --git a/src/libstore-tests/worker-protocol.cc b/src/libstore-tests/worker-protocol.cc index bbea9ed75..99b042d5b 100644 --- a/src/libstore-tests/worker-protocol.cc +++ b/src/libstore-tests/worker-protocol.cc @@ -39,6 +39,8 @@ VERSIONED_CHARACTERIZATION_TEST( "oh no \0\0\0 what was that!", })) +#ifndef DOXYGEN_SKIP + VERSIONED_CHARACTERIZATION_TEST( WorkerProtoTest, storePath, @@ -69,6 +71,8 @@ VERSIONED_CHARACTERIZATION_TEST( }, })) +#endif + VERSIONED_CHARACTERIZATION_TEST( WorkerProtoTest, derivedPath_1_29, @@ -725,21 +729,14 @@ TEST_F(WorkerProtoTest, handshake_client_truncated_replay_throws) CharacterizationTest::readTest("handshake-to-client", [&](std::string toClientLog) { for (size_t len = 0; len < toClientLog.size(); ++len) { NullBufferedSink nullSink; - StringSource in { - // truncate - toClientLog.substr(0, len) - }; + auto substring = toClientLog.substr(0, len); + StringSource in{substring}; if (len < 8) { EXPECT_THROW( - WorkerProto::BasicClientConnection::handshake( - nullSink, in, defaultVersion, {}), - EndOfFile); + WorkerProto::BasicClientConnection::handshake(nullSink, in, defaultVersion, {}), EndOfFile); } else { // Not sure why cannot keep on checking for `EndOfFile`. - EXPECT_THROW( - WorkerProto::BasicClientConnection::handshake( - nullSink, in, defaultVersion, {}), - Error); + EXPECT_THROW(WorkerProto::BasicClientConnection::handshake(nullSink, in, defaultVersion, {}), Error); } } }); diff --git a/src/libstore/build/derivation-goal.cc b/src/libstore/build/derivation-goal.cc index 34ed16a38..794be1568 100644 --- a/src/libstore/build/derivation-goal.cc +++ b/src/libstore/build/derivation-goal.cc @@ -991,7 +991,10 @@ Goal::Co DerivationGoal::buildDone() auto nixLogCommand = experimentalFeatureSettings.isEnabled(Xp::NixCommand) ? "nix log" : "nix-store -l"; - msg += fmt("For full logs, run '" ANSI_BOLD "%s %s" ANSI_NORMAL "'.", + // The command is on a separate line for easy copying, such as with triple click. + // This message will be indented elsewhere, so removing the indentation before the + // command will not put it at the start of the line unfortunately. + msg += fmt("For full logs, run:\n " ANSI_BOLD "%s %s" ANSI_NORMAL, nixLogCommand, worker.store.printStorePath(drvPath)); } diff --git a/src/libstore/build/entry-points.cc b/src/libstore/build/entry-points.cc index 4c1373bfa..3bf22320e 100644 --- a/src/libstore/build/entry-points.cc +++ b/src/libstore/build/entry-points.cc @@ -66,6 +66,7 @@ std::vector Store::buildPathsWithResults( worker.run(goals); std::vector results; + results.reserve(state.size()); for (auto & [req, goalPtr] : state) results.emplace_back(KeyedBuildResult { diff --git a/src/libstore/build/goal.hh b/src/libstore/build/goal.hh index 9c6a40c84..1dd7ed525 100644 --- a/src/libstore/build/goal.hh +++ b/src/libstore/build/goal.hh @@ -107,7 +107,7 @@ protected: public: /** - * Suspend our goal and wait until we get @ref work()-ed again. + * Suspend our goal and wait until we get `work`-ed again. * `co_await`-able by @ref Co. */ struct Suspend {}; @@ -192,7 +192,7 @@ public: bool await_ready() { return false; }; /** - * When we `co_await` another @ref Co-returning coroutine, + * When we `co_await` another `Co`-returning coroutine, * we tell the caller of `caller_coroutine.resume()` to switch to our coroutine (@ref handle). * To make sure we return to the original coroutine, we set it as the continuation of our * coroutine. In @ref promise_type::final_awaiter we check if it's set and if so we return to it. @@ -208,7 +208,7 @@ public: }; /** - * Used on initial suspend, does the same as @ref std::suspend_always, + * Used on initial suspend, does the same as `std::suspend_always`, * but asserts that everything has been set correctly. */ struct InitialSuspend { @@ -269,8 +269,8 @@ public: }; /** - * Called by compiler generated code to construct the @ref Co - * that is returned from a @ref Co-returning coroutine. + * Called by compiler generated code to construct the `Co` + * that is returned from a `Co`-returning coroutine. */ Co get_return_object(); diff --git a/src/libstore/build/worker.hh b/src/libstore/build/worker.hh index e083dbea6..f5e617208 100644 --- a/src/libstore/build/worker.hh +++ b/src/libstore/build/worker.hh @@ -208,7 +208,7 @@ public: const OutputsSpec & wantedOutputs, BuildMode buildMode = bmNormal); /** - * @ref SubstitutionGoal "substitution goal" + * @ref PathSubstitutionGoal "substitution goal" */ std::shared_ptr makePathSubstitutionGoal(const StorePath & storePath, RepairFlag repair = NoRepair, std::optional ca = std::nullopt); std::shared_ptr makeDrvOutputSubstitutionGoal(const DrvOutput & id, RepairFlag repair = NoRepair, std::optional ca = std::nullopt); diff --git a/src/libstore/content-address.hh b/src/libstore/content-address.hh index bb515013a..2b5d1296a 100644 --- a/src/libstore/content-address.hh +++ b/src/libstore/content-address.hh @@ -97,8 +97,9 @@ struct ContentAddressMethod * were ingested, with the fixed output case not prefixed for back * compat. * - * @param [in] m A string that should begin with the prefix. - * @param [out] m The remainder of the string after the prefix. + * @param m A string that should begin with the + * prefix. On return, the remainder of the string after the + * prefix. */ static ContentAddressMethod parsePrefix(std::string_view & m); @@ -139,14 +140,14 @@ struct ContentAddressMethod /** * We've accumulated several types of content-addressed paths over the * years; fixed-output derivations support multiple hash algorithms and - * serialisation methods (flat file vs NAR). Thus, ‘ca’ has one of the + * serialisation methods (flat file vs NAR). Thus, `ca` has one of the * following forms: * * - `TextIngestionMethod`: - * ‘text:sha256:’ + * `text:sha256:` * * - `FixedIngestionMethod`: - * ‘fixed:::’ + * `fixed:::` */ struct ContentAddress { diff --git a/src/libstore/derivations.cc b/src/libstore/derivations.cc index 9b6f67852..1f37b0c38 100644 --- a/src/libstore/derivations.cc +++ b/src/libstore/derivations.cc @@ -1017,29 +1017,31 @@ std::string hashPlaceholder(const OutputNameView outputName) return "/" + hashString(HashAlgorithm::SHA256, concatStrings("nix-output:", outputName)).to_string(HashFormat::Nix32, false); } - - - -static void rewriteDerivation(Store & store, BasicDerivation & drv, const StringMap & rewrites) +void BasicDerivation::applyRewrites(const StringMap & rewrites) { - debug("Rewriting the derivation"); + if (rewrites.empty()) return; - for (auto & rewrite : 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) { + builder = rewriteStrings(builder, rewrites); + for (auto & arg : args) arg = rewriteStrings(arg, rewrites); - } StringPairs newEnv; - for (auto & envVar : drv.env) { + for (auto & envVar : env) { auto envName = rewriteStrings(envVar.first, rewrites); auto envValue = rewriteStrings(envVar.second, rewrites); newEnv.emplace(envName, envValue); } - drv.env = newEnv; + env = std::move(newEnv); +} + +static void rewriteDerivation(Store & store, BasicDerivation & drv, const StringMap & rewrites) +{ + drv.applyRewrites(rewrites); auto hashModulo = hashDerivationModulo(store, Derivation(drv), true); for (auto & [outputName, output] : drv.outputs) { diff --git a/src/libstore/derivations.hh b/src/libstore/derivations.hh index 58e5328a5..765b66ade 100644 --- a/src/libstore/derivations.hh +++ b/src/libstore/derivations.hh @@ -298,6 +298,10 @@ struct BasicDerivation std::string name; BasicDerivation() = default; + BasicDerivation(BasicDerivation &&) = default; + BasicDerivation(const BasicDerivation &) = default; + BasicDerivation& operator=(BasicDerivation &&) = default; + BasicDerivation& operator=(const BasicDerivation &) = default; virtual ~BasicDerivation() { }; bool isBuiltin() const; @@ -321,6 +325,12 @@ struct BasicDerivation static std::string_view nameFromPath(const StorePath & storePath); + /** + * Apply string rewrites to the `env`, `args` and `builder` + * fields. + */ + void applyRewrites(const StringMap & rewrites); + bool operator == (const BasicDerivation &) const = default; // TODO libc++ 16 (used by darwin) missing `std::map::operator <=>`, can't do yet. //auto operator <=> (const BasicDerivation &) const = default; diff --git a/src/libstore/filetransfer.cc b/src/libstore/filetransfer.cc index e9e4b2c44..42b93cfe0 100644 --- a/src/libstore/filetransfer.cc +++ b/src/libstore/filetransfer.cc @@ -153,7 +153,7 @@ struct curlFileTransfer : public FileTransfer template void fail(T && e) { - failEx(std::make_exception_ptr(std::move(e))); + failEx(std::make_exception_ptr(std::forward(e))); } LambdaSink finalSink; diff --git a/src/libstore/gc.cc b/src/libstore/gc.cc index 73195794a..45dfe4ad8 100644 --- a/src/libstore/gc.cc +++ b/src/libstore/gc.cc @@ -4,6 +4,7 @@ #include "finally.hh" #include "unix-domain-socket.hh" #include "signals.hh" +#include "posix-fs-canonicalise.hh" #if !defined(__linux__) // For shelling out to lsof @@ -763,13 +764,18 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results) } } } - for (auto & path : topoSortPaths(visited)) { if (!dead.insert(path).second) continue; if (shouldDelete) { - invalidatePathChecked(path); - deleteFromStore(path.to_string()); - referrersCache.erase(path); + try { + invalidatePathChecked(path); + deleteFromStore(path.to_string()); + referrersCache.erase(path); + } catch (PathInUse &e) { + // If we end up here, it's likely a new occurence + // of https://github.com/NixOS/nix/issues/11923 + printError("BUG: %s", e.what()); + } } } }; diff --git a/src/libstore/length-prefixed-protocol-helper.hh b/src/libstore/length-prefixed-protocol-helper.hh index 0cf950a47..7e977bbf1 100644 --- a/src/libstore/length-prefixed-protocol-helper.hh +++ b/src/libstore/length-prefixed-protocol-helper.hh @@ -1,6 +1,8 @@ #pragma once /** - * @file Reusable serialisers for serialization container types in a + * @file + * + * Reusable serialisers for serialization container types in a * length-prefixed manner. * * Used by both the Worker and Serve protocols. @@ -28,25 +30,22 @@ struct StoreDirConfig; template struct LengthPrefixedProtoHelper; -/*! - * \typedef LengthPrefixedProtoHelper::S - * - * Read this as simply `using S = Inner::Serialise;`. - * - * It would be nice to use that directly, but C++ doesn't seem to allow - * it. The `typename` keyword needed to refer to `Inner` seems to greedy - * (low precedence), and then C++ complains that `Serialise` is not a - * type parameter but a real type. - * - * Making this `S` alias seems to be the only way to avoid these issues. - */ - #define LENGTH_PREFIXED_PROTO_HELPER(Inner, T) \ struct LengthPrefixedProtoHelper< Inner, T > \ { \ static T read(const StoreDirConfig & store, typename Inner::ReadConn conn); \ static void write(const StoreDirConfig & store, typename Inner::WriteConn conn, const T & str); \ private: \ + /*! \ + * Read this as simply `using S = Inner::Serialise;`. \ + * \ + * It would be nice to use that directly, but C++ doesn't seem to allow \ + * it. The `typename` keyword needed to refer to `Inner` seems to greedy \ + * (low precedence), and then C++ complains that `Serialise` is not a \ + * type parameter but a real type. \ + * \ + * Making this `S` alias seems to be the only way to avoid these issues. \ + */ \ template using S = typename Inner::template Serialise; \ } @@ -60,9 +59,8 @@ template LENGTH_PREFIXED_PROTO_HELPER(Inner, std::tuple); template -#define _X std::map -LENGTH_PREFIXED_PROTO_HELPER(Inner, _X); -#undef _X +#define LENGTH_PREFIXED_PROTO_HELPER_X std::map +LENGTH_PREFIXED_PROTO_HELPER(Inner, LENGTH_PREFIXED_PROTO_HELPER_X); template std::vector diff --git a/src/libstore/local.mk b/src/libstore/local.mk deleted file mode 100644 index 43d8993ba..000000000 --- a/src/libstore/local.mk +++ /dev/null @@ -1,103 +0,0 @@ -libraries += libstore - -libstore_NAME = libnixstore - -libstore_DIR := $(d) - -libstore_SOURCES := $(wildcard $(d)/*.cc $(d)/builtins/*.cc $(d)/build/*.cc) -ifdef HOST_UNIX - libstore_SOURCES += $(wildcard $(d)/unix/*.cc $(d)/unix/build/*.cc) -endif -ifdef HOST_LINUX - libstore_SOURCES += $(wildcard $(d)/linux/*.cc) -endif -ifdef HOST_WINDOWS - libstore_SOURCES += $(wildcard $(d)/windows/*.cc) -endif - -libstore_LIBS = libutil - -libstore_LDFLAGS += $(SQLITE3_LIBS) $(LIBCURL_LIBS) $(THREAD_LDFLAGS) -ifdef HOST_LINUX - libstore_LDFLAGS += -ldl -endif -ifdef HOST_WINDOWS - libstore_LDFLAGS += -lws2_32 -endif - -$(foreach file,$(libstore_FILES),$(eval $(call install-data-in,$(d)/$(file),$(datadir)/nix/sandbox))) - -ifeq ($(ENABLE_S3), 1) - libstore_LDFLAGS += -laws-cpp-sdk-transfer -laws-cpp-sdk-s3 -laws-cpp-sdk-core -laws-crt-cpp -endif - -ifdef HOST_SOLARIS - libstore_LDFLAGS += -lsocket -endif - -ifeq ($(HAVE_SECCOMP), 1) - libstore_LDFLAGS += $(LIBSECCOMP_LIBS) -endif - -# Not just for this library itself, but also for downstream libraries using this library - -INCLUDE_libstore := -I $(d) -I $(d)/build -ifdef HOST_UNIX - INCLUDE_libstore += -I $(d)/unix -I $(d)/unix/build -endif -ifdef HOST_LINUX - INCLUDE_libstore += -I $(d)/linux -endif -ifdef HOST_WINDOWS - INCLUDE_libstore += -I $(d)/windows -endif - -ifdef HOST_WINDOWS -NIX_ROOT = N:\\\\ -else -NIX_ROOT = -endif - -# Prefix all but `NIX_STORE_DIR`, since we aren't doing a local store -# yet so a "logical" store dir that is the same as unix is preferred. -# -# Also, it keeps the unit tests working. - -libstore_CXXFLAGS += \ - $(INCLUDE_libutil) $(INCLUDE_libstore) $(INCLUDE_libstore) \ - -DNIX_PREFIX=\"$(NIX_ROOT)$(prefix)\" \ - -DNIX_STORE_DIR=\"$(storedir)\" \ - -DNIX_DATA_DIR=\"$(NIX_ROOT)$(datadir)\" \ - -DNIX_STATE_DIR=\"$(NIX_ROOT)$(localstatedir)/nix\" \ - -DNIX_LOG_DIR=\"$(NIX_ROOT)$(localstatedir)/log/nix\" \ - -DNIX_CONF_DIR=\"$(NIX_ROOT)$(sysconfdir)/nix\" \ - -DNIX_MAN_DIR=\"$(NIX_ROOT)$(mandir)\" \ - -DLSOF=\"$(NIX_ROOT)$(lsof)\" - -ifeq ($(embedded_sandbox_shell),yes) -libstore_CXXFLAGS += -DSANDBOX_SHELL=\"__embedded_sandbox_shell__\" - -$(d)/unix/build/local-derivation-goal.cc: $(d)/unix/embedded-sandbox-shell.gen.hh - -$(d)/unix/embedded-sandbox-shell.gen.hh: $(sandbox_shell) - $(trace-gen) hexdump -v -e '1/1 "0x%x," "\n"' < $< > $@.tmp - @mv $@.tmp $@ -else - ifneq ($(sandbox_shell),) - libstore_CXXFLAGS += -DSANDBOX_SHELL="\"$(sandbox_shell)\"" - endif -endif - -$(d)/local-store.cc: $(d)/schema.sql.gen.hh $(d)/ca-specific-schema.sql.gen.hh - -$(d)/unix/build.cc: - -clean-files += $(d)/schema.sql.gen.hh $(d)/ca-specific-schema.sql.gen.hh - -$(eval $(call install-file-in, $(buildprefix)$(d)/nix-store.pc, $(libdir)/pkgconfig, 0644)) - -$(foreach i, $(wildcard src/libstore/builtins/*.hh), \ - $(eval $(call install-file-in, $(i), $(includedir)/nix/builtins, 0644))) - -$(foreach i, $(wildcard src/libstore/build/*.hh), \ - $(eval $(call install-file-in, $(i), $(includedir)/nix/build, 0644))) diff --git a/src/libstore/machines.cc b/src/libstore/machines.cc index 5e038fb28..eb729b697 100644 --- a/src/libstore/machines.cc +++ b/src/libstore/machines.cc @@ -33,7 +33,7 @@ Machine::Machine( systemTypes(systemTypes), sshKey(sshKey), maxJobs(maxJobs), - speedFactor(speedFactor == 0.0f ? 1.0f : std::move(speedFactor)), + speedFactor(speedFactor == 0.0f ? 1.0f : speedFactor), supportedFeatures(supportedFeatures), mandatoryFeatures(mandatoryFeatures), sshPublicHostKey(sshPublicHostKey) diff --git a/src/libstore/machines.hh b/src/libstore/machines.hh index 983652d5f..b70ab9078 100644 --- a/src/libstore/machines.hh +++ b/src/libstore/machines.hh @@ -32,12 +32,12 @@ struct Machine { /** * @return Whether `features` is a subset of the union of `supportedFeatures` and - * `mandatoryFeatures` + * `mandatoryFeatures`. */ bool allSupported(const std::set & features) const; /** - * @return @Whether `mandatoryFeatures` is a subset of `features` + * @return Whether `mandatoryFeatures` is a subset of `features`. */ bool mandatoryMet(const std::set & features) const; diff --git a/src/libstore/meson.build b/src/libstore/meson.build index c2aa5bff3..101879e90 100644 --- a/src/libstore/meson.build +++ b/src/libstore/meson.build @@ -34,6 +34,8 @@ subdir('build-utils-meson/subprojects') run_command('ln', '-s', meson.project_build_root() / '__nothing_link_target', meson.project_build_root() / '__nothing_symlink', + # native doesn't allow dangling symlinks, which the tests require + env : { 'MSYS' : 'winsymlinks:lnk' }, check : true, ) can_link_symlink = run_command('ln', @@ -74,6 +76,12 @@ if host_machine.system() == 'darwin' deps_other += [sandbox] endif +if host_machine.system() == 'windows' + wsock32 = cxx.find_library('wsock32') + deps_other += [wsock32] +endif + +subdir('build-utils-meson/libatomic') subdir('build-utils-meson/threads') boost = dependency( @@ -410,6 +418,7 @@ foreach name, value : cpp_str_defines endforeach subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') this_library = library( 'nixstore', diff --git a/src/libstore/nix-store.pc.in b/src/libstore/nix-store.pc.in deleted file mode 100644 index cd3f2b8da..000000000 --- a/src/libstore/nix-store.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: Nix -Description: Nix Package Manager -Version: @PACKAGE_VERSION@ -Requires: nix-util -Libs: -L${libdir} -lnixstore -Cflags: -I${includedir}/nix -std=c++2a diff --git a/src/libstore/outputs-spec.cc b/src/libstore/outputs-spec.cc index f5ecbd74b..b623a975c 100644 --- a/src/libstore/outputs-spec.cc +++ b/src/libstore/outputs-spec.cc @@ -153,7 +153,10 @@ namespace nlohmann { using namespace nix; -OutputsSpec adl_serializer::from_json(const json & json) { +#ifndef DOXYGEN_SKIP + +OutputsSpec adl_serializer::from_json(const json & json) +{ auto names = json.get(); if (names == StringSet({"*"})) return OutputsSpec::All {}; @@ -161,7 +164,8 @@ OutputsSpec adl_serializer::from_json(const json & json) { return OutputsSpec::Names { std::move(names) }; } -void adl_serializer::to_json(json & json, OutputsSpec t) { +void adl_serializer::to_json(json & json, OutputsSpec t) +{ std::visit(overloaded { [&](const OutputsSpec::All &) { json = std::vector({"*"}); @@ -172,8 +176,8 @@ void adl_serializer::to_json(json & json, OutputsSpec t) { }, t.raw); } - -ExtendedOutputsSpec adl_serializer::from_json(const json & json) { +ExtendedOutputsSpec adl_serializer::from_json(const json & json) +{ if (json.is_null()) return ExtendedOutputsSpec::Default {}; else { @@ -181,7 +185,8 @@ ExtendedOutputsSpec adl_serializer::from_json(const json & } } -void adl_serializer::to_json(json & json, ExtendedOutputsSpec t) { +void adl_serializer::to_json(json & json, ExtendedOutputsSpec t) +{ std::visit(overloaded { [&](const ExtendedOutputsSpec::Default &) { json = nullptr; @@ -192,4 +197,6 @@ void adl_serializer::to_json(json & json, ExtendedOutputsSp }, t.raw); } +#endif + } diff --git a/src/libstore/path-info.hh b/src/libstore/path-info.hh index 71f1476a6..9a4c466a8 100644 --- a/src/libstore/path-info.hh +++ b/src/libstore/path-info.hh @@ -176,17 +176,18 @@ struct ValidPathInfo : UnkeyedValidPathInfo { */ Strings shortRefs() const; - ValidPathInfo(const ValidPathInfo & other) = default; - ValidPathInfo(StorePath && path, UnkeyedValidPathInfo info) : UnkeyedValidPathInfo(info), path(std::move(path)) { }; ValidPathInfo(const StorePath & path, UnkeyedValidPathInfo info) : UnkeyedValidPathInfo(info), path(path) { }; ValidPathInfo(const Store & store, std::string_view name, ContentAddressWithReferences && ca, Hash narHash); - - virtual ~ValidPathInfo() { } }; +static_assert(std::is_move_assignable_v); +static_assert(std::is_copy_assignable_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_move_constructible_v); + using ValidPathInfos = std::map; } diff --git a/src/libstore/path-with-outputs.cc b/src/libstore/path-with-outputs.cc index 161d023d1..e526b1ff6 100644 --- a/src/libstore/path-with-outputs.cc +++ b/src/libstore/path-with-outputs.cc @@ -37,6 +37,7 @@ DerivedPath StorePathWithOutputs::toDerivedPath() const std::vector toDerivedPaths(const std::vector ss) { std::vector reqs; + reqs.reserve(ss.size()); for (auto & s : ss) reqs.push_back(s.toDerivedPath()); return reqs; } diff --git a/src/libstore/path.hh b/src/libstore/path.hh index 2380dc6a2..902262362 100644 --- a/src/libstore/path.hh +++ b/src/libstore/path.hh @@ -81,7 +81,7 @@ typedef std::set StorePathSet; typedef std::vector StorePaths; /** - * The file extension of \ref Derivation derivations when serialized + * The file extension of \ref nix::Derivation derivations when serialized * into store objects. */ constexpr std::string_view drvExtension = ".drv"; diff --git a/src/libstore/profiles.hh b/src/libstore/profiles.hh index b10a72330..33fcf04b3 100644 --- a/src/libstore/profiles.hh +++ b/src/libstore/profiles.hh @@ -1,6 +1,8 @@ #pragma once /** - * @file Implementation of Profiles. + * @file + * + * Implementation of Profiles. * * See the manual for additional information. */ diff --git a/src/libstore/remote-store-connection.hh b/src/libstore/remote-store-connection.hh index 513bd6838..f8549d0b2 100644 --- a/src/libstore/remote-store-connection.hh +++ b/src/libstore/remote-store-connection.hh @@ -40,7 +40,7 @@ struct RemoteStore::ConnectionHandle : handle(std::move(handle)) { } - ConnectionHandle(ConnectionHandle && h) + ConnectionHandle(ConnectionHandle && h) noexcept : handle(std::move(h.handle)) { } diff --git a/src/libstore/serve-protocol-impl.hh b/src/libstore/serve-protocol-impl.hh index 6f3b177ac..099eade64 100644 --- a/src/libstore/serve-protocol-impl.hh +++ b/src/libstore/serve-protocol-impl.hh @@ -29,11 +29,10 @@ SERVE_USE_LENGTH_PREFIX_SERIALISER(template, std::vector) SERVE_USE_LENGTH_PREFIX_SERIALISER(template, std::set) SERVE_USE_LENGTH_PREFIX_SERIALISER(template, std::tuple) -#define COMMA_ , +#define SERVE_USE_LENGTH_PREFIX_SERIALISER_COMMA , SERVE_USE_LENGTH_PREFIX_SERIALISER( - template, - std::map) -#undef COMMA_ + template, + std::map) /** * Use `CommonProto` where possible. diff --git a/src/libstore/sqlite.hh b/src/libstore/sqlite.hh index 003e4d101..037380b71 100644 --- a/src/libstore/sqlite.hh +++ b/src/libstore/sqlite.hh @@ -42,7 +42,8 @@ struct SQLite SQLite(const Path & path, SQLiteOpenMode mode = SQLiteOpenMode::Normal); SQLite(const SQLite & from) = delete; SQLite& operator = (const SQLite & from) = delete; - SQLite& operator = (SQLite && from) { db = from.db; from.db = 0; return *this; } + // NOTE: This is noexcept since we are only copying and assigning raw pointers. + SQLite& operator = (SQLite && from) noexcept { db = from.db; from.db = 0; return *this; } ~SQLite(); operator sqlite3 * () { return db; } diff --git a/src/libstore/ssh.hh b/src/libstore/ssh.hh index 4097134d0..85be704ec 100644 --- a/src/libstore/ssh.hh +++ b/src/libstore/ssh.hh @@ -59,7 +59,7 @@ public: /** * @param command The command (arg vector) to execute. * - * @param extraSShArgs Extra args to pass to SSH (not the command to + * @param extraSshArgs Extra arguments to pass to SSH (not the command to * execute). Will not be used when "fake SSHing" to the local * machine. */ diff --git a/src/libstore/store-api.hh b/src/libstore/store-api.hh index 8288cfdf0..f45012061 100644 --- a/src/libstore/store-api.hh +++ b/src/libstore/store-api.hh @@ -260,11 +260,11 @@ public: /** * Query the set of all valid paths. Note that for some store - * 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 + * 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. FIXME: should return a set of - * std::variant to get rid of this hack. + * `std::variant` to get rid of this hack. */ virtual StorePathSet queryAllValidPaths() { unsupported("queryAllValidPaths"); } diff --git a/src/libstore/store-dir-config.hh b/src/libstore/store-dir-config.hh index 64c0dd8b7..fd4332b91 100644 --- a/src/libstore/store-dir-config.hh +++ b/src/libstore/store-dir-config.hh @@ -59,20 +59,20 @@ struct StoreDirConfig : public Config std::string showPaths(const StorePathSet & paths); /** - * @return true if ‘path’ is in the Nix store (but not the Nix + * @return true if *path* is in the Nix store (but not the Nix * store itself). */ bool isInStore(PathView path) const; /** - * @return true if ‘path’ is a store path, i.e. a direct child of the + * @return true if *path* is a store path, i.e. a direct child of the * Nix store. */ bool isStorePath(std::string_view path) const; /** - * Split a path like /nix/store/-/ into - * /nix/store/- and /. + * Split a path like `/nix/store/-/` into + * `/nix/store/-` and `/`. */ std::pair toStorePath(PathView path) const; diff --git a/src/libstore/store-reference.hh b/src/libstore/store-reference.hh index 459cea9c2..7100a1db0 100644 --- a/src/libstore/store-reference.hh +++ b/src/libstore/store-reference.hh @@ -13,31 +13,31 @@ namespace nix { * * Supported values are: * - * - ‘local’: The Nix store in /nix/store and database in + * - `local`: The Nix store in /nix/store and database in * /nix/var/nix/db, accessed directly. * - * - ‘daemon’: The Nix store accessed via a Unix domain socket + * - `daemon`: The Nix store accessed via a Unix domain socket * connection to nix-daemon. * - * - ‘unix://’: The Nix store accessed via a Unix domain socket - * connection to nix-daemon, with the socket located at . + * - `unix://`: The Nix store accessed via a Unix domain socket + * connection to nix-daemon, with the socket located at ``. * - * - ‘auto’ or ‘’: Equivalent to ‘local’ or ‘daemon’ depending on + * - `auto` or ``: Equivalent to `local` or `daemon` depending on * whether the user has write access to the local Nix * store/database. * - * - ‘file://’: A binary cache stored in . + * - `file://`: A binary cache stored in ``. * - * - ‘https://’: A binary cache accessed via HTTP. + * - `https://`: A binary cache accessed via HTTP. * - * - ‘s3://’: A writable binary cache stored on Amazon's Simple + * - `s3://`: A writable binary cache stored on Amazon's Simple * Storage Service. * - * - ‘ssh://[user@]’: A remote Nix store accessed by running - * ‘nix-store --serve’ via SSH. + * - `ssh://[user@]`: A remote Nix store accessed by running + * `nix-store --serve` via SSH. * * You can pass parameters to the store type by appending - * ‘?key=value&key=value&...’ to the URI. + * `?key=value&key=value&...` to the URI. */ struct StoreReference { diff --git a/src/libstore/worker-protocol-connection.hh b/src/libstore/worker-protocol-connection.hh index 9665067dd..c2f446db1 100644 --- a/src/libstore/worker-protocol-connection.hh +++ b/src/libstore/worker-protocol-connection.hh @@ -78,7 +78,7 @@ struct WorkerProto::BasicClientConnection : WorkerProto::BasicConnection /** * Establishes connection, negotiating version. * - * @return the minimum version supported by both sides and the set + * @return The minimum version supported by both sides and the set * of protocol features supported by both sides. * * @param to Taken by reference to allow for various error handling @@ -87,9 +87,9 @@ struct WorkerProto::BasicClientConnection : WorkerProto::BasicConnection * @param from Taken by reference to allow for various error * handling mechanisms. * - * @param localVersion Our version which is sent over + * @param localVersion Our version which is sent over. * - * @param features The protocol features that we support + * @param supportedFeatures The protocol features that we support. */ // FIXME: this should probably be a constructor. static std::tuple> handshake( @@ -141,7 +141,7 @@ struct WorkerProto::BasicServerConnection : WorkerProto::BasicConnection /** * Establishes connection, negotiating version. * - * @return the version provided by the other side of the + * @return The version provided by the other side of the * connection. * * @param to Taken by reference to allow for various error handling @@ -150,9 +150,9 @@ struct WorkerProto::BasicServerConnection : WorkerProto::BasicConnection * @param from Taken by reference to allow for various error * handling mechanisms. * - * @param localVersion Our version which is sent over + * @param localVersion Our version which is sent over. * - * @param features The protocol features that we support + * @param supportedFeatures The protocol features that we support. */ // FIXME: this should probably be a constructor. static std::tuple> handshake( diff --git a/src/libstore/worker-protocol-impl.hh b/src/libstore/worker-protocol-impl.hh index 026cc37bc..87398df90 100644 --- a/src/libstore/worker-protocol-impl.hh +++ b/src/libstore/worker-protocol-impl.hh @@ -29,11 +29,10 @@ WORKER_USE_LENGTH_PREFIX_SERIALISER(template, std::vector) WORKER_USE_LENGTH_PREFIX_SERIALISER(template, std::set) WORKER_USE_LENGTH_PREFIX_SERIALISER(template, std::tuple) -#define COMMA_ , +#define WORKER_USE_LENGTH_PREFIX_SERIALISER_COMMA , WORKER_USE_LENGTH_PREFIX_SERIALISER( - template, - std::map) -#undef COMMA_ + template, + std::map) /** * Use `CommonProto` where possible. diff --git a/src/libutil-c/local.mk b/src/libutil-c/local.mk deleted file mode 100644 index f2df1ef43..000000000 --- a/src/libutil-c/local.mk +++ /dev/null @@ -1,18 +0,0 @@ -libraries += libutilc - -libutilc_NAME = libnixutilc - -libutilc_DIR := $(d) - -libutilc_SOURCES := $(wildcard $(d)/*.cc) - -# Not just for this library itself, but also for downstream libraries using this library - -INCLUDE_libutilc := -I $(d) -libutilc_CXXFLAGS += $(INCLUDE_libutil) $(INCLUDE_libutilc) - -libutilc_LIBS = libutil - -libutilc_LDFLAGS += $(THREAD_LDFLAGS) - -libutilc_FORCE_INSTALL := 1 diff --git a/src/libutil-c/meson.build b/src/libutil-c/meson.build index b5ed19631..3d5a0b9c2 100644 --- a/src/libutil-c/meson.build +++ b/src/libutil-c/meson.build @@ -63,6 +63,7 @@ headers = [config_h] + files( headers += files('nix_api_util_internal.h') subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') this_library = library( 'nixutilc', diff --git a/src/libutil-c/nix-util-c.pc.in b/src/libutil-c/nix-util-c.pc.in deleted file mode 100644 index 0ccae3f8a..000000000 --- a/src/libutil-c/nix-util-c.pc.in +++ /dev/null @@ -1,9 +0,0 @@ -prefix=@prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: Nix libutil C API -Description: Common functions for the Nix C API, such as error handling -Version: @PACKAGE_VERSION@ -Libs: -L${libdir} -lnixutil -Cflags: -I${includedir}/nix -std=c++2a diff --git a/src/libutil-c/nix_api_util.h b/src/libutil-c/nix_api_util.h index 6790a6964..43f9fa9dc 100644 --- a/src/libutil-c/nix_api_util.h +++ b/src/libutil-c/nix_api_util.h @@ -162,7 +162,7 @@ void nix_c_context_free(nix_c_context * context); */ nix_err nix_libutil_init(nix_c_context * context); -/** @defgroup settings +/** @defgroup settings Nix configuration settings * @{ */ /** diff --git a/src/libutil-test-support/local.mk b/src/libutil-test-support/local.mk deleted file mode 100644 index 5f7835c9f..000000000 --- a/src/libutil-test-support/local.mk +++ /dev/null @@ -1,19 +0,0 @@ -libraries += libutil-test-support - -libutil-test-support_NAME = libnixutil-test-support - -libutil-test-support_DIR := $(d) - -ifeq ($(INSTALL_UNIT_TESTS), yes) - libutil-test-support_INSTALL_DIR := $(checklibdir) -else - libutil-test-support_INSTALL_DIR := -endif - -libutil-test-support_SOURCES := $(wildcard $(d)/tests/*.cc) - -libutil-test-support_CXXFLAGS += $(libutil-tests_EXTRA_INCLUDES) - -libutil-test-support_LIBS = libutil - -libutil-test-support_LDFLAGS := $(THREAD_LDFLAGS) -lrapidcheck diff --git a/src/libutil-test-support/meson.build b/src/libutil-test-support/meson.build index 42b49a6a0..c5e1ba80b 100644 --- a/src/libutil-test-support/meson.build +++ b/src/libutil-test-support/meson.build @@ -53,6 +53,7 @@ headers = files( ) subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') this_library = library( 'nix-util-test-support', diff --git a/src/libutil-test-support/tests/gtest-with-params.hh b/src/libutil-test-support/tests/gtest-with-params.hh index 323a083fe..d72aec4fd 100644 --- a/src/libutil-test-support/tests/gtest-with-params.hh +++ b/src/libutil-test-support/tests/gtest-with-params.hh @@ -6,7 +6,9 @@ // The lion's share of this code is copy pasted directly out of RapidCheck // headers, so the copyright is set accordingly. /** - * @file Implements the ability to run a RapidCheck test under gtest with changed + * @file + * + * Implements the ability to run a RapidCheck test under gtest with changed * test parameters such as the number of tests to run. This is useful for * running very large numbers of the extremely cheap property tests. */ diff --git a/src/libutil-tests/local.mk b/src/libutil-tests/local.mk deleted file mode 100644 index c747863a4..000000000 --- a/src/libutil-tests/local.mk +++ /dev/null @@ -1,37 +0,0 @@ -check: libutil-tests_RUN - -programs += libutil-tests - -libutil-tests_NAME = libnixutil-tests - -libutil-tests_ENV := _NIX_TEST_UNIT_DATA=$(d)/data GTEST_OUTPUT=xml:$$testresults/libutil-tests.xml - -libutil-tests_DIR := $(d) - -ifeq ($(INSTALL_UNIT_TESTS), yes) - libutil-tests_INSTALL_DIR := $(checkbindir) -else - libutil-tests_INSTALL_DIR := -endif - -libutil-tests_SOURCES := $(wildcard $(d)/*.cc) - -libutil-tests_EXTRA_INCLUDES = \ - -I src/libutil-test-support \ - $(INCLUDE_libutil) \ - $(INCLUDE_libutilc) - -libutil-tests_CXXFLAGS += $(libutil-tests_EXTRA_INCLUDES) - -libutil-tests_LIBS = libutil-test-support libutil libutilc - -libutil-tests_LDFLAGS := -lrapidcheck $(GTEST_LIBS) - -ifdef HOST_WINDOWS - # Increase the default reserved stack size to 65 MB so Nix doesn't run out of space - libutil-tests_LDFLAGS += -Wl,--stack,$(shell echo $$((65 * 1024 * 1024))) -endif - -check: $(d)/data/git/check-data.sh.test - -$(eval $(call run-test,$(d)/data/git/check-data.sh)) diff --git a/src/libutil-tests/meson.build b/src/libutil-tests/meson.build index c39db8cda..5c3b5e5a3 100644 --- a/src/libutil-tests/meson.build +++ b/src/libutil-tests/meson.build @@ -28,6 +28,7 @@ subdir('build-utils-meson/subprojects') subdir('build-utils-meson/threads') subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') rapidcheck = dependency('rapidcheck') deps_private += rapidcheck diff --git a/src/libutil-tests/nix_api_util.cc b/src/libutil-tests/nix_api_util.cc index 0f1cbe5dd..b36f71042 100644 --- a/src/libutil-tests/nix_api_util.cc +++ b/src/libutil-tests/nix_api_util.cc @@ -7,6 +7,8 @@ #include +#include + namespace nixC { TEST_F(nix_api_util_context, nix_context_error) @@ -57,6 +59,14 @@ struct MySettings : nix::Config MySettings mySettings; static nix::GlobalConfig::Register rs(&mySettings); +static auto createOwnedNixContext() +{ + return std::unique_ptr(nix_c_context_create(), {}); +} + TEST_F(nix_api_util_context, nix_setting_get) { ASSERT_EQ(ctx->last_err_code, NIX_OK); @@ -97,7 +107,8 @@ TEST_F(nix_api_util_context, nix_err_msg) // advanced usage unsigned int sz; - err_msg = nix_err_msg(nix_c_context_create(), ctx, &sz); + auto new_ctx = createOwnedNixContext(); + err_msg = nix_err_msg(new_ctx.get(), ctx, &sz); ASSERT_EQ(sz, err_msg.size()); } @@ -113,7 +124,8 @@ TEST_F(nix_api_util_context, nix_err_info_msg) } catch (...) { nix_context_error(ctx); } - nix_err_info_msg(nix_c_context_create(), ctx, OBSERVE_STRING(err_info)); + auto new_ctx = createOwnedNixContext(); + nix_err_info_msg(new_ctx.get(), ctx, OBSERVE_STRING(err_info)); ASSERT_STREQ("testing error", err_info.c_str()); } @@ -130,7 +142,8 @@ TEST_F(nix_api_util_context, nix_err_name) } catch (...) { nix_context_error(ctx); } - nix_err_name(nix_c_context_create(), ctx, OBSERVE_STRING(err_name)); + auto new_ctx = createOwnedNixContext(); + nix_err_name(new_ctx.get(), ctx, OBSERVE_STRING(err_name)); ASSERT_EQ(std::string(err_name), "nix::Error"); } diff --git a/src/libutil-tests/terminal.cc b/src/libutil-tests/terminal.cc index cdeb9fd94..714d5a237 100644 --- a/src/libutil-tests/terminal.cc +++ b/src/libutil-tests/terminal.cc @@ -57,4 +57,9 @@ TEST(filterANSIEscapes, utf8) ASSERT_EQ(filterANSIEscapes("f𐍈𐍈bär", true, 4), "f𐍈𐍈b"); } +TEST(filterANSIEscapes, osc8) +{ + ASSERT_EQ(filterANSIEscapes("\e]8;;http://example.com\e\\This is a link\e]8;;\e\\"), "This is a link"); +} + } // namespace nix diff --git a/src/libutil/args.cc b/src/libutil/args.cc index 4e87389d6..385b6cd34 100644 --- a/src/libutil/args.cc +++ b/src/libutil/args.cc @@ -91,9 +91,6 @@ struct Parser { /** * @brief Parse the next character(s) - * - * @param r - * @return std::shared_ptr */ virtual void operator()(std::shared_ptr & state, Strings & r) = 0; diff --git a/src/libutil/args.hh b/src/libutil/args.hh index 127a0809e..c30d6cef8 100644 --- a/src/libutil/args.hh +++ b/src/libutil/args.hh @@ -371,7 +371,7 @@ using Commands = std::map()>>; /** * An argument parser that supports multiple subcommands, - * i.e. ‘ ’. + * i.e. ` `. */ class MultiCommand : virtual public Args { diff --git a/src/libutil/callback.hh b/src/libutil/callback.hh index 3710d1239..26c386d80 100644 --- a/src/libutil/callback.hh +++ b/src/libutil/callback.hh @@ -21,7 +21,9 @@ public: Callback(std::function)> fun) : fun(fun) { } - Callback(Callback && callback) : fun(std::move(callback.fun)) + // NOTE: std::function is noexcept move-constructible since C++20. + Callback(Callback && callback) noexcept(std::is_nothrow_move_constructible_v) + : fun(std::move(callback.fun)) { auto prev = callback.done.test_and_set(); if (prev) done.test_and_set(); diff --git a/src/libutil/checked-arithmetic.hh b/src/libutil/checked-arithmetic.hh index 55d6ad205..dcc6d86af 100644 --- a/src/libutil/checked-arithmetic.hh +++ b/src/libutil/checked-arithmetic.hh @@ -1,6 +1,8 @@ #pragma once /** - * @file Checked arithmetic with classes that make it hard to accidentally make something an unchecked operation. + * @file + * + * Checked arithmetic with classes that make it hard to accidentally make something an unchecked operation. */ #include diff --git a/src/libutil/executable-path.cc b/src/libutil/executable-path.cc index 9fb5214b2..ebd522a41 100644 --- a/src/libutil/executable-path.cc +++ b/src/libutil/executable-path.cc @@ -35,7 +35,7 @@ ExecutablePath ExecutablePath::parse(const OsString & path) std::make_move_iterator(strings.begin()), std::make_move_iterator(strings.end()), std::back_inserter(ret), - [](auto && str) { + [](OsString && str) { return fs::path{ str.empty() // "A zero-length prefix is a legacy feature that @@ -56,6 +56,7 @@ ExecutablePath ExecutablePath::parse(const OsString & path) OsString ExecutablePath::render() const { std::vector path2; + path2.reserve(directories.size()); for (auto & p : directories) path2.push_back(p.native()); return basicConcatStringsSep(path_var_separator, path2); diff --git a/src/libutil/file-content-address.hh b/src/libutil/file-content-address.hh index 0c584ea8a..226068387 100644 --- a/src/libutil/file-content-address.hh +++ b/src/libutil/file-content-address.hh @@ -65,7 +65,7 @@ void dumpPath( /** * Restore a serialisation of the given file system object. * - * @TODO use an arbitrary `FileSystemObjectSink`. + * \todo use an arbitrary `FileSystemObjectSink`. */ void restorePath( const Path & path, diff --git a/src/libutil/file-descriptor.cc b/src/libutil/file-descriptor.cc index 3d8d70fdb..542c33f3b 100644 --- a/src/libutil/file-descriptor.cc +++ b/src/libutil/file-descriptor.cc @@ -45,8 +45,9 @@ AutoCloseFD::AutoCloseFD() : fd{INVALID_DESCRIPTOR} {} AutoCloseFD::AutoCloseFD(Descriptor fd) : fd{fd} {} - -AutoCloseFD::AutoCloseFD(AutoCloseFD && that) : fd{that.fd} +// NOTE: This can be noexcept since we are just copying a value and resetting +// the file descriptor in the rhs. +AutoCloseFD::AutoCloseFD(AutoCloseFD && that) noexcept : fd{that.fd} { that.fd = INVALID_DESCRIPTOR; } diff --git a/src/libutil/file-descriptor.hh b/src/libutil/file-descriptor.hh index b54bab83c..fde362999 100644 --- a/src/libutil/file-descriptor.hh +++ b/src/libutil/file-descriptor.hh @@ -77,8 +77,13 @@ void writeFull(Descriptor fd, std::string_view s, bool allowInterrupts = true); /** * Read a line from a file descriptor. + * + * @param fd The file descriptor to read from + * @param eofOk If true, return an unterminated line if EOF is reached. (e.g. the empty string) + * + * @return A line of text ending in `\n`, or a string without `\n` if `eofOk` is true and EOF is reached. */ -std::string readLine(Descriptor fd); +std::string readLine(Descriptor fd, bool eofOk = false); /** * Write a line to a file descriptor. @@ -101,8 +106,25 @@ void drainFD( #endif ); +/** + * Get [Standard Input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)) + */ [[gnu::always_inline]] -inline Descriptor getStandardOut() { +inline Descriptor getStandardInput() +{ +#ifndef _WIN32 + return STDIN_FILENO; +#else + return GetStdHandle(STD_INPUT_HANDLE); +#endif +} + +/** + * Get [Standard Output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) + */ +[[gnu::always_inline]] +inline Descriptor getStandardOutput() +{ #ifndef _WIN32 return STDOUT_FILENO; #else @@ -110,6 +132,19 @@ inline Descriptor getStandardOut() { #endif } +/** + * Get [Standard Error](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) + */ +[[gnu::always_inline]] +inline Descriptor getStandardError() +{ +#ifndef _WIN32 + return STDERR_FILENO; +#else + return GetStdHandle(STD_ERROR_HANDLE); +#endif +} + /** * Automatic cleanup of resources. */ @@ -120,7 +155,7 @@ public: AutoCloseFD(); AutoCloseFD(Descriptor fd); AutoCloseFD(const AutoCloseFD & fd) = delete; - AutoCloseFD(AutoCloseFD&& fd); + AutoCloseFD(AutoCloseFD&& fd) noexcept; ~AutoCloseFD(); AutoCloseFD& operator =(const AutoCloseFD & fd) = delete; AutoCloseFD& operator =(AutoCloseFD&& fd); diff --git a/src/libutil/file-system.cc b/src/libutil/file-system.cc index fd51d7d3c..92996ea47 100644 --- a/src/libutil/file-system.cc +++ b/src/libutil/file-system.cc @@ -501,7 +501,7 @@ void deletePath(const fs::path & path, uint64_t & bytesFreed) AutoDelete::AutoDelete() : del{false} {} -AutoDelete::AutoDelete(const fs::path & p, bool recursive) : _path(p) +AutoDelete::AutoDelete(const std::filesystem::path & p, bool recursive) : _path(p) { del = true; this->recursive = recursive; diff --git a/src/libutil/file-system.hh b/src/libutil/file-system.hh index eb3e4ec66..4c08cdf58 100644 --- a/src/libutil/file-system.hh +++ b/src/libutil/file-system.hh @@ -227,7 +227,7 @@ void createDir(const Path & path, mode_t mode = 0755); * Set the access and modification times of the given path, not * following symlinks. * - * @param accessTime Specified in seconds. + * @param accessedTime Specified in seconds. * * @param modificationTime Specified in seconds. * diff --git a/src/libutil/finally.hh b/src/libutil/finally.hh index bda4227e6..2b25010a1 100644 --- a/src/libutil/finally.hh +++ b/src/libutil/finally.hh @@ -20,7 +20,11 @@ public: // Copying Finallys is definitely not a good idea and will cause them to be // called twice. Finally(Finally &other) = delete; - Finally(Finally &&other) : fun(std::move(other.fun)) { + // NOTE: Move constructor can be nothrow if the callable type is itself nothrow + // move-constructible. + Finally(Finally && other) noexcept(std::is_nothrow_move_constructible_v) + : fun(std::move(other.fun)) + { other.movedFrom = true; } ~Finally() noexcept(false) diff --git a/src/libutil/git.hh b/src/libutil/git.hh index 1dbdb7335..1a6a7c333 100644 --- a/src/libutil/git.hh +++ b/src/libutil/git.hh @@ -104,7 +104,7 @@ void parseTree( /** * Helper putting the previous three `parse*` functions together. * - * @rootModeIfBlob How to interpret a root blob, for which there is no + * @param rootModeIfBlob How to interpret a root blob, for which there is no * disambiguating dir entry to answer that questino. If the root it not * a blob, this is ignored. */ diff --git a/src/libutil/json-utils.hh b/src/libutil/json-utils.hh index a61c9cada..546334e1e 100644 --- a/src/libutil/json-utils.hh +++ b/src/libutil/json-utils.hh @@ -91,12 +91,14 @@ namespace nlohmann { * round trip. We do that with a static assert. */ template -struct adl_serializer> { +struct adl_serializer> +{ /** * @brief Convert a JSON type to an `optional` treating * `null` as `std::nullopt`. */ - static void from_json(const json & json, std::optional & t) { + static void from_json(const json & json, std::optional & t) + { static_assert( nix::json_avoids_null::value, "null is already in use for underlying type's JSON"); @@ -109,7 +111,8 @@ struct adl_serializer> { * @brief Convert an optional type to a JSON type treating `std::nullopt` * as `null`. */ - static void to_json(json & json, const std::optional & t) { + static void to_json(json & json, const std::optional & t) + { static_assert( nix::json_avoids_null::value, "null is already in use for underlying type's JSON"); diff --git a/src/libutil/local.mk b/src/libutil/local.mk deleted file mode 100644 index e9b498e65..000000000 --- a/src/libutil/local.mk +++ /dev/null @@ -1,44 +0,0 @@ -libraries += libutil - -libutil_NAME = libnixutil - -libutil_DIR := $(d) - -libutil_SOURCES := $(wildcard $(d)/*.cc $(d)/signature/*.cc) -ifdef HOST_UNIX - libutil_SOURCES += $(wildcard $(d)/unix/*.cc) -endif -ifdef HOST_LINUX - libutil_SOURCES += $(wildcard $(d)/linux/*.cc) -endif -ifdef HOST_WINDOWS - libutil_SOURCES += $(wildcard $(d)/windows/*.cc) -endif - -# Not just for this library itself, but also for downstream libraries using this library - -INCLUDE_libutil := -I $(d) -ifdef HOST_UNIX - INCLUDE_libutil += -I $(d)/unix -endif -ifdef HOST_LINUX - INCLUDE_libutil += -I $(d)/linux -endif -ifdef HOST_WINDOWS - INCLUDE_libutil += -I $(d)/windows -endif -libutil_CXXFLAGS += $(INCLUDE_libutil) - -libutil_LDFLAGS += $(THREAD_LDFLAGS) $(LIBCURL_LIBS) $(SODIUM_LIBS) $(OPENSSL_LIBS) $(LIBBROTLI_LIBS) $(LIBARCHIVE_LIBS) $(BOOST_LDFLAGS) -lboost_context - -$(foreach i, $(wildcard $(d)/args/*.hh), \ - $(eval $(call install-file-in, $(i), $(includedir)/nix/args, 0644))) -$(foreach i, $(wildcard $(d)/signature/*.hh), \ - $(eval $(call install-file-in, $(i), $(includedir)/nix/signature, 0644))) - - -ifeq ($(HAVE_LIBCPUID), 1) - libutil_LDFLAGS += -lcpuid -endif - -$(eval $(call install-file-in, $(buildprefix)$(d)/nix-util.pc, $(libdir)/pkgconfig, 0644)) diff --git a/src/libutil/logging.cc b/src/libutil/logging.cc index 3d7371457..80c107ef5 100644 --- a/src/libutil/logging.cc +++ b/src/libutil/logging.cc @@ -38,7 +38,7 @@ void Logger::warn(const std::string & msg) void Logger::writeToStdout(std::string_view s) { - Descriptor standard_out = getStandardOut(); + Descriptor standard_out = getStandardOutput(); writeFull(standard_out, s); writeFull(standard_out, "\n"); } @@ -118,11 +118,7 @@ void writeToStderr(std::string_view s) { try { writeFull( -#ifdef _WIN32 - GetStdHandle(STD_ERROR_HANDLE), -#else - STDERR_FILENO, -#endif + getStandardError(), s, false); } catch (SystemError & e) { /* Ignore failing writes to stderr. We need to ignore write diff --git a/src/libutil/meson.build b/src/libutil/meson.build index 08413783d..a6dc86394 100644 --- a/src/libutil/meson.build +++ b/src/libutil/meson.build @@ -53,16 +53,9 @@ endforeach configdata.set('HAVE_DECL_AT_SYMLINK_NOFOLLOW', cxx.has_header_symbol('fcntl.h', 'AT_SYMLINK_NOFOLLOW').to_int()) +subdir('build-utils-meson/libatomic') subdir('build-utils-meson/threads') -# Check if -latomic is needed -# This is needed for std::atomic on some platforms -# We did not manage to test this reliably on all platforms, so we hardcode -# it for now. -if host_machine.cpu_family() == 'arm' - deps_other += cxx.find_library('atomic') -endif - if host_machine.system() == 'windows' socket = cxx.find_library('ws2_32') deps_other += socket @@ -265,6 +258,7 @@ else endif subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') this_library = library( 'nixutil', diff --git a/src/libutil/nix-util.pc.in b/src/libutil/nix-util.pc.in deleted file mode 100644 index 85bb1e70e..000000000 --- a/src/libutil/nix-util.pc.in +++ /dev/null @@ -1,9 +0,0 @@ -prefix=@prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: Nix -Description: Nix Package Manager -Version: @PACKAGE_VERSION@ -Libs: -L${libdir} -lnixutil -Cflags: -I${includedir}/nix -std=c++2a diff --git a/src/libutil/pool.hh b/src/libutil/pool.hh index 6247b6125..b2ceb7143 100644 --- a/src/libutil/pool.hh +++ b/src/libutil/pool.hh @@ -109,7 +109,15 @@ public: Handle(Pool & pool, std::shared_ptr r) : pool(pool), r(r) { } public: - Handle(Handle && h) : pool(h.pool), r(h.r) { h.r.reset(); } + // NOTE: Copying std::shared_ptr and calling a .reset() on it is always noexcept. + Handle(Handle && h) noexcept + : pool(h.pool) + , r(h.r) + { + static_assert(noexcept(h.r.reset())); + static_assert(noexcept(std::shared_ptr(h.r))); + h.r.reset(); + } Handle(const Handle & l) = delete; diff --git a/src/libutil/position.cc b/src/libutil/position.cc index 5a2529262..946f167b6 100644 --- a/src/libutil/position.cc +++ b/src/libutil/position.cc @@ -9,7 +9,7 @@ Pos::Pos(const Pos * other) } line = other->line; column = other->column; - origin = std::move(other->origin); + origin = other->origin; } Pos::operator std::shared_ptr() const diff --git a/src/libutil/posix-source-accessor.cc b/src/libutil/posix-source-accessor.cc index f26f74d58..50b436893 100644 --- a/src/libutil/posix-source-accessor.cc +++ b/src/libutil/posix-source-accessor.cc @@ -7,8 +7,8 @@ namespace nix { -PosixSourceAccessor::PosixSourceAccessor(std::filesystem::path && root) - : root(std::move(root)) +PosixSourceAccessor::PosixSourceAccessor(std::filesystem::path && argRoot) + : root(std::move(argRoot)) { assert(root.empty() || root.is_absolute()); displayPrefix = root.string(); diff --git a/src/libutil/ref.hh b/src/libutil/ref.hh index 3d0e64ab4..92688bf1e 100644 --- a/src/libutil/ref.hh +++ b/src/libutil/ref.hh @@ -18,11 +18,6 @@ private: std::shared_ptr p; public: - - ref(const ref & r) - : p(r.p) - { } - explicit ref(const std::shared_ptr & p) : p(p) { @@ -75,8 +70,6 @@ public: return ref((std::shared_ptr) p); } - ref & operator=(ref const & rhs) = default; - bool operator == (const ref & other) const { return p == other.p; diff --git a/src/libutil/serialise.hh b/src/libutil/serialise.hh index d9e34e1e0..14721d069 100644 --- a/src/libutil/serialise.hh +++ b/src/libutil/serialise.hh @@ -2,6 +2,7 @@ ///@file #include +#include #include "types.hh" #include "util.hh" @@ -202,7 +203,14 @@ struct StringSource : Source { std::string_view s; size_t pos; + + // NOTE: Prevent unintentional dangling views when an implicit conversion + // from std::string -> std::string_view occurs when the string is passed + // by rvalue. + StringSource(std::string &&) = delete; StringSource(std::string_view s) : s(s), pos(0) { } + StringSource(const std::string& str): StringSource(std::string_view(str)) {} + size_t read(char * data, size_t len) override; }; diff --git a/src/libutil/std-hash.hh b/src/libutil/std-hash.hh index c359d11ca..f99faac46 100644 --- a/src/libutil/std-hash.hh +++ b/src/libutil/std-hash.hh @@ -1,14 +1,17 @@ #pragma once - -//!@file Hashing utilities for use with unordered_map, etc. (ie low level implementation logic, not domain logic like -//! Nix hashing) +/** + * @file + * + * Hashing utilities for use with `std::unordered_map`, etc. (i.e. low + * level implementation logic, not domain logic like Nix hashing). + */ #include namespace nix { /** - * hash_combine() from Boost. Hash several hashable values together + * `hash_combine()` from Boost. Hash several hashable values together * into a single hash. */ inline void hash_combine(std::size_t & seed) {} diff --git a/src/libutil/tarfile.cc b/src/libutil/tarfile.cc index a8a22d283..e412930bb 100644 --- a/src/libutil/tarfile.cc +++ b/src/libutil/tarfile.cc @@ -106,7 +106,7 @@ TarArchive::TarArchive(Source & source, bool raw, std::optional com "Failed to open archive (%s)"); } -TarArchive::TarArchive(const fs::path & path) +TarArchive::TarArchive(const std::filesystem::path & path) : archive{archive_read_new()} , buffer(defaultBufferSize) { diff --git a/src/libutil/terminal.cc b/src/libutil/terminal.cc index 5d5ff7dcb..db7a6fcd1 100644 --- a/src/libutil/terminal.cc +++ b/src/libutil/terminal.cc @@ -45,6 +45,13 @@ std::string filterANSIEscapes(std::string_view s, bool filterAll, unsigned int w while (i != s.end() && *i >= 0x20 && *i <= 0x2f) e += *i++; // eat final byte if (i != s.end() && *i >= 0x40 && *i <= 0x7e) e += last = *i++; + } else if (i != s.end() && *i == ']') { + // OSC + e += *i++; + // eat ESC + while (i != s.end() && *i != '\e') e += *i++; + // eat backslash + if (i != s.end() && *i == '\\') e += last = *i++; } else { if (i != s.end() && *i >= 0x40 && *i <= 0x5f) e += *i++; } diff --git a/src/libutil/unix/file-descriptor.cc b/src/libutil/unix/file-descriptor.cc index 2c1126e09..ac7c086af 100644 --- a/src/libutil/unix/file-descriptor.cc +++ b/src/libutil/unix/file-descriptor.cc @@ -47,7 +47,7 @@ void writeFull(int fd, std::string_view s, bool allowInterrupts) } -std::string readLine(int fd) +std::string readLine(int fd, bool eofOk) { std::string s; while (1) { @@ -58,8 +58,12 @@ std::string readLine(int fd) if (rd == -1) { if (errno != EINTR) throw SysError("reading a line"); - } else if (rd == 0) - throw EndOfFile("unexpected EOF reading a line"); + } else if (rd == 0) { + if (eofOk) + return s; + else + throw EndOfFile("unexpected EOF reading a line"); + } else { if (ch == '\n') return s; s += ch; diff --git a/src/libutil/windows/environment-variables.cc b/src/libutil/windows/environment-variables.cc index 525d08c64..5ce8a1395 100644 --- a/src/libutil/windows/environment-variables.cc +++ b/src/libutil/windows/environment-variables.cc @@ -13,7 +13,7 @@ std::optional getEnvOs(const OsString & key) } // Allocate a buffer to hold the environment variable value - std::wstring value{L'\0', bufferSize}; + std::wstring value{bufferSize, L'\0'}; // Retrieve the environment variable value DWORD resultSize = GetEnvironmentVariableW(key.c_str(), &value[0], bufferSize); diff --git a/src/libutil/windows/file-descriptor.cc b/src/libutil/windows/file-descriptor.cc index 16773e3ea..7b8a712e8 100644 --- a/src/libutil/windows/file-descriptor.cc +++ b/src/libutil/windows/file-descriptor.cc @@ -61,7 +61,7 @@ void writeFull(HANDLE handle, std::string_view s, bool allowInterrupts) } -std::string readLine(HANDLE handle) +std::string readLine(HANDLE handle, bool eofOk) { std::string s; while (1) { @@ -71,8 +71,12 @@ std::string readLine(HANDLE handle) DWORD rd; if (!ReadFile(handle, &ch, 1, &rd, NULL)) { throw WinError("reading a line"); - } else if (rd == 0) - throw EndOfFile("unexpected EOF reading a line"); + } else if (rd == 0) { + if (eofOk) + return s; + else + throw EndOfFile("unexpected EOF reading a line"); + } else { if (ch == '\n') return s; s += ch; diff --git a/src/nix-build/nix-build.cc b/src/nix-build/nix-build.cc index c394836da..de01e1afc 100644 --- a/src/nix-build/nix-build.cc +++ b/src/nix-build/nix-build.cc @@ -340,13 +340,15 @@ static void main_nix_build(int argc, char * * argv) exprs = {state->parseStdin()}; else for (auto i : remainingArgs) { - auto baseDir = inShebang && !packages ? absPath(dirOf(script)) : i; - - if (fromArgs) + if (fromArgs) { + auto shebangBaseDir = absPath(dirOf(script)); exprs.push_back(state->parseExprFromString( std::move(i), - (inShebang && compatibilitySettings.nixShellShebangArgumentsRelativeToScript) ? lookupFileArg(*state, baseDir) : state->rootPath(".") + (inShebang && compatibilitySettings.nixShellShebangArgumentsRelativeToScript) + ? lookupFileArg(*state, shebangBaseDir) + : state->rootPath(".") )); + } else { auto absolute = i; try { diff --git a/src/nix-store/nix-store.cc b/src/nix-store/nix-store.cc index b4de42ba1..c823c930e 100644 --- a/src/nix-store/nix-store.cc +++ b/src/nix-store/nix-store.cc @@ -694,7 +694,7 @@ static void opDump(Strings opFlags, Strings opArgs) if (!opFlags.empty()) throw UsageError("unknown flag"); if (opArgs.size() != 1) throw UsageError("only one argument allowed"); - FdSink sink(getStandardOut()); + FdSink sink(getStandardOutput()); std::string path = *opArgs.begin(); dumpPath(path, sink); sink.flush(); @@ -722,7 +722,7 @@ static void opExport(Strings opFlags, Strings opArgs) for (auto & i : opArgs) paths.insert(store->followLinksToStorePath(i)); - FdSink sink(getStandardOut()); + FdSink sink(getStandardOutput()); store->exportPaths(paths, sink); sink.flush(); } @@ -835,7 +835,7 @@ static void opServe(Strings opFlags, Strings opArgs) if (!opArgs.empty()) throw UsageError("no arguments expected"); FdSource in(STDIN_FILENO); - FdSink out(getStandardOut()); + FdSink out(getStandardOutput()); /* Exchange the greeting. */ ServeProto::Version clientVersion = diff --git a/src/nix/cat.cc b/src/nix/cat.cc index ee904b0c5..e0179c348 100644 --- a/src/nix/cat.cc +++ b/src/nix/cat.cc @@ -16,7 +16,7 @@ struct MixCat : virtual Args throw Error("path '%1%' is not a regular file", path); stopProgressBar(); - writeFull(getStandardOut(), accessor->readFile(CanonPath(path))); + writeFull(getStandardOutput(), accessor->readFile(CanonPath(path))); } }; diff --git a/src/nix/develop.cc b/src/nix/develop.cc index c7a733025..9a95bc695 100644 --- a/src/nix/develop.cc +++ b/src/nix/develop.cc @@ -610,6 +610,7 @@ struct CmdDevelop : Common, MixEnvironment else if (!command.empty()) { std::vector args; + args.reserve(command.size()); for (auto s : command) args.push_back(shellEscape(s)); script += fmt("exec %s\n", concatStringsSep(" ", args)); diff --git a/src/nix/dump-path.cc b/src/nix/dump-path.cc index 953d77d31..98a059fa1 100644 --- a/src/nix/dump-path.cc +++ b/src/nix/dump-path.cc @@ -20,7 +20,7 @@ struct CmdDumpPath : StorePathCommand void run(ref store, const StorePath & storePath) override { - FdSink sink(getStandardOut()); + FdSink sink(getStandardOutput()); store->narFromPath(storePath, sink); sink.flush(); } @@ -55,7 +55,7 @@ struct CmdDumpPath2 : Command void run() override { - FdSink sink(getStandardOut()); + FdSink sink(getStandardOutput()); dumpPath(path, sink); sink.flush(); } diff --git a/src/nix/eval.cc b/src/nix/eval.cc index babf2ca32..7811b77ed 100644 --- a/src/nix/eval.cc +++ b/src/nix/eval.cc @@ -115,7 +115,7 @@ struct CmdEval : MixJSON, InstallableValueCommand, MixReadOnlyOption else if (raw) { stopProgressBar(); - writeFull(getStandardOut(), *state->coerceToString(noPos, *v, context, "while generating the eval command output")); + writeFull(getStandardOutput(), *state->coerceToString(noPos, *v, context, "while generating the eval command output")); } else if (json) { diff --git a/src/nix/flake.cc b/src/nix/flake.cc index 640a80aed..ce2faacb0 100644 --- a/src/nix/flake.cc +++ b/src/nix/flake.cc @@ -17,7 +17,6 @@ #include "eval-cache.hh" #include "markdown.hh" #include "users.hh" -#include "terminal.hh" #include #include @@ -892,37 +891,32 @@ struct CmdFlakeInitCommon : virtual Args, EvalCommand auto cursor = installable.getCursor(*evalState); - auto templateDirAttr = cursor->getAttr("path"); - auto templateDir = templateDirAttr->getString(); - - if (!store->isInStore(templateDir)) - evalState->error( - "'%s' was not found in the Nix store\n" - "If you've set '%s' to a string, try using a path instead.", - templateDir, templateDirAttr->getAttrPathStr()).debugThrow(); + auto templateDirAttr = cursor->getAttr("path")->forceValue(); + NixStringContext context; + auto templateDir = evalState->coerceToPath(noPos, templateDirAttr, context, ""); std::vector changedFiles; std::vector conflictedFiles; - std::function copyDir; - copyDir = [&](const fs::path & from, const fs::path & to) + std::function copyDir; + copyDir = [&](const SourcePath & from, const fs::path & to) { fs::create_directories(to); - for (auto & entry : fs::directory_iterator{from}) { + for (auto & [name, entry] : from.readDirectory()) { checkInterrupt(); - auto from2 = entry.path(); - auto to2 = to / entry.path().filename(); - auto st = entry.symlink_status(); + auto from2 = from / name; + auto to2 = to / name; + auto st = from2.lstat(); auto to_st = fs::symlink_status(to2); - if (fs::is_directory(st)) + if (st.type == SourceAccessor::tDirectory) copyDir(from2, to2); - else if (fs::is_regular_file(st)) { - auto contents = readFile(from2.string()); + else if (st.type == SourceAccessor::tRegular) { + auto contents = from2.readFile(); if (fs::exists(to_st)) { auto contents2 = readFile(to2.string()); if (contents != contents2) { - printError("refusing to overwrite existing file '%s'\n please merge it manually with '%s'", to2.string(), from2.string()); + printError("refusing to overwrite existing file '%s'\n please merge it manually with '%s'", to2.string(), from2); conflictedFiles.push_back(to2); } else { notice("skipping identical file: %s", from2); @@ -931,18 +925,18 @@ struct CmdFlakeInitCommon : virtual Args, EvalCommand } else writeFile(to2, contents); } - else if (fs::is_symlink(st)) { - auto target = fs::read_symlink(from2); + else if (st.type == SourceAccessor::tSymlink) { + auto target = from2.readLink(); if (fs::exists(to_st)) { if (fs::read_symlink(to2) != target) { - printError("refusing to overwrite existing file '%s'\n please merge it manually with '%s'", to2.string(), from2.string()); + printError("refusing to overwrite existing file '%s'\n please merge it manually with '%s'", to2.string(), from2); conflictedFiles.push_back(to2); } else { notice("skipping identical file: %s", from2); } continue; } else - fs::create_symlink(target, to2); + fs::create_symlink(target, to2); } else throw Error("file '%s' has unsupported type", from2); @@ -958,14 +952,14 @@ struct CmdFlakeInitCommon : virtual Args, EvalCommand for (auto & s : changedFiles) args.emplace_back(s.string()); runProgram("git", true, args); } - auto welcomeText = cursor->maybeGetAttr("welcomeText"); - if (welcomeText) { + + if (auto welcomeText = cursor->maybeGetAttr("welcomeText")) { notice("\n"); notice(renderMarkdownToTerminal(welcomeText->getString())); } if (!conflictedFiles.empty()) - throw Error("Encountered %d conflicts - see above", conflictedFiles.size()); + throw Error("encountered %d conflicts - see above", conflictedFiles.size()); } }; @@ -1275,97 +1269,25 @@ struct CmdFlakeShow : FlakeCommand, MixJSON auto showDerivation = [&]() { auto name = visitor.getAttr(state->sName)->getString(); - std::optional description; - if (auto aMeta = visitor.maybeGetAttr(state->sMeta)) { - if (auto aDescription = aMeta->maybeGetAttr(state->sDescription)) - description = aDescription->getString(); - } if (json) { + std::optional description; + if (auto aMeta = visitor.maybeGetAttr(state->sMeta)) { + if (auto aDescription = aMeta->maybeGetAttr(state->sDescription)) + description = aDescription->getString(); + } j.emplace("type", "derivation"); j.emplace("name", name); j.emplace("description", description ? *description : ""); } else { - auto type = + logger->cout("%s: %s '%s'", + headerPrefix, attrPath.size() == 2 && attrPathS[0] == "devShell" ? "development environment" : attrPath.size() >= 2 && attrPathS[0] == "devShells" ? "development environment" : attrPath.size() == 3 && attrPathS[0] == "checks" ? "derivation" : attrPath.size() >= 1 && attrPathS[0] == "hydraJobs" ? "derivation" : - "package"; - if (description && !description->empty()) { - - // Takes a string and returns the # of characters displayed - auto columnLengthOfString = [](std::string_view s) -> unsigned int { - unsigned int columnCount = 0; - for (auto i = s.begin(); i < s.end();) { - // Test first character to determine if it is one of - // treeConn, treeLast, treeLine - if (*i == -30) { - i += 3; - ++columnCount; - } - // Escape sequences - // https://en.wikipedia.org/wiki/ANSI_escape_code - else if (*i == '\e') { - // Eat '[' - if (*(++i) == '[') { - ++i; - // Eat parameter bytes - while(*i >= 0x30 && *i <= 0x3f) ++i; - - // Eat intermediate bytes - while(*i >= 0x20 && *i <= 0x2f) ++i; - - // Eat final byte - if(*i >= 0x40 && *i <= 0x73) ++i; - } - else { - // Eat Fe Escape sequence - if (*i >= 0x40 && *i <= 0x5f) ++i; - } - } - else { - ++i; - ++columnCount; - } - } - - return columnCount; - }; - - // Maximum length to print - size_t maxLength = getWindowSize().second > 0 ? getWindowSize().second : 80; - - // Trim the description and only use the first line - auto trimmed = trim(*description); - auto newLinePos = trimmed.find('\n'); - auto length = newLinePos != std::string::npos ? newLinePos : trimmed.length(); - - auto beginningOfLine = fmt("%s: %s '%s'", headerPrefix, type, name); - auto line = fmt("%s: %s '%s' - '%s'", headerPrefix, type, name, trimmed.substr(0, length)); - - // If we are already over the maximum length then do not trim - // and don't print the description (preserves existing behavior) - if (columnLengthOfString(beginningOfLine) >= maxLength) { - logger->cout("%s", beginningOfLine); - } - // If the entire line fits then print that - else if (columnLengthOfString(line) < maxLength) { - logger->cout("%s", line); - } - // Otherwise we need to truncate - else { - auto lineLength = columnLengthOfString(line); - auto chopOff = lineLength - maxLength; - line.resize(line.length() - chopOff); - line = line.replace(line.length() - 3, 3, "..."); - - logger->cout("%s", line); - } - } - else { - logger->cout("%s: %s '%s'", headerPrefix, type, name); - } + "package", + name); } }; diff --git a/src/nix/flake.md b/src/nix/flake.md index 2b999431c..682ce9ce3 100644 --- a/src/nix/flake.md +++ b/src/nix/flake.md @@ -84,6 +84,8 @@ Here are some examples of flake references in their URL-like representation: repository on GitHub. * `github:NixOS/nixpkgs/nixos-20.09`: The `nixos-20.09` branch of the `nixpkgs` repository. +* `github:NixOS/nixpkgs/pull/357207/head`: The `357207` pull request + of the nixpkgs repository. * `github:NixOS/nixpkgs/a3a3dda3bacf61e8a39258a0ed9c924eeca8e293`: A specific revision of the `nixpkgs` repository. * `github:edolstra/nix-warez?dir=blender`: A flake in a subdirectory @@ -148,7 +150,7 @@ reference types: * `ref`: A Git or Mercurial branch or tag name. -Finally, some attribute are typically not specified by the user, but +Finally, some attributes are typically not specified by the user, but can occur in *locked* flake references and are available to Nix code: * `revCount`: The number of ancestors of the commit `rev`. @@ -666,6 +668,11 @@ following fields: other attributes are necessary because they provide information not stored in the store path. + The attributes in `locked` are considered "final", meaning that they are the only ones that are passed via the arguments of the `outputs` function of a flake. + For instance, if `locked` contains a `lastModified` attribute while the fetcher does not return a `lastModified` attribute, then the `lastModified` attribute will be passed to the `outputs` function. + Conversely, if `locked` does *not* contain a `lastModified` attribute while the fetcher *does* return a `lastModified` attribute, then no `lastModified` attribute will be passed. + If `locked` contains a `lastModifed` attribute and the fetcher returns a `lastModified` attribute, then they must have the same value. + * `flake`: A Boolean denoting whether this is a flake or non-flake dependency. Corresponds to the `flake` attribute in the `inputs` attribute in `flake.nix`. diff --git a/src/nix/fmt.md b/src/nix/fmt.md index a2afde61c..b4693eb65 100644 --- a/src/nix/fmt.md +++ b/src/nix/fmt.md @@ -22,13 +22,13 @@ With [nixpkgs-fmt](https://github.com/nix-community/nixpkgs-fmt): } ``` -With [nixfmt](https://github.com/serokell/nixfmt): +With [nixfmt](https://github.com/NixOS/nixfmt): ```nix # flake.nix { outputs = { nixpkgs, self }: { - formatter.x86_64-linux = nixpkgs.legacyPackages.x86_64-linux.nixfmt; + formatter.x86_64-linux = nixpkgs.legacyPackages.x86_64-linux.nixfmt-rfc-style; }; } ``` diff --git a/src/nix/local.mk b/src/nix/local.mk deleted file mode 100644 index b57f6b3e2..000000000 --- a/src/nix/local.mk +++ /dev/null @@ -1,59 +0,0 @@ -programs += nix - -nix_DIR := $(d) - -nix_SOURCES := \ - $(wildcard $(d)/*.cc) \ - $(wildcard src/nix-build/*.cc) \ - $(wildcard src/nix-env/*.cc) \ - $(wildcard src/nix-instantiate/*.cc) \ - $(wildcard src/nix-store/*.cc) - -ifdef HOST_UNIX -nix_SOURCES += \ - $(wildcard $(d)/unix/*.cc) \ - $(wildcard src/build-remote/*.cc) \ - $(wildcard src/nix-channel/*.cc) \ - $(wildcard src/nix-collect-garbage/*.cc) \ - $(wildcard src/nix-copy-closure/*.cc) \ - $(wildcard src/nix-daemon/*.cc) -endif - -INCLUDE_nix := -I $(d) -ifdef HOST_UNIX - INCLUDE_nix += -I $(d)/unix -endif - -nix_CXXFLAGS += $(INCLUDE_libutil) $(INCLUDE_libstore) $(INCLUDE_libfetchers) $(INCLUDE_libexpr) $(INCLUDE_libflake) $(INCLUDE_libmain) -I src/libcmd -I doc/manual $(INCLUDE_nix) - -nix_CXXFLAGS += -DNIX_BIN_DIR=\"$(NIX_ROOT)$(bindir)\" - -nix_LIBS = libexpr libmain libfetchers libflake libstore libutil libcmd - -nix_LDFLAGS = $(THREAD_LDFLAGS) $(SODIUM_LIBS) $(EDITLINE_LIBS) $(BOOST_LDFLAGS) $(LOWDOWN_LIBS) - -ifdef HOST_WINDOWS - # Increase the default reserved stack size to 65 MB so Nix doesn't run out of space - nix_LDFLAGS += -Wl,--stack,$(shell echo $$((65 * 1024 * 1024))) -endif - -$(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, \ - $(eval $(call install-symlink, nix, $(bindir)/$(name)))) -$(eval $(call install-symlink, $(bindir)/nix, $(libexecdir)/nix/build-remote)) - -src/nix-env/user-env.cc: src/nix-env/buildenv.nix.gen.hh - -$(d)/develop.cc: $(d)/get-env.sh.gen.hh - -src/nix-channel/nix-channel.cc: src/nix-channel/unpack-channel.nix.gen.hh - -$(d)/main.cc: \ - doc/manual/generate-manpage.nix.gen.hh \ - doc/manual/utils.nix.gen.hh doc/manual/generate-settings.nix.gen.hh \ - doc/manual/generate-store-info.nix.gen.hh \ - $(d)/help-stores.md.gen.hh - -$(d)/profile.cc: $(d)/profile.md - -$(d)/profile.md: $(d)/profiles.md.gen.hh diff --git a/src/nix/log.cc b/src/nix/log.cc index 7f590c708..1a6f48f5e 100644 --- a/src/nix/log.cc +++ b/src/nix/log.cc @@ -57,7 +57,7 @@ struct CmdLog : InstallableCommand if (!log) continue; stopProgressBar(); printInfo("got build log for '%s' from '%s'", installable->what(), logSub.getUri()); - writeFull(getStandardOut(), *log); + writeFull(getStandardOutput(), *log); return; } diff --git a/src/nix/main.cc b/src/nix/main.cc index eff2d60a4..b0e26e093 100644 --- a/src/nix/main.cc +++ b/src/nix/main.cc @@ -435,7 +435,8 @@ void mainWrapped(int argc, char * * argv) evalSettings.pureEval = false; EvalState state({}, openStore("dummy://"), fetchSettings, evalSettings); auto builtinsJson = nlohmann::json::object(); - for (auto & builtin : *state.baseEnv.values[0]->attrs()) { + for (auto & builtinPtr : state.getBuiltins().attrs()->lexicographicOrder(state.symbols)) { + auto & builtin = *builtinPtr; auto b = nlohmann::json::object(); if (!builtin.value->isPrimOp()) continue; auto primOp = builtin.value->primOp(); diff --git a/src/nix/meson.build b/src/nix/meson.build index 55089d821..60ee48035 100644 --- a/src/nix/meson.build +++ b/src/nix/meson.build @@ -35,6 +35,7 @@ subdir('build-utils-meson/subprojects') subdir('build-utils-meson/threads') subdir('build-utils-meson/export-all-symbols') +subdir('build-utils-meson/windows-version') configdata = configuration_data() @@ -229,6 +230,8 @@ foreach linkname : nix_symlinks t = custom_target( command: ['ln', '-sf', fs.name(this_exe), '@OUTPUT@'], output: linkname + executable_suffix, + # native doesn't allow dangling symlinks, but the target executable often doesn't exist at this time + env : { 'MSYS' : 'winsymlinks:lnk' }, # TODO(Ericson2314): Don't do this once we have the `meson.override_find_program` working) build_by_default: true ) @@ -247,6 +250,8 @@ install_symlink( custom_target( command: ['ln', '-sf', fs.name(this_exe), '@OUTPUT@'], output: 'build-remote' + executable_suffix, + # native doesn't allow dangling symlinks, but the target executable often doesn't exist at this time + env : { 'MSYS' : 'winsymlinks:lnk' }, # TODO(Ericson2314): Don't do this once we have the `meson.override_find_program` working) build_by_default: true ) diff --git a/src/nix/path-info.cc b/src/nix/path-info.cc index e7cfb6e7a..8e3d0406d 100644 --- a/src/nix/path-info.cc +++ b/src/nix/path-info.cc @@ -139,12 +139,12 @@ struct CmdPathInfo : StorePathsCommand, MixJSON Category category() override { return catSecondary; } - void printSize(uint64_t value) + void printSize(std::ostream & str, uint64_t value) { if (humanReadable) - std::cout << fmt("\t%s", renderSize(value, true)); + str << fmt("\t%s", renderSize(value, true)); else - std::cout << fmt("\t%11d", value); + str << fmt("\t%11d", value); } void run(ref store, StorePaths && storePaths) override @@ -154,11 +154,11 @@ struct CmdPathInfo : StorePathsCommand, MixJSON pathLen = std::max(pathLen, store->printStorePath(storePath).size()); if (json) { - std::cout << pathInfoToJSON( + logger->cout(pathInfoToJSON( *store, // FIXME: preserve order? StorePathSet(storePaths.begin(), storePaths.end()), - showClosureSize).dump(); + showClosureSize).dump()); } else { @@ -167,30 +167,32 @@ struct CmdPathInfo : StorePathsCommand, MixJSON auto info = store->queryPathInfo(storePath); auto storePathS = store->printStorePath(info->path); - std::cout << storePathS; + std::ostringstream str; + + str << storePathS; if (showSize || showClosureSize || showSigs) - std::cout << std::string(std::max(0, (int) pathLen - (int) storePathS.size()), ' '); + str << std::string(std::max(0, (int) pathLen - (int) storePathS.size()), ' '); if (showSize) - printSize(info->narSize); + printSize(str, info->narSize); if (showClosureSize) { StorePathSet closure; store->computeFSClosure(storePath, closure, false, false); - printSize(getStoreObjectsTotalSize(*store, closure)); + printSize(str, getStoreObjectsTotalSize(*store, closure)); } if (showSigs) { - std::cout << '\t'; + str << '\t'; Strings ss; if (info->ultimate) ss.push_back("ultimate"); if (info->ca) ss.push_back("ca:" + renderContentAddress(*info->ca)); for (auto & sig : info->sigs) ss.push_back(sig); - std::cout << concatStringsSep(" ", ss); + str << concatStringsSep(" ", ss); } - std::cout << std::endl; + logger->cout(str.str()); } } diff --git a/src/nix/sigs.cc b/src/nix/sigs.cc index 1e277cbbe..2afe4b267 100644 --- a/src/nix/sigs.cc +++ b/src/nix/sigs.cc @@ -177,7 +177,7 @@ struct CmdKeyGenerateSecret : Command throw UsageError("required argument '--key-name' is missing"); stopProgressBar(); - writeFull(getStandardOut(), SecretKey::generate(*keyName).to_string()); + writeFull(getStandardOutput(), SecretKey::generate(*keyName).to_string()); } }; @@ -199,7 +199,7 @@ struct CmdKeyConvertSecretToPublic : Command { SecretKey secretKey(drainFD(STDIN_FILENO)); stopProgressBar(); - writeFull(getStandardOut(), secretKey.toPublicKey().to_string()); + writeFull(getStandardOutput(), secretKey.toPublicKey().to_string()); } }; diff --git a/src/perl/package.nix b/src/perl/package.nix index fe617fd47..5ee0df13c 100644 --- a/src/perl/package.nix +++ b/src/perl/package.nix @@ -40,6 +40,10 @@ perl.pkgs.toPerlModule (mkMesonDerivation (finalAttrs: { buildInputs = [ nix-store + ] ++ finalAttrs.passthru.externalBuildInputs; + + # Hack for sake of the dev shell + passthru.externalBuildInputs = [ bzip2 libsodium ]; diff --git a/tests/functional/build-hook-ca-fixed.nix b/tests/functional/build-hook-ca-fixed.nix index 427ec2c31..0ce6d9b12 100644 --- a/tests/functional/build-hook-ca-fixed.nix +++ b/tests/functional/build-hook-ca-fixed.nix @@ -1,6 +1,6 @@ { busybox }: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; let diff --git a/tests/functional/build-hook.nix b/tests/functional/build-hook.nix index 1f0e17a3b..99a13aee4 100644 --- a/tests/functional/build-hook.nix +++ b/tests/functional/build-hook.nix @@ -1,6 +1,6 @@ { busybox, contentAddressed ? false }: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; let diff --git a/tests/functional/ca/config.nix b/tests/functional/ca/config.nix new file mode 100644 index 000000000..451fbae4f --- /dev/null +++ b/tests/functional/ca/config.nix @@ -0,0 +1,2 @@ +# Shim to get generated file +import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/ca/config.nix" diff --git a/tests/functional/ca/content-addressed.nix b/tests/functional/ca/content-addressed.nix index 411ebb86b..2559c562f 100644 --- a/tests/functional/ca/content-addressed.nix +++ b/tests/functional/ca/content-addressed.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/ca/config.nix"; +with import ./config.nix; let mkCADerivation = args: mkDerivation ({ __contentAddressed = true; diff --git a/tests/functional/ca/local.mk b/tests/functional/ca/local.mk deleted file mode 100644 index 7c2fcc451..000000000 --- a/tests/functional/ca/local.mk +++ /dev/null @@ -1,29 +0,0 @@ -ca-tests := \ - $(d)/build-with-garbage-path.sh \ - $(d)/build.sh \ - $(d)/build-cache.sh \ - $(d)/concurrent-builds.sh \ - $(d)/derivation-json.sh \ - $(d)/duplicate-realisation-in-closure.sh \ - $(d)/eval-store.sh \ - $(d)/gc.sh \ - $(d)/import-from-derivation.sh \ - $(d)/new-build-cmd.sh \ - $(d)/nix-copy.sh \ - $(d)/nix-run.sh \ - $(d)/nix-shell.sh \ - $(d)/post-hook.sh \ - $(d)/recursive.sh \ - $(d)/repl.sh \ - $(d)/selfref-gc.sh \ - $(d)/signatures.sh \ - $(d)/substitute.sh \ - $(d)/why-depends.sh - -install-tests-groups += ca - -clean-files += \ - $(d)/config.nix - -test-deps += \ - tests/functional/ca/config.nix diff --git a/tests/functional/ca/nix-run.sh b/tests/functional/ca/nix-run.sh index 21c09117e..e6638cc91 100755 --- a/tests/functional/ca/nix-run.sh +++ b/tests/functional/ca/nix-run.sh @@ -6,7 +6,4 @@ flakeDir="$TEST_HOME/flake" mkdir -p "${flakeDir}" cp flake.nix "${_NIX_TEST_BUILD_DIR}/ca/config.nix" content-addressed.nix "${flakeDir}" -# `config.nix` cannot be gotten via build dir / env var (runs afoul pure eval). Instead get from flake. -removeBuildDirRef "$flakeDir"/*.nix - nix run --no-write-lock-file "path:${flakeDir}#runnable" diff --git a/tests/functional/ca/nondeterministic.nix b/tests/functional/ca/nondeterministic.nix index 740be4bd2..d6d099a3e 100644 --- a/tests/functional/ca/nondeterministic.nix +++ b/tests/functional/ca/nondeterministic.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/ca/config.nix"; +with import ./config.nix; let mkCADerivation = args: mkDerivation ({ __contentAddressed = true; diff --git a/tests/functional/ca/racy.nix b/tests/functional/ca/racy.nix index cadd98675..555a15484 100644 --- a/tests/functional/ca/racy.nix +++ b/tests/functional/ca/racy.nix @@ -2,7 +2,7 @@ # build it at once. -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/ca/config.nix"; +with import ./config.nix; mkDerivation { name = "simple"; diff --git a/tests/functional/check-refs.nix b/tests/functional/check-refs.nix index 54957f635..89690e456 100644 --- a/tests/functional/check-refs.nix +++ b/tests/functional/check-refs.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { diff --git a/tests/functional/check-reqs.nix b/tests/functional/check-reqs.nix index 4e059f5a4..41436cb48 100644 --- a/tests/functional/check-reqs.nix +++ b/tests/functional/check-reqs.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { dep1 = mkDerivation { diff --git a/tests/functional/check.nix b/tests/functional/check.nix index 13638eae8..ddab8eea9 100644 --- a/tests/functional/check.nix +++ b/tests/functional/check.nix @@ -1,6 +1,6 @@ {checkBuildId ? 0}: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; { nondeterministic = mkDerivation { diff --git a/tests/functional/chroot-store.sh b/tests/functional/chroot-store.sh index 8c2a969d3..46e91f0aa 100755 --- a/tests/functional/chroot-store.sh +++ b/tests/functional/chroot-store.sh @@ -39,9 +39,6 @@ EOF cp simple.nix shell.nix simple.builder.sh "${config_nix}" "$flakeDir/" - # `config.nix` cannot be gotten via build dir / env var (runs afoul pure eval). Instead get from flake. - removeBuildDirRef "$flakeDir"/*.nix - TODO_NixOS outPath=$(nix build --print-out-paths --no-link --sandbox-paths '/nix? /bin? /lib? /lib64? /usr?' --store "$TEST_ROOT/x" path:"$flakeDir") diff --git a/tests/functional/common/functions.sh b/tests/functional/common/functions.sh index 286bb58e8..7195149cb 100644 --- a/tests/functional/common/functions.sh +++ b/tests/functional/common/functions.sh @@ -343,15 +343,6 @@ count() { echo $# } -# Sometimes, e.g. due to pure eval, restricted eval, or sandboxing, we -# cannot look up `config.nix` in the build dir, and have to instead get -# it from the current directory. (In this case, the current directly -# will be somewhere in `$TEST_ROOT`.) -removeBuildDirRef() { - # shellcheck disable=SC2016 # The ${} in this is Nix, not shell - sed -i -e 's,"${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/[^ ]*config.nix",./config.nix,' "$@" -} - trap onError ERR fi # COMMON_FUNCTIONS_SH_SOURCED diff --git a/tests/functional/common/init.sh b/tests/functional/common/init.sh index d849c0734..66b44c76f 100755 --- a/tests/functional/common/init.sh +++ b/tests/functional/common/init.sh @@ -19,7 +19,7 @@ EOF # When we're doing everything in the same store, we need to bring # dependencies into context. - sed -i "$(dirname "${BASH_SOURCE[0]}")"/../config.nix \ + sed -i "${_NIX_TEST_BUILD_DIR}/config.nix" \ -e 's^\(shell\) = "/nix/store/\([^/]*\)/\(.*\)";^\1 = builtins.appendContext "/nix/store/\2" { "/nix/store/\2".path = true; } + "/\3";^' \ -e 's^\(path\) = "/nix/store/\([^/]*\)/\(.*\)";^\1 = builtins.appendContext "/nix/store/\2" { "/nix/store/\2".path = true; } + "/\3";^' \ ; diff --git a/tests/functional/common/subst-vars.sh.in b/tests/functional/common/subst-vars.sh.in index 6ad22fa70..df140dec1 100644 --- a/tests/functional/common/subst-vars.sh.in +++ b/tests/functional/common/subst-vars.sh.in @@ -1,4 +1,4 @@ -# NOTE: instances of @variable@ are substituted as defined in /mk/templates.mk +# NOTE: instances of @variable@ are substituted by the build system if [[ -z "${COMMON_SUBST_VARS_SH_SOURCED-}" ]]; then diff --git a/tests/functional/config.nix b/tests/functional/config.nix new file mode 100644 index 000000000..5d1cb74ec --- /dev/null +++ b/tests/functional/config.nix @@ -0,0 +1,2 @@ +# Shim to get generated file +import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix" diff --git a/tests/functional/dependencies.nix b/tests/functional/dependencies.nix index db06321da..be1a7ae9a 100644 --- a/tests/functional/dependencies.nix +++ b/tests/functional/dependencies.nix @@ -1,5 +1,5 @@ { hashInvalidator ? "" }: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; let { diff --git a/tests/functional/dyn-drv/config.nix b/tests/functional/dyn-drv/config.nix new file mode 100644 index 000000000..8ec2c67ea --- /dev/null +++ b/tests/functional/dyn-drv/config.nix @@ -0,0 +1,2 @@ +# Shim to get generated file +import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/dyn-drv/config.nix" diff --git a/tests/functional/dyn-drv/local.mk b/tests/functional/dyn-drv/local.mk deleted file mode 100644 index c87534944..000000000 --- a/tests/functional/dyn-drv/local.mk +++ /dev/null @@ -1,15 +0,0 @@ -dyn-drv-tests := \ - $(d)/text-hashed-output.sh \ - $(d)/recursive-mod-json.sh \ - $(d)/build-built-drv.sh \ - $(d)/eval-outputOf.sh \ - $(d)/dep-built-drv.sh \ - $(d)/old-daemon-error-hack.sh - -install-tests-groups += dyn-drv - -clean-files += \ - $(d)/config.nix - -test-deps += \ - tests/functional/dyn-drv/config.nix diff --git a/tests/functional/dyn-drv/old-daemon-error-hack.nix b/tests/functional/dyn-drv/old-daemon-error-hack.nix index 7d3ccf7e4..c9d4a62d4 100644 --- a/tests/functional/dyn-drv/old-daemon-error-hack.nix +++ b/tests/functional/dyn-drv/old-daemon-error-hack.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/dyn-drv/config.nix"; +with import ./config.nix; # A simple content-addressed derivation. # The derivation can be arbitrarily modified by passing a different `seed`, diff --git a/tests/functional/dyn-drv/recursive-mod-json.nix b/tests/functional/dyn-drv/recursive-mod-json.nix index 0e778aa7f..c6a24ca4f 100644 --- a/tests/functional/dyn-drv/recursive-mod-json.nix +++ b/tests/functional/dyn-drv/recursive-mod-json.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/dyn-drv/config.nix"; +with import ./config.nix; let innerName = "foo"; in diff --git a/tests/functional/dyn-drv/text-hashed-output.nix b/tests/functional/dyn-drv/text-hashed-output.nix index aa46fff61..99203b518 100644 --- a/tests/functional/dyn-drv/text-hashed-output.nix +++ b/tests/functional/dyn-drv/text-hashed-output.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/dyn-drv/config.nix"; +with import ./config.nix; # A simple content-addressed derivation. # The derivation can be arbitrarily modified by passing a different `seed`, diff --git a/tests/functional/export-graph.nix b/tests/functional/export-graph.nix index 97ffe73a9..64fe36bd1 100644 --- a/tests/functional/export-graph.nix +++ b/tests/functional/export-graph.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { diff --git a/tests/functional/extra-sandbox-profile.nix b/tests/functional/extra-sandbox-profile.nix index 5f0e4753f..aa680b918 100644 --- a/tests/functional/extra-sandbox-profile.nix +++ b/tests/functional/extra-sandbox-profile.nix @@ -1,6 +1,6 @@ { destFile, seed }: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; mkDerivation { name = "simple"; diff --git a/tests/functional/failing.nix b/tests/functional/failing.nix index 8b7990679..d25e2d6b6 100644 --- a/tests/functional/failing.nix +++ b/tests/functional/failing.nix @@ -1,5 +1,5 @@ { busybox }: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; let mkDerivation = args: diff --git a/tests/functional/filter-source.nix b/tests/functional/filter-source.nix index dcef9c4e2..907163639 100644 --- a/tests/functional/filter-source.nix +++ b/tests/functional/filter-source.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; mkDerivation { name = "filter"; diff --git a/tests/functional/fixed.nix b/tests/functional/fixed.nix index f70b89091..a920a2167 100644 --- a/tests/functional/fixed.nix +++ b/tests/functional/fixed.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { diff --git a/tests/functional/flakes/bundle.sh b/tests/functional/flakes/bundle.sh index 61aa040e7..2946aea35 100755 --- a/tests/functional/flakes/bundle.sh +++ b/tests/functional/flakes/bundle.sh @@ -4,9 +4,6 @@ source common.sh cp ../simple.nix ../simple.builder.sh "${config_nix}" "$TEST_HOME" -# `config.nix` cannot be gotten via build dir / env var (runs afoul pure eval). Instead get from flake. -removeBuildDirRef "$TEST_HOME"/*.nix - cd "$TEST_HOME" cat < flake.nix diff --git a/tests/functional/flakes/common.sh b/tests/functional/flakes/common.sh index 8af72f2ad..cc9b2e466 100644 --- a/tests/functional/flakes/common.sh +++ b/tests/functional/flakes/common.sh @@ -35,9 +35,6 @@ writeSimpleFlake() { EOF cp ../simple.nix ../shell.nix ../simple.builder.sh "${config_nix}" "$flakeDir/" - - # `config.nix` cannot be gotten via build dir / env var (runs afoul pure eval). Instead get from flake. - removeBuildDirRef "$flakeDir"/*.nix } createSimpleGitFlake() { diff --git a/tests/functional/flakes/config.sh b/tests/functional/flakes/config.sh index 256a595bc..ab2d9f47c 100755 --- a/tests/functional/flakes/config.sh +++ b/tests/functional/flakes/config.sh @@ -3,7 +3,6 @@ source common.sh cp ../simple.nix ../simple.builder.sh "${config_nix}" $TEST_HOME -removeBuildDirRef "$TEST_HOME/simple.nix" cd $TEST_HOME @@ -27,7 +26,17 @@ cat < flake.nix EOF # Without --accept-flake-config, the post hook should not run. +# To test variations in stderr tty-ness, we run the command in different ways, +# none of which should block on stdin or accept the `nixConfig`s. nix build < /dev/null +nix build < /dev/null 2>&1 | cat +# EOF counts as no, even when interactive (throw EOF error before) +if type -p script >/dev/null && script -q -c true /dev/null; then + echo "script is available and GNU-like, so we can ensure a tty" + script -q -c 'nix build < /dev/null' /dev/null +else + echo "script is not available or not GNU-like, so we skip testing with an added tty" +fi (! [[ -f post-hook-ran ]]) TODO_NixOS clearStore diff --git a/tests/functional/flakes/develop.sh b/tests/functional/flakes/develop.sh index 2e75081d4..c222f0fbb 100755 --- a/tests/functional/flakes/develop.sh +++ b/tests/functional/flakes/develop.sh @@ -27,9 +27,6 @@ EOF mkdir -p "$TEST_HOME/nixpkgs" cp "${config_nix}" ../shell.nix "$TEST_HOME/nixpkgs" -# `config.nix` cannot be gotten via build dir / env var (runs afoul pure eval). Instead get from flake. -removeBuildDirRef "$TEST_HOME/nixpkgs"/*.nix - cat <"$TEST_HOME/nixpkgs/flake.nix" { outputs = {self}: { @@ -125,7 +122,7 @@ expectStderr 1 nix develop --unset-env-var FOO --set-env-var FOO 'BAR' --no-writ grepQuiet "error: Cannot set environment variable 'FOO' that is unset with '--unset-env-var'" # Check that multiple `--ignore-env`'s are okay. -expectStderr 0 nix develop --ignore-env --set-env-var FOO 'BAR' --ignore-env .#hello +expectStderr 0 nix develop --ignore-env --set-env-var FOO 'BAR' --ignore-env .#hello < /dev/null # Determine the bashInteractive executable. nix build --no-write-lock-file './nixpkgs#bashInteractive' --out-link ./bash-interactive diff --git a/tests/functional/flakes/local.mk b/tests/functional/flakes/local.mk deleted file mode 100644 index a37840240..000000000 --- a/tests/functional/flakes/local.mk +++ /dev/null @@ -1,25 +0,0 @@ -flake-tests := \ - $(d)/flakes.sh \ - $(d)/develop.sh \ - $(d)/edit.sh \ - $(d)/run.sh \ - $(d)/mercurial.sh \ - $(d)/circular.sh \ - $(d)/init.sh \ - $(d)/inputs.sh \ - $(d)/follow-paths.sh \ - $(d)/bundle.sh \ - $(d)/check.sh \ - $(d)/unlocked-override.sh \ - $(d)/absolute-paths.sh \ - $(d)/absolute-attr-paths.sh \ - $(d)/build-paths.sh \ - $(d)/flake-in-submodule.sh \ - $(d)/prefetch.sh \ - $(d)/eval-cache.sh \ - $(d)/search-root.sh \ - $(d)/config.sh \ - $(d)/show.sh \ - $(d)/dubious-query.sh - -install-tests-groups += flake diff --git a/tests/functional/flakes/run.sh b/tests/functional/flakes/run.sh index 2077c965b..c92ddca2b 100755 --- a/tests/functional/flakes/run.sh +++ b/tests/functional/flakes/run.sh @@ -8,8 +8,6 @@ clearStore rm -rf $TEST_HOME/.cache $TEST_HOME/.config $TEST_HOME/.local cp ../shell-hello.nix "${config_nix}" $TEST_HOME -# `config.nix` cannot be gotten via build dir / env var (runs afoul pure eval). Instead get from flake. -removeBuildDirRef "$TEST_HOME"/*.nix cd $TEST_HOME cat < flake.nix diff --git a/tests/functional/flakes/show.sh b/tests/functional/flakes/show.sh index 0edc450c3..22e1f4193 100755 --- a/tests/functional/flakes/show.sh +++ b/tests/functional/flakes/show.sh @@ -87,28 +87,3 @@ assert show_output.legacyPackages.${builtins.currentSystem}.AAAAAASomeThingsFail assert show_output.legacyPackages.${builtins.currentSystem}.simple.name == "simple"; true ' - -cat >flake.nix< ./show-output.txt -test "$(awk -F '[:] ' '/aNoDescription/{print $NF}' ./show-output.txt)" = "package 'simple'" -test "$(awk -F '[:] ' '/bOneLineDescription/{print $NF}' ./show-output.txt)" = "package 'simple' - 'one line'" -test "$(awk -F '[:] ' '/cMultiLineDescription/{print $NF}' ./show-output.txt)" = "package 'simple' - 'line one'" -test "$(awk -F '[:] ' '/dLongDescription/{print $NF}' ./show-output.txt)" = "package 'simple' - '012345678901234567890123456..." -test "$(awk -F '[:] ' '/eEmptyDescription/{print $NF}' ./show-output.txt)" = "package 'simple'" \ No newline at end of file diff --git a/tests/functional/fod-failing.nix b/tests/functional/fod-failing.nix index 7881a3fbf..37c04fe12 100644 --- a/tests/functional/fod-failing.nix +++ b/tests/functional/fod-failing.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { x1 = mkDerivation { name = "x1"; diff --git a/tests/functional/gc-concurrent.nix b/tests/functional/gc-concurrent.nix index a5c3c97c3..0aba1f983 100644 --- a/tests/functional/gc-concurrent.nix +++ b/tests/functional/gc-concurrent.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; { lockFifo ? null }: diff --git a/tests/functional/gc-runtime.nix b/tests/functional/gc-runtime.nix index 2603fafdf..ee5980bdf 100644 --- a/tests/functional/gc-runtime.nix +++ b/tests/functional/gc-runtime.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; mkDerivation { name = "gc-runtime"; diff --git a/tests/functional/git-hashing/local.mk b/tests/functional/git-hashing/local.mk deleted file mode 100644 index ebec01940..000000000 --- a/tests/functional/git-hashing/local.mk +++ /dev/null @@ -1,7 +0,0 @@ -git-hashing-tests := \ - $(d)/simple.sh - -install-tests-groups += git-hashing - -clean-files += \ - $(d)/config.nix diff --git a/tests/functional/hermetic.nix b/tests/functional/hermetic.nix index dafe8ad9f..d1dccdff3 100644 --- a/tests/functional/hermetic.nix +++ b/tests/functional/hermetic.nix @@ -5,7 +5,7 @@ , withFinalRefs ? false }: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; let contentAddressedByDefault = builtins.getEnv "NIX_TESTS_CA_BY_DEFAULT" == "1"; diff --git a/tests/functional/ifd.nix b/tests/functional/ifd.nix index c84ffbc66..d0b9b54ad 100644 --- a/tests/functional/ifd.nix +++ b/tests/functional/ifd.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; import ( mkDerivation { name = "foo"; diff --git a/tests/functional/import-from-derivation.nix b/tests/functional/import-from-derivation.nix index 8864fb30a..cc53451cf 100644 --- a/tests/functional/import-from-derivation.nix +++ b/tests/functional/import-from-derivation.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { bar = mkDerivation { diff --git a/tests/functional/impure-derivations.nix b/tests/functional/impure-derivations.nix index 04710323f..98547e6c1 100644 --- a/tests/functional/impure-derivations.nix +++ b/tests/functional/impure-derivations.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { diff --git a/tests/functional/impure-env.nix b/tests/functional/impure-env.nix index 6b9e5a825..2b0380ed7 100644 --- a/tests/functional/impure-env.nix +++ b/tests/functional/impure-env.nix @@ -1,6 +1,6 @@ { var, value }: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; mkDerivation { name = "test"; diff --git a/tests/functional/linux-sandbox-cert-test.nix b/tests/functional/linux-sandbox-cert-test.nix index e506b6a0f..2fc083ea9 100644 --- a/tests/functional/linux-sandbox-cert-test.nix +++ b/tests/functional/linux-sandbox-cert-test.nix @@ -1,6 +1,6 @@ { mode }: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; mkDerivation ( { diff --git a/tests/functional/local-overlay-store/local.mk b/tests/functional/local-overlay-store/local.mk deleted file mode 100644 index 6348a4423..000000000 --- a/tests/functional/local-overlay-store/local.mk +++ /dev/null @@ -1,14 +0,0 @@ -local-overlay-store-tests := \ - $(d)/check-post-init.sh \ - $(d)/redundant-add.sh \ - $(d)/build.sh \ - $(d)/bad-uris.sh \ - $(d)/add-lower.sh \ - $(d)/delete-refs.sh \ - $(d)/delete-duplicate.sh \ - $(d)/gc.sh \ - $(d)/verify.sh \ - $(d)/optimise.sh \ - $(d)/stale-file-handle.sh - -install-tests-groups += local-overlay-store diff --git a/tests/functional/local.mk b/tests/functional/local.mk deleted file mode 100644 index e50b5eaf1..000000000 --- a/tests/functional/local.mk +++ /dev/null @@ -1,146 +0,0 @@ -nix_tests = \ - test-infra.sh \ - gc.sh \ - nix-collect-garbage-d.sh \ - remote-store.sh \ - legacy-ssh-store.sh \ - lang.sh \ - lang-gc.sh \ - characterisation-test-infra.sh \ - experimental-features.sh \ - fetchMercurial.sh \ - gc-auto.sh \ - user-envs.sh \ - user-envs-migration.sh \ - binary-cache.sh \ - multiple-outputs.sh \ - nix-build.sh \ - gc-concurrent.sh \ - repair.sh \ - fixed.sh \ - export-graph.sh \ - timeout.sh \ - fetchGitRefs.sh \ - gc-runtime.sh \ - tarball.sh \ - fetchGit.sh \ - fetchurl.sh \ - fetchPath.sh \ - fetchTree-file.sh \ - simple.sh \ - referrers.sh \ - optimise-store.sh \ - substitute-with-invalid-ca.sh \ - signing.sh \ - hash-convert.sh \ - hash-path.sh \ - gc-non-blocking.sh \ - check.sh \ - nix-shell.sh \ - check-refs.sh \ - build-remote-input-addressed.sh \ - secure-drv-outputs.sh \ - restricted.sh \ - fetchGitSubmodules.sh \ - fetchGitVerification.sh \ - readfile-context.sh \ - nix-channel.sh \ - recursive.sh \ - dependencies.sh \ - check-reqs.sh \ - build-remote-content-addressed-fixed.sh \ - build-remote-content-addressed-floating.sh \ - build-remote-trustless-should-pass-0.sh \ - build-remote-trustless-should-pass-1.sh \ - build-remote-trustless-should-pass-2.sh \ - build-remote-trustless-should-pass-3.sh \ - build-remote-trustless-should-fail-0.sh \ - build-remote-with-mounted-ssh-ng.sh \ - nar-access.sh \ - impure-eval.sh \ - pure-eval.sh \ - eval.sh \ - repl.sh \ - binary-cache-build-remote.sh \ - search.sh \ - logging.sh \ - export.sh \ - config.sh \ - add.sh \ - chroot-store.sh \ - filter-source.sh \ - misc.sh \ - dump-db.sh \ - linux-sandbox.sh \ - supplementary-groups.sh \ - build-dry.sh \ - structured-attrs.sh \ - shell.sh \ - brotli.sh \ - zstd.sh \ - compression-levels.sh \ - nix-copy-ssh.sh \ - nix-copy-ssh-ng.sh \ - post-hook.sh \ - function-trace.sh \ - fmt.sh \ - eval-store.sh \ - why-depends.sh \ - derivation-json.sh \ - derivation-advanced-attributes.sh \ - import-from-derivation.sh \ - nix_path.sh \ - nars.sh \ - placeholders.sh \ - ssh-relay.sh \ - build.sh \ - build-delete.sh \ - output-normalization.sh \ - selfref-gc.sh \ - db-migration.sh \ - bash-profile.sh \ - pass-as-file.sh \ - nix-profile.sh \ - suggestions.sh \ - store-info.sh \ - fetchClosure.sh \ - completions.sh \ - impure-derivations.sh \ - path-from-hash-part.sh \ - path-info.sh \ - toString-path.sh \ - read-only-store.sh \ - nested-sandboxing.sh \ - impure-env.sh \ - debugger.sh \ - extra-sandbox-profile.sh \ - -ifeq ($(HAVE_LIBCPUID), 1) - nix_tests += compute-levels.sh -endif - -ifeq ($(ENABLE_BUILD), yes) - nix_tests += test-libstoreconsumer.sh - - ifeq ($(BUILD_SHARED_LIBS), 1) - nix_tests += plugins.sh - endif -endif - -ifeq ($(ENABLE_DOC_GEN), yes) - nix_tests += help.sh -endif - -$(d)/test-libstoreconsumer.sh.test $(d)/test-libstoreconsumer.sh.test-debug: \ - $(buildprefix)$(d)/test-libstoreconsumer/test-libstoreconsumer -$(d)/plugins.sh.test $(d)/plugins.sh.test-debug: \ - $(buildprefix)$(d)/plugins/libplugintest.$(SO_EXT) - -install-tests += $(foreach x, $(nix_tests), $(d)/$(x)) - -test-clean-files := \ - $(d)/common/subst-vars.sh \ - $(d)/config.nix - -clean-files += $(test-clean-files) -test-deps += $(test-clean-files) diff --git a/tests/functional/meson.build b/tests/functional/meson.build index b3ac1560c..0d46f9ce2 100644 --- a/tests/functional/meson.build +++ b/tests/functional/meson.build @@ -1,4 +1,4 @@ -project('nix-functional-tests', 'cpp', +project('nix-functional-tests', version : files('.version'), default_options : [ 'cpp_std=c++2a', @@ -17,7 +17,12 @@ fs = import('fs') nix = find_program('nix') bash = find_program('bash', native : true) busybox = find_program('busybox', native : true, required : false) -coreutils = find_program('coreutils', native : true) +if host_machine.system() == 'windows' + # Because of the state of symlinks on Windows, coreutils.exe doesn't usually exist, but things like ls.exe will + coreutils = find_program('ls', native : true) +else + coreutils = find_program('coreutils', native : true) +endif dot = find_program('dot', native : true, required : false) nix_bin_dir = fs.parent(nix.full_path()) @@ -170,6 +175,7 @@ suites = [ nix_store = dependency('nix-store', required : false) if nix_store.found() + add_languages('cpp') subdir('test-libstoreconsumer') suites += { 'name': 'libstoreconsumer', @@ -187,6 +193,7 @@ endif # Plugin tests require shared libraries support. nix_expr = dependency('nix-expr', required : false) if nix_expr.found() and get_option('default_library') != 'static' + add_languages('cpp') subdir('plugins') suites += { 'name': 'plugins', diff --git a/tests/functional/multiple-outputs.nix b/tests/functional/multiple-outputs.nix index 19ae2a45d..6ba7c523d 100644 --- a/tests/functional/multiple-outputs.nix +++ b/tests/functional/multiple-outputs.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { diff --git a/tests/functional/nar-access.nix b/tests/functional/nar-access.nix index 78972bd36..9948abe59 100644 --- a/tests/functional/nar-access.nix +++ b/tests/functional/nar-access.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { a = mkDerivation { diff --git a/tests/functional/nix-build-examples.nix b/tests/functional/nix-build-examples.nix index aaea8fc07..e54dbbf62 100644 --- a/tests/functional/nix-build-examples.nix +++ b/tests/functional/nix-build-examples.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { diff --git a/tests/functional/nix-shell.sh b/tests/functional/nix-shell.sh index 2b78216f4..b054b7f75 100755 --- a/tests/functional/nix-shell.sh +++ b/tests/functional/nix-shell.sh @@ -167,6 +167,35 @@ EOF chmod a+x $TEST_ROOT/marco/polo/default.nix (cd $TEST_ROOT/marco && ./polo/default.nix | grepQuiet "Polo") +# https://github.com/NixOS/nix/issues/11892 +mkdir $TEST_ROOT/issue-11892 +cat >$TEST_ROOT/issue-11892/shebangscript <$TEST_ROOT/issue-11892/my_package.nix < \$out/bin/my_package + cat \$out/bin/my_package + chmod a+x \$out/bin/my_package + ''; +} +EOF +chmod a+x $TEST_ROOT/issue-11892/shebangscript +$TEST_ROOT/issue-11892/shebangscript \ + | tee /dev/stderr \ + | grepQuiet "ok baz11892" + ##################### # Flake equivalents # diff --git a/tests/functional/package.nix b/tests/functional/package.nix index 9cf6b62e1..d1582b05d 100644 --- a/tests/functional/package.nix +++ b/tests/functional/package.nix @@ -1,7 +1,6 @@ { lib , stdenv , mkMesonDerivation -, releaseTools , meson , ninja @@ -16,14 +15,11 @@ , nix-expr , nix-cli -, rapidcheck -, gtest -, runCommand - , busybox-sandbox-shell ? null # Configuration Options +, pname ? "nix-functional-tests" , version # For running the functional tests against a different pre-built Nix. @@ -35,8 +31,7 @@ let in mkMesonDerivation (finalAttrs: { - pname = "nix-functional-tests"; - inherit version; + inherit pname version; workDir = ./.; fileset = fileset.unions [ @@ -60,6 +55,7 @@ mkMesonDerivation (finalAttrs: { # etc. busybox-sandbox-shell # For Overlay FS tests need `mount`, `umount`, and `unshare`. + # For `script` command (ensuring a TTY) # TODO use `unixtools` to be precise over which executables instead? util-linux ]; diff --git a/tests/functional/parallel.nix b/tests/functional/parallel.nix index 1f2411c92..23f142059 100644 --- a/tests/functional/parallel.nix +++ b/tests/functional/parallel.nix @@ -1,6 +1,6 @@ {sleepTime ? 3}: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; let diff --git a/tests/functional/path.nix b/tests/functional/path.nix index b23300f90..883c3c41b 100644 --- a/tests/functional/path.nix +++ b/tests/functional/path.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; mkDerivation { name = "filter"; diff --git a/tests/functional/plugins/local.mk b/tests/functional/plugins/local.mk deleted file mode 100644 index 2314e1341..000000000 --- a/tests/functional/plugins/local.mk +++ /dev/null @@ -1,11 +0,0 @@ -libraries += libplugintest - -libplugintest_DIR := $(d) - -libplugintest_SOURCES := $(d)/plugintest.cc - -libplugintest_ALLOW_UNDEFINED := 1 - -libplugintest_EXCLUDE_FROM_LIBRARY_LIST := 1 - -libplugintest_CXXFLAGS := $(INCLUDE_libutil) $(INCLUDE_libstore) $(INCLUDE_libexpr) $(INCLUDE_libfetchers) diff --git a/tests/functional/readfile-context.nix b/tests/functional/readfile-context.nix index b8f4a4c27..54cd1afd9 100644 --- a/tests/functional/readfile-context.nix +++ b/tests/functional/readfile-context.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; let diff --git a/tests/functional/restricted.sh b/tests/functional/restricted.sh index 63bf56cd7..a92a9b8a3 100755 --- a/tests/functional/restricted.sh +++ b/tests/functional/restricted.sh @@ -12,10 +12,6 @@ mkdir -p "$TEST_ROOT/nix" cp ./simple.nix "$TEST_ROOT/nix" cp ./simple.builder.sh "$TEST_ROOT/nix" cp "${config_nix}" "$TEST_ROOT/nix" -simple_nix="$TEST_ROOT/nix/simple.nix" -# N.B. redefine -config_nix="$TEST_ROOT/nix/config.nix" -removeBuildDirRef "${simple_nix}" cd "$TEST_ROOT/nix" nix-instantiate --restrict-eval ./simple.nix -I src=. @@ -27,7 +23,7 @@ nix-instantiate --restrict-eval ./simple.nix -I src1=./simple.nix -I src2=./conf (! nix-instantiate --restrict-eval --eval -E 'builtins.readFile ./simple.nix') nix-instantiate --restrict-eval --eval -E 'builtins.readFile ./simple.nix' -I src=../.. -expectStderr 1 nix-instantiate --restrict-eval --eval -E 'let __nixPath = [ { prefix = "foo"; path = ./.; } ]; in builtins.readFile ' | grepQuiet "forbidden in restricted mode" +expectStderr 1 nix-instantiate --restrict-eval --eval -E 'let __nixPath = [ { prefix = "foo"; path = ./.; } ]; in builtins.readFile ' | grepQuiet "was not found in the Nix search path" nix-instantiate --restrict-eval --eval -E 'let __nixPath = [ { prefix = "foo"; path = ./.; } ]; in builtins.readFile ' -I src=. p=$(nix eval --raw --expr "builtins.fetchurl file://${_NIX_TEST_SOURCE_DIR}/restricted.sh" --impure --restrict-eval --allowed-uris "file://${_NIX_TEST_SOURCE_DIR}") diff --git a/tests/functional/search.nix b/tests/functional/search.nix index 3c3564bda..fea6e7a7a 100644 --- a/tests/functional/search.nix +++ b/tests/functional/search.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; { hello = mkDerivation rec { diff --git a/tests/functional/secure-drv-outputs.nix b/tests/functional/secure-drv-outputs.nix index cd111c315..b4ac8ff53 100644 --- a/tests/functional/secure-drv-outputs.nix +++ b/tests/functional/secure-drv-outputs.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; { diff --git a/tests/functional/shell-hello.nix b/tests/functional/shell-hello.nix index fa02e2bb4..c920d7cb4 100644 --- a/tests/functional/shell-hello.nix +++ b/tests/functional/shell-hello.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; rec { hello = mkDerivation { diff --git a/tests/functional/shell.nix b/tests/functional/shell.nix index f6622a487..4b1a0623a 100644 --- a/tests/functional/shell.nix +++ b/tests/functional/shell.nix @@ -1,6 +1,6 @@ { inNixShell ? false, contentAddressed ? false, fooContents ? "foo" }: -let cfg = import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; in +let cfg = import ./config.nix; in with cfg; let @@ -37,7 +37,7 @@ let pkgs = rec { mkdir -p $out ln -s ${setupSh} $out/setup ''; - }; + } // { inherit mkDerivation; }; shellDrv = mkDerivation { name = "shellDrv"; @@ -94,5 +94,9 @@ let pkgs = rec { chmod a+rx $out/bin/ruby ''; + inherit (cfg) shell; + + callPackage = f: args: f (pkgs // args); + inherit pkgs; }; in pkgs diff --git a/tests/functional/simple-failing.nix b/tests/functional/simple-failing.nix index 228971734..d176c9c51 100644 --- a/tests/functional/simple-failing.nix +++ b/tests/functional/simple-failing.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; mkDerivation { name = "simple-failing"; diff --git a/tests/functional/simple.nix b/tests/functional/simple.nix index 96237695c..2035ca294 100644 --- a/tests/functional/simple.nix +++ b/tests/functional/simple.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; mkDerivation { name = "simple"; diff --git a/tests/functional/structured-attrs-shell.nix b/tests/functional/structured-attrs-shell.nix index 7ed28c03f..57c1e6bd2 100644 --- a/tests/functional/structured-attrs-shell.nix +++ b/tests/functional/structured-attrs-shell.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; let dep = mkDerivation { name = "dep"; diff --git a/tests/functional/structured-attrs.nix b/tests/functional/structured-attrs.nix index ae461c21a..e93139a44 100644 --- a/tests/functional/structured-attrs.nix +++ b/tests/functional/structured-attrs.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; let diff --git a/tests/functional/symlink-derivation.nix b/tests/functional/symlink-derivation.nix index 96765d355..e9a74cdce 100644 --- a/tests/functional/symlink-derivation.nix +++ b/tests/functional/symlink-derivation.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; let foo_in_store = builtins.toFile "foo" "foo"; diff --git a/tests/functional/test-libstoreconsumer/local.mk b/tests/functional/test-libstoreconsumer/local.mk deleted file mode 100644 index 3e8581c57..000000000 --- a/tests/functional/test-libstoreconsumer/local.mk +++ /dev/null @@ -1,15 +0,0 @@ -programs += test-libstoreconsumer - -test-libstoreconsumer_DIR := $(d) - -# do not install -test-libstoreconsumer_INSTALL_DIR := - -test-libstoreconsumer_SOURCES := \ - $(wildcard $(d)/*.cc) \ - -test-libstoreconsumer_CXXFLAGS += $(INCLUDE_libutil) $(INCLUDE_libstore) - -test-libstoreconsumer_LIBS = libstore libutil - -test-libstoreconsumer_LDFLAGS = $(THREAD_LDFLAGS) $(SODIUM_LIBS) $(EDITLINE_LIBS) $(BOOST_LDFLAGS) $(LOWDOWN_LIBS) diff --git a/tests/functional/timeout.nix b/tests/functional/timeout.nix index ad71e61e2..d0e949e31 100644 --- a/tests/functional/timeout.nix +++ b/tests/functional/timeout.nix @@ -1,4 +1,4 @@ -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; { diff --git a/tests/functional/user-envs.nix b/tests/functional/user-envs.nix index c8e846d4b..46f8b51dd 100644 --- a/tests/functional/user-envs.nix +++ b/tests/functional/user-envs.nix @@ -2,7 +2,7 @@ { foo ? "foo" }: -with import "${builtins.getEnv "_NIX_TEST_BUILD_DIR"}/config.nix"; +with import ./config.nix; assert foo == "foo"; diff --git a/tests/nixos/default.nix b/tests/nixos/default.nix index 49e2603e1..c5f4a23aa 100644 --- a/tests/nixos/default.nix +++ b/tests/nixos/default.nix @@ -21,7 +21,8 @@ let defaults = { nixpkgs.pkgs = nixpkgsFor.${system}.native; nix.checkAllErrors = false; - nix.package = noTests nixpkgsFor.${system}.native.nix; + # TODO: decide which packaging stage to use. `nix-cli` is efficient, but not the same as the user-facing `everything.nix` package (`default`). Perhaps a good compromise is `everything.nix` + `noTests` defined above? + nix.package = nixpkgsFor.${system}.native.nixComponents.nix-cli; }; _module.args.nixpkgs = nixpkgs; _module.args.system = system; @@ -33,10 +34,9 @@ let forNix = nixVersion: runNixOSTestFor system { imports = [test]; defaults.nixpkgs.overlays = [(curr: prev: { - # NOTE: noTests pkg might not have been built yet for some older versions of the package - # and in versions before 2.25, the untested build wasn't shared with the tested build yet - # Add noTests here when those versions become irrelevant. - nix = (builtins.getFlake "nix/${nixVersion}").packages.${system}.nix; + nix = let + packages = (builtins.getFlake "nix/${nixVersion}").packages.${system}; + in packages.nix-cli or packages.nix; })]; }; }; @@ -124,6 +124,8 @@ in nix-copy = runNixOSTestFor "x86_64-linux" ./nix-copy.nix; + nix-docker = runNixOSTestFor "x86_64-linux" ./nix-docker.nix; + nssPreload = runNixOSTestFor "x86_64-linux" ./nss-preload.nix; githubFlakes = runNixOSTestFor "x86_64-linux" ./github-flakes.nix; diff --git a/tests/nixos/functional/common.nix b/tests/nixos/functional/common.nix index 86d55d0b6..561271ba0 100644 --- a/tests/nixos/functional/common.nix +++ b/tests/nixos/functional/common.nix @@ -24,47 +24,42 @@ in environment.systemPackages = let run-test-suite = pkgs.writeShellApplication { name = "run-test-suite"; - runtimeInputs = [ pkgs.gnumake pkgs.jq pkgs.git ]; + runtimeInputs = [ + pkgs.meson + pkgs.ninja + pkgs.jq + pkgs.git + + # Want to avoid `/run/current-system/sw/bin/bash` because we + # want a store path. Likewise for coreutils. + pkgs.bash + pkgs.coreutils + ]; text = '' set -x + cat /proc/sys/fs/file-max ulimit -Hn ulimit -Sn + cd ~ - cp -r ${pkgs.nix.overrideAttrs (o: { - name = "nix-configured-source"; - outputs = [ "out" ]; - separateDebugInfo = false; - disallowedReferences = [ ]; - buildPhase = ":"; - checkPhase = ":"; - installPhase = '' - cp -r . $out - ''; - installCheckPhase = ":"; - fixupPhase = ":"; - doInstallCheck = true; - })} nix + + cp -r ${pkgs.nixComponents.nix-functional-tests.src} nix chmod -R +w nix - cd nix - # Tests we don't need - echo >tests/functional/plugins/local.mk - sed -i tests/functional/local.mk \ - -e 's!nix_tests += plugins\.sh!!' \ - -e 's!nix_tests += test-libstoreconsumer\.sh!!' \ - ; - - _NIX_TEST_SOURCE_DIR="$(realpath tests/functional)" - export _NIX_TEST_SOURCE_DIR - export _NIX_TEST_BUILD_DIR="''${_NIX_TEST_SOURCE_DIR}" + chmod u+w nix/.version + echo ${pkgs.nixComponents.version} > nix/.version export isTestOnNixOS=1 - export version=${config.nix.package.version} + export NIX_REMOTE_=daemon export NIX_REMOTE=daemon + export NIX_STORE=${builtins.storeDir} - make -j1 installcheck --keep-going + + meson setup nix/tests/functional build + cd build + meson test -j1 --print-errorlogs ''; }; in [ diff --git a/tests/nixos/nix-copy.nix b/tests/nixos/nix-copy.nix index 7db5197aa..8691d0138 100644 --- a/tests/nixos/nix-copy.nix +++ b/tests/nixos/nix-copy.nix @@ -37,7 +37,8 @@ in { { config, pkgs, ... }: { services.openssh.enable = true; services.openssh.settings.PermitRootLogin = "yes"; - users.users.root.password = "foobar"; + users.users.root.hashedPasswordFile = null; + users.users.root.password = "foobar"; virtualisation.writableStore = true; virtualisation.additionalPaths = [ pkgB pkgC ]; }; @@ -64,7 +65,7 @@ in { # Copy the closure of package A from the client to the server using password authentication, # and check that all prompts are visible server.fail("nix-store --check-validity ${pkgA}") - client.send_chars("nix copy --to ssh://server ${pkgA} >&2; echo done\n") + client.send_chars("nix copy --to ssh://server ${pkgA} >&2; echo -n do; echo ne\n") client.wait_for_text("continue connecting") client.send_chars("yes\n") client.wait_for_text("Password:") diff --git a/tests/nixos/nix-docker-test.sh b/tests/nixos/nix-docker-test.sh new file mode 100644 index 000000000..1f65e1a94 --- /dev/null +++ b/tests/nixos/nix-docker-test.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# docker.nix test script. Runs inside a built docker.nix container. + +set -eEuo pipefail + +export NIX_CONFIG='substituters = http://cache:5000?trusted=1' + +cd /tmp + +# Test getting a fetched derivation +test "$("$(nix-build -E '(import {}).hello')"/bin/hello)" = "Hello, world!" + +# Test building a simple derivation +# shellcheck disable=SC2016 +nix-build -E ' +let + pkgs = import {}; +in +builtins.derivation { + name = "test"; + system = builtins.currentSystem; + builder = "${pkgs.bash}/bin/bash"; + args = ["-c" "echo OK > $out"]; +}' +test "$(cat result)" = OK + +# Ensure #!/bin/sh shebang works +echo '#!/bin/sh' > ./shebang-test +echo 'echo OK' >> ./shebang-test +chmod +x ./shebang-test +test "$(./shebang-test)" = OK + +# Ensure #!/usr/bin/env shebang works +echo '#!/usr/bin/env bash' > ./shebang-test +echo 'echo OK' >> ./shebang-test +chmod +x ./shebang-test +test "$(./shebang-test)" = OK + +# Test nix-shell +{ + echo '#!/usr/bin/env nix-shell' + echo '#! nix-shell -i bash' + echo '#! nix-shell -p hello' + echo 'hello' +} > ./nix-shell-test +chmod +x ./nix-shell-test +test "$(./nix-shell-test)" = "Hello, world!" diff --git a/tests/nixos/nix-docker.nix b/tests/nixos/nix-docker.nix new file mode 100644 index 000000000..dfd508988 --- /dev/null +++ b/tests/nixos/nix-docker.nix @@ -0,0 +1,53 @@ +# Test the container built by ../../docker.nix. + +{ lib, config, nixpkgs, hostPkgs, ... }: + +let + pkgs = config.nodes.machine.nixpkgs.pkgs; + + nixImage = import ../../docker.nix { + inherit (config.nodes.machine.nixpkgs) pkgs; + }; + nixUserImage = import ../../docker.nix { + inherit (config.nodes.machine.nixpkgs) pkgs; + name = "nix-user"; + uid = 1000; + gid = 1000; + uname = "user"; + gname = "user"; + }; + + containerTestScript = ./nix-docker-test.sh; + +in { + name = "nix-docker"; + + nodes = + { machine = + { config, lib, pkgs, ... }: + { virtualisation.diskSize = 4096; + }; + cache = + { config, lib, pkgs, ... }: + { virtualisation.additionalPaths = [ pkgs.stdenv pkgs.hello ]; + services.harmonia.enable = true; + networking.firewall.allowedTCPPorts = [ 5000 ]; + }; + }; + + testScript = { nodes }: '' + cache.wait_for_unit("harmonia.service") + + machine.succeed("mkdir -p /etc/containers") + machine.succeed("""echo '{"default":[{"type":"insecureAcceptAnything"}]}' > /etc/containers/policy.json""") + + machine.succeed("${pkgs.podman}/bin/podman load -i ${nixImage}") + machine.succeed("${pkgs.podman}/bin/podman run --rm nix nix --version") + machine.succeed("${pkgs.podman}/bin/podman run --rm -i nix < ${containerTestScript}") + + machine.succeed("${pkgs.podman}/bin/podman load -i ${nixUserImage}") + machine.succeed("${pkgs.podman}/bin/podman run --rm nix-user nix --version") + machine.succeed("${pkgs.podman}/bin/podman run --rm -i nix-user < ${containerTestScript}") + machine.succeed("[[ $(${pkgs.podman}/bin/podman run --rm nix-user stat -c %u /nix/store) = 1000 ]]") + ''; +} diff --git a/tests/nixos/remote-builds.nix b/tests/nixos/remote-builds.nix index ab159eaad..84e5176b7 100644 --- a/tests/nixos/remote-builds.nix +++ b/tests/nixos/remote-builds.nix @@ -34,6 +34,8 @@ let } ''; + supportsBadShell = lib.versionAtLeast config.nodes.client.nix.package.version "2.25pre"; + in { @@ -82,7 +84,7 @@ in nix.settings.substituters = lib.mkForce [ ]; programs.ssh.extraConfig = "ConnectTimeout 30"; environment.systemPackages = [ - # `bad-shell` is used to make sure Nix works an environment with a misbehaving shell. + # `bad-shell` is used to make sure Nix works in an environment with a misbehaving shell. # # More realistically, a bad shell would still run the command ("echo started") # but considering that our solution is to avoid this shell (set via $SHELL), we @@ -125,13 +127,15 @@ in 'echo hello world on $(hostname)' >&2 """) + ${lib.optionalString supportsBadShell '' # Check that SSH uses SHELL for LocalCommand, as expected, and check that # our test setup here is working. The next test will use this bad SHELL. client.succeed(f"SHELL=$(which bad-shell) ssh -oLocalCommand='true' -oPermitLocalCommand=yes {builder1.name} 'echo hello world' | grep -F 'Hello, I am a broken shell'") + ''} # Perform a build and check that it was performed on the builder. out = client.succeed( - "SHELL=$(which bad-shell) nix-build ${expr nodes.client 1} 2> build-output", + "${lib.optionalString supportsBadShell "SHELL=$(which bad-shell)"} nix-build ${expr nodes.client 1} 2> build-output", "grep -q Hello build-output" ) builder1.succeed(f"test -e {out}")