1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2017, 2020 Mathieu Othacehe <m.othacehe@gmail.com>
3 ;;; Copyright © 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
5 ;;; This file is part of GNU Guix.
7 ;;; GNU Guix is free software; you can redistribute it and/or modify it
8 ;;; under the terms of the GNU General Public License as published by
9 ;;; the Free Software Foundation; either version 3 of the License, or (at
10 ;;; your option) any later version.
12 ;;; GNU Guix is distributed in the hope that it will be useful, but
13 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;;; GNU General Public License for more details.
17 ;;; You should have received a copy of the GNU General Public License
18 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
20 (define-module (guix git)
22 #:use-module (git object)
23 #:use-module (guix i18n)
24 #:use-module (guix base32)
25 #:use-module (gcrypt hash)
26 #:use-module ((guix build utils) #:select (mkdir-p))
27 #:use-module (guix store)
28 #:use-module (guix utils)
29 #:use-module (guix records)
30 #:use-module (guix gexp)
31 #:use-module (guix sets)
32 #:use-module ((guix diagnostics) #:select (leave))
33 #:use-module (rnrs bytevectors)
34 #:use-module (ice-9 match)
35 #:use-module (srfi srfi-1)
36 #:use-module (srfi srfi-11)
37 #:use-module (srfi srfi-34)
38 #:use-module (srfi srfi-35)
39 #:export (%repository-cache-directory
40 honor-system-x509-certificates!
44 with-git-error-handling
45 false-if-git-not-found
46 update-cached-checkout
48 latest-repository-commit
57 git-checkout-recursive?))
59 (define %repository-cache-directory
60 (make-parameter (string-append (cache-directory #:ensure? #f)
63 (define (honor-system-x509-certificates!)
64 "Use the system's X.509 certificates for Git checkouts over HTTPS. Honor
65 the 'SSL_CERT_FILE' and 'SSL_CERT_DIR' environment variables."
66 ;; On distros such as CentOS 7, /etc/ssl/certs contains only a couple of
67 ;; files (instead of all the certificates) among which "ca-bundle.crt". On
68 ;; other distros /etc/ssl/certs usually contains the whole set of
69 ;; certificates along with "ca-certificates.crt". Try to choose the right
71 (let ((file (letrec-syntax ((choose
75 (if (and f (file-exists? f))
80 (choose (getenv "SSL_CERT_FILE")
81 "/etc/ssl/certs/ca-certificates.crt"
82 "/etc/ssl/certs/ca-bundle.crt")))
83 (directory (or (getenv "SSL_CERT_DIR") "/etc/ssl/certs")))
85 (and=> (stat directory #f)
87 (> (stat:nlink st) 2))))
89 (set-tls-certificate-locations! directory file)
92 (define %certificates-initialized?
93 ;; Whether 'honor-system-x509-certificates!' has already been called.
96 (define-syntax-rule (with-libgit2 thunk ...)
98 ;; XXX: The right thing to do would be to call (libgit2-shutdown) here,
99 ;; but pointer finalizers used in guile-git may be called after shutdown,
100 ;; resulting in a segfault. Hence, let's skip shutdown call for now.
102 (unless %certificates-initialized?
103 (honor-system-x509-certificates!)
104 (set! %certificates-initialized? #t))
107 (define* (url-cache-directory url
108 #:optional (cache-directory
109 (%repository-cache-directory))
111 "Return the directory associated to URL in %repository-cache-directory."
114 (bytevector->base32-string
115 (sha256 (string->utf8 (if recursive?
116 (string-append "R:" url)
119 ;; Authentication appeared in Guile-Git 0.3.0, check if it is available.
120 (define auth-supported?
121 (false-if-exception (resolve-interface '(git auth))))
123 (define (clone* url directory)
124 "Clone git repository at URL into DIRECTORY. Upon failure,
125 make sure no empty directory is left behind."
126 (with-throw-handler #t
130 ;; Note: Explicitly pass options to work around the invalid default
131 ;; value in Guile-Git: <https://bugs.gnu.org/29238>.
132 (if (module-defined? (resolve-interface '(git))
134 (let ((auth-method (and auth-supported?
135 (%make-auth-ssh-agent))))
139 #:fetch-options (make-fetch-options auth-method))
140 (clone-init-options))))
141 (clone url directory)))
143 (false-if-exception (rmdir directory)))))
145 (define (url+commit->name url sha1)
146 "Return the string \"<REPO-NAME>-<SHA1:7>\" where REPO-NAME is the name of
147 the git repository, extracted from URL and SHA1:7 the seven first digits
150 (string-replace-substring
151 (last (string-split url #\/)) ".git" "")
152 "-" (string-take sha1 7)))
154 (define (resolve-reference repository ref)
155 "Resolve the branch, commit or tag specified by REF, and return the
156 corresponding Git object."
157 (let resolve ((ref ref))
160 (let ((oid (reference-target
161 (branch-lookup repository branch BRANCH-REMOTE))))
162 (object-lookup repository oid)))
164 (let ((len (string-length commit)))
165 ;; 'object-lookup-prefix' appeared in Guile-Git in Mar. 2018, so we
166 ;; can't be sure it's available. Furthermore, 'string->oid' used to
167 ;; read out-of-bounds when passed a string shorter than 40 chars,
168 ;; which is why we delay calls to it below.
170 (if (module-defined? (resolve-interface '(git object))
171 'object-lookup-prefix)
172 (object-lookup-prefix repository (string->oid commit) len)
175 (message "long Git object ID is required")))))
176 (object-lookup repository (string->oid commit)))))
177 (('tag-or-commit . str)
178 (if (or (> (string-length str) 40)
179 (not (string-every char-set:hex-digit str)))
180 (resolve `(tag . ,str)) ;definitely a tag
183 (resolve `(tag . ,str)))
185 ;; There's no such tag, so it must be a commit ID.
186 (resolve `(commit . ,str))))))
188 (let ((oid (reference-name->oid repository
189 (string-append "refs/tags/" tag))))
190 ;; OID may point to a "tag" object, but it can also point directly
191 ;; to a "commit" object, as surprising as it may seem. Return that
192 ;; object, whatever that is.
193 (object-lookup repository oid))))))
195 (define (switch-to-ref repository ref)
196 "Switch to REPOSITORY's branch, commit or tag specified by REF. Return the
197 OID (roughly the commit hash) corresponding to REF."
199 (resolve-reference repository ref))
201 (reset repository obj RESET_HARD)
204 (define (call-with-repository directory proc)
205 (let ((repository #f))
208 (set! repository (repository-open directory)))
212 (repository-close! repository)))))
214 (define-syntax-rule (with-repository directory repository exp ...)
215 "Open the repository at DIRECTORY and bind REPOSITORY to it within the
216 dynamic extent of EXP."
217 (call-with-repository directory
218 (lambda (repository) exp ...)))
220 (define (report-git-error error)
221 "Report the given Guile-Git error."
222 ;; Prior to Guile-Git commit b6b2760c2fd6dfaa5c0fedb43eeaff06166b3134,
223 ;; errors would be represented by integers.
225 ((? integer? error) ;old Guile-Git
226 (leave (G_ "Git error ~a~%") error))
227 ((? git-error? error) ;new Guile-Git
228 (leave (G_ "Git error: ~a~%") (git-error-message error)))))
230 (define-syntax-rule (with-git-error-handling body ...)
235 (report-git-error err))))
237 (define (load-git-submodules)
238 "Attempt to load (git submodules), which was missing until Guile-Git 0.2.0.
239 Return true on success, false on failure."
240 (match (false-if-exception (resolve-interface '(git submodule)))
242 (set! load-git-submodules (const #f))
245 (module-use! (resolve-module '(guix git)) iface)
246 (set! load-git-submodules (const #t))
249 (define* (update-submodules repository
250 #:key (log-port (current-error-port)))
251 "Update the submodules of REPOSITORY, a Git repository object."
252 ;; Guile-Git < 0.2.0 did not have (git submodule).
253 (if (load-git-submodules)
254 (for-each (lambda (name)
255 (let ((submodule (submodule-lookup repository name)))
256 (format log-port (G_ "updating submodule '~a'...~%")
258 (submodule-update submodule)
260 ;; Recurse in SUBMODULE.
261 (let ((directory (string-append
262 (repository-working-directory repository)
263 "/" (submodule-path submodule))))
264 (with-repository directory repository
265 (update-submodules repository
266 #:log-port log-port)))))
267 (repository-submodules repository))
268 (format (current-error-port)
269 (G_ "Support for submodules is missing; \
270 please upgrade Guile-Git.~%"))))
272 (define-syntax-rule (false-if-git-not-found exp)
273 "Evaluate EXP, returning #false if a GIT_ENOTFOUND error is raised."
277 (lambda (key error . rest)
278 (if (= GIT_ENOTFOUND (git-error-code error))
280 (apply throw key error rest)))))
282 (define (reference-available? repository ref)
283 "Return true if REF, a reference such as '(commit . \"cabba9e\"), is
284 definitely available in REPOSITORY, false otherwise."
287 (false-if-git-not-found
288 (->bool (commit-lookup repository (string->oid commit)))))
292 (define* (update-cached-checkout url
294 (ref '(branch . "master"))
298 (log-port (%make-void-port "w"))
301 url (%repository-cache-directory)
302 #:recursive? recursive?)))
303 "Update the cached checkout of URL to REF in CACHE-DIRECTORY. Return three
304 values: the cache directory name, and the SHA1 commit (a string) corresponding
305 to REF, and the relation of the new commit relative to STARTING-COMMIT (if
306 provided) as returned by 'commit-relation'.
308 REF is pair whose key is [branch | commit | tag | tag-or-commit ] and value
309 the associated data: [<branch name> | <sha1> | <tag name> | <string>].
311 When RECURSIVE? is true, check out submodules as well, if any.
313 When CHECK-OUT? is true, reset the cached working tree to REF; otherwise leave
315 (define canonical-ref
316 ;; We used to require callers to specify "origin/" for each branch, which
317 ;; made little sense since the cache should be transparent to them. So
318 ;; here we append "origin/" if it's missing and otherwise keep it.
321 `(branch . ,(if (string-prefix? "origin/" branch)
323 (string-append "origin/" branch))))
327 (let* ((cache-exists? (openable-repository? cache-directory))
328 (repository (if cache-exists?
329 (repository-open cache-directory)
330 (clone* url cache-directory))))
331 ;; Only fetch remote if it has not been cloned just before.
332 (when (and cache-exists?
333 (not (reference-available? repository ref)))
335 (let ((auth-method (and auth-supported?
336 (%make-auth-ssh-agent))))
337 (remote-fetch (remote-lookup repository "origin")
338 #:fetch-options (make-fetch-options auth-method)))
339 (remote-fetch (remote-lookup repository "origin"))))
341 (update-submodules repository #:log-port log-port))
343 ;; Note: call 'commit-relation' from here because it's more efficient
344 ;; than letting users re-open the checkout later on.
345 (let* ((oid (if check-out?
346 (switch-to-ref repository canonical-ref)
348 (resolve-reference repository canonical-ref))))
349 (new (and starting-commit
350 (commit-lookup repository oid)))
351 (old (and starting-commit
352 (false-if-git-not-found
353 (commit-lookup repository
354 (string->oid starting-commit)))))
355 (relation (and starting-commit
357 (commit-relation old new)
360 ;; Reclaim file descriptors and memory mappings associated with
361 ;; REPOSITORY as soon as possible.
362 (when (module-defined? (resolve-interface '(git repository))
364 (repository-close! repository))
366 (values cache-directory (oid->string oid) relation)))))
368 (define* (latest-repository-commit store url
371 (log-port (%make-void-port "w"))
373 (%repository-cache-directory))
374 (ref '(branch . "master")))
375 "Return two values: the content of the git repository at URL copied into a
376 store directory and the sha1 of the top level commit in this directory. The
377 reference to be checkout, once the repository is fetched, is specified by REF.
378 REF is pair whose key is [branch | commit | tag] and value the associated
379 data, respectively [<branch name> | <sha1> | <tag name>].
381 When RECURSIVE? is true, check out submodules as well, if any.
383 Git repositories are kept in the cache directory specified by
384 %repository-cache-directory parameter.
386 Log progress and checkout info to LOG-PORT."
387 (define (dot-git? file stat)
388 (and (string=? (basename file) ".git")
389 (or (eq? 'directory (stat:type stat))
391 ;; Submodule checkouts end up with a '.git' regular file that
392 ;; contains metadata about where their actual '.git' directory
395 (eq? 'regular (stat:type stat))))))
397 (format log-port "updating checkout of '~a'...~%" url)
399 (((checkout commit _)
400 (update-cached-checkout url
401 #:recursive? recursive?
404 (url-cache-directory url cache-directory
407 #:log-port log-port))
409 (url+commit->name url commit)))
410 (format log-port "retrieved commit ~a~%" commit)
411 (values (add-to-store store name #t "sha256" checkout
412 #:select? (negate dot-git?))
415 (define (print-git-error port key args default-printer)
417 (((? git-error? error) . _)
418 (format port (G_ "Git error: ~a~%")
419 (git-error-message error)))))
421 (set-exception-printer! 'git-error print-git-error)
425 ;;; Commit difference.
428 (define* (commit-closure commit #:optional (visited (setq)))
429 "Return the closure of COMMIT as a set. Skip commits contained in VISITED,
430 a set, and adjoin VISITED to the result."
431 (let loop ((commits (list commit))
437 (if (set-contains? visited head)
439 (loop (append (commit-parents head) tail)
440 (set-insert head visited)))))))
442 (define* (commit-difference new old #:optional (excluded '()))
443 "Return the list of commits between NEW and OLD, where OLD is assumed to be
444 an ancestor of NEW. Exclude all the commits listed in EXCLUDED along with
447 Essentially, this computes the set difference between the closure of NEW and
449 (let loop ((commits (list new))
451 (visited (fold commit-closure
453 (cons old excluded))))
458 (if (set-contains? visited head)
459 (loop tail result visited)
460 (loop (append (commit-parents head) tail)
462 (set-insert head visited)))))))
464 (define (commit-relation old new)
465 "Return a symbol denoting the relation between OLD and NEW, two commit
466 objects: 'ancestor (meaning that OLD is an ancestor of NEW), 'descendant, or
467 'unrelated, or 'self (OLD and NEW are the same commit)."
470 (let ((newest (commit-closure new)))
471 (if (set-contains? newest old)
473 (let* ((seen (list->setq (commit-parents new)))
474 (oldest (commit-closure old seen)))
475 (if (set-contains? oldest new)
484 ;; Representation of the "latest" checkout of a branch or a specific commit.
485 (define-record-type* <git-checkout>
486 git-checkout make-git-checkout
488 (url git-checkout-url)
489 (branch git-checkout-branch (default "master"))
490 (commit git-checkout-commit (default #f)) ;#f | tag | commit
491 (recursive? git-checkout-recursive? (default #f)))
493 (define* (latest-repository-commit* url #:key ref recursive? log-port)
494 ;; Monadic variant of 'latest-repository-commit'.
496 ;; The caller--e.g., (guix scripts build)--may not handle 'git-error' so
497 ;; translate it into '&message' conditions that we know will be properly
501 (values (latest-repository-commit store url
503 #:recursive? recursive?
506 (lambda (key error . _)
512 (format #f (G_ "cannot fetch commit ~a from ~a: ~a")
513 commit url (git-error-message error)))
515 (format #f (G_ "cannot fetch branch '~a' from ~a: ~a")
516 branch url (git-error-message error)))
518 (format #f (G_ "Git failure while fetching ~a: ~a")
519 url (git-error-message error))))))))))))
521 (define-gexp-compiler (git-checkout-compiler (checkout <git-checkout>)
523 ;; "Compile" CHECKOUT by updating the local checkout and adding it to the
526 (($ <git-checkout> url branch commit recursive?)
527 (latest-repository-commit* url
529 `(tag-or-commit . ,commit)
531 #:recursive? recursive?
532 #:log-port (current-error-port)))))
535 ;; eval: (put 'with-repository 'scheme-indent-function 2)