|
| 1 | +from collections.abc import Callable |
| 2 | +from pathlib import Path |
| 3 | +from time import perf_counter |
| 4 | + |
| 5 | +from fastapi_forge.io import ArtifactBuilder, create_fastapi_project_builder |
| 6 | +from fastapi_forge.logger import logger |
| 7 | +from fastapi_forge.schemas import ProjectSpec |
| 8 | + |
| 9 | +from .cookiecutter_adapter import CookiecutterAdapter, OverwriteCookiecutterAdapter |
| 10 | +from .project_validators import ProjectNameValidator, ProjectValidator |
| 11 | +from .template_processors import DefaultTemplateProcessor, TemplateProcessor |
| 12 | + |
| 13 | + |
| 14 | +class ProjectBuildDirector: |
| 15 | + def __init__( |
| 16 | + self, |
| 17 | + builder: ArtifactBuilder, |
| 18 | + template_processor: TemplateProcessor, |
| 19 | + template_generator: CookiecutterAdapter, |
| 20 | + template_resolver: Callable, |
| 21 | + project_validator: ProjectValidator | None = None, |
| 22 | + ): |
| 23 | + self.builder = builder |
| 24 | + self.validator = project_validator |
| 25 | + self.template_processor = template_processor |
| 26 | + self.template_generator = template_generator |
| 27 | + self.template_resolver = template_resolver |
| 28 | + |
| 29 | + async def build(self, spec: ProjectSpec) -> None: |
| 30 | + if self.validator: |
| 31 | + self.validator.validate(spec) |
| 32 | + await self.builder.build_artifacts() |
| 33 | + |
| 34 | + context = self.template_processor.process(spec) |
| 35 | + template_path = self.template_resolver() |
| 36 | + |
| 37 | + self.template_generator.generate( |
| 38 | + template_path=template_path, |
| 39 | + output_dir=Path.cwd().resolve(), |
| 40 | + extra_context=context, |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +def _get_template_path() -> Path: |
| 45 | + template_path = Path(__file__).resolve().parent.parent / "template" |
| 46 | + if not template_path.exists(): |
| 47 | + raise RuntimeError(f"Template directory not found: {template_path}") |
| 48 | + if not template_path.is_dir(): |
| 49 | + raise RuntimeError(f"Template path is not a directory: {template_path}") |
| 50 | + return template_path |
| 51 | + |
| 52 | + |
| 53 | +async def build_fastapi_project(spec: ProjectSpec) -> None: |
| 54 | + start_time = perf_counter() |
| 55 | + |
| 56 | + try: |
| 57 | + director = ProjectBuildDirector( |
| 58 | + builder=create_fastapi_project_builder(spec), |
| 59 | + project_validator=ProjectNameValidator(), |
| 60 | + template_processor=DefaultTemplateProcessor(), |
| 61 | + template_generator=OverwriteCookiecutterAdapter(), |
| 62 | + template_resolver=_get_template_path, |
| 63 | + ) |
| 64 | + |
| 65 | + await director.build(spec) |
| 66 | + |
| 67 | + build_time = perf_counter() - start_time |
| 68 | + logger.info(f"Project built successfully in {build_time:.2f} seconds.") |
| 69 | + |
| 70 | + except Exception as error: |
| 71 | + logger.error(f"Project build failed: {error}") |
| 72 | + raise |
0 commit comments