# GNU Guix --- Functional package management for GNU
# Copyright © 2012-2015, 2017, 2019, 2022 Ludovic Courtès <ludo@gnu.org>
# Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
# Copyright © 2020 Simon Tournier <zimon.toutoune@gmail.com>
#
# This file is part of GNU Guix.
#
# GNU Guix is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or (at
# your option) any later version.
#
# GNU Guix is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

#
# Test the `guix package' command-line utility.  This test requires network
# access and is skipped when that is lacking.
#

guix package --version

readlink_base ()
{
    basename `readlink "$1"`
}

# Return true if a typical shebang in the store would exceed Linux's default
# static limit.
shebang_too_long ()
{
    test `echo $NIX_STORE_DIR/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bootstrap-binaries-0/bin/bash | wc -c` \
	 -ge 128
}

if ! guile -c '(getaddrinfo "www.gnu.org" "80" AI_NUMERICSERV)' 2> /dev/null \
	|| shebang_too_long
then
    # Skipping.
    exit 77
fi


profile="t-profile-$$"
profile_alt="t-profile-alt-$$"
rm -f "$profile"

module_dir="t-guix-package-net-$$"
mkdir "$module_dir"

trap 'rm -f "$profile" "$profile_alt" "$profile.lock" "$profile_alt.lock" "$profile-"[0-9]* "$profile_alt-"[0-9]* ; rm -r "$module_dir" t-home-'"$$" EXIT


guix package --bootstrap -p "$profile" -i guile-bootstrap
test -L "$profile" && test -L "$profile-1-link"
test ! -f "$profile-2-link"
test -f "$profile/bin/guile"

boot_make="(@ (guix tests) gnu-make-for-tests)"
boot_make_drv="`guix build -e "$boot_make" | grep -v -e -debug`"
guix package --bootstrap -p "$profile" -i "$boot_make_drv"
test -L "$profile-2-link"
test -f "$profile/bin/make" && test -f "$profile/bin/guile"

# Check whether `--list-installed' works.
# XXX: Change the tests when `--install' properly extracts the package
# name and version string.
installed="`guix package -p "$profile" --list-installed | cut -f1 | xargs echo | sort`"
case "x$installed" in
    "guile-bootstrap make-boot0")
        true;;
    "make-boot0 guile-bootstrap")
        true;;
    "*")
        false;;
esac

test "`guix package -p "$profile" -I 'g.*e' | cut -f1`" = "guile-bootstrap"

guix package --bootstrap -p "$profile_alt" -i gcc-bootstrap
installed="`guix package -p "$profile" -p "$profile_alt" -I | cut -f1 | xargs echo | sort`"
case "x$installed" in
    "gcc-bootstrap guile-bootstrap make-boot0")
        true;;
    "*")
        false;;
esac
test "`guix package -p "$profile_alt" -p "$profile" -I | wc -l`" = "3"
rm "$profile_alt"

# List generations.
test "`guix package -p "$profile" -l | cut -f1 | grep guile | head -n1`" \
     = "  guile-bootstrap"

# Exit with 1 when a generation does not exist.
guix package -p "$profile" --list-generations=42 && false
guix package -p "$profile" --switch-generation=99 && false

# Remove a package.
guix package --bootstrap -p "$profile" -r "guile-bootstrap"
test -L "$profile-3-link"
test -f "$profile/bin/make" && test ! -f "$profile/bin/guile"

# Roll back.
guix package --roll-back -p "$profile"
test "`readlink_base "$profile"`" = "$profile-2-link"
test -x "$profile/bin/guile" && test -x "$profile/bin/make"
guix package --roll-back -p "$profile"
test "`readlink_base "$profile"`" = "$profile-1-link"
test -x "$profile/bin/guile" && test ! -x "$profile/bin/make"

# Switch to the rolled generation and switch back.
guix package -p "$profile" --switch-generation=2
test "`readlink_base "$profile"`" = "$profile-2-link"
guix package -p "$profile" --switch-generation=-1
test "`readlink_base "$profile"`" = "$profile-1-link"

# Move to the empty profile.
for i in `seq 1 3`
do
    guix package --bootstrap --roll-back -p "$profile"
    test ! -f "$profile/bin"
    test ! -f "$profile/lib"
    test "`readlink_base "$profile"`" = "$profile-0-link"
done

# Test that '--list-generations' does not output the zeroth generation.
test -z "`guix package -p "$profile" -l 0`"

# Reinstall after roll-back to the empty profile.
guix package --bootstrap -p "$profile" -e "$boot_make"
test "`readlink_base "$profile"`" = "$profile-1-link"
test -x "$profile/bin/guile" && test ! -x "$profile/bin/make"

