feat: 增加命令行工具的参数支持,包括路径、干运行模式和输出目录选项

This commit is contained in:
Rogee
2025-09-10 14:38:53 +08:00
parent 3b804b83da
commit 7187205143
7 changed files with 174 additions and 104 deletions

View File

@@ -9,16 +9,21 @@ import (
)
func CommandBuf(root *cobra.Command) {
cmd := &cobra.Command{
Use: "buf",
Short: "run buf commands",
RunE: commandBufE,
}
cmd := &cobra.Command{
Use: "buf",
Short: "run buf commands",
RunE: commandBufE,
}
cmd.Flags().String("dir", ".", "Directory to run buf from")
cmd.Flags().Bool("dry-run", false, "Preview buf command without executing")
root.AddCommand(cmd)
}
func commandBufE(cmd *cobra.Command, args []string) error {
dir := cmd.Flag("dir").Value.String()
dryRun, _ := cmd.Flags().GetBool("dry-run")
if _, err := exec.LookPath("buf"); err != nil {
log.Warn("buf 命令不存在,正在安装 buf...")
log.Info("go install github.com/bufbuild/buf/cmd/buf@v1.48.0")
@@ -33,9 +38,19 @@ func commandBufE(cmd *cobra.Command, args []string) error {
}
}
log.Info("buf 命令已存在,正在运行 buf generate...")
log.Info("PROTOBUF GUIDE: https://buf.build/docs/best-practices/style-guide/")
generateCmd := exec.Command("buf", "generate")
// preflight: ensure buf.yaml exists
if _, err := os.Stat(filepath.Join(dir, "buf.yaml")); err != nil {
log.Warnf("未找到 %sbuf generate 可能失败", filepath.Join(dir, "buf.yaml"))
}
log.Info("buf 命令已存在,正在运行 buf generate...")
log.Info("PROTOBUF GUIDE: https://buf.build/docs/best-practices/style-guide/")
if dryRun {
log.Infof("[dry-run] (cd %s && buf generate)", dir)
return nil
}
generateCmd := exec.Command("buf", "generate")
generateCmd.Dir = dir
if err := generateCmd.Run(); err != nil {
return fmt.Errorf("运行 buf generate 失败: %v", err)
}