feat: config system — TOML load/save with provider auth map
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
type ProviderConfig struct {
|
||||
APIKey string `toml:"api_key,omitempty"`
|
||||
AccessKeyID string `toml:"access_key_id,omitempty"`
|
||||
AccessKeySecret string `toml:"access_key_secret,omitempty"`
|
||||
Endpoint string `toml:"endpoint,omitempty"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
CurrentProvider string `toml:"current_provider"`
|
||||
Output string `toml:"output"`
|
||||
Providers map[string]ProviderConfig `toml:"providers"`
|
||||
}
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
cfg := &Config{
|
||||
Output: "table",
|
||||
Providers: make(map[string]ProviderConfig),
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return cfg, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err := toml.Unmarshal(data, cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.Providers == nil {
|
||||
cfg.Providers = make(map[string]ProviderConfig)
|
||||
}
|
||||
if cfg.Output == "" {
|
||||
cfg.Output = "table"
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func Save(path string, cfg *Config) error {
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
enc := toml.NewEncoder(f)
|
||||
return enc.Encode(cfg)
|
||||
}
|
||||
|
||||
func DefaultPath() string {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "config.toml"
|
||||
}
|
||||
return filepath.Join(home, ".config", "ry", "config.toml")
|
||||
}
|
||||
Reference in New Issue
Block a user