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