2023-08-14 16:23:34 +08:00
|
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
2023-08-29 11:21:52 +08:00
|
|
|
|
"io/fs"
|
2023-08-14 16:23:34 +08:00
|
|
|
|
"log"
|
|
|
|
|
"os"
|
|
|
|
|
"os/exec"
|
|
|
|
|
"path/filepath"
|
2023-11-09 14:26:08 +08:00
|
|
|
|
"strings"
|
2023-08-14 16:23:34 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var (
|
|
|
|
|
basePath, _ = os.Getwd()
|
2023-08-29 11:21:52 +08:00
|
|
|
|
protoFolder = filepath.Join(basePath, "proto", "src")
|
|
|
|
|
protocPath = filepath.Join(basePath, "proto", "protoc-23.1", "bin", "win64", "protoc")
|
2023-08-14 16:23:34 +08:00
|
|
|
|
)
|
2023-08-29 17:38:20 +08:00
|
|
|
|
var goOutDir string = "./"
|
2023-08-14 16:23:34 +08:00
|
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
|
//先安装以下插件
|
|
|
|
|
//go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
|
2023-08-28 09:59:36 +08:00
|
|
|
|
args := os.Args
|
|
|
|
|
if len(args) >= 2 {
|
2023-08-29 17:38:20 +08:00
|
|
|
|
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])
|
2023-08-30 13:13:21 +08:00
|
|
|
|
goOutDir = "../"
|
2023-08-29 17:38:20 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
2023-08-28 09:59:36 +08:00
|
|
|
|
}
|
|
|
|
|
//
|
2023-08-14 16:23:34 +08:00
|
|
|
|
protoFiles := getProtoFiles()
|
|
|
|
|
// 编译proto文件为Go文件
|
|
|
|
|
if err := compileProto(protoFiles); err != nil {
|
|
|
|
|
log.Fatalf("编译proto文件失败:%v", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-29 11:21:52 +08:00
|
|
|
|
// 获取指定文件夹下的所有proto文件的绝对路径
|
2023-08-14 16:23:34 +08:00
|
|
|
|
func getProtoFiles() []string {
|
|
|
|
|
var protoFiles []string
|
2023-08-29 11:21:52 +08:00
|
|
|
|
err := filepath.WalkDir(protoFolder, func(path string, d fs.DirEntry, err error) error {
|
2023-11-09 14:26:08 +08:00
|
|
|
|
if !d.IsDir() && strings.HasSuffix(path, ".proto") {
|
2023-08-29 11:21:52 +08:00
|
|
|
|
protoFiles = append(protoFiles, path)
|
|
|
|
|
}
|
|
|
|
|
return err
|
|
|
|
|
})
|
2023-08-14 16:23:34 +08:00
|
|
|
|
if err != nil {
|
2023-08-29 11:21:52 +08:00
|
|
|
|
log.Fatal("获取proto文件列表失败:", err)
|
2023-08-14 16:23:34 +08:00
|
|
|
|
}
|
|
|
|
|
return protoFiles
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 编译proto文件为Go文件
|
|
|
|
|
func compileProto(protoFiles []string) error {
|
2023-08-29 11:21:52 +08:00
|
|
|
|
for _, fileName := range protoFiles {
|
2023-08-29 17:38:20 +08:00
|
|
|
|
cmd := exec.Command(protocPath, "-I="+protoFolder, fmt.Sprintf("--go_out=%s", goOutDir), fileName)
|
2023-08-14 16:23:34 +08:00
|
|
|
|
fmt.Println(cmd.String())
|
|
|
|
|
cmd.Stdout = os.Stdout
|
|
|
|
|
cmd.Stderr = os.Stderr
|
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|