code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2012, 2013, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2016 Jelle Licht <jlicht@fsfe.org>
;;; Copyright © 2016 David Craven <david@craven.ch>
;;; Copyright © 2017, 2019, 2020 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2018 Oleg Pykhalov <go.wigust@gmail.com>
;;; Copyright © 2019 Robert Vollmert <rob@vllmrt.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 import utils)
  #:use-module (guix base32)
  #:use-module ((guix build download) #:prefix build:)
  #:use-module ((gcrypt hash) #:hide (sha256))
  #:use-module (guix http-client)
  #:use-module ((guix licenses) #:prefix license:)
  #:use-module (guix utils)
  #:use-module (guix packages)
  #:use-module (guix discovery)
  #:use-module (guix build-system)
  #:use-module (guix gexp)
  #:use-module (guix store)
  #:use-module (guix download)
  #:use-module (guix sets)
  #:use-module (gnu packages)
  #:use-module (ice-9 match)
  #:use-module (ice-9 rdelim)
  #:use-module (ice-9 receive)
  #:use-module (ice-9 regex)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-26)
  #:export (factorize-uri

            flatten

            url-fetch
            guix-hash-url

            package-names->package-inputs
            maybe-inputs
            maybe-native-inputs
            package->definition

            spdx-string->license
            license->symbol

            snake-case
            beautify-description

            alist->package

            read-lines
            chunk-lines

            guix-name

            recursive-import))

