protoc-gen-ts/main.go

70 lines
1.5 KiB
Go

package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"git.apinb.com/bsm-sdk/core/utils"
"git.apinb.com/bsm-tools/protoc-gen-ts/internal/plugin"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/pluginpb"
)
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
os.Exit(1)
}
genConst()
}
func genConst() {
var body map[string][]*plugin.SrvMethod = make(map[string][]*plugin.SrvMethod)
for _, item := range plugin.AllSrvMethods {
name := strings.ToLower(item.PkgName)
body[name] = append(body[name], &item)
}
for name, item := range body {
constPath := "./sdk/typescript/" + name + "/const.ts"
var code string
for _, row := range item {
code += "/** " + strings.TrimSpace(row.Comment) + " */\n"
code += "/** Request: " + row.In + " */\n"
code += "/** Response: " + row.Out + " */\n"
code += fmt.Sprintf("export const URL_%s_%s = \"/%s.%s/%s\"\n", row.ServiceName, row.MethodName, name, row.ServiceName, row.MethodName)
code += "\n"
}
utils.StringToFile(constPath, code)
}
}
func run() error {
in, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
req := &pluginpb.CodeGeneratorRequest{}
if err := proto.Unmarshal(in, req); err != nil {
return err
}
resp, err := plugin.Generate(req)
if err != nil {
return err
}
out, err := proto.Marshal(resp)
if err != nil {
return err
}
if _, err := os.Stdout.Write(out); err != nil {
return err
}
return nil
}