forked from p93542168/wheat-cache
93 lines
2.2 KiB
Python
93 lines
2.2 KiB
Python
import os
|
|
|
|
import yaml
|
|
from jinja2 import Template
|
|
|
|
sysPath = os.getcwd()
|
|
tempPath = f"{sysPath}/pkg/structure/generate"
|
|
structurePath = f"{sysPath}/pkg/structure"
|
|
protobufPath = f"{sysPath}/protobuf"
|
|
|
|
|
|
class KeyMap(object):
|
|
def __init__(self, key: str, val) -> None:
|
|
self.key = key
|
|
self.val = val
|
|
self.upper = [v.upper() for v in val]
|
|
|
|
|
|
def go_fmt(path: str):
|
|
os.system(f"go fmt {path}")
|
|
|
|
|
|
def to_camel(val: str) -> str:
|
|
return "".join([k.capitalize() for k in val.split('_')])
|
|
|
|
|
|
def load_template(name: str) -> str:
|
|
with open(f"{tempPath}/{name}", "r", encoding="utf-8") as fp:
|
|
return fp.read()
|
|
|
|
|
|
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():
|
|
cfg_camel[key] = [to_camel(v) for v in val]
|
|
|
|
return cfg, cfg_camel
|
|
|
|
|
|
# 生成常量
|
|
def set_structure_const_template(conf: dict):
|
|
tem_text = load_template("const.template")
|
|
keys = conf.keys()
|
|
key_map = []
|
|
val_set = []
|
|
for k, v in conf.items():
|
|
key_map.append(KeyMap(key=k, val=v))
|
|
|
|
for val in v:
|
|
val_set.append(val.upper())
|
|
|
|
template = Template(tem_text)
|
|
text = template.render(keys=keys, key_maps=key_map, sets=val_set)
|
|
|
|
temp_path = f"{tempPath}/structure.gen.go"
|
|
with open(temp_path, 'w', encoding='utf-8') as f:
|
|
f.write(text)
|
|
|
|
|
|
# 生成接口
|
|
def set_structure_interface(conf):
|
|
text = load_template("interface.template")
|
|
Dic = {}
|
|
template = Template(text)
|
|
for i in conf.keys():
|
|
x = i.lower().title()
|
|
Dic["".join(x.split("_"))] = conf[i]
|
|
yamlData = [Dic]
|
|
text = template.render(Data=yamlData)
|
|
temp_path = f"{structurePath}/interface.gen.go"
|
|
with open(temp_path, 'w', encoding='utf-8') as f:
|
|
f.write(text)
|
|
|
|
|
|
def format_code_go():
|
|
go_fmt(f"{structurePath}/interface.gen.go")
|
|
go_fmt(f"{structurePath}/generate/structure.gen.go")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
conf, cfg_camel = load_conf()
|
|
set_structure_const_template(conf)
|
|
set_structure_interface(cfg_camel)
|
|
# 格式化代码
|
|
format_code_go()
|