git.scm 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2017, 2020 Mathieu Othacehe <m.othacehe@gmail.com>
  3. ;;; Copyright © 2018, 2019, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
  4. ;;; Copyright © 2021 Kyle Meyer <kyle@kyleam.com>
  5. ;;; Copyright © 2021 Marius Bakke <marius@gnu.org>
  6. ;;; Copyright © 2022 Maxime Devos <maximedevos@telenet.be>
  7. ;;;
  8. ;;; This file is part of GNU Guix.
  9. ;;;
  10. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  11. ;;; under the terms of the GNU General Public License as published by
  12. ;;; the Free Software Foundation; either version 3 of the License, or (at
  13. ;;; your option) any later version.
  14. ;;;
  15. ;;; GNU Guix is distributed in the hope that it will be useful, but
  16. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;;; GNU General Public License for more details.
  19. ;;;
  20. ;;; You should have received a copy of the GNU General Public License
  21. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  22. (define-module (guix git)
  23. #:use-module (git)
  24. #:use-module (git object)
  25. #:use-module (git submodule)
  26. #:use-module (guix i18n)
  27. #:use-module (guix base32)
  28. #:use-module (guix cache)
  29. #:use-module (gcrypt hash)
  30. #:use-module ((guix build utils)
  31. #:select (mkdir-p delete-file-recursively))
  32. #:use-module (guix store)
  33. #:use-module (guix utils)
  34. #:use-module (guix records)
  35. #:use-module (guix gexp)
  36. #:autoload (guix git-download)
  37. (git-reference-url git-reference-commit git-reference-recursive?)
  38. #:use-module (guix sets)
  39. #:use-module ((guix diagnostics) #:select (leave warning))
  40. #:use-module (guix progress)
  41. #:autoload (guix swh) (swh-download commit-id?)
  42. #:use-module (rnrs bytevectors)
  43. #:use-module (ice-9 format)
  44. #:use-module (ice-9 match)
  45. #:use-module (ice-9 ftw)
  46. #:use-module (srfi srfi-1)
  47. #:use-module (srfi srfi-11)
  48. #:use-module (srfi srfi-34)
  49. #:use-module (srfi srfi-35)
  50. #:export (%repository-cache-directory
  51. honor-system-x509-certificates!
  52. url-cache-directory
  53. with-repository
  54. with-git-error-handling
  55. false-if-git-not-found
  56. update-cached-checkout
  57. url+commit->name
  58. latest-repository-commit
  59. commit-difference
  60. commit-relation
  61. remote-refs
  62. git-checkout
  63. git-checkout?
  64. git-checkout-url
  65. git-checkout-branch
  66. git-checkout-commit
  67. git-checkout-recursive?
  68. git-reference->git-checkout))
  69. (define %repository-cache-directory
  70. (make-parameter (string-append (cache-directory #:ensure? #f)
  71. "/checkouts")))
  72. (define (honor-system-x509-certificates!)
  73. "Use the system's X.509 certificates for Git checkouts over HTTPS. Honor
  74. the 'SSL_CERT_FILE' and 'SSL_CERT_DIR' environment variables."
  75. ;; On distros such as CentOS 7, /etc/ssl/certs contains only a couple of
  76. ;; files (instead of all the certificates) among which "ca-bundle.crt". On
  77. ;; other distros /etc/ssl/certs usually contains the whole set of
  78. ;; certificates along with "ca-certificates.crt". Try to choose the right
  79. ;; one.
  80. (let ((file (letrec-syntax ((choose
  81. (syntax-rules ()
  82. ((_ file rest ...)
  83. (let ((f file))
  84. (if (and f (file-exists? f))
  85. f
  86. (choose rest ...))))
  87. ((_)
  88. #f))))
  89. (choose (getenv "SSL_CERT_FILE")
  90. "/etc/ssl/certs/ca-certificates.crt"
  91. "/etc/ssl/certs/ca-bundle.crt")))
  92. (directory (or (getenv "SSL_CERT_DIR") "/etc/ssl/certs")))
  93. (and (or file
  94. (and=> (stat directory #f)
  95. (lambda (st)
  96. (> (stat:nlink st) 2))))
  97. (begin
  98. (set-tls-certificate-locations! directory file)
  99. #t))))
  100. (define %certificates-initialized?
  101. ;; Whether 'honor-system-x509-certificates!' has already been called.
  102. #f)
  103. (define-syntax-rule (with-libgit2 thunk ...)
  104. (begin
  105. ;; XXX: The right thing to do would be to call (libgit2-shutdown) here,
  106. ;; but pointer finalizers used in guile-git may be called after shutdown,
  107. ;; resulting in a segfault. Hence, let's skip shutdown call for now.
  108. (libgit2-init!)
  109. (unless %certificates-initialized?
  110. (honor-system-x509-certificates!)
  111. (set! %certificates-initialized? #t))
  112. thunk ...))
  113. (define* (url-cache-directory url
  114. #:optional (cache-directory
  115. (%repository-cache-directory))
  116. #:key recursive?)
  117. "Return the directory associated to URL in %repository-cache-directory."
  118. (string-append
  119. cache-directory "/"
  120. (bytevector->base32-string
  121. (sha256 (string->utf8 (if recursive?
  122. (string-append "R:" url)
  123. url))))))
  124. (define (show-progress progress)
  125. "Display a progress bar as we fetch Git code. PROGRESS is an
  126. <indexer-progress> record from (git)."
  127. (define total
  128. (indexer-progress-total-objects progress))
  129. (define hundredth
  130. (match (quotient (indexer-progress-total-objects progress) 100)
  131. (0 1)
  132. (x x)))
  133. (define-values (done label)
  134. (if (< (indexer-progress-received-objects progress) total)
  135. (values (indexer-progress-received-objects progress)
  136. (G_ "receiving objects"))
  137. (values (indexer-progress-indexed-objects progress)
  138. (G_ "indexing objects"))))
  139. (define %
  140. (* 100. (/ done total)))
  141. (when (and (< % 100) (zero? (modulo done hundredth)))
  142. (erase-current-line (current-error-port))
  143. (let ((width (max (- (current-terminal-columns)
  144. (string-length label) 7)
  145. 3)))
  146. (format (current-error-port) "~a ~3,d% ~a"
  147. label (inexact->exact (round %))
  148. (progress-bar % width)))
  149. (force-output (current-error-port)))
  150. (when (= % 100.)
  151. ;; We're done, erase the line.
  152. (erase-current-line (current-error-port))
  153. (force-output (current-error-port)))
  154. ;; Return true to indicate that we should go on.
  155. #t)
  156. (define (make-default-fetch-options)
  157. "Return the default fetch options."
  158. (let ((auth-method (%make-auth-ssh-agent)))
  159. ;; The #:transfer-progress and #:proxy-url options appeared in Guile-Git
  160. ;; 0.4.0. Omit them when using an older version.
  161. (catch 'wrong-number-of-args
  162. (lambda ()
  163. (make-fetch-options auth-method
  164. ;; Guile-Git doesn't distinguish between these.
  165. #:proxy-url (or (getenv "http_proxy")
  166. (getenv "https_proxy"))
  167. #:transfer-progress
  168. (and (isatty? (current-error-port))
  169. show-progress)))
  170. (lambda args
  171. (make-fetch-options auth-method)))))
  172. (define GITERR_HTTP
  173. ;; Guile-Git <= 0.5.2 lacks this constant.
  174. (let ((errors (resolve-interface '(git errors))))
  175. (if (module-defined? errors 'GITERR_HTTP)
  176. (module-ref errors 'GITERR_HTTP)
  177. 34)))
  178. (define (clone* url directory)
  179. "Clone git repository at URL into DIRECTORY. Upon failure,
  180. make sure no empty directory is left behind."
  181. (with-throw-handler #t
  182. (lambda ()
  183. (mkdir-p directory)
  184. (clone url directory
  185. (make-clone-options
  186. #:fetch-options (make-default-fetch-options))))
  187. (lambda _
  188. (false-if-exception (rmdir directory)))))
  189. (define (url+commit->name url sha1)
  190. "Return the string \"<REPO-NAME>-<SHA1:7>\" where REPO-NAME is the name of
  191. the git repository, extracted from URL and SHA1:7 the seven first digits
  192. of SHA1 string."
  193. (string-append
  194. (string-replace-substring
  195. (last (string-split url #\/)) ".git" "")
  196. "-" (string-take sha1 7)))
  197. (define (resolve-reference repository ref)
  198. "Resolve the branch, commit or tag specified by REF, and return the
  199. corresponding Git object."
  200. (let resolve ((ref ref))
  201. (match ref
  202. (('branch . branch)
  203. (let ((oid (reference-target
  204. (branch-lookup repository branch BRANCH-REMOTE))))
  205. (object-lookup repository oid)))
  206. (('symref . symref)
  207. (let ((oid (reference-name->oid repository symref)))
  208. (object-lookup repository oid)))
  209. (('commit . commit)
  210. (let ((len (string-length commit)))
  211. ;; 'object-lookup-prefix' appeared in Guile-Git in Mar. 2018, so we
  212. ;; can't be sure it's available. Furthermore, 'string->oid' used to
  213. ;; read out-of-bounds when passed a string shorter than 40 chars,
  214. ;; which is why we delay calls to it below.
  215. (if (< len 40)
  216. (object-lookup-prefix repository (string->oid commit) len)
  217. (object-lookup repository (string->oid commit)))))
  218. (('tag-or-commit . str)
  219. (cond ((and (string-contains str "-g")
  220. (match (string-split str #\-)
  221. ((version ... revision g+commit)
  222. (if (and (> (string-length g+commit) 4)
  223. (string-every char-set:digit revision)
  224. (string-every char-set:hex-digit
  225. (string-drop g+commit 1)))
  226. ;; Looks like a 'git describe' style ID, like
  227. ;; v1.3.0-7-gaa34d4d28d.
  228. (string-drop g+commit 1)
  229. #f))
  230. (_ #f)))
  231. => (lambda (commit) (resolve `(commit . ,commit))))
  232. ((or (> (string-length str) 40)
  233. (not (string-every char-set:hex-digit str)))
  234. (resolve `(tag . ,str))) ;definitely a tag
  235. (else
  236. (catch 'git-error
  237. (lambda ()
  238. (resolve `(tag . ,str)))
  239. (lambda _
  240. ;; There's no such tag, so it must be a commit ID.
  241. (resolve `(commit . ,str)))))))
  242. (('tag . tag)
  243. (let ((oid (reference-name->oid repository
  244. (string-append "refs/tags/" tag))))
  245. ;; OID may point to a "tag" object, but it can also point directly
  246. ;; to a "commit" object, as surprising as it may seem. Return that
  247. ;; object, whatever that is.
  248. (object-lookup repository oid))))))
  249. (define (switch-to-ref repository ref)
  250. "Switch to REPOSITORY's branch, commit or tag specified by REF. Return the
  251. OID (roughly the commit hash) corresponding to REF."
  252. (define obj
  253. (resolve-reference repository ref))
  254. (reset repository obj RESET_HARD)
  255. (object-id obj))
  256. (define (call-with-repository directory proc)
  257. (let ((repository #f))
  258. (dynamic-wind
  259. (lambda ()
  260. (set! repository (repository-open directory)))
  261. (lambda ()
  262. (proc repository))
  263. (lambda ()
  264. (repository-close! repository)))))
  265. (define-syntax-rule (with-repository directory repository exp ...)
  266. "Open the repository at DIRECTORY and bind REPOSITORY to it within the
  267. dynamic extent of EXP."
  268. (call-with-repository directory
  269. (lambda (repository) exp ...)))
  270. (define (report-git-error error)
  271. "Report the given Guile-Git error."
  272. ;; Prior to Guile-Git commit b6b2760c2fd6dfaa5c0fedb43eeaff06166b3134,
  273. ;; errors would be represented by integers.
  274. (match error
  275. ((? integer? error) ;old Guile-Git
  276. (leave (G_ "Git error ~a~%") error))
  277. ((? git-error? error) ;new Guile-Git
  278. (leave (G_ "Git error: ~a~%") (git-error-message error)))))
  279. (define-syntax-rule (with-git-error-handling body ...)
  280. (catch 'git-error
  281. (lambda ()
  282. body ...)
  283. (lambda (key err)
  284. (report-git-error err))))
  285. (define* (update-submodules repository
  286. #:key (log-port (current-error-port))
  287. (fetch-options #f))
  288. "Update the submodules of REPOSITORY, a Git repository object."
  289. (for-each (lambda (name)
  290. (let ((submodule (submodule-lookup repository name)))
  291. (format log-port (G_ "updating submodule '~a'...~%")
  292. name)
  293. (submodule-update submodule
  294. #:fetch-options fetch-options)
  295. ;; Recurse in SUBMODULE.
  296. (let ((directory (string-append
  297. (repository-working-directory repository)
  298. "/" (submodule-path submodule))))
  299. (with-repository directory repository
  300. (update-submodules repository
  301. #:fetch-options fetch-options
  302. #:log-port log-port)))))
  303. (repository-submodules repository)))
  304. (define-syntax-rule (false-if-git-not-found exp)
  305. "Evaluate EXP, returning #false if a GIT_ENOTFOUND error is raised."
  306. (catch 'git-error
  307. (lambda ()
  308. exp)
  309. (lambda (key error . rest)
  310. (if (= GIT_ENOTFOUND (git-error-code error))
  311. #f
  312. (apply throw key error rest)))))
  313. (define (reference-available? repository ref)
  314. "Return true if REF, a reference such as '(commit . \"cabba9e\"), is
  315. definitely available in REPOSITORY, false otherwise."
  316. (match ref
  317. ((or ('commit . commit)
  318. ('tag-or-commit . (? commit-id? commit)))
  319. (let ((len (string-length commit))
  320. (oid (string->oid commit)))
  321. (false-if-git-not-found
  322. (->bool (if (< len 40)
  323. (object-lookup-prefix repository oid len OBJ-COMMIT)
  324. (commit-lookup repository oid))))))
  325. (_
  326. #f)))
  327. (define (clone-from-swh url tag-or-commit output)
  328. "Attempt to clone TAG-OR-COMMIT (a string), which originates from URL, using
  329. a copy archived at Software Heritage."
  330. (call-with-temporary-directory
  331. (lambda (bare)
  332. (and (swh-download url tag-or-commit bare
  333. #:archive-type 'git-bare)
  334. (let ((repository (clone* bare output)))
  335. (remote-set-url! repository "origin" url)
  336. repository)))))
  337. (define (clone/swh-fallback url ref cache-directory)
  338. "Like 'clone', but fallback to Software Heritage if the repository cannot be
  339. found at URL."
  340. (define (inaccessible-url-error? err)
  341. (let ((class (git-error-class err))
  342. (code (git-error-code err)))
  343. (or (= class GITERR_HTTP) ;404 or similar
  344. (= class GITERR_NET)))) ;unknown host, etc.
  345. (catch 'git-error
  346. (lambda ()
  347. (clone* url cache-directory))
  348. (lambda (key err)
  349. (match ref
  350. (((or 'commit 'tag-or-commit) . commit)
  351. (if (inaccessible-url-error? err)
  352. (or (clone-from-swh url commit cache-directory)
  353. (begin
  354. (warning (G_ "revision ~a of ~a \
  355. could not be fetched from Software Heritage~%")
  356. commit url)
  357. (throw key err)))
  358. (throw key err)))
  359. (_ (throw key err))))))
  360. (define cached-checkout-expiration
  361. ;; Return the expiration time procedure for a cached checkout.
  362. ;; TODO: Honor $GUIX_GIT_CACHE_EXPIRATION.
  363. ;; Use the mtime rather than the atime to cope with file systems mounted
  364. ;; with 'noatime'.
  365. (file-expiration-time (* 90 24 3600) stat:mtime))
  366. (define %checkout-cache-cleanup-period
  367. ;; Period for the removal of expired cached checkouts.
  368. (* 5 24 3600))
  369. (define (delete-checkout directory)
  370. "Delete DIRECTORY recursively, in an atomic fashion."
  371. (let ((trashed (string-append directory ".trashed")))
  372. (rename-file directory trashed)
  373. (delete-file-recursively trashed)))
  374. (define* (update-cached-checkout url
  375. #:key
  376. (ref '())
  377. recursive?
  378. (check-out? #t)
  379. starting-commit
  380. (log-port (%make-void-port "w"))
  381. (cache-directory
  382. (url-cache-directory
  383. url (%repository-cache-directory)
  384. #:recursive? recursive?)))
  385. "Update the cached checkout of URL to REF in CACHE-DIRECTORY. Return three
  386. values: the cache directory name, and the SHA1 commit (a string) corresponding
  387. to REF, and the relation of the new commit relative to STARTING-COMMIT (if
  388. provided) as returned by 'commit-relation'.
  389. REF is pair whose key is [branch | commit | tag | tag-or-commit ] and value
  390. the associated data: [<branch name> | <sha1> | <tag name> | <string>].
  391. If REF is the empty list, the remote HEAD is used.
  392. When RECURSIVE? is true, check out submodules as well, if any.
  393. When CHECK-OUT? is true, reset the cached working tree to REF; otherwise leave
  394. it unchanged."
  395. (define (cache-entries directory)
  396. (filter-map (match-lambda
  397. ((or "." "..")
  398. #f)
  399. (file
  400. (string-append directory "/" file)))
  401. (or (scandir directory) '())))
  402. (define canonical-ref
  403. ;; We used to require callers to specify "origin/" for each branch, which
  404. ;; made little sense since the cache should be transparent to them. So
  405. ;; here we append "origin/" if it's missing and otherwise keep it.
  406. (match ref
  407. (() '(symref . "refs/remotes/origin/HEAD"))
  408. (('branch . branch)
  409. `(branch . ,(if (string-prefix? "origin/" branch)
  410. branch
  411. (string-append "origin/" branch))))
  412. (_ ref)))
  413. (with-libgit2
  414. (let* ((cache-exists? (openable-repository? cache-directory))
  415. (repository (if cache-exists?
  416. (repository-open cache-directory)
  417. (clone/swh-fallback url ref cache-directory))))
  418. ;; Only fetch remote if it has not been cloned just before.
  419. (when (and cache-exists?
  420. (not (reference-available? repository ref)))
  421. (remote-fetch (remote-lookup repository "origin")
  422. #:fetch-options (make-default-fetch-options)))
  423. (when recursive?
  424. (update-submodules repository #:log-port log-port
  425. #:fetch-options (make-default-fetch-options)))
  426. ;; Note: call 'commit-relation' from here because it's more efficient
  427. ;; than letting users re-open the checkout later on.
  428. (let* ((oid (if check-out?
  429. (switch-to-ref repository canonical-ref)
  430. (object-id
  431. (resolve-reference repository canonical-ref))))
  432. (new (and starting-commit
  433. (commit-lookup repository oid)))
  434. (old (and starting-commit
  435. (false-if-git-not-found
  436. (commit-lookup repository
  437. (string->oid starting-commit)))))
  438. (relation (and starting-commit
  439. (if old
  440. (commit-relation old new)
  441. 'unrelated))))
  442. ;; Reclaim file descriptors and memory mappings associated with
  443. ;; REPOSITORY as soon as possible.
  444. (repository-close! repository)
  445. ;; Update CACHE-DIRECTORY's mtime to so the cache logic sees it.
  446. (match (gettimeofday)
  447. ((seconds . microseconds)
  448. (let ((nanoseconds (* 1000 microseconds)))
  449. (utime cache-directory
  450. seconds seconds
  451. nanoseconds nanoseconds))))
  452. ;; When CACHE-DIRECTORY is a sub-directory of the default cache
  453. ;; directory, remove expired checkouts that are next to it.
  454. (let ((parent (dirname cache-directory)))
  455. (when (string=? parent (%repository-cache-directory))
  456. (maybe-remove-expired-cache-entries parent cache-entries
  457. #:entry-expiration
  458. cached-checkout-expiration
  459. #:delete-entry delete-checkout
  460. #:cleanup-period
  461. %checkout-cache-cleanup-period)))
  462. (values cache-directory (oid->string oid) relation)))))
  463. (define* (latest-repository-commit store url
  464. #:key
  465. recursive?
  466. (log-port (%make-void-port "w"))
  467. (cache-directory
  468. (%repository-cache-directory))
  469. (ref '()))
  470. "Return two values: the content of the git repository at URL copied into a
  471. store directory and the sha1 of the top level commit in this directory. The
  472. reference to be checkout, once the repository is fetched, is specified by REF.
  473. REF is pair whose key is [branch | commit | tag] and value the associated
  474. data, respectively [<branch name> | <sha1> | <tag name>]. If REF is the empty
  475. list, the remote HEAD is used.
  476. When RECURSIVE? is true, check out submodules as well, if any.
  477. Git repositories are kept in the cache directory specified by
  478. %repository-cache-directory parameter.
  479. Log progress and checkout info to LOG-PORT."
  480. (define (dot-git? file stat)
  481. (and (string=? (basename file) ".git")
  482. (or (eq? 'directory (stat:type stat))
  483. ;; Submodule checkouts end up with a '.git' regular file that
  484. ;; contains metadata about where their actual '.git' directory
  485. ;; lives.
  486. (and recursive?
  487. (eq? 'regular (stat:type stat))))))
  488. (format log-port "updating checkout of '~a'...~%" url)
  489. (let*-values
  490. (((checkout commit _)
  491. (update-cached-checkout url
  492. #:recursive? recursive?
  493. #:ref ref
  494. #:cache-directory
  495. (url-cache-directory url cache-directory
  496. #:recursive?
  497. recursive?)
  498. #:log-port log-port))
  499. ((name)
  500. (url+commit->name url commit)))
  501. (format log-port "retrieved commit ~a~%" commit)
  502. (values (add-to-store store name #t "sha256" checkout
  503. #:select? (negate dot-git?))
  504. commit)))
  505. (define (print-git-error port key args default-printer)
  506. (match args
  507. (((? git-error? error) . _)
  508. (format port (G_ "Git error: ~a~%")
  509. (git-error-message error)))))
  510. (set-exception-printer! 'git-error print-git-error)
  511. ;;;
  512. ;;; Commit difference.
  513. ;;;
  514. (define* (commit-closure commit #:optional (visited (setq)))
  515. "Return the closure of COMMIT as a set. Skip commits contained in VISITED,
  516. a set, and adjoin VISITED to the result."
  517. (let loop ((commits (list commit))
  518. (visited visited))
  519. (match commits
  520. (()
  521. visited)
  522. ((head . tail)
  523. (if (set-contains? visited head)
  524. (loop tail visited)
  525. (loop (append (commit-parents head) tail)
  526. (set-insert head visited)))))))
  527. (define* (commit-difference new old #:optional (excluded '()))
  528. "Return the list of commits between NEW and OLD, where OLD is assumed to be
  529. an ancestor of NEW. Exclude all the commits listed in EXCLUDED along with
  530. their ancestors.
  531. Essentially, this computes the set difference between the closure of NEW and
  532. that of OLD."
  533. (let loop ((commits (list new))
  534. (result '())
  535. (visited (fold commit-closure
  536. (setq)
  537. (cons old excluded))))
  538. (match commits
  539. (()
  540. (reverse result))
  541. ((head . tail)
  542. (if (set-contains? visited head)
  543. (loop tail result visited)
  544. (loop (append (commit-parents head) tail)
  545. (cons head result)
  546. (set-insert head visited)))))))
  547. (define (commit-relation old new)
  548. "Return a symbol denoting the relation between OLD and NEW, two commit
  549. objects: 'ancestor (meaning that OLD is an ancestor of NEW), 'descendant, or
  550. 'unrelated, or 'self (OLD and NEW are the same commit)."
  551. (if (eq? old new)
  552. 'self
  553. (let ((newest (commit-closure new)))
  554. (if (set-contains? newest old)
  555. 'ancestor
  556. (let* ((seen (list->setq (commit-parents new)))
  557. (oldest (commit-closure old seen)))
  558. (if (set-contains? oldest new)
  559. 'descendant
  560. 'unrelated))))))
  561. ;;
  562. ;;; Remote operations.
  563. ;;;
  564. (define* (remote-refs url #:key tags?)
  565. "Return the list of references advertised at Git repository URL. If TAGS?
  566. is true, limit to only refs/tags."
  567. (define (ref? ref)
  568. ;; Like `git ls-remote --refs', only show actual references.
  569. (and (string-prefix? "refs/" ref)
  570. (not (string-suffix? "^{}" ref))))
  571. (define (tag? ref)
  572. (string-prefix? "refs/tags/" ref))
  573. (define (include? ref)
  574. (and (ref? ref)
  575. (or (not tags?) (tag? ref))))
  576. (define (remote-head->ref remote)
  577. (let ((name (remote-head-name remote)))
  578. (and (include? name)
  579. name)))
  580. (with-libgit2
  581. (call-with-temporary-directory
  582. (lambda (cache-directory)
  583. (let* ((repository (repository-init cache-directory))
  584. ;; Create an in-memory remote so we don't touch disk.
  585. (remote (remote-create-anonymous repository url)))
  586. (remote-connect remote)
  587. (let* ((remote-heads (remote-ls remote))
  588. (refs (filter-map remote-head->ref remote-heads)))
  589. ;; Wait until we're finished with the repository before closing it.
  590. (remote-disconnect remote)
  591. (repository-close! repository)
  592. refs))))))
  593. ;;;
  594. ;;; Checkouts.
  595. ;;;
  596. ;; Representation of the "latest" checkout of a branch or a specific commit.
  597. (define-record-type* <git-checkout>
  598. git-checkout make-git-checkout
  599. git-checkout?
  600. (url git-checkout-url)
  601. (branch git-checkout-branch (default #f))
  602. (commit git-checkout-commit (default #f)) ;#f | tag | commit
  603. (recursive? git-checkout-recursive? (default #f)))
  604. (define (git-reference->git-checkout reference)
  605. "Convert the <git-reference> REFERENCE to an equivalent <git-checkout>."
  606. (git-checkout
  607. (url (git-reference-url reference))
  608. (commit (git-reference-commit reference))
  609. (recursive? (git-reference-recursive? reference))))
  610. (define* (latest-repository-commit* url #:key ref recursive? log-port)
  611. ;; Monadic variant of 'latest-repository-commit'.
  612. (lambda (store)
  613. ;; The caller--e.g., (guix scripts build)--may not handle 'git-error' so
  614. ;; translate it into '&message' conditions that we know will be properly
  615. ;; handled.
  616. (catch 'git-error
  617. (lambda ()
  618. (values (latest-repository-commit store url
  619. #:ref ref
  620. #:recursive? recursive?
  621. #:log-port log-port)
  622. store))
  623. (lambda (key error . _)
  624. (raise (condition
  625. (&message
  626. (message
  627. (match ref
  628. (('commit . commit)
  629. (format #f (G_ "cannot fetch commit ~a from ~a: ~a")
  630. commit url (git-error-message error)))
  631. (('branch . branch)
  632. (format #f (G_ "cannot fetch branch '~a' from ~a: ~a")
  633. branch url (git-error-message error)))
  634. (_
  635. (format #f (G_ "Git failure while fetching ~a: ~a")
  636. url (git-error-message error))))))))))))
  637. (define-gexp-compiler (git-checkout-compiler (checkout <git-checkout>)
  638. system target)
  639. ;; "Compile" CHECKOUT by updating the local checkout and adding it to the
  640. ;; store.
  641. (match checkout
  642. (($ <git-checkout> url branch commit recursive?)
  643. (latest-repository-commit* url
  644. #:ref (cond (commit
  645. `(tag-or-commit . ,commit))
  646. (branch
  647. `(branch . ,branch))
  648. (else '()))
  649. #:recursive? recursive?
  650. #:log-port (current-error-port)))))
  651. ;; Local Variables:
  652. ;; eval: (put 'with-repository 'scheme-indent-function 2)
  653. ;; End: