From e94151cec5050094cd79cc6b375e231ca3e1f7f1 Mon Sep 17 00:00:00 2001 From: zhilv Date: Mon, 22 Dec 2025 14:21:11 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=B7=BB=E5=8A=A0=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=9B=AE=E5=BD=95=E4=B8=8B=E7=9A=84=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 ++- Makefile | 2 +- cmd/export.go | 33 +++++++++++++++++++++++++++++---- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index 4917994..026610c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ bin config.* -.idea \ No newline at end of file +.idea +nul diff --git a/Makefile b/Makefile index c530e33..8f8ac97 100644 --- a/Makefile +++ b/Makefile @@ -14,7 +14,7 @@ BUILD_TIME := $(shell date -u +%Y-%m-%dT%H:%M:%SZ) # Detect Zig ifeq ($(OS),Windows_NT) - ZIG_BIN := $(shell where zig 2>nul) + ZIG_BIN := $(shell where zig 2>/dev/null) else ZIG_BIN := $(shell which zig 2>/dev/null) endif diff --git a/cmd/export.go b/cmd/export.go index 7ed9595..0781c3a 100644 --- a/cmd/export.go +++ b/cmd/export.go @@ -23,9 +23,15 @@ var exportCmd = &cobra.Command{ filePath, _ := cmd.Flags().GetString("file") format, _ := cmd.Flags().GetString("format") - // 默认文件名和格式 + // 默认文件路径和格式 if filePath == "" { - filePath = "config.yaml" + // 获取用户的 Home 目录 + homeDir, err := os.UserHomeDir() + if err != nil { + return fmt.Errorf("获取用户主目录失败: %w", err) + } + // 默认导出到 Home 目录下的 myapp_config.yaml + filePath = filepath.Join(homeDir, "netctl", "config.yaml") } if format == "" { format = "yaml" @@ -42,9 +48,23 @@ var exportCmd = &cobra.Command{ filePath = strings.TrimSuffix(filePath, ext) + "." + format } + // 确保目录存在 + dir := filepath.Dir(filePath) + if err := os.MkdirAll(dir, os.ModePerm); err != nil { + return fmt.Errorf("无法创建目录: %w", err) + } + // 获取默认配置 defaultConfig := config.DefaultConfig() + // 检查文件是否存在并提示覆盖 + if _, err := os.Stat(filePath); err == nil { + overwrite, _ := cmd.Flags().GetBool("overwrite") + if !overwrite { + return fmt.Errorf("文件 %s 已存在,使用 --overwrite 强制覆盖", filePath) + } + } + // 创建文件 f, err := os.Create(filePath) if err != nil { @@ -76,14 +96,19 @@ var exportCmd = &cobra.Command{ } } - absPath, _ := filepath.Abs(filePath) + absPath, err := filepath.Abs(filePath) + if err != nil { + return fmt.Errorf("获取绝对路径失败: %w", err) + } fmt.Printf("默认配置已导出到: %s\n", absPath) return nil }, } func init() { - exportCmd.Flags().StringP("file", "f", "", "导出文件路径 (默认 ./config.yaml)") + exportCmd.Flags().StringP("file", "f", "", "导出文件路径 (默认导出到用户 Home 目录下 netctl/config.yaml)") exportCmd.Flags().StringP("format", "t", "yaml", "导出格式: yaml, toml, json (默认 yaml)") + exportCmd.Flags().BoolP("overwrite", "o", false, "强制覆盖已存在的文件") + rootCmd.AddCommand(exportCmd) }