wheat-cache/shell/make-struct.py

86 lines
1.8 KiB
Python
Raw Permalink Normal View History

import os
import yaml
from jinja2 import Template
sysPath = os.getcwd()
2021-10-23 23:41:36 +08:00
tempPath = f"{sysPath}/storage/temp"
2021-09-19 10:37:30 +08:00
protobufPath = f"{sysPath}/protobuf"
2021-09-28 22:43:11 +08:00
storagePath = f"{sysPath}/storage"
2021-09-19 10:37:30 +08:00
class KeyMap(object):
def __init__(self, key: str, val) -> None:
self.key = key
self.val = val
2021-10-23 23:41:36 +08:00
self.upper = val
def go_fmt(path: str):
os.system(f"go fmt {path}")
2021-09-19 10:37:30 +08:00
def to_camel(val: str) -> str:
return "".join([k.capitalize() for k in val.split('_')])
2021-09-28 22:43:11 +08:00
class KeyOption(object):
def __init__(self, key, option):
2021-10-23 23:41:36 +08:00
self.key = key
2021-09-28 22:43:11 +08:00
self.option = option
def __str__(self):
return "{}:{}".format(self.key, self.option)
2021-09-19 10:37:30 +08:00
def load_template(name: str) -> str:
with open(f"{tempPath}/{name}", "r", encoding="utf-8") as fp:
return fp.read()
def load_conf():
2021-09-19 10:37:30 +08:00
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)
2021-09-19 10:37:30 +08:00
cfg_camel = {}
for key, val in cfg.items():
cfg_camel[key] = [to_camel(v) for v in val]
return cfg, cfg_camel
2021-09-19 10:37:30 +08:00
# 生成常量
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))
2021-09-19 10:37:30 +08:00
for val in v:
2021-10-23 23:41:36 +08:00
val_set.append(val)
template = Template(tem_text)
text = template.render(keys=keys, key_maps=key_map, sets=val_set)
2021-09-19 10:37:30 +08:00
2021-10-23 23:41:36 +08:00
temp_path = f"{tempPath}/const.gen.go"
2021-09-28 22:43:11 +08:00
with open(temp_path, 'w', encoding='utf-8') as f:
f.write(text)
def format_code_go():
2021-10-23 23:41:36 +08:00
go_fmt(f"{tempPath}/const.gen.go")
if __name__ == "__main__":
2021-09-19 10:37:30 +08:00
conf, cfg_camel = load_conf()
2021-10-23 23:41:36 +08:00
set_structure_const_template(cfg_camel)
# 格式化代码
format_code_go()