opencode-config/.opencode/templates/cli/hooks/pre_gen_project.py
Sergey e4f9313641
fix(templates): validate cookiecutter project_name as python identifier (#263)
* fix(templates): add pre_gen_project hook validating project_name identifier

* fix(templates): use valid identifier defaults in cookiecutter.json

* test(templates): add regression tests for project_name identifier validation

* fix(tests): resolve fullstack package name via backend ctx

---------

Co-authored-by: opencode-agent <agent@opencode.local>
2026-08-04 14:36:33 +03:00

34 lines
No EOL
1.1 KiB
Python

"""Pre-generation hook for the cli cookiecutter template.
Validates that ``project_name`` is a valid Python identifier so the
generated package dir + imports (``from <project_name>.X import Y``) do
not raise ``SyntaxError``. Hyphens, dots, spaces and leading digits are
rejected with a hint to use an underscore-separated name instead.
See issue #262: default ``my-cli`` used to render as
``from my-cli.core import app`` which is a ``SyntaxError`` (``-`` is not
allowed in a Python identifier).
"""
from __future__ import annotations
import re
import sys
_VALID_IDENTIFIER = re.compile(r"^[a-z][a-z0-9_]*$")
def main() -> None:
project_name = "{{ cookiecutter.project_name }}"
if not _VALID_IDENTIFIER.fullmatch(project_name):
sys.exit(
f"Invalid project_name: {project_name!r}\n"
"project_name must be a valid Python identifier matching "
"^[a-z][a-z0-9_]*$ (lowercase, no hyphens/dots/spaces, "
"no leading digit).\n"
f"Use 'my_cli' instead of 'my-cli' (or 'my.cli', 'my cli')."
)
if __name__ == "__main__":
main()