69 lines
1.5 KiB
Go
69 lines
1.5 KiB
Go
package initcmd
|
||
|
||
import (
|
||
"fmt"
|
||
"os"
|
||
|
||
"sunhpc/internal/auth"
|
||
"sunhpc/internal/config"
|
||
"sunhpc/internal/log"
|
||
|
||
"github.com/spf13/cobra"
|
||
)
|
||
|
||
// NewConfigCmd 创建 "init config" 命令
|
||
func NewConfigCmd() *cobra.Command {
|
||
var (
|
||
force bool
|
||
path string
|
||
verbose bool
|
||
)
|
||
|
||
cmd := &cobra.Command{
|
||
Use: "config",
|
||
Short: "生成默认配置文件",
|
||
Long: `
|
||
在指定路径生成 SunHPC 默认配置文件 (sunhpc.yaml)
|
||
|
||
示例:
|
||
sunhpc init config # 生成默认配置文件
|
||
sunhpc init config -f # 强制覆盖已有配置文件
|
||
sunhpc init config -p /etc/sunhpc/sunhpc.yaml # 指定路径
|
||
`,
|
||
|
||
Annotations: map[string]string{
|
||
"require-root": "true", // 假设需要 root(你可自定义策略)
|
||
},
|
||
|
||
RunE: func(cmd *cobra.Command, args []string) error {
|
||
if err := auth.RequireRoot(); err != nil {
|
||
return err
|
||
}
|
||
|
||
if path == "" {
|
||
path = "/etc/sunhpc/sunhpc.yaml"
|
||
}
|
||
|
||
if !force {
|
||
if _, err := os.Stat(path); err == nil {
|
||
return fmt.Errorf("配置文件已存在: %s (使用 --force 覆盖)", path)
|
||
}
|
||
}
|
||
|
||
if err := config.WriteDefaultConfig(path); err != nil {
|
||
return fmt.Errorf("写入配置失败: %w", err)
|
||
}
|
||
|
||
log.Infof("✅ 配置文件已生成: %s", path)
|
||
return nil
|
||
},
|
||
}
|
||
|
||
// 定义局部 flags
|
||
cmd.Flags().BoolVarP(&force, "force", "f", false, "强制覆盖已有配置文件")
|
||
cmd.Flags().StringVarP(&path, "path", "p", "", "指定配置文件路径")
|
||
cmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "显示详细日志")
|
||
|
||
return cmd
|
||
}
|