package modsum
import (
modzip
)
type Checksums struct {
Module string
Version string
ZipHash string
ModHash string
}
type fsZipFile struct {
zipPath string
fsys fs.FS
fsPath string
}
func ( fsZipFile) () string { return .zipPath }
func ( fsZipFile) () (fs.FileInfo, error) { return fs.Stat(.fsys, .fsPath) }
func ( fsZipFile) () (io.ReadCloser, error) { return .fsys.Open(.fsPath) }
func ( fs.FS, , , string, []vcs.FileEntry) (Checksums, error) {
= path.Clean(strings.TrimPrefix(filepath.ToSlash(), "./"))
:= ""
if != "." {
= + "/"
}
:= make(map[string]bool)
for , := range {
, := trimModulePrefix(.Path, )
if && path.Base() == "go.mod" && != "go.mod" {
[path.Dir()] = true
}
}
var []modzip.File
for , := range {
, := trimModulePrefix(.Path, )
if ! || isInsideNestedSubmod(, ) {
continue
}
= append(, fsZipFile{
zipPath: ,
fsys: ,
fsPath: path.Clean(strings.TrimPrefix(.Path, "./")),
})
}
if len() == 0 {
return Checksums{}, fmt.Errorf("no tracked files found for module %s in %q", , )
}
var bytes.Buffer
:= module.Version{Path: , Version: }
if := modzip.Create(&, , ); != nil {
return Checksums{}, fmt.Errorf("create module zip for %s@%s: %w", , , )
}
, := hashZipBytes(.Bytes())
if != nil {
return Checksums{}, fmt.Errorf("hash module zip for %s@%s: %w", , , )
}
:= path.Join(, "go.mod")
, := dirhash.Hash1([]string{"go.mod"}, func(string) (io.ReadCloser, error) {
return .Open()
})
if != nil {
return Checksums{}, fmt.Errorf("hash go.mod for %s@%s: %w", , , )
}
return Checksums{
Module: ,
Version: ,
ZipHash: ,
ModHash: ,
}, nil
}
func (, , , string, []vcs.FileEntry) (Checksums, error) {
return ComputeFS(os.DirFS(), , , , )
}
func ( []byte) (string, error) {
, := zip.NewReader(bytes.NewReader(), int64(len()))
if != nil {
return "",
}
:= make([]string, 0, len(.File))
:= make(map[string]*zip.File, len(.File))
for , := range .File {
= append(, .Name)
[.Name] =
}
return dirhash.Hash1(, func( string) (io.ReadCloser, error) {
, := []
if ! {
return nil, fmt.Errorf("zip entry %q not found", )
}
return .Open()
})
}
func (, string) (string, bool) {
if == "" {
return , true
}
if !strings.HasPrefix(, ) {
return "", false
}
return strings.TrimPrefix(, ), true
}
func ( string, map[string]bool) bool {
if len() == 0 {
return false
}
for := path.Dir(); != "." && != ""; = path.Dir() {
if [] {
return true
}
}
return false
}