Improve Python config file template substitution #8

Merged
Jan Lindemann merged 10 commits from jan/feature/20260609-pyproject-toml-add-mypypath into master 2026-06-09 08:13:09 +02:00 AGit
Showing only changes of commit 841fb8b361 - Show all commits

cmds.projects.lib.templates.tmpl_render(): search_path

Add an additional keyword-argument search_path to templates.tmpl_render(). It allows to specifiy a list of directory paths in which a template of a given name can be found. It defaults to [], in which case only the built-in templates are considered. Otherwise file locations are tried first, then the built-in templates.

Signed-off-by: Jan Lindemann <jan@janware.com>
Jan Lindemann 2026-06-02 21:08:00 +02:00
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61

View file

@ -1,6 +1,8 @@
import textwrap import textwrap
def format_lines(template, values, li_quote, li_delimiter): def format_lines(
template: str, values: dict[str, str], li_quote: bool, li_delimiter: str
) -> str:
def __format_value(val): def __format_value(val):
if not li_quote: if not li_quote:
@ -63,11 +65,31 @@ _templates = {
} }
def tmpl_render( def tmpl_render(
template_name: str, values, li_quote = False, li_delimiter = '\n' template_name: str,
values,
li_quote = False,
li_delimiter = '\n',
search_path: list[str] = []
) -> str: ) -> str:
return format_lines(
textwrap.dedent(_templates[template_name]), def __format(template: str) -> str:
values, return format_lines(
li_quote = li_quote, template,
li_delimiter = li_delimiter, values,
) li_quote = li_quote,
li_delimiter = li_delimiter,
)
for d in search_path:
path = d + '/' + template_name
try:
with open(path, 'r') as f:
template = f.read()
return __format(template)
except FileNotFoundError:
pass
raw = _templates.get(template_name, None)
if raw is None:
raise Exception(f'Failed to find template "{template_name}"')
return __format(textwrap.dedent(raw))