feat: 增加命令行工具的参数支持,包括路径、干运行模式和输出目录选项
This commit is contained in:
50
cmd/fmt.go
50
cmd/fmt.go
@@ -10,17 +10,20 @@ import (
|
||||
)
|
||||
|
||||
func CommandFmt(root *cobra.Command) {
|
||||
cmd := &cobra.Command{
|
||||
Use: "fmt",
|
||||
Short: "fmt codes",
|
||||
RunE: commandFmtE,
|
||||
}
|
||||
cmd := &cobra.Command{
|
||||
Use: "fmt",
|
||||
Short: "fmt codes",
|
||||
RunE: commandFmtE,
|
||||
}
|
||||
|
||||
cmd.Flags().Bool("check", false, "Check formatting without writing changes")
|
||||
cmd.Flags().String("path", ".", "Path to format (default .)")
|
||||
|
||||
root.AddCommand(cmd)
|
||||
}
|
||||
|
||||
func commandFmtE(cmd *cobra.Command, args []string) error {
|
||||
log.Info("开始格式化代码")
|
||||
log.Info("开始格式化代码")
|
||||
if _, err := exec.LookPath("gofumpt"); err != nil {
|
||||
log.Info("gofumpt 不存在,正在安装...")
|
||||
installCmd := exec.Command("go", "install", "mvdan.cc/gofumpt@latest")
|
||||
@@ -34,14 +37,31 @@ func commandFmtE(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("运行 gofumpt...")
|
||||
gofumptCmd := exec.Command("gofumpt", "-l", "-extra", "-w", ".")
|
||||
gofumptCmd.Stdout = os.Stdout
|
||||
gofumptCmd.Stderr = os.Stderr
|
||||
if err := gofumptCmd.Run(); err != nil {
|
||||
return fmt.Errorf("运行 gofumpt 失败: %v", err)
|
||||
}
|
||||
check, _ := cmd.Flags().GetBool("check")
|
||||
path, _ := cmd.Flags().GetString("path")
|
||||
|
||||
log.Info("格式化代码完成")
|
||||
return nil
|
||||
if check {
|
||||
log.Info("运行 gofumpt 检查模式...")
|
||||
out, err := exec.Command("gofumpt", "-l", "-extra", path).CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("运行 gofumpt 失败: %v", err)
|
||||
}
|
||||
if len(out) > 0 {
|
||||
fmt.Fprintln(os.Stdout, string(out))
|
||||
return fmt.Errorf("发现未格式化文件,请运行: gofumpt -l -extra -w %s", path)
|
||||
}
|
||||
log.Info("代码格式良好")
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Info("运行 gofumpt...")
|
||||
gofumptCmd := exec.Command("gofumpt", "-l", "-extra", "-w", path)
|
||||
gofumptCmd.Stdout = os.Stdout
|
||||
gofumptCmd.Stderr = os.Stderr
|
||||
if err := gofumptCmd.Run(); err != nil {
|
||||
return fmt.Errorf("运行 gofumpt 失败: %v", err)
|
||||
}
|
||||
|
||||
log.Info("格式化代码完成")
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user