feat(config): 添加 JSON/TOML 配置读取与 YAML/JSON/TOML 导出功能, 优化部分内部代码结构, 更新 Makefile:添加 Zig 外链检测、可选 UPX 压缩、构建流程优化
This commit is contained in:
89
cmd/export.go
Normal file
89
cmd/export.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"netcli/config"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
"github.com/spf13/cobra"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
var exportCmd = &cobra.Command{
|
||||
Use: "export",
|
||||
Short: "导出默认配置文件",
|
||||
Long: "可以将默认配置导出为 YAML, TOML, JSON 格式文件,支持自定义路径和格式, 生效顺序: YAML, TOML, JSON",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
// 获取参数
|
||||
filePath, _ := cmd.Flags().GetString("file")
|
||||
format, _ := cmd.Flags().GetString("format")
|
||||
|
||||
// 默认文件名和格式
|
||||
if filePath == "" {
|
||||
filePath = "config.yaml"
|
||||
}
|
||||
if format == "" {
|
||||
format = "yaml"
|
||||
}
|
||||
|
||||
format = strings.ToLower(format)
|
||||
if format != "yaml" && format != "yml" && format != "toml" && format != "json" {
|
||||
return fmt.Errorf("不支持的格式: %s, 可选: yaml, toml, json", format)
|
||||
}
|
||||
|
||||
// 根据格式修改文件后缀
|
||||
ext := strings.ToLower(filepath.Ext(filePath))
|
||||
if ext == "" || ext != "."+format {
|
||||
filePath = strings.TrimSuffix(filePath, ext) + "." + format
|
||||
}
|
||||
|
||||
// 获取默认配置
|
||||
defaultConfig := config.DefaultConfig()
|
||||
|
||||
// 创建文件
|
||||
f, err := os.Create(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建文件失败: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// 写入不同格式
|
||||
switch format {
|
||||
case "yaml", "yml":
|
||||
enc := yaml.NewEncoder(f)
|
||||
defer enc.Close()
|
||||
if err := enc.Encode(defaultConfig); err != nil {
|
||||
return fmt.Errorf("YAML 编码失败: %w", err)
|
||||
}
|
||||
case "json":
|
||||
enc := json.NewEncoder(f)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(defaultConfig); err != nil {
|
||||
return fmt.Errorf("JSON 编码失败: %w", err)
|
||||
}
|
||||
case "toml":
|
||||
data, err := toml.Marshal(defaultConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("TOML 编码失败: %w", err)
|
||||
}
|
||||
if _, err := f.Write(data); err != nil {
|
||||
return fmt.Errorf("写入 TOML 文件失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
absPath, _ := filepath.Abs(filePath)
|
||||
fmt.Printf("默认配置已导出到: %s\n", absPath)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.Flags().StringP("file", "f", "", "导出文件路径 (默认 ./config.yaml)")
|
||||
exportCmd.Flags().StringP("format", "t", "yaml", "导出格式: yaml, toml, json (默认 yaml)")
|
||||
rootCmd.AddCommand(exportCmd)
|
||||
}
|
||||
Reference in New Issue
Block a user