From d500811b2835195ce2f21bf47d1ff149d48cca66 Mon Sep 17 00:00:00 2001 From: zqj <582132116@qq.com> Date: Wed, 6 Apr 2022 16:26:07 +0800 Subject: [PATCH] feat: 使用python3 自动生成proto文件 --- Makefile | 1 + tools/generator.py | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 0 deletions(-) create mode 100644 tools/generator.py diff --git a/Makefile b/Makefile index a75dd1a..ca9e078 100644 --- a/Makefile +++ b/Makefile @@ -7,6 +7,7 @@ DEBUG= gen: protoc -I./protos --go_out=./protos --go-grpc_out=./protos ./protos/*proto protoc-go-inject-tag -input=./pb/*.pb.go + python3 tools/generator.py test: go run cmd/test/client.go diff --git a/tools/generator.py b/tools/generator.py new file mode 100644 index 0000000..c8c447d --- /dev/null +++ b/tools/generator.py @@ -0,0 +1,67 @@ +import os + +ProtoCodeGO = './cmd/gameserver/action/protocode.go' +ProtoCodeFile = './protos/protocode.proto' +ProtoFileDir = "./protos" + +ProtoCodeStr = "syntax = \"proto3\";\noption go_package = \"../pb;pb\";\n\npackage protocode;\n\nenum ProtoCode\n{{\n " \ + "UNKNOWN = 0;\n {}\n}} " +ProtoCodeLineReq = "\t{}Req = {};\n" +ProtoCodeLineRsp = "\t{}Rsp = {};\n" + +GoProtoCodeStr = "package action\n\nimport (\n\t\"pro2d/common/logger\"\n\t\"pro2d/pb\"\n)\n\nfunc GetActionMap() " \ + "map[interface{{}}]interface{{}} {{\n\tlogger.Debug(\"init protocode...\")\n\tam := make(map[interface{{" \ + "}}]interface{{}})\n{}\n\treturn am\n}}" +GoProtoCodeLine = "\tam[uint32(pb.ProtoCode_{}Req)] = {}Rpc\n" + + +def generatorProto(path): + files = os.listdir(path) + code = 0 + ProtoCodeData = "" + GoCodeData = "" + for file in files: + if os.path.isdir(file): + continue + + with open(path + "/" + file, 'r', encoding='utf-8', errors='ignore') as f: + lines = f.readlines() # 读取所有行 + firstline = lines[0] + if firstline.find("proto3") == -1: + continue + + for line in lines: + if line.find("message") == -1: + continue + + sline = line.split(' ') + if len(sline) < 2: + continue + + messageStr = sline[1].replace('\n', '').replace('{', "") + n1 = messageStr.find('Req') + n2 = messageStr.find('Rsp') + + if n1 != -1: + code += 1 + ProtoCodeData += ProtoCodeLineReq.format(messageStr[:n1], code) + GoCodeData += GoProtoCodeLine.format(messageStr[:n1], messageStr[:n1]) + elif n2 != -1: + code += 1 + ProtoCodeData += ProtoCodeLineRsp.format(messageStr[:n2], code) + + # protocode.go + gostr = GoProtoCodeStr.format(GoCodeData) + fo = open(ProtoCodeGO, "w") + fo.write(gostr) + fo.close() + + #protocode.proto + protostr = ProtoCodeStr.format(ProtoCodeData) + fo = open(ProtoCodeFile, "w") + fo.write(protostr) + fo.close() + + +if __name__ == "__main__": + generatorProto(ProtoFileDir) -- libgit2 0.21.2