forgejo-cli/internal/config/config.go
2026-01-28 16:23:42 +00:00

79 lines
1.7 KiB
Go

package config
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
type Config struct {
ForgejoInstanceURL string `json:"forgejo_instance_url"`
filepath string `json:"-"`
}
// Load tries to load a saved configuration.
func Load(path string) (*Config, error) {
var err error
if path == "" {
path, err = getUserConfigDir()
if err != nil {
return nil, fmt.Errorf("failed to load config: %w", err)
}
}
if _, err := os.Stat(path); os.IsNotExist(err) {
return &Config{filepath: path}, nil
}
fileData, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read config file: %w", err)
}
var cfg Config
err = json.Unmarshal(fileData, &cfg)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal config file: %w", err)
}
cfg.filepath = path
return &cfg, nil
}
func (cfg *Config) Save(path string) error {
var err error
if path == "" {
path = cfg.filepath
}
fileData, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal config: %w", err)
}
err = os.WriteFile(path, fileData, 0600)
if err != nil {
return fmt.Errorf("failed to write config file: %w", err)
}
return nil
}
// getUserConfigDir creates the full path to the config file.
func getUserConfigDir() (string, error) {
userConfigPath, err := os.UserConfigDir()
if err != nil {
return "", fmt.Errorf("failed to get user configuration path: %w", err)
}
configDir := filepath.Join(userConfigPath, "forgejo-cli")
if _, err := os.Stat(configDir); os.IsNotExist(err) {
err = os.MkdirAll(configDir, 0700)
if err != nil {
return "", fmt.Errorf("failed to create config dir: %w", err)
}
}
filename := filepath.Join(configDir, "config.json")
return filename, nil
}