diff --git a/.github/workflows/template-security-scan.yml b/.github/workflows/template-security-scan.yml index faaf6c1d..0760c1f3 100644 --- a/.github/workflows/template-security-scan.yml +++ b/.github/workflows/template-security-scan.yml @@ -53,12 +53,20 @@ jobs: fi req_file="$template_dir/requirements.txt-tpl" + dev_req_file="$template_dir/requirements-dev.txt-tpl" if [ -f "$req_file" ]; then echo "๐Ÿ” Scanning $template_name..." - # Create temp requirements file + # One temp requirements file with the runtime pins and, when the + # template splits them out, the dev pins. The dev file's + # "-r requirements.txt" line is dropped: the runtime pins are + # already in the file and the include would not resolve here. temp_req=$(mktemp) cp "$req_file" "$temp_req" + if [ -f "$dev_req_file" ]; then + printf '\n' >> "$temp_req" + grep -v -E '^[[:space:]]*-r[[:space:]]' "$dev_req_file" >> "$temp_req" || true + fi audit_file="$TEMP_DIR/${template_name}.json" err_file="$TEMP_DIR/${template_name}.err" diff --git a/CHANGELOG.md b/CHANGELOG.md index 309fc128..7de896ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,12 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - Projects created with Poetry now get a working virtual environment and install with `poetry install`; fastkit sets `package-mode = false` so Poetry installs the dependencies without packaging the application. Poetry 2 or later is required: with an older Poetry, fastkit stops before creating anything, reports the version it found and explains how to upgrade or choose another package manager. - Projects created with PDM now get their `.venv` inside the project even when PDM is configured with `venv.in_project = false`, and `fastapi-hello` installs with PDM without being built as a package. - `list-templates` lists templates from the simplest to the most involved, in the same order on every operating system. `fastkit --help` has a one-sentence description and a "Start here" section. +- `startdemo` shows the template's runtime dependencies in its dependency table and `--dry-run` list, without comment lines or test tools, and the `--dry-run` file list matches the files that are written. Shell scripts in generated projects (`scripts/*.sh`) are executable. +- With `--no-venv`, `init` output no longer depends on which package managers are installed. If the requested package manager is not installed and an environment is being created, fastkit prints a warning and sets the project up for an available one; the project's metadata records the one actually used. +- `addroute` sorts generated and inserted imports the way isort (black profile) does, for any route name, including names that differ only by a number, and wraps an over-long inserted import. +- `startdemo` and `init` refuse to write through a symbolic link in the target directory and list the links before writing anything. +- When `startdemo` or `init` fails or is interrupted after overwriting files in an existing directory, those files get their original content back and the files the run created are removed; a file that cannot be restored keeps its original copy in a backup directory whose path is printed. An existing `.env` is kept even when a custom template ships one. +- `addroute` no longer treats a router registration or import under `if TYPE_CHECKING:` or `if False:` as present, and inserts imports below `from __future__` imports when the import anchor sits above them. ### `fastkit init` options @@ -60,6 +66,8 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - `classic-layered` and `domain-starter` wire every selected feature into the template's `main.py`. - Generated tests run against in-memory SQLite and do not export telemetry. - **Docker:** the image runs as a non-root user and has a healthcheck, `.dockerignore` is generated, compose points the app at its services, and `.env` is supplied at run time instead of copied into the image. **Loguru** is now configured at startup. +- **Dev tools:** test and lint tools (pytest and its plugins, ruff, pre-commit) stay out of runtime dependencies. They go to the dev dependency group and to a new `requirements-dev.txt` that includes `requirements.txt`. Generated Dockerfiles install runtime dependencies only; the Makefile, GitHub Actions workflow and devcontainer install `requirements-dev.txt`. +- **ruff:** projects created with the ruff option pass their own `ruff check`; generic classes use the Python 3.12 type parameter syntax. ### Templates @@ -71,6 +79,7 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - `fastapi-llm-agent`: the SSE stream is declared in OpenAPI, the calculator tool and the conversation store are bounded (`MAX_CONVERSATIONS`, `MAX_MESSAGES_PER_CONVERSATION`), and there are hook points for authentication and rate limiting. - Templates that store items in a JSON file no longer reuse ids, write atomically, and their tests no longer overwrite the shipped data. - Unused dependencies and `setup.cfg` files are removed. Template Dockerfiles run as a non-root user and ship a `.dockerignore`. +- `fastapi-sqlmodel`, `fastapi-auth-jwt` and `fastapi-llm-agent` ship a `requirements-dev.txt` for test and lint tools, and their Docker images no longer contain them. ### Documentation diff --git a/MANIFEST.in b/MANIFEST.in index 502804e8..b1fa7b8c 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,3 +4,6 @@ recursive-exclude src/fastapi_fastkit/fastapi_project_template *.pyo recursive-exclude src/fastapi_fastkit/fastapi_project_template __pycache__ recursive-include src/fastapi_fastkit/fragments * recursive-exclude src/fastapi_fastkit/fragments __pycache__ +recursive-include src/fastapi_fastkit/catalog *.toml +recursive-include src/fastapi_fastkit/catalog/i18n * +recursive-exclude src/fastapi_fastkit/catalog __pycache__ diff --git a/docs/en/contributing/development-setup.md b/docs/en/contributing/development-setup.md index f0219ac9..62cb3d17 100644 --- a/docs/en/contributing/development-setup.md +++ b/docs/en/contributing/development-setup.md @@ -254,6 +254,23 @@ anchors โ€” `fastkit addroute` inserts at them. The authoritative procedure lives next to the fragments themselves, in [`src/fastapi_fastkit/fragments/README.md`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fragments/README.md). +### Options live in one catalog + +The options `fastkit init` offers, their dependencies and the rules that +limit combinations come from `src/fastapi_fastkit/catalog/catalog.toml`. To +add an option: + +1. Add it to its axis in `catalog.toml` (`[[axes.options]]`, with its + packages and tags), and to the matching `*Choice` enum in + `src/fastapi_fastkit/core/settings.py`. The enum and the catalog list the + same options in the same order. +2. Teach `DynamicConfigGenerator` to generate it (see the fragments above). +3. Run `tests/test_catalog/test_agreement.py`; it fails when the enums, + the catalog and the generator disagree. + +Project generation is also available as a function without prompts or +subprocesses: `fastapi_fastkit.generation.generate(spec, target_dir)`. + ### Documentation Commands | Command | Description | diff --git a/docs/en/contributing/template-creation-guide.md b/docs/en/contributing/template-creation-guide.md index 96985731..2229a2f4 100644 --- a/docs/en/contributing/template-creation-guide.md +++ b/docs/en/contributing/template-creation-guide.md @@ -191,6 +191,35 @@ copy. project. The CLI is a development tool; a template's dependency list should contain only what the generated application itself imports. +### Register the Template in the Catalog + +A template directory is not enough. Add a `[[templates]]` entry to +`src/fastapi_fastkit/catalog/catalog.toml`, in the position where the +template should appear in `fastkit list-templates` (the file's order is the +display order): + +```toml +[[templates]] +id = "fastapi-your-template" +kind = "example" +description = "Your Template Title" +concepts = ["dependencies", "settings"] +``` + +- `id` is the template directory name. The entries and the directories under + `fastapi_project_template/` must be the same set. +- `description` must equal the first heading of `README.md-tpl` without the + `# `: with `# Your Template Title` on its first line, the description is + `Your Template Title`. +- `kind` is `level`, `example` or `internal`; new example projects use + `example`. +- `concepts` lists ids of the `[[concepts]]` entries in the same file; use + `[]` if none apply. + +`tests/test_catalog/test_agreement.py` fails when an entry and its directory +or README heading disagree, and the catalog loader rejects unknown keys or +concepts. + ### File Writing Guide #### 1. Writing main.py-tpl @@ -283,7 +312,10 @@ build-backend = "hatchling.build" #### 3. Writing requirements.txt-tpl (optional) Optional when `pyproject.toml-tpl` declares `[project].dependencies`. Still -useful for templates that prefer `pip`-only workflows. +useful for templates that prefer `pip`-only workflows. It lists runtime +dependencies only, because the Dockerfile installs it. Test and lint tools go +in `requirements-dev.txt-tpl`, which starts with `-r requirements.txt`, and +in the dev dependency group of `pyproject.toml-tpl`. Packages that do not install on every platform need an environment marker. `uvloop` does not support Windows, so templates pin it as @@ -305,6 +337,12 @@ python-dotenv==1.0.0 sqlalchemy==2.0.23 alembic==1.13.0 +``` + +```txt +# requirements-dev.txt-tpl +-r requirements.txt + # Development tools pytest==7.4.3 pytest-asyncio==0.21.1 diff --git a/docs/en/reference/translation-status.md b/docs/en/reference/translation-status.md index c11b0ab9..18ed8ed3 100644 --- a/docs/en/reference/translation-status.md +++ b/docs/en/reference/translation-status.md @@ -75,6 +75,18 @@ behaviour, the `doctor` output, and the `fastapi-hello` answer in `user-guide/choosing-a-starter`. Translated pages that describe these still show the earlier behaviour; follow the English pages. +**English pages changed for the development-dependency split (not yet +translated).** `fastkit init` projects and the `fastapi-sqlmodel`, +`fastapi-auth-jwt` and `fastapi-llm-agent` templates keep test and lint tools +out of `requirements.txt` and ship `requirements-dev.txt`. This is described +in the English pages only: `user-guide/cli-reference` (also the `testing` +default, `startdemo`, package manager fallback and `addroute` import order), +`user-guide/creating-projects`, `user-guide/quick-start`, `tutorial/sqlmodel`, +`tutorial/auth-jwt`, `tutorial/llm-agent`, `contributing/template-creation-guide` +(catalog entry for a new template) and `contributing/development-setup` +(adding an option). Translated pages still show the earlier behaviour; follow +the English pages. + *Snapshot verified 2026-10-14, after the v1.5.0 release. All six translated locales were brought to parity with the English sources: the three tutorials added in v1.4.0 were translated and every page that had drifted since its diff --git a/docs/en/tutorial/auth-jwt.md b/docs/en/tutorial/auth-jwt.md index 035f4b04..84c73cd3 100644 --- a/docs/en/tutorial/auth-jwt.md +++ b/docs/en/tutorial/auth-jwt.md @@ -58,7 +58,8 @@ startup, so there is nothing to install or configure first. Docs are at ``` accounts-api/ โ”œโ”€โ”€ pyproject.toml # PEP 621 metadata + [tool.fastapi-fastkit] -โ”œโ”€โ”€ requirements.txt +โ”œโ”€โ”€ requirements.txt # runtime dependencies (the Docker image installs these) +โ”œโ”€โ”€ requirements-dev.txt # + test and lint tools โ”œโ”€โ”€ alembic.ini โ”œโ”€โ”€ Dockerfile โ”œโ”€โ”€ .env # SECRET_KEY, DATABASE_URL, token lifetimes (git-ignored) @@ -320,6 +321,8 @@ comma-separated list of front-end origins. $ bash scripts/test.sh # or: pytest ``` +The test and lint tools are in `requirements-dev.txt` (and the dev dependency group), so install that file with pip. The Docker image installs `requirements.txt` only. + The suite runs `httpx.AsyncClient` against an in-memory SQLite database and covers the whole happy path โ€” register โ†’ login โ†’ me โ†’ refresh โ†’ logout โ€” plus the rejection paths that actually matter: wrong password, diff --git a/docs/en/tutorial/llm-agent.md b/docs/en/tutorial/llm-agent.md index 9736a007..2c4a84f8 100644 --- a/docs/en/tutorial/llm-agent.md +++ b/docs/en/tutorial/llm-agent.md @@ -67,7 +67,8 @@ $ bash scripts/chat.sh "What is 12 * 34?" ``` support-agent/ โ”œโ”€โ”€ pyproject.toml # PEP 621 metadata + [tool.fastapi-fastkit] -โ”œโ”€โ”€ requirements.txt +โ”œโ”€โ”€ requirements.txt # runtime dependencies (the Docker image installs these) +โ”œโ”€โ”€ requirements-dev.txt # + test and lint tools โ”œโ”€โ”€ Dockerfile โ”œโ”€โ”€ .env # local settings, git-ignored โ”œโ”€โ”€ .env.example # shareable copy with placeholder values @@ -227,6 +228,8 @@ the concrete class. $ bash scripts/test.sh # or: pytest ``` +The test and lint tools are in `requirements-dev.txt` (and the dev dependency group), so install that file with pip. The Docker image installs `requirements.txt` only. + `tests/conftest.py` replays scripted turns through a fake that mimics `AsyncAnthropic.messages.stream`. So the suite is deterministic, runs offline, costs nothing, and still covers the paths that matter: the diff --git a/docs/en/tutorial/sqlmodel.md b/docs/en/tutorial/sqlmodel.md index ea8045ca..a4edd0a6 100644 --- a/docs/en/tutorial/sqlmodel.md +++ b/docs/en/tutorial/sqlmodel.md @@ -49,7 +49,8 @@ no database server to install. Docs are at . ``` catalog-api/ โ”œโ”€โ”€ pyproject.toml # PEP 621 metadata + [tool.fastapi-fastkit] -โ”œโ”€โ”€ requirements.txt +โ”œโ”€โ”€ requirements.txt # runtime dependencies (the Docker image installs these) +โ”œโ”€โ”€ requirements-dev.txt # + test and lint tools โ”œโ”€โ”€ alembic.ini โ”œโ”€โ”€ Dockerfile โ”œโ”€โ”€ docker-compose.yml # local PostgreSQL / MySQL (profiles) @@ -305,6 +306,8 @@ changes: `src/app/db/url.py` picks the async driver for the URL, and $ bash scripts/test.sh # or: pytest ``` +The test and lint tools are in `requirements-dev.txt` (and the dev dependency group), so install that file with pip. The Docker image installs `requirements.txt` only. + Each test runs against a fresh in-memory SQLite database: no migrations, no fixture files, no cleanup between tests. To run them on PostgreSQL or MySQL, set `TEST_DATABASE_URL` to the `app_test` database the compose file diff --git a/docs/en/user-guide/cli-reference.md b/docs/en/user-guide/cli-reference.md index fec7ef73..14262fd2 100644 --- a/docs/en/user-guide/cli-reference.md +++ b/docs/en/user-guide/cli-reference.md @@ -241,6 +241,16 @@ CI or a piped run), fastkit refuses to overwrite anything unless `--yes` is given: `init` and `startdemo` exit with status 1 before writing any file. An existing `.env` is never overwritten (see [Generated `.env` file](#generated-env-file)). +fastkit never writes through a symbolic link in the target directory. If a +file it would write is a symlink, or one of its parent directories is a +symlink that leads outside the target, it lists those paths and exits with +status 1 before writing any file. If generation or the environment setup +fails after the overwrite (or you press Ctrl+C), the overwritten files get +their original content back and the files and directories the run created +are removed. If a file cannot be restored, its original copy stays in a +backup directory whose path fastkit prints. An existing `.venv` is not +restored. + #### Generated `.env` file Templates ship a shareable `.env.example`. fastkit creates the project's @@ -290,9 +300,10 @@ The `init` command will prompt you for: `fastkit init --interactive` walks a different, axis-based catalog instead of the minimal/standard/full stack above (source of truth: -`FastkitConfig.PACKAGE_CATALOG` in `core/settings.py`, and -`DynamicConfigGenerator.build_artifacts()` for what each choice generates). -Every axis defaults to `None` (skip); `utilities` and `tooling` are +`catalog/catalog.toml`, and `DynamicConfigGenerator.build_artifacts()` for +what each choice generates). +In the prompts every axis is pre-selected as `None` (skip) except `testing`, +which is pre-selected as `Coverage`; `utilities` and `tooling` are multi-select. Every selection now generates real code, not just installed packages โ€” see @@ -315,6 +326,8 @@ warnings) differ. | `logging` | structured, None | None (stdlib `logging` + `json` only) | `/logging_config.py` (structured JSON logging + request-id middleware), wired into `main.py` | | `deployment` (multi-select) | Docker, docker-compose | none | `Dockerfile` (non-root user, healthcheck on `/health`, `ENVIRONMENT=production`, no `.env` in the image), `.dockerignore`; docker-compose adds `docker-compose.yml` with the database / cache services, healthchecks and service URLs, reading `.env` at run time | +Test and lint tools (`pytest` and its plugins, `faker`, `factory-boy`, `ruff`, `pre-commit`) are development dependencies: they go to the dev dependency group and to `requirements-dev.txt` (which includes `requirements.txt`), not to the runtime dependencies. The generated `Dockerfile` installs `requirements.txt` only; the generated `Makefile`, GitHub Actions workflow and devcontainer install `requirements-dev.txt`. + CORS (off until `BACKEND_CORS_ORIGINS` is set) and pagination (`core/pagination.py`) are part of every project, so the menu does not offer them; saved configs that still list `CORS` or `Pagination` load and generate the same project. Regardless of selection, every generated project serves `GET /health` @@ -376,6 +389,7 @@ my-api/ โ”œโ”€โ”€ tests/ โ”œโ”€โ”€ scripts/ โ”œโ”€โ”€ requirements.txt +โ”œโ”€โ”€ requirements-dev.txt โ”œโ”€โ”€ setup.py โ””โ”€โ”€ README.md ``` @@ -521,8 +535,9 @@ api_router.include_router(health.router) Keep those comments in place when you edit the file. `addroute` registers the router below `# fastkit:routes` and adds the import in sorted position -below `# fastkit:imports` (or in its isort section higher up), so ruff stays -clean. An import is skipped only when the same names are already imported. +below `# fastkit:imports` (or in its isort section higher up), in the order isort +(black profile) would sort it, so ruff stays clean; an import that would be too +long is wrapped. An import is skipped only when the same names are already imported. A project that lost them (or was generated before the anchors existed) still works: fastkit falls back to an AST-based insertion that finds the import block and the @@ -624,6 +639,8 @@ $ fastkit startdemo [OPTIONS] | `--yes` / `-y` | Create the project without asking and, when deploying in place, overwrite existing files | off | | `--help` | Show command help | - | +The dependency table and the `--dry-run` list show the template's runtime dependencies (no comments, no test tools), and the `--dry-run` file list matches the files that are written. Shell scripts in the generated `scripts/` directory are executable. + Like `init`, `startdemo` refuses to run when the target project directory already exists (`Error: Project '{name}' already exists.`). `--dry-run` is the exception: since it never writes to disk, it is still allowed to target @@ -1019,7 +1036,7 @@ If virtual environment creation fails: ```console $ python -m venv .venv $ source .venv/bin/activate - $ pip install -r requirements.txt + $ pip install -r requirements-dev.txt ``` @@ -1174,7 +1191,9 @@ owns and keeps everything else, including the template's `requires-python`, dependency groups, other `[tool.*]` tables and comments. If fastkit cannot edit the file safely, it stops with an error; a `pyproject.toml` that is not valid TOML is kept as `pyproject.toml.bak` and replaced. These projects -also get a `requirements.txt` with the same dependencies. +also get a `requirements.txt` with the same runtime dependencies and a `requirements-dev.txt` that includes it and adds the test and lint tools. + +If the package manager you request is not installed and fastkit is creating an environment, `init` prints a warning and sets the project up for an available one; the `package_manager` in the project's `[tool.fastapi-fastkit]` block is the one actually used. With `--no-venv` the result does not depend on which package managers are installed. Generated Poetry projects require Poetry 2 or later. @@ -1254,7 +1273,7 @@ $ fastkit init --package-manager poetry ```console $ fastkit init --package-manager pip -# Creates requirements.txt +# Creates requirements.txt and requirements-dev.txt ``` @@ -1292,7 +1311,7 @@ poetry run pytest # Run commands in environment cd my-project source .venv/bin/activate # Linux/macOS .venv\Scripts\activate # Windows -pip install -r requirements.txt +pip install -r requirements-dev.txt pip install requests pytest ``` diff --git a/docs/en/user-guide/creating-projects.md b/docs/en/user-guide/creating-projects.md index 7ee0a8fa..c2c9b7bc 100644 --- a/docs/en/user-guide/creating-projects.md +++ b/docs/en/user-guide/creating-projects.md @@ -140,7 +140,8 @@ my-awesome-api/ โ”‚ โ”œโ”€โ”€ test.sh # Run tests โ”‚ โ”œโ”€โ”€ coverage.sh # Test coverage โ”‚ โ””โ”€โ”€ lint.sh # Code linting -โ”œโ”€โ”€ requirements.txt # Python dependencies +โ”œโ”€โ”€ requirements.txt # Runtime dependencies (what the Dockerfile installs) +โ”œโ”€โ”€ requirements-dev.txt # Adds test and lint tools to requirements.txt โ”œโ”€โ”€ pyproject.toml # Package and tool configuration โ”œโ”€โ”€ .env.example # Settings to share; .env is generated and git-ignored โ””โ”€โ”€ README.md # Project documentation @@ -249,14 +250,15 @@ poetry run pytest # Run tests **Generated files:** -- `requirements.txt` +- `requirements.txt` (runtime dependencies) +- `requirements-dev.txt` (includes `requirements.txt` and adds the test and lint tools) **Usage after creation:** ```console cd my-project source .venv/bin/activate # Linux/macOS .venv\Scripts\activate # Windows -pip install -r requirements.txt +pip install -r requirements-dev.txt pip install requests pytest ``` diff --git a/docs/en/user-guide/quick-start.md b/docs/en/user-guide/quick-start.md index 26814b7a..49714712 100644 --- a/docs/en/user-guide/quick-start.md +++ b/docs/en/user-guide/quick-start.md @@ -330,7 +330,7 @@ Each package manager creates its appropriate dependency files: - **UV/PDM**: `pyproject.toml` (PEP 621 format) - **Poetry**: `pyproject.toml` (Poetry format) -- **PIP**: `requirements.txt` +- **PIP**: `requirements.txt` and `requirements-dev.txt` (test and lint tools) ## 9. What's Next? diff --git a/src/fastapi_fastkit/backend/inspection/freshness.py b/src/fastapi_fastkit/backend/inspection/freshness.py index 4b55dbfd..aa4caf17 100644 --- a/src/fastapi_fastkit/backend/inspection/freshness.py +++ b/src/fastapi_fastkit/backend/inspection/freshness.py @@ -27,6 +27,8 @@ _VERSION_RE = re.compile(r"(\d+)\.(\d+)") #: Only exact/lower-bound pins carry a meaningful "current version". _PIN_OPERATORS = ("==", ">=", "~=") +#: Template requirements files whose pins are checked, in order. +REQUIREMENTS_FILES = ("requirements.txt-tpl", "requirements-dev.txt-tpl") def _pinned_version(requirement: str) -> Tuple[str, str]: @@ -69,8 +71,12 @@ def _collect_pins(ctx: InspectionContext) -> Dict[str, str]: """Map package name -> pinned version from the template's metadata files.""" pins: Dict[str, str] = {} - requirements_path = ctx.template_path / "requirements.txt-tpl" - if requirements_path.exists(): + # Runtime pins, then the dev pins that templates with a split + # requirements file keep next to them. + for file_name in REQUIREMENTS_FILES: + requirements_path = ctx.template_path / file_name + if not requirements_path.exists(): + continue try: with open(requirements_path, encoding="utf-8") as f: lines = f.read().splitlines() @@ -78,7 +84,8 @@ def _collect_pins(ctx: InspectionContext) -> Dict[str, str]: lines = [] for line in lines: line = line.strip() - if not line or line.startswith("#"): + # Comments and option lines ("-r requirements.txt"). + if not line or line.startswith(("#", "-")): continue name, version = _pinned_version(line) if name and version: diff --git a/src/fastapi_fastkit/backend/interactive/prompts.py b/src/fastapi_fastkit/backend/interactive/prompts.py index f140a2a8..50fb407d 100644 --- a/src/fastapi_fastkit/backend/interactive/prompts.py +++ b/src/fastapi_fastkit/backend/interactive/prompts.py @@ -12,26 +12,42 @@ # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- -from typing import Any, Dict, List, Optional, cast +from typing import Any, Callable, Dict, List, Optional import click -from fastapi_fastkit.backend.project_builder.config_generator import SQL_DATABASES from fastapi_fastkit.backend.project_builder.config_schema import combination_errors -from fastapi_fastkit.core.settings import ( - NONE_CHOICE, - FeatureAxis, - LoggingChoice, - MigrationsChoice, - ToolingChoice, - UtilityChoice, -) +from fastapi_fastkit.catalog import Axis, Option, load_catalog +from fastapi_fastkit.core.settings import NONE_CHOICE, FeatureAxis, MigrationsChoice from fastapi_fastkit.utils.main import console, print_error -from .selectors import BUILT_IN_UTILITIES, render_selection_table +from .selectors import render_selection_table from .validators import validate_email_format, validate_project_name +def _axis(axis_id: str) -> Axis: + """The catalog axis whose options, texts and default a prompt shows.""" + return load_catalog().axis(axis_id) + + +def _packages_text(option: Option) -> str: + """``Packages: a, b`` (``Packages: None`` when the option adds nothing).""" + return f"Packages: {', '.join(option.packages) or 'None'}" + + +def _option_texts(axis: Axis, fallback: Callable[[Option], str]) -> Dict[str, str]: + """Option id -> the catalog summary, or ``fallback(option)`` without one.""" + return { + option.id: option.summary if option.summary is not None else fallback(option) + for option in axis.options + } + + +def _default_index(axis: Axis) -> int: + """1-based position of the axis' default option.""" + return axis.choice_ids.index(axis.default) + 1 + + def prompt_basic_info() -> Dict[str, str]: """ Prompt for basic project information. @@ -189,25 +205,22 @@ def prompt_database_selection(settings: Any) -> Dict[str, Any]: console.print("\n[bold cyan]๐Ÿ—„๏ธ Database Selection[/bold cyan]") console.print("[dim]Choose your database backend[/dim]\n") - db_catalog = settings.PACKAGE_CATALOG["database"] - options = { - name: f"Packages: {', '.join(pkgs) if pkgs else 'None'}" - for name, pkgs in db_catalog.items() - } + axis = _axis(FeatureAxis.DATABASE) + options = _option_texts(axis, _packages_text) render_selection_table("Database Options", options) choice = click.prompt( "\nSelect database", type=click.IntRange(1, len(options)), - default=len(options), # Default to "None" + default=_default_index(axis), ) - selected_type = list(options.keys())[choice - 1] + selected = axis.options[choice - 1] return { - "type": selected_type, - "packages": db_catalog[selected_type], + "type": selected.id, + "packages": list(selected.packages), } @@ -224,32 +237,19 @@ def prompt_authentication_selection(settings: Any) -> str: console.print("\n[bold cyan]๐Ÿ” Authentication Selection[/bold cyan]") console.print("[dim]Choose your authentication strategy[/dim]\n") - auth_catalog = settings.PACKAGE_CATALOG["authentication"] - options = {} - - for name, pkgs in auth_catalog.items(): - if name == "None": - options[name] = "No authentication" - elif name == "JWT": - options[name] = "OAuth2 password flow with JWT (recommended for APIs)" - elif name == "OAuth2": - options[name] = "OAuth2 with authlib" - elif name == "FastAPI-Users": - options[name] = "Complete user management (JWT; SQL databases only)" - elif name == "Session-based": - options[name] = "Traditional session-based authentication" - else: - options[name] = f"Packages: {', '.join(pkgs)}" + axis = _axis(FeatureAxis.AUTHENTICATION) + options = _option_texts(axis, _packages_text) render_selection_table("Authentication Options", options) choice = click.prompt( "\nSelect authentication method", type=click.IntRange(1, len(options)), - default=len(options), # Default to "None" + default=_default_index(axis), ) - return cast(str, list(options.keys())[choice - 1]) + selected: str = list(options.keys())[choice - 1] + return selected def prompt_async_tasks_selection(settings: Any) -> str: @@ -265,21 +265,19 @@ def prompt_async_tasks_selection(settings: Any) -> str: console.print("\n[bold cyan]โšก Background Tasks Selection[/bold cyan]") console.print("[dim]Choose a task queue for background processing[/dim]\n") - task_catalog = settings.PACKAGE_CATALOG["async_tasks"] - options = { - name: f"Packages: {', '.join(pkgs) if pkgs else 'None'}" - for name, pkgs in task_catalog.items() - } + axis = _axis(FeatureAxis.ASYNC_TASKS) + options = _option_texts(axis, _packages_text) render_selection_table("Task Queue Options", options) choice = click.prompt( "\nSelect task queue", type=click.IntRange(1, len(options)), - default=len(options), # Default to "None" + default=_default_index(axis), ) - return cast(str, list(options.keys())[choice - 1]) + selected: str = list(options.keys())[choice - 1] + return selected def prompt_caching_selection(settings: Any) -> str: @@ -295,21 +293,19 @@ def prompt_caching_selection(settings: Any) -> str: console.print("\n[bold cyan]๐Ÿ’พ Caching Selection[/bold cyan]") console.print("[dim]Add caching layer for better performance[/dim]\n") - cache_catalog = settings.PACKAGE_CATALOG["caching"] - options = { - name: f"Packages: {', '.join(pkgs) if pkgs else 'None'}" - for name, pkgs in cache_catalog.items() - } + axis = _axis(FeatureAxis.CACHING) + options = _option_texts(axis, _packages_text) render_selection_table("Caching Options", options) choice = click.prompt( "\nSelect caching", type=click.IntRange(1, len(options)), - default=len(options), # Default to "None" + default=_default_index(axis), ) - return cast(str, list(options.keys())[choice - 1]) + selected: str = list(options.keys())[choice - 1] + return selected def prompt_monitoring_selection(settings: Any) -> str: @@ -325,30 +321,19 @@ def prompt_monitoring_selection(settings: Any) -> str: console.print("\n[bold cyan]๐Ÿ“Š Monitoring & Logging Selection[/bold cyan]") console.print("[dim]Add monitoring and logging capabilities[/dim]\n") - monitoring_catalog = settings.PACKAGE_CATALOG["monitoring"] - options = {} - - for name, pkgs in monitoring_catalog.items(): - if name == "None": - options[name] = "No additional monitoring" - elif name == "Loguru": - options[name] = "Enhanced logging with Loguru" - elif name == "OpenTelemetry": - options[name] = "Distributed tracing and metrics" - elif name == "Prometheus": - options[name] = "Prometheus metrics instrumentation" - else: - options[name] = f"Packages: {', '.join(pkgs)}" + axis = _axis(FeatureAxis.MONITORING) + options = _option_texts(axis, _packages_text) render_selection_table("Monitoring Options", options) choice = click.prompt( "\nSelect monitoring", type=click.IntRange(1, len(options)), - default=len(options), # Default to "None" + default=_default_index(axis), ) - return cast(str, list(options.keys())[choice - 1]) + selected: str = list(options.keys())[choice - 1] + return selected def prompt_testing_selection(settings: Any) -> str: @@ -364,30 +349,19 @@ def prompt_testing_selection(settings: Any) -> str: console.print("\n[bold cyan]๐Ÿงช Testing Framework Selection[/bold cyan]") console.print("[dim]Choose testing tools and coverage[/dim]\n") - testing_catalog = settings.PACKAGE_CATALOG["testing"] - options = {} - - for name, pkgs in testing_catalog.items(): - if name == "None": - options[name] = "No testing framework" - elif name == "Basic": - options[name] = "pytest + httpx for API testing" - elif name == "Coverage": - options[name] = "Basic + code coverage" - elif name == "Advanced": - options[name] = "Coverage + faker + factory-boy for fixtures" - else: - options[name] = f"Packages: {', '.join(pkgs)}" + axis = _axis(FeatureAxis.TESTING) + options = _option_texts(axis, _packages_text) render_selection_table("Testing Options", options) choice = click.prompt( "\nSelect testing framework", type=click.IntRange(1, len(options)), - default=2, # Default to "Basic" + default=_default_index(axis), # "Coverage" ) - return cast(str, list(options.keys())[choice - 1]) + selected: str = list(options.keys())[choice - 1] + return selected def prompt_utilities_selection(settings: Any) -> List[str]: @@ -410,22 +384,18 @@ def prompt_utilities_selection(settings: Any) -> List[str]: "[dim]Select additional utilities (comma-separated numbers, e.g., 1,2)[/dim]\n" ) - utilities_catalog = settings.PACKAGE_CATALOG["utilities"] - options = [] - descriptions = {} - - for name, pkgs in utilities_catalog.items(): - # Built-in behaviour is described above rather than offered as a - # choice; the catalog keeps the values so saved configs still load. - if name in BUILT_IN_UTILITIES or name == NONE_CHOICE: - continue - options.append(name) - if name == UtilityChoice.RATE_LIMITING: - descriptions[name] = "Per-client API rate limits (limits)" - elif name == UtilityChoice.WEBSOCKET: - descriptions[name] = "Example WebSocket endpoint (websockets)" - else: - descriptions[name] = f"({', '.join(pkgs)})" + # Built-in behaviour is described above rather than offered as a + # choice; the catalog keeps the values so saved configs still load. + offered = _axis(FeatureAxis.UTILITIES).offered + options = [option.id for option in offered] + descriptions = { + option.id: ( + option.summary + if option.summary is not None + else f"({', '.join(option.packages)})" + ) + for option in offered + } for i, option in enumerate(options, 1): desc = descriptions.get(option, "") @@ -460,27 +430,19 @@ def prompt_logging_selection(settings: Any) -> str: console.print("\n[bold cyan]๐Ÿชต Logging Format[/bold cyan]") console.print("[dim]Choose how the application emits its logs[/dim]\n") - logging_catalog = settings.PACKAGE_CATALOG[FeatureAxis.LOGGING] - descriptions = { - LoggingChoice.STRUCTURED: ( - "JSON logs + X-Request-ID correlation middleware (stdlib only)" - ), - LoggingChoice.NONE: "Uvicorn's default plain-text logging", - } - options = { - name: descriptions.get(name, f"Packages: {', '.join(pkgs) or 'None'}") - for name, pkgs in logging_catalog.items() - } + axis = _axis(FeatureAxis.LOGGING) + options = _option_texts(axis, _packages_text) render_selection_table("Logging Options", options) choice = click.prompt( "\nSelect logging format", type=click.IntRange(1, len(options)), - default=len(options), # Default to "None" + default=_default_index(axis), ) - return cast(str, list(options.keys())[choice - 1]) + selected: str = list(options.keys())[choice - 1] + return selected def prompt_migrations_selection(settings: Any, database_type: str = "None") -> str: @@ -501,27 +463,28 @@ def prompt_migrations_selection(settings: Any, database_type: str = "None") -> s console.print("\n[bold cyan]๐Ÿงฌ Database Migrations[/bold cyan]") console.print("[dim]Version-control your database schema[/dim]\n") - migrations_catalog = settings.PACKAGE_CATALOG[FeatureAxis.MIGRATIONS] - is_sql = database_type in SQL_DATABASES + axis = _axis(FeatureAxis.MIGRATIONS) + try: + database = _axis(FeatureAxis.DATABASE).option(database_type) + except KeyError: + is_sql = False + else: + is_sql = "sql" in database.tags - descriptions = { - MigrationsChoice.ALEMBIC: ( - "alembic.ini + async alembic/env.py + scripts/migrate.sh" - + ( - " [bold green](recommended for SQL databases)[/bold green]" - if is_sql - else " [yellow](needs a relational database)[/yellow]" - ) - ), - MigrationsChoice.NONE: "No migration tooling", - } - options = {name: descriptions.get(name, "") for name in migrations_catalog} + options = _option_texts(axis, lambda option: "") + options[MigrationsChoice.ALEMBIC] += ( + " [bold green](recommended for SQL databases)[/bold green]" + if is_sql + else " [yellow](needs a relational database)[/yellow]" + ) render_selection_table("Migration Options", options) option_names = list(options.keys()) default_idx = ( - option_names.index(MigrationsChoice.ALEMBIC) + 1 if is_sql else len(options) + option_names.index(MigrationsChoice.ALEMBIC) + 1 + if is_sql + else _default_index(axis) ) choice = click.prompt( @@ -530,7 +493,8 @@ def prompt_migrations_selection(settings: Any, database_type: str = "None") -> s default=default_idx, ) - return cast(str, option_names[choice - 1]) + selected: str = option_names[choice - 1] + return selected def prompt_tooling_selection(settings: Any) -> List[str]: @@ -548,16 +512,10 @@ def prompt_tooling_selection(settings: Any) -> List[str]: "[dim]Select tooling to generate (comma-separated numbers, e.g., 1,3)[/dim]\n" ) - tooling_catalog = settings.PACKAGE_CATALOG[FeatureAxis.TOOLING] - descriptions = { - ToolingChoice.RUFF: "ruff + ruff-format config in pyproject.toml (replaces black/isort)", - ToolingChoice.PRE_COMMIT: ".pre-commit-config.yaml", - ToolingChoice.GITHUB_ACTIONS: ".github/workflows/test.yml (Python 3.12)", - ToolingChoice.DEVCONTAINER: ".devcontainer/devcontainer.json", - ToolingChoice.MAKEFILE: "Makefile with install/test/lint/format/run", - } + offered = _axis(FeatureAxis.TOOLING).offered + descriptions = {option.id: option.summary or "" for option in offered} - options = [name for name in tooling_catalog if name != NONE_CHOICE] + options = [option.id for option in offered] for i, option in enumerate(options, 1): console.print( f" [cyan]{i}[/cyan]. {option} [dim]{descriptions.get(option, '')}[/dim]" @@ -588,17 +546,9 @@ def prompt_deployment_options() -> List[str]: console.print("\n[bold cyan]๐Ÿš€ Deployment Configuration[/bold cyan]") console.print("[dim]Select deployment options (comma-separated numbers)[/dim]\n") - options = [ - "Docker", - "docker-compose", - "None", - ] - - descriptions = { - "Docker": "Generate Dockerfile", - "docker-compose": "Generate docker-compose.yml (includes Docker)", - "None": "No deployment configuration", - } + axis = _axis("deployment") + options = list(axis.choice_ids) + descriptions = _option_texts(axis, lambda option: "") for i, option in enumerate(options, 1): desc = descriptions.get(option, "") @@ -607,12 +557,12 @@ def prompt_deployment_options() -> List[str]: choice = click.prompt( "\nSelect deployment option", type=click.IntRange(1, len(options)), - default=3, # Default to "None" + default=_default_index(axis), # "None" ) selected = options[choice - 1] - if selected == "None": + if selected == NONE_CHOICE: return [] elif selected == "docker-compose": return ["Docker", "docker-compose"] @@ -633,14 +583,13 @@ def prompt_package_manager_selection(settings: Any) -> str: console.print("\n[bold cyan]๐Ÿ“ฆ Package Manager Selection[/bold cyan]") console.print("[dim]Choose your preferred package manager[/dim]\n") - options = {} - for manager, config in settings.PACKAGE_MANAGER_CONFIG.items(): - options[manager] = config["description"] + catalog = load_catalog() + options = {manager.id: manager.description for manager in catalog.package_managers} render_selection_table("Package Managers", options) # Find default index - default_idx = list(options.keys()).index(settings.DEFAULT_PACKAGE_MANAGER) + 1 + default_idx = list(options.keys()).index(catalog.defaults.package_manager) + 1 choice = click.prompt( "\nSelect package manager", @@ -648,7 +597,8 @@ def prompt_package_manager_selection(settings: Any) -> str: default=default_idx, ) - return cast(str, list(options.keys())[choice - 1]) + selected: str = list(options.keys())[choice - 1] + return selected def prompt_custom_packages() -> List[str]: diff --git a/src/fastapi_fastkit/backend/interactive/selectors.py b/src/fastapi_fastkit/backend/interactive/selectors.py index 5c9993f3..91656c17 100644 --- a/src/fastapi_fastkit/backend/interactive/selectors.py +++ b/src/fastapi_fastkit/backend/interactive/selectors.py @@ -13,12 +13,18 @@ from rich.panel import Panel from rich.table import Table -from fastapi_fastkit.core.settings import NONE_CHOICE, FeatureAxis, UtilityChoice +from fastapi_fastkit.catalog import load_catalog +from fastapi_fastkit.core.settings import NONE_CHOICE, FeatureAxis from fastapi_fastkit.utils.main import console -#: Utilities every generated project has anyway. They stay in the catalog -#: (configs saved with them keep loading) but are not offered as choices. -BUILT_IN_UTILITIES = frozenset({UtilityChoice.CORS, UtilityChoice.PAGINATION}) +#: Utilities every generated project has anyway (``built_in`` in the +#: catalog). They stay in the catalog (configs saved with them keep loading) +#: but are not offered as choices. +BUILT_IN_UTILITIES = frozenset( + option.id + for option in load_catalog().axis(FeatureAxis.UTILITIES).options + if option.built_in +) def render_selection_table( diff --git a/src/fastapi_fastkit/backend/interactive/validators.py b/src/fastapi_fastkit/backend/interactive/validators.py index 1e73159b..7d3dee6a 100644 --- a/src/fastapi_fastkit/backend/interactive/validators.py +++ b/src/fastapi_fastkit/backend/interactive/validators.py @@ -11,6 +11,7 @@ import re from typing import Any, Dict, List, Optional, Tuple +from fastapi_fastkit.catalog import evaluate, selection_from_config from fastapi_fastkit.utils.main import REGEX as EMAIL_REGEX @@ -96,6 +97,8 @@ def validate_feature_compatibility( Validates that selected features don't have conflicting requirements. Selections that cannot be generated together (FastAPI-Users without a SQL database) make the configuration incompatible; the message says why. + Both the errors and the informational notes (Redis shared by caching and + the task queue) are the catalog's rules. Args: config: Project configuration dictionary @@ -103,35 +106,11 @@ def validate_feature_compatibility( Returns: Tuple of (is_compatible, warning_or_error_message) """ - # Imported lazily: the project builder package imports this module. - from fastapi_fastkit.backend.project_builder.config_schema import ( - combination_errors, - ) - - errors = combination_errors(config) - if errors: - return False, " | ".join(errors) - - warnings = [] - - # Check if Celery is selected with Redis - if config.get("async_tasks") == "Celery" or config.get("async_tasks") == "Dramatiq": - # These already include Redis in their dependencies - pass - - # Check if caching Redis is selected along with task queue Redis - cache_type = config.get("caching", "None") - task_type = config.get("async_tasks", "None") - if cache_type == "Redis" and task_type in ["Celery", "Dramatiq"]: - # This is actually compatible, just a note - warnings.append( - "Info: Redis will be used for both caching and task queue (shared dependency)." - ) - - # If there are warnings, return them - if warnings: - return True, " | ".join(warnings) - + outcome = evaluate(selection_from_config(config)) + if outcome.errors: + return False, " | ".join(outcome.errors) + if outcome.notes: + return True, " | ".join(outcome.notes) return True, None diff --git a/src/fastapi_fastkit/backend/main.py b/src/fastapi_fastkit/backend/main.py index 93219be5..cbe25bb2 100644 --- a/src/fastapi_fastkit/backend/main.py +++ b/src/fastapi_fastkit/backend/main.py @@ -12,7 +12,7 @@ import sys import tokenize import tomllib -from typing import Any, Dict, Iterable, List, Optional +from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence import click @@ -27,11 +27,22 @@ PyprojectMergeError, replace_project_dependencies, ) +from fastapi_fastkit.backend.package_managers.requirements import ( + write_requirements_files, +) from fastapi_fastkit.backend.project_builder.preset_layout import ( app_module_from_main_path, ) +from fastapi_fastkit.backend.route_format import NaturalKey, natural_key from fastapi_fastkit.backend.route_plan import RoutePlan -from fastapi_fastkit.backend.route_wiring import router_alias +from fastapi_fastkit.backend.route_wiring import ( + TYPING_MODULES, + live_branches, + reachable_nodes, + router_alias, + static_truth, + typing_names, +) from fastapi_fastkit.backend.transducer import copy_and_convert_template from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import settings @@ -127,47 +138,21 @@ def find_template_core_modules(project_dir: str) -> Dict[str, str]: def read_template_stack(template_path: str) -> List[str]: """ - Read dependencies from a template's metadata files. - - Lookup order preserves legacy behaviour for templates that still ship - ``requirements.txt-tpl`` while allowing modern pyproject-first templates - to resolve their stack from ``pyproject.toml-tpl``: + Read a template's runtime dependencies. - 1. ``requirements.txt-tpl`` (legacy, highest precedence) - 2. ``pyproject.toml-tpl`` ``[project].dependencies`` - 3. ``setup.py-tpl`` ``install_requires`` + ``pyproject.toml-tpl`` is read first (``[project].dependencies``), then + ``requirements.txt-tpl`` (comments, option lines and development tools + left out), then ``setup.py-tpl``. See + :func:`fastapi_fastkit.generation.dependencies.template_dependencies`, + which also returns the development dependencies. :param template_path: Path to the template directory :return: List of PEP 508 requirement strings """ - req_file = os.path.join(template_path, "requirements.txt-tpl") - if os.path.exists(req_file): - try: - with open(req_file, "r", encoding="utf-8") as f: - deps = [dep.strip() for dep in f.readlines() if dep.strip()] - return deps - except (OSError, UnicodeDecodeError) as e: - debug_log( - f"Error reading template dependencies from {req_file}: {e}", "error" - ) - return [] - - pyproject_file = os.path.join(template_path, "pyproject.toml-tpl") - if os.path.exists(pyproject_file): - deps = _parse_pyproject_dependencies(pyproject_file) - if deps: - return deps - - setup_file = os.path.join(template_path, "setup.py-tpl") - if os.path.exists(setup_file): - try: - with open(setup_file, "r", encoding="utf-8") as f: - content = f.read() - return _parse_setup_dependencies(content) - except (OSError, UnicodeDecodeError) as e: - debug_log(f"Error reading setup.py template: {e}", "error") + # Imported lazily: the generation package imports this module. + from fastapi_fastkit.generation.dependencies import template_dependencies - return [] + return list(template_dependencies(template_path).runtime) def _parse_setup_dependencies(content: str) -> List[str]: @@ -543,11 +528,16 @@ def inject_project_metadata( ENV_EXAMPLE_FILE = ".env.example" ENV_FILE = ".env" +#: Printed whenever generation leaves an existing ``.env`` as it is. +ENV_KEPT_MESSAGE = f"Keeping the existing {ENV_FILE}; it was not regenerated." + # A non-commented ``SECRET_KEY=`` assignment, optionally ``export``-prefixed. _SECRET_KEY_LINE = re.compile(r"^([ \t]*(?:export[ \t]+)?SECRET_KEY[ \t]*=).*$", re.M) -def render_local_env(example_content: str) -> str: +def render_local_env( + example_content: str, secret_factory: Optional[Callable[[], str]] = None +) -> str: """ Build the content of a local ``.env`` from a ``.env.example``. @@ -557,15 +547,18 @@ def render_local_env(example_content: str) -> str: reaches a running app. Everything else is kept verbatim. :param example_content: Text of the project's ``.env.example`` + :param secret_factory: Returns one key per call; defaults to + ``secrets.token_urlsafe(32)``. Tests inject a seeded factory. :return: Text for the project's ``.env`` """ + new_secret = secret_factory or (lambda: secrets.token_urlsafe(32)) content = example_content.replace("\r\n", "\n").replace("\r", "\n") - return _SECRET_KEY_LINE.sub( - lambda match: match.group(1) + secrets.token_urlsafe(32), content - ) + return _SECRET_KEY_LINE.sub(lambda match: match.group(1) + new_secret(), content) -def create_local_env_file(project_dir: str) -> Optional[str]: +def create_local_env_file( + project_dir: str, secret_factory: Optional[Callable[[], str]] = None +) -> Optional[str]: """ Create the project's local ``.env`` from its ``.env.example``. @@ -577,6 +570,7 @@ def create_local_env_file(project_dir: str) -> Optional[str]: printed. :param project_dir: Path to the generated project + :param secret_factory: Passed to :func:`render_local_env` :return: Absolute path of the ``.env`` that was written, or None when the project has no ``.env.example`` or already has a ``.env`` :raises BackendExceptions: If the file cannot be read or written @@ -587,7 +581,7 @@ def create_local_env_file(project_dir: str) -> Optional[str]: if not os.path.isfile(example_path): return None if os.path.lexists(env_path): - print_info(f"Keeping the existing {ENV_FILE}; it was not regenerated.") + print_info(ENV_KEPT_MESSAGE) return None try: @@ -596,14 +590,14 @@ def create_local_env_file(project_dir: str) -> Optional[str]: except (OSError, UnicodeDecodeError) as e: raise BackendExceptions(f"Failed to read {ENV_EXAMPLE_FILE}: {e}") from e - content = render_local_env(example_content) + content = render_local_env(example_content, secret_factory) try: # "x" refuses to clobber a .env that appeared since the check above. with open(env_path, "x", encoding="utf-8", newline="\n") as f: f.write(content) except FileExistsError: - print_info(f"Keeping the existing {ENV_FILE}; it was not regenerated.") + print_info(ENV_KEPT_MESSAGE) return None except OSError as e: raise BackendExceptions(f"Failed to create {ENV_FILE}: {e}") from e @@ -1186,45 +1180,60 @@ def generate_dependency_file_with_manager( author: str = "", author_email: str = "", description: str = "", + *, + dev_dependencies: Optional[Sequence[str]] = None, ) -> None: """ - Generate a dependency file using the specified package manager. + Generate a dependency file for the specified package manager. + + The file is rendered for ``manager_type`` whether or not that tool is + installed: rendering never probes the system, so the output does not + depend on the machine it runs on. :param project_dir: Path to the project directory - :param dependencies: List of dependency specifications + :param dependencies: Runtime dependency specifications :param manager_type: Type of package manager to use :param project_name: Name of the project :param author: Author name :param author_email: Author email :param description: Project description + :param dev_dependencies: Development dependencies. ``None`` leaves the + development declarations as they are and writes a single + ``requirements.txt`` for pip compatibility; a list is written to the + manager's dev group and to ``requirements-dev.txt``. :return: None :raises: BackendExceptions if dependency file generation fails """ try: package_manager = PackageManagerFactory.create_manager( - manager_type, project_dir, auto_detect=True + manager_type, project_dir, probe=False ) package_manager.generate_dependency_file( - dependencies, project_name, author, author_email, description + dependencies, + project_name, + author, + author_email, + description, + dev_dependencies=dev_dependencies, ) - # Also generate requirements.txt for pip compatibility. Decided by the - # manager actually in use: auto-detection may have replaced the - # requested one, and a stale template requirements.txt would then - # disagree with pyproject.toml. - if package_manager.get_dependency_file_name() != "requirements.txt": - from pathlib import Path - - requirements_path = Path(project_dir) / "requirements.txt" - try: + # Also generate requirements.txt (and requirements-dev.txt) for pip + # compatibility. + if package_manager.get_dependency_file_name() == "requirements.txt": + return + try: + if dev_dependencies is None: write_generated_text( - requirements_path, "".join(f"{dep}\n" for dep in dependencies) + os.path.join(project_dir, "requirements.txt"), + "".join(f"{dep}\n" for dep in dependencies), ) - debug_log("Generated requirements.txt for pip compatibility", "info") - except (OSError, UnicodeEncodeError) as e: - debug_log( - f"Warning: Could not generate requirements.txt: {e}", "warning" + else: + write_requirements_files( + project_dir, dependencies, list(dev_dependencies) ) + debug_log("Generated requirements.txt for pip compatibility", "info") + except (OSError, UnicodeEncodeError) as e: + debug_log(f"Warning: Could not generate requirements.txt: {e}", "warning") except Exception as e: debug_log(f"Error generating dependency file with {manager_type}: {e}", "error") @@ -1430,26 +1439,60 @@ def insert_import_line(content: str, import_line: str) -> str: if placed is not None: return placed + lines = content.split("\n") + future_end = _future_imports_end(content) + anchors = _anchor_line_numbers(content, IMPORT_ANCHOR) + if anchors and anchors[0] <= future_end: + # Nothing may precede a ``from __future__`` import: an anchor above + # one cannot be honoured, the import goes right below the last one. + lines.insert(future_end, import_line) + return "\n".join(lines) + anchored = _insert_after_anchor(content, IMPORT_ANCHOR, import_line) if anchored is not None: return anchored - lines = content.split("\n") insert_at = _last_import_line(content) lines.insert(insert_at, import_line) return "\n".join(lines) -def _module_level_imports(body: List[ast.stmt]) -> Iterable[ast.stmt]: - """Imports binding module-level names (also inside ``if`` / ``try``).""" +def _future_imports_end(content: str) -> int: + """1-based last line of the module's ``from __future__`` imports, else 0.""" + try: + tree = ast.parse(content) + except SyntaxError: + return 0 + end = 0 + for node in tree.body: + if isinstance(node, ast.ImportFrom) and node.module == "__future__": + end = node.end_lineno or node.lineno + return end + + +def _module_level_imports( + body: List[ast.stmt], typing_aliases: frozenset[str] = TYPING_MODULES +) -> Iterable[ast.stmt]: + """ + Imports binding module-level names at runtime (also inside ``if`` / + ``try``). Branches that never run (``if TYPE_CHECKING:``, ``if False:``, + the ``else`` of ``if True:``) are left out; see + :func:`~fastapi_fastkit.backend.route_wiring.static_truth`. + """ for node in body: if isinstance(node, (ast.Import, ast.ImportFrom)): yield node - elif isinstance(node, (ast.If, ast.Try, ast.With)): + elif isinstance(node, ast.If): + yield from _module_level_imports( + live_branches(node, typing_aliases), typing_aliases + ) + elif isinstance(node, (ast.Try, ast.With)): for field in ("body", "orelse", "finalbody"): - yield from _module_level_imports(getattr(node, field, [])) + yield from _module_level_imports( + getattr(node, field, []), typing_aliases + ) for handler in getattr(node, "handlers", []): - yield from _module_level_imports(handler.body) + yield from _module_level_imports(handler.body, typing_aliases) def _import_bindings(nodes: Iterable[ast.stmt]) -> set[tuple[Any, ...]]: @@ -1481,7 +1524,9 @@ def _import_already_present(content: str, import_line: str) -> bool: new_nodes, tree = [], None wanted = _import_bindings(new_nodes) if tree is not None and wanted: - return wanted <= _import_bindings(_module_level_imports(tree.body)) + return wanted <= _import_bindings( + _module_level_imports(tree.body, typing_names(tree)) + ) target = import_line.strip() return any(line.strip() == target for line in content.splitlines()) @@ -1495,11 +1540,12 @@ def _import_already_present(content: str, import_line: str) -> bool: _SECTION_FIRST_PARTY, _SECTION_LOCAL = 3, 4 -def _import_sort_key(node: ast.stmt) -> Optional[tuple[int, int, str]]: +def _import_sort_key(node: ast.stmt) -> Optional[tuple[int, int, NaturalKey]]: """isort / ruff sort key of a top-level import: (section, kind, module). Within a section ruff's defaults put ``import x`` before ``from x import - y`` and compare module names case-insensitively. + y`` and compare module names case-insensitively, numbers by value + (``orders9`` before ``orders10``). """ if isinstance(node, ast.Import): module, level, kind = node.names[0].name, 0, 0 @@ -1519,7 +1565,7 @@ def _import_sort_key(node: ast.stmt) -> Optional[tuple[int, int, str]]: section = _SECTION_STDLIB else: section = _SECTION_THIRD_PARTY - return section, kind, module.lower() + return section, kind, natural_key(module) def _insert_import_sorted(content: str, import_line: str) -> Optional[str]: @@ -1712,14 +1758,31 @@ def statement_present(content: str, statement: str) -> bool: return statement.strip() in code_without_comments(content) if not wanted: return True - for node in ast.walk(tree): - body = getattr(node, "body", None) - if not isinstance(body, list): - continue - dumped = [ast.dump(child) for child in body if isinstance(child, ast.stmt)] - for start in range(len(dumped) - len(wanted) + 1): - if dumped[start : start + len(wanted)] == wanted: - return True + # A copy in a branch that never runs (``if TYPE_CHECKING:``) does not + # count; one inside a function does (an app factory), and so does one in + # any block of a ``try`` / ``for`` / ``while`` (``else``, ``finally``, + # ``except``). + aliases = typing_names(tree) + for node in reachable_nodes(tree, aliases): + if isinstance(node, ast.If): + truth = static_truth(node.test, aliases) + blocks = [node.body] if truth is not False else [] + if truth is not True: + blocks.append(node.orelse) + else: + blocks = [ + block + for block in ( + getattr(node, field, None) + for field in ("body", "orelse", "finalbody") + ) + if isinstance(block, list) + ] + for block in blocks: + dumped = [ast.dump(child) for child in block if isinstance(child, ast.stmt)] + for start in range(len(dumped) - len(wanted) + 1): + if dumped[start : start + len(wanted)] == wanted: + return True return False @@ -2009,6 +2072,37 @@ def _versioned_include( return main_content, "app.include_router(api_router)" +def _includes_api_router(content: str) -> bool: + """Whether ``app.include_router(api_router, ...)`` runs in ``content``. + + A call in a branch that never runs (``if TYPE_CHECKING:``) does not + count; see :func:`~fastapi_fastkit.backend.route_wiring.reachable_nodes`. + A module that does not parse falls back to a text search without + comments. + """ + try: + tree = ast.parse(content) + except SyntaxError: + return "app.include_router(api_router" in code_without_comments(content) + for node in reachable_nodes(tree): + if not ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "include_router" + and isinstance(node.func.value, ast.Name) + and node.func.value.id == "app" + ): + continue + router = node.args[0] if node.args else None + if router is None: + router = next( + (item.value for item in node.keywords if item.arg == "router"), None + ) + if isinstance(router, ast.Name) and router.id == "api_router": + return True + return False + + def _plan_main_app( plan: RoutePlan, src_dir: str, @@ -2017,10 +2111,11 @@ def _plan_main_app( router_module: str, ) -> None: router_import = f"from {router_module} import api_router" - router_include = "app.include_router(api_router" code = code_without_comments(main_content) - if router_import in code and router_include in code: + if _import_already_present(main_content, router_import) and _includes_api_router( + main_content + ): # Router already fully configured, nothing to do return @@ -2033,7 +2128,7 @@ def _plan_main_app( main_content = insert_import_line(main_content, router_import) - if router_include not in code_without_comments(main_content): + if not _includes_api_router(main_content): main_content, include = _versioned_include( plan, src_dir, main_py_path, main_content, router_module ) @@ -2117,6 +2212,23 @@ def ask_create_project_folder(project_name: str) -> bool: ) +def deployment_message(user_local: str, project_name: str, create_folder: bool) -> str: + """ + The line printed before a template is deployed. + + :param user_local: User's workspace directory + :param project_name: Name of the project + :param create_folder: Whether the project goes into a new folder + :return: Message text + """ + if create_folder: + return ( + f"FastAPI template project will deploy at '{user_local}' " + f"in folder '{project_name}'" + ) + return f"FastAPI template project will deploy directly at '{user_local}'" + + def deploy_template_files( target_template: str, user_local: str, project_name: str, create_folder: bool ) -> tuple[str, str, List[str]]: @@ -2131,19 +2243,16 @@ def deploy_template_files( file list lets callers keep later rewriting passes scoped to what this deployment actually wrote. """ + message = deployment_message(user_local, project_name, create_folder) if create_folder: project_dir = os.path.join(user_local, project_name) - deployment_message = f"FastAPI template project will deploy at '{user_local}' in folder '{project_name}'" copied = copy_and_convert_template(target_template, user_local, project_name) else: project_dir = user_local - deployment_message = ( - f"FastAPI template project will deploy directly at '{user_local}'" - ) copied = copy_and_convert_template(target_template, user_local, "") - click.echo(deployment_message) - return project_dir, deployment_message, copied + click.echo(message) + return project_dir, message, copied def deploy_template_with_folder_option( diff --git a/src/fastapi_fastkit/backend/package_managers/base.py b/src/fastapi_fastkit/backend/package_managers/base.py index 99619a0f..cb1cbe98 100644 --- a/src/fastapi_fastkit/backend/package_managers/base.py +++ b/src/fastapi_fastkit/backend/package_managers/base.py @@ -8,7 +8,7 @@ import subprocess from abc import ABC, abstractmethod from pathlib import Path -from typing import Any, Callable, Dict, List, Mapping, Optional +from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import settings @@ -119,15 +119,23 @@ def generate_dependency_file( author: str = "", author_email: str = "", description: str = "", + *, + dev_dependencies: Optional[Sequence[str]] = None, ) -> None: """ Generate a dependency file with the given dependencies and metadata. - :param dependencies: List of dependency specifications + :param dependencies: List of runtime dependency specifications :param project_name: Name of the project :param author: Author name :param author_email: Author email :param description: Project description + :param dev_dependencies: Development dependencies. ``None`` leaves the + development declarations as they are; a list (even an empty one) + is written as the project's development dependencies, exactly as + given (uv / PDM: ``[dependency-groups].dev``, Poetry: + ``[tool.poetry.group.dev.dependencies]``, pip: + ``requirements-dev.txt``) """ pass diff --git a/src/fastapi_fastkit/backend/package_managers/factory.py b/src/fastapi_fastkit/backend/package_managers/factory.py index 6e67864b..8906c6bb 100644 --- a/src/fastapi_fastkit/backend/package_managers/factory.py +++ b/src/fastapi_fastkit/backend/package_managers/factory.py @@ -34,7 +34,11 @@ class PackageManagerFactory: @classmethod def create_manager( - self, manager_type: str, project_dir: str, auto_detect: bool = False + self, + manager_type: str, + project_dir: str, + auto_detect: bool = False, + probe: bool = True, ) -> BasePackageManager: """ Create a package manager instance. @@ -42,6 +46,10 @@ def create_manager( :param manager_type: Type of package manager ('pip', 'uv', 'pdm', 'poetry') :param project_dir: Path to the project directory :param auto_detect: If True, auto-detect available package manager when requested type is not available + :param probe: If False, the tool is not looked for on the system + (``is_available()`` is never called and ``auto_detect`` is + ignored): the manager of the requested type is returned as is. + Rendering dependency files needs no installed tool. :return: Package manager instance :raises: BackendExceptions if manager type is not supported or not available """ @@ -58,6 +66,14 @@ def create_manager( manager_class = self._managers[manager_type] manager = manager_class(project_dir) + if not probe: + debug_log( + f"Created {manager_type} package manager for {project_dir} " + "(not probed)", + "info", + ) + return manager + # Check if the manager is available on the system if not manager.is_available(): if auto_detect: @@ -108,6 +124,43 @@ def _auto_detect_manager( debug_log(error_msg, "error") raise BackendExceptions(error_msg) + @classmethod + def detect_manager(self, project_dir: str, prefer: str) -> str: + """ + Pick the package manager to set a project up with. + + :param project_dir: Path to the project directory + :param prefer: The requested manager type + :return: ``prefer`` when it is installed, else the first installed + manager of :attr:`DETECTION_ORDER` + :raises BackendExceptions: if ``prefer`` is not a supported manager, + or no package manager is available on the system + """ + prefer = prefer.lower() + if prefer not in self._managers: + available_managers = list(self._managers.keys()) + error_msg = ( + f"Unsupported package manager: {prefer}. " + f"Available: {available_managers}" + ) + debug_log(error_msg, "error") + raise BackendExceptions(error_msg) + + if self._managers[prefer](project_dir).is_available(): + return prefer + + debug_log(f"{prefer} is not available, looking for an alternative", "warning") + for manager_type in self.DETECTION_ORDER: + if manager_type == prefer or manager_type not in self._managers: + continue + if self._managers[manager_type](project_dir).is_available(): + debug_log(f"Auto-detected package manager: {manager_type}", "info") + return manager_type + + error_msg = "No package manager is available on the system" + debug_log(error_msg, "error") + raise BackendExceptions(error_msg) + @classmethod def get_available_managers(self) -> list[str]: """ diff --git a/src/fastapi_fastkit/backend/package_managers/pdm_manager.py b/src/fastapi_fastkit/backend/package_managers/pdm_manager.py index be648a6e..eedc5c3f 100644 --- a/src/fastapi_fastkit/backend/package_managers/pdm_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/pdm_manager.py @@ -7,7 +7,7 @@ import subprocess import sys from pathlib import Path -from typing import Dict, List, Union +from typing import Dict, List, Optional, Sequence, Union from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import DEFAULT_REQUIRES_PYTHON, settings @@ -20,6 +20,7 @@ from .pyproject import ( append_tool_table_to_file, render_dependency_array, + replace_dev_declarations, toml_string, update_pep621_pyproject, ) @@ -167,6 +168,8 @@ def generate_dependency_file( author: str = "", author_email: str = "", description: str = "", + *, + dev_dependencies: Optional[Sequence[str]] = None, ) -> None: """ Write the dependencies and metadata into pyproject.toml. @@ -183,20 +186,31 @@ def generate_dependency_file( :param author: Author name :param author_email: Author email :param description: Project description + :param dev_dependencies: Development dependencies written as + ``[dependency-groups].dev`` (the table is created when missing) + and to an existing ``dev`` extra (:func:`replace_dev_declarations`); + ``None`` leaves the development declarations as they are """ pyproject_path = self.get_dependency_file_path() + def with_dev_group(content: str) -> str: + if dev_dependencies is None: + return content + return replace_dev_declarations(content, dev_dependencies) + try: - fresh_content = _pdm_pyproject( - dependencies, - project_name or "fastapi-project", - description or "A FastAPI project", - author or "Author", - author_email or "author@example.com", + fresh_content = with_dev_group( + _pdm_pyproject( + dependencies, + project_name or "fastapi-project", + description or "A FastAPI project", + author or "Author", + author_email or "author@example.com", + ) ) self._write_pyproject( - lambda existing: update_pep621_pyproject( - existing, fresh_content, dependencies + lambda existing: with_dev_group( + update_pep621_pyproject(existing, fresh_content, dependencies) ), fresh_content, ) diff --git a/src/fastapi_fastkit/backend/package_managers/pip_manager.py b/src/fastapi_fastkit/backend/package_managers/pip_manager.py index 1ef2d205..e81a4205 100644 --- a/src/fastapi_fastkit/backend/package_managers/pip_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/pip_manager.py @@ -4,7 +4,7 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import sys -from typing import List +from typing import List, Optional, Sequence from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import settings @@ -18,6 +18,8 @@ ) from .base import BasePackageManager +from .pyproject import sync_pyproject_dev_file +from .requirements import REQUIREMENTS_DEV_FILE, write_requirements_files logger = get_logger(__name__) @@ -76,6 +78,11 @@ def install_dependencies(self, venv_path: str, upgrade_pip: bool = False) -> Non """ venv_path = self._ensure_venv(venv_path) requirements_path = self._require_dependency_file("Requirements file not found") + # requirements-dev.txt pulls in requirements.txt and adds the + # development tools, as uv / PDM / Poetry install the dev group. + dev_requirements_path = self.project_dir / REQUIREMENTS_DEV_FILE + if dev_requirements_path.is_file(): + requirements_path = dev_requirements_path pip_path = self.get_executable_path("pip", venv_path) @@ -105,16 +112,32 @@ def generate_dependency_file( author: str = "", author_email: str = "", description: str = "", + *, + dev_dependencies: Optional[Sequence[str]] = None, ) -> None: """ Generate a requirements.txt file with the given dependencies. - :param dependencies: List of dependency specifications + With ``dev_dependencies`` a ``requirements-dev.txt`` is written next + to it (``-r requirements.txt`` plus the development dependencies), and + the dev declarations a project ``pyproject.toml`` already has are set + to the same list (:func:`sync_pyproject_dev_file`). + + :param dependencies: List of runtime dependency specifications :param project_name: Name of the project (not used for pip) :param author: Author name (not used for pip) :param author_email: Author email (not used for pip) :param description: Project description (not used for pip) + :param dev_dependencies: Development dependencies for + ``requirements-dev.txt``; ``None`` writes requirements.txt only """ + if dev_dependencies is not None: + write_requirements_files( + self.project_dir, dependencies, list(dev_dependencies) + ) + sync_pyproject_dev_file(self.project_dir, dev_dependencies) + return + requirements_path = self.get_dependency_file_path() try: diff --git a/src/fastapi_fastkit/backend/package_managers/poetry_manager.py b/src/fastapi_fastkit/backend/package_managers/poetry_manager.py index d10837ee..9ebff377 100644 --- a/src/fastapi_fastkit/backend/package_managers/poetry_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/poetry_manager.py @@ -7,7 +7,8 @@ import subprocess import sys from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple, Union +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union +from urllib.parse import unquote, urlsplit from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import DEFAULT_POETRY_PYTHON, settings @@ -27,6 +28,7 @@ declared_requires_python, merge_pyproject_tables, parse_toml, + replace_dev_declarations, toml_string, toml_string_array, ) @@ -121,8 +123,57 @@ def _parse_pip_requirement( return req, extras, version_spec, marker +#: A PEP 508 direct reference: ``name[extras] @ url ; marker``. +_DIRECT_REFERENCE = re.compile( + r"^\s*(?P[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)\s*" + r"(?:\[(?P[^\]]*)\])?\s*@\s*(?P\S+)\s*(?:;\s*(?P.*\S))?\s*$" +) + + +def _direct_reference_source(url: str) -> List[str]: + """Poetry's source keys for the URL of a direct reference.""" + if url.startswith("git+"): + location, _, fragment = url[len("git+") :].partition("#") + parts: List[str] = [] + head, at, rev = location.rpartition("@") + if at and "/" not in rev and "://" in head: + location = head + else: + rev = "" + parts.append(f"git = {toml_string(location)}") + if rev: + parts.append(f"rev = {toml_string(rev)}") + for item in fragment.split("&"): + key, _, value = item.partition("=") + if key == "subdirectory" and value: + parts.append(f"subdirectory = {toml_string(value)}") + return parts + if url.startswith("file:"): + path = unquote(urlsplit(url).path) + if re.match(r"^/[A-Za-z]:", path): + path = path[1:] # file:///C:/x names C:/x + return [f"path = {toml_string(path)}"] + return [f"url = {toml_string(url)}"] + + def _poetry_dependency_line(requirement: str) -> str: """Render one pip requirement as a Poetry dependency line ("" to skip).""" + direct = _DIRECT_REFERENCE.match(requirement) + if direct: + parts = _direct_reference_source(direct.group("url")) + extras = [ + extra.strip() + for extra in (direct.group("extras") or "").split(",") + if extra.strip() + ] + if extras: + parts.append(f"extras = {toml_string_array(extras)}") + if direct.group("marker"): + parts.append(f"markers = {toml_string(direct.group('marker'))}") + name = direct.group("name") + key = name if re.fullmatch(r"[A-Za-z0-9_-]+", name) else toml_string(name) + return f"{key} = {{{', '.join(parts)}}}\n" + name_part, extras, version_spec, marker = _parse_pip_requirement(requirement) if not name_part: return "" @@ -429,6 +480,8 @@ def generate_dependency_file( author: str = "", author_email: str = "", description: str = "", + *, + dev_dependencies: Optional[Sequence[str]] = None, ) -> None: """ Write the Poetry tables for the given dependencies into pyproject.toml. @@ -447,23 +500,42 @@ def generate_dependency_file( ``poetry install`` does not try to install a package that does not exist. + With ``dev_dependencies`` the dev group is that list instead, written + both as ``[tool.poetry.group.dev.dependencies]`` and as + ``[dependency-groups].dev``: Poetry 2.0 and 2.1 read only the former, + and Poetry 2.2 and later install only what the latter lists once the + file has a ``[dependency-groups].dev`` (the Poetry table then merely + adds details to it), so both must hold the whole list. An existing + ``dev`` extra is set to the list too (:func:`replace_dev_declarations`). + :param dependencies: List of dependency specifications :param project_name: Name of the project :param author: Author name :param author_email: Author email :param description: Project description + :param dev_dependencies: Development dependencies; ``None`` takes the + dev group from the template's ``[dependency-groups].dev`` """ pyproject_path = self.get_dependency_file_path() def render(existing: Optional[str]) -> str: + text = render_tables(existing) + if dev_dependencies is None: + return text + return replace_dev_declarations(text, dev_dependencies) + + def render_tables(existing: Optional[str]) -> str: python = DEFAULT_POETRY_PYTHON - dev_dependencies: List[str] = [] + dev_group: List[str] = ( + [] if dev_dependencies is None else list(dev_dependencies) + ) if existing is not None and existing.strip(): python = declared_requires_python(existing) or python - dev_dependencies = _dev_dependency_group(parse_toml(existing)) + if dev_dependencies is None: + dev_group = _dev_dependency_group(parse_toml(existing)) tables = _poetry_tables( dependencies, - dev_dependencies, + dev_group, python, project_name or "fastapi-project", description or "A FastAPI project", diff --git a/src/fastapi_fastkit/backend/package_managers/pyproject.py b/src/fastapi_fastkit/backend/package_managers/pyproject.py index 0ad0dd25..67b79905 100644 --- a/src/fastapi_fastkit/backend/package_managers/pyproject.py +++ b/src/fastapi_fastkit/backend/package_managers/pyproject.py @@ -794,6 +794,327 @@ def update_pep621_pyproject( return ensure_requires_python(updated) +# ------------------------------------------------------------------ +# [dependency-groups] editing (PEP 735; uv, PDM, Poetry 2.2+) +# ------------------------------------------------------------------ + + +def declared_dependency_group(content: str, group: str) -> List[str]: + """ + Return the string entries of ``[dependency-groups].``. + + Entries that are not strings (``{include-group = "..."}`` tables) are + left out; a missing table or group gives an empty list. + + :param content: pyproject text + :param group: Group name (``dev``) + :return: The group's requirement strings, in file order + :raises PyprojectMergeError: if ``content`` is invalid TOML + """ + groups = parse_toml(content).get("dependency-groups") + if not isinstance(groups, dict): + return [] + entries = groups.get(group) + if not isinstance(entries, list): + return [] + return [entry for entry in entries if isinstance(entry, str)] + + +def _with_group_tables(current: Any, entries: List[str]) -> List[Any]: + """ + ``entries`` with the non-string items of ``current`` kept in place. + + The strings of ``entries`` fill the string positions of ``current`` in + order; an ``{include-group = ...}`` table stays after the same number of + strings it followed (fewer when the list got shorter), and strings + beyond the old ones are appended. + """ + if not isinstance(current, list): + return list(entries) + merged: List[Any] = [] + remaining = iter(entries) + for item in current: + if isinstance(item, str): + replacement = next(remaining, None) + if replacement is not None: + merged.append(replacement) + else: + merged.append(item) + merged.extend(remaining) + return merged + + +def _render_group_item(item: Any) -> str: + if isinstance(item, str): + return toml_string(item) + if isinstance(item, dict) and all( + isinstance(key, str) and isinstance(value, str) for key, value in item.items() + ): + pairs = ", ".join( + f"{_key_repr(key)} = {toml_string(value)}" for key, value in item.items() + ) + return f"{{{pairs}}}" + raise PyprojectMergeError( + f"dependency group entry {item!r} cannot be rewritten by fastkit" + ) + + +def _render_group_array(items: List[Any], newline: str) -> str: + if not items: + return "[]" + body = newline.join(f" {_render_group_item(item)}," for item in items) + return f"[{newline}{body}{newline}]" + + +def replace_dependency_group(content: str, group: str, entries: List[str]) -> str: + """ + Set ``[dependency-groups].`` in pyproject text to ``entries``. + + The group's array is located among the statements of the standard + ``[dependency-groups]`` table (masked scan, as for + :func:`replace_project_dependencies`) and replaced; a missing group is + added to that table, and a missing table is appended at the end of the + file. Everything else is kept byte for byte, which the semantic + post-condition checks before the text is returned. + + Non-string entries of an existing group (``{include-group = "lint"}``) + are kept in place and the string entries are replaced around them + (:func:`_with_group_tables`). The text is returned unchanged when the + parsed group already equals that result, and when the group is missing + and ``entries`` is empty (an empty group declares nothing). + + :param content: pyproject text + :param group: Group name (``dev``) + :param entries: Requirement strings to write, in order + :return: Updated text + :raises PyprojectMergeError: if ``content`` is invalid TOML, or the group + is declared in a form that cannot be edited safely (dotted keys or an + inline ``dependency-groups`` table) + """ + data = parse_toml(content) + groups = data.get("dependency-groups") + current = groups.get(group) if isinstance(groups, dict) else None + items = _with_group_tables(current, list(entries)) + if current == items or (current is None and not items): + return content + + newline = _newline_of(content) + rendered = f"{_key_repr(group)} = {_render_group_array(items, newline)}" + blocks = _split_blocks(content) + table = next( + ( + block + for block in blocks + if block.parts == ("dependency-groups",) and not block.is_array + ), + None, + ) + + if groups is None: + body = _ensure_trailing_newline(content, newline) + if body.strip(): + body = body.rstrip("\r\n") + newline + newline + else: + body = "" + updated = body + "[dependency-groups]" + newline + rendered + newline + elif table is None or not isinstance(groups, dict): + raise PyprojectMergeError( + "[dependency-groups] is defined with dotted keys or as an inline " + "table; fastkit only edits a standard [dependency-groups] table" + ) + else: + statement = next( + (item for item in _statements(table.text, True) if item.key == group), + None, + ) + if statement is None: + if group in groups: + raise PyprojectMergeError( + f"[dependency-groups].{group} is declared in a form fastkit " + "cannot edit safely" + ) + table.text = _insert_statement(table.text, rendered, newline) + else: + table.text = ( + table.text[: statement.key_start] + + rendered + + table.text[statement.value_end :] + ) + updated = "".join(block.text for block in blocks) + + parsed = _check_preserved( + content, + updated, + owned_keys=[("dependency-groups", group)], + owned_tables=[("dependency-groups",)], + ) + if parsed.get("dependency-groups", {}).get(group) != items: + raise PyprojectMergeError( + f"[dependency-groups].{group} could not be replaced in pyproject.toml" + ) + return updated + + +def replace_declared_optional_dependencies( + content: str, extra: str, entries: List[str] +) -> str: + """ + Set ``[project.optional-dependencies].`` to ``entries`` when the + file already declares that extra. + + Templates declare their development tools twice: as the PEP 735 ``dev`` + group (uv, PDM) and as a ``dev`` extra (``pip install -e ".[dev]"``). + PDM installs the extra instead of the group when both exist, so the two + lists have to stay equal. A missing extra is never added; the text is + returned unchanged then, and when the extra already equals ``entries``. + Everything else is kept byte for byte (semantic post-condition). + + :param content: pyproject text + :param extra: Extra name (``dev``) + :param entries: Requirement strings to write, in order + :return: Updated text + :raises PyprojectMergeError: if ``content`` is invalid TOML, or the extra + is declared in a form that cannot be edited safely (an inline + ``optional-dependencies`` table or dotted keys) + """ + entries = list(entries) + project = parse_toml(content).get("project") + extras = project.get("optional-dependencies") if isinstance(project, dict) else None + if not isinstance(extras, dict) or extra not in extras: + return content + if extras[extra] == entries: + return content + + blocks = _split_blocks(content) + table = next( + ( + block + for block in blocks + if block.parts == ("project", "optional-dependencies") + and not block.is_array + ), + None, + ) + statement = None + if table is not None: + statement = next( + (item for item in _statements(table.text, True) if item.key == extra), + None, + ) + if table is None or statement is None: + raise PyprojectMergeError( + f"[project.optional-dependencies].{extra} is declared in a form " + "fastkit cannot edit safely" + ) + + newline = _newline_of(content) + rendered = f"{_key_repr(extra)} = {render_dependency_array(entries, newline)}" + table.text = ( + table.text[: statement.key_start] + rendered + table.text[statement.value_end :] + ) + updated = "".join(block.text for block in blocks) + + parsed = _check_preserved( + content, updated, owned_keys=[("project", "optional-dependencies", extra)] + ) + if parsed.get("project", {}).get("optional-dependencies", {}).get(extra) != entries: + raise PyprojectMergeError( + f"[project.optional-dependencies].{extra} could not be replaced in " + "pyproject.toml" + ) + return updated + + +def replace_dev_declarations( + content: str, entries: Sequence[str], *, add_group: bool = True +) -> str: + """ + Make the development declarations of pyproject text list ``entries``. + + Templates declare their development tools both as the ``dev`` + dependency group and as the ``dev`` extra. PDM installs the extra and + ignores the group when both exist, pip installs the extra + (``pip install -e ".[dev]"``) and uv the group, so every manager that + writes a dev list keeps both equal through this helper. + + The group is replaced (:func:`replace_dependency_group`, which keeps + ``{include-group = ...}`` entries); it is added when missing only with + ``add_group``. The extra is replaced only when the text already declares + it; when it cannot be edited safely a warning says so and the rest of + the update is kept. + + :param content: pyproject text + :param entries: The final dev list + :param add_group: Create ``[dependency-groups].dev`` when it is missing + :return: Updated text + :raises PyprojectMergeError: if ``content`` is invalid TOML or the group + cannot be edited safely + """ + # Imported here: the message helpers pull in the console setup. + from fastapi_fastkit.utils.main import print_warning + + entries = list(entries) + updated = content + groups = parse_toml(content).get("dependency-groups") + if add_group or (isinstance(groups, dict) and "dev" in groups): + updated = replace_dependency_group(updated, "dev", entries) + try: + return replace_declared_optional_dependencies(updated, "dev", entries) + except PyprojectMergeError as e: + print_warning( + "Could not update [project.optional-dependencies].dev in " + f"pyproject.toml safely ({e}); it was left unchanged and may " + "list other development dependencies than the dev group." + ) + return updated + + +def sync_pyproject_dev_file( + project_dir: Union[str, "os.PathLike[str]"], dev: Sequence[str] +) -> bool: + """ + Apply :func:`replace_dev_declarations` (without adding a group) to the + project's pyproject.toml, for managers whose own file is not + pyproject.toml (pip). + + The file is left as it is when it is missing, unreadable or cannot be + edited safely (a warning says so). + + :param project_dir: Project directory + :param dev: The final dev list + :return: True when pyproject.toml was rewritten + """ + from fastapi_fastkit.utils.main import print_warning + + path = os.path.join(os.fspath(project_dir), "pyproject.toml") + if not os.path.isfile(path): + return False + try: + content, newline = read_text_preserving_newlines(path) + except (OSError, UnicodeDecodeError) as e: + debug_log(f"Could not read {path}: {e}", "warning") + return False + + text = content.removeprefix("\ufeff") + try: + updated = replace_dev_declarations(text, dev, add_group=False) + except PyprojectMergeError as e: + print_warning( + f"Could not update the development dependencies in {path} safely " + f"({e}); the file was left unchanged." + ) + return False + if updated == text: + return False + + try: + write_text_preserving_newlines(path, updated, newline) + except OSError as e: + debug_log(f"Error writing {path}: {e}", "error") + return False + return True + + def append_tool_table( content: str, tool: str, @@ -920,11 +1241,14 @@ def append_tool_table_to_file( "PyprojectMergeError", "append_tool_table", "append_tool_table_to_file", + "declared_dependency_group", "declared_requires_python", "ensure_requires_python", "merge_pyproject_tables", "parse_toml", "render_dependency_array", + "replace_declared_optional_dependencies", + "replace_dependency_group", "replace_project_dependencies", "split_toml_tables", "toml_string", diff --git a/src/fastapi_fastkit/backend/package_managers/requirements.py b/src/fastapi_fastkit/backend/package_managers/requirements.py new file mode 100644 index 00000000..e7d8f3d7 --- /dev/null +++ b/src/fastapi_fastkit/backend/package_managers/requirements.py @@ -0,0 +1,76 @@ +# -------------------------------------------------------------------------- +# requirements.txt / requirements-dev.txt rendering. +# +# ``requirements.txt`` lists the runtime dependencies (the Docker image +# installs it) and ``requirements-dev.txt`` pulls those in with +# ``-r requirements.txt`` and adds the development tools (tests, linters). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from pathlib import Path +from typing import List, Sequence, Union + +from fastapi_fastkit.core.exceptions import BackendExceptions +from fastapi_fastkit.utils.logging import debug_log +from fastapi_fastkit.utils.textio import write_generated_text + +#: Runtime dependencies, one requirement per line. +REQUIREMENTS_FILE = "requirements.txt" +#: ``-r requirements.txt`` plus the development dependencies. +REQUIREMENTS_DEV_FILE = "requirements-dev.txt" + + +def render_requirements(requirements: Sequence[str]) -> str: + """One requirement per line, each line ending in a newline.""" + return "".join(f"{requirement}\n" for requirement in requirements) + + +def render_dev_requirements(dev: Sequence[str]) -> str: + """``-r requirements.txt`` followed by the development requirements.""" + return f"-r {REQUIREMENTS_FILE}\n" + render_requirements(dev) + + +def write_requirements_files( + project_dir: Union[str, Path], + runtime: Sequence[str], + dev: Sequence[str], +) -> List[str]: + """ + Write ``requirements.txt`` and ``requirements-dev.txt`` into a project. + + ``requirements-dev.txt`` is always written, even when ``dev`` is empty + (it then holds only the ``-r requirements.txt`` line), so development + instructions can always point at it. + + :param project_dir: Project root + :param runtime: Runtime requirements, written as given + :param dev: Development requirements, written as given + :return: The names of the files written, relative to ``project_dir`` + :raises BackendExceptions: if a file cannot be written + """ + root = Path(project_dir) + files = ( + (REQUIREMENTS_FILE, render_requirements(runtime)), + (REQUIREMENTS_DEV_FILE, render_dev_requirements(dev)), + ) + for name, content in files: + try: + write_generated_text(root / name, content) + except (OSError, UnicodeEncodeError) as e: + debug_log(f"Error generating {name}: {e}", "error") + raise BackendExceptions(f"Failed to generate {name}: {str(e)}") + debug_log( + f"Generated {REQUIREMENTS_FILE} ({len(runtime)} entries) and " + f"{REQUIREMENTS_DEV_FILE} ({len(dev)} entries) in {root}", + "info", + ) + return [name for name, _ in files] + + +__all__ = [ + "REQUIREMENTS_DEV_FILE", + "REQUIREMENTS_FILE", + "render_dev_requirements", + "render_requirements", + "write_requirements_files", +] diff --git a/src/fastapi_fastkit/backend/package_managers/uv_manager.py b/src/fastapi_fastkit/backend/package_managers/uv_manager.py index 77df9336..0eb950e0 100644 --- a/src/fastapi_fastkit/backend/package_managers/uv_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/uv_manager.py @@ -4,7 +4,7 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import subprocess -from typing import List +from typing import List, Optional, Sequence from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import DEFAULT_REQUIRES_PYTHON, settings @@ -16,6 +16,7 @@ from .base import BasePackageManager from .pyproject import ( render_dependency_array, + replace_dev_declarations, toml_string, update_pep621_pyproject, ) @@ -121,6 +122,8 @@ def generate_dependency_file( author: str = "", author_email: str = "", description: str = "", + *, + dev_dependencies: Optional[Sequence[str]] = None, ) -> None: """ Write the dependencies and metadata into pyproject.toml. @@ -136,20 +139,31 @@ def generate_dependency_file( :param author: Author name :param author_email: Author email :param description: Project description + :param dev_dependencies: Development dependencies written as + ``[dependency-groups].dev`` (the table is created when missing) + and to an existing ``dev`` extra (:func:`replace_dev_declarations`); + ``None`` leaves the development declarations as they are """ pyproject_path = self.get_dependency_file_path() + def with_dev_group(content: str) -> str: + if dev_dependencies is None: + return content + return replace_dev_declarations(content, dev_dependencies) + try: - fresh_content = _uv_pyproject( - dependencies, - project_name or "fastapi-project", - description or "A FastAPI project", - author or "Author", - author_email or "author@example.com", + fresh_content = with_dev_group( + _uv_pyproject( + dependencies, + project_name or "fastapi-project", + description or "A FastAPI project", + author or "Author", + author_email or "author@example.com", + ) ) self._write_pyproject( - lambda existing: update_pep621_pyproject( - existing, fresh_content, dependencies + lambda existing: with_dev_group( + update_pep621_pyproject(existing, fresh_content, dependencies) ), fresh_content, ) diff --git a/src/fastapi_fastkit/backend/project_builder/config_generator.py b/src/fastapi_fastkit/backend/project_builder/config_generator.py index f9c7e492..c3e16cfe 100644 --- a/src/fastapi_fastkit/backend/project_builder/config_generator.py +++ b/src/fastapi_fastkit/backend/project_builder/config_generator.py @@ -51,6 +51,7 @@ ToolingChoice, UtilityChoice, ) +from fastapi_fastkit.utils.filemodes import is_executable_path, mark_executable from fastapi_fastkit.utils.textio import ( read_text_preserving_newlines, write_generated_text, @@ -112,9 +113,6 @@ #: Default Redis URL shared by the cache, the Redis database and the brokers. _REDIS_URL = "redis://localhost:6379/0" -#: Files written with the executable bit set. -_EXECUTABLE_ARTIFACTS = frozenset({"scripts/migrate.sh"}) - #: The shareable environment file the generated project documents its #: variables in. The local ``.env`` is derived from it afterwards. ENV_EXAMPLE_RELPATH = ".env.example" @@ -1923,8 +1921,8 @@ def generate_all_files(self, include_main: bool = True) -> List[str]: target = self.project_dir / relpath target.parent.mkdir(parents=True, exist_ok=True) write_generated_text(target, content) - if relpath in _EXECUTABLE_ARTIFACTS: - target.chmod(0o755) + if is_executable_path(relpath): + mark_executable(target) written.append(relpath) written.extend(self.apply_settings_module()) diff --git a/src/fastapi_fastkit/backend/project_builder/config_schema.py b/src/fastapi_fastkit/backend/project_builder/config_schema.py index f6e60b87..98a3e2d3 100644 --- a/src/fastapi_fastkit/backend/project_builder/config_schema.py +++ b/src/fastapi_fastkit/backend/project_builder/config_schema.py @@ -34,17 +34,19 @@ # -------------------------------------------------------------------------- from typing import Any, Dict, List, Optional, Tuple +from fastapi_fastkit.catalog import evaluate, load_catalog, selection_from_config from fastapi_fastkit.core.settings import ( MULTI_SELECT_AXES, NONE_CHOICE, - AuthChoice, - DatabaseChoice, FastkitConfig, FeatureAxis, ) +#: Rules, deployment targets and option lists come from the catalog. +_CATALOG = load_catalog() + #: Deployment targets ``prompt_deployment_options`` can produce. -DEPLOYMENT_CHOICES: Tuple[str, ...] = ("Docker", "docker-compose", NONE_CHOICE) +DEPLOYMENT_CHOICES: Tuple[str, ...] = _CATALOG.axis("deployment").choice_ids #: Non-axis keys the interactive builder writes. Anything outside this set #: (and outside :class:`FeatureAxis`) is a typo rather than a feature block. @@ -71,11 +73,9 @@ #: Databases FastAPI-Users' SQLAlchemy backend (the generated one) supports. -FASTAPI_USERS_DATABASES: Tuple[str, ...] = ( - DatabaseChoice.POSTGRESQL, - DatabaseChoice.MYSQL, - DatabaseChoice.SQLITE, -) +FASTAPI_USERS_DATABASES: Tuple[str, ...] = _CATALOG.rule( + "fastapi-users-needs-sql" +).require[str(FeatureAxis.DATABASE)] def combination_errors(config: Dict[str, Any]) -> List[str]: @@ -83,25 +83,14 @@ def combination_errors(config: Dict[str, Any]) -> List[str]: Report feature selections that cannot be generated together. Expects the canonical shape (see :func:`normalize_project_config`), but - also accepts the interactive builder's. + also accepts the interactive builder's. The checks are the catalog's + ``requires`` rules. :param config: Configuration mapping :return: Human-readable error messages, empty when every pair works """ - errors: List[str] = [] - database = config.get(str(FeatureAxis.DATABASE)) or {} - db_type = database.get("type") if isinstance(database, dict) else database - db_type = str(db_type or NONE_CHOICE) - auth = config.get(str(FeatureAxis.AUTHENTICATION)) - if auth == AuthChoice.FASTAPI_USERS and db_type not in FASTAPI_USERS_DATABASES: - selected = "no database" if db_type == NONE_CHOICE else f"database '{db_type}'" - errors.append( - "Authentication 'FastAPI-Users' needs a SQL database " - f"({', '.join(FASTAPI_USERS_DATABASES)}), but {selected} is selected. " - "Choose one of those databases, or the 'JWT' option, which works " - "with every database." - ) - return errors + selection = selection_from_config(config, _CATALOG) + return list(evaluate(selection, _CATALOG).errors) class ConfigSchemaError(Exception): @@ -395,9 +384,11 @@ def _normalize_deployment( selected.append(item) # ``docker-compose.yml`` builds the image the Dockerfile describes, so - # picking compose implies Docker โ€” the interactive prompt does the same. - if "docker-compose" in selected and "Docker" not in selected: - selected.insert(0, "Docker") + # picking compose implies Docker (a catalog ``implies`` rule) โ€” the + # interactive prompt does the same. Implied targets go first. + outcome = evaluate({"deployment": tuple(selected)}, _CATALOG) + for offset, target in enumerate(outcome.implied.get("deployment", ())): + selected.insert(offset, target) normalized["deployment"] = selected return errors diff --git a/src/fastapi_fastkit/backend/project_builder/dependency_collector.py b/src/fastapi_fastkit/backend/project_builder/dependency_collector.py index de1ec9b9..6e25cc4b 100644 --- a/src/fastapi_fastkit/backend/project_builder/dependency_collector.py +++ b/src/fastapi_fastkit/backend/project_builder/dependency_collector.py @@ -9,20 +9,22 @@ # - Custom packages # # Handles deduplication, including folding ``pkg`` and ``pkg[extra]`` into a -# single requirement so a package never appears twice. +# single requirement so a package never appears twice, and splits the result +# into runtime and development dependencies (``DependencySet``) using the +# catalog's ``runtime`` / ``dev`` lists. # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import re +from dataclasses import dataclass from typing import Any, Dict, Iterable, List, Set, Tuple from fastapi_fastkit.backend.package_managers.poetry_manager import ( _parse_pip_requirement, ) +from fastapi_fastkit.catalog import evaluate, load_catalog, selection_from_config from fastapi_fastkit.core.settings import ( - MULTI_SELECT_AXES, NONE_CHOICE, - DatabaseChoice, FeatureAxis, ) @@ -96,6 +98,72 @@ def _format_requirement(name: str, extras: List[str], spec: str, marker: str) -> return text +def _requirement_key(requirement: str) -> str: + """Canonical distribution name of a requirement string.""" + return canonical_package_name(_parse_pip_requirement(requirement.strip())[0]) + + +def unconditional_names(requirements: Iterable[str]) -> Set[str]: + """ + Canonical names of the requirements that apply on every platform. + + An entry with an environment marker (``httpx; sys_platform == "win32"``) + installs the package only where the marker holds, so it does not make + another entry for that name redundant. + """ + names: Set[str] = set() + for requirement in requirements: + name, _extras, _spec, marker = _parse_pip_requirement(requirement.strip()) + if not marker: + names.add(canonical_package_name(name)) + return names + + +@dataclass(frozen=True) +class DependencySet: + """ + A project's dependencies, split into runtime and development packages. + + Runtime packages go to ``[project].dependencies`` / ``requirements.txt``; + development packages (test runners, linters) to the dev group / + ``requirements-dev.txt``. Both tuples are sorted and merged (see + :func:`merge_requirements`), and a package never sits in both: an entry + of ``dev`` whose name ``runtime`` already installs unconditionally (no + environment marker) is dropped. + """ + + runtime: Tuple[str, ...] = () + dev: Tuple[str, ...] = () + + @classmethod + def from_lists( + cls, runtime: Iterable[str], dev: Iterable[str] = () + ) -> "DependencySet": + """ + Merge two requirement lists into a :class:`DependencySet`. + + Args: + runtime: Runtime requirement strings (any order, duplicates allowed) + dev: Development requirement strings + + Returns: + Sorted, merged sets with unconditional runtime names removed + from ``dev`` + """ + merged_runtime = merge_requirements(runtime) + runtime_names = unconditional_names(merged_runtime) + merged_dev = [ + item + for item in merge_requirements(dev) + if _requirement_key(item) not in runtime_names + ] + return cls(runtime=tuple(merged_runtime), dev=tuple(merged_dev)) + + def all(self) -> List[str]: + """Runtime and development dependencies as one merged, sorted list.""" + return merge_requirements([*self.runtime, *self.dev]) + + class DependencyCollector: """ Collects and manages project dependencies. @@ -114,69 +182,99 @@ def __init__(self, settings: Any) -> None: self.settings = settings self.dependencies: Set[str] = set() - def collect_from_config(self, config: Dict[str, Any]) -> List[str]: + def collect(self, config: Dict[str, Any]) -> DependencySet: """ - Collect all dependencies from configuration. + Collect the runtime and development dependencies of a configuration. - Every axis in ``PACKAGE_CATALOG`` is walked generically through - :class:`~fastapi_fastkit.core.settings.FeatureAxis`, so a new axis - only has to be added to the catalog โ€” there is no per-axis branch - here to forget to update. + Runtime: the catalog's base dependencies, the ``runtime`` packages of + every selected option and of every matching ``adds`` rule, and the + (sanitised) ``custom_packages``. Development: the ``dev`` packages of + the selected options and matching ``adds`` rules. Every axis of the + catalog is walked generically, so a new axis only has to be added to + ``catalog.toml``. + + ``all_dependencies`` is not read: packages a saved configuration + lists beyond its selections are the caller's to classify (see + :meth:`classify`). Args: - config: Project configuration dictionary + config: Project configuration (canonical or interactive shape) Returns: - Sorted list of all dependencies + The split, merged dependency set """ - # Reset dependencies - self.dependencies = set() - - # Add base dependencies - self.add_base_dependencies() - - for axis in FeatureAxis: - for choice in self._selected_choices(config, axis): - self.add_axis_dependencies(axis, choice) + # Imported here: the interactive package imports this module. + from fastapi_fastkit.backend.interactive.validators import ( + sanitize_custom_packages, + ) - # Add custom packages - self.add_combination_dependencies(config) + catalog = load_catalog() + selection = selection_from_config(config, catalog) + runtime: List[str] = list(catalog.defaults.base_dependencies) + dev: List[str] = [] + for axis in catalog.feature_axes(): + value = selection[axis.id] + for choice in value if isinstance(value, tuple) else (value,): + try: + option = axis.option(choice) + except KeyError: + continue # unknown choice: nothing to install (as before) + runtime.extend(option.runtime) + dev.extend(option.dev) + + outcome = evaluate(selection, catalog) + runtime.extend(outcome.runtime) + dev.extend(outcome.dev) + + custom = config.get("custom_packages") or [] + if isinstance(custom, (list, tuple)): + runtime.extend(sanitize_custom_packages([str(item) for item in custom])) + + result = DependencySet.from_lists(runtime, dev) + self.dependencies = set(result.all()) + return result + + def classify(self, requirements: Iterable[str]) -> DependencySet: + """ + Split free-form requirements into runtime and development packages. + + An entry is a development dependency when its name appears in the + catalog only as a ``dev`` package (``pytest``, ``ruff``, ...). Names + the catalog lists both ways (``httpx2``, ``aiosqlite``) and names it + does not know are runtime dependencies. - custom = config.get("custom_packages", []) - if custom: - self.dependencies.update(custom) + Args: + requirements: Requirement strings (a stack list, legacy entries) - return self.get_final_dependencies() + Returns: + The split, merged dependency set + """ + dev_only = load_catalog().dev_only_names() + runtime: List[str] = [] + dev: List[str] = [] + for requirement in requirements: + if not requirement.strip(): + continue + if _requirement_key(requirement) in dev_only: + dev.append(requirement) + else: + runtime.append(requirement) + return DependencySet.from_lists(runtime, dev) - @staticmethod - def _selected_choices(config: Dict[str, Any], axis: str) -> List[str]: + def collect_from_config(self, config: Dict[str, Any]) -> List[str]: """ - Normalise one axis' selection into a list of catalog keys. + Collect all dependencies from configuration as one flat list. - Handles the three shapes the interactive config uses: the database - axis stores ``{"type": ..., "packages": [...]}``, multi-select axes - store a list, and every other axis stores a bare string. + Equals ``self.collect(config).all()``: runtime and development + dependencies merged, for callers that do not need the split. Args: config: Project configuration dictionary - axis: Axis key to read Returns: - Selected choice names, with the ``None`` sentinel filtered out + Sorted list of all dependencies """ - raw = config.get(axis) - - if axis == FeatureAxis.DATABASE and isinstance(raw, dict): - raw = raw.get("type", NONE_CHOICE) - - if raw is None: - return [] - if axis in MULTI_SELECT_AXES or isinstance(raw, list): - selected = [str(item) for item in raw] - else: - selected = [str(raw)] - - return [choice for choice in selected if choice != NONE_CHOICE] + return self.collect(config).all() def add_axis_dependencies(self, axis: str, choice: str) -> None: """ @@ -193,32 +291,23 @@ def add_combination_dependencies(self, config: Dict[str, Any]) -> None: """ Add packages one selection needs only together with another. - Generated tests run against an in-memory SQLite database - (``sqlite+aiosqlite://``, set by the root ``conftest.py``), so a - project on PostgreSQL or MySQL with testing selected also gets + These come from the catalog's ``adds`` rules (runtime and dev + packages alike). Generated tests run against an in-memory SQLite + database (``sqlite+aiosqlite://``, set by the root ``conftest.py``), + so a project on PostgreSQL or MySQL with testing selected also gets ``aiosqlite``. Args: config: Project configuration dictionary """ - databases = self._selected_choices(config, FeatureAxis.DATABASE) - testing = self._selected_choices(config, FeatureAxis.TESTING) - if testing and set(databases) & { - DatabaseChoice.POSTGRESQL, - DatabaseChoice.MYSQL, - }: - self.dependencies.add("aiosqlite") + catalog = load_catalog() + outcome = evaluate(selection_from_config(config, catalog), catalog) + self.dependencies.update(outcome.runtime) + self.dependencies.update(outcome.dev) def add_base_dependencies(self) -> None: - """Add core FastAPI dependencies.""" - self.dependencies.update( - [ - "fastapi", - "uvicorn", - "pydantic", - "pydantic-settings", - ] - ) + """Add core FastAPI dependencies (the catalog's ``base_dependencies``).""" + self.dependencies.update(load_catalog().defaults.base_dependencies) def add_database_dependencies(self, db_type: str) -> None: """ diff --git a/src/fastapi_fastkit/backend/rollback.py b/src/fastapi_fastkit/backend/rollback.py new file mode 100644 index 00000000..c8ffa7f8 --- /dev/null +++ b/src/fastapi_fastkit/backend/rollback.py @@ -0,0 +1,198 @@ +# -------------------------------------------------------------------------- +# Undoing a failed scaffold. +# +# ``generate`` never deletes anything; the scaffolder decides what a failed +# run leaves behind. Two facts make that safe: ``make_directories`` reports +# exactly the directories this run created (``os.mkdir`` fails on an +# existing one, so a directory somebody else made in the meantime is never +# claimed), and ``TargetSnapshot`` copies the files a run is about to +# overwrite in a directory that already existed, so they can be put back. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import shutil +import tempfile +from dataclasses import dataclass, field +from typing import Iterable, List, Optional, Tuple + +from fastapi_fastkit.utils.logging import debug_log +from fastapi_fastkit.utils.platform import rmtree_force + + +def make_directories(path: str) -> List[str]: + """ + ``os.makedirs(path, exist_ok=True)`` that reports what it created. + + Each missing directory is made with ``os.mkdir``, which fails when the + directory exists; one that appears between the check and the call is + counted as pre-existing, so it is never removed by a rollback. + + :return: The directories created, outermost first + """ + missing: List[str] = [] + current = os.path.abspath(path) + while not os.path.isdir(current): + missing.append(current) + parent = os.path.dirname(current) + if parent == current: + break + current = parent + + created: List[str] = [] + try: + for directory in reversed(missing): + try: + os.mkdir(directory) + except FileExistsError: + continue + created.append(directory) + except BaseException: + remove_created_directories(created) + raise + return created + + +def remove_created_directories(created: Iterable[str]) -> None: + """Remove directories :func:`make_directories` created, innermost first. + + Only empty ones go: whatever is still inside was not this run's to + delete. + """ + for directory in sorted(created, key=len, reverse=True): + try: + os.rmdir(directory) + except OSError: + pass + + +@dataclass +class TargetSnapshot: + """ + The state of the paths a run may write in an existing directory. + + Existing files are copied (bytes, mode and times) to a temporary + directory, under their project-relative paths; missing ones are + remembered so that :meth:`restore` can remove what the run created. + Only regular files are copied: the run refuses symlinks up front. The + copies are deleted only after a complete restore (or a successful run), + so the user can recover what a failed restore left behind. + """ + + project_dir: str + #: ``(relative path, backup copy)`` of the files that existed. + saved: List[Tuple[str, str]] = field(default_factory=list) + #: Relative paths of files that did not exist. + absent: List[str] = field(default_factory=list) + #: Directories (absolute) that did not exist, to remove when empty. + absent_dirs: List[str] = field(default_factory=list) + #: Directories (absolute) that did not exist and are removed whole. + absent_trees: List[str] = field(default_factory=list) + backup_dir: Optional[str] = None + + @classmethod + def take( + cls, + project_dir: str, + relpaths: Iterable[str], + trees: Iterable[str] = (), + directories: Iterable[str] = (), + ) -> "TargetSnapshot": + """ + Record ``relpaths`` (project-relative, ``/``-separated) before a run. + + :param trees: Project-relative directories the run creates whole + when missing (the virtualenv); removed entirely on restore + :param directories: Project-relative directories the run creates + when missing, empty ones included; removed on restore when empty + """ + snapshot = cls(project_dir) + try: + for relpath in sorted(set(relpaths)): + path = snapshot._path(relpath) + if os.path.isfile(path): + snapshot._save(relpath, path) + elif not os.path.lexists(path): + snapshot.absent.append(relpath) + snapshot._remember_missing_parents(path) + for relpath in trees: + path = snapshot._path(relpath) + if not os.path.lexists(path): + snapshot.absent_trees.append(path) + for relpath in directories: + path = snapshot._path(relpath) + if not os.path.lexists(path): + if path not in snapshot.absent_dirs: + snapshot.absent_dirs.append(path) + snapshot._remember_missing_parents(path) + except BaseException: + snapshot.discard() + raise + return snapshot + + def _path(self, relpath: str) -> str: + return os.path.join(self.project_dir, *relpath.split("/")) + + def _save(self, relpath: str, path: str) -> None: + if self.backup_dir is None: + self.backup_dir = tempfile.mkdtemp(prefix="fastkit-backup-") + backup = os.path.join(self.backup_dir, *relpath.split("/")) + os.makedirs(os.path.dirname(backup), exist_ok=True) + shutil.copy2(path, backup) + self.saved.append((relpath, backup)) + + def _remember_missing_parents(self, path: str) -> None: + parent = os.path.dirname(path) + root = os.path.abspath(self.project_dir) + while ( + os.path.abspath(parent) != root + and parent not in self.absent_dirs + and not os.path.lexists(parent) + ): + self.absent_dirs.append(parent) + parent = os.path.dirname(parent) + + def restore(self) -> List[str]: + """ + Put every recorded path back the way it was. + + Best effort: a file that cannot be restored is reported, not raised. + The backup is dropped only when every file came back; after a failure + or an interruption it stays in :attr:`backup_dir`. + + :return: Relative paths whose original content could not be restored + """ + failed: List[str] = [] + complete = False + try: + for relpath, backup in self.saved: + try: + shutil.copy2(backup, self._path(relpath)) + except OSError as e: + debug_log(f"Could not restore {relpath}: {e}", "warning") + failed.append(relpath) + for relpath in self.absent: + path = self._path(relpath) + if os.path.isfile(path) or os.path.islink(path): + try: + os.remove(path) + except OSError as e: + debug_log(f"Could not remove {relpath}: {e}", "warning") + for tree in self.absent_trees: + if os.path.isdir(tree) and not os.path.islink(tree): + rmtree_force(tree, ignore_errors=True) + remove_created_directories(self.absent_dirs) + complete = not failed + finally: + if complete: + self.discard() + return failed + + def discard(self) -> None: + """Delete the backup copies (after success, or once restored).""" + if self.backup_dir is not None: + rmtree_force(self.backup_dir, ignore_errors=True) + self.backup_dir = None + + +__all__ = ["TargetSnapshot", "make_directories", "remove_created_directories"] diff --git a/src/fastapi_fastkit/backend/route_format.py b/src/fastapi_fastkit/backend/route_format.py new file mode 100644 index 00000000..a849606c --- /dev/null +++ b/src/fastapi_fastkit/backend/route_format.py @@ -0,0 +1,134 @@ +# -------------------------------------------------------------------------- +# Import ordering and wrapping for the code ``fastkit addroute`` writes. +# +# The route templates are black-formatted for ordinary names. Two things +# depend on the names substituted into them and are handled here, in the +# form isort (black profile) and black give them: the order of imports (a +# module named after the route may sort before or after its neighbours) and +# the length of import lines, including the import and registration lines +# inserted into the API router module. +# +# Other lines are not reformatted: a long route or entity name gives valid, +# working code, but some of its lines may be longer than black leaves them. +# tests/test_backends/test_route_generated_format.py states the name lengths +# whose output is in black's format. +# -------------------------------------------------------------------------- +import ast +import re +from typing import List, Tuple, Union + +LINE_LENGTH = 88 + +#: A natural sort key: text and numbers alternate, starting with text. +NaturalKey = Tuple[Union[str, int], ...] + + +def natural_key(text: str) -> NaturalKey: + """isort's natural, case-insensitive sort key (``item2`` < ``item10``).""" + return tuple( + int(part) if part.isdigit() else part + for part in re.split(r"(\d+)", text.lower()) + ) + + +def _import_key(node: ast.stmt) -> Tuple[int, int, NaturalKey]: + """``from __future__`` first (Python requires it), then ``import x`` + before ``from x import y``, then by module name.""" + if isinstance(node, ast.Import): + return 1, 0, natural_key(node.names[0].name) + assert isinstance(node, ast.ImportFrom) + future = node.level == 0 and node.module == "__future__" + return 0 if future else 1, 1, natural_key("." * node.level + (node.module or "")) + + +def wrap_import(statement: str, line_length: int = LINE_LENGTH) -> str: + """isort's vertical hanging indent for a ``from`` import that is too long. + + ``from a import b as c`` longer than the limit becomes:: + + from a import ( + b as c, + ) + + Shorter imports, already wrapped ones, ``import x`` statements and + imports with comments are returned unchanged. + """ + if len(statement) <= line_length or "\n" in statement or "#" in statement: + return statement + match = re.fullmatch(r"(from\s+\S+\s+import)\s+([^()]+)", statement.strip()) + if match is None: + return statement + names = [name.strip() for name in match.group(2).split(",") if name.strip()] + body = "".join(f" {name},\n" for name in names) + return f"{match.group(1)} (\n{body})" + + +def wrap_call(statement: str, line_length: int = LINE_LENGTH) -> str: + """A one-argument call statement exploded with a magic trailing comma. + + ``api_router.include_router(orders_router)`` is returned as it is while + it fits; past the limit it becomes:: + + api_router.include_router( + orders_router, + ) + + which black keeps at any length. Anything else is returned unchanged. + """ + if len(statement) <= line_length or "\n" in statement: + return statement + match = re.fullmatch(r"([\w.]+)\(([\w.]+)\)", statement.strip()) + if match is None: + return statement + return f"{match.group(1)}(\n {match.group(2)},\n)" + + +def wrap_imports(content: str, line_length: int = LINE_LENGTH) -> str: + """Apply :func:`wrap_import` to every too-long top-level import line.""" + return "\n".join( + wrap_import(line, line_length) if line.startswith("from ") else line + for line in content.split("\n") + ) + + +def sort_imports(content: str) -> str: + """Sort each run of adjacent top-level imports the way isort orders them. + + A run ends at a blank line, a comment line or any other statement, so + the sections the template separates stay apart. A module that does not + parse is returned unchanged. + """ + try: + tree = ast.parse(content) + except SyntaxError: + return content + lines = content.split("\n") + runs: List[List[ast.stmt]] = [] + for node in tree.body: + if not isinstance(node, (ast.Import, ast.ImportFrom)): + runs.append([]) + continue + if runs and runs[-1] and (runs[-1][-1].end_lineno or 0) + 1 == node.lineno: + runs[-1].append(node) + else: + runs.append([node]) + for run in reversed([run for run in runs if len(run) > 1]): + start = run[0].lineno - 1 + stop = run[-1].end_lineno or run[-1].lineno + chunks = [ + lines[node.lineno - 1 : node.end_lineno or node.lineno] + for node in sorted(run, key=_import_key) + ] + lines[start:stop] = [row for chunk in chunks for row in chunk] + return "\n".join(lines) + + +__all__ = [ + "LINE_LENGTH", + "NaturalKey", + "natural_key", + "sort_imports", + "wrap_imports", + "wrap_call", + "wrap_import", +] diff --git a/src/fastapi_fastkit/backend/route_generators.py b/src/fastapi_fastkit/backend/route_generators.py index 17bc38cf..6bcaea32 100644 --- a/src/fastapi_fastkit/backend/route_generators.py +++ b/src/fastapi_fastkit/backend/route_generators.py @@ -16,6 +16,11 @@ from fastapi_fastkit.backend import main as backend from fastapi_fastkit.backend.project_builder.preset_layout import PresetLayoutStrategist +from fastapi_fastkit.backend.route_format import ( + natural_key, + sort_imports, + wrap_imports, +) from fastapi_fastkit.backend.route_plan import RoutePlan from fastapi_fastkit.backend.route_wiring import ( plan_router_registration, @@ -371,6 +376,17 @@ def _render(template: Path, replacements: Dict[str, str]) -> str: return content +def _render_route_module(template: Path, replacements: Dict[str, str]) -> str: + """Render a route template with its imports in isort form. + + Module names built from the route name (``src.schemas.``) can + sort before or after the template's other imports, and make an import + too long for one line, so each import block is re-sorted and long + imports are wrapped once the names are substituted. + """ + return sort_imports(wrap_imports(_render(template, replacements))) + + def _module(package: str, *parts: str) -> str: return ".".join(part for part in (package, *parts) if part) @@ -485,9 +501,9 @@ def _plan_tests( app_import += " as app" imports = sorted( [app_import, f"from {store_module} import reset_store"], - key=lambda line: line.split()[1].lower(), + key=lambda line: natural_key(line.split()[1]), ) - content = _render( + content = _render_route_module( _modules_dir() / "tests" / "test_new_route.py-tpl", _replacements( names, @@ -574,7 +590,7 @@ def plan( "schemas": "new_route.py-tpl", } contents = { - relative: _render(modules / relative / template, replacements) + relative: _render_route_module(modules / relative / template, replacements) for relative, template in templates.items() } @@ -646,7 +662,7 @@ def plan( plan.write(domains_init, "") domain_dir = os.path.join(domains_dir, names.route) for filename in _DOMAIN_FILES: - content = _render(templates / f"{filename}-tpl", replacements) + content = _render_route_module(templates / f"{filename}-tpl", replacements) plan.create(os.path.join(domain_dir, filename), content) _plan_shared_core(plan, package) diff --git a/src/fastapi_fastkit/backend/route_wiring.py b/src/fastapi_fastkit/backend/route_wiring.py index 9ba134d4..5f18bf9a 100644 --- a/src/fastapi_fastkit/backend/route_wiring.py +++ b/src/fastapi_fastkit/backend/route_wiring.py @@ -3,8 +3,9 @@ import ast import os from pathlib import Path -from typing import Dict, Optional, Sequence, Tuple +from typing import Dict, Iterable, Iterator, Optional, Sequence, Tuple +from fastapi_fastkit.backend.route_format import wrap_call, wrap_import from fastapi_fastkit.backend.route_plan import RoutePlan from fastapi_fastkit.utils.main import print_info, print_warning from fastapi_fastkit.utils.textio import read_text_preserving_newlines @@ -35,6 +36,85 @@ def _parse_module(content: str) -> ast.Module: return ast.Module(body=statements, type_ignores=[]) +#: Modules whose ``TYPE_CHECKING`` is False at runtime. +TYPING_MODULES = frozenset({"typing", "typing_extensions"}) + + +def typing_names(tree: ast.AST) -> frozenset[str]: + """The names ``typing`` / ``typing_extensions`` are bound to in a module: + the module names themselves plus aliases (``import typing as t``).""" + names = set(TYPING_MODULES) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + names.update( + item.asname + for item in node.names + if item.name in TYPING_MODULES and item.asname + ) + return frozenset(names) + + +def static_truth( + test: ast.expr, typing_aliases: frozenset[str] = TYPING_MODULES +) -> Optional[bool]: + """The value an ``if`` test always has, or None when it depends on runtime. + + ``False`` / ``0`` / ``None`` and ``TYPE_CHECKING`` (the bare name, or the + attribute of ``typing`` / ``typing_extensions`` under one of + ``typing_aliases``) are always false at runtime; ``True`` and other + non-zero number constants are always true. ``config.TYPE_CHECKING`` is + an ordinary runtime value. + """ + if isinstance(test, ast.Constant) and ( + test.value is None or isinstance(test.value, (bool, int)) + ): + return bool(test.value) + if isinstance(test, ast.Name) and test.id == "TYPE_CHECKING": + return False + if ( + isinstance(test, ast.Attribute) + and test.attr == "TYPE_CHECKING" + and isinstance(test.value, ast.Name) + and test.value.id in typing_aliases + ): + return False + return None + + +def live_branches( + node: ast.If, typing_aliases: frozenset[str] = TYPING_MODULES +) -> list[ast.stmt]: + """The statements of an ``if`` that can run: dead branches are dropped.""" + truth = static_truth(node.test, typing_aliases) + if truth is True: + return list(node.body) + if truth is False: + return list(node.orelse) + return list(node.body) + list(node.orelse) + + +def reachable_nodes( + node: ast.AST, typing_aliases: Optional[frozenset[str]] = None +) -> Iterator[ast.AST]: + """Like :func:`ast.walk`, without the branches that never run. + + Function bodies are kept: whether a function (an app factory, say) is + called cannot be decided statically. + + :param typing_aliases: See :func:`typing_names`; computed from ``node`` + when omitted + """ + aliases = typing_names(node) if typing_aliases is None else typing_aliases + yield node + children: Iterable[ast.AST] + if isinstance(node, ast.If): + children = [node.test, *live_branches(node, aliases)] + else: + children = ast.iter_child_nodes(node) + for child in children: + yield from reachable_nodes(child, aliases) + + def _router_argument(call: ast.Call) -> ast.expr | None: if call.args: return call.args[0] @@ -47,10 +127,19 @@ def plan_router_registration( import_line: str, statement: str, ) -> None: - """Plan the import and registration of a router in the API router module.""" + """Plan the import and registration of a router in the API router module. + + Both lines are inserted at module level in a form isort and black keep: + on one line while they fit in 88 columns, wrapped (the import in + isort's vertical hanging indent, the call with a magic trailing comma) + when a long route name pushes them past it. + """ from fastapi_fastkit.backend.main import insert_import_line, insert_statement_line + import_line = wrap_import(import_line) + statement = wrap_call(statement) + api_dir = Path(project_layout["api_dir"]) init = api_dir / "__init__.py" if not plan.exists(str(init)): @@ -67,7 +156,7 @@ def plan_router_registration( existing = next( ( node - for node in ast.walk(_parse_module(content)) + for node in reachable_nodes(_parse_module(content)) if isinstance(node, ast.Call) and ast.dump(node.func) == ast.dump(expected.func) and (argument := _router_argument(node)) is not None diff --git a/src/fastapi_fastkit/backend/scaffolder.py b/src/fastapi_fastkit/backend/scaffolder.py index e40f3ee5..f908c07e 100644 --- a/src/fastapi_fastkit/backend/scaffolder.py +++ b/src/fastapi_fastkit/backend/scaffolder.py @@ -1,63 +1,89 @@ # -------------------------------------------------------------------------- # Project scaffolding service. # -# ``init`` and ``startdemo`` used to carry the whole generation pipeline -# inline: template lookup, copy, metadata injection, dependency files, -# dynamic config generation, virtualenv creation, install, and the rollback -# for every failure mode in between. That left the CLI functions unable to -# be reused or tested apart from Click, and the two commands drifted. -# -# ``ProjectScaffolder`` owns that pipeline. The CLI is left with argument -# parsing, prompting and reporting. +# ``ProjectScaffolder`` is the CLI-layer orchestrator around the generation +# API (``fastapi_fastkit.generation``): it turns the CLI's options into a +# ``GenerationSpec``, asks before overwriting files, picks an installed +# package manager when a virtualenv is created, prints what generation +# reports, creates the virtualenv, installs dependencies and rolls back a +# failed run (restoring the files it overwrote in an existing directory and +# removing only what it created). Generating the files themselves is ``generate``'s job, which +# never prompts, prints or runs a subprocess. # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import os from dataclasses import dataclass, field -from typing import Any, Dict, List, Optional +from typing import Any, Callable, Dict, Iterable, List, Optional import click from rich.tree import Tree from fastapi_fastkit.backend.main import ( - ENV_EXAMPLE_FILE, ENV_FILE, check_package_manager_supported, - create_local_env_file, create_venv_with_manager, - deploy_template_files, - generate_dependency_file_with_manager, - inject_project_metadata, + deployment_message, install_dependencies_with_manager, - prepare_dependency_file_for_manager, - read_template_stack, - update_setup_py_dependencies, - write_fastkit_metadata, -) -from fastapi_fastkit.backend.project_builder import ( - DependencyCollector, - DynamicConfigGenerator, - PresetLayoutStrategist, - app_module_from_relpath, ) +from fastapi_fastkit.backend.package_managers import PackageManagerFactory +from fastapi_fastkit.backend.project_builder import PresetLayoutStrategist from fastapi_fastkit.backend.project_builder.config_schema import ( normalize_project_config, ) -from fastapi_fastkit.backend.project_builder.dependency_collector import ( - merge_requirements, +from fastapi_fastkit.backend.rollback import ( + TargetSnapshot, + make_directories, + remove_created_directories, ) from fastapi_fastkit.core.exceptions import BackendExceptions -from fastapi_fastkit.core.settings import FeatureAxis +from fastapi_fastkit.generation import ( + GenerationError, + GenerationPlan, + GenerationSpec, + ProjectInfo, + generate, + plan, + spec_from_config, +) +from fastapi_fastkit.generation.dependencies import resolve_dependencies +from fastapi_fastkit.generation.metadata import app_module_for +from fastapi_fastkit.generation.metadata import build_metadata as _build_metadata +from fastapi_fastkit.generation.pipeline import ( + apply_feature_overlay, + symlink_refusal, + symlinked_targets, + template_directories, + writable_paths, +) from fastapi_fastkit.utils.logging import debug_log from fastapi_fastkit.utils.main import ( console, + print_error, print_info, print_success, print_warning, ) +from fastapi_fastkit.utils.messages import Message, capture_messages from fastapi_fastkit.utils.platform import rmtree_force, stdin_is_interactive -from .. import __version__ +#: The in-project virtualenv the package managers create. +VENV_DIR = ".venv" + +#: Files creating the virtualenv and installing may write into the project. +SETUP_ARTIFACTS = ("uv.lock", "poetry.lock", "pdm.lock", ".pdm-python") + + +def replay_messages(messages: Iterable[Message]) -> None: + """Print messages that generation recorded, in order.""" + printers: Dict[str, Callable[..., None]] = { + "info": print_info, + "success": print_success, + "warning": print_warning, + "error": print_error, + } + for message in messages: + printers[message.level](message.text, title=message.title) class ScaffoldCancelled(BackendExceptions): @@ -142,10 +168,13 @@ class ScaffoldResult: project_dir: str template: str app_module: str + #: Runtime and development dependencies, merged. dependencies: List[str] = field(default_factory=list) metadata: Dict[str, Any] = field(default_factory=dict) venv_path: str = "" dry_run: bool = False + #: The development part of ``dependencies``. + dev_dependencies: List[str] = field(default_factory=list) class ProjectScaffolder: @@ -184,41 +213,61 @@ def app_module(self) -> str: ``startdemo`` on any template (not just the preset-backed ones) records a correct entrypoint; the preset profile is the fallback. """ - template_main = self._template_main_relpath() - if template_main: - return app_module_from_relpath(template_main) - return self.strategist.app_module - - def _template_main_relpath(self) -> str: - """Project-relative ``main.py`` path shipped by the template.""" - for root, _dirs, files in os.walk(self.template_dir): - for file_name in files: - if file_name.removesuffix("-tpl") != "main.py": - continue - relative = os.path.relpath( - os.path.join(root, "main.py"), self.template_dir - ) - return relative.replace(os.sep, "/") - return "" + return app_module_for(self.template_dir, self.strategist) - def resolve_dependencies(self) -> List[str]: - """Return the dependency list that will end up in the project. + def spec(self, package_manager: Optional[str] = None) -> GenerationSpec: + """ + The generation spec for these options. - Feature selections are always re-derived from the catalog and merged - in. Callers assemble ``options.dependencies`` themselves, and an - axis they forget to walk would otherwise ship a project whose - generated code imports a package nobody installed. + :param package_manager: Manager to generate for, when it differs from + the requested one (an installed fallback) """ - if self.options.dependencies is None: - return read_template_stack(self.template_dir) + options = self.options + manager = package_manager or options.package_manager + if options.config: + # The CLI fills the identity options from the config; they win so + # a caller can name the project without editing the config. + config = dict( + options.config, + project_name=options.project_name, + author=options.author, + author_email=options.author_email, + description=options.description, + ) + return spec_from_config( + config, + package_manager=manager, + template=options.template, + preset=options.preset_id, + legacy_dependencies=options.dependencies, + ) + + project = ProjectInfo( + name=options.project_name, + author=options.author, + author_email=options.author_email, + description=options.description, + ) + if options.dependencies is not None: + return GenerationSpec( + project=project, + template=options.template, + preset=options.preset_id, + dependency_files="generated", + package_manager=manager, + extra_dependencies=tuple(options.dependencies), + ) + return GenerationSpec( + project=project, + template=options.template, + preset=options.preset_id, + package_manager=manager, + ) - dependencies = list(self.options.dependencies) - if self.options.config: - collector = DependencyCollector(self.settings) - dependencies.extend(collector.collect_from_config(self.options.config)) - # A config saved before a catalog entry gained an extra (plain - # ``sqlalchemy`` vs ``sqlalchemy[asyncio]``) must not list both. - return merge_requirements(dependencies) + def resolve_dependencies(self) -> List[str]: + """Return the dependency list (runtime and dev, merged) of the project.""" + deps = resolve_dependencies(self.spec(), self.settings.FASTKIT_TEMPLATE_ROOT) + return deps.all() def build_metadata(self) -> Dict[str, Any]: """ @@ -229,17 +278,14 @@ def build_metadata(self) -> Dict[str, Any]: through it, and ``preset`` / ``features`` document how the project was produced. """ - metadata: Dict[str, Any] = { - "managed": True, - "version": __version__, - "template": self.options.template, - "package_manager": self.options.package_manager, - "app_module": self.app_module, - "features": self._collect_features(), - } - if self.options.preset_id: - metadata["preset"] = self.options.preset_id - return metadata + return _build_metadata(self.spec(), self.app_module) + + def _plan(self) -> GenerationPlan: + return plan( + self.spec(), + self.project_dir, + template_root=self.settings.FASTKIT_TEMPLATE_ROOT, + ) def preview(self) -> ScaffoldResult: """ @@ -249,11 +295,11 @@ def preview(self) -> ScaffoldResult: """ self._require_template() - dependencies = self.resolve_dependencies() - metadata = self.build_metadata() + planned = self._plan() + dependencies = planned.dependencies.all() tree = Tree(f"[bold]{self.project_dir}[/bold]") - for relative_path in self._planned_files(): + for relative_path in planned.files: _add_tree_path(tree, relative_path) console.print("\n[bold]Files that would be created:[/bold]") console.print(tree) @@ -280,121 +326,235 @@ def preview(self) -> ScaffoldResult: return ScaffoldResult( project_dir=self.project_dir, template=self.options.template, - app_module=self.app_module, + app_module=planned.app_module, dependencies=dependencies, - metadata=metadata, + metadata=dict(planned.metadata), dry_run=True, + dev_dependencies=list(planned.dependencies.dev), ) def run(self) -> ScaffoldResult: """ Generate the project. - Any failure aborts immediately and rolls back the partially created - project (never the user's workspace itself). + Any failure (also Ctrl+C) aborts immediately and rolls back: a + project folder this run created is removed; in a directory that + already existed, the files the run overwrote get their original + content back and the files and directories it created are removed. + Nothing is written through a symlink in the target directory. :return: Details of the generated project :raises ScaffoldCancelled: If the user declines the overwrite prompt - :raises BackendExceptions: If any generation step fails, or an - in-place deployment would overwrite files and there is neither - ``--yes`` nor a terminal to confirm it + :raises BackendExceptions: If any generation step fails, the target + holds a symlink generation would write through, or an in-place + deployment would overwrite files and there is neither ``--yes`` + nor a terminal to confirm it """ self._require_template() if self.options.dry_run: return self.preview() + # Before anything is written or asked. + manager = self._effective_package_manager() if self.options.with_venv: - # Before anything is written or asked: an installed tool that - # cannot handle the generated project (Poetry 1.x) would - # otherwise fail half-way through. - check_package_manager_supported( - self.project_dir, self.options.package_manager - ) + # An installed tool that cannot handle the generated project + # (Poetry 1.x) would otherwise fail half-way through. + check_package_manager_supported(self.project_dir, manager) - if not self._confirm_overwrites(): + paths = self._writable_paths(manager) + self._refuse_symlinks(paths + [VENV_DIR] if self.options.with_venv else paths) + if not self._confirm_overwrites(paths): raise ScaffoldCancelled("Project creation aborted by user.") - pre_existed = os.path.isdir(self.project_dir) - project_dir = "" - try: - project_dir, _, copied_files = deploy_template_files( - self.template_dir, + click.echo( + deployment_message( self.settings.USER_WORKSPACE, self.options.project_name, self.options.create_project_folder, ) + ) - inject_project_metadata( - project_dir, - self.options.project_name, - self.options.author, - self.options.author_email, - self.options.description, - files=copied_files, - ) - - dependencies = self.resolve_dependencies() - if self.options.dependencies is not None: - self._write_dependency_files(project_dir, dependencies) - - if self.options.config: - self._generate_dynamic_config(project_dir, self.options.config) - - # After substitution, so placeholders in .env.example are filled - # in the generated .env too, and after the feature overlay, which - # appends the variables the selected features read. Never - # overwrites an existing .env. - create_local_env_file(project_dir) - - metadata = self.build_metadata() - write_fastkit_metadata(project_dir, metadata) - prepare_dependency_file_for_manager( - project_dir, self.options.package_manager - ) + project_dir = os.path.abspath(self.project_dir) + created_dirs: List[str] = [] + snapshot: Optional[TargetSnapshot] = None + # An existing virtualenv is too large to copy; a failed run says so. + venv_kept = self.options.with_venv and os.path.lexists( + os.path.join(project_dir, VENV_DIR) + ) + try: + # A fact, not a guess: a directory that appears between a check + # and its creation is treated as the user's. + created_dirs = make_directories(project_dir) + if project_dir not in created_dirs: + snapshot = TargetSnapshot.take( + project_dir, + paths, + trees=(VENV_DIR,) if self.options.with_venv else (), + directories=template_directories( + self.spec(manager), self.settings.FASTKIT_TEMPLATE_ROOT + ), + ) + try: + generated = generate( + self.spec(manager), + project_dir, + template_root=self.settings.FASTKIT_TEMPLATE_ROOT, + ) + except GenerationError as e: + replay_messages(e.messages) + raise + replay_messages(generated.messages) - venv_path = self._setup_environment(project_dir) + venv_path = self._setup_environment(project_dir, manager) + if snapshot is not None: + snapshot.discard() return ScaffoldResult( project_dir=project_dir, template=self.options.template, - app_module=self.app_module, - dependencies=dependencies, - metadata=metadata, + app_module=generated.app_module, + dependencies=generated.dependencies.all(), + metadata=dict(generated.metadata), venv_path=venv_path, + dev_dependencies=list(generated.dependencies.dev), ) - except Exception as e: - debug_log(f"Scaffolding failed, rolling back: {e}", "error") + except BaseException as e: + debug_log(f"Scaffolding failed, rolling back: {e!r}", "error") + self._roll_back(project_dir, created_dirs, snapshot, venv_kept) + raise + + def _roll_back( + self, + project_dir: str, + created_dirs: List[str], + snapshot: Optional[TargetSnapshot], + venv_kept: bool = False, + ) -> None: + """Undo a failed run: see :meth:`run`.""" + if snapshot is not None: + try: + failed = snapshot.restore() + except BaseException: + # Interrupted (a second Ctrl+C): the copies stay on disk. + if snapshot.backup_dir is not None: + print_warning( + "Restoring the existing files was interrupted; their " + f"original copies are kept in {snapshot.backup_dir}" + ) + raise + restored = len(snapshot.saved) - len(failed) + if restored: + print_info( + f"Restored {restored} existing file(s) to their state before " + "the run." + ) + if failed: + print_warning( + f"Could not restore {len(failed)} existing file(s): " + f"{', '.join(failed)}. Their original copies are kept in " + f"{snapshot.backup_dir}" + ) + if venv_kept: + print_warning( + f"The existing {VENV_DIR} was not restored; it is left as the " + "failed run left it." + ) + if project_dir in created_dirs: cleanup_failed_project( project_dir, self.settings.USER_WORKSPACE, self.options.create_project_folder, - project_dir_pre_existed=pre_existed, ) - raise + remove_created_directories( + directory for directory in created_dirs if directory != project_dir + ) # ---------------------------------------------------------------- # Pipeline steps # ---------------------------------------------------------------- - def existing_targets(self) -> List[str]: - """Project-relative files that a run would overwrite. + def _effective_package_manager(self) -> str: + """ + The package manager the project is generated and set up with. + + Without a virtualenv nothing is installed, so the requested manager + is used as is and no tool is looked for. With one, an installed + manager is needed: the requested one when it is there, else the first + installed one, announced with a warning. + + :raises BackendExceptions: If no package manager is installed + """ + requested = self.options.package_manager + if not self.options.with_venv: + return requested + effective = PackageManagerFactory.detect_manager( + self.project_dir, prefer=requested + ) + if effective != requested: + print_warning( + f"{requested} is not installed; the project is set up for " + f"{effective} instead.", + title="Package manager", + ) + return effective + + def _writable_paths(self, manager: str) -> List[str]: + """Project-relative paths a run with ``manager`` may write.""" + files = plan( + self.spec(manager), + self.project_dir, + template_root=self.settings.FASTKIT_TEMPLATE_ROOT, + ).files + paths = writable_paths(files, self.project_dir) + if self.options.with_venv: + paths.extend(SETUP_ARTIFACTS) + return paths + + def _refuse_symlinks(self, paths: List[str]) -> None: + """Stop before anything is written when the target holds a symlink + that generation would write through (see + :func:`~fastapi_fastkit.generation.pipeline.symlinked_targets`). - Only meaningful for an in-place deployment: the target directory is - the user's own workspace, so files planned by the template may - collide with work that is already there. + :raises BackendExceptions: If there is one + """ + if not os.path.isdir(self.project_dir): + return + links = symlinked_targets(self.project_dir, paths) + if not links: + return + print_warning( + f"Deploying into '{self.project_dir}' would write through " + f"{len(links)} symbolic link(s):" + ) + for relative_path in links: + console.print(f" [yellow]{relative_path}[/yellow]") + raise BackendExceptions(symlink_refusal(self.project_dir, links)) + + def existing_targets(self, paths: Optional[List[str]] = None) -> List[str]: + """Project-relative files that already exist and a run may overwrite. + + Meaningful when the target directory exists (an in-place deployment + into the user's workspace, or a project folder that is already + there): every path the run may write is checked, not only the + template's files, so an existing ``pyproject.toml`` or settings + module that generation rewrites is listed too. + + :param paths: The run's writable paths; computed when omitted """ project_dir = self.project_dir + if paths is None: + paths = self._writable_paths(self.options.package_manager) return [ relative_path - for relative_path in self._planned_files() + for relative_path in sorted(set(paths)) # The generated .env never replaces an existing one. if relative_path != ENV_FILE and os.path.isfile(os.path.join(project_dir, *relative_path.split("/"))) ] - def _confirm_overwrites(self) -> bool: + def _confirm_overwrites(self, paths: Optional[List[str]] = None) -> bool: """Ask before overwriting files that are already in the target directory. Returns True when the run may proceed and False when the user @@ -405,15 +565,20 @@ def _confirm_overwrites(self) -> bool: :raises BackendExceptions: If files would be overwritten, stdin is not interactive and ``assume_yes`` is not set """ - if self.options.create_project_folder: + if not os.path.isdir(self.project_dir): return True - clashes = self.existing_targets() + clashes = self.existing_targets(paths) if not clashes: return True + action = ( + "Generating into the existing folder" + if self.options.create_project_folder + else "Deploying in place" + ) print_warning( - f"Deploying in place will overwrite {len(clashes)} existing " + f"{action} will overwrite {len(clashes)} existing " f"file(s) in '{self.project_dir}':" ) for relative_path in clashes: @@ -428,7 +593,7 @@ def _confirm_overwrites(self) -> bool: # back. Not ScaffoldCancelled: nobody declined, and a script must # see a non-zero exit status. raise BackendExceptions( - f"Deploying in place would overwrite {len(clashes)} existing " + f"{action} would overwrite {len(clashes)} existing " f"file(s) in '{self.project_dir}' and there is no terminal to " "confirm it; re-run with --yes to allow it." ) @@ -442,90 +607,28 @@ def _require_template(self) -> None: f"'{self.settings.FASTKIT_TEMPLATE_ROOT}'." ) - def _write_dependency_files( - self, project_dir: str, dependencies: List[str] - ) -> None: - generate_dependency_file_with_manager( - project_dir, - dependencies, - self.options.package_manager, - self.options.project_name, - self.options.author, - self.options.author_email, - self.options.description, - ) - update_setup_py_dependencies(project_dir, dependencies) - print_success(f"Generated dependency file with {len(dependencies)} packages") - - def _config_generator(self, project_dir: str) -> DynamicConfigGenerator: - """Build a generator that knows this preset's file layout.""" - return DynamicConfigGenerator( - self.options.config or {}, - project_dir, - app_module=self.app_module, - main_py_relpath=self.strategist.profile.main_py_relpath, - db_config_relpath=self.strategist.profile.db_config_relpath, - auth_package_relpath=self.strategist.profile.auth_package_relpath, - settings_relpath=self.strategist.profile.settings_relpath, - shipped_paths=( - () - if self.strategist.should_regenerate_main - else self.strategist.profile.shipped_paths - ), - provide_pagination=self.strategist.profile.provide_pagination, - ) - def _generate_dynamic_config( self, project_dir: str, config: Dict[str, Any] ) -> None: - """Write the feature-driven modules on top of the deployed template. + """Write the feature-driven modules on top of a deployed template. - The generator owns the full artifact list; the only preset decision - left here is whether the dynamic ``main.py`` overlay replaces the - template-shipped entrypoint. For richer presets (classic-layered, - domain-starter) we keep the template's router-aware main.py intact. + Runs the generation pipeline's overlay step + (:func:`fastapi_fastkit.generation.pipeline.apply_feature_overlay`) + with this scaffolder's preset layout and prints what it reports. """ - generator = self._config_generator(project_dir) - include_main = self.strategist.should_regenerate_main - - if not include_main: - print_info( - f"Preserving template-shipped main.py for preset " - f"'{self.strategist.preset_id}'." - ) - - written = generator.generate_all_files(include_main=include_main) - - if "Dockerfile" in written or "docker-compose.yml" in written: - print_success("Generated Docker deployment files") - - # Presets that preserve their template's main.py still get the - # generated features mounted through the file's ``# fastkit:`` - # anchors; whatever can't be spliced in safely is reported instead - # so the user knows to wire it up themselves. - wired = self.strategist.wire_generated_routers(project_dir, config) - if wired: - print_success( - f"Wired generated features into " - f"{self.strategist.profile.main_py_relpath}: {', '.join(wired)}" - ) - for note in self.strategist.generation_notes(config): - print_info(note) - self.strategist.append_readme_notes(project_dir, config) - for conflict in self.strategist.auth_route_conflicts(project_dir, config): - print_warning(conflict, title="Authentication routes") - - # Surface preset-specific warnings (e.g. "you picked a preset whose - # shipped main.py we kept; Prometheus must be wired manually"). - for warning in self.strategist.compatibility_warnings(config, wired=wired): - print_warning(warning, title="Preset compatibility") - - print_success( - f"Generated {len(written)} configuration files for selected stack" - ) + with capture_messages() as messages: + try: + apply_feature_overlay( + project_dir, config, self.strategist, self.app_module + ) + finally: + replay_messages(list(messages)) - def _setup_environment(self, project_dir: str) -> str: + def _setup_environment( + self, project_dir: str, manager: Optional[str] = None + ) -> str: """Create the virtualenv and install dependencies, honouring opt-outs.""" + manager = manager or self.options.package_manager if not self.options.with_venv: print_info("Skipping virtual environment creation (--no-venv).") if self.options.with_install: @@ -534,59 +637,19 @@ def _setup_environment(self, project_dir: str) -> str: ) return "" - venv_path = create_venv_with_manager(project_dir, self.options.package_manager) + venv_path = create_venv_with_manager(project_dir, manager) if not self.options.with_install: print_info("Skipping dependency installation (--no-install).") return venv_path - install_dependencies_with_manager( - project_dir, venv_path, self.options.package_manager - ) + install_dependencies_with_manager(project_dir, venv_path, manager) return venv_path # ---------------------------------------------------------------- # Helpers # ---------------------------------------------------------------- - def _collect_features(self) -> List[str]: - """ - Flatten the selected features into ``":"`` entries. - - Recorded in project metadata so a later ``fastkit`` run (or a human) - can tell what the project was generated with. - """ - config = self.options.config or {} - features: List[str] = [] - - db_info = config.get("database", {}) - if isinstance(db_info, dict) and db_info.get("type", "None") != "None": - features.append(f"database:{db_info['type']}") - - for category in ( - FeatureAxis.AUTHENTICATION, - FeatureAxis.ASYNC_TASKS, - FeatureAxis.TESTING, - FeatureAxis.CACHING, - FeatureAxis.MONITORING, - FeatureAxis.MIGRATIONS, - FeatureAxis.LOGGING, - ): - choice = config.get(category, "None") - if isinstance(choice, str) and choice != "None": - features.append(f"{category}:{choice}") - - for axis in (FeatureAxis.UTILITIES, FeatureAxis.TOOLING): - for choice in config.get(axis, []) or []: - if choice != "None": - features.append(f"{axis}:{choice}") - - for target in config.get("deployment", []) or []: - if target != "None": - features.append(f"deployment:{target}") - - return features - def _planned_files(self) -> List[str]: """ List the project-relative files a real run would create. @@ -595,43 +658,7 @@ def _planned_files(self) -> List[str]: marker is stripped on copy), plus the extra modules the dynamic config generator writes for the selected features. """ - planned: List[str] = [] - - for root, _dirs, files in os.walk(self.template_dir): - for file_name in files: - relative_dir = os.path.relpath(root, self.template_dir) - converted = file_name.removesuffix("-tpl") - if relative_dir == ".": - planned.append(converted) - else: - planned.append(os.path.join(relative_dir, converted)) - - config = self.options.config or {} - if config: - planned.extend( - self._config_generator(self.project_dir).planned_files( - include_main=self.strategist.should_regenerate_main - ) - ) - deployment = config.get("deployment", []) - if deployment and deployment != ["None"]: - planned.append(".dockerignore") - - # ``.env`` is generated from ``.env.example`` (see - # ``create_local_env_file``) unless the target already has one. - if ENV_EXAMPLE_FILE in planned and not os.path.lexists( - os.path.join(self.project_dir, ENV_FILE) - ): - planned.append(ENV_FILE) - - if self.options.dependencies is not None: - planned.append( - self.settings.PACKAGE_MANAGER_CONFIG[self.options.package_manager][ - "dependency_file" - ] - ) - - return sorted(set(path.replace(os.sep, "/") for path in planned)) + return list(self._plan().files) def _add_tree_path(tree: Tree, relative_path: str) -> None: @@ -654,4 +681,5 @@ def _add_tree_path(tree: Tree, relative_path: str) -> None: "ScaffoldOptions", "ScaffoldResult", "cleanup_failed_project", + "replay_messages", ] diff --git a/src/fastapi_fastkit/backend/transducer.py b/src/fastapi_fastkit/backend/transducer.py index f6783f0d..9c7247d7 100644 --- a/src/fastapi_fastkit/backend/transducer.py +++ b/src/fastapi_fastkit/backend/transducer.py @@ -8,7 +8,7 @@ # -------------------------------------------------------------------------- import os import shutil -from typing import Dict, List, Optional +from typing import Collection, Dict, List, Optional from fastapi_fastkit.core.exceptions import TemplateExceptions from fastapi_fastkit.utils.logging import debug_log, get_logger @@ -105,10 +105,10 @@ def _normalize_line_endings(file_path: str, file_name: str) -> None: Templates checked out on Windows (or with ``core.autocrlf=true``) carry CRLF, which makes a generated project's shell scripts unusable inside a - Linux container: ``env: 'bash\r': No such file or directory``. The rewrite - happens in place through :func:`fix_script_line_endings`, which truncates - rather than recreates the file and therefore keeps the executable bit - ``shutil.copy2`` just carried over. + Linux container: ``env: 'bash\r': No such file or directory``. The file + is truncated and rewritten in place, so its mode is kept; executable bits + are set afterwards by the generation pipeline + (:func:`fastapi_fastkit.utils.filemodes.mark_executable`). :param file_path: Path of the copied file :param file_name: File name used for the text/binary decision @@ -116,16 +116,36 @@ def _normalize_line_endings(file_path: str, file_name: str) -> None: if not _looks_like_text_file(file_path, file_name): return - # Imported lazily: ``fastapi_fastkit.backend.inspection`` pulls in the - # scaffolder, which imports this module, so a top-level import would be - # circular. - from fastapi_fastkit.backend.inspection.fsutils import fix_script_line_endings + try: + with open(file_path, "rb") as f: + content = f.read() + normalized = content.replace(b"\r\n", b"\n").replace(b"\r", b"\n") + if normalized != content: + with open(file_path, "wb") as f: + f.write(normalized) + except OSError as e: + debug_log(f"Failed to fix line endings in {file_path}: {e}", "warning") - fix_script_line_endings(file_path) + +def same_file(path: str, other: str) -> bool: + """Whether two existing paths name the same file on this file system. + + ``.ENV`` and ``.env`` are one file on a case-insensitive file system + (Windows, macOS by default) and two elsewhere; asking the file system + is the only reliable answer. False when either path is missing. + """ + try: + return os.path.samefile(path, other) + except OSError: + return False def copy_and_convert_template( - template_dir: str, target_dir: str, project_name: str = "" + template_dir: str, + target_dir: str, + project_name: str = "", + *, + skip: Collection[str] = (), ) -> List[str]: """ Copies all files from the template directory to the target directory, @@ -136,6 +156,10 @@ def copy_and_convert_template( :type template_dir: str :param target_dir: The destination directory where files will be copied. :type target_dir: str + :param skip: Target-relative POSIX paths (converted names) never to + write, such as an existing ``.env`` the template also ships. A + template file whose destination is the same file on disk under + another case (``.ENV``) is skipped too. :raises OSError: If directory operations fail :raises PermissionError: If file access is denied :return: Absolute paths of the files this copy actually wrote. Callers use @@ -154,18 +178,22 @@ def copy_and_convert_template( debug_log(f"Failed to create target directory {target_path}: {e}", "error") raise - return _process_directory_tree(template_dir, target_path) + return _process_directory_tree(template_dir, target_path, skip) -def _process_directory_tree(template_dir: str, target_path: str) -> List[str]: +def _process_directory_tree( + template_dir: str, target_path: str, skip: Collection[str] = () +) -> List[str]: """ Process directory tree and copy files with template conversion. :param template_dir: Source template directory :param target_path: Target directory path + :param skip: Target-relative POSIX paths (converted names) to leave alone :return: Absolute paths of the written files """ copied: List[str] = [] + skip_paths = [os.path.join(target_path, *relpath.split("/")) for relpath in skip] for root, dirs, files in os.walk(template_dir): relative_path = os.path.relpath(root, template_dir) @@ -180,6 +208,18 @@ def _process_directory_tree(template_dir: str, target_path: str) -> List[str]: # Process files in current directory for file in files: + converted = file.removesuffix("-tpl") + relative_file = ( + converted + if relative_path == "." + else f"{relative_path.replace(os.sep, '/')}/{converted}" + ) + if relative_file in skip or any( + same_file(os.path.join(destination_dir, converted), skipped) + for skipped in skip_paths + ): + debug_log(f"Keeping the existing {relative_file}", "debug") + continue src_file = os.path.join(root, file) dst_file = _copy_template_file(src_file, destination_dir, file) if dst_file: @@ -230,7 +270,9 @@ def _copy_template_file( dst_file = os.path.join(destination_dir, dst_file_name) try: - shutil.copy2(src_file, dst_file) + # Content only: the mode a wheel or checkout carried must not leak + # into the project. Scripts are marked executable by name later. + shutil.copyfile(src_file, dst_file) _normalize_line_endings(dst_file, dst_file_name) debug_log(f"Copied {src_file} to {dst_file}", "debug") return dst_file diff --git a/src/fastapi_fastkit/catalog/__init__.py b/src/fastapi_fastkit/catalog/__init__.py new file mode 100644 index 00000000..2d809294 --- /dev/null +++ b/src/fastapi_fastkit/catalog/__init__.py @@ -0,0 +1,59 @@ +# -------------------------------------------------------------------------- +# The fastkit catalog: levels, presets, templates, package managers, feature +# axes with their options and packages, rules and FastAPI concepts. +# +# ``catalog.toml`` is the single source for CLI prompts, config validation, +# docs tables and the web generator. The package is pure stdlib and imports +# nothing else from fastkit, so it loads first and under Pyodide. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from .export import catalog_to_dict, dumps +from .i18n import apply_overlay, translatable_strings +from .loader import LANGUAGES, available_languages, load_catalog, parse_catalog +from .model import ( + Axis, + Catalog, + CatalogError, + Concept, + Defaults, + Level, + Option, + PackageManager, + Preset, + Rule, + SelectionValue, + Template, + canonical_name, + requirement_name, +) +from .rules import RuleOutcome, Selection, evaluate, selection_from_config + +__all__ = [ + "LANGUAGES", + "Axis", + "Catalog", + "CatalogError", + "Concept", + "Defaults", + "Level", + "Option", + "PackageManager", + "Preset", + "Rule", + "RuleOutcome", + "Selection", + "SelectionValue", + "Template", + "apply_overlay", + "available_languages", + "canonical_name", + "catalog_to_dict", + "dumps", + "evaluate", + "load_catalog", + "parse_catalog", + "requirement_name", + "selection_from_config", + "translatable_strings", +] diff --git a/src/fastapi_fastkit/catalog/__main__.py b/src/fastapi_fastkit/catalog/__main__.py new file mode 100644 index 00000000..5523e6a6 --- /dev/null +++ b/src/fastapi_fastkit/catalog/__main__.py @@ -0,0 +1,84 @@ +# -------------------------------------------------------------------------- +# ``python -m fastapi_fastkit.catalog {export,strings}`` +# +# ``export`` writes the catalog as JSON (docs build, web generator); +# ``strings`` prints the translation overlay skeleton as TOML. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import argparse +import json +import sys +from typing import Any, Mapping, Sequence + +from .export import dumps +from .i18n import translatable_strings +from .loader import LANGUAGES, load_catalog + + +def _toml_string(value: str) -> str: + # JSON string escapes are valid TOML basic-string escapes. + return json.dumps(value, ensure_ascii=False) + + +def strings_toml(skeleton: Mapping[str, Any]) -> str: + """ + Render :func:`~fastapi_fastkit.catalog.i18n.translatable_strings` as TOML. + + :param skeleton: ``{kind: {id: {field: text}}}`` + :return: TOML text with quoted table keys + """ + lines: list[str] = [] + for kind, entries in skeleton.items(): + for item_id, fields in entries.items(): + header = f"{kind}.{_toml_string(item_id)}" + lines.append(f"[{header}]") + for field, text in fields.items(): + if field != "options": + lines.append(f"{field} = {_toml_string(text)}") + lines.append("") + for option_id, texts in fields.get("options", {}).items(): + lines.append(f"[{header}.options.{_toml_string(option_id)}]") + for field, text in texts.items(): + lines.append(f"{field} = {_toml_string(text)}") + lines.append("") + return "\n".join(lines) + + +def _write_stdout(text: str) -> None: + # UTF-8 regardless of the console code page, so piping the output into + # a file gives the same bytes on every platform. + buffer = getattr(sys.stdout, "buffer", None) + if buffer is None: + sys.stdout.write(text) + return + sys.stdout.flush() + buffer.write(text.encode("utf-8")) + buffer.flush() + + +def main(argv: Sequence[str] | None = None) -> int: + """Entry point of ``python -m fastapi_fastkit.catalog``.""" + parser = argparse.ArgumentParser(prog="python -m fastapi_fastkit.catalog") + commands = parser.add_subparsers(dest="command", required=True) + export = commands.add_parser("export", help="write the catalog as JSON") + export.add_argument("--lang", default="en", choices=LANGUAGES) + export.add_argument("--out", help="output file (default: standard output)") + commands.add_parser("strings", help="print the translation overlay skeleton") + args = parser.parse_args(argv) + + if args.command == "export": + text = dumps(load_catalog(args.lang)) + if args.out: + with open(args.out, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text) + else: + _write_stdout(text) + return 0 + + _write_stdout(strings_toml(translatable_strings(load_catalog()))) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/fastapi_fastkit/catalog/catalog.toml b/src/fastapi_fastkit/catalog/catalog.toml new file mode 100644 index 00000000..610cde88 --- /dev/null +++ b/src/fastapi_fastkit/catalog/catalog.toml @@ -0,0 +1,669 @@ +# FastAPI-fastkit catalog: the single source for CLI prompts, config +# validation, docs tables and the web generator. +# +# Array order is the display order everywhere. Unknown keys are a load error, +# so the loader and this file are extended together. English text is the base +# language; translations live in ``i18n/.toml`` overlays. + +schema_version = 1 + +[defaults] +level = "hello" +preset = "domain-starter" +package_manager = "uv" +# Added by every feature-based project (``init --interactive`` / ``--config``). +base_dependencies = ["fastapi", "uvicorn", "pydantic", "pydantic-settings"] + +# ---------------------------------------------------------------- concepts +# Concept id -> official FastAPI documentation page. Stage 4 writes at most one +# concept comment per concept per project, ending with this URL. +[[concepts]] +id = "path-parameters" +title = "Path parameters" +url = "https://fastapi.tiangolo.com/tutorial/path-params/" + +[[concepts]] +id = "query-parameters" +title = "Query parameters" +url = "https://fastapi.tiangolo.com/tutorial/query-params/" + +[[concepts]] +id = "request-body" +title = "Request body" +url = "https://fastapi.tiangolo.com/tutorial/body/" + +[[concepts]] +id = "response-model" +title = "Response model" +url = "https://fastapi.tiangolo.com/tutorial/response-model/" + +[[concepts]] +id = "status-codes" +title = "Response status codes" +url = "https://fastapi.tiangolo.com/tutorial/response-status-code/" + +[[concepts]] +id = "handling-errors" +title = "Handling errors" +url = "https://fastapi.tiangolo.com/tutorial/handling-errors/" + +[[concepts]] +id = "dependencies" +title = "Dependencies" +url = "https://fastapi.tiangolo.com/tutorial/dependencies/" + +[[concepts]] +id = "bigger-applications" +title = "Bigger applications with multiple files" +url = "https://fastapi.tiangolo.com/tutorial/bigger-applications/" + +[[concepts]] +id = "settings" +title = "Settings and environment variables" +url = "https://fastapi.tiangolo.com/advanced/settings/" + +[[concepts]] +id = "lifespan" +title = "Lifespan events" +url = "https://fastapi.tiangolo.com/advanced/events/" + +[[concepts]] +id = "sql-databases" +title = "SQL databases" +url = "https://fastapi.tiangolo.com/tutorial/sql-databases/" + +[[concepts]] +id = "security-jwt" +title = "OAuth2 with password and JWT tokens" +url = "https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/" + +[[concepts]] +id = "cors" +title = "CORS" +url = "https://fastapi.tiangolo.com/tutorial/cors/" + +[[concepts]] +id = "middleware" +title = "Middleware" +url = "https://fastapi.tiangolo.com/tutorial/middleware/" + +[[concepts]] +id = "testing" +title = "Testing" +url = "https://fastapi.tiangolo.com/tutorial/testing/" + +[[concepts]] +id = "background-tasks" +title = "Background tasks" +url = "https://fastapi.tiangolo.com/tutorial/background-tasks/" + +[[concepts]] +id = "websockets" +title = "WebSockets" +url = "https://fastapi.tiangolo.com/advanced/websockets/" + +[[concepts]] +id = "deployment-docker" +title = "FastAPI in containers (Docker)" +url = "https://fastapi.tiangolo.com/deployment/docker/" + +[[concepts]] +id = "async" +title = "Concurrency and async / await" +url = "https://fastapi.tiangolo.com/async/" + +# ------------------------------------------------------------------ levels +# A level uses either ``template`` (no preset, no feature overlay) or +# ``preset`` (template comes from the preset). ``bundle`` holds feature +# selections applied on top, validated against ``rules`` at load time. +[[levels]] +id = "hello" +label = "Hello" +description = "One main.py with three async endpoints, an in-memory store and tests." +template = "fastapi-hello" +asks_database = false +concepts = ["path-parameters", "query-parameters", "request-body", "status-codes", "testing"] + +[[levels]] +id = "single-file" +label = "Single file" +description = "The whole application in one module, with settings and tests next to it." +preset = "single-module" +asks_database = true +concepts = ["response-model", "handling-errors", "settings", "testing"] + +[[levels]] +id = "layered" +label = "Layered" +description = "A layered split into routes, CRUD, schemas and core configuration." +preset = "classic-layered" +asks_database = true +concepts = ["bigger-applications", "dependencies", "response-model", "settings"] + +[[levels]] +id = "domain" +label = "Domain" +description = "One package per domain concept with router, service and repository." +preset = "domain-starter" +asks_database = true +concepts = ["bigger-applications", "dependencies", "lifespan", "settings"] + +[[levels]] +id = "production" +label = "Production" +description = "The domain layout with PostgreSQL, Alembic, JWT login, coverage, structured logs, ruff, CI and Docker." +preset = "domain-starter" +asks_database = true +concepts = ["bigger-applications", "dependencies", "sql-databases", "security-jwt", "deployment-docker"] + +[levels.bundle] +database = "PostgreSQL" +migrations = "Alembic" +authentication = "JWT" +testing = "Coverage" +logging = "structured" +tooling = ["ruff", "github-actions"] +deployment = ["Docker", "docker-compose"] + +# ----------------------------------------------------------------- presets +[[presets]] +id = "minimal" +template = "fastapi-empty" +summary = "Smallest viable FastAPI app โ€” a single app + a couple of files." + +[[presets]] +id = "single-module" +template = "fastapi-single-module" +summary = "Everything in one module; ideal for tiny scripts and prototypes." + +[[presets]] +id = "classic-layered" +template = "fastapi-default" +summary = "Layered split: api/routes, crud, schemas, core (a la fastapi-default)." + +[[presets]] +id = "domain-starter" +template = "fastapi-domain-starter" +summary = "Domain-oriented: src/app/domains// with router/service/repository (recommended)." + +# --------------------------------------------------------------- templates +# kind: "level" (reachable through a level), "example" (``--template`` only), +# "internal" (still listed in stage 2; ``fastapi-empty`` is removed in stage 3). +# ``description`` equals the template README's first heading (tested). +[[templates]] +id = "fastapi-hello" +kind = "level" +description = "Smallest FastAPI app: three endpoints, one model, their tests" +concepts = ["path-parameters", "query-parameters", "request-body", "status-codes", "testing"] + +[[templates]] +id = "fastapi-empty" +kind = "internal" +description = "Minimal FastAPI Template" +concepts = [] + +[[templates]] +id = "fastapi-single-module" +kind = "level" +description = "FastAPI Single Module Template" +concepts = ["response-model", "settings", "testing"] + +[[templates]] +id = "fastapi-default" +kind = "level" +description = "Simple FastAPI Project" +concepts = ["bigger-applications", "dependencies", "response-model", "settings"] + +[[templates]] +id = "fastapi-domain-starter" +kind = "level" +description = "FastAPI Domain Starter" +concepts = ["bigger-applications", "dependencies", "lifespan", "settings"] + +[[templates]] +id = "fastapi-custom-response" +kind = "example" +description = "Async Item Management API with Custom Response System" +concepts = ["response-model", "handling-errors", "async"] + +[[templates]] +id = "fastapi-auth-jwt" +kind = "example" +description = "FastAPI JWT Authentication" +concepts = ["security-jwt", "dependencies"] + +[[templates]] +id = "fastapi-sqlmodel" +kind = "example" +description = "FastAPI SQLModel" +concepts = ["sql-databases", "dependencies"] + +[[templates]] +id = "fastapi-mcp" +kind = "example" +description = "FastAPI MCP Project" +concepts = ["security-jwt", "bigger-applications"] + +[[templates]] +id = "fastapi-llm-agent" +kind = "example" +description = "FastAPI LLM Agent" +concepts = ["async", "settings"] + +# -------------------------------------------------------- package managers +[[package_managers]] +id = "pip" +dependency_file = "requirements.txt" +executable = "pip" +description = "Standard Python package manager" + +[[package_managers]] +id = "uv" +dependency_file = "pyproject.toml" +executable = "uv" +description = "Fast Python package manager" + +[[package_managers]] +id = "pdm" +dependency_file = "pyproject.toml" +executable = "pdm" +description = "Modern Python dependency management" + +[[package_managers]] +id = "poetry" +dependency_file = "pyproject.toml" +executable = "poetry" +description = "Python dependency management and packaging" + +# -------------------------------------------------------------------- axes +# section = "features" -> part of FeatureAxis / PACKAGE_CATALOG / list-features +# section = "deployment" -> the ``deployment`` config key (not a FeatureAxis) +# +# Options keep the order prompts show them in, with ``None`` last (prompt +# defaults depend on it). ``label`` defaults to the id. ``summary`` is the +# text a prompt shows; options without one are shown with their packages. +# ``runtime`` packages go to [project].dependencies / requirements.txt, +# ``dev`` packages to the dev group / requirements-dev.txt. +# Package choices are based on recommendations from +# https://github.com/mjhea0/awesome-fastapi +[[axes]] +id = "database" +label = "Database" +description = "Database and ORM selection" +section = "features" +multi = false +default = "None" + + [[axes.options]] + id = "PostgreSQL" + # The generated database module is async (``sqlalchemy.ext.asyncio``), + # which needs greenlet. SQLAlchemy 2.1 only installs it through the + # ``asyncio`` extra, and 2.0 skipped it on some platforms (macOS arm64). + runtime = ["asyncpg", "sqlalchemy[asyncio]"] + tags = ["sql"] + concepts = ["sql-databases"] + + [[axes.options]] + id = "MySQL" + runtime = ["aiomysql", "sqlalchemy[asyncio]"] + tags = ["sql"] + concepts = ["sql-databases"] + + [[axes.options]] + id = "MongoDB" + # PyMongo's native asyncio client (AsyncMongoClient, PyMongo 4.13+) + # replaces Motor, which MongoDB deprecated on 2026-05-14. The floor keeps + # an older environment or constraint file from resolving to a release + # without it (or with the beta API). + runtime = ["pymongo>=4.13"] + + [[axes.options]] + id = "Redis" + # ``aioredis`` is abandoned (merged into redis-py) and does not install on + # Python 3.12; redis[hiredis] ships the asyncio client. + runtime = ["redis[hiredis]"] + + [[axes.options]] + id = "SQLite" + runtime = ["sqlalchemy[asyncio]", "aiosqlite"] + tags = ["sql"] + concepts = ["sql-databases"] + + [[axes.options]] + id = "None" + none = true + +[[axes]] +id = "authentication" +label = "Authentication" +description = "User authentication and authorization" +section = "features" +multi = false +default = "None" + + [[axes.options]] + id = "JWT" + summary = "OAuth2 password flow with JWT (recommended for APIs)" + # OAuth2PasswordRequestForm needs python-multipart; EmailStr needs + # email-validator. PyJWT signs the tokens, pwdlib hashes (argon2). + runtime = ["pyjwt[crypto]", "pwdlib[argon2]", "email-validator", "python-multipart"] + concepts = ["security-jwt"] + + [[axes.options]] + id = "OAuth2" + summary = "OAuth2 with authlib" + # SessionMiddleware (used by the OAuth2 login flow) needs itsdangerous. + # Authlib talks to the providers through httpx2 (it falls back to httpx + # with an AuthlibDeprecationWarning), and the generated router catches + # httpx2's errors, so httpx2 is what gets installed. + runtime = ["authlib", "itsdangerous", "httpx2"] + concepts = ["middleware"] + + [[axes.options]] + id = "FastAPI-Users" + summary = "Complete user management (JWT; SQL databases only)" + # The generated module targets the FastAPI-Users 15 API (it pins pwdlib, + # PyJWT and python-multipart itself). SQL databases only. + runtime = ["fastapi-users[sqlalchemy]>=15.0.5,<16"] + concepts = ["security-jwt"] + + [[axes.options]] + id = "Session-based" + summary = "Traditional session-based authentication" + runtime = ["itsdangerous", "pwdlib[argon2]", "email-validator"] + concepts = ["middleware"] + + [[axes.options]] + id = "None" + none = true + summary = "No authentication" + +[[axes]] +id = "async_tasks" +label = "Background tasks" +description = "Background task processing" +section = "features" +multi = false +default = "None" + + [[axes.options]] + id = "Celery" + runtime = ["celery[redis]", "redis[hiredis]"] + concepts = ["background-tasks"] + + [[axes.options]] + id = "Dramatiq" + runtime = ["dramatiq[redis]", "redis[hiredis]"] + concepts = ["background-tasks"] + + [[axes.options]] + id = "None" + none = true + +[[axes]] +id = "testing" +label = "Testing" +description = "Testing framework and tools" +section = "features" +multi = false +# The prompt has always pre-selected the second entry (Coverage). +default = "Coverage" + + [[axes.options]] + id = "Basic" + summary = "pytest + httpx for API testing" + # Starlette's TestClient is built on httpx2 and warns when it has to fall + # back to httpx; httpx stays for tests that use its AsyncClient / + # ASGITransport directly. + dev = ["pytest", "pytest-asyncio", "httpx", "httpx2"] + concepts = ["testing"] + + [[axes.options]] + id = "Coverage" + summary = "Basic + code coverage" + dev = ["pytest", "pytest-asyncio", "pytest-cov", "httpx", "httpx2"] + concepts = ["testing"] + + [[axes.options]] + id = "Advanced" + summary = "Coverage + faker + factory-boy for fixtures" + dev = ["pytest", "pytest-asyncio", "pytest-cov", "httpx", "httpx2", "faker", "factory-boy"] + concepts = ["testing"] + + [[axes.options]] + id = "None" + none = true + summary = "No testing framework" + +[[axes]] +id = "caching" +label = "Caching" +description = "Response and data caching" +section = "features" +multi = false +default = "None" + + [[axes.options]] + id = "Redis" + # fastapi-cache2 imports starlette.templating at module scope, which + # hard-requires jinja2; without it the app fails to import. + runtime = ["redis[hiredis]", "fastapi-cache2", "jinja2"] + + [[axes.options]] + id = "None" + none = true + +[[axes]] +id = "monitoring" +label = "Monitoring" +description = "Application monitoring and logging" +section = "features" +multi = false +default = "None" + + [[axes.options]] + id = "Loguru" + summary = "Enhanced logging with Loguru" + runtime = ["loguru"] + + [[axes.options]] + id = "OpenTelemetry" + summary = "Distributed tracing and metrics" + runtime = [ + "opentelemetry-api", + "opentelemetry-sdk", + "opentelemetry-instrumentation-fastapi", + "opentelemetry-exporter-otlp-proto-http", + ] + concepts = ["middleware"] + + [[axes.options]] + id = "Prometheus" + summary = "Prometheus metrics instrumentation" + runtime = ["prometheus-client", "prometheus-fastapi-instrumentator"] + concepts = ["middleware"] + + [[axes.options]] + id = "None" + none = true + summary = "No additional monitoring" + +[[axes]] +id = "utilities" +label = "Utilities" +description = "Additional utilities and middleware" +section = "features" +multi = true +default = "None" + + [[axes.options]] + id = "CORS" + # Built in to FastAPI; every project has it. Accepted in saved configs, + # never offered. + built_in = true + concepts = ["cors"] + + [[axes.options]] + id = "Rate-Limiting" + summary = "Per-client API rate limits (limits)" + # The generated middleware uses ``limits`` directly: slowapi's + # SlowAPIMiddleware skips routes added with include_router. It needs + # ``limits.aio`` and ``WindowStats.reset_time``; 3.4 is the first release + # where that works on Python 3.12 (older ones import ``pkg_resources``). + runtime = ["limits>=3.4"] + concepts = ["middleware"] + + [[axes.options]] + id = "Pagination" + # Built into the generated list endpoints (core/pagination.py); kept + # selectable for saved configs. + built_in = true + concepts = ["query-parameters"] + + [[axes.options]] + id = "WebSocket" + summary = "Example WebSocket endpoint (websockets)" + runtime = ["websockets"] + concepts = ["websockets"] + + [[axes.options]] + id = "None" + none = true + +[[axes]] +id = "migrations" +label = "Migrations" +description = "Database schema migrations" +section = "features" +multi = false +default = "None" + + [[axes.options]] + id = "Alembic" + # The prompt appends a recommendation for SQL databases (code). + summary = "alembic.ini + async alembic/env.py + scripts/migrate.sh" + # Runtime: the container's migrate script runs it. + runtime = ["alembic"] + concepts = ["sql-databases"] + + [[axes.options]] + id = "None" + none = true + summary = "No migration tooling" + +[[axes]] +id = "tooling" +label = "Developer tooling" +description = "Developer tooling and CI configuration" +section = "features" +multi = true +default = "None" + + [[axes.options]] + id = "ruff" + summary = "ruff + ruff-format config in pyproject.toml (replaces black/isort)" + dev = ["ruff"] + + [[axes.options]] + id = "pre-commit" + summary = ".pre-commit-config.yaml" + dev = ["pre-commit"] + + [[axes.options]] + id = "github-actions" + # Workflow file only. + summary = ".github/workflows/test.yml (Python 3.12)" + + [[axes.options]] + id = "devcontainer" + # devcontainer.json only. + summary = ".devcontainer/devcontainer.json" + + [[axes.options]] + id = "makefile" + # Makefile only. + summary = "Makefile with install/test/lint/format/run" + + [[axes.options]] + id = "None" + none = true + +[[axes]] +id = "logging" +label = "Logging" +description = "Application logging format" +section = "features" +multi = false +default = "None" + + [[axes.options]] + id = "structured" + summary = "JSON logs + X-Request-ID correlation middleware (stdlib only)" + # Stdlib ``logging`` + ``json`` only; no third-party dependency. + concepts = ["middleware"] + + [[axes.options]] + id = "None" + none = true + summary = "Uvicorn's default plain-text logging" + +[[axes]] +id = "deployment" +label = "Deployment" +description = "Container deployment files" +section = "deployment" +multi = true +default = "None" + + [[axes.options]] + id = "Docker" + summary = "Generate Dockerfile" + concepts = ["deployment-docker"] + + [[axes.options]] + id = "docker-compose" + summary = "Generate docker-compose.yml (includes Docker)" + concepts = ["deployment-docker"] + + [[axes.options]] + id = "None" + none = true + summary = "No deployment configuration" + +# ------------------------------------------------------------------- rules +# kind = "requires": when matches and the required axis value is outside +# ``require``, the selection is invalid; ``message`` placeholders: +# {allowed} = comma-joined allowed values, {selected} = "no " or +# " ''" (axis id with "_" -> " "). +# kind = "implies": when matches, values in ``add`` are added. +# kind = "adds": when matches, ``runtime`` / ``dev`` packages are added. +# kind = "note": when matches, ``message`` is an informational note. +# ``when`` values: a string, a list (any of), or "*" (anything but None / +# a non-empty multi selection). All keys must match. +[[rules]] +id = "fastapi-users-needs-sql" +kind = "requires" +when = { authentication = "FastAPI-Users" } +require = { database = ["PostgreSQL", "MySQL", "SQLite"] } +message = "Authentication 'FastAPI-Users' needs a SQL database ({allowed}), but {selected} is selected. Choose one of those databases, or the 'JWT' option, which works with every database." + +[[rules]] +id = "compose-implies-docker" +kind = "implies" +# docker-compose.yml builds the image the Dockerfile describes. +when = { deployment = "docker-compose" } +add = { deployment = ["Docker"] } + +[[rules]] +id = "sqlite-for-tests" +kind = "adds" +# Generated tests run on in-memory SQLite (sqlite+aiosqlite://, set by the +# root conftest.py), so PostgreSQL / MySQL projects with tests need aiosqlite. +when = { testing = "*", database = ["PostgreSQL", "MySQL"] } +dev = ["aiosqlite"] + +[[rules]] +id = "shared-redis" +kind = "note" +when = { caching = "Redis", async_tasks = ["Celery", "Dramatiq"] } +message = "Info: Redis will be used for both caching and task queue (shared dependency)." diff --git a/src/fastapi_fastkit/catalog/export.py b/src/fastapi_fastkit/catalog/export.py new file mode 100644 index 00000000..ee2a5c62 --- /dev/null +++ b/src/fastapi_fastkit/catalog/export.py @@ -0,0 +1,126 @@ +# -------------------------------------------------------------------------- +# JSON export of the catalog (docs tables and the web generator read it). +# +# The output depends on the catalog and fastkit's version only: no paths, +# no timestamps, keys in a fixed order, lists in catalog order. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import json +from typing import Any, Mapping + +from .model import Catalog + + +def _values(mapping: Mapping[str, Any]) -> dict[str, Any]: + return { + key: list(value) if isinstance(value, tuple) else value + for key, value in mapping.items() + } + + +def catalog_to_dict(catalog: Catalog) -> dict[str, Any]: + """ + The catalog as plain JSON-ready data. + + :param catalog: Catalog to export + :return: Mapping with the keys ``schema_version``, ``fastkit_version``, + ``lang``, ``defaults``, ``levels``, ``presets``, ``templates``, + ``package_managers``, ``axes``, ``rules`` and ``concepts`` + """ + # Imported here: the package ``__init__`` holds only the version string, + # and the catalog must not import anything else from fastkit. + from fastapi_fastkit import __version__ + + return { + "schema_version": catalog.schema_version, + "fastkit_version": __version__, + "lang": catalog.lang, + "defaults": { + "level": catalog.defaults.level, + "preset": catalog.defaults.preset, + "package_manager": catalog.defaults.package_manager, + "base_dependencies": list(catalog.defaults.base_dependencies), + }, + "levels": [ + { + "id": level.id, + "label": level.label, + "description": level.description, + "template": level.template, + "preset": level.preset, + "asks_database": level.asks_database, + "bundle": _values(level.bundle), + "concepts": list(level.concepts), + } + for level in catalog.levels + ], + "presets": [ + {"id": preset.id, "template": preset.template, "summary": preset.summary} + for preset in catalog.presets + ], + "templates": [ + { + "id": template.id, + "kind": template.kind, + "description": template.description, + "concepts": list(template.concepts), + } + for template in catalog.templates + ], + "package_managers": [ + { + "id": manager.id, + "dependency_file": manager.dependency_file, + "description": manager.description, + } + for manager in catalog.package_managers + ], + "axes": [ + { + "id": axis.id, + "label": axis.label, + "description": axis.description, + "section": axis.section, + "multi": axis.multi, + "default": axis.default, + "options": [ + { + "id": option.id, + "label": option.label, + "summary": option.summary, + "runtime": list(option.runtime), + "dev": list(option.dev), + "tags": list(option.tags), + "concepts": list(option.concepts), + "none": option.none, + "built_in": option.built_in, + } + for option in axis.options + ], + } + for axis in catalog.axes + ], + "rules": [ + { + "id": rule.id, + "kind": rule.kind, + "when": _values(rule.when), + "require": _values(rule.require), + "add": _values(rule.add), + "runtime": list(rule.runtime), + "dev": list(rule.dev), + "message": rule.message, + } + for rule in catalog.rules + ], + "concepts": [ + {"id": concept.id, "title": concept.title, "url": concept.url} + for concept in catalog.concepts + ], + } + + +def dumps(catalog: Catalog) -> str: + """The catalog as indented JSON text ending in a newline.""" + return json.dumps(catalog_to_dict(catalog), indent=2, ensure_ascii=False) + "\n" diff --git a/src/fastapi_fastkit/catalog/i18n.py b/src/fastapi_fastkit/catalog/i18n.py new file mode 100644 index 00000000..0b2c418f --- /dev/null +++ b/src/fastapi_fastkit/catalog/i18n.py @@ -0,0 +1,164 @@ +# -------------------------------------------------------------------------- +# Translation overlays for the catalog. +# +# English text lives in ``catalog.toml``. ``i18n/.toml`` overlays +# replace the text fields listed in ``_FIELDS``; a key the overlay leaves out +# keeps its English text, and a key the base catalog does not have is an +# error (no orphans). Ids, package names and URLs are never translated. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import string +from dataclasses import replace +from typing import Any, Mapping, TypeVar + +from .model import Axis, Catalog, CatalogError, Option +from .rules import check_message + +#: Translatable fields per kind (the overlay's top-level tables). +_FIELDS: dict[str, tuple[str, ...]] = { + "levels": ("label", "description"), + "presets": ("summary",), + "templates": ("description",), + "package_managers": ("description",), + "axes": ("label", "description"), + "rules": ("message",), + "concepts": ("title",), +} +_OPTION_FIELDS = ("label", "summary") + +_T = TypeVar("_T") + + +def _placeholders(text: str, where: str) -> set[str]: + try: + return { + field + for _, field, _, _ in string.Formatter().parse(text) + if field is not None + } + except ValueError as error: + raise CatalogError(f"{where}: not a valid format string ({error})") from error + + +def _text_fields( + entry: Mapping[str, Any], allowed: tuple[str, ...], where: str +) -> dict[str, str]: + if not isinstance(entry, Mapping): + raise CatalogError(f"{where}: expected a table") + result: dict[str, str] = {} + for key, value in entry.items(): + if key not in allowed: + raise CatalogError(f"{where}: '{key}' is not translatable") + if not isinstance(value, str) or not value: + raise CatalogError(f"{where}.{key}: must be a non-empty string") + result[key] = value + return result + + +def _translated(item: _T, fields: dict[str, str], where: str) -> _T: + for key in fields: + if getattr(item, key) is None: + raise CatalogError( + f"{where}.{key}: the base catalog has no English text to translate" + ) + return replace(item, **fields) # type: ignore[type-var] + + +def _overlay_options(axis: Axis, raw: Any, where: str) -> tuple[Option, ...]: + if not isinstance(raw, Mapping): + raise CatalogError(f"{where}: expected a table") + options = list(axis.options) + index = {option.id: position for position, option in enumerate(options)} + for option_id, entry in raw.items(): + option_where = f'{where}."{option_id}"' + if option_id not in index: + raise CatalogError(f"{option_where}: unknown option") + fields = _text_fields(entry, _OPTION_FIELDS, option_where) + position = index[option_id] + options[position] = _translated(options[position], fields, option_where) + return tuple(options) + + +def apply_overlay(catalog: Catalog, overlay: Mapping[str, Any], lang: str) -> Catalog: + """ + Return ``catalog`` with the overlay's text applied (pure). + + :param catalog: The English base catalog + :param overlay: Parsed overlay, shaped like :func:`translatable_strings` + :param lang: Language recorded on the result + :return: The translated catalog + :raises CatalogError: For an unknown kind, id or field, a non-string + value, or a rule message whose placeholders differ from English + """ + changes: dict[str, Any] = {"lang": lang} + for kind, entries in overlay.items(): + if kind not in _FIELDS: + raise CatalogError(f"i18n/{lang}: unknown table '{kind}'") + if not isinstance(entries, Mapping): + raise CatalogError(f"i18n/{lang}.{kind}: expected a table") + items = list(getattr(catalog, kind)) + index = {item.id: position for position, item in enumerate(items)} + for item_id, entry in entries.items(): + where = f'i18n/{lang}.{kind}."{item_id}"' + if item_id not in index: + raise CatalogError(f"{where}: unknown id") + position = index[item_id] + item = items[position] + if kind == "axes" and isinstance(entry, Mapping) and "options" in entry: + entry = dict(entry) + options = _overlay_options( + item, entry.pop("options"), f"{where}.options" + ) + item = replace(item, options=options) + fields = _text_fields(entry, _FIELDS[kind], where) + if kind == "rules" and "message" in fields: + english = _placeholders(item.message or "", f"{where}.message") + if _placeholders(fields["message"], f"{where}.message") != english: + raise CatalogError( + f"{where}.message: placeholders must match the English " + f"message ({', '.join(sorted(english)) or 'none'})" + ) + check_message(item.kind, fields["message"], f"{where}.message") + items[position] = _translated(item, fields, where) + changes[kind] = tuple(items) + return replace(catalog, **changes) + + +def translatable_strings(catalog: Catalog) -> dict[str, Any]: + """ + The overlay skeleton filled with the catalog's (English) text. + + Covers every translatable field that has text: level labels and + descriptions, preset summaries, template and package-manager + descriptions, axis labels and descriptions, option summaries and the + labels of ``None`` options, rule messages and concept titles. + + :param catalog: Catalog to read + :return: ``{kind: {id: {field: text}}}``; axes carry an ``options`` table + """ + result: dict[str, Any] = {} + for kind, fields in _FIELDS.items(): + entries: dict[str, Any] = {} + for item in getattr(catalog, kind): + values: dict[str, Any] = { + field: getattr(item, field) + for field in fields + if getattr(item, field) is not None + } + if kind == "axes": + options: dict[str, Any] = {} + for option in item.options: + texts: dict[str, str] = {} + if option.none: + texts["label"] = option.label + if option.summary is not None: + texts["summary"] = option.summary + if texts: + options[option.id] = texts + if options: + values["options"] = options + if values: + entries[item.id] = values + result[kind] = entries + return result diff --git a/src/fastapi_fastkit/catalog/i18n/.gitkeep b/src/fastapi_fastkit/catalog/i18n/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/src/fastapi_fastkit/catalog/loader.py b/src/fastapi_fastkit/catalog/loader.py new file mode 100644 index 00000000..49e93203 --- /dev/null +++ b/src/fastapi_fastkit/catalog/loader.py @@ -0,0 +1,620 @@ +# -------------------------------------------------------------------------- +# Read, validate and cache ``catalog.toml``. +# +# Resources are read through ``importlib.resources`` only (no ``__file__``, +# no ``os.path``), so the catalog loads from a wheel, a zip and Pyodide's +# in-memory file system alike. Every validation failure raises +# ``CatalogError`` naming the offending entry. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import tomllib +from dataclasses import replace +from functools import lru_cache +from importlib.resources import files +from importlib.resources.abc import Traversable +from types import MappingProxyType +from typing import Any, Mapping + +from .model import ( + Axis, + Catalog, + CatalogError, + Concept, + Defaults, + Level, + Option, + PackageManager, + Preset, + Rule, + SelectionValue, + Template, +) +from .rules import WILDCARD, check_implications, check_message, evaluate + +#: Languages the docs site is published in; ``load_catalog`` accepts these. +LANGUAGES: tuple[str, ...] = ("en", "ko", "ja", "zh", "es", "fr", "de") + +#: The only schema version this loader understands. +SCHEMA_VERSION = 1 + +#: Prefix every concept URL must start with (official FastAPI docs). +CONCEPT_URL_PREFIX = "https://fastapi.tiangolo.com/" + +_PACKAGE = "fastapi_fastkit.catalog" +_CATALOG_FILE = "catalog.toml" +_I18N_DIR = "i18n" + +_TOP_LEVEL_KEYS = frozenset( + { + "schema_version", + "defaults", + "concepts", + "levels", + "presets", + "templates", + "package_managers", + "axes", + "rules", + } +) +_RULE_KINDS = ("requires", "implies", "adds", "note") +_TEMPLATE_KINDS = ("level", "example", "internal") +_AXIS_SECTIONS = ("features", "deployment") + + +def resource_root() -> Traversable: + """The catalog package directory as an ``importlib.resources`` traversable.""" + return files(_PACKAGE) + + +class _Table: + """Typed access to one TOML table, tracking the keys that were read.""" + + def __init__(self, data: Any, where: str) -> None: + if not isinstance(data, dict): + raise CatalogError(f"{where}: expected a table") + self.data: dict[str, Any] = data + self.where = where + self._seen: set[str] = set() + + def _get(self, key: str, required: bool) -> Any: + self._seen.add(key) + if key not in self.data: + if required: + raise CatalogError(f"{self.where}: missing required key '{key}'") + return None + return self.data[key] + + def string(self, key: str) -> str: + value = self._get(key, True) + if not isinstance(value, str) or not value: + raise CatalogError(f"{self.where}: '{key}' must be a non-empty string") + return value + + def optional_string(self, key: str) -> str | None: + value = self._get(key, False) + if value is None: + return None + if not isinstance(value, str) or not value: + raise CatalogError(f"{self.where}: '{key}' must be a non-empty string") + return value + + def boolean(self, key: str, default: bool | None = None) -> bool: + value = self._get(key, default is None) + if value is None: + assert default is not None + return default + if not isinstance(value, bool): + raise CatalogError(f"{self.where}: '{key}' must be true or false") + return value + + def integer(self, key: str) -> int: + value = self._get(key, True) + if not isinstance(value, int) or isinstance(value, bool): + raise CatalogError(f"{self.where}: '{key}' must be an integer") + return value + + def strings(self, key: str) -> tuple[str, ...]: + value = self._get(key, False) + if value is None: + return () + if not isinstance(value, list) or not all( + isinstance(item, str) and item for item in value + ): + raise CatalogError(f"{self.where}: '{key}' must be a list of strings") + return tuple(value) + + def table(self, key: str, required: bool = False) -> "_Table | None": + value = self._get(key, required) + if value is None: + return None + return _Table(value, f"{self.where}.{key}") + + def tables(self, key: str) -> list["_Table"]: + value = self._get(key, True) + if not isinstance(value, list): + raise CatalogError(f"{self.where}: '{key}' must be an array of tables") + return [ + _Table(item, f"{self.where}.{key}[{index}]") + for index, item in enumerate(value) + ] + + def finish(self) -> None: + unknown = sorted(set(self.data) - self._seen) + if unknown: + raise CatalogError(f"{self.where}: unknown key(s) {', '.join(unknown)}") + + +def _value_list(value: Any, where: str) -> tuple[str, ...]: + """A ``when`` / ``require`` / ``add`` value: a string or a list of strings.""" + if isinstance(value, str) and value: + return (value,) + if ( + isinstance(value, list) + and value + and all(isinstance(item, str) and item for item in value) + ): + return tuple(value) + raise CatalogError(f"{where}: must be a string or a non-empty list of strings") + + +def _value_map(table: "_Table | None") -> Mapping[str, tuple[str, ...]]: + if table is None: + return MappingProxyType({}) + result = { + key: _value_list(value, f"{table.where}.{key}") + for key, value in table.data.items() + } + return MappingProxyType(result) + + +def _unique(ids: list[str], where: str) -> None: + seen: set[str] = set() + for item_id in ids: + if item_id in seen: + raise CatalogError(f"{where}: duplicate id '{item_id}'") + seen.add(item_id) + + +def _with_id(table: _Table) -> str: + """Read ``id`` and name the entry after it in later messages.""" + item_id = table.string("id") + table.where = f"{table.where} ('{item_id}')" + return item_id + + +def _build_option(table: _Table) -> Option: + option_id = _with_id(table) + option = Option( + id=option_id, + label=table.optional_string("label") or option_id, + summary=table.optional_string("summary"), + runtime=table.strings("runtime"), + dev=table.strings("dev"), + tags=table.strings("tags"), + concepts=table.strings("concepts"), + none=table.boolean("none", False), + built_in=table.boolean("built_in", False), + ) + table.finish() + return option + + +def _build_axis(table: _Table) -> Axis: + axis_id = _with_id(table) + label = table.string("label") + description = table.string("description") + section = table.string("section") + if section not in _AXIS_SECTIONS: + raise CatalogError( + f"{table.where}: 'section' must be one of {', '.join(_AXIS_SECTIONS)}" + ) + multi = table.boolean("multi") + default = table.string("default") + options = tuple(_build_option(item) for item in table.tables("options")) + table.finish() + + _unique([option.id for option in options], f"{table.where}.options") + none_options = [option for option in options if option.none] + if len(none_options) != 1: + raise CatalogError(f"{table.where}: needs exactly one option with none = true") + if options[-1] is not none_options[0]: + raise CatalogError(f"{table.where}: the none = true option must be the last") + if default not in {option.id for option in options}: + raise CatalogError(f"{table.where}: default '{default}' is not an option") + for option in options: + if option.built_in and not multi: + raise CatalogError( + f"{table.where}: option '{option.id}' is built_in on a " + "single-select axis" + ) + if option.none and (option.runtime or option.dev): + raise CatalogError( + f"{table.where}: the none option '{option.id}' cannot add packages" + ) + return Axis( + id=axis_id, + label=label, + description=description, + section=section, # type: ignore[arg-type] + multi=multi, + default=default, + options=options, + ) + + +def _build_level(table: _Table) -> Level: + level_id = _with_id(table) + label = table.string("label") + description = table.string("description") + template = table.optional_string("template") + preset = table.optional_string("preset") + if (template is None) == (preset is None): + raise CatalogError( + f"{table.where}: needs exactly one of 'template' and 'preset'" + ) + asks_database = table.boolean("asks_database") + bundle_table = table.table("bundle") + bundle: dict[str, SelectionValue] = {} + if bundle_table is not None: + for key, value in bundle_table.data.items(): + if isinstance(value, str) and value: + bundle[key] = value + elif isinstance(value, list) and all( + isinstance(item, str) and item for item in value + ): + bundle[key] = tuple(value) + else: + raise CatalogError( + f"{bundle_table.where}.{key}: must be a string or a list of strings" + ) + concepts = table.strings("concepts") + table.finish() + return Level( + id=level_id, + label=label, + description=description, + template=template, + preset=preset, + asks_database=asks_database, + bundle=MappingProxyType(bundle), + concepts=concepts, + ) + + +def _build_rule(table: _Table) -> Rule: + rule_id = _with_id(table) + kind = table.string("kind") + if kind not in _RULE_KINDS: + raise CatalogError( + f"{table.where}: 'kind' must be one of {', '.join(_RULE_KINDS)}" + ) + when_table = table.table("when", required=True) + assert when_table is not None + when = _value_map(when_table) + if not when: + raise CatalogError(f"{table.where}: 'when' needs at least one condition") + require = _value_map(table.table("require")) + add = _value_map(table.table("add")) + runtime = table.strings("runtime") + dev = table.strings("dev") + message = table.optional_string("message") + table.finish() + + present = { + "require": bool(require), + "add": bool(add), + "runtime": bool(runtime), + "dev": bool(dev), + "message": message is not None, + } + allowed = { + "requires": {"require", "message"}, + "implies": {"add"}, + "adds": {"runtime", "dev"}, + "note": {"message"}, + }[kind] + extra = sorted( + field for field, given in present.items() if given and field not in allowed + ) + if extra: + raise CatalogError( + f"{table.where}: kind '{kind}' does not take {', '.join(extra)}" + ) + if kind == "requires" and not (require and message): + raise CatalogError( + f"{table.where}: kind 'requires' needs 'require' and 'message'" + ) + if kind == "implies" and not add: + raise CatalogError(f"{table.where}: kind 'implies' needs 'add'") + if kind == "adds" and not (runtime or dev): + raise CatalogError(f"{table.where}: kind 'adds' needs 'runtime' or 'dev'") + if kind == "note" and message is None: + raise CatalogError(f"{table.where}: kind 'note' needs 'message'") + return Rule( + id=rule_id, + kind=kind, # type: ignore[arg-type] + when=when, + require=require, + add=add, + runtime=runtime, + dev=dev, + message=message, + ) + + +def _build(data: dict[str, Any], lang: str) -> Catalog: + root = _Table(data, "catalog") + schema_version = root.integer("schema_version") + if schema_version != SCHEMA_VERSION: + raise CatalogError( + f"catalog: unsupported schema_version {schema_version} " + f"(expected {SCHEMA_VERSION})" + ) + + defaults_table = root.table("defaults", required=True) + assert defaults_table is not None + defaults = Defaults( + level=defaults_table.string("level"), + preset=defaults_table.string("preset"), + package_manager=defaults_table.string("package_manager"), + base_dependencies=defaults_table.strings("base_dependencies"), + ) + defaults_table.finish() + + concepts = [] + for table in root.tables("concepts"): + concept = Concept( + id=_with_id(table), title=table.string("title"), url=table.string("url") + ) + table.finish() + if not concept.url.startswith(CONCEPT_URL_PREFIX): + raise CatalogError( + f"{table.where}: url must start with {CONCEPT_URL_PREFIX}" + ) + concepts.append(concept) + + levels = [_build_level(table) for table in root.tables("levels")] + + presets = [] + for table in root.tables("presets"): + presets.append( + Preset( + id=_with_id(table), + template=table.string("template"), + summary=table.string("summary"), + ) + ) + table.finish() + + templates = [] + for table in root.tables("templates"): + template_id = _with_id(table) + kind = table.string("kind") + if kind not in _TEMPLATE_KINDS: + raise CatalogError( + f"{table.where}: 'kind' must be one of {', '.join(_TEMPLATE_KINDS)}" + ) + templates.append( + Template( + id=template_id, + kind=kind, # type: ignore[arg-type] + description=table.string("description"), + concepts=table.strings("concepts"), + ) + ) + table.finish() + + managers = [] + for table in root.tables("package_managers"): + managers.append( + PackageManager( + id=_with_id(table), + dependency_file=table.string("dependency_file"), + executable=table.string("executable"), + description=table.string("description"), + ) + ) + table.finish() + + axes = [_build_axis(table) for table in root.tables("axes")] + rules = [_build_rule(table) for table in root.tables("rules")] + root.finish() + + catalog = Catalog( + schema_version=schema_version, + lang=lang, + defaults=defaults, + concepts=tuple(concepts), + levels=tuple(levels), + presets=tuple(presets), + templates=tuple(templates), + package_managers=tuple(managers), + axes=tuple(axes), + rules=tuple(rules), + ) + _check_references(catalog) + return catalog + + +def _check_option_values( + catalog: Catalog, + values: Mapping[str, tuple[str, ...]], + where: str, + allow_wildcard: bool, +) -> None: + axis_ids = {axis.id for axis in catalog.axes} + for axis_id, choices in values.items(): + if axis_id not in axis_ids: + raise CatalogError(f"{where}: unknown axis '{axis_id}'") + known = set(catalog.axis(axis_id).choice_ids) + for choice in choices: + if allow_wildcard and choice == WILDCARD: + if len(choices) > 1: + raise CatalogError( + f"{where}.{axis_id}: '{WILDCARD}' cannot be combined " + "with other values" + ) + continue + if choice not in known: + raise CatalogError(f"{where}.{axis_id}: unknown option '{choice}'") + + +def _check_references(catalog: Catalog) -> None: + """Uniqueness, cross references, bundles and rules of a parsed catalog.""" + for kind, items in ( + ("concepts", catalog.concepts), + ("levels", catalog.levels), + ("presets", catalog.presets), + ("templates", catalog.templates), + ("package_managers", catalog.package_managers), + ("axes", catalog.axes), + ("rules", catalog.rules), + ): + _unique([item.id for item in items], f"catalog.{kind}") + + concept_ids = {concept.id for concept in catalog.concepts} + template_ids = {template.id for template in catalog.templates} + preset_ids = {preset.id for preset in catalog.presets} + level_ids = {level.id for level in catalog.levels} + manager_ids = {manager.id for manager in catalog.package_managers} + + def check_concepts(ids: tuple[str, ...], where: str) -> None: + for concept_id in ids: + if concept_id not in concept_ids: + raise CatalogError(f"{where}: unknown concept '{concept_id}'") + + if catalog.defaults.level not in level_ids: + raise CatalogError( + f"catalog.defaults: unknown level '{catalog.defaults.level}'" + ) + if catalog.defaults.preset not in preset_ids: + raise CatalogError( + f"catalog.defaults: unknown preset '{catalog.defaults.preset}'" + ) + if catalog.defaults.package_manager not in manager_ids: + raise CatalogError( + "catalog.defaults: unknown package manager " + f"'{catalog.defaults.package_manager}'" + ) + + for preset in catalog.presets: + if preset.template not in template_ids: + raise CatalogError( + f"preset '{preset.id}': unknown template '{preset.template}'" + ) + for template in catalog.templates: + check_concepts(template.concepts, f"template '{template.id}'") + for axis in catalog.axes: + for option in axis.options: + check_concepts(option.concepts, f"axis '{axis.id}' option '{option.id}'") + for rule in catalog.rules: + where = f"rule '{rule.id}'" + _check_option_values(catalog, rule.when, f"{where}.when", True) + _check_option_values(catalog, rule.require, f"{where}.require", False) + _check_option_values(catalog, rule.add, f"{where}.add", False) + check_message(rule.kind, rule.message, f"{where}.message") + for axis_id, values in rule.add.items(): + if not catalog.axis(axis_id).multi and len(values) != 1: + raise CatalogError( + f"{where}.add.{axis_id}: a single-select axis takes one value" + ) + check_implications(catalog) + + for level in catalog.levels: + where = f"level '{level.id}'" + if level.template is not None and level.template not in template_ids: + raise CatalogError(f"{where}: unknown template '{level.template}'") + if level.preset is not None and level.preset not in preset_ids: + raise CatalogError(f"{where}: unknown preset '{level.preset}'") + check_concepts(level.concepts, where) + if level.bundle and level.template is not None: + raise CatalogError( + f"{where}: a bundle needs a preset (template levels have no features)" + ) + for axis_id, value in level.bundle.items(): + try: + axis = catalog.axis(axis_id) + except KeyError: + raise CatalogError(f"{where}.bundle: unknown axis '{axis_id}'") + if axis.multi != isinstance(value, tuple): + shape = "a list" if axis.multi else "a single value" + raise CatalogError(f"{where}.bundle.{axis_id}: must be {shape}") + values = value if isinstance(value, tuple) else (value,) + for choice in values: + if choice not in axis.choice_ids: + raise CatalogError( + f"{where}.bundle.{axis_id}: unknown option '{choice}'" + ) + outcome = evaluate(level.bundle, catalog) + if outcome.errors: + raise CatalogError( + f"{where}.bundle violates a rule: {' | '.join(outcome.errors)}" + ) + + +def parse_catalog(text: str, *, lang: str = "en") -> Catalog: + """ + Parse and validate catalog TOML text. + + :param text: TOML document in the ``catalog.toml`` schema + :param lang: Language recorded on the result + :return: The validated catalog + :raises CatalogError: If the text is not valid TOML or breaks the schema + """ + try: + data = tomllib.loads(text) + except tomllib.TOMLDecodeError as error: + raise CatalogError(f"catalog: invalid TOML ({error})") from error + return _build(data, lang) + + +def _overlay_file(lang: str) -> Traversable: + return resource_root().joinpath(_I18N_DIR, f"{lang}.toml") + + +def available_languages() -> tuple[str, ...]: + """``"en"`` plus every language that ships an overlay file, in docs order.""" + return ("en",) + tuple( + lang for lang in LANGUAGES[1:] if _overlay_file(lang).is_file() + ) + + +def load_catalog(lang: str = "en") -> Catalog: + """ + Load the bundled catalog in ``lang`` (cached; the result is immutable). + + English text is the base. Another docs language overlays + ``i18n/.toml`` when it exists; keys it does not translate keep + their English text. + + :param lang: One of :data:`LANGUAGES` + :return: The catalog + :raises CatalogError: For an unknown language or an invalid file + """ + return _load(lang) + + +@lru_cache(maxsize=None) +def _load(lang: str) -> Catalog: + if lang not in LANGUAGES: + raise CatalogError( + f"Unknown catalog language '{lang}'. Allowed values: {', '.join(LANGUAGES)}" + ) + if lang != "en": + base = _load("en") + overlay = _overlay_file(lang) + if not overlay.is_file(): + return replace(base, lang=lang) + try: + data = tomllib.loads(overlay.read_bytes().decode("utf-8")) + except tomllib.TOMLDecodeError as error: + raise CatalogError(f"i18n/{lang}.toml: invalid TOML ({error})") from error + + from .i18n import apply_overlay + + return apply_overlay(base, data, lang) + + text = resource_root().joinpath(_CATALOG_FILE).read_bytes().decode("utf-8") + return parse_catalog(text, lang="en") diff --git a/src/fastapi_fastkit/catalog/model.py b/src/fastapi_fastkit/catalog/model.py new file mode 100644 index 00000000..d408117c --- /dev/null +++ b/src/fastapi_fastkit/catalog/model.py @@ -0,0 +1,256 @@ +# -------------------------------------------------------------------------- +# Typed, immutable view of ``catalog.toml``. +# +# Every class is a frozen dataclass whose sequences are tuples and whose +# mappings are read-only, so a loaded catalog can be cached and shared. +# This module is pure stdlib and imports nothing else from fastkit. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import re +from dataclasses import dataclass +from typing import Literal, Mapping, Protocol + +#: A selection on one axis: a choice id, or a tuple of ids on multi axes. +SelectionValue = str | tuple[str, ...] + +#: Leading distribution name of a PEP 508 requirement string. +_REQUIREMENT_NAME = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)") + + +class CatalogError(Exception): + """Raised when the catalog or one of its overlays is invalid.""" + + +def canonical_name(name: str) -> str: + """Normalise a distribution name the way PEP 503 does (``Foo_Bar`` -> ``foo-bar``).""" + return re.sub(r"[-_.]+", "-", name).lower() + + +def requirement_name(requirement: str) -> str: + """ + Canonical distribution name of a requirement string. + + ``"sqlalchemy[asyncio]>=2"`` -> ``"sqlalchemy"``. A string that does not + start with a distribution name (a URL, an option line) is returned + canonicalised as a whole so it never collides with a real name. + + :param requirement: PEP 508 requirement string + :return: Canonical name + """ + match = _REQUIREMENT_NAME.match(requirement) + return canonical_name(match.group(1) if match else requirement.strip()) + + +@dataclass(frozen=True, slots=True) +class Concept: + """A FastAPI concept and the official documentation page explaining it.""" + + id: str + title: str + url: str + + +@dataclass(frozen=True, slots=True) +class Option: + """One choice of an axis.""" + + id: str + label: str + summary: str | None + runtime: tuple[str, ...] + dev: tuple[str, ...] + tags: tuple[str, ...] + concepts: tuple[str, ...] + none: bool + built_in: bool + + @property + def packages(self) -> tuple[str, ...]: + """Every package of the option, runtime first.""" + return self.runtime + self.dev + + +@dataclass(frozen=True, slots=True) +class Axis: + """A feature axis (or the deployment axis) and its options.""" + + id: str + label: str + description: str + section: Literal["features", "deployment"] + multi: bool + default: str + options: tuple[Option, ...] + + def option(self, option_id: str) -> Option: + """ + Return the option with ``option_id``. + + :raises KeyError: If the axis has no such option + """ + for option in self.options: + if option.id == option_id: + return option + raise KeyError(f"Axis '{self.id}' has no option '{option_id}'") + + @property + def choice_ids(self) -> tuple[str, ...]: + """Ids of every option in display order, ``None`` included.""" + return tuple(option.id for option in self.options) + + @property + def offered(self) -> tuple[Option, ...]: + """Options a prompt offers: neither the ``None`` option nor built-in ones.""" + return tuple( + option for option in self.options if not option.none and not option.built_in + ) + + +@dataclass(frozen=True, slots=True) +class Level: + """A step of the learning ladder (``hello`` ... ``production``).""" + + id: str + label: str + description: str + template: str | None + preset: str | None + asks_database: bool + bundle: Mapping[str, SelectionValue] + concepts: tuple[str, ...] + + +@dataclass(frozen=True, slots=True) +class Preset: + """An architecture preset and the template it builds on.""" + + id: str + template: str + summary: str + + +@dataclass(frozen=True, slots=True) +class Template: + """A bundled template directory.""" + + id: str + kind: Literal["level", "example", "internal"] + description: str + concepts: tuple[str, ...] + + +@dataclass(frozen=True, slots=True) +class PackageManager: + """A supported package manager.""" + + id: str + dependency_file: str + executable: str + description: str + + +@dataclass(frozen=True, slots=True) +class Rule: + """A compatibility, implication, package or note rule between selections.""" + + id: str + kind: Literal["requires", "implies", "adds", "note"] + when: Mapping[str, tuple[str, ...]] + require: Mapping[str, tuple[str, ...]] + add: Mapping[str, tuple[str, ...]] + runtime: tuple[str, ...] + dev: tuple[str, ...] + message: str | None + + +@dataclass(frozen=True, slots=True) +class Defaults: + """Catalog-wide defaults.""" + + level: str + preset: str + package_manager: str + base_dependencies: tuple[str, ...] + + +class _HasId(Protocol): + @property + def id(self) -> str: ... + + +def _find[T: _HasId](items: tuple[T, ...], item_id: str, kind: str) -> T: + for item in items: + if item.id == item_id: + return item + raise KeyError(f"Unknown {kind} '{item_id}'") + + +@dataclass(frozen=True, slots=True) +class Catalog: + """The whole catalog in one language.""" + + schema_version: int + lang: str + defaults: Defaults + concepts: tuple[Concept, ...] + levels: tuple[Level, ...] + presets: tuple[Preset, ...] + templates: tuple[Template, ...] + package_managers: tuple[PackageManager, ...] + axes: tuple[Axis, ...] + rules: tuple[Rule, ...] + + def axis(self, axis_id: str) -> Axis: + """Return the axis with ``axis_id`` (``KeyError`` when unknown).""" + return _find(self.axes, axis_id, "axis") + + def feature_axes(self) -> tuple[Axis, ...]: + """Axes of the ``features`` section, in display order.""" + return tuple(axis for axis in self.axes if axis.section == "features") + + def level(self, level_id: str) -> Level: + """Return the level with ``level_id`` (``KeyError`` when unknown).""" + return _find(self.levels, level_id, "level") + + def preset(self, preset_id: str) -> Preset: + """Return the preset with ``preset_id`` (``KeyError`` when unknown).""" + return _find(self.presets, preset_id, "preset") + + def template(self, template_id: str) -> Template: + """Return the template with ``template_id`` (``KeyError`` when unknown).""" + return _find(self.templates, template_id, "template") + + def concept(self, concept_id: str) -> Concept: + """Return the concept with ``concept_id`` (``KeyError`` when unknown).""" + return _find(self.concepts, concept_id, "concept") + + def package_manager(self, manager_id: str) -> PackageManager: + """Return the package manager with ``manager_id`` (``KeyError`` when unknown).""" + return _find(self.package_managers, manager_id, "package manager") + + def rule(self, rule_id: str) -> Rule: + """Return the rule with ``rule_id`` (``KeyError`` when unknown).""" + return _find(self.rules, rule_id, "rule") + + def _runtime_and_dev_names(self) -> tuple[frozenset[str], frozenset[str]]: + runtime = {requirement_name(r) for r in self.defaults.base_dependencies} + dev: set[str] = set() + for axis in self.axes: + for option in axis.options: + runtime.update(requirement_name(r) for r in option.runtime) + dev.update(requirement_name(r) for r in option.dev) + for rule in self.rules: + runtime.update(requirement_name(r) for r in rule.runtime) + dev.update(requirement_name(r) for r in rule.dev) + return frozenset(runtime), frozenset(dev) + + def dev_only_names(self) -> frozenset[str]: + """Canonical names listed only as ``dev`` packages, never as runtime ones.""" + runtime, dev = self._runtime_and_dev_names() + return dev - runtime + + def known_names(self) -> frozenset[str]: + """Every canonical package name in the catalog, base dependencies included.""" + runtime, dev = self._runtime_and_dev_names() + return runtime | dev diff --git a/src/fastapi_fastkit/catalog/rules.py b/src/fastapi_fastkit/catalog/rules.py new file mode 100644 index 00000000..8df9fc58 --- /dev/null +++ b/src/fastapi_fastkit/catalog/rules.py @@ -0,0 +1,298 @@ +# -------------------------------------------------------------------------- +# Selections and rule evaluation. +# +# A selection maps axis ids to a choice id (single-select axes) or a tuple of +# choice ids (multi-select axes). ``evaluate`` applies the catalog's rules to +# it: ``implies`` rules first (to a fixed point), then ``requires``, ``adds`` +# and ``note`` rules in catalog order. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from dataclasses import dataclass +from types import MappingProxyType +from typing import Any, Mapping + +from .model import Axis, Catalog, CatalogError, Rule, SelectionValue + +#: A (possibly partial) selection: ``{axis_id: choice or (choices...)}``. +Selection = Mapping[str, SelectionValue] + +#: ``when`` value matching any selection except ``None`` / an empty list. +WILDCARD = "*" + + +def _active(catalog: Catalog | None) -> Catalog: + if catalog is not None: + return catalog + from .loader import load_catalog + + return load_catalog() + + +def _none_id(axis: Axis) -> str: + return axis.options[-1].id + + +def _axis_value(axis: Axis, raw: Any) -> SelectionValue: + """One axis' value from a config, in selection form.""" + if isinstance(raw, Mapping): + raw = raw.get("type") + none_id = _none_id(axis) + if axis.multi: + if raw is None: + return () + items = [raw] if isinstance(raw, str) else raw + if not isinstance(items, (list, tuple)): + return () + selected: list[str] = [] + for item in items: + if isinstance(item, str) and item != none_id and item not in selected: + selected.append(item) + return tuple(selected) + return raw if isinstance(raw, str) and raw else none_id + + +def selection_from_config( + config: Mapping[str, Any], catalog: Catalog | None = None +) -> dict[str, SelectionValue]: + """ + Read every axis of a project configuration into a selection. + + Accepts the canonical shape and the interactive builder's: ``database`` + as ``{"type": ...}`` (any axis may use that spelling), multi axes as a + list or a single string. Missing single axes read as ``"None"``, missing + multi axes as ``()``; the ``deployment`` axis is included. + + :param config: Project configuration mapping + :param catalog: Catalog to read the axes from (default: English catalog) + :return: ``{axis_id: value}`` for every axis of the catalog + """ + active = _active(catalog) + return {axis.id: _axis_value(axis, config.get(axis.id)) for axis in active.axes} + + +@dataclass(frozen=True, slots=True) +class RuleOutcome: + """What the rules make of a selection.""" + + errors: tuple[str, ...] + notes: tuple[str, ...] + implied: Mapping[str, tuple[str, ...]] + runtime: tuple[str, ...] + dev: tuple[str, ...] + + +def _complete(selection: Selection, catalog: Catalog) -> dict[str, SelectionValue]: + completed: dict[str, SelectionValue] = {} + for axis in catalog.axes: + value = selection.get(axis.id) + if axis.multi: + if value is None: + completed[axis.id] = () + elif isinstance(value, str): + completed[axis.id] = () if value == _none_id(axis) else (value,) + else: + completed[axis.id] = tuple(v for v in value if v != _none_id(axis)) + else: + completed[axis.id] = value if isinstance(value, str) else _none_id(axis) + return completed + + +def _values(value: SelectionValue) -> tuple[str, ...]: + return value if isinstance(value, tuple) else (value,) + + +def _condition_holds( + axis: Axis, value: SelectionValue, accepted: tuple[str, ...] +) -> bool: + if accepted == (WILDCARD,): + return bool(value) if axis.multi else value != _none_id(axis) + return any(item in accepted for item in _values(value)) + + +def _matches( + rule: Rule, selection: Mapping[str, SelectionValue], catalog: Catalog +) -> bool: + return all( + _condition_holds(catalog.axis(axis_id), selection[axis_id], accepted) + for axis_id, accepted in rule.when.items() + ) + + +def _described(axis: Axis, value: SelectionValue) -> str: + name = axis.id.replace("_", " ") + values = _values(value) + if not values or values == (_none_id(axis),): + return f"no {name}" + return f"{name} '{', '.join(values)}'" + + +#: Placeholders a ``requires`` message is formatted with. +_REQUIRES_PLACEHOLDERS = ("allowed", "selected") + + +def _requires_message(message: str, allowed: str, selected: str) -> str: + return message.format(allowed=allowed, selected=selected) + + +def check_message(kind: str, message: str | None, where: str) -> None: + """ + Check that a rule message can be shown when its rule fires. + + ``requires`` messages are formatted with ``{allowed}`` and ``{selected}`` + (both strings); ``note`` messages are shown as written. + + :param kind: Rule kind + :param message: The message (``None`` for kinds without one) + :param where: Location for the error message + :raises CatalogError: If formatting the message would fail + """ + if kind != "requires" or message is None: + return + try: + _requires_message(message, *_REQUIRES_PLACEHOLDERS) + except (KeyError, IndexError, ValueError, AttributeError, TypeError) as error: + raise CatalogError( + f"{where}: cannot be formatted with " + f"{', '.join('{' + name + '}' for name in _REQUIRES_PLACEHOLDERS)} " + f"({type(error).__name__}: {error})" + ) from error + + +def _apply_implications( + selection: dict[str, SelectionValue], catalog: Catalog +) -> dict[str, list[str]]: + implied: dict[str, list[str]] = {} + implies = [rule for rule in catalog.rules if rule.kind == "implies"] + # A pass is a pure function of the selection, so a selection seen before + # means the passes run in a circle and never reach a fixed point. + seen = {tuple(selection.items())} + while True: + changed = False + for rule in implies: + if not _matches(rule, selection, catalog): + continue + for axis_id, values in rule.add.items(): + axis = catalog.axis(axis_id) + current = selection[axis_id] + if axis.multi: + assert isinstance(current, tuple) + missing = [v for v in values if v not in current] + if missing: + selection[axis_id] = current + tuple(missing) + implied.setdefault(axis_id, []).extend(missing) + changed = True + elif current != values[0]: + selection[axis_id] = values[0] + implied.setdefault(axis_id, []).append(values[0]) + changed = True + if not changed: + return implied + state = tuple(selection.items()) + if state in seen: + raise CatalogError( + "catalog: the 'implies' rules do not settle for this selection " + f"(rules: {', '.join(rule.id for rule in implies)})" + ) + seen.add(state) + + +def _accepted_choices(axis: Axis, accepted: tuple[str, ...]) -> set[str]: + if accepted == (WILDCARD,): + return {option.id for option in axis.options if not option.none} + return set(accepted) + + +def _can_hold_together(first: Rule, second: Rule, catalog: Catalog) -> bool: + """Whether some selection satisfies the conditions of both rules.""" + for axis_id in first.when.keys() & second.when.keys(): + axis = catalog.axis(axis_id) + if axis.multi: + continue + both = _accepted_choices(axis, first.when[axis_id]) & _accepted_choices( + axis, second.when[axis_id] + ) + if not both: + return False + return True + + +def check_implications(catalog: Catalog) -> None: + """ + Reject ``implies`` rules that would set one single-select axis to two + values for the same selection (evaluation would flip between them). + + :param catalog: Catalog whose rules are checked + :raises CatalogError: For the first conflicting pair + """ + implies = [rule for rule in catalog.rules if rule.kind == "implies"] + for position, first in enumerate(implies): + for second in implies[position + 1 :]: + for axis_id in first.add.keys() & second.add.keys(): + if catalog.axis(axis_id).multi: + continue + if first.add[axis_id] == second.add[axis_id]: + continue + if _can_hold_together(first, second, catalog): + raise CatalogError( + f"rules '{first.id}' and '{second.id}' can apply to the " + f"same selection and set '{axis_id}' to different values" + ) + + +def _extend_unique(target: list[str], items: tuple[str, ...]) -> None: + for item in items: + if item not in target: + target.append(item) + + +def evaluate(selection: Selection, catalog: Catalog | None = None) -> RuleOutcome: + """ + Apply the catalog's rules to a selection. + + :param selection: ``{axis_id: value}``; missing axes read as ``None`` + :param catalog: Catalog whose rules (and message language) apply + (default: English catalog) + :return: Errors and notes in rule order, values ``implies`` rules added, + and the packages ``adds`` rules contribute + """ + active = _active(catalog) + current = _complete(selection, active) + implied = _apply_implications(current, active) + + errors: list[str] = [] + notes: list[str] = [] + runtime: list[str] = [] + dev: list[str] = [] + for rule in active.rules: + if rule.kind == "implies" or not _matches(rule, current, active): + continue + if rule.kind == "requires": + for axis_id, allowed in rule.require.items(): + axis = active.axis(axis_id) + if _condition_holds(axis, current[axis_id], allowed): + continue + assert rule.message is not None + errors.append( + _requires_message( + rule.message, + allowed=", ".join(allowed), + selected=_described(axis, current[axis_id]), + ) + ) + elif rule.kind == "adds": + _extend_unique(runtime, rule.runtime) + _extend_unique(dev, rule.dev) + else: + assert rule.message is not None + notes.append(rule.message) + + return RuleOutcome( + errors=tuple(errors), + notes=tuple(notes), + implied=MappingProxyType( + {axis_id: tuple(values) for axis_id, values in implied.items()} + ), + runtime=tuple(runtime), + dev=tuple(dev), + ) diff --git a/src/fastapi_fastkit/cli.py b/src/fastapi_fastkit/cli.py index f6bee5c9..09c80d3d 100644 --- a/src/fastapi_fastkit/cli.py +++ b/src/fastapi_fastkit/cli.py @@ -53,8 +53,10 @@ ScaffoldOptions, cleanup_failed_project, ) +from fastapi_fastkit.catalog import load_catalog from fastapi_fastkit.core.exceptions import BackendExceptions, CLIExceptions from fastapi_fastkit.core.settings import FastkitConfig +from fastapi_fastkit.generation.spec import is_template_name from fastapi_fastkit.utils.config_file import ( ConfigFileError, load_project_config, @@ -205,24 +207,13 @@ def echo(ctx: Context) -> None: #: ``list-templates`` order: from the simplest project to the most involved, -#: then the example projects. Templates missing from this list follow it, -#: sorted by name, so the order never depends on the filesystem. -TEMPLATE_DISPLAY_ORDER: Tuple[str, ...] = ( - "fastapi-hello", - "fastapi-empty", - "fastapi-single-module", - "fastapi-default", - "fastapi-domain-starter", - "fastapi-custom-response", - "fastapi-auth-jwt", - "fastapi-sqlmodel", - "fastapi-mcp", - "fastapi-llm-agent", +#: then the example projects (the catalog's template order). Templates +#: missing from this list follow it, sorted by name, so the order never +#: depends on the filesystem. +TEMPLATE_DISPLAY_ORDER: Tuple[str, ...] = tuple( + template.id for template in load_catalog().templates ) -#: Directories of the template root that are not templates. -_NON_TEMPLATE_DIRS = frozenset({"__pycache__", "modules"}) - def available_templates(template_root: str) -> List[str]: """ @@ -238,9 +229,7 @@ def available_templates(template_root: str) -> List[str]: names = [ name for name in os.listdir(template_root) - if os.path.isdir(os.path.join(template_root, name)) - and name not in _NON_TEMPLATE_DIRS - and not name.startswith(".") + if is_template_name(template_root, name) ] rank = {name: index for index, name in enumerate(TEMPLATE_DISPLAY_ORDER)} return sorted(names, key=lambda name: (rank.get(name, len(rank)), name)) @@ -296,8 +285,16 @@ def list_templates(ctx: Context) -> None: print_warning("No available templates.") return + catalog_descriptions = { + template.id: template.description for template in load_catalog().templates + } template_data = {} for template in templates: + if template in catalog_descriptions: + template_data[template] = catalog_descriptions[template] + continue + + # A directory the catalog does not know: its README heading. template_path = os.path.join(template_dir, template) readme_path = os.path.join(template_path, "README.md-tpl") @@ -433,7 +430,7 @@ def _scaffold( @click.option( "--package-manager", help="Package manager to use for the project.", - type=click.Choice(["pip", "uv", "pdm", "poetry"]), + type=click.Choice(FastkitConfig.SUPPORTED_PACKAGE_MANAGERS), default=None, ) @click.option( @@ -703,7 +700,7 @@ def _offer_config_save(config: Dict[str, Any], save_config: Optional[str]) -> No @click.option( "--package-manager", help="Package manager to use for the project.", - type=click.Choice(["pip", "uv", "pdm", "poetry"]), + type=click.Choice(FastkitConfig.SUPPORTED_PACKAGE_MANAGERS), default=None, ) @click.option( diff --git a/src/fastapi_fastkit/core/settings.py b/src/fastapi_fastkit/core/settings.py index 37e2d78c..740cddf9 100644 --- a/src/fastapi_fastkit/core/settings.py +++ b/src/fastapi_fastkit/core/settings.py @@ -8,12 +8,22 @@ from enum import StrEnum from pathlib import Path +from fastapi_fastkit.catalog import load_catalog + from .exceptions import BackendExceptions +#: The catalog (``catalog/catalog.toml``) every list, description, default +#: and package set below is derived from. The enums in this module stay +#: hand-written because code branches on their members; an agreement test +#: fails when they and the catalog drift apart. +_CATALOG = load_catalog() + class FeatureAxis(StrEnum): """Canonical keys of every axis in :attr:`FastkitConfig.PACKAGE_CATALOG`. + Mirrors the ``features`` axes of the catalog (checked by a test). + The interactive config dict is keyed by these strings, and both ``DynamicConfigGenerator`` and ``DependencyCollector`` look choices up through them. Keeping the literals in one place stops the three modules @@ -36,9 +46,8 @@ class FeatureAxis(StrEnum): NONE_CHOICE = "None" #: Axes whose selection is a list of choices rather than a single choice. -MULTI_SELECT_AXES: tuple[str, ...] = ( - FeatureAxis.UTILITIES, - FeatureAxis.TOOLING, +MULTI_SELECT_AXES: tuple[str, ...] = tuple( + FeatureAxis(axis.id) for axis in _CATALOG.feature_axes() if axis.multi ) #: Python version generated projects target. Matches fastkit's own @@ -182,18 +191,15 @@ class FastkitConfig: # Architecture Presets (interactive ``init`` wizard) # # The preset shapes how the generated project is laid out (single file vs. - # layered vs. domain-oriented). Preset-specific generation logic lives in - # later issues โ€” this catalog is the user-facing menu and the canonical - # set of preset ids persisted in the interactive config. + # layered vs. domain-oriented): preset id -> summary, from the catalog. ARCHITECTURE_PRESETS: dict[str, str] = { - "minimal": "Smallest viable FastAPI app โ€” a single app + a couple of files.", - "single-module": "Everything in one module; ideal for tiny scripts and prototypes.", - "classic-layered": "Layered split: api/routes, crud, schemas, core (a la fastapi-default).", - "domain-starter": "Domain-oriented: src/app/domains// with router/service/repository (recommended).", + preset.id: preset.summary for preset in _CATALOG.presets } - DEFAULT_ARCHITECTURE_PRESET: str = "domain-starter" + DEFAULT_ARCHITECTURE_PRESET: str = _CATALOG.defaults.preset # Startproject Options + # Removed in stage 3 together with the stack question. Test tools in + # these lists are routed to the dev group by the dependency collector. PROJECT_STACKS: dict[str, list[str]] = { "minimal": ["fastapi", "uvicorn", "pydantic", "pydantic-settings"], "standard": [ @@ -231,164 +237,29 @@ class FastkitConfig: "default": 300, } - DEFAULT_PACKAGE_MANAGER: str = "uv" - SUPPORTED_PACKAGE_MANAGERS: list[str] = ["pip", "uv", "pdm", "poetry"] + DEFAULT_PACKAGE_MANAGER: str = _CATALOG.defaults.package_manager + SUPPORTED_PACKAGE_MANAGERS: list[str] = [ + manager.id for manager in _CATALOG.package_managers + ] PACKAGE_MANAGER_CONFIG: dict[str, dict[str, str]] = { - "pip": { - "dependency_file": "requirements.txt", - "executable": "pip", - "description": "Standard Python package manager", - }, - "uv": { - "dependency_file": "pyproject.toml", - "executable": "uv", - "description": "Fast Python package manager", - }, - "pdm": { - "dependency_file": "pyproject.toml", - "executable": "pdm", - "description": "Modern Python dependency management", - }, - "poetry": { - "dependency_file": "pyproject.toml", - "executable": "poetry", - "description": "Python dependency management and packaging", - }, + manager.id: { + "dependency_file": manager.dependency_file, + "executable": manager.executable, + "description": manager.description, + } + for manager in _CATALOG.package_managers } - # Package Catalog for Interactive Mode (v1.2.0+) - # Based on recommendations from: https://github.com/mjhea0/awesome-fastapi + # Package Catalog for Interactive Mode: feature axis -> option -> packages + # (runtime and dev packages together; ``catalog.toml`` keeps them apart). PACKAGE_CATALOG: dict[str, dict[str, list[str]]] = { - FeatureAxis.DATABASE: { - # The generated database module is async (``sqlalchemy.ext.asyncio``), - # which needs greenlet. SQLAlchemy 2.1 only installs it through the - # ``asyncio`` extra, and 2.0 skipped it on some platforms (macOS arm64). - DatabaseChoice.POSTGRESQL: ["asyncpg", "sqlalchemy[asyncio]"], - DatabaseChoice.MYSQL: ["aiomysql", "sqlalchemy[asyncio]"], - # PyMongo's native asyncio client (AsyncMongoClient, PyMongo 4.13+) - # replaces Motor, which MongoDB deprecated on 2026-05-14. The - # floor keeps an older environment or constraint file from - # resolving to a release without it (or with the beta API). - DatabaseChoice.MONGODB: ["pymongo>=4.13"], - # ``aioredis`` is abandoned (merged into redis-py) and does not - # install on Python 3.12 โ€” redis[hiredis] ships the asyncio client. - DatabaseChoice.REDIS: ["redis[hiredis]"], - DatabaseChoice.SQLITE: ["sqlalchemy[asyncio]", "aiosqlite"], - DatabaseChoice.NONE: [], - }, - FeatureAxis.AUTHENTICATION: { - # OAuth2PasswordRequestForm needs python-multipart; EmailStr needs - # email-validator. PyJWT signs the tokens, pwdlib hashes (argon2). - AuthChoice.JWT: [ - "pyjwt[crypto]", - "pwdlib[argon2]", - "email-validator", - "python-multipart", - ], - # SessionMiddleware (used by the OAuth2 login flow) needs itsdangerous. - # Authlib talks to the providers through httpx2 (it falls back to - # httpx with an AuthlibDeprecationWarning), and the generated router - # catches httpx2's errors, so httpx2 is what gets installed. - AuthChoice.OAUTH2: ["authlib", "itsdangerous", "httpx2"], - # The generated module targets the FastAPI-Users 15 API (it pins - # pwdlib, PyJWT and python-multipart itself). SQL databases only. - AuthChoice.FASTAPI_USERS: ["fastapi-users[sqlalchemy]>=15.0.5,<16"], - AuthChoice.SESSION: ["itsdangerous", "pwdlib[argon2]", "email-validator"], - AuthChoice.NONE: [], - }, - FeatureAxis.ASYNC_TASKS: { - AsyncTaskChoice.CELERY: ["celery[redis]", "redis[hiredis]"], - AsyncTaskChoice.DRAMATIQ: ["dramatiq[redis]", "redis[hiredis]"], - AsyncTaskChoice.NONE: [], - }, - FeatureAxis.TESTING: { - # Starlette's TestClient is built on httpx2 and warns when it has to - # fall back to httpx; httpx stays for tests that use its - # AsyncClient / ASGITransport directly. - TestingChoice.BASIC: ["pytest", "pytest-asyncio", "httpx", "httpx2"], - TestingChoice.COVERAGE: [ - "pytest", - "pytest-asyncio", - "pytest-cov", - "httpx", - "httpx2", - ], - TestingChoice.ADVANCED: [ - "pytest", - "pytest-asyncio", - "pytest-cov", - "httpx", - "httpx2", - "faker", - "factory-boy", - ], - TestingChoice.NONE: [], - }, - FeatureAxis.CACHING: { - # fastapi-cache2 imports starlette.templating at module scope, - # which hard-requires jinja2 โ€” without it the app fails to import. - CachingChoice.REDIS: ["redis[hiredis]", "fastapi-cache2", "jinja2"], - CachingChoice.NONE: [], - }, - FeatureAxis.MONITORING: { - MonitoringChoice.LOGURU: ["loguru"], - MonitoringChoice.OPENTELEMETRY: [ - "opentelemetry-api", - "opentelemetry-sdk", - "opentelemetry-instrumentation-fastapi", - "opentelemetry-exporter-otlp-proto-http", - ], - MonitoringChoice.PROMETHEUS: [ - "prometheus-client", - "prometheus-fastapi-instrumentator", - ], - MonitoringChoice.NONE: [], - }, - FeatureAxis.UTILITIES: { - UtilityChoice.CORS: [], # Built-in to FastAPI - # The generated middleware uses ``limits`` directly: slowapi's - # SlowAPIMiddleware skips routes added with include_router. It - # needs ``limits.aio`` and ``WindowStats.reset_time``; 3.4 is the - # first release where that works on Python 3.12 (older ones - # import ``pkg_resources``). - UtilityChoice.RATE_LIMITING: ["limits>=3.4"], - # Pagination is built into the generated list endpoints - # (core/pagination.py); kept selectable for saved configs. - UtilityChoice.PAGINATION: [], - UtilityChoice.WEBSOCKET: ["websockets"], - UtilityChoice.NONE: [], - }, - FeatureAxis.MIGRATIONS: { - MigrationsChoice.ALEMBIC: ["alembic"], - MigrationsChoice.NONE: [], - }, - FeatureAxis.TOOLING: { - ToolingChoice.RUFF: ["ruff"], - ToolingChoice.PRE_COMMIT: ["pre-commit"], - ToolingChoice.GITHUB_ACTIONS: [], # workflow file only - ToolingChoice.DEVCONTAINER: [], # devcontainer.json only - ToolingChoice.MAKEFILE: [], # Makefile only - ToolingChoice.NONE: [], - }, - FeatureAxis.LOGGING: { - # Stdlib ``logging`` + ``json`` only โ€” no third-party dependency. - LoggingChoice.STRUCTURED: [], - LoggingChoice.NONE: [], - }, + axis.id: {option.id: list(option.packages) for option in axis.options} + for axis in _CATALOG.feature_axes() } # Feature descriptions for display in interactive mode FEATURE_DESCRIPTIONS: dict[str, str] = { - FeatureAxis.DATABASE: "Database and ORM selection", - FeatureAxis.AUTHENTICATION: "User authentication and authorization", - FeatureAxis.ASYNC_TASKS: "Background task processing", - FeatureAxis.TESTING: "Testing framework and tools", - FeatureAxis.CACHING: "Response and data caching", - FeatureAxis.MONITORING: "Application monitoring and logging", - FeatureAxis.UTILITIES: "Additional utilities and middleware", - FeatureAxis.MIGRATIONS: "Database schema migrations", - FeatureAxis.TOOLING: "Developer tooling and CI configuration", - FeatureAxis.LOGGING: "Application logging format", + axis.id: axis.description for axis in _CATALOG.feature_axes() } # Testing Options diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl index a9fa5121..2d68baae 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl @@ -38,6 +38,7 @@ database-backed CRUD without auth, use `fastapi-sqlmodel`. โ”œโ”€โ”€ README.md โ”œโ”€โ”€ pyproject.toml โ”œโ”€โ”€ requirements.txt +โ”œโ”€โ”€ requirements-dev.txt โ”œโ”€โ”€ alembic.ini โ”œโ”€โ”€ Dockerfile โ”œโ”€โ”€ .env # local settings, git-ignored (generated) @@ -98,8 +99,9 @@ its router in `src/app/api/router.py`, which is served under `/api/v1`. ## Running the app ```bash -# create a virtualenv and install dependencies -$ uv sync # or: pip install -r requirements.txt +# create a virtualenv and install dependencies (requirements-dev.txt adds +# the test and lint tools to requirements.txt, which the Dockerfile installs) +$ uv sync # or: pip install -r requirements-dev.txt # launch the dev server $ bash scripts/run-server.sh diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/requirements-dev.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/requirements-dev.txt-tpl new file mode 100644 index 00000000..97d34f1f --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/requirements-dev.txt-tpl @@ -0,0 +1,9 @@ +-r requirements.txt + +# Development / test tooling +pytest==9.1.1 +pytest-asyncio==1.4.0 +httpx==0.28.1 +black==26.10.1 +isort==9.0.1 +mypy==2.3.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/requirements.txt-tpl index f1d58125..00410d5a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/requirements.txt-tpl @@ -14,10 +14,3 @@ psycopg[binary]==3.3.5 # Authentication PyJWT==2.15.1 pwdlib[argon2]==0.3.1 -# Development & tests -pytest==9.1.1 -pytest-asyncio==1.4.0 -httpx==0.28.1 -black==26.10.1 -isort==9.0.1 -mypy==2.3.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/pagination.py-tpl index 26888221..92daef7b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/pagination.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/pagination.py-tpl @@ -6,13 +6,11 @@ # {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range # values are rejected with a 422 rather than clamped. # -------------------------------------------------------------------------- -from typing import Annotated, Generic, TypeVar +from typing import Annotated from fastapi import Query from pydantic import BaseModel -T = TypeVar("T") - #: Page size used when the client sends no ``limit``. DEFAULT_LIMIT = 20 #: Largest page a client may ask for. @@ -24,7 +22,7 @@ LimitParam = Annotated[ OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] -class Page(BaseModel, Generic[T]): +class Page[T](BaseModel): """One page of a collection, ordered by primary key. ``total`` counts the whole collection, so a client knows there is a next diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/pagination.py-tpl index 26888221..92daef7b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/pagination.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/pagination.py-tpl @@ -6,13 +6,11 @@ # {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range # values are rejected with a 422 rather than clamped. # -------------------------------------------------------------------------- -from typing import Annotated, Generic, TypeVar +from typing import Annotated from fastapi import Query from pydantic import BaseModel -T = TypeVar("T") - #: Page size used when the client sends no ``limit``. DEFAULT_LIMIT = 20 #: Largest page a client may ask for. @@ -24,7 +22,7 @@ LimitParam = Annotated[ OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] -class Page(BaseModel, Generic[T]): +class Page[T](BaseModel): """One page of a collection, ordered by primary key. ``total`` counts the whole collection, so a client knows there is a next diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/pagination.py-tpl index 26888221..92daef7b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/pagination.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/pagination.py-tpl @@ -6,13 +6,11 @@ # {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range # values are rejected with a 422 rather than clamped. # -------------------------------------------------------------------------- -from typing import Annotated, Generic, TypeVar +from typing import Annotated from fastapi import Query from pydantic import BaseModel -T = TypeVar("T") - #: Page size used when the client sends no ``limit``. DEFAULT_LIMIT = 20 #: Largest page a client may ask for. @@ -24,7 +22,7 @@ LimitParam = Annotated[ OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] -class Page(BaseModel, Generic[T]): +class Page[T](BaseModel): """One page of a collection, ordered by primary key. ``total`` counts the whole collection, so a client knows there is a next diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/pagination.py-tpl index 26888221..92daef7b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/pagination.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/pagination.py-tpl @@ -6,13 +6,11 @@ # {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range # values are rejected with a 422 rather than clamped. # -------------------------------------------------------------------------- -from typing import Annotated, Generic, TypeVar +from typing import Annotated from fastapi import Query from pydantic import BaseModel -T = TypeVar("T") - #: Page size used when the client sends no ``limit``. DEFAULT_LIMIT = 20 #: Largest page a client may ask for. @@ -24,7 +22,7 @@ LimitParam = Annotated[ OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] -class Page(BaseModel, Generic[T]): +class Page[T](BaseModel): """One page of a collection, ordered by primary key. ``total`` counts the whole collection, so a client knows there is a next diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/db/memory.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/db/memory.py-tpl index 57277eb5..84c50547 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/db/memory.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/db/memory.py-tpl @@ -7,12 +7,9 @@ # -------------------------------------------------------------------------- from collections.abc import Callable from threading import Lock -from typing import Generic, TypeVar -T = TypeVar("T") - -class InMemoryStore(Generic[T]): +class InMemoryStore[T]: """Tiny ID-keyed collection backed by a dict. Sync route handlers run in a thread pool, so every read-modify-write is diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/pagination.py-tpl index 26888221..92daef7b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/pagination.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/pagination.py-tpl @@ -6,13 +6,11 @@ # {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range # values are rejected with a 422 rather than clamped. # -------------------------------------------------------------------------- -from typing import Annotated, Generic, TypeVar +from typing import Annotated from fastapi import Query from pydantic import BaseModel -T = TypeVar("T") - #: Page size used when the client sends no ``limit``. DEFAULT_LIMIT = 20 #: Largest page a client may ask for. @@ -24,7 +22,7 @@ LimitParam = Annotated[ OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] -class Page(BaseModel, Generic[T]): +class Page[T](BaseModel): """One page of a collection, ordered by primary key. ``total`` counts the whole collection, so a client knows there is a next diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl index 3ca4ecc7..16e25ebe 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl @@ -39,6 +39,7 @@ you need a database-backed API, use `fastapi-sqlmodel`. โ”œโ”€โ”€ README.md โ”œโ”€โ”€ pyproject.toml โ”œโ”€โ”€ requirements.txt +โ”œโ”€โ”€ requirements-dev.txt โ”œโ”€โ”€ Dockerfile โ”œโ”€โ”€ .env # local settings, git-ignored (generated) โ”œโ”€โ”€ .env.example # shareable example, committed @@ -109,8 +110,9 @@ Anthropic Messages API; a gateway is what translates for other providers. ## Running the app ```bash -# create a virtualenv and install dependencies -$ uv venv && uv pip install -r requirements.txt +# create a virtualenv and install dependencies (requirements-dev.txt adds +# the test and lint tools to requirements.txt, which the Dockerfile installs) +$ uv venv && uv pip install -r requirements-dev.txt # launch the dev server $ bash scripts/run-server.sh diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/requirements-dev.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/requirements-dev.txt-tpl new file mode 100644 index 00000000..97d34f1f --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/requirements-dev.txt-tpl @@ -0,0 +1,9 @@ +-r requirements.txt + +# Development / test tooling +pytest==9.1.1 +pytest-asyncio==1.4.0 +httpx==0.28.1 +black==26.10.1 +isort==9.0.1 +mypy==2.3.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/requirements.txt-tpl index e4f7026f..5bced7e4 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/requirements.txt-tpl @@ -5,11 +5,3 @@ pydantic-settings==2.15.0 python-dotenv==1.2.3 anthropic==1.3.0 sse-starlette==3.4.10 - -# Development / test tooling -pytest==9.1.1 -pytest-asyncio==1.4.0 -httpx==0.28.1 -black==26.10.1 -isort==9.0.1 -mypy==2.3.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/pagination.py-tpl index 26888221..92daef7b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/pagination.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/pagination.py-tpl @@ -6,13 +6,11 @@ # {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range # values are rejected with a 422 rather than clamped. # -------------------------------------------------------------------------- -from typing import Annotated, Generic, TypeVar +from typing import Annotated from fastapi import Query from pydantic import BaseModel -T = TypeVar("T") - #: Page size used when the client sends no ``limit``. DEFAULT_LIMIT = 20 #: Largest page a client may ask for. @@ -24,7 +22,7 @@ LimitParam = Annotated[ OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] -class Page(BaseModel, Generic[T]): +class Page[T](BaseModel): """One page of a collection, ordered by primary key. ``total`` counts the whole collection, so a client knows there is a next diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl index 23947d6f..5e4f1d1f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl @@ -40,6 +40,7 @@ If you don't need a database, start with `fastapi-domain-starter`. โ”œโ”€โ”€ README.md โ”œโ”€โ”€ pyproject.toml โ”œโ”€โ”€ requirements.txt +โ”œโ”€โ”€ requirements-dev.txt โ”œโ”€โ”€ alembic.ini โ”œโ”€โ”€ Dockerfile โ”œโ”€โ”€ docker-compose.yml # local PostgreSQL / MySQL for trying them (profiles) @@ -91,8 +92,9 @@ If you don't need a database, start with `fastapi-domain-starter`. ## Running the app ```bash -# create a virtualenv and install dependencies -$ uv venv && uv pip install -r requirements.txt +# create a virtualenv and install dependencies (requirements-dev.txt adds +# the test and lint tools to requirements.txt, which the Dockerfile installs) +$ uv venv && uv pip install -r requirements-dev.txt # or: uv sync # apply migrations diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/requirements-dev.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/requirements-dev.txt-tpl new file mode 100644 index 00000000..97d34f1f --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/requirements-dev.txt-tpl @@ -0,0 +1,9 @@ +-r requirements.txt + +# Development / test tooling +pytest==9.1.1 +pytest-asyncio==1.4.0 +httpx==0.28.1 +black==26.10.1 +isort==9.0.1 +mypy==2.3.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/requirements.txt-tpl index 97a59be2..e196f449 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/requirements.txt-tpl @@ -17,11 +17,3 @@ greenlet==3.5.5 # MySQL (mysql+asyncmy://...); cryptography for MySQL 8's default login # asyncmy==0.2.18 # cryptography==50.0.2 - -# Development / test tooling -pytest==9.1.1 -pytest-asyncio==1.4.0 -httpx==0.28.1 -black==26.10.1 -isort==9.0.1 -mypy==2.3.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/scripts/lint.sh-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/scripts/lint.sh-tpl index 2b894583..ea2ac462 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/scripts/lint.sh-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/scripts/lint.sh-tpl @@ -3,4 +3,4 @@ set -x black . --check isort . --check-only -mypy src +mypy src tests diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/pagination.py-tpl index 26888221..92daef7b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/pagination.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/pagination.py-tpl @@ -6,13 +6,11 @@ # {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range # values are rejected with a 422 rather than clamped. # -------------------------------------------------------------------------- -from typing import Annotated, Generic, TypeVar +from typing import Annotated from fastapi import Query from pydantic import BaseModel -T = TypeVar("T") - #: Page size used when the client sends no ``limit``. DEFAULT_LIMIT = 20 #: Largest page a client may ask for. @@ -24,7 +22,7 @@ LimitParam = Annotated[ OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] -class Page(BaseModel, Generic[T]): +class Page[T](BaseModel): """One page of a collection, ordered by primary key. ``total`` counts the whole collection, so a client knows there is a next diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/base.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/base.py-tpl index 778a7175..6e82aeed 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/base.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/base.py-tpl @@ -8,17 +8,15 @@ # Write methods commit their own transaction: the request-scoped session # dependency only rolls back when a request fails. # -------------------------------------------------------------------------- -from typing import Any, Generic, Sequence, TypeVar +from typing import Any, Sequence from sqlmodel import SQLModel, func, select from sqlmodel.ext.asyncio.session import AsyncSession -ModelType = TypeVar("ModelType", bound=SQLModel) -CreateSchemaType = TypeVar("CreateSchemaType", bound=SQLModel) -UpdateSchemaType = TypeVar("UpdateSchemaType", bound=SQLModel) - -class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): +class CRUDBase[ + ModelType: SQLModel, CreateSchemaType: SQLModel, UpdateSchemaType: SQLModel +]: """Reusable data-access layer for a single SQLModel table.""" def __init__(self, model: type[ModelType]) -> None: diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_database.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_database.py-tpl index 7b1aaecf..99513160 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_database.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_database.py-tpl @@ -11,8 +11,7 @@ from pathlib import Path import pytest from sqlalchemy import text -from sqlalchemy.dialects import mysql, postgresql -from sqlalchemy.engine import Dialect +from sqlalchemy.engine import Dialect, make_url from sqlalchemy.schema import CreateTable from src.app.core.config import settings @@ -285,12 +284,20 @@ def test_other_import_errors_are_not_disguised( create_engine(POSTGRES) +def server_dialect(url: str) -> Dialect: + """The SQLAlchemy dialect of ``url``; its driver need not be installed.""" + return make_url(url).get_dialect()() + + @pytest.mark.parametrize( ("dialect", "expected"), [ - (mysql.dialect(), ["VARCHAR(128)", "VARCHAR(512)", "DOUBLE", "DATETIME(6)"]), ( - postgresql.dialect(), + server_dialect(MYSQL), + ["VARCHAR(128)", "VARCHAR(512)", "DOUBLE", "DATETIME(6)"], + ), + ( + server_dialect(POSTGRES), [ "VARCHAR(128)", "VARCHAR(512)", diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/core/pagination.py-tpl index 26888221..92daef7b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/modules/core/pagination.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/modules/core/pagination.py-tpl @@ -6,13 +6,11 @@ # {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range # values are rejected with a 422 rather than clamped. # -------------------------------------------------------------------------- -from typing import Annotated, Generic, TypeVar +from typing import Annotated from fastapi import Query from pydantic import BaseModel -T = TypeVar("T") - #: Page size used when the client sends no ``limit``. DEFAULT_LIMIT = 20 #: Largest page a client may ask for. @@ -24,7 +22,7 @@ LimitParam = Annotated[ OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] -class Page(BaseModel, Generic[T]): +class Page[T](BaseModel): """One page of a collection, ordered by primary key. ``total`` counts the whole collection, so a client knows there is a next diff --git a/src/fastapi_fastkit/fragments/README.md b/src/fastapi_fastkit/fragments/README.md index 053b3ea0..861111ce 100644 --- a/src/fastapi_fastkit/fragments/README.md +++ b/src/fastapi_fastkit/fragments/README.md @@ -92,12 +92,14 @@ class has no such validator. Both render the example keys from ## Adding a new feature -1. **Catalog.** Add the choice to `FastkitConfig.PACKAGE_CATALOG` in - `core/settings.py`, together with a member on the matching `*Choice` enum - (a brand new axis also needs a `FeatureAxis` member, a `FEATURE_DESCRIPTIONS` - entry, and โ€” if it is multi-select โ€” an entry in `MULTI_SELECT_AXES`). - `DependencyCollector` walks `FeatureAxis` generically, so packages are - picked up with no further changes. +1. **Catalog.** Add the choice as an `[[axes.options]]` entry of its axis in + `catalog/catalog.toml` (packages under `runtime` or `dev`, an optional + `summary`, before the axis' `None` option), and add the same id as a + member of the matching `*Choice` enum in `core/settings.py`. A new axis is + an `[[axes]]` entry (`multi = true` for multi-select) plus a `FeatureAxis` + member. Settings, prompts and `DependencyCollector` read the catalog, and + `tests/test_catalog/test_agreement.py` fails when the enums and the + catalog disagree. 2. **Prompt.** Add a `prompt_*_selection()` to `backend/interactive/prompts.py` and call it from `prompt_additional_features()`. Export it from `backend/interactive/__init__.py` and add a summary row in diff --git a/src/fastapi_fastkit/fragments/tooling/devcontainer.j2 b/src/fastapi_fastkit/fragments/tooling/devcontainer.j2 index 5caba916..3af65323 100644 --- a/src/fastapi_fastkit/fragments/tooling/devcontainer.j2 +++ b/src/fastapi_fastkit/fragments/tooling/devcontainer.j2 @@ -4,7 +4,7 @@ "features": { "ghcr.io/devcontainers/features/docker-in-docker:2": {} }, - "postCreateCommand": "pip install -r requirements.txt", + "postCreateCommand": "pip install -r requirements-dev.txt", "forwardPorts": [ 8000 ], diff --git a/src/fastapi_fastkit/fragments/tooling/github_actions.j2 b/src/fastapi_fastkit/fragments/tooling/github_actions.j2 index a65606eb..f3687c2e 100644 --- a/src/fastapi_fastkit/fragments/tooling/github_actions.j2 +++ b/src/fastapi_fastkit/fragments/tooling/github_actions.j2 @@ -23,12 +23,11 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install -r requirements.txt + pip install -r requirements-dev.txt {% if with_ruff %} - name: Lint run: | - pip install ruff ruff check . ruff format --check . {% endif %} diff --git a/src/fastapi_fastkit/fragments/tooling/makefile.j2 b/src/fastapi_fastkit/fragments/tooling/makefile.j2 index 077748e8..7baf3bbf 100644 --- a/src/fastapi_fastkit/fragments/tooling/makefile.j2 +++ b/src/fastapi_fastkit/fragments/tooling/makefile.j2 @@ -13,7 +13,7 @@ help: ## Show this help awk 'BEGIN {FS = ":.*?## "}; {printf " %-10s %s\n", $$1, $$2}' install: ## Install project dependencies - $(PYTHON) -m pip install -r requirements.txt + $(PYTHON) -m pip install -r requirements-dev.txt test: ## Run the test suite $(PYTHON) -m pytest diff --git a/src/fastapi_fastkit/generation/__init__.py b/src/fastapi_fastkit/generation/__init__.py new file mode 100644 index 00000000..b5d37456 --- /dev/null +++ b/src/fastapi_fastkit/generation/__init__.py @@ -0,0 +1,42 @@ +# -------------------------------------------------------------------------- +# The generation API. +# +# ``generate(spec, target_dir)`` writes one project from a +# :class:`GenerationSpec`, without prompts, subprocesses, tool probing or +# console output. The CLI (through ``ProjectScaffolder``) and the browser +# build both call it. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from fastapi_fastkit.generation.errors import GenerationError, SpecError +from fastapi_fastkit.generation.pipeline import ( + GenerationPlan, + GenerationResult, + generate, + plan, +) +from fastapi_fastkit.generation.secrets import ( + SecretFactory, + default_secret_factory, + seeded_secret_factory, +) +from fastapi_fastkit.generation.spec import ( + GenerationSpec, + ProjectInfo, + spec_from_config, +) + +__all__ = [ + "GenerationError", + "GenerationPlan", + "GenerationResult", + "GenerationSpec", + "ProjectInfo", + "SecretFactory", + "SpecError", + "default_secret_factory", + "generate", + "plan", + "seeded_secret_factory", + "spec_from_config", +] diff --git a/src/fastapi_fastkit/generation/dependencies.py b/src/fastapi_fastkit/generation/dependencies.py new file mode 100644 index 00000000..59245eb5 --- /dev/null +++ b/src/fastapi_fastkit/generation/dependencies.py @@ -0,0 +1,331 @@ +# -------------------------------------------------------------------------- +# Dependency resolution and dependency file rendering for generation. +# +# Runtime and development dependencies are kept apart: runtime packages go +# to ``[project].dependencies`` / ``requirements.txt`` (what a Docker image +# installs), development tools to the manager's dev group and +# ``requirements-dev.txt``. Rendering never looks for installed tools. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import tomllib +from typing import Any, Dict, Iterable, List, Sequence + +from fastapi_fastkit.backend.main import ( + _parse_setup_dependencies, + update_setup_py_dependencies, +) +from fastapi_fastkit.backend.package_managers import PackageManagerFactory +from fastapi_fastkit.backend.package_managers.poetry_manager import ( + _parse_pip_requirement, +) +from fastapi_fastkit.backend.package_managers.pyproject import ( + PyprojectMergeError, + declared_dependency_group, +) +from fastapi_fastkit.backend.package_managers.pyproject import ( + sync_pyproject_dev_file as sync_pyproject_dev_declarations, +) +from fastapi_fastkit.backend.package_managers.requirements import ( + REQUIREMENTS_DEV_FILE, + REQUIREMENTS_FILE, + write_requirements_files, +) +from fastapi_fastkit.backend.project_builder.dependency_collector import ( + DependencyCollector, + DependencySet, + canonical_package_name, + merge_requirements, + unconditional_names, +) +from fastapi_fastkit.core.settings import settings +from fastapi_fastkit.generation.spec import GenerationSpec +from fastapi_fastkit.utils.logging import debug_log +from fastapi_fastkit.utils.main import print_success +from fastapi_fastkit.utils.textio import read_text_preserving_newlines + +#: Files that can hold a project's dependency declarations. +DEPENDENCY_FILES: tuple[str, ...] = ( + "pyproject.toml", + REQUIREMENTS_FILE, + REQUIREMENTS_DEV_FILE, + "setup.py", +) + + +def requirement_name(requirement: str) -> str: + """Canonical distribution name of a PEP 508 requirement string.""" + name, _extras, _spec, _marker = _parse_pip_requirement(requirement.strip()) + return canonical_package_name(name) + + +def classify(requirements: Iterable[str]) -> DependencySet: + """Split requirements into runtime and dev by catalog package names.""" + return DependencyCollector(settings).classify(list(requirements)) + + +def sanitized_custom_packages(packages: Sequence[str]) -> List[str]: + """Custom package entries cleaned the way the interactive prompt does.""" + # Imported lazily: the interactive package pulls in the prompt modules. + from fastapi_fastkit.backend.interactive.validators import ( + sanitize_custom_packages, + ) + + return sanitize_custom_packages(list(packages)) + + +def _features_dependencies(spec: GenerationSpec) -> DependencySet: + """Base, selected options, rule additions and custom packages.""" + config: Dict[str, Any] = spec.to_config() + config["custom_packages"] = sanitized_custom_packages(spec.custom_packages) + return DependencyCollector(settings).collect(config) + + +def legacy_leftovers(spec: GenerationSpec, legacy: Sequence[str]) -> List[str]: + """ + Entries of a saved dependency list that the selections do not explain. + + A config saved by fastkit 1.x lists every package in ``all_dependencies``; + 1.x merged that list with the derived one (:func:`merge_requirements`). + Entries the derived set already covers as written are dropped; the rest + are kept in their original order: hand-added packages (``redis``, an old + ``motor``) and entries that pin, extend or mark a derived package + (``fastapi==0.99.0``, ``uvicorn[standard]>=0.20``), which then win over + the bare derived requirement when the lists are merged. + + :param spec: Features-mode spec without extra dependencies + :param legacy: The saved dependency list + """ + if not legacy: + return [] + derived = _features_dependencies(spec) + by_name: Dict[str, List[str]] = {} + for item in (*derived.runtime, *derived.dev): + by_name.setdefault(requirement_name(item), []).append(item) + leftovers: List[str] = [] + for requirement in legacy: + requirement = requirement.strip() + if not requirement or requirement in leftovers: + continue + same_name = by_name.get(requirement_name(requirement)) + if same_name is not None and merge_requirements( + [*same_name, requirement] + ) == merge_requirements(same_name): + continue + leftovers.append(requirement) + return leftovers + + +def resolve_dependencies( + spec: GenerationSpec, template_root: str = "" +) -> DependencySet: + """ + The runtime and dev dependencies of the project a spec describes. + + * template mode: the template's own declarations + (:func:`template_dependencies`); + * stack mode: ``extra_dependencies`` split by name; + * features mode: base dependencies, the selected options, rule additions + and custom packages, plus the extra dependencies split by name. + + :param spec: The spec + :param template_root: Template directory root (template mode); defaults + to ``settings.FASTKIT_TEMPLATE_ROOT`` + """ + mode = spec.mode + if mode == "template": + root = template_root or settings.FASTKIT_TEMPLATE_ROOT + return template_dependencies(os.path.join(root, spec.template)) + + extra = classify(spec.extra_dependencies) + if mode == "stack": + return DependencySet.from_lists(extra.runtime, extra.dev) + + collected = _features_dependencies(spec) + return DependencySet.from_lists( + [*collected.runtime, *extra.runtime], [*collected.dev, *extra.dev] + ) + + +def _pyproject_template_dependencies(path: str) -> DependencySet | None: + try: + with open(path, "rb") as f: + data = tomllib.load(f) + except (OSError, tomllib.TOMLDecodeError, UnicodeDecodeError) as e: + debug_log(f"Error reading pyproject.toml template: {e}", "error") + return None + + def strings(value: Any) -> List[str]: + if not isinstance(value, list): + return [] + return [v.strip() for v in value if isinstance(v, str) and v.strip()] + + project = data.get("project") + runtime = strings(project.get("dependencies")) if isinstance(project, dict) else [] + groups = data.get("dependency-groups") + dev = strings(groups.get("dev")) if isinstance(groups, dict) else [] + if not runtime and not dev: + return None + return DependencySet(runtime=tuple(runtime), dev=tuple(dev)) + + +def parse_requirements_text(content: str) -> List[str]: + """ + Requirement lines of a requirements file. + + Blank lines, comment lines and option lines (``-r``, ``-c``, ``--...``) + are skipped; inline `` #`` comments are stripped. + """ + requirements: List[str] = [] + for raw in content.splitlines(): + line = raw.strip() + if not line or line.startswith(("#", "-")): + continue + comment = line.find(" #") + if comment != -1: + line = line[:comment].rstrip() + if line: + requirements.append(line) + return requirements + + +def template_dependencies(template_dir: str) -> DependencySet: + """ + The dependencies a template declares. + + 1. ``pyproject.toml-tpl``: ``[project].dependencies`` (runtime) and + ``[dependency-groups].dev`` (dev); + 2. else ``requirements.txt-tpl``, split into runtime and dev by name, + plus every entry of a ``requirements-dev.txt-tpl`` beside it (dev); + 3. else ``setup.py-tpl`` ``install_requires`` (runtime). + + Entries are returned in file order. + + :param template_dir: Path to the template directory + """ + pyproject = os.path.join(template_dir, "pyproject.toml-tpl") + if os.path.isfile(pyproject): + declared = _pyproject_template_dependencies(pyproject) + if declared is not None: + return declared + + requirements = os.path.join(template_dir, "requirements.txt-tpl") + if os.path.isfile(requirements): + try: + content, _ = read_text_preserving_newlines(requirements) + except (OSError, UnicodeDecodeError) as e: + debug_log(f"Error reading {requirements}: {e}", "error") + return DependencySet() + split = classify(parse_requirements_text(content)) + dev_file = os.path.join(template_dir, f"{REQUIREMENTS_DEV_FILE}-tpl") + declared_dev: List[str] = [] + if os.path.isfile(dev_file): + try: + dev_content, _ = read_text_preserving_newlines(dev_file) + declared_dev = parse_requirements_text(dev_content) + except (OSError, UnicodeDecodeError) as e: + debug_log(f"Error reading {dev_file}: {e}", "error") + return DependencySet.from_lists(split.runtime, [*split.dev, *declared_dev]) + + setup = os.path.join(template_dir, "setup.py-tpl") + if os.path.isfile(setup): + try: + content, _ = read_text_preserving_newlines(setup) + except (OSError, UnicodeDecodeError) as e: + debug_log(f"Error reading {setup}: {e}", "error") + return DependencySet() + return DependencySet(runtime=tuple(_parse_setup_dependencies(content))) + + return DependencySet() + + +def merge_dev_group(template_dev: Sequence[str], dev: Iterable[str]) -> List[str]: + """ + The dev group to write: the template's entries verbatim and first, then + the requested dev packages the template does not already name without + an environment marker (sorted). + """ + present = unconditional_names(template_dev) + added = sorted( + requirement + for requirement in merge_requirements(dev) + if requirement_name(requirement) not in present + ) + return [*template_dev, *added] + + +def _template_dev_group(project_dir: str) -> List[str]: + path = os.path.join(project_dir, "pyproject.toml") + if not os.path.isfile(path): + return [] + try: + content, _ = read_text_preserving_newlines(path) + return declared_dependency_group(content.removeprefix("\ufeff"), "dev") + except (OSError, UnicodeDecodeError, PyprojectMergeError) as e: + debug_log(f"Could not read the dev group of {path}: {e}", "warning") + return [] + + +def render_dependency_files( + project_dir: str, spec: GenerationSpec, deps: DependencySet +) -> List[str]: + """ + Write the project's dependency files for ``spec.package_manager``. + + The manager is created without probing, so the files do not depend on + which tools are installed. Runtime packages go to the manager's main + declaration and ``requirements.txt``; the template's dev group plus the + resolved dev packages go to the manager's dev group, + ``requirements-dev.txt`` and every other dev declaration the template's + pyproject.toml has (the managers keep those equal through + :func:`~fastapi_fastkit.backend.package_managers.pyproject.replace_dev_declarations`). + + :param project_dir: Generated project directory + :param spec: The spec (package manager and project info) + :param deps: Resolved dependencies + :return: Project-relative paths of the dependency files present afterwards + """ + runtime = list(deps.runtime) + dev_final = merge_dev_group(_template_dev_group(project_dir), deps.dev) + + manager = PackageManagerFactory.create_manager( + spec.package_manager, project_dir, probe=False + ) + manager.generate_dependency_file( + runtime, + spec.project.name, + spec.project.author, + spec.project.author_email, + spec.project.description, + dev_dependencies=dev_final, + ) + if manager.get_dependency_file_name() != REQUIREMENTS_FILE: + write_requirements_files(project_dir, runtime, dev_final) + + update_setup_py_dependencies(project_dir, runtime) + print_success( + f"Generated dependency file with {len(deps.runtime) + len(deps.dev)} packages" + ) + + return [ + name + for name in DEPENDENCY_FILES + if os.path.isfile(os.path.join(project_dir, name)) + ] + + +__all__ = [ + "DEPENDENCY_FILES", + "DependencySet", + "classify", + "legacy_leftovers", + "merge_dev_group", + "parse_requirements_text", + "render_dependency_files", + "requirement_name", + "resolve_dependencies", + "sanitized_custom_packages", + "sync_pyproject_dev_declarations", + "template_dependencies", +] diff --git a/src/fastapi_fastkit/generation/errors.py b/src/fastapi_fastkit/generation/errors.py new file mode 100644 index 00000000..6fa527e5 --- /dev/null +++ b/src/fastapi_fastkit/generation/errors.py @@ -0,0 +1,24 @@ +# -------------------------------------------------------------------------- +# Errors raised by the generation API. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from typing import Iterable + +from fastapi_fastkit.core.exceptions import BackendExceptions +from fastapi_fastkit.utils.messages import Message + + +class GenerationError(BackendExceptions): + """Generation failed; ``messages`` holds what was emitted before it did.""" + + def __init__(self, message: str, messages: Iterable[Message] = ()) -> None: + super().__init__(message) + self.messages: tuple[Message, ...] = tuple(messages) + + +class SpecError(GenerationError): + """The generation spec (or the config it was built from) is unusable.""" + + +__all__ = ["GenerationError", "SpecError"] diff --git a/src/fastapi_fastkit/generation/metadata.py b/src/fastapi_fastkit/generation/metadata.py new file mode 100644 index 00000000..19fa41c8 --- /dev/null +++ b/src/fastapi_fastkit/generation/metadata.py @@ -0,0 +1,113 @@ +# -------------------------------------------------------------------------- +# The ``[tool.fastapi-fastkit]`` metadata of a generated project. +# +# This mapping is the contract other fastkit commands read back: +# ``runserver`` takes ``app_module`` from it, ``addroute`` locates the +# entrypoint through it, and ``preset`` / ``features`` document how the +# project was produced. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +from typing import Any, Dict, List, Mapping + +from fastapi_fastkit import __version__ +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, + app_module_from_relpath, +) +from fastapi_fastkit.core.settings import FeatureAxis +from fastapi_fastkit.generation.spec import GenerationSpec + + +def template_main_relpath(template_dir: str) -> str: + """Project-relative ``main.py`` path shipped by the template, or ``""``.""" + for root, dirs, files in os.walk(template_dir): + # Sorted so the result does not depend on the file system's order. + dirs.sort() + for file_name in sorted(files): + if file_name.removesuffix("-tpl") != "main.py": + continue + relative = os.path.relpath(os.path.join(root, "main.py"), template_dir) + return relative.replace(os.sep, "/") + return "" + + +def app_module_for(template_dir: str, strategist: PresetLayoutStrategist) -> str: + """ + The uvicorn entrypoint the generated layout will expose. + + Discovered from the template's own ``main.py-tpl`` location so any + template (not just the preset-backed ones) records a correct entrypoint; + the preset profile is the fallback. + """ + template_main = template_main_relpath(template_dir) + if template_main: + return app_module_from_relpath(template_main) + return strategist.app_module + + +def feature_strings(config: Mapping[str, Any]) -> List[str]: + """ + Flatten the selected features into ``":"`` entries. + + :param config: Canonical project config (``GenerationSpec.to_config``) + """ + features: List[str] = [] + + db_info = config.get("database", {}) + if isinstance(db_info, dict) and db_info.get("type", "None") != "None": + features.append(f"database:{db_info['type']}") + + for category in ( + FeatureAxis.AUTHENTICATION, + FeatureAxis.ASYNC_TASKS, + FeatureAxis.TESTING, + FeatureAxis.CACHING, + FeatureAxis.MONITORING, + FeatureAxis.MIGRATIONS, + FeatureAxis.LOGGING, + ): + choice = config.get(category, "None") + if isinstance(choice, str) and choice != "None": + features.append(f"{category}:{choice}") + + for axis in (FeatureAxis.UTILITIES, FeatureAxis.TOOLING): + for choice in config.get(axis, []) or []: + if choice != "None": + features.append(f"{axis}:{choice}") + + for target in config.get("deployment", []) or []: + if target != "None": + features.append(f"deployment:{target}") + + return features + + +def build_metadata(spec: GenerationSpec, app_module: str) -> Dict[str, Any]: + """ + Build the ``[tool.fastapi-fastkit]`` mapping for a spec. + + :param spec: The generation spec + :param app_module: Entrypoint from :func:`app_module_for` + """ + features = feature_strings(spec.to_config()) if spec.features is not None else [] + metadata: Dict[str, Any] = { + "managed": True, + "version": __version__, + "template": spec.template, + "package_manager": spec.package_manager, + "app_module": app_module, + "features": features, + } + if spec.preset: + metadata["preset"] = spec.preset + return metadata + + +__all__ = [ + "app_module_for", + "build_metadata", + "feature_strings", + "template_main_relpath", +] diff --git a/src/fastapi_fastkit/generation/pipeline.py b/src/fastapi_fastkit/generation/pipeline.py new file mode 100644 index 00000000..9dcd5994 --- /dev/null +++ b/src/fastapi_fastkit/generation/pipeline.py @@ -0,0 +1,516 @@ +# -------------------------------------------------------------------------- +# The generation pipeline: one spec in, one project tree out. +# +# ``generate`` never prompts, never runs a subprocess, never looks for +# installed tools and never prints. Messages the steps used to print are +# returned as data (``GenerationResult.messages``), and nothing is ever +# deleted: rolling back a failed run is the caller's decision. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +from dataclasses import dataclass +from typing import Any, Dict, Iterable, List, Mapping, Optional, Union + +from fastapi_fastkit.backend.main import ( + ENV_EXAMPLE_FILE, + ENV_FILE, + ENV_KEPT_MESSAGE, + create_local_env_file, + inject_project_metadata, + is_within_directory, + prepare_dependency_file_for_manager, + write_fastkit_metadata, +) +from fastapi_fastkit.backend.project_builder import DynamicConfigGenerator +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, +) +from fastapi_fastkit.backend.transducer import ( + TEMPLATE_ONLY_FILES, + copy_and_convert_template, + same_file, +) +from fastapi_fastkit.core.settings import settings +from fastapi_fastkit.generation.dependencies import ( + DependencySet, + render_dependency_files, + resolve_dependencies, +) +from fastapi_fastkit.generation.errors import GenerationError +from fastapi_fastkit.generation.metadata import app_module_for, build_metadata +from fastapi_fastkit.generation.secrets import SecretFactory +from fastapi_fastkit.generation.spec import GenerationSpec, validate_spec +from fastapi_fastkit.utils.filemodes import is_executable_path, mark_executable +from fastapi_fastkit.utils.main import print_info, print_success, print_warning +from fastapi_fastkit.utils.messages import Message, capture_messages + +#: ``requirements-dev.txt`` is written next to every generated dependency file. +REQUIREMENTS_DEV_FILE = "requirements-dev.txt" + + +def _core_module_paths() -> List[str]: + """Where generation looks for (and rewrites) setup / pyproject / main / + settings modules, whether or not the template ships them.""" + paths = settings.TEMPLATE_PATHS + found: List[str] = [] + for key in ("main", "setup", "pyproject"): + entries = paths[key] + if isinstance(entries, list): + found.extend(entries) + config = paths["config"] + if isinstance(config, dict): + for directory in config["paths"]: + for name in config["files"]: + found.append(f"{directory}/{name}" if directory else name) + # The feature overlay appends to an existing README.md and .env.example + # whether or not the template ships them. + found.extend(("README.md", ENV_EXAMPLE_FILE)) + return found + + +@dataclass(frozen=True) +class GenerationResult: + """What ``generate`` wrote.""" + + #: Absolute project directory. + project_dir: str + template: str + preset: Optional[str] + app_module: str + #: Runtime / dev dependencies as rendered (template mode: the template's). + dependencies: DependencySet + #: The ``[tool.fastapi-fastkit]`` mapping written into pyproject.toml. + metadata: Mapping[str, Any] + #: Sorted project-relative POSIX paths this run wrote. + files: tuple[str, ...] + messages: tuple[Message, ...] + + +@dataclass(frozen=True) +class GenerationPlan: + """What ``generate`` would write (``plan``); nothing is touched.""" + + project_dir: str + template: str + preset: Optional[str] + app_module: str + dependencies: DependencySet + metadata: Mapping[str, Any] + files: tuple[str, ...] + + +# ------------------------------------------------------------------ +# Feature overlay +# ------------------------------------------------------------------ + + +def config_generator( + config: Dict[str, Any], + project_dir: str, + strategist: PresetLayoutStrategist, + app_module: str, +) -> DynamicConfigGenerator: + """Build a generator that knows the preset's file layout.""" + profile = strategist.profile + return DynamicConfigGenerator( + config, + project_dir, + app_module=app_module, + main_py_relpath=profile.main_py_relpath, + db_config_relpath=profile.db_config_relpath, + auth_package_relpath=profile.auth_package_relpath, + settings_relpath=profile.settings_relpath, + shipped_paths=( + () if strategist.should_regenerate_main else profile.shipped_paths + ), + provide_pagination=profile.provide_pagination, + ) + + +def apply_feature_overlay( + project_dir: str, + config: Dict[str, Any], + strategist: PresetLayoutStrategist, + app_module: str, +) -> List[str]: + """ + Write the feature-driven modules on top of the deployed template. + + The generator owns the full artifact list; the only preset decision left + here is whether the dynamic ``main.py`` overlay replaces the + template-shipped entrypoint. Richer presets (classic-layered, + domain-starter) keep the template's router-aware ``main.py`` and get the + generated features spliced in through its ``# fastkit:`` anchors; + whatever cannot be spliced in safely is reported instead. + + :return: Project-relative paths the generator wrote + """ + generator = config_generator(config, project_dir, strategist, app_module) + include_main = strategist.should_regenerate_main + + if not include_main: + print_info( + f"Preserving template-shipped main.py for preset " + f"'{strategist.preset_id}'." + ) + + written = generator.generate_all_files(include_main=include_main) + + if "Dockerfile" in written or "docker-compose.yml" in written: + print_success("Generated Docker deployment files") + + wired = strategist.wire_generated_routers(project_dir, config) + if wired: + print_success( + f"Wired generated features into " + f"{strategist.profile.main_py_relpath}: {', '.join(wired)}" + ) + for note in strategist.generation_notes(config): + print_info(note) + strategist.append_readme_notes(project_dir, config) + for conflict in strategist.auth_route_conflicts(project_dir, config): + print_warning(conflict, title="Authentication routes") + + for warning in strategist.compatibility_warnings(config, wired=wired): + print_warning(warning, title="Preset compatibility") + + print_success(f"Generated {len(written)} configuration files for selected stack") + return list(written) + + +# ------------------------------------------------------------------ +# generate / plan +# ------------------------------------------------------------------ + + +def _relative(project_dir: str, paths: Iterable[str]) -> List[str]: + relative: List[str] = [] + for path in paths: + rel = os.path.relpath(path, project_dir) if os.path.isabs(path) else path + relative.append(rel.replace(os.sep, "/")) + return relative + + +def _template_dir(spec: GenerationSpec, template_root: Optional[str]) -> str: + return os.path.join(template_root or settings.FASTKIT_TEMPLATE_ROOT, spec.template) + + +def template_directories( + spec: GenerationSpec, template_root: Optional[str] = None +) -> List[str]: + """Project-relative POSIX paths of every directory the template copy + creates, empty ones included.""" + template_dir = _template_dir(spec, template_root) + found: List[str] = [] + for root, dirs, _files in os.walk(template_dir): + for name in dirs: + relative = os.path.relpath(os.path.join(root, name), template_dir) + found.append(relative.replace(os.sep, "/")) + return sorted(found) + + +def writable_paths(files: Iterable[str], project_dir: str) -> List[str]: + """ + Every project-relative path a run may write, given its planned files. + + Besides the planned files, generation rewrites the core modules it finds + in ``project_dir`` (an existing ``pyproject.toml``, ``setup.py``, + ``main.py`` or settings module, ``README.md`` or ``.env.example``, also + one the template does not ship) and the requirements files. + """ + candidates = set(files) + candidates.update( + relpath + for relpath in _core_module_paths() + if os.path.lexists(os.path.join(project_dir, *relpath.split("/"))) + ) + candidates.update(("requirements.txt", REQUIREMENTS_DEV_FILE)) + return sorted(candidates) + + +def symlinked_targets(project_dir: str, relpaths: Iterable[str]) -> List[str]: + """ + The paths among ``relpaths`` that writing would follow a symlink for. + + A destination that is itself a symlink (dangling or not) is listed, and + so is a directory link on the way to it that leads outside + ``project_dir``. A directory link that stays inside is followed. A + Windows directory junction counts as a directory link. + + :return: Sorted project-relative POSIX paths of the offending links + """ + found = set() + for relpath in relpaths: + parts = relpath.split("/") + current = project_dir + for index, part in enumerate(parts): + current = os.path.join(current, part) + if not (os.path.islink(current) or os.path.isjunction(current)): + if not os.path.lexists(current): + break + continue + last = index == len(parts) - 1 + if last or not is_within_directory(current, project_dir): + found.add("/".join(parts[: index + 1])) + break + return sorted(found) + + +def symlink_refusal(project_dir: str, links: Iterable[str]) -> str: + """The error for :func:`symlinked_targets` findings.""" + return ( + f"Refusing to write into '{project_dir}' through symbolic links: " + f"{', '.join(links)}. Replace them with regular files or directories, " + "or generate into another directory." + ) + + +def generate( + spec: GenerationSpec, + target_dir: Union[str, "os.PathLike[str]"], + *, + secret_factory: Optional[SecretFactory] = None, + template_root: Optional[str] = None, +) -> GenerationResult: + """ + Generate the project a spec describes into ``target_dir``. + + ``target_dir`` is the project directory itself; it is created when + missing and may already exist (files the template ships are then + overwritten, an existing ``.env`` is kept). Nothing is deleted, also + when a step fails. + + :param spec: What to generate + :param target_dir: Project directory + :param secret_factory: Source of ``SECRET_KEY`` values for ``.env``; + defaults to ``secrets.token_urlsafe(32)`` + :param template_root: Directory holding the templates; defaults to the + bundled templates + :return: What was written + :raises GenerationError: If the spec is invalid (nothing is written) or a + step fails; ``messages`` holds what was emitted until then + """ + root = template_root or settings.FASTKIT_TEMPLATE_ROOT + project_dir = os.path.abspath(os.fspath(target_dir)) + with capture_messages() as sink: + try: + return _generate(spec, project_dir, root, secret_factory, sink) + except GenerationError as e: + # Keeps its type (SpecError stays SpecError). + e.messages = tuple(sink) + raise + except Exception as e: + raise GenerationError(str(e), messages=tuple(sink)) from e + + +def _generate( + spec: GenerationSpec, + project_dir: str, + template_root: str, + secret_factory: Optional[SecretFactory], + sink: List[Message], +) -> GenerationResult: + config = validate_spec(spec, template_root) + template_dir = os.path.join(template_root, spec.template) + strategist = PresetLayoutStrategist(spec.preset) + app_module = app_module_for(template_dir, strategist) + + env_path = os.path.join(project_dir, ENV_FILE) + keep_env = os.path.lexists(env_path) + if os.path.isdir(project_dir): + links = symlinked_targets( + project_dir, + writable_paths( + planned_files(spec, project_dir, template_root, config), project_dir + ), + ) + if links: + raise GenerationError(symlink_refusal(project_dir, links)) + + os.makedirs(project_dir, exist_ok=True) + # An existing .env is the user's secret file; a template shipping one + # (``.env-tpl``) never replaces it. + copied = copy_and_convert_template( + template_dir, project_dir, "", skip=(ENV_FILE,) if keep_env else () + ) + written: List[str] = _relative(project_dir, copied) + + project = spec.project + inject_project_metadata( + project_dir, + project.name, + project.author, + project.author_email, + project.description, + files=copied, + ) + + deps = resolve_dependencies(spec, template_root) + if spec.dependency_files == "generated": + written.extend(render_dependency_files(project_dir, spec, deps)) + + if spec.features is not None: + written.extend( + apply_feature_overlay(project_dir, config, strategist, app_module) + ) + + # After substitution, so placeholders in .env.example are filled in the + # generated .env too, and after the feature overlay, which appends the + # variables the selected features read. Never overwrites a .env. + if create_local_env_file(project_dir, secret_factory=secret_factory): + written.append(ENV_FILE) + elif ( + keep_env + and _template_ships(template_dir, ENV_FILE) + and not os.path.isfile(os.path.join(project_dir, ENV_EXAMPLE_FILE)) + ): + # create_local_env_file reports the kept .env only next to a + # .env.example. + print_info(ENV_KEPT_MESSAGE) + + metadata = build_metadata(spec, app_module) + write_fastkit_metadata(project_dir, metadata) + prepare_dependency_file_for_manager(project_dir, spec.package_manager) + + files = tuple(sorted(set(written))) + for relpath in files: + path = os.path.join(project_dir, *relpath.split("/")) + if is_executable_path(relpath) and os.path.isfile(path): + mark_executable(path) + + return GenerationResult( + project_dir=project_dir, + template=spec.template, + preset=spec.preset, + app_module=app_module, + dependencies=deps, + metadata=metadata, + files=files, + messages=tuple(sink), + ) + + +def _template_ships(template_dir: str, relpath: str) -> bool: + path = os.path.join(template_dir, *relpath.split("/")) + return os.path.isfile(path) or os.path.isfile(path + "-tpl") + + +def planned_files( + spec: GenerationSpec, + project_dir: str, + template_root: Optional[str] = None, + config: Optional[Dict[str, Any]] = None, +) -> List[str]: + """ + The project-relative files a real run would write. + + Template files are reported under their converted names (the ``-tpl`` + marker stripped; template-only files such as ``template-config.yml`` + are left out, as the copy skips them), plus the modules the feature + overlay writes, ``.env`` when the project has none yet and the + dependency files of generated mode. + """ + template_dir = _template_dir(spec, template_root) + planned: List[str] = [] + + for root, _dirs, files in os.walk(template_dir): + relative_dir = os.path.relpath(root, template_dir) + for file_name in files: + converted = file_name.removesuffix("-tpl") + if converted in TEMPLATE_ONLY_FILES: + continue + if relative_dir == ".": + planned.append(converted) + else: + planned.append(os.path.join(relative_dir, converted)) + + if spec.features is not None: + config = config if config is not None else spec.to_config() + strategist = PresetLayoutStrategist(spec.preset) + app_module = app_module_for(template_dir, strategist) + planned.extend( + config_generator(config, project_dir, strategist, app_module).planned_files( + include_main=strategist.should_regenerate_main + ) + ) + deployment = config.get("deployment", []) + if deployment and deployment != ["None"]: + planned.append(".dockerignore") + + env_path = os.path.join(project_dir, ENV_FILE) + if os.path.lexists(env_path): + # Never replaced, also when the template ships a .env (in any case + # the file system treats as the same name). + planned = [ + path + for path in planned + if path != ENV_FILE + and not same_file(os.path.join(project_dir, path), env_path) + ] + elif ENV_EXAMPLE_FILE in planned or os.path.isfile( + os.path.join(project_dir, ENV_EXAMPLE_FILE) + ): + # Also from a .env.example the directory already has. + planned.append(ENV_FILE) + + if spec.dependency_files == "generated": + planned.append( + settings.PACKAGE_MANAGER_CONFIG[spec.package_manager]["dependency_file"] + ) + planned.append(REQUIREMENTS_DEV_FILE) + + return sorted(set(path.replace(os.sep, "/") for path in planned)) + + +def plan( + spec: GenerationSpec, + target_dir: Union[str, "os.PathLike[str]"], + *, + template_root: Optional[str] = None, +) -> GenerationPlan: + """ + Describe what :func:`generate` would write, writing nothing. + + :raises GenerationError: If the spec is invalid + """ + root = template_root or settings.FASTKIT_TEMPLATE_ROOT + project_dir = os.path.abspath(os.fspath(target_dir)) + with capture_messages(): + try: + config = validate_spec(spec, root) + template_dir = os.path.join(root, spec.template) + strategist = PresetLayoutStrategist(spec.preset) + app_module = app_module_for(template_dir, strategist) + deps = resolve_dependencies(spec, root) + files = planned_files(spec, project_dir, root, config) + except GenerationError: + raise + except Exception as e: + raise GenerationError(str(e)) from e + + return GenerationPlan( + project_dir=project_dir, + template=spec.template, + preset=spec.preset, + app_module=app_module, + dependencies=deps, + metadata=build_metadata(spec, app_module), + files=tuple(files), + ) + + +__all__ = [ + "GenerationError", + "GenerationPlan", + "GenerationResult", + "apply_feature_overlay", + "config_generator", + "generate", + "plan", + "planned_files", + "symlink_refusal", + "symlinked_targets", + "template_directories", + "writable_paths", +] diff --git a/src/fastapi_fastkit/generation/secrets.py b/src/fastapi_fastkit/generation/secrets.py new file mode 100644 index 00000000..eee7b87b --- /dev/null +++ b/src/fastapi_fastkit/generation/secrets.py @@ -0,0 +1,45 @@ +# -------------------------------------------------------------------------- +# Secret values written into a generated project's local ``.env``. +# +# ``SECRET_KEY`` is the only random value generation produces. It comes from +# an injectable factory so tests (and the web/CLI comparison) can get +# reproducible trees without a CLI switch for predictable secrets. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import base64 +import hashlib +import itertools +import secrets +from typing import Callable + +#: Returns one fresh secret per call. +SecretFactory = Callable[[], str] + + +def default_secret_factory() -> str: + """Return a random URL-safe secret (43 characters).""" + return secrets.token_urlsafe(32) + + +def seeded_secret_factory(seed: str) -> SecretFactory: + """ + Return a factory whose values depend only on ``seed`` and the call count. + + The values have the shape of :func:`default_secret_factory` output (43 + URL-safe base64 characters, no padding). Meant for tests; never use a + seeded factory for a real project. + + :param seed: Any string; equal seeds give equal sequences + :return: Factory producing the n-th value of the seed's sequence + """ + counter = itertools.count() + + def factory() -> str: + digest = hashlib.sha256(f"{seed}:{next(counter)}".encode("utf-8")).digest() + return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") + + return factory + + +__all__ = ["SecretFactory", "default_secret_factory", "seeded_secret_factory"] diff --git a/src/fastapi_fastkit/generation/spec.py b/src/fastapi_fastkit/generation/spec.py new file mode 100644 index 00000000..c0b2879e --- /dev/null +++ b/src/fastapi_fastkit/generation/spec.py @@ -0,0 +1,305 @@ +# -------------------------------------------------------------------------- +# What to generate: the generation spec. +# +# A ``GenerationSpec`` describes one project completely (template, preset, +# feature selections, package manager, dependency handling) without saying +# how the answers were obtained. The CLI builds one from its options and +# prompts, the browser build from a form, tests directly. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +from dataclasses import dataclass, replace +from typing import Any, Dict, List, Literal, Mapping, Optional, Sequence, Union + +from fastapi_fastkit.backend.project_builder.config_schema import ( + ConfigSchemaError, + normalize_project_config, +) +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, +) +from fastapi_fastkit.core.settings import ( + MULTI_SELECT_AXES, + NONE_CHOICE, + FeatureAxis, + settings, +) +from fastapi_fastkit.generation.errors import SpecError + +#: One axis selection: a choice id, or a tuple of ids for multi-select axes. +FeatureValue = Union[str, tuple[str, ...]] + +#: The non-feature selection key that :attr:`GenerationSpec.features` accepts. +DEPLOYMENT_KEY = "deployment" + +GenerationMode = Literal["template", "stack", "features"] + + +@dataclass(frozen=True) +class ProjectInfo: + """Name and authorship written into the generated project.""" + + name: str + author: str = "" + author_email: str = "" + description: str = "" + #: Application version a regenerated ``main.py`` passes to ``FastAPI()`` + #: (the ``version`` key of a project config); empty means the + #: generator's default, ``0.1.0``. + version: str = "" + + +@dataclass(frozen=True) +class GenerationSpec: + """ + Everything ``generate`` needs to produce one project. + + ``features`` is ``None`` when no feature overlay is applied. Otherwise its + keys are feature axis ids plus ``"deployment"``; a missing single-select + axis means ``"None"`` and a missing multi-select axis means no choice. + """ + + project: ProjectInfo + #: Template directory id (``fastapi-default``, ...). + template: str + #: Architecture preset id; features mode only. + preset: Optional[str] = None + features: Optional[Mapping[str, FeatureValue]] = None + #: ``"template"`` keeps the template's dependency files as shipped; + #: ``"generated"`` renders them from the resolved dependencies. + dependency_files: Literal["template", "generated"] = "template" + package_manager: str = "uv" + custom_packages: tuple[str, ...] = () + #: Stack list or legacy leftovers; split into runtime / dev by name. + extra_dependencies: tuple[str, ...] = () + + @property + def mode(self) -> GenerationMode: + """``features`` with an overlay, ``stack`` with generated files, else ``template``.""" + if self.features is not None: + return "features" + if self.dependency_files == "generated": + return "stack" + return "template" + + def to_config(self) -> Dict[str, Any]: + """ + Return the canonical config mapping for this spec. + + This is the shape ``DynamicConfigGenerator``, ``PresetLayoutStrategist`` + and ``DependencyCollector`` read. It is passed through + ``normalize_project_config``, so it is validated and canonical. + + :raises ConfigSchemaError: If a selection is unknown or invalid + """ + features: Mapping[str, FeatureValue] = self.features or {} + config: Dict[str, Any] = { + "project_name": self.project.name, + "author": self.project.author, + "author_email": self.project.author_email, + "description": self.project.description, + } + if self.project.version: + config["version"] = self.project.version + if self.preset: + config["architecture_preset"] = self.preset + for axis in FeatureAxis: + key = str(axis) + value = features.get(key) + if axis in MULTI_SELECT_AXES: + config[key] = _as_list(value) + elif axis == FeatureAxis.DATABASE: + config[key] = {"type": value or NONE_CHOICE} + else: + config[key] = value or NONE_CHOICE + config[DEPLOYMENT_KEY] = _as_list(features.get(DEPLOYMENT_KEY)) + config["package_manager"] = self.package_manager + config["custom_packages"] = list(self.custom_packages) + return normalize_project_config(config) + + +def _as_list(value: Optional[FeatureValue]) -> List[str]: + """A multi-select value as a list (a bare string counts as one choice).""" + if value is None: + return [] + if isinstance(value, str): + return [value] + return list(value) + + +def _config_version(value: Any) -> str: + """A config's ``version`` value as text; ``""`` when it is not set.""" + if value is None or value == "": + return "" + return str(value) + + +def feature_keys() -> tuple[str, ...]: + """Keys :attr:`GenerationSpec.features` accepts, in catalog order.""" + return tuple(str(axis) for axis in FeatureAxis) + (DEPLOYMENT_KEY,) + + +#: Directories of the template root that are not templates. +NON_TEMPLATE_DIRS = frozenset({"__pycache__", "modules"}) + + +def is_template_name(template_root: str, name: str) -> bool: + """ + Whether ``name`` names a template: a directory directly under + ``template_root`` that is not hidden and not one of + :data:`NON_TEMPLATE_DIRS`. Paths (absolute, relative or with a drive) + are never template names. + + :param template_root: Directory holding the template directories + :param name: Candidate template name + """ + if not name or name.startswith(".") or name in NON_TEMPLATE_DIRS: + return False + if any(separator in name for separator in ("/", "\\", ":")): + return False + return os.path.isdir(os.path.join(template_root, name)) + + +def validate_spec(spec: GenerationSpec, template_root: str) -> Dict[str, Any]: + """ + Check a spec before anything is written. + + :param spec: Spec to check + :param template_root: Directory holding the template directories + :return: The spec's canonical config (see :meth:`GenerationSpec.to_config`) + :raises SpecError: If the spec cannot be generated + """ + if not spec.project.name: + raise SpecError("The project name must not be empty.") + supported: List[str] = list(settings.SUPPORTED_PACKAGE_MANAGERS) + if spec.package_manager not in supported: + raise SpecError( + f"Unknown package manager '{spec.package_manager}'. Allowed values: " + f"{', '.join(sorted(supported))}" + ) + if spec.features is not None: + unknown = sorted(set(spec.features) - set(feature_keys())) + if unknown: + raise SpecError( + f"Unknown feature key(s): {', '.join(unknown)}. Allowed keys: " + f"{', '.join(feature_keys())}" + ) + if spec.preset is not None and ( + spec.preset not in PresetLayoutStrategist.supported_presets() + ): + raise SpecError( + f"Unknown architecture preset '{spec.preset}'. Allowed values: " + f"{', '.join(sorted(PresetLayoutStrategist.supported_presets()))}" + ) + if not is_template_name(template_root, spec.template): + raise SpecError( + f"Template '{spec.template}' does not exist in '{template_root}'." + ) + try: + return spec.to_config() + except ConfigSchemaError as e: + raise SpecError(str(e)) from e + + +def spec_from_config( + config: Mapping[str, Any], + *, + package_manager: Optional[str] = None, + template: Optional[str] = None, + preset: Optional[str] = None, + legacy_dependencies: Optional[Sequence[str]] = None, +) -> GenerationSpec: + """ + Build a features-mode spec from a project config mapping. + + Accepts every shape ``normalize_project_config`` accepts: an interactive + session's config, a hand-written ``--config`` file and a file saved by + fastkit 1.x (``all_dependencies``, ``base_template`` and + ``architecture_preset_description`` are accepted; entries of + ``all_dependencies`` that the selections do not explain are kept as + extra dependencies). ``version`` becomes :attr:`ProjectInfo.version`, as + 1.x passed it to the generated ``main.py``. + + :param config: Project config mapping + :param package_manager: Override for the config's package manager + :param template: Override for the preset's base template + :param preset: Override for the config's preset + :param legacy_dependencies: Dependency list to keep leftovers from; + defaults to the config's ``all_dependencies`` + :return: The spec + :raises SpecError: If the config is invalid or has no project name + """ + try: + normalized = normalize_project_config(dict(config)) + except ConfigSchemaError as e: + raise SpecError(str(e)) from e + + name = normalized.get("project_name") + if not name or not isinstance(name, str): + raise SpecError("Project configuration is missing 'project_name'.") + + strategist = PresetLayoutStrategist(preset or normalized.get("architecture_preset")) + + features: Dict[str, FeatureValue] = {} + for axis in FeatureAxis: + key = str(axis) + value = normalized.get(key) + if axis in MULTI_SELECT_AXES: + features[key] = tuple(value or ()) + elif axis == FeatureAxis.DATABASE: + features[key] = str((value or {}).get("type", NONE_CHOICE)) + else: + features[key] = str(value or NONE_CHOICE) + features[DEPLOYMENT_KEY] = tuple(normalized.get(DEPLOYMENT_KEY) or ()) + + # Imported here: the dependency module needs the catalog-backed collector, + # which the spec dataclasses themselves do not. + from fastapi_fastkit.generation.dependencies import ( + legacy_leftovers, + sanitized_custom_packages, + ) + + custom = sanitized_custom_packages(normalized.get("custom_packages") or []) + manager = ( + package_manager + or normalized.get("package_manager") + or settings.DEFAULT_PACKAGE_MANAGER + ) + legacy = ( + list(legacy_dependencies) + if legacy_dependencies is not None + else list(normalized.get("all_dependencies") or []) + ) + + spec = GenerationSpec( + project=ProjectInfo( + name=name, + author=str(normalized.get("author") or ""), + author_email=str(normalized.get("author_email") or ""), + description=str(normalized.get("description") or ""), + version=_config_version(normalized.get("version")), + ), + template=template or strategist.base_template, + preset=strategist.preset_id, + features=features, + dependency_files="generated", + package_manager=str(manager), + custom_packages=tuple(custom), + ) + leftovers = legacy_leftovers(spec, legacy) + return replace(spec, extra_dependencies=tuple(leftovers)) if leftovers else spec + + +__all__ = [ + "DEPLOYMENT_KEY", + "FeatureValue", + "GenerationMode", + "GenerationSpec", + "ProjectInfo", + "SpecError", + "feature_keys", + "is_template_name", + "spec_from_config", + "validate_spec", +] diff --git a/src/fastapi_fastkit/utils/filemodes.py b/src/fastapi_fastkit/utils/filemodes.py new file mode 100644 index 00000000..5047eb05 --- /dev/null +++ b/src/fastapi_fastkit/utils/filemodes.py @@ -0,0 +1,42 @@ +# -------------------------------------------------------------------------- +# Executable bits for generated files. +# +# Template files are copied by content only, so the mode a wheel or a +# checkout happened to carry never reaches a generated project. The files +# that must be executable are chosen by name here and marked explicitly. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import stat +from typing import Union + +#: File name suffixes of generated files that get execute permission. +EXECUTABLE_SUFFIXES: tuple[str, ...] = (".sh",) + + +def is_executable_path(relpath: str) -> bool: + """ + Return True when a generated file should be executable. + + :param relpath: Project-relative path, POSIX or native separators + """ + name = relpath.replace("\\", "/").rsplit("/", 1)[-1] + return name.endswith(EXECUTABLE_SUFFIXES) + + +def mark_executable(path: Union[str, "os.PathLike[str]"]) -> None: + """ + Add execute permission wherever read permission is set. + + ``0o644`` becomes ``0o755`` and ``0o600`` becomes ``0o700``, so the + umask the file was created with is respected. On Windows ``chmod`` only + touches the read-only flag, which this leaves as it is. + + :param path: File to mark + """ + mode = stat.S_IMODE(os.stat(path).st_mode) + os.chmod(path, mode | ((mode & 0o444) >> 2)) + + +__all__ = ["EXECUTABLE_SUFFIXES", "is_executable_path", "mark_executable"] diff --git a/src/fastapi_fastkit/utils/main.py b/src/fastapi_fastkit/utils/main.py index e28e60eb..0cb38912 100644 --- a/src/fastapi_fastkit/utils/main.py +++ b/src/fastapi_fastkit/utils/main.py @@ -18,6 +18,7 @@ from fastapi_fastkit.core.settings import settings from fastapi_fastkit.utils.logging import debug_log, get_logger +from fastapi_fastkit.utils.messages import emit logger = get_logger(__name__) @@ -107,6 +108,9 @@ def print_error( :param console: Rich console instance :param show_traceback: Whether to show stack trace in debug mode """ + # Recorded instead of drawn while generation captures messages. + if emit("error", message, title): + return error_text = Text() error_text.append("โŒ ", style="bold red") error_text.append(message) @@ -148,6 +152,8 @@ def print_success( :param title: Title for the success panel :param console: Rich console instance """ + if emit("success", message, title): + return success_text = Text() success_text.append("โœจ ", style="bold yellow") success_text.append(message, style="bold green") @@ -168,6 +174,8 @@ def print_warning( :param title: Title for the warning panel :param console: Rich console instance """ + if emit("warning", message, title): + return warning_text = Text() warning_text.append("โš ๏ธ ", style="bold yellow") warning_text.append(message) @@ -186,6 +194,8 @@ def print_info(message: str, title: str = "Info", console: Console = console) -> :param title: Title for the info panel :param console: Rich console instance """ + if emit("info", message, title): + return info_text = Text() info_text.append("โ„น ", style="bold blue") info_text.append(message) diff --git a/src/fastapi_fastkit/utils/messages.py b/src/fastapi_fastkit/utils/messages.py new file mode 100644 index 00000000..3ff03430 --- /dev/null +++ b/src/fastapi_fastkit/utils/messages.py @@ -0,0 +1,87 @@ +# -------------------------------------------------------------------------- +# User-facing messages as data. +# +# Generation must not print: the browser build has no terminal, and the CLI +# wants to decide when panels appear. The ``print_*`` helpers in +# ``fastapi_fastkit.utils.main`` hand their message to :func:`emit` first; +# while a :func:`capture_messages` block is active the message is recorded +# here instead of being drawn, and the caller replays it later. +# +# Standard library only, so it can be imported anywhere (and under Pyodide). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from typing import Iterator, List, Literal, Optional, cast + +MessageLevel = Literal["info", "success", "warning", "error"] + +#: Levels :func:`emit` accepts, in no particular order. +MESSAGE_LEVELS: tuple[str, ...] = ("info", "success", "warning", "error") + + +@dataclass(frozen=True) +class Message: + """One message a ``print_*`` helper would have shown.""" + + level: MessageLevel + text: str + title: str + + +_SINK: ContextVar[Optional[List[Message]]] = ContextVar( + "fastkit_message_sink", default=None +) + + +@contextmanager +def capture_messages() -> Iterator[List[Message]]: + """ + Record messages instead of printing them for the duration of the block. + + Blocks nest: the innermost one receives the messages. The yielded list + keeps growing while the block runs and stays readable afterwards. + """ + sink: List[Message] = [] + token = _SINK.set(sink) + try: + yield sink + finally: + _SINK.reset(token) + + +def emit(level: str, text: str, title: str) -> bool: + """ + Record a message when a capture is active. + + :param level: One of :data:`MESSAGE_LEVELS` + :param text: Message text + :param title: Panel title + :return: True when the message was recorded (the caller must not print + it), False when nothing is capturing + :raises ValueError: If ``level`` is not a known level + """ + if level not in MESSAGE_LEVELS: + raise ValueError(f"Unknown message level: {level!r}") + sink = _SINK.get() + if sink is None: + return False + sink.append(Message(cast(MessageLevel, level), text, title)) + return True + + +def is_capturing() -> bool: + """Return True while a :func:`capture_messages` block is active.""" + return _SINK.get() is not None + + +__all__ = [ + "MESSAGE_LEVELS", + "Message", + "MessageLevel", + "capture_messages", + "emit", + "is_capturing", +] diff --git a/tests/test_backends/test_dependency_groups.py b/tests/test_backends/test_dependency_groups.py new file mode 100644 index 00000000..eb805386 --- /dev/null +++ b/tests/test_backends/test_dependency_groups.py @@ -0,0 +1,466 @@ +# -------------------------------------------------------------------------- +# [dependency-groups] editing (PEP 735): replace_dependency_group keeps every +# byte it does not own, and declared_dependency_group reads the group back. +# replace_declared_optional_dependencies keeps a template's ``dev`` extra +# equal to the group. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import tomllib +from pathlib import Path +from typing import List + +import pytest + +from fastapi_fastkit.backend.package_managers.pyproject import ( + PyprojectMergeError, + declared_dependency_group, + replace_declared_optional_dependencies, + replace_dependency_group, +) +from fastapi_fastkit.core.settings import FastkitConfig + +TEMPLATE_ROOT = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + +BEFORE_GROUPS = """\ +# A template pyproject: comments and layout must survive. +[project] +name = "demo" +version = "0.1.0" +dependencies = [ + "fastapi>=0.141.1", # the web framework +] + +""" + +AFTER_GROUPS = """ +[tool.black] +line-length = 88 +extend-exclude = ''' +[dependency-groups] +dev = ["not-a-table"] +''' +""" + +DEV_GROUP = """\ +[dependency-groups] +# Tools for tests and linting. +dev = [ + "pytest>=9.1.1", # tests + "httpx>=0.28.1", +] +docs = ["mkdocs"] +""" + +DOCUMENT = BEFORE_GROUPS + DEV_GROUP + AFTER_GROUPS + + +def _group(content: str, group: str = "dev") -> List[str]: + return list(tomllib.loads(content)["dependency-groups"][group]) + + +class TestReplaceDependencyGroup: + def test_replaces_the_group_and_keeps_everything_else(self) -> None: + updated = replace_dependency_group( + DOCUMENT, "dev", ["pytest>=9.1.1", "httpx>=0.28.1", "ruff"] + ) + + assert _group(updated) == ["pytest>=9.1.1", "httpx>=0.28.1", "ruff"] + assert updated.startswith(BEFORE_GROUPS) + assert updated.endswith('docs = ["mkdocs"]\n' + AFTER_GROUPS) + assert "# Tools for tests and linting.\n" in updated + assert _group(updated, "docs") == ["mkdocs"] + + def test_renders_one_entry_per_line_like_the_templates(self) -> None: + updated = replace_dependency_group(DOCUMENT, "dev", ["pytest", "ruff"]) + + assert 'dev = [\n "pytest",\n "ruff",\n]' in updated + + def test_equal_group_returns_the_text_unchanged(self) -> None: + assert ( + replace_dependency_group( + DOCUMENT, "dev", ["pytest>=9.1.1", "httpx>=0.28.1"] + ) + is DOCUMENT + ) + + def test_adds_a_missing_group_to_the_existing_table(self) -> None: + updated = replace_dependency_group(DOCUMENT, "lint", ["ruff"]) + + assert _group(updated, "lint") == ["ruff"] + assert _group(updated) == ["pytest>=9.1.1", "httpx>=0.28.1"] + assert updated.startswith(BEFORE_GROUPS + DEV_GROUP) + + def test_creates_the_table_at_the_end_when_missing(self) -> None: + content = BEFORE_GROUPS + AFTER_GROUPS.lstrip("\n") + updated = replace_dependency_group(content, "dev", ["pytest"]) + + assert updated.startswith(content.rstrip("\n") + "\n\n") + assert updated.endswith('[dependency-groups]\ndev = [\n "pytest",\n]\n') + assert _group(updated) == ["pytest"] + + def test_creates_the_table_in_a_file_without_trailing_newline(self) -> None: + updated = replace_dependency_group('[project]\nname = "x"', "dev", ["pytest"]) + + assert updated == ( + '[project]\nname = "x"\n\n[dependency-groups]\ndev = [\n "pytest",\n]\n' + ) + + def test_creates_the_table_in_an_empty_file(self) -> None: + assert replace_dependency_group("", "dev", ["pytest"]) == ( + '[dependency-groups]\ndev = [\n "pytest",\n]\n' + ) + + def test_missing_group_with_no_entries_is_left_out(self) -> None: + content = BEFORE_GROUPS + assert replace_dependency_group(content, "dev", []) is content + + def test_existing_group_can_be_emptied(self) -> None: + updated = replace_dependency_group(DOCUMENT, "dev", []) + + assert _group(updated) == [] + assert "dev = []\n" in updated + + def test_keeps_crlf_line_endings(self) -> None: + content = DOCUMENT.replace("\n", "\r\n") + updated = replace_dependency_group(content, "dev", ["pytest", "ruff"]) + + assert updated.count("\r\n") == updated.count("\n") + assert _group(updated) == ["pytest", "ruff"] + + def test_quoted_table_header_is_found(self) -> None: + content = '["dependency-groups"]\ndev = ["pytest"]\n' + updated = replace_dependency_group(content, "dev", ["pytest", "ruff"]) + + assert updated.startswith('["dependency-groups"]\n') + assert _group(updated) == ["pytest", "ruff"] + + def test_group_name_that_needs_quoting(self) -> None: + updated = replace_dependency_group(BEFORE_GROUPS, "dev tools", ["pytest"]) + + assert '"dev tools" = [' in updated + assert _group(updated, "dev tools") == ["pytest"] + + def test_include_group_entries_are_kept_in_place(self) -> None: + content = '[dependency-groups]\ndev = [{include-group = "test"}]\n' + updated = replace_dependency_group(content, "dev", ["pytest"]) + + assert _group(updated) == [{"include-group": "test"}, "pytest"] + + @pytest.mark.parametrize( + ("entries", "expected"), + [ + ( + ["black", "ruff", "mypy"], + ["black", {"include-group": "lint"}, "ruff", "mypy"], + ), + (["black"], ["black", {"include-group": "lint"}]), + ([], [{"include-group": "lint"}]), + ], + ) + def test_strings_are_replaced_around_include_group_entries( + self, entries: List[str], expected: List[object] + ) -> None: + content = ( + "[dependency-groups]\n" + 'lint = ["ruff"]\n' + 'dev = ["pytest", {include-group = "lint"}, "httpx"]\n' + ) + + updated = replace_dependency_group(content, "dev", entries) + + assert _group(updated) == expected + assert _group(updated, "lint") == ["ruff"] + + def test_group_equal_up_to_include_entries_is_unchanged(self) -> None: + content = '[dependency-groups]\ndev = ["pytest", {include-group = "lint"}]\n' + + assert replace_dependency_group(content, "dev", ["pytest"]) is content + + def test_refuses_a_table_entry_it_cannot_render(self) -> None: + content = '[dependency-groups]\ndev = ["pytest", {include-group = 3}]\n' + + with pytest.raises(PyprojectMergeError, match="cannot be rewritten"): + replace_dependency_group(content, "dev", ["ruff"]) + + @pytest.mark.parametrize( + "content", + [ + 'dependency-groups.dev = ["pytest"]\n', + 'dependency-groups = {dev = ["pytest"]}\n', + '[dependency-groups]\n[dependency-groups.dev]\nx = ["pytest"]\n', + 'dependency-groups = "nonsense"\n', + ], + ids=["dotted-keys", "inline-table", "group-sub-table", "not-a-table"], + ) + def test_refuses_a_layout_it_cannot_edit_safely(self, content: str) -> None: + with pytest.raises(PyprojectMergeError): + replace_dependency_group(content, "dev", ["ruff"]) + + def test_refuses_invalid_toml(self) -> None: + with pytest.raises(PyprojectMergeError): + replace_dependency_group("[project\n", "dev", ["ruff"]) + + @pytest.mark.parametrize( + "template", ["fastapi-sqlmodel", "fastapi-auth-jwt", "fastapi-llm-agent"] + ) + def test_template_file_is_byte_identical_when_the_group_is_kept( + self, template: str + ) -> None: + content = (TEMPLATE_ROOT / template / "pyproject.toml-tpl").read_text( + encoding="utf-8" + ) + dev = declared_dependency_group(content, "dev") + + assert dev + assert replace_dependency_group(content, "dev", dev) is content + extended = replace_dependency_group(content, "dev", [*dev, "ruff"]) + assert declared_dependency_group(extended, "dev") == [*dev, "ruff"] + # Only the group's own lines changed. + assert extended.replace(' "ruff",\n', "", 1) == content + + +class TestDeclaredDependencyGroup: + def test_reads_the_string_entries(self) -> None: + assert declared_dependency_group(DOCUMENT, "dev") == [ + "pytest>=9.1.1", + "httpx>=0.28.1", + ] + assert declared_dependency_group(DOCUMENT, "docs") == ["mkdocs"] + + def test_skips_include_group_tables(self) -> None: + content = '[dependency-groups]\ndev = ["pytest", {include-group = "docs"}]\n' + assert declared_dependency_group(content, "dev") == ["pytest"] + + @pytest.mark.parametrize( + "content", + [ + BEFORE_GROUPS, + '[dependency-groups]\ndocs = ["mkdocs"]\n', + 'dependency-groups = "nonsense"\n', + '[dependency-groups]\ndev = "pytest"\n', + ], + ids=["no-table", "no-group", "table-not-a-table", "group-not-a-list"], + ) + def test_missing_or_malformed_group_is_empty(self, content: str) -> None: + assert declared_dependency_group(content, "dev") == [] + + def test_invalid_toml_raises(self) -> None: + with pytest.raises(PyprojectMergeError): + declared_dependency_group("[project\n", "dev") + + +EXTRAS = """\ +[project] +name = "demo" +dependencies = ["fastapi"] + +[project.optional-dependencies] +# Drivers, then the tools. +postgresql = ["asyncpg>=0.31.0"] +dev = [ + "pytest>=9.1.1", # tests + "httpx>=0.28.1", +] + +[dependency-groups] +dev = ["pytest>=9.1.1", "httpx>=0.28.1"] +""" + + +class TestReplaceDeclaredOptionalDependencies: + def test_replaces_the_extra_and_keeps_everything_else(self) -> None: + # when + updated = replace_declared_optional_dependencies( + EXTRAS, "dev", ["pytest>=9.1.1", "httpx>=0.28.1", "ruff"] + ) + + # then + data = tomllib.loads(updated) + assert data["project"]["optional-dependencies"]["dev"] == [ + "pytest>=9.1.1", + "httpx>=0.28.1", + "ruff", + ] + assert data["project"]["optional-dependencies"]["postgresql"] == [ + "asyncpg>=0.31.0" + ] + assert "# Drivers, then the tools." in updated + before, _, after = EXTRAS.partition("dev = [\n") + assert updated.startswith(before) + assert updated.endswith(after.partition("]\n")[2]) + + @pytest.mark.parametrize( + "content", + [ + BEFORE_GROUPS, + '[project]\nname = "x"\n\n[project.optional-dependencies]\n' + 'docs = ["mkdocs"]\n', + 'name = "not a project"\n', + ], + ids=["no-extras", "other-extra-only", "no-project"], + ) + def test_a_missing_extra_is_not_added(self, content: str) -> None: + assert replace_declared_optional_dependencies(content, "dev", ["ruff"]) is ( + content + ) + + def test_an_equal_extra_leaves_the_text_untouched(self) -> None: + assert ( + replace_declared_optional_dependencies( + EXTRAS, "dev", ["pytest>=9.1.1", "httpx>=0.28.1"] + ) + is EXTRAS + ) + + def test_keeps_crlf_line_endings(self) -> None: + content = EXTRAS.replace("\n", "\r\n") + + updated = replace_declared_optional_dependencies(content, "dev", ["ruff"]) + + assert updated.count("\r\n") == updated.count("\n") + assert tomllib.loads(updated)["project"]["optional-dependencies"]["dev"] == [ + "ruff" + ] + + @pytest.mark.parametrize( + "content", + [ + '[project]\nname = "x"\noptional-dependencies = {dev = ["pytest"]}\n', + '[project]\nname = "x"\noptional-dependencies.dev = ["pytest"]\n', + '[project]\nname = "x"\n\n[project.optional-dependencies.dev]\n' + 'x = "pytest"\n', + ], + ids=["inline-table", "dotted-key", "extra-sub-table"], + ) + def test_refuses_a_layout_it_cannot_edit_safely(self, content: str) -> None: + with pytest.raises(PyprojectMergeError): + replace_declared_optional_dependencies(content, "dev", ["ruff"]) + + def test_refuses_invalid_toml(self) -> None: + with pytest.raises(PyprojectMergeError): + replace_declared_optional_dependencies("[project\n", "dev", ["ruff"]) + + @pytest.mark.parametrize( + "template", + sorted( + path.parent.name + for path in TEMPLATE_ROOT.glob("*/pyproject.toml-tpl") + if "optional-dependencies" in path.read_text(encoding="utf-8") + ), + ) + def test_template_extra_follows_the_dev_list(self, template: str) -> None: + content = (TEMPLATE_ROOT / template / "pyproject.toml-tpl").read_text( + encoding="utf-8" + ) + dev = declared_dependency_group(content, "dev") + + extended = replace_declared_optional_dependencies( + content, "dev", [*dev, "ruff"] + ) + + extras = tomllib.loads(extended)["project"]["optional-dependencies"] + assert extras["dev"] == [*dev, "ruff"] + assert declared_dependency_group(extended, "dev") == dev + + +TEMPLATE_DEV_DECLARATIONS = """\ +[project] +name = "demo" +version = "0.1.0" +requires-python = ">=3.12" +dependencies = ["fastapi"] + +[project.optional-dependencies] +dev = ["pytest"] + +[dependency-groups] +dev = ["pytest", {include-group = "lint"}] +lint = ["ruff"] +""" + + +class TestManagersKeepDevDeclarationsEqual: + """Every manager, called directly, keeps the ``dev`` extra equal to the + final dev list (PDM installs the extra and ignores the group otherwise).""" + + @pytest.mark.parametrize("manager", ["pip", "uv", "pdm", "poetry"]) + def test_existing_dev_extra_follows_the_dev_list( + self, tmp_path: Path, manager: str + ) -> None: + from fastapi_fastkit.backend.main import generate_dependency_file_with_manager + + # given + pyproject = tmp_path / "pyproject.toml" + pyproject.write_text(TEMPLATE_DEV_DECLARATIONS, encoding="utf-8") + + # when + generate_dependency_file_with_manager( + str(tmp_path), ["fastapi"], manager, dev_dependencies=["pytest", "mypy"] + ) + + # then + data = tomllib.loads(pyproject.read_text(encoding="utf-8")) + assert data["project"]["optional-dependencies"]["dev"] == ["pytest", "mypy"] + assert data["dependency-groups"]["dev"] == [ + "pytest", + {"include-group": "lint"}, + "mypy", + ] + assert data["dependency-groups"]["lint"] == ["ruff"] + + @pytest.mark.parametrize("manager", ["pip", "uv", "pdm", "poetry"]) + def test_without_a_dev_list_nothing_is_rewritten( + self, tmp_path: Path, manager: str + ) -> None: + from fastapi_fastkit.backend.main import generate_dependency_file_with_manager + + pyproject = tmp_path / "pyproject.toml" + pyproject.write_text(TEMPLATE_DEV_DECLARATIONS, encoding="utf-8") + + generate_dependency_file_with_manager(str(tmp_path), ["fastapi"], manager) + + data = tomllib.loads(pyproject.read_text(encoding="utf-8")) + assert data["project"]["optional-dependencies"]["dev"] == ["pytest"] + + def test_pip_does_not_add_a_dev_group(self, tmp_path: Path) -> None: + from fastapi_fastkit.backend.main import generate_dependency_file_with_manager + + pyproject = tmp_path / "pyproject.toml" + content = TEMPLATE_DEV_DECLARATIONS.split("[dependency-groups]")[0] + pyproject.write_text(content, encoding="utf-8") + + generate_dependency_file_with_manager( + str(tmp_path), ["fastapi"], "pip", dev_dependencies=["pytest", "mypy"] + ) + + data = tomllib.loads(pyproject.read_text(encoding="utf-8")) + assert "dependency-groups" not in data + assert data["project"]["optional-dependencies"]["dev"] == ["pytest", "mypy"] + + def test_extra_that_cannot_be_edited_warns_and_keeps_the_group( + self, tmp_path: Path + ) -> None: + from fastapi_fastkit.backend.main import generate_dependency_file_with_manager + from fastapi_fastkit.utils.messages import capture_messages + + pyproject = tmp_path / "pyproject.toml" + pyproject.write_text( + TEMPLATE_DEV_DECLARATIONS.replace( + '[project.optional-dependencies]\ndev = ["pytest"]\n', "" + ).replace( + 'dependencies = ["fastapi"]\n', + 'dependencies = ["fastapi"]\noptional-dependencies = {dev = ["x"]}\n', + ), + encoding="utf-8", + ) + + with capture_messages() as messages: + generate_dependency_file_with_manager( + str(tmp_path), ["fastapi"], "uv", dev_dependencies=["pytest", "mypy"] + ) + + data = tomllib.loads(pyproject.read_text(encoding="utf-8")) + assert data["project"]["optional-dependencies"]["dev"] == ["x"] + assert data["dependency-groups"]["dev"][-1] == "mypy" + assert any("optional-dependencies" in m.text for m in messages) diff --git a/tests/test_backends/test_inspector.py b/tests/test_backends/test_inspector.py index 7ab9637b..f35c1757 100644 --- a/tests/test_backends/test_inspector.py +++ b/tests/test_backends/test_inspector.py @@ -26,6 +26,7 @@ TemplateInspector, inspect_fastapi_template, ) +from fastapi_fastkit.generation import GenerationError from fastapi_fastkit.utils.platform import venv_python PYPROJECT_TPL = """ @@ -140,7 +141,9 @@ def test_context_manager_cleans_up_on_failure(self, temp_dir: str) -> None: """A generation failure removes the half-written project directory. The project is produced by the real ``ProjectScaffolder``, so the - failure is injected at the template copy the scaffolder performs. + failure is injected at the template copy the generation pipeline + performs; the pipeline reports it as a ``GenerationError`` caused by + the original exception. """ # given self.create_valid_template_structure() @@ -148,11 +151,13 @@ def test_context_manager_cleans_up_on_failure(self, temp_dir: str) -> None: # when / then with patch( - "fastapi_fastkit.backend.main.copy_and_convert_template", + "fastapi_fastkit.generation.pipeline.copy_and_convert_template", side_effect=OSError("copy failed"), - ): - with pytest.raises(OSError): + ) as copy: + with pytest.raises(GenerationError) as excinfo: inspector.__enter__() + copy.assert_called_once() + assert isinstance(excinfo.value.__cause__, OSError) assert not os.path.exists(inspector.temp_dir) def test_generated_project_carries_fastkit_metadata(self, temp_dir: str) -> None: diff --git a/tests/test_backends/test_inspector_checks.py b/tests/test_backends/test_inspector_checks.py index 5898170a..fe5b9298 100644 --- a/tests/test_backends/test_inspector_checks.py +++ b/tests/test_backends/test_inspector_checks.py @@ -403,6 +403,24 @@ def test_silent_when_up_to_date(self, tmp_path: Path) -> None: # then assert ctx.warnings == [] + def test_dev_requirements_pins_are_checked(self, tmp_path: Path) -> None: + # given: a template whose dev pins live in requirements-dev.txt-tpl + ctx = make_context(tmp_path, requirements="fastapi==0.115.8\n", pyproject=None) + (ctx.template_path / "requirements-dev.txt-tpl").write_text( + "-r requirements.txt\n# tools\npytest==8.0.0\n" + ) + + # when + with patch.object( + freshness, "fetch_latest_version", return_value="9.1.0" + ) as mock_fetch: + freshness.check_dependency_freshness(ctx) + + # then + looked_up = sorted(call.args[0] for call in mock_fetch.call_args_list) + assert looked_up == ["fastapi", "pytest"] + assert any(warning.startswith("pytest is 1 major") for warning in ctx.warnings) + def test_network_failure_is_skipped(self, tmp_path: Path) -> None: # given ctx = make_context(tmp_path, requirements="fastapi==0.115.8\n", pyproject=None) diff --git a/tests/test_backends/test_interactive_prompts.py b/tests/test_backends/test_interactive_prompts.py index 118c6f24..06b411fd 100644 --- a/tests/test_backends/test_interactive_prompts.py +++ b/tests/test_backends/test_interactive_prompts.py @@ -557,3 +557,119 @@ def test_collects_every_axis( assert features["tooling"] == ["ruff"] # The migrations prompt needs the database choice to pick its default. mock_migrations.assert_called_once_with(settings, "PostgreSQL") + + +class TestCatalogDrivenPrompts: + """Option lists, texts and defaults come from the catalog.""" + + @patch("fastapi_fastkit.backend.interactive.prompts.click.prompt") + @patch("fastapi_fastkit.backend.interactive.prompts.render_selection_table") + def test_prompts_without_summaries_show_packages( + self, mock_render, mock_prompt + ) -> None: + """Axes with no catalog summary keep the ``Packages: ...`` text.""" + # given + mock_prompt.return_value = 1 + settings = FastkitConfig() + + # when + tasks = prompts.prompt_async_tasks_selection(settings) + caching = prompts.prompt_caching_selection(settings) + + # then + assert (tasks, caching) == ("Celery", "Redis") + task_options = mock_render.call_args_list[0].args[1] + cache_options = mock_render.call_args_list[1].args[1] + assert task_options == { + "Celery": "Packages: celery[redis], redis[hiredis]", + "Dramatiq": "Packages: dramatiq[redis], redis[hiredis]", + "None": "Packages: None", + } + assert cache_options["None"] == "Packages: None" + # "None" is the default of both prompts. + assert [c.kwargs["default"] for c in mock_prompt.call_args_list] == [3, 2] + + @patch("fastapi_fastkit.backend.interactive.prompts.click.prompt") + @patch("fastapi_fastkit.backend.interactive.prompts.render_selection_table") + def test_monitoring_uses_catalog_summaries(self, mock_render, mock_prompt) -> None: + """Monitoring options are described by their catalog summaries.""" + # given + mock_prompt.return_value = 3 + + # when + result = prompts.prompt_monitoring_selection(FastkitConfig()) + + # then + assert result == "Prometheus" + assert mock_render.call_args.args[1] == { + "Loguru": "Enhanced logging with Loguru", + "OpenTelemetry": "Distributed tracing and metrics", + "Prometheus": "Prometheus metrics instrumentation", + "None": "No additional monitoring", + } + assert mock_prompt.call_args.kwargs["default"] == 4 + + @patch("fastapi_fastkit.backend.interactive.prompts.click.prompt") + @patch("fastapi_fastkit.backend.interactive.prompts.render_selection_table") + def test_testing_default_is_the_second_option( + self, mock_render, mock_prompt + ) -> None: + """Enter on the testing prompt keeps selecting the second entry.""" + # given + mock_prompt.return_value = 2 + + # when + result = prompts.prompt_testing_selection(FastkitConfig()) + + # then + assert mock_prompt.call_args.kwargs["default"] == 2 + assert result == "Coverage" + + @patch("fastapi_fastkit.backend.interactive.prompts.click.prompt") + @patch("fastapi_fastkit.backend.interactive.prompts.render_selection_table") + def test_migrations_with_an_unknown_database( + self, mock_render, mock_prompt + ) -> None: + """An unknown database is not relational: Alembic is not recommended.""" + # given + mock_prompt.return_value = 2 + + # when + result = prompts.prompt_migrations_selection(FastkitConfig(), "Oracle") + + # then + assert result == "None" + assert mock_prompt.call_args.kwargs["default"] == 2 + assert ( + "(needs a relational database)" in mock_render.call_args.args[1]["Alembic"] + ) + + @patch("fastapi_fastkit.backend.interactive.prompts.console") + def test_utilities_invalid_input_is_skipped(self, mock_console) -> None: + """Non-numeric input skips the utilities step.""" + # given + mock_console.input.return_value = "one, two" + + # when + result = prompts.prompt_utilities_selection(FastkitConfig()) + + # then + assert result == [] + + @patch("fastapi_fastkit.backend.interactive.prompts.console") + @patch("fastapi_fastkit.backend.interactive.prompts.click.prompt") + def test_deployment_options_come_from_the_catalog( + self, mock_prompt, mock_console + ) -> None: + """Deployment targets and their texts are the catalog's.""" + # given + mock_prompt.return_value = 3 + + # when + prompts.prompt_deployment_options() + + # then + printed = [str(c.args[0]) for c in mock_console.print.call_args_list] + assert " [cyan]1[/cyan]. Docker - Generate Dockerfile" in printed + assert " [cyan]3[/cyan]. None - No deployment configuration" in printed + assert mock_prompt.call_args.kwargs["default"] == 3 diff --git a/tests/test_backends/test_local_env.py b/tests/test_backends/test_local_env.py index af0008d1..4602b67c 100644 --- a/tests/test_backends/test_local_env.py +++ b/tests/test_backends/test_local_env.py @@ -367,7 +367,7 @@ def test_failure_after_env_creation_rolls_back_the_project( # when with patch( - "fastapi_fastkit.backend.scaffolder.write_fastkit_metadata", + "fastapi_fastkit.generation.pipeline.write_fastkit_metadata", side_effect=BackendExceptions("boom"), ): with pytest.raises(BackendExceptions): diff --git a/tests/test_backends/test_main.py b/tests/test_backends/test_main.py index 06e3b20f..7e2fb58e 100644 --- a/tests/test_backends/test_main.py +++ b/tests/test_backends/test_main.py @@ -451,8 +451,8 @@ def test_read_template_stack_pyproject_only(self) -> None: shutil.rmtree(str(template_path)) - def test_read_template_stack_precedence_requirements_over_pyproject(self) -> None: - """requirements.txt-tpl wins over pyproject.toml-tpl to preserve legacy behaviour.""" + def test_read_template_stack_precedence_pyproject_over_requirements(self) -> None: + """pyproject.toml-tpl wins over requirements.txt-tpl (runtime dependencies only).""" # given template_path = Path(tempfile.mkdtemp()) try: @@ -464,23 +464,42 @@ def test_read_template_stack_precedence_requirements_over_pyproject(self) -> Non 'name = "test"\n' 'version = "0.1.0"\n' "dependencies = [\n" - ' "fastapi>=0.999.0",\n' # distinct marker โ€” must NOT be chosen + ' "fastapi>=0.999.0",\n' "]\n" + "[dependency-groups]\n" + 'dev = ["pytest>=8"]\n' ) # when result = read_template_stack(str(template_path)) # then - assert "fastapi>=0.100.0" in result - assert "uvicorn>=0.23.0" in result - assert "fastapi>=0.999.0" not in result + assert result == ["fastapi>=0.999.0"] finally: import shutil shutil.rmtree(str(template_path)) + def test_read_template_stack_skips_comments_and_dev_tools( + self, tmp_path: Path + ) -> None: + """Without pyproject.toml-tpl, comments, options and test tools are left out.""" + # given + (tmp_path / "requirements.txt-tpl").write_text( + "# runtime\n" + "-r base.txt\n" + "fastapi>=0.100.0 # web framework\n" + "\n" + "pytest>=8\n" + ) + + # when + result = read_template_stack(str(tmp_path)) + + # then + assert result == ["fastapi>=0.100.0"] + def test_parse_pyproject_dependencies_malformed(self) -> None: """_parse_pyproject_dependencies returns [] on TOML parse errors.""" # given diff --git a/tests/test_backends/test_package_managers.py b/tests/test_backends/test_package_managers.py index a9659983..30407290 100644 --- a/tests/test_backends/test_package_managers.py +++ b/tests/test_backends/test_package_managers.py @@ -1601,3 +1601,478 @@ def test_add_dependency_keeps_lf(self, tmp_path: Path) -> None: requirements.write_bytes(b"fastapi\n") PipManager(str(tmp_path)).add_dependency("httpx") assert requirements.read_bytes() == b"fastapi\nhttpx\n" + + +TEMPLATE_PYPROJECT = """\ +[project] +name = "demo" +version = "0.1.0" +requires-python = ">=3.12" +dependencies = [ + "fastapi>=0.141.1", +] + +[dependency-groups] +dev = [ + "pytest>=9.1.1", +] + +[tool.fastapi-fastkit] +managed = true +""" + +_IS_AVAILABLE = { + "pip": "fastapi_fastkit.backend.package_managers.pip_manager.PipManager.is_available", + "uv": "fastapi_fastkit.backend.package_managers.uv_manager.UvManager.is_available", + "pdm": "fastapi_fastkit.backend.package_managers.pdm_manager.PdmManager.is_available", + "poetry": ( + "fastapi_fastkit.backend.package_managers.poetry_manager." + "PoetryManager.is_available" + ), +} + + +def _patch_availability( + monkeypatch: pytest.MonkeyPatch, installed: "set[str]" +) -> "list[str]": + """Make exactly ``installed`` available; return the probe log.""" + probed: "list[str]" = [] + for name, target in _IS_AVAILABLE.items(): + + def is_available(self: Any, _name: str = name) -> bool: + probed.append(_name) + return _name in installed + + monkeypatch.setattr(target, is_available) + return probed + + +def _forbid_probing(monkeypatch: pytest.MonkeyPatch) -> None: + def refuse(self: Any) -> bool: + raise AssertionError("is_available() must not be called") + + for target in _IS_AVAILABLE.values(): + monkeypatch.setattr(target, refuse) + + +def _pyproject(tmp_path: Path) -> "dict[str, Any]": + import tomllib + + return tomllib.loads((tmp_path / "pyproject.toml").read_text(encoding="utf-8")) + + +class TestDevDependencyRendering: + """``generate_dependency_file(..., dev_dependencies=...)`` per manager.""" + + @pytest.mark.parametrize("manager_class", [UvManager, PdmManager]) + def test_pep621_managers_write_the_dev_group_into_a_template( + self, tmp_path: Path, manager_class: Any + ) -> None: + (tmp_path / "pyproject.toml").write_text(TEMPLATE_PYPROJECT) + + manager_class(str(tmp_path)).generate_dependency_file( + ["fastapi>=0.141.1", "httpx2"], + "demo", + dev_dependencies=["pytest>=9.1.1", "ruff"], + ) + + data = _pyproject(tmp_path) + assert data["project"]["dependencies"] == ["fastapi>=0.141.1", "httpx2"] + assert data["dependency-groups"]["dev"] == ["pytest>=9.1.1", "ruff"] + assert data["tool"]["fastapi-fastkit"] == {"managed": True} + + @pytest.mark.parametrize("manager_class", [UvManager, PdmManager]) + def test_pep621_managers_create_the_dev_group_without_a_file( + self, tmp_path: Path, manager_class: Any + ) -> None: + manager_class(str(tmp_path)).generate_dependency_file( + ["fastapi"], "demo", dev_dependencies=["pytest"] + ) + + data = _pyproject(tmp_path) + assert data["project"]["dependencies"] == ["fastapi"] + assert data["dependency-groups"]["dev"] == ["pytest"] + + @pytest.mark.parametrize("manager_class", [UvManager, PdmManager]) + def test_pep621_managers_keep_the_file_when_the_group_is_unchanged( + self, tmp_path: Path, manager_class: Any + ) -> None: + (tmp_path / "pyproject.toml").write_text(TEMPLATE_PYPROJECT) + + manager_class(str(tmp_path)).generate_dependency_file( + ["fastapi>=0.141.1"], "demo", dev_dependencies=["pytest>=9.1.1"] + ) + + assert (tmp_path / "pyproject.toml").read_text() == TEMPLATE_PYPROJECT + + @pytest.mark.parametrize("manager_class", [UvManager, PdmManager]) + def test_pep621_managers_put_the_group_into_a_replaced_invalid_file( + self, tmp_path: Path, manager_class: Any + ) -> None: + (tmp_path / "pyproject.toml").write_text("[project\n") + + manager_class(str(tmp_path)).generate_dependency_file( + ["fastapi"], "demo", dev_dependencies=["pytest"] + ) + + assert (tmp_path / "pyproject.toml.bak").exists() + assert _pyproject(tmp_path)["dependency-groups"]["dev"] == ["pytest"] + + @pytest.mark.parametrize("manager_class", [UvManager, PdmManager]) + def test_pep621_managers_refuse_a_group_they_cannot_edit( + self, tmp_path: Path, manager_class: Any + ) -> None: + content = TEMPLATE_PYPROJECT.replace( + '[dependency-groups]\ndev = [\n "pytest>=9.1.1",\n]\n', + '[dependency-groups.dev]\nitems = ["pytest>=9.1.1"]\n', + ) + (tmp_path / "pyproject.toml").write_text(content) + + with pytest.raises(BackendExceptions, match="safely"): + manager_class(str(tmp_path)).generate_dependency_file( + ["fastapi"], "demo", dev_dependencies=["ruff"] + ) + assert (tmp_path / "pyproject.toml").read_text() == content + + @pytest.mark.parametrize( + "manager_class", [UvManager, PdmManager, PoetryManager, PipManager] + ) + def test_none_matches_the_call_without_the_keyword( + self, tmp_path: Path, manager_class: Any + ) -> None: + outputs = [] + for name in ("old", "new"): + project = tmp_path / name + project.mkdir() + (project / "pyproject.toml").write_text(TEMPLATE_PYPROJECT) + manager = manager_class(str(project)) + args = (["fastapi>=0.141.1", "uvicorn"], "demo", "me", "me@x.io", "d") + if name == "old": + manager.generate_dependency_file(*args) + else: + manager.generate_dependency_file(*args, dev_dependencies=None) + outputs.append( + sorted( + (path.name, path.read_bytes()) + for path in project.iterdir() + if path.is_file() + ) + ) + + assert outputs[0] == outputs[1] + assert "requirements-dev.txt" not in [name for name, _ in outputs[1]] + + def test_poetry_writes_the_list_to_both_dev_tables(self, tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_text(TEMPLATE_PYPROJECT) + + PoetryManager(str(tmp_path)).generate_dependency_file( + ["fastapi>=0.141.1"], + "demo", + dev_dependencies=["pytest>=9.1.1", "ruff", "httpx[http2]>=0.28"], + ) + + data = _pyproject(tmp_path) + assert data["tool"]["poetry"]["group"]["dev"]["dependencies"] == { + "pytest": ">=9.1.1", + "ruff": "*", + "httpx": {"version": ">=0.28", "extras": ["http2"]}, + } + # Poetry 2.2+ installs only what [dependency-groups].dev lists. + assert data["dependency-groups"]["dev"] == [ + "pytest>=9.1.1", + "ruff", + "httpx[http2]>=0.28", + ] + assert data["project"]["dependencies"] == ["fastapi>=0.141.1"] + assert data["tool"]["poetry"]["package-mode"] is False + + def test_poetry_without_a_list_keeps_the_template_group( + self, tmp_path: Path + ) -> None: + (tmp_path / "pyproject.toml").write_text(TEMPLATE_PYPROJECT) + + PoetryManager(str(tmp_path)).generate_dependency_file(["fastapi>=0.141.1"]) + + data = _pyproject(tmp_path) + assert data["tool"]["poetry"]["group"]["dev"]["dependencies"] == { + "pytest": ">=9.1.1" + } + assert data["dependency-groups"]["dev"] == ["pytest>=9.1.1"] + + def test_poetry_standalone_file_gets_both_dev_tables(self, tmp_path: Path) -> None: + PoetryManager(str(tmp_path)).generate_dependency_file( + ["fastapi"], "demo", dev_dependencies=["pytest"] + ) + + data = _pyproject(tmp_path) + assert data["tool"]["poetry"]["group"]["dev"]["dependencies"] == {"pytest": "*"} + assert data["dependency-groups"]["dev"] == ["pytest"] + assert data["build-system"]["build-backend"] == "poetry.core.masonry.api" + + def test_poetry_empty_list_empties_both_dev_tables(self, tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_text(TEMPLATE_PYPROJECT) + + PoetryManager(str(tmp_path)).generate_dependency_file( + ["fastapi"], dev_dependencies=[] + ) + + data = _pyproject(tmp_path) + assert data["tool"]["poetry"]["group"]["dev"]["dependencies"] == {} + assert data["dependency-groups"]["dev"] == [] + + def test_pip_writes_requirements_and_requirements_dev(self, tmp_path: Path) -> None: + PipManager(str(tmp_path)).generate_dependency_file( + ["fastapi", "uvicorn"], dev_dependencies=["pytest", "ruff"] + ) + + assert (tmp_path / "requirements.txt").read_bytes() == b"fastapi\nuvicorn\n" + assert (tmp_path / "requirements-dev.txt").read_bytes() == ( + b"-r requirements.txt\npytest\nruff\n" + ) + + def test_pip_empty_dev_list_still_writes_requirements_dev( + self, tmp_path: Path + ) -> None: + PipManager(str(tmp_path)).generate_dependency_file( + ["fastapi"], dev_dependencies=[] + ) + + assert (tmp_path / "requirements-dev.txt").read_bytes() == ( + b"-r requirements.txt\n" + ) + + @pytest.mark.parametrize( + "manager_class", [UvManager, PdmManager, PoetryManager, PipManager] + ) + def test_rendering_never_probes_for_the_tool( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + manager_class: Any, + ) -> None: + _forbid_probing(monkeypatch) + (tmp_path / "pyproject.toml").write_text(TEMPLATE_PYPROJECT) + + manager_class(str(tmp_path)).generate_dependency_file( + ["fastapi"], dev_dependencies=["pytest", "ruff"] + ) + + +class TestUnprobedManagerCreation: + """``create_manager(..., probe=False)`` returns the requested manager.""" + + @pytest.mark.parametrize( + "name, manager_class", + [ + ("pip", PipManager), + ("uv", UvManager), + ("pdm", PdmManager), + ("POETRY", PoetryManager), + ], + ) + @pytest.mark.parametrize("auto_detect", [False, True]) + def test_probe_false_never_calls_is_available( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + name: str, + manager_class: Any, + auto_detect: bool, + ) -> None: + _forbid_probing(monkeypatch) + + manager = PackageManagerFactory.create_manager( + name, str(tmp_path), auto_detect=auto_detect, probe=False + ) + + assert type(manager) is manager_class + assert manager.project_dir == tmp_path + + def test_probe_false_still_rejects_an_unknown_manager(self, tmp_path: Path) -> None: + with pytest.raises(BackendExceptions, match="Unsupported package manager"): + PackageManagerFactory.create_manager("conda", str(tmp_path), probe=False) + + def test_probe_defaults_to_true( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + probed = _patch_availability(monkeypatch, {"uv"}) + + with pytest.raises(BackendExceptions, match="not available"): + PackageManagerFactory.create_manager("pdm", str(tmp_path)) + assert probed == ["pdm"] + + +class TestDetectManager: + """``detect_manager`` picks the requested manager or the first installed one.""" + + def test_returns_the_preferred_manager_when_installed( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + probed = _patch_availability(monkeypatch, {"pip", "uv", "pdm", "poetry"}) + + assert PackageManagerFactory.detect_manager(str(tmp_path), "poetry") == "poetry" + assert probed == ["poetry"] + + def test_preference_is_case_insensitive( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + _patch_availability(monkeypatch, {"pdm"}) + + assert PackageManagerFactory.detect_manager(str(tmp_path), "PDM") == "pdm" + + @pytest.mark.parametrize( + "prefer, installed, expected, order", + [ + ("pdm", {"uv", "poetry", "pip"}, "uv", ["pdm", "uv"]), + ("uv", {"pdm", "poetry", "pip"}, "pdm", ["uv", "pdm"]), + ("uv", {"poetry", "pip"}, "poetry", ["uv", "pdm", "poetry"]), + ("poetry", {"pip"}, "pip", ["poetry", "uv", "pdm", "pip"]), + ("pip", {"poetry"}, "poetry", ["pip", "uv", "pdm", "poetry"]), + ], + ) + def test_falls_back_in_detection_order_without_the_preferred_one( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + prefer: str, + installed: "set[str]", + expected: str, + order: "list[str]", + ) -> None: + probed = _patch_availability(monkeypatch, installed) + + assert PackageManagerFactory.detect_manager(str(tmp_path), prefer) == expected + assert probed == order + + def test_no_manager_at_all_raises( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + probed = _patch_availability(monkeypatch, set()) + + with pytest.raises( + BackendExceptions, match="^No package manager is available on the system$" + ): + PackageManagerFactory.detect_manager(str(tmp_path), "uv") + assert probed == ["uv", "pdm", "poetry", "pip"] + + def test_unknown_preference_raises( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + _forbid_probing(monkeypatch) + + with pytest.raises(BackendExceptions, match="Unsupported package manager"): + PackageManagerFactory.detect_manager(str(tmp_path), "conda") + + def test_skips_detection_entries_that_are_not_registered( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + _patch_availability(monkeypatch, {"pip"}) + monkeypatch.setattr( + PackageManagerFactory, + "DETECTION_ORDER", + ["conda", "uv", "pip"], + ) + + assert PackageManagerFactory.detect_manager(str(tmp_path), "uv") == "pip" + + +class TestPipInstallsRequirementsDev: + """pip installs requirements-dev.txt when the project has one.""" + + def _install(self, tmp_path: Path, mock_run: Mock) -> List[str]: + venv = tmp_path / ".venv" + venv.mkdir() + mock_run.return_value.returncode = 0 + mock_run.return_value.stdout = "" + mock_run.return_value.stderr = "" + PipManager(str(tmp_path)).install_dependencies(str(venv)) + command: List[str] = mock_run.call_args_list[-1].args[0] + return command + + @patch("subprocess.run") + def test_installs_requirements_dev_when_present( + self, mock_run: Mock, tmp_path: Path + ) -> None: + (tmp_path / "requirements.txt").write_text("fastapi\n") + (tmp_path / "requirements-dev.txt").write_text("-r requirements.txt\npytest\n") + + command = self._install(tmp_path, mock_run) + + assert command[-2:] == ["-r", "requirements-dev.txt"] + + @patch("subprocess.run") + def test_installs_requirements_without_requirements_dev( + self, mock_run: Mock, tmp_path: Path + ) -> None: + (tmp_path / "requirements.txt").write_text("fastapi\n") + + command = self._install(tmp_path, mock_run) + + assert command[-2:] == ["-r", "requirements.txt"] + + @patch("subprocess.run") + def test_requirements_txt_is_still_required( + self, mock_run: Mock, tmp_path: Path + ) -> None: + (tmp_path / ".venv").mkdir() + (tmp_path / "requirements-dev.txt").write_text("-r requirements.txt\n") + + with pytest.raises(BackendExceptions, match="Requirements file not found"): + PipManager(str(tmp_path)).install_dependencies(str(tmp_path / ".venv")) + mock_run.assert_not_called() + + +class TestPoetryDirectReferences: + """PEP 508 direct references become Poetry source tables, not bare keys.""" + + @pytest.mark.parametrize( + ("requirement", "expected"), + [ + ( + "mypkg @ https://example.com/mypkg-1.0.tar.gz", + {"url": "https://example.com/mypkg-1.0.tar.gz"}, + ), + ( + "mypkg[cli] @ https://example.com/mypkg-1.0.tar.gz ; " + 'sys_platform == "win32"', + { + "url": "https://example.com/mypkg-1.0.tar.gz", + "extras": ["cli"], + "markers": 'sys_platform == "win32"', + }, + ), + ( + "mypkg @ git+https://github.com/org/mypkg.git@v1.2#subdirectory=pkg", + { + "git": "https://github.com/org/mypkg.git", + "rev": "v1.2", + "subdirectory": "pkg", + }, + ), + ( + "mypkg @ git+ssh://git@github.com/org/mypkg.git", + {"git": "ssh://git@github.com/org/mypkg.git"}, + ), + ("mypkg @ file:///opt/wheels/mypkg", {"path": "/opt/wheels/mypkg"}), + ("mypkg @ file:///C:/wheels/my%20pkg", {"path": "C:/wheels/my pkg"}), + ], + ) + def test_dev_and_runtime_direct_references_render_valid_toml( + self, tmp_path: Path, requirement: str, expected: Any + ) -> None: + import tomllib + + # when + PoetryManager(str(tmp_path)).generate_dependency_file( + ["fastapi", requirement.replace("mypkg", "rtpkg", 1)], + "demo", + dev_dependencies=["pytest", requirement], + ) + + # then + data = tomllib.loads((tmp_path / "pyproject.toml").read_text("utf-8")) + poetry = data["tool"]["poetry"] + assert poetry["group"]["dev"]["dependencies"]["mypkg"] == expected + assert poetry["dependencies"]["rtpkg"] == expected + # The PEP 735 group keeps the requirement string itself. + assert data["dependency-groups"]["dev"] == ["pytest", requirement] diff --git a/tests/test_backends/test_project_builder_config_generator.py b/tests/test_backends/test_project_builder_config_generator.py index 1bc9ce22..ba37f0b2 100644 --- a/tests/test_backends/test_project_builder_config_generator.py +++ b/tests/test_backends/test_project_builder_config_generator.py @@ -1163,6 +1163,36 @@ def test_makefile_exposes_the_documented_targets(self) -> None: assert target in makefile, target assert "src.main:app" in makefile + def test_tooling_installs_the_dev_requirements(self) -> None: + """CI, Makefile and devcontainer need the test tools: requirements-dev.txt.""" + # given / when + artifacts = self._generate( + tooling=["github-actions", "makefile", "devcontainer"] + ) + + # then + for path in ( + ".github/workflows/test.yml", + "Makefile", + ".devcontainer/devcontainer.json", + ): + assert "install -r requirements-dev.txt" in artifacts[path], path + assert "-r requirements.txt" not in artifacts[path], path + + def test_dockerfile_installs_runtime_requirements_only(self) -> None: + """The image gets runtime packages; dev tools stay out of it.""" + # given / when + with tempfile.TemporaryDirectory() as tmp: + generator = DynamicConfigGenerator( + {"project_name": "P", "deployment": ["Docker"]}, tmp + ) + generator.generate_all_files() + dockerfile = (Path(tmp) / "Dockerfile").read_text(encoding="utf-8") + + # then + assert "-r requirements.txt" in dockerfile + assert "requirements-dev.txt" not in dockerfile + def test_devcontainer_is_valid_json(self) -> None: """A malformed devcontainer.json silently breaks the whole feature.""" # given / when diff --git a/tests/test_backends/test_project_builder_dependency_collector.py b/tests/test_backends/test_project_builder_dependency_collector.py index ca94b457..aad77529 100644 --- a/tests/test_backends/test_project_builder_dependency_collector.py +++ b/tests/test_backends/test_project_builder_dependency_collector.py @@ -22,6 +22,7 @@ ) from fastapi_fastkit.backend.project_builder.dependency_collector import ( DependencyCollector, + DependencySet, merge_requirements, ) from fastapi_fastkit.core.settings import ( @@ -855,3 +856,165 @@ def test_fastapi_users_is_pinned_to_the_generated_api(self) -> None: ) assert "fastapi-users[sqlalchemy]>=15.0.5,<16" in dependencies + + +class TestDependencySet: + """Runtime / dev split of a dependency set.""" + + def test_from_lists_sorts_merges_and_drops_dev_names_in_runtime(self) -> None: + deps = DependencySet.from_lists( + ["uvicorn", "sqlalchemy", "sqlalchemy[asyncio]", "aiosqlite"], + ["pytest", "aiosqlite", "Pytest", "ruff"], + ) + + assert deps.runtime == ("aiosqlite", "sqlalchemy[asyncio]", "uvicorn") + assert deps.dev == ("pytest", "ruff") + + def test_conditional_runtime_entry_keeps_the_dev_entry(self) -> None: + # given: httpx at runtime on Windows only, the test client everywhere + marked = 'httpx>=0.27; sys_platform == "win32"' + + deps = DependencySet.from_lists(["fastapi", marked], ["httpx", "pytest"]) + + assert deps.runtime == ("fastapi", marked) + assert deps.dev == ("httpx", "pytest") + + def test_unconditional_runtime_entry_removes_conditional_dev_entries( + self, + ) -> None: + deps = DependencySet.from_lists( + ["httpx"], ['httpx; sys_platform == "win32"', "pytest"] + ) + + assert deps.dev == ("pytest",) + + def test_classify_keeps_a_dev_tool_next_to_a_conditional_runtime_pin( + self, + ) -> None: + marked = 'pytest>=8; sys_platform == "win32"' + + deps = DependencySet.from_lists([marked], ["pytest"]) + + assert deps.dev == ("pytest",) + + def test_all_merges_both_parts(self) -> None: + deps = DependencySet(runtime=("fastapi",), dev=("pytest", "fastapi")) + + assert deps.all() == ["fastapi", "pytest"] + + def test_defaults_are_empty(self) -> None: + assert DependencySet().all() == [] + + +class TestCollect: + """``collect`` separates runtime from development dependencies.""" + + def test_testing_and_lint_tools_are_dev(self) -> None: + deps = DependencyCollector(FastkitConfig()).collect( + { + "database": {"type": "PostgreSQL"}, + "authentication": "JWT", + "testing": "Advanced", + "migrations": "Alembic", + "tooling": ["ruff", "pre-commit", "makefile"], + } + ) + + assert "pytest" in deps.dev + assert "factory-boy" in deps.dev + assert "ruff" in deps.dev + assert "pre-commit" in deps.dev + # aiosqlite only serves the in-memory test database here. + assert "aiosqlite" in deps.dev + assert "pytest" not in deps.runtime + assert "ruff" not in deps.runtime + for runtime in ("fastapi", "asyncpg", "alembic", "pyjwt[crypto]"): + assert runtime in deps.runtime + + def test_package_listed_as_runtime_elsewhere_stays_runtime(self) -> None: + deps = DependencyCollector(FastkitConfig()).collect( + {"authentication": "OAuth2", "testing": "Basic"} + ) + + assert "httpx2" in deps.runtime + assert "httpx2" not in deps.dev + assert "httpx" in deps.dev + + def test_sqlite_keeps_aiosqlite_runtime(self) -> None: + deps = DependencyCollector(FastkitConfig()).collect( + {"database": {"type": "SQLite"}, "testing": "Basic"} + ) + + assert "aiosqlite" in deps.runtime + assert "aiosqlite" not in deps.dev + + def test_custom_packages_are_sanitised_runtime_entries(self) -> None: + deps = DependencyCollector(FastkitConfig()).collect( + {"custom_packages": [" requests ", "requests", "", "not a package"]} + ) + + assert "requests" in deps.runtime + assert "not a package" not in deps.all() + + def test_unknown_choice_installs_nothing(self) -> None: + deps = DependencyCollector(FastkitConfig()).collect( + {"caching": "Memcached", "utilities": ["Unknown"]} + ) + + assert deps.runtime == ("fastapi", "pydantic", "pydantic-settings", "uvicorn") + assert deps.dev == () + + def test_all_dependencies_are_not_read(self) -> None: + deps = DependencyCollector(FastkitConfig()).collect( + {"all_dependencies": ["motor"]} + ) + + assert "motor" not in deps.all() + + def test_collect_from_config_is_the_merged_set(self) -> None: + config = { + "database": {"type": "MySQL"}, + "testing": "Coverage", + "tooling": ["ruff"], + } + collector = DependencyCollector(FastkitConfig()) + + assert collector.collect_from_config(config) == collector.collect(config).all() + assert collector.get_dependency_count() == len(collector.collect(config).all()) + + +class TestClassify: + """``classify`` routes free-form requirements by the catalog's dev names.""" + + def test_stack_list_moves_pytest_to_dev(self) -> None: + deps = DependencyCollector(FastkitConfig()).classify( + FastkitConfig.PROJECT_STACKS["standard"] + ) + + assert deps.dev == ("pytest",) + assert "sqlalchemy" in deps.runtime + assert "alembic" in deps.runtime + + def test_names_are_compared_canonically_with_specifiers(self) -> None: + deps = DependencyCollector(FastkitConfig()).classify( + ["PyTest>=8", "pytest_cov", "Ruff==0.5", "motor", " "] + ) + + assert deps.dev == ("PyTest>=8", "Ruff==0.5", "pytest_cov") + assert deps.runtime == ("motor",) + + def test_names_used_both_ways_are_runtime(self) -> None: + deps = DependencyCollector(FastkitConfig()).classify(["httpx2", "aiosqlite"]) + + assert deps.runtime == ("aiosqlite", "httpx2") + assert deps.dev == () + + def test_add_combination_dependencies_uses_the_catalog_rules(self) -> None: + collector = DependencyCollector(FastkitConfig()) + + collector.add_combination_dependencies( + {"database": {"type": "PostgreSQL"}, "testing": "Basic"} + ) + collector.add_combination_dependencies({"database": {"type": "SQLite"}}) + + assert collector.get_final_dependencies() == ["aiosqlite"] diff --git a/tests/test_backends/test_pyproject_merge.py b/tests/test_backends/test_pyproject_merge.py index 2bdf5841..45d97a44 100644 --- a/tests/test_backends/test_pyproject_merge.py +++ b/tests/test_backends/test_pyproject_merge.py @@ -9,6 +9,7 @@ # -------------------------------------------------------------------------- import re import tomllib +from contextlib import ExitStack from pathlib import Path from typing import Any, Dict, List from unittest.mock import Mock, patch @@ -477,17 +478,35 @@ def fake_run(command: List[str], **_: Any) -> Mock: assert probe[-1] == "import ensurepip, venv" -def test_requirements_txt_follows_the_manager_actually_used(tmp_path: Path) -> None: - """A pip request that auto-detection turned into uv still gets requirements.txt.""" +@pytest.mark.parametrize("manager", ["pip", "uv", "pdm", "poetry"]) +def test_dependency_file_rendering_never_probes(tmp_path: Path, manager: str) -> None: + """The requested manager renders the files whether or not it is installed.""" (tmp_path / "pyproject.toml").write_text(TEMPLATE_PYPROJECT, encoding="utf-8") (tmp_path / "requirements.txt").write_text("stale==1.0\n", encoding="utf-8") - with patch( - "fastapi_fastkit.backend.main.PackageManagerFactory.create_manager", - return_value=UvManager(str(tmp_path)), - ): - generate_dependency_file_with_manager(str(tmp_path), DEPENDENCIES, "pip") + with ExitStack() as stack: + for cls in (PipManager, UvManager, PdmManager, PoetryManager): + stack.enter_context( + patch.object(cls, "is_available", side_effect=AssertionError("probed")) + ) + generate_dependency_file_with_manager(str(tmp_path), DEPENDENCIES, manager) requirements = (tmp_path / "requirements.txt").read_text(encoding="utf-8") assert requirements.splitlines() == DEPENDENCIES - assert _load(tmp_path / "pyproject.toml")["project"]["dependencies"] == DEPENDENCIES + + +def test_dev_dependencies_go_to_requirements_dev_txt(tmp_path: Path) -> None: + """With dev dependencies a non-pip manager also writes requirements-dev.txt.""" + (tmp_path / "pyproject.toml").write_text(TEMPLATE_PYPROJECT, encoding="utf-8") + + generate_dependency_file_with_manager( + str(tmp_path), DEPENDENCIES, "uv", dev_dependencies=["pytest"] + ) + + assert (tmp_path / "requirements.txt").read_text(encoding="utf-8").splitlines() == ( + DEPENDENCIES + ) + assert (tmp_path / "requirements-dev.txt").read_text( + encoding="utf-8" + ).splitlines() == ["-r requirements.txt", "pytest"] + assert _load(tmp_path / "pyproject.toml")["dependency-groups"]["dev"] == ["pytest"] diff --git a/tests/test_backends/test_requirements_files.py b/tests/test_backends/test_requirements_files.py new file mode 100644 index 00000000..cf6d15d2 --- /dev/null +++ b/tests/test_backends/test_requirements_files.py @@ -0,0 +1,84 @@ +# -------------------------------------------------------------------------- +# requirements.txt (runtime) and requirements-dev.txt (-r requirements.txt +# plus the development tools) written by write_requirements_files. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from pathlib import Path +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.backend.package_managers.requirements import ( + REQUIREMENTS_DEV_FILE, + REQUIREMENTS_FILE, + write_requirements_files, +) +from fastapi_fastkit.core.exceptions import BackendExceptions + + +def _read_bytes(path: Path) -> bytes: + return path.read_bytes() + + +def test_writes_both_files_with_one_requirement_per_line(tmp_path: Path) -> None: + written = write_requirements_files( + tmp_path, + ["fastapi>=0.141.1", "uvicorn[standard]>=0.52.4"], + ["pytest>=9.1.1", "ruff"], + ) + + assert written == ["requirements.txt", "requirements-dev.txt"] + assert written == [REQUIREMENTS_FILE, REQUIREMENTS_DEV_FILE] + assert _read_bytes(tmp_path / "requirements.txt") == ( + b"fastapi>=0.141.1\nuvicorn[standard]>=0.52.4\n" + ) + assert _read_bytes(tmp_path / "requirements-dev.txt") == ( + b"-r requirements.txt\npytest>=9.1.1\nruff\n" + ) + + +def test_empty_dev_list_writes_only_the_include_line(tmp_path: Path) -> None: + write_requirements_files(str(tmp_path), ["fastapi"], []) + + assert _read_bytes(tmp_path / "requirements-dev.txt") == b"-r requirements.txt\n" + + +def test_empty_runtime_list_writes_an_empty_file(tmp_path: Path) -> None: + write_requirements_files(tmp_path, [], ["pytest"]) + + assert _read_bytes(tmp_path / "requirements.txt") == b"" + + +def test_existing_files_are_replaced_with_lf_endings(tmp_path: Path) -> None: + (tmp_path / "requirements.txt").write_bytes(b"old\r\nstale\r\n") + (tmp_path / "requirements-dev.txt").write_bytes(b"old-dev\r\n") + + write_requirements_files(tmp_path, ["fastapi"], ["pytest"]) + + assert _read_bytes(tmp_path / "requirements.txt") == b"fastapi\n" + assert _read_bytes(tmp_path / "requirements-dev.txt") == ( + b"-r requirements.txt\npytest\n" + ) + + +def test_non_ascii_requirement_is_written_as_utf8(tmp_path: Path) -> None: + write_requirements_files(tmp_path, ["fastapi"], ["pytest # tests โœ“"]) + + assert (tmp_path / "requirements-dev.txt").read_text(encoding="utf-8") == ( + "-r requirements.txt\npytest # tests โœ“\n" + ) + + +def test_write_failure_raises_backend_exception(tmp_path: Path) -> None: + with patch( + "fastapi_fastkit.backend.package_managers.requirements.write_generated_text", + side_effect=OSError("disk full"), + ): + with pytest.raises(BackendExceptions, match="requirements.txt: disk full"): + write_requirements_files(tmp_path, ["fastapi"], ["pytest"]) + + +def test_missing_project_directory_raises_backend_exception(tmp_path: Path) -> None: + with pytest.raises(BackendExceptions, match="Failed to generate requirements"): + write_requirements_files(tmp_path / "missing", ["fastapi"], []) diff --git a/tests/test_backends/test_route_format.py b/tests/test_backends/test_route_format.py new file mode 100644 index 00000000..35ab2c42 --- /dev/null +++ b/tests/test_backends/test_route_format.py @@ -0,0 +1,178 @@ +# -------------------------------------------------------------------------- +# Import ordering and wrapping for the code addroute writes. +# +# isort (black profile, the generated projects' settings) and black are the +# oracles: what route_format produces must be what they produce, or a form +# they keep unchanged. +# -------------------------------------------------------------------------- +import black +import isort +import pytest + +from fastapi_fastkit.backend.route_format import ( + natural_key, + sort_imports, + wrap_call, + wrap_import, + wrap_imports, +) + +ISORT = isort.Config(profile="black", line_length=88, known_first_party=["src"]) +MODE = black.Mode(line_length=88, target_versions={black.TargetVersion.PY312}) + +W = "w" * 40 + + +def test_natural_key_orders_numbers_by_value_and_ignores_case() -> None: + names = ["item10", "Item9", "item_a", "item", "items", "item9b", "item2_x"] + source = "".join( + f"from src.{name} import value_{index}\n" for index, name in enumerate(names) + ) + isort_order = [ + line.split()[1].removeprefix("src.") + for line in isort.code(source, config=ISORT).splitlines() + ] + + assert sorted(names, key=natural_key) == isort_order + assert natural_key("orders9") < natural_key("orders10") + + +@pytest.mark.parametrize( + "source", + [ + # Numbers by value, case-insensitive, ``import x`` before ``from``. + "import sys\n" + "import os\n" + "\n" + "from src.schemas.base import ResponseSchema\n" + "from src.schemas.archived_orders import (\n" + " OrderCreate,\n" + " OrderRead,\n" + ")\n" + "from src.api.routes.item10 import router as item10_router\n" + "import src.legacy\n" + "from src.api.routes.Item9 import router as item9_router\n" + "\n" + "VALUE = 1\n", + # Relative imports below a docstring. + '"""Module."""\n' + "from .routes import b\n" + "from . import a\n" + "\n" + "VALUE = 1\n", + ], +) +def test_sort_imports_matches_isort(source: str) -> None: + formatted = sort_imports(source) + + assert formatted == isort.code(source, config=ISORT) + + +def test_sort_imports_keeps_runs_apart_and_leaves_nested_imports() -> None: + source = ( + "from src.b import b\n" + "\n" + "from src.a import a\n" + "\n" + "if a:\n" + " from src.d import d\n" + " from src.c import c\n" + ) + + assert sort_imports(source) == source + + +@pytest.mark.parametrize( + "source", + [ + "import abc\nfrom __future__ import annotations\n\nVALUE = 1\n", + "from src.a import a\nfrom __future__ import annotations\nimport os\n", + '"""Doc."""\nfrom . import a\nfrom __future__ import annotations\n', + ], +) +def test_sort_imports_keeps_future_imports_first(source: str) -> None: + lines = sort_imports(source).splitlines() + + first_import = next(line for line in lines if "import" in line) + assert first_import == "from __future__ import annotations" + compile(sort_imports(source), "", "exec") + + +def test_sort_imports_leaves_a_module_that_does_not_parse() -> None: + assert sort_imports("from b import b\nfrom a import (\n") == ( + "from b import b\nfrom a import (\n" + ) + + +@pytest.mark.parametrize( + "statement", + [ + f"from src.api.routes.{W} import router as {W}_router", + f"from src.app.domains.{W}.repository import {W}Other, {W}Repository", + "from src.api.routes.orders import router as orders_router", + ], +) +def test_wrap_import_matches_isort(statement: str) -> None: + expected = isort.code(statement + "\n", config=ISORT) + + assert wrap_import(statement) + "\n" == expected + + +@pytest.mark.parametrize( + "statement", + [ + f"import src.{W}.{W}.module", + f"from src.{W} import ( # noqa: F401\n {W},\n)", + f"from src.{W}.{W} import {W} # noqa: F401", + ], +) +def test_wrap_import_leaves_other_imports_alone(statement: str) -> None: + assert wrap_import(statement) == statement + + +def test_wrap_imports_wraps_long_top_level_imports_like_isort() -> None: + source = ( + "from src.app.domains.orders.models import Order\n" + f"from src.app.domains.{W}.repository import {W}Repository\n" + "\n" + f"VALUE = '{W} {W} {W}'\n" + ) + + assert wrap_imports(source) == isort.code(source, config=ISORT) + + +@pytest.mark.parametrize( + "statement", + [ + "api_router.include_router(orders_router)", + f"api_router.include_router({W}_router)", + f"api_router.include_router({W}{W}_router.router)", + f"api_router.include_router({W}{W}{W}_router.router)", + ], +) +def test_wrap_call_is_kept_by_black(statement: str) -> None: + wrapped = wrap_call(statement) + "\n" + + assert black.format_str(wrapped, mode=MODE) == wrapped + + +def test_wrap_call_explodes_only_past_the_limit() -> None: + short = "api_router.include_router(orders_router)" + long = f"api_router.include_router({W}{W}_router.router)" + + assert wrap_call(short) == short + assert wrap_call(long) == ( + f"api_router.include_router(\n {W}{W}_router.router,\n)" + ) + + +@pytest.mark.parametrize( + "statement", + [ + f"api_router.include_router({W}{W}_router, prefix='/x')", + f"api_router.include_router(\n {W}{W}_router,\n)", + f"value = function({W}{W}_argument_that_is_long)", + ], +) +def test_wrap_call_leaves_other_statements_alone(statement: str) -> None: + assert wrap_call(statement) == statement diff --git a/tests/test_backends/test_route_generated_format.py b/tests/test_backends/test_route_generated_format.py new file mode 100644 index 00000000..e67ba951 --- /dev/null +++ b/tests/test_backends/test_route_generated_format.py @@ -0,0 +1,280 @@ +# -------------------------------------------------------------------------- +# Code written by ``fastkit addroute`` is in black / isort form. +# +# Routes are added to real projects generated from the templates of each +# route layout, and every file addroute creates or rewrites is checked with +# black and isort under the generated project's own configuration (and with +# ruff when it is installed). +# +# The templates are black-formatted for ordinary names; imports are sorted +# and wrapped for the names substituted, other lines are not reformatted. +# So the output is in black's format for names up to SUPPORTED_ROUTE_LENGTH; +# longer names are accepted and give valid, working code. +# -------------------------------------------------------------------------- +import difflib +import shutil +import subprocess +import tomllib +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Tuple + +import black +import isort +import pytest + +from fastapi_fastkit.backend.main import add_new_route, write_fastkit_metadata +from fastapi_fastkit.backend.route_generators import plan_new_route +from fastapi_fastkit.backend.route_plan import RoutePlan +from fastapi_fastkit.backend.transducer import copy_and_convert_template +from fastapi_fastkit.core.settings import settings + +LAYOUTS = { + "classic": ("fastapi-default", "src.main:app"), + "envelope": ("fastapi-custom-response", "src.main:app"), + "domain": ("fastapi-domain-starter", "src.app.main:app"), +} + +#: Longest route name and ``--entity`` class name whose generated files pass +#: black in every layout (measured; the boundary test below keeps it exact). +#: A derived entity is about as long as the route (``rrrs`` -> ``Rrr``). The +#: domain layout sets the bound with +#: ``return Read.model_validate(service.get(_id))``; the +#: classic and envelope layouts reach a route of 23 and an entity of 22 +#: characters, bounded by the list route's +#: ``items=[Read.model_validate(record) for ...]``. +SUPPORTED_ROUTE_LENGTH = 19 +SUPPORTED_ENTITY_LENGTH = 18 + +#: ``(route, --entity)`` pairs added one after another to the same project. +ROUTES: List[Tuple[str, Optional[str]]] = [ + ("orders", None), # short + ("archived_orders", None), # sorts before ``base`` (envelope schemas) + ("zebras", None), # sorts after every module of the project + ("stock_level_entries", None), # long, inside the supported range + ("people", "Member"), # --entity override + ("audit_entries", "AuditRevision"), # longer --entity +] +LONG_ROUTE = "stock_level_entries" + + +def generate(root: Path, layout: str) -> Path: + template, app_module = LAYOUTS[layout] + project = root / layout + copy_and_convert_template( + str(Path(settings.FASTKIT_TEMPLATE_ROOT) / template), str(project) + ) + write_fastkit_metadata( + str(project), {"template": template, "app_module": app_module} + ) + return project + + +def black_mode(project: Path) -> black.Mode: + """The generated project's ``[tool.black]`` settings.""" + with open(project / "pyproject.toml", "rb") as file: + config = tomllib.load(file)["tool"]["black"] + return black.Mode( + line_length=config["line-length"], + target_versions={ + black.TargetVersion[version.upper()] + for version in config.get("target-version", []) + }, + ) + + +def format_problems(project: Path, sources: Dict[str, str]) -> List[str]: + """What black and isort would change, as one diff per file and tool.""" + mode = black_mode(project) + isort_config = isort.Config(settings_path=str(project)) + problems: List[str] = [] + for name, source in sorted(sources.items()): + expected = { + "black": black.format_str(source, mode=mode), + "isort": isort.code(source, config=isort_config), + } + for tool, formatted in expected.items(): + if formatted != source: + diff = difflib.unified_diff( + source.splitlines(), + formatted.splitlines(), + f"{name} (generated)", + f"{name} ({tool})", + lineterm="", + ) + problems.append("\n".join(diff)) + return problems + + +def planned_python(plan: RoutePlan) -> Dict[str, str]: + return { + plan.display(item.path): item.content + for item in plan.created + plan.modified + if item.path.endswith(".py") + } + + +def add_routes( + project: Path, routes: Iterable[Tuple[str, Optional[str]]] +) -> List[Path]: + """Run addroute for each route; every Python file it wrote, once.""" + written: Dict[str, Path] = {} + for route, entity in routes: + plan = plan_new_route(str(project), route, entity=entity) + for item in plan.created + plan.modified: + if item.path.endswith(".py"): + written[str(item.path)] = Path(item.path) + add_new_route(str(project), route, entity=entity, plan=plan) + return list(written.values()) + + +def read_sources(project: Path, paths: Iterable[Path]) -> Dict[str, str]: + return { + path.relative_to(project).as_posix(): path.read_text(encoding="utf-8") + for path in paths + } + + +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +def test_added_routes_are_black_and_isort_clean(tmp_path: Path, layout: str) -> None: + project = generate(tmp_path, layout) + + written = add_routes(project, ROUTES) + + names = {path.name for path in written} + assert names & {"api.py", "router.py"}, "the router aggregator was not rewritten" + assert f"test_{LONG_ROUTE}.py" in names + assert format_problems(project, read_sources(project, written)) == [] + + +@pytest.mark.skipif(shutil.which("ruff") is None, reason="ruff is not installed") +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +def test_added_routes_are_ruff_clean(tmp_path: Path, layout: str) -> None: + project = generate(tmp_path, layout) + written = add_routes(project, ROUTES) + + ruff = shutil.which("ruff") + assert ruff is not None + result = subprocess.run( + [ruff, "check", "--no-cache", "--extend-select", "I", *map(str, written)], + cwd=project, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + ) + + assert result.returncode == 0, result.stdout + result.stderr + + +def route_of_length(length: int, underscores: bool) -> str: + """A route name; without underscores its entity is one character shorter.""" + if not underscores: + return "r" * (length - 1) + "s" if length > 1 else "r" + words = "_".join(["ab"] * length)[:length] + return words.rstrip("_") + "s" * (len(words) - len(words.rstrip("_"))) + + +def entity_of_length(length: int) -> str: + return "E" + "x" * (length - 1) + + +@pytest.fixture(scope="module") +def projects(tmp_path_factory: pytest.TempPathFactory) -> Dict[str, Path]: + root = tmp_path_factory.mktemp("route_format") + return {layout: generate(root, layout) for layout in LAYOUTS} + + +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +def test_names_up_to_the_supported_length_are_black_and_isort_clean( + projects: Dict[str, Path], layout: str +) -> None: + project = projects[layout] + problems: List[str] = [] + for length in [1, 2, 9, 17, SUPPORTED_ROUTE_LENGTH]: + for underscores in (False, True): + route = route_of_length(length, underscores) + assert len(route) == length + problems += format_problems( + project, planned_python(plan_new_route(str(project), route)) + ) + for length in [1, 9, 17, SUPPORTED_ENTITY_LENGTH]: + plan = plan_new_route(str(project), "things", entity=entity_of_length(length)) + problems += format_problems(project, planned_python(plan)) + + assert problems == [] + + +def test_supported_lengths_are_the_longest_that_pass( + projects: Dict[str, Path], +) -> None: + """One character more fails black in some layout: the bounds are exact.""" + route = route_of_length(SUPPORTED_ROUTE_LENGTH + 1, underscores=False) + entity = entity_of_length(SUPPORTED_ENTITY_LENGTH + 1) + route_problems: List[str] = [] + entity_problems: List[str] = [] + for project in projects.values(): + route_problems += format_problems( + project, planned_python(plan_new_route(str(project), route)) + ) + entity_problems += format_problems( + project, + planned_python(plan_new_route(str(project), "things", entity=entity)), + ) + + assert route_problems and entity_problems + + +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +def test_names_beyond_the_supported_length_give_valid_sorted_code( + projects: Dict[str, Path], layout: str +) -> None: + project = projects[layout] + isort_config = isort.Config(settings_path=str(project)) + route = route_of_length(60, underscores=True) + plans = [ + plan_new_route(str(project), route), + plan_new_route(str(project), "things", entity=entity_of_length(80)), + ] + + for plan in plans: + sources = planned_python(plan) + assert len(sources) >= 5 + for name, source in sources.items(): + compile(source, name, "exec") + assert isort.code(source, config=isort_config) == source, name + + +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +@pytest.mark.parametrize("length", [SUPPORTED_ROUTE_LENGTH + 1, 50, 70]) +def test_router_registration_of_long_names_is_black_and_isort_clean( + projects: Dict[str, Path], layout: str, length: int +) -> None: + """The aggregator import and include_router() wrap at any length.""" + project = projects[layout] + + plan = plan_new_route(str(project), route_of_length(length, underscores=True)) + + aggregator = { + name: source + for name, source in planned_python(plan).items() + if name.endswith(("api/api.py", "api/router.py")) + } + assert len(aggregator) == 1 + assert format_problems(project, aggregator) == [] + + +@pytest.mark.parametrize("layout", ["classic", "domain"]) +def test_router_imports_with_numbers_sort_by_value(tmp_path: Path, layout: str) -> None: + project = generate(tmp_path, layout) + + written = add_routes(project, [("orders10", None), ("orders9", None)]) + + aggregator = [ + path + for path in written + if path.parent.name == "api" and path.name in ("api.py", "router.py") + ] + assert len(aggregator) == 1 + sources = read_sources(project, aggregator) + assert format_problems(project, sources) == [] diff --git a/tests/test_backends/test_route_generators.py b/tests/test_backends/test_route_generators.py index ff50bcd9..375f1fb0 100644 --- a/tests/test_backends/test_route_generators.py +++ b/tests/test_backends/test_route_generators.py @@ -901,3 +901,65 @@ def test_summary_heading_matches_the_function_derived_summary() -> None: names = RouteNames("things", entity) derived = f"get_{names.snake}".replace("_", " ").title() assert f"Get {names.heading}" == derived + + +@pytest.mark.parametrize( + "template, app_module, runtime", + [ + ("fastapi-default", "src.main:app", ("fastapi", "httpx", "pydantic_settings")), + ( + "fastapi-custom-response", + "src.main:app", + ("fastapi", "httpx", "pydantic_settings", "aiofiles"), + ), + ( + "fastapi-domain-starter", + "src.app.main:app", + ("fastapi", "httpx", "pydantic_settings"), + ), + ], + ids=["classic", "envelope", "domain"], +) +def test_long_names_give_working_routes( + tmp_path: Path, template: str, app_module: str, runtime: tuple[str, ...] +) -> None: + """Names past the black-formatted range still give routes that work. + + The generated tests of a 50-character route and of a 60-character + ``--entity`` pass (test_route_generated_format.py covers the format). + """ + if any(importlib.util.find_spec(name) is None for name in runtime): + pytest.skip("Generated application runtime is not installed") + copy_and_convert_template( + str(Path(settings.FASTKIT_TEMPLATE_ROOT) / template), str(tmp_path) + ) + write_fastkit_metadata( + str(tmp_path), {"template": template, "app_module": app_module} + ) + route = "customer_order_line_item_adjustment_history_records" + assert len(route) > 50 + add_new_route(str(tmp_path), route) + add_new_route(str(tmp_path), "things", entity="Audit" + "Entry" * 11) + + result = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + f"tests/test_{route}.py", + "tests/test_things.py", + "-q", + "-p", + "no:cacheprovider", + "--override-ini", + "addopts=", + ], + cwd=tmp_path, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + ) + + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tests/test_backends/test_route_wiring.py b/tests/test_backends/test_route_wiring.py index 46384039..8dc15b3f 100644 --- a/tests/test_backends/test_route_wiring.py +++ b/tests/test_backends/test_route_wiring.py @@ -48,3 +48,344 @@ def test_alias_avoids_all_top_level_bindings(tmp_path: Path) -> None: "import package as users\nfrom package import module as users_2\nusers_3 = None\nusers_4: int = 1\ndef users_5(): pass\nclass users_6: pass\n" ) assert router_alias(str(target), "routes", "users", "users") == "users_7" + + +def _api_module(guard: str, branch: str) -> str: + return ( + "import typing\n" + "from typing import TYPE_CHECKING\n" + "\n" + "from fastapi import APIRouter\n" + "\n" + f"if {guard}:\n" + f"{branch}" + "\n" + "# fastkit:imports\n" + "\n" + "api_router = APIRouter()\n" + "# fastkit:routes\n" + ) + + +def _runtime_imports(source: str) -> list[str]: + import ast + + return [ + alias.name + for node in ast.parse(source).body + if isinstance(node, ast.ImportFrom) and node.module == "routes" + for alias in node.names + ] + + +@pytest.mark.parametrize("guard", ["TYPE_CHECKING", "typing.TYPE_CHECKING"]) +def test_type_checking_import_does_not_count_as_imported( + tmp_path: Path, guard: str +) -> None: + target = tmp_path / "api.py" + target.write_text(_api_module(guard, " from .routes import users\n")) + + register_router( + {"api_dir": str(tmp_path), "api_router_file": str(target)}, + "from .routes import users", + 'api_router.include_router(users.router, prefix="/users")', + ) + + result = target.read_text() + assert _runtime_imports(result) == ["users"] + assert "include_router(users.router" in result + + +def test_import_in_the_else_branch_of_type_checking_counts(tmp_path: Path) -> None: + target = tmp_path / "api.py" + source = _api_module( + "TYPE_CHECKING", + " from .routes import users\nelse:\n from .routes import users\n", + ) + target.write_text(source) + + register_router( + {"api_dir": str(tmp_path), "api_router_file": str(target)}, + "from .routes import users", + 'api_router.include_router(users.router, prefix="/users")', + ) + + result = target.read_text() + assert result.count("from .routes import users") == 2 + assert "include_router(users.router" in result + + +@pytest.mark.parametrize("new_import", ["import abc", "from . import routes"]) +def test_sorted_insertion_keeps_future_imports_first(new_import: str) -> None: + from fastapi_fastkit.backend.main import insert_import_line + + source = ( + "from __future__ import annotations\n" + "\n" + "import os\n" + "# fastkit:imports\n" + "\n" + "VALUE = 1\n" + ) + + result = insert_import_line(source, new_import) + + assert result.splitlines()[0] == "from __future__ import annotations" + assert new_import in result + compile(result, "", "exec") + + +@pytest.mark.parametrize( + "guard", + ["False", "0", "TYPE_CHECKING", "typing.TYPE_CHECKING"], +) +def test_registration_in_a_branch_that_never_runs_does_not_count( + tmp_path: Path, guard: str +) -> None: + target = tmp_path / "api.py" + target.write_text( + _api_module( + guard, + " from .routes import users\n" + ' api_router.include_router(users.router, prefix="/users")\n', + ) + ) + + register_router( + {"api_dir": str(tmp_path), "api_router_file": str(target)}, + "from .routes import users", + 'api_router.include_router(users.router, prefix="/users")', + ) + + result = target.read_text() + assert _runtime_imports(result) == ["users"] + assert result.count("include_router(users.router") == 2 + # The new registration is the module-level one under the routes anchor. + assert 'api_router.include_router(users.router, prefix="/users")\n' in ( + result.split("# fastkit:routes", 1)[1] + ) + + +def test_registration_in_the_else_of_if_true_does_not_count(tmp_path: Path) -> None: + target = tmp_path / "api.py" + target.write_text( + _api_module( + "True", + " pass\nelse:\n" + " from .routes import users\n" + ' api_router.include_router(users.router, prefix="/users")\n', + ) + ) + + register_router( + {"api_dir": str(tmp_path), "api_router_file": str(target)}, + "from .routes import users", + 'api_router.include_router(users.router, prefix="/users")', + ) + + result = target.read_text() + assert _runtime_imports(result) == ["users"] + assert result.count("include_router(users.router") == 2 + + +@pytest.mark.parametrize( + "branch", + [ + # The body of ``if True`` runs. + ("True", ""), + # The ``else`` of ``if TYPE_CHECKING`` runs. + ("TYPE_CHECKING", " pass\nelse:\n"), + ], +) +def test_registration_in_a_branch_that_runs_counts( + tmp_path: Path, branch: tuple[str, str] +) -> None: + guard, prefix = branch + target = tmp_path / "api.py" + source = _api_module( + guard, + prefix + " from .routes import users\n" + ' api_router.include_router(users.router, prefix="/users")\n', + ) + target.write_text(source) + + register_router( + {"api_dir": str(tmp_path), "api_router_file": str(target)}, + "from .routes import users", + 'api_router.include_router(users.router, prefix="/users")', + ) + + assert target.read_text() == source + + +def test_registration_inside_an_app_factory_counts(tmp_path: Path) -> None: + target = tmp_path / "api.py" + source = ( + "from fastapi import APIRouter\n" + "\n" + "from .routes import users\n" + "\n" + "# fastkit:imports\n" + "\n" + "\n" + "def build() -> APIRouter:\n" + " api_router = APIRouter()\n" + ' api_router.include_router(users.router, prefix="/users")\n' + " return api_router\n" + "# fastkit:routes\n" + ) + target.write_text(source) + + register_router( + {"api_dir": str(tmp_path), "api_router_file": str(target)}, + "from .routes import users", + 'api_router.include_router(users.router, prefix="/users")', + ) + + assert target.read_text() == source + + +def test_import_anchor_above_a_future_import_inserts_after_it() -> None: + from fastapi_fastkit.backend.main import insert_import_line + + source = ( + '"""API router."""\n' + "# fastkit:imports\n" + "from __future__ import annotations\n" + "from __future__ import generator_stop\n" + "\n" + "VALUE = 1\n" + ) + + result = insert_import_line(source, "from .routes import users") + + compile(result, "", "exec") + lines = result.splitlines() + assert lines.index("from .routes import users") == ( + lines.index("from __future__ import generator_stop") + 1 + ) + + +@pytest.mark.parametrize( + ("prelude", "guard", "dead"), + [ + ("", "config.TYPE_CHECKING", False), + ("import typing as t\n", "t.TYPE_CHECKING", True), + ("import typing_extensions\n", "typing_extensions.TYPE_CHECKING", True), + ("import typing_extensions as te\n", "te.TYPE_CHECKING", True), + ], +) +def test_only_typing_type_checking_counts_as_dead( + tmp_path: Path, prelude: str, guard: str, dead: bool +) -> None: + target = tmp_path / "api.py" + source = prelude + _api_module( + guard, + " from .routes import users\n" + ' api_router.include_router(users.router, prefix="/users")\n', + ) + target.write_text(source) + + register_router( + {"api_dir": str(tmp_path), "api_router_file": str(target)}, + "from .routes import users", + 'api_router.include_router(users.router, prefix="/users")', + ) + + result = target.read_text() + expected = 2 if dead else 1 + assert result.count("include_router(users.router") == expected + assert result.count("from .routes import users") == expected + + +@pytest.mark.parametrize( + "block", + [ + "try:\n pass\nexcept ImportError:\n pass\nelse:\n {stmt}\n", + "try:\n pass\nfinally:\n {stmt}\n", + "try:\n pass\nexcept ImportError:\n {stmt}\n", + "for _ in ():\n pass\nelse:\n {stmt}\n", + "while False:\n pass\nelse:\n {stmt}\n", + ], + ids=["try-else", "finally", "except", "for-else", "while-else"], +) +def test_statement_in_any_executable_block_counts(block: str) -> None: + from fastapi_fastkit.backend.main import insert_statement_line + + statement = 'api_router.include_router(users.router, prefix="/users")' + source = "api_router = None\n" + block.format(stmt=statement) + "# fastkit:routes\n" + + assert insert_statement_line(source, statement) == source + + +def test_main_app_wiring_ignores_a_dead_import_and_registration( + tmp_path: Path, +) -> None: + from fastapi_fastkit.backend.main import _update_main_app + + src = tmp_path / "src" + src.mkdir() + main = src / "main.py" + main.write_text( + "from typing import TYPE_CHECKING\n" + "\n" + "from fastapi import FastAPI\n" + "\n" + "if TYPE_CHECKING:\n" + " from src.api.api import api_router\n" + "\n" + "# fastkit:imports\n" + "\n" + "app = FastAPI()\n" + "if TYPE_CHECKING:\n" + " app.include_router(api_router)\n" + "# fastkit:routes\n", + encoding="utf-8", + ) + + _update_main_app(str(src), "orders") + + import ast + + tree = ast.parse(main.read_text(encoding="utf-8")) + top_imports = [ + alias.name + for node in tree.body + if isinstance(node, ast.ImportFrom) and node.module == "src.api.api" + for alias in node.names + ] + top_includes = [ + node + for node in tree.body + if isinstance(node, ast.Expr) + and isinstance(node.value, ast.Call) + and ast.unparse(node.value.func) == "app.include_router" + ] + assert top_imports == ["api_router"] + assert len(top_includes) == 1 + + +def test_main_app_wiring_keeps_a_live_registration(tmp_path: Path) -> None: + from fastapi_fastkit.backend.main import _update_main_app + + src = tmp_path / "src" + src.mkdir() + main = src / "main.py" + source = ( + "from fastapi import FastAPI\n" + "\n" + "from src.api.api import api_router\n" + "\n" + "# fastkit:imports\n" + "\n" + "app = FastAPI()\n" + "app.include_router(\n" + " api_router,\n" + ")\n" + "# fastkit:routes\n" + ) + main.write_text(source, encoding="utf-8") + + _update_main_app(str(src), "orders") + + assert main.read_text(encoding="utf-8") == source diff --git a/tests/test_backends/test_safety_regressions.py b/tests/test_backends/test_safety_regressions.py index 6a8da6a1..9ee7500b 100644 --- a/tests/test_backends/test_safety_regressions.py +++ b/tests/test_backends/test_safety_regressions.py @@ -29,6 +29,7 @@ cleanup_failed_project, ) from fastapi_fastkit.core.settings import FastkitConfig +from fastapi_fastkit.generation import GenerationError HOSTILE_NAME = 'my"proj' HOSTILE_AUTHOR = "A\\B" @@ -114,10 +115,10 @@ def test_failed_run_into_an_existing_directory_keeps_the_users_files(self) -> No # when with patch( - "fastapi_fastkit.backend.scaffolder.inject_project_metadata", + "fastapi_fastkit.generation.pipeline.inject_project_metadata", side_effect=RuntimeError("simulated metadata failure"), ): - with pytest.raises(RuntimeError): + with pytest.raises(GenerationError): scaffolder.run() # then diff --git a/tests/test_backends/test_scaffolder.py b/tests/test_backends/test_scaffolder.py index 9490d346..f0fe7af5 100644 --- a/tests/test_backends/test_scaffolder.py +++ b/tests/test_backends/test_scaffolder.py @@ -4,18 +4,27 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import os +from contextlib import ExitStack from pathlib import Path -from typing import Any, Dict +from typing import Any, Dict, List from unittest.mock import patch import pytest +from fastapi_fastkit.backend.package_managers import ( + PdmManager, + PipManager, + PoetryManager, + UvManager, +) from fastapi_fastkit.backend.scaffolder import ( ProjectScaffolder, ScaffoldOptions, cleanup_failed_project, ) +from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import FastkitConfig +from fastapi_fastkit.generation import GenerationError from fastapi_fastkit.utils.main import read_fastkit_metadata @@ -149,10 +158,10 @@ def test_run_rolls_back_the_project_folder_on_failure(self) -> None: # when with patch( - "fastapi_fastkit.backend.scaffolder.inject_project_metadata", + "fastapi_fastkit.generation.pipeline.inject_project_metadata", side_effect=RuntimeError("simulated metadata failure"), ): - with pytest.raises(RuntimeError, match="simulated metadata failure"): + with pytest.raises(GenerationError, match="simulated metadata failure"): scaffolder.run() # then @@ -168,10 +177,10 @@ def test_run_never_deletes_the_workspace_on_failure(self) -> None: # when with patch( - "fastapi_fastkit.backend.scaffolder.inject_project_metadata", + "fastapi_fastkit.generation.pipeline.inject_project_metadata", side_effect=RuntimeError("simulated metadata failure"), ): - with pytest.raises(RuntimeError): + with pytest.raises(GenerationError): scaffolder.run() # then @@ -261,3 +270,222 @@ def test_auth_route_conflicts_are_reported(tmp_path: Path) -> None: titles = [call.kwargs.get("title") for call in warn.call_args_list] assert "Authentication routes" in titles + + +def _fail_probe(self: Any) -> bool: + raise AssertionError("must not probe for installed tools") + + +class TestScaffolderOnTheGenerationApi: + @pytest.fixture(autouse=True) + def _workspace(self, tmp_path: Path) -> None: + self.workspace = str(tmp_path) + self.settings = _settings(self.workspace) + + def test_spec_follows_the_options(self) -> None: + # given + template = ProjectScaffolder(self.settings, _options()) + stack = ProjectScaffolder( + self.settings, + _options(template="fastapi-empty", dependencies=["fastapi", "pytest"]), + ) + features = ProjectScaffolder( + self.settings, + _options( + template="fastapi-default", + preset_id="classic-layered", + config={"testing": "Basic"}, + dependencies=["fastapi", "motor"], + ), + ) + + # then + assert template.spec().mode == "template" + assert stack.spec().mode == "stack" + assert stack.spec().extra_dependencies == ("fastapi", "pytest") + assert stack.spec("uv").package_manager == "uv" + spec = features.spec() + assert spec.mode == "features" + assert spec.project.name == "scaffold-test" + assert spec.preset == "classic-layered" + assert spec.extra_dependencies == ("motor",) + + def test_run_without_venv_never_probes(self) -> None: + # given + scaffolder = ProjectScaffolder( + self.settings, + _options( + template="fastapi-empty", + package_manager="poetry", + dependencies=["fastapi"], + ), + ) + + # when + with ExitStack() as stack: + for cls in (PipManager, UvManager, PdmManager, PoetryManager): + stack.enter_context(patch.object(cls, "is_available", _fail_probe)) + result = scaffolder.run() + + # then + assert result.metadata["package_manager"] == "poetry" + assert read_fastkit_metadata(result.project_dir)["package_manager"] == "poetry" + + def test_missing_manager_with_venv_warns_once_and_uses_the_fallback(self) -> None: + # given + scaffolder = ProjectScaffolder( + self.settings, + _options(package_manager="poetry", with_venv=True, with_install=True), + ) + + # when + with ( + patch.object(PoetryManager, "is_available", return_value=False), + patch.object(UvManager, "is_available", return_value=True), + patch.object(UvManager, "check_supported", return_value=None), + patch( + "fastapi_fastkit.backend.scaffolder.create_venv_with_manager", + return_value="venv", + ) as venv, + patch( + "fastapi_fastkit.backend.scaffolder.install_dependencies_with_manager" + ) as install, + patch("fastapi_fastkit.backend.scaffolder.print_warning") as warn, + ): + result = scaffolder.run() + + # then + fallback_warnings = [ + call + for call in warn.call_args_list + if call.kwargs.get("title") == "Package manager" + ] + assert len(fallback_warnings) == 1 + assert fallback_warnings[0].args[0] == ( + "poetry is not installed; the project is set up for uv instead." + ) + assert result.metadata["package_manager"] == "uv" + assert read_fastkit_metadata(result.project_dir)["package_manager"] == "uv" + venv.assert_called_once_with(result.project_dir, "uv") + install.assert_called_once_with(result.project_dir, "venv", "uv") + + def test_no_package_manager_at_all_fails_before_writing(self) -> None: + # given + scaffolder = ProjectScaffolder(self.settings, _options(with_venv=True)) + + # when + with ExitStack() as stack: + for cls in (PipManager, UvManager, PdmManager, PoetryManager): + stack.enter_context( + patch.object(cls, "is_available", return_value=False) + ) + with pytest.raises(BackendExceptions, match="No package manager"): + scaffolder.run() + + # then + assert os.listdir(self.workspace) == [] + + def test_messages_are_replayed_in_order(self) -> None: + # given + scaffolder = ProjectScaffolder( + self.settings, _options(template="fastapi-empty", dependencies=["fastapi"]) + ) + order: List[str] = [] + + def record(level: str) -> Any: + return lambda message, title="": order.append(f"{level}:{message}") + + # when + with ( + patch("fastapi_fastkit.backend.scaffolder.print_info", record("info")), + patch( + "fastapi_fastkit.backend.scaffolder.print_success", record("success") + ), + patch( + "fastapi_fastkit.backend.scaffolder.print_warning", record("warning") + ), + ): + scaffolder.run() + + # then + assert order.index("success:Project metadata injected successfully") < ( + order.index("success:Generated dependency file with 1 packages") + ) + assert order[-1] == "info:Skipping virtual environment creation (--no-venv)." + + def test_generation_failure_replays_messages_and_rolls_back(self) -> None: + # given + scaffolder = ProjectScaffolder(self.settings, _options()) + + # when + with ( + patch( + "fastapi_fastkit.generation.pipeline.write_fastkit_metadata", + side_effect=OSError("disk full"), + ), + patch("fastapi_fastkit.backend.scaffolder.print_success") as success, + ): + with pytest.raises(GenerationError, match="disk full"): + scaffolder.run() + + # then + replayed = [call.args[0] for call in success.call_args_list] + assert "Project metadata injected successfully" in replayed + assert not os.path.exists(os.path.join(self.workspace, "scaffold-test")) + + def test_results_carry_the_dev_dependencies(self) -> None: + # given + options = _options( + template="fastapi-empty", dependencies=["fastapi", "uvicorn", "pytest"] + ) + + # when + preview = ProjectScaffolder( + self.settings, + _options( + template="fastapi-empty", + dependencies=["fastapi", "uvicorn", "pytest"], + dry_run=True, + ), + ).run() + result = ProjectScaffolder(self.settings, options).run() + + # then + for outcome in (preview, result): + assert outcome.dev_dependencies == ["pytest"] + assert outcome.dependencies == ["fastapi", "pytest", "uvicorn"] + assert ProjectScaffolder(self.settings, options).resolve_dependencies() == [ + "fastapi", + "pytest", + "uvicorn", + ] + + def test_preview_without_dependencies_says_so(self, tmp_path: Path) -> None: + # given: a template that declares no dependencies at all + root = tmp_path / "templates" + (root / "bare").mkdir(parents=True) + (root / "bare" / "main.py-tpl").write_text("app = None\n") + self.settings.FASTKIT_TEMPLATE_ROOT = str(root) + scaffolder = ProjectScaffolder( + self.settings, _options(template="bare", dry_run=True) + ) + + # when + result = scaffolder.run() + + # then + assert result.dependencies == [] + assert result.app_module == "main:app" + + def test_no_venv_with_install_requested_warns(self) -> None: + scaffolder = ProjectScaffolder( + self.settings, _options(with_venv=False, with_install=True) + ) + + with patch("fastapi_fastkit.backend.scaffolder.print_warning") as warn: + scaffolder.run() + + assert any( + "not installed without a virtual environment" in call.args[0] + for call in warn.call_args_list + ) diff --git a/tests/test_backends/test_scaffolder_rollback.py b/tests/test_backends/test_scaffolder_rollback.py new file mode 100644 index 00000000..b01dc1c8 --- /dev/null +++ b/tests/test_backends/test_scaffolder_rollback.py @@ -0,0 +1,632 @@ +# -------------------------------------------------------------------------- +# Testcases of what a failed or refused scaffold leaves behind: symlinks in +# the target are never written through, files overwritten in an existing +# directory are restored, and only directories this run created are removed. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import shutil +import stat +import tempfile +from pathlib import Path +from typing import Any, Dict, List +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.backend.rollback import TargetSnapshot, make_directories +from fastapi_fastkit.backend.scaffolder import ProjectScaffolder, ScaffoldOptions +from fastapi_fastkit.core.exceptions import BackendExceptions +from fastapi_fastkit.core.settings import FastkitConfig +from fastapi_fastkit.generation import GenerationError + +_FAIL_LATE = "fastapi_fastkit.generation.pipeline.write_fastkit_metadata" + + +def _settings(workspace: str) -> FastkitConfig: + settings = FastkitConfig() + settings.USER_WORKSPACE = workspace + return settings + + +def _options(**overrides: Any) -> ScaffoldOptions: + base: Dict[str, Any] = { + "project_name": "demo", + "author": "bnbong", + "author_email": "bbbong9@gmail.com", + "description": "rollback testcase project", + "package_manager": "pip", + "template": "fastapi-default", + "with_venv": False, + "with_install": False, + "create_project_folder": False, + "assume_yes": True, + } + base.update(overrides) + return ScaffoldOptions(**base) + + +def _tree(root: Path) -> Dict[str, bytes]: + """Every file and directory under ``root`` (directories map to b"").""" + found: Dict[str, bytes] = {} + for path in root.rglob("*"): + key = path.relative_to(root).as_posix() + if path.is_symlink(): + found[key] = b"" + os.readlink(path).encode() + elif path.is_dir(): + found[key] = b"" + else: + found[key] = path.read_bytes() + return found + + +def _symlink(target: Path, link: Path, *, directory: bool = False) -> None: + try: + os.symlink(target, link, target_is_directory=directory) + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + + +@pytest.fixture +def backups(tmp_path: Path) -> List[str]: + """Temporary backup directories the run created (all under tmp_path).""" + made: List[str] = [] + real_mkdtemp = tempfile.mkdtemp + holder = tmp_path / "backups" + holder.mkdir() + + def recording_mkdtemp(*args: Any, **kwargs: Any) -> str: + kwargs["dir"] = str(holder) + path = real_mkdtemp(*args, **kwargs) + made.append(path) + return path + + with patch( + "fastapi_fastkit.backend.rollback.tempfile.mkdtemp", + side_effect=recording_mkdtemp, + ): + yield made + + +class TestSymlinksInTheTarget: + def test_in_place_run_refuses_a_symlinked_file_before_writing( + self, tmp_path: Path + ) -> None: + # given: README.md in the workspace links to a file outside it + workspace = tmp_path / "ws" + workspace.mkdir() + outside = tmp_path / "outside.md" + outside.write_text("not yours\n") + _symlink(outside, workspace / "README.md") + before = _tree(workspace) + + # when + with pytest.raises(BackendExceptions, match="README.md") as excinfo: + ProjectScaffolder(_settings(str(workspace)), _options()).run() + + # then + assert "symbolic link" in str(excinfo.value) + assert outside.read_text() == "not yours\n" + assert _tree(workspace) == before + + def test_in_place_run_refuses_a_directory_link_leading_outside( + self, tmp_path: Path + ) -> None: + # given: the template writes src/..., and src points outside + workspace = tmp_path / "ws" + workspace.mkdir() + outside = tmp_path / "elsewhere" + outside.mkdir() + _symlink(outside, workspace / "src", directory=True) + + # when + with pytest.raises(BackendExceptions, match="src"): + ProjectScaffolder(_settings(str(workspace)), _options()).run() + + # then + assert list(outside.iterdir()) == [] + assert [p.name for p in workspace.iterdir()] == ["src"] + + def test_a_symlinked_env_is_left_alone(self, tmp_path: Path) -> None: + # given: an existing .env is never written, so its link is harmless + workspace = tmp_path / "ws" + workspace.mkdir() + outside = tmp_path / "secrets.env" + outside.write_text("SECRET_KEY=mine\n") + _symlink(outside, workspace / ".env") + + # when + ProjectScaffolder(_settings(str(workspace)), _options()).run() + + # then + assert outside.read_text() == "SECRET_KEY=mine\n" + assert os.path.islink(workspace / ".env") + + +class TestRestoreAfterAFailedInPlaceRun: + def _workspace(self, tmp_path: Path) -> Path: + workspace = tmp_path / "ws" + (workspace / "src").mkdir(parents=True) + (workspace / "README.md").write_text("my readme\r\n") + (workspace / "src" / "main.py").write_text("print('mine')\n") + (workspace / ".env").write_text("SECRET_KEY=mine\n") + (workspace / "notes.txt").write_text("unrelated\n") + return workspace + + @pytest.mark.parametrize( + "error", [OSError("disk full"), KeyboardInterrupt()], ids=["error", "ctrl-c"] + ) + def test_overwritten_files_come_back_and_new_files_go( + self, tmp_path: Path, backups: List[str], error: BaseException + ) -> None: + # given + workspace = self._workspace(tmp_path) + before = _tree(workspace) + + # when + with patch(_FAIL_LATE, side_effect=error): + with pytest.raises((GenerationError, KeyboardInterrupt)): + ProjectScaffolder(_settings(str(workspace)), _options()).run() + + # then + assert _tree(workspace) == before + assert backups and not any(os.path.exists(path) for path in backups) + + @pytest.mark.skipif(os.name == "nt", reason="POSIX file modes") + def test_the_original_mode_is_restored( + self, tmp_path: Path, backups: List[str] + ) -> None: + # given + workspace = self._workspace(tmp_path) + readme = workspace / "README.md" + readme.chmod(0o640) + + # when + with patch(_FAIL_LATE, side_effect=OSError("disk full")): + with pytest.raises(GenerationError): + ProjectScaffolder(_settings(str(workspace)), _options()).run() + + # then + assert stat.S_IMODE(readme.stat().st_mode) == 0o640 + assert readme.read_bytes() == b"my readme\r\n" + + def test_feature_runs_are_restored_too( + self, tmp_path: Path, backups: List[str] + ) -> None: + # given: ``init`` with a preset and features + workspace = self._workspace(tmp_path) + before = _tree(workspace) + options = _options( + template="fastapi-domain-starter", + preset_id="domain-starter", + config={"database": {"type": "SQLite"}, "testing": "Basic"}, + dependencies=["fastapi", "uvicorn"], + ) + + # when + with patch(_FAIL_LATE, side_effect=OSError("disk full")): + with pytest.raises(GenerationError): + ProjectScaffolder(_settings(str(workspace)), options).run() + + # then + assert _tree(workspace) == before + + def test_a_failed_environment_setup_restores_and_removes_the_venv( + self, tmp_path: Path, backups: List[str] + ) -> None: + # given + workspace = self._workspace(tmp_path) + before = _tree(workspace) + + def install(project_dir: str, venv_path: str, manager: str) -> None: + # A lock file appears before the install fails. + Path(project_dir, "uv.lock").write_text("lock\n") + raise RuntimeError("install failed") + + def create_venv(project_dir: str, manager: str) -> str: + venv = os.path.join(project_dir, ".venv") + os.makedirs(os.path.join(venv, "bin")) + return venv + + # when + with ( + patch( + "fastapi_fastkit.backend.scaffolder.PackageManagerFactory.detect_manager", + return_value="pip", + ), + patch("fastapi_fastkit.backend.scaffolder.check_package_manager_supported"), + patch( + "fastapi_fastkit.backend.scaffolder.create_venv_with_manager", + side_effect=create_venv, + ), + patch( + "fastapi_fastkit.backend.scaffolder.install_dependencies_with_manager", + side_effect=install, + ), + ): + with pytest.raises(RuntimeError, match="install failed"): + ProjectScaffolder( + _settings(str(workspace)), + _options(with_venv=True, with_install=True), + ).run() + + # then + assert _tree(workspace) == before + + def test_success_keeps_the_new_files_and_drops_the_backup( + self, tmp_path: Path, backups: List[str] + ) -> None: + # given + workspace = self._workspace(tmp_path) + + # when + ProjectScaffolder(_settings(str(workspace)), _options()).run() + + # then + assert (workspace / "README.md").read_bytes() != b"my readme\r\n" + assert (workspace / ".env").read_text() == "SECRET_KEY=mine\n" + assert (workspace / "notes.txt").read_text() == "unrelated\n" + assert backups and not any(os.path.exists(path) for path in backups) + + def test_a_pre_existing_project_folder_is_kept_and_emptied_again( + self, tmp_path: Path + ) -> None: + # given: the template inspector creates the folder before the run + project = tmp_path / "demo" + project.mkdir() + + # when + with patch(_FAIL_LATE, side_effect=OSError("disk full")): + with pytest.raises(GenerationError): + ProjectScaffolder( + _settings(str(tmp_path)), _options(create_project_folder=True) + ).run() + + # then + assert project.is_dir() + assert list(project.iterdir()) == [] + + +class TestOnlyDirectoriesThisRunCreatedAreRemoved: + def test_a_folder_created_by_someone_else_after_the_check_is_kept( + self, tmp_path: Path + ) -> None: + # given: the folder appears between the existence check and the run + project = tmp_path / "demo" + project.mkdir() + (project / "theirs.txt").write_text("theirs\n") + real_isdir = os.path.isdir + + def isdir(path: Any) -> bool: + if os.fspath(path) == str(project): + return False + return real_isdir(path) + + # when + with ( + patch("os.path.isdir", side_effect=isdir), + patch(_FAIL_LATE, side_effect=OSError("disk full")), + ): + with pytest.raises(GenerationError): + ProjectScaffolder( + _settings(str(tmp_path)), _options(create_project_folder=True) + ).run() + + # then + assert (project / "theirs.txt").read_text() == "theirs\n" + + def test_created_folder_and_parents_are_removed(self, tmp_path: Path) -> None: + # given: neither the workspace nor the project folder exists yet + workspace = tmp_path / "missing" / "ws" + + # when + with patch(_FAIL_LATE, side_effect=OSError("disk full")): + with pytest.raises(GenerationError): + ProjectScaffolder( + _settings(str(workspace)), _options(create_project_folder=True) + ).run() + + # then + assert list(tmp_path.iterdir()) == [] + + +class TestMakeDirectories: + def test_reports_each_directory_it_created(self, tmp_path: Path) -> None: + target = tmp_path / "a" / "b" + + created = make_directories(str(target)) + + assert created == [str(tmp_path / "a"), str(target)] + assert target.is_dir() + + def test_an_existing_directory_is_not_reported(self, tmp_path: Path) -> None: + assert make_directories(str(tmp_path)) == [] + + def test_losing_the_race_counts_as_pre_existing(self, tmp_path: Path) -> None: + target = tmp_path / "late" + real_mkdir = os.mkdir + + def someone_else_first(path: Any, *args: Any) -> None: + real_mkdir(path, *args) + raise FileExistsError(path) + + with patch( + "fastapi_fastkit.backend.rollback.os.mkdir", side_effect=someone_else_first + ): + assert make_directories(str(target)) == [] + assert target.is_dir() + + +class TestTargetSnapshot: + def test_restore_is_best_effort_and_reports_what_failed( + self, tmp_path: Path, backups: List[str] + ) -> None: + # given + (tmp_path / "a.txt").write_text("a\n") + snapshot = TargetSnapshot.take(str(tmp_path), ["a.txt", "new.txt"]) + (tmp_path / "a.txt").write_text("changed\n") + (tmp_path / "new.txt").write_text("new\n") + + # when + with patch( + "fastapi_fastkit.backend.rollback.shutil.copy2", + side_effect=OSError("read-only"), + ): + failed = snapshot.restore() + + # then: the copy that could not be put back is kept + assert failed == ["a.txt"] + assert not (tmp_path / "new.txt").exists() + assert snapshot.backup_dir == backups[0] + assert Path(backups[0], "a.txt").read_text() == "a\n" + + def test_an_interrupted_restore_keeps_the_backup( + self, tmp_path: Path, backups: List[str] + ) -> None: + # given + (tmp_path / "a.txt").write_text("a\n") + (tmp_path / "b.txt").write_text("b\n") + snapshot = TargetSnapshot.take(str(tmp_path), ["a.txt", "b.txt"]) + + # when: a second Ctrl+C during the restore + with patch( + "fastapi_fastkit.backend.rollback.shutil.copy2", + side_effect=KeyboardInterrupt(), + ): + with pytest.raises(KeyboardInterrupt): + snapshot.restore() + + # then + assert Path(backups[0], "a.txt").read_text() == "a\n" + assert Path(backups[0], "b.txt").read_text() == "b\n" + + def test_a_complete_restore_drops_the_backup( + self, tmp_path: Path, backups: List[str] + ) -> None: + (tmp_path / "sub").mkdir() + (tmp_path / "sub" / "a.txt").write_text("a\n") + snapshot = TargetSnapshot.take( + str(tmp_path), ["sub/a.txt"], directories=["empty", "sub"] + ) + (tmp_path / "sub" / "a.txt").write_text("changed\n") + (tmp_path / "empty").mkdir() + + assert snapshot.restore() == [] + + assert (tmp_path / "sub" / "a.txt").read_text() == "a\n" + assert not (tmp_path / "empty").exists() + assert not any(os.path.exists(path) for path in backups) + + def test_nothing_to_back_up_needs_no_temporary_directory( + self, tmp_path: Path, backups: List[str] + ) -> None: + snapshot = TargetSnapshot.take(str(tmp_path), ["new.txt"]) + snapshot.discard() + + assert backups == [] + + +def _flat(output: str) -> str: + """Console output without the panel borders and line wrapping.""" + return "".join(output.replace("โ”‚", "").split()) + + +def test_a_file_that_cannot_be_restored_is_reported_with_its_backup( + tmp_path: Path, capsys: pytest.CaptureFixture[str], backups: List[str] +) -> None: + # given + workspace = tmp_path / "ws" + workspace.mkdir() + (workspace / "README.md").write_text("mine\n") + real_copy2 = shutil.copy2 + + def copy_back_fails(src: str, dst: str) -> str: + if src.startswith(str(tmp_path / "backups")): + raise PermissionError(dst) + return real_copy2(src, dst) + + # when + with ( + patch(_FAIL_LATE, side_effect=OSError("disk full")), + patch( + "fastapi_fastkit.backend.rollback.shutil.copy2", + side_effect=copy_back_fails, + ), + ): + with pytest.raises(GenerationError): + ProjectScaffolder(_settings(str(workspace)), _options()).run() + + # then + output = _flat(capsys.readouterr().out) + assert "Couldnotrestore1existingfile(s):README.md" in output + assert _flat(backups[0]) in output + assert Path(backups[0], "README.md").read_text() == "mine\n" + + +def test_an_interrupted_restore_prints_where_the_backup_is( + tmp_path: Path, capsys: pytest.CaptureFixture[str], backups: List[str] +) -> None: + workspace = tmp_path / "ws" + workspace.mkdir() + (workspace / "README.md").write_text("mine\n") + + with ( + patch(_FAIL_LATE, side_effect=KeyboardInterrupt()), + patch.object(TargetSnapshot, "restore", side_effect=KeyboardInterrupt()), + ): + with pytest.raises(KeyboardInterrupt): + ProjectScaffolder(_settings(str(workspace)), _options()).run() + + output = _flat(capsys.readouterr().out) + assert "Restoringtheexistingfileswasinterrupted" in output + assert _flat(backups[0]) in output + + +def test_make_directories_undoes_itself_when_it_fails(tmp_path: Path) -> None: + target = tmp_path / "a" / "b" + real_mkdir = os.mkdir + + def fail_on_the_inner_one(path: Any, *args: Any) -> None: + if os.fspath(path) == str(target): + raise PermissionError(path) + real_mkdir(path, *args) + + with patch( + "fastapi_fastkit.backend.rollback.os.mkdir", side_effect=fail_on_the_inner_one + ): + with pytest.raises(PermissionError): + make_directories(str(target)) + + assert list(tmp_path.iterdir()) == [] + + +def test_a_failed_backup_drops_the_partial_copy( + tmp_path: Path, backups: List[str] +) -> None: + (tmp_path / "a.txt").write_text("a\n") + (tmp_path / "b.txt").write_text("b\n") + real_copy2 = __import__("shutil").copy2 + calls: List[str] = [] + + def copy_once(src: str, dst: str) -> str: + calls.append(src) + if len(calls) > 1: + raise OSError("disk full") + return real_copy2(src, dst) + + with patch("fastapi_fastkit.backend.rollback.shutil.copy2", side_effect=copy_once): + with pytest.raises(OSError, match="disk full"): + TargetSnapshot.take(str(tmp_path), ["a.txt", "b.txt"]) + + assert backups and not any(os.path.exists(path) for path in backups) + + +def test_a_created_file_that_cannot_be_removed_is_skipped(tmp_path: Path) -> None: + snapshot = TargetSnapshot.take(str(tmp_path), ["new.txt"]) + (tmp_path / "new.txt").write_text("new\n") + + with patch( + "fastapi_fastkit.backend.rollback.os.remove", side_effect=OSError("busy") + ): + assert snapshot.restore() == [] + + assert (tmp_path / "new.txt").exists() + + +class TestOverwriteConfirmationListsEveryWrite: + def test_an_existing_core_module_the_template_does_not_ship_is_listed( + self, tmp_path: Path + ) -> None: + # given: generation rewrites src/core/config.py when it finds one + workspace = tmp_path / "ws" + (workspace / "src" / "core").mkdir(parents=True) + (workspace / "src" / "core" / "config.py").write_text("NAME = 'x'\n") + scaffolder = ProjectScaffolder( + _settings(str(workspace)), _options(template="fastapi-hello") + ) + + # then + assert "src/core/config.py" in scaffolder.existing_targets() + + def test_an_existing_project_folder_is_confirmed_too(self, tmp_path: Path) -> None: + # given: the project folder is already there with a README + project = tmp_path / "demo" + project.mkdir() + (project / "README.md").write_text("mine\n") + + # when: no terminal and no --yes + with patch( + "fastapi_fastkit.backend.scaffolder.stdin_is_interactive", + return_value=False, + ): + with pytest.raises(BackendExceptions, match="existing folder"): + ProjectScaffolder( + _settings(str(tmp_path)), + _options(create_project_folder=True, assume_yes=False), + ).run() + + # then + assert [p.name for p in project.iterdir()] == ["README.md"] + assert (project / "README.md").read_text() == "mine\n" + + +class TestExistingVirtualenv: + def test_a_linked_venv_is_refused_when_one_will_be_created( + self, tmp_path: Path + ) -> None: + workspace = tmp_path / "ws" + workspace.mkdir() + outside = tmp_path / "shared-venv" + outside.mkdir() + _symlink(outside, workspace / ".venv", directory=True) + + with ( + patch( + "fastapi_fastkit.backend.scaffolder.PackageManagerFactory.detect_manager", + return_value="pip", + ), + patch("fastapi_fastkit.backend.scaffolder.check_package_manager_supported"), + ): + with pytest.raises(BackendExceptions, match=r"symbolic links: \.venv"): + ProjectScaffolder( + _settings(str(workspace)), _options(with_venv=True) + ).run() + + assert [p.name for p in workspace.iterdir()] == [".venv"] + + def test_a_linked_venv_is_fine_without_an_environment(self, tmp_path: Path) -> None: + workspace = tmp_path / "ws" + workspace.mkdir() + outside = tmp_path / "shared-venv" + outside.mkdir() + _symlink(outside, workspace / ".venv", directory=True) + + ProjectScaffolder(_settings(str(workspace)), _options()).run() + + assert list(outside.iterdir()) == [] + + def test_a_failed_run_says_the_existing_venv_was_left_as_is( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + workspace = tmp_path / "ws" + (workspace / ".venv").mkdir(parents=True) + + with ( + patch( + "fastapi_fastkit.backend.scaffolder.PackageManagerFactory.detect_manager", + return_value="pip", + ), + patch("fastapi_fastkit.backend.scaffolder.check_package_manager_supported"), + patch( + "fastapi_fastkit.backend.scaffolder.create_venv_with_manager", + side_effect=RuntimeError("venv failed"), + ), + ): + with pytest.raises(RuntimeError): + ProjectScaffolder( + _settings(str(workspace)), _options(with_venv=True) + ).run() + + assert "Theexisting.venvwasnotrestored" in _flat(capsys.readouterr().out) + assert (workspace / ".venv").is_dir() diff --git a/tests/test_backends/test_scaffolder_touch_coverage.py b/tests/test_backends/test_scaffolder_touch_coverage.py new file mode 100644 index 00000000..daf700e7 --- /dev/null +++ b/tests/test_backends/test_scaffolder_touch_coverage.py @@ -0,0 +1,203 @@ +# -------------------------------------------------------------------------- +# Every file a run changes in an existing directory is one the scaffolder +# link-checks and snapshots, and a failed run restores all of it. +# +# For each template, stack and preset (with a feature-rich config) and each +# package manager, a run into an empty directory shows which paths a run +# touches. A second directory is pre-filled with a sentinel at each of +# those paths (and at the README / .env.example a project may already have); +# a successful run there may change only paths the scaffolder lists, and a +# run that fails at the very end must leave the directory exactly as it was. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import shutil +import stat +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.backend.scaffolder import ProjectScaffolder, ScaffoldOptions +from fastapi_fastkit.catalog import load_catalog +from fastapi_fastkit.core.settings import FastkitConfig, settings + +_SENTINEL = b"# fastkit sentinel\n" + +#: Files a user's directory commonly has that generation may also touch. +_USER_FILES = ("README.md", ".env.example") + +_RICH_CONFIG: Dict[str, Any] = { + "database": "PostgreSQL", + "authentication": "JWT", + "async_tasks": "Celery", + "testing": "Coverage", + "caching": "Redis", + "monitoring": "Prometheus", + "migrations": "Alembic", + "logging": "structured", + "utilities": ["Rate-Limiting", "WebSocket"], + "tooling": ["ruff", "pre-commit", "github-actions", "makefile", "devcontainer"], + "deployment": ["Docker", "docker-compose"], +} + +_MANAGERS = sorted(settings.SUPPORTED_PACKAGE_MANAGERS) + + +def _cases() -> List[Tuple[str, Dict[str, Any]]]: + catalog = load_catalog() + cases: List[Tuple[str, Dict[str, Any]]] = [] + for template in catalog.templates: + cases.append((f"template-{template.id}", {"template": template.id})) + for stack, deps in settings.PROJECT_STACKS.items(): + cases.append( + ( + f"stack-{stack}", + {"template": "fastapi-empty", "dependencies": list(deps)}, + ) + ) + for preset in catalog.presets: + cases.append( + ( + f"preset-{preset.id}", + { + "template": preset.template, + "preset_id": preset.id, + "config": dict(_RICH_CONFIG, architecture_preset=preset.id), + "dependencies": ["fastapi", "uvicorn"], + }, + ) + ) + # A custom template without README.md and with an empty directory. + cases.append( + ( + f"custom-{preset.id}", + { + "template": "custom", + "custom_base": preset.template, + "preset_id": preset.id, + "config": dict(_RICH_CONFIG, architecture_preset=preset.id), + "dependencies": ["fastapi", "uvicorn"], + }, + ) + ) + return cases + + +_CASES = _cases() + + +def _custom_root(base: str) -> str: + root = Path(os.environ["FASTKIT_TOUCH_ROOT"]) / f"templates-{base}" + if not root.exists(): + template = root / "custom" + shutil.copytree(os.path.join(settings.FASTKIT_TEMPLATE_ROOT, base), template) + for readme in template.glob("README.md*"): + readme.unlink() + (template / "static" / "empty").mkdir(parents=True) + return str(root) + + +def _scaffolder(workspace: Path, manager: str, case: Dict[str, Any]) -> Any: + case = dict(case) + config = FastkitConfig() + config.USER_WORKSPACE = str(workspace) + base = case.pop("custom_base", None) + if base is not None: + config.FASTKIT_TEMPLATE_ROOT = _custom_root(base) + options = ScaffoldOptions( + project_name="demo", + author="me", + author_email="me@example.com", + description="touch coverage", + package_manager=manager, + create_project_folder=False, + assume_yes=True, + with_venv=False, + with_install=False, + **case, + ) + return ProjectScaffolder(config, options) + + +def _tree(root: Path) -> Dict[str, Optional[Tuple[bytes, int]]]: + """Path -> (bytes, mode) for files, None for directories.""" + found: Dict[str, Optional[Tuple[bytes, int]]] = {} + for path in root.rglob("*"): + key = path.relative_to(root).as_posix() + if path.is_dir() and not path.is_symlink(): + found[key] = None + else: + found[key] = (path.read_bytes(), stat.S_IMODE(path.stat().st_mode)) + return found + + +def _prefill(root: Path, touched: Dict[str, Optional[Tuple[bytes, int]]]) -> None: + root.mkdir() + for relpath, entry in sorted(touched.items()): + path = root / relpath + if entry is None: + path.mkdir(parents=True, exist_ok=True) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(_SENTINEL) + for relpath in _USER_FILES: + if not (root / relpath).exists(): + (root / relpath).write_bytes(_SENTINEL) + + +def _fail_at_the_end(*args: Any, **kwargs: Any) -> str: + raise RuntimeError("forced failure after generation") + + +@pytest.mark.parametrize("manager", _MANAGERS) +@pytest.mark.parametrize( + "case", [case for _, case in _CASES], ids=[i for i, _ in _CASES] +) +def test_every_changed_file_is_listed_and_restored( + tmp_path: Path, manager: str, case: Dict[str, Any], monkeypatch: Any +) -> None: + monkeypatch.setenv("FASTKIT_TOUCH_ROOT", str(tmp_path)) + # given: the paths a run touches + empty = tmp_path / "empty" + empty.mkdir() + _scaffolder(empty, manager, case).run() + touched = _tree(empty) + + # when: a successful run over sentinels + filled = tmp_path / "filled" + _prefill(filled, touched) + before = _tree(filled) + scaffolder = _scaffolder(filled, manager, case) + listed = set(scaffolder._writable_paths(manager)) + scaffolder.run() + after = _tree(filled) + + # then: whatever changed was listed + changed = sorted( + relpath + for relpath in set(before) | set(after) + if before.get(relpath, "missing") != after.get(relpath, "missing") + and after.get(relpath, ()) is not None + ) + assert [relpath for relpath in changed if relpath not in listed] == [] + + # when: the same run fails at the very end + failing = tmp_path / "failing" + _prefill(failing, touched) + with patch.object(ProjectScaffolder, "_setup_environment", _fail_at_the_end): + with pytest.raises(RuntimeError, match="forced failure"): + _scaffolder(failing, manager, case).run() + + # then: everything is as it was + assert _tree(failing) == before + + # and a pre-existing empty directory is empty again + bare = tmp_path / "bare" + bare.mkdir() + with patch.object(ProjectScaffolder, "_setup_environment", _fail_at_the_end): + with pytest.raises(RuntimeError, match="forced failure"): + _scaffolder(bare, manager, case).run() + assert sorted(os.listdir(bare)) == [] diff --git a/tests/test_backends/test_transducer.py b/tests/test_backends/test_transducer.py index 2c338d7f..66727488 100644 --- a/tests/test_backends/test_transducer.py +++ b/tests/test_backends/test_transducer.py @@ -16,6 +16,7 @@ _copy_template_file, _ensure_directory_exists, _looks_like_text_file, + _normalize_line_endings, _process_directory_tree, _read_template_content, _write_target_file, @@ -23,6 +24,7 @@ copy_and_convert_template_file, ) from fastapi_fastkit.core.exceptions import TemplateExceptions +from fastapi_fastkit.utils.platform import is_windows class TestTransducer: @@ -464,7 +466,7 @@ def test_copy_template_file_permission_error(self) -> None: source_file.write_text("content") # when & then - with patch("shutil.copy2", side_effect=PermissionError("Access denied")): + with patch("shutil.copyfile", side_effect=PermissionError("Access denied")): with pytest.raises(TemplateExceptions): _copy_template_file(str(source_file), str(dest_dir), "test.py-tpl") @@ -520,7 +522,7 @@ def test_copy_template_file_raises_on_copy_failure(self) -> None: source_file.write_text("content") # when & then - with patch("shutil.copy2", side_effect=PermissionError("Access denied")): + with patch("shutil.copyfile", side_effect=PermissionError("Access denied")): with pytest.raises(TemplateExceptions): _copy_template_file( str(source_file), str(self.dest_path), "main.py-tpl" @@ -642,8 +644,10 @@ def test_crlf_text_templates_are_converted_to_lf(self) -> None: assert b"\r" not in content, f"{converted} still contains CR" assert content == payload.replace(b"\r\n", b"\n") - def test_executable_bit_survives_normalization(self) -> None: - """A CRLF shell script stays executable after being rewritten.""" + def test_template_mode_is_not_carried_over(self) -> None: + """Only content is copied: a 0755 template file lands with the umask default.""" + if is_windows(): + pytest.skip("Windows has no POSIX executable bit to check") # given script = self.source_path / "pre-start.sh-tpl" script.write_bytes(b"#!/usr/bin/env bash\r\nexit 0\r\n") @@ -655,10 +659,39 @@ def test_executable_bit_survives_normalization(self) -> None: # then converted = self.dest_path / "pre-start.sh" assert converted.read_bytes() == b"#!/usr/bin/env bash\nexit 0\n" - if os.name == "nt": + assert converted.stat().st_mode & 0o111 == 0 + + def test_normalization_keeps_an_existing_files_mode(self) -> None: + """Rewriting line endings in place keeps the destination's mode.""" + if is_windows(): pytest.skip("Windows has no POSIX executable bit to check") - assert os.access(str(converted), os.X_OK) - assert converted.stat().st_mode & 0o111 == 0o111 + # given: the destination already exists and is executable + (self.source_path / "run.sh-tpl").write_bytes(b"echo hi\r\n") + target = self.dest_path / "run.sh" + target.write_bytes(b"old\n") + target.chmod(0o755) + + # when + copy_and_convert_template(str(self.source_path), str(self.dest_path)) + + # then + assert target.read_bytes() == b"echo hi\n" + assert target.stat().st_mode & 0o777 == 0o755 + + def test_normalization_failure_is_logged_not_raised(self) -> None: + """A file that cannot be rewritten is left as copied.""" + # given: a path that cannot be opened + missing = self.dest_path / "missing.txt" + + # when + with patch( + "fastapi_fastkit.backend.transducer._looks_like_text_file", + return_value=True, + ): + _normalize_line_endings(str(missing), "missing.txt") + + # then: nothing raised + assert not (self.dest_path / "missing.txt").exists() def test_binary_files_are_copied_untouched(self) -> None: """A PNG carrying a CRLF byte pair is copied byte for byte.""" diff --git a/tests/test_catalog/__init__.py b/tests/test_catalog/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_catalog/conftest.py b/tests/test_catalog/conftest.py new file mode 100644 index 00000000..8e0964cd --- /dev/null +++ b/tests/test_catalog/conftest.py @@ -0,0 +1,190 @@ +# -------------------------------------------------------------------------- +# Shared fixtures for the catalog tests. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import pytest + +#: The smallest catalog the loader accepts; tests break one thing at a time. +MINIMAL_CATALOG = """ +schema_version = 1 + +[defaults] +level = "hello" +preset = "layered" +package_manager = "pip" +base_dependencies = ["fastapi"] + +[[concepts]] +id = "testing" +title = "Testing" +url = "https://fastapi.tiangolo.com/tutorial/testing/" + +[[levels]] +id = "hello" +label = "Hello" +description = "Hello level" +template = "fastapi-hello" +asks_database = false +concepts = ["testing"] + +[[levels]] +id = "prod" +label = "Production" +description = "Production level" +preset = "layered" +asks_database = true + +[levels.bundle] +database = "SQLite" +auth = "Users" +deployment = ["compose"] + +[[presets]] +id = "layered" +template = "fastapi-default" +summary = "Layered" + +[[templates]] +id = "fastapi-hello" +kind = "level" +description = "Hello" +concepts = ["testing"] + +[[templates]] +id = "fastapi-default" +kind = "level" +description = "Default" + +[[package_managers]] +id = "pip" +dependency_file = "requirements.txt" +executable = "pip" +description = "pip" + +[[axes]] +id = "database" +label = "Database" +description = "Database" +section = "features" +multi = false +default = "None" + + [[axes.options]] + id = "SQLite" + runtime = ["aiosqlite"] + tags = ["sql"] + + [[axes.options]] + id = "Mongo" + runtime = ["pymongo"] + + [[axes.options]] + id = "None" + none = true + +[[axes]] +id = "auth" +label = "Auth" +description = "Auth" +section = "features" +multi = false +default = "None" + + [[axes.options]] + id = "Users" + summary = "Users" + runtime = ["fastapi-users"] + + [[axes.options]] + id = "None" + none = true + summary = "No auth" + +[[axes]] +id = "testing" +label = "Testing" +description = "Testing" +section = "features" +multi = false +default = "Basic" + + [[axes.options]] + id = "Basic" + dev = ["pytest"] + concepts = ["testing"] + + [[axes.options]] + id = "None" + none = true + +[[axes]] +id = "utilities" +label = "Utilities" +description = "Utilities" +section = "features" +multi = true +default = "None" + + [[axes.options]] + id = "CORS" + built_in = true + + [[axes.options]] + id = "Limits" + runtime = ["limits"] + + [[axes.options]] + id = "None" + none = true + +[[axes]] +id = "deployment" +label = "Deployment" +description = "Deployment" +section = "deployment" +multi = true +default = "None" + + [[axes.options]] + id = "Docker" + + [[axes.options]] + id = "compose" + + [[axes.options]] + id = "None" + none = true + +[[rules]] +id = "users-need-sql" +kind = "requires" +when = { auth = "Users" } +require = { database = ["SQLite"] } +message = "Users needs {allowed}, but {selected} is selected." + +[[rules]] +id = "compose-docker" +kind = "implies" +when = { deployment = "compose" } +add = { deployment = ["Docker"] } + +[[rules]] +id = "tests-on-sqlite" +kind = "adds" +when = { testing = "*", database = ["Mongo"] } +dev = ["aiosqlite"] +runtime = ["mongomock"] + +[[rules]] +id = "note-limits" +kind = "note" +when = { utilities = "*" } +message = "Limits are per process." +""" + + +@pytest.fixture +def minimal_catalog_text() -> str: + """TOML text of :data:`MINIMAL_CATALOG`.""" + return MINIMAL_CATALOG diff --git a/tests/test_catalog/test_agreement.py b/tests/test_catalog/test_agreement.py new file mode 100644 index 00000000..03f9fdc3 --- /dev/null +++ b/tests/test_catalog/test_agreement.py @@ -0,0 +1,231 @@ +# -------------------------------------------------------------------------- +# The catalog and the code that branches on it agree. +# +# Enums, presets, templates on disk, package managers and the generator must +# match ``catalog.toml``; the settings derived from the catalog must equal +# the literals they replaced (golden values copied from fastkit 1.x). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from pathlib import Path +from typing import Any, Dict, List + +import pytest + +from fastapi_fastkit.backend.package_managers.factory import PackageManagerFactory +from fastapi_fastkit.backend.project_builder import ( + DynamicConfigGenerator, + PresetLayoutStrategist, +) +from fastapi_fastkit.backend.project_builder.config_generator import SQL_DATABASES +from fastapi_fastkit.backend.project_builder.config_schema import ( + FASTAPI_USERS_DATABASES, + combination_errors, + normalize_project_config, +) +from fastapi_fastkit.catalog import load_catalog +from fastapi_fastkit.cli import TEMPLATE_DISPLAY_ORDER, available_templates +from fastapi_fastkit.core import settings as settings_module +from fastapi_fastkit.core.settings import ( + MULTI_SELECT_AXES, + AsyncTaskChoice, + AuthChoice, + CachingChoice, + DatabaseChoice, + FastkitConfig, + FeatureAxis, + LoggingChoice, + MigrationsChoice, + MonitoringChoice, + TestingChoice, + ToolingChoice, + UtilityChoice, +) + +CATALOG = load_catalog() + +CHOICE_ENUMS: Dict[str, Any] = { + FeatureAxis.DATABASE: DatabaseChoice, + FeatureAxis.AUTHENTICATION: AuthChoice, + FeatureAxis.ASYNC_TASKS: AsyncTaskChoice, + FeatureAxis.TESTING: TestingChoice, + FeatureAxis.CACHING: CachingChoice, + FeatureAxis.MONITORING: MonitoringChoice, + FeatureAxis.UTILITIES: UtilityChoice, + FeatureAxis.MIGRATIONS: MigrationsChoice, + FeatureAxis.TOOLING: ToolingChoice, + FeatureAxis.LOGGING: LoggingChoice, +} + +# fmt: off +GOLDEN_PACKAGE_CATALOG = {'database': {'PostgreSQL': ['asyncpg', 'sqlalchemy[asyncio]'], 'MySQL': ['aiomysql', 'sqlalchemy[asyncio]'], 'MongoDB': ['pymongo>=4.13'], 'Redis': ['redis[hiredis]'], 'SQLite': ['sqlalchemy[asyncio]', 'aiosqlite'], 'None': []}, 'authentication': {'JWT': ['pyjwt[crypto]', 'pwdlib[argon2]', 'email-validator', 'python-multipart'], 'OAuth2': ['authlib', 'itsdangerous', 'httpx2'], 'FastAPI-Users': ['fastapi-users[sqlalchemy]>=15.0.5,<16'], 'Session-based': ['itsdangerous', 'pwdlib[argon2]', 'email-validator'], 'None': []}, 'async_tasks': {'Celery': ['celery[redis]', 'redis[hiredis]'], 'Dramatiq': ['dramatiq[redis]', 'redis[hiredis]'], 'None': []}, 'testing': {'Basic': ['pytest', 'pytest-asyncio', 'httpx', 'httpx2'], 'Coverage': ['pytest', 'pytest-asyncio', 'pytest-cov', 'httpx', 'httpx2'], 'Advanced': ['pytest', 'pytest-asyncio', 'pytest-cov', 'httpx', 'httpx2', 'faker', 'factory-boy'], 'None': []}, 'caching': {'Redis': ['redis[hiredis]', 'fastapi-cache2', 'jinja2'], 'None': []}, 'monitoring': {'Loguru': ['loguru'], 'OpenTelemetry': ['opentelemetry-api', 'opentelemetry-sdk', 'opentelemetry-instrumentation-fastapi', 'opentelemetry-exporter-otlp-proto-http'], 'Prometheus': ['prometheus-client', 'prometheus-fastapi-instrumentator'], 'None': []}, 'utilities': {'CORS': [], 'Rate-Limiting': ['limits>=3.4'], 'Pagination': [], 'WebSocket': ['websockets'], 'None': []}, 'migrations': {'Alembic': ['alembic'], 'None': []}, 'tooling': {'ruff': ['ruff'], 'pre-commit': ['pre-commit'], 'github-actions': [], 'devcontainer': [], 'makefile': [], 'None': []}, 'logging': {'structured': [], 'None': []}} +GOLDEN_FEATURE_DESCRIPTIONS = {'database': 'Database and ORM selection', 'authentication': 'User authentication and authorization', 'async_tasks': 'Background task processing', 'testing': 'Testing framework and tools', 'caching': 'Response and data caching', 'monitoring': 'Application monitoring and logging', 'utilities': 'Additional utilities and middleware', 'migrations': 'Database schema migrations', 'tooling': 'Developer tooling and CI configuration', 'logging': 'Application logging format'} +GOLDEN_ARCHITECTURE_PRESETS = {'minimal': 'Smallest viable FastAPI app โ€” a single app + a couple of files.', 'single-module': 'Everything in one module; ideal for tiny scripts and prototypes.', 'classic-layered': 'Layered split: api/routes, crud, schemas, core (a la fastapi-default).', 'domain-starter': 'Domain-oriented: src/app/domains// with router/service/repository (recommended).'} +GOLDEN_PACKAGE_MANAGER_CONFIG = {'pip': {'dependency_file': 'requirements.txt', 'executable': 'pip', 'description': 'Standard Python package manager'}, 'uv': {'dependency_file': 'pyproject.toml', 'executable': 'uv', 'description': 'Fast Python package manager'}, 'pdm': {'dependency_file': 'pyproject.toml', 'executable': 'pdm', 'description': 'Modern Python dependency management'}, 'poetry': {'dependency_file': 'pyproject.toml', 'executable': 'poetry', 'description': 'Python dependency management and packaging'}} +GOLDEN_SUPPORTED_PACKAGE_MANAGERS = ['pip', 'uv', 'pdm', 'poetry'] +GOLDEN_DEFAULT_PACKAGE_MANAGER = 'uv' +GOLDEN_DEFAULT_ARCHITECTURE_PRESET = 'domain-starter' +GOLDEN_MULTI_SELECT_AXES = ('utilities', 'tooling') +# fmt: on + + +def _ordered(value: Any) -> Any: + """A dict as a list of pairs (recursively), so key order is compared too.""" + if isinstance(value, dict): + return [(str(key), _ordered(item)) for key, item in value.items()] + if isinstance(value, (list, tuple)): + return [_ordered(item) for item in value] + return value + + +class TestGoldenSettings: + """Values derived from the catalog equal the literals they replaced.""" + + @pytest.mark.parametrize( + ("name", "golden"), + [ + ("PACKAGE_CATALOG", GOLDEN_PACKAGE_CATALOG), + ("FEATURE_DESCRIPTIONS", GOLDEN_FEATURE_DESCRIPTIONS), + ("ARCHITECTURE_PRESETS", GOLDEN_ARCHITECTURE_PRESETS), + ("PACKAGE_MANAGER_CONFIG", GOLDEN_PACKAGE_MANAGER_CONFIG), + ("SUPPORTED_PACKAGE_MANAGERS", GOLDEN_SUPPORTED_PACKAGE_MANAGERS), + ("DEFAULT_PACKAGE_MANAGER", GOLDEN_DEFAULT_PACKAGE_MANAGER), + ("DEFAULT_ARCHITECTURE_PRESET", GOLDEN_DEFAULT_ARCHITECTURE_PRESET), + ], + ) + def test_derived_setting_equals_the_former_literal( + self, name: str, golden: Any + ) -> None: + value = getattr(FastkitConfig, name) + + assert type(value) is type(golden) + assert _ordered(value) == _ordered(golden) + + def test_multi_select_axes(self) -> None: + assert MULTI_SELECT_AXES == GOLDEN_MULTI_SELECT_AXES + assert all(isinstance(axis, FeatureAxis) for axis in MULTI_SELECT_AXES) + + def test_settings_read_the_bundled_catalog(self) -> None: + assert settings_module._CATALOG is CATALOG + + +class TestEnumsAgree: + """Hand-written enums mirror the catalog's axes and options.""" + + def test_feature_axes_are_the_feature_axis_enum(self) -> None: + assert [axis.id for axis in CATALOG.feature_axes()] == [ + str(axis) for axis in FeatureAxis + ] + assert {axis.id for axis in CATALOG.axes} == set(FeatureAxis) | {"deployment"} + + @pytest.mark.parametrize("axis_id", [str(axis) for axis in FeatureAxis]) + def test_choice_enum_matches_axis_options(self, axis_id: str) -> None: + enum = CHOICE_ENUMS[axis_id] + + assert [str(member) for member in enum] == list( + CATALOG.axis(axis_id).choice_ids + ) + + def test_multi_select_axes_match(self) -> None: + assert list(MULTI_SELECT_AXES) == [ + axis.id for axis in CATALOG.feature_axes() if axis.multi + ] + + def test_sql_tagged_options_are_the_generator_sql_databases(self) -> None: + sql = [ + option.id + for option in CATALOG.axis("database").options + if "sql" in option.tags + ] + + assert tuple(sql) == SQL_DATABASES + assert set(FASTAPI_USERS_DATABASES) <= set(sql) + + +class TestPresetsTemplatesManagersAgree: + def test_presets_match_the_strategist(self) -> None: + assert [preset.id for preset in CATALOG.presets] == ( + PresetLayoutStrategist.supported_presets() + ) + for preset in CATALOG.presets: + strategist = PresetLayoutStrategist(preset.id) + assert strategist.preset_id == preset.id + assert strategist.base_template == preset.template + + def test_templates_match_the_directories_on_disk(self) -> None: + on_disk = available_templates(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + + assert [template.id for template in CATALOG.templates] == on_disk + assert list(TEMPLATE_DISPLAY_ORDER) == on_disk + + @pytest.mark.parametrize("template", [t.id for t in CATALOG.templates]) + def test_template_description_is_the_readme_heading(self, template: str) -> None: + readme = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT, template, "README.md-tpl") + first_line = readme.read_text(encoding="utf-8").splitlines()[0] + + assert first_line == f"# {CATALOG.template(template).description}" + + def test_package_managers_match_the_factory(self) -> None: + ids = [manager.id for manager in CATALOG.package_managers] + + assert sorted(ids) == sorted(PackageManagerFactory.get_supported_managers()) + assert ids == FastkitConfig.SUPPORTED_PACKAGE_MANAGERS + + +def _offered_selections() -> List[Dict[str, Any]]: + """One config per offered option of every feature axis.""" + configs: List[Dict[str, Any]] = [] + for axis in CATALOG.feature_axes(): + for option in axis.offered: + value: Any = [option.id] if axis.multi else option.id + config: Dict[str, Any] = {axis.id: value} + if axis.id == FeatureAxis.AUTHENTICATION: + # FastAPI-Users needs a SQL database (catalog rule). + config[FeatureAxis.DATABASE] = DatabaseChoice.SQLITE + configs.append(config) + return configs + + +class TestCodeHandlesEveryCatalogOption: + @pytest.mark.parametrize("preset", [p.id for p in CATALOG.presets]) + @pytest.mark.parametrize( + "selection", + _offered_selections(), + ids=lambda config: "-".join( + str(v if isinstance(v, str) else v[0]) for v in config.values() + ), + ) + def test_option_builds_artifacts( + self, preset: str, selection: Dict[str, Any], tmp_path: Path + ) -> None: + config = normalize_project_config( + {"project_name": "demo", "architecture_preset": preset, **selection} + ) + profile = PresetLayoutStrategist(preset).profile + generator = DynamicConfigGenerator( + config, + str(tmp_path), + app_module=PresetLayoutStrategist(preset).app_module, + main_py_relpath=profile.main_py_relpath, + db_config_relpath=profile.db_config_relpath, + auth_package_relpath=profile.auth_package_relpath, + settings_relpath=profile.settings_relpath, + provide_pagination=profile.provide_pagination, + ) + + artifacts = generator.build_artifacts(include_main=profile.regenerate_main) + + assert isinstance(artifacts, dict) + + @pytest.mark.parametrize("level", [level for level in CATALOG.levels]) + def test_level_bundles_are_valid_configs(self, level: Any) -> None: + config: Dict[str, Any] = { + key: list(value) if isinstance(value, tuple) else value + for key, value in level.bundle.items() + } + if level.preset is not None: + config["architecture_preset"] = level.preset + + normalized = normalize_project_config(config) + + assert combination_errors(normalized) == [] diff --git a/tests/test_catalog/test_export.py b/tests/test_catalog/test_export.py new file mode 100644 index 00000000..00c53c92 --- /dev/null +++ b/tests/test_catalog/test_export.py @@ -0,0 +1,108 @@ +# -------------------------------------------------------------------------- +# Test cases for catalog/export.py and ``python -m fastapi_fastkit.catalog`` +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import json +import os +import subprocess +import sys +import tomllib +from pathlib import Path + +import pytest + +from fastapi_fastkit import __version__ +from fastapi_fastkit.catalog import catalog_to_dict, dumps, load_catalog +from fastapi_fastkit.catalog.__main__ import main + +CATALOG = load_catalog() + + +class TestDumps: + def test_round_trip(self) -> None: + data = json.loads(dumps(CATALOG)) + + assert data == catalog_to_dict(CATALOG) + assert list(data) == [ + "schema_version", + "fastkit_version", + "lang", + "defaults", + "levels", + "presets", + "templates", + "package_managers", + "axes", + "rules", + "concepts", + ] + assert data["fastkit_version"] == __version__ + assert data["lang"] == "en" + + def test_output_is_stable(self) -> None: + assert dumps(CATALOG) == dumps(load_catalog()) + assert dumps(CATALOG).endswith("}\n") + + def test_every_axis_and_option_is_present(self) -> None: + data = catalog_to_dict(CATALOG) + + assert [axis["id"] for axis in data["axes"]] == [a.id for a in CATALOG.axes] + for exported, axis in zip(data["axes"], CATALOG.axes): + assert [o["id"] for o in exported["options"]] == list(axis.choice_ids) + basic = data["axes"][3]["options"][0] + assert basic["id"] == "Basic" + assert basic["dev"] == ["pytest", "pytest-asyncio", "httpx", "httpx2"] + production = next( + level for level in data["levels"] if level["id"] == "production" + ) + assert production["bundle"]["deployment"] == ["Docker", "docker-compose"] + rule = next(r for r in data["rules"] if r["id"] == "sqlite-for-tests") + assert rule["when"] == {"testing": ["*"], "database": ["PostgreSQL", "MySQL"]} + + def test_nothing_machine_specific(self) -> None: + text = dumps(CATALOG) + + assert os.getcwd() not in text + assert str(Path.home()) not in text + assert "\\\\" not in text + assert '"executable"' not in text + + +class TestMain: + def test_export_to_stdout(self, capsys: pytest.CaptureFixture[str]) -> None: + assert main(["export"]) == 0 + + assert json.loads(capsys.readouterr().out) == catalog_to_dict(CATALOG) + + def test_export_to_a_file(self, tmp_path: Path) -> None: + out = tmp_path / "catalog.ko.json" + + assert main(["export", "--lang", "ko", "--out", str(out)]) == 0 + + data = json.loads(out.read_text(encoding="utf-8")) + assert data["lang"] == "ko" + + def test_strings(self, capsys: pytest.CaptureFixture[str]) -> None: + assert main(["strings"]) == 0 + + parsed = tomllib.loads(capsys.readouterr().out) + assert parsed["axes"]["database"]["label"] == "Database" + + def test_unknown_language_is_refused(self) -> None: + with pytest.raises(SystemExit): + main(["export", "--lang", "xx"]) + + @pytest.mark.parametrize("command", [["export"], ["strings"]]) + def test_module_runs(self, command: list[str]) -> None: + result = subprocess.run( + [sys.executable, "-m", "fastapi_fastkit.catalog", *command], + capture_output=True, + check=True, + ) + + text = result.stdout.decode("utf-8") + if command == ["export"]: + assert json.loads(text)["schema_version"] == 1 + else: + assert tomllib.loads(text)["levels"]["hello"]["label"] == "Hello" diff --git a/tests/test_catalog/test_i18n.py b/tests/test_catalog/test_i18n.py new file mode 100644 index 00000000..2687e9d9 --- /dev/null +++ b/tests/test_catalog/test_i18n.py @@ -0,0 +1,195 @@ +# -------------------------------------------------------------------------- +# Test cases for catalog/i18n.py +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import tomllib +from typing import Any, Dict + +import pytest + +from fastapi_fastkit.catalog import ( + CatalogError, + apply_overlay, + available_languages, + load_catalog, + translatable_strings, +) +from fastapi_fastkit.catalog.__main__ import strings_toml + +CATALOG = load_catalog() + + +class TestApplyOverlay: + def test_overlay_replaces_text_and_falls_back(self) -> None: + overlay: Dict[str, Any] = { + "levels": {"hello": {"label": "Bonjour"}}, + "presets": {"minimal": {"summary": "Minimal FR"}}, + "templates": {"fastapi-sqlmodel": {"description": "SQLModel FR"}}, + "package_managers": {"uv": {"description": "uv FR"}}, + "axes": { + "database": { + "label": "Base de donnรฉes", + "options": {"None": {"label": "Aucune"}}, + }, + "testing": {"options": {"Basic": {"summary": "pytest FR"}}}, + }, + "rules": { + "fastapi-users-needs-sql": { + "message": "SQL requis ({allowed}) ; {selected} choisi." + } + }, + "concepts": {"testing": {"title": "Tests"}}, + } + + translated = apply_overlay(CATALOG, overlay, "fr") + + assert translated.lang == "fr" + assert translated.level("hello").label == "Bonjour" + assert ( + translated.level("hello").description == CATALOG.level("hello").description + ) + assert translated.preset("minimal").summary == "Minimal FR" + assert translated.template("fastapi-sqlmodel").description == "SQLModel FR" + assert translated.package_manager("uv").description == "uv FR" + assert translated.axis("database").label == "Base de donnรฉes" + assert translated.axis("database").option("None").label == "Aucune" + assert translated.axis("database").description == "Database and ORM selection" + assert translated.axis("testing").option("Basic").summary == "pytest FR" + assert translated.axis("testing").option("Basic").dev == ( + CATALOG.axis("testing").option("Basic").dev + ) + assert translated.concept("testing").title == "Tests" + assert translated.concept("testing").url == CATALOG.concept("testing").url + assert translated.rule("fastapi-users-needs-sql").message == ( + "SQL requis ({allowed}) ; {selected} choisi." + ) + # The base catalog is untouched. + assert CATALOG.level("hello").label == "Hello" + + @pytest.mark.parametrize( + ("overlay", "message"), + [ + ({"widgets": {}}, "unknown table 'widgets'"), + ({"levels": []}, "expected a table"), + ({"levels": {"expert": {"label": "x"}}}, "unknown id"), + ( + {"levels": {"hello": {"template": "x"}}}, + "'template' is not translatable", + ), + ({"levels": {"hello": {"label": 3}}}, "must be a non-empty string"), + ({"levels": {"hello": "x"}}, "expected a table"), + ( + {"axes": {"database": {"options": {"Oracle": {"label": "x"}}}}}, + "unknown option", + ), + ({"axes": {"database": {"options": []}}}, "expected a table"), + ( + {"axes": {"database": {"options": {"None": {"runtime": "x"}}}}}, + "not translatable", + ), + # Orphan: the base option has no summary to translate. + ( + {"axes": {"database": {"options": {"SQLite": {"summary": "x"}}}}}, + "no English text", + ), + ( + {"rules": {"fastapi-users-needs-sql": {"message": "SQL {allowed}"}}}, + "placeholders must match", + ), + ( + {"rules": {"shared-redis": {"message": "Redis {selected}"}}}, + r"placeholders must match the English message \(none\)", + ), + ( + { + "rules": { + "fastapi-users-needs-sql": { + "message": "SQL {allowed:bad}; {selected}" + } + } + }, + "cannot be formatted", + ), + ( + { + "rules": { + "fastapi-users-needs-sql": { + "message": "SQL {allowed!z}; {selected}" + } + } + }, + "cannot be formatted", + ), + ( + { + "rules": { + "fastapi-users-needs-sql": { + "message": "SQL {allowed}; {selected:d}" + } + } + }, + "cannot be formatted", + ), + ( + {"rules": {"shared-redis": {"message": "Redis {"}}}, + "not a valid format string", + ), + ], + ) + def test_invalid_overlay_is_rejected( + self, overlay: Dict[str, Any], message: str + ) -> None: + with pytest.raises(CatalogError, match=message): + apply_overlay(CATALOG, overlay, "fr") + + +class TestTranslatableStrings: + def test_covers_every_text_field(self) -> None: + strings = translatable_strings(CATALOG) + + assert set(strings) == { + "levels", + "presets", + "templates", + "package_managers", + "axes", + "rules", + "concepts", + } + assert len(strings["levels"]) == len(CATALOG.levels) + assert strings["levels"]["hello"] == { + "label": "Hello", + "description": CATALOG.level("hello").description, + } + assert set(strings["presets"]) == {preset.id for preset in CATALOG.presets} + assert set(strings["templates"]) == {t.id for t in CATALOG.templates} + assert set(strings["package_managers"]) == { + m.id for m in CATALOG.package_managers + } + assert set(strings["concepts"]) == {c.id for c in CATALOG.concepts} + assert set(strings["axes"]) == {axis.id for axis in CATALOG.axes} + # Rules without a message (implies, adds) have nothing to translate. + assert set(strings["rules"]) == {"fastapi-users-needs-sql", "shared-redis"} + for axis in CATALOG.axes: + options = strings["axes"][axis.id].get("options", {}) + for option in axis.options: + texts = options.get(option.id, {}) + assert ("summary" in texts) == (option.summary is not None) + assert ("label" in texts) == option.none + + def test_skeleton_round_trips_as_an_identity_overlay(self) -> None: + strings = translatable_strings(CATALOG) + + assert apply_overlay(CATALOG, strings, "en") == CATALOG + + def test_strings_toml_parses_back_to_the_skeleton(self) -> None: + strings = translatable_strings(CATALOG) + + parsed = tomllib.loads(strings_toml(strings)) + + assert parsed == {kind: entries for kind, entries in strings.items() if entries} + + +def test_only_english_is_available_in_stage_two() -> None: + assert available_languages() == ("en",) diff --git a/tests/test_catalog/test_loader.py b/tests/test_catalog/test_loader.py new file mode 100644 index 00000000..5c14370d --- /dev/null +++ b/tests/test_catalog/test_loader.py @@ -0,0 +1,458 @@ +# -------------------------------------------------------------------------- +# Test cases for catalog/loader.py and catalog/model.py +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from importlib.resources import files +from pathlib import Path + +import pytest + +from fastapi_fastkit.catalog import ( + LANGUAGES, + CatalogError, + canonical_name, + load_catalog, +) +from fastapi_fastkit.catalog import loader as loader_module +from fastapi_fastkit.catalog import parse_catalog, requirement_name + + +def _replace(text: str, old: str, new: str) -> str: + assert text.count(old) == 1, old + return text.replace(old, new) + + +class TestBundledCatalog: + def test_bundled_catalog_loads(self) -> None: + catalog = load_catalog() + + assert catalog.schema_version == 1 + assert catalog.lang == "en" + assert catalog.defaults.level == "hello" + assert catalog.defaults.package_manager == "uv" + assert [axis.id for axis in catalog.feature_axes()][0] == "database" + assert catalog.axes[-1].id == "deployment" + + def test_catalog_is_a_packaged_resource(self) -> None: + root = files("fastapi_fastkit.catalog") + + assert root.joinpath("catalog.toml").is_file() + assert root.joinpath("i18n").is_dir() + + def test_load_is_cached(self) -> None: + assert load_catalog() is load_catalog("en") + + def test_unknown_language_is_rejected(self) -> None: + with pytest.raises(CatalogError, match="Unknown catalog language 'xx'"): + load_catalog("xx") + + def test_language_without_overlay_falls_back_to_english(self) -> None: + catalog = load_catalog("ko") + + assert catalog.lang == "ko" + assert catalog.axis("database").label == "Database" + + def test_every_docs_language_is_accepted(self) -> None: + for lang in LANGUAGES: + assert load_catalog(lang).lang == lang + + def test_lookups(self) -> None: + catalog = load_catalog() + + assert catalog.level("hello").template == "fastapi-hello" + assert catalog.preset("domain-starter").template == "fastapi-domain-starter" + assert catalog.template("fastapi-sqlmodel").kind == "example" + assert catalog.concept("testing").url.endswith("/tutorial/testing/") + assert catalog.package_manager("pip").dependency_file == "requirements.txt" + assert catalog.rule("shared-redis").kind == "note" + with pytest.raises(KeyError, match="Unknown level 'nope'"): + catalog.level("nope") + + def test_axis_helpers(self) -> None: + utilities = load_catalog().axis("utilities") + + assert utilities.choice_ids[-1] == "None" + assert [option.id for option in utilities.offered] == [ + "Rate-Limiting", + "WebSocket", + ] + assert utilities.option("CORS").built_in + with pytest.raises(KeyError, match="no option 'Nope'"): + utilities.option("Nope") + + def test_option_packages_are_runtime_then_dev(self) -> None: + sqlite = load_catalog().axis("database").option("SQLite") + basic = load_catalog().axis("testing").option("Basic") + + assert sqlite.packages == ("sqlalchemy[asyncio]", "aiosqlite") + assert sqlite.label == "SQLite" + assert basic.runtime == () + assert basic.packages == basic.dev + + def test_dev_only_and_known_names(self) -> None: + catalog = load_catalog() + + assert "pytest" in catalog.dev_only_names() + assert "ruff" in catalog.dev_only_names() + # Listed as runtime somewhere, so never dev-only. + assert "httpx2" not in catalog.dev_only_names() + assert "aiosqlite" not in catalog.dev_only_names() + assert {"fastapi", "sqlalchemy", "pytest", "aiosqlite"} <= catalog.known_names() + + def test_production_level_bundle(self) -> None: + bundle = load_catalog().level("production").bundle + + assert bundle["database"] == "PostgreSQL" + assert bundle["deployment"] == ("Docker", "docker-compose") + + +class TestNames: + @pytest.mark.parametrize( + ("requirement", "name"), + [ + ("sqlalchemy[asyncio]>=2", "sqlalchemy"), + ("Foo_Bar.baz", "foo-bar-baz"), + (" pytest ; python_version>'3'", "pytest"), + ("-r requirements.txt", "-r requirements-txt"), + ], + ) + def test_requirement_name(self, requirement: str, name: str) -> None: + assert requirement_name(requirement) == name + + def test_canonical_name(self) -> None: + assert canonical_name("Pytest__Cov") == "pytest-cov" + + +class TestParseCatalog: + def test_minimal_catalog_parses(self, minimal_catalog_text: str) -> None: + catalog = parse_catalog(minimal_catalog_text, lang="de") + + assert catalog.lang == "de" + assert catalog.level("prod").bundle["deployment"] == ("compose",) + assert catalog.rule("tests-on-sqlite").when["testing"] == ("*",) + + @pytest.mark.parametrize( + ("old", "new", "message"), + [ + # duplicate ids + ( + 'id = "Mongo"\n', + 'id = "SQLite"\n', + "duplicate id 'SQLite'", + ), + ( + 'id = "fastapi-default"\nkind', + 'id = "fastapi-hello"\nkind', + "duplicate id 'fastapi-hello'", + ), + # unknown keys + ("schema_version = 1\n", 'schema_version = 1\ncolour = "red"\n', "colour"), + (' id = "Limits"\n', ' id = "Limits"\n colour = "red"\n', "colour"), + # missing / misplaced none option + ( + ' [[axes.options]]\n id = "None"\n none = true\n summary = "No auth"\n', + "", + "exactly one option with none = true", + ), + ( + 'id = "Mongo"\n runtime = ["pymongo"]\n', + 'id = "Mongo"\n none = true\n', + "exactly one option with none = true", + ), + # bad default + ( + 'default = "Basic"', + 'default = "Advanced"', + "default 'Advanced' is not an option", + ), + # both template and preset + ( + 'template = "fastapi-hello"\nasks_database = false', + 'template = "fastapi-hello"\npreset = "layered"\nasks_database = false', + "exactly one of 'template' and 'preset'", + ), + # unknown references + ( + 'template = "fastapi-hello"\nasks_database', + 'template = "fastapi-nope"\nasks_database', + "unknown template 'fastapi-nope'", + ), + ( + 'preset = "layered"\nasks_database = true', + 'preset = "classic"\nasks_database = true', + "unknown preset 'classic'", + ), + ( + 'template = "fastapi-default"\nsummary', + 'template = "fastapi-gone"\nsummary', + "unknown template 'fastapi-gone'", + ), + ( + 'concepts = ["testing"]\n\n[[levels]]', + 'concepts = ["routing"]\n\n[[levels]]', + "unknown concept 'routing'", + ), + ( + 'when = { auth = "Users" }', + 'when = { authn = "Users" }', + "unknown axis 'authn'", + ), + ( + 'when = { auth = "Users" }', + 'when = { auth = "Admins" }', + "unknown option 'Admins'", + ), + ( + 'level = "hello"\npreset', + 'level = "nope"\npreset', + "unknown level 'nope'", + ), + ( + 'preset = "layered"\npackage_manager', + 'preset = "nope"\npackage_manager', + "unknown preset 'nope'", + ), + ( + 'package_manager = "pip"', + 'package_manager = "npm"', + "unknown package manager 'npm'", + ), + # bundle violating a rule + ( + 'database = "SQLite"\nauth', + 'database = "Mongo"\nauth', + "bundle violates a rule: Users needs SQLite, but database 'Mongo'", + ), + ( + "Users needs {allowed}, but {selected} is selected.", + "Users needs {allowed}, but {chosen} is selected.", + "rule 'users-need-sql'.message: cannot be formatted", + ), + ( + "Users needs {allowed}, but {selected} is selected.", + "Users needs {allowed:bad}, but {selected} is selected.", + "rule 'users-need-sql'.message: cannot be formatted", + ), + ( + "Users needs {allowed}, but {selected} is selected.", + "Users needs {0}, but {selected} is selected.", + "rule 'users-need-sql'.message: cannot be formatted", + ), + # non-FastAPI concept URL + ( + "https://fastapi.tiangolo.com/tutorial/testing/", + "https://example.com/testing/", + "url must start with https://fastapi.tiangolo.com/", + ), + ], + ) + def test_invalid_catalog_is_rejected( + self, minimal_catalog_text: str, old: str, new: str, message: str + ) -> None: + text = _replace(minimal_catalog_text, old, new) + + with pytest.raises(CatalogError, match=message.replace("(", r"\(")): + parse_catalog(text) + + @pytest.mark.parametrize( + ("old", "new", "message"), + [ + ("schema_version = 1", "schema_version = 2", "unsupported schema_version"), + ("schema_version = 1", 'schema_version = "1"', "must be an integer"), + ('section = "deployment"', 'section = "infra"', "'section' must be one of"), + ( + 'kind = "level"\ndescription = "Hello"', + 'kind = "demo"\ndescription = "Hello"', + "'kind' must be one of", + ), + ('kind = "note"', 'kind = "warning"', "'kind' must be one of"), + ( + 'multi = false\ndefault = "Basic"', + 'multi = "no"\ndefault = "Basic"', + "must be true or false", + ), + ('title = "Testing"', 'title = ""', "must be a non-empty string"), + ('title = "Testing"', "title = 3", "must be a non-empty string"), + (' summary = "Users"', ' summary = ""', "must be a non-empty string"), + ('runtime = ["limits"]', 'runtime = "limits"', "must be a list of strings"), + ( + '[defaults]\nlevel = "hello"', + 'defaults = 3\n[unused]\nlevel = "hello"', + "expected a table", + ), + ( + ' id = "CORS"\n built_in = true', + ' id = "CORS"\n built_in = true', + "", + ), + ( + ' id = "Users"\n', + ' id = "Users"\n built_in = true\n', + "built_in on a single-select axis", + ), + ( + ' id = "None"\n none = true\n summary = "No auth"', + ' id = "None"\n none = true\n runtime = ["x"]', + "cannot add packages", + ), + ( + "[levels.bundle]\n", + '[levels.bundle]\ntesting = ["Basic"]\n', + "must be a single value", + ), + ('deployment = ["compose"]', 'deployment = "compose"', "must be a list"), + ( + 'deployment = ["compose"]', + 'deployment = ["swarm"]', + "unknown option 'swarm'", + ), + ( + 'deployment = ["compose"]', + "deployment = 3", + "must be a string or a list of strings", + ), + ( + "[levels.bundle]\n", + '[levels.bundle]\ncloud = "aws"\n', + "unknown axis 'cloud'", + ), + ( + 'template = "fastapi-hello"\nasks_database = false\nconcepts = ["testing"]', + 'template = "fastapi-hello"\nasks_database = false\nconcepts = ["testing"]\nbundle = { database = "SQLite" }', + "a bundle needs a preset", + ), + ('when = { auth = "Users" }', "when = {}", "needs at least one condition"), + ( + 'when = { auth = "Users" }', + "when = { auth = [] }", + "non-empty list of strings", + ), + ( + 'when = { testing = "*", database', + 'when = { testing = ["*", "Basic"], database', + "cannot be combined", + ), + ( + 'message = "Users needs {allowed}, but {selected} is selected."', + "", + "kind 'requires' needs 'require' and 'message'", + ), + ( + 'add = { deployment = ["Docker"] }', + 'message = "x"', + "does not take message", + ), + ( + 'add = { deployment = ["Docker"] }', + "runtime = []", + "kind 'implies' needs 'add'", + ), + ( + 'dev = ["aiosqlite"]\nruntime = ["mongomock"]', + "", + "kind 'adds' needs 'runtime' or 'dev'", + ), + ('message = "Limits are per process."', "", "kind 'note' needs 'message'"), + ( + 'add = { deployment = ["Docker"] }', + 'add = { database = ["SQLite", "Mongo"] }', + "a single-select axis takes one value", + ), + ( + 'require = { database = ["SQLite"] }', + 'require = { database = ["*"] }', + "unknown option '*'", + ), + ("[[presets]]", "[[presets]\n", "invalid TOML"), + ], + ) + def test_schema_errors( + self, minimal_catalog_text: str, old: str, new: str, message: str + ) -> None: + text = _replace(minimal_catalog_text, old, new) + if not message: + parse_catalog(text) + return + + with pytest.raises(CatalogError, match=message.replace("(", r"\(")): + parse_catalog(text) + + def test_none_option_must_be_last(self, minimal_catalog_text: str) -> None: + text = _replace( + minimal_catalog_text, + ' id = "None"\n none = true\n summary = "No auth"', + ' id = "None"\n summary = "No auth"', + ) + text = _replace(text, ' id = "Users"\n', ' id = "Users"\n none = true\n') + + with pytest.raises( + CatalogError, match="the none = true option must be the last" + ): + parse_catalog(text) + + def test_missing_required_key(self, minimal_catalog_text: str) -> None: + text = _replace(minimal_catalog_text, 'executable = "pip"\n', "") + + with pytest.raises( + CatalogError, + match=r"package_managers\[0\] \('pip'\): missing required key 'executable'", + ): + parse_catalog(text) + + def test_array_of_tables_is_required(self, minimal_catalog_text: str) -> None: + text = _replace( + minimal_catalog_text, + '[[presets]]\nid = "layered"\ntemplate = "fastapi-default"\nsummary = "Layered"\n', + "", + ) + text = _replace( + text, "schema_version = 1\n", "schema_version = 1\npresets = 3\n" + ) + + with pytest.raises(CatalogError, match="'presets' must be an array of tables"): + parse_catalog(text) + + def test_error_names_the_entry(self, minimal_catalog_text: str) -> None: + text = _replace( + minimal_catalog_text, 'id = "Mongo"\n', 'id = "Mongo"\n oops = 1\n' + ) + + with pytest.raises(CatalogError, match=r"\('database'\).*\('Mongo'\)"): + parse_catalog(text) + + +class TestLanguages: + def test_only_english_ships_in_stage_two(self) -> None: + assert loader_module.available_languages() == ("en",) + + def test_invalid_overlay_toml_is_reported( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + overlay = tmp_path / "fr.toml" + overlay.write_text("[levels\n", encoding="utf-8") + monkeypatch.setattr(loader_module, "_overlay_file", lambda lang: overlay) + loader_module._load.cache_clear() + try: + with pytest.raises(CatalogError, match="i18n/fr.toml: invalid TOML"): + loader_module.load_catalog("fr") + finally: + loader_module._load.cache_clear() + + def test_overlay_file_is_applied( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + overlay = tmp_path / "fr.toml" + overlay.write_text( + '[axes."database"]\nlabel = "Base de donnรฉes"\n', encoding="utf-8" + ) + monkeypatch.setattr(loader_module, "_overlay_file", lambda lang: overlay) + loader_module._load.cache_clear() + try: + catalog = loader_module.load_catalog("fr") + assert catalog.lang == "fr" + assert catalog.axis("database").label == "Base de donnรฉes" + assert catalog.axis("testing").label == "Testing" + assert loader_module.available_languages() == LANGUAGES + finally: + loader_module._load.cache_clear() diff --git a/tests/test_catalog/test_rules.py b/tests/test_catalog/test_rules.py new file mode 100644 index 00000000..2c63c060 --- /dev/null +++ b/tests/test_catalog/test_rules.py @@ -0,0 +1,427 @@ +# -------------------------------------------------------------------------- +# Test cases for catalog/rules.py and the rule consumers. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import pytest + +from fastapi_fastkit.backend.interactive.validators import ( + validate_feature_compatibility, +) +from fastapi_fastkit.backend.project_builder.config_schema import ( + DEPLOYMENT_CHOICES, + FASTAPI_USERS_DATABASES, + combination_errors, + normalize_project_config, +) +from fastapi_fastkit.catalog import ( + CatalogError, + evaluate, + parse_catalog, + selection_from_config, +) + +#: The FastAPI-Users message fastkit 1.x printed, word for word. +FASTAPI_USERS_MESSAGE = ( + "Authentication 'FastAPI-Users' needs a SQL database " + "(PostgreSQL, MySQL, SQLite), but {selected} is selected. " + "Choose one of those databases, or the 'JWT' option, which works " + "with every database." +) + + +class TestRequires: + @pytest.mark.parametrize( + ("database", "selected"), + [("None", "no database"), ("MongoDB", "database 'MongoDB'")], + ) + def test_fastapi_users_message_is_unchanged( + self, database: str, selected: str + ) -> None: + outcome = evaluate({"authentication": "FastAPI-Users", "database": database}) + + assert outcome.errors == (FASTAPI_USERS_MESSAGE.format(selected=selected),) + assert combination_errors( + {"authentication": "FastAPI-Users", "database": {"type": database}} + ) == [FASTAPI_USERS_MESSAGE.format(selected=selected)] + + def test_missing_database_reads_as_none(self) -> None: + outcome = evaluate({"authentication": "FastAPI-Users"}) + + assert outcome.errors == (FASTAPI_USERS_MESSAGE.format(selected="no database"),) + + @pytest.mark.parametrize("database", ["PostgreSQL", "MySQL", "SQLite"]) + def test_sql_databases_satisfy_the_rule(self, database: str) -> None: + assert ( + evaluate({"authentication": "FastAPI-Users", "database": database}).errors + == () + ) + + def test_derived_constants(self) -> None: + assert FASTAPI_USERS_DATABASES == ("PostgreSQL", "MySQL", "SQLite") + assert DEPLOYMENT_CHOICES == ("Docker", "docker-compose", "None") + + +class TestImplies: + def test_compose_implies_docker(self) -> None: + outcome = evaluate({"deployment": ("docker-compose",)}) + + assert dict(outcome.implied) == {"deployment": ("Docker",)} + + def test_nothing_implied_when_docker_is_selected(self) -> None: + outcome = evaluate({"deployment": ("docker-compose", "Docker")}) + + assert dict(outcome.implied) == {} + + def test_normalisation_puts_docker_first(self) -> None: + config = normalize_project_config({"deployment": ["docker-compose"]}) + + assert config["deployment"] == ["Docker", "docker-compose"] + + def test_implications_chain_to_a_fixed_point(self) -> None: + catalog = parse_catalog(_CHAINED) + + outcome = evaluate({"a": "x"}, catalog) + + assert dict(outcome.implied) == {"b": ("y",), "c": ("z",)} + + +class TestAdds: + @pytest.mark.parametrize( + ("database", "auth", "testing", "expected"), + [ + ("PostgreSQL", "JWT", "Basic", True), + ("MySQL", "Session-based", "Coverage", True), + ("PostgreSQL", "FastAPI-Users", "Advanced", True), + ("SQLite", "JWT", "Basic", False), + ("PostgreSQL", "JWT", "None", False), + ("PostgreSQL", "OAuth2", "Basic", True), + ("MySQL", "None", "Basic", True), + ("MongoDB", "JWT", "Basic", False), + ("None", "JWT", "Basic", False), + ], + ) + def test_aiosqlite_is_a_dev_package_for_server_databases( + self, database: str, auth: str, testing: str, expected: bool + ) -> None: + outcome = evaluate( + {"database": database, "authentication": auth, "testing": testing} + ) + + assert (outcome.dev == ("aiosqlite",)) is expected + assert outcome.runtime == () + + +class TestNotes: + @pytest.mark.parametrize("tasks", ["Celery", "Dramatiq"]) + def test_shared_redis_note(self, tasks: str) -> None: + config = {"caching": "Redis", "async_tasks": tasks} + + outcome = evaluate(selection_from_config(config)) + + note = "Info: Redis will be used for both caching and task queue (shared dependency)." + assert outcome.notes == (note,) + assert validate_feature_compatibility(config) == (True, note) + + def test_no_note_without_both(self) -> None: + assert validate_feature_compatibility({"caching": "Redis"}) == (True, None) + + def test_errors_win_over_notes(self) -> None: + is_valid, message = validate_feature_compatibility( + { + "authentication": "FastAPI-Users", + "caching": "Redis", + "async_tasks": "Celery", + } + ) + + assert is_valid is False + assert message == FASTAPI_USERS_MESSAGE.format(selected="no database") + + +class TestWildcardAndMulti: + def test_wildcard_on_a_multi_axis_needs_a_selection( + self, minimal_catalog_text: str + ) -> None: + catalog = parse_catalog(minimal_catalog_text) + + assert evaluate({"utilities": ()}, catalog).notes == () + assert evaluate({"utilities": "None"}, catalog).notes == () + assert evaluate({"utilities": ("None",)}, catalog).notes == () + assert evaluate({"utilities": "Limits"}, catalog).notes == ( + "Limits are per process.", + ) + assert evaluate({"utilities": ("CORS",)}, catalog).notes == ( + "Limits are per process.", + ) + + def test_wildcard_on_a_single_axis_excludes_none( + self, minimal_catalog_text: str + ) -> None: + catalog = parse_catalog(minimal_catalog_text) + + added = evaluate({"database": "Mongo", "testing": "Basic"}, catalog) + absent = evaluate({"database": "Mongo", "testing": "None"}, catalog) + + assert (added.runtime, added.dev) == (("mongomock",), ("aiosqlite",)) + assert (absent.runtime, absent.dev) == ((), ()) + + def test_requires_on_a_multi_axis_describes_the_selection(self) -> None: + catalog = parse_catalog(_MULTI_REQUIRE) + + assert evaluate({"a": "x"}, catalog).errors == ("needs one of y: no b",) + assert evaluate({"a": "x", "b": ("z",)}, catalog).errors == ( + "needs one of y: b 'z'", + ) + assert evaluate({"a": "x", "b": ("y", "z")}, catalog).errors == () + + +class TestSelectionFromConfig: + def test_reads_every_shape(self) -> None: + selection = selection_from_config( + { + "database": {"type": "SQLite", "packages": []}, + "authentication": {"type": "JWT"}, + "utilities": "WebSocket", + "tooling": ["ruff", "None", "ruff", 3], + "deployment": ["docker-compose"], + "caching": 7, + "monitoring": "", + } + ) + + assert selection["database"] == "SQLite" + assert selection["authentication"] == "JWT" + assert selection["utilities"] == ("WebSocket",) + assert selection["tooling"] == ("ruff",) + assert selection["deployment"] == ("docker-compose",) + assert selection["caching"] == "None" + assert selection["monitoring"] == "None" + assert selection["testing"] == "None" + assert selection["logging"] == "None" + + def test_bad_multi_value_reads_as_empty(self) -> None: + assert selection_from_config({"tooling": 5})["tooling"] == () + assert selection_from_config({})["deployment"] == () + + +_CHAINED = """ +schema_version = 1 +concepts = [] + +[defaults] +level = "l" +preset = "p" +package_manager = "m" +base_dependencies = [] + +[[levels]] +id = "l" +label = "L" +description = "L" +preset = "p" +asks_database = false + +[[presets]] +id = "p" +template = "t" +summary = "P" + +[[templates]] +id = "t" +kind = "level" +description = "T" + +[[package_managers]] +id = "m" +dependency_file = "requirements.txt" +executable = "m" +description = "M" + +[[axes]] +id = "a" +label = "A" +description = "A" +section = "features" +multi = false +default = "None" +options = [{ id = "x" }, { id = "None", none = true }] + +[[axes]] +id = "b" +label = "B" +description = "B" +section = "features" +multi = true +default = "None" +options = [{ id = "y" }, { id = "z" }, { id = "None", none = true }] + +[[axes]] +id = "c" +label = "C" +description = "C" +section = "features" +multi = false +default = "None" +options = [{ id = "z" }, { id = "None", none = true }] + +# Listed before the rule that triggers it, so one pass is not enough. +[[rules]] +id = "b-implies-c" +kind = "implies" +when = { b = "y" } +add = { c = ["z"] } + +[[rules]] +id = "a-implies-b" +kind = "implies" +when = { a = "x" } +add = { b = ["y"] } +""" + +_MULTI_REQUIRE = _CHAINED.split("# Listed before")[0] + """ +[[rules]] +id = "a-needs-b" +kind = "requires" +when = { a = "x" } +require = { b = ["y"] } +message = "needs one of {allowed}: {selected}" +""" + + +_CYCLE_HEADER = _CHAINED.split("[[axes]]")[0] + """ +[[axes]] +id = "a" +label = "A" +description = "A" +section = "features" +multi = false +default = "None" +options = [{ id = "x" }, { id = "w" }, { id = "None", none = true }] + +[[axes]] +id = "b" +label = "B" +description = "B" +section = "features" +multi = false +default = "None" +options = [{ id = "y" }, { id = "v" }, { id = "None", none = true }] + +[[axes]] +id = "m" +label = "M" +description = "M" +section = "features" +multi = true +default = "None" +options = [{ id = "p" }, { id = "q" }, { id = "None", none = true }] +""" + +# Every pair of rules that sets the same axis has disjoint conditions, so the +# loader cannot reject it; evaluation runs in a circle a=x -> b=y -> a=w -> +# b=v -> a=x. +_CYCLE = _CYCLE_HEADER + """ +[[rules]] +id = "r1" +kind = "implies" +when = { a = "x" } +add = { b = ["y"] } + +[[rules]] +id = "r2" +kind = "implies" +when = { b = "y" } +add = { a = ["w"] } + +[[rules]] +id = "r3" +kind = "implies" +when = { a = "w" } +add = { b = ["v"] } + +[[rules]] +id = "r4" +kind = "implies" +when = { b = "v" } +add = { a = ["x"] } +""" + + +def _conflict(first_when: str, second_when: str) -> str: + return _CYCLE_HEADER + f""" +[[rules]] +id = "first" +kind = "implies" +when = {first_when} +add = {{ b = ["y"] }} + +[[rules]] +id = "second" +kind = "implies" +when = {second_when} +add = {{ b = ["v"] }} +""" + + +class TestImpliesConvergence: + @pytest.mark.parametrize( + ("first_when", "second_when"), + [ + ('{ a = "x" }', '{ a = "x" }'), + ('{ a = "*" }', '{ a = ["x", "w"] }'), + ('{ a = "x" }', '{ b = "y" }'), + # Both values of a multi-select axis can be selected together. + ('{ m = "p" }', '{ m = "q" }'), + ], + ) + def test_conflicting_overlapping_implications_are_rejected( + self, first_when: str, second_when: str + ) -> None: + with pytest.raises(CatalogError, match="rules 'first' and 'second'"): + parse_catalog(_conflict(first_when, second_when)) + + @pytest.mark.parametrize( + ("first_when", "second_when"), + [('{ a = "x" }', '{ a = "w" }'), ('{ a = "*" }', '{ a = "None" }')], + ) + def test_disjoint_conditions_are_accepted( + self, first_when: str, second_when: str + ) -> None: + catalog = parse_catalog(_conflict(first_when, second_when)) + + assert evaluate({"a": "x"}, catalog).implied == {"b": ("y",)} + + def test_agreeing_or_multi_select_implications_are_accepted(self) -> None: + text = _CYCLE_HEADER + """ +[[rules]] +id = "same-value-1" +kind = "implies" +when = { a = "x" } +add = { b = ["y"], m = ["p"] } + +[[rules]] +id = "same-value-2" +kind = "implies" +when = { a = "x" } +add = { b = ["y"], m = ["q"] } +""" + + outcome = evaluate({"a": "x"}, parse_catalog(text)) + + assert dict(outcome.implied) == {"b": ("y",), "m": ("p", "q")} + + def test_a_cycle_is_an_error(self) -> None: + catalog = parse_catalog(_CYCLE) + + with pytest.raises(CatalogError, match="do not settle"): + evaluate({"a": "x"}, catalog) + + def test_a_long_chain_still_settles(self) -> None: + # Overriding a single-select value set earlier in the chain is not a + # cycle. + catalog = parse_catalog(_CYCLE.split('[[rules]]\nid = "r4"')[0]) + + outcome = evaluate({"a": "x"}, catalog) + + assert dict(outcome.implied) == {"b": ("y", "v"), "a": ("w",)} diff --git a/tests/test_cli_operations/test_cli_config_noninteractive.py b/tests/test_cli_operations/test_cli_config_noninteractive.py index fe2755bc..f844e748 100644 --- a/tests/test_cli_operations/test_cli_config_noninteractive.py +++ b/tests/test_cli_operations/test_cli_config_noninteractive.py @@ -274,7 +274,7 @@ def test_unreadable_config_exits_non_zero(self, tmp_path: Path) -> None: # then assert result.exit_code == 1 - @patch("fastapi_fastkit.backend.scaffolder.inject_project_metadata") + @patch("fastapi_fastkit.generation.pipeline.inject_project_metadata") def test_scaffold_failure_exits_non_zero_and_rolls_back( self, mock_inject: MagicMock, tmp_path: Path ) -> None: diff --git a/tests/test_cli_operations/test_cli_portability.py b/tests/test_cli_operations/test_cli_portability.py index e30ff224..e32f22e0 100644 --- a/tests/test_cli_operations/test_cli_portability.py +++ b/tests/test_cli_operations/test_cli_portability.py @@ -268,7 +268,7 @@ def test_declining_the_overwrite_prompt_exits_zero(self, tmp_path: Path) -> None assert "aborted by user" in result.output assert (tmp_path / "README.md").read_text(encoding="utf-8") == "mine" - @patch("fastapi_fastkit.backend.scaffolder.inject_project_metadata") + @patch("fastapi_fastkit.generation.pipeline.inject_project_metadata") def test_real_failure_exits_non_zero( self, mock_inject: MagicMock, tmp_path: Path ) -> None: diff --git a/tests/test_cli_operations/test_cli_rough_edges.py b/tests/test_cli_operations/test_cli_rough_edges.py index b4126ab2..90804fd4 100644 --- a/tests/test_cli_operations/test_cli_rough_edges.py +++ b/tests/test_cli_operations/test_cli_rough_edges.py @@ -358,3 +358,39 @@ def test_failed_deletion_exits_1(self, runner: CliRunner, tmp_path: Path) -> Non assert result.exit_code == 1 assert "Error during project deletion" in _flat(result.output) + + +class TestListTemplatesDescriptions: + """Known templates show the catalog text; other directories their README.""" + + def test_catalog_text_then_readme_heading_then_fallback( + self, runner: CliRunner, tmp_path: Path + ) -> None: + known = tmp_path / "fastapi-hello" + known.mkdir() + (known / "README.md-tpl").write_text("# Local heading\n", encoding="utf-8") + custom = tmp_path / "fastapi-custom" + custom.mkdir() + (custom / "README.md-tpl").write_text("# Custom template\n", encoding="utf-8") + bare = tmp_path / "fastapi-bare" + bare.mkdir() + (bare / "README.md-tpl").write_text("no heading\n", encoding="utf-8") + + with patch( + "fastapi_fastkit.core.settings.FastkitConfig._FastkitConfig__get_template_root", + return_value=tmp_path, + ): + result = runner.invoke(fastkit_cli, ["list-templates"]) + + assert result.exit_code == 0 + output = result.output + assert "Smallest FastAPI app" in output + assert "Local heading" not in output + assert "Custom template" in output + assert "No description" in output + # Catalog templates first, then unknown ones by name. + assert ( + output.index("fastapi-hello") + < output.index("fastapi-bare") + < output.index("fastapi-custom") + ) diff --git a/tests/test_generation/__init__.py b/tests/test_generation/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_generation/test_dependencies.py b/tests/test_generation/test_dependencies.py new file mode 100644 index 00000000..88a05f22 --- /dev/null +++ b/tests/test_generation/test_dependencies.py @@ -0,0 +1,592 @@ +# -------------------------------------------------------------------------- +# Testcases of dependency resolution and dependency file rendering. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import tomllib +from pathlib import Path +from typing import Any, Dict, List +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.backend.package_managers import ( + PdmManager, + PipManager, + PoetryManager, + UvManager, +) +from fastapi_fastkit.backend.project_builder.dependency_collector import ( + DependencySet, +) +from fastapi_fastkit.core.settings import FastkitConfig +from fastapi_fastkit.generation import GenerationSpec, ProjectInfo +from fastapi_fastkit.generation.dependencies import ( + merge_dev_group, + parse_requirements_text, + render_dependency_files, + requirement_name, + resolve_dependencies, + sync_pyproject_dev_declarations, + template_dependencies, +) +from fastapi_fastkit.utils.messages import capture_messages + +TEMPLATE_ROOT = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + + +def _templates() -> List[str]: + return sorted( + d.name + for d in TEMPLATE_ROOT.iterdir() + if d.is_dir() and (d / "pyproject.toml-tpl").is_file() + ) + + +def _fail_probe(self: Any) -> bool: + raise AssertionError("rendering must not probe for installed tools") + + +@pytest.fixture +def no_probing(monkeypatch: pytest.MonkeyPatch) -> None: + """Any availability probe fails the test.""" + for cls in (PipManager, UvManager, PdmManager, PoetryManager): + monkeypatch.setattr(cls, "is_available", _fail_probe) + + +# ------------------------------------------------------------------ template + + +@pytest.mark.parametrize("template", _templates()) +def test_template_dependencies_follow_the_template_pyproject(template: str) -> None: + # given + data = tomllib.loads( + (TEMPLATE_ROOT / template / "pyproject.toml-tpl").read_text(encoding="utf-8") + ) + + # when + deps = template_dependencies(str(TEMPLATE_ROOT / template)) + + # then + assert list(deps.runtime) == data["project"]["dependencies"] + assert list(deps.dev) == data.get("dependency-groups", {}).get("dev", []) + assert not any(entry.startswith("#") for entry in [*deps.runtime, *deps.dev]) + + +def test_requirements_fallback_strips_comments_options_and_dev_tools( + tmp_path: Path, +) -> None: + # given + (tmp_path / "requirements.txt-tpl").write_text( + "# Database drivers\n" + "-r base.txt\n" + "-c constraints.txt\n" + "--index-url https://example.invalid/simple\n" + "\n" + "fastapi>=0.100 # web\n" + "sqlmodel\n" + "pytest>=8\n" + "ruff\n" + ) + + # when + deps = template_dependencies(str(tmp_path)) + + # then + assert deps.runtime == ("fastapi>=0.100", "sqlmodel") + assert deps.dev == ("pytest>=8", "ruff") + + +def test_requirements_template_reads_the_dev_file_next_to_it(tmp_path: Path) -> None: + # given: no pyproject.toml-tpl, runtime and dev requirements files + (tmp_path / "requirements.txt-tpl").write_text("fastapi\nruff\n") + (tmp_path / "requirements-dev.txt-tpl").write_text( + "-r requirements.txt\nblack>=24 # fmt\nmypy\nfastapi\n" + ) + + # when + deps = template_dependencies(str(tmp_path)) + + # then: every entry of the dev file is dev; a runtime name stays runtime + assert deps.runtime == ("fastapi",) + assert deps.dev == ("black>=24", "mypy", "ruff") + + +def test_unreadable_dev_requirements_template_is_skipped(tmp_path: Path) -> None: + (tmp_path / "requirements.txt-tpl").write_text("fastapi\npytest\n") + (tmp_path / "requirements-dev.txt-tpl").write_bytes(b"\xff\xfe\x00 bad") + + assert template_dependencies(str(tmp_path)) == DependencySet( + runtime=("fastapi",), dev=("pytest",) + ) + + +def test_pyproject_without_dependencies_falls_back(tmp_path: Path) -> None: + (tmp_path / "pyproject.toml-tpl").write_text("[project]\nname = 'x'\n") + (tmp_path / "requirements.txt-tpl").write_text("fastapi\n") + + assert template_dependencies(str(tmp_path)).runtime == ("fastapi",) + + +def test_broken_pyproject_falls_back(tmp_path: Path) -> None: + (tmp_path / "pyproject.toml-tpl").write_text("[project\n") + (tmp_path / "requirements.txt-tpl").write_text("uvicorn\n") + + assert template_dependencies(str(tmp_path)).runtime == ("uvicorn",) + + +def test_setup_py_fallback(tmp_path: Path) -> None: + (tmp_path / "setup.py-tpl").write_text( + 'install_requires: list[str] = [\n "fastapi",\n "uvicorn",\n]\n' + ) + + assert template_dependencies(str(tmp_path)) == DependencySet( + runtime=("fastapi", "uvicorn") + ) + + +def test_template_without_declarations(tmp_path: Path) -> None: + assert template_dependencies(str(tmp_path)) == DependencySet() + + +def test_parse_requirements_text_keeps_markers() -> None: + assert parse_requirements_text( + 'uvloop==0.22.1; sys_platform != "win32"\n # x\n' + ) == ['uvloop==0.22.1; sys_platform != "win32"'] + + +def test_requirement_name_is_canonical() -> None: + assert requirement_name("Pydantic_Settings[x]>=2; python_version>'3'") == ( + "pydantic-settings" + ) + + +def test_template_mode_resolves_the_template_declarations() -> None: + spec = GenerationSpec(ProjectInfo("p"), "fastapi-hello") + + deps = resolve_dependencies(spec) + + assert deps == template_dependencies(str(TEMPLATE_ROOT / "fastapi-hello")) + + +# ------------------------------------------------------------- stack/features + + +def _features(**features: Any) -> GenerationSpec: + return GenerationSpec( + ProjectInfo("p"), + "fastapi-default", + preset="classic-layered", + features=features, + dependency_files="generated", + ) + + +def test_features_mode_puts_testing_and_tooling_into_dev() -> None: + # when + deps = resolve_dependencies( + _features(testing="Coverage", tooling=("ruff", "pre-commit")) + ) + + # then + assert {"fastapi", "uvicorn", "pydantic", "pydantic-settings"} <= set(deps.runtime) + assert {"pytest", "pytest-cov", "ruff", "pre-commit"} <= set(deps.dev) + assert not {"pytest", "ruff"} & set(deps.runtime) + + +def test_httpx2_stays_runtime_with_oauth2() -> None: + deps = resolve_dependencies(_features(authentication="OAuth2", testing="Basic")) + + assert "httpx2" in deps.runtime + assert "httpx2" not in deps.dev + assert "pytest" in deps.dev + + +def test_aiosqlite_is_a_dev_dependency_for_postgresql_tests() -> None: + deps = resolve_dependencies(_features(database="PostgreSQL", testing="Basic")) + + assert "aiosqlite" in deps.dev + assert "asyncpg" in deps.runtime + + +def test_custom_packages_are_sanitised_runtime_dependencies() -> None: + spec = GenerationSpec( + ProjectInfo("p"), + "fastapi-empty", + features={}, + dependency_files="generated", + custom_packages=("orjson", " ", "ORJSON", "bad name!"), + ) + + deps = resolve_dependencies(spec) + + assert "orjson" in deps.runtime + assert not any(" " in d for d in deps.runtime) + + +def test_stack_standard_puts_pytest_into_dev() -> None: + spec = GenerationSpec( + ProjectInfo("p"), + "fastapi-empty", + dependency_files="generated", + extra_dependencies=tuple(FastkitConfig.PROJECT_STACKS["standard"]), + ) + + deps = resolve_dependencies(spec) + + assert deps.dev == ("pytest",) + assert "sqlalchemy" in deps.runtime and "alembic" in deps.runtime + + +def test_legacy_leftovers_are_classified() -> None: + spec = GenerationSpec( + ProjectInfo("p"), + "fastapi-empty", + features={}, + dependency_files="generated", + extra_dependencies=("motor", "pytest"), + ) + + deps = resolve_dependencies(spec) + + assert "motor" in deps.runtime + assert "pytest" in deps.dev + + +def test_conditional_custom_package_keeps_the_dev_tool_everywhere() -> None: + marked = 'httpx>=0.27; sys_platform == "win32"' + spec = GenerationSpec( + ProjectInfo("p"), + "fastapi-empty", + features={"testing": "Basic"}, + dependency_files="generated", + custom_packages=(marked,), + ) + + deps = resolve_dependencies(spec) + + assert marked in deps.runtime + assert "httpx" in deps.dev + + +# ------------------------------------------------------------------ dev merge + + +def test_merge_dev_group_keeps_template_entries_first_and_verbatim() -> None: + template = ["pytest>=9.1.1", "httpx>=0.28.1", "black>=26"] + + assert merge_dev_group(template, ["pytest", "ruff", "pytest-cov"]) == [ + "pytest>=9.1.1", + "httpx>=0.28.1", + "black>=26", + "pytest-cov", + "ruff", + ] + assert merge_dev_group(template, ["httpx"]) == template + + +def test_merge_dev_group_adds_an_unconditional_entry_next_to_a_marked_one() -> None: + template = ['httpx>=0.28; sys_platform == "win32"', "pytest"] + + assert merge_dev_group(template, ["httpx", "pytest"]) == [*template, "httpx"] + + +# ------------------------------------------------------------------ rendering + + +def _deploy(tmp_path: Path, template: str = "fastapi-default") -> Path: + from fastapi_fastkit.backend.transducer import copy_and_convert_template + + project = tmp_path / "proj" + copy_and_convert_template(str(TEMPLATE_ROOT / template), str(project), "") + return project + + +def _load(path: Path) -> Dict[str, Any]: + return tomllib.loads(path.read_text(encoding="utf-8")) + + +DEPS = DependencySet(runtime=("fastapi", "uvicorn"), dev=("pytest", "ruff")) + + +def test_pip_renders_both_requirements_files(tmp_path: Path, no_probing: None) -> None: + # given + project = _deploy(tmp_path) + template_dev = _load(project / "pyproject.toml")["dependency-groups"]["dev"] + spec = GenerationSpec( + ProjectInfo("proj"), + "fastapi-default", + package_manager="pip", + dependency_files="generated", + ) + + # when + written = render_dependency_files(str(project), spec, DEPS) + + # then + assert (project / "requirements.txt").read_text().splitlines() == [ + "fastapi", + "uvicorn", + ] + dev_lines = (project / "requirements-dev.txt").read_text().splitlines() + assert dev_lines[0] == "-r requirements.txt" + assert dev_lines[1 : 1 + len(template_dev)] == template_dev + assert dev_lines[-1] == "ruff" + assert {"requirements.txt", "requirements-dev.txt", "pyproject.toml"} <= set( + written + ) + + +@pytest.mark.parametrize("manager", ["uv", "pdm"]) +def test_uv_and_pdm_render_the_dependency_group( + tmp_path: Path, manager: str, no_probing: None +) -> None: + # given + project = _deploy(tmp_path) + template_dev = _load(project / "pyproject.toml")["dependency-groups"]["dev"] + spec = GenerationSpec( + ProjectInfo("proj"), + "fastapi-default", + package_manager=manager, + dependency_files="generated", + ) + + # when + render_dependency_files(str(project), spec, DEPS) + + # then + data = _load(project / "pyproject.toml") + assert data["project"]["dependencies"] == ["fastapi", "uvicorn"] + assert data["dependency-groups"]["dev"] == [*template_dev, "ruff"] + assert (project / "requirements.txt").read_text().splitlines() == [ + "fastapi", + "uvicorn", + ] + assert (project / "requirements-dev.txt").read_text().splitlines() == [ + "-r requirements.txt", + *template_dev, + "ruff", + ] + + +def test_poetry_renders_its_dev_group(tmp_path: Path, no_probing: None) -> None: + # given + project = _deploy(tmp_path) + spec = GenerationSpec( + ProjectInfo("proj"), + "fastapi-default", + package_manager="poetry", + dependency_files="generated", + ) + + # when + render_dependency_files(str(project), spec, DEPS) + + # then + data = _load(project / "pyproject.toml") + poetry_dev = data["tool"]["poetry"]["group"]["dev"]["dependencies"] + assert "ruff" in poetry_dev and "pytest" in poetry_dev + assert set(data["tool"]["poetry"]["dependencies"]) == { + "python", + "fastapi", + "uvicorn", + } + assert (project / "requirements-dev.txt").is_file() + + +def test_nothing_added_leaves_the_dev_group_byte_identical( + tmp_path: Path, no_probing: None +) -> None: + # given: requested dev packages are all in the template's group already + project = _deploy(tmp_path) + before = (project / "pyproject.toml").read_text(encoding="utf-8") + spec = GenerationSpec( + ProjectInfo("proj"), + "fastapi-default", + package_manager="uv", + dependency_files="generated", + ) + runtime = tuple(_load(project / "pyproject.toml")["project"]["dependencies"]) + + # when + render_dependency_files( + str(project), spec, DependencySet(runtime=runtime, dev=("pytest",)) + ) + + # then + assert (project / "pyproject.toml").read_text(encoding="utf-8") == before + + +def test_project_without_pyproject_renders_requirements_only( + tmp_path: Path, no_probing: None +) -> None: + project = tmp_path / "bare" + project.mkdir() + spec = GenerationSpec( + ProjectInfo("bare"), + "fastapi-default", + package_manager="pip", + dependency_files="generated", + ) + + written = render_dependency_files(str(project), spec, DEPS) + + assert written == ["requirements.txt", "requirements-dev.txt"] + + +@pytest.mark.parametrize("name", ["requirements.txt-tpl", "setup.py-tpl"]) +def test_unreadable_template_declarations_give_nothing( + tmp_path: Path, name: str +) -> None: + (tmp_path / name).write_bytes(b"\xff\xfe\x00 not utf-8") + + assert template_dependencies(str(tmp_path)) == DependencySet() + + +def test_unparsable_project_pyproject_counts_as_an_empty_dev_group( + tmp_path: Path, no_probing: None +) -> None: + # given: the project's pyproject cannot be parsed, so no group is read + project = tmp_path / "broken" + project.mkdir() + (project / "pyproject.toml").write_text("[project\n") + spec = GenerationSpec( + ProjectInfo("broken"), + "fastapi-default", + package_manager="pip", + dependency_files="generated", + ) + + # when + render_dependency_files(str(project), spec, DEPS) + + # then + assert (project / "requirements-dev.txt").read_text().splitlines() == [ + "-r requirements.txt", + "pytest", + "ruff", + ] + + +# ------------------------------------------------- dev declarations stay equal + + +@pytest.mark.parametrize("template", _templates()) +def test_template_dev_extra_equals_the_dev_group(template: str) -> None: + """ + PDM installs ``[project.optional-dependencies].dev`` instead of + ``[dependency-groups].dev`` when a project declares both, so a template + that ships both must list the same packages in each. + """ + data = tomllib.loads( + (TEMPLATE_ROOT / template / "pyproject.toml-tpl").read_text(encoding="utf-8") + ) + extras = data["project"].get("optional-dependencies", {}) + + if "dev" in extras: + assert extras["dev"] == data["dependency-groups"]["dev"] + + +@pytest.mark.parametrize("manager", ["pip", "uv", "pdm", "poetry"]) +def test_every_dev_declaration_lists_the_final_dev_packages( + tmp_path: Path, manager: str, no_probing: None +) -> None: + # given: the template declares its tools as a group and as an extra + project = _deploy(tmp_path, "fastapi-domain-starter") + template_dev = _load(project / "pyproject.toml")["dependency-groups"]["dev"] + spec = GenerationSpec( + ProjectInfo("proj"), + "fastapi-domain-starter", + package_manager=manager, + dependency_files="generated", + ) + + # when + render_dependency_files(str(project), spec, DEPS) + + # then: the group, the extra and requirements-dev.txt agree + expected = [*template_dev, "ruff"] + data = _load(project / "pyproject.toml") + assert data["dependency-groups"]["dev"] == expected + assert data["project"]["optional-dependencies"]["dev"] == expected + assert (project / "requirements-dev.txt").read_text().splitlines() == [ + "-r requirements.txt", + *expected, + ] + + +def test_sync_adds_no_declaration_the_file_does_not_have(tmp_path: Path) -> None: + content = '[project]\nname = "x"\ndependencies = []\n' + (tmp_path / "pyproject.toml").write_text(content) + + assert not sync_pyproject_dev_declarations(str(tmp_path), ["ruff"]) + assert (tmp_path / "pyproject.toml").read_text() == content + + +def test_sync_without_pyproject_does_nothing(tmp_path: Path) -> None: + assert not sync_pyproject_dev_declarations(str(tmp_path), ["ruff"]) + assert not (tmp_path / "pyproject.toml").exists() + + +def test_sync_keeps_crlf_line_endings(tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_bytes( + b'[project]\r\nname = "x"\r\n\r\n[project.optional-dependencies]\r\n' + b'dev = ["pytest"]\r\n\r\n[dependency-groups]\r\ndev = ["pytest"]\r\n' + ) + + assert sync_pyproject_dev_declarations(str(tmp_path), ["pytest", "ruff"]) + + raw = (tmp_path / "pyproject.toml").read_bytes() + assert raw.count(b"\r\n") == raw.count(b"\n") + data = tomllib.loads(raw.decode("utf-8")) + assert data["project"]["optional-dependencies"]["dev"] == ["pytest", "ruff"] + assert data["dependency-groups"]["dev"] == ["pytest", "ruff"] + + +def test_sync_warns_and_keeps_a_file_it_cannot_edit_safely(tmp_path: Path) -> None: + # given: the extra is an inline table fastkit does not edit + content = '[project]\nname = "x"\noptional-dependencies = {dev = ["pytest"]}\n' + (tmp_path / "pyproject.toml").write_text(content) + + # when + with capture_messages() as messages: + changed = sync_pyproject_dev_declarations(str(tmp_path), ["ruff"]) + + # then + assert not changed + assert (tmp_path / "pyproject.toml").read_text() == content + assert [m.level for m in messages] == ["warning"] + assert "left unchanged" in messages[0].text + + +def test_sync_keeps_a_group_it_cannot_edit_safely(tmp_path: Path) -> None: + # given: the dev group is written with dotted keys + content = '[project]\nname = "x"\n\n[dependency-groups.dev]\nx = 1\n' + (tmp_path / "pyproject.toml").write_text(content) + + with capture_messages() as messages: + changed = sync_pyproject_dev_declarations(str(tmp_path), ["ruff"]) + + assert not changed + assert (tmp_path / "pyproject.toml").read_text() == content + assert "left unchanged" in messages[0].text + + +def test_sync_ignores_an_unreadable_file(tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_bytes(b"\xff\xfe not utf-8") + + assert not sync_pyproject_dev_declarations(str(tmp_path), ["ruff"]) + + +def test_sync_reports_a_failed_write(tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_text( + '[project]\nname = "x"\n\n[project.optional-dependencies]\n' + 'dev = ["pytest"]\n' + ) + + with patch( + "fastapi_fastkit.backend.package_managers.pyproject." + "write_text_preserving_newlines", + side_effect=OSError("disk full"), + ): + assert not sync_pyproject_dev_declarations(str(tmp_path), ["ruff"]) diff --git a/tests/test_generation/test_determinism.py b/tests/test_generation/test_determinism.py new file mode 100644 index 00000000..c51d6bf7 --- /dev/null +++ b/tests/test_generation/test_determinism.py @@ -0,0 +1,102 @@ +# -------------------------------------------------------------------------- +# Equal specs give equal trees. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import re +from pathlib import Path +from typing import Dict, Tuple + +import pytest + +from fastapi_fastkit.backend.doctor.known import KNOWN_EXAMPLE_SECRETS +from fastapi_fastkit.generation import ( + GenerationSpec, + ProjectInfo, + default_secret_factory, + generate, + seeded_secret_factory, +) +from fastapi_fastkit.utils.platform import is_windows + +SPECS = { + "features": GenerationSpec( + ProjectInfo("same", "me", "me@example.com", "twice"), + "fastapi-domain-starter", + preset="domain-starter", + features={ + "database": "PostgreSQL", + "authentication": "JWT", + "migrations": "Alembic", + "testing": "Coverage", + "tooling": ("ruff", "github-actions"), + "deployment": ("Docker", "docker-compose"), + }, + dependency_files="generated", + package_manager="uv", + ), + "template": GenerationSpec(ProjectInfo("same"), "fastapi-auth-jwt"), +} + +_SECRET_LINE = re.compile(rb"(?m)^SECRET_KEY=.*$") + + +def _snapshot(root: Path) -> Dict[str, Tuple[bytes, bool]]: + snapshot = {} + for path in sorted(root.rglob("*")): + if path.is_file(): + executable = (not is_windows()) and os.access(path, os.X_OK) + snapshot[path.relative_to(root).as_posix()] = ( + path.read_bytes(), + executable, + ) + return snapshot + + +@pytest.mark.parametrize("name", sorted(SPECS)) +def test_seeded_runs_produce_identical_trees(name: str, tmp_path: Path) -> None: + # when + first = generate( + SPECS[name], tmp_path / "a", secret_factory=seeded_secret_factory("t") + ) + second = generate( + SPECS[name], tmp_path / "b", secret_factory=seeded_secret_factory("t") + ) + + # then + assert _snapshot(tmp_path / "a") == _snapshot(tmp_path / "b") + assert first.files == second.files + assert first.messages == second.messages + + +@pytest.mark.parametrize("name", sorted(SPECS)) +def test_default_runs_differ_only_in_env_secret_values( + name: str, tmp_path: Path +) -> None: + # when + generate(SPECS[name], tmp_path / "a") + generate(SPECS[name], tmp_path / "b") + + # then + a, b = _snapshot(tmp_path / "a"), _snapshot(tmp_path / "b") + assert a.keys() == b.keys() + differing = {path for path in a if a[path] != b[path]} + assert differing == {".env"} + masked = [_SECRET_LINE.sub(b"SECRET_KEY=", tree[".env"][0]) for tree in (a, b)] + assert masked[0] == masked[1] + + +def test_seeded_factory_has_the_shape_of_a_real_secret() -> None: + # given + factory = seeded_secret_factory("seed") + values = [factory() for _ in range(5)] + + # then + assert len(set(values)) == 5 + assert seeded_secret_factory("seed")() == values[0] + for value in values: + assert len(value) == len(default_secret_factory()) == 43 + assert re.fullmatch(r"[A-Za-z0-9_-]{43}", value) + assert value not in KNOWN_EXAMPLE_SECRETS + assert seeded_secret_factory("other")() != values[0] diff --git a/tests/test_generation/test_filemodes.py b/tests/test_generation/test_filemodes.py new file mode 100644 index 00000000..8eda8404 --- /dev/null +++ b/tests/test_generation/test_filemodes.py @@ -0,0 +1,130 @@ +# -------------------------------------------------------------------------- +# Testcases of executable bits on generated files. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import stat +from pathlib import Path + +import pytest + +from fastapi_fastkit.core.settings import FastkitConfig +from fastapi_fastkit.generation import GenerationSpec, ProjectInfo, generate +from fastapi_fastkit.utils.filemodes import is_executable_path, mark_executable +from fastapi_fastkit.utils.platform import is_windows + +posix_only = pytest.mark.skipif(is_windows(), reason="POSIX file modes") + + +def _mode(path: Path) -> int: + return stat.S_IMODE(path.stat().st_mode) + + +@pytest.mark.parametrize( + ("relpath", "expected"), + [ + ("scripts/test.sh", True), + ("scripts\\lint.sh", True), + ("run.sh", True), + ("scripts/test.sh.bak", False), + ("README.md", False), + ("Makefile", False), + ], +) +def test_is_executable_path(relpath: str, expected: bool) -> None: + assert is_executable_path(relpath) is expected + + +@posix_only +@pytest.mark.parametrize( + ("before", "after"), + [(0o644, 0o755), (0o600, 0o700), (0o640, 0o750), (0o200, 0o200)], +) +def test_mark_executable_adds_x_only_where_r_is_set( + tmp_path: Path, before: int, after: int +) -> None: + # given + target = tmp_path / "script.sh" + target.write_text("echo hi\n") + target.chmod(before) + + # when + mark_executable(target) + + # then + assert _mode(target) == after + + +def _templates_with_scripts() -> list[str]: + root = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + return sorted( + d.name for d in root.iterdir() if d.is_dir() and any(d.glob("scripts/*.sh-tpl")) + ) + + +def test_some_templates_ship_scripts() -> None: + assert _templates_with_scripts() + + +@posix_only +@pytest.mark.parametrize("template", _templates_with_scripts()) +def test_generated_template_scripts_are_executable( + template: str, tmp_path: Path +) -> None: + # when + result = generate( + GenerationSpec(project=ProjectInfo(name="modes"), template=template), + tmp_path / "modes", + ) + + # then + scripts = sorted((tmp_path / "modes" / "scripts").glob("*.sh")) + assert scripts + for script in scripts: + assert os.access(script, os.X_OK), script + assert not os.access(tmp_path / "modes" / "README.md", os.X_OK) + assert "scripts/test.sh" in result.files + + +@posix_only +def test_overlay_migrate_script_is_executable(tmp_path: Path) -> None: + # when + generate( + GenerationSpec( + project=ProjectInfo(name="migrations"), + template="fastapi-domain-starter", + preset="domain-starter", + features={"database": "PostgreSQL", "migrations": "Alembic"}, + dependency_files="generated", + ), + tmp_path / "migrations", + ) + + # then + assert os.access(tmp_path / "migrations" / "scripts" / "migrate.sh", os.X_OK) + + +@posix_only +def test_template_file_mode_does_not_leak(tmp_path: Path) -> None: + """A non-script file that is 0755 in the template is not executable.""" + # given + root = tmp_path / "templates" + template = root / "tiny" + template.mkdir(parents=True) + (template / "pyproject.toml-tpl").write_text( + '[project]\nname = ""\nversion = "0.1.0"\n' + 'dependencies = ["fastapi"]\n' + ) + (template / "main.py-tpl").write_text("app = None\n") + (template / "main.py-tpl").chmod(0o755) + + # when + generate( + GenerationSpec(project=ProjectInfo(name="tiny"), template="tiny"), + tmp_path / "out", + template_root=str(root), + ) + + # then + assert not os.access(tmp_path / "out" / "main.py", os.X_OK) diff --git a/tests/test_generation/test_messages.py b/tests/test_generation/test_messages.py new file mode 100644 index 00000000..75e74c8c --- /dev/null +++ b/tests/test_generation/test_messages.py @@ -0,0 +1,94 @@ +# -------------------------------------------------------------------------- +# Testcases of the message sink (print_* helpers captured as data). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from io import StringIO + +import pytest +from rich.console import Console + +from fastapi_fastkit.utils.main import ( + handle_exception, + print_error, + print_info, + print_success, + print_warning, +) +from fastapi_fastkit.utils.messages import ( + Message, + capture_messages, + emit, + is_capturing, +) + + +def _console() -> Console: + return Console(file=StringIO(), width=80) + + +def test_print_helpers_are_recorded_instead_of_printed() -> None: + # given + console = _console() + + # when + with capture_messages() as messages: + print_info("an info", console=console) + print_success("done", title="Custom", console=console) + print_warning("careful", console=console) + print_error("broken", console=console) + + # then + assert console.file.getvalue() == "" # type: ignore[attr-defined] + assert messages == [ + Message("info", "an info", "Info"), + Message("success", "done", "Custom"), + Message("warning", "careful", "Warning"), + Message("error", "broken", "Error"), + ] + + +def test_handle_exception_is_captured_through_print_error() -> None: + with capture_messages() as messages: + handle_exception(RuntimeError("x"), "Failed to do it") + + assert messages == [Message("error", "Failed to do it", "Error")] + + +def test_captures_nest_and_the_inner_one_wins() -> None: + with capture_messages() as outer: + print_info("outer 1") + with capture_messages() as inner: + print_info("inner") + print_info("outer 2") + + assert [m.text for m in outer] == ["outer 1", "outer 2"] + assert [m.text for m in inner] == ["inner"] + + +def test_outside_a_capture_the_console_is_used() -> None: + # given + console = _console() + + # when + print_info("visible", console=console) + + # then + assert "visible" in console.file.getvalue() # type: ignore[attr-defined] + assert emit("info", "nobody listens", "Info") is False + assert is_capturing() is False + + +def test_capture_state_is_restored_after_an_exception() -> None: + with pytest.raises(RuntimeError): + with capture_messages(): + assert is_capturing() is True + raise RuntimeError("boom") + + assert is_capturing() is False + + +def test_unknown_level_is_rejected() -> None: + with capture_messages(): + with pytest.raises(ValueError, match="Unknown message level"): + emit("debug", "text", "Title") diff --git a/tests/test_generation/test_no_side_effects.py b/tests/test_generation/test_no_side_effects.py new file mode 100644 index 00000000..b55ebc45 --- /dev/null +++ b/tests/test_generation/test_no_side_effects.py @@ -0,0 +1,184 @@ +# -------------------------------------------------------------------------- +# generate() runs without subprocesses, tool lookups, prompts, console +# output or network access. +# +# Every such entry point is replaced by a function that fails the test, and +# generation is run for every template, every preset with two feature-rich +# selections, every stack list and every package manager. A second test +# checks statically that the generation package does not import click, rich +# or subprocess itself. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +import os +import shutil +import socket +import subprocess +import tomllib +import urllib.request +from pathlib import Path +from typing import Any, Dict, List + +import click +import pytest +import rich.console + +import fastapi_fastkit.generation as generation_package +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, +) +from fastapi_fastkit.core.settings import FastkitConfig +from fastapi_fastkit.generation import GenerationSpec, ProjectInfo, generate + +MANAGERS = ["pip", "uv", "pdm", "poetry"] + +RICH_FEATURES: Dict[str, Any] = { + "database": "SQLite", + "authentication": "JWT", + "testing": "Coverage", + "migrations": "Alembic", + "logging": "structured", + "tooling": ("ruff", "pre-commit", "github-actions", "makefile", "devcontainer"), + "deployment": ("Docker", "docker-compose"), +} + +SERVICE_FEATURES: Dict[str, Any] = { + "database": "PostgreSQL", + "async_tasks": "Celery", + "caching": "Redis", + "monitoring": "Prometheus", + "testing": "Basic", +} + + +def _forbidden(name: str) -> Any: + def fail(*args: Any, **kwargs: Any) -> Any: + raise AssertionError(f"generate() must not call {name}") + + return fail + + +@pytest.fixture(autouse=True) +def forbid_side_effects(monkeypatch: pytest.MonkeyPatch) -> None: + for module, names in ( + (subprocess, ("run", "Popen", "call", "check_call", "check_output")), + (shutil, ("which",)), + (os, ("system",)), + (click, ("echo", "secho", "prompt", "confirm")), + (urllib.request, ("urlopen",)), + ): + for name in names: + monkeypatch.setattr(module, name, _forbidden(f"{module.__name__}.{name}")) + for name in ("print", "input", "status"): + monkeypatch.setattr(rich.console.Console, name, _forbidden(f"Console.{name}")) + monkeypatch.setattr(socket.socket, "connect", _forbidden("socket.connect")) + + +def _templates() -> List[str]: + root = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + return sorted( + d.name for d in root.iterdir() if (d / "pyproject.toml-tpl").is_file() + ) + + +def _check(result: Any) -> None: + assert result.files + assert result.messages + tomllib.loads(Path(result.project_dir, "pyproject.toml").read_text("utf-8")) + + +@pytest.mark.parametrize("template", _templates()) +def test_template_mode(template: str, tmp_path: Path) -> None: + spec = GenerationSpec(ProjectInfo("side-effects", "me", "me@example.com"), template) + + _check(generate(spec, tmp_path / "p")) + + +@pytest.mark.parametrize("features", [RICH_FEATURES, SERVICE_FEATURES]) +@pytest.mark.parametrize("preset", PresetLayoutStrategist.supported_presets()) +def test_features_mode(preset: str, features: Dict[str, Any], tmp_path: Path) -> None: + spec = GenerationSpec( + ProjectInfo("side-effects"), + PresetLayoutStrategist(preset).base_template, + preset=preset, + features=features, + dependency_files="generated", + ) + + _check(generate(spec, tmp_path / "p")) + + +@pytest.mark.parametrize("stack", sorted(FastkitConfig.PROJECT_STACKS)) +def test_stack_mode(stack: str, tmp_path: Path) -> None: + spec = GenerationSpec( + ProjectInfo("side-effects"), + "fastapi-empty", + dependency_files="generated", + extra_dependencies=tuple(FastkitConfig.PROJECT_STACKS[stack]), + ) + + _check(generate(spec, tmp_path / "p")) + + +@pytest.mark.parametrize("manager", MANAGERS) +def test_every_package_manager(manager: str, tmp_path: Path) -> None: + features = generate( + GenerationSpec( + ProjectInfo("side-effects"), + "fastapi-domain-starter", + preset="domain-starter", + features=RICH_FEATURES, + dependency_files="generated", + package_manager=manager, + ), + tmp_path / "features", + ) + stack = generate( + GenerationSpec( + ProjectInfo("side-effects"), + "fastapi-empty", + dependency_files="generated", + package_manager=manager, + extra_dependencies=tuple(FastkitConfig.PROJECT_STACKS["full"]), + ), + tmp_path / "stack", + ) + template = generate( + GenerationSpec( + ProjectInfo("side-effects"), "fastapi-default", package_manager=manager + ), + tmp_path / "template", + ) + + for result in (features, stack, template): + _check(result) + assert result.metadata["package_manager"] == manager + + +def test_generation_package_imports_no_click_rich_or_subprocess() -> None: + package_dir = Path(generation_package.__file__).parent + forbidden = {"click", "rich", "subprocess"} + offenders = [] + for path in sorted(package_dir.glob("*.py")): + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.level == 0: + names = [node.module or ""] + else: + continue + for name in names: + if name.split(".")[0] in forbidden: + offenders.append(f"{path.name}: {name}") + assert offenders == [] + assert len(list(package_dir.glob("*.py"))) >= 6 + + +def test_the_guard_catches_a_tool_probe(tmp_path: Path) -> None: + """Sanity check: probing an installed tool trips the fixture.""" + from fastapi_fastkit.backend.package_managers import UvManager + + with pytest.raises(AssertionError, match="must not call"): + UvManager(str(tmp_path)).is_available() diff --git a/tests/test_generation/test_pipeline.py b/tests/test_generation/test_pipeline.py new file mode 100644 index 00000000..e1970881 --- /dev/null +++ b/tests/test_generation/test_pipeline.py @@ -0,0 +1,387 @@ +# -------------------------------------------------------------------------- +# Testcases of generate() and plan(). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import tomllib +from pathlib import Path +from typing import Set +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.catalog import load_catalog +from fastapi_fastkit.generation import ( + GenerationError, + GenerationSpec, + ProjectInfo, + SpecError, + generate, + plan, + seeded_secret_factory, +) +from fastapi_fastkit.utils.messages import Message + + +def _tree(root: Path) -> Set[str]: + return {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()} + + +def _features_spec(**overrides: object) -> GenerationSpec: + values = dict( + project=ProjectInfo("shop", "me", "me@example.com", "a shop"), + template="fastapi-domain-starter", + preset="domain-starter", + features={ + "database": "SQLite", + "authentication": "JWT", + "testing": "Basic", + "tooling": ("ruff", "makefile"), + "deployment": ("Docker",), + }, + dependency_files="generated", + package_manager="uv", + ) + values.update(overrides) + return GenerationSpec(**values) # type: ignore[arg-type] + + +def test_files_match_the_tree_for_a_fresh_directory(tmp_path: Path) -> None: + # given + target = tmp_path / "shop" + + # when + result = generate(_features_spec(), target) + + # then + assert result.project_dir == str(target) + assert set(result.files) == _tree(target) + assert list(result.files) == sorted(result.files) + assert result.template == "fastapi-domain-starter" + assert result.preset == "domain-starter" + assert result.app_module == "src.app.main:app" + assert result.metadata["package_manager"] == "uv" + assert "database:SQLite" in result.metadata["features"] + assert "pytest" in result.dependencies.dev + assert "fastapi" in result.dependencies.runtime + assert {"requirements.txt", "requirements-dev.txt", ".env"} <= set(result.files) + pyproject = tomllib.loads((target / "pyproject.toml").read_text()) + assert pyproject["tool"]["fastapi-fastkit"]["preset"] == "domain-starter" + assert all(isinstance(m, Message) for m in result.messages) + + +def test_template_mode_keeps_the_template_dependency_files(tmp_path: Path) -> None: + # when + result = generate( + GenerationSpec(ProjectInfo("hello"), "fastapi-hello"), tmp_path / "hello" + ) + + # then + assert "requirements-dev.txt" not in result.files + assert result.metadata["features"] == [] + assert "preset" not in result.metadata + assert result.app_module == "main:app" + assert set(result.files) == _tree(tmp_path / "hello") + + +def test_stack_mode_writes_a_dev_requirements_file(tmp_path: Path) -> None: + # when + result = generate( + GenerationSpec( + ProjectInfo("stack"), + "fastapi-empty", + dependency_files="generated", + package_manager="pip", + extra_dependencies=("fastapi", "uvicorn", "pytest"), + ), + tmp_path / "stack", + ) + + # then + project = tmp_path / "stack" + assert (project / "requirements.txt").read_text().splitlines() == [ + "fastapi", + "uvicorn", + ] + dev_lines = (project / "requirements-dev.txt").read_text().splitlines() + assert dev_lines[0] == "-r requirements.txt" + assert "pytest>=9.1.1" in dev_lines # the template's pinned entry wins + assert result.dependencies.dev == ("pytest",) + + +def test_generation_into_an_existing_directory_keeps_env_and_other_files( + tmp_path: Path, +) -> None: + # given + target = tmp_path / "shop" + target.mkdir() + (target / ".env").write_text("SECRET_KEY=mine\n") + (target / "NOTES.txt").write_text("keep") + + # when + result = generate(_features_spec(), target) + + # then + assert (target / ".env").read_text() == "SECRET_KEY=mine\n" + assert (target / "NOTES.txt").read_text() == "keep" + assert ".env" not in result.files + assert "NOTES.txt" not in result.files + assert any("Keeping the existing .env" in m.text for m in result.messages) + + +def test_generating_twice_into_the_same_directory_works(tmp_path: Path) -> None: + target = tmp_path / "again" + generate(_features_spec(), target) + + result = generate(_features_spec(), target) + + assert (target / "pyproject.toml").is_file() + assert tomllib.loads((target / "pyproject.toml").read_text()) + assert ".env" not in result.files + + +@pytest.mark.parametrize( + ("spec", "error"), + [ + (GenerationSpec(ProjectInfo("p"), "no-such-template"), "does not exist"), + ( + GenerationSpec(ProjectInfo("p"), "fastapi-default", package_manager="npm"), + "Unknown package manager", + ), + ( + _features_spec(features={"authentication": "Kerberos"}), + "Unknown 'authentication' option", + ), + ( + _features_spec(features={"authentication": "FastAPI-Users"}), + "FastAPI-Users", + ), + ], +) +def test_invalid_specs_fail_before_anything_is_written( + tmp_path: Path, spec: GenerationSpec, error: str +) -> None: + # given + target = tmp_path / "never" + + # when / then + with pytest.raises(SpecError, match=error): + generate(spec, target) + assert not target.exists() + + +def test_step_failure_keeps_messages_and_the_directory(tmp_path: Path) -> None: + # given + target = tmp_path / "broken" + + # when + with patch( + "fastapi_fastkit.generation.pipeline.write_fastkit_metadata", + side_effect=OSError("disk full"), + ): + with pytest.raises(GenerationError, match="disk full") as excinfo: + generate(_features_spec(), target) + + # then: no rollback, and what was emitted before the failure is kept + assert target.is_dir() + assert (target / "pyproject.toml").is_file() + texts = [m.text for m in excinfo.value.messages] + assert "Project metadata injected successfully" in texts + assert isinstance(excinfo.value.__cause__, OSError) + + +def test_seeded_secret_factory_is_used_for_env(tmp_path: Path) -> None: + # given + expected = seeded_secret_factory("x")() + + # when + generate( + _features_spec(), + tmp_path / "seeded", + secret_factory=seeded_secret_factory("x"), + ) + + # then + env = (tmp_path / "seeded" / ".env").read_text() + assert f"SECRET_KEY={expected}" in env.splitlines() + + +def test_target_dir_accepts_a_path_and_is_made_absolute( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.chdir(tmp_path) + + result = generate(GenerationSpec(ProjectInfo("rel"), "fastapi-hello"), "rel") + + assert result.project_dir == os.path.join(str(tmp_path), "rel") + + +# ----------------------------------------------------------------------- plan + + +def test_plan_writes_nothing_and_lists_requirements_dev(tmp_path: Path) -> None: + # given + target = tmp_path / "planned" + + # when + planned = plan(_features_spec(), target) + + # then + assert not target.exists() + assert os.listdir(tmp_path) == [] + assert "requirements-dev.txt" in planned.files + assert "pyproject.toml" in planned.files + assert ".env" in planned.files + assert "Dockerfile" in planned.files and ".dockerignore" in planned.files + assert planned.app_module == "src.app.main:app" + assert planned.metadata["preset"] == "domain-starter" + assert "pytest" in planned.dependencies.dev + + +def test_plan_matches_what_generate_writes(tmp_path: Path) -> None: + # given + spec = _features_spec() + + # when + planned = plan(spec, tmp_path / "p") + result = generate(spec, tmp_path / "p") + + # then + assert set(planned.files) <= _tree(tmp_path / "p") + assert planned.dependencies == result.dependencies + assert dict(planned.metadata) == dict(result.metadata) + + +_TEMPLATE_IDS = [template.id for template in load_catalog().templates] + +_RICH_FEATURES = { + "database": "PostgreSQL", + "authentication": "JWT", + "async_tasks": "Celery", + "testing": "Coverage", + "caching": "Redis", + "monitoring": "Prometheus", + "migrations": "Alembic", + "logging": "structured", + "tooling": ("ruff", "pre-commit", "github-actions", "makefile", "devcontainer"), + "deployment": ("Docker", "docker-compose"), +} + + +def _assert_plan_lists_exactly_what_generate_writes( + spec: GenerationSpec, target: Path +) -> None: + planned = plan(spec, target) + result = generate(spec, target) + + assert planned.files == result.files + assert set(result.files) == _tree(target) + + +@pytest.mark.parametrize("template", _TEMPLATE_IDS) +def test_plan_files_equal_generate_files_for_every_template( + tmp_path: Path, template: str +) -> None: + """The dry-run tree of ``startdemo`` is the tree a real run writes.""" + spec = GenerationSpec(ProjectInfo("demo"), template) + + _assert_plan_lists_exactly_what_generate_writes(spec, tmp_path / "demo") + + +@pytest.mark.parametrize( + "preset, template", + [ + ("minimal", "fastapi-empty"), + ("single-module", "fastapi-single-module"), + ("classic-layered", "fastapi-default"), + ("domain-starter", "fastapi-domain-starter"), + ], +) +@pytest.mark.parametrize("package_manager", ["pip", "uv", "pdm", "poetry"]) +def test_plan_files_equal_generate_files_in_features_mode( + tmp_path: Path, preset: str, template: str, package_manager: str +) -> None: + spec = GenerationSpec( + ProjectInfo("demo"), + template, + preset=preset, + features=_RICH_FEATURES, + dependency_files="generated", + package_manager=package_manager, + ) + + _assert_plan_lists_exactly_what_generate_writes(spec, tmp_path / "demo") + + +def test_plan_files_equal_generate_files_in_stack_mode(tmp_path: Path) -> None: + spec = GenerationSpec( + ProjectInfo("demo"), + "fastapi-default", + dependency_files="generated", + package_manager="pip", + extra_dependencies=("fastapi", "uvicorn", "pytest"), + ) + + _assert_plan_lists_exactly_what_generate_writes(spec, tmp_path / "demo") + + +def test_plan_leaves_out_template_only_files(tmp_path: Path) -> None: + """``template-config.yml`` drives inspection and is never written.""" + planned = plan(GenerationSpec(ProjectInfo("p"), "fastapi-sqlmodel"), tmp_path) + + assert "template-config.yml" not in planned.files + assert not any(path.endswith("/template-config.yml") for path in planned.files) + + +@pytest.mark.parametrize("package_manager", ["pip", "uv", "pdm", "poetry"]) +def test_ci_lint_step_relies_on_ruff_from_the_dev_requirements( + tmp_path: Path, package_manager: str +) -> None: + """The workflow installs requirements-dev.txt, which carries ruff.""" + # given + spec = _features_spec( + features={"tooling": ("ruff", "github-actions")}, + package_manager=package_manager, + ) + + # when + generate(spec, tmp_path / "p") + + # then + workflow = (tmp_path / "p" / ".github" / "workflows" / "test.yml").read_text() + dev_requirements = (tmp_path / "p" / "requirements-dev.txt").read_text() + assert "ruff" in dev_requirements.splitlines() + assert "pip install -r requirements-dev.txt" in workflow + assert "pip install ruff" not in workflow + assert workflow.index("requirements-dev.txt") < workflow.index("ruff check .") + + +def test_plan_template_mode_has_no_requirements_dev(tmp_path: Path) -> None: + planned = plan(GenerationSpec(ProjectInfo("p"), "fastapi-default"), tmp_path / "p") + + assert "requirements-dev.txt" not in planned.files + assert "requirements.txt" in planned.files + + +def test_plan_does_not_list_env_when_the_target_has_one(tmp_path: Path) -> None: + (tmp_path / ".env").write_text("X=1\n") + + planned = plan(GenerationSpec(ProjectInfo("p"), "fastapi-default"), tmp_path) + + assert ".env" not in planned.files + assert ".env.example" in planned.files + + +def test_plan_rejects_an_invalid_spec(tmp_path: Path) -> None: + with pytest.raises(SpecError): + plan(GenerationSpec(ProjectInfo("p"), "nope"), tmp_path) + + +def test_plan_wraps_unexpected_errors(tmp_path: Path) -> None: + with patch( + "fastapi_fastkit.generation.pipeline.resolve_dependencies", + side_effect=RuntimeError("catalog broke"), + ): + with pytest.raises(GenerationError, match="catalog broke"): + plan(GenerationSpec(ProjectInfo("p"), "fastapi-default"), tmp_path) diff --git a/tests/test_generation/test_spec.py b/tests/test_generation/test_spec.py new file mode 100644 index 00000000..cb6e626e --- /dev/null +++ b/tests/test_generation/test_spec.py @@ -0,0 +1,334 @@ +# -------------------------------------------------------------------------- +# Testcases of the generation spec and spec_from_config. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +from pathlib import Path +from typing import Any, Dict + +import pytest + +from fastapi_fastkit.backend.project_builder.config_schema import ( + normalize_project_config, +) +from fastapi_fastkit.core.settings import FastkitConfig +from fastapi_fastkit.generation import ( + GenerationSpec, + ProjectInfo, + SpecError, + generate, + spec_from_config, +) +from fastapi_fastkit.generation.spec import feature_keys, validate_spec + +TEMPLATE_ROOT = FastkitConfig().FASTKIT_TEMPLATE_ROOT + +INTERACTIVE_CONFIG: Dict[str, Any] = { + "project_name": "shop", + "author": "me", + "author_email": "me@example.com", + "description": "a shop", + "architecture_preset": "classic-layered", + "architecture_preset_description": "Layered split", + "base_template": None, + "database": {"type": "PostgreSQL", "packages": ["asyncpg"]}, + "authentication": "JWT", + "async_tasks": "None", + "caching": "None", + "monitoring": "None", + "testing": "Basic", + "utilities": ["CORS"], + "migrations": "Alembic", + "tooling": ["ruff", "makefile"], + "logging": "structured", + "deployment": ["docker-compose"], + "package_manager": "pdm", + "custom_packages": ["orjson", "", "orjson"], +} + + +def test_mode_follows_features_and_dependency_files() -> None: + project = ProjectInfo(name="p") + assert GenerationSpec(project, "fastapi-default").mode == "template" + assert ( + GenerationSpec(project, "fastapi-empty", dependency_files="generated").mode + == "stack" + ) + assert GenerationSpec(project, "fastapi-empty", features={}).mode == "features" + + +def test_spec_from_an_interactive_config() -> None: + # when + spec = spec_from_config(INTERACTIVE_CONFIG) + + # then + assert spec.project == ProjectInfo("shop", "me", "me@example.com", "a shop") + assert spec.preset == "classic-layered" + assert spec.template == "fastapi-default" + assert spec.package_manager == "pdm" + assert spec.dependency_files == "generated" + assert spec.mode == "features" + assert spec.custom_packages == ("orjson",) + assert spec.extra_dependencies == () + features = dict(spec.features or {}) + assert features["database"] == "PostgreSQL" + assert features["authentication"] == "JWT" + assert features["utilities"] == ("CORS",) + assert features["tooling"] == ("ruff", "makefile") + # compose implies Docker, inserted first + assert features["deployment"] == ("Docker", "docker-compose") + assert set(features) == set(feature_keys()) + + +def test_hand_written_minimal_config_defaults_to_the_minimal_preset() -> None: + # when + spec = spec_from_config({"project_name": "tiny", "testing": "Basic"}) + + # then + assert spec.preset == "minimal" + assert spec.template == "fastapi-empty" + assert spec.package_manager == FastkitConfig.DEFAULT_PACKAGE_MANAGER + assert spec.project.author == "" + assert dict(spec.features or {})["testing"] == "Basic" + assert dict(spec.features or {})["database"] == "None" + + +def test_saved_1x_config_keeps_only_unexplained_dependencies() -> None: + # given: a --save-config file written by fastkit 1.x + config = dict( + INTERACTIVE_CONFIG, + version="0.1.0", + base_template="fastapi-default", + custom_packages=[], + all_dependencies=[ + "fastapi", + "uvicorn", + "pydantic", + "pydantic-settings", + "asyncpg", + "sqlalchemy[asyncio]", + "pyjwt[crypto]", + "pytest", + "motor", + "redis", + ], + ) + + # when + spec = spec_from_config(config) + + # then: catalog-derived entries are dropped, hand-added ones are kept + assert spec.extra_dependencies == ("motor", "redis") + + +def test_saved_1x_pins_and_extras_win_over_derived_entries() -> None: + """As 1.x merged ``all_dependencies`` with the derived set, a saved pin or + extra replaces the bare derived requirement (runtime or dev by name).""" + from fastapi_fastkit.generation.dependencies import resolve_dependencies + + # given + config = dict( + INTERACTIVE_CONFIG, + all_dependencies=[ + "fastapi==0.99.0", + "uvicorn[standard]>=0.20", + "pytest>=8", + "sqlalchemy", + "pydantic", + " ", + "fastapi==0.99.0", + ], + ) + + # when + spec = spec_from_config(config) + deps = resolve_dependencies(spec, TEMPLATE_ROOT) + + # then: entries the selection explains as written are still dropped + assert spec.extra_dependencies == ( + "fastapi==0.99.0", + "uvicorn[standard]>=0.20", + "pytest>=8", + ) + assert "fastapi==0.99.0" in deps.runtime and "fastapi" not in deps.runtime + assert "uvicorn[standard]>=0.20" in deps.runtime + assert "uvicorn" not in deps.runtime + assert "pytest>=8" in deps.dev and "pytest" not in deps.dev + + +@pytest.mark.parametrize( + "value, expected", + [("2.3.4", "2.3.4"), (2, "2"), (None, ""), ("", "")], +) +def test_config_version_becomes_the_project_version(value: Any, expected: str) -> None: + config = {"project_name": "p", "preset": "minimal"} + if value is not None: + config["version"] = value + + spec = spec_from_config(config) + + assert spec.project.version == expected + assert spec.to_config().get("version") == (expected or None) + + +@pytest.mark.parametrize("version, rendered", [("2.3.4", "2.3.4"), (None, "0.1.0")]) +def test_config_version_reaches_the_regenerated_main_py( + tmp_path: Path, version: Any, rendered: str +) -> None: + """As in 1.x, a config's ``version`` is the app version of ``main.py``.""" + # given: a preset whose main.py is regenerated by the feature overlay + config: Dict[str, Any] = {"project_name": "p", "preset": "minimal"} + if version is not None: + config["version"] = version + + # when + generate(spec_from_config(config), tmp_path / "p") + + # then + main = (tmp_path / "p" / "src" / "main.py").read_text(encoding="utf-8") + assert f'version="{rendered}"' in main + + +def test_legacy_dependencies_argument_wins_over_the_config() -> None: + spec = spec_from_config( + dict(INTERACTIVE_CONFIG, all_dependencies=["motor"]), + legacy_dependencies=["fastapi", "httpie"], + ) + + assert spec.extra_dependencies == ("httpie",) + + +def test_preset_alias_and_overrides() -> None: + # given + config = {"project_name": "p", "preset": "single-module", "package_manager": "uv"} + + # when + aliased = spec_from_config(config) + overridden = spec_from_config( + config, + package_manager="poetry", + preset="domain-starter", + template="fastapi-default", + ) + + # then + assert aliased.preset == "single-module" + assert aliased.template == "fastapi-single-module" + assert aliased.package_manager == "uv" + assert overridden.preset == "domain-starter" + assert overridden.template == "fastapi-default" + assert overridden.package_manager == "poetry" + + +def test_missing_project_name_is_a_spec_error() -> None: + with pytest.raises(SpecError, match="project_name"): + spec_from_config({"testing": "Basic"}) + + +def test_invalid_config_is_a_spec_error() -> None: + with pytest.raises(SpecError, match="Unknown 'database' option"): + spec_from_config({"project_name": "p", "database": "Oracle"}) + + +def test_to_config_round_trip_is_idempotent() -> None: + # given + spec = spec_from_config(INTERACTIVE_CONFIG) + + # when + config = spec.to_config() + + # then + assert normalize_project_config(config) == config + assert spec_from_config(config) == spec + assert config["database"]["type"] == "PostgreSQL" + assert config["architecture_preset"] == "classic-layered" + assert config["deployment"] == ["Docker", "docker-compose"] + + +def test_to_config_accepts_a_bare_string_for_a_multi_axis() -> None: + spec = GenerationSpec( + ProjectInfo("p"), "fastapi-empty", features={"tooling": "ruff"} + ) + + assert spec.to_config()["tooling"] == ["ruff"] + + +@pytest.mark.parametrize( + ("spec", "message"), + [ + (GenerationSpec(ProjectInfo(""), "fastapi-default"), "project name"), + ( + GenerationSpec(ProjectInfo("p"), "fastapi-default", package_manager="npm"), + "Unknown package manager", + ), + (GenerationSpec(ProjectInfo("p"), "no-such-template"), "does not exist"), + ( + GenerationSpec(ProjectInfo("p"), "fastapi-empty", features={"colour": "x"}), + "Unknown feature key", + ), + ( + GenerationSpec(ProjectInfo("p"), "fastapi-empty", preset="huge"), + "Unknown architecture preset", + ), + ( + GenerationSpec( + ProjectInfo("p"), "fastapi-empty", features={"database": "Oracle"} + ), + "Unknown 'database' option", + ), + ], +) +def test_validate_spec_rejects(spec: GenerationSpec, message: str) -> None: + with pytest.raises(SpecError, match=message): + validate_spec(spec, TEMPLATE_ROOT) + + +@pytest.mark.parametrize( + "template", ["../outside", "OUTSIDE", "root/inner", ".hidden", "__pycache__"] +) +def test_validate_spec_accepts_only_a_template_directory_name( + tmp_path: Path, template: str +) -> None: + """Like ``startdemo``, only a direct, listed child of the root is a template.""" + root = tmp_path / "root" + for directory in ("inner", ".hidden", "__pycache__"): + (root / directory).mkdir(parents=True) + (tmp_path / "outside").mkdir() + if template == "OUTSIDE": + template = str(tmp_path / "outside") # an absolute path + elif template == "root/inner": + template = os.path.join("..", "root", "inner") + + with pytest.raises(SpecError, match="does not exist"): + validate_spec(GenerationSpec(ProjectInfo("p"), template), str(root)) + + +def test_validate_spec_and_startdemo_agree_on_template_names() -> None: + from fastapi_fastkit.cli import available_templates + from fastapi_fastkit.generation.spec import is_template_name + + names = sorted(os.listdir(TEMPLATE_ROOT)) + + assert [n for n in names if is_template_name(TEMPLATE_ROOT, n)] == sorted( + available_templates(TEMPLATE_ROOT) + ) + assert not is_template_name(TEMPLATE_ROOT, "modules") + + +def test_app_module_falls_back_to_the_preset_without_a_template_main( + tmp_path: Path, +) -> None: + from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, + ) + from fastapi_fastkit.generation.metadata import ( + app_module_for, + template_main_relpath, + ) + + (tmp_path / "README.md-tpl").write_text("# x\n") + + assert template_main_relpath(str(tmp_path)) == "" + strategist = PresetLayoutStrategist("domain-starter") + assert app_module_for(str(tmp_path), strategist) == strategist.app_module diff --git a/tests/test_generation/test_target_safety.py b/tests/test_generation/test_target_safety.py new file mode 100644 index 00000000..bda6beb6 --- /dev/null +++ b/tests/test_generation/test_target_safety.py @@ -0,0 +1,245 @@ +# -------------------------------------------------------------------------- +# Testcases of generate() in a directory that already has content: symlinks +# are never written through and an existing .env is never replaced. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import shutil +from pathlib import Path +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.core.settings import settings +from fastapi_fastkit.generation import ( + GenerationError, + GenerationSpec, + ProjectInfo, + generate, + plan, +) +from fastapi_fastkit.generation.pipeline import symlinked_targets + + +def _symlink(target: Path, link: Path, *, directory: bool = False) -> None: + try: + os.symlink(target, link, target_is_directory=directory) + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + + +def _hello() -> GenerationSpec: + return GenerationSpec(ProjectInfo("hello"), "fastapi-hello") + + +def test_a_symlinked_destination_file_is_refused(tmp_path: Path) -> None: + # given + target = tmp_path / "p" + target.mkdir() + outside = tmp_path / "outside.md" + outside.write_text("keep\n") + _symlink(outside, target / "README.md") + + # when + with pytest.raises(GenerationError, match="README.md"): + generate(_hello(), target) + + # then: refused before anything was written + assert outside.read_text() == "keep\n" + assert [p.name for p in target.iterdir()] == ["README.md"] + + +def test_a_dangling_symlink_is_refused(tmp_path: Path) -> None: + target = tmp_path / "p" + target.mkdir() + _symlink(tmp_path / "nowhere.py", target / "main.py") + + with pytest.raises(GenerationError, match="main.py"): + generate(_hello(), target) + + assert not (tmp_path / "nowhere.py").exists() + + +def test_a_directory_link_leading_outside_is_refused(tmp_path: Path) -> None: + target = tmp_path / "p" + target.mkdir() + outside = tmp_path / "elsewhere" + outside.mkdir() + _symlink(outside, target / "tests", directory=True) + + with pytest.raises(GenerationError, match="tests"): + generate(_hello(), target) + + assert list(outside.iterdir()) == [] + + +def test_a_directory_link_staying_inside_is_allowed(tmp_path: Path) -> None: + # given + target = tmp_path / "p" + (target / "real-tests").mkdir(parents=True) + _symlink(target / "real-tests", target / "tests", directory=True) + + # when + generate(_hello(), target) + + # then + assert any((target / "real-tests").iterdir()) + + +def test_symlinked_targets_lists_project_relative_paths(tmp_path: Path) -> None: + (tmp_path / "plain.txt").write_text("x") + _symlink(tmp_path / "plain.txt", tmp_path / "link.txt") + + found = symlinked_targets(str(tmp_path), ["plain.txt", "link.txt", "a/b.py"]) + + assert found == ["link.txt"] + + +def _template_root_with_env(tmp_path: Path) -> str: + root = tmp_path / "templates" + shutil.copytree( + os.path.join(settings.FASTKIT_TEMPLATE_ROOT, "fastapi-hello"), + root / "custom-env", + ) + (root / "custom-env" / ".env-tpl").write_text("SECRET_KEY=from-template\n") + return str(root) + + +def test_a_template_env_never_replaces_an_existing_env(tmp_path: Path) -> None: + # given + root = _template_root_with_env(tmp_path) + target = tmp_path / "p" + target.mkdir() + (target / ".env").write_text("SECRET_KEY=mine\n") + spec = GenerationSpec(ProjectInfo("p"), "custom-env") + + # when + planned = plan(spec, target, template_root=root) + result = generate(spec, target, template_root=root) + + # then + assert (target / ".env").read_text() == "SECRET_KEY=mine\n" + assert ".env" not in planned.files + assert ".env" not in result.files + kept = [m.text for m in result.messages if "Keeping the existing .env" in m.text] + assert len(kept) == 1 + + +def test_a_template_env_is_copied_into_a_fresh_directory(tmp_path: Path) -> None: + root = _template_root_with_env(tmp_path) + target = tmp_path / "p" + + result = generate( + GenerationSpec(ProjectInfo("p"), "custom-env"), target, template_root=root + ) + + assert (target / ".env").read_text() == "SECRET_KEY=from-template\n" + assert ".env" in result.files + + +def test_a_linked_core_module_the_template_does_not_ship_is_refused( + tmp_path: Path, +) -> None: + # given: generation rewrites an existing src/main.py even when the + # template ships main.py at the root + target = tmp_path / "p" + (target / "src").mkdir(parents=True) + outside = tmp_path / "main.py" + outside.write_text("app = None\n") + _symlink(outside, target / "src" / "main.py") + + # when + with pytest.raises(GenerationError, match="src/main.py"): + generate(_hello(), target) + + # then + assert outside.read_text() == "app = None\n" + + +def test_an_unrelated_directory_link_is_allowed(tmp_path: Path) -> None: + # given: nothing generation writes lives under ``src`` for this template + target = tmp_path / "p" + target.mkdir() + outside = tmp_path / "elsewhere" + outside.mkdir() + _symlink(outside, target / "src", directory=True) + + # when + generate(_hello(), target) + + # then + assert list(outside.iterdir()) == [] + assert (target / "main.py").is_file() + + +@pytest.mark.parametrize("name", [".ENV-tpl", ".Env"]) +def test_a_differently_cased_template_env_never_replaces_the_env( + tmp_path: Path, name: str +) -> None: + # given: on a case-insensitive file system ``.ENV`` is the user's ``.env`` + root = tmp_path / "templates" + shutil.copytree( + os.path.join(settings.FASTKIT_TEMPLATE_ROOT, "fastapi-hello"), + root / "custom-env", + ) + (root / "custom-env" / name).write_text("SECRET_KEY=from-template\n") + target = tmp_path / "p" + target.mkdir() + (target / ".env").write_text("SECRET_KEY=mine\n") + spec = GenerationSpec(ProjectInfo("p"), "custom-env") + + # when + generate(spec, target, template_root=str(root)) + + # then + assert (target / ".env").read_text() == "SECRET_KEY=mine\n" + + +def _junction(target: Path, link: Path) -> None: + try: + import _winapi + + _winapi.CreateJunction(str(target), str(link)) + except (ImportError, AttributeError, OSError): + pytest.skip("directory junctions are not available") + + +def test_a_junction_leading_outside_is_refused(tmp_path: Path) -> None: + target = tmp_path / "p" + target.mkdir() + outside = tmp_path / "elsewhere" + outside.mkdir() + _junction(outside, target / "tests") + + with pytest.raises(GenerationError, match="tests"): + generate(_hello(), target) + + assert list(outside.iterdir()) == [] + + +def test_symlinked_targets_treats_a_junction_like_a_directory_link( + tmp_path: Path, +) -> None: + # Junctions exist only on Windows; elsewhere the check is simulated. + outside = tmp_path / "elsewhere" + outside.mkdir() + project = tmp_path / "p" + (project / "tests").mkdir(parents=True) + real_realpath = os.path.realpath + + def realpath(path: object, *args: object, **kwargs: object) -> str: + if os.fspath(path) == str(project / "tests"): # type: ignore[arg-type] + return str(outside) + return real_realpath(path, *args, **kwargs) # type: ignore[arg-type] + + with ( + patch( + "fastapi_fastkit.generation.pipeline.os.path.isjunction", + side_effect=lambda path: os.fspath(path) == str(project / "tests"), + ), + patch("os.path.realpath", side_effect=realpath), + ): + found = symlinked_targets(str(project), ["tests/test_main.py", "main.py"]) + + assert found == ["tests"] diff --git a/tests/test_templates/test_generated_pyproject.py b/tests/test_templates/test_generated_pyproject.py index d110e487..dccbe049 100644 --- a/tests/test_templates/test_generated_pyproject.py +++ b/tests/test_templates/test_generated_pyproject.py @@ -164,3 +164,50 @@ def test_config_generation_writes_one_valid_pyproject( assert text.count("[tool.ruff]") == 1 else: assert data["tool"]["black"]["target-version"] == ["py312"] + + +@pytest.mark.parametrize("manager", sorted(_MANAGERS)) +def test_requested_dev_packages_join_the_template_dev_group( + manager: str, tmp_path: Path +) -> None: + """``testing: Basic`` adds its tools to the dev group, never to runtime.""" + # given + config = { + "project_name": "devgroup", + "author": "bnbong", + "author_email": "bbbong9@gmail.com", + "description": "dev group test", + "package_manager": manager, + "preset": "classic-layered", + "testing": "Basic", + } + config_path = tmp_path / "fastkit.config.json" + config_path.write_text(json.dumps(config), encoding="utf-8") + previous = os.getcwd() + os.chdir(tmp_path) + + # when + try: + result = CliRunner().invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + finally: + os.chdir(previous) + + # then + assert result.exit_code == 0, result.output + project = tmp_path / "devgroup" + data = tomllib.loads((project / "pyproject.toml").read_text(encoding="utf-8")) + template_dev = _template_pyproject("fastapi-default")["dependency-groups"]["dev"] + added = ["httpx2", "pytest-asyncio"] + assert "pytest" not in data["project"]["dependencies"] + assert "pytest-asyncio" not in data["project"]["dependencies"] + dev_lines = (project / "requirements-dev.txt").read_text().splitlines() + assert dev_lines == ["-r requirements.txt", *template_dev, *added] + runtime_lines = (project / "requirements.txt").read_text().splitlines() + assert not {"pytest", "pytest-asyncio"} & set(runtime_lines) + if manager in ("uv", "pdm"): + assert data["dependency-groups"]["dev"] == [*template_dev, *added] + if manager == "poetry": + poetry_dev = data["tool"]["poetry"]["group"]["dev"]["dependencies"] + assert set(added) <= set(poetry_dev) diff --git a/tests/test_templates/test_template_requirements_split.py b/tests/test_templates/test_template_requirements_split.py new file mode 100644 index 00000000..29eb2750 --- /dev/null +++ b/tests/test_templates/test_template_requirements_split.py @@ -0,0 +1,98 @@ +# -------------------------------------------------------------------------- +# Templates with a Docker image keep runtime and development requirements +# apart: requirements.txt (installed by the image) holds runtime pins only, +# requirements-dev.txt adds the dev group's tools on top of it. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import re +import tomllib +from pathlib import Path +from typing import Dict, List + +import pytest + +from fastapi_fastkit.core.settings import FastkitConfig + +TEMPLATE_ROOT = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + +TEMPLATES = ["fastapi-sqlmodel", "fastapi-auth-jwt", "fastapi-llm-agent"] + + +def _canonical(name: str) -> str: + return re.sub(r"[-_.]+", "-", name).lower() + + +def _name(requirement: str) -> str: + return _canonical(re.split(r"[<>=!~;\[ ]", requirement.strip(), maxsplit=1)[0]) + + +def _requirement_lines(text: str) -> List[str]: + return [ + line.strip() + for line in text.splitlines() + if line.strip() and not line.lstrip().startswith(("#", "-")) + ] + + +def _pins(text: str) -> Dict[str, str]: + pins: Dict[str, str] = {} + for line in _requirement_lines(text): + assert "==" in line, line + name, version = line.split("==", 1) + pins[_name(name)] = version + return pins + + +def _read(template: str, name: str) -> str: + return (TEMPLATE_ROOT / template / name).read_text(encoding="utf-8") + + +def _pyproject(template: str) -> Dict[str, List[str]]: + data = tomllib.loads(_read(template, "pyproject.toml-tpl")) + return { + "runtime": data["project"]["dependencies"], + "dev": data["dependency-groups"]["dev"], + } + + +@pytest.mark.parametrize("template", TEMPLATES) +def test_requirements_txt_holds_runtime_packages_only(template: str) -> None: + pyproject = _pyproject(template) + pins = _pins(_read(template, "requirements.txt-tpl")) + dev_names = {_name(dep) for dep in pyproject["dev"]} + + assert not dev_names & set(pins) + assert {_name(dep) for dep in pyproject["runtime"]} <= set(pins) + + +@pytest.mark.parametrize("template", TEMPLATES) +def test_requirements_dev_txt_adds_the_dev_group_to_requirements_txt( + template: str, +) -> None: + text = _read(template, "requirements-dev.txt-tpl") + pins = _pins(text) + + assert text.splitlines()[0] == "-r requirements.txt" + assert text.endswith("\n") + for dep in _pyproject(template)["dev"]: + name, floor = dep.split(">=", 1) + assert pins.get(_name(name)) == floor, dep + assert set(pins) == {_name(dep) for dep in _pyproject(template)["dev"]} + + +@pytest.mark.parametrize("template", TEMPLATES) +def test_dockerfile_installs_requirements_txt_only(template: str) -> None: + dockerfile = _read(template, "Dockerfile-tpl") + + assert "COPY requirements.txt ." in dockerfile + assert "pip install --no-cache-dir -r requirements.txt" in dockerfile + assert "requirements-dev" not in dockerfile + + +@pytest.mark.parametrize("template", TEMPLATES) +def test_readme_installs_requirements_dev_txt_for_development(template: str) -> None: + readme = _read(template, "README.md-tpl") + + assert "โ”œโ”€โ”€ requirements-dev.txt\n" in readme + assert "install -r requirements-dev.txt" in readme