# Check that the first generation is the current one.
test "`guix package -p "$profile" -l 1 | cut -f3 | head -n1`" = "(current)"

# Roll-back to generation 0, and install---all at once.
guix package --bootstrap -p "$profile" --roll-back -i guile-bootstrap
test "`readlink_base "$profile"`" = "$profile-1-link"
test -x "$profile/bin/guile" && test ! -x "$profile/bin/make"

# Install Make.
guix package --bootstrap -p "$profile" -e "$boot_make"
test "`readlink_base "$profile"`" = "$profile-2-link"
test -x "$profile/bin/guile" && test -x "$profile/bin/make"
grep "`guix build -e "$boot_make"`" "$profile/manifest"

# Make a "hole" in the list of generations, and make sure we can
# roll back and switch "over" it.
rm "$profile-1-link"
guix package --bootstrap -p "$profile" --roll-back
test "`readlink_base "$profile"`" = "$profile-0-link"
guix package -p "$profile" --switch-generation=+1
test "`readlink_base "$profile"`" = "$profile-2-link"

# Make sure LIBRARY_PATH gets listed by `--search-paths'.
guix package --bootstrap -p "$profile" -i guile-bootstrap -i gcc-bootstrap
guix package -p "$profile" --search-paths | grep LIBRARY_PATH

# Roll back so we can delete #3 below.
guix package -p "$profile" --switch-generation=2

# Delete the third generation and check that it was actually deleted.
guix package -p "$profile" --delete-generations=3
test -z "`guix package -p "$profile" -l 3`"

# Search path of combined profiles.  'LIBRARY_PATH' should show up only in the
# combination, not in the individual profiles.
rm "$profile"
guix package --bootstrap -p "$profile" -i guile-bootstrap
guix package --bootstrap -p "$profile_alt" -i gcc-bootstrap
guix package -p "$profile" --search-paths | grep LIBRARY_PATH && false
guix package -p "$profile" -p "$profile_alt" --search-paths \
     | grep "LIBRARY_PATH.*$profile/lib.$profile_alt/lib"

# Simulate an upgrade and make sure the package order is preserved.
cat > "$module_dir/new.scm" <<EOF
(define-module (new)
  #:use-module (guix)
  #:use-module (gnu packages bootstrap))

(define-public new-guile
  (package (inherit %bootstrap-guile)
           (version (string-append "42." (getenv "V_MINOR")))))
(define-public new-gcc
  (package (inherit %bootstrap-gcc)
           (version (string-append "77." (getenv "V_MINOR")))))
EOF

guix package --bootstrap -p "$profile" -i gcc-bootstrap
installed="`guix package -p "$profile" -I | cut -f1`"

# Dry-run upgrade.  Make sure no new generation is created when things are
# already in store and '-n' is used: <https://issues.guix.gnu.org/53267>.
V_MINOR=0
export V_MINOR
profile_before="$(readlink "$profile")"
guix package -p "$profile" --bootstrap -L "$module_dir" -u # build the profile
guix package -p "$profile" --roll-back
guix package -p "$profile" --bootstrap -L "$module_dir" -u . -n # check '-n'
test "$(readlink "$profile")" = "$profile_before"

for i in 1 2
do
    V_MINOR="$i"
    export V_MINOR

    guix package -p "$profile" --bootstrap -L "$module_dir" -u .
    post_upgrade="`guix package -p "$profile" -I | cut -f1`"
    test "$post_upgrade" = "$installed"
done

#
# Try with the default profile.
#

XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}"
export XDG_CACHE_HOME
HOME="$PWD/t-home-$$"
export HOME

mkdir -p "$HOME"

# Get the canonical directory name so that 'guix package' recognizes it.
HOME="`cd $HOME; pwd -P`"

guix package --bootstrap -e "$boot_make"
test -f "$HOME/.guix-profile/bin/make"

