code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2019 Julien Lepiller <julien@lepiller.eu>
;;; Copyright © 2020 Ludovic Courtès <ludo@gnu.org>
;;;
;;; 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/>.

(define-module (guix build po)
  #:use-module (ice-9 match)
  #:use-module (ice-9 peg)
  #:use-module (ice-9 textual-ports)
  #:export (read-po-file))

;; A small parser for po files
(define-peg-pattern po-file body (* (or comment entry whitespace)))
(define-peg-pattern whitespace body (or " " "\t" "\n"))
(define-peg-pattern comment-chr body (range #\space #\頋))
(define-peg-pattern comment none (and "#" (* comment-chr) "\n"))
(define-peg-pattern entry all
  (and (ignore (* whitespace)) (ignore "msgid ") msgid
       (ignore (* whitespace)) (ignore "msgstr ") msgstr))
(define-peg-pattern escape body (or "\\\\" "\\\"" "\\n"))
(define-peg-pattern str-chr body (or " " "!" (and (ignore "\\") "\"")
                                     "\\n" (and (ignore "\\") "\\")
                                     (range #\# #\頋)))
(define-peg-pattern msgid all content)
(define-peg-pattern msgstr all content)
(define-peg-pattern content body
  (and (ignore "\"") (* str-chr) (ignore "\"")
       (? (and (ignore (* whitespace)) content))))

(define (interpret-newline-escape str)
  "Replace '\\n' sequences in STR with a newline character."
  (let loop ((str str)
             (result '()))
    (match (string-contains str "\\n")
      (#f (string-concatenate-reverse (cons str result)))
      (index
       (let ((prefix (string-take str index)))
         (loop (string-drop str (+ 2 index))
               (append (list "\n" prefix) result)))))))

(define (parse-tree->assoc parse-tree)
  "Converts a po PARSE-TREE to an association list."
  (match parse-tree
    (() '())
    ((entry . parse-tree)
     (match entry
       ((? string? entry)
        (parse-tree->assoc parse-tree))
       ;; empty msgid
       (('entry ('msgid ('msgstr msgstr)))
        (parse-tree->assoc parse-tree))
       ;; empty msgstr
       (('entry ('msgid msgid) 'msgstr)
        (parse-tree->assoc parse-tree))
       (('entry ('msgid msgid) ('msgstr msgstr))
        (acons (interpret-newline-escape msgid)
               (interpret-newline-escape msgstr)
               (parse-tree->assoc parse-tree)))))))

(define (read-po-file port)
  "Read a .po file from PORT and return an alist of msgid and msgstr."
  (let ((tree (peg:tree (match-pattern
                          po-file
                          (get-string-all port)))))
    (parse-tree->assoc tree)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;;
;;; 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/>.

(define-module (guix build profiles)
  #:use-module (guix build union)
  #:use-module (guix build utils)
  #:use-module (guix search-paths)
  #:use-module (srfi srfi-26)
  #:use-module (ice-9 ftw)
  #:use-module (ice-9 match)
  #:use-module (ice-9 pretty-print)
  #:re-export (symlink-relative)                  ;for convenience
  #:export (ensure-writable-directory
            build-profile))

;;; Commentary:
;;;
;;; Build a user profile (essentially the union of all the installed packages)
;;; with its associated meta-data.
;;;
;;; Code:

(define (abstract-profile profile)
  "Return a procedure that replaces PROFILE in VALUE with a reference to the
'GUIX_PROFILE' environment variable.  This allows users to specify what the
user-friendly name of the profile is, for instance ~/.guix-profile rather than
/gnu/store/...-profile."
  (let ((replacement (string-append "${GUIX_PROFILE:-" profile "}"))
        (crop        (cute string-drop <> (string-length profile))))
    (match-lambda
      ((search-path . value)
       (match (search-path-specification-separator search-path)
         (#f
          (cons search-path
                (string-append replacement (crop value))))
         ((? string? separator)
          (let ((items (string-tokenize* value separator)))
            (cons search-path
                  (string-join (map (lambda (str)
                                      (string-append replacement (crop str)))
                                    items)
                               separator)))))))))

(define (write-environment-variable-definition port)
  "Write the given environment variable definition to PORT."
  (match-lambda
    ((search-path . value)
     (display (search-path-definition search-path value #:kind 'prefix)
              port)
     (newline port))))

(define (build-etc/profile output search-paths)
  "Build the 'OUTPUT/etc/profile' shell file containing environment variable
definitions for all the SEARCH-PATHS."
  (define file
    (string-append output "/etc/profile"))

  (mkdir-p (dirname file))
  (when (file-exists? file)
    (delete-file file))

  (call-with-output-file file
    (lambda (port)
      ;; The use of $GUIX_PROFILE described below is not great.  Another
      ;; option would have been to use "$1" and have users run:
      ;;
      ;;   source ~/.guix-profile/etc/profile ~/.guix-profile
      ;;
      ;; However, when 'source' is used with no arguments, $1 refers to the
      ;; first positional parameter of the calling script, so we cannot rely
      ;; on it.
      (display "\
# Source this file to define all the relevant environment variables in Bash
# for this profile.  You may want to define the 'GUIX_PROFILE' environment
# variable to point to the \"visible\" name of the profile, like this:
#
#  GUIX_PROFILE=/path/to/profile ; \\
#  source /path/to/profile/etc/profile
#
# When GUIX_PROFILE is undefined, the various environment variables refer
# to this specific profile generation.
\n" port)
      (let ((variables (evaluate-search-paths search-paths
                                              (list output))))
        (for-each (write-environment-variable-definition port)
                  (map (abstract-profile output) variables))))))

(define* (ensure-writable-directory directory
                                    #:key (symlink symlink))
  "Ensure DIRECTORY exists and is writable.  If DIRECTORY is currently a
symlink (to a read-only directory in the store), then delete the symlink and
instead make DIRECTORY a \"real\" directory containing symlinks."
  (define (absolute? file)
    (string-prefix? "/" file))

  (define (unsymlink link)
    (let* ((target (match (readlink link)
                     ((? absolute? target)
                      target)
                     ((? string? relative)
                      (string-append (dirname link) "/" relative))))
           ;; TARGET might itself be a symlink, so append "/" to make sure
           ;; 'scandir' enters it.
           (files  (scandir (string-append target "/")
                            (negate (cut member <> '("." ".."))))))
      (delete-file link)
      (mkdir link)
      (for-each (lambda (file)
                  (symlink (string-append target "/" file)
                           (string-append link "/" file)))
                files)))

  (catch 'system-error
    (lambda ()
      (mkdir directory))
    (lambda args
      (let ((errno (system-error-errno args)))
        (if (= errno EEXIST)
            (let ((stat (lstat directory)))
              (case (stat:type stat)
                ((symlink)
                 ;; "Unsymlink" DIRECTORY so that it is writable.
                 (unsymlink directory))
                ((directory)
                 #t)
                (else
                 (error "cannot mkdir because a same-named file exists"
                        directory))))
            (apply throw args))))))

(define* (build-profile output inputs
                        #:key manifest search-paths
                        (symlink symlink))
  "Build a user profile from INPUTS in directory OUTPUT, using SYMLINK to
create symlinks.  Write MANIFEST, an sexp, to OUTPUT/manifest.  Create
OUTPUT/etc/profile with Bash definitions for -all the variables listed in
SEARCH-PATHS."
  (define manifest-file
    (string-append output "/manifest"))

  ;; Make the symlinks.
  (union-build output inputs
               #:symlink symlink
               #:log-port (%make-void-port "w"))

  ;; If one of the INPUTS provides a '/manifest' file, delete it.  That can
  ;; happen if MANIFEST contains something such as a Guix instance, which is
  ;; ultimately built as a profile.
  (when (file-exists? manifest-file)
    (delete-file manifest-file))

  ;; Store meta-data.
  (call-with-output-file manifest-file
    (lambda (p)
      (display "\
;; This file was automatically generated and is for internal use only.
;; It cannot be passed to the '--manifest' option.\n\n"
               p)
      (pretty-print manifest p)))

  ;; Make sure we can write to 'OUTPUT/etc'.  'union-build' above could have
  ;; made 'etc' a symlink to a read-only sub-directory in the store so we need
  ;; to work around that.
  (ensure-writable-directory (string-append output "/etc")
                             #:symlink symlink)

  ;; Write 'OUTPUT/etc/profile'.
  (build-etc/profile output search-paths))

;;; profile.scm ends here

license: mit


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2015, 2016, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2013 Andreas Enge <andreas@enge.fr>
;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
;;; Copyright © 2015, 2018 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2016 Hartmut Goebel <h.goebel@crazy-compilers.com>
;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2018 Arun Isaac <arunisaac@systemreboot.net>
;;; Copyright © 2020 Jakub Kądziołka <kuba@kadziolka.net>
;;;
;;; 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/>.

(define-module (guix build python-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module (guix build utils)
  #:use-module (ice-9 match)
  #:use-module (ice-9 ftw)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:export (%standard-phases
            add-installed-pythonpath
            site-packages
            python-version
            python-build))

;; Commentary:
;;
;; Builder-side code of the standard Python package build procedure.
;;
;;
;; Backgound about the Python installation methods
;;
;; In Python there are different ways to install packages: distutils,
;; setuptools, easy_install and pip.  All of these are sharing the file
;; setup.py, introduced with distutils in Python 2.0. The setup.py file can be
;; considered as a kind of Makefile accepting targets (or commands) like
;; "build" and "install".  As of autumn 2016 the recommended way to install
;; Python packages is using pip.
;;
;; For both distutils and setuptools, running "python setup.py install" is the
;; way to install Python packages.  With distutils the "install" command
;; basically copies all packages into <prefix>/lib/pythonX.Y/site-packages.
;;
;; Some time later "setuptools" was established to enhance distutils.  To use
;; setuptools, the developer imports setuptools in setup.py.  When importing
;; setuptools, the original "install" command gets overwritten by setuptools'
;; "install" command.
;;
;; The command-line tools easy_install and pip are both capable of finding and
;; downloading the package source from PyPI (the Python Package Index).  Both
;; of them import setuptools and execute the "setup.py" file under their
;; control.  Thus the "setup.py" behaves as if the developer had imported
;; setuptools within setup.py - even is still using only distutils.
;;
;; Setuptools' "install" command (to be more precise: the "easy_install"
;; command which is called by "install") will put the path of the currently
;; installed version of each package and it's dependencies (as declared in
;; setup.py) into an "easy-install.pth" file.  In Guix each packages gets its
;; own "site-packages" directory and thus an "easy-install.pth" of its own.
;; To avoid conflicts, the python build system renames the file to
;; <packagename>.pth in the phase rename-pth-file.  To ensure that Python will
;; process the .pth file, easy_install also creates a basic "site.py" in each
;; "site-packages" directory.  The file is the same for all packages, thus
;; there is no need to rename it.  For more information about .pth files and
;; the site module, please refere to
;; https://docs.python.org/3/library/site.html.
;;
;; The .pth files contain the file-system paths (pointing to the store) of all
;; dependencies.  So the dependency is hidden in the .pth file but is not
;; visible in the file-system.  Now if packages A and B both required packages
;; P, but in different versions, Guix will not detect this when installing
;; both A and B to a profile. (For details and example see
;; https://lists.gnu.org/archive/html/guix-devel/2016-10/msg01233.html.)
;;
;; Pip behaves a bit different then easy_install: it always executes
;; "setup.py" with the option "--single-version-externally-managed" set.  This
;; makes setuptools' "install" command run the original "install" command
;; instead of the "easy_install" command, so no .pth file (and no site.py)
;; will be created.  The "site-packages" directory only contains the package
;; and the related .egg-info directory.
;;
;; This is exactly what we need for Guix and this is what we mimic in the
;; install phase below.
;;
;; As a draw back, the magic of the .pth file of linking to the other required
;; packages is gone and these packages have now to be declared as
;; "propagated-inputs".
;;
;; Note: Importing setuptools also adds two sub-commands: "install_egg_info"
;; and "install_scripts".  These sub-commands are executed even if
;; "--single-version-externally-managed" is set, thus the .egg-info directory
;; and the scripts defined in entry-points will always be created.

(define setuptools-shim
  ;; Run setup.py with "setuptools" being imported, which will patch
  ;; "distutils". This is needed for packages using "distutils" instead of
  ;; "setuptools" since the former does not understand the
  ;; "--single-version-externally-managed" flag.
  ;; Python code taken from pip 9.0.1 pip/utils/setuptools_build.py
  (string-append
   "import setuptools, tokenize;__file__='setup.py';"
   "f=getattr(tokenize, 'open', open)(__file__);"
   "code=f.read().replace('\\r\\n', '\\n');"
   "f.close();"
   "exec(compile(code, __file__, 'exec'))"))

(define (call-setuppy command params use-setuptools?)
  (if (file-exists? "setup.py")
      (begin
         (format #t "running \"python setup.py\" with command ~s and parameters ~s~%"
                command params)
         (if use-setuptools?
             (apply invoke "python" "-c" setuptools-shim
                    command params)
             (apply invoke "python" "./setup.py" command params)))
      (error "no setup.py found")))

(define* (build #:key use-setuptools? #:allow-other-keys)
  "Build a given Python package."
  (call-setuppy "build" '() use-setuptools?)
  #t)

(define* (check #:key tests? test-target use-setuptools? #:allow-other-keys)
  "Run the test suite of a given Python package."
  (if tests?
      ;; Running `setup.py test` creates an additional .egg-info directory in
      ;; build/lib in some cases, e.g. if the source is in a sub-directory
      ;; (given with `package_dir`). This will by copied to the output, too,
      ;; so we need to remove.
      (let ((before (find-files "build" "\\.egg-info$" #:directories? #t)))
        (call-setuppy test-target '() use-setuptools?)
        (let* ((after (find-files "build" "\\.egg-info$" #:directories? #t))
               (inter (lset-difference string=? after before)))
          (for-each delete-file-recursively inter)))
      (format #t "test suite not run~%"))
  #t)

(define (python-version python)
  (let* ((version     (last (string-split python #\-)))
         (components  (string-split version #\.))
         (major+minor (take components 2)))
    (string-join major+minor ".")))

(define (python-output outputs)
  "Return the path of the python output, if there is one, or fall-back to out."
  (or (assoc-ref outputs "python")
      (assoc-ref outputs "out")))

(define (site-packages inputs outputs)
  "Return the path of the current output's Python site-package."
  (let* ((out (python-output outputs))
         (python (assoc-ref inputs "python")))
    (string-append out "/lib/python"
                   (python-version python)
                   "/site-packages/")))

(define (add-installed-pythonpath inputs outputs)
  "Prepend the Python site-package of OUTPUT to PYTHONPATH.  This is useful
when running checks after installing the package."
  (let ((old-path (getenv "PYTHONPATH"))
        (add-path (site-packages inputs outputs)))
    (setenv "PYTHONPATH"
            (string-append add-path
                           (if old-path (string-append ":" old-path) "")))
    #t))

(define* (install #:key outputs (configure-flags '()) use-setuptools?
                  #:allow-other-keys)
  "Install a given Python package."
  (let* ((out (python-output outputs))
         (params (append (list (string-append "--prefix=" out))
                         (if use-setuptools?
                             ;; distutils does not accept these flags
                             (list "--single-version-externally-managed"
                                    "--root=/")
                             '())
                         configure-flags)))
    (call-setuppy "install" params use-setuptools?)
    #t))

(define* (wrap #:key inputs outputs #:allow-other-keys)
  (define (list-of-files dir)
    (find-files dir (lambda (file stat)
                      (and (eq? 'regular (stat:type stat))
                           (not (wrapper? file))))))

  (define bindirs
    (append-map (match-lambda
                 ((_ . dir)
                  (list (string-append dir "/bin")
                        (string-append dir "/sbin"))))
                outputs))

  (let* ((var `("PYTHONPATH" prefix
                ,(cons (site-packages inputs outputs)
                       (search-path-as-string->list
                        (or (getenv "PYTHONPATH") ""))))))
    (for-each (lambda (dir)
                (let ((files (list-of-files dir)))
                  (for-each (cut wrap-program <> var)
                            files)))
              bindirs)
    #t))

(define* (rename-pth-file #:key name inputs outputs #:allow-other-keys)
  "Rename easy-install.pth to NAME.pth to avoid conflicts between packages
installed with setuptools."
  ;; Even if the "easy-install.pth" is not longer created, we kept this phase.
  ;; There still may be packages creating an "easy-install.pth" manually for
  ;; some good reason.
  (let* ((site-packages (site-packages inputs outputs))
         (easy-install-pth (string-append site-packages "/easy-install.pth"))
         (new-pth (string-append site-packages "/" name ".pth")))
    (when (file-exists? easy-install-pth)
      (rename-file easy-install-pth new-pth))
    #t))

(define* (ensure-no-mtimes-pre-1980 #:rest _)
  "Ensure that there are no mtimes before 1980-01-02 in the source tree."
  ;; Rationale: patch-and-repack creates tarballs with timestamps at the POSIX
  ;; epoch, 1970-01-01 UTC.  This causes problems with Python packages,
  ;; because Python eggs are ZIP files, and the ZIP format does not support
  ;; timestamps before 1980.
  (let ((early-1980 315619200))  ; 1980-01-02 UTC
    (ftw "." (lambda (file stat flag)
               (unless (<= early-1980 (stat:mtime stat))
                 (utime file early-1980 early-1980))
               #t))
    #t))

(define* (enable-bytecode-determinism #:rest _)
  "Improve determinism of pyc files."
  ;; Use deterministic hashes for strings, bytes, and datetime objects.
  (setenv "PYTHONHASHSEED" "0")
  #t)

(define %standard-phases
  ;; The build phase only builds C extensions and copies the Python sources,
  ;; while the install phase byte-compiles and copies them to the prefix
  ;; directory.  The tests are run after the install phase because otherwise
  ;; the cached .pyc generated during the tests execution seem to interfere
  ;; with the byte compilation of the install phase.
  (modify-phases gnu:%standard-phases
    (add-after 'unpack 'ensure-no-mtimes-pre-1980 ensure-no-mtimes-pre-1980)
    (add-after 'ensure-no-mtimes-pre-1980 'enable-bytecode-determinism
      enable-bytecode-determinism)
    (delete 'bootstrap)
    (delete 'configure)                 ;not needed
    (replace 'build build)
    (delete 'check)                     ;moved after the install phase
    (replace 'install install)
    (add-after 'install 'check check)
    (add-after 'install 'wrap wrap)
    (add-before 'strip 'rename-pth-file rename-pth-file)))

(define* (python-build #:key inputs (phases %standard-phases)
                       #:allow-other-keys #:rest args)
  "Build the given Python package, applying all of PHASES in order."
  (apply gnu:gnu-build #:inputs inputs #:phases phases args))

;;; python-build-system.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014 Federico Beffa <beffa@fbengineering.ch>
;;; Copyright © 2014, 2015 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2018 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2019, 2020 Hartmut Goebel <h.goebel@crazy-compilers.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/>.

(define-module (guix build qt-build-system)
  #:use-module ((guix build cmake-build-system) #:prefix cmake:)
  #:use-module (guix build utils)
  #:use-module (ice-9 match)
  #:use-module (ice-9 regex)
  #:use-module (ice-9 ftw)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:export (%standard-phases
            qt-build))

;; Commentary:
;;
;; Builder-side code of the standard Qt build procedure.
;;
;; Code:

(define* (check-setup #:rest args)
  ;; Make Qt render "offscreen". In many cases this allows to run tests
  ;; without starting a X11 server.
  (setenv "QT_QPA_PLATFORM" "offscreen")
  ;; Qt/KDE tests often need dbus (`dbus-launch …`) which is not fully
  ;; set-up the the build container.
  (setenv "DBUS_FATAL_WARNINGS" "0")
  ;; Set here to ease overwriting 'check (even if set there, too)
  (setenv "CTEST_OUTPUT_ON_FAILURE" "1")
  #t)

(define (variables-for-wrapping base-directories)

  (define (collect-sub-dirs base-directories subdirectory)
    (filter-map
     (lambda (dir)
       (let ((directory (string-append dir subdirectory)))
         (if (directory-exists? directory) directory #f)))
     base-directories))

  (filter
   (lambda (var-to-wrap) (not (null? (last var-to-wrap))))
   (map
    (lambda (var-spec)
      `(,(first var-spec) = ,(collect-sub-dirs base-directories (last var-spec))))
    (list
     ;; these shall match the search-path-specification for Qt and KDE
     ;; libraries
     '("XDG_DATA_DIRS" "/share")
     '("XDG_CONFIG_DIRS" "/etc/xdg")
     '("QT_PLUGIN_PATH" "/lib/qt5/plugins")
     '("QML2_IMPORT_PATH" "/lib/qt5/qml")))))

(define* (wrap-all-programs #:key inputs outputs
                            (qt-wrap-excluded-outputs '())
                            #:allow-other-keys)
  "Implement phase \"qt-wrap\": look for GSettings schemas and
gtk+-v.0 libraries and create wrappers with suitably set environment variables
if found.

Wrapping is not applied to outputs whose name is listed in
QT-WRAP-EXCLUDED-OUTPUTS.  This is useful when an output is known not
to contain any Qt binaries, and where wrapping would gratuitously
add a dependency of that output on Qt."
  (define (find-files-to-wrap directory)
    (append-map
     (lambda (dir)
       (if (directory-exists? dir) (find-files dir ".*") (list)))
     (list (string-append directory "/bin")
           (string-append directory "/sbin")
           (string-append directory "/libexec")
           (string-append directory "/lib/libexec"))))

  (define input-directories
    ;; FIXME: Filter out unwanted inputs, e.g. cmake
    (match inputs
           (((_ . dir) ...)
            dir)))

  (define handle-output
    (match-lambda
     ((output . directory)
      (unless (member output qt-wrap-excluded-outputs)
        (let ((bin-list     (find-files-to-wrap directory))
              (vars-to-wrap (variables-for-wrapping
                             (append (list directory)
                                     input-directories))))
          (when (not (null? vars-to-wrap))
            (for-each (cut apply wrap-program <> vars-to-wrap)
                      bin-list)))))))

  (for-each handle-output outputs)
  #t)

(define %standard-phases
  (modify-phases cmake:%standard-phases
    (add-before 'check 'check-setup check-setup)
    (add-after 'install 'qt-wrap wrap-all-programs)))

(define* (qt-build #:key inputs (phases %standard-phases)
                   #:allow-other-keys #:rest args)
  "Build the given package, applying all of PHASES in order."
  (apply cmake:cmake-build #:inputs inputs #:phases phases args))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2016 David Craven <david@craven.ch>
;;;
;;; 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/>.

(define-module (guix build qt-utils)
  #:use-module (guix build utils)
  #:export (wrap-qt-program))

(define (wrap-qt-program out program)
  (define (suffix env-var path)
    (let ((env-val (getenv env-var)))
      (if env-val (string-append env-val ":" path) path)))

  (let ((qml-path        (suffix "QML2_IMPORT_PATH"
                                 (string-append out "/lib/qt5/qml")))
        (plugin-path     (suffix "QT_PLUGIN_PATH"
                                 (string-append out "/lib/qt5/plugins")))
        (xdg-data-path   (suffix "XDG_DATA_DIRS"
                                 (string-append out "/share")))
        (xdg-config-path (suffix "XDG_CONFIG_DIRS"
                                 (string-append out "/etc/xdg"))))
    (wrap-program (string-append out "/bin/" program)
      `("QML2_IMPORT_PATH" = (,qml-path))
      `("QT_PLUGIN_PATH" = (,plugin-path))
      `("XDG_DATA_DIRS" = (,xdg-data-path))
      `("XDG_CONFIG_DIRS" = (,xdg-config-path)))))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015, 2017, 2018 Ricardo Wurmus <rekado@elephly.net>
;;;
;;; 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/>.

(define-module (guix build r-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module (guix build utils)
  #:use-module (ice-9 match)
  #:use-module (ice-9 ftw)
  #:use-module (ice-9 popen)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-35)
  #:export (%standard-phases
            r-build))

;; Commentary:
;;
;; Builder-side code of the standard build procedure for R packages.
;;
;; Code:

(define (invoke-r command params)
  (apply invoke "R" "CMD" command params))

(define (pipe-to-r command params)
  (let ((port (apply open-pipe* OPEN_WRITE "R" params)))
    (display command port)
    (let ((code (status:exit-val (close-pipe port))))
      (unless (zero? code)
        (raise (condition ((@@ (guix build utils) &invoke-error)
                           (program "R")
                           (arguments (cons command params))
                           (exit-status (status:exit-val code))
                           (term-signal (status:term-sig code))
                           (stop-signal (status:stop-sig code)))))))))

(define (generate-site-path inputs)
  (string-join (map (match-lambda
                      ((_ . path)
                       (string-append path "/site-library")))
                    ;; Restrict to inputs beginning with "r-".
                    (filter (match-lambda
                              ((name . _)
                               (string-prefix? "r-" name)))
                            inputs))
               ":"))

(define* (check #:key test-target inputs outputs tests? #:allow-other-keys)
  "Run the test suite of a given R package."
  (let* ((libdir    (string-append (assoc-ref outputs "out") "/site-library/"))

         ;; R package names are case-sensitive and cannot be derived from the
         ;; Guix package name.  The exact package name is required as an
         ;; argument to ‘tools::testInstalledPackage’, which runs the tests
         ;; for a package given its name and the path to the “library” (a
         ;; location for a collection of R packages) containing it.

         ;; Since there can only be one R package in any collection (=
         ;; “library”), the name of the only directory in the collection path
         ;; is the original name of the R package.
         (pkg-name  (car (scandir libdir (negate (cut member <> '("." ".."))))))
         (testdir   (string-append libdir pkg-name "/" test-target))
         (site-path (string-append libdir ":" (generate-site-path inputs))))
    (when (and tests? (file-exists? testdir))
      (setenv "R_LIBS_SITE" site-path)
      (pipe-to-r (string-append "tools::testInstalledPackage(\"" pkg-name "\", "
                                "lib.loc = \"" libdir "\")")
                 '("--no-save" "--slave")))
    #t))

(define* (install #:key outputs inputs (configure-flags '())
                  #:allow-other-keys)
  "Install a given R package."
  (let* ((out          (assoc-ref outputs "out"))
         (site-library (string-append out "/site-library/"))
         (params       (append configure-flags
                               (list "--install-tests"
                                     (string-append "--library=" site-library)
                                     "--built-timestamp=1970-01-01"
                                     ".")))
         (site-path    (string-append site-library ":"
                                      (generate-site-path inputs))))
    ;; If dependencies cannot be found at install time, R will refuse to
    ;; install the package.
    (setenv "R_LIBS_SITE" site-path)
    ;; Some R packages contain a configure script for which the CONFIG_SHELL
    ;; variable should be set.
    (setenv "CONFIG_SHELL" (which "bash"))
    (mkdir-p site-library)
    (invoke-r "INSTALL" params)))

(define %standard-phases
  (modify-phases gnu:%standard-phases
    (delete 'bootstrap)
    (delete 'configure)
    (delete 'build)
    (delete 'check) ; tests must be run after installation
    (replace 'install install)
    (add-after 'install 'check check)))

(define* (r-build #:key inputs (phases %standard-phases)
                       #:allow-other-keys #:rest args)
  "Build the given R package, applying all of PHASES in order."
  (apply gnu:gnu-build #:inputs inputs #:phases phases args))

;;; r-build-system.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2019 Efraim Flashner <efraim@flashner.co.il>
;;;
;;; 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/>.

(define-module (guix build rakudo-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module (guix build utils)
  #:use-module (ice-9 ftw)
  #:use-module (ice-9 match)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:export (%standard-phases
            rakudo-build))

;; Commentary:
;;
;; Builder-side code of the standard Rakudo package build procedure.
;;
;; Code:

(define* (check #:key tests? inputs with-prove6? #:allow-other-keys)
  (if (and tests? (assoc-ref inputs "perl6-tap-harness"))
  ;(if (and tests? with-prove6?)
      (invoke "prove6" "-I=lib" "t/")
      (format #t "test suite not run~%"))
  #t)

(define* (install #:key inputs outputs with-zef? #:allow-other-keys)
  "Install a given Perl6 package."
  (let* ((out   (assoc-ref outputs "out"))
         (perl6 (string-append out "/share/perl6")))
    (if (assoc-ref inputs "perl6-zef")
    ;(if with-zef?
        (begin
          (let ((zef (string-append (assoc-ref inputs "perl6-zef")
                                    "/bin/zef")))
            (setenv "HOME" (getcwd))
            (mkdir-p perl6)
            (invoke zef "install" "--verbose" "."
                    ;; Don't install any of the following:
                    "--/depends" "--/build-depends" "--/test-depends"
                    (string-append "--install-to=" perl6))
            (delete-file (string-append perl6 "/repo.lock")))
          #t)
        (begin
          (let ((inst (string-append (assoc-ref inputs "rakudo")
                                     "/share/perl6/tools/install-dist.p6")))
            (setenv "RAKUDO_RERESOLVE_DEPENDENCIES" "0")
            (setenv "RAKUDO_MODULE_DEBUG" "1") ; be verbose while building
            (invoke inst (string-append "--to=" perl6) "--for=site"))))))

(define* (install-libs #:key outputs #:allow-other-keys)
  (let ((out  (assoc-ref outputs "out"))
        (lock "lib/.precomp/.lock"))
    (when (file-exists? lock)
      (delete-file "lib/.precomp/.lock"))
    (copy-recursively "lib" (string-append out "/share/perl6/lib"))
    #t))

(define* (install-bins #:key outputs #:allow-other-keys)
  (let ((out  (assoc-ref outputs "out")))
    (when (file-exists? "bin")
      (for-each (lambda (file)
                  (install-file file (string-append out "/bin"))
                  (chmod (string-append out "/" file) #o555))
                (find-files "bin" ".*")))
    (when (file-exists? "sbin")
      (for-each (lambda (file)
                  (install-file file (string-append out "/sbin"))
                  (chmod (string-append out "/" file) #o555))
                (find-files "sbin" ".*")))
    #t))

(define* (install-resources #:key outputs #:allow-other-keys)
  (let ((out  (assoc-ref outputs "out")))
    (when (file-exists? "resources")
      (copy-recursively "resources"
                        (string-append out "/share/perl6/resources")))
  #t))

(define* (wrap #:key inputs outputs #:allow-other-keys)
  (define (list-of-files dir)
    (map (cut string-append dir "/" <>)
         (or (scandir dir (lambda (f)
                            (let ((s (stat (string-append dir "/" f))))
                              (eq? 'regular (stat:type s)))))
             '())))

  (define bindirs
    (append-map (match-lambda
                 ((_ . dir)
                  (list (string-append dir "/bin")
                        (string-append dir "/sbin"))))
                outputs))

  (let* ((out  (assoc-ref outputs "out"))
         (var `("PERL6LIB" "," prefix
                ,(cons (string-append out "/share/perl6/lib,"
                                      out "/share/perl6/site/lib,"
                                      out "/share/perl6/vendor/lib")
                       (search-path-as-string->list
                        (or (getenv "PERL6LIB") "") #\,)))))
    (for-each (lambda (dir)
                (let ((files (list-of-files dir)))
                  (for-each (cut wrap-program <> var)
                            files)))
              bindirs)
    #t))

(define %standard-phases
  ;; No need for 'bootstrap, 'configure or 'build.
  (modify-phases gnu:%standard-phases
    (delete 'bootstrap)
    (delete 'configure)
    (delete 'build)
    (replace 'check check)
    (replace 'install install)
    (add-before 'install 'install-lib-dir install-libs)
    (add-after 'install-lib-dir 'install-resources install-resources)
    (add-after 'install-resources 'install-binaries install-bins)
    ;; needs to be after 'install-binaries and all 'install phases
    (add-after 'install 'wrap wrap)))

(define* (rakudo-build #:key inputs (phases %standard-phases)
                       #:allow-other-keys #:rest args)
  "Build the given Perl6 package, applying all of PHASES in order."
  (apply gnu:gnu-build
         #:inputs inputs #:phases phases
         args))

;;; rakudo-build-system.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015 David Thompson <davet@gnu.org>
;;; Copyright © 2015 Pjotr Prins <pjotr.public01@thebird.nl>
;;; Copyright © 2015, 2016 Ben Woodcroft <donttrustben@gmail.com>
;;; Copyright © 2020 Maxim Cournoyer <maxim.cournoyer@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/>.

(define-module (guix build ruby-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module (guix build utils)
  #:use-module (ice-9 ftw)
  #:use-module (ice-9 match)
  #:use-module (ice-9 popen)
  #:use-module (ice-9 rdelim)
  #:use-module (ice-9 regex)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:export (%standard-phases
            ruby-build))

;; Commentary:
;;
;; Builder-side code of the standard Ruby package build procedure.
;;
;; Code:

(define (first-matching-file pattern)
  "Return the first file name that matches PATTERN in the current working
directory."
  (match (find-files "." pattern)
    ((file-name . _) file-name)
    (() (error "No files matching pattern: " pattern))))

(define gnu:unpack (assq-ref gnu:%standard-phases 'unpack))

(define (gem-archive? file-name)
  (string-match "^.*\\.gem$" file-name))

(define* (unpack #:key source #:allow-other-keys)
  "Unpack the gem SOURCE and enter the resulting directory."
  (if (gem-archive? source)
      (begin
        (invoke "gem" "unpack" source)
        ;; The unpacked gem directory is named the same as the archive,
        ;; sans the ".gem" extension.  It is renamed to simply "gem" in an
        ;; effort to keep file names shorter to avoid UNIX-domain socket
        ;; file names and shebangs that exceed the system's fixed maximum
        ;; length when running test suites.
        (let ((dir (match:substring (string-match "^(.*)\\.gem$"
                                                  (basename source))
                                    1)))
          (rename-file dir "gem")
          (chdir "gem"))
        #t)
      ;; Use GNU unpack strategy for things that aren't gem archives.
      (gnu:unpack #:source source)))

(define (first-gemspec)
  (first-matching-file "\\.gemspec$"))

(define* (replace-git-ls-files #:key source #:allow-other-keys)
  "Many gemspec files downloaded from outside rubygems.org use `git ls-files`
to list the files to be included in the built gem.  However, since this
operation is not deterministic, we replace it with `find`."
  (unless (gem-archive? source)
    (let ((gemspec (first-gemspec)))
      ;; Do not include the freshly built .gem itself as it causes problems.
      ;; Strip the first 2 characters ("./") to more exactly match the output
      ;; given by 'git ls-files'.  This is useful to prevent breaking regexps
      ;; that could be used to filter the list of files.
      (substitute* gemspec
        (("`git ls-files`")
         "`find . -type f -not -regex '.*\\.gem$' | sort | cut -c3-`")
        (("`git ls-files -z`")
         "`find . -type f -not -regex '.*\\.gem$' -print0 | sort -z | cut -zc3-`"))))
  #t)

(define* (extract-gemspec #:key source #:allow-other-keys)
  "Remove the original gemspec, if present, and replace it with a new one.
This avoids issues with upstream gemspecs requiring tools such as git to
generate the files list."
  (if (gem-archive? source)
      (let ((gemspec (or (false-if-exception (first-gemspec))
                         ;; Make new gemspec if one wasn't shipped.
                         ".gemspec")))

        (when (file-exists? gemspec) (delete-file gemspec))

        ;; Extract gemspec from source gem.
        (let ((pipe (open-pipe* OPEN_READ "gem" "spec" "--ruby" source)))
          (dynamic-wind
            (const #t)
            (lambda ()
              (call-with-output-file gemspec
                (lambda (out)
                  ;; 'gem spec' writes to stdout, but 'gem build' only reads
                  ;; gemspecs from a file, so we redirect the output to a file.
                  (while (not (eof-object? (peek-char pipe)))
                    (write-char (read-char pipe) out))))
              #t)
            (lambda ()
              (close-pipe pipe)))))
      (display "extract-gemspec: skipping as source is not a gem archive\n"))
  #t)

(define* (build #:key source #:allow-other-keys)
  "Build a new gem using the gemspec from the SOURCE gem."

  ;; Build a new gem from the current working directory.  This also allows any
  ;; dynamic patching done in previous phases to be present in the installed
  ;; gem.
  (invoke "gem" "build" (first-gemspec)))

(define* (check #:key tests? test-target #:allow-other-keys)
  "Run the gem's test suite rake task TEST-TARGET.  Skip the tests if TESTS?
is #f."
  (if tests?
      (invoke "rake" test-target)
      #t))

(define* (install #:key inputs outputs (gem-flags '())
                  #:allow-other-keys)
  "Install the gem archive SOURCE to the output store item.  Additional
GEM-FLAGS are passed to the 'gem' invocation, if present."
  (let* ((out (assoc-ref outputs "out"))
         (vendor-dir (string-append out "/lib/ruby/vendor_ruby"))
         (gem-file (first-matching-file "\\.gem$"))
         (gem-file-basename (basename gem-file))
         (gem-name (substring gem-file-basename
                              0
                              (- (string-length gem-file-basename) 4)))
         (gem-dir (string-append vendor-dir "/gems/" gem-name)))
    (setenv "GEM_VENDOR" vendor-dir)

    (or (zero?
         ;; 'zero? system*' allows the custom error handling to function as
         ;; expected, while 'invoke' raises its own exception.
         (apply system* "gem" "install" gem-file
                "--verbose"
                "--local" "--ignore-dependencies" "--vendor"
                ;; Executables should go into /bin, not
                ;; /lib/ruby/gems.
                "--bindir" (string-append out "/bin")
                gem-flags))
        (begin
          (let ((failed-output-dir (string-append (getcwd) "/out")))
            (mkdir failed-output-dir)
            (copy-recursively out failed-output-dir))
          (error "installation failed")))

    ;; Remove the cached gem file as this is unnecessary and contains
    ;; timestamped files rendering builds not reproducible.
    (let ((cached-gem (string-append vendor-dir "/cache/" gem-file)))
      (log-file-deletion cached-gem)
      (delete-file cached-gem))

    ;; For gems with native extensions, several Makefile-related files
    ;; are created that contain timestamps or other elements making
    ;; them not reproducible.  They are unnecessary so we remove them.
    (when (file-exists? (string-append gem-dir "/ext"))
      (for-each (lambda (file)
                  (log-file-deletion file)
                  (delete-file file))
                (append
                 (find-files (string-append vendor-dir "/doc")
                             "page-Makefile.ri")
                 (find-files (string-append vendor-dir "/extensions")
                             "gem_make.out")
                 (find-files (string-append gem-dir "/ext")
                             "Makefile"))))

    #t))

(define* (wrap-ruby-program prog #:key (gem-clear-paths #t) #:rest vars)
  "Make a wrapper for PROG.  VARS should look like this:

  '(VARIABLE DELIMITER POSITION LIST-OF-DIRECTORIES)

where DELIMITER is optional.  ':' will be used if DELIMITER is not given.

For example, this command:

  (wrap-ruby-program \"foo\"
                '(\"PATH\" \":\" = (\"/gnu/.../bar/bin\"))
                '(\"CERT_PATH\" suffix (\"/gnu/.../baz/certs\"
                                        \"/qux/certs\")))

will copy 'foo' to '.real/fool' and create the file 'foo' with the following
contents:

  #!location/of/bin/ruby
  ENV['PATH'] = \"/gnu/.../bar/bin\"
  ENV['CERT_PATH'] = (ENV.key?('CERT_PATH') ? (ENV['CERT_PATH'] + ':') : '') + '/gnu/.../baz/certs:/qux/certs'
  load location/of/.real/foo

This is useful for scripts that expect particular programs to be in $PATH, for
programs that expect particular gems to be in the GEM_PATH.

This is preferable to wrap-program, which uses a bash script, as this prevents
ruby scripts from being executed with @command{ruby -S ...}.

If PROG has previously been wrapped by 'wrap-ruby-program', the wrapper is
extended with definitions for VARS."
  (define wrapped-file
    (string-append (dirname prog) "/.real/" (basename prog)))

  (define already-wrapped?
    (file-exists? wrapped-file))

  (define (last-line port)
    ;; Return the last line read from PORT and leave PORT's cursor right
    ;; before it.
    (let loop ((previous-line-offset 0)
               (previous-line "")
               (position (seek port 0 SEEK_CUR)))
      (match (read-line port 'concat)
        ((? eof-object?)
         (seek port previous-line-offset SEEK_SET)
         previous-line)
        ((? string? line)
         (loop position line (+ (string-length line) position))))))

  (define (export-variable lst)
    ;; Return a string that exports an environment variable.
    (match lst
      ((var sep '= rest)
       (format #f "ENV['~a'] = '~a'"
               var (string-join rest sep)))
      ((var sep 'prefix rest)
       (format #f "ENV['~a'] = '~a' + (ENV.key?('~a') ? ('~a' + ENV['~a']) : '')"
               var (string-join rest sep) var sep var))
      ((var sep 'suffix rest)
       (format #f "ENV['~a'] = (ENV.key?('~a') ? (ENV['~a'] + '~a') : '') + '~a'"
               var var var sep (string-join rest sep)))
      ((var '= rest)
       (format #f "ENV['~a'] = '~a'"
               var (string-join rest ":")))
      ((var 'prefix rest)
       (format #f "ENV['~a'] = '~a' + (ENV.key?('~a') ? (':' + ENV['~a']) : '')"
               var (string-join rest ":") var var))
      ((var 'suffix rest)
       (format #f "ENV['~a'] = (ENV.key?('~a') ? (ENV['~a'] + ':') : '') + '~a'"
               var var var (string-join rest ":")))))

  (if already-wrapped?

      ;; PROG is already a wrapper: add the new "export VAR=VALUE" lines just
      ;; before the last line.
      (let* ((port (open-file prog "r+"))
             (last (last-line port)))
        (for-each (lambda (var)
                    (display (export-variable var) port)
                    (newline port))
                  vars)
        (display last port)
        (close-port port))

      ;; PROG is not wrapped yet: create a shell script that sets VARS.
      (let ((prog-tmp (string-append wrapped-file "-tmp")))
        (mkdir-p (dirname prog-tmp))
        (link prog wrapped-file)

        (call-with-output-file prog-tmp
          (lambda (port)
            (format port
                    "#!~a~%~a~%~a~%load '~a'~%"
                    (which "ruby")
                    (string-join (map export-variable vars) "\n")
                    ;; This ensures that if the GEM_PATH has been changed,
                    ;; then that change will be noticed.
                    (if gem-clear-paths "Gem.clear_paths" "")
                    (canonicalize-path wrapped-file))))

        (chmod prog-tmp #o755)
        (rename-file prog-tmp prog))))

(define* (wrap #:key inputs outputs #:allow-other-keys)
  (define (list-of-files dir)
    (map (cut string-append dir "/" <>)
         (or (scandir dir (lambda (f)
                            (let ((s (stat (string-append dir "/" f))))
                              (eq? 'regular (stat:type s)))))
             '())))

  (define bindirs
    (append-map (match-lambda
                 ((_ . dir)
                  (list (string-append dir "/bin")
                        (string-append dir "/sbin"))))
                outputs))

  (let* ((out  (assoc-ref outputs "out"))
         (var `("GEM_PATH" prefix
                (,(string-append out "/lib/ruby/vendor_ruby")
                 ,(getenv "GEM_PATH")))))
    (for-each (lambda (dir)
                (let ((files (list-of-files dir)))
                  (for-each (cut wrap-ruby-program <> var)
                            files)))
              bindirs))
  #t)

(define (log-file-deletion file)
  (display (string-append "deleting '" file "' for reproducibility\n")))

(define %standard-phases
  (modify-phases gnu:%standard-phases
    (delete 'bootstrap)
    (delete 'configure)
    (replace 'unpack unpack)
    (add-before 'build 'extract-gemspec extract-gemspec)
    (add-after 'extract-gemspec 'replace-git-ls-files replace-git-ls-files)
    (replace 'build build)
    (replace 'check check)
    (replace 'install install)
    (add-after 'install 'wrap wrap)))

(define* (ruby-build #:key inputs (phases %standard-phases)
                     #:allow-other-keys #:rest args)
  (apply gnu:gnu-build #:inputs inputs #:phases phases args))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2017 Arun Isaac <arunisaac@systemreboot.net>
;;; Copyright © 2018 Mark H Weaver <mhw@netris.org>
;;;
;;; 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/>.

(define-module (guix build scons-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module (guix build utils)
  #:export (%standard-phases
            scons-build))

;; Commentary:
;;
;; Builder-side code of the SCons build system.
;;
;; Code:

(define* (build #:key outputs (build-targets '()) (scons-flags '()) (parallel-build? #t) #:allow-other-keys)
  (let ((out (assoc-ref outputs "out")))
    (mkdir-p out)
    (apply invoke "scons"
           (append (if parallel-build?
                       (list "-j" (number->string
                                   (parallel-job-count)))
                       (list))
                   scons-flags
                   build-targets))))

(define* (check #:key tests? test-target (scons-flags '()) #:allow-other-keys)
  "Run the test suite of a given SCons application."
  (if tests?
      (apply invoke "scons" test-target scons-flags)
      (format #t "test suite not run~%"))
  #t)

(define* (install #:key outputs (install-targets '("install")) (scons-flags '()) #:allow-other-keys)
  "Install a given SCons application."
  (apply invoke "scons" (append scons-flags install-targets)))

(define %standard-phases
  (modify-phases gnu:%standard-phases
    (delete 'bootstrap)
    (delete 'configure)
    (replace 'build build)
    (replace 'check check)
    (replace 'install install)))

(define* (scons-build #:key inputs (phases %standard-phases)
                       #:allow-other-keys #:rest args)
  "Build a given SCons application, applying all of PHASES in order."
  (apply gnu:gnu-build #:inputs inputs #:phases phases args))

;;; scons-build-system.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2014, 2017, 2018 Ludovic Courtès <ludo@gnu.org>
;;;
;;; 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/>.

(define-module (guix build store-copy)
  #:use-module (guix build utils)
  #:use-module (guix sets)
  #:use-module (guix progress)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-26)
  #:use-module (ice-9 match)
  #:use-module (ice-9 rdelim)
  #:use-module (ice-9 ftw)
  #:use-module (ice-9 vlist)
  #:export (store-info?
            store-info
            store-info-item
            store-info-deriver
            store-info-references

            read-reference-graph

            file-size
            closure-size
            populate-store))

;;; Commentary:
;;;
;;; This module provides the tools to copy store items and their dependencies
;;; to another store.  It relies on the availability of "reference graph"
;;; files as produced by 'gexp->derivation' et al. with the
;;; #:references-graphs parameter.
;;;
;;; Code:

;; Information about a store item as produced by #:references-graphs.
(define-record-type <store-info>
  (store-info item deriver references)
  store-info?
  (item        store-info-item)                   ;string
  (deriver     store-info-deriver)                ;#f | string
  (references  store-info-references))            ;?

;; TODO: Factorize with that in (guix store).
(define (topological-sort nodes edges)
  "Return NODES in topological order according to EDGES.  EDGES must be a
one-argument procedure that takes a node and returns the nodes it is connected
to."
  (define (traverse)
    ;; Do a simple depth-first traversal of all of PATHS.
    (let loop ((nodes nodes)
               (visited (setq))
               (result '()))
      (match nodes
        ((head tail ...)
         (if (set-contains? visited head)
             (loop tail visited result)
             (call-with-values
                 (lambda ()
                   (loop (edges head)
                         (set-insert head visited)
                         result))
               (lambda (visited result)
                 (loop tail visited (cons head result))))))
        (()
         (values visited result)))))

  (call-with-values traverse
    (lambda (_ result)
      (reverse result))))

(define (read-reference-graph port)
  "Read the reference graph as produced by #:references-graphs from PORT and
return it as a list of <store-info> records in topological order--i.e., leaves
come first.  IOW, store items in the resulting list can be registered in the
order in which they appear.

The reference graph format consists of sequences of lines like this:

     FILE
     DERIVER
     NUMBER-OF-REFERENCES
     REF1
     ...
     REFN

It is meant as an internal format."
  (let loop ((result '())
             (table vlist-null)
             (referrers vlist-null))
    (match (read-line port)
      ((? eof-object?)
       ;; 'guix-daemon' gives us something that's in "reverse topological
       ;; order"--i.e., leaves (items with zero references) come last.  Here
       ;; we compute the topological order that we want: leaves come first.
       (let ((unreferenced? (lambda (item)
                              (let ((referrers (vhash-fold* cons '()
                                                            (store-info-item item)
                                                            referrers)))
                                (or (null? referrers)
                                    (equal? (list item) referrers))))))
         (topological-sort (filter unreferenced? result)
                           (lambda (item)
                             (map (lambda (item)
                                    (match (vhash-assoc item table)
                                      ((_ . node) node)))
                                  (store-info-references item))))))
      (item
       (let* ((deriver (match (read-line port)
                         ("" #f)
                         (line line)))
              (count   (string->number (read-line port)))
              (refs    (unfold-right (cut >= <> count)
                                     (lambda (n)
                                       (read-line port))
                                     1+
                                     0))
              (item    (store-info item deriver refs)))
         (loop (cons item result)
               (vhash-cons (store-info-item item) item table)
               (fold (cut vhash-cons <> item <>)
                     referrers
                     refs)))))))

(define (file-size file)
  "Return the size of bytes of FILE, entering it if FILE is a directory."
  (file-system-fold (const #t)
                    (lambda (file stat result)    ;leaf
                      (+ (stat:size stat) result))
                    (lambda (directory stat result) ;down
                      (+ (stat:size stat) result))
                    (lambda (directory stat result) ;up
                      result)
                    (lambda (file stat result)    ;skip
                      result)
                    (lambda (file stat errno result)
                      (format (current-error-port)
                              "file-size: ~a: ~a~%" file
                              (strerror errno))
                      result)
                    0
                    file
                    lstat))

(define (closure-size reference-graphs)
  "Return an estimate of the size of the closure described by
REFERENCE-GRAPHS, a list of reference-graph files."
  (define (graph-from-file file)
    (map store-info-item
         (call-with-input-file file read-reference-graph)))

  (define items
    (delete-duplicates (append-map graph-from-file reference-graphs)))

  (reduce + 0 (map file-size items)))

(define (reset-permissions file)
  "Reset the permissions on FILE and its sub-directories so that they are all
read-only."
  ;; XXX: This procedure exists just to work around the inability of
  ;; 'copy-recursively' to preserve permissions.
  (file-system-fold (const #t)                    ;enter?
                    (lambda (file stat _)         ;leaf
                      (unless (eq? 'symlink (stat:type stat))
                        (chmod file
                               (if (zero? (logand (stat:mode stat)
                                                  #o100))
                                   #o444
                                   #o555))))
                    (const #t)                    ;down
                    (lambda (directory stat _)    ;up
                      (chmod directory #o555))
                    (const #f)                    ;skip
                    (const #f)                    ;error
                    #t
                    file
                    lstat))

(define* (populate-store reference-graphs target
                         #:key (log-port (current-error-port)))
  "Populate the store under directory TARGET with the items specified in
REFERENCE-GRAPHS, a list of reference-graph files."
  (define store
    (string-append target (%store-directory)))

  (define (things-to-copy)
    ;; Return the list of store files to copy to the image.
    (define (graph-from-file file)
      (map store-info-item
           (call-with-input-file file read-reference-graph)))

    (delete-duplicates (append-map graph-from-file reference-graphs)))

  (mkdir-p store)
  (chmod store #o1775)

  (let* ((things   (things-to-copy))
         (len      (length things))
         (progress (progress-reporter/bar len
                                          (format #f "copying ~a store items"
                                                  len)
                                          log-port)))
    (call-with-progress-reporter progress
      (lambda (report)
        (for-each (lambda (thing)
                    (copy-recursively thing
                                      (string-append target thing)
                                      #:keep-mtime? #t
                                      #:log (%make-void-port "w"))

                    ;; XXX: Since 'copy-recursively' doesn't allow us to
                    ;; preserve permissions, we have to traverse TARGET to
                    ;; make sure everything is read-only.
                    (reset-permissions (string-append target thing))
                    (report))
                  things)))))

;;; store-copy.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2014 Sree Harsha Totakura <sreeharsha@totakura.in>
;;; Copyright © 2018 Mark H Weaver <mhw@netris.org>
;;;
;;; 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/>.

(define-module (guix build svn)
  #:use-module (guix build utils)
  #:export (svn-fetch))

;;; Commentary:
;;;
;;; This is the build-side support code of (guix svn-download).  It allows a
;;; Subversion repository to be cloned and checked out at a specific revision.
;;;
;;; Code:

(define* (svn-fetch url revision directory
                    #:key (svn-command "svn")
                    (recursive? #t)
                    (user-name #f)
                    (password #f))
  "Fetch REVISION from URL into DIRECTORY.  REVISION must be an integer, and a
valid Subversion revision.  Return #t on success, #f otherwise."
  (apply invoke svn-command
         "export" "--non-interactive"
         ;; Trust the server certificate.  This is OK as we
         ;; verify the checksum later.  This can be removed when
         ;; ca-certificates package is added.
         "--trust-server-cert" "-r" (number->string revision)
         `(,@(if (and user-name password)
                 (list (string-append "--username=" user-name)
                       (string-append "--password=" password))
                 '())
           ,@(if recursive?
                 '()
                 (list "--ignore-externals"))
           ,url ,directory))
  #t)

;;; svn.scm ends here