Files
cloudsave/pkg/remote/remote.go
Aurélie DELHAIE 5f7ca22b8f
Some checks failed
CloudSave/pipeline/head There was a failure building this commit
wip
2025-09-11 17:41:57 +02:00

101 lines
1.8 KiB
Go

package remote
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
)
type (
Remote struct {
URL string `json:"url"`
GameID string `json:"-"`
}
)
var (
roaming string
datastorepath string
)
var (
ErrNoRemote error = errors.New("no remote found for this game")
)
func init() {
var err error
roaming, err = os.UserConfigDir()
if err != nil {
panic("failed to get user config path: " + err.Error())
}
datastorepath = filepath.Join(roaming, "cloudsave", "data")
err = os.MkdirAll(datastorepath, 0740)
if err != nil {
panic("cannot make the datastore:" + err.Error())
}
}
func One(gameID string) (Remote, error) {
content, err := os.ReadFile(filepath.Clean(filepath.Join(datastorepath, gameID, "remote.json")))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return Remote{}, ErrNoRemote
}
return Remote{}, err
}
var r Remote
err = json.Unmarshal(content, &r)
if err != nil {
return Remote{}, fmt.Errorf("corrupted datastore: failed to parse %s/remote.json: %w", gameID, err)
}
r.GameID = gameID
return r, nil
}
func All() ([]Remote, error) {
d, err := os.ReadDir(filepath.Clean(datastorepath))
if err != nil {
return nil, fmt.Errorf("failed to load datastore: %w", err)
}
var res []Remote
for _, g := range d {
r, err := One(g.Name())
if err != nil {
if errors.Is(err, ErrNoRemote) {
continue
}
return nil, fmt.Errorf("failed to load remote: %w", err)
}
res = append(res, r)
}
return res, nil
}
func Set(gameID, url string) error {
r := Remote{
URL: url,
}
f, err := os.OpenFile(filepath.Join(filepath.Join(datastorepath, gameID, "remote.json")), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0740)
if err != nil {
return err
}
defer f.Close()
e := json.NewEncoder(f)
err = e.Encode(r)
if err != nil {
return err
}
return nil
}