cmds.projects.lib.templates: Add module
Add tmpl_render(), a function to provide a primitive template renderer. It takes a dictionary for values to replace variables shaped {some-variable} in templates found by their name. For now, the templates are defined in the templates module instead of being read from a template directory. The values may be lists, in which case they are rendered with a delimiter, defaulting to ",".
Using an existing template engine like jinja2 is tempting but would introduce additional dependencies jw-pkg is trying hard to avoid.
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
4e15552fc2
commit
7edf5a4c26
1 changed files with 73 additions and 0 deletions
73
src/python/jw/pkg/cmds/projects/lib/templates.py
Normal file
73
src/python/jw/pkg/cmds/projects/lib/templates.py
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import textwrap
|
||||
|
||||
def format_lines(template, values, li_quote, li_delimiter):
|
||||
|
||||
def __format_value(val):
|
||||
if not li_quote:
|
||||
return str(val)
|
||||
return f'"{val}"'
|
||||
|
||||
for key, value in values.items():
|
||||
if isinstance(value, (list, tuple)):
|
||||
values[key] = li_delimiter.join(map(__format_value, value))
|
||||
|
||||
ret = []
|
||||
parts = template.splitlines(keepends = True)
|
||||
|
||||
for line in parts:
|
||||
for key, value in values.items():
|
||||
marker = '{' + key + '}'
|
||||
if marker in line:
|
||||
indent = line[:line.index(marker)]
|
||||
value = str(value).replace('\n', '\n' + indent)
|
||||
line = line.replace(marker, value)
|
||||
ret.append(line)
|
||||
|
||||
return ''.join(ret)
|
||||
|
||||
_templates = {
|
||||
'pkg-config':
|
||||
"""\
|
||||
prefix = {prefix}
|
||||
exec_prefix = {{prefix}}
|
||||
includedir = {{prefix}}/include
|
||||
libdir = {{exec_prefix}}/lib
|
||||
|
||||
Name: {name}
|
||||
Description: {description}
|
||||
Version: {version}
|
||||
""",
|
||||
'pyrightconfig.json':
|
||||
"""\
|
||||
{
|
||||
"extends": {base},
|
||||
"include": [
|
||||
{include}
|
||||
],
|
||||
"exclude": [
|
||||
"**/__pycache__",
|
||||
"**/.pytest_cache",
|
||||
"**/.mypy_cache",
|
||||
"**/.ruff_cache",
|
||||
"**/.venv",
|
||||
"**/build",
|
||||
"**/dist"
|
||||
],
|
||||
"extraPaths": [
|
||||
{extra_paths}
|
||||
],
|
||||
"typeCheckingMode": "basic",
|
||||
"pythonPlatform": "Linux"
|
||||
}
|
||||
""",
|
||||
}
|
||||
|
||||
def tmpl_render(
|
||||
template_name: str, values, li_quote = False, li_delimiter = '\n'
|
||||
) -> str:
|
||||
return format_lines(
|
||||
textwrap.dedent(_templates[template_name]),
|
||||
values,
|
||||
li_quote = li_quote,
|
||||
li_delimiter = li_delimiter,
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue