zilch/lang/go/src/sum.sld

64 lines
2.8 KiB
Scheme

;; Parses `go.sum` files.
(define-library (zilch lang go sum)
(import
(scheme base) (scheme write) (scheme read) (scheme file) (scheme process-context) (scheme lazy) (scheme case-lambda)
(chicken file)
(zilch magic) (zilch file) (zilch zexpr)
(zilch nix drv) (zilch nix path) (zilch nixpkgs)
(json)
(chicken base) (chicken format) (chicken foreign)
(scheme char)
(srfi 4) (srfi 128) (srfi 146) (srfi 207)
(chicken foreign))
(export
parse-go-sum-line parse-go-sum-file go-sum-line? go-sum-module go-sum-version go-sum-path go-sum-hash)
(begin
;; Contains the values from a single line from a `go.sum` file.
(define-record-type <go-sum-line>
(make-go-sum-line module version path hash)
go-sum-line?
(module go-sum-module)
(version go-sum-version)
(path go-sum-path)
(hash go-sum-hash))
(define-record-printer (<go-sum-line> sum out)
(fprintf out "#<go-sum ~A ~A~A h1:~A>"
(go-sum-module sum)
(go-sum-version sum)
(if (go-sum-path sum) (go-sum-path sum) "")
(bytevector->base64 (go-sum-hash sum))))
(define (string-find str index char)
(cond
((= index (string-length str)) #f)
((char=? (string-ref str index) char) index)
(else (string-find str (+ index 1) char))))
;; Parses a `go.sum` line, and returns a `<go-sum-line>`.
(define (parse-go-sum-line line)
(define version-space-index (string-find line 0 #\space))
(unless version-space-index (error "go.sum line contains no space characters"))
(define hash-space-index (string-find line (+ version-space-index 1) #\space))
(unless hash-space-index (error "go.sum line contains only one space character"))
(when (string-find line (+ hash-space-index 1) #\space) (error "go.sum line contains too many space characters"))
(define module-path (string-copy line 0 version-space-index))
(define version (string-copy line (+ version-space-index 1) hash-space-index))
(define hash (string-copy line (+ hash-space-index 1)))
(unless (string=? (string-copy hash 0 3) "h1:") (error "go.sum line has invalid algorithm for hash" hash))
(define path #f)
(define path-index (string-find version 0 #\/))
(when path-index
(set! path (string-copy version path-index))
(set! version (string-copy version 0 path-index)))
(make-go-sum-line module-path version path (base64->bytevector (string-copy hash 3))))
;; Parses all the `go.sum` lines from `port`.
(define (parse-go-sum-file port)
(do ((parsed '())
(line "" (read-line port)))
((eof-object? line) (list->vector (reverse parsed)))
(unless (string=? line "") (set! parsed (cons (parse-go-sum-line line) parsed)))))))