2022-09-03 21:58:02 +00:00
|
|
|
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 != ""
|
|
|
|
}
|
|
|
|
|
2022-09-04 02:06:06 +00:00
|
|
|
func (c *Config) Branches() ([]string, error) {
|
|
|
|
dirs, err := os.ReadDir(c.Workspace())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
branches := make([]string, 0, len(dirs))
|
|
|
|
for _, dir := range dirs {
|
|
|
|
if !dir.IsDir() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
branches = append(branches, dir.Name())
|
|
|
|
}
|
|
|
|
return branches, nil
|
|
|
|
}
|
|
|
|
|
2022-09-03 21:58:02 +00:00
|
|
|
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)
|
|
|
|
}
|