git.scm 29 KB

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