git-ea/config/config.go

77 lines
1.3 KiB
Go
Raw Normal View History

package config
import (
"encoding/json"
"errors"
"io/fs"
"os"
"path/filepath"
)
type Config struct {
Base string `json:"base"`
}
func (c *Config) Workspace() string {
return filepath.Join(c.Base, ".workspace")
}
func (c *Config) WorkspaceBranch(name string) string {
return filepath.Join(c.Workspace(), name)
}
func (c *Config) IsInit() bool {
return c.Base != ""
}
func path() (string, error) {
userCfgDir, err := os.UserConfigDir()
if err != nil {
return "", err
}
cfgDir := filepath.Join(userCfgDir, "git-ea")
return filepath.Join(cfgDir, "config.json"), os.MkdirAll(cfgDir, os.ModePerm)
}
func Load() (*Config, error) {
cfgPath, err := path()
if err != nil {
return nil, err
}
fi, err := os.Open(cfgPath)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return nil, err
}
fi, err = os.Create(cfgPath)
if err != nil {
return nil, err
}
if _, err := fi.WriteString("{}"); err != nil {
return nil, err
}
if _, err := fi.Seek(0, 0); err != nil {
return nil, err
}
}
defer fi.Close()
var cfg Config
return &cfg, json.NewDecoder(fi).Decode(&cfg)
}
func Save(c Config) error {
cfgPath, err := path()
if err != nil {
return err
}
fi, err := os.Create(cfgPath)
if err != nil {
return err
}
defer fi.Close()
return json.NewEncoder(fi).Encode(c)
}