import textwrap def format_lines( template: str, values: dict[str, str], li_quote: bool, li_delimiter: str ) -> str: 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', search_path: list[str] = [] ) -> str: def __format(template: str) -> str: return format_lines( 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))