(define (factorize-uri uri version)
  "Factorize URI, a package tarball URI as a string, such that any occurrences
of the string VERSION is replaced by the symbol 'version."
  (let ((version-rx (make-regexp (regexp-quote version))))
    (match (regexp-exec version-rx uri)
      (#f
       uri)
      (_
       (let ((indices (fold-matches version-rx uri
                                    '((0))
                                    (lambda (m result)
                                      (match result
                                        (((start) rest ...)
                                         `((,(match:end m))
                                           (,start . ,(match:start m))
                                           ,@rest)))))))
         (fold (lambda (index result)
                 (match index
                   ((start)
                    (cons (substring uri start)
                          result))
                   ((start . end)
                    (cons* (substring uri start end)
                           'version
                           result))))
               '()
               indices))))))

(define (flatten lst)
  "Return a list that recursively concatenates all sub-lists of LST."
  (fold-right
   (match-lambda*
    (((sub-list ...) memo)
     (append (flatten sub-list) memo))
    ((elem memo)
     (cons elem memo)))
   '() lst))

(define (url-fetch url file-name)
  "Save the contents of URL to FILE-NAME.  Return #f on failure."
  (parameterize ((current-output-port (current-error-port)))
    (build:url-fetch url file-name)))

(define (guix-hash-url filename)
  "Return the hash of FILENAME in nix-base32 format."
  (bytevector->nix-base32-string (file-sha256 filename)))

(define (spdx-string->license str)
  "Convert STR, a SPDX formatted license identifier, to a license object.
   Return #f if STR does not match any known identifiers."
  ;; https://spdx.org/licenses/
  ;; The psfl, gfl1.0, nmap, repoze
  ;; licenses doesn't have SPDX identifiers
  (match str
    ("AGPL-1.0"                    'license:agpl-1.0)
    ("AGPL-3.0"                    'license:agpl-3.0)
    ("Apache-1.1"                  'license:asl1.1)
    ("Apache-2.0"                  'license:asl2.0)
    ("BSL-1.0"                     'license:boost1.0)
    ("BSD-2-Clause-FreeBSD"        'license:bsd-2)
    ("BSD-3-Clause"                'license:bsd-3)
    ("BSD-4-Clause"                'license:bsd-4)
    ("CC0-1.0"                     'license:cc0)
    ("CC-BY-2.0"                   'license:cc-by2.0)
    ("CC-BY-3.0"                   'license:cc-by3.0)
    ("CC-BY-SA-2.0"                'license:cc-by-sa2.0)
    ("CC-BY-SA-3.0"                'license:cc-by-sa3.0)
    ("CC-BY-SA-4.0"                'license:cc-by-sa4.0)
    ("CDDL-1.0"                    'license:cddl1.0)
    ("CECILL-C"                    'license:cecill-c)
    ("Artistic-2.0"                'license:artistic2.0)
    ("ClArtistic"                  'license:clarified-artistic)
    ("CPL-1.0"                     'license:cpl1.0)
    ("EPL-1.0"                     'license:epl1.0)
    ("MIT"                         'license:expat)
    ("FTL"                         'license:freetype)
    ("GFDL-1.1"                    'license:fdl1.1+)
    ("GFDL-1.2"                    'license:fdl1.2+)
    ("GFDL-1.3"                    'license:fdl1.3+)
    ("Giftware"                    'license:giftware)
    ("GPL-1.0"                     'license:gpl1)
    ("GPL-1.0+"                    'license:gpl1+)
    ("GPL-2.0"                     'license:gpl2)
    ("GPL-2.0+"                    'license:gpl2+)
    ("GPL-3.0"                     'license:gpl3)
    ("GPL-3.0+"                    'license:gpl3+)
    ("ISC"                         'license:isc)
    ("IJG"                         'license:ijg)
    ("Imlib2"                      'license:imlib2)
    ("IPA"                         'license:ipa)
    ("IPL-1.0"                     'license:ibmpl1.0)
    ("LGPL-2.0"                    'license:lgpl2.0)
    ("LGPL-2.0+"                   'license:lgpl2.0+)
    ("LGPL-2.1"                    'license:lgpl2.1)
    ("LGPL-2.1+"                   'license:lgpl2.1+)
    ("LGPL-3.0"                    'license:lgpl3.0)
    ("LGPL-3.0+"                   'license:lgpl3.0+)
    ("MPL-1.0"                     'license:mpl1.0)
    ("MPL-1.1"                     'license:mpl1.1)
    ("MPL-2.0"                     'license:mpl2.0)
    ("MS-PL"                       'license:ms-pl)
    ("NCSA"                        'license:ncsa)
    ("OpenSSL"                     'license:openssl)
    ("OLDAP-2.8"                   'license:openldap2.8)
    ("CUA-OPL-1.0"                 'license:opl1.0)
    ("QPL-1.0"                     'license:qpl)
    ("Ruby"                        'license:ruby)
    ("SGI-B-2.0"                   'license:sgifreeb2.0)
    ("OFL-1.1"                     'license:silofl1.1)
    ("Sleepycat"                   'license:sleepycat)
    ("TCL"                         'license:tcl/tk)
    ("Unlicense"                   'license:unlicense)
    ("Vim"                         'license:vim)
    ("X11"                         'license:x11)
    ("ZPL-2.1"                     'license:zpl2.1)
    ("Zlib"                        'license:zlib)
    (_ #f)))

(define (license->symbol license)
  "Convert license to a symbol representing the variable the object is bound
to in the (guix licenses) module, or #f if there is no such known license."
  (define licenses
    (module-map (lambda (sym var) `(,(variable-ref var) . ,sym))
                (resolve-interface '(guix licenses) #:prefix 'license:)))
  (assoc-ref licenses license))

(define (snake-case str)
  "Return a downcased version of the string STR where underscores are replaced
with dashes."
  (string-join (string-split (string-downcase str) #\_) "-"))

(define (beautify-description description)
  "Improve the package DESCRIPTION by turning a beginning sentence fragment
into a proper sentence and by using two spaces between sentences."
  (let ((cleaned (cond
                  ((string-prefix? "A " description)
                   (string-append "This package provides a"
                                  (substring description 1)))
                  ((string-prefix? "Provides " description)
                   (string-append "This package provides"
                                  (substring description
                                             (string-length "Provides"))))
                  ((string-prefix? "Functions " description)
                   (string-append "This package provides functions"
                                  (substring description
                                             (string-length "Functions"))))
                  (else description))))
    ;; Use double spacing between sentences
    (regexp-substitute/global #f "\\. \\b"
                              cleaned 'pre ".  " 'post)))

(define* (package-names->package-inputs names #:optional (output #f))
  "Given a list of PACKAGE-NAMES, and an optional OUTPUT, tries to generate a
quoted list of inputs, as suitable to use in an 'inputs' field of a package
definition."
  (map (lambda (input)
         (cons* input (list 'unquote (string->symbol input))
                            (or (and output (list output))
                                '())))
       names))

(define* (maybe-inputs package-names #:optional (output #f))
  "Given a list of PACKAGE-NAMES, tries to generate the 'inputs' field of a
package definition."
  (match (package-names->package-inputs package-names output)
    (()
     '())
    ((package-inputs ...)
     `((inputs (,'quasiquote ,package-inputs))))))

(define* (maybe-native-inputs package-names #:optional (output #f))
  "Given a list of PACKAGE-NAMES, tries to generate the 'inputs' field of a
package definition."
  (match (package-names->package-inputs package-names output)
    (()
     '())
    ((package-inputs ...)
     `((native-inputs (,'quasiquote ,package-inputs))))))

(define (package->definition guix-package)
  (match guix-package
    (('package ('name (? string? name)) _ ...)
     `(define-public ,(string->symbol name)
        ,guix-package))
    (('let anything ('package ('name (? string? name)) _ ...))
     `(define-public ,(string->symbol name)
        ,guix-package))))

(define (build-system-modules)
  (all-modules (map (lambda (entry)
                      `(,entry . "guix/build-system"))
                    %load-path)))

(define (lookup-build-system-by-name name)
  "Return a <build-system> value for the symbol NAME, representing the name of
the build system."
  (fold-module-public-variables (lambda (obj result)
                                  (if (and (build-system? obj)
                                           (eq? name (build-system-name obj)))
                                      obj result))
                                #f
                                (build-system-modules)))

(define (specs->package-lists specs)
  "Convert each string in the SPECS list to a list of a package label and a
package value."
  (map (lambda (spec)
         (let-values (((pkg out) (specification->package+output spec)))
           (match out
             ("out" (list (package-name pkg) pkg))
             (_ (list (package-name pkg) pkg out)))))
       specs))

(define (source-spec->object source)
  "Generate an <origin> object from a SOURCE specification.  The SOURCE can
either be a simple URL string, #F, or an alist containing entries for each of
the expected fields of an <origin> object."
  (match source
    ((? string? source-url)
     (let ((tarball (with-store store (download-to-store store source-url))))
       (origin
         (method url-fetch)
         (uri source-url)
         (sha256 (base32 (guix-hash-url tarball))))))
    (#f #f)
    (orig (let ((sha (match (assoc-ref orig "sha256")
                       ((("base32" . value))
                        (base32 value))
                       (_ #f))))
            (origin
              (method (match (assoc-ref orig "method")
                        ("url-fetch" (@ (guix download) url-fetch))
                        ("git-fetch" (@ (guix git-download) git-fetch))
                        ("svn-fetch" (@ (guix svn-download) svn-fetch))
                        ("hg-fetch"  (@ (guix hg-download) hg-fetch))
                        (_ #f)))
              (uri (assoc-ref orig "uri"))
              (sha256 sha))))))

(define* (alist->package meta #:optional (known-inputs '()))
  "Return a package value generated from the alist META.  If the list of
strings KNOWN-INPUTS is provided, do not treat the mentioned inputs as
specifications to look up and replace them with plain symbols instead."
  (define (process-inputs which)
    (let-values (((regular known)
                  (lset-diff+intersection
                   string=?
                   (vector->list (or (assoc-ref meta which) #()))
                   known-inputs)))
      (append (specs->package-lists regular)
              (map string->symbol known))))
  (define (process-arguments arguments)
    (append-map (match-lambda
                  ((key . value)
                   (list (symbol->keyword (string->symbol key)) value)))
                arguments))
  (package
    (name (assoc-ref meta "name"))
    (version (assoc-ref meta "version"))
    (source (source-spec->object (assoc-ref meta "source")))
    (build-system
      (lookup-build-system-by-name
       (string->symbol (assoc-ref meta "build-system"))))
    (arguments
     (or (and=> (assoc-ref meta "arguments")
                process-arguments)
         '()))
    (native-inputs (process-inputs "native-inputs"))
    (inputs (process-inputs "inputs"))
    (propagated-inputs (process-inputs "propagated-inputs"))
    (home-page
     (assoc-ref meta "home-page"))
    (synopsis
     (assoc-ref meta "synopsis"))
    (description
     (assoc-ref meta "description"))
    (license
     (match (assoc-ref meta "license")
       (#f #f)
       (l
        (or (module-ref (resolve-interface '(guix licenses) #:prefix 'license:)
                        (spdx-string->license l))
            (license:fsdg-compatible l)))))))

(define* (read-lines #:optional (port (current-input-port)))
  "Read lines from PORT and return them as a list."
  (let loop ((line (read-line port))
             (lines '()))
    (if (eof-object? line)
        (reverse lines)
        (loop (read-line port)
              (cons line lines)))))

(define* (chunk-lines lines #:optional (pred string-null?))
  "Return a list of chunks, each of which is a list of lines.  The chunks are
separated by PRED."
  (let loop ((rest lines)
             (parts '()))
    (receive (before after)
        (break pred rest)
      (let ((res (cons before parts)))
        (if (null? after)
            (reverse res)
            (loop (cdr after) res))))))

(define (guix-name prefix name)
  "Return a Guix package name for a given package name."
  (string-append prefix (string-map (match-lambda
                                      (#\_ #\-)
                                      (#\. #\-)
                                      (chr (char-downcase chr)))
                                    name)))

(define (topological-sort nodes
                          node-dependencies
                          node-name)
  "Perform a breadth-first traversal of the graph rooted at NODES, a list of
nodes, and return the list of nodes sorted in topological order.  Call
NODE-DEPENDENCIES to obtain the dependencies of a node, and NODE-NAME to
obtain a node's uniquely identifying \"key\"."
  (let loop ((nodes nodes)
             (result '())
             (visited (set)))
    (match nodes
      (()
       result)
      ((head . tail)
       (if (set-contains? visited (node-name head))
           (loop tail result visited)
           (let ((dependencies (node-dependencies head)))
             (loop (append dependencies tail)
                   (cons head result)
                   (set-insert (node-name head) visited))))))))

(define* (recursive-import package-name repo
                           #:key repo->guix-package guix-name
                           #:allow-other-keys)
  "Return a list of package expressions for PACKAGE-NAME and all its
dependencies, sorted in topological order.  For each package,
call (REPO->GUIX-PACKAGE NAME REPO), which should return a package expression
and a list of dependencies; call (GUIX-NAME NAME) to obtain the Guix package
name corresponding to the upstream name."
  (define-record-type <node>
    (make-node name package dependencies)
    node?
    (name         node-name)
    (package      node-package)
    (dependencies node-dependencies))

  (define (exists? name)
    (not (null? (find-packages-by-name (guix-name name)))))

  (define (lookup-node name)
    (receive (package dependencies) (repo->guix-package name repo)
      (make-node name package dependencies)))

  (map node-package
       (topological-sort (list (lookup-node package-name))
                         (lambda (node)
                           (map lookup-node
                                (remove exists?
                                        (node-dependencies node))))
                         node-name)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 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 inferior)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-9 gnu)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module ((guix diagnostics)
                #:select (source-properties->location))
  #:use-module ((guix utils)
                #:select (%current-system
                          call-with-temporary-directory
                          version>? version-prefix?
                          cache-directory))
  #:use-module ((guix store)
                #:select (store-connection-socket
                          store-connection-major-version
                          store-connection-minor-version
                          store-lift
                          &store-protocol-error))
  #:use-module ((guix derivations)
                #:select (read-derivation-from-file))
  #:use-module (guix gexp)
  #:use-module (guix search-paths)
  #:use-module (guix profiles)
  #:use-module (guix channels)
  #:use-module (guix monads)
  #:use-module (guix store)
  #:use-module (guix derivations)
  #:use-module (guix base32)
  #:use-module (gcrypt hash)
  #:autoload   (guix cache) (maybe-remove-expired-cache-entries
                             file-expiration-time)
  #:autoload   (guix ui) (show-what-to-build*)
  #:autoload   (guix build utils) (mkdir-p)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:autoload   (ice-9 ftw) (scandir)
  #:use-module (ice-9 match)
  #:use-module (ice-9 popen)
  #:use-module (ice-9 vlist)
  #:use-module (ice-9 binary-ports)
  #:use-module ((rnrs bytevectors) #:select (string->utf8))
  #:export (inferior?
            open-inferior
            port->inferior
            close-inferior
            inferior-eval
            inferior-eval-with-store
            inferior-object?
            inferior-exception?
            inferior-exception-arguments
            inferior-exception-inferior
            inferior-exception-stack
            read-repl-response

            inferior-packages
            inferior-available-packages
            lookup-inferior-packages

            inferior-package?
            inferior-package-name
            inferior-package-version
            inferior-package-synopsis
            inferior-package-description
            inferior-package-home-page
            inferior-package-location
            inferior-package-inputs
            inferior-package-native-inputs
            inferior-package-propagated-inputs
            inferior-package-transitive-propagated-inputs
            inferior-package-native-search-paths
            inferior-package-transitive-native-search-paths
            inferior-package-search-paths
            inferior-package-provenance
            inferior-package-derivation

            inferior-package->manifest-entry

            gexp->derivation-in-inferior

            %inferior-cache-directory
            cached-channel-instance
            inferior-for-channels))

;;; Commentary:
;;;
;;; This module provides a way to spawn Guix "inferior" processes and to talk
;;; to them.  It allows us, from one instance of Guix, to interact with
;;; another instance of Guix coming from a different commit.
;;;
;;; Code:

;; Inferior Guix process.
(define-record-type <inferior>
  (inferior pid socket close version packages table)
  inferior?
  (pid      inferior-pid)
  (socket   inferior-socket)
  (close    inferior-close-socket)               ;procedure
  (version  inferior-version)                    ;REPL protocol version
  (packages inferior-package-promise)            ;promise of inferior packages
  (table    inferior-package-table))             ;promise of vhash

(define* (inferior-pipe directory command error-port)
  "Return an input/output pipe on the Guix instance in DIRECTORY.  This runs
'DIRECTORY/COMMAND repl' if it exists, or falls back to some other method if
it's an old Guix."
  (let ((pipe (with-error-to-port error-port
                (lambda ()
                  (open-pipe* OPEN_BOTH
                              (string-append directory "/" command)
                              "repl" "-t" "machine")))))
    (if (eof-object? (peek-char pipe))
        (begin
          (close-pipe pipe)

          ;; Older versions of Guix didn't have a 'guix repl' command, so
          ;; emulate it.
          (with-error-to-port error-port
            (lambda ()
              (open-pipe* OPEN_BOTH "guile"
                          "-L" (string-append directory "/share/guile/site/"
                                              (effective-version))
                          "-C" (string-append directory "/share/guile/site/"
                                              (effective-version))
                          "-C" (string-append directory "/lib/guile/"
                                              (effective-version) "/site-ccache")
                          "-c"
                          (object->string
                           `(begin
                              (primitive-load ,(search-path %load-path
                                                            "guix/repl.scm"))
                              ((@ (guix repl) machine-repl))))))))
        pipe)))

(define* (port->inferior pipe #:optional (close close-port))
  "Given PIPE, an input/output port, return an inferior that talks over PIPE.
PIPE is closed with CLOSE when 'close-inferior' is called on the returned
inferior."
  (setvbuf pipe 'line)

  (match (read pipe)
    (('repl-version 0 rest ...)
     (letrec ((result (inferior 'pipe pipe close (cons 0 rest)
                                (delay (%inferior-packages result))
                                (delay (%inferior-package-table result)))))

       ;; For protocol (0 1) and later, send the protocol version we support.
       (match rest
         ((n _ ...)
          (when (>= n 1)
            (send-inferior-request '(() repl-version 0 1 1) result)))
         (_
          #t))

       (inferior-eval '(use-modules (guix)) result)
       (inferior-eval '(use-modules (gnu)) result)
       (inferior-eval '(use-modules (ice-9 match)) result)
       (inferior-eval '(use-modules (srfi srfi-34)) result)
       (inferior-eval '(define %package-table (make-hash-table))
                      result)
       result))
    (_
     #f)))

(define* (open-inferior directory
                        #:key (command "bin/guix")
                        (error-port (%make-void-port "w")))
  "Open the inferior Guix in DIRECTORY, running 'DIRECTORY/COMMAND repl' or
equivalent.  Return #f if the inferior could not be launched."
  (define pipe
    (inferior-pipe directory command error-port))

  (port->inferior pipe close-pipe))

(define (close-inferior inferior)
  "Close INFERIOR."
  (let ((close (inferior-close-socket inferior)))
    (close (inferior-socket inferior))))

;; Non-self-quoting object of the inferior.
(define-record-type <inferior-object>
  (inferior-object address appearance)
  inferior-object?
  (address     inferior-object-address)
  (appearance  inferior-object-appearance))

(define (write-inferior-object object port)
  (match object
    (($ <inferior-object> _ appearance)
     (format port "#<inferior-object ~a>" appearance))))

(set-record-type-printer! <inferior-object> write-inferior-object)

;; Reified exception thrown by an inferior.
(define-condition-type &inferior-exception &error
  inferior-exception?
  (arguments  inferior-exception-arguments)       ;key + arguments
  (inferior   inferior-exception-inferior)        ;<inferior> | #f
  (stack      inferior-exception-stack))          ;list of (FILE COLUMN LINE)

(define* (read-repl-response port #:optional inferior)
  "Read a (guix repl) response from PORT and return it as a Scheme object.
Raise '&inferior-exception' when an exception is read from PORT."
  (define sexp->object
    (match-lambda
      (('value value)
       value)
      (('non-self-quoting address string)
       (inferior-object address string))))

  (match (read port)
    (('values objects ...)
     (apply values (map sexp->object objects)))
    (('exception ('arguments key objects ...)
                 ('stack frames ...))
     ;; Protocol (0 1 1) and later.
     (raise (condition (&inferior-exception
                        (arguments (cons key (map sexp->object objects)))
                        (inferior inferior)
                        (stack frames)))))
    (('exception key objects ...)
     ;; Protocol (0 0).
     (raise (condition (&inferior-exception
                        (arguments (cons key (map sexp->object objects)))
                        (inferior inferior)
                        (stack '())))))))

(define (read-inferior-response inferior)
  (read-repl-response (inferior-socket inferior)
                      inferior))

(define (send-inferior-request exp inferior)
  (write exp (inferior-socket inferior))
  (newline (inferior-socket inferior)))

(define (inferior-eval exp inferior)
  "Evaluate EXP in INFERIOR."
  (send-inferior-request exp inferior)
  (read-inferior-response inferior))

;;;
;;; Inferior packages.
;;;

(define-record-type <inferior-package>
  (inferior-package inferior name version id)
  inferior-package?
  (inferior   inferior-package-inferior)
  (name       inferior-package-name)
  (version    inferior-package-version)
  (id         inferior-package-id))

(define (write-inferior-package package port)
  (match package
    (($ <inferior-package> _ name version)
     (format port "#<inferior-package ~a@~a ~a>"
             name version
             (number->string (object-address package) 16)))))

(set-record-type-printer! <inferior-package> write-inferior-package)

(define (%inferior-packages inferior)
  "Compute the list of inferior packages from INFERIOR."
  (let ((result (inferior-eval
                 '(fold-packages (lambda (package result)
                                   (let ((id (object-address package)))
                                     (hashv-set! %package-table id package)
                                     (cons (list (package-name package)
                                                 (package-version package)
                                                 id)
                                           result)))
                                 '())
                 inferior)))
    (map (match-lambda
           ((name version id)
            (inferior-package inferior name version id)))
         result)))

(define (inferior-packages inferior)
  "Return the list of packages known to INFERIOR."
  (force (inferior-package-promise inferior)))

(define (%inferior-package-table inferior)
  "Compute a package lookup table for INFERIOR."
  (fold (lambda (package table)
          (vhash-cons (inferior-package-name package) package
                      table))
        vlist-null
        (inferior-packages inferior)))

(define (inferior-available-packages inferior)
  "Return the list of name/version pairs corresponding to the set of packages
available in INFERIOR.

This is faster and requires less resource-intensive than calling
'inferior-packages'."
  (if (inferior-eval '(defined? 'fold-available-packages)
                     inferior)
      (inferior-eval '(fold-available-packages
                       (lambda* (name version result
                                      #:key supported? deprecated?
                                      #:allow-other-keys)
                         (if (and supported? (not deprecated?))
                             (acons name version result)
                             result))
                       '())
                     inferior)

      ;; As a last resort, if INFERIOR is old and lacks
      ;; 'fold-available-packages', fall back to 'inferior-packages'.
      (map (lambda (package)
             (cons (inferior-package-name package)
                   (inferior-package-version package)))
           (inferior-packages inferior))))

(define* (lookup-inferior-packages inferior name #:optional version)
  "Return the sorted list of inferior packages matching NAME in INFERIOR, with
highest version numbers first.  If VERSION is true, return only packages with
a version number prefixed by VERSION."
  ;; This is the counterpart of 'find-packages-by-name'.
  (sort (filter (lambda (package)
                  (or (not version)
                      (version-prefix? version
                                       (inferior-package-version package))))
                (vhash-fold* cons '() name
                             (force (inferior-package-table inferior))))
        (lambda (p1 p2)
          (version>? (inferior-package-version p1)
                     (inferior-package-version p2)))))

(define (inferior-package-field package getter)
  "Return the field of PACKAGE, an inferior package, accessed with GETTER."
  (let ((inferior (inferior-package-inferior package))
        (id       (inferior-package-id package)))
    (inferior-eval `(,getter (hashv-ref %package-table ,id))
                   inferior)))

(define* (inferior-package-synopsis package #:key (translate? #t))
  "Return the Texinfo synopsis of PACKAGE, an inferior package.  When
TRANSLATE? is true, translate it to the current locale's language."
  (inferior-package-field package
                          (if translate?
                              '(compose (@ (guix ui) P_) package-synopsis)
                              'package-synopsis)))

(define* (inferior-package-description package #:key (translate? #t))
  "Return the Texinfo description of PACKAGE, an inferior package.  When
TRANSLATE? is true, translate it to the current locale's language."
  (inferior-package-field package
                          (if translate?
                              '(compose (@ (guix ui) P_) package-description)
                              'package-description)))

(define (inferior-package-home-page package)
  "Return the home page of PACKAGE."
  (inferior-package-field package 'package-home-page))

(define (inferior-package-location package)
  "Return the source code location of PACKAGE, either #f or a <location>
record."
  (source-properties->location
   (inferior-package-field package
                           '(compose (lambda (loc)
                                       (and loc
                                            (location->source-properties
                                             loc)))
                                     package-location))))

(define (inferior-package-input-field package field)
  "Return the input field FIELD (e.g., 'native-inputs') of PACKAGE, an
inferior package."
  (define field*
    `(compose (lambda (inputs)
                (map (match-lambda
                       ;; XXX: Origins are not handled.
                       ((label (? package? package) rest ...)
                        (let ((id (object-address package)))
                          (hashv-set! %package-table id package)
                          `(,label (package ,id
                                            ,(package-name package)
                                            ,(package-version package))
                                   ,@rest)))
                       (x
                        x))
                     inputs))
              ,field))

  (define inputs
    (inferior-package-field package field*))

  (define inferior
    (inferior-package-inferior package))

  (map (match-lambda
         ((label ('package id name version) . rest)
          ;; XXX: eq?-ness of inferior packages is not preserved here.
          `(,label ,(inferior-package inferior name version id)
                   ,@rest))
         (x x))
       inputs))

(define inferior-package-inputs
  (cut inferior-package-input-field <> 'package-inputs))

(define inferior-package-native-inputs
  (cut inferior-package-input-field <> 'package-native-inputs))

(define inferior-package-propagated-inputs
  (cut inferior-package-input-field <> 'package-propagated-inputs))

(define inferior-package-transitive-propagated-inputs
  (cut inferior-package-input-field <> 'package-transitive-propagated-inputs))

(define (%inferior-package-search-paths package field)
  "Return the list of search path specifications of PACKAGE, an inferior
package."
  (define paths
    (inferior-package-field package
                            `(compose (lambda (paths)
                                        (map (@ (guix search-paths)
                                                search-path-specification->sexp)
                                             paths))
                                      ,field)))

  (map sexp->search-path-specification paths))

(define inferior-package-native-search-paths
  (cut %inferior-package-search-paths <> 'package-native-search-paths))

(define inferior-package-search-paths
  (cut %inferior-package-search-paths <> 'package-search-paths))

(define inferior-package-transitive-native-search-paths
  (cut %inferior-package-search-paths <> 'package-transitive-native-search-paths))

(define (inferior-package-provenance package)
  "Return a \"provenance sexp\" for PACKAGE, an inferior package.  The result
is similar to the sexp returned by 'package-provenance' for regular packages."
  (inferior-package-field package
                          '(let* ((describe
                                   (false-if-exception
                                    (resolve-interface '(guix describe))))
                                  (provenance
                                   (false-if-exception
                                    (module-ref describe
                                                'package-provenance))))
                             (or provenance (const #f)))))

(define (proxy client backend)                    ;adapted from (guix ssh)
  "Proxy communication between CLIENT and BACKEND until CLIENT closes the
connection, at which point CLIENT is closed (both CLIENT and BACKEND must be
input/output ports.)"
  (define (select* read write except)
    ;; This is a workaround for <https://bugs.gnu.org/30365> in Guile < 2.2.4:
    ;; since 'select' sometimes returns non-empty sets for no good reason,
    ;; call 'select' a second time with a zero timeout to filter out incorrect
    ;; replies.
    (match (select read write except)
      ((read write except)
       (select read write except 0))))

  ;; Use buffered ports so that 'get-bytevector-some' returns up to the
  ;; whole buffer like read(2) would--see <https://bugs.gnu.org/30066>.
  (setvbuf client 'block 65536)
  (setvbuf backend 'block 65536)

  (let loop ()
    (match (select* (list client backend) '() '())
      ((reads () ())
       (when (memq client reads)
         (match (get-bytevector-some client)
           ((? eof-object?)
            (close-port client))
           (bv
            (put-bytevector backend bv)
            (force-output backend))))
       (when (memq backend reads)
         (match (get-bytevector-some backend)
           (bv
            (put-bytevector client bv)
            (force-output client))))
       (unless (port-closed? client)
         (loop))))))

(define (inferior-eval-with-store inferior store code)
  "Evaluate CODE in INFERIOR, passing it STORE as its argument.  CODE must
thus be the code of a one-argument procedure that accepts a store."
  ;; Create a named socket in /tmp and let INFERIOR connect to it and use it
  ;; as its store.  This ensures the inferior uses the same store, with the
  ;; same options, the same per-session GC roots, etc.
  ;; FIXME: This strategy doesn't work for remote inferiors (SSH).
  (call-with-temporary-directory
   (lambda (directory)
     (chmod directory #o700)
     (let* ((name     (string-append directory "/inferior"))
            (socket   (socket AF_UNIX SOCK_STREAM 0))
            (major    (store-connection-major-version store))
            (minor    (store-connection-minor-version store))
            (proto    (logior major minor)))
       (bind socket AF_UNIX name)
       (listen socket 1024)
       (send-inferior-request
        `(let ((proc   ,code)
               (socket (socket AF_UNIX SOCK_STREAM 0))
               (error? (if (defined? 'store-protocol-error?)
                           store-protocol-error?
                           nix-protocol-error?))
               (error-message (if (defined? 'store-protocol-error-message)
                                  store-protocol-error-message
                                  nix-protocol-error-message)))
           (connect socket AF_UNIX ,name)

           ;; 'port->connection' appeared in June 2018 and we can hardly
           ;; emulate it on older versions.  Thus fall back to
           ;; 'open-connection', at the risk of talking to the wrong daemon or
           ;; having our build result reclaimed (XXX).
           (let ((store (if (defined? 'port->connection)
                            (port->connection socket #:version ,proto)
                            (open-connection))))
             (dynamic-wind
               (const #t)
               (lambda ()
                 ;; Serialize '&store-protocol-error' conditions.  The
                 ;; exception serialization mechanism that
                 ;; 'read-repl-response' expects is unsuitable for SRFI-35
                 ;; error conditions, hence this special case.
                 (guard (c ((error? c)
                            `(store-protocol-error ,(error-message c))))
                   `(result ,(proc store))))
               (lambda ()
                 (close-connection store)
                 (close-port socket)))))
        inferior)
       (match (accept socket)
         ((client . address)
          (proxy client (store-connection-socket store))))
       (close-port socket)

       (match (read-inferior-response inferior)
         (('store-protocol-error message)
          (raise (condition
                  (&store-protocol-error (message message)
                                         (status 1)))))
         (('result result)
          result))))))

(define* (inferior-package-derivation store package
                                      #:optional
                                      (system (%current-system))
                                      #:key target)
  "Return the derivation for PACKAGE, an inferior package, built for SYSTEM
and cross-built for TARGET if TARGET is true.  The inferior corresponding to
PACKAGE must be live."
  (define proc
    `(lambda (store)
       (let* ((package (hashv-ref %package-table
                                  ,(inferior-package-id package)))
              (drv     ,(if target
                            `(package-cross-derivation store package
                                                       ,target
                                                       ,system)
                            `(package-derivation store package
                                                 ,system))))
         (derivation-file-name drv))))

  (and=> (inferior-eval-with-store (inferior-package-inferior package) store
                                   proc)
         read-derivation-from-file))

(define inferior-package->derivation
  (store-lift inferior-package-derivation))

(define-gexp-compiler (package-compiler (package <inferior-package>) system
                                        target)
  ;; Compile PACKAGE for SYSTEM, optionally cross-building for TARGET.
  (inferior-package->derivation package system #:target target))

(define* (gexp->derivation-in-inferior name exp guix
                                       #:key silent-failure?
                                       #:allow-other-keys
                                       #:rest rest)
  "Return a derivation that evaluates EXP with GUIX, an instance of Guix as
returned for example by 'channel-instances->derivation'.  Other arguments are
passed as-is to 'gexp->derivation'.

When SILENT-FAILURE? is true, create an empty output directory instead of
failing when GUIX is too old and lacks the 'guix repl' command."
  (define script
    ;; EXP wrapped with a proper (set! %load-path …) prologue.
    (scheme-file "inferior-script.scm" exp))

  (define trampoline
    ;; This is a crude way to run EXP on GUIX.  TODO: use 'raw-derivation' and
    ;; make 'guix repl' the "builder"; this will require "opening up" the
    ;; mechanisms behind 'gexp->derivation', and adding '-l' to 'guix repl'.
    #~(begin
        (use-modules (ice-9 popen))

        (let ((pipe (open-pipe* OPEN_WRITE
                                #+(file-append guix "/bin/guix")
                                "repl" "-t" "machine")))

          ;; XXX: EXP presumably refers to #$output but that reference is lost
          ;; so explicitly reference it here.
          #$output

          (write `(primitive-load #$script) pipe)

          (unless (zero? (close-pipe pipe))
            (if #$silent-failure?
                (mkdir #$output)
                (error "inferior failed" #+guix))))))

  (define (drop-extra-keyword lst)
    (let loop ((lst lst)
               (result '()))
      (match lst
        (()
         (reverse result))
        ((#:silent-failure? _ . rest)
         (loop rest result))
        ((kw value . tail)
         (loop tail (cons* value kw result))))))

  (apply gexp->derivation name trampoline
         (drop-extra-keyword rest)))

;;;
;;; Manifest entries.
;;;

(define* (inferior-package->manifest-entry package
                                           #:optional (output "out")
                                           #:key (parent (delay #f))
                                           (properties '()))
  "Return a manifest entry for the OUTPUT of package PACKAGE."
  ;; For each dependency, keep a promise pointing to its "parent" entry.
  (letrec* ((deps  (map (match-lambda
                          ((label package)
                           (inferior-package->manifest-entry package
                                                             #:parent (delay entry)))
                          ((label package output)
                           (inferior-package->manifest-entry package output
                                                             #:parent (delay entry))))
                        (inferior-package-propagated-inputs package)))
            (entry (manifest-entry
                     (name (inferior-package-name package))
                     (version (inferior-package-version package))
                     (output output)
                     (item package)
                     (dependencies (delete-duplicates deps))
                     (search-paths
                      (inferior-package-transitive-native-search-paths package))
                     (parent parent)
                     (properties properties))))
    entry))

;;;
;;; Cached inferiors.
;;;

(define %inferior-cache-directory
  ;; Directory for cached inferiors (GC roots).
  (make-parameter (string-append (cache-directory #:ensure? #f)
                                 "/inferiors")))

(define* (cached-channel-instance store
                                  channels
                                  #:key
                                  (authenticate? #t)
                                  (cache-directory (%inferior-cache-directory))
                                  (ttl (* 3600 24 30)))
  "Return a directory containing a guix filetree defined by CHANNELS, a list of channels.
The directory is a subdirectory of CACHE-DIRECTORY, where entries can be reclaimed after TTL seconds.
This procedure opens a new connection to the build daemon.  AUTHENTICATE?
determines whether CHANNELS are authenticated."
  (define instances
    (latest-channel-instances store channels
                              #:authenticate? authenticate?))

  (define key
    (bytevector->base32-string
     (sha256
      (string->utf8
       (string-concatenate (map channel-instance-commit instances))))))

  (define cached
    (string-append cache-directory "/" key))

  (define (base32-encoded-sha256? str)
    (= (string-length str) 52))

  (define (cache-entries directory)
    (map (lambda (file)
           (string-append directory "/" file))
         (scandir directory base32-encoded-sha256?)))

  (define symlink*
    (lift2 symlink %store-monad))

  (define add-indirect-root*
    (store-lift add-indirect-root))

  (mkdir-p cache-directory)
  (maybe-remove-expired-cache-entries cache-directory
                                      cache-entries
                                      #:entry-expiration
                                      (file-expiration-time ttl))

  (if (file-exists? cached)
      cached
      (run-with-store store
        (mlet %store-monad ((profile
                             (channel-instances->derivation instances)))
          (mbegin %store-monad
            (show-what-to-build* (list profile))
            (built-derivations (list profile))
            ;; Note: Caching is fine even when AUTHENTICATE? is false because
            ;; we always call 'latest-channel-instances?'.
            (symlink* (derivation->output-path profile) cached)
            (add-indirect-root* cached)
            (return cached))))))

(define* (inferior-for-channels channels
                                #:key
                                (cache-directory (%inferior-cache-directory))
                                (ttl (* 3600 24 30)))
  "Return an inferior for CHANNELS, a list of channels.  Use the cache at
CACHE-DIRECTORY, where entries can be reclaimed after TTL seconds.  This
procedure opens a new connection to the build daemon.

This is a convenience procedure that people may use in manifests passed to
'guix package -m', for instance."
  (define cached
    (with-store store
      (cached-channel-instance store
                               channels
                               #:cache-directory cache-directory
                               #:ttl ttl)))
  (open-inferior cached))

license: mit


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2012, 2014, 2015, 2017, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2013, 2015 Andreas Enge <andreas@enge.fr>
;;; Copyright © 2012, 2013 Nikita Karetnikov <nikita@karetnikov.org>
;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2015, 2019 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2016 Eric Bavier <bavier@member.fsf.org>
;;; Copyright © 2016 Leo Famulari <leo@famulari.name>
;;; Copyright © 2016 Fabian Harfert <fhmgufs@web.de>
;;; Copyright © 2016 Rene Saavedra <rennes@openmailbox.org>
;;; Copyright © 2016, 2017 Nikita <nikita@n0.is>
;;; Copyright © 2017 Clément Lassieur <clement@lassieur.org>
;;; Copyright © 2017 Petter <petter@mykolab.ch>
;;; Copyright © 2017 Marius Bakke <mbakke@fastmail.com>
;;; Copyright © 2017 Arun Isaac <arunisaac@systemreboot.net>
;;; Copyright © 2017 Rutger Helling <rhelling@mykolab.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 licenses)
  #:use-module (srfi srfi-9)
  #:export (license? license-name license-uri license-comment
            agpl1 agpl3 agpl3+
            asl1.1 asl2.0
            boost1.0
            bsd-2 bsd-3 bsd-4
            non-copyleft
            cc0
            cc-by2.0 cc-by3.0 cc-by4.0
            cc-by-sa2.0 cc-by-sa3.0 cc-by-sa4.0
            cc-sampling-plus-1.0
            cddl1.0 cddl1.1
            cecill cecill-b cecill-c
            artistic2.0 clarified-artistic
            copyleft-next
            cpl1.0
            edl1.0
            epl1.0
            epl2.0
            expat
            freetype
            freebsd-doc
            giftware
            gpl1 gpl1+ gpl2 gpl2+ gpl3 gpl3+
            gfl1.0
            fdl1.1+ fdl1.2+ fdl1.3+
            opl1.0+
            isc
            ijg
            ibmpl1.0
            imlib2
            ipa
            knuth
            lgpl2.0 lgpl2.0+ lgpl2.1 lgpl2.1+ lgpl3 lgpl3+ llgpl
            lppl lppl1.0+ lppl1.1+ lppl1.2 lppl1.2+
            lppl1.3 lppl1.3+
            lppl1.3a lppl1.3a+
            lppl1.3b lppl1.3b+
            lppl1.3c lppl1.3c+
            miros
            mpl1.0 mpl1.1 mpl2.0
            ms-pl
            ncsa
            nmap
            ogl-psi1.0
            openldap2.8 openssl
            perl-license
            psfl public-domain
            qpl
            qwt1.0
            repoze
            ruby
            sgifreeb2.0
            silofl1.1
            sleepycat
            tcl/tk
            unicode
            unlicense
            vim
            w3c
            x11 x11-style
            zpl2.1
            zlib
            fsf-free
            wtfpl2
            wxwindows3.1+
            hpnd
            fsdg-compatible))

(define-record-type <license>
  (license name uri comment)
  license?
  (name    license-name)
  (uri     license-uri)
  (comment license-comment))

;;; Commentary:
;;;
;;; Available licenses.
;;;
;;; This list is based on these links:
;;; https://github.com/NixOS/nixpkgs/blob/master/lib/licenses.nix
;;; https://www.gnu.org/licenses/license-list
;;;
;;; Code:

(define agpl1
  (license "AGPL 1"
           "https://gnu.org/licenses/agpl.html"
           "https://gnu.org/licenses/why-affero-gpl.html"))

(define agpl3
  (license "AGPL 3"
           "https://gnu.org/licenses/agpl.html"
           "https://gnu.org/licenses/why-affero-gpl.html"))

(define agpl3+
  (license "AGPL 3+"
           "https://gnu.org/licenses/agpl.html"
           "https://gnu.org/licenses/why-affero-gpl.html"))

(define asl1.1
  (license "ASL 1.1"
           "http://directory.fsf.org/wiki/License:Apache1.1"
           "https://www.gnu.org/licenses/license-list#apache1"))

(define asl2.0
  (license "ASL 2.0"
           "http://directory.fsf.org/wiki/License:Apache2.0"
           "https://www.gnu.org/licenses/license-list#apache2"))

(define boost1.0
  (license "Boost 1.0"
           "http://directory.fsf.org/wiki/License:Boost1.0"
           "https://www.gnu.org/licenses/license-list#boost"))

(define bsd-2
  (license "FreeBSD"
           "http://directory.fsf.org/wiki/License:FreeBSD"
           "https://www.gnu.org/licenses/license-list#FreeBSD"))

(define bsd-3
  (license "Modified BSD"
           "http://directory.fsf.org/wiki/License:BSD_3Clause"
           "https://www.gnu.org/licenses/license-list#ModifiedBSD"))

(define bsd-4
  (license "Original BSD"
           "http://directory.fsf.org/wiki/License:BSD_4Clause"
           "https://www.gnu.org/licenses/license-list#OriginalBSD"))

(define* (non-copyleft uri #:optional (comment ""))
  "Return a lax, permissive, non-copyleft license (for example a variant of
the 3-clause BSD license or the Expat license), whose full text can be found
at URI, which may be a file:// URI pointing the package's tree."
  (license "non-copyleft"
           uri
           (string-append
            "This is a lax, non-copyleft free software license.  "
            "Check the URI for details.  "
            comment)))

(define cc0
  (license "CC0"
           "http://directory.fsf.org/wiki/License:CC0"
           "http://www.gnu.org/licenses/license-list.html#CC0"))

(define cc-by-sa4.0
  (license "CC-BY-SA 4.0"
           "http://creativecommons.org/licenses/by-sa/4.0/"
           "Creative Commons Attribution-ShareAlike 4.0 International"))

(define cc-by-sa3.0
  (license "CC-BY-SA 3.0"
           "http://creativecommons.org/licenses/by-sa/3.0/"
           "Creative Commons Attribution-ShareAlike 3.0 Unported"))

(define cc-by-sa2.0
  (license "CC-BY-SA 2.0"
           "http://creativecommons.org/licenses/by-sa/2.0/"
           "Creative Commons Attribution-ShareAlike 2.0 Generic"))

(define cc-by4.0
  (license "CC-BY 4.0"
           "http://creativecommons.org/licenses/by/4.0/"
           "Creative Commons Attribution 4.0 Unported"))

(define cc-by3.0
  (license "CC-BY 3.0"
           "http://creativecommons.org/licenses/by/3.0/"
           "Creative Commons Attribution 3.0 Unported"))

(define cc-by2.0
  (license "CC-BY 2.0"
           "http://creativecommons.org/licenses/by/2.0/"
           "Creative Commons Attribution 2.0 Generic"))

(define cc-sampling-plus-1.0
  (license "CC-Sampling+ 1.0"
           "https://creativecommons.org/licenses/sampling+/1.0"
           "Creative Commons Sampling Plus 1.0"))

(define cddl1.0
  (license "CDDL 1.0"
           "http://directory.fsf.org/wiki/License:CDDLv1.0"
           "https://www.gnu.org/licenses/license-list#CDDL"))

;; CDDL1.1 is the same as 1.0, except that "Sun Microsystems, Inc" becomes "Oracle",
;; "LOST PROFITS" becoms "LOSS OF GOODWILL" and a section is added between 6.2
;; and 6.3.
(define cddl1.1
  (license "CDDL 1.1"
           "https://oss.oracle.com/licenses/CDDL+GPL-1.1"
           "https://www.gnu.org/licenses/license-list#CDDL"))

(define cecill                                    ;copyleft
  (license "CeCILL"
           "http://www.cecill.info/licences/Licence_CeCILL_V2.1-en.html"
           "https://www.gnu.org/licenses/license-list.html#CeCILL"))

(define cecill-b                                  ;non-copyleft
  (license "CeCILL-B"
           "http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html"
           "https://www.gnu.org/licenses/license-list.html#CeCILL"))

(define cecill-c                                  ;weak copyleft
  (license "CeCILL-C"
           "http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html"
           "https://www.gnu.org/licenses/license-list.html#CeCILL"))

(define artistic2.0
  (license "Artistic License 2.0"
           "http://www.perlfoundation.org/artistic_license_2_0"
           "http://www.gnu.org/licenses/license-list.html#ArtisticLicense2"))

(define clarified-artistic
  (license "Clarified Artistic"
           ;; http://directory.fsf.org/wiki/User:Jgay/license-categorization#Clarified_Artistic_License
           "http://gianluca.dellavedova.org/2011/01/03/clarified-artistic-license/"
           "https://www.gnu.org/licenses/license-list.html#ArtisticLicense2"))

(define copyleft-next
  (license "copyleft-next"
           "https://raw.github.com/richardfontana/copyleft-next/master/Releases/copyleft-next-0.3.0"
           "GPL-compatible copyleft license"))

(define cpl1.0
  (license "CPL 1.0"
           "http://directory.fsf.org/wiki/License:CPLv1.0"
           "https://www.gnu.org/licenses/license-list#CommonPublicLicense10"))

(define edl1.0
  (license "EDL 1.0"
           "http://directory.fsf.org/wiki/License:EDLv1.0"
           "https://eclipse.org/org/documents/edl-v10.php"))

(define epl1.0
  (license "EPL 1.0"
           "http://directory.fsf.org/wiki/License:EPLv1.0"
           "https://www.gnu.org/licenses/license-list#EPL"))

(define epl2.0
  (license "EPL 2.0"
           "https://www.eclipse.org/legal/epl-2.0/"
           "https://www.gnu.org/licenses/license-list#EPL2"))

(define expat
  (license "Expat"
           "http://directory.fsf.org/wiki/License:Expat"
           "https://www.gnu.org/licenses/license-list.html#Expat"))

(define freetype
  (license "Freetype"
           "http://directory.fsf.org/wiki/License:Freetype"
           "https://www.gnu.org/licenses/license-list.html#freetype"))

(define giftware
  (license "Giftware"
           "https://liballeg.org/license.html"
           "The Allegro 4 license"))

(define gpl1
  (license "GPL 1"
           "https://www.gnu.org/licenses/old-licenses/gpl-1.0.html"
           #f))

(define gpl1+
  (license "GPL 1+"
           "https://www.gnu.org/licenses/old-licenses/gpl-1.0.html"
           #f))

(define gpl2
  (license "GPL 2"
           "https://www.gnu.org/licenses/old-licenses/gpl-2.0.html"
           "https://www.gnu.org/licenses/license-list#GPLv2"))

(define gpl2+
  (license "GPL 2+"
           "https://www.gnu.org/licenses/old-licenses/gpl-2.0.html"
           "https://www.gnu.org/licenses/license-list#GPLv2"))

(define gpl3
  (license "GPL 3"
           "https://www.gnu.org/licenses/gpl.html"
           "https://www.gnu.org/licenses/license-list#GNUGPLv3"))

(define gpl3+
  (license "GPL 3+"
           "https://www.gnu.org/licenses/gpl.html"
           "https://www.gnu.org/licenses/license-list#GNUGPLv3"))

;; The “GUST font license” is legally equivalent to LPPL v1.3c as it only
;; extends the LPPL with an optional request.
(define gfl1.0
  (license "GUST font license 1.0"
           "http://www.gust.org.pl/projects/e-foundry/licenses/GUST-FONT-LICENSE.txt"
           "https://www.gnu.org/licenses/license-list#LPPL-1.3a"))

(define fdl1.1+
  (license "FDL 1.1+"
           "https://www.gnu.org/licenses/fdl-1.1"
           "https://www.gnu.org/licenses/license-list#FDL"))

(define fdl1.2+
  (license "FDL 1.2+"
           "https://www.gnu.org/licenses/fdl-1.2"
           "https://www.gnu.org/licenses/license-list#FDL"))

(define fdl1.3+
  (license "FDL 1.3+"
           "https://www.gnu.org/licenses/fdl.html"
           "https://www.gnu.org/licenses/license-list#FDL"))

(define freebsd-doc
  (license "FreeBSD Documentation License"
           "https://www.freebsd.org/copyright/freebsd-doc-license.html"
           "https://www.gnu.org/licenses/license-list.html#FreeBSDDL"))

(define opl1.0+
  (license "Open Publication License 1.0 or later"
           "http://opencontent.org/openpub/"
           "https://www.gnu.org/licenses/license-list#OpenPublicationL"))

(define isc
  (license "ISC"
           "http://directory.fsf.org/wiki/License:ISC"
           "https://www.gnu.org/licenses/license-list.html#ISC"))

(define ijg
  (license "IJG"
           "http://directory.fsf.org/wiki/License:JPEG"
           "https://www.gnu.org/licenses/license-list#ijg"))

(define ibmpl1.0
  (license "IBMPL 1.0"
           "http://directory.fsf.org/wiki/License:IBMPLv1.0"
           "https://www.gnu.org/licenses/license-list#IBMPL"))

(define imlib2
  (license "Imlib2"
           "http://directory.fsf.org/wiki/License:Imlib2"
           "https://www.gnu.org/licenses/license-list#imlib"))

(define ipa
  (license "IPA Font License"
           "http://directory.fsf.org/wiki/License:IPA_Font_License"
           "https://www.gnu.org/licenses/license-list#IPAFONT"))

(define knuth
  (license "Donald Knuth's license for TeX"
           "http://www.ctan.org/license/knuth"
           "Modification are only permitted under a different name."))

(define lgpl2.0
  (license "LGPL 2.0"
           "https://www.gnu.org/licenses/old-licenses/lgpl-2.0.html"
           "https://www.gnu.org/licenses/why-not-lgpl.html"))

(define lgpl2.0+
  (license "LGPL 2.0+"
           "https://www.gnu.org/licenses/old-licenses/lgpl-2.0.html"
           "https://www.gnu.org/licenses/why-not-lgpl.html"))

(define lgpl2.1
  (license "LGPL 2.1"
           "https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
           "https://www.gnu.org/licenses/license-list#LGPLv2.1"))

(define lgpl2.1+
  (license "LGPL 2.1+"
           "https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html"
           "https://www.gnu.org/licenses/license-list#LGPLv2.1"))

(define lgpl3
  (license "LGPL 3"
           "https://www.gnu.org/licenses/lgpl.html"
           "https://www.gnu.org/licenses/license-list#LGPLv3"))

(define lgpl3+
  (license "LGPL 3+"
           "https://www.gnu.org/licenses/lgpl.html"
           "https://www.gnu.org/licenses/license-list#LGPLv3"))

(define llgpl
  (license "LLGPL"
           "https://opensource.franz.com/preamble.html"
           "Lisp Lesser General Public License"))

(define lppl
  (license "LPPL (any version)"
           "https://www.latex-project.org/lppl/lppl-1-0/"
           "LaTeX Project Public License 1.0"))

(define lppl1.0+
  (license "LPPL 1.0+"
           "https://www.latex-project.org/lppl/lppl-1-0/"
           "LaTeX Project Public License 1.0"))

(define lppl1.1+
  (license "LPPL 1.1+"
           "https://www.latex-project.org/lppl/lppl-1-1/"
           "LaTeX Project Public License 1.1"))

(define lppl1.2
  (license "LPPL 1.2"
           "http://directory.fsf.org/wiki/License:LPPLv1.2"
           "https://www.gnu.org/licenses/license-list#LPPL-1.2"))

(define lppl1.2+
  (license "LPPL 1.2+"
           "http://directory.fsf.org/wiki/License:LPPLv1.2"
           "https://www.gnu.org/licenses/license-list#LPPL-1.2"))

(define lppl1.3
  (license "LPPL 1.3"
           "https://www.latex-project.org/lppl/lppl-1-3/"
           "LaTeX Project Public License 1.3"))

(define lppl1.3+
  (license "LPPL 1.3+"
           "https://www.latex-project.org/lppl/lppl-1-3/"
           "LaTeX Project Public License 1.3+"))

(define lppl1.3a
  (license "LPPL 1.3a"
           "http://directory.fsf.org/wiki/License:LPPLv1.3a"
           "https://www.gnu.org/licenses/license-list#LPPL-1.3a"))

(define lppl1.3a+
  (license "LPPL 1.3a+"
           "http://directory.fsf.org/wiki/License:LPPLv1.3a"
           "https://www.gnu.org/licenses/license-list#LPPL-1.3a"))

(define lppl1.3b
  (license "LPPL 1.3b"
           "https://www.latex-project.org/lppl/lppl-1-3b/"
           "LaTeX Project Public License 1.3b"))

(define lppl1.3b+
  (license "LPPL 1.3b+"
           "https://www.latex-project.org/lppl/lppl-1-3b/"
           "LaTeX Project Public License 1.3b or later"))

(define lppl1.3c
  (license "LPPL 1.3c"
           "https://www.latex-project.org/lppl/lppl-1-3c/"
           "LaTeX Project Public License 1.3c"))

(define lppl1.3c+
  (license "LPPL 1.3c+"
           "https://www.latex-project.org/lppl/lppl-1-3c/"
           "LaTeX Project Public License 1.3c or later"))

(define miros
  (license "MirOS"
           "https://www.mirbsd.org/MirOS-Licence.htm"
           "MirOS License"))

(define mpl1.0
  (license "MPL 1.0"
           "http://www.mozilla.org/MPL/1.0/"
           "https://www.gnu.org/licenses/license-list.html#MPL"))

(define mpl1.1
  (license "MPL 1.1"
           "http://directory.fsf.org/wiki/License:MPLv1.1"
           "https://www.gnu.org/licenses/license-list#MPL"))

(define mpl2.0
  (license "MPL 2.0"
           "http://directory.fsf.org/wiki/License:MPLv2.0"
           "https://www.gnu.org/licenses/license-list#MPL-2.0"))

(define ms-pl
  (license "Ms-PL"                                ;Microsoft Public License
           "http://directory.fsf.org/wiki/License:MsPL"
           "http://www.gnu.org/licenses/license-list.html#ms-pl"))

(define ncsa
  (license "NCSA/University of Illinois Open Source License"
           "http://directory.fsf.org/wiki/License:IllinoisNCSA"
           "https://www.gnu.org/licenses/license-list#NCSA"))

(define nmap
  (license "Nmap license"
           "https://svn.nmap.org/nmap/COPYING"
           "https://fedoraproject.org/wiki/Licensing/Nmap"))

(define ogl-psi1.0
  (license "Open Government Licence for Public Sector Information"
           "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/1/"
           #f))

(define openssl
  (license "OpenSSL"
           "http://directory.fsf.org/wiki/License:OpenSSL"
           "https://www.gnu.org/licenses/license-list#OpenSSL"))

(define openldap2.8
  (license "OpenLDAPv2.8"
           "http://directory.fsf.org/wiki/License:OpenLDAPv2.8"
           "https://www.gnu.org/licenses/license-list#newOpenLDAP"))
              ;; lists OpenLDAPv2.7, which is virtually identical

(define perl-license
  ;; The license of Perl, GPLv1+ or Artistic (we ignore the latter here).
  ;; We define this alias to avoid circular dependencies introduced by the use
  ;; of the '(package-license perl)' idiom.
  gpl1+)

(define psfl
  (license "Python Software Foundation License"
           "http://docs.python.org/license.html"
           #f))

(define public-domain
  (license "Public Domain"
           "http://directory.fsf.org/wiki/License:PublicDomain"
           "https://www.gnu.org/licenses/license-list#PublicDomain"))

(define qpl
  (license "QPL"
           "http://directory.fsf.org/wiki/License:QPLv1.0"
           "http://www.gnu.org/licenses/license-list.html#QPL"))

(define qwt1.0
  (license "QWT 1.0"
           "http://qwt.sourceforge.net/qwtlicense.html"
           "GNU Lesser General Public License with exceptions"))

(define repoze
  (license "Repoze"
           "http://repoze.org/LICENSE.txt"
           "A BSD-like license with a clause requiring all changes to be
           attributed by author and date."))

(define ruby
  (license "Ruby License"
           "http://directory.fsf.org/wiki/License:Ruby"
           "https://www.ruby-lang.org/en/about/license.txt"))

(define sgifreeb2.0
  (license "SGI Free Software License B, version 2.0"
           "http://directory.fsf.org/wiki/License:SGIFreeBv2"
           "https://www.gnu.org/licenses/license-list.html#SGIFreeB"))

(define silofl1.1
  (license "SIL OFL 1.1"
           "http://scripts.sil.org/OFL_web"
           "https://www.gnu.org/licenses/license-list#SILOFL"))

(define sleepycat
  (license "Sleepycat"
           "http://directory.fsf.org/wiki/License:Sleepycat"
           "https://www.gnu.org/licenses/license-list#BerkeleyDB"))

(define tcl/tk
  (license "Tcl/Tk"
           "http://www.tcl.tk/software/tcltk/license.html"
           "A non-copyleft free software license from the Tcl/Tk project"))

(define vim
  (license "Vim"
           "http://directory.fsf.org/wiki/License:Vim7.2"
           "http://www.gnu.org/licenses/license-list.html#Vim"))

(define unicode
  (license "Unicode"
           "https://directory.fsf.org/wiki/License:Unicode"
           "http://www.gnu.org/licenses/license-list.html#Unicode"))

(define unlicense
  (license "Unlicense"
           "https://unlicense.org/"
           "https://www.gnu.org/licenses/license-list.html#Unlicense"))

(define w3c
  (license "W3C Software Notice and License"
           "https://directory.fsf.org/wiki/License:W3C_31Dec2002"
           "https://www.gnu.org/licenses/license-list.en.html#W3C"))

(define wtfpl2
  (license "WTFPL 2"
           "http://www.wtfpl.net"
           "http://www.wtfpl.net/about/"))

(define wxwindows3.1+
  (license "wxWindows 3.1+"
           "https://wxwidgets.org/about/licence"
           "https://www.gnu.org/licenses/license-list.html#Wxwind"))

(define x11
  (license "X11"
           "http://directory.fsf.org/wiki/License:X11"
           "https://www.gnu.org/licenses/license-list#X11License"))

(define* (x11-style uri #:optional (comment ""))
  "Return an X11-style license, whose full text can be found at URI,
which may be a file:// URI pointing the package's tree."
  (license "X11-style"
           uri
           (string-append
            "This is an X11-style, non-copyleft free software license.  "
            "Check the URI for details.  "
            comment)))

(define zpl2.1
  (license "Zope Public License 2.1"
           "http://directory.fsf.org/wiki?title=License:ZopePLv2.1"
           "https://www.gnu.org/licenses/license-list.html#Zope2.0"))

(define zlib
  (license "Zlib"
           "https://zlib.net/zlib_license.html"
           "https://www.gnu.org/licenses/license-list#ZLib"))

(define hpnd
  (license "HPND"
           "https://directory.fsf.org/wiki/License:HPND"
           "https://www.gnu.org/licenses/license-list#HPND"))

(define* (fsf-free uri #:optional (comment ""))
  "Return a license that does not fit any of the ones above or a collection
of licenses, approved as free by the FSF.  More details can be found at URI."
  (license "FSF-free"
           uri
           comment))

(define* (fsdg-compatible uri #:optional (comment ""))
  "Return a license that does not fit any of the ones above or a collection
of licenses, not necessarily free, but in accordance with FSDG as Non-functional
Data.  More details can be found at URI.  See also
https://www.gnu.org/distros/free-system-distribution-guidelines.en.html#non-functional-data."
  (license "FSDG-compatible"
           uri
           comment))

;;; licenses.scm ends here