76 lines
1.9 KiB
Go
76 lines
1.9 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
// AppConfig 应用配置结构体,对应 config.yaml
|
|
type AppConfig struct {
|
|
// 日志设置
|
|
LogLevel string `yaml:"log_level"` // 日志级别: trace|debug|info|warn|error
|
|
LogFile string `yaml:"log_file"` // 日志文件路径(可选)
|
|
|
|
// 默认 Profile
|
|
DefaultProfile string `yaml:"default_profile"`
|
|
|
|
// 还原选项
|
|
Restore RestoreConfig `yaml:"restore"`
|
|
}
|
|
|
|
// RestoreConfig 还原相关配置
|
|
type RestoreConfig struct {
|
|
ConflictStrategy string `yaml:"conflict_strategy"` // skip|overwrite|merge|prompt|newest
|
|
CreateRestorePoint bool `yaml:"create_restore_point"` // 是否创建还原点
|
|
DryRunFirst bool `yaml:"dry_run_first"` // 是否先执行干运行
|
|
}
|
|
|
|
// DefaultAppConfig 返回带有合理默认值的配置
|
|
func DefaultAppConfig() *AppConfig {
|
|
return &AppConfig{
|
|
LogLevel: "info",
|
|
DefaultProfile: "standard",
|
|
Restore: RestoreConfig{
|
|
ConflictStrategy: "prompt",
|
|
CreateRestorePoint: true,
|
|
DryRunFirst: false,
|
|
},
|
|
}
|
|
}
|
|
|
|
// LoadConfig 从指定路径加载配置文件,文件不存在时返回默认配置
|
|
func LoadConfig(path string) (*AppConfig, error) {
|
|
cfg := DefaultAppConfig()
|
|
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
// 配置文件不存在,返回默认配置
|
|
return cfg, nil
|
|
}
|
|
return nil, fmt.Errorf("读取配置文件失败: %w", err)
|
|
}
|
|
|
|
if err := yaml.Unmarshal(data, cfg); err != nil {
|
|
return nil, fmt.Errorf("解析配置文件失败: %w", err)
|
|
}
|
|
|
|
return cfg, nil
|
|
}
|
|
|
|
// SaveConfig 将配置保存到指定路径
|
|
func SaveConfig(path string, cfg *AppConfig) error {
|
|
data, err := yaml.Marshal(cfg)
|
|
if err != nil {
|
|
return fmt.Errorf("序列化配置失败: %w", err)
|
|
}
|
|
|
|
if err := os.WriteFile(path, data, 0o644); err != nil {
|
|
return fmt.Errorf("写入配置文件失败: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|