Add 'guix git authenticate'.
[jackhill/guix/guix.git] / guix / git.scm
CommitLineData
6b7b3ca9 1;;; GNU Guix --- Functional package management for GNU
c3574749 2;;; Copyright © 2017, 2020 Mathieu Othacehe <m.othacehe@gmail.com>
6a7c4636 3;;; Copyright © 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
6b7b3ca9
MO
4;;;
5;;; This file is part of GNU Guix.
6;;;
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.
11;;;
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.
16;;;
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/>.
19
20(define-module (guix git)
21 #:use-module (git)
22 #:use-module (git object)
a3d77c51 23 #:use-module (guix i18n)
6b7b3ca9 24 #:use-module (guix base32)
ca719424 25 #:use-module (gcrypt hash)
0ad5f809 26 #:use-module ((guix build utils) #:select (mkdir-p))
6b7b3ca9
MO
27 #:use-module (guix store)
28 #:use-module (guix utils)
49ae3f6d
LC
29 #:use-module (guix records)
30 #:use-module (guix gexp)
873f6f13 31 #:use-module (guix sets)
69db2993 32 #:use-module ((guix diagnostics) #:select (leave))
6b7b3ca9
MO
33 #:use-module (rnrs bytevectors)
34 #:use-module (ice-9 match)
35 #:use-module (srfi srfi-1)
91881986 36 #:use-module (srfi srfi-11)
95bd9f65
LC
37 #:use-module (srfi srfi-34)
38 #:use-module (srfi srfi-35)
6b7b3ca9 39 #:export (%repository-cache-directory
bc041b3e
LC
40 honor-system-x509-certificates!
41
873f6f13 42 with-repository
69db2993 43 with-git-error-handling
e7827560 44 false-if-git-not-found
91881986 45 update-cached-checkout
053b10c3 46 url+commit->name
49ae3f6d 47 latest-repository-commit
873f6f13 48 commit-difference
c098c11b 49 commit-relation
49ae3f6d
LC
50
51 git-checkout
52 git-checkout?
53 git-checkout-url
a063bac6
LC
54 git-checkout-branch
55 git-checkout-commit
56 git-checkout-recursive?))
6b7b3ca9
MO
57
58(define %repository-cache-directory
e83b2b0f
LC
59 (make-parameter (string-append (cache-directory #:ensure? #f)
60 "/checkouts")))
6b7b3ca9 61
bc041b3e
LC
62(define (honor-system-x509-certificates!)
63 "Use the system's X.509 certificates for Git checkouts over HTTPS. Honor
64the 'SSL_CERT_FILE' and 'SSL_CERT_DIR' environment variables."
65 ;; On distros such as CentOS 7, /etc/ssl/certs contains only a couple of
66 ;; files (instead of all the certificates) among which "ca-bundle.crt". On
67 ;; other distros /etc/ssl/certs usually contains the whole set of
68 ;; certificates along with "ca-certificates.crt". Try to choose the right
69 ;; one.
70 (let ((file (letrec-syntax ((choose
71 (syntax-rules ()
72 ((_ file rest ...)
73 (let ((f file))
74 (if (and f (file-exists? f))
75 f
76 (choose rest ...))))
77 ((_)
78 #f))))
79 (choose (getenv "SSL_CERT_FILE")
80 "/etc/ssl/certs/ca-certificates.crt"
81 "/etc/ssl/certs/ca-bundle.crt")))
82 (directory (or (getenv "SSL_CERT_DIR") "/etc/ssl/certs")))
83 (and (or file
84 (and=> (stat directory #f)
85 (lambda (st)
86 (> (stat:nlink st) 2))))
87 (begin
88 (set-tls-certificate-locations! directory file)
89 #t))))
90
91(define %certificates-initialized?
92 ;; Whether 'honor-system-x509-certificates!' has already been called.
93 #f)
94
6b7b3ca9 95(define-syntax-rule (with-libgit2 thunk ...)
b02469d2
MO
96 (begin
97 ;; XXX: The right thing to do would be to call (libgit2-shutdown) here,
98 ;; but pointer finalizers used in guile-git may be called after shutdown,
99 ;; resulting in a segfault. Hence, let's skip shutdown call for now.
100 (libgit2-init!)
bc041b3e
LC
101 (unless %certificates-initialized?
102 (honor-system-x509-certificates!)
103 (set! %certificates-initialized? #t))
b02469d2 104 thunk ...))
6b7b3ca9
MO
105
106(define* (url-cache-directory url
107 #:optional (cache-directory
60cbc6a8
LC
108 (%repository-cache-directory))
109 #:key recursive?)
6b7b3ca9
MO
110 "Return the directory associated to URL in %repository-cache-directory."
111 (string-append
112 cache-directory "/"
60cbc6a8
LC
113 (bytevector->base32-string
114 (sha256 (string->utf8 (if recursive?
115 (string-append "R:" url)
116 url))))))
6b7b3ca9 117
c3574749
MO
118;; Authentication appeared in Guile-Git 0.3.0, check if it is available.
119(define auth-supported?
120 (false-if-exception (resolve-interface '(git auth))))
121
6b7b3ca9
MO
122(define (clone* url directory)
123 "Clone git repository at URL into DIRECTORY. Upon failure,
124make sure no empty directory is left behind."
125 (with-throw-handler #t
126 (lambda ()
127 (mkdir-p directory)
195f0d05
LC
128
129 ;; Note: Explicitly pass options to work around the invalid default
130 ;; value in Guile-Git: <https://bugs.gnu.org/29238>.
b1488c76
LC
131 (if (module-defined? (resolve-interface '(git))
132 'clone-init-options)
c3574749
MO
133 (let ((auth-method (and auth-supported?
134 (%make-auth-ssh-agent))))
135 (clone url directory
136 (if auth-supported?
137 (make-clone-options
138 #:fetch-options (make-fetch-options auth-method))
139 (clone-init-options))))
b1488c76 140 (clone url directory)))
6b7b3ca9
MO
141 (lambda _
142 (false-if-exception (rmdir directory)))))
143
6b7b3ca9
MO
144(define (url+commit->name url sha1)
145 "Return the string \"<REPO-NAME>-<SHA1:7>\" where REPO-NAME is the name of
146the git repository, extracted from URL and SHA1:7 the seven first digits
147of SHA1 string."
148 (string-append
149 (string-replace-substring
150 (last (string-split url #\/)) ".git" "")
151 "-" (string-take sha1 7)))
152
6b7b3ca9 153(define (switch-to-ref repository ref)
91881986
LC
154 "Switch to REPOSITORY's branch, commit or tag specified by REF. Return the
155OID (roughly the commit hash) corresponding to REF."
95bd9f65 156 (define obj
c4c2449f
LC
157 (let resolve ((ref ref))
158 (match ref
159 (('branch . branch)
160 (let ((oid (reference-target
161 (branch-lookup repository branch BRANCH-REMOTE))))
162 (object-lookup repository oid)))
163 (('commit . commit)
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.
169 (if (< len 40)
170 (if (module-defined? (resolve-interface '(git object))
171 'object-lookup-prefix)
172 (object-lookup-prefix repository (string->oid commit) len)
173 (raise (condition
174 (&message
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
181 (catch 'git-error
182 (lambda ()
183 (resolve `(tag . ,str)))
184 (lambda _
185 ;; There's no such tag, so it must be a commit ID.
186 (resolve `(commit . ,str))))))
187 (('tag . tag)
188 (let ((oid (reference-name->oid repository
189 (string-append "refs/tags/" tag))))
efa578ec
LC
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))))))
95bd9f65 194
91881986
LC
195 (reset repository obj RESET_HARD)
196 (object-id obj))
197
60cbc6a8
LC
198(define (call-with-repository directory proc)
199 (let ((repository #f))
200 (dynamic-wind
201 (lambda ()
202 (set! repository (repository-open directory)))
203 (lambda ()
204 (proc repository))
205 (lambda ()
206 (repository-close! repository)))))
207
208(define-syntax-rule (with-repository directory repository exp ...)
209 "Open the repository at DIRECTORY and bind REPOSITORY to it within the
210dynamic extent of EXP."
211 (call-with-repository directory
212 (lambda (repository) exp ...)))
213
69db2993
LC
214(define (report-git-error error)
215 "Report the given Guile-Git error."
216 ;; Prior to Guile-Git commit b6b2760c2fd6dfaa5c0fedb43eeaff06166b3134,
217 ;; errors would be represented by integers.
218 (match error
219 ((? integer? error) ;old Guile-Git
220 (leave (G_ "Git error ~a~%") error))
221 ((? git-error? error) ;new Guile-Git
222 (leave (G_ "Git error: ~a~%") (git-error-message error)))))
223
224(define-syntax-rule (with-git-error-handling body ...)
225 (catch 'git-error
226 (lambda ()
227 body ...)
228 (lambda (key err)
229 (report-git-error err))))
230
6a7c4636
LC
231(define (load-git-submodules)
232 "Attempt to load (git submodules), which was missing until Guile-Git 0.2.0.
233Return true on success, false on failure."
234 (match (false-if-exception (resolve-interface '(git submodule)))
235 (#f
236 (set! load-git-submodules (const #f))
237 #f)
238 (iface
058d0251 239 (module-use! (resolve-module '(guix git)) iface)
6a7c4636
LC
240 (set! load-git-submodules (const #t))
241 #t)))
242
60cbc6a8
LC
243(define* (update-submodules repository
244 #:key (log-port (current-error-port)))
245 "Update the submodules of REPOSITORY, a Git repository object."
246 ;; Guile-Git < 0.2.0 did not have (git submodule).
6a7c4636 247 (if (load-git-submodules)
60cbc6a8
LC
248 (for-each (lambda (name)
249 (let ((submodule (submodule-lookup repository name)))
250 (format log-port (G_ "updating submodule '~a'...~%")
251 name)
252 (submodule-update submodule)
253
254 ;; Recurse in SUBMODULE.
255 (let ((directory (string-append
256 (repository-working-directory repository)
257 "/" (submodule-path submodule))))
258 (with-repository directory repository
259 (update-submodules repository
260 #:log-port log-port)))))
261 (repository-submodules repository))
262 (format (current-error-port)
263 (G_ "Support for submodules is missing; \
264please upgrade Guile-Git.~%"))))
265
1fd7de45
LC
266(define-syntax-rule (false-if-git-not-found exp)
267 "Evaluate EXP, returning #false if a GIT_ENOTFOUND error is raised."
268 (catch 'git-error
269 (lambda ()
270 exp)
271 (lambda (key error . rest)
272 (if (= GIT_ENOTFOUND (git-error-code error))
273 #f
274 (apply throw key error rest)))))
275
a78dcb3d
LC
276(define (reference-available? repository ref)
277 "Return true if REF, a reference such as '(commit . \"cabba9e\"), is
278definitely available in REPOSITORY, false otherwise."
279 (match ref
280 (('commit . commit)
1fd7de45
LC
281 (false-if-git-not-found
282 (->bool (commit-lookup repository (string->oid commit)))))
a78dcb3d
LC
283 (_
284 #f)))
285
91881986
LC
286(define* (update-cached-checkout url
287 #:key
37a6cdbf 288 (ref '(branch . "master"))
60cbc6a8 289 recursive?
8d1d5657 290 starting-commit
60cbc6a8 291 (log-port (%make-void-port "w"))
91881986 292 (cache-directory
ffc3fcad 293 (url-cache-directory
60cbc6a8
LC
294 url (%repository-cache-directory)
295 #:recursive? recursive?)))
8d1d5657 296 "Update the cached checkout of URL to REF in CACHE-DIRECTORY. Return three
91881986 297values: the cache directory name, and the SHA1 commit (a string) corresponding
8d1d5657
LC
298to REF, and the relation of the new commit relative to STARTING-COMMIT (if
299provided) as returned by 'commit-relation'.
91881986 300
c4c2449f
LC
301REF is pair whose key is [branch | commit | tag | tag-or-commit ] and value
302the associated data: [<branch name> | <sha1> | <tag name> | <string>].
60cbc6a8
LC
303
304When RECURSIVE? is true, check out submodules as well, if any."
37a6cdbf
LC
305 (define canonical-ref
306 ;; We used to require callers to specify "origin/" for each branch, which
307 ;; made little sense since the cache should be transparent to them. So
308 ;; here we append "origin/" if it's missing and otherwise keep it.
309 (match ref
310 (('branch . branch)
311 `(branch . ,(if (string-prefix? "origin/" branch)
312 branch
313 (string-append "origin/" branch))))
314 (_ ref)))
315
91881986 316 (with-libgit2
ffc3fcad 317 (let* ((cache-exists? (openable-repository? cache-directory))
91881986 318 (repository (if cache-exists?
e3e1a7ba 319 (repository-open cache-directory)
ffc3fcad 320 (clone* url cache-directory))))
91881986 321 ;; Only fetch remote if it has not been cloned just before.
a78dcb3d
LC
322 (when (and cache-exists?
323 (not (reference-available? repository ref)))
c3574749
MO
324 (if auth-supported?
325 (let ((auth-method (and auth-supported?
326 (%make-auth-ssh-agent))))
327 (remote-fetch (remote-lookup repository "origin")
328 #:fetch-options (make-fetch-options auth-method)))
329 (remote-fetch (remote-lookup repository "origin"))))
60cbc6a8
LC
330 (when recursive?
331 (update-submodules repository #:log-port log-port))
8d1d5657
LC
332
333 ;; Note: call 'commit-relation' from here because it's more efficient
334 ;; than letting users re-open the checkout later on.
335 (let* ((oid (switch-to-ref repository canonical-ref))
336 (new (and starting-commit
337 (commit-lookup repository oid)))
338 (old (and starting-commit
1fd7de45
LC
339 (false-if-git-not-found
340 (commit-lookup repository
341 (string->oid starting-commit)))))
8d1d5657 342 (relation (and starting-commit
1fd7de45
LC
343 (if old
344 (commit-relation old new)
345 'unrelated))))
91881986
LC
346
347 ;; Reclaim file descriptors and memory mappings associated with
348 ;; REPOSITORY as soon as possible.
349 (when (module-defined? (resolve-interface '(git repository))
350 'repository-close!)
351 (repository-close! repository))
352
8d1d5657 353 (values cache-directory (oid->string oid) relation)))))
6b7b3ca9
MO
354
355(define* (latest-repository-commit store url
356 #:key
60cbc6a8 357 recursive?
35cb37ea 358 (log-port (%make-void-port "w"))
6b7b3ca9
MO
359 (cache-directory
360 (%repository-cache-directory))
37a6cdbf 361 (ref '(branch . "master")))
6b7b3ca9
MO
362 "Return two values: the content of the git repository at URL copied into a
363store directory and the sha1 of the top level commit in this directory. The
364reference to be checkout, once the repository is fetched, is specified by REF.
365REF is pair whose key is [branch | commit | tag] and value the associated
366data, respectively [<branch name> | <sha1> | <tag name>].
367
60cbc6a8
LC
368When RECURSIVE? is true, check out submodules as well, if any.
369
6b7b3ca9 370Git repositories are kept in the cache directory specified by
35cb37ea
LC
371%repository-cache-directory parameter.
372
373Log progress and checkout info to LOG-PORT."
91881986
LC
374 (define (dot-git? file stat)
375 (and (string=? (basename file) ".git")
60cbc6a8
LC
376 (or (eq? 'directory (stat:type stat))
377
378 ;; Submodule checkouts end up with a '.git' regular file that
379 ;; contains metadata about where their actual '.git' directory
380 ;; lives.
381 (and recursive?
382 (eq? 'regular (stat:type stat))))))
dfca2418 383
35cb37ea 384 (format log-port "updating checkout of '~a'...~%" url)
ffc3fcad 385 (let*-values
8d1d5657 386 (((checkout commit _)
ffc3fcad 387 (update-cached-checkout url
60cbc6a8 388 #:recursive? recursive?
ffc3fcad
OP
389 #:ref ref
390 #:cache-directory
60cbc6a8
LC
391 (url-cache-directory url cache-directory
392 #:recursive?
393 recursive?)
394 #:log-port log-port))
ffc3fcad
OP
395 ((name)
396 (url+commit->name url commit)))
35cb37ea 397 (format log-port "retrieved commit ~a~%" commit)
91881986
LC
398 (values (add-to-store store name #t "sha256" checkout
399 #:select? (negate dot-git?))
400 commit)))
49ae3f6d 401
1d8b10d0
LC
402(define (print-git-error port key args default-printer)
403 (match args
404 (((? git-error? error) . _)
405 (format port (G_ "Git error: ~a~%")
406 (git-error-message error)))))
407
408(set-exception-printer! 'git-error print-git-error)
409
49ae3f6d 410\f
873f6f13
LC
411;;;
412;;; Commit difference.
413;;;
414
785af04a
LC
415(define* (commit-closure commit #:optional (visited (setq)))
416 "Return the closure of COMMIT as a set. Skip commits contained in VISITED,
417a set, and adjoin VISITED to the result."
873f6f13 418 (let loop ((commits (list commit))
785af04a 419 (visited visited))
873f6f13
LC
420 (match commits
421 (()
422 visited)
423 ((head . tail)
424 (if (set-contains? visited head)
425 (loop tail visited)
426 (loop (append (commit-parents head) tail)
427 (set-insert head visited)))))))
428
785af04a 429(define* (commit-difference new old #:optional (excluded '()))
873f6f13 430 "Return the list of commits between NEW and OLD, where OLD is assumed to be
785af04a
LC
431an ancestor of NEW. Exclude all the commits listed in EXCLUDED along with
432their ancestors.
873f6f13
LC
433
434Essentially, this computes the set difference between the closure of NEW and
435that of OLD."
436 (let loop ((commits (list new))
437 (result '())
72357e21
LC
438 (visited (fold commit-closure
439 (setq)
440 (cons old excluded))))
873f6f13
LC
441 (match commits
442 (()
443 (reverse result))
444 ((head . tail)
445 (if (set-contains? visited head)
446 (loop tail result visited)
447 (loop (append (commit-parents head) tail)
448 (cons head result)
449 (set-insert head visited)))))))
450
c098c11b
LC
451(define (commit-relation old new)
452 "Return a symbol denoting the relation between OLD and NEW, two commit
453objects: 'ancestor (meaning that OLD is an ancestor of NEW), 'descendant, or
454'unrelated, or 'self (OLD and NEW are the same commit)."
455 (if (eq? old new)
456 'self
457 (let ((newest (commit-closure new)))
458 (if (set-contains? newest old)
459 'ancestor
460 (let* ((seen (list->setq (commit-parents new)))
461 (oldest (commit-closure old seen)))
462 (if (set-contains? oldest new)
463 'descendant
464 'unrelated))))))
465
873f6f13 466\f
49ae3f6d
LC
467;;;
468;;; Checkouts.
469;;;
470
b18f7234 471;; Representation of the "latest" checkout of a branch or a specific commit.
49ae3f6d
LC
472(define-record-type* <git-checkout>
473 git-checkout make-git-checkout
474 git-checkout?
475 (url git-checkout-url)
b18f7234 476 (branch git-checkout-branch (default "master"))
177fecb5 477 (commit git-checkout-commit (default #f)) ;#f | tag | commit
06fff484 478 (recursive? git-checkout-recursive? (default #f)))
49ae3f6d 479
06fff484 480(define* (latest-repository-commit* url #:key ref recursive? log-port)
a3d77c51
LC
481 ;; Monadic variant of 'latest-repository-commit'.
482 (lambda (store)
483 ;; The caller--e.g., (guix scripts build)--may not handle 'git-error' so
484 ;; translate it into '&message' conditions that we know will be properly
485 ;; handled.
486 (catch 'git-error
487 (lambda ()
488 (values (latest-repository-commit store url
06fff484
LC
489 #:ref ref
490 #:recursive? recursive?
491 #:log-port log-port)
a3d77c51
LC
492 store))
493 (lambda (key error . _)
494 (raise (condition
495 (&message
496 (message
497 (match ref
498 (('commit . commit)
499 (format #f (G_ "cannot fetch commit ~a from ~a: ~a")
500 commit url (git-error-message error)))
501 (('branch . branch)
502 (format #f (G_ "cannot fetch branch '~a' from ~a: ~a")
503 branch url (git-error-message error)))
504 (_
505 (format #f (G_ "Git failure while fetching ~a: ~a")
506 url (git-error-message error))))))))))))
49ae3f6d
LC
507
508(define-gexp-compiler (git-checkout-compiler (checkout <git-checkout>)
509 system target)
510 ;; "Compile" CHECKOUT by updating the local checkout and adding it to the
511 ;; store.
512 (match checkout
06fff484 513 (($ <git-checkout> url branch commit recursive?)
49ae3f6d 514 (latest-repository-commit* url
b18f7234 515 #:ref (if commit
177fecb5 516 `(tag-or-commit . ,commit)
b18f7234 517 `(branch . ,branch))
06fff484 518 #:recursive? recursive?
49ae3f6d 519 #:log-port (current-error-port)))))
60cbc6a8
LC
520
521;; Local Variables:
522;; eval: (put 'with-repository 'scheme-indent-function 2)
523;; End: