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>
6 ;;; This file is part of GNU Guix.
8 ;;; GNU Guix is free software; you can redistribute it and/or modify it
9 ;;; under the terms of the GNU General Public License as published by
10 ;;; the Free Software Foundation; either version 3 of the License, or (at
11 ;;; your option) any later version.
13 ;;; GNU Guix is distributed in the hope that it will be useful, but
14 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;;; GNU General Public License for more details.
18 ;;; You should have received a copy of the GNU General Public License
19 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
21 (define-module (guix git)
23 #:use-module (git object)
24 #:use-module (git submodule)
25 #:use-module (guix i18n)
26 #:use-module (guix base32)
27 #:use-module (guix cache)
28 #:use-module (gcrypt hash)
29 #:use-module ((guix build utils)
30 #:select (mkdir-p delete-file-recursively))
31 #:use-module (guix store)
32 #:use-module (guix utils)
33 #:use-module (guix records)
34 #:use-module (guix gexp)
35 #:use-module (guix sets)
36 #:use-module ((guix diagnostics) #:select (leave))
37 #:use-module (guix progress)
38 #:use-module (rnrs bytevectors)
39 #:use-module (ice-9 format)
40 #:use-module (ice-9 match)
41 #:use-module (ice-9 ftw)
42 #:use-module (srfi srfi-1)
43 #:use-module (srfi srfi-11)
44 #:use-module (srfi srfi-34)
45 #:use-module (srfi srfi-35)
46 #:export (%repository-cache-directory
47 honor-system-x509-certificates!
51 with-git-error-handling
52 false-if-git-not-found
53 update-cached-checkout
55 latest-repository-commit
64 git-checkout-recursive?))
66 (define %repository-cache-directory
67 (make-parameter (string-append (cache-directory #:ensure? #f)
70 (define (honor-system-x509-certificates!)
71 "Use the system's X.509 certificates for Git checkouts over HTTPS. Honor
72 the 'SSL_CERT_FILE' and 'SSL_CERT_DIR' environment variables."
73 ;; On distros such as CentOS 7, /etc/ssl/certs contains only a couple of
74 ;; files (instead of all the certificates) among which "ca-bundle.crt". On
75 ;; other distros /etc/ssl/certs usually contains the whole set of
76 ;; certificates along with "ca-certificates.crt". Try to choose the right
78 (let ((file (letrec-syntax ((choose
82 (if (and f (file-exists? f))
87 (choose (getenv "SSL_CERT_FILE")
88 "/etc/ssl/certs/ca-certificates.crt"
89 "/etc/ssl/certs/ca-bundle.crt")))
90 (directory (or (getenv "SSL_CERT_DIR") "/etc/ssl/certs")))
92 (and=> (stat directory #f)
94 (> (stat:nlink st) 2))))
96 (set-tls-certificate-locations! directory file)
99 (define %certificates-initialized?
100 ;; Whether 'honor-system-x509-certificates!' has already been called.
103 (define-syntax-rule (with-libgit2 thunk ...)
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.
109 (unless %certificates-initialized?
110 (honor-system-x509-certificates!)
111 (set! %certificates-initialized? #t))
114 (define* (url-cache-directory url
115 #:optional (cache-directory
116 (%repository-cache-directory))
118 "Return the directory associated to URL in %repository-cache-directory."
121 (bytevector->base32-string
122 (sha256 (string->utf8 (if recursive?
123 (string-append "R:" 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)."
130 (indexer-progress-total-objects progress))
133 (match (quotient (indexer-progress-total-objects progress) 100)
137 (define-values (done label)
138 (if (< (indexer-progress-received-objects progress) total)
139 (values (indexer-progress-received-objects progress)
140 (G_ "receiving objects"))
141 (values (indexer-progress-indexed-objects progress)
142 (G_ "indexing objects"))))
145 (* 100. (/ done total)))
147 (when (and (< % 100) (zero? (modulo done hundredth)))
148 (erase-current-line (current-error-port))
149 (let ((width (max (- (current-terminal-columns)
150 (string-length label) 7)
152 (format (current-error-port) "~a ~3,d% ~a"
153 label (inexact->exact (round %))
154 (progress-bar % width)))
155 (force-output (current-error-port)))
158 ;; We're done, erase the line.
159 (erase-current-line (current-error-port))
160 (force-output (current-error-port)))
162 ;; Return true to indicate that we should go on.
165 (define (make-default-fetch-options)
166 "Return the default fetch options."
167 (let ((auth-method (%make-auth-ssh-agent)))
168 ;; The #:transfer-progress and #:proxy-url options appeared in Guile-Git
169 ;; 0.4.0. Omit them when using an older version.
170 (catch 'wrong-number-of-args
172 (make-fetch-options auth-method
173 ;; Guile-Git doesn't distinguish between these.
174 #:proxy-url (or (getenv "http_proxy")
175 (getenv "https_proxy"))
177 (and (isatty? (current-error-port))
180 (make-fetch-options auth-method)))))
182 (define (clone* url directory)
183 "Clone git repository at URL into DIRECTORY. Upon failure,
184 make sure no empty directory is left behind."
185 (with-throw-handler #t
191 #:fetch-options (make-default-fetch-options))))
193 (false-if-exception (rmdir directory)))))
195 (define (url+commit->name url sha1)
196 "Return the string \"<REPO-NAME>-<SHA1:7>\" where REPO-NAME is the name of
197 the git repository, extracted from URL and SHA1:7 the seven first digits
200 (string-replace-substring
201 (last (string-split url #\/)) ".git" "")
202 "-" (string-take sha1 7)))
204 (define (resolve-reference repository ref)
205 "Resolve the branch, commit or tag specified by REF, and return the
206 corresponding Git object."
207 (let resolve ((ref ref))
210 (let ((oid (reference-target
211 (branch-lookup repository branch BRANCH-REMOTE))))
212 (object-lookup repository oid)))
214 (let ((oid (reference-name->oid repository symref)))
215 (object-lookup repository oid)))
217 (let ((len (string-length commit)))
218 ;; 'object-lookup-prefix' appeared in Guile-Git in Mar. 2018, so we
219 ;; can't be sure it's available. Furthermore, 'string->oid' used to
220 ;; read out-of-bounds when passed a string shorter than 40 chars,
221 ;; which is why we delay calls to it below.
223 (object-lookup-prefix repository (string->oid commit) len)
224 (object-lookup repository (string->oid commit)))))
225 (('tag-or-commit . str)
226 (if (or (> (string-length str) 40)
227 (not (string-every char-set:hex-digit str)))
228 (resolve `(tag . ,str)) ;definitely a tag
231 (resolve `(tag . ,str)))
233 ;; There's no such tag, so it must be a commit ID.
234 (resolve `(commit . ,str))))))
236 (let ((oid (reference-name->oid repository
237 (string-append "refs/tags/" tag))))
238 ;; OID may point to a "tag" object, but it can also point directly
239 ;; to a "commit" object, as surprising as it may seem. Return that
240 ;; object, whatever that is.
241 (object-lookup repository oid))))))
243 (define (switch-to-ref repository ref)
244 "Switch to REPOSITORY's branch, commit or tag specified by REF. Return the
245 OID (roughly the commit hash) corresponding to REF."
247 (resolve-reference repository ref))
249 (reset repository obj RESET_HARD)
252 (define (call-with-repository directory proc)
253 (let ((repository #f))
256 (set! repository (repository-open directory)))
260 (repository-close! repository)))))
262 (define-syntax-rule (with-repository directory repository exp ...)
263 "Open the repository at DIRECTORY and bind REPOSITORY to it within the
264 dynamic extent of EXP."
265 (call-with-repository directory
266 (lambda (repository) exp ...)))
268 (define (report-git-error error)
269 "Report the given Guile-Git error."
270 ;; Prior to Guile-Git commit b6b2760c2fd6dfaa5c0fedb43eeaff06166b3134,
271 ;; errors would be represented by integers.
273 ((? integer? error) ;old Guile-Git
274 (leave (G_ "Git error ~a~%") error))
275 ((? git-error? error) ;new Guile-Git
276 (leave (G_ "Git error: ~a~%") (git-error-message error)))))
278 (define-syntax-rule (with-git-error-handling body ...)
283 (report-git-error err))))
285 (define* (update-submodules repository
286 #:key (log-port (current-error-port))
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'...~%")
293 (submodule-update submodule
294 #:fetch-options fetch-options)
296 ;; Recurse in SUBMODULE.
297 (let ((directory (string-append
298 (repository-working-directory repository)
299 "/" (submodule-path submodule))))
300 (with-repository directory repository
301 (update-submodules repository
302 #:fetch-options fetch-options
303 #:log-port log-port)))))
304 (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."
311 (lambda (key error . rest)
312 (if (= GIT_ENOTFOUND (git-error-code error))
314 (apply throw key error rest)))))
316 (define (reference-available? repository ref)
317 "Return true if REF, a reference such as '(commit . \"cabba9e\"), is
318 definitely available in REPOSITORY, false otherwise."
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))))))
330 (define cached-checkout-expiration
331 ;; Return the expiration time procedure for a cached checkout.
332 ;; TODO: Honor $GUIX_GIT_CACHE_EXPIRATION.
334 ;; Use the mtime rather than the atime to cope with file systems mounted
336 (file-expiration-time (* 90 24 3600) stat:mtime))
338 (define %checkout-cache-cleanup-period
339 ;; Period for the removal of expired cached checkouts.
342 (define (delete-checkout directory)
343 "Delete DIRECTORY recursively, in an atomic fashion."
344 (let ((trashed (string-append directory ".trashed")))
345 (rename-file directory trashed)
346 (delete-file-recursively trashed)))
348 (define* (update-cached-checkout url
354 (log-port (%make-void-port "w"))
357 url (%repository-cache-directory)
358 #:recursive? recursive?)))
359 "Update the cached checkout of URL to REF in CACHE-DIRECTORY. Return three
360 values: the cache directory name, and the SHA1 commit (a string) corresponding
361 to REF, and the relation of the new commit relative to STARTING-COMMIT (if
362 provided) as returned by 'commit-relation'.
364 REF is pair whose key is [branch | commit | tag | tag-or-commit ] and value
365 the associated data: [<branch name> | <sha1> | <tag name> | <string>].
366 If REF is the empty list, the remote HEAD is used.
368 When RECURSIVE? is true, check out submodules as well, if any.
370 When CHECK-OUT? is true, reset the cached working tree to REF; otherwise leave
372 (define (cache-entries directory)
373 (filter-map (match-lambda
377 (string-append directory "/" file)))
378 (or (scandir directory) '())))
380 (define canonical-ref
381 ;; We used to require callers to specify "origin/" for each branch, which
382 ;; made little sense since the cache should be transparent to them. So
383 ;; here we append "origin/" if it's missing and otherwise keep it.
385 (() '(symref . "refs/remotes/origin/HEAD"))
387 `(branch . ,(if (string-prefix? "origin/" branch)
389 (string-append "origin/" branch))))
393 (let* ((cache-exists? (openable-repository? cache-directory))
394 (repository (if cache-exists?
395 (repository-open cache-directory)
396 (clone* url cache-directory))))
397 ;; Only fetch remote if it has not been cloned just before.
398 (when (and cache-exists?
399 (not (reference-available? repository ref)))
400 (remote-fetch (remote-lookup repository "origin")
401 #:fetch-options (make-default-fetch-options)))
403 (update-submodules repository #:log-port log-port
404 #:fetch-options (make-default-fetch-options)))
406 ;; Note: call 'commit-relation' from here because it's more efficient
407 ;; than letting users re-open the checkout later on.
408 (let* ((oid (if check-out?
409 (switch-to-ref repository canonical-ref)
411 (resolve-reference repository canonical-ref))))
412 (new (and starting-commit
413 (commit-lookup repository oid)))
414 (old (and starting-commit
415 (false-if-git-not-found
416 (commit-lookup repository
417 (string->oid starting-commit)))))
418 (relation (and starting-commit
420 (commit-relation old new)
423 ;; Reclaim file descriptors and memory mappings associated with
424 ;; REPOSITORY as soon as possible.
425 (repository-close! repository)
427 ;; When CACHE-DIRECTORY is a sub-directory of the default cache
428 ;; directory, remove expired checkouts that are next to it.
429 (let ((parent (dirname cache-directory)))
430 (when (string=? parent (%repository-cache-directory))
431 (maybe-remove-expired-cache-entries parent cache-entries
433 cached-checkout-expiration
434 #:delete-entry delete-checkout
436 %checkout-cache-cleanup-period)))
438 (values cache-directory (oid->string oid) relation)))))
440 (define* (latest-repository-commit store url
443 (log-port (%make-void-port "w"))
445 (%repository-cache-directory))
447 "Return two values: the content of the git repository at URL copied into a
448 store directory and the sha1 of the top level commit in this directory. The
449 reference to be checkout, once the repository is fetched, is specified by REF.
450 REF is pair whose key is [branch | commit | tag] and value the associated
451 data, respectively [<branch name> | <sha1> | <tag name>]. If REF is the empty
452 list, the remote HEAD is used.
454 When RECURSIVE? is true, check out submodules as well, if any.
456 Git repositories are kept in the cache directory specified by
457 %repository-cache-directory parameter.
459 Log progress and checkout info to LOG-PORT."
460 (define (dot-git? file stat)
461 (and (string=? (basename file) ".git")
462 (or (eq? 'directory (stat:type stat))
464 ;; Submodule checkouts end up with a '.git' regular file that
465 ;; contains metadata about where their actual '.git' directory
468 (eq? 'regular (stat:type stat))))))
470 (format log-port "updating checkout of '~a'...~%" url)
472 (((checkout commit _)
473 (update-cached-checkout url
474 #:recursive? recursive?
477 (url-cache-directory url cache-directory
480 #:log-port log-port))
482 (url+commit->name url commit)))
483 (format log-port "retrieved commit ~a~%" commit)
484 (values (add-to-store store name #t "sha256" checkout
485 #:select? (negate dot-git?))
488 (define (print-git-error port key args default-printer)
490 (((? git-error? error) . _)
491 (format port (G_ "Git error: ~a~%")
492 (git-error-message error)))))
494 (set-exception-printer! 'git-error print-git-error)
498 ;;; Commit difference.
501 (define* (commit-closure commit #:optional (visited (setq)))
502 "Return the closure of COMMIT as a set. Skip commits contained in VISITED,
503 a set, and adjoin VISITED to the result."
504 (let loop ((commits (list commit))
510 (if (set-contains? visited head)
512 (loop (append (commit-parents head) tail)
513 (set-insert head visited)))))))
515 (define* (commit-difference new old #:optional (excluded '()))
516 "Return the list of commits between NEW and OLD, where OLD is assumed to be
517 an ancestor of NEW. Exclude all the commits listed in EXCLUDED along with
520 Essentially, this computes the set difference between the closure of NEW and
522 (let loop ((commits (list new))
524 (visited (fold commit-closure
526 (cons old excluded))))
531 (if (set-contains? visited head)
532 (loop tail result visited)
533 (loop (append (commit-parents head) tail)
535 (set-insert head visited)))))))
537 (define (commit-relation old new)
538 "Return a symbol denoting the relation between OLD and NEW, two commit
539 objects: 'ancestor (meaning that OLD is an ancestor of NEW), 'descendant, or
540 'unrelated, or 'self (OLD and NEW are the same commit)."
543 (let ((newest (commit-closure new)))
544 (if (set-contains? newest old)
546 (let* ((seen (list->setq (commit-parents new)))
547 (oldest (commit-closure old seen)))
548 (if (set-contains? oldest new)
557 ;; Representation of the "latest" checkout of a branch or a specific commit.
558 (define-record-type* <git-checkout>
559 git-checkout make-git-checkout
561 (url git-checkout-url)
562 (branch git-checkout-branch (default #f))
563 (commit git-checkout-commit (default #f)) ;#f | tag | commit
564 (recursive? git-checkout-recursive? (default #f)))
566 (define* (latest-repository-commit* url #:key ref recursive? log-port)
567 ;; Monadic variant of 'latest-repository-commit'.
569 ;; The caller--e.g., (guix scripts build)--may not handle 'git-error' so
570 ;; translate it into '&message' conditions that we know will be properly
574 (values (latest-repository-commit store url
576 #:recursive? recursive?
579 (lambda (key error . _)
585 (format #f (G_ "cannot fetch commit ~a from ~a: ~a")
586 commit url (git-error-message error)))
588 (format #f (G_ "cannot fetch branch '~a' from ~a: ~a")
589 branch url (git-error-message error)))
591 (format #f (G_ "Git failure while fetching ~a: ~a")
592 url (git-error-message error))))))))))))
594 (define-gexp-compiler (git-checkout-compiler (checkout <git-checkout>)
596 ;; "Compile" CHECKOUT by updating the local checkout and adding it to the
599 (($ <git-checkout> url branch commit recursive?)
600 (latest-repository-commit* url
602 `(tag-or-commit . ,commit))
606 #:recursive? recursive?
607 #:log-port (current-error-port)))))
610 ;; eval: (put 'with-repository 'scheme-indent-function 2)