diff --git a/new_python/render.py b/new_python/render.py new file mode 100644 index 0000000..802527d --- /dev/null +++ b/new_python/render.py @@ -0,0 +1,32 @@ +"""Render the project template into a mapping of relative paths to file contents.""" + +from pathlib import Path + +TEMPLATE_DIR = Path(__file__).resolve().parent.parent / "template" + +DEFAULT_PYTHON = "3.12.4" + + +def render(name: str, python_version: str = DEFAULT_PYTHON) -> dict[str, str]: + """Render the template for *name* into {relative path: content}. + + The package name is derived from *name* by replacing hyphens with + underscores. Every {{PKG}}, {{NAME}}, and {{PYVER}} token is substituted; + just's own {{args}} interpolation is left untouched. + """ + package = name.replace("-", "_") + substitutions = { + "{{PKG}}": package, + "{{NAME}}": name, + "{{PYVER}}": python_version, + } + files: dict[str, str] = {} + for path in sorted(TEMPLATE_DIR.rglob("*")): + if not path.is_file(): + continue + content = path.read_text() + for token, value in substitutions.items(): + content = content.replace(token, value) + files[path.relative_to(TEMPLATE_DIR).as_posix()] = content + files[f"{package}/__init__.py"] = "" + return files diff --git a/tests/test_render.py b/tests/test_render.py new file mode 100644 index 0000000..f87e65a --- /dev/null +++ b/tests/test_render.py @@ -0,0 +1,39 @@ +"""Tests for rendering the project template.""" + +from new_python.render import DEFAULT_PYTHON, render + +TEMPLATE_FILES = { + ".gitignore", + "AGENTS.md", + "Pipfile", + "conftest.py", + "hooks/pre-commit", + "justfile", + "pyproject.toml", +} + +TEMPLATE_TOKENS = ("{{PKG}}", "{{NAME}}", "{{PYVER}}") + + +def test_render_substitutes_all_tokens_for_a_dashed_name(): + """Rendering a dashed name derives the package and substitutes every token.""" + files = render("demo-project") + + assert set(files) == TEMPLATE_FILES | {"demo_project/__init__.py"} + assert files["demo_project/__init__.py"] == "" + + justfile = files["justfile"] + assert justfile.count("demo_project") == 7 + assert "{{args}}" in justfile + + assert 'known_first_party = ["demo_project"]' in files["pyproject.toml"] + assert files["AGENTS.md"].startswith("# demo-project\n") + assert f'python_version = "{DEFAULT_PYTHON}"' in files["Pipfile"] + + assert "Put the repo root on sys.path" in files["conftest.py"] + assert "__pycache__/" in files[".gitignore"] + assert "just ci" in files["hooks/pre-commit"] + + for rel, content in files.items(): + for token in TEMPLATE_TOKENS: + assert token not in content, f"{token} left unsubstituted in {rel}"