2024-06-07 18:38:38 +08:00
|
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"io/fs"
|
|
|
|
|
"log"
|
|
|
|
|
"os"
|
|
|
|
|
"os/exec"
|
|
|
|
|
"path/filepath"
|
|
|
|
|
"strings"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var (
|
|
|
|
|
basePath, _ = os.Getwd()
|
|
|
|
|
protoFolder = filepath.Join(basePath, "protodef", "src")
|
|
|
|
|
protocPath = filepath.Join(basePath, "protodef", "protoc-23.1", "bin", "win64", "protoc")
|
|
|
|
|
)
|
|
|
|
|
var goOutDir string = "./"
|
|
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
|
//先安装以下插件
|
|
|
|
|
//go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
|
|
|
|
|
args := os.Args
|
2024-06-19 19:29:46 +08:00
|
|
|
|
if len(args) < 3 {
|
|
|
|
|
log.Fatal("usage: go run protodef/main.go [path/to/proto/dir] [goOutDir]")
|
2024-06-07 18:38:38 +08:00
|
|
|
|
}
|
2024-06-19 19:29:46 +08:00
|
|
|
|
protoFolder = filepath.Join(basePath, args[1])
|
|
|
|
|
goOutDir = args[2]
|
|
|
|
|
|
|
|
|
|
log.Println(protoFolder, goOutDir)
|
|
|
|
|
// if len(args) >= 2 {
|
|
|
|
|
// switch {
|
|
|
|
|
// case args[1] == "component": //go run . component 编译组件proto
|
|
|
|
|
// {
|
|
|
|
|
// protocPath = filepath.Join(basePath, "protoc-23.1", "bin", "win64", "protoc")
|
|
|
|
|
// protoFolder = filepath.Join(basePath, "src", args[1])
|
|
|
|
|
// goOutDir = "../"
|
|
|
|
|
// }
|
|
|
|
|
// }
|
|
|
|
|
// }
|
2024-06-07 18:38:38 +08:00
|
|
|
|
//
|
2024-06-19 19:29:46 +08:00
|
|
|
|
// protoFolder = filepath.Join(basePath)
|
2024-06-07 18:38:38 +08:00
|
|
|
|
protoFiles := getProtoFiles()
|
2024-06-19 19:29:46 +08:00
|
|
|
|
log.Println(protoFiles)
|
2024-06-07 18:38:38 +08:00
|
|
|
|
// 编译proto文件为Go文件
|
|
|
|
|
if err := compileProto(protoFiles); err != nil {
|
|
|
|
|
log.Fatalf("编译proto文件失败:%v", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 获取指定文件夹下的所有proto文件的绝对路径
|
|
|
|
|
func getProtoFiles() []string {
|
|
|
|
|
var protoFiles []string
|
|
|
|
|
err := filepath.WalkDir(protoFolder, func(path string, d fs.DirEntry, err error) error {
|
|
|
|
|
if !d.IsDir() && strings.HasSuffix(path, ".proto") {
|
|
|
|
|
protoFiles = append(protoFiles, path)
|
|
|
|
|
}
|
|
|
|
|
return err
|
|
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Fatal("获取proto文件列表失败:", err)
|
|
|
|
|
}
|
|
|
|
|
return protoFiles
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 编译proto文件为Go文件
|
|
|
|
|
func compileProto(protoFiles []string) error {
|
|
|
|
|
for _, fileName := range protoFiles {
|
2024-06-19 19:29:46 +08:00
|
|
|
|
cmd := exec.Command(protocPath, "-I="+protoFolder, fmt.Sprintf("--go_out=%s", goOutDir), "--go_opt=paths=source_relative", fileName)
|
2024-06-07 18:38:38 +08:00
|
|
|
|
fmt.Println(cmd.String())
|
|
|
|
|
cmd.Stdout = os.Stdout
|
|
|
|
|
cmd.Stderr = os.Stderr
|
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|