wheat-cache/shell/gen_protobuf.py

85 lines
2.7 KiB
Python
Raw Normal View History

import os
import yaml
sysPath = os.getcwd()
2021-10-24 00:34:43 +08:00
tempPath = f"{sysPath}/storage/temp"
structurePath = f"{sysPath}/pkg/structure"
protobufPath = f"{sysPath}/protobuf"
def to_camel(val: str) -> str:
return "".join([k.capitalize() for k in val.split('_')])
def load_conf():
conf_path = f"{tempPath}/tem.yaml"
with open(conf_path, 'r', encoding='utf-8') as f:
cfg = f.read()
cfg = yaml.load(cfg, Loader=yaml.FullLoader)
cfg_camel = {}
for key, val in cfg.items():
key = to_camel(key).lower()
cfg_camel[key] = [to_camel(v) for v in val]
return cfg, cfg_camel
2021-09-25 23:37:24 +08:00
# 生成对应的数据结构proto文件
2021-09-21 11:03:31 +08:00
def mk_structure(cfg_camel):
for key, value in cfg_camel.items():
2021-10-24 00:34:43 +08:00
proto_path = f"{protobufPath}/{key}.proto"
if not os.path.exists(proto_path): # 如果这个文件不存在
2021-09-21 10:11:13 +08:00
'''生成对应的数据结构proto文件'''
file = open(proto_path, 'w')
2021-09-21 10:11:13 +08:00
file.write('syntax = "proto3";\nimport "base.proto";\noption go_package = "pkg/proto";\n')
for v in value:
file.write('\nmessage ' + v + 'Request ' + '{\n BaseKey key = 1;\n}\n')
2021-10-05 16:39:00 +08:00
file.write('\nmessage ' + v + 'Response ' + '{\n}\n')
2021-09-21 10:11:13 +08:00
file.close()
else: # 如果这个文件存在
2021-09-21 11:03:31 +08:00
'''更新数据结构proto文件'''
2021-09-21 10:11:13 +08:00
with open(proto_path) as f:
line = f.readlines()
2021-09-21 10:11:13 +08:00
f.close()
for v in value:
function = v + 'Request'
flag = 0
for l in line:
if function in l:
flag = 1
2021-09-21 10:11:13 +08:00
break
if flag == 0:
file = open(proto_path, 'a')
file.write('\nmessage ' + v + 'Request ' + '{\n BaseKey key = 1;\n}\n')
2021-10-05 16:39:00 +08:00
file.write("\nmessage %sResponse {\n}\n" % v)
2021-09-21 10:11:13 +08:00
file.close()
2021-09-21 11:03:31 +08:00
print(f"{key}.proto", "-> success")
def mk_storage(cfg_camel):
storagePath = f"{protobufPath}/storage.proto"
file = open(storagePath, 'w')
file.write(
'// Code generated by gen-struct. DO NOT EDIT.\n// make gen-protobuf generated\n\nsyntax = "proto3";\n\noption go_package = "pkg/proto";\n\n')
for key, value in cfg_camel.items():
file.write('import "' + key + '.proto";\n')
2021-09-25 23:37:24 +08:00
file.write('\n\nservice CommServer {\n')
for key, value in cfg_camel.items():
2021-09-21 11:03:31 +08:00
for v in value:
2021-09-25 23:37:24 +08:00
file.write(' rpc ' + v + ' (' + v + 'Request) returns (%s);\n' % "{}Response".format(v))
2021-09-21 11:03:31 +08:00
file.write('}')
file.close()
print("storage.proto", "-> success")
2021-09-21 09:44:22 +08:00
2021-09-21 09:44:22 +08:00
if __name__ == "__main__":
2021-10-24 00:34:43 +08:00
_, cfg_camel = load_conf()
2021-09-21 11:03:31 +08:00
mk_structure(cfg_camel) # 生成对应的数据结构proto文件
mk_storage(cfg_camel)