84 lines
1.6 KiB
Go
84 lines
1.6 KiB
Go
package meta
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/adrg/xdg"
|
|
)
|
|
|
|
type Meta struct {
|
|
Packages []Package `json:"packages"`
|
|
}
|
|
|
|
type Package struct {
|
|
Name string `json:"name"`
|
|
Version string `json:"version"`
|
|
}
|
|
|
|
func Add(pkg Package) error {
|
|
m, err := Read()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, p := range m.Packages {
|
|
if strings.EqualFold(pkg.Name, p.Name) {
|
|
return errors.New("package already exists locally")
|
|
}
|
|
}
|
|
m.Packages = append(m.Packages, pkg)
|
|
return save(m)
|
|
}
|
|
|
|
func Read() (Meta, error) {
|
|
var m Meta
|
|
fp, err := metaPath()
|
|
if err != nil {
|
|
return m, fmt.Errorf("could not get meta file: %w", err)
|
|
}
|
|
fi, err := os.Open(fp)
|
|
if err != nil {
|
|
return m, fmt.Errorf("could not open meta file: %w", err)
|
|
}
|
|
defer fi.Close()
|
|
|
|
if err := json.NewDecoder(fi).Decode(&m); err != nil {
|
|
return m, fmt.Errorf("could not decode meta: %w", err)
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
func Remove(name string) error {
|
|
m, err := Read()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for idx, p := range m.Packages {
|
|
if strings.EqualFold(name, p.Name) {
|
|
m.Packages = append(m.Packages[:idx], m.Packages[idx+1:]...)
|
|
return save(m)
|
|
}
|
|
}
|
|
return fmt.Errorf("could not find package to remove for %q", name)
|
|
}
|
|
|
|
func metaPath() (string, error) {
|
|
return xdg.DataFile("eget/meta.json")
|
|
}
|
|
|
|
func save(m Meta) error {
|
|
fp, err := metaPath()
|
|
if err != nil {
|
|
return fmt.Errorf("could not get meta path: %w", err)
|
|
}
|
|
fi, err := os.Create(fp)
|
|
if err != nil {
|
|
return fmt.Errorf("could not create meta file: %w", err)
|
|
}
|
|
defer fi.Close()
|
|
return json.NewEncoder(fi).Encode(m)
|
|
}
|