sdk_generate/internal/postprocess/postprocess.go

57 lines
1.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package postprocess
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
func Process(ctx context.Context, sdkPackage string) error {
// 确保 outputDir 存在
if err := os.MkdirAll(sdkPackage, 0755); err != nil {
return fmt.Errorf("创建输出目录失败: %w", err)
}
// 检查是否有 go.mod没有则初始化
goModPath := filepath.Join(sdkPackage, "go.mod")
if _, err := os.Stat(goModPath); os.IsNotExist(err) {
cmd := exec.Command("go", "mod", "init", sdkPackage)
cmd.Dir = sdkPackage
if err := cmd.Run(); err != nil {
// 忽略错误,可能已经有 go.mod 了
}
}
commands := []struct {
name string
args []string
desc string
}{
{"go", []string{"fmt", "./..."}, "格式化代码"},
{"go", []string{"mod", "tidy"}, "整理依赖"},
{"go", []string{"build", "./..."}, "编译检查"},
}
var errors []string
for _, cmdInfo := range commands {
c := exec.Command(cmdInfo.name, cmdInfo.args...)
c.Dir = sdkPackage
var stderr bytes.Buffer
c.Stderr = &stderr
if err := c.Run(); err != nil {
errors = append(errors, fmt.Sprintf("%s: %v\n%s", cmdInfo.desc, err, stderr.String()))
}
}
if len(errors) > 0 {
return fmt.Errorf("\n%s", strings.Join(errors, "\n"))
}
return nil
}