72 lines
1.4 KiB
Go
72 lines
1.4 KiB
Go
package data
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
type (
|
|
Data struct {
|
|
Softwares []Software
|
|
}
|
|
|
|
Software struct {
|
|
Slug string `json:"slug"`
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
Version string `json:"version"`
|
|
IconURL string `json:"icon_url"`
|
|
ScreenshotURLs []string `json:"screenshot_urls"`
|
|
DownloadLinks []DownloadLink `json:"download_links"`
|
|
}
|
|
|
|
DownloadLink struct {
|
|
OS string `json:"os"`
|
|
Arch string `json:"arch"`
|
|
Name string `json:"name"`
|
|
URL string `json:"url"`
|
|
}
|
|
|
|
document struct {
|
|
Softwares []Software `json:"softwares"`
|
|
}
|
|
)
|
|
|
|
func Load(path string) (Data, error) {
|
|
f, err := os.OpenFile(path, os.O_RDONLY, 0)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return Data{}, nil
|
|
}
|
|
return Data{}, fmt.Errorf("failed to open data file: %w", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
var s document
|
|
d := json.NewDecoder(f)
|
|
err = d.Decode(&s)
|
|
if err != nil {
|
|
return Data{}, fmt.Errorf("failed to parse data file: %w", err)
|
|
}
|
|
|
|
return Data(s), nil
|
|
}
|
|
|
|
func Save(doc Data, path string) error {
|
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0740)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to open data file: %w", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
e := json.NewEncoder(f)
|
|
err = e.Encode(document(doc))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|