git.scm 21 KB

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