Improve Python config file template substitution #8
1 changed files with 30 additions and 8 deletions
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>
commit
841fb8b361
|
|
@ -1,6 +1,8 @@
|
|||
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):
|
||||
if not li_quote:
|
||||
|
|
@ -63,11 +65,31 @@ _templates = {
|
|||
}
|
||||
|
||||
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:
|
||||
|
||||
def __format(template: str) -> str:
|
||||
return format_lines(
|
||||
textwrap.dedent(_templates[template_name]),
|
||||
template,
|
||||
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))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue