Files
bortstack-forge/templates/flask-react/generate.py
T

66 lines
2.7 KiB
Python

#!/usr/bin/env python3
"""Generate an independent Flask/React project from Forge's migrated template."""
import argparse
import re
import shutil
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parent
TOKEN_FILES = (".env.example", "docker-compose.yml", "react/index.html",
"react/src/config/site.js", "react/src/components/Logo/Logo.jsx")
def generate(name, destination, git_init=False):
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9 _-]{0,79}", name):
raise ValueError("project name must use letters, numbers, spaces, underscores or hyphens")
slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
if not slug:
raise ValueError("project name needs a letter or number")
target = Path(destination).expanduser().resolve()
if target.exists() or target.is_symlink():
raise FileExistsError(f"destination already exists: {target}")
if target.is_relative_to(ROOT.parent.parent):
raise ValueError("destination must be outside the Forge repository")
if not target.parent.is_dir():
raise ValueError("destination parent must already exist")
target.mkdir()
try:
shutil.copytree(ROOT / "source", target, symlinks=False, dirs_exist_ok=True)
shutil.copytree(ROOT / "boilerplate", target, dirs_exist_ok=True)
values = {"__PROJECT_NAME__": name, "__APP_SLUG__": slug,
"__DATABASE_NAME__": slug.replace("-", "_")}
for relative in TOKEN_FILES:
path = target / relative
content = path.read_text(encoding="utf-8")
for token, value in values.items():
content = content.replace(token, value)
path.write_text(content, encoding="utf-8")
for relative in ("README.md", "docs/PROJECT_OVERVIEW.md", "docs/CURRENT_STATE.md",
"docs/DECISIONS.md", "docs/TASKS.md", "docs/HANDOFF.md"):
path = target / relative
path.write_text(path.read_text(encoding="utf-8").replace("__PROJECT_NAME__", name), encoding="utf-8")
if git_init:
subprocess.run(["git", "-C", str(target), "init", "--initial-branch=main"], check=True, capture_output=True)
except Exception:
shutil.rmtree(target, ignore_errors=True)
raise
return target
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("project_name")
parser.add_argument("destination")
parser.add_argument("--git-init", action="store_true")
args = parser.parse_args()
try:
print(f"Created {generate(args.project_name, args.destination, args.git_init)}")
except (OSError, ValueError, subprocess.CalledProcessError) as exc:
parser.exit(1, f"ERROR: {exc}\n")
if __name__ == "__main__":
main()