libyear/pkg/gomod/gomod.go

68 lines
1.8 KiB
Go
Raw Normal View History

2021-04-10 02:01:41 +00:00
package gomod
import (
"os"
2021-04-11 02:22:06 +00:00
"git.yetaga.in/alazyreader/libyear/pkg/libyear"
2021-04-10 02:01:41 +00:00
"golang.org/x/mod/modfile"
)
2021-05-09 21:25:23 +00:00
// GoMod represents a Go Modules parser.
// Running LoadAndComputePairs with a filename will return a slice of parsed dependencies.
2021-04-11 02:14:45 +00:00
type GoMod struct {
IncludeIndirect bool
ProxyLoader Queryer
Logger logger
}
2021-05-09 21:25:23 +00:00
// logger is an extremely simple leveled logger
type logger interface {
Logf(f string, s ...interface{})
Debugf(f string, s ...interface{})
2021-04-11 02:14:45 +00:00
}
2021-05-09 21:25:23 +00:00
// LoadAndComputePairs takes a filename of a go.mod file,
// runs the resolution algorithm in the provided Querier,
// and returns parsed pairs of dependencies and their latest versions.
2021-04-11 02:14:45 +00:00
func (g *GoMod) LoadAndComputePairs(filename string) ([]libyear.Pair, error) {
2021-04-10 02:01:41 +00:00
b, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
f, err := modfile.Parse(filename, b, nil)
if err != nil {
return nil, err
}
pairs := []libyear.Pair{}
for v := range f.Require {
if f.Require[v].Mod.Path != "" && f.Require[v].Mod.Version != "" {
2021-04-11 02:14:45 +00:00
if isReplaced(f.Require[v].Mod.Path, f.Replace) {
g.Logger.Logf("%s is replaced, skipping...\n", f.Require[v].Mod.Path)
continue
}
if !g.IncludeIndirect && f.Require[v].Indirect {
g.Logger.Logf("%s is indirect, skipping...\n", f.Require[v].Mod.Path)
continue
}
latest := g.ProxyLoader.GetLatestVersion(f.Require[v].Mod.Path)
current := g.ProxyLoader.GetVersion(f.Require[v].Mod.Path, f.Require[v].Mod.Version)
2021-04-10 02:01:41 +00:00
pairs = append(pairs, libyear.Pair{
Name: f.Require[v].Mod.Path,
Current: current,
Latest: latest,
})
}
}
return pairs, nil
}
2021-05-09 21:25:23 +00:00
func isReplaced(module string, replaces []*modfile.Replace) bool {
for i := range replaces {
if module == replaces[i].Old.Path {
return true
}
}
return false
}