rts-sim-module/proto/main.go

59 lines
1.3 KiB
Go
Raw Normal View History

2023-08-14 16:23:34 +08:00
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
)
var (
basePath, _ = os.Getwd()
protoFolder = filepath.Join(basePath, "src")
protocPath = filepath.Join(basePath, "protoc-23.1", "bin", "win64", "protoc")
)
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 {
//go run . component 编译组件proto
protoFolder = filepath.Join(protoFolder, args[1])
}
//
2023-08-14 16:23:34 +08:00
protoFiles := getProtoFiles()
// 编译proto文件为Go文件
if err := compileProto(protoFiles); err != nil {
log.Fatalf("编译proto文件失败%v", err)
}
}
// 获取指定文件夹下的所有proto文件的绝对路径列表
func getProtoFiles() []string {
var protoFiles []string
files, err := os.ReadDir(protoFolder)
if err != nil {
log.Fatal("获取proto文件列表失败")
}
for _, file := range files {
protoFiles = append(protoFiles, file.Name())
}
return protoFiles
}
// 编译proto文件为Go文件
func compileProto(protoFiles []string) error {
for _, protoFile := range protoFiles {
2023-08-23 15:13:06 +08:00
cmd := exec.Command(protocPath, "--proto_path="+protoFolder, "--go_out=../components", protoFile)
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
}