pypi.scm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2014 David Thompson <davet@gnu.org>
  3. ;;; Copyright © 2015 Cyril Roelandt <tipecaml@gmail.com>
  4. ;;; Copyright © 2015, 2016, 2017, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
  5. ;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
  6. ;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
  7. ;;; Copyright © 2019 Maxim Cournoyer <maxim.cournoyer@gmail.com>
  8. ;;; Copyright © 2020 Jakub Kądziołka <kuba@kadziolka.net>
  9. ;;; Copyright © 2020 Lars-Dominik Braun <ldb@leibniz-psychology.org>
  10. ;;; Copyright © 2020 Arun Isaac <arunisaac@systemreboot.net>
  11. ;;; Copyright © 2020 Martin Becze <mjbecze@riseup.net>
  12. ;;;
  13. ;;; This file is part of GNU Guix.
  14. ;;;
  15. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  16. ;;; under the terms of the GNU General Public License as published by
  17. ;;; the Free Software Foundation; either version 3 of the License, or (at
  18. ;;; your option) any later version.
  19. ;;;
  20. ;;; GNU Guix is distributed in the hope that it will be useful, but
  21. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  22. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. ;;; GNU General Public License for more details.
  24. ;;;
  25. ;;; You should have received a copy of the GNU General Public License
  26. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  27. (define-module (guix import pypi)
  28. #:use-module (ice-9 match)
  29. #:use-module (ice-9 regex)
  30. #:use-module (ice-9 receive)
  31. #:use-module ((ice-9 rdelim) #:select (read-line))
  32. #:use-module (srfi srfi-1)
  33. #:use-module (srfi srfi-11)
  34. #:use-module (srfi srfi-26)
  35. #:use-module (srfi srfi-34)
  36. #:use-module (srfi srfi-35)
  37. #:use-module (guix utils)
  38. #:use-module (guix memoization)
  39. #:use-module (guix diagnostics)
  40. #:use-module (guix i18n)
  41. #:use-module ((guix build utils)
  42. #:select ((package-name->name+version
  43. . hyphen-package-name->name+version)
  44. find-files
  45. invoke))
  46. #:use-module (guix import utils)
  47. #:use-module ((guix download) #:prefix download:)
  48. #:use-module (guix import json)
  49. #:use-module (json)
  50. #:use-module (guix packages)
  51. #:use-module (guix upstream)
  52. #:use-module ((guix licenses) #:prefix license:)
  53. #:use-module (guix build-system python)
  54. #:export (parse-requires.txt
  55. parse-wheel-metadata
  56. specification->requirement-name
  57. guix-package->pypi-name
  58. pypi-recursive-import
  59. pypi->guix-package
  60. %pypi-updater))
  61. ;; The PyPI API (notice the rhyme) is "documented" at:
  62. ;; <https://warehouse.readthedocs.io/api-reference/json/>.
  63. (define non-empty-string-or-false
  64. (match-lambda
  65. ("" #f)
  66. ((? string? str) str)
  67. ((or 'null #f) #f)))
  68. ;; PyPI project.
  69. (define-json-mapping <pypi-project> make-pypi-project pypi-project?
  70. json->pypi-project
  71. (info pypi-project-info "info" json->project-info) ;<project-info>
  72. (last-serial pypi-project-last-serial "last_serial") ;integer
  73. (releases pypi-project-releases "releases" ;string/<distribution>* pairs
  74. (match-lambda
  75. (((versions . dictionaries) ...)
  76. (map (lambda (version vector)
  77. (cons version
  78. (map json->distribution
  79. (vector->list vector))))
  80. versions dictionaries))))
  81. (distributions pypi-project-distributions "urls" ;<distribution>*
  82. (lambda (vector)
  83. (map json->distribution (vector->list vector)))))
  84. ;; Project metadata.
  85. (define-json-mapping <project-info> make-project-info project-info?
  86. json->project-info
  87. (name project-info-name) ;string
  88. (author project-info-author) ;string
  89. (maintainer project-info-maintainer) ;string
  90. (classifiers project-info-classifiers ;list of strings
  91. "classifiers" vector->list)
  92. (description project-info-description) ;string
  93. (summary project-info-summary) ;string
  94. (keywords project-info-keywords) ;string
  95. (license project-info-license) ;string
  96. (download-url project-info-download-url ;string | #f
  97. "download_url" non-empty-string-or-false)
  98. (home-page project-info-home-page ;string
  99. "home_page")
  100. (url project-info-url "project_url") ;string
  101. (release-url project-info-release-url "release_url") ;string
  102. (version project-info-version)) ;string
  103. ;; Distribution: a URL along with cryptographic hashes and metadata.
  104. (define-json-mapping <distribution> make-distribution distribution?
  105. json->distribution
  106. (url distribution-url) ;string
  107. (digests distribution-digests) ;list of string pairs
  108. (file-name distribution-file-name "filename") ;string
  109. (has-signature? distribution-has-signature? "hash_sig") ;Boolean
  110. (package-type distribution-package-type "packagetype") ;"bdist_wheel" | ...
  111. (python-version distribution-package-python-version
  112. "python_version"))
  113. (define (pypi-fetch name)
  114. "Return a <pypi-project> record for package NAME, or #f on failure."
  115. (and=> (json-fetch (string-append "https://pypi.org/pypi/" name "/json"))
  116. json->pypi-project))
  117. ;; For packages found on PyPI that lack a source distribution.
  118. (define-condition-type &missing-source-error &error
  119. missing-source-error?
  120. (package missing-source-error-package))
  121. (define (latest-source-release pypi-package)
  122. "Return the latest source release for PYPI-PACKAGE."
  123. (let ((releases (assoc-ref (pypi-project-releases pypi-package)
  124. (project-info-version
  125. (pypi-project-info pypi-package)))))
  126. (or (find (lambda (release)
  127. (string=? "sdist" (distribution-package-type release)))
  128. releases)
  129. (raise (condition (&missing-source-error
  130. (package pypi-package)))))))
  131. (define (latest-wheel-release pypi-package)
  132. "Return the url of the wheel for the latest release of pypi-package,
  133. or #f if there isn't any."
  134. (let ((releases (assoc-ref (pypi-project-releases pypi-package)
  135. (project-info-version
  136. (pypi-project-info pypi-package)))))
  137. (or (find (lambda (release)
  138. (string=? "bdist_wheel" (distribution-package-type release)))
  139. releases)
  140. #f)))
  141. (define (python->package-name name)
  142. "Given the NAME of a package on PyPI, return a Guix-compliant name for the
  143. package."
  144. (if (string-prefix? "python-" name)
  145. (snake-case name)
  146. (string-append "python-" (snake-case name))))
  147. (define (guix-package->pypi-name package)
  148. "Given a Python PACKAGE built from pypi.org, return the name of the
  149. package on PyPI."
  150. (define (url->pypi-name url)
  151. (hyphen-package-name->name+version
  152. (basename (file-sans-extension url))))
  153. (match (and=> (package-source package) origin-uri)
  154. ((? string? url)
  155. (url->pypi-name url))
  156. ((lst ...)
  157. (any url->pypi-name lst))
  158. (#f #f)))
  159. (define (wheel-url->extracted-directory wheel-url)
  160. (match (string-split (basename wheel-url) #\-)
  161. ((name version _ ...)
  162. (string-append name "-" version ".dist-info"))))
  163. (define (maybe-inputs package-inputs input-type)
  164. "Given a list of PACKAGE-INPUTS, tries to generate the 'inputs' field of a
  165. package definition. INPUT-TYPE, a symbol, is used to populate the name of
  166. the input field."
  167. (match package-inputs
  168. (()
  169. '())
  170. ((package-inputs ...)
  171. `((,input-type (,'quasiquote ,package-inputs))))))
  172. (define %requirement-name-regexp
  173. ;; Regexp to match the requirement name in a requirement specification.
  174. ;; Some grammar, taken from PEP-0508 (see:
  175. ;; https://www.python.org/dev/peps/pep-0508/).
  176. ;; Using this grammar makes the PEP-0508 regexp easier to understand for
  177. ;; humans. The use of a regexp is preferred to more primitive string
  178. ;; manipulations because we can more directly match what upstream uses
  179. ;; (again, per PEP-0508). The regexp approach is also easier to extend,
  180. ;; should we want to implement more completely the grammar of PEP-0508.
  181. ;; The unified rule can be expressed as:
  182. ;; specification = wsp* ( url_req | name_req ) wsp*
  183. ;; where url_req is:
  184. ;; url_req = name wsp* extras? wsp* urlspec wsp+ quoted_marker?
  185. ;; and where name_req is:
  186. ;; name_req = name wsp* extras? wsp* versionspec? wsp* quoted_marker?
  187. ;; Thus, we need only matching NAME, which is expressed as:
  188. ;; identifer_end = letterOrDigit | (('-' | '_' | '.' )* letterOrDigit)
  189. ;; identifier = letterOrDigit identifier_end*
  190. ;; name = identifier
  191. (let* ((letter-or-digit "[A-Za-z0-9]")
  192. (identifier-end (string-append "(" letter-or-digit "|"
  193. "[-_.]*" letter-or-digit ")"))
  194. (identifier (string-append "^" letter-or-digit identifier-end "*"))
  195. (name identifier))
  196. (make-regexp name)))
  197. (define (specification->requirement-name spec)
  198. "Given a specification SPEC, return the requirement name."
  199. (match:substring
  200. (or (regexp-exec %requirement-name-regexp spec)
  201. (error (G_ "Could not extract requirement name in spec:") spec))))
  202. (define (test-section? name)
  203. "Return #t if the section name contains 'test' or 'dev'."
  204. (any (cut string-contains-ci name <>)
  205. '("test" "dev")))
  206. (define (parse-requires.txt requires.txt)
  207. "Given REQUIRES.TXT, a path to a Setuptools requires.txt file, return a list
  208. of lists of requirements.
  209. The first list contains the required dependencies while the second the
  210. optional test dependencies. Note that currently, optional, non-test
  211. dependencies are omitted since these can be difficult or expensive to
  212. satisfy."
  213. (define (comment? line)
  214. ;; Return #t if the given LINE is a comment, #f otherwise.
  215. (string-prefix? "#" (string-trim line)))
  216. (define (section-header? line)
  217. ;; Return #t if the given LINE is a section header, #f otherwise.
  218. (string-prefix? "[" (string-trim line)))
  219. (call-with-input-file requires.txt
  220. (lambda (port)
  221. (let loop ((required-deps '())
  222. (test-deps '())
  223. (inside-test-section? #f)
  224. (optional? #f))
  225. (let ((line (read-line port)))
  226. (cond
  227. ((eof-object? line)
  228. ;; Duplicates can occur, since the same requirement can be
  229. ;; listed multiple times with different conditional markers, e.g.
  230. ;; pytest >= 3 ; python_version >= "3.3"
  231. ;; pytest < 3 ; python_version < "3.3"
  232. (map (compose reverse delete-duplicates)
  233. (list required-deps test-deps)))
  234. ((or (string-null? line) (comment? line))
  235. (loop required-deps test-deps inside-test-section? optional?))
  236. ((section-header? line)
  237. ;; Encountering a section means that all the requirements
  238. ;; listed below are optional. Since we want to pick only the
  239. ;; test dependencies from the optional dependencies, we must
  240. ;; track those separately.
  241. (loop required-deps test-deps (test-section? line) #t))
  242. (inside-test-section?
  243. (loop required-deps
  244. (cons (specification->requirement-name line)
  245. test-deps)
  246. inside-test-section? optional?))
  247. ((not optional?)
  248. (loop (cons (specification->requirement-name line)
  249. required-deps)
  250. test-deps inside-test-section? optional?))
  251. (optional?
  252. ;; Skip optional items.
  253. (loop required-deps test-deps inside-test-section? optional?))
  254. (else
  255. (warning (G_ "parse-requires.txt reached an unexpected \
  256. condition on line ~a~%") line))))))))
  257. (define (parse-wheel-metadata metadata)
  258. "Given METADATA, a Wheel metadata file, return a list of lists of
  259. requirements.
  260. Refer to the documentation of PARSE-REQUIRES.TXT for a description of the
  261. returned value."
  262. ;; METADATA is a RFC-2822-like, header based file.
  263. (define (requires-dist-header? line)
  264. ;; Return #t if the given LINE is a Requires-Dist header.
  265. (string-match "^Requires-Dist: " line))
  266. (define (requires-dist-value line)
  267. (string-drop line (string-length "Requires-Dist: ")))
  268. (define (extra? line)
  269. ;; Return #t if the given LINE is an "extra" requirement.
  270. (string-match "extra == '(.*)'" line))
  271. (define (test-requirement? line)
  272. (and=> (match:substring (extra? line) 1) test-section?))
  273. (call-with-input-file metadata
  274. (lambda (port)
  275. (let loop ((required-deps '())
  276. (test-deps '()))
  277. (let ((line (read-line port)))
  278. (cond
  279. ((eof-object? line)
  280. (map (compose reverse delete-duplicates)
  281. (list required-deps test-deps)))
  282. ((and (requires-dist-header? line) (not (extra? line)))
  283. (loop (cons (specification->requirement-name
  284. (requires-dist-value line))
  285. required-deps)
  286. test-deps))
  287. ((and (requires-dist-header? line) (test-requirement? line))
  288. (loop required-deps
  289. (cons (specification->requirement-name (requires-dist-value line))
  290. test-deps)))
  291. (else
  292. (loop required-deps test-deps)))))))) ;skip line
  293. (define (guess-requirements source-url wheel-url archive)
  294. "Given SOURCE-URL, WHEEL-URL and an ARCHIVE of the package, return a list
  295. of the required packages specified in the requirements.txt file. ARCHIVE will
  296. be extracted in a temporary directory."
  297. (define (read-wheel-metadata wheel-archive)
  298. ;; Given WHEEL-ARCHIVE, a ZIP Python wheel archive, return the package's
  299. ;; requirements, or #f if the metadata file contained therein couldn't be
  300. ;; extracted.
  301. (let* ((dirname (wheel-url->extracted-directory wheel-url))
  302. (metadata (string-append dirname "/METADATA")))
  303. (call-with-temporary-directory
  304. (lambda (dir)
  305. (if (zero?
  306. (parameterize ((current-error-port (%make-void-port "rw+"))
  307. (current-output-port (%make-void-port "rw+")))
  308. (system* "unzip" wheel-archive "-d" dir metadata)))
  309. (parse-wheel-metadata (string-append dir "/" metadata))
  310. (begin
  311. (warning
  312. (G_ "Failed to extract file: ~a from wheel.~%") metadata)
  313. #f))))))
  314. (define (guess-requirements-from-wheel)
  315. ;; Return the package's requirements using the wheel, or #f if an error
  316. ;; occurs.
  317. (call-with-temporary-output-file
  318. (lambda (temp port)
  319. (if wheel-url
  320. (and (url-fetch wheel-url temp)
  321. (read-wheel-metadata temp))
  322. #f))))
  323. (define (guess-requirements-from-source)
  324. ;; Return the package's requirements by guessing them from the source.
  325. (if (compressed-file? source-url)
  326. (call-with-temporary-directory
  327. (lambda (dir)
  328. (parameterize ((current-error-port (%make-void-port "rw+"))
  329. (current-output-port (%make-void-port "rw+")))
  330. (if (string=? "zip" (file-extension source-url))
  331. (invoke "unzip" archive "-d" dir)
  332. (invoke "tar" "xf" archive "-C" dir)))
  333. (let ((requires.txt-files
  334. (find-files dir (lambda (abs-file-name _)
  335. (string-match "\\.egg-info/requires.txt$"
  336. abs-file-name)))))
  337. (match requires.txt-files
  338. (()
  339. (warning (G_ "Cannot guess requirements from source archive:\
  340. no requires.txt file found.~%"))
  341. (list '() '()))
  342. (else (parse-requires.txt (first requires.txt-files)))))))
  343. (begin
  344. (warning (G_ "Unsupported archive format; \
  345. cannot determine package dependencies from source archive: ~a~%")
  346. (basename source-url))
  347. (list '() '()))))
  348. ;; First, try to compute the requirements using the wheel, else, fallback to
  349. ;; reading the "requires.txt" from the egg-info directory from the source
  350. ;; archive.
  351. (or (guess-requirements-from-wheel)
  352. (guess-requirements-from-source)))
  353. (define (compute-inputs source-url wheel-url archive)
  354. "Given the SOURCE-URL and WHEEL-URL of an already downloaded ARCHIVE, return
  355. a pair of lists, each consisting of a list of name/variable pairs, for the
  356. propagated inputs and the native inputs, respectively. Also
  357. return the unaltered list of upstream dependency names."
  358. (define (strip-argparse deps)
  359. (remove (cut string=? "argparse" <>) deps))
  360. (define (requirement->package-name/sort deps)
  361. (sort
  362. (map (lambda (input)
  363. (let ((guix-name (python->package-name input)))
  364. (list guix-name (list 'unquote (string->symbol guix-name)))))
  365. deps)
  366. (lambda args
  367. (match args
  368. (((a _ ...) (b _ ...))
  369. (string-ci<? a b))))))
  370. (define process-requirements
  371. (compose requirement->package-name/sort strip-argparse))
  372. (let ((dependencies (guess-requirements source-url wheel-url archive)))
  373. (values (map process-requirements dependencies)
  374. (concatenate dependencies))))
  375. (define (make-pypi-sexp name version source-url wheel-url home-page synopsis
  376. description license)
  377. "Return the `package' s-expression for a python package with the given NAME,
  378. VERSION, SOURCE-URL, HOME-PAGE, SYNOPSIS, DESCRIPTION, and LICENSE."
  379. (call-with-temporary-output-file
  380. (lambda (temp port)
  381. (and (url-fetch source-url temp)
  382. (receive (guix-dependencies upstream-dependencies)
  383. (compute-inputs source-url wheel-url temp)
  384. (match guix-dependencies
  385. ((required-inputs native-inputs)
  386. (when (string-suffix? ".zip" source-url)
  387. (set! native-inputs (cons
  388. '("unzip" ,unzip)
  389. native-inputs)))
  390. (values
  391. `(package
  392. (name ,(python->package-name name))
  393. (version ,version)
  394. (source
  395. (origin
  396. (method url-fetch)
  397. (uri (pypi-uri
  398. ;; PyPI URL are case sensitive, but sometimes
  399. ;; a project named using mixed case has a URL
  400. ;; using lower case, so we must work around this
  401. ;; inconsistency. For actual examples, compare
  402. ;; the URLs of the "Deprecated" and "uWSGI" PyPI
  403. ;; packages.
  404. ,(if (string-contains source-url name)
  405. name
  406. (string-downcase name))
  407. version
  408. ;; Some packages have been released as `.zip`
  409. ;; instead of the more common `.tar.gz`. For
  410. ;; example, see "path-and-address".
  411. ,@(if (string-suffix? ".zip" source-url)
  412. '(".zip")
  413. '())))
  414. (sha256
  415. (base32
  416. ,(guix-hash-url temp)))))
  417. (build-system python-build-system)
  418. ,@(maybe-inputs required-inputs 'propagated-inputs)
  419. ,@(maybe-inputs native-inputs 'native-inputs)
  420. (home-page ,home-page)
  421. (synopsis ,synopsis)
  422. (description ,description)
  423. (license ,(license->symbol license)))
  424. upstream-dependencies))))))))
  425. (define pypi->guix-package
  426. (memoize
  427. (lambda* (package-name #:key repo version)
  428. "Fetch the metadata for PACKAGE-NAME from pypi.org, and return the
  429. `package' s-expression corresponding to that package, or #f on failure."
  430. (let* ((project (pypi-fetch package-name))
  431. (info (and project (pypi-project-info project))))
  432. (and project
  433. (guard (c ((missing-source-error? c)
  434. (let ((package (missing-source-error-package c)))
  435. (leave (G_ "no source release for pypi package ~a ~a~%")
  436. (project-info-name info)
  437. (project-info-version info)))))
  438. (make-pypi-sexp (project-info-name info)
  439. (project-info-version info)
  440. (and=> (latest-source-release project)
  441. distribution-url)
  442. (and=> (latest-wheel-release project)
  443. distribution-url)
  444. (project-info-home-page info)
  445. (project-info-summary info)
  446. (project-info-summary info)
  447. (string->license
  448. (project-info-license info)))))))))
  449. (define (pypi-recursive-import package-name)
  450. (recursive-import package-name
  451. #:repo->guix-package pypi->guix-package
  452. #:guix-name python->package-name))
  453. (define (string->license str)
  454. "Convert the string STR into a license object."
  455. (match str
  456. ("GNU LGPL" license:lgpl2.0)
  457. ("GPL" license:gpl3)
  458. ((or "BSD" "BSD-3" "BSD License") license:bsd-3)
  459. ("BSD-2-Clause" license:bsd-2)
  460. ((or "MIT" "MIT license" "MIT License" "Expat license") license:expat)
  461. ("Public domain" license:public-domain)
  462. ((or "Apache License, Version 2.0" "Apache 2.0") license:asl2.0)
  463. ("MPL 2.0" license:mpl2.0)
  464. (_ #f)))
  465. (define pypi-package?
  466. (url-predicate
  467. (lambda (url)
  468. (or (string-prefix? "https://pypi.org/" url)
  469. (string-prefix? "https://pypi.python.org/" url)
  470. (string-prefix? "https://pypi.org/packages" url)
  471. (string-prefix? "https://files.pythonhosted.org/packages" url)))))
  472. (define (latest-release package)
  473. "Return an <upstream-source> for the latest release of PACKAGE."
  474. (let* ((pypi-name (guix-package->pypi-name package))
  475. (pypi-package (pypi-fetch pypi-name)))
  476. (and pypi-package
  477. (guard (c ((missing-source-error? c) #f))
  478. (let* ((info (pypi-project-info pypi-package))
  479. (version (project-info-version info))
  480. (url (distribution-url
  481. (latest-source-release pypi-package))))
  482. (upstream-source
  483. (package (package-name package))
  484. (version version)
  485. (urls (list url))))))))
  486. (define %pypi-updater
  487. (upstream-updater
  488. (name 'pypi)
  489. (description "Updater for PyPI packages")
  490. (pred pypi-package?)
  491. (latest latest-release)))