guix package --bootstrap --roll-back
test ! -f "$HOME/.guix-profile/bin/make"
package? object) (select? object)) (proc object result) result)) init modules)) (define %package-cache-file ;; Location of the package cache. "/lib/guix/package.cache") (define load-package-cache (mlambda (profile) "Attempt to load the package cache. On success return a vhash keyed by package names. Return #f on failure." (match profile (#f #f) (profile (catch 'system-error (lambda () (define lst (load-compiled (string-append profile %package-cache-file))) (fold (lambda (item vhash) (match item (#(name version module symbol outputs supported? deprecated? file line column) (vhash-cons name item vhash)))) vlist-null lst)) (lambda args (if (= ENOENT (system-error-errno args)) #f (apply throw args)))))))) (define find-packages-by-name/direct ;bypass the cache (let ((packages (delay (fold-packages (lambda (p r) (vhash-cons (package-name p) p r)) vlist-null))) (version>? (lambda (p1 p2) (version>? (package-version p1) (package-version p2))))) (lambda* (name #:optional version) "Return the list of packages with the given NAME. If VERSION is not #f, then only return packages whose version is prefixed by VERSION, sorted in decreasing version order." (let ((matching (sort (vhash-fold* cons '() name (force packages)) version>?))) (if version (filter (lambda (package) (version-prefix? version (package-version package))) matching) matching))))) (define (cache-lookup cache name) "Lookup package NAME in CACHE. Return a list sorted in increasing version order." (define (package-version<? v1 v2) (version>? (vector-ref v2 1) (vector-ref v1 1))) (sort (vhash-fold* cons '() name cache) package-version<?)) (define* (find-packages-by-name name #:optional version) "Return the list of packages with the given NAME. If VERSION is not #f, then only return packages whose version is prefixed by VERSION, sorted in decreasing version order." (define cache (load-package-cache (current-profile))) (if (and (cache-is-authoritative?) cache) (match (cache-lookup cache name) (#f #f) ((#(_ versions modules symbols _ _ _ _ _ _) ...) (fold (lambda (version* module symbol result) (if (or (not version) (version-prefix? version version*)) (cons (module-ref (resolve-interface module) symbol) result) result)) '() versions modules symbols))) (find-packages-by-name/direct name version))) (define* (find-package-locations name #:optional version) "Return a list of version/location pairs corresponding to each package matching NAME and VERSION." (define cache (load-package-cache (current-profile))) (if (and cache (cache-is-authoritative?)) (match (cache-lookup cache name) (#f '()) ((#(name versions modules symbols outputs supported? deprecated? files lines columns) ...) (fold (lambda (version* file line column result) (if (and file (or (not version) (version-prefix? version version*))) (alist-cons version* (location file line column) result) result)) '() versions files lines columns))) (map (lambda (package) (cons (package-version package) (package-location package))) (find-packages-by-name/direct name version)))) (define (find-best-packages-by-name name version) "If version is #f, return the list of packages named NAME with the highest version numbers; otherwise, return the list of packages named NAME and at VERSION." (if version (find-packages-by-name name version) (match (find-packages-by-name name) (() '()) ((matches ...) ;; Return the subset of MATCHES with the higher version number. (let ((highest (package-version (first matches)))) (take-while (lambda (p) (string=? (package-version p) highest)) matches)))))) ;; Prevent Guile 3 from inlining this procedure so we can mock it in tests. (set! find-best-packages-by-name find-best-packages-by-name) (define (generate-package-cache directory) "Generate under DIRECTORY a cache of all the available packages. The primary purpose of the cache is to speed up package lookup by name such that we don't have to traverse and load all the package modules, thereby also reducing the memory footprint." (define cache-file (string-append directory %package-cache-file)) (define expand-cache (match-lambda* (((module symbol variable) (result . seen)) (let ((package (variable-ref variable))) (if (or (vhash-assq package seen) (hidden-package? package)) (cons result seen) (cons (cons `#(,(package-name package) ,(package-version package) ,(module-name module) ,symbol ,(package-outputs package) ,(->bool (supported-package? package)) ,(->bool (package-superseded package)) ,@(let ((loc (package-location package))) (if loc `(,(location-file loc) ,(location-line loc) ,(location-column loc)) '(#f #f #f)))) result) (vhash-consq package #t seen))))))) (define entry-key (match-lambda ((module symbol variable) (let ((value (variable-ref variable))) (string-append (package-name value) (package-version value) (object->string module) (symbol->string symbol)))))) (define (entry<? a b) (string<? (entry-key a) (entry-key b))) (define variables ;; First sort variables so that 'expand-cache' later dismisses ;; already-seen package objects in a deterministic fashion. (sort (fold-module-public-variables* (lambda (module symbol variable lst) (let ((value (false-if-exception (variable-ref variable)))) (if (package? value) (cons (list module symbol variable) lst) lst))) '() (all-modules (%package-module-path) #:warn warn-about-load-error)) entry<?)) (define exp (first (fold expand-cache (cons '() vlist-null) variables))) (mkdir-p (dirname cache-file)) (call-with-output-file cache-file (lambda (port) ;; Store the cache as a '.go' file. This makes loading fast and reduces ;; heap usage since some of the static data is directly mmapped. (match (compile `'(,@exp) #:to 'bytecode #:opts '(#:to-file? #t)) ((? bytevector? bv) (put-bytevector port bv)) (proc ;; In Guile 3.0.9, the linker can return a procedure instead of a ;; bytevector. Adjust to that. (proc port))))) cache-file) (define %sigint-prompt ;; The prompt to jump to upon SIGINT. (make-prompt-tag "interruptible")) (define (call-with-sigint-handler thunk handler) "Call THUNK and return its value. Upon SIGINT, call HANDLER with the signal number in the context of the continuation of the call to this function, and return its return value." (call-with-prompt %sigint-prompt (lambda () (sigaction SIGINT (lambda (signum) (sigaction SIGINT SIG_DFL) (abort-to-prompt %sigint-prompt signum))) (dynamic-wind (const #t) thunk (cut sigaction SIGINT SIG_DFL))) (lambda (k signum) (handler signum)))) ;;; ;;; Package specification. ;;; (define* (%find-package spec name version) (match (find-best-packages-by-name name version) ((pkg . pkg*) (unless (null? pkg*) (warning (G_ "ambiguous package specification `~a'~%") spec) (warning (G_ "choosing ~a@~a from ~a~%") (package-name pkg) (package-version pkg) (location->string (package-location pkg)))) (match (package-superseded pkg) ((? package? new) (info (G_ "package '~a' has been superseded by '~a'~%") (package-name pkg) (package-name new)) new) (#f pkg))) (x (if version (leave (G_ "~A: package not found for version ~a~%") name version) (leave (G_ "~A: unknown package~%") name))))) (define (specification->package spec) "Return a package matching SPEC. SPEC may be a package name, or a package name followed by an at-sign and a version number. If the version number is not present, return the preferred newest version." (let ((name version (package-name->name+version spec))) (%find-package spec name version))) (define (specification->location spec) "Return the location of the highest-numbered package matching SPEC, a specification such as \"guile@2\" or \"emacs\"." (let ((name version (package-name->name+version spec))) (match (find-package-locations name version) (() (if version (leave (G_ "~A: package not found for version ~a~%") name version) (leave (G_ "~A: unknown package~%") name))) (lst (let* ((highest (match lst (((version . _) _ ...) version))) (locations (take-while (match-lambda ((version . location) (string=? version highest))) lst))) (match locations (((version . location) . rest) (unless (null? rest) (warning (G_ "ambiguous package specification `~a'~%") spec) (warning (G_ "choosing ~a@~a from ~a~%") name version (location->string location))) location))))))) (define* (specification->package+output spec #:optional (output "out")) "Return the package and output specified by SPEC, or #f and #f; SPEC may optionally contain a version number and an output name, as in these examples: guile guile@2.0.9 guile:debug guile@2.0.9:debug If SPEC does not specify a version number, return the preferred newest version; if SPEC does not specify an output, return OUTPUT. When OUTPUT is false and SPEC does not specify any output, return #f as the output." (let ((name version sub-drv (package-specification->name+version+output spec output))) (match (%find-package spec name version) (#f (values #f #f)) (package (if (or (and (not output) (not sub-drv)) (member sub-drv (package-outputs package))) (values package sub-drv) (leave (G_ "package `~a' lacks output `~a'~%") (package-full-name package) sub-drv)))))) (define (specifications->packages specs) "Given SPECS, a list of specifications such as \"emacs@25.2\" or \"guile:debug\", return a list of package/output tuples." ;; This procedure exists so users of 'guix home' don't have to write out the ;; (map (compose list specification->package+output)... boilerplate. (map (compose list specification->package+output) specs)) (define (specifications->manifest specs) "Given SPECS, a list of specifications such as \"emacs@25.2\" or \"guile:debug\", return a profile manifest." ;; This procedure exists mostly so users of 'guix package -m' don't have to ;; fiddle with multiple-value returns. (packages->manifest (specifications->packages specs))) (define (package-unique-version-prefix name version) "Search among all the versions of package NAME that are available, and return the shortest unambiguous version prefix to designate VERSION. If only one version of the package is available, return the empty string." (match (map package-version (find-packages-by-name name)) ((_) ;; A single version of NAME is available, so do not specify the version ;; number, even if the available version doesn't match VERSION. "") (versions ;; If VERSION is the latest version, don't specify any version. ;; Otherwise return the shortest unique version prefix. Note that this ;; is based on the currently available packages so the result may vary ;; over time. (if (every (cut version>? version <>) (delete version versions)) "" (version-unique-prefix version versions)))))