go.scm 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2020 Katherine Cox-Buday <cox.katherine.e@gmail.com>
  3. ;;; Copyright © 2020 Helio Machado <0x2b3bfa0+guix@googlemail.com>
  4. ;;; Copyright © 2021 François Joulaud <francois.joulaud@radiofrance.com>
  5. ;;; Copyright © 2021 Maxim Cournoyer <maxim.cournoyer@gmail.com>
  6. ;;; Copyright © 2021-2022 Ludovic Courtès <ludo@gnu.org>
  7. ;;; Copyright © 2021 Xinglu Chen <public@yoctocell.xyz>
  8. ;;; Copyright © 2021 Sarah Morgensen <iskarian@mgsn.dev>
  9. ;;; Copyright © 2021 Simon Tournier <zimon.toutoune@gmail.com>
  10. ;;;
  11. ;;; This file is part of GNU Guix.
  12. ;;;
  13. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  14. ;;; under the terms of the GNU General Public License as published by
  15. ;;; the Free Software Foundation; either version 3 of the License, or (at
  16. ;;; your option) any later version.
  17. ;;;
  18. ;;; GNU Guix is distributed in the hope that it will be useful, but
  19. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  20. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. ;;; GNU General Public License for more details.
  22. ;;;
  23. ;;; You should have received a copy of the GNU General Public License
  24. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  25. (define-module (guix import go)
  26. #:use-module (guix build-system go)
  27. #:use-module (guix git)
  28. #:use-module (guix hash)
  29. #:use-module (guix i18n)
  30. #:use-module (guix diagnostics)
  31. #:use-module (guix import utils)
  32. #:use-module (guix import json)
  33. #:use-module (guix packages)
  34. #:use-module (guix http-client)
  35. #:use-module (guix memoization)
  36. #:autoload (htmlprag) (html->sxml) ;from Guile-Lib
  37. #:autoload (guix base32) (bytevector->nix-base32-string)
  38. #:autoload (guix build utils) (mkdir-p)
  39. #:autoload (gcrypt hash) (hash-algorithm sha256)
  40. #:use-module (ice-9 format)
  41. #:use-module (ice-9 match)
  42. #:use-module (ice-9 peg)
  43. #:use-module (ice-9 receive)
  44. #:use-module (ice-9 regex)
  45. #:use-module (ice-9 textual-ports)
  46. #:use-module ((rnrs io ports) #:select (call-with-port))
  47. #:use-module (srfi srfi-1)
  48. #:use-module (srfi srfi-9)
  49. #:use-module (srfi srfi-11)
  50. #:use-module (srfi srfi-26)
  51. #:use-module (srfi srfi-34)
  52. #:use-module (srfi srfi-35)
  53. #:use-module (sxml match)
  54. #:use-module ((sxml xpath) #:renamer (lambda (s)
  55. (if (eq? 'filter s)
  56. 'xfilter
  57. s)))
  58. #:use-module (web uri)
  59. #:export (go-module->guix-package
  60. go-module->guix-package*
  61. go-module-recursive-import))
  62. ;;; Commentary:
  63. ;;;
  64. ;;; (guix import go) attempts to make it easier to create Guix package
  65. ;;; declarations for Go modules.
  66. ;;;
  67. ;;; Modules in Go are a "collection of related Go packages" which are "the
  68. ;;; unit of source code interchange and versioning". Modules are generally
  69. ;;; hosted in a repository.
  70. ;;;
  71. ;;; At this point it should handle correctly modules which have only Go
  72. ;;; dependencies and are accessible from proxy.golang.org (or configured via
  73. ;;; GOPROXY).
  74. ;;;
  75. ;;; We want it to work more or less this way:
  76. ;;; - get latest version for the module from GOPROXY
  77. ;;; - infer VCS root repo from which we will check-out source by
  78. ;;; + recognising known patterns (like github.com)
  79. ;;; + or recognizing .vcs suffix
  80. ;;; + or parsing meta tag in HTML served at the URL
  81. ;;; + or (TODO) if nothing else works by using zip file served by GOPROXY
  82. ;;; - get go.mod from GOPROXY (which is able to synthetize one if needed)
  83. ;;; - extract list of dependencies from this go.mod
  84. ;;;
  85. ;;; The Go module paths are translated to a Guix package name under the
  86. ;;; assumption that there will be no collision.
  87. ;;; TODO list
  88. ;;; - get correct hash in vcs->origin for Mercurial and Subversion
  89. ;;; Code:
  90. (define http-fetch*
  91. ;; Like http-fetch, but memoized and returning the body as a string.
  92. (memoize (lambda args
  93. (call-with-port (apply http-fetch args) get-string-all))))
  94. (define json-fetch*
  95. (memoize json-fetch))
  96. (define (go-path-escape path)
  97. "Escape a module path by replacing every uppercase letter with an
  98. exclamation mark followed with its lowercase equivalent, as per the module
  99. Escaped Paths specification (see:
  100. https://godoc.org/golang.org/x/mod/module#hdr-Escaped_Paths)."
  101. (define (escape occurrence)
  102. (string-append "!" (string-downcase (match:substring occurrence))))
  103. (regexp-substitute/global #f "[A-Z]" path 'pre escape 'post))
  104. ;; Prevent inlining of this procedure, which is accessed by unit tests.
  105. (set! go-path-escape go-path-escape)
  106. (define (go.pkg.dev-info name)
  107. (http-fetch* (string-append "https://pkg.go.dev/" name)))
  108. (define* (go-module-version-string goproxy name #:key version)
  109. "Fetch the version string of the latest version for NAME from the given
  110. GOPROXY server, or for VERSION when specified."
  111. (let ((file (if version
  112. (string-append "@v/" version ".info")
  113. "@latest")))
  114. (assoc-ref (json-fetch* (format #f "~a/~a/~a"
  115. goproxy (go-path-escape name) file))
  116. "Version")))
  117. (define* (go-module-available-versions goproxy name)
  118. "Retrieve the available versions for a given module from the module proxy.
  119. Versions are being returned **unordered** and may contain different versioning
  120. styles for the same package."
  121. (let* ((url (string-append goproxy "/" (go-path-escape name) "/@v/list"))
  122. (body (http-fetch* url))
  123. (versions (remove string-null? (string-split body #\newline))))
  124. (if (null? versions)
  125. (list (go-module-version-string goproxy name)) ;latest version
  126. versions)))
  127. (define (go-package-licenses name)
  128. "Retrieve the list of licenses that apply to NAME, a Go package or module
  129. name (e.g. \"github.com/golang/protobuf/proto\")."
  130. (let* ((body (go.pkg.dev-info (string-append name "?tab=licenses")))
  131. ;; Extract the text contained in a h2 child node of any
  132. ;; element marked with a "License" class attribute.
  133. (select (sxpath `(// (* (@ (equal? (class "License"))))
  134. h2 // div // *text*))))
  135. (select (html->sxml body #:strict? #t))))
  136. (define (sxml->texi sxml-node)
  137. "A very basic SXML to Texinfo converter which attempts to preserve HTML
  138. formatting and links as text."
  139. (sxml-match sxml-node
  140. ((strong ,text)
  141. (format #f "@strong{~a}" text))
  142. ((a (@ (href ,url)) ,text)
  143. (format #f "@url{~a,~a}" url text))
  144. ((code ,text)
  145. (format #f "@code{~a}" text))
  146. (,something-else something-else)))
  147. (define (go-package-description name)
  148. "Retrieve a short description for NAME, a Go package name,
  149. e.g. \"google.golang.org/protobuf/proto\"."
  150. (let* ((body (go.pkg.dev-info name))
  151. (sxml (html->sxml body #:strict? #t))
  152. (overview ((sxpath
  153. `(//
  154. (* (@ (equal? (class "Documentation-overview"))))
  155. (p 1))) sxml))
  156. ;; Sometimes, the first paragraph just contains images/links that
  157. ;; has only "\n" for text. The following filter is designed to
  158. ;; omit it.
  159. (contains-text? (lambda (node)
  160. (remove string-null?
  161. (map string-trim-both
  162. (filter (node-typeof? '*text*)
  163. (cdr node))))))
  164. (select-content (sxpath
  165. `(//
  166. (* (@ (equal? (class "UnitReadme-content"))))
  167. div // p ,(xfilter contains-text?))))
  168. ;; Fall-back to use content; this is less desirable as it is more
  169. ;; verbose, but not every page has an overview.
  170. (description (if (not (null? overview))
  171. overview
  172. (select-content sxml)))
  173. (description* (if (not (null? description))
  174. (first description)
  175. description)))
  176. (match description*
  177. (() #f) ;nothing selected
  178. ((p elements ...)
  179. (apply string-append (filter string? (map sxml->texi elements)))))))
  180. (define (go-package-synopsis module-name)
  181. "Retrieve a short synopsis for a Go module named MODULE-NAME,
  182. e.g. \"google.golang.org/protobuf\". The data is scraped from
  183. the https://pkg.go.dev/ web site."
  184. ;; Note: Only the *module* (rather than package) page has the README title
  185. ;; used as a synopsis on the https://pkg.go.dev web site.
  186. (let* ((url (string-append "https://pkg.go.dev/" module-name))
  187. (body (http-fetch* url))
  188. ;; Extract the text contained in a h2 child node of any
  189. ;; element marked with a "License" class attribute.
  190. (select-title (sxpath
  191. `(// (div (@ (equal? (class "UnitReadme-content"))))
  192. // h3 *text*))))
  193. (match (select-title (html->sxml body #:strict? #t))
  194. (() #f) ;nothing selected
  195. ((title more ...) ;title is the first string of the list
  196. (string-trim-both title)))))
  197. (define (list->licenses licenses)
  198. "Given a list of LICENSES mostly following the SPDX conventions, return the
  199. corresponding Guix license or 'unknown-license!"
  200. (filter-map (lambda (license)
  201. (and (not (string-null? license))
  202. (not (any (cut string=? <> license)
  203. '("AND" "OR" "WITH")))
  204. ;; Adjust the license names scraped from
  205. ;; https://pkg.go.dev to an equivalent SPDX identifier,
  206. ;; if they differ (see: https://github.com/golang/pkgsite
  207. ;; /internal/licenses/licenses.go#L174).
  208. (or (spdx-string->license
  209. (match license
  210. ("BlueOak-1.0" "BlueOak-1.0.0")
  211. ("BSD-0-Clause" "0BSD")
  212. ("BSD-2-Clause" "BSD-2-Clause-FreeBSD")
  213. ("GPL2" "GPL-2.0")
  214. ("GPL3" "GPL-3.0")
  215. ("NIST" "NIST-PD")
  216. (_ license)))
  217. 'unknown-license!)))
  218. licenses))
  219. (define (fetch-go.mod goproxy module-path version)
  220. "Fetch go.mod from the given GOPROXY server for the given MODULE-PATH
  221. and VERSION and return an input port."
  222. (let ((url (format #f "~a/~a/@v/~a.mod" goproxy
  223. (go-path-escape module-path)
  224. (go-path-escape version))))
  225. (http-fetch* url)))
  226. (define (parse-go.mod content)
  227. "Parse the go.mod file CONTENT, returning a list of directives, comments,
  228. and unknown lines. Each sublist begins with a symbol (go, module, require,
  229. replace, exclude, retract, comment, or unknown) and is followed by one or more
  230. sublists. Each sublist begins with a symbol (module-path, version, file-path,
  231. comment, or unknown) and is followed by the indicated data."
  232. ;; https://golang.org/ref/mod#go-mod-file-grammar
  233. (define-peg-pattern NL none "\n")
  234. (define-peg-pattern WS none (or " " "\t" "\r"))
  235. (define-peg-pattern => none (and (* WS) "=>"))
  236. (define-peg-pattern punctuation none (or "," "=>" "[" "]" "(" ")"))
  237. (define-peg-pattern comment all
  238. (and (ignore "//") (* WS) (* (and (not-followed-by NL) peg-any))))
  239. (define-peg-pattern EOL body (and (* WS) (? comment) NL))
  240. (define-peg-pattern block-start none (and (* WS) "(" EOL))
  241. (define-peg-pattern block-end none (and (* WS) ")" EOL))
  242. (define-peg-pattern any-line body
  243. (and (* WS) (* (and (not-followed-by NL) peg-any)) EOL))
  244. ;; Strings and identifiers
  245. (define-peg-pattern identifier body
  246. (+ (and (not-followed-by (or NL WS punctuation)) peg-any)))
  247. (define-peg-pattern string-raw body
  248. (and (ignore "`") (+ (and (not-followed-by "`") peg-any)) (ignore "`")))
  249. (define-peg-pattern string-quoted body
  250. (and (ignore "\"")
  251. (+ (or (and (ignore "\\") peg-any)
  252. (and (not-followed-by "\"") peg-any)))
  253. (ignore "\"")))
  254. (define-peg-pattern string-or-ident body
  255. (and (* WS) (or string-raw string-quoted identifier)))
  256. (define-peg-pattern version all string-or-ident)
  257. (define-peg-pattern module-path all string-or-ident)
  258. (define-peg-pattern file-path all string-or-ident)
  259. ;; Non-directive lines
  260. (define-peg-pattern unknown all any-line)
  261. (define-peg-pattern block-line body
  262. (or EOL (and (not-followed-by block-end) unknown)))
  263. ;; GoDirective = "go" GoVersion newline .
  264. (define-peg-pattern go all (and (ignore "go") version EOL))
  265. ;; ModuleDirective = "module" ( ModulePath | "(" newline ModulePath newline ")" ) newline .
  266. (define-peg-pattern module all
  267. (and (ignore "module") (or (and block-start module-path EOL block-end)
  268. (and module-path EOL))))
  269. ;; The following directives may all be used solo or in a block
  270. ;; RequireSpec = ModulePath Version newline .
  271. (define-peg-pattern require all (and module-path version EOL))
  272. (define-peg-pattern require-top body
  273. (and (ignore "require")
  274. (or (and block-start (* (or require block-line)) block-end) require)))
  275. ;; ExcludeSpec = ModulePath Version newline .
  276. (define-peg-pattern exclude all (and module-path version EOL))
  277. (define-peg-pattern exclude-top body
  278. (and (ignore "exclude")
  279. (or (and block-start (* (or exclude block-line)) block-end) exclude)))
  280. ;; ReplaceSpec = ModulePath [ Version ] "=>" FilePath newline
  281. ;; | ModulePath [ Version ] "=>" ModulePath Version newline .
  282. (define-peg-pattern original all (or (and module-path version) module-path))
  283. (define-peg-pattern with all (or (and module-path version) file-path))
  284. (define-peg-pattern replace all (and original => with EOL))
  285. (define-peg-pattern replace-top body
  286. (and (ignore "replace")
  287. (or (and block-start (* (or replace block-line)) block-end) replace)))
  288. ;; RetractSpec = ( Version | "[" Version "," Version "]" ) newline .
  289. (define-peg-pattern range all
  290. (and (* WS) (ignore "[") version
  291. (* WS) (ignore ",") version (* WS) (ignore "]")))
  292. (define-peg-pattern retract all (and (or range version) EOL))
  293. (define-peg-pattern retract-top body
  294. (and (ignore "retract")
  295. (or (and block-start (* (or retract block-line)) block-end) retract)))
  296. (define-peg-pattern go-mod body
  297. (* (and (* WS) (or go module require-top exclude-top replace-top
  298. retract-top EOL unknown))))
  299. (let ((tree (peg:tree (match-pattern go-mod content)))
  300. (keywords '(go module require replace exclude retract comment unknown)))
  301. (keyword-flatten keywords tree)))
  302. ;; Prevent inlining of this procedure, which is accessed by unit tests.
  303. (set! parse-go.mod parse-go.mod)
  304. (define (go.mod-directives go.mod directive)
  305. "Return the list of top-level directive bodies in GO.MOD matching the symbol
  306. DIRECTIVE."
  307. (filter-map (match-lambda
  308. (((? (cut eq? <> directive) head) . rest) rest)
  309. (_ #f))
  310. go.mod))
  311. (define (go.mod-requirements go.mod)
  312. "Compute and return the list of requirements specified by GO.MOD."
  313. (define (replace directive requirements)
  314. (define (maybe-replace module-path new-requirement)
  315. ;; Do not allow version updates for indirect dependencies (see:
  316. ;; https://golang.org/ref/mod#go-mod-file-replace).
  317. (if (and (equal? module-path (first new-requirement))
  318. (not (assoc-ref requirements module-path)))
  319. requirements
  320. (cons new-requirement (alist-delete module-path requirements))))
  321. (match directive
  322. ((('original ('module-path module-path) . _) with . _)
  323. (match with
  324. (('with ('file-path _) . _)
  325. (alist-delete module-path requirements))
  326. (('with ('module-path new-module-path) ('version new-version) . _)
  327. (maybe-replace module-path
  328. (list new-module-path new-version)))))))
  329. (define (require directive requirements)
  330. (match directive
  331. ((('module-path module-path) ('version version) . _)
  332. (cons (list module-path version) requirements))))
  333. (let* ((requires (go.mod-directives go.mod 'require))
  334. (replaces (go.mod-directives go.mod 'replace))
  335. (requirements (fold require '() requires)))
  336. (fold replace requirements replaces)))
  337. ;; Prevent inlining of this procedure, which is accessed by unit tests.
  338. (set! go.mod-requirements go.mod-requirements)
  339. (define-record-type <vcs>
  340. (%make-vcs url-prefix root-regex type)
  341. vcs?
  342. (url-prefix vcs-url-prefix)
  343. (root-regex vcs-root-regex)
  344. (type vcs-type))
  345. (define (make-vcs prefix regexp type)
  346. (%make-vcs prefix (make-regexp regexp) type))
  347. (define known-vcs
  348. ;; See the following URL for the official Go equivalent:
  349. ;; https://github.com/golang/go/blob/846dce9d05f19a1f53465e62a304dea21b99f910/src/cmd/go/internal/vcs/vcs.go#L1026-L1087
  350. (list
  351. (make-vcs
  352. "github.com"
  353. "^(github\\.com/[A-Za-z0-9_.\\-]+/[A-Za-z0-9_.\\-]+)(/[A-Za-z0-9_.\\-]+)*$"
  354. 'git)
  355. (make-vcs
  356. "bitbucket.org"
  357. "^(bitbucket\\.org/([A-Za-z0-9_.\\-]+/[A-Za-z0-9_.\\-]+))(/[A-Za-z0-9_.\\-]+)*$"
  358. 'unknown)
  359. (make-vcs
  360. "hub.jazz.net/git/"
  361. "^(hub\\.jazz\\.net/git/[a-z0-9]+/[A-Za-z0-9_.\\-]+)(/[A-Za-z0-9_.\\-]+)*$"
  362. 'git)
  363. (make-vcs
  364. "git.apache.org"
  365. "^(git\\.apache\\.org/[a-z0-9_.\\-]+\\.git)(/[A-Za-z0-9_.\\-]+)*$"
  366. 'git)
  367. (make-vcs
  368. "git.openstack.org"
  369. "^(git\\.openstack\\.org/[A-Za-z0-9_.\\-]+/[A-Za-z0-9_.\\-]+)(\\.git)?\
  370. (/[A-Za-z0-9_.\\-]+)*$"
  371. 'git)))
  372. (define (module-path->repository-root module-path)
  373. "Infer the repository root from a module path. Go modules can be
  374. defined at any level of a repository tree, but querying for the meta tag
  375. usually can only be done from the web page at the root of the repository,
  376. hence the need to derive this information."
  377. ;; For reference, see: https://golang.org/ref/mod#vcs-find.
  378. (define vcs-qualifiers '(".bzr" ".fossil" ".git" ".hg" ".svn"))
  379. (define (vcs-qualified-module-path->root-repo-url module-path)
  380. (let* ((vcs-qualifiers-group (string-join vcs-qualifiers "|"))
  381. (pattern (format #f "^(.*(~a))(/|$)" vcs-qualifiers-group))
  382. (m (string-match pattern module-path)))
  383. (and=> m (cut match:substring <> 1))))
  384. (or (and=> (find (lambda (vcs)
  385. (string-prefix? (vcs-url-prefix vcs) module-path))
  386. known-vcs)
  387. (lambda (vcs)
  388. (match:substring (regexp-exec (vcs-root-regex vcs)
  389. module-path) 1)))
  390. (vcs-qualified-module-path->root-repo-url module-path)
  391. module-path))
  392. (define* (go-module->guix-package-name module-path #:optional version)
  393. "Converts a module's path to the canonical Guix format for Go packages.
  394. Optionally include a VERSION string to append to the name."
  395. ;; Map dot, slash, underscore and tilde characters to hyphens.
  396. (let ((module-path* (string-map (lambda (c)
  397. (if (member c '(#\. #\/ #\_ #\~))
  398. #\-
  399. c))
  400. module-path)))
  401. (string-downcase (string-append "go-" module-path*
  402. (if version
  403. (string-append "-" version)
  404. "")))))
  405. (define (strip-.git-suffix/maybe repo-url)
  406. "Strip a repository URL '.git' suffix from REPO-URL if hosted at GitHub."
  407. (match repo-url
  408. ((and (? (cut string-prefix? "https://github.com" <>))
  409. (? (cut string-suffix? ".git" <>)))
  410. (string-drop-right repo-url 4))
  411. (_ repo-url)))
  412. (define-record-type <module-meta>
  413. (make-module-meta import-prefix vcs repo-root)
  414. module-meta?
  415. (import-prefix module-meta-import-prefix)
  416. (vcs module-meta-vcs) ;a symbol
  417. (repo-root module-meta-repo-root))
  418. (define (fetch-module-meta-data module-path)
  419. "Retrieve the module meta-data from its landing page. This is necessary
  420. because goproxy servers don't currently provide all the information needed to
  421. build a package."
  422. (define (go-import->module-meta content-text)
  423. (match (string-tokenize content-text char-set:graphic)
  424. ((root-path vcs repo-url)
  425. (make-module-meta root-path (string->symbol vcs)
  426. (strip-.git-suffix/maybe repo-url)))))
  427. ;; <meta name="go-import" content="import-prefix vcs repo-root">
  428. (let* ((meta-data (http-fetch* (format #f "https://~a?go-get=1" module-path)))
  429. (select (sxpath `(// (meta (@ (equal? (name "go-import"))))
  430. // content))))
  431. (match (select (html->sxml meta-data #:strict? #t))
  432. (() #f) ;nothing selected
  433. ((('content content-text) ..1)
  434. (or
  435. (find (lambda (meta)
  436. (string-prefix? (module-meta-import-prefix meta) module-path))
  437. (map go-import->module-meta content-text))
  438. ;; Fallback to the first meta if no import prefixes match.
  439. (go-import->module-meta (first content-text)))))))
  440. (define (module-meta-data-repo-url meta-data goproxy)
  441. "Return the URL where the fetcher which will be used can download the
  442. source."
  443. (if (member (module-meta-vcs meta-data) '(fossil mod))
  444. goproxy
  445. (module-meta-repo-root meta-data)))
  446. (define* (git-checkout-hash url reference algorithm)
  447. "Return the ALGORITHM hash of the checkout of URL at REFERENCE, a commit or
  448. tag."
  449. (define cache
  450. (string-append (or (getenv "TMPDIR") "/tmp")
  451. "/guix-import-go-"
  452. (passwd:name (getpwuid (getuid)))))
  453. ;; Use a custom cache to avoid cluttering the default one under
  454. ;; ~/.cache/guix, but choose one under /tmp so that it's persistent across
  455. ;; subsequent "guix import" invocations.
  456. (mkdir-p cache)
  457. (chmod cache #o700)
  458. (let-values (((checkout commit _)
  459. (parameterize ((%repository-cache-directory cache))
  460. (update-cached-checkout url
  461. #:ref
  462. `(tag-or-commit . ,reference)))))
  463. (file-hash* checkout #:algorithm algorithm #:recursive? #true)))
  464. (define (vcs->origin vcs-type vcs-repo-url version)
  465. "Generate the `origin' block of a package depending on what type of source
  466. control system is being used."
  467. (case vcs-type
  468. ((git)
  469. (let ((plain-version? (string=? version (go-version->git-ref version)))
  470. (v-prefixed? (string-prefix? "v" version)))
  471. `(origin
  472. (method git-fetch)
  473. (uri (git-reference
  474. (url ,vcs-repo-url)
  475. ;; This is done because the version field of the package,
  476. ;; which the generated quoted expression refers to, has been
  477. ;; stripped of any 'v' prefixed.
  478. (commit ,(if (and plain-version? v-prefixed?)
  479. '(string-append "v" version)
  480. '(go-version->git-ref version)))))
  481. (file-name (git-file-name name version))
  482. (sha256
  483. (base32
  484. ,(bytevector->nix-base32-string
  485. (git-checkout-hash vcs-repo-url (go-version->git-ref version)
  486. (hash-algorithm sha256))))))))
  487. ((hg)
  488. `(origin
  489. (method hg-fetch)
  490. (uri (hg-reference
  491. (url ,vcs-repo-url)
  492. (changeset ,version)))
  493. (file-name (string-append name "-" version "-checkout"))
  494. (sha256
  495. (base32
  496. ;; FIXME: populate hash for hg repo checkout
  497. "0000000000000000000000000000000000000000000000000000"))))
  498. ((svn)
  499. `(origin
  500. (method svn-fetch)
  501. (uri (svn-reference
  502. (url ,vcs-repo-url)
  503. (revision (string->number version))))
  504. (file-name (string-append name "-" version "-checkout"))
  505. (sha256
  506. (base32
  507. ;; FIXME: populate hash for svn repo checkout
  508. "0000000000000000000000000000000000000000000000000000"))))
  509. (else
  510. (raise
  511. (formatted-message (G_ "unsupported vcs type '~a' for package '~a'")
  512. vcs-type vcs-repo-url)))))
  513. (define (strip-v-prefix version)
  514. "Strip from VERSION the \"v\" prefix that Go uses."
  515. (string-trim version #\v))
  516. (define (ensure-v-prefix version)
  517. "Add a \"v\" prefix to VERSION if it does not already have one."
  518. (if (string-prefix? "v" version)
  519. version
  520. (string-append "v" version)))
  521. (define (validate-version version available-versions module-path)
  522. "Raise an error if VERSION is not among AVAILABLE-VERSIONS, unless VERSION
  523. is a pseudo-version. Return VERSION."
  524. ;; Pseudo-versions do not appear in the versions list; skip the
  525. ;; following check.
  526. (if (or (go-pseudo-version? version)
  527. (member version available-versions))
  528. version
  529. (raise
  530. (make-compound-condition
  531. (formatted-message (G_ "version ~a of ~a is not available~%")
  532. version module-path available-versions)
  533. (condition (&fix-hint
  534. (hint (format #f (G_ "Pick one of the following \
  535. available versions:~{ ~a~}.")
  536. (map strip-v-prefix
  537. available-versions)))))))))
  538. (define* (go-module->guix-package module-path #:key
  539. (goproxy "https://proxy.golang.org")
  540. version
  541. pin-versions?
  542. #:allow-other-keys)
  543. "Return the package S-expression corresponding to MODULE-PATH at VERSION, a Go package.
  544. The meta-data is fetched from the GOPROXY server and https://pkg.go.dev/.
  545. When VERSION is unspecified, the latest version available is used."
  546. (let* ((available-versions (go-module-available-versions goproxy module-path))
  547. (version* (validate-version
  548. (or (and version (ensure-v-prefix version))
  549. (go-module-version-string goproxy module-path)) ;latest
  550. available-versions
  551. module-path))
  552. (content (fetch-go.mod goproxy module-path version*))
  553. (dependencies+versions (go.mod-requirements (parse-go.mod content)))
  554. (dependencies (if pin-versions?
  555. dependencies+versions
  556. (map car dependencies+versions)))
  557. (module-path-sans-suffix
  558. (match:prefix (string-match "([\\./]v[0-9]+)?$" module-path)))
  559. (guix-name (go-module->guix-package-name module-path))
  560. (root-module-path (module-path->repository-root module-path))
  561. ;; The VCS type and URL are not included in goproxy information. For
  562. ;; this we need to fetch it from the official module page.
  563. (meta-data (fetch-module-meta-data root-module-path))
  564. (vcs-type (module-meta-vcs meta-data))
  565. (vcs-repo-url (module-meta-data-repo-url meta-data goproxy))
  566. (synopsis (go-package-synopsis module-path))
  567. (description (go-package-description module-path))
  568. (licenses (go-package-licenses module-path)))
  569. (values
  570. `(package
  571. (name ,guix-name)
  572. (version ,(strip-v-prefix version*))
  573. (source
  574. ,(vcs->origin vcs-type vcs-repo-url version*))
  575. (build-system go-build-system)
  576. (arguments
  577. '(#:import-path ,module-path
  578. ,@(if (string=? module-path-sans-suffix root-module-path)
  579. '()
  580. `(#:unpack-path ,root-module-path))))
  581. ,@(maybe-propagated-inputs
  582. (map (match-lambda
  583. ((name version)
  584. (go-module->guix-package-name name (strip-v-prefix version)))
  585. (name
  586. (go-module->guix-package-name name)))
  587. dependencies))
  588. (home-page ,(format #f "https://~a" root-module-path))
  589. (synopsis ,synopsis)
  590. (description ,(and=> description beautify-description))
  591. (license ,(match (list->licenses licenses)
  592. (() #f) ;unknown license
  593. ((license) ;a single license
  594. license)
  595. ((license ...) ;a list of licenses
  596. `(list ,@license)))))
  597. (if pin-versions?
  598. dependencies+versions
  599. dependencies))))
  600. (define go-module->guix-package*
  601. (lambda args
  602. ;; Disable output buffering so that the following warning gets printed
  603. ;; consistently.
  604. (setvbuf (current-error-port) 'none)
  605. (let ((package-name (match args ((name _ ...) name))))
  606. (guard (c ((http-get-error? c)
  607. (warning (G_ "Failed to import package ~s.
  608. reason: ~s could not be fetched: HTTP error ~a (~s).
  609. This package and its dependencies won't be imported.~%")
  610. package-name
  611. (uri->string (http-get-error-uri c))
  612. (http-get-error-code c)
  613. (http-get-error-reason c))
  614. (values #f '())))
  615. (apply go-module->guix-package args)))))
  616. (define* (go-module-recursive-import package-name
  617. #:key (goproxy "https://proxy.golang.org")
  618. version
  619. pin-versions?)
  620. (recursive-import
  621. package-name
  622. #:repo->guix-package
  623. (memoize
  624. (lambda* (name #:key version repo #:allow-other-keys)
  625. (receive (package-sexp dependencies)
  626. (go-module->guix-package* name #:goproxy goproxy
  627. #:version version
  628. #:pin-versions? pin-versions?)
  629. (values package-sexp dependencies))))
  630. #:guix-name go-module->guix-package-name
  631. #:version version))