2016-02-13 01:18:06 -08:00
|
|
|
package vain
|
|
|
|
|
|
|
|
import (
|
2016-02-14 22:19:41 -08:00
|
|
|
"encoding/json"
|
|
|
|
"os"
|
2016-02-13 10:44:41 -08:00
|
|
|
"strings"
|
2016-02-13 01:18:06 -08:00
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2016-02-13 10:44:41 -08:00
|
|
|
func Valid(p string, packages []Package) bool {
|
|
|
|
for _, pkg := range packages {
|
|
|
|
if strings.HasPrefix(pkg.Path, p) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2016-02-13 01:18:06 -08:00
|
|
|
type MemStore struct {
|
|
|
|
l sync.RWMutex
|
|
|
|
p map[string]Package
|
2016-02-14 22:19:41 -08:00
|
|
|
|
|
|
|
dbl sync.Mutex
|
|
|
|
path string
|
2016-02-13 01:18:06 -08:00
|
|
|
}
|
|
|
|
|
2016-02-14 22:19:41 -08:00
|
|
|
func NewMemStore(path string) *MemStore {
|
2016-02-13 01:18:06 -08:00
|
|
|
return &MemStore{
|
2016-02-14 22:19:41 -08:00
|
|
|
path: path,
|
|
|
|
p: make(map[string]Package),
|
2016-02-13 01:18:06 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-14 22:19:41 -08:00
|
|
|
func (ms *MemStore) Add(p Package) error {
|
2016-02-13 01:18:06 -08:00
|
|
|
ms.l.Lock()
|
|
|
|
ms.p[p.Path] = p
|
|
|
|
ms.l.Unlock()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-02-14 22:19:41 -08:00
|
|
|
func (ms *MemStore) Remove(path string) error {
|
2016-02-13 01:18:06 -08:00
|
|
|
ms.l.Lock()
|
|
|
|
delete(ms.p, path)
|
|
|
|
ms.l.Unlock()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-02-14 22:19:41 -08:00
|
|
|
func (ms *MemStore) Save() error {
|
|
|
|
// running in-memory only
|
|
|
|
if ms.path == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
ms.dbl.Lock()
|
|
|
|
defer ms.dbl.Unlock()
|
|
|
|
f, err := os.Create(ms.path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
return json.NewEncoder(f).Encode(ms.p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ms *MemStore) Load() error {
|
|
|
|
// running in-memory only
|
|
|
|
if ms.path == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
ms.dbl.Lock()
|
|
|
|
defer ms.dbl.Unlock()
|
|
|
|
f, err := os.Open(ms.path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
return json.NewDecoder(f).Decode(&ms.p)
|
2016-02-13 01:18:06 -08:00
|
|
|
}
|
|
|
|
|
2016-02-14 22:19:41 -08:00
|
|
|
func (ms *MemStore) All() []Package {
|
2016-02-13 01:18:06 -08:00
|
|
|
r := []Package{}
|
|
|
|
ms.l.RLock()
|
|
|
|
for _, p := range ms.p {
|
|
|
|
r = append(r, p)
|
|
|
|
}
|
|
|
|
ms.l.RUnlock()
|
|
|
|
return r
|
|
|
|
}
|