vanity/router/cache.go

111 lines
2.3 KiB
Go

package router
import (
"go.jolheiser.com/beaver"
"go.jolheiser.com/vanity/flags"
"go.jolheiser.com/vanity/service"
"strings"
"sync"
"go.jolheiser.com/vanity/api"
)
var cache = &packageCache{
Packages: make(map[string]*api.Package),
}
type packageList map[string]*api.Package
func (p packageList) Names() []string {
names := make([]string, len(p))
idx := 0
for name := range p {
names[idx] = name
idx++
}
return names
}
func (p packageList) Topics() map[string][]*api.Package {
topics := make(map[string][]*api.Package, 0)
for _, pkg := range p {
if len(pkg.Topics) == 0 {
if tt, ok := topics["other"]; ok {
topics["other"] = append(tt, pkg)
} else {
topics["other"] = []*api.Package{pkg}
}
}
for _, t := range pkg.Topics {
if tt, ok := topics[t]; ok {
topics[t] = append(tt, pkg)
} else {
topics[t] = []*api.Package{pkg}
}
}
}
return topics
}
type packageCache struct {
Packages packageList
sync.Mutex
}
func (c *packageCache) Update(packages map[string]*api.Package) {
c.Lock()
c.Packages = packages
c.Unlock()
}
func updateCache() {
packages, err := svc.Packages()
if err != nil {
beaver.Errorf("could not update packages: %v", err)
return
}
// Filter
for name, pkg := range packages {
if err := service.Check(pkg); err != nil {
beaver.Debug(err)
delete(packages, name)
continue
}
goMod, err := svc.GoMod(pkg)
if err != nil {
beaver.Debugf("No go.mod could be found in the root directory of %s", pkg.Name)
delete(packages, name)
continue
}
lines := strings.Split(goMod, "\n")
line := strings.Fields(lines[0])
if !strings.HasPrefix(line[1], flags.Domain) {
beaver.Debugf("%s is a Go project, however its module does not include this domain", pkg.Name)
delete(packages, name)
continue
}
beaver.Debugf("Including %s", pkg.Name)
}
// Overrides
for name, pkg := range packages {
for key, override := range flags.Override {
if strings.EqualFold(name, key) {
beaver.Debugf("Overriding %s -> %s", name, override)
delete(packages, key)
pkg.Name = override
packages[override] = pkg
}
}
}
// Add packages manually added to config
for _, pkg := range flags.ConfigPackages {
packages[pkg.Name] = pkg
}
cache.Update(packages)
canUpdate = false
}