python-build-system.scm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2013, 2015, 2016, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2013 Andreas Enge <andreas@enge.fr>
  4. ;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
  5. ;;; Copyright © 2015, 2018 Mark H Weaver <mhw@netris.org>
  6. ;;; Copyright © 2016 Hartmut Goebel <h.goebel@crazy-compilers.com>
  7. ;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
  8. ;;; Copyright © 2018 Arun Isaac <arunisaac@systemreboot.net>
  9. ;;; Copyright © 2019, 2020, 2021 Maxim Cournoyer <maxim.cournoyer@gmail.com>
  10. ;;; Copyright © 2020 Jakub Kądziołka <kuba@kadziolka.net>
  11. ;;; Copyright © 2020 Efraim Flashner <efraim@flashner.co.il>
  12. ;;; Copyright © 2021 Lars-Dominik Braun <lars@6xq.net>
  13. ;;; Copyright © 2021 Maxime Devos <maximedevos@telenet.be>
  14. ;;;
  15. ;;; This file is part of GNU Guix.
  16. ;;;
  17. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  18. ;;; under the terms of the GNU General Public License as published by
  19. ;;; the Free Software Foundation; either version 3 of the License, or (at
  20. ;;; your option) any later version.
  21. ;;;
  22. ;;; GNU Guix is distributed in the hope that it will be useful, but
  23. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  24. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. ;;; GNU General Public License for more details.
  26. ;;;
  27. ;;; You should have received a copy of the GNU General Public License
  28. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  29. (define-module (guix build python-build-system)
  30. #:use-module ((guix build gnu-build-system) #:prefix gnu:)
  31. #:use-module (guix build utils)
  32. #:use-module (ice-9 match)
  33. #:use-module (ice-9 ftw)
  34. #:use-module (ice-9 format)
  35. #:use-module (srfi srfi-1)
  36. #:use-module (srfi srfi-26)
  37. #:export (%standard-phases
  38. add-installed-pythonpath
  39. site-packages
  40. python-version
  41. python-build))
  42. ;; Commentary:
  43. ;;
  44. ;; Builder-side code of the standard Python package build procedure.
  45. ;;
  46. ;;
  47. ;; Backgound about the Python installation methods
  48. ;;
  49. ;; In Python there are different ways to install packages: distutils,
  50. ;; setuptools, easy_install and pip. All of these are sharing the file
  51. ;; setup.py, introduced with distutils in Python 2.0. The setup.py file can be
  52. ;; considered as a kind of Makefile accepting targets (or commands) like
  53. ;; "build" and "install". As of autumn 2016 the recommended way to install
  54. ;; Python packages is using pip.
  55. ;;
  56. ;; For both distutils and setuptools, running "python setup.py install" is the
  57. ;; way to install Python packages. With distutils the "install" command
  58. ;; basically copies all packages into <prefix>/lib/pythonX.Y/site-packages.
  59. ;;
  60. ;; Some time later "setuptools" was established to enhance distutils. To use
  61. ;; setuptools, the developer imports setuptools in setup.py. When importing
  62. ;; setuptools, the original "install" command gets overwritten by setuptools'
  63. ;; "install" command.
  64. ;;
  65. ;; The command-line tools easy_install and pip are both capable of finding and
  66. ;; downloading the package source from PyPI (the Python Package Index). Both
  67. ;; of them import setuptools and execute the "setup.py" file under their
  68. ;; control. Thus the "setup.py" behaves as if the developer had imported
  69. ;; setuptools within setup.py - even if it is still using only distutils.
  70. ;;
  71. ;; Setuptools' "install" command (to be more precise: the "easy_install"
  72. ;; command which is called by "install") will put the path of the currently
  73. ;; installed version of each package and it's dependencies (as declared in
  74. ;; setup.py) into an "easy-install.pth" file. In Guix each packages gets its
  75. ;; own "site-packages" directory and thus an "easy-install.pth" of its own.
  76. ;; To avoid conflicts, the python build system renames the file to
  77. ;; <packagename>.pth in the phase rename-pth-file. To ensure that Python will
  78. ;; process the .pth file, easy_install also creates a basic "site.py" in each
  79. ;; "site-packages" directory. The file is the same for all packages, thus
  80. ;; there is no need to rename it. For more information about .pth files and
  81. ;; the site module, please refere to
  82. ;; https://docs.python.org/3/library/site.html.
  83. ;;
  84. ;; The .pth files contain the file-system paths (pointing to the store) of all
  85. ;; dependencies. So the dependency is hidden in the .pth file but is not
  86. ;; visible in the file-system. Now if packages A and B both required packages
  87. ;; P, but in different versions, Guix will not detect this when installing
  88. ;; both A and B to a profile. (For details and example see
  89. ;; https://lists.gnu.org/archive/html/guix-devel/2016-10/msg01233.html.)
  90. ;;
  91. ;; Pip behaves a bit different then easy_install: it always executes
  92. ;; "setup.py" with the option "--single-version-externally-managed" set. This
  93. ;; makes setuptools' "install" command run the original "install" command
  94. ;; instead of the "easy_install" command, so no .pth file (and no site.py)
  95. ;; will be created. The "site-packages" directory only contains the package
  96. ;; and the related .egg-info directory.
  97. ;;
  98. ;; This is exactly what we need for Guix and this is what we mimic in the
  99. ;; install phase below.
  100. ;;
  101. ;; As a draw back, the magic of the .pth file of linking to the other required
  102. ;; packages is gone and these packages have now to be declared as
  103. ;; "propagated-inputs".
  104. ;;
  105. ;; Note: Importing setuptools also adds two sub-commands: "install_egg_info"
  106. ;; and "install_scripts". These sub-commands are executed even if
  107. ;; "--single-version-externally-managed" is set, thus the .egg-info directory
  108. ;; and the scripts defined in entry-points will always be created.
  109. (define setuptools-shim
  110. ;; Run setup.py with "setuptools" being imported, which will patch
  111. ;; "distutils". This is needed for packages using "distutils" instead of
  112. ;; "setuptools" since the former does not understand the
  113. ;; "--single-version-externally-managed" flag.
  114. ;; Python code taken from pip 9.0.1 pip/utils/setuptools_build.py
  115. (string-append
  116. "import setuptools, tokenize;__file__='setup.py';"
  117. "f=getattr(tokenize, 'open', open)(__file__);"
  118. "code=f.read().replace('\\r\\n', '\\n');"
  119. "f.close();"
  120. "exec(compile(code, __file__, 'exec'))"))
  121. (define (call-setuppy command params use-setuptools?)
  122. (if (file-exists? "setup.py")
  123. (begin
  124. (format #t "running \"python setup.py\" with command ~s and parameters ~s~%"
  125. command params)
  126. (if use-setuptools?
  127. (apply invoke "python" "-c" setuptools-shim
  128. command params)
  129. (apply invoke "python" "./setup.py" command params)))
  130. (error "no setup.py found")))
  131. (define* (sanity-check #:key tests? inputs outputs #:allow-other-keys)
  132. "Ensure packages depending on this package via setuptools work properly,
  133. their advertised endpoints work and their top level modules are importable
  134. without errors."
  135. (let ((sanity-check.py (assoc-ref inputs "sanity-check.py")))
  136. ;; Make sure the working directory is empty (i.e. no Python modules in it)
  137. (with-directory-excursion "/tmp"
  138. (invoke "python" sanity-check.py (site-packages inputs outputs)))))
  139. (define* (build #:key use-setuptools? #:allow-other-keys)
  140. "Build a given Python package."
  141. (call-setuppy "build" '() use-setuptools?)
  142. #t)
  143. (define* (check #:key tests? test-target use-setuptools? #:allow-other-keys)
  144. "Run the test suite of a given Python package."
  145. (if tests?
  146. ;; Running `setup.py test` creates an additional .egg-info directory in
  147. ;; build/lib in some cases, e.g. if the source is in a sub-directory
  148. ;; (given with `package_dir`). This will by copied to the output, too,
  149. ;; so we need to remove.
  150. (let ((before (find-files "build" "\\.egg-info$" #:directories? #t)))
  151. (call-setuppy test-target '() use-setuptools?)
  152. (let* ((after (find-files "build" "\\.egg-info$" #:directories? #t))
  153. (inter (lset-difference string=? after before)))
  154. (for-each delete-file-recursively inter)))
  155. (format #t "test suite not run~%"))
  156. #t)
  157. (define (python-version python)
  158. (let* ((version (last (string-split python #\-)))
  159. (components (string-split version #\.))
  160. (major+minor (take components 2)))
  161. (string-join major+minor ".")))
  162. (define (python-output outputs)
  163. "Return the path of the python output, if there is one, or fall-back to out."
  164. (or (assoc-ref outputs "python")
  165. (assoc-ref outputs "out")))
  166. (define (site-packages inputs outputs)
  167. "Return the path of the current output's Python site-package."
  168. (let ((out (python-output outputs))
  169. (python (assoc-ref inputs "python")))
  170. (string-append out "/lib/python" (python-version python) "/site-packages")))
  171. (define (add-installed-pythonpath inputs outputs)
  172. "Prepend the site-package of OUTPUT to GUIX_PYTHONPATH. This is useful when
  173. running checks after installing the package."
  174. (setenv "GUIX_PYTHONPATH" (string-append (site-packages inputs outputs) ":"
  175. (getenv "GUIX_PYTHONPATH"))))
  176. (define* (add-install-to-pythonpath #:key inputs outputs #:allow-other-keys)
  177. "A phase that just wraps the 'add-installed-pythonpath' procedure."
  178. (add-installed-pythonpath inputs outputs))
  179. (define* (add-install-to-path #:key outputs #:allow-other-keys)
  180. "Adding Python scripts to PATH is also often useful in tests."
  181. (setenv "PATH" (string-append (assoc-ref outputs "out")
  182. "/bin:"
  183. (getenv "PATH"))))
  184. (define* (install #:key inputs outputs (configure-flags '()) use-setuptools?
  185. #:allow-other-keys)
  186. "Install a given Python package."
  187. (let* ((out (python-output outputs))
  188. (python (assoc-ref inputs "python"))
  189. (major-minor (map string->number
  190. (take (string-split (python-version python) #\.) 2)))
  191. (<3.7? (match major-minor
  192. ((major minor)
  193. (or (< major 3) (and (= major 3) (< minor 7))))))
  194. (params (append (list (string-append "--prefix=" out)
  195. "--no-compile")
  196. (if use-setuptools?
  197. ;; distutils does not accept these flags
  198. (list "--single-version-externally-managed"
  199. "--root=/")
  200. '())
  201. configure-flags)))
  202. (call-setuppy "install" params use-setuptools?)
  203. ;; Rather than produce potentially non-reproducible .pyc files on Pythons
  204. ;; older than 3.7, whose 'compileall' module lacks the
  205. ;; '--invalidation-mode' option, do not generate any.
  206. (unless <3.7?
  207. (invoke "python" "-m" "compileall" "--invalidation-mode=unchecked-hash"
  208. out))))
  209. (define* (wrap #:key inputs outputs #:allow-other-keys)
  210. (define (list-of-files dir)
  211. (find-files dir (lambda (file stat)
  212. (and (eq? 'regular (stat:type stat))
  213. (not (wrapped-program? file))))))
  214. (define bindirs
  215. (append-map (match-lambda
  216. ((_ . dir)
  217. (list (string-append dir "/bin")
  218. (string-append dir "/sbin"))))
  219. outputs))
  220. ;; Do not require "bash" to be present in the package inputs
  221. ;; even when there is nothing to wrap.
  222. ;; Also, calculate (sh) only once to prevent some I/O.
  223. (define %sh (delay (search-input-file inputs "bin/bash")))
  224. (define (sh) (force %sh))
  225. (let* ((var `("GUIX_PYTHONPATH" prefix
  226. ,(search-path-as-string->list
  227. (or (getenv "GUIX_PYTHONPATH") "")))))
  228. (for-each (lambda (dir)
  229. (let ((files (list-of-files dir)))
  230. (for-each (cut wrap-program <> #:sh (sh) var)
  231. files)))
  232. bindirs)))
  233. (define* (rename-pth-file #:key name inputs outputs #:allow-other-keys)
  234. "Rename easy-install.pth to NAME.pth to avoid conflicts between packages
  235. installed with setuptools."
  236. ;; Even if the "easy-install.pth" is not longer created, we kept this phase.
  237. ;; There still may be packages creating an "easy-install.pth" manually for
  238. ;; some good reason.
  239. (let* ((site-packages (site-packages inputs outputs))
  240. (easy-install-pth (string-append site-packages "/easy-install.pth"))
  241. (new-pth (string-append site-packages "/" name ".pth")))
  242. (when (file-exists? easy-install-pth)
  243. (rename-file easy-install-pth new-pth))))
  244. (define* (ensure-no-mtimes-pre-1980 #:rest _)
  245. "Ensure that there are no mtimes before 1980-01-02 in the source tree."
  246. ;; Rationale: patch-and-repack creates tarballs with timestamps at the POSIX
  247. ;; epoch, 1970-01-01 UTC. This causes problems with Python packages,
  248. ;; because Python eggs are ZIP files, and the ZIP format does not support
  249. ;; timestamps before 1980.
  250. (let ((early-1980 315619200)) ; 1980-01-02 UTC
  251. (ftw "." (lambda (file stat flag)
  252. (unless (<= early-1980 (stat:mtime stat))
  253. (utime file early-1980 early-1980))
  254. #t))))
  255. (define* (enable-bytecode-determinism #:rest _)
  256. "Improve determinism of pyc files."
  257. ;; Use deterministic hashes for strings, bytes, and datetime objects.
  258. (setenv "PYTHONHASHSEED" "0")
  259. ;; Prevent Python from creating .pyc files when loading modules (such as
  260. ;; when running a test suite).
  261. (setenv "PYTHONDONTWRITEBYTECODE" "1"))
  262. (define* (ensure-no-cythonized-files #:rest _)
  263. "Check the source code for @code{.c} files which may have been pre-generated
  264. by Cython."
  265. (for-each
  266. (lambda (file)
  267. (let ((generated-file
  268. (string-append (string-drop-right file 3) "c")))
  269. (when (file-exists? generated-file)
  270. (format #t "Possible Cythonized file found: ~a~%" generated-file))))
  271. (find-files "." "\\.pyx$")))
  272. (define %standard-phases
  273. ;; The build phase only builds C extensions and copies the Python sources,
  274. ;; while the install phase copies then byte-compiles the sources to the
  275. ;; prefix directory. The check phase is moved after the installation phase
  276. ;; to ease testing the built package.
  277. (modify-phases gnu:%standard-phases
  278. (add-after 'unpack 'ensure-no-mtimes-pre-1980 ensure-no-mtimes-pre-1980)
  279. (add-after 'ensure-no-mtimes-pre-1980 'enable-bytecode-determinism
  280. enable-bytecode-determinism)
  281. (add-after 'enable-bytecode-determinism 'ensure-no-cythonized-files
  282. ensure-no-cythonized-files)
  283. (delete 'bootstrap)
  284. (delete 'configure) ;not needed
  285. (replace 'build build)
  286. (delete 'check) ;moved after the install phase
  287. (replace 'install install)
  288. (add-after 'install 'add-install-to-pythonpath add-install-to-pythonpath)
  289. (add-after 'add-install-to-pythonpath 'add-install-to-path
  290. add-install-to-path)
  291. (add-after 'add-install-to-path 'wrap wrap)
  292. (add-after 'wrap 'check check)
  293. (add-after 'check 'sanity-check sanity-check)
  294. (add-before 'strip 'rename-pth-file rename-pth-file)))
  295. (define* (python-build #:key inputs (phases %standard-phases)
  296. #:allow-other-keys #:rest args)
  297. "Build the given Python package, applying all of PHASES in order."
  298. (apply gnu:gnu-build #:inputs inputs #:phases phases args))
  299. ;;; python-build-system.scm ends here