package meta import ( "encoding/json" "errors" "fmt" "io/fs" "os" "strings" "go.jolheiser.com/eget/disk" "github.com/adrg/xdg" ) type Meta struct { Packages map[string]Package `json:"packages"` } type Package struct { Repo string `json:"repo"` Version string `json:"version"` } func Upsert(name, repo, version string) error { m, err := Read() if err != nil { return err } for n := range m.Packages { if strings.EqualFold(n, name) { m.Packages[n] = Package{ Repo: repo, Version: version, } return save(m) } } m.Packages[name] = Package{ Repo: repo, Version: version, } return save(m) } func Read() (Meta, error) { m := Meta{ Packages: make(map[string]Package), } 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 { if errors.Is(err, fs.ErrNotExist) { return m, json.Unmarshal([]byte(`{}`), &m) } 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 n := range m.Packages { if strings.EqualFold(n, name) { delete(m.Packages, name) return save(m) } } return fmt.Errorf("could not find package to remove for %q", name) } func metaPath() (string, error) { return xdg.ConfigFile("eget/packages.json") } func nushellPath() (string, error) { return xdg.DataFile("eget/eget.nu") } 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) } if err := json.NewEncoder(fi).Encode(m); err != nil { return err } if err := fi.Close(); err != nil { return err } fp, err = nushellPath() if err != nil { return fmt.Errorf("could not get nushell path: %w", err) } fi, err = os.Create(fp) if err != nil { return fmt.Errorf("could not create nushell file: %w", err) } defer fi.Close() out, err := m.nushell() if err != nil { return fmt.Errorf("could not generate nushell environment: %w", err) } fi.WriteString(out) return nil } func (m Meta) nushell() (string, error) { tmpl := "let-env PATH = ($env.PATH | append '%s')\n" var out strings.Builder out.WriteString("# managed by eget; DO NOT EDIT\n\n") for name := range m.Packages { out.WriteString(fmt.Sprintf(tmpl, disk.Path(name))) } return out.String(), nil }