diff options
author | crupest <crupest@outlook.com> | 2023-05-31 22:56:15 +0800 |
---|---|---|
committer | Yuqian Yang <crupest@crupest.life> | 2024-12-18 18:31:27 +0800 |
commit | 723c9a963a96b25a7498f3e0417307e89c8bb684 (patch) | |
tree | 3eff901a5b96eb4ff88d272bed4bb964c6397f1f /tools/cru-py/crupest/template.py | |
parent | 6e60bb06bd7a5052a7d6c2b5b8df0ab084697fdd (diff) | |
download | crupest-723c9a963a96b25a7498f3e0417307e89c8bb684.tar.gz crupest-723c9a963a96b25a7498f3e0417307e89c8bb684.tar.bz2 crupest-723c9a963a96b25a7498f3e0417307e89c8bb684.zip |
HALF WORK: for sync.
Diffstat (limited to 'tools/cru-py/crupest/template.py')
-rw-r--r-- | tools/cru-py/crupest/template.py | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/tools/cru-py/crupest/template.py b/tools/cru-py/crupest/template.py new file mode 100644 index 0000000..9747af1 --- /dev/null +++ b/tools/cru-py/crupest/template.py @@ -0,0 +1,32 @@ +import os.path +import re + + +class Template: + def __init__(self, template_path: str, var_prefix: str = "CRUPEST"): + if len(var_prefix) != 0 and re.fullmatch(r"^[a-zA-Z_][a-zA-Z0-9_]*$", var_prefix) is None: + raise ValueError("Invalid var prefix.") + self.template_path = template_path + self.template_name = os.path.basename( + template_path)[:-len(".template")] + with open(template_path, "r") as f: + self.template = f.read() + self.var_prefix = var_prefix + self.__var_regex = re.compile(r"\$(" + var_prefix + r"_[a-zA-Z0-9_]+)") + self.__var_brace_regex = re.compile( + r"\$\{\s*(" + var_prefix + r"_[a-zA-Z0-9_]+)\s*\}") + var_set = set() + for match in self.__var_regex.finditer(self.template): + var_set.add(match.group(1)) + for match in self.__var_brace_regex.finditer(self.template): + var_set.add(match.group(1)) + self.var_set = var_set + + def generate(self, config: dict) -> str: + result = self.template + for var in self.var_set: + if var not in config: + raise ValueError(f"Missing config var {var}.") + result = result.replace("$" + var, config[var]) + result = re.sub(r"\$\{\s*" + var + r"\s*\}", config[var], result) + return result |