From 7edf5a4c26e075fe34714519b0c46e2e465f7277 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 27 May 2026 18:27:32 +0200 Subject: [PATCH] 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 --- .../jw/pkg/cmds/projects/lib/templates.py | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/python/jw/pkg/cmds/projects/lib/templates.py diff --git a/src/python/jw/pkg/cmds/projects/lib/templates.py b/src/python/jw/pkg/cmds/projects/lib/templates.py new file mode 100644 index 00000000..eec74085 --- /dev/null +++ b/src/python/jw/pkg/cmds/projects/lib/templates.py @@ -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, + )