code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2016, 2017 Andy Patterson <ajpatter@uwaterloo.ca>
;;;
;;; 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 lisp-utils)
  #:use-module (ice-9 format)
  #:use-module (ice-9 hash-table)
  #:use-module (ice-9 match)
  #:use-module (ice-9 regex)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:use-module (guix build utils)
  #:export (%lisp
            %lisp-type
            %source-install-prefix
            lisp-eval-program
            compile-system
            test-system
            replace-escaped-macros
            generate-executable-wrapper-system
            generate-executable-entry-point
            generate-executable-for-system
            %bundle-install-prefix
            bundle-asd-file
            wrap-output-translations
            prepend-to-source-registry
            build-program
            build-image
            make-asd-file
            valid-char-set
            normalize-string
            library-output))

;;; Commentary:
;;;
;;; Tools to evaluate lisp programs within a lisp session, generate wrapper
;;; systems for executables. Compile, test, and produce images for systems and
;;; programs, and link them with their dependencies.
;;;
;;; Code:

(define %lisp
  ;; File name of the Lisp compiler.
  (make-parameter "lisp"))

(define %lisp-type
  ;; String representing the class of implementation being used.
  (make-parameter "lisp"))

;; The common parent for Lisp source files, as will as the symbolic
;; link farm for system definition (.asd) files.
(define %source-install-prefix "/share/common-lisp")

(define (%bundle-install-prefix)
  (string-append %source-install-prefix "/" (%lisp-type) "-bundle-systems"))

(define (library-output outputs)
  "If a `lib' output exists, build things there. Otherwise use `out'."
  (or (assoc-ref outputs "lib") (assoc-ref outputs "out")))

;; See nix/libstore/store-api.cc#checkStoreName.
(define valid-char-set
  (string->char-set
   "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-._?="))

(define (normalize-string str)
  "Replace invalid characters in STR with a hyphen."
  (string-join (string-tokenize str valid-char-set) "-"))

(define (normalize-dependency dependency)
  "Normalize the name of DEPENDENCY.  Handles dependency definitions of the
dependency-def form described by
<https://common-lisp.net/project/asdf/asdf.html#The-defsystem-grammar>.
Assume that any symbols in DEPENDENCY will be in upper-case."
  (match dependency
    ((':VERSION name rest ...)
     `(:version ,(normalize-string name) ,@rest))
    ((':FEATURE feature-specification dependency-specification)
     `(:feature
       ,feature-specification
       ,(normalize-dependency dependency-specification)))
    ((? string? name) (normalize-string name))
    (require-specification require-specification)))

(define (inputs->asd-file-map inputs)
  "Produce a hash table of the form (system . asd-file), where system is the
name of an ASD system, and asd-file is the full path to its definition."
  (alist->hash-table
   (filter-map
    (match-lambda
      ((_ . path)
       (let ((prefix (string-append path (%bundle-install-prefix))))
         (and (directory-exists? prefix)
              (match (find-files prefix "\\.asd$")
                ((asd-file)
                 (cons
                  (string-drop-right (basename asd-file) 4) ; drop ".asd"
                  asd-file))
                (_ #f))))))
    inputs)))

(define (wrap-output-translations translations)
  `(:output-translations
    ,@translations
    :inherit-configuration))

(define (lisp-eval-program program)
  "Evaluate PROGRAM with a given LISP implementation."
  (define invocation (lisp-invocation program))
  (format #t "Invoking ~a: ~{~s ~}~%" (%lisp-type) invocation)
  (apply invoke invocation))

(define (spread-statements program argument-name)
  "Return a list with the statements from PROGRAM spread between
ARGUMENT-NAME, a string representing the argument a lisp implementation uses
to accept statements to be evaluated before starting."
  (append-map (lambda (statement)
                (list argument-name (format #f "~S" statement)))
              program))

(define (lisp-invocation program)
  "Return a list of arguments for system* determining how to invoke LISP
with PROGRAM."
  (match (%lisp-type)
    ("sbcl" `(,(%lisp) "--non-interactive"
              ,@(spread-statements program "--eval")))
    ("ecl" `(,(%lisp)
             ,@(spread-statements program "--eval")
             "--eval" "(quit)"))
    (_ (error "The LISP provided is not supported at this time."))))

(define (asdf-load-all systems)
  (map (lambda (system)
         `(asdf:load-system ,system))
       systems))

(define (compile-system system asd-file)
  "Use a lisp implementation to compile SYSTEM using asdf.  Load ASD-FILE
first."
  (lisp-eval-program
   `((require :asdf)
     (asdf:load-asd (truename ,asd-file) :name ,(normalize-string system))
     (asdf:operate 'asdf:compile-bundle-op ,system))))

(define (system-dependencies system asd-file)
  "Return the dependencies of SYSTEM, as reported by
asdf:system-depends-on.  First load the system's ASD-FILE."
  (define deps-file ".deps.sexp")
  (define program
    `((require :asdf)
      (asdf:load-asd (truename ,asd-file) :name ,(normalize-string system))
      (with-open-file
       (stream ,deps-file :direction :output)
       (format stream
               "~s~%"
               (asdf:system-depends-on
                (asdf:find-system ,system))))))

  (dynamic-wind
    (lambda _
      (lisp-eval-program program))
    (lambda _
      (call-with-input-file deps-file read))
    (lambda _
      (when (file-exists? deps-file)
        (delete-file deps-file)))))

(define (compiled-system system)
  (let ((system (basename system))) ; this is how asdf handles slashes
    (match (%lisp-type)
      ("sbcl" (string-append system "--system"))
      (_ system))))

(define* (generate-system-definition system
                                     #:key version dependencies component?)
  `(asdf:defsystem
    ,(normalize-string system)
    ,@(if component?
          '(:class asdf/bundle:prebuilt-system)
          '())
    :version ,version
    :depends-on ,dependencies
    ,@(if component?
          `(:components ((:compiled-file ,(compiled-system system))))
          '())
    ,@(if (string=? "ecl" (%lisp-type))
          `(:lib ,(string-append system ".a"))
          '())))

(define (test-system system asd-file test-asd-file)
  "Use a lisp implementation to test SYSTEM using asdf.  Load ASD-FILE first.
Also load TEST-ASD-FILE if necessary."
  (lisp-eval-program
   `((require :asdf)
     (asdf:load-asd (truename ,asd-file) :name ,(normalize-string system))
     ,@(if test-asd-file
           `((asdf:load-asd (truename ,test-asd-file)))
           ;; Try some likely files.
           (map (lambda (file)
                  `(when (uiop:file-exists-p ,file)
                     (asdf:load-asd (truename ,file))))
                (list
                 (string-append system "-tests.asd")
                 (string-append system "-test.asd")
                 "tests.asd"
                 "test.asd")))
     (asdf:test-system ,system))))

(define (string->lisp-keyword . strings)
  "Return a lisp keyword for the concatenation of STRINGS."
  (string->symbol (apply string-append ":" strings)))

(define* (generate-executable-for-system type system #:key compress?)
  "Use LISP to generate an executable, whose TYPE can be 'asdf:image-op or
'asdf:program-op.  The latter will always be standalone.  Depends on having
created a \"SYSTEM-exec\" system which contains the entry program."
  (lisp-eval-program
   `((require :asdf)
     ;; Only SBCL supports compression as of 2019-09-02.
     ,(if (and compress? (string=? (%lisp-type) "sbcl"))
          '(defmethod asdf:perform ((o asdf:image-op) (c asdf:system))
                      (uiop:dump-image (asdf:output-file o c)
                                       :executable t
                                       :compression t))
          '())
     (asdf:operate ',type ,(string-append system "-exec")))))

(define (generate-executable-wrapper-system system dependencies)
  "Generates a system which can be used by asdf to produce an image or program
inside the current directory.  The image or program will contain
DEPENDENCIES."
  (with-output-to-file (string-append system "-exec.asd")
    (lambda _
      (format #t "~y~%"
              `(defsystem ,(string->lisp-keyword system "-exec")
                 :entry-point ,(string-append system "-exec:main")
                 :depends-on (:uiop
                              ,@(map string->lisp-keyword
                                     dependencies))
                 :components ((:file ,(string-append system "-exec"))))))))

(define (generate-executable-entry-point system entry-program)
  "Generates an entry point program from the list of lisp statements
ENTRY-PROGRAM for SYSTEM within the current directory."
  (with-output-to-file (string-append system "-exec.lisp")
    (lambda _
      (let ((system (string->lisp-keyword system "-exec")))
        (format #t "~{~y~%~%~}"
                `((defpackage ,system
                    (:use :cl)
                    (:export :main))

                  (in-package ,system)

                  (defun main ()
                    (let ((arguments uiop:*command-line-arguments*))
                      (declare (ignorable arguments))
                      ,@entry-program))))))))

(define (generate-dependency-links registry system)
  "Creates a program which populates asdf's source registry from REGISTRY, an
alist of dependency names to corresponding asd files.  This allows the system
to locate its dependent systems."
  `(progn
    (asdf/source-registry:ensure-source-registry)
    ,@(map (match-lambda
             ((name . asd-file)
              `(setf
                (gethash ,name
                         asdf/source-registry:*source-registry*)
                ,(string->symbol "#p")
                ,asd-file)))
           registry)))

(define* (make-asd-file asd-file
                        #:key system version inputs
                        (system-asd-file #f))
  "Create an ASD-FILE for SYSTEM@VERSION, appending a program to allow the
system to find its dependencies, as described by GENERATE-DEPENDENCY-LINKS."
  (define dependencies
    (let ((deps
           (system-dependencies system system-asd-file)))
      (if (eq? 'NIL deps)
          '()
          (map normalize-dependency deps))))

  (define lisp-input-map
    (inputs->asd-file-map inputs))

  (define dependency-name
    (match-lambda
      ((':version name _ ...) name)
      ((':feature _ dependency-specification)
       (dependency-name dependency-specification))
      ((? string? name) name)
      (_ #f)))

  (define registry
    (filter-map hash-get-handle
                (make-list (length dependencies)
                           lisp-input-map)
                (map dependency-name dependencies)))

  ;; Ensure directory exists, which might not be the case for an .asd without components.
  (mkdir-p (dirname asd-file))
  (call-with-output-file asd-file
    (lambda (port)
      (display
       (replace-escaped-macros
        (format #f "~y~%~y~%"
                (generate-system-definition
                 system
                 #:version version
                 #:dependencies dependencies
                 ;; Some .asd don't have components, and thus they don't generate any .fasl.
                 #:component? (match (%lisp-type)
                                ("sbcl" (pair? (find-files (dirname asd-file)
                                                           "--system\\.fasl$")))
                                ("ecl" (pair? (find-files (dirname asd-file)
                                                          "\\.fasb$")))
                                (_ (error "The LISP provided is not supported at this time."))))
                (generate-dependency-links registry system)))
       port))))

(define (bundle-asd-file output-path original-asd-file)
  "Find the symlinked bundle file for ORIGINAL-ASD-FILE by looking in
OUTPUT-PATH/share/common-lisp/LISP-bundle-systems/<system>.asd.  Returns two
values: the asd file itself and the directory in which it resides."
  (let ((bundle-asd-path (string-append output-path
                                        (%bundle-install-prefix))))
    (values (string-append bundle-asd-path "/" (basename original-asd-file))
            bundle-asd-path)))

(define (replace-escaped-macros string)
  "Replace simple lisp forms that the guile writer escapes, for example by
replacing #{#p}# with #p.  Should only be used to replace truly simple forms
which are not nested."
  (regexp-substitute/global #f "(#\\{)(\\S*)(\\}#)" string
                            'pre 2 'post))

(define (prepend-to-source-registry path)
  (setenv "CL_SOURCE_REGISTRY"
          (string-append path ":" (or (getenv "CL_SOURCE_REGISTRY") ""))))

(define* (build-program program outputs #:key
                        (dependency-prefixes (list (library-output outputs)))
                        (dependencies (list (basename program)))
                        entry-program
                        compress?
                        #:allow-other-keys)
  "Generate an executable program containing all DEPENDENCIES, and which will
execute ENTRY-PROGRAM.  The result is placed in PROGRAM.  When executed, it
will run ENTRY-PROGRAM, a list of Common Lisp expressions in which `arguments'
has been bound to the command-line arguments which were passed.  Link in any
asd files from DEPENDENCY-PREFIXES to ensure references to those libraries are
retained."
  (generate-executable program
                       #:dependencies dependencies
                       #:dependency-prefixes dependency-prefixes
                       #:entry-program entry-program
                       #:compress? compress?
                       #:type 'asdf:program-op)
  (let* ((name (basename program))
         (bin-directory (dirname program)))
    (with-directory-excursion bin-directory
      (rename-file (string-append name "-exec")
                   name)))
  #t)

(define* (build-image image outputs #:key
                      (dependency-prefixes (list (library-output outputs)))
                      (dependencies (list (basename image)))
                      #:allow-other-keys)
  "Generate an image, possibly standalone, which contains all DEPENDENCIES,
placing the result in IMAGE.image.  Link in any asd files from
DEPENDENCY-PREFIXES to ensure references to those libraries are retained."
  (generate-executable image
                       #:dependencies dependencies
                       #:dependency-prefixes dependency-prefixes
                       #:entry-program '(nil)
                       #:type 'asdf:image-op)
  (let* ((name (basename image))
         (bin-directory (dirname image)))
    (with-directory-excursion bin-directory
      (rename-file (string-append name "-exec--all-systems.image")
                   (string-append name ".image"))))
  #t)

(define* (generate-executable out-file #:key
                              dependencies
                              dependency-prefixes
                              entry-program
                              type
                              compress?
                              #:allow-other-keys)
  "Generate an executable by using asdf operation TYPE, containing whithin the
image all DEPENDENCIES, and running ENTRY-PROGRAM in the case of an
executable.  Link in any asd files from DEPENDENCY-PREFIXES to ensure
references to those libraries are retained."
  (let* ((bin-directory (dirname out-file))
         (name (basename out-file)))
    (mkdir-p bin-directory)
    (with-directory-excursion bin-directory
      (generate-executable-wrapper-system name dependencies)
      (generate-executable-entry-point name entry-program))

    (prepend-to-source-registry
     (string-append bin-directory "/"))

    (setenv "ASDF_OUTPUT_TRANSLATIONS"
            (replace-escaped-macros
             (format
              #f "~S"
              (wrap-output-translations
               `(((,bin-directory :**/ :*.*.*)
                  (,bin-directory :**/ :*.*.*)))))))

    (generate-executable-for-system type name #:compress? compress?)

    (let* ((after-store-prefix-index
            (string-index out-file #\/
                          (1+ (string-length (%store-directory)))))
           (output (string-take out-file after-store-prefix-index))
           (hidden-asd-links (string-append output "/.asd-files")))

      (mkdir-p hidden-asd-links)
      (for-each
       (lambda (path)
         (for-each
          (lambda (asd-file)
            (symlink asd-file
                     (string-append hidden-asd-links
                                    "/" (basename asd-file))))
          (find-files (string-append path (%bundle-install-prefix))
                      "\\.asd$")))
       dependency-prefixes))

    (delete-file (string-append bin-directory "/" name "-exec.asd"))
    (delete-file (string-append bin-directory "/" name "-exec.lisp"))))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015, 2017 Manolis Fragkiskos Ragkousis <manolis837@gmail.com>
;;; Copyright © 2015, 2019 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2018 Jan (janneke) Nieuwenhuizen <janneke@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 make-bootstrap)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-19)
  #:use-module (srfi srfi-26)
  #:use-module (guix build utils)
  #:export (copy-linux-headers
            make-stripped-libc))

;; Commentary:
;;
;; This module provides facilities to build the bootstrap binaries.
;;
;; Code:

(define (copy-linux-headers output kernel-headers)
  "Copy to OUTPUT the subset of KERNEL-HEADERS that is needed when producing a
bootstrap libc."

  (let* ((incdir (string-append output "/include")))
    (mkdir-p incdir)

    ;; Copy some of the Linux-Libre headers that glibc headers
    ;; refer to.
    (mkdir (string-append incdir "/linux"))
    (for-each (lambda (file)
                (install-file (pk 'src (string-append kernel-headers "/include/linux/" file))
                              (pk 'dest (string-append incdir "/linux"))))
              '(
                "atalk.h"               ; for 2.2.5
                "errno.h"
                "falloc.h"
                "if_addr.h"             ; for 2.16.0
                "if_ether.h"            ; for 2.2.5
                "if_link.h"             ; for 2.16.0
                "ioctl.h"
                "kernel.h"
                "limits.h"
                "neighbour.h"           ; for 2.16.0
                "netlink.h"             ; for 2.16.0
                "param.h"
                "prctl.h"               ; for 2.16.0
                "posix_types.h"
                "rtnetlink.h"           ; for 2.16.0
                "socket.h"
                "stddef.h"
                "swab.h"                ; for 2.2.5
                "sysctl.h"
                "sysinfo.h"             ; for 2.2.5
                "types.h"
                "version.h"             ; for 2.2.5
                ))

    (copy-recursively (string-append kernel-headers "/include/asm")
                      (string-append incdir "/asm"))
    (copy-recursively (string-append kernel-headers "/include/asm-generic")
                      (string-append incdir "/asm-generic"))
    (copy-recursively (string-append kernel-headers "/include/linux/byteorder")
                      (string-append incdir "/linux/byteorder"))
    #t))

(define (make-stripped-libc output libc kernel-headers)
  "Copy to OUTPUT the subset of LIBC and KERNEL-HEADERS that is needed
when producing a bootstrap libc."

  (define (copy-mach-headers output kernel-headers)
    (let* ((incdir (string-append output "/include")))
      (copy-recursively (string-append libc "/include") incdir)

      (copy-recursively (string-append kernel-headers "/include/mach")
                        (string-append incdir "/mach"))
      #t))

  (define (copy-libc+linux-headers output kernel-headers)
    (let* ((incdir (string-append output "/include")))
      (copy-recursively (string-append libc "/include") incdir)
      (copy-linux-headers output kernel-headers)))

  (define %libc-object-files-rx "^(crt.*|ld.*|lib(c|m|dl|rt|pthread|nsl|\
util).*\\.so(\\..*)?|lib(machuser|hurduser).so.*|(libc(rt|)|libpthread)\
_nonshared\\.a)$")

  (setvbuf (current-output-port) 'line)
  (let* ((libdir (string-append output "/lib")))
    (mkdir-p libdir)
    (for-each (lambda (file)
                (let ((target (string-append libdir "/"
                                             (basename file))))
                  (copy-file file target)
                  (remove-store-references target)))
              (find-files (string-append libc "/lib") %libc-object-files-rx))
    #t)

    (if (directory-exists? (string-append kernel-headers "/include/mach"))
        (copy-mach-headers output kernel-headers)
        (copy-libc+linux-headers output kernel-headers)))

license: mit


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2020 Julien Lepiller <julien@lepiller.eu>
;;;
;;; 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 maven-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module (guix build utils)
  #:use-module (guix build maven pom)
  #:use-module (ice-9 match)
  #:export (%standard-phases
            maven-build))

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

(define* (set-home #:key outputs inputs #:allow-other-keys)
  (let ((home (string-append (getcwd) "/build-home")))
    (setenv "HOME" home))
  (setenv "JAVA_HOME" (assoc-ref inputs "jdk"))
  #t)

(define* (configure #:key inputs #:allow-other-keys)
  (let* ((m2-files (map
                     (lambda (input)
                       (match input
                         ((name . dir)
                          (let ((m2-dir (string-append dir "/lib/m2")))
                            (if (file-exists? m2-dir) m2-dir #f)))))
                     inputs))
         (m2-files (filter (lambda (a) a) m2-files)))
    (for-each
      (lambda (m2-dir)
        (for-each
          (lambda (file)
            (let ((dir (string-append (getenv "HOME") "/.m2/repository/"
                                      (dirname file))))
              (mkdir-p dir)
              (symlink (string-append m2-dir "/" file)
                       (string-append dir "/" (basename file)))))
          (with-directory-excursion m2-dir
            (find-files "." ".*.(jar|pom)$"))))
      m2-files))
  (invoke "mvn" "-v")
  #t)

(define (add-local-package local-packages group artifact version)
  (define (alist-set lst key val)
    (match lst
      ('() (list (cons key val)))
      (((k . v) lst ...)
       (if (equal? k key)
         (cons (cons key val) lst)
         (cons (cons k v) (alist-set lst key val))))))
  (alist-set local-packages group
    (alist-set (or (assoc-ref local-packages group) '()) artifact
      version)))

(define (fix-pom pom-file inputs local-packages excludes)
  (chmod pom-file #o644)
  (format #t "fixing ~a~%" pom-file)
  (fix-pom-dependencies pom-file (map cdr inputs)
                        #:with-plugins? #t #:with-build-dependencies? #t
                        #:local-packages local-packages
                        #:excludes excludes)
  (let* ((pom (get-pom pom-file))
         (java-inputs (map cdr inputs))
         (artifact (pom-artifactid pom))
         (group (pom-groupid pom java-inputs local-packages))
         (version (pom-version pom java-inputs local-packages)))
    (let loop ((modules (pom-ref pom "modules"))
               (local-packages
                 (add-local-package local-packages group artifact version)))
      (pk 'local-packages local-packages)
      (match modules
        (#f local-packages)
        ('() local-packages)
        (((? string? _) modules ...)
         (loop modules local-packages))
        (((_ module) modules ...)
         (loop
           modules
           (fix-pom (string-append (dirname pom-file) "/" module "/pom.xml")
                    inputs local-packages excludes)))))))

(define* (fix-pom-files #:key inputs local-packages exclude #:allow-other-keys)
  (fix-pom "pom.xml" inputs local-packages exclude))

(define* (build #:key outputs #:allow-other-keys)
  "Build the given package."
  (invoke "mvn" "package"
          ;; offline mode: don't download dependencies
          "-o"
          ;, set directory where dependencies are installed
          (string-append "-Duser.home=" (getenv "HOME")))
  #t)

(define* (check #:key tests? #:allow-other-keys)
  "Check the given package."
  (when tests?
    (invoke "mvn" "test"
            (string-append "-Duser.home=" (getenv "HOME"))
            "-e"))
  #t)

(define* (install #:key outputs #:allow-other-keys)
  "Install the given package."
  (let* ((out (assoc-ref outputs "out"))
         (java (string-append out "/lib/m2")))
    (invoke "mvn" "install" "-o" "-e"
            "-DskipTests"
            (string-append "-Duser.home=" (getenv "HOME")))
    ;; Go through the repository to find files that can be installed
    (with-directory-excursion (string-append (getenv "HOME") "/.m2/repository")
      (let ((installable
              (filter (lambda (file)
                        (not (eq? 'symlink (stat:type (lstat file)))))
                      (find-files "." "."))))
        (mkdir-p java)
        (for-each
          (lambda (file)
            (mkdir-p (string-append java "/" (dirname file)))
            (copy-file file (string-append java "/" file)))
          installable)))
    ;; Remove some files that are not required and introduce timestamps
    (for-each delete-file (find-files out "maven-metadata-local.xml"))
    (for-each delete-file (find-files out "_remote.repositories")))
  #t)

(define %standard-phases
  ;; Everything is as with the GNU Build System except for the `configure'
  ;; , `build', `check' and `install' phases.
  (modify-phases gnu:%standard-phases
    (delete 'bootstrap)
    (add-before 'configure 'set-home set-home)
    (replace 'configure configure)
    (add-after 'configure 'fix-pom-files fix-pom-files)
    (replace 'build build)
    (replace 'check check)
    (replace 'install install)))

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

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


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2019, 2020 Julien Lepiller <julien@lepiller.eu>
;;;
;;; 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 maven java)
  #:use-module (ice-9 peg)
  #:use-module (ice-9 textual-ports)
  #:export (parse-java-file))

(define-peg-pattern java-file body (and (* WS) (* (and top-level-statement
                                                       (* WS)))))
(define-peg-pattern WS none (or " " "\n" "\t" "\r"))
(define-peg-pattern top-level-statement body (or package import-pat class-pat comment inline-comment))
(define-peg-pattern package all (and (ignore "package") (* WS) package-name
                                     (* WS) (ignore ";")))
(define-peg-pattern import-pat all (and (ignore "import") (* WS)
                                        (? (and (ignore "static") (* WS)))
                                        package-name
                                        (* WS) (ignore ";")))
(define-peg-pattern comment all (and (? (and annotation-pat (* WS))) (ignore "/*")
                                     comment-part))
(define-peg-pattern comment-part body (or (ignore (and (* "*") "/"))
                                          (and (* "*") (+ comment-chr) comment-part)))
(define-peg-pattern comment-chr body (or "\t" "\n" (range #\ #\)) (range #\+ #\xffff)))
(define-peg-pattern inline-comment none (and (ignore "//") (* inline-comment-chr)
                                            (ignore "\n")))
(define-peg-pattern inline-comment-chr body (range #\ #\xffff))
(define-peg-pattern package-name body (* (or (range #\a #\z) (range #\A #\Z)
                                             (range #\0 #\9) "_" ".")))
(define-peg-pattern class-pat all (and (? (and annotation-pat (* WS)))
                                       (* (ignore (or inline-comment comment)))
                                       (? (and (ignore "private") (* WS)))
                                       (? (and (ignore "public") (* WS)))
                                       (? (and (ignore "static") (* WS)))
                                       (? (and (ignore "final") (* WS)))
                                       (? (and (ignore "abstract") (* WS)))
                                       (ignore "class")
                                       (* WS) package-name (* WS)
                                       (? extends)
                                       (? implements)
                                       (ignore "{") class-body (ignore "}")))
(define-peg-pattern extends all (? (and (ignore "extends") (* WS)
                                        package-name (* WS))))
(define-peg-pattern implements all (? (and (ignore "implements") (* WS)
                                           package-name (* WS))))
(define-peg-pattern annotation-pat all (and (ignore "@") package-name
                                            (? (and
                                                 (* WS)
                                                 (ignore "(") (* WS)
                                                 annotation-attr (* WS)
                                                 (* (and (ignore ",") (* WS)
                                                         annotation-attr (* WS)))
                                                 (ignore ")")))))
(define-peg-pattern annotation-attr all (or (and attr-name (* WS) (ignore "=")
                                                 (* WS) attr-value (* WS))
                                            attr-value))
(define-peg-pattern attr-name all (* (or (range #\a #\z) (range #\A #\Z) (range #\0 #\9)
                                         "_")))
(define-peg-pattern attr-value all (or "true" "false"
                                       (+ (or (range #\0 #\9) (range #\a #\z)
                                              (range #\A #\Z) "." "_"))
                                       array-pat
                                       string-pat))
(define-peg-pattern array-pat body
  (and (ignore "{") (* WS) value
       (* (and (* WS) "," (* WS) value))
       (* WS) (ignore "}")))
(define-peg-pattern string-pat body (and (ignore "\"") (* string-chr) (ignore "\"")))
(define-peg-pattern string-chr body (or " " "!" (and (ignore "\\") "\"")
                                        (and (ignore "\\") "\\") (range #\# #\xffff)))

(define-peg-pattern class-body all (and (* WS) (* (and class-statement (* WS)))))
(define-peg-pattern class-statement body (or inline-comment comment param-pat
                                             method-pat class-pat))
(define-peg-pattern param-pat all (and (* (and annotation-pat (* WS)
                                               (? (ignore inline-comment))
                                               (* WS)))
                                       (? (and (ignore (or "private" "public"
                                                           "protected"))
                                               (* WS)))
                                       (? (and (ignore "static") (* WS)))
                                       (? (and (ignore "volatile") (* WS)))
                                       (? (and (ignore "final") (* WS)))
                                       type-name (* WS) param-name
                                       (? (and (* WS) (ignore "=") (* WS) value))
                                       (ignore ";")))
(define-peg-pattern value none (or string-pat (+ valuechr)))
(define-peg-pattern valuechr none (or comment inline-comment "\n"
                                      "\t" "\r"
                                      (range #\  #\:) (range #\< #\xffff)))
(define-peg-pattern param-name all (* (or (range #\a #\z) (range #\A #\Z) (range #\0 #\9)
                                          "_")))
(define-peg-pattern type-name all type-pat)
(define-peg-pattern type-pat body
  (or "?"
      (and (* (or (range #\a #\z) (range #\A #\Z) (range #\0 #\9) "_"))
           (? "...")
           (? "[]")
           (? type-param))))
(define-peg-pattern type-param body (and "<" (? type-pat)
                                         (* (and (* WS) "," (* WS) type-pat))
                                         (* WS) ">"))
(define-peg-pattern method-pat all (and (* (and annotation-pat (* WS)))
                                        (? (and (ignore (or "private" "public" "protected"))
                                                (* WS)))
                                        (? (and (ignore type-param) (* WS)))
                                        (? (and (ignore (or "abstract" "final"))
                                                (* WS)))
                                        (? (and (ignore "static") (* WS)))
                                        type-name (* WS) param-name (* WS)
                                        (ignore "(")
                                        param-list (ignore ")") (* WS)
                                        (? (and (ignore "throws") (* WS) package-name (* WS)
                                                (* (and (ignore ",") (* WS) package-name
                                                        (* WS)))))
                                        (or (ignore ";")
                                            (and (ignore "{") (* WS)
                                                 (? (and method-statements (* WS)))
                                            (ignore "}")))))
(define-peg-pattern param-list all (and (* WS) (* (and (? annotation-pat) (* WS)
                                                       type-name (* WS)
                                                       param-name (* WS)
                                                       (? (ignore ",")) (* WS)))))
(define-peg-pattern method-statements none (and (or (+ method-chr)
                                                    (and "{" method-statements "}")
                                                    string-pat)
                                                (? method-statements)))
(define-peg-pattern method-chr none (or "\t" "\n" "\r" " " "!" (range #\# #\z) "|"
                                        (range #\~ #\xffff)))

(define (parse-java-file file)
  (peg:tree (match-pattern java-file (call-with-input-file file get-string-all))))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2019, 2020 Julien Lepiller <julien@lepiller.eu>
;;;
;;; 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 maven plugin)
  #:use-module (guix build maven java)
  #:use-module (ice-9 textual-ports)
  #:use-module (ice-9 match)
  #:use-module (srfi srfi-9)
  #:export (generate-mojo-from-files
	    default-convert-type
	    maven-convert-type))

(define-record-type mojo
  (make-mojo package name goal description requires-dependency-collection
             requires-dependency-resolution requires-direct-invocation?
             requires-project? requires-reports? aggregator? requires-online?
             inherited-by-default?  instantiation-strategy execution-strategy
             since thread-safe? phase parameters components)
  mojo?
  (package mojo-package)
  (name mojo-name)
  (goal mojo-goal)
  (description mojo-description)
  (requires-dependency-collection mojo-requires-dependency-collection)
  (requires-dependency-resolution mojo-requires-dependency-resolution)
  (requires-direct-invocation? mojo-requires-direct-invocation?)
  (requires-project? mojo-requires-project?)
  (requires-reports? mojo-requires-reports?)
  (aggregator? mojo-aggregator?)
  (requires-online? mojo-requires-online?)
  (inherited-by-default? mojo-inherited-by-default?)
  (instantiation-strategy mojo-instantiation-strategy)
  (execution-strategy mojo-execution-strategy)
  (since mojo-since)
  (thread-safe? mojo-thread-safe?)
  (phase mojo-phase)
  (parameters mojo-parameters)
  (components mojo-components))

(define* (update-mojo mojo
           #:key
           (package (mojo-package mojo))
           (name (mojo-name mojo))
           (goal (mojo-goal mojo))
           (description (mojo-description mojo))
           (requires-dependency-collection (mojo-requires-dependency-collection mojo))
           (requires-dependency-resolution (mojo-requires-dependency-resolution mojo))
           (requires-direct-invocation? (mojo-requires-direct-invocation? mojo))
           (requires-project? (mojo-requires-project? mojo))
           (requires-reports? (mojo-requires-reports? mojo))
           (aggregator? (mojo-aggregator? mojo))
           (requires-online? (mojo-requires-online? mojo))
           (inherited-by-default? (mojo-inherited-by-default? mojo))
           (instantiation-strategy (mojo-instantiation-strategy mojo))
           (execution-strategy (mojo-execution-strategy mojo))
           (since (mojo-since mojo))
           (thread-safe? (mojo-thread-safe? mojo))
           (phase (mojo-phase mojo))
           (parameters (mojo-parameters mojo))
           (components (mojo-components mojo)))
  (make-mojo package name goal description requires-dependency-collection
             requires-dependency-resolution requires-direct-invocation?
             requires-project? requires-reports? aggregator? requires-online?
             inherited-by-default? instantiation-strategy execution-strategy
             since thread-safe? phase parameters components))

(define-record-type mojo-parameter
  (make-mojo-parameter name type since required editable property description
                       configuration)
  mojo-parameter?
  (name          mojo-parameter-name)
  (type          mojo-parameter-type)
  (since         mojo-parameter-since)
  (required      mojo-parameter-required)
  (editable      mojo-parameter-editable)
  (property      mojo-parameter-property)
  (description   mojo-parameter-description)
  (configuration mojo-parameter-configuration))

(define* (update-mojo-parameter mojo-parameter
           #:key (name (mojo-parameter-name mojo-parameter))
                 (type (mojo-parameter-type mojo-parameter))
                 (since (mojo-parameter-since mojo-parameter))
                 (required (mojo-parameter-required mojo-parameter))
                 (editable (mojo-parameter-editable mojo-parameter))
                 (property (mojo-parameter-property mojo-parameter))
                 (description (mojo-parameter-description mojo-parameter))
                 (configuration (mojo-parameter-configuration mojo-parameter)))
  (make-mojo-parameter name type since required editable property description
                       configuration))

(define-record-type <mojo-component>
  (make-mojo-component field role hint)
  mojo-component?
  (field mojo-component-field)
  (role  mojo-component-role)
  (hint  mojo-component-hint))

(define* (update-mojo-component mojo-component
           #:key (field (mojo-component-field mojo-component))
                 (role (mojo-component-role mojo-component))
                 (hint (mojo-component-hint mojo-component)))
  (make-mojo-component field role hint))

(define (generate-mojo-parameter mojo-parameter)
  `(parameter (name ,(mojo-parameter-name mojo-parameter))
              (type ,(mojo-parameter-type mojo-parameter))
              ,@(if (mojo-parameter-since mojo-parameter)
                    `(since (mojo-parameter-since mojo-parameter))
                    '())
              (required ,(if (mojo-parameter-required mojo-parameter) "true" "false"))
              (editable ,(if (mojo-parameter-editable mojo-parameter) "true" "false"))
              (description ,(mojo-parameter-description mojo-parameter))))

(define (generate-mojo-configuration mojo-parameter)
  (let ((config (mojo-parameter-configuration mojo-parameter)))
    (if (or config (mojo-parameter-property mojo-parameter))
        `(,(string->symbol (mojo-parameter-name mojo-parameter))
           (@ ,@(cons (list 'implementation (mojo-parameter-type mojo-parameter))
                      (or config '())))
          ,@(if (mojo-parameter-property mojo-parameter)
                (list (string-append "${" (mojo-parameter-property mojo-parameter)
                                     "}"))
                '()))
        #f)))

(define (generate-mojo-component mojo-component)
  (let ((role (mojo-component-role mojo-component))
        (field (mojo-component-field mojo-component))
        (hint (mojo-component-hint mojo-component)))
    `(requirement
       (role ,role)
       ,@(if hint
          `((role-hint ,hint))
          '())
       (field-name ,field))))

(define (generate-mojo mojo)
  `(mojo
     (goal ,(mojo-goal mojo))
     (description ,(mojo-description mojo))
     ,@(let ((val (mojo-requires-dependency-collection mojo)))
         (if val
             `((requiresDependencyCollection ,val))
             '()))
     ,@(let ((val (mojo-requires-dependency-resolution mojo)))
         (if val
             `((requiresDependencyResolution ,val))
             '()))
     ,@(let ((val (mojo-requires-direct-invocation? mojo)))
         (if val
             `((requiresDirectInvocation ,val))
             '()))
     ,@(let ((val (mojo-requires-project? mojo)))
         (if val
             `((requiresProject ,val))
             '()))
     ,@(let ((val (mojo-requires-reports? mojo)))
         (if val
             `((requiresReports ,val))
             '()))
     ,@(let ((val (mojo-aggregator? mojo)))
         (if val
             `((aggregator ,val))
             '()))
     ,@(let ((val (mojo-requires-online? mojo)))
         (if val
             `((requiresOnline ,val))
             '()))
     ,@(let ((val (mojo-inherited-by-default? mojo)))
         (if val
             `((inheritedByDefault ,val))
             '()))
     ,@(let ((phase (mojo-phase mojo)))
             (if phase
                 `((phase ,phase))
                 '()))
     (implementation ,(string-append (mojo-package mojo) "." (mojo-name mojo)))
     (language "java")
     (instantiationStrategy ,(mojo-instantiation-strategy mojo))
     (executionStrategy ,(mojo-execution-strategy mojo))
     ,@(let ((since (mojo-since mojo)))
             (if since
                 `((since ,since))
                 '()))
     ,@(let ((val (mojo-thread-safe? mojo)))
         (if val
             `((threadSafe ,val))
             '()))
     (parameters
       ,(map generate-mojo-parameter (mojo-parameters mojo)))
     (configuration
       ,@(filter (lambda (a) a) (map generate-mojo-configuration (mojo-parameters mojo))))
     (requirements
       ,@(map generate-mojo-component (mojo-components mojo)))))

(define (default-convert-type type)
  (cond
    ((equal? type "String") "java.lang.String")
    ((equal? type "String[]") "java.lang.String[]")
    ((equal? type "File") "java.io.File")
    ((equal? type "File[]") "java.io.File[]")
    ((equal? type "List") "java.util.List")
    ((equal? type "Boolean") "java.lang.Boolean")
    ((equal? type "Properties") "java.util.Properties")
    ((and (> (string-length type) 5)
          (equal? (substring type 0 4) "Map<"))
     "java.util.Map")
    ((and (> (string-length type) 6)
          (equal? (substring type 0 5) "List<"))
     "java.util.List")
    ((and (> (string-length type) 15)
          (equal? (substring type 0 14) "LinkedHashSet<"))
     "java.util.LinkedHashSet")
    (else type)))

(define (maven-convert-type type)
  (cond
    ((equal? type "MavenProject")
     "org.apache.maven.project.MavenProject")
    (else (default-convert-type type))))

(define (update-mojo-from-file mojo file convert-type)
  (define parse-tree (parse-java-file file))

  (define (update-mojo-from-attrs mojo attrs)
    (let loop ((mojo mojo) (attrs attrs))
      (match attrs
        ('() mojo)
        ((attr attrs ...)
         (match attr
           (('annotation-attr ('attr-name name) ('attr-value value))
            (cond
              ((equal? name "name")
               (loop (update-mojo mojo #:goal value) attrs))
              ((equal? name "defaultPhase")
               (let* ((phase (car (reverse (string-split value #\.))))
                      (phase (string-downcase phase))
                      (phase (string-join (string-split phase #\_) "-")))
               (loop (update-mojo mojo #:phase phase) attrs)))
              ((equal? name "requiresProject")
               (loop (update-mojo mojo #:requires-project? value) attrs))
              ((equal? name "threadSafe")
               (loop (update-mojo mojo #:thread-safe? value) attrs))
              ((equal? name "aggregator")
               (loop (update-mojo mojo #:aggregator? value) attrs))
              ((equal? name "requiresDependencyCollection")
               (loop
                 (update-mojo mojo #:requires-dependency-collection
                              (match value
                                ("ResolutionScope.COMPILE" "compile")
                                ("ResolutionScope.COMPILE_PLUS_RUNTIME"
                                 "compile+runtime")
                                ("ResolutionScope.RUNTIME" "runtime")
                                ("ResolutionScope.RUNTIME_PLUS_SYSTEM"
                                 "runtime+system")
                                ("ResolutionScope.TEST" "test")
                                ("ResolutionScope.PROVIDED" "provided")
                                ("ResolutionScope.SYSTEM" "system")
                                ("ResolutionScope.IMPORT" "import")))
                 attrs))
              ((equal? name "requiresDependencyResolution")
               (loop
                 (update-mojo mojo #:requires-dependency-resolution
                              (match value
                                ("ResolutionScope.COMPILE" "compile")
                                ("ResolutionScope.COMPILE_PLUS_RUNTIME"
                                 "compile+runtime")
                                ("ResolutionScope.RUNTIME" "runtime")
                                ("ResolutionScope.RUNTIME_PLUS_SYSTEM"
                                 "runtime+system")
                                ("ResolutionScope.TEST" "test")
                                ("ResolutionScope.PROVIDED" "provided")
                                ("ResolutionScope.SYSTEM" "system")
                                ("ResolutionScope.IMPORT" "import")))
                 attrs))
              (else
                (throw 'not-found-attr name))))
           ((attrs ...) (loop mojo attrs))
           (_ (loop mojo attrs)))))))

  (define (string->attr name)
    (define (string-split-upper s)
      (let ((i (string-index s char-set:upper-case)))
        (if (and i (> i 0))
            (cons (substring s 0 i) (string-split-upper (substring s i)))
            (list s))))
    (string->symbol
      (string-join (map string-downcase (string-split-upper name)) "-")))

  (define (update-mojo-parameter-from-attrs mojo-parameter attrs)
    (match attrs
      ('() mojo-parameter)
      (('annotation-attr ('attr-name name) 'attr-value)
       mojo-parameter)
       ;(update-mojo-parameter-from-attrs mojo-parameter
       ;  `(annotation-attr (attr-name ,name) (attr-value ""))))
      (('annotation-attr ('attr-name name) ('attr-value value))
       (cond
         ((equal? name "editable")
          (update-mojo-parameter mojo-parameter #:editable value))
         ((equal? name "required")
          (update-mojo-parameter mojo-parameter #:required value))
         ((equal? name "property")
          (update-mojo-parameter mojo-parameter #:property value))
         (else
           (update-mojo-parameter mojo-parameter
                                  #:configuration
                                  (cons
                                    (list (string->attr name) value)
                                    (or
				      (mojo-parameter-configuration mojo-parameter)
				      '()))))))
      ((attr attrs ...)
       (update-mojo-parameter-from-attrs
         (update-mojo-parameter-from-attrs mojo-parameter attr)
         attrs))))

  (define (update-mojo-component-from-attrs mojo-component inverse-import attrs)
    (match attrs
      ('() mojo-component)
      ((attr attrs ...)
       (match attr
         (('annotation-attr ('attr-name name) ('attr-value value))
          (cond
            ((equal? name "role")
             (update-mojo-component-from-attrs
               (update-mojo-component mojo-component
                 #:role (select-import inverse-import value convert-type))
               inverse-import
               attrs))
            ((equal? name "hint")
             (update-mojo-component-from-attrs
               (update-mojo-component mojo-component #:hint value)
               inverse-import
               attrs))
            (else (throw 'not-found-attr name))))
         ((attrss ...)
          (update-mojo-component-from-attrs
            mojo-component inverse-import (append attrss attrs)))))))

  (define (add-mojo-parameter parameters name type last-comment attrs inverse-import)
    (let loop ((parameters parameters))
      (match parameters
        ('() (list (update-mojo-parameter-from-attrs
                     (make-mojo-parameter
                       ;; name convert since required editable property comment config
                       name (select-import inverse-import type convert-type)
                       #f #f #t #f last-comment #f)
                     attrs)))
        ((parameter parameters ...)
         (if (equal? (mojo-parameter-name parameter) name)
             (cons (update-mojo-parameter-from-attrs
                     (make-mojo-parameter
                       name (select-import inverse-import type convert-type)
                       #f #f #t #f last-comment #f)
                     attrs) parameters)
             (cons parameter (loop parameters)))))))

  (define (update-mojo-from-class-content mojo inverse-import content)
    (let loop ((content content)
               (mojo mojo)
               (last-comment #f))
      (match content
        ('() mojo)
        ((('comment ('annotation-pat _ ...) last-comment) content ...)
         (loop content mojo last-comment))
        ((('comment last-comment) content ...)
         (loop content mojo last-comment))
        ((('param-pat ('annotation-pat annot-name attrs ...) ('type-name type)
           ('param-name name)) content ...)
         (cond
           ((equal? annot-name "Parameter")
            (loop content
                  (update-mojo mojo
                               #:parameters
                               (add-mojo-parameter
                                 (mojo-parameters mojo) name type last-comment
                                 attrs inverse-import))
                  #f))
           ((equal? annot-name "Component")
            (loop content
                  (update-mojo mojo
                               #:components
                               (cons (update-mojo-component-from-attrs
                                       (make-mojo-component
                                         name
                                         (select-import inverse-import type
                                                        convert-type)
                                         #f)
                                       inverse-import
                                       attrs)
                                     (mojo-components mojo)))
                  #f))
           (else (throw 'not-found-annot annot-name))))
        ((('class-pat _ ...) content ...)
         (loop content mojo #f))
        ((('param-pat _ ...) content ...)
         (loop content mojo #f))
        ((('method-pat _ ...) content ...)
         (loop content mojo #f)))))

  (define (update-inverse-import inverse-import package)
    (let ((package-name (car (reverse (string-split package #\.)))))
      (cons (cons package-name package) inverse-import)))

  (define (select-import inverse-import package convert-type)
    (let* ((package (car (string-split package #\<)))
           (package (string-split package #\.))
           (rest (reverse (cdr package)))
           (rest (cond
                   ((null? rest) '())
                   ((equal? (car rest) "class") (cdr rest))
                   (else rest)))
           (base (or (assoc-ref inverse-import (car package)) (car package))))
      (convert-type (string-join (cons base rest) "."))))

  (let loop ((content parse-tree)
             (mojo mojo)
             (inverse-import '())
             (last-comment #f))
    (if (null? content)
        mojo
        (match content
          ((tls content ...)
           (match tls
             (('package package)
              (loop content (update-mojo mojo #:package package) inverse-import
                    last-comment))
             (('import-pat package)
              (loop content mojo (update-inverse-import inverse-import package)
                    last-comment))
             (('comment last-comment)
              (loop content mojo inverse-import last-comment))
             (('class-pat class-tls ...)
              (let loop2 ((class-tls class-tls) (mojo mojo))
                (match class-tls
                  ('() (loop content mojo inverse-import #f))
                  (((? string? name) class-tls ...)
                   (loop2 class-tls (update-mojo mojo #:name name)))
                  ((('annotation-pat annot-name (attrs ...)) class-tls ...)
                   (loop2
                     class-tls
                     (update-mojo-from-attrs mojo attrs)))
                  ((('class-body class-content ...) class-tls ...)
                   (loop2
                     class-tls
                     (update-mojo-from-class-content
                       mojo inverse-import class-content)))
                  ((_ class-tls ...)
                   (loop2 class-tls mojo)))))
             (_
              (loop content mojo inverse-import last-comment))))))))

(define (generate-mojo-from-files convert-type . files)
  (let ((mojo (make-mojo #f #f #f #f #f #f #f #f #f #f #f #f "per-lookup"
                         "once-per-session" #f #f #f '() '())))
    (let loop ((files files) (mojo mojo))
      (if (null? files)
          (generate-mojo mojo)
          (loop
            (cdr files)
            (update-mojo-from-file
              (update-mojo mojo
                #:package #f
                #:name #f
                #:goal #f
                #:description #f
                #:requires-dependency-resolution #f
                #:requires-direct-invocation? #f
                #:requires-project? #f
                #:requires-reports? #f
                #:aggregator? #f
                #:requires-online? #f
                #:inherited-by-default? #f
                #:instantiation-strategy "per-lookup"
                #:execution-strategy "once-per-session"
                #:since #f
                #:thread-safe? #f
                #:phase #f)
              (car files)
	      convert-type))))))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2019, 2020 Julien Lepiller <julien@lepiller.eu>
;;;
;;; 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 maven pom)
  #:use-module (sxml simple)
  #:use-module (system foreign)
  #:use-module (ice-9 match)
  #:use-module (srfi srfi-1)
  #:export (get-pom
            pom-ref
            pom-description
            pom-name
            pom-version
            pom-artifactid
            pom-groupid
            pom-dependencies
            group->dir
            fix-pom-dependencies))

(define (get-pom file)
  "Return the content of a @file{.pom} file."
  (let ((pom-content (call-with-input-file file xml->sxml)))
    (match pom-content
      (('*TOP* _ (_ ('@ _ ...) content ...))
        content)
      (('*TOP* (_ ('@ _ ...) content ...))
       content)
      (('*TOP* _ (_ content ...))
        content)
      (('*TOP* (_ content ...))
       content))))

(define (pom-ref content attr)
  "Gets a value associated to @var{attr} in @var{content}, an sxml value that
represents a @file{.pom} file content, or parts of it."
  (or
    (assoc-ref
      content
      (string->symbol
        (string-append "http://maven.apache.org/POM/4.0.0:" attr)))
    (assoc-ref content (string->symbol attr))))

(define (get-parent content)
  (pom-ref content "parent"))

(define* (find-parent content inputs #:optional local-packages)
  "Find the parent pom for the pom file whith @var{content} in a package's
@var{inputs}.  When the parent pom cannot be found in @var{inputs}, but
@var{local-packages} is defined, the parent pom is looked up in it.

@var{local-packages} is an association list of groupID to an association list
of artifactID to version number.

The result is an sxml document that describes the content of the parent pom, or
of an hypothetical parent pom if it was generated from @var{local-packages}.
If no result is found, the result is @code{#f}."
  (let ((parent (pom-ref content "parent")))
    (if parent
        (let* ((groupid (car (pom-ref parent "groupId")))
               (artifactid (car (pom-ref parent "artifactId")))
               (version (car (pom-ref parent "version")))
               (pom-file (string-append "lib/m2/" (group->dir groupid)
                                        "/" artifactid "/" version "/"
                                        artifactid "-" version ".pom"))
               (java-inputs (filter
                              (lambda (input)
                                (file-exists? (string-append input "/" pom-file)))
                              inputs))
               (java-inputs (map (lambda (input) (string-append input "/" pom-file))
                                 java-inputs)))
          (if (null? java-inputs)
              (let ((version (assoc-ref (assoc-ref local-packages groupid) artifactid)))
                (if version
                    `((groupId ,groupid)
                      (artifactId ,artifactid)
                      (version ,version))
                    #f))
              (get-pom (car java-inputs))))
        #f)))

(define* (pom-groupid content inputs #:optional local-packages)
  "Find the groupID of a pom file, potentially looking at its parent pom file.
See @code{find-parent} for the meaning of the arguments."
  (if content
    (let ((res (or (pom-ref content "groupId")
                   (pom-groupid (find-parent content inputs local-packages)
                                inputs))))
      (cond
        ((string? res) res)
        ((null? res) #f)
        ((list? res) (car res))
        (else #f)))
    #f))

(define (pom-artifactid content)
  "Find the artifactID of a pom file, from its sxml @var{content}."
  (let ((res (pom-ref content "artifactId")))
    (if (and res (>= (length res) 1))
      (car res)
      #f)))

(define* (pom-version content inputs #:optional local-packages)
  "Find the version of a pom file, potentially looking at its parent pom file.
See @code{find-parent} for the meaning of the arguments."
  (if content
    (let ((res (or (pom-ref content "version")
                   (pom-version (find-parent content inputs local-packages)
                                inputs))))
      (cond
        ((string? res) res)
        ((null? res) #f)
        ((list? res) (car res))
        (else #f)))
    #f))

(define (pom-name content)
  "Return the name of the package as contained in the sxml @var{content} of the
pom file."
  (let ((res (pom-ref content "name")))
    (if (and res (>= (length res) 1))
      (car res)
      #f)))

(define (pom-description content)
  "Return the description of the package as contained in the sxml @var{content}
of the pom file."
  (let ((res (pom-ref content "description")))
    (if (and res (>= (length res) 1))
      (car res)
      #f)))

(define (pom-dependencies content)
  "Return the list of dependencies listed in the sxml @var{content} of the pom
file."
  (filter
    (lambda (a) a)
    (map
      (match-lambda
        ((? string? _) #f)
        (('http://maven.apache.org/POM/4.0.0:dependency content ...)
         (let loop ((content content) (groupid #f) (artifactid #f) (version #f) (scope #f))
           (match content
             ('()
              `(dependency
                 (groupId ,groupid)
                 (artifactId ,artifactid)
                 (version ,version)
                 ,@(if scope `((scope ,scope)) '())))
             (((? string? _) content ...)
              (loop content groupid artifactid version scope))
             ((('http://maven.apache.org/POM/4.0.0:scope scope) content ...)
              (loop content groupid artifactid version scope))
             ((('http://maven.apache.org/POM/4.0.0:groupId groupid) content ...)
              (loop content groupid artifactid version scope))
             ((('http://maven.apache.org/POM/4.0.0:artifactId artifactid) content ...)
              (loop content groupid artifactid version scope))
             ((('http://maven.apache.org/POM/4.0.0:version version) content ...)
              (loop content groupid artifactid version scope))
             ((_ content ...)
              (loop content groupid artifactid version scope))))))
      (pom-ref content "dependencies"))))

(define version-compare
  (let ((strverscmp
         (let ((sym (or (dynamic-func "strverscmp" (dynamic-link))
                        (error "could not find `strverscmp' (from GNU libc)"))))
           (pointer->procedure int sym (list '* '*)))))
    (lambda (a b)
      "Return '> when A denotes a newer version than B,
'< when A denotes a older version than B,
or '= when they denote equal versions."
      (let ((result (strverscmp (string->pointer a) (string->pointer b))))
        (cond ((positive? result) '>)
              ((negative? result) '<)
              (else '=))))))

(define (version>? a b)
  "Return #t when A denotes a version strictly newer than B."
  (eq? '> (version-compare a b)))

(define (fix-maven-xml sxml)
  "When writing an xml file from an sxml representation, it is not possible to
use namespaces in tag names.  This procedure takes an @var{sxml} representation
of a pom file and removes the namespace uses.  It also adds the required bits
to re-declare the namespaces in the top-level element."
  (define (fix-xml sxml)
    (match sxml
      ((tag ('@ opts ...) rest ...)
       (if (> (string-length (symbol->string tag))
              (string-length "http://maven.apache.org/POM/4.0.0:"))
         (let* ((tag (symbol->string tag))
                (tag (substring tag (string-length
                                      "http://maven.apache.org/POM/4.0.0:")))
                (tag (string->symbol tag)))
           `(,tag (@ ,@opts) ,@(map fix-xml rest)))
         `(,tag (@ ,@opts) ,@(map fix-xml rest))))
      ((tag (rest ...))
       (if (> (string-length (symbol->string tag))
              (string-length "http://maven.apache.org/POM/4.0.0:"))
         (let* ((tag (symbol->string tag))
                (tag (substring tag (string-length
                                      "http://maven.apache.org/POM/4.0.0:")))
                (tag (string->symbol tag)))
           `(,tag ,@(map fix-xml rest)))
         `(,tag ,@(map fix-xml rest))))
      ((tag rest ...)
       (if (> (string-length (symbol->string tag))
              (string-length "http://maven.apache.org/POM/4.0.0:"))
         (let* ((tag (symbol->string tag))
                (tag (substring tag (string-length
                                      "http://maven.apache.org/POM/4.0.0:")))
                (tag (string->symbol tag)))
           `(,tag ,@(map fix-xml rest)))
         `(,tag ,@(map fix-xml rest))))
      (_ sxml)))

  `((*TOP* (*PI* xml "version=\"1.0\" encoding=\"UTF-8\"")
     (project (@ (xmlns "http://maven.apache.org/POM/4.0.0")
                 (xmlns:xsi "http://www.w3.org/2001/XMLSchema-instance")
                 (xmlns:schemaLocation "http://maven.apache.org/POM/4.0.0
                   http://maven.apache.org/xsd/maven-4.0.0.xsd"))
       ,(map fix-xml sxml)))))

(define (group->dir group)
  "Convert a group ID to a directory path."
  (string-join (string-split group #\.) "/"))

(define* (fix-pom-dependencies pom-file inputs
                               #:key with-plugins? with-build-dependencies?
                                     (excludes '()) (local-packages '()))
  "Open @var{pom-file}, and override its content, rewritting its dependencies
to set their version to the latest version available in the @var{inputs}.

@var{#:with-plugins?} controls whether plugins are also overiden.
@var{#:with-build-dependencies?} controls whether build dependencies (whose
scope is not empty) are also overiden.  By default build dependencies and
plugins are not overiden.

@var{#:excludes} is an association list of groupID to a list of artifactIDs.
When a pair (groupID, artifactID) is present in the list, its entry is
removed instead of being overiden.  If the entry is ignored because of the
previous arguments, the entry is not removed.

@var{#:local-packages} is an association list that contains additional version
information for packages that are not in @var{inputs}.  If the package is
not found in @var{inputs}, information from this list is used instead to determine
the latest version of the package.  This is an association list of group IDs
to another association list of artifact IDs to a version number.

Returns nothing, but overides the @var{pom-file} as a side-effect."
  (define pom (get-pom pom-file))

  (define (ls dir)
    (let ((dir (opendir dir)))
      (let loop ((res '()))
        (let ((entry (readdir dir)))
          (if (eof-object? entry)
              res
              (loop (cons entry res)))))))

  (define fix-pom
    (match-lambda
      ('() '())
      ((tag rest ...)
       (match tag
         (('http://maven.apache.org/POM/4.0.0:dependencies deps ...)
          `((http://maven.apache.org/POM/4.0.0:dependencies ,(fix-deps deps))
            ,@(fix-pom rest)))
         (('http://maven.apache.org/POM/4.0.0:dependencyManagement deps ...)
          `((http://maven.apache.org/POM/4.0.0:dependencyManagement
              ,(fix-dep-management deps))
            ,@(fix-pom rest)))
         (('http://maven.apache.org/POM/4.0.0:build build ...)
          (if with-plugins?
              `((http://maven.apache.org/POM/4.0.0:build ,(fix-build build))
                ,@(fix-pom rest))
              (cons tag (fix-pom rest))))
         (tag (cons tag (fix-pom rest)))))))

  (define fix-dep-management
    (match-lambda
      ('() '())
      ((tag rest ...)
       (match tag
         (('http://maven.apache.org/POM/4.0.0:dependencies deps ...)
          `((http://maven.apache.org/POM/4.0.0:dependencies ,(fix-deps deps #t))
            ,@(fix-dep-management rest)))
         (tag (cons tag (fix-dep-management rest)))))))

  (define* (fix-deps deps #:optional optional?)
    (match deps
      ('() '())
      ((tag rest ...)
       (match tag
         (('http://maven.apache.org/POM/4.0.0:dependency dep ...)
          `((http://maven.apache.org/POM/4.0.0:dependency ,(fix-dep dep optional?))
            ,@(fix-deps rest optional?)))
         (tag (cons tag (fix-deps rest optional?)))))))

  (define fix-build
    (match-lambda
      ('() '())
      ((tag rest ...)
       (match tag
         (('http://maven.apache.org/POM/4.0.0:pluginManagement management ...)
          `((http://maven.apache.org/POM/4.0.0:pluginManagement
              ,(fix-management management))
            ,@(fix-build rest)))
         (('http://maven.apache.org/POM/4.0.0:plugins plugins ...)
          `((http://maven.apache.org/POM/4.0.0:plugins
              ,(fix-plugins plugins))
            ,@(fix-build rest)))
         (tag (cons tag (fix-build rest)))))))

  (define fix-management
    (match-lambda
      ('() '())
      ((tag rest ...)
       (match tag
         (('http://maven.apache.org/POM/4.0.0:plugins plugins ...)
          `((http://maven.apache.org/POM/4.0.0:plugins
              ,(fix-plugins plugins #t))
            ,@(fix-management rest)))
         (tag (cons tag (fix-management rest)))))))

  (define* (fix-plugins plugins #:optional optional?)
    (match plugins
      ('() '())
      ((tag rest ...)
       (match tag
         (('http://maven.apache.org/POM/4.0.0:plugin plugin ...)
          (let ((group (or (pom-groupid plugin inputs) "org.apache.maven.plugins"))
                (artifact (pom-artifactid plugin)))
            (if (member artifact (or (assoc-ref excludes group) '()))
              (fix-plugins rest optional?)
              `((http://maven.apache.org/POM/4.0.0:plugin
                  ,(fix-plugin plugin optional?))
                ,@(fix-plugins rest optional?)))))
         (tag (cons tag (fix-plugins rest optional?)))))))

  (define* (fix-plugin plugin #:optional optional?)
    (let* ((artifact (pom-artifactid plugin))
           (group (or (pom-groupid plugin inputs) "org.apache.maven.plugins"))
           (version (or (assoc-ref (assoc-ref local-packages group) artifact)
                        (find-version inputs group artifact optional?)
                        (pom-version plugin inputs))))
      (if (pom-version plugin inputs)
        (map
          (lambda (tag)
            (match tag
              (('http://maven.apache.org/POM/4.0.0:version _)
               `(http://maven.apache.org/POM/4.0.0:version ,version))
              (('version _)
               `(http://maven.apache.org/POM/4.0.0:version ,version))
              (tag tag)))
          plugin)
        (cons `(http://maven.apache.org/POM/4.0.0:version ,version) plugin))))

  (define* (fix-dep dep #:optional optional?)
    (let* ((artifact (pom-artifactid dep))
           (group (or (pom-groupid dep inputs) (pom-groupid pom inputs)))
           (scope (pom-ref dep "scope"))
           (is-optional? (equal? (pom-ref dep "optional") '("true"))))
      (format (current-error-port) "maven: ~a:~a :: ~a (optional: ~a)~%"
              group artifact scope optional?)
      (if (or (and (not (equal? scope '("test"))) (not is-optional?))
              with-build-dependencies?)
          (let ((version (or (assoc-ref (assoc-ref local-packages group) artifact)
                             (find-version inputs group artifact optional?)
                             (pom-version dep inputs))))
            (if (pom-version dep inputs)
              (map
                (lambda (tag)
                  (match tag
                    (('http://maven.apache.org/POM/4.0.0:version _)
                     `(http://maven.apache.org/POM/4.0.0:version ,version))
                    (('version _)
                     `(http://maven.apache.org/POM/4.0.0:version ,version))
                    (_ tag)))
                dep)
              (cons `(http://maven.apache.org/POM/4.0.0:version ,version) dep)))
          dep)))

  (define* (find-version inputs group artifact #:optional optional?)
    (let* ((directory (string-append "lib/m2/" (group->dir group)
                                     "/" artifact))
           (java-inputs (filter
                          (lambda (input)
                            (file-exists? (string-append input "/" directory)))
                          inputs))
           (java-inputs (map (lambda (input) (string-append input "/" directory))
                             java-inputs))
           (versions (append-map ls java-inputs))
           (versions (sort versions version>?)))
      (if (null? versions)
        (if optional?
          #f
          (begin
            (format (current-error-port) "maven: ~a:~a is missing from inputs~%"
                    group artifact)
            (throw 'no-such-input group artifact)))
        (car versions))))

  (let ((tmpfile (string-append pom-file ".tmp")))
    (with-output-to-file pom-file
      (lambda _
        (sxml->xml (fix-maven-xml (fix-pom pom)))))))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2017 Peter Mikkelsen <petermikkelsen10@gmail.com>
;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2018 Marius Bakke <mbakke@fastmail.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 meson-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module ((guix build glib-or-gtk-build-system) #:prefix glib-or-gtk:)
  #:use-module (guix build utils)
  #:use-module (guix build gremlin)
  #:use-module (guix elf)
  #:use-module (ice-9 match)
  #:use-module (rnrs io ports)
  #:use-module (srfi srfi-1)
  #:export (%standard-phases
            meson-build))

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

(define* (configure #:key outputs configure-flags build-type
                    #:allow-other-keys)
  "Configure the given package."
  (let* ((out (assoc-ref outputs "out"))
         (source-dir (getcwd))
         (build-dir "../build")
         (prefix (assoc-ref outputs "out"))
         (args `(,(string-append "--prefix=" prefix)
                 ,(string-append "--buildtype=" build-type)
                 ,(string-append "-Dc_link_args=-Wl,-rpath="
                                 (assoc-ref outputs "out") "/lib")
                 ,(string-append "-Dcpp_link_args=-Wl,-rpath="
                                 (assoc-ref outputs "out") "/lib")
                 ,@configure-flags
                 ,source-dir)))

    (mkdir build-dir)
    (chdir build-dir)
    (apply invoke "meson" args)))

(define* (build #:key parallel-build?
                #:allow-other-keys)
  "Build a given meson package."
  (invoke "ninja" "-j" (if parallel-build?
                           (number->string (parallel-job-count))
                           "1")))

(define* (check #:key test-target parallel-tests? tests?
                #:allow-other-keys)
  (setenv "MESON_TESTTHREADS"
          (if parallel-tests?
              (number->string (parallel-job-count))
              "1"))
  (if tests?
      (invoke "ninja" test-target)
      (format #t "test suite not run~%"))
  #t)

(define* (install #:rest args)
  (invoke "ninja" "install"))

(define* (shrink-runpath #:key (elf-directories '("lib" "lib64" "libexec"
                                                  "bin" "sbin"))
                         outputs #:allow-other-keys)
  "Go through all ELF files from ELF-DIRECTORIES and shrink the RUNPATH
since a lot of directories are left over from the build phase of meson,
for example libraries only needed for the tests."

  (define handle-output
    (match-lambda
      ((output . directory)
       (let* ((elf-dirnames (map (lambda (subdir)
                                   (string-append directory "/" subdir))
                                 elf-directories))
              (existing-elf-dirs (filter (lambda (dir)
                                            (and (file-exists? dir)
                                                 (file-is-directory? dir)))
                                          elf-dirnames))
              (elf-pred (lambda (name stat)
                          (elf-file? name)))
              (elf-list (concatenate (map (lambda (dir)
                                            (find-files dir elf-pred))
                                          existing-elf-dirs))))
         (for-each strip-runpath elf-list)))))
  (for-each handle-output outputs)
  #t)

(define %standard-phases
  ;; The standard-phases of glib-or-gtk contains a superset of the phases
  ;; from the gnu-build-system.  If the glib-or-gtk? key is #f (the default)
  ;; then the extra phases will be removed again in (guix build-system meson).
  (modify-phases glib-or-gtk:%standard-phases
    (delete 'bootstrap)
    (replace 'configure configure)
    (replace 'build build)
    (replace 'check check)
    (replace 'install install)
    (add-after 'strip 'shrink-runpath shrink-runpath)))

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

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


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2016 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2020 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 minify-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module ((guix build minify-build-system) #:prefix minify:)
  #:use-module (guix build utils)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:use-module (ice-9 popen)
  #:export (%standard-phases
            minify-build
            minify))

;; Commentary:
;;
;; Builder-side code of the standard minification procedure for JavaScript
;; files.
;;
;; Code:

(define* (minify file #:key target (directory ""))
  (format #t "minifying ~a\n" file)
  (let* ((base (basename file ".js"))
         (installed (or target (string-append directory base ".min.js")))
         (minified (open-pipe* OPEN_READ "uglify-js" file)))
    (call-with-output-file installed
      (cut dump-port minified <>))
    #t))

(define* (build #:key javascript-files
                #:allow-other-keys)
  (let ((files (or javascript-files
                   (find-files "src" "\\.js$"))))
    (mkdir-p "guix/build")
    (every (cut minify <> #:directory "guix/build/") files)))

(define* (install #:key outputs #:allow-other-keys)
  (let* ((out (assoc-ref outputs "out"))
         (js  (string-append out "/share/javascript/")))
    (mkdir-p js)
    (for-each
      (lambda (file)
        (if (not (zero? (stat:size (stat file))))
          (install-file file js)
          (error "File is empty: " file)))
      (find-files "guix/build" "\\.min\\.js$")))
  #t)

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

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

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


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015 David Thompson <davet@gnu.org>
;;; Copyright © 2016 Jelle Licht <jlicht@fsfe.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 node-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module (guix build json)
  #:use-module (guix build union)
  #:use-module (guix build utils)
  #:use-module (ice-9 match)
  #:use-module (ice-9 popen)
  #:use-module (ice-9 regex)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:export (%standard-phases
            node-build))

;; Commentary:
;;
;; Builder-side code of the standard Node/npm package build procedure.
;;
;; Code:

(define* (read-package-data #:key (filename "package.json"))
  (call-with-input-file filename
    (lambda (port)
      (read-json port))))

(define* (build #:key inputs #:allow-other-keys)
  (define (build-from-package-json? package-file)
    (let* ((package-data (read-package-data #:filename package-file))
           (scripts (assoc-ref package-data "scripts")))
      (assoc-ref scripts "build")))
  "Build a new node module using the appropriate build system."
  ;; XXX: Develop a more robust heuristic, allow override
  (cond ((file-exists? "gulpfile.js")
         (invoke "gulp"))
        ((file-exists? "gruntfile.js")
         (invoke "grunt"))
        ((file-exists? "Makefile")
         (invoke "make"))
        ((and (file-exists? "package.json")
              (build-from-package-json? "package.json"))
         (invoke "npm" "run" "build")))
  #t)

(define* (link-npm-dependencies #:key inputs #:allow-other-keys)
  (define (inputs->node-inputs inputs)
    "Filter the directory part from INPUTS."
    (filter (lambda (input)
              (match input
                ((name . _) (node-package? name))))
            inputs))
  (define (inputs->directories inputs)
    "Extract the directory part from INPUTS."
    (match inputs
      (((names . directories) ...)
       directories)))
  (define (make-node-path root)
    (string-append root "/lib/node_modules/"))

  (let ((input-node-directories (inputs->directories
                                 (inputs->node-inputs inputs))))
    (union-build "node_modules"
                 (map make-node-path input-node-directories))
    #t))

(define configure link-npm-dependencies)

(define* (check #:key tests? #:allow-other-keys)
  "Run 'npm test' if TESTS?"
  (if tests?
      ;; Should only be enabled once we know that there are tests
      (invoke "npm" "test"))
  #t)

(define (node-package? name)
  "Check if NAME correspond to the name of an Node package."
  (string-prefix? "node-" name))

(define* (install #:key outputs inputs #:allow-other-keys)
  "Install the node module to the output store item. The module itself is
installed in a subdirectory of @file{node_modules} and its runtime dependencies
as defined by @file{package.json} are symlinked into a @file{node_modules}
subdirectory of the module's directory. Additionally, binaries are installed in
the @file{bin} directory."
  (let* ((out                  (assoc-ref outputs "out"))
         (target               (string-append out "/lib"))
         (binaries             (string-append out "/bin"))
         (data                 (read-package-data))
         (modulename           (assoc-ref data "name"))
         (binary-configuration (match (assoc-ref data "bin")
				 (('@ configuration ...) configuration)
				 ((? string? configuration) configuration)
				 (#f #f)))
         (dependencies (match (assoc-ref data "dependencies")
                         (('@ deps ...) deps)
                         (#f #f))))
    (mkdir-p target)
    (copy-recursively "." (string-append target "/node_modules/" modulename))
    ;; Remove references to dependencies
    (delete-file-recursively
      (string-append target "/node_modules/" modulename "/node_modules"))
    (cond
      ((string? binary-configuration)
       (begin
         (mkdir-p binaries)
         (symlink (string-append target "/node_modules/" modulename "/"
				 binary-configuration)
                  (string-append binaries "/" modulename))))
      ((list? binary-configuration)
       (for-each
         (lambda (conf)
           (match conf
             ((key . value)
              (begin
                (mkdir-p (dirname (string-append binaries "/" key)))
                (symlink (string-append target "/node_modules/" modulename "/"
					value)
                         (string-append binaries "/" key))))))
         binary-configuration)))
    (when dependencies
      (mkdir-p
        (string-append target "/node_modules/" modulename "/node_modules"))
      (for-each
        (lambda (dependency)
          (let ((dependency (car dependency)))
            (symlink
              (string-append (assoc-ref inputs (string-append "node-" dependency))
                             "/lib/node_modules/" dependency)
              (string-append target "/node_modules/" modulename
                             "/node_modules/" dependency))))
        dependencies))
    #t))

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

(define* (node-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 © 2016, 2017 Julien Lepiller <julien@lepiller.eu>
;;;
;;; 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 ocaml-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module (guix build utils)
  #:use-module (ice-9 match)
  #:export (%standard-phases
            ocaml-build))

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

(define* (ocaml-findlib-environment #:key outputs #:allow-other-keys)
  (let* ((out (assoc-ref outputs "out")))
    (setenv "OCAMLFIND_DESTDIR" (string-append out "/lib/ocaml/site-lib"))
    (setenv "OCAMLFIND_LDCONF" "ignore"))
  #t)

(define* (configure #:key outputs (configure-flags '())
                    (test-flags '("--enable-tests")) tests?
                    #:allow-other-keys)
  "Configure the given package."
  (let* ((out        (assoc-ref outputs "out")))
    (format #t "build directory: ~s~%" (getcwd))
    (if (file-exists? "setup.ml")
      (let ((args `("-configure"
                    "--prefix" ,out
                    ,@(if tests?
                          test-flags
                          '())
                    ,@configure-flags)))
        (format #t "running 'setup.ml' with arguments ~s~%" args)
        (apply invoke "ocaml" "setup.ml" args))
       (let ((args `("-prefix" ,out ,@configure-flags)))
        (format #t "running 'configure' with arguments ~s~%" args)
        (apply invoke "./configure" args))))
    #t)

(define* (build #:key inputs outputs (build-flags '()) (make-flags '())
                (use-make? #f) #:allow-other-keys)
  "Build the given package."
  (if (and (file-exists? "setup.ml") (not use-make?))
    (apply invoke "ocaml" "setup.ml" "-build" build-flags)
    (if (file-exists? "Makefile")
      (apply invoke "make" make-flags)
      (let ((file (if (file-exists? "pkg/pkg.ml") "pkg/pkg.ml" "pkg/build.ml")))
        (apply invoke "ocaml" "-I"
                      (string-append (assoc-ref inputs "findlib")
                                     "/lib/ocaml/site-lib")
                      file build-flags))))
  #t)

(define* (check #:key inputs outputs (make-flags '()) (test-target "test") tests?
                  (use-make? #f) #:allow-other-keys)
  "Install the given package."
  (when tests?
    (if (and (file-exists? "setup.ml") (not use-make?))
      (invoke "ocaml" "setup.ml" (string-append "-" test-target))
      (if (file-exists? "Makefile")
        (apply invoke "make" test-target make-flags)
        (let ((file (if (file-exists? "pkg/pkg.ml") "pkg/pkg.ml" "pkg/build.ml")))
          (invoke "ocaml" "-I"
                  (string-append (assoc-ref inputs "findlib")
                                 "/lib/ocaml/site-lib")
                  file test-target)))))
  #t)

(define* (install #:key outputs (build-flags '()) (make-flags '()) (use-make? #f)
                  (install-target "install")
                  #:allow-other-keys)
  "Install the given package."
  (let ((out (assoc-ref outputs "out")))
    (if (and (file-exists? "setup.ml") (not use-make?))
      (apply invoke "ocaml" "setup.ml"
             (string-append "-" install-target) build-flags)
      (if (file-exists? "Makefile")
        (apply invoke "make" install-target make-flags)
        (invoke "opam-installer" "-i" (string-append "--prefix=" out)
                (string-append "--libdir=" out "/lib/ocaml/site-lib")))))
  #t)

(define* (prepare-install #:key outputs #:allow-other-keys)
  "Prepare for building the given package."
  (mkdir-p (string-append (assoc-ref outputs "out") "/lib/ocaml/site-lib"))
  (mkdir-p (string-append (assoc-ref outputs "out") "/bin"))
  #t)

(define %standard-phases
  ;; Everything is as with the GNU Build System except for the `configure'
  ;; , `build', `check' and `install' phases.
  (modify-phases gnu:%standard-phases
    (delete 'bootstrap)
    (add-before 'configure 'ocaml-findlib-environment
                ocaml-findlib-environment)
    (add-before 'install 'prepare-install prepare-install)
    (replace 'configure configure)
    (replace 'build build)
    (replace 'check check)
    (replace 'install install)))

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

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


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2015, 2018 Ludovic Courtès <ludo@gnu.org>
;;; 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 perl-build-system)
  #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  #:use-module (guix build utils)
  #:use-module (ice-9 match)
  #:export (%standard-phases
            perl-build))

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

(define* (configure #:key outputs make-maker?
                    (make-maker-flags '()) (module-build-flags '())
                    #:allow-other-keys)
  "Configure the given Perl package."
  (let* ((out (assoc-ref outputs "out"))
         (args (cond
                ;; Prefer to use Module::Build unless otherwise told
                ((and (file-exists? "Build.PL")
                      (not make-maker?))
                 `("Build.PL" ,(string-append "--prefix=" out)
                   "--installdirs=site" ,@module-build-flags))
                ((file-exists? "Makefile.PL")
                 `("Makefile.PL" ,(string-append "PREFIX=" out)
                   ;; Prevent installation of 'perllocal.pod' files for
                   ;; determinism.  These are typically used to build a
                   ;; catalogue of installed packages, but does not provide
                   ;; any useful information when installed with a module.
                   "INSTALLDIRS=site" "NO_PERLLOCAL=1" ,@make-maker-flags))
                (else (error "no Build.PL or Makefile.PL found")))))
    (format #t "running `perl' with arguments ~s~%" args)
    (apply invoke "perl" args)))

(define-syntax-rule (define-w/gnu-fallback* (name args ...) body ...)
  (define* (name args ... #:rest rest)
    (if (access? "Build" X_OK)
        (begin body ...)
        (apply (assoc-ref gnu:%standard-phases 'name) rest))))

(define-w/gnu-fallback* (build)
  (invoke "./Build"))

(define-w/gnu-fallback* (check #:key target
                               (tests? (not target)) (test-flags '())
                               #:allow-other-keys)
  (if tests?
      (apply invoke "./Build" "test" test-flags)
      (format #t "test suite not run~%"))
  #t)

(define-w/gnu-fallback* (install)
  (invoke "./Build" "install"))

(define %standard-phases
  ;; Everything is as with the GNU Build System except for the `configure',
  ;; `build', `check', and `install' phases.
  (modify-phases gnu:%standard-phases
    (delete 'bootstrap)
    (replace 'install install)
    (replace 'check check)
    (replace 'build build)
    (replace 'configure configure)))

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

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