wheat-cache/shell/gen_protobuf.py

116 lines
3.7 KiB
Python
Raw Normal View History

import os
from typing import Dict, List
from jinja2 import Template
import yaml
sysPath = os.getcwd()
tempPath = f"{sysPath}/pkg/structure/generate"
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)
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
# 生成文件,并写入
def mkdir(cfg_camel):
path = "protobuf"
2021-09-21 10:11:13 +08:00
storagePath = f"{protobufPath}/storage.proto"
for key,value in cfg_camel.items():
'''生成、更新数据结构proto文件'''
proto_path = path + '/' + key + '.proto'
if not os.path.exists(proto_path): # 如果这个文件不存在
'''生成对应的数据结构proto文件'''
file = open(proto_path,'w')
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}')
file.close()
'''给strong.proto添加import该新的数据结构'''
import_structure = 'import "'+ key +'.proto";\n'
mess = 'message CommendResponse {\n'
with open(storagePath) as f:
line = f.readlines()
# print(line)
f.close
for i in range(len(line)):
if mess in line[i]:
break
line.insert(i,import_structure)
file = open(storagePath,'w')
for l in line:
file.write(l)
file.close()
i=0
for i in range(len(line)-1,0,-1):
if '}' in line[i]:
break
for v in value:
line.insert(i,' rpc '+ v +' ('+ v +'Request) returns (CommendResponse);\n')
file = open(storagePath,'w')
for l in line:
file.write(l)
file.close()
else: # 如果这个文件存在
with open(proto_path) as f:
line = f.readlines()
f.close()
for v in value:
function = v + 'Request'
flag = 0
for l in line:
if function in l:
flag=1
break
if flag == 0:
file = open(proto_path,'a')
file.write('\nmessage ' + v +'Request '+'{\n BaseKey key = 1;\n}')
file.close()
flag = 0
'''更新storage.proto文件'''
with open(storagePath) as f:
line = f.readlines()
f.close
for v in value:
flg=0
for l in range(len(line)):
if ' rpc '+ v +' ('+ v +'Request) returns (CommendResponse);\n' in line[l]:
flg = 1
break
if flg==0:
i=0
for i in range(len(line)-1,0,-1):
if '}' in line[i]:
break
2021-09-21 10:11:13 +08:00
line.insert(i,' rpc '+ v +' ('+ v +'Request) returns (CommendResponse);\n')
i=0
file = open(storagePath,'w')
for l in line:
file.write(l)
file.close()
2021-09-21 09:44:22 +08:00
2021-09-21 09:44:22 +08:00
if __name__ == "__main__":
conf, cfg_camel = load_conf()
2021-09-21 10:11:13 +08:00
print(cfg_camel)
mkdir(cfg_camel)
2021-09-21 10:11:13 +08:00