From 7073b88ac9ef9de83a07438a82649c88b8c9bb92 Mon Sep 17 00:00:00 2001 From: bnbong Date: Thu, 3 Dec 2026 21:03:21 +0900 Subject: [PATCH 1/2] [FEAT, DOCS] add web generator page, browser generation API and its CI check --- .github/workflows/build-docs.yml | 24 + .github/workflows/labeler.yml | 11 +- .github/workflows/test.yml | 8 +- .github/workflows/web-generator.yml | 77 + .gitignore | 4 + CHANGELOG.md | 5 + README.md | 2 + docs/css/web-generator.css | 698 ++++++++ docs/de/start/web-generator.md | 17 + docs/en/contributing/development-setup.md | 30 + docs/en/index.md | 2 + docs/en/start/web-generator.md | 17 + docs/en/user-guide/installation.md | 2 + docs/es/start/web-generator.md | 17 + docs/fr/start/web-generator.md | 17 + docs/ja/start/web-generator.md | 16 + docs/js/web-generator-core.mjs | 190 +++ docs/js/web-generator-strings/de.json | 74 + docs/js/web-generator-strings/en.json | 74 + docs/js/web-generator-strings/es.json | 74 + docs/js/web-generator-strings/fr.json | 74 + docs/js/web-generator-strings/ja.json | 74 + docs/js/web-generator-strings/ko.json | 74 + docs/js/web-generator-strings/zh.json | 74 + docs/js/web-generator-worker.mjs | 90 + docs/js/web-generator.mjs | 1207 +++++++++++++ docs/ko/start/web-generator.md | 16 + docs/zh/start/web-generator.md | 16 + mkdocs.yml | 8 + pdm.lock | 127 +- pyproject.toml | 8 + scripts/web_generator/build_assets.py | 629 +++++++ scripts/web_generator/check_site.py | 171 ++ scripts/web_generator/compare.py | 240 +++ scripts/web_generator/compare_with_cli.py | 370 ++++ scripts/web_generator/generate.mjs | 134 ++ scripts/web_generator/pyodide.toml | 31 + src/fastapi_fastkit/backend/doctor/known.py | 82 +- .../backend/interactive/validators.py | 163 +- src/fastapi_fastkit/backend/main.py | 15 +- .../backend/package_managers/base.py | 8 +- .../backend/package_managers/pdm_manager.py | 2 +- .../backend/package_managers/pip_manager.py | 2 +- .../package_managers/poetry_manager.py | 6 +- .../backend/package_managers/pyproject.py | 6 +- .../backend/package_managers/uv_manager.py | 2 +- .../project_builder/config_generator.py | 2 +- .../project_builder/dependency_collector.py | 6 +- .../backend/route_generators.py | 3 +- src/fastapi_fastkit/backend/route_wiring.py | 2 +- src/fastapi_fastkit/catalog/i18n/de.toml | 387 +++++ src/fastapi_fastkit/catalog/i18n/es.toml | 387 +++++ src/fastapi_fastkit/catalog/i18n/fr.toml | 387 +++++ src/fastapi_fastkit/catalog/i18n/ja.toml | 387 +++++ src/fastapi_fastkit/catalog/i18n/ko.toml | 387 +++++ src/fastapi_fastkit/catalog/i18n/zh.toml | 387 +++++ src/fastapi_fastkit/core/known.py | 91 + src/fastapi_fastkit/generation/browser.py | 973 +++++++++++ .../generation/dependencies.py | 8 +- src/fastapi_fastkit/generation/levels.py | 34 +- src/fastapi_fastkit/generation/pipeline.py | 2 +- src/fastapi_fastkit/utils/config_file.py | 12 +- src/fastapi_fastkit/utils/logging.py | 8 +- src/fastapi_fastkit/utils/main.py | 149 +- src/fastapi_fastkit/utils/messages.py | 5 +- src/fastapi_fastkit/utils/output.py | 103 ++ src/fastapi_fastkit/utils/project_meta.py | 145 ++ src/fastapi_fastkit/utils/validation.py | 188 +++ tests/fixtures/web_generator/cases.json | 312 ++++ tests/test_catalog/test_i18n.py | 4 +- tests/test_catalog/test_loader.py | 17 +- tests/test_catalog/test_overlays.py | 134 ++ tests/test_docs/__init__.py | 0 tests/test_docs/test_web_generator_page.py | 330 ++++ tests/test_generation/test_browser.py | 1195 +++++++++++++ tests/test_generation/test_browser_parity.py | 201 +++ tests/test_generation/test_import_boundary.py | 279 +++ tests/test_generation/test_levels.py | 66 +- tests/test_scripts/__init__.py | 0 .../test_web_generator_scripts.py | 1499 +++++++++++++++++ tests/test_utils_output.py | 297 ++++ uv.lock | 99 ++ 82 files changed, 13059 insertions(+), 415 deletions(-) create mode 100644 .github/workflows/web-generator.yml create mode 100644 docs/css/web-generator.css create mode 100644 docs/de/start/web-generator.md create mode 100644 docs/en/start/web-generator.md create mode 100644 docs/es/start/web-generator.md create mode 100644 docs/fr/start/web-generator.md create mode 100644 docs/ja/start/web-generator.md create mode 100644 docs/js/web-generator-core.mjs create mode 100644 docs/js/web-generator-strings/de.json create mode 100644 docs/js/web-generator-strings/en.json create mode 100644 docs/js/web-generator-strings/es.json create mode 100644 docs/js/web-generator-strings/fr.json create mode 100644 docs/js/web-generator-strings/ja.json create mode 100644 docs/js/web-generator-strings/ko.json create mode 100644 docs/js/web-generator-strings/zh.json create mode 100644 docs/js/web-generator-worker.mjs create mode 100644 docs/js/web-generator.mjs create mode 100644 docs/ko/start/web-generator.md create mode 100644 docs/zh/start/web-generator.md create mode 100644 scripts/web_generator/build_assets.py create mode 100644 scripts/web_generator/check_site.py create mode 100644 scripts/web_generator/compare.py create mode 100644 scripts/web_generator/compare_with_cli.py create mode 100644 scripts/web_generator/generate.mjs create mode 100644 scripts/web_generator/pyodide.toml create mode 100644 src/fastapi_fastkit/catalog/i18n/de.toml create mode 100644 src/fastapi_fastkit/catalog/i18n/es.toml create mode 100644 src/fastapi_fastkit/catalog/i18n/fr.toml create mode 100644 src/fastapi_fastkit/catalog/i18n/ja.toml create mode 100644 src/fastapi_fastkit/catalog/i18n/ko.toml create mode 100644 src/fastapi_fastkit/catalog/i18n/zh.toml create mode 100644 src/fastapi_fastkit/core/known.py create mode 100644 src/fastapi_fastkit/generation/browser.py create mode 100644 src/fastapi_fastkit/utils/output.py create mode 100644 src/fastapi_fastkit/utils/project_meta.py create mode 100644 src/fastapi_fastkit/utils/validation.py create mode 100644 tests/fixtures/web_generator/cases.json create mode 100644 tests/test_catalog/test_overlays.py create mode 100644 tests/test_docs/__init__.py create mode 100644 tests/test_docs/test_web_generator_page.py create mode 100644 tests/test_generation/test_browser.py create mode 100644 tests/test_generation/test_browser_parity.py create mode 100644 tests/test_generation/test_import_boundary.py create mode 100644 tests/test_scripts/__init__.py create mode 100644 tests/test_scripts/test_web_generator_scripts.py create mode 100644 tests/test_utils_output.py diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index aeda2628..80e6cf6c 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -34,6 +34,30 @@ jobs: - name: Install docs dependencies run: | pip install -r requirements-docs.txt + # Web generator page: assets from this commit's wheel, checked against + # the CLI before anything is deployed. + - uses: actions/setup-node@v4 + with: + node-version: "22" + - uses: actions/cache@v4 + with: + path: .cache/web-generator + key: web-generator-${{ hashFiles('scripts/web_generator/pyodide.toml') }} + - name: Build and install the fastkit wheel + run: | + python -m pip wheel --no-deps -w dist . + python -m pip install dist/fastapi_fastkit-*.whl + - name: Build the web generator assets + run: >- + python scripts/web_generator/build_assets.py + --wheel dist/fastapi_fastkit-*.whl + --out docs/en/assets/fastkit-generator + --commit "$GITHUB_SHA" + - name: Compare web output with the CLI + run: >- + python scripts/web_generator/compare_with_cli.py + --assets docs/en/assets/fastkit-generator + --cases tests/fixtures/web_generator/cases.json - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV - uses: actions/cache@v4 with: diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index e57cd86e..333d5091 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -1,12 +1,19 @@ name: "Pull Request Labeler" on: -- pull_request_target + pull_request: + types: [opened, synchronize, reopened] + +permissions: {} jobs: labeler: + # pull_request_target is blocked on public repositories by GitHub's default + # policy; with pull_request a fork's token cannot write labels, so forks + # are skipped and labelled by hand. + if: github.event.pull_request.head.repo.full_name == github.repository permissions: contents: read pull-requests: write runs-on: ubuntu-latest steps: - - uses: actions/labeler@v5 + - uses: actions/labeler@v6 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 32b243bd..2479e2c0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -55,7 +55,9 @@ jobs: # PDM is already installed via setup-pdm action - name: Install dependencies - run: pdm install -G dev + # test-runtime: FastAPI and friends, so the tests that start generated + # applications run instead of skipping. + run: pdm install -G dev -G test-runtime - name: Run tests with coverage if: runner.os == 'Linux' @@ -102,7 +104,9 @@ jobs: pip install poetry - name: Install dependencies - run: pdm install -G dev + # test-runtime: FastAPI and friends, so the tests that start generated + # applications run instead of skipping. + run: pdm install -G dev -G test-runtime - name: Fail on implicit text encodings in fastapi_fastkit env: diff --git a/.github/workflows/web-generator.yml b/.github/workflows/web-generator.yml new file mode 100644 index 00000000..dbd7e92f --- /dev/null +++ b/.github/workflows/web-generator.yml @@ -0,0 +1,77 @@ +name: Web generator + +# The docs site's web generator runs fastkit in the browser with Pyodide. +# This job runs the page's generator core under Node with the same assets and +# compares every case with the `fastkit init` CLI from the same wheel, then +# builds the docs site and checks the page in every locale. + +on: + pull_request: + paths: + - "src/**" + - "docs/js/**" + - "docs/css/web-generator.css" + - "docs/*/start/web-generator.md" + - "scripts/web_generator/**" + - "tests/fixtures/web_generator/**" + - "pyproject.toml" + - "mkdocs.yml" + - "requirements-docs.txt" + - ".github/workflows/web-generator.yml" + push: + branches: + - main + +permissions: + contents: read + +jobs: + web-vs-cli: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: "22" + + - name: Cache Pyodide downloads + uses: actions/cache@v4 + with: + path: .cache/web-generator + key: web-generator-${{ hashFiles('scripts/web_generator/pyodide.toml') }} + + - name: Build and install the fastkit wheel + run: | + python -m pip install --upgrade pip + python -m pip wheel --no-deps -w dist . + python -m pip install dist/fastapi_fastkit-*.whl + + - name: Build the web generator assets + run: >- + python scripts/web_generator/build_assets.py + --wheel dist/fastapi_fastkit-*.whl + --out docs/en/assets/fastkit-generator + --commit "$GITHUB_SHA" + + - name: Compare web output with the CLI + run: >- + python scripts/web_generator/compare_with_cli.py + --assets docs/en/assets/fastkit-generator + --cases tests/fixtures/web_generator/cases.json + + - name: Build the docs site + run: | + python -m pip install -r requirements-docs.txt + mkdocs build --strict -d site + + - name: Check the web generator page + run: python scripts/web_generator/check_site.py site diff --git a/.gitignore b/.gitignore index f157d7e5..6708401a 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,10 @@ temp/ *_api_key.txt translation_cache/ +# Web generator assets (built by scripts/web_generator/build_assets.py) and downloads +docs/en/assets/fastkit-generator/ +.cache/web-generator/ + .pdm-python ### VisualStudioCode template .vscode/* diff --git a/CHANGELOG.md b/CHANGELOG.md index 482ccbac..d985f5cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,6 +64,11 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - 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. +### Web generator + +- A web generator page on the documentation site, in all seven languages, creates a project in your browser and downloads it as a zip with the same files as `fastkit init ... --no-venv`; it shows the matching command line and the next steps, and nothing you enter is uploaded. +- Level, feature and next-step texts are translated for the documentation languages; the CLI and the generated files stay English. + ### `fastkit init` options - **JWT** generates an OAuth2 password flow: `POST /api/v1/auth/register`, `POST /api/v1/auth/token` and `GET /api/v1/users/me`, with users stored in the selected SQL database or MongoDB (in memory otherwise). diff --git a/README.md b/README.md index 305fd2d0..0b03e6ee 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,8 @@ This project was inspired by the `SpringBoot initializer` & Python Django's `dja Install `FastAPI-fastkit` in your Python environment. +To try fastkit without installing anything, use the [web generator](https://bnbong.github.io/FastAPI-fastkit/start/web-generator/) in your browser. + ```console $ pip install FastAPI-fastkit ``` diff --git a/docs/css/web-generator.css b/docs/css/web-generator.css new file mode 100644 index 00000000..16cab5a5 --- /dev/null +++ b/docs/css/web-generator.css @@ -0,0 +1,698 @@ +/* Web generator page (docs//start/web-generator.md). Every selector is + scoped under .fkg; colours come from Material's theme variables so the + page follows the light/dark palette toggle without a reload. */ + +.fkg { + --fkg-error: #b3261e; + --fkg-border: var(--md-default-fg-color--lightest); + --fkg-muted: var(--md-default-fg-color--light); + --fkg-radius: 0.3rem; + margin: 1.2em 0 2em; + overflow-wrap: break-word; +} + +/* Korean breaks between words, not inside them. */ +.fkg:lang(ko) { + word-break: keep-all; +} + +/* Long German compounds: hyphenate (the page sets lang="de"). */ +.fkg:lang(de) { + hyphens: auto; +} + +[data-md-color-scheme="slate"] .fkg { + --fkg-error: #f2b8b5; +} + +.fkg *, +.fkg *::before, +.fkg *::after { + box-sizing: border-box; +} + +.fkg [hidden] { + display: none !important; +} + +.fkg .fkg-static { + color: var(--fkg-muted); +} + +/* ---------- layout ---------- */ + +.fkg .fkg-layout { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 1.5rem; +} + +@media screen and (min-width: 60em) { + .fkg .fkg-layout { + grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); + align-items: start; + } +} + +.fkg .fkg-main > * + *, +.fkg .fkg-side > * + * { + margin-top: 1.25rem; +} + +.fkg .fkg-row { + display: flex; + flex-wrap: wrap; + gap: 0.5rem 0.75rem; + align-items: center; + margin: 0.6em 0 0; +} + +/* ---------- disclosure widgets: undo Material's admonition look ---------- */ + +.md-typeset .fkg details { + display: block; + margin: 0; + padding: 0; + overflow: visible; + font-size: inherit; + background: none; + border: 0; + border-radius: 0; + box-shadow: none; +} + +.md-typeset .fkg details > summary { + display: block; + position: static; + margin: 0; + padding: 0; + font-weight: inherit; + background: none; + border: 0; + border-radius: 0; + cursor: pointer; +} + +.md-typeset .fkg details > summary::after { + display: none; +} + +.md-typeset .fkg details > summary::before { + content: "\25B8"; + position: static; + display: inline-block; + width: 1em; + height: auto; + margin: 0; + background: none; + -webkit-mask-image: none; + mask-image: none; + transform: none; + color: var(--fkg-muted); +} + +.md-typeset .fkg details[open] > summary::before { + content: "\25BE"; +} + +/* ---------- fields ---------- */ + +.fkg fieldset { + margin: 0; + padding: 0; + border: 0; + min-width: 0; +} + +.fkg legend, +.fkg .fkg-field > label { + display: block; + padding: 0; + margin: 0 0 0.35em; + font-weight: 700; + color: var(--md-default-fg-color); +} + +.fkg .fkg-field + .fkg-field, +.fkg .fkg-group + .fkg-group, +.fkg .fkg-group .fkg-field + .fkg-multi, +.fkg .fkg-group .fkg-multi + .fkg-field, +.fkg .fkg-group .fkg-multi + .fkg-multi { + margin-top: 1rem; +} + +.fkg input[type="text"], +.fkg input[type="email"], +.fkg select, +.fkg textarea { + display: block; + width: 100%; + max-width: 32rem; + min-height: 2.25rem; + padding: 0.4em 0.6em; + font: inherit; + font-size: 0.8rem; + color: var(--md-default-fg-color); + background-color: var(--md-default-bg-color); + border: 1px solid var(--md-default-fg-color--lighter); + border-radius: var(--fkg-radius); +} + +.fkg textarea { + resize: vertical; +} + +.fkg input:focus-visible, +.fkg select:focus-visible, +.fkg textarea:focus-visible, +.fkg button:focus-visible, +.fkg summary:focus-visible, +.fkg a:focus-visible, +.fkg [tabindex="-1"]:focus-visible { + outline: 2px solid var(--md-accent-fg-color); + outline-offset: 2px; +} + +.fkg [aria-invalid="true"]:not(fieldset) { + border-color: var(--fkg-error); + border-width: 2px; +} + +.fkg .fkg-help { + margin: 0.35em 0 0; + font-size: 0.7rem; + line-height: 1.6; + color: var(--fkg-muted); +} + +.fkg .fkg-help-line { + display: block; +} + +.fkg .fkg-summary:empty { + display: none; +} + +.fkg .fkg-summary { + color: var(--md-default-fg-color); +} + +.fkg .fkg-error { + margin: 0.35em 0 0; + font-size: 0.75rem; + font-weight: 700; + line-height: 1.5; + color: var(--fkg-error); +} + +.fkg .fkg-error::before { + content: "\2715\00A0"; +} + +.fkg .fkg-hint { + display: block; + margin-top: 0.25em; + font-weight: 700; + color: var(--md-default-fg-color); +} + +/* ---------- level cards ---------- */ + +.fkg .fkg-cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(min(100%, 13rem), 1fr)); + gap: 0.6rem; + margin-top: 0.6rem; +} + +.fkg .fkg-card { + position: relative; + display: flex; + gap: 0.6rem; + align-items: flex-start; + min-height: 100%; + padding: 0.7rem 0.8rem; + cursor: pointer; + border: 1px solid var(--md-default-fg-color--lighter); + border-radius: var(--fkg-radius); + background-color: var(--md-default-bg-color); +} + +.fkg .fkg-card:hover { + border-color: var(--md-accent-fg-color); +} + +.fkg .fkg-card input { + flex: none; + width: 1.1rem; + height: 1.1rem; + margin: 0.15rem 0 0; + accent-color: var(--md-primary-fg-color); +} + +.fkg .fkg-card:has(input:checked) { + border-color: var(--md-primary-fg-color); + box-shadow: inset 0 0 0 1px var(--md-primary-fg-color); +} + +.fkg .fkg-card:has(input:focus-visible) { + outline: 2px solid var(--md-accent-fg-color); + outline-offset: 2px; +} + +.fkg .fkg-card-step { + flex: none; + display: inline-grid; + place-items: center; + width: 1.4rem; + height: 1.4rem; + font-size: 0.65rem; + font-weight: 700; + border-radius: 50%; + color: var(--md-default-bg-color); + background-color: var(--md-default-fg-color--light); +} + +.fkg .fkg-card:has(input:checked) .fkg-card-step { + background-color: var(--md-primary-fg-color); + color: var(--md-primary-bg-color); +} + +.fkg .fkg-card-body { + display: flex; + flex-direction: column; + gap: 0.2rem; + min-width: 0; +} + +.fkg .fkg-card-title { + font-weight: 700; +} + +.fkg .fkg-card-desc { + font-size: 0.7rem; + line-height: 1.5; + color: var(--fkg-muted); +} + +/* ---------- customise ---------- */ + +.md-typeset .fkg .fkg-customise { + border: 1px solid var(--fkg-border); + border-radius: var(--fkg-radius); + padding: 0 0.9rem; +} + +.md-typeset .fkg .fkg-customise[open] { + padding-bottom: 1rem; +} + +.md-typeset .fkg .fkg-customise > summary { + min-height: 2.5rem; + padding: 0.6rem 0; + font-weight: 700; +} + +.fkg .fkg-group { + margin-top: 1.2rem; + padding-top: 1rem; + border-top: 1px solid var(--fkg-border); +} + +.fkg .fkg-group > legend { + float: left; + width: 100%; + margin-bottom: 0.8rem; + font-size: 0.85rem; +} + +.fkg .fkg-group > legend + * { + clear: both; +} + +.fkg .fkg-multi > legend { + font-weight: 700; +} + +.fkg .fkg-check { + display: flex; + gap: 0.5rem; + align-items: flex-start; + margin-top: 0.4rem; +} + +.fkg .fkg-check input { + flex: none; + width: 1.1rem; + height: 1.1rem; + margin: 0.2rem 0 0; + accent-color: var(--md-primary-fg-color); +} + +.fkg .fkg-check label { + display: flex; + flex-direction: column; + min-width: 0; + cursor: pointer; +} + +.fkg .fkg-check-desc { + font-size: 0.7rem; + line-height: 1.5; + color: var(--fkg-muted); +} + +/* ---------- message boxes ---------- */ + +.fkg .fkg-box, +.fkg .fkg-alert { + padding: 0.7rem 0.9rem; + border: 1px solid var(--fkg-border); + border-left-width: 0.25rem; + border-radius: var(--fkg-radius); + font-size: 0.75rem; + line-height: 1.6; +} + +.fkg .fkg-customise .fkg-rules { + margin-top: 1rem; +} + +.fkg .fkg-box + .fkg-box { + margin-top: 0.75rem; +} + +.fkg .fkg-box-error, +.fkg .fkg-alert { + border-left-color: var(--fkg-error); +} + +.fkg .fkg-box-note { + border-left-color: var(--md-typeset-a-color); +} + +.fkg .fkg-alert { + margin: 0 0 1.25rem; +} + +.fkg .fkg-alert:empty { + display: none; +} + +.fkg .fkg-alert p, +.fkg .fkg-box p { + margin: 0.3em 0; +} + +.fkg .fkg-box ul { + margin: 0.3em 0 0; +} + +.fkg .fkg-box-title { + font-weight: 700; +} + +.fkg .fkg-icon { + display: inline-grid; + place-items: center; + width: 1.2em; + height: 1.2em; + margin-right: 0.4em; + font-size: 0.85em; + font-weight: 700; + border-radius: 50%; + border: 1.5px solid currentColor; + vertical-align: -0.15em; +} + +.fkg .fkg-alert pre { + margin: 0.4em 0 0; + white-space: pre-wrap; +} + +/* ---------- side panels ---------- */ + +.fkg .fkg-panel { + padding: 0.8rem 0.9rem; + border: 1px solid var(--fkg-border); + border-radius: var(--fkg-radius); + transition: opacity 0.15s; +} + +.md-typeset .fkg .fkg-panel h2, +.md-typeset .fkg .fkg-result h2 { + margin: 0 0 0.5em; + font-size: 1rem; + font-weight: 700; + line-height: 1.4; +} + +.md-typeset .fkg .fkg-result h3 { + margin: 1.4em 0 0.5em; + font-size: 0.9rem; + font-weight: 700; +} + +.md-typeset .fkg .fkg-result h4 { + margin: 0 0 0.3em; + font-size: 0.8rem; +} + +.fkg.fkg-checking .fkg-panel, +.fkg .fkg-panel.fkg-stale { + opacity: 0.55; +} + +.fkg .fkg-count { + margin: 0 0 0.5em; + font-size: 0.75rem; + color: var(--fkg-muted); +} + +.fkg .fkg-tree { + font-family: var(--md-code-font-family); + font-size: 0.7rem; + line-height: 1.7; + max-height: 22rem; + overflow: auto; +} + +.md-typeset .fkg .fkg-tree ul { + list-style: none; + margin: 0 0 0 1.1em; + padding: 0; +} + +.md-typeset .fkg .fkg-tree ul.fkg-tree-root { + margin-left: 0; +} + +.md-typeset .fkg .fkg-tree li { + margin: 0; +} + +.fkg .fkg-tree summary { + cursor: pointer; + min-height: 1.5rem; +} + +.fkg .fkg-dir { + font-weight: 700; +} + +.fkg .fkg-badge { + display: inline-block; + padding: 0 0.4em; + font-family: var(--md-text-font-family); + font-size: 0.6rem; + border: 1px solid var(--md-default-fg-color--lighter); + border-radius: 0.2rem; + color: var(--fkg-muted); +} + +.md-typeset .fkg pre.fkg-command, +.md-typeset .fkg pre.fkg-step-code { + margin: 0.3em 0 0; +} + +.md-typeset .fkg pre.fkg-command > code, +.md-typeset .fkg pre.fkg-step-code > code { + white-space: pre-wrap; + overflow-wrap: anywhere; + padding: 0.6em 0.8em; +} + +.fkg .fkg-copy-status { + font-size: 0.7rem; + color: var(--fkg-muted); +} + +/* ---------- buttons ---------- */ + +.md-typeset .fkg .md-button { + min-height: 2.25rem; + margin: 0; + padding: 0.45em 1.1em; + font-size: 0.75rem; + cursor: pointer; +} + +.md-typeset .fkg .fkg-generate { + display: inline-flex; + align-items: center; + gap: 0.5em; + font-size: 0.85rem; +} + +.md-typeset .fkg .fkg-generate[aria-disabled="true"] { + opacity: 0.6; + cursor: not-allowed; +} + +.fkg .fkg-privacy { + margin-top: 0.75rem; +} + +/* ---------- status line and spinner ---------- */ + +.fkg .fkg-status { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.2rem 0.5rem; + margin: 0 0 1rem; + font-size: 0.75rem; + color: var(--fkg-muted); +} + +.fkg .fkg-status-text { + font-weight: 700; + color: var(--md-default-fg-color); +} + +.fkg .fkg-spinner { + display: none; + flex: none; + width: 0.9em; + height: 0.9em; + border: 2px solid var(--md-default-fg-color--lighter); + border-top-color: var(--md-primary-fg-color); + border-radius: 50%; + animation: fkg-spin 0.8s linear infinite; + align-self: center; +} + +.fkg[data-fkg-state="starting"] .fkg-status .fkg-spinner, +.fkg .fkg-generate.fkg-busy .fkg-button-spinner { + display: inline-block; +} + +.fkg .fkg-generate .fkg-button-spinner { + border-color: currentColor; + border-top-color: transparent; +} + +@keyframes fkg-spin { + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: reduce) { + .fkg .fkg-spinner { + animation: none; + border-top-color: var(--md-default-fg-color--lighter); + } + + .fkg .fkg-panel { + transition: none; + } +} + +/* ---------- result ---------- */ + +.fkg .fkg-result { + margin-top: 2rem; + padding: 1rem 1.1rem; + border: 1px solid var(--md-primary-fg-color); + border-radius: var(--fkg-radius); +} + +.fkg .fkg-done { + margin: 0; + font-weight: 700; +} + +.fkg .fkg-os { + display: flex; + flex-wrap: wrap; + gap: 0.25rem 1rem; + align-items: center; + margin: 0.4rem 0 0.6rem; + font-size: 0.75rem; +} + +.fkg .fkg-os > legend { + float: left; + margin: 0 0.5rem 0 0; +} + +.fkg .fkg-os-option { + display: inline-flex; + gap: 0.35rem; + align-items: center; + min-height: 1.5rem; +} + +.fkg .fkg-os-option input { + width: 1rem; + height: 1rem; + margin: 0; + accent-color: var(--md-primary-fg-color); +} + +.md-typeset .fkg .fkg-step-list > li { + margin-bottom: 0.8em; +} + +.md-typeset .fkg .fkg-step-list p { + margin: 0 0 0.3em; +} + +.fkg .fkg-feature { + padding: 0.7rem 0; + border-top: 1px solid var(--fkg-border); +} + +.md-typeset .fkg .fkg-feature dl { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + gap: 0.2em 0.8em; + margin: 0.4em 0; + font-size: 0.75rem; +} + +.md-typeset .fkg .fkg-feature dd { + margin: 0; +} + +.fkg .fkg-messages { + margin-top: 1rem; + font-size: 0.75rem; +} + +.fkg .fkg-footer { + margin-top: 1.5rem; + font-size: 0.65rem; + color: var(--fkg-muted); +} + +@media screen and (max-width: 30em) { + .fkg .fkg-customise { + padding: 0 0.6rem; + } + + .md-typeset .fkg .fkg-feature dl { + grid-template-columns: minmax(0, 1fr); + } +} diff --git a/docs/de/start/web-generator.md b/docs/de/start/web-generator.md new file mode 100644 index 00000000..52d02a4a --- /dev/null +++ b/docs/de/start/web-generator.md @@ -0,0 +1,17 @@ +--- +hide: + - toc +--- +# Web-Generator + +Erstelle ein fastkit-Projekt in deinem Browser. Diese Seite führt den fastkit-Generator selbst mit +[Pyodide](https://pyodide.org/) aus, daher enthält das heruntergeladene Zip dieselben Dateien wie +`fastkit init ... --no-venv` mit den gewählten Optionen. Nichts, was du eingibst, verlässt deinen Browser. + +
+ +

Der Generator wird gestartet…

+ +
+ diff --git a/docs/en/contributing/development-setup.md b/docs/en/contributing/development-setup.md index 122ce767..da48a93c 100644 --- a/docs/en/contributing/development-setup.md +++ b/docs/en/contributing/development-setup.md @@ -86,6 +86,8 @@ pre-commit hooks and both lock files: black 26.10.1, isort 9.0.1, mypy 2.3.1 and ruff 0.17.6. After pulling, bring your environment in line with `pdm sync -G dev --clean` (or `uv sync --extra dev`). +The tests that start generated applications need FastAPI and a few more packages, which the `test-runtime` dependency group provides; without them those tests are skipped. CI installs it with `pdm install -G dev -G test-runtime`, and locally you can use `pdm sync -G dev -G test-runtime --clean`, `uv sync --extra dev --group test-runtime` or `pip install --group test-runtime` (pip 25.1 or later). + ### 4. Set Up Pre-commit Hooks
@@ -629,6 +631,34 @@ INFO - Documentation built in 0.43 seconds
+### Web generator page + +The page `docs/en/start/web-generator.md` runs fastkit in the browser with Pyodide. It loads files that `scripts/web_generator/build_assets.py` builds from the fastkit wheel, so build them before you preview the page. You need Node.js (CI uses 22) for the comparison below, and a virtual environment you can reinstall fastkit into, because the wheel replaces an editable install. + +```bash +python -m pip wheel --no-deps -w dist . +python -m pip install dist/fastapi_fastkit-*.whl +python scripts/web_generator/build_assets.py --wheel dist/fastapi_fastkit-*.whl \ + --out docs/en/assets/fastkit-generator +make serve-docs +``` + +Then open `/start/web-generator/` on the local server. The first build downloads Pyodide into `.cache/web-generator` and checks every file against the pinned checksums (`--no-cache` skips the cache). `docs/en/assets/fastkit-generator/` and `.cache/web-generator/` are git-ignored and never committed. Without the assets the page shows a message that the generator files are not built. + +To check that the page makes the same projects as the command line, run every case of the fixture file through the page's generator in Node and through the `fastkit` command of the installed wheel: + +```bash +python scripts/web_generator/compare_with_cli.py \ + --assets docs/en/assets/fastkit-generator \ + --cases tests/fixtures/web_generator/cases.json +``` + +Add `--only 01-hello,03-layered` to run some cases (use ids from the fixture) and `--keep DIR` to keep both outputs. To compare one zip you downloaded from the page with the command shown next to it, use `compare_with_cli.py --zip demo.zip -- init --project-name demo ...`. To check a built site, run `mkdocs build --strict -d site` and then `python scripts/web_generator/check_site.py site`. + +The page strings of each language are in `docs/js/web-generator-strings/.json`, and the level and feature texts come from the catalog overlays in `src/fastapi_fastkit/catalog/i18n/`. `tests/test_docs` checks that every language has the same keys and placeholders. + +In CI the `Web generator` workflow runs on pull requests that touch the page, its scripts, the catalog or `src/`, and on pushes to `main`. It builds the wheel and the assets, compares every case with the command line, builds the docs site in strict mode and checks the page in all seven languages. The docs deployment repeats the build and the comparison before it publishes. + ### Writing Documentation Documentation is written in Markdown and built with MkDocs. Here's an example structure: diff --git a/docs/en/index.md b/docs/en/index.md index 7e244c29..b2200b5c 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -44,6 +44,8 @@ This project was inspired by the `SpringBoot initializer` & Python Django's `dja Install `FastAPI-fastkit` at your Python environment. +To try fastkit without installing anything, use the [web generator](start/web-generator.md) in your browser. +
```console diff --git a/docs/en/start/web-generator.md b/docs/en/start/web-generator.md new file mode 100644 index 00000000..3ce7feb7 --- /dev/null +++ b/docs/en/start/web-generator.md @@ -0,0 +1,17 @@ +--- +hide: + - toc +--- +# Web generator + +Create a fastkit project in your browser. This page runs the fastkit generator itself with +[Pyodide](https://pyodide.org/), so the zip you download holds the same files as +`fastkit init ... --no-venv` with the options you pick. Nothing you enter leaves your browser. + +
+ +

The generator is starting…

+ +
+ diff --git a/docs/en/user-guide/installation.md b/docs/en/user-guide/installation.md index adc96abe..52ebfedd 100644 --- a/docs/en/user-guide/installation.md +++ b/docs/en/user-guide/installation.md @@ -2,6 +2,8 @@ This guide explains how to install FastAPI-fastkit. +To try fastkit without installing anything, use the [web generator](../start/web-generator.md) in your browser. + ## Requirements To use FastAPI-fastkit, you need to meet the following requirements: diff --git a/docs/es/start/web-generator.md b/docs/es/start/web-generator.md new file mode 100644 index 00000000..3dab6988 --- /dev/null +++ b/docs/es/start/web-generator.md @@ -0,0 +1,17 @@ +--- +hide: + - toc +--- +# Generador web + +Crea un proyecto de fastkit en tu navegador. Esta página ejecuta el propio generador de fastkit con +[Pyodide](https://pyodide.org/), así que el zip que descargas contiene los mismos archivos que +`fastkit init ... --no-venv` con las opciones que elijas. Nada de lo que escribes sale de tu navegador. + +
+ +

El generador se está iniciando…

+ +
+ diff --git a/docs/fr/start/web-generator.md b/docs/fr/start/web-generator.md new file mode 100644 index 00000000..3e36bcda --- /dev/null +++ b/docs/fr/start/web-generator.md @@ -0,0 +1,17 @@ +--- +hide: + - toc +--- +# Générateur web + +Créez un projet fastkit dans votre navigateur. Cette page exécute le générateur de fastkit lui-même avec +[Pyodide](https://pyodide.org/), si bien que le zip que vous téléchargez contient les mêmes fichiers que +`fastkit init ... --no-venv` avec les options que vous choisissez. Rien de ce que vous saisissez ne quitte votre navigateur. + +
+ +

Le générateur démarre…

+ +
+ diff --git a/docs/ja/start/web-generator.md b/docs/ja/start/web-generator.md new file mode 100644 index 00000000..fc5cf9c7 --- /dev/null +++ b/docs/ja/start/web-generator.md @@ -0,0 +1,16 @@ +--- +hide: + - toc +--- +# Web ジェネレーター + +ブラウザ上で fastkit のプロジェクトを作成できます。このページは fastkit のジェネレーターそのものを [Pyodide](https://pyodide.org/) で実行するため、ダウンロードする zip には、選んだオプションで実行した +`fastkit init ... --no-venv` と同じファイルが入っています。入力した内容がブラウザの外に出ることはありません。 + +
+ +

ジェネレーターを起動しています…

+ +
+ diff --git a/docs/js/web-generator-core.mjs b/docs/js/web-generator-core.mjs new file mode 100644 index 00000000..15e83b0e --- /dev/null +++ b/docs/js/web-generator-core.mjs @@ -0,0 +1,190 @@ +// Runs the fastkit generator in Pyodide. Environment-neutral on purpose: no +// DOM access, so the docs page's worker and the Node CI runner +// (scripts/web_generator/generate.mjs) execute exactly this code. + +export const MANIFEST_SCHEMA = 1; + +const GENERATION_ERRORS = new Set(["GenerationError", "SpecError", "ChoiceError"]); + +export class GeneratorError extends Error { + constructor(kind, message, options = {}) { + super(message); + this.name = "GeneratorError"; + this.kind = kind; + if (options.problems) this.problems = options.problems; + if (options.cause) this.cause = options.cause; + } +} + +function base64url(bytes) { + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} + +// Same shape as Python's secrets.token_urlsafe(32): 43 characters. +export function makeSecret() { + return base64url(globalThis.crypto.getRandomValues(new Uint8Array(32))); +} + +export async function sha256Hex(bytes) { + const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes); + return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join(""); +} + +function isMissing(error) { + return Boolean(error) && (error.status === 404 || error.code === "ENOENT"); +} + +// The last line of a Python traceback ("ValueError: ...") without the type. +function pythonMessage(error) { + const lines = String(error && error.message ? error.message : error).trim().split("\n"); + const last = lines[lines.length - 1] || ""; + const type = error && error.type; + return type && last.startsWith(type + ": ") ? last.slice(type.length + 2) : last; +} + +function translateError(error) { + if (error instanceof GeneratorError) return error; + const type = error && error.type; + if (type === "FormError") { + return new GeneratorError("form", pythonMessage(error), { cause: error }); + } + if (GENERATION_ERRORS.has(type)) { + return new GeneratorError("generation", pythonMessage(error), { cause: error }); + } + return new GeneratorError("internal", pythonMessage(error), { cause: error }); +} + +async function readManifest(assetsURL, readBytes) { + let bytes; + try { + bytes = await readBytes(assetsURL + "manifest.json"); + } catch (error) { + if (isMissing(error)) { + throw new GeneratorError("missing", "manifest.json was not found", { cause: error }); + } + throw new GeneratorError("load", "manifest.json could not be read: " + error, { cause: error }); + } + let manifest; + try { + manifest = JSON.parse(new TextDecoder().decode(bytes)); + } catch (error) { + throw new GeneratorError("load", "manifest.json is not valid JSON", { cause: error }); + } + if (!manifest || manifest.schema !== MANIFEST_SCHEMA) { + throw new GeneratorError("load", "unsupported manifest schema: " + (manifest && manifest.schema)); + } + if (typeof manifest.wheel !== "string" || typeof manifest.wheel_sha256 !== "string") { + throw new GeneratorError("load", "manifest.json names no wheel"); + } + return manifest; +} + +export async function startGenerator({ assetsURL, readBytes, onStage = () => {} }) { + if (typeof assetsURL !== "string" || !assetsURL.endsWith("/")) { + throw new GeneratorError("load", "assetsURL must be a string ending in '/'"); + } + const manifest = await readManifest(assetsURL, readBytes); + + let py; + let browser; + try { + onStage("runtime"); + const { loadPyodide } = await import(assetsURL + "pyodide/pyodide.mjs"); + let indexURL = assetsURL + "pyodide/"; + if (indexURL.startsWith("file:")) { + // Pyodide under Node wants a file system path, not a file: URL. + const { fileURLToPath } = await import("node:url"); + indexURL = fileURLToPath(indexURL); + if (!/[\\/]$/.test(indexURL)) indexURL += "/"; + } + py = await loadPyodide({ + indexURL, + stdout() {}, + stderr() {}, + }); + + onStage("packages"); + // Pyodide reports a failed package through errorCallback; keep the first + // message so the error the page shows says what went wrong. + let packageError = null; + try { + await py.loadPackage(manifest.packages || [], { + messageCallback() {}, + errorCallback(message) { + if (packageError === null) packageError = String(message); + }, + }); + } catch (error) { + const detail = packageError ? packageError + "; " : ""; + throw new GeneratorError("load", "loading packages failed: " + detail + pythonMessage(error), { cause: error }); + } + if (packageError !== null) { + throw new GeneratorError("load", "loading packages failed: " + packageError); + } + + onStage("fastkit"); + const wheel = await readBytes(assetsURL + manifest.wheel); + const digest = await sha256Hex(wheel); + if (digest !== manifest.wheel_sha256.toLowerCase()) { + throw new GeneratorError("load", "the fastkit wheel does not match manifest.json"); + } + const purelib = py.runPython("import sysconfig\nsysconfig.get_paths()['purelib']"); + py.unpackArchive(wheel, "zip", { extractDir: purelib }); + browser = py.pyimport("fastapi_fastkit.generation.browser"); + } catch (error) { + if (error instanceof GeneratorError) throw error; + throw new GeneratorError("load", pythonMessage(error), { cause: error }); + } + + let closed = false; + function ensureOpen() { + if (closed) throw new GeneratorError("internal", "the generator was closed"); + } + + return { + manifest, + + async check(form, lang = "en") { + ensureOpen(); + try { + return JSON.parse(browser.check_json(JSON.stringify(form), lang)); + } catch (error) { + throw translateError(error); + } + }, + + async build(form, lang = "en") { + ensureOpen(); + let result; + let zipProxy; + try { + result = browser.build_for_js(JSON.stringify(form), lang, makeSecret); + const meta = JSON.parse(result.get(1)); + if (!meta.ok) { + // Form and generation problems come back as data, not exceptions. + const failure = meta.error || {}; + throw new GeneratorError(failure.kind === "form" ? "form" : "generation", failure.message || "", { + problems: failure.problems && failure.problems.length ? failure.problems : undefined, + }); + } + delete meta.ok; + zipProxy = result.get(0); + const zip = zipProxy.toJs(); + return { zip, meta }; + } catch (error) { + throw translateError(error); + } finally { + if (zipProxy && typeof zipProxy.destroy === "function") zipProxy.destroy(); + if (result && typeof result.destroy === "function") result.destroy(); + } + }, + + close() { + if (closed) return; + closed = true; + if (browser && typeof browser.destroy === "function") browser.destroy(); + }, + }; +} diff --git a/docs/js/web-generator-strings/de.json b/docs/js/web-generator-strings/de.json new file mode 100644 index 00000000..76f26803 --- /dev/null +++ b/docs/js/web-generator-strings/de.json @@ -0,0 +1,74 @@ +{ + "intro_privacy": "Alles läuft auf dieser Seite: Nichts, was du eingibst, wird irgendwohin gesendet.", + "loading_runtime": "Python (Pyodide) wird geladen…", + "loading_packages": "Python-Pakete werden geladen…", + "loading_fastkit": "fastkit wird geladen…", + "loading_note": "Etwa 7 MB, die einmal heruntergeladen und dann von deinem Browser zwischengespeichert werden. Du kannst das Formular schon ausfüllen.", + "ready": "Bereit.", + "unsupported_browser": "Dieser Browser kann den Generator nicht ausführen: Er benötigt WebAssembly und Module Worker. Verwende eine aktuelle Version von Chrome, Edge, Firefox oder Safari.", + "assets_missing": "Die Generator-Dateien sind nicht Teil dieses Builds. Wie du sie erstellst, steht im Beitragsleitfaden.", + "load_failed": "Der Generator konnte nicht gestartet werden.", + "retry": "Erneut versuchen", + "reload": "Seite neu laden", + "cli_pointer": "Du kannst das Projekt auch über die Kommandozeile erstellen: Installiere fastkit und führe fastkit init aus.", + "installation_link": "Installationsanleitung", + "error_details": "Technische Details", + "field_name": "Projektname", + "field_name_help": "Buchstaben, Ziffern, Unterstriche und Bindestriche. Er ist auch der Ordnername im Zip.", + "name_empty": "Gib einen Projektnamen ein.", + "name_characters": "Verwende nur Buchstaben, Ziffern, Unterstriche (_) und Bindestriche (-), ohne Leerzeichen.", + "name_digit": "Der Name darf nicht mit einer Ziffer beginnen.", + "name_keyword": "„{name}“ ist ein reserviertes Wort in Python. Wähle einen anderen Namen.", + "field_level": "Stufe", + "field_level_help": "Fang klein an: Jede Stufe fügt dem Projekt mehr Struktur hinzu.", + "field_database": "Datenbank", + "customise_summary": "Funktionen und Projektdetails anpassen", + "customise_help": "Solange dieser Bereich geschlossen bleibt, nutzt das Projekt die Standardwerte der Stufe, so als würdest du die Anpassungsfrage auf der Kommandozeile mit „Nein“ beantworten.", + "features_legend": "Funktionen", + "deployment_legend": "Deployment", + "project_legend": "Projektdetails", + "field_package_manager": "Paketmanager", + "field_author": "Autor", + "field_author_email": "E-Mail des Autors", + "email_invalid": "Gib eine gültige E-Mail-Adresse ein oder lass das Feld leer.", + "field_description": "Beschreibung", + "field_extra_packages": "Zusätzliche Pakete", + "extra_packages_help": "PyPI-Paketnamen, durch Kommas getrennt, zum Beispiel: orjson, httpx>=0.28", + "extra_package_invalid": "„{package}“ ist kein gültiger Paketname.", + "too_long": "Verwende höchstens {max} Zeichen.", + "too_many_packages": "Füge höchstens {max} Pakete hinzu.", + "invalid_value": "Dieser Wert kann nicht verwendet werden.", + "alembic_needs_sql": "Alembic-Migrationen benötigen eine SQL-Datenbank.", + "rule_errors_heading": "Diese Auswahl passt nicht zusammen", + "notes_heading": "Hinweise", + "checking": "Wird geprüft…", + "preview_heading": "Dateien", + "preview_count": "{count} Dateien", + "preview_waiting": "Die Dateiliste erscheint, sobald Python geladen ist.", + "executable": "ausführbar", + "command_heading": "Dasselbe Projekt auf der Kommandozeile", + "copy": "Kopieren", + "copied": "In die Zwischenablage kopiert.", + "copy_manual": "Der Befehl ist markiert. Drücke Strg+C (⌘C unter macOS), um ihn zu kopieren.", + "git_identity_note": "Ohne --author und --author-email übernimmt fastkit sie aus deiner git config.", + "windows_shell_note": "Diese Zeile gilt für PowerShell.", + "generate": "Erzeugen und herunterladen", + "generating": "Wird erzeugt…", + "generate_wait": "Erzeugen ist möglich, sobald Python geladen ist.", + "generate_fix": "Korrigiere die markierten Felder, um das Projekt zu erzeugen.", + "generated": "{filename} heruntergeladen ({count} Dateien).", + "download_again": "Erneut herunterladen", + "result_heading": "Dein Projekt ist fertig", + "os_label": "Befehle für", + "os_posix": "macOS / Linux", + "os_windows": "Windows", + "features_heading": "Ausgewählte Funktionen", + "files_label": "Dateien", + "settings_label": "Einstellungen", + "docs_link": "Dokumentation", + "details_heading": "Meldungen des Generators", + "generation_failed": "Das Projekt konnte nicht erzeugt werden.", + "report_issue": "Dieses Problem melden", + "version_note": "fastkit {version} ({commit})", + "runs_on_pyodide": "Läuft auf Pyodide (MPL-2.0)" +} diff --git a/docs/js/web-generator-strings/en.json b/docs/js/web-generator-strings/en.json new file mode 100644 index 00000000..4d3b0ade --- /dev/null +++ b/docs/js/web-generator-strings/en.json @@ -0,0 +1,74 @@ +{ + "intro_privacy": "Everything runs on this page: nothing you enter is sent anywhere.", + "loading_runtime": "Loading Python (Pyodide)…", + "loading_packages": "Loading Python packages…", + "loading_fastkit": "Loading fastkit…", + "loading_note": "About 7 MB, downloaded once and then cached by your browser. You can fill in the form meanwhile.", + "ready": "Ready.", + "unsupported_browser": "This browser cannot run the generator: it needs WebAssembly and module workers. Use a recent version of Chrome, Edge, Firefox or Safari.", + "assets_missing": "The generator files are not part of this build. See the contributing guide to build them.", + "load_failed": "The generator could not start.", + "retry": "Try again", + "reload": "Reload the page", + "cli_pointer": "You can also create the project with the command line: install fastkit and run fastkit init.", + "installation_link": "Installation guide", + "error_details": "Technical details", + "field_name": "Project name", + "field_name_help": "Letters, digits, underscores and hyphens. It is also the folder name inside the zip.", + "name_empty": "Enter a project name.", + "name_characters": "Use only letters, digits, underscores (_) and hyphens (-), without spaces.", + "name_digit": "The name cannot start with a digit.", + "name_keyword": "“{name}” is a reserved word in Python. Choose another name.", + "field_level": "Level", + "field_level_help": "Start small: each level adds more structure to the project.", + "field_database": "Database", + "customise_summary": "Customise features and project details", + "customise_help": "While this stays closed, the project uses the level's defaults, as when you answer “No” to the customise question in the command line.", + "features_legend": "Features", + "deployment_legend": "Deployment", + "project_legend": "Project details", + "field_package_manager": "Package manager", + "field_author": "Author", + "field_author_email": "Author email", + "email_invalid": "Enter a valid email address or leave the field empty.", + "field_description": "Description", + "field_extra_packages": "Extra packages", + "extra_packages_help": "PyPI package names separated by commas, for example: orjson, httpx>=0.28", + "extra_package_invalid": "“{package}” is not a valid package name.", + "too_long": "Use at most {max} characters.", + "too_many_packages": "Add at most {max} packages.", + "invalid_value": "This value cannot be used.", + "alembic_needs_sql": "Alembic migrations need a SQL database.", + "rule_errors_heading": "These choices do not work together", + "notes_heading": "Notes", + "checking": "Checking…", + "preview_heading": "Files", + "preview_count": "{count} files", + "preview_waiting": "The file list appears when Python has loaded.", + "executable": "executable", + "command_heading": "The same project with the command line", + "copy": "Copy", + "copied": "Copied to the clipboard.", + "copy_manual": "The command is selected. Press Ctrl+C (⌘C on macOS) to copy it.", + "git_identity_note": "Without --author and --author-email, fastkit takes them from your git config.", + "windows_shell_note": "This line is for PowerShell.", + "generate": "Generate and download", + "generating": "Generating…", + "generate_wait": "Generating is possible once Python has loaded.", + "generate_fix": "Fix the marked fields to generate the project.", + "generated": "{filename} downloaded ({count} files).", + "download_again": "Download again", + "result_heading": "Your project is ready", + "os_label": "Commands for", + "os_posix": "macOS / Linux", + "os_windows": "Windows", + "features_heading": "Selected features", + "files_label": "Files", + "settings_label": "Settings", + "docs_link": "Documentation", + "details_heading": "Messages from the generator", + "generation_failed": "The project could not be generated.", + "report_issue": "Report this problem", + "version_note": "fastkit {version} ({commit})", + "runs_on_pyodide": "Runs on Pyodide (MPL-2.0)" +} diff --git a/docs/js/web-generator-strings/es.json b/docs/js/web-generator-strings/es.json new file mode 100644 index 00000000..a08bf8b2 --- /dev/null +++ b/docs/js/web-generator-strings/es.json @@ -0,0 +1,74 @@ +{ + "intro_privacy": "Todo se ejecuta en esta página: nada de lo que escribas se envía a ningún sitio.", + "loading_runtime": "Cargando Python (Pyodide)…", + "loading_packages": "Cargando paquetes de Python…", + "loading_fastkit": "Cargando fastkit…", + "loading_note": "Unos 7 MB, que se descargan una vez y luego el navegador guarda en caché. Mientras tanto puedes rellenar el formulario.", + "ready": "Listo.", + "unsupported_browser": "Este navegador no puede ejecutar el generador: necesita WebAssembly y module workers. Usa una versión reciente de Chrome, Edge, Firefox o Safari.", + "assets_missing": "Los archivos del generador no forman parte de esta compilación. Consulta la guía de contribución para construirlos.", + "load_failed": "No se pudo iniciar el generador.", + "retry": "Reintentar", + "reload": "Recargar la página", + "cli_pointer": "También puedes crear el proyecto con la línea de comandos: instala fastkit y ejecuta fastkit init.", + "installation_link": "Guía de instalación", + "error_details": "Detalles técnicos", + "field_name": "Nombre del proyecto", + "field_name_help": "Letras, dígitos, guiones bajos y guiones. También es el nombre de la carpeta dentro del zip.", + "name_empty": "Escribe un nombre de proyecto.", + "name_characters": "Usa solo letras, dígitos, guiones bajos (_) y guiones (-), sin espacios.", + "name_digit": "El nombre no puede empezar por un dígito.", + "name_keyword": "«{name}» es una palabra reservada de Python. Elige otro nombre.", + "field_level": "Nivel", + "field_level_help": "Empieza poco a poco: cada nivel añade más estructura al proyecto.", + "field_database": "Base de datos", + "customise_summary": "Personalizar funcionalidades y datos del proyecto", + "customise_help": "Mientras esté cerrado, el proyecto usa los valores predeterminados del nivel, como cuando respondes «No» a la pregunta de personalización en la línea de comandos.", + "features_legend": "Funcionalidades", + "deployment_legend": "Despliegue", + "project_legend": "Datos del proyecto", + "field_package_manager": "Gestor de paquetes", + "field_author": "Autor", + "field_author_email": "Correo del autor", + "email_invalid": "Escribe una dirección de correo válida o deja el campo vacío.", + "field_description": "Descripción", + "field_extra_packages": "Paquetes adicionales", + "extra_packages_help": "Nombres de paquetes de PyPI separados por comas, por ejemplo: orjson, httpx>=0.28", + "extra_package_invalid": "«{package}» no es un nombre de paquete válido.", + "too_long": "Usa como máximo {max} caracteres.", + "too_many_packages": "Añade como máximo {max} paquetes.", + "invalid_value": "Este valor no se puede usar.", + "alembic_needs_sql": "Las migraciones de Alembic necesitan una base de datos SQL.", + "rule_errors_heading": "Estas opciones no son compatibles entre sí", + "notes_heading": "Notas", + "checking": "Comprobando…", + "preview_heading": "Archivos", + "preview_count": "{count} archivos", + "preview_waiting": "La lista de archivos aparece cuando Python se haya cargado.", + "executable": "ejecutable", + "command_heading": "El mismo proyecto con la línea de comandos", + "copy": "Copiar", + "copied": "Copiado al portapapeles.", + "copy_manual": "El comando está seleccionado. Pulsa Ctrl+C (⌘C en macOS) para copiarlo.", + "git_identity_note": "Sin --author y --author-email, fastkit los toma de tu git config.", + "windows_shell_note": "Esta línea es para PowerShell.", + "generate": "Generar y descargar", + "generating": "Generando…", + "generate_wait": "Se podrá generar cuando Python se haya cargado.", + "generate_fix": "Corrige los campos marcados para generar el proyecto.", + "generated": "{filename} descargado ({count} archivos).", + "download_again": "Descargar de nuevo", + "result_heading": "Tu proyecto está listo", + "os_label": "Comandos para", + "os_posix": "macOS / Linux", + "os_windows": "Windows", + "features_heading": "Funcionalidades seleccionadas", + "files_label": "Archivos", + "settings_label": "Configuración", + "docs_link": "Documentación", + "details_heading": "Mensajes del generador", + "generation_failed": "No se pudo generar el proyecto.", + "report_issue": "Informar de este problema", + "version_note": "fastkit {version} ({commit})", + "runs_on_pyodide": "Funciona con Pyodide (MPL-2.0)" +} diff --git a/docs/js/web-generator-strings/fr.json b/docs/js/web-generator-strings/fr.json new file mode 100644 index 00000000..df38b5bc --- /dev/null +++ b/docs/js/web-generator-strings/fr.json @@ -0,0 +1,74 @@ +{ + "intro_privacy": "Tout s'exécute sur cette page : rien de ce que vous saisissez n'est envoyé ailleurs.", + "loading_runtime": "Chargement de Python (Pyodide)…", + "loading_packages": "Chargement des paquets Python…", + "loading_fastkit": "Chargement de fastkit…", + "loading_note": "Environ 7 Mo, téléchargés une seule fois puis mis en cache par votre navigateur. Vous pouvez remplir le formulaire en attendant.", + "ready": "Prêt.", + "unsupported_browser": "Ce navigateur ne peut pas exécuter le générateur : il faut WebAssembly et les module workers. Utilisez une version récente de Chrome, Edge, Firefox ou Safari.", + "assets_missing": "Les fichiers du générateur ne font pas partie de cette version. Consultez le guide de contribution pour les construire.", + "load_failed": "Le générateur n'a pas pu démarrer.", + "retry": "Réessayer", + "reload": "Recharger la page", + "cli_pointer": "Vous pouvez aussi créer le projet en ligne de commande : installez fastkit et lancez fastkit init.", + "installation_link": "Guide d'installation", + "error_details": "Détails techniques", + "field_name": "Nom du projet", + "field_name_help": "Lettres, chiffres, tirets bas et tirets. C'est aussi le nom du dossier dans le zip.", + "name_empty": "Saisissez un nom de projet.", + "name_characters": "Utilisez uniquement des lettres, des chiffres, des tirets bas (_) et des tirets (-), sans espaces.", + "name_digit": "Le nom ne peut pas commencer par un chiffre.", + "name_keyword": "« {name} » est un mot réservé de Python. Choisissez un autre nom.", + "field_level": "Niveau", + "field_level_help": "Commencez petit : chaque niveau ajoute de la structure au projet.", + "field_database": "Base de données", + "customise_summary": "Personnaliser les fonctionnalités et le projet", + "customise_help": "Tant que cette section reste fermée, le projet utilise les valeurs par défaut du niveau, comme lorsque vous répondez « Non » à la question de personnalisation en ligne de commande.", + "features_legend": "Fonctionnalités", + "deployment_legend": "Déploiement", + "project_legend": "Détails du projet", + "field_package_manager": "Gestionnaire de paquets", + "field_author": "Auteur", + "field_author_email": "E-mail de l'auteur", + "email_invalid": "Saisissez une adresse e-mail valide ou laissez le champ vide.", + "field_description": "Description", + "field_extra_packages": "Paquets supplémentaires", + "extra_packages_help": "Noms de paquets PyPI séparés par des virgules, par exemple : orjson, httpx>=0.28", + "extra_package_invalid": "« {package} » n'est pas un nom de paquet valide.", + "too_long": "Utilisez au maximum {max} caractères.", + "too_many_packages": "Ajoutez au maximum {max} paquets.", + "invalid_value": "Cette valeur ne peut pas être utilisée.", + "alembic_needs_sql": "Les migrations Alembic nécessitent une base de données SQL.", + "rule_errors_heading": "Ces choix sont incompatibles", + "notes_heading": "Remarques", + "checking": "Vérification…", + "preview_heading": "Fichiers", + "preview_count": "{count} fichiers", + "preview_waiting": "La liste des fichiers apparaît une fois Python chargé.", + "executable": "exécutable", + "command_heading": "Le même projet en ligne de commande", + "copy": "Copier", + "copied": "Copié dans le presse-papiers.", + "copy_manual": "La commande est sélectionnée. Appuyez sur Ctrl+C (⌘C sur macOS) pour la copier.", + "git_identity_note": "Sans --author ni --author-email, fastkit les prend dans votre git config.", + "windows_shell_note": "Cette ligne est destinée à PowerShell.", + "generate": "Générer et télécharger", + "generating": "Génération…", + "generate_wait": "La génération sera possible une fois Python chargé.", + "generate_fix": "Corrigez les champs signalés pour générer le projet.", + "generated": "{filename} téléchargé ({count} fichiers).", + "download_again": "Télécharger à nouveau", + "result_heading": "Votre projet est prêt", + "os_label": "Commandes pour", + "os_posix": "macOS / Linux", + "os_windows": "Windows", + "features_heading": "Fonctionnalités sélectionnées", + "files_label": "Fichiers", + "settings_label": "Paramètres", + "docs_link": "Documentation", + "details_heading": "Messages du générateur", + "generation_failed": "Le projet n'a pas pu être généré.", + "report_issue": "Signaler ce problème", + "version_note": "fastkit {version} ({commit})", + "runs_on_pyodide": "Fonctionne avec Pyodide (MPL-2.0)" +} diff --git a/docs/js/web-generator-strings/ja.json b/docs/js/web-generator-strings/ja.json new file mode 100644 index 00000000..78338803 --- /dev/null +++ b/docs/js/web-generator-strings/ja.json @@ -0,0 +1,74 @@ +{ + "intro_privacy": "すべての処理はこのページ上で実行され、入力した内容はどこにも送信されません。", + "loading_runtime": "Python(Pyodide)を読み込んでいます…", + "loading_packages": "Python パッケージを読み込んでいます…", + "loading_fastkit": "fastkit を読み込んでいます…", + "loading_note": "約 7 MB で、一度ダウンロードするとブラウザにキャッシュされます。その間にフォームを入力できます。", + "ready": "準備ができました。", + "unsupported_browser": "このブラウザではジェネレーターを実行できません。WebAssembly とモジュールワーカーが必要です。最新版の Chrome、Edge、Firefox、Safari を使ってください。", + "assets_missing": "このビルドにはジェネレーターのファイルが含まれていません。作成方法はコントリビューションガイドを参照してください。", + "load_failed": "ジェネレーターを起動できませんでした。", + "retry": "もう一度試す", + "reload": "ページを再読み込み", + "cli_pointer": "コマンドラインでもプロジェクトを作成できます。fastkit をインストールして fastkit init を実行してください。", + "installation_link": "インストールガイド", + "error_details": "技術的な詳細", + "field_name": "プロジェクト名", + "field_name_help": "英字、数字、アンダースコア、ハイフンが使えます。zip 内のフォルダー名にもなります。", + "name_empty": "プロジェクト名を入力してください。", + "name_characters": "英字、数字、アンダースコア(_)、ハイフン(-)のみを使い、スペースは入れないでください。", + "name_digit": "名前は数字で始められません。", + "name_keyword": "「{name}」は Python の予約語です。別の名前を選んでください。", + "field_level": "レベル", + "field_level_help": "小さく始めましょう。レベルが上がるほど、プロジェクトの構造が増えます。", + "field_database": "データベース", + "customise_summary": "機能とプロジェクト情報をカスタマイズ", + "customise_help": "ここを開かない場合は、そのレベルの既定値でプロジェクトを作成します。コマンドラインでカスタマイズの質問に「No」と答えた場合と同じです。", + "features_legend": "機能", + "deployment_legend": "デプロイ", + "project_legend": "プロジェクト情報", + "field_package_manager": "パッケージマネージャー", + "field_author": "作成者", + "field_author_email": "作成者のメールアドレス", + "email_invalid": "有効なメールアドレスを入力するか、空のままにしてください。", + "field_description": "説明", + "field_extra_packages": "追加パッケージ", + "extra_packages_help": "カンマ区切りの PyPI パッケージ名です。例: orjson, httpx>=0.28", + "extra_package_invalid": "「{package}」は有効なパッケージ名ではありません。", + "too_long": "{max} 文字以内で入力してください。", + "too_many_packages": "パッケージは {max} 個まで追加できます。", + "invalid_value": "この値は使用できません。", + "alembic_needs_sql": "Alembic のマイグレーションには SQL データベースが必要です。", + "rule_errors_heading": "一緒に使えない選択があります", + "notes_heading": "メモ", + "checking": "確認しています…", + "preview_heading": "ファイル", + "preview_count": "{count} ファイル", + "preview_waiting": "Python の読み込みが終わると、ファイル一覧が表示されます。", + "executable": "実行可能", + "command_heading": "コマンドラインで作成する同じプロジェクト", + "copy": "コピー", + "copied": "クリップボードにコピーしました。", + "copy_manual": "コマンドを選択しました。Ctrl+C(macOS では ⌘C)を押してコピーしてください。", + "git_identity_note": "--author と --author-email を指定しない場合、fastkit は git config から値を取得します。", + "windows_shell_note": "この行は PowerShell 用です。", + "generate": "生成してダウンロード", + "generating": "生成しています…", + "generate_wait": "Python の読み込みが終わると生成できます。", + "generate_fix": "印の付いた項目を修正すると、プロジェクトを生成できます。", + "generated": "{filename} をダウンロードしました({count} ファイル)。", + "download_again": "もう一度ダウンロード", + "result_heading": "プロジェクトができました", + "os_label": "コマンドの対象 OS", + "os_posix": "macOS / Linux", + "os_windows": "Windows", + "features_heading": "選択した機能", + "files_label": "ファイル", + "settings_label": "設定", + "docs_link": "ドキュメント", + "details_heading": "ジェネレーターからのメッセージ", + "generation_failed": "プロジェクトを生成できませんでした。", + "report_issue": "この問題を報告", + "version_note": "fastkit {version} ({commit})", + "runs_on_pyodide": "Pyodide で動作しています(MPL-2.0)" +} diff --git a/docs/js/web-generator-strings/ko.json b/docs/js/web-generator-strings/ko.json new file mode 100644 index 00000000..bb2e39d4 --- /dev/null +++ b/docs/js/web-generator-strings/ko.json @@ -0,0 +1,74 @@ +{ + "intro_privacy": "모든 작업이 이 페이지 안에서 실행되며, 입력한 내용은 어디로도 전송되지 않습니다.", + "loading_runtime": "Python(Pyodide)을 불러오는 중…", + "loading_packages": "Python 패키지를 불러오는 중…", + "loading_fastkit": "fastkit을 불러오는 중…", + "loading_note": "약 7 MB이며, 한 번 내려받으면 브라우저에 저장됩니다. 그동안 양식을 먼저 작성해도 됩니다.", + "ready": "준비되었습니다.", + "unsupported_browser": "이 브라우저에서는 생성기를 실행할 수 없습니다. WebAssembly와 모듈 워커가 필요하므로 최신 버전의 Chrome, Edge, Firefox, Safari를 사용하세요.", + "assets_missing": "이 빌드에는 생성기 파일이 포함되어 있지 않습니다. 파일을 만드는 방법은 기여 가이드를 참고하세요.", + "load_failed": "생성기를 시작하지 못했습니다.", + "retry": "다시 시도", + "reload": "페이지 새로고침", + "cli_pointer": "명령줄로도 프로젝트를 만들 수 있습니다. fastkit을 설치한 다음 fastkit init을 실행하세요.", + "installation_link": "설치 가이드", + "error_details": "기술 세부 정보", + "field_name": "프로젝트 이름", + "field_name_help": "영문자, 숫자, 밑줄, 하이픈을 사용할 수 있습니다. zip 안의 폴더 이름으로도 쓰입니다.", + "name_empty": "프로젝트 이름을 입력하세요.", + "name_characters": "영문자, 숫자, 밑줄(_), 하이픈(-)만 사용하고 공백은 넣지 마세요.", + "name_digit": "이름은 숫자로 시작할 수 없습니다.", + "name_keyword": "“{name}”은(는) Python의 예약어입니다. 다른 이름을 선택하세요.", + "field_level": "단계", + "field_level_help": "작게 시작하세요. 단계가 올라갈수록 프로젝트에 구조가 더 추가됩니다.", + "field_database": "데이터베이스", + "customise_summary": "기능과 프로젝트 정보 직접 설정", + "customise_help": "이 항목을 열지 않으면 해당 단계의 기본값으로 프로젝트를 만듭니다. 명령줄에서 맞춤 설정 질문에 “아니요”라고 답하는 것과 같습니다.", + "features_legend": "기능", + "deployment_legend": "배포", + "project_legend": "프로젝트 정보", + "field_package_manager": "패키지 관리자", + "field_author": "작성자", + "field_author_email": "작성자 이메일", + "email_invalid": "올바른 이메일 주소를 입력하거나 비워 두세요.", + "field_description": "설명", + "field_extra_packages": "추가 패키지", + "extra_packages_help": "쉼표로 구분한 PyPI 패키지 이름입니다. 예: orjson, httpx>=0.28", + "extra_package_invalid": "“{package}”은(는) 올바른 패키지 이름이 아닙니다.", + "too_long": "{max}자 이내로 입력하세요.", + "too_many_packages": "패키지는 {max}개까지 추가할 수 있습니다.", + "invalid_value": "이 값은 사용할 수 없습니다.", + "alembic_needs_sql": "Alembic 마이그레이션에는 SQL 데이터베이스가 필요합니다.", + "rule_errors_heading": "함께 사용할 수 없는 선택이 있습니다", + "notes_heading": "참고", + "checking": "확인하는 중…", + "preview_heading": "파일", + "preview_count": "파일 {count}개", + "preview_waiting": "Python을 불러오면 파일 목록이 표시됩니다.", + "executable": "실행 가능", + "command_heading": "명령줄로 만드는 같은 프로젝트", + "copy": "복사", + "copied": "클립보드에 복사했습니다.", + "copy_manual": "명령이 선택되었습니다. Ctrl+C(macOS에서는 ⌘C)를 눌러 복사하세요.", + "git_identity_note": "--author와 --author-email을 지정하지 않으면 fastkit이 git config에서 값을 가져옵니다.", + "windows_shell_note": "이 줄은 PowerShell용입니다.", + "generate": "생성하고 내려받기", + "generating": "생성하는 중…", + "generate_wait": "Python을 불러온 뒤에 생성할 수 있습니다.", + "generate_fix": "표시된 항목을 수정하면 프로젝트를 생성할 수 있습니다.", + "generated": "{filename}을(를) 내려받았습니다(파일 {count}개).", + "download_again": "다시 내려받기", + "result_heading": "프로젝트가 준비되었습니다", + "os_label": "명령 실행 환경", + "os_posix": "macOS / Linux", + "os_windows": "Windows", + "features_heading": "선택한 기능", + "files_label": "파일", + "settings_label": "설정", + "docs_link": "문서", + "details_heading": "생성기가 보낸 메시지", + "generation_failed": "프로젝트를 생성하지 못했습니다.", + "report_issue": "이 문제 신고하기", + "version_note": "fastkit {version} ({commit})", + "runs_on_pyodide": "Pyodide로 실행됩니다(MPL-2.0)" +} diff --git a/docs/js/web-generator-strings/zh.json b/docs/js/web-generator-strings/zh.json new file mode 100644 index 00000000..28097c81 --- /dev/null +++ b/docs/js/web-generator-strings/zh.json @@ -0,0 +1,74 @@ +{ + "intro_privacy": "所有操作都在本页面中运行,你输入的内容不会发送到任何地方。", + "loading_runtime": "正在加载 Python(Pyodide)…", + "loading_packages": "正在加载 Python 包…", + "loading_fastkit": "正在加载 fastkit…", + "loading_note": "约 7 MB,下载一次后会由浏览器缓存。加载期间你可以先填写表单。", + "ready": "已就绪。", + "unsupported_browser": "此浏览器无法运行生成器:它需要 WebAssembly 和模块 Worker。请使用较新版本的 Chrome、Edge、Firefox 或 Safari。", + "assets_missing": "此构建不包含生成器文件。请参阅贡献指南了解如何构建它们。", + "load_failed": "生成器无法启动。", + "retry": "重试", + "reload": "重新加载页面", + "cli_pointer": "你也可以用命令行创建项目:安装 fastkit,然后运行 fastkit init。", + "installation_link": "安装指南", + "error_details": "技术详情", + "field_name": "项目名称", + "field_name_help": "可使用字母、数字、下划线和连字符,同时也是 zip 内的文件夹名称。", + "name_empty": "请输入项目名称。", + "name_characters": "只能使用字母、数字、下划线(_)和连字符(-),不能包含空格。", + "name_digit": "名称不能以数字开头。", + "name_keyword": "“{name}”是 Python 的保留字,请换一个名称。", + "field_level": "级别", + "field_level_help": "从小处开始:每提高一个级别,项目就多一层结构。", + "field_database": "数据库", + "customise_summary": "自定义功能和项目详情", + "customise_help": "保持折叠时,项目使用该级别的默认设置,相当于在命令行中对自定义提问回答“否”。", + "features_legend": "功能", + "deployment_legend": "部署", + "project_legend": "项目详情", + "field_package_manager": "包管理器", + "field_author": "作者", + "field_author_email": "作者邮箱", + "email_invalid": "请输入有效的邮箱地址,或将此项留空。", + "field_description": "描述", + "field_extra_packages": "额外的包", + "extra_packages_help": "用逗号分隔的 PyPI 包名,例如:orjson, httpx>=0.28", + "extra_package_invalid": "“{package}”不是有效的包名。", + "too_long": "最多使用 {max} 个字符。", + "too_many_packages": "最多添加 {max} 个包。", + "invalid_value": "无法使用此值。", + "alembic_needs_sql": "Alembic 迁移需要 SQL 数据库。", + "rule_errors_heading": "这些选择不能同时使用", + "notes_heading": "说明", + "checking": "正在检查…", + "preview_heading": "文件", + "preview_count": "{count} 个文件", + "preview_waiting": "Python 加载完成后会显示文件列表。", + "executable": "可执行", + "command_heading": "用命令行创建同样的项目", + "copy": "复制", + "copied": "已复制到剪贴板。", + "copy_manual": "命令已选中。请按 Ctrl+C(macOS 上为 ⌘C)复制。", + "git_identity_note": "如果不指定 --author 和 --author-email,fastkit 会从你的 git config 中读取。", + "windows_shell_note": "这一行适用于 PowerShell。", + "generate": "生成并下载", + "generating": "正在生成…", + "generate_wait": "Python 加载完成后才能生成。", + "generate_fix": "请修正标记的字段,然后生成项目。", + "generated": "已下载 {filename}({count} 个文件)。", + "download_again": "再次下载", + "result_heading": "项目已就绪", + "os_label": "命令适用于", + "os_posix": "macOS / Linux", + "os_windows": "Windows", + "features_heading": "已选功能", + "files_label": "文件", + "settings_label": "设置", + "docs_link": "文档", + "details_heading": "生成器发出的消息", + "generation_failed": "无法生成项目。", + "report_issue": "报告此问题", + "version_note": "fastkit {version} ({commit})", + "runs_on_pyodide": "运行于 Pyodide(MPL-2.0)" +} diff --git a/docs/js/web-generator-worker.mjs b/docs/js/web-generator-worker.mjs new file mode 100644 index 00000000..644b2b57 --- /dev/null +++ b/docs/js/web-generator-worker.mjs @@ -0,0 +1,90 @@ +// Module worker for the web generator page: loads Pyodide and fastkit off the +// main thread and answers {id, type: "check" | "build", form, lang} messages. + +import { startGenerator } from "./web-generator-core.mjs"; + +let generator = null; +let startup = null; + +async function readBytes(url) { + // Revalidate: manifest.json and the wheel keep their names across docs + // deploys, and a stale copy of one would fail the sha256 check. + const response = await fetch(url, { credentials: "same-origin", cache: "no-cache" }); + if (!response.ok) { + const error = new Error(response.status + " " + response.statusText + ": " + url); + error.status = response.status; + throw error; + } + return new Uint8Array(await response.arrayBuffer()); +} + +function describe(error) { + const kind = error && error.kind ? error.kind : "internal"; + const message = error && error.message ? error.message : String(error); + const out = { kind, message }; + if (error && error.problems) out.problems = error.problems; + return out; +} + +function start(assetsURL) { + if (startup) return startup; + startup = startGenerator({ + assetsURL, + readBytes, + onStage(stage) { + self.postMessage({ type: "stage", stage }); + }, + }).then( + (started) => { + generator = started; + const { manifest } = started; + self.postMessage({ + type: "ready", + manifest: { + fastkit_version: manifest.fastkit_version || "", + commit: manifest.commit || "", + pyodide_version: manifest.pyodide_version || "", + }, + }); + }, + (error) => { + // Allow a later "start" (the page's retry) to try again. + startup = null; + self.postMessage({ type: "failed", error: describe(error) }); + }, + ); + return startup; +} + +async function answer(message) { + const { id, type, form, lang } = message; + if (!generator) { + self.postMessage({ id, ok: false, error: { kind: "load", message: "the generator is not ready" } }); + return; + } + try { + if (type === "check") { + const result = await generator.check(form, lang); + self.postMessage({ id, ok: true, result }); + } else if (type === "build") { + const { zip, meta } = await generator.build(form, lang); + const buffer = zip.buffer.slice(zip.byteOffset, zip.byteOffset + zip.byteLength); + self.postMessage({ id, ok: true, result: { zip: buffer, meta } }, [buffer]); + } else { + self.postMessage({ id, ok: false, error: { kind: "internal", message: "unknown message " + type } }); + } + } catch (error) { + self.postMessage({ id, ok: false, error: describe(error) }); + } +} + +self.addEventListener("message", (event) => { + const message = event.data || {}; + if (message.type === "start") { + start(message.assetsURL); + } else if (message.type === "ping") { + self.postMessage({ type: "pong" }); + } else { + answer(message); + } +}); diff --git a/docs/js/web-generator.mjs b/docs/js/web-generator.mjs new file mode 100644 index 00000000..c6dbf1c1 --- /dev/null +++ b/docs/js/web-generator.mjs @@ -0,0 +1,1207 @@ +// Web generator page: renders the form from the precomputed model at once and +// lets a module worker (web-generator-worker.mjs) run fastkit in Pyodide. +// Every visible text comes from web-generator-strings/.json or from the +// model (catalog text). User and catalog text is only ever set as text. +// +// The page loads this module with a plain diff --git a/docs/zh/start/web-generator.md b/docs/zh/start/web-generator.md new file mode 100644 index 00000000..ce63aa47 --- /dev/null +++ b/docs/zh/start/web-generator.md @@ -0,0 +1,16 @@ +--- +hide: + - toc +--- +# 网页生成器 + +在浏览器中创建 fastkit 项目。本页面用 [Pyodide](https://pyodide.org/) 直接运行 fastkit 生成器,因此你下载的 zip 中的文件,与按所选选项运行 +`fastkit init ... --no-venv` 得到的文件相同。你输入的内容不会离开浏览器。 + +
+ +

生成器正在启动…

+ +
+ diff --git a/mkdocs.yml b/mkdocs.yml index 78810669..b502ced5 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -59,6 +59,7 @@ plugins: build: true nav_translations: Home: 홈 + Web Generator: 웹 생성기 User Guide: 사용자 가이드 Tutorial: 튜토리얼 Contributing: 기여하기 @@ -69,6 +70,7 @@ plugins: build: true nav_translations: Home: ホーム + Web Generator: Webジェネレーター User Guide: ユーザーガイド Tutorial: チュートリアル Contributing: 貢献 @@ -79,6 +81,7 @@ plugins: build: true nav_translations: Home: 首页 + Web Generator: 网页生成器 User Guide: 用户指南 Tutorial: 教程 Contributing: 贡献 @@ -89,6 +92,7 @@ plugins: build: true nav_translations: Home: Inicio + Web Generator: Generador web User Guide: Guía del Usuario Tutorial: Tutorial Contributing: Contribuir @@ -99,6 +103,7 @@ plugins: build: true nav_translations: Home: Accueil + Web Generator: Générateur web User Guide: Guide de l'Utilisateur Tutorial: Tutoriel Contributing: Contribuer @@ -109,6 +114,7 @@ plugins: build: true nav_translations: Home: Startseite + Web Generator: Web-Generator User Guide: Benutzerhandbuch Tutorial: Tutorial Contributing: Beitragen @@ -117,6 +123,7 @@ plugins: nav: - Home: index.md + - Web Generator: start/web-generator.md - User Guide: - Installation: user-guide/installation.md - Quick Start: user-guide/quick-start.md @@ -168,6 +175,7 @@ markdown_extensions: extra_css: - css/termynal.css - css/custom.css + - css/web-generator.css extra_javascript: - js/termynal.js diff --git a/pdm.lock b/pdm.lock index 78ce79dd..4405950d 100644 --- a/pdm.lock +++ b/pdm.lock @@ -2,20 +2,42 @@ # It is not intended for manual editing. [metadata] -groups = ["default", "dev", "docs", "translation"] +groups = ["default", "dev", "docs", "test-runtime", "translation"] strategy = ["inherit_metadata"] lock_version = "4.5.0" -content_hash = "sha256:5454dfa2e948ec296f599d8bd6c1971361b1689d1dfaacd9cfa4e91c22ae4b50" +content_hash = "sha256:56e8c86505c1513ca24b2552ede59133d1ee56c035124e1575e6a120a4229487" [[metadata.targets]] requires_python = ">=3.12" +[[package]] +name = "aiofiles" +version = "25.1.0" +requires_python = ">=3.9" +summary = "File support for asyncio." +groups = ["test-runtime"] +files = [ + {file = "aiofiles-25.1.0-py3-none-any.whl", hash = "sha256:abe311e527c862958650f9438e859c1fa7568a141b22abcd015e120e86a85695"}, + {file = "aiofiles-25.1.0.tar.gz", hash = "sha256:a8d728f0a29de45dc521f18f07297428d56992a742f0cd2701ba86e44d23d5b2"}, +] + +[[package]] +name = "annotated-doc" +version = "0.0.7" +requires_python = ">=3.11" +summary = "Document parameters, class attributes, return types, and variables inline, with Annotated." +groups = ["test-runtime"] +files = [ + {file = "annotated_doc-0.0.7-py3-none-any.whl", hash = "sha256:6bc31bbbec6dfaaedc1676dbc11dbda96fe22a2b5c400e9ebad113fec44a9dc6"}, + {file = "annotated_doc-0.0.7.tar.gz", hash = "sha256:0a30ef8f5322a4173720ae6712dc9a5e58f5a19868f3f167b4b5778db066c2b5"}, +] + [[package]] name = "annotated-types" version = "0.7.0" requires_python = ">=3.8" summary = "Reusable constraint types to use with typing.Annotated" -groups = ["translation"] +groups = ["test-runtime", "translation"] dependencies = [ "typing-extensions>=4.0.0; python_version < \"3.9\"", ] @@ -50,7 +72,7 @@ name = "anyio" version = "4.15.1" requires_python = ">=3.10" summary = "High-level concurrency and networking framework on top of asyncio or Trio" -groups = ["translation"] +groups = ["test-runtime", "translation"] dependencies = [ "exceptiongroup>=1.0.2; python_version < \"3.11\"", "idna>=2.8", @@ -195,7 +217,7 @@ name = "certifi" version = "2026.10.23" requires_python = ">=3.7" summary = "Python package for providing Mozilla's CA Bundle." -groups = ["docs", "translation"] +groups = ["docs", "test-runtime", "translation"] files = [ {file = "certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1"}, {file = "certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd"}, @@ -531,6 +553,26 @@ files = [ {file = "docstring_parser-0.18.0.tar.gz", hash = "sha256:292510982205c12b1248696f44959db3cdd1740237a968ea1e2e7a900eeb2015"}, ] +[[package]] +name = "fastapi" +version = "0.165.0" +requires_python = ">=3.11" +summary = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" +groups = ["test-runtime"] +dependencies = [ + "annotated-doc>=0.0.2", + "anyio>=4.1.0", + "opentelemetry-api>=1.44.0", + "pydantic>=2.9.0", + "starlette>=1.6.0", + "typing-extensions>=4.8.0", + "typing-inspection>=0.4.2", +] +files = [ + {file = "fastapi-0.165.0-py3-none-any.whl", hash = "sha256:896f48462042bb4f162147eb8fac7e858753dc1f486765709baf105d70e4fc5b"}, + {file = "fastapi-0.165.0.tar.gz", hash = "sha256:dd94d4128319c1e1d50535ab023ab698f850a4d2822f0e181747b46f4ff3c0ab"}, +] + [[package]] name = "filelock" version = "4.2.4" @@ -560,7 +602,7 @@ name = "h11" version = "0.16.0" requires_python = ">=3.8" summary = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1" -groups = ["translation"] +groups = ["test-runtime", "translation"] files = [ {file = "h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86"}, {file = "h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1"}, @@ -571,7 +613,7 @@ name = "httpcore" version = "1.0.9" requires_python = ">=3.8" summary = "A minimal low-level HTTP client." -groups = ["translation"] +groups = ["test-runtime", "translation"] dependencies = [ "certifi", "h11>=0.16", @@ -586,7 +628,7 @@ name = "httpx" version = "0.28.1" requires_python = ">=3.8" summary = "The next generation HTTP client." -groups = ["translation"] +groups = ["test-runtime", "translation"] dependencies = [ "anyio", "certifi", @@ -614,7 +656,7 @@ name = "idna" version = "3.19" requires_python = ">=3.9" summary = "Internationalized Domain Names in Applications (IDNA)" -groups = ["docs", "translation"] +groups = ["docs", "test-runtime", "translation"] files = [ {file = "idna-3.19-py3-none-any.whl", hash = "sha256:815e7be7a7806d54abb586dc943addc79e8b2ee16915059658cbeff4b1b43bf4"}, {file = "idna-3.19.tar.gz", hash = "sha256:5e0811a4383b21dc5838069f801c4fb62113b7447663d2530d2bd6e77b49bf15"}, @@ -1185,6 +1227,20 @@ files = [ {file = "openai-2.32.0.tar.gz", hash = "sha256:c54b27a9e4cb8d51f0dd94972ffd1a04437efeb259a9e60d8922b8bd26fe55e0"}, ] +[[package]] +name = "opentelemetry-api" +version = "1.45.3" +requires_python = ">=3.10" +summary = "OpenTelemetry Python API" +groups = ["test-runtime"] +dependencies = [ + "typing-extensions>=4.5.0", +] +files = [ + {file = "opentelemetry_api-1.45.3-py3-none-any.whl", hash = "sha256:7b9fcabfdfda5167446caa86641f085915fc1eb7ea9cbd23038c861f6a3c02bf"}, + {file = "opentelemetry_api-1.45.3.tar.gz", hash = "sha256:3b8b2769fffe5118a310c93639da9c02cbbcfde488866c721b0e7bc0d67a4ab5"}, +] + [[package]] name = "packaging" version = "26.3" @@ -1262,7 +1318,7 @@ name = "pydantic" version = "2.13.1" requires_python = ">=3.9" summary = "Data validation using Python type hints" -groups = ["translation"] +groups = ["test-runtime", "translation"] dependencies = [ "annotated-types>=0.6.0", "pydantic-core==2.46.1", @@ -1279,7 +1335,7 @@ name = "pydantic-core" version = "2.46.1" requires_python = ">=3.9" summary = "Core functionality for Pydantic validation and serialization" -groups = ["translation"] +groups = ["test-runtime", "translation"] dependencies = [ "typing-extensions>=4.14.1", ] @@ -1347,6 +1403,23 @@ files = [ {file = "pydantic_core-2.46.1.tar.gz", hash = "sha256:d408153772d9f298098fb5d620f045bdf0f017af0d5cb6e309ef8c205540caa4"}, ] +[[package]] +name = "pydantic-settings" +version = "2.16.3" +requires_python = ">=3.11" +summary = "Settings management using Pydantic" +groups = ["test-runtime"] +dependencies = [ + "pydantic>=2.7.0", + "python-dotenv>=1.2.2", + "typing-extensions>=4.0.0", + "typing-inspection>=0.4.0", +] +files = [ + {file = "pydantic_settings-2.16.3-py3-none-any.whl", hash = "sha256:d1db16a2d34006323a1b42c0640898da58adfbad7ec30baaa9e2b18aafc08999"}, + {file = "pydantic_settings-2.16.3.tar.gz", hash = "sha256:10e36f616623ebb586c05ca3d3cd22927146869db413d4f14c20c514442a1337"}, +] + [[package]] name = "pygments" version = "2.20.0" @@ -1437,6 +1510,17 @@ files = [ {file = "python_discovery-1.6.4.tar.gz", hash = "sha256:bc70d31f0ec5de11eda13d4d64c16e24b3506a65984684f2b6c98cb83b2ea9df"}, ] +[[package]] +name = "python-dotenv" +version = "1.2.4" +requires_python = ">=3.10" +summary = "Read key-value pairs from a .env file and set them as environment variables" +groups = ["test-runtime"] +files = [ + {file = "python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc"}, + {file = "python_dotenv-1.2.4.tar.gz", hash = "sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0"}, +] + [[package]] name = "pytokens" version = "0.4.1" @@ -1473,7 +1557,7 @@ name = "pyyaml" version = "6.0.3" requires_python = ">=3.8" summary = "YAML parser and emitter for Python" -groups = ["dev", "docs"] +groups = ["dev", "docs", "test-runtime"] files = [ {file = "pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196"}, {file = "pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0"}, @@ -1621,6 +1705,21 @@ files = [ {file = "sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc"}, ] +[[package]] +name = "starlette" +version = "1.10.0" +requires_python = ">=3.11" +summary = "The little ASGI library that shines." +groups = ["test-runtime"] +dependencies = [ + "anyio<5,>=4.0.0", + "typing-extensions>=4.10.0; python_version < \"3.13\"", +] +files = [ + {file = "starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4"}, + {file = "starlette-1.10.0.tar.gz", hash = "sha256:b8399098d4c1e3522734f7235dc79b1fc967f96cf139c81e0fa30479e0685f9b"}, +] + [[package]] name = "tqdm" version = "4.67.3" @@ -1652,7 +1751,7 @@ name = "typing-extensions" version = "4.16.0" requires_python = ">=3.9" summary = "Backported and Experimental Type Hints for Python 3.9+" -groups = ["dev", "translation"] +groups = ["dev", "test-runtime", "translation"] files = [ {file = "typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8"}, {file = "typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5"}, @@ -1663,7 +1762,7 @@ name = "typing-inspection" version = "0.4.2" requires_python = ">=3.9" summary = "Runtime typing introspection tools" -groups = ["translation"] +groups = ["test-runtime", "translation"] dependencies = [ "typing-extensions>=4.12.0", ] diff --git a/pyproject.toml b/pyproject.toml index c6b6910b..bf71e822 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -118,6 +118,14 @@ docs = [ # 2.20+ (NoneType filename passed to html.escape), see pymdown-extensions#2580. "pymdown-extensions>=11.0.1", ] +# Lets the tests that start generated applications run (CI included). +test-runtime = [ + "fastapi>=0.141.1", + "httpx>=0.28.1", + "pydantic-settings>=2.15.0", + "aiofiles>=25.1.0", + "pyyaml>=6.0.3", +] translation = [ "openai>=2.8.1", "anthropic>=0.74.0", diff --git a/scripts/web_generator/build_assets.py b/scripts/web_generator/build_assets.py new file mode 100644 index 00000000..8ae42fa8 --- /dev/null +++ b/scripts/web_generator/build_assets.py @@ -0,0 +1,629 @@ +#!/usr/bin/env python3 +# -------------------------------------------------------------------------- +# Build the files the web generator page loads (docs/en/assets/fastkit-generator) +# +# Run with an interpreter in which the fastkit wheel given by --wheel is +# installed: the form models are computed by that installed package. +# +# python -m pip wheel --no-deps -w dist . +# python -m pip install dist/fastapi_fastkit-*.whl +# python scripts/web_generator/build_assets.py --wheel dist/fastapi_fastkit-*.whl \ +# --out docs/en/assets/fastkit-generator +# +# Stdlib only. Every download is checked: the Pyodide npm tarball against the +# pinned integrity in pyodide.toml, the package wheels against the sha256 in +# the tarball's pyodide-lock.json. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import argparse +import base64 +import glob +import hashlib +import io +import json +import os +import posixpath +import re +import shutil +import sys +import tarfile +import tomllib +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence + +HERE = os.path.dirname(os.path.abspath(__file__)) +DEFAULT_CONFIG = os.path.join(HERE, "pyodide.toml") +DEFAULT_CACHE = os.path.join(".cache", "web-generator") +MANIFEST_SCHEMA = 1 +PYODIDE_DIR = "pyodide" +TARBALL_PREFIX = "package/" +FASTKIT_SOURCE = "https://github.com/bnbong/FastAPI-kit" +CPYTHON_SOURCE = "https://github.com/python/cpython" +WHEEL_NAME = re.compile( + r"^fastapi_fastkit-(?P[^-]+)(-\d[^-]*)?-py3-none-any\.whl$", re.I +) + +Fetch = Callable[[str], bytes] + + +class BuildError(Exception): + """A problem that stops the build; the message is printed as one line.""" + + +@dataclass(frozen=True) +class PyodideConfig: + version: str + tarball: str + integrity: str + wheel_base: str + packages: List[str] + core_files: List[str] + license: str + source: str + notices: Dict[str, Dict[str, str]] = field(default_factory=dict) + + +def load_config(path: str = DEFAULT_CONFIG) -> PyodideConfig: + with open(path, "rb") as handle: + data = tomllib.load(handle) + try: + config = PyodideConfig( + version=str(data["version"]), + tarball=str(data["tarball"]), + integrity=str(data["integrity"]), + wheel_base=str(data["wheel_base"]), + packages=[str(p) for p in data["packages"]], + core_files=[str(f) for f in data["core_files"]], + license=str(data["license"]), + source=str(data["source"]), + notices={str(k): dict(v) for k, v in data.get("notices", {}).items()}, + ) + except (KeyError, TypeError, AttributeError) as exc: + raise BuildError(f"{path}: missing or invalid key {exc}") from exc + for name in config.core_files: + if "/" in name or "\\" in name or name in ("", ".", ".."): + raise BuildError(f"{path}: core file {name!r} must be a plain file name") + if not config.wheel_base.endswith("/"): + raise BuildError(f"{path}: wheel_base must end with '/'") + return config + + +# ---------------------------------------------------------------- integrity + + +def check_integrity(data: bytes, integrity: str, what: str) -> None: + """Check ``data`` against an npm/SRI integrity string (``sha512-``).""" + algorithm, sep, expected = integrity.partition("-") + if not sep or algorithm not in ("sha256", "sha384", "sha512"): + raise BuildError(f"unsupported integrity value for {what}: {integrity!r}") + actual = base64.b64encode(hashlib.new(algorithm, data).digest()).decode("ascii") + if actual != expected: + raise BuildError(f"{what} does not match its pinned {algorithm} integrity") + + +def sha256_hex(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def check_sha256(data: bytes, expected: str, what: str) -> None: + if sha256_hex(data) != expected.lower(): + raise BuildError(f"{what} does not match the sha256 in pyodide-lock.json") + + +def sha256_checker(expected: str, what: str) -> Callable[[bytes], None]: + def check(data: bytes) -> None: + check_sha256(data, expected, what) + + return check + + +# ---------------------------------------------------------------- downloads + + +def https_host(url: str) -> str: + parts = urllib.parse.urlsplit(url) + if parts.scheme != "https" or not parts.hostname: + raise BuildError(f"refusing a non-https URL: {url}") + return parts.hostname + + +def fetch_url(url: str) -> bytes: + https_host(url) + request = urllib.request.Request( + url, headers={"User-Agent": "fastkit-build-assets"} + ) + try: + with urllib.request.urlopen(request, timeout=120) as response: + data: bytes = response.read() + return data + except (urllib.error.URLError, OSError) as exc: + raise BuildError(f"download failed: {url}: {exc}") from exc + + +def fetch_checked( + url: str, allowed_host: str, fetch: Fetch, check: Callable[[bytes], None] +) -> bytes: + """Download ``url`` only from ``allowed_host`` and run ``check`` on it.""" + host = https_host(url) + if host != allowed_host: + raise BuildError( + f"refusing to download from {host} (expected {allowed_host}): {url}" + ) + data = fetch(url) + check(data) + return data + + +def cached_or_fetch( + cache_path: Optional[str], + url: str, + allowed_host: str, + fetch: Fetch, + check: Callable[[bytes], None], +) -> bytes: + """Return the cached file when it passes ``check``, else download it.""" + if cache_path and os.path.isfile(cache_path): + with open(cache_path, "rb") as handle: + data = handle.read() + try: + check(data) + return data + except BuildError: + pass # stale or damaged cache entry: download again + data = fetch_checked(url, allowed_host, fetch, check) + if cache_path: + os.makedirs(os.path.dirname(cache_path), exist_ok=True) + tmp = cache_path + ".part" + with open(tmp, "wb") as handle: + handle.write(data) + os.replace(tmp, cache_path) + return data + + +# ---------------------------------------------------------------- tarball + + +def safe_member_name(name: str) -> bool: + if not name or "\\" in name or "\x00" in name: + return False + if name.startswith("/") or re.match(r"^[A-Za-z]:", name): + return False + return ".." not in name.split("/") + + +def extract_core(tar_bytes: bytes, core_files: Sequence[str], dest: str) -> List[str]: + """ + Copy ``package/`` for each core file out of the npm tarball. + + The whole archive is refused when any member has an unsafe path or is a + link; nothing but the listed regular files is written. + """ + wanted = {TARBALL_PREFIX + name: name for name in core_files} + found: Dict[str, bytes] = {} + try: + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:*") as archive: + for member in archive.getmembers(): + if not safe_member_name(member.name): + raise BuildError( + f"unsafe path in the Pyodide tarball: {member.name!r}" + ) + if member.issym() or member.islnk(): + raise BuildError(f"link in the Pyodide tarball: {member.name!r}") + if member.name not in wanted: + continue + if not member.isfile(): + raise BuildError( + f"not a regular file in the Pyodide tarball: {member.name!r}" + ) + handle = archive.extractfile(member) + assert handle is not None # regular file + found[wanted[member.name]] = handle.read() + except tarfile.TarError as exc: + raise BuildError(f"the Pyodide tarball cannot be read: {exc}") from exc + missing = [name for name in core_files if name not in found] + if missing: + raise BuildError(f"missing in the Pyodide tarball: {', '.join(missing)}") + os.makedirs(dest, exist_ok=True) + for name in core_files: + with open(os.path.join(dest, name), "wb") as handle: + handle.write(found[name]) + return list(core_files) + + +# ---------------------------------------------------------------- lock + + +def resolve_packages( + lock: Mapping[str, Any], names: Iterable[str] +) -> List[Dict[str, Any]]: + """Lock entries for ``names`` and their ``depends``, dependencies first.""" + packages = lock.get("packages") + if not isinstance(packages, dict): + raise BuildError("pyodide-lock.json has no packages table") + ordered: List[Dict[str, Any]] = [] + seen: set[str] = set() + + def visit(name: str, chain: tuple[str, ...]) -> None: + key = name.lower() + if key in seen: + return + if key in chain: + raise BuildError( + f"dependency cycle in pyodide-lock.json: {' -> '.join(chain + (key,))}" + ) + entry = packages.get(key) + if not isinstance(entry, dict): + raise BuildError(f"package {name!r} is not in pyodide-lock.json") + for dep in entry.get("depends", []): + visit(str(dep), chain + (key,)) + seen.add(key) + ordered.append({"key": key, **entry}) + + for name in names: + visit(name, ()) + return ordered + + +def wheel_url(wheel_base: str, file_name: str) -> str: + if not file_name or "/" in file_name or "\\" in file_name or ":" in file_name: + raise BuildError(f"unexpected file name in pyodide-lock.json: {file_name!r}") + if file_name in (".", ".."): + raise BuildError(f"unexpected file name in pyodide-lock.json: {file_name!r}") + return wheel_base + urllib.parse.quote(file_name) + + +def fetch_package_wheels( + entries: Sequence[Mapping[str, Any]], + config: PyodideConfig, + dest: str, + fetch: Fetch, + cache_dir: Optional[str], +) -> List[str]: + host = https_host(config.wheel_base) + written = [] + for entry in entries: + file_name = str(entry.get("file_name", "")) + expected = str(entry.get("sha256", "")) + url = wheel_url(config.wheel_base, file_name) + if not re.fullmatch(r"[0-9a-fA-F]{64}", expected): + raise BuildError(f"no sha256 for {file_name} in pyodide-lock.json") + cache_path = os.path.join(cache_dir, file_name) if cache_dir else None + data = cached_or_fetch( + cache_path, + url, + host, + fetch, + sha256_checker(expected, file_name), + ) + with open(os.path.join(dest, file_name), "wb") as handle: + handle.write(data) + written.append(file_name) + return written + + +# ---------------------------------------------------------------- fastkit wheel + + +def resolve_wheel_arg(pattern: str) -> str: + """``--wheel`` may be a glob (CI passes ``dist/fastapi_fastkit-*.whl``).""" + matches = sorted(glob.glob(pattern)) if glob.has_magic(pattern) else [pattern] + matches = [m for m in matches if os.path.isfile(m)] + if len(matches) != 1: + found = ", ".join(matches) if matches else "nothing" + raise BuildError( + f"--wheel must name exactly one wheel file ({pattern!r} matched {found})" + ) + return matches[0] + + +def wheel_version(path: str) -> str: + match = WHEEL_NAME.match(os.path.basename(path)) + if not match: + raise BuildError( + f"not a fastapi_fastkit pure-Python wheel name: {os.path.basename(path)}" + ) + return match.group("version") + + +def check_installed_version(wheel_path: str, installed_version: str) -> str: + version = wheel_version(wheel_path) + if version != installed_version: + raise BuildError( + f"the installed fastapi_fastkit is {installed_version} but the wheel is {version}; " + "install the wheel into this interpreter first" + ) + return version + + +# ---------------------------------------------------------------- outputs + + +# Written first into every output directory, so a later run may clear the +# directory even when that build failed halfway. A dot file: MkDocs leaves +# hidden files out of the site, so the marker is never published. +MARKER = ".fastkit-generator-assets" +MARKER_TEXT = "Built by scripts/web_generator/build_assets.py; rebuilt on every run.\n" +MANIFEST_KEYS = frozenset( + { + "schema", + "fastkit_version", + "commit", + "wheel", + "wheel_sha256", + "pyodide_version", + "packages", + } +) + + +def is_earlier_build(out: str) -> bool: + """A directory left by a build from before the marker: its manifest is ours.""" + path = os.path.join(out, "manifest.json") + if not os.path.isfile(path): + return False + try: + with open(path, "rb") as handle: + manifest = json.loads(handle.read().decode("utf-8")) + except (OSError, ValueError): + return False + return ( + isinstance(manifest, dict) + and set(manifest) == MANIFEST_KEYS + and manifest.get("schema") == MANIFEST_SCHEMA + ) + + +def prepare_out_dir(out: str) -> None: + """ + Empty ``out`` and mark it as ours, or refuse. + + Only an empty directory, one holding the marker, or an earlier build + recognised by its manifest is cleared. + """ + if os.path.isdir(out): + clearable = ( + not os.listdir(out) + or os.path.isfile(os.path.join(out, MARKER)) + or is_earlier_build(out) + ) + if not clearable: + raise BuildError( + f"{out} is not empty and was not made by build_assets.py; " + "refusing to clear it" + ) + shutil.rmtree(out) + elif os.path.exists(out): + raise BuildError(f"{out} exists and is not a directory") + os.makedirs(out) + with open(os.path.join(out, MARKER), "w", encoding="utf-8", newline="\n") as handle: + handle.write(MARKER_TEXT) + os.makedirs(os.path.join(out, PYODIDE_DIR)) + + +def write_json(path: str, data: Any, *, indent: Optional[int] = None) -> None: + text = json.dumps(data, ensure_ascii=False, sort_keys=False, indent=indent) + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text + "\n") + + +def write_models( + out: str, languages: Sequence[str], form_model: Callable[[str], Dict[str, Any]] +) -> List[str]: + names = [] + for lang in languages: + name = f"model-{lang}.json" + write_json(os.path.join(out, name), form_model(lang)) + names.append(name) + return names + + +def build_manifest( + *, + fastkit_version: str, + commit: str, + wheel: str, + wheel_sha256: str, + pyodide_version: str, + packages: Sequence[str], +) -> Dict[str, Any]: + return { + "schema": MANIFEST_SCHEMA, + "fastkit_version": fastkit_version, + "commit": commit, + "wheel": wheel, + "wheel_sha256": wheel_sha256, + "pyodide_version": pyodide_version, + "packages": list(packages), + } + + +# Plain text on purpose: MkDocs would render a NOTICE.md under docs/ as a page +# (once per locale) instead of copying the file. +def notice_text( + config: PyodideConfig, + lock: Mapping[str, Any], + entries: Sequence[Mapping[str, Any]], + fastkit_version: str, +) -> str: + python_version = str(lock.get("info", {}).get("python", "unknown")) + lines = [ + "Third-party software in this directory", + "=======================================", + "", + "The web generator page runs these files unmodified in your browser.", + "", + f"- Pyodide {config.version}: {config.license}. Source: {config.source}" + f" (files from {config.tarball}).", + f"- CPython {python_version}, inside pyodide/pyodide.asm.wasm and" + f" pyodide/python_stdlib.zip: PSF-2.0. Source: {CPYTHON_SOURCE}", + ] + for entry in entries: + key = str(entry["key"]) + notice = config.notices.get(key) + if not notice or "license" not in notice or "source" not in notice: + raise BuildError( + f"pyodide.toml has no [notices.{key}] with license and source" + ) + lines.append( + f"- {entry.get('name', key)} {entry.get('version', '')}" + f" (pyodide/{entry['file_name']}): {notice['license']}. Source: {notice['source']}" + ) + lines.append(f"- FastAPI-fastkit {fastkit_version}: MIT. Source: {FASTKIT_SOURCE}") + return "\n".join(lines) + "\n" + + +# ---------------------------------------------------------------- main + + +@dataclass +class BuildResult: + out: str + files: List[str] + manifest: Dict[str, Any] + + +def build( + *, + wheel: str, + out: str, + cache_dir: Optional[str], + commit: str, + config: PyodideConfig, + fetch: Fetch, + installed_version: str, + languages: Sequence[str], + form_model: Callable[[str], Dict[str, Any]], +) -> BuildResult: + version = check_installed_version(wheel, installed_version) + with open(wheel, "rb") as handle: + wheel_bytes = handle.read() + + version_cache = os.path.join(cache_dir, config.version) if cache_dir else None + tarball_cache = ( + os.path.join( + version_cache, + posixpath.basename(urllib.parse.urlsplit(config.tarball).path), + ) + if version_cache + else None + ) + tar_bytes = cached_or_fetch( + tarball_cache, + config.tarball, + https_host(config.tarball), + fetch, + lambda d: check_integrity(d, config.integrity, "the Pyodide tarball"), + ) + + prepare_out_dir(out) + pyodide_dir = os.path.join(out, PYODIDE_DIR) + files = [ + PYODIDE_DIR + "/" + n + for n in extract_core(tar_bytes, config.core_files, pyodide_dir) + ] + + lock_path = os.path.join(pyodide_dir, "pyodide-lock.json") + if not os.path.isfile(lock_path): + raise BuildError("pyodide-lock.json must be one of the core files") + with open(lock_path, "rb") as handle: + lock = json.loads(handle.read().decode("utf-8")) + lock_version = str(lock.get("info", {}).get("version", config.version)) + if lock_version != config.version: + raise BuildError( + f"pyodide-lock.json is for Pyodide {lock_version}, not {config.version}" + ) + entries = resolve_packages(lock, config.packages) + wheels = fetch_package_wheels(entries, config, pyodide_dir, fetch, version_cache) + files += [PYODIDE_DIR + "/" + n for n in wheels] + + wheel_name = os.path.basename(wheel) + with open(os.path.join(out, wheel_name), "wb") as handle: + handle.write(wheel_bytes) + files.append(wheel_name) + + files += write_models(out, languages, form_model) + manifest = build_manifest( + fastkit_version=version, + commit=commit, + wheel=wheel_name, + wheel_sha256=sha256_hex(wheel_bytes), + pyodide_version=config.version, + packages=config.packages, + ) + with open( + os.path.join(out, "NOTICE.txt"), "w", encoding="utf-8", newline="\n" + ) as handle: + handle.write(notice_text(config, lock, entries, version)) + files.append("NOTICE.txt") + write_json(os.path.join(out, "manifest.json"), manifest, indent=2) + files.append("manifest.json") + return BuildResult(out=out, files=files, manifest=manifest) + + +def parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=__doc__ or "Build the web generator assets." + ) + parser.add_argument( + "--wheel", required=True, help="the fastapi_fastkit wheel (a glob is allowed)" + ) + parser.add_argument( + "--out", + required=True, + help="output directory, e.g. docs/en/assets/fastkit-generator", + ) + parser.add_argument( + "--cache", + default=DEFAULT_CACHE, + help=f"download cache (default: {DEFAULT_CACHE})", + ) + parser.add_argument( + "--no-cache", + action="store_true", + help="do not read or write the download cache", + ) + parser.add_argument( + "--commit", default="local", help="commit shown on the page (default: local)" + ) + parser.add_argument("--config", default=DEFAULT_CONFIG, help=argparse.SUPPRESS) + return parser.parse_args(argv) + + +def main(argv: Optional[Sequence[str]] = None) -> int: + args = parse_args(argv) + try: + import fastapi_fastkit + from fastapi_fastkit.catalog import LANGUAGES + from fastapi_fastkit.generation.browser import form_model + + config = load_config(args.config) + result = build( + wheel=resolve_wheel_arg(args.wheel), + out=args.out, + cache_dir=None if args.no_cache else args.cache, + commit=args.commit, + config=config, + fetch=fetch_url, + installed_version=fastapi_fastkit.__version__, + languages=LANGUAGES, + form_model=form_model, + ) + except BuildError as exc: + print(f"build_assets: {exc}", file=sys.stderr) + return 1 + except ImportError as exc: + print( + f"build_assets: fastapi_fastkit is not installed in this interpreter ({exc})", + file=sys.stderr, + ) + return 1 + print(f"build_assets: wrote {len(result.files)} files to {result.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/web_generator/check_site.py b/scripts/web_generator/check_site.py new file mode 100644 index 00000000..5cac5b60 --- /dev/null +++ b/scripts/web_generator/check_site.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +# -------------------------------------------------------------------------- +# Check a built docs site for the web generator page +# +# mkdocs build --strict -d site +# python scripts/web_generator/check_site.py site +# +# - the assets exist once, at site/assets/fastkit-generator/, and hold every +# file the manifest, pyodide.toml and the languages need; +# - each locale's start/web-generator/index.html has the mount element and +# the module script, and that script exists next to the page. +# Stdlib only; exit 1 with one line per problem. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import posixpath +import re +import sys +import tomllib +from typing import List, Optional, Sequence + +HERE = os.path.dirname(os.path.abspath(__file__)) +DEFAULT_CONFIG = os.path.join(HERE, "pyodide.toml") +LANGUAGES = ("en", "ko", "ja", "zh", "es", "fr", "de") +ASSETS = posixpath.join("assets", "fastkit-generator") +PAGE = posixpath.join("start", "web-generator", "index.html") +MOUNT = 'id="fastkit-generator"' +SCRIPT = re.compile( + r']*\btype="module"[^>]*\bsrc="([^"]*web-generator\.mjs)"' +) + + +def page_path(site: str, lang: str) -> str: + parts = [site] + ([] if lang == "en" else [lang]) + PAGE.split("/") + return os.path.join(*parts) + + +def manifests(site: str) -> List[str]: + found = [] + for dirpath, _dirnames, filenames in os.walk(site): + if "manifest.json" in filenames and "fastkit-generator" in dirpath.replace( + os.sep, "/" + ): + found.append(os.path.relpath(os.path.join(dirpath, "manifest.json"), site)) + return sorted(found) + + +def check_assets(site: str, languages: Sequence[str], config_path: str) -> List[str]: + problems: List[str] = [] + found = manifests(site) + expected = os.path.join(*ASSETS.split("/"), "manifest.json") + if found != [expected]: + problems.append( + f"expected one asset directory at {ASSETS}/, found manifests: {found or 'none'}" + ) + assets = os.path.join(site, *ASSETS.split("/")) + manifest_path = os.path.join(assets, "manifest.json") + if not os.path.isfile(manifest_path): + return problems + with open(manifest_path, encoding="utf-8") as handle: + manifest = json.load(handle) + with open(config_path, "rb") as handle: + config = tomllib.load(handle) + + if manifest.get("schema") != 1: + problems.append(f"manifest schema is {manifest.get('schema')!r}, expected 1") + if manifest.get("pyodide_version") != config["version"]: + problems.append( + f"manifest names Pyodide {manifest.get('pyodide_version')}, pyodide.toml {config['version']}" + ) + wheel = str(manifest.get("wheel", "")) + wheel_path = os.path.join(assets, wheel) + if not wheel or "/" in wheel or not os.path.isfile(wheel_path): + problems.append(f"the wheel named in the manifest is missing: {wheel!r}") + else: + with open(wheel_path, "rb") as handle: + if hashlib.sha256(handle.read()).hexdigest() != manifest.get( + "wheel_sha256" + ): + problems.append(f"{wheel} does not match wheel_sha256 in the manifest") + + required = ["NOTICE.txt"] + [f"model-{lang}.json" for lang in languages] + required += [posixpath.join("pyodide", name) for name in config["core_files"]] + lock_path = os.path.join(assets, "pyodide", "pyodide-lock.json") + if os.path.isfile(lock_path): + with open(lock_path, encoding="utf-8") as handle: + packages = json.load(handle).get("packages", {}) + pending = [str(p).lower() for p in manifest.get("packages", [])] + seen: set[str] = set() + while pending: + key = pending.pop() + if key in seen: + continue + seen.add(key) + entry = packages.get(key) + if not entry: + problems.append( + f"package {key!r} from the manifest is not in pyodide-lock.json" + ) + continue + required.append(posixpath.join("pyodide", entry["file_name"])) + pending.extend(str(d).lower() for d in entry.get("depends", [])) + for rel in required: + if not os.path.isfile(os.path.join(assets, *rel.split("/"))): + problems.append(f"missing asset: {ASSETS}/{rel}") + return problems + + +def check_pages(site: str, languages: Sequence[str]) -> List[str]: + problems: List[str] = [] + for lang in languages: + path = page_path(site, lang) + rel = os.path.relpath(path, site) + if not os.path.isfile(path): + problems.append(f"{lang}: page missing: {rel}") + continue + with open(path, encoding="utf-8") as handle: + html = handle.read() + if MOUNT not in html: + problems.append(f"{lang}: {rel} has no {MOUNT} element") + match = SCRIPT.search(html) + if not match: + problems.append(f"{lang}: {rel} has no module script for web-generator.mjs") + continue + src = match.group(1) + if "://" in src or src.startswith("/"): + problems.append( + f"{lang}: {rel} loads the script from {src!r}, expected a relative path" + ) + continue + target = os.path.normpath(os.path.join(os.path.dirname(path), *src.split("/"))) + if not os.path.isfile(target): + problems.append(f"{lang}: {rel} loads {src}, which is not in the site") + return problems + + +def check_site( + site: str, languages: Sequence[str] = LANGUAGES, config_path: str = DEFAULT_CONFIG +) -> List[str]: + if not os.path.isdir(site): + return [f"{site} is not a directory"] + return check_assets(site, languages, config_path) + check_pages(site, languages) + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser( + description="Check the web generator page in a built docs site." + ) + parser.add_argument("site", help="mkdocs build output directory") + parser.add_argument( + "--languages", + default=",".join(LANGUAGES), + help="comma-separated locales to check (default: all seven)", + ) + args = parser.parse_args(argv) + languages = [lang.strip() for lang in args.languages.split(",") if lang.strip()] + problems = check_site(args.site, languages) + for problem in problems: + print(f"check_site: {problem}", file=sys.stderr) + if problems: + return 1 + print(f"check_site: web generator page and assets ok ({', '.join(languages)})") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/web_generator/compare.py b/scripts/web_generator/compare.py new file mode 100644 index 00000000..e620a776 --- /dev/null +++ b/scripts/web_generator/compare.py @@ -0,0 +1,240 @@ +# -------------------------------------------------------------------------- +# Compare a web generator zip with the project `fastkit init` wrote +# +# Used by compare_with_cli.py; importable and stdlib only. The rules are the +# equality definition of the web generator: same file set, same bytes (the +# random SECRET_KEY in .env masked after a shape check), same executable bits, +# and a clean zip (UTF-8 names, sorted, no duplicates, no unsafe names, +# deflated, Unix modes on regular files only). +# -------------------------------------------------------------------------- +from __future__ import annotations + +import difflib +import io +import os +import re +import stat +import zipfile +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple + +# Same pattern fastkit uses to write the key (backend/main.py). +SECRET_LINE = re.compile(r"^([ \t]*(?:export[ \t]+)?SECRET_KEY[ \t]*=)(.*)$", re.M) +# secrets.token_urlsafe(32) on the CLI side, 32 random bytes in base64url on the web side. +SECRET_VALUE = re.compile(r"[A-Za-z0-9_-]{43}") +SECRET_MASK = "" +ENV_FILE = ".env" +MODE_EXECUTABLE = 0o755 +MODE_REGULAR = 0o644 +UNIX_SYSTEM = 3 +UTF8_FLAG = 0x800 +DIFF_LINES = 40 + + +@dataclass +class Tree: + """Files of a project: POSIX relpath -> bytes, and -> 0o755 / 0o644.""" + + files: Dict[str, bytes] = field(default_factory=dict) + modes: Dict[str, int] = field(default_factory=dict) + + +# ---------------------------------------------------------------- zip side + + +def unsafe_name_reason(name: str) -> Optional[str]: + if not name: + return "empty name" + if "\x00" in name: + return "NUL in name" + if "\\" in name: + return "backslash in name" + if name.startswith("/"): + return "absolute name" + if re.match(r"^[A-Za-z]:", name): + return "drive letter in name" + if ".." in name.split("/"): + return "'..' segment in name" + return None + + +def zip_problems(data: bytes, root: str) -> List[str]: + """Hygiene problems of a web zip whose entries must all live under ``root/``.""" + problems: List[str] = [] + try: + archive = zipfile.ZipFile(io.BytesIO(data)) + except zipfile.BadZipFile as exc: + return [f"not a zip file: {exc}"] + with archive: + infos = archive.infolist() + names = [info.filename for info in infos] + if not infos: + problems.append("the zip is empty") + if names != sorted(names): + problems.append("entries are not sorted by name") + seen: set[str] = set() + for info in infos: + name = info.filename + if name in seen: + problems.append(f"{name}: duplicate entry") + seen.add(name) + reason = unsafe_name_reason(name) + if reason: + problems.append(f"{name!r}: {reason}") + continue + if not name.startswith(root + "/") or name == root + "/": + problems.append(f"{name}: not under {root}/") + if name.endswith("/"): + problems.append(f"{name}: directory entry") + continue + if not name.isascii() and not info.flag_bits & UTF8_FLAG: + problems.append(f"{name}: non-ASCII name without the UTF-8 flag") + if info.compress_type != zipfile.ZIP_DEFLATED: + problems.append(f"{name}: not deflated") + if info.create_system != UNIX_SYSTEM: + problems.append( + f"{name}: create_system {info.create_system}, expected {UNIX_SYSTEM}" + ) + mode = info.external_attr >> 16 + if not stat.S_ISREG(mode): + problems.append(f"{name}: not a regular file (mode {mode:o})") + elif stat.S_IMODE(mode) not in (MODE_EXECUTABLE, MODE_REGULAR): + problems.append( + f"{name}: mode {stat.S_IMODE(mode):o}, expected 755 or 644" + ) + return problems + + +def read_zip(data: bytes, root: str) -> Tree: + """Files under ``root/`` in a zip (call :func:`zip_problems` for hygiene).""" + tree = Tree() + prefix = root + "/" + with zipfile.ZipFile(io.BytesIO(data)) as archive: + for info in archive.infolist(): + if info.is_dir() or not info.filename.startswith(prefix): + continue + rel = info.filename[len(prefix) :] + tree.files[rel] = archive.read(info) + mode = stat.S_IMODE(info.external_attr >> 16) + tree.modes[rel] = MODE_EXECUTABLE if mode & stat.S_IXUSR else MODE_REGULAR + return tree + + +def zip_root(data: bytes) -> str: + """The single top-level folder of a zip, or ``""`` when there is none.""" + with zipfile.ZipFile(io.BytesIO(data)) as archive: + roots = {info.filename.split("/", 1)[0] for info in archive.infolist()} + return roots.pop() if len(roots) == 1 else "" + + +# ---------------------------------------------------------------- CLI side + + +def read_dir(path: str) -> Tuple[Tree, List[str]]: + """Regular files under ``path`` (recursive) and anything that is not one.""" + tree = Tree() + problems: List[str] = [] + for dirpath, dirnames, filenames in os.walk(path): + dirnames.sort() + for name in sorted(filenames) + [ + d for d in dirnames if os.path.islink(os.path.join(dirpath, d)) + ]: + full = os.path.join(dirpath, name) + rel = os.path.relpath(full, path).replace(os.sep, "/") + info = os.lstat(full) + if not stat.S_ISREG(info.st_mode): + problems.append(f"{rel}: not a regular file in the CLI project") + continue + with open(full, "rb") as handle: + tree.files[rel] = handle.read() + tree.modes[rel] = ( + MODE_EXECUTABLE if info.st_mode & stat.S_IXUSR else MODE_REGULAR + ) + return tree, problems + + +# ---------------------------------------------------------------- comparison + + +def mask_secrets(data: bytes, side: str) -> Tuple[bytes, List[str]]: + """Replace each ``SECRET_KEY=`` value by a mask after checking its shape.""" + problems: List[str] = [] + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + return data, [f"{side} {ENV_FILE} is not UTF-8"] + + def replace(match: "re.Match[str]") -> str: + value = match.group(2) + if not SECRET_VALUE.fullmatch(value): + problems.append( + f"{side} {ENV_FILE}: SECRET_KEY value is not 43 base64url characters " + f"(length {len(value)})" + ) + return match.group(1) + SECRET_MASK + + return SECRET_LINE.sub(replace, text).encode("utf-8"), problems + + +def is_env_file(rel: str) -> bool: + # fastkit writes a random key only into the project root's .env (rendered + # from .env.example); every other file must match byte for byte. + return rel == ENV_FILE + + +def text_diff(rel: str, web: bytes, cli: bytes, limit: int = DIFF_LINES) -> List[str]: + try: + web_text = web.decode("utf-8").splitlines(keepends=True) + cli_text = cli.decode("utf-8").splitlines(keepends=True) + except UnicodeDecodeError: + return [f" binary content differs ({len(web)} vs {len(cli)} bytes)"] + if [line.rstrip("\r\n") for line in web_text] == [ + line.rstrip("\r\n") for line in cli_text + ]: + return [" line endings or final newline differ"] + lines = [ + " " + line.rstrip("\r\n") + for line in difflib.unified_diff(cli_text, web_text, f"cli/{rel}", f"web/{rel}") + ] + if len(lines) > limit: + lines = lines[:limit] + [f" ... ({len(lines) - limit} more diff lines)"] + return lines + + +def compare_trees(web: Tree, cli: Tree, *, diff_lines: int = DIFF_LINES) -> List[str]: + """Differences between the web zip and the CLI project; empty means equal.""" + out: List[str] = [] + for rel in sorted(set(cli.files) - set(web.files)): + out.append(f"{rel}: only in the CLI project") + for rel in sorted(set(web.files) - set(cli.files)): + out.append(f"{rel}: only in the web zip") + for rel in sorted(set(web.files) & set(cli.files)): + web_bytes, cli_bytes = web.files[rel], cli.files[rel] + if is_env_file(rel): + web_bytes, web_problems = mask_secrets(web_bytes, "web") + cli_bytes, cli_problems = mask_secrets(cli_bytes, "CLI") + out.extend(f"{rel}: {p}" for p in web_problems + cli_problems) + if web_bytes != cli_bytes: + out.append(f"{rel}: content differs") + out.extend(text_diff(rel, web_bytes, cli_bytes, diff_lines)) + if web.modes.get(rel) != cli.modes.get(rel): + out.append( + f"{rel}: mode {web.modes.get(rel, 0):o} in the web zip, " + f"{cli.modes.get(rel, 0):o} in the CLI project" + ) + return out + + +def compare_zip_with_dir( + zip_bytes: bytes, root: str, project_dir: str, *, diff_lines: int = DIFF_LINES +) -> List[str]: + """Every difference between a web zip and a CLI project directory.""" + problems = zip_problems(zip_bytes, root) + if problems and problems[0].startswith("not a zip file"): + return problems + cli, dir_problems = read_dir(project_dir) + return ( + problems + + dir_problems + + compare_trees(read_zip(zip_bytes, root), cli, diff_lines=diff_lines) + ) diff --git a/scripts/web_generator/compare_with_cli.py b/scripts/web_generator/compare_with_cli.py new file mode 100644 index 00000000..7db8bbce --- /dev/null +++ b/scripts/web_generator/compare_with_cli.py @@ -0,0 +1,370 @@ +#!/usr/bin/env python3 +# -------------------------------------------------------------------------- +# Check that the web generator makes the same projects as the fastkit CLI +# +# python scripts/web_generator/compare_with_cli.py \ +# --assets docs/en/assets/fastkit-generator \ +# --cases tests/fixtures/web_generator/cases.json +# +# runs every case through the page's generator core in Pyodide under Node +# (generate.mjs), runs the command line the page shows with the `fastkit` +# console script of the same wheel, and compares the two (compare.py). +# +# python scripts/web_generator/compare_with_cli.py --zip demo.zip -- init --project-name demo ... +# +# compares one zip downloaded from the page with the command shown next to it. +# Both forms exit 1 on any difference. Stdlib only. +# -------------------------------------------------------------------------- +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +import tempfile +import zipfile +from dataclasses import dataclass +from typing import Any, Dict, List, Mapping, Optional, Sequence + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import compare # noqa: E402 + +GENERATE_MJS = os.path.join(HERE, "generate.mjs") +CLI_TIMEOUT = 120 +NODE_TIMEOUT = 900 + + +class CompareError(Exception): + """A problem that stops the run before cases are compared.""" + + +@dataclass +class CaseOutcome: + case_id: str + problems: List[str] + file_count: int + + @property + def ok(self) -> bool: + return not self.problems + + +# Variables that could hand the CLI a git identity, another repository or +# another fastkit copy; cli_env drops them. +DROPPED_ENV = frozenset( + { + "VIRTUAL_ENV", + "PYTHONPATH", + "PYTHONHOME", + "PYTHONSTARTUP", + "PYTHONUSERBASE", + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_CONFIG", + "GIT_CONFIG_COUNT", + "GIT_CONFIG_PARAMETERS", + "GIT_CONFIG_SYSTEM", + "EMAIL", + } +) +DROPPED_ENV_PREFIXES = ( + "GIT_CONFIG_KEY_", + "GIT_CONFIG_VALUE_", + "GIT_AUTHOR_", + "GIT_COMMITTER_", +) + + +def inherited_identity(name: str) -> bool: + upper = name.upper() # Windows environment names are case-insensitive + return upper in DROPPED_ENV or upper.startswith(DROPPED_ENV_PREFIXES) + + +def cli_env(base: Mapping[str, str], work: str) -> Dict[str, str]: + """Environment for the CLI: empty git identity, own HOME, no colour.""" + home = os.path.join(work, "home") + os.makedirs(home, exist_ok=True) + git_config = os.path.join(work, "gitconfig") + with open(git_config, "w", encoding="utf-8"): + pass + env = {name: value for name, value in base.items() if not inherited_identity(name)} + env.update( + { + "HOME": home, + "USERPROFILE": home, + "XDG_CONFIG_HOME": os.path.join(home, ".config"), + "GIT_CONFIG_GLOBAL": git_config, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CEILING_DIRECTORIES": work, + "NO_COLOR": "1", + "PYTHONIOENCODING": "utf-8", + } + ) + return env + + +def strip_program(argv: Sequence[str]) -> List[str]: + """The page's command starts with ``fastkit``; the runner wants what follows.""" + args = list(argv) + if args and args[0] == "fastkit": + args = args[1:] + if not args or args[0] != "init": + raise CompareError( + f"expected a `fastkit init ...` command, got {' '.join(argv)!r}" + ) + return args + + +def run_cli( + fastkit: str, argv: Sequence[str], cwd: str, env: Mapping[str, str] +) -> List[str]: + """Run ``fastkit `` in an empty ``cwd``; problems as lines (empty = ran fine).""" + os.makedirs(cwd, exist_ok=True) + try: + completed = subprocess.run( + [fastkit, *argv], + cwd=cwd, + env=dict(env), + stdin=subprocess.DEVNULL, + capture_output=True, + encoding="utf-8", + errors="replace", + timeout=CLI_TIMEOUT, + ) + except subprocess.TimeoutExpired: + return [f"fastkit did not finish within {CLI_TIMEOUT} s"] + except OSError as exc: + return [f"fastkit could not be started: {exc}"] + if completed.returncode != 0: + output = (completed.stdout + completed.stderr).strip().splitlines()[-20:] + return [f"fastkit exited with status {completed.returncode}"] + [ + " " + line for line in output + ] + return [] + + +def compare_case( + case_id: str, + zip_bytes: bytes, + root: str, + argv: Sequence[str], + *, + fastkit: str, + work: str, + env: Mapping[str, str], + planned: Optional[Sequence[str]] = None, +) -> CaseOutcome: + cwd = os.path.join(work, "cli", case_id) + problems = run_cli(fastkit, argv, cwd, env) + if problems: + return CaseOutcome(case_id, problems, 0) + entries = sorted(os.listdir(cwd)) + if entries != [root]: + return CaseOutcome( + case_id, [f"the CLI workspace holds {entries}, expected [{root!r}]"], 0 + ) + problems = compare.compare_zip_with_dir(zip_bytes, root, os.path.join(cwd, root)) + try: + web_files = compare.read_zip(zip_bytes, root).files + except zipfile.BadZipFile: + return CaseOutcome(case_id, problems, 0) + if planned is not None and sorted(planned) != sorted(web_files): + missing = sorted(set(web_files) - set(planned)) + extra = sorted(set(planned) - set(web_files)) + problems.append( + f"the page's file list differs from the zip (not listed: {missing}, not in zip: {extra})" + ) + return CaseOutcome(case_id, problems, len(web_files)) + + +def report(outcome: CaseOutcome) -> None: + if outcome.ok: + print(f"ok {outcome.case_id} ({outcome.file_count} files)") + return + print(f"FAIL {outcome.case_id}") + for line in outcome.problems: + print(f" {line}") + + +def resolve_program(name: str, what: str) -> str: + found = shutil.which(name) + if not found: + raise CompareError(f"{what} not found: {name}") + return found + + +def run_generate( + node: str, assets: str, cases: str, out: str, only: Optional[str] +) -> None: + command = [node, GENERATE_MJS, "--assets", assets, "--cases", cases, "--out", out] + if only: + command += ["--only", only] + try: + completed = subprocess.run(command, timeout=NODE_TIMEOUT) + except subprocess.TimeoutExpired as exc: + raise CompareError( + f"generate.mjs did not finish within {NODE_TIMEOUT} s" + ) from exc + if completed.returncode != 0: + raise CompareError(f"generate.mjs failed with status {completed.returncode}") + + +def parse_only(text: Optional[str]) -> Optional[List[str]]: + """Case ids from ``--only`` (trimmed, empty parts dropped), None without it.""" + if text is None: + return None + ids = [part.strip() for part in text.split(",") if part.strip()] + if not ids: + raise CompareError("--only names no case id") + return ids + + +def load_cases(path: str) -> List[Dict[str, Any]]: + try: + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError) as exc: + raise CompareError(f"cannot read the cases file {path}: {exc}") from exc + cases = data if isinstance(data, list) else data.get("cases") + if not isinstance(cases, list) or not cases: + raise CompareError(f"{path} holds no cases") + return cases + + +def select_cases( + cases: Sequence[Mapping[str, Any]], only: Optional[Sequence[str]] +) -> List[Mapping[str, Any]]: + if only is None: + return list(cases) + known = {case["id"] for case in cases} + unknown = [case_id for case_id in only if case_id not in known] + if unknown: + raise CompareError(f"unknown case id: {', '.join(unknown)}") + return [case for case in cases if case["id"] in set(only)] + + +def compare_all(args: argparse.Namespace, work: str) -> int: + only = parse_only(args.only) + selected = select_cases(load_cases(args.cases), only) + node = resolve_program(args.node, "node") + fastkit = resolve_program(args.fastkit, "fastkit") + web_dir = os.path.join(work, "web") + run_generate( + node, args.assets, args.cases, web_dir, ",".join(only) if only else None + ) + env = cli_env(os.environ, work) + + failures = 0 + count = 0 + for case in selected: + case_id = case["id"] + count += 1 + with open(os.path.join(web_dir, f"{case_id}.json"), encoding="utf-8") as handle: + record = json.load(handle) + with open(os.path.join(web_dir, f"{case_id}.zip"), "rb") as handle: + zip_bytes = handle.read() + outcome = compare_case( + case_id, + zip_bytes, + record["root"], + strip_program(record["argv"]), + fastkit=fastkit, + work=work, + env=env, + planned=record.get("files"), + ) + report(outcome) + failures += not outcome.ok + print(f"{count - failures} of {count} cases equal") + return 1 if failures or not count else 0 + + +def compare_one_zip(args: argparse.Namespace, work: str) -> int: + fastkit = resolve_program(args.fastkit, "fastkit") + with open(args.zip, "rb") as handle: + zip_bytes = handle.read() + try: + root = compare.zip_root(zip_bytes) + except zipfile.BadZipFile as exc: + raise CompareError(f"{args.zip} is not a zip file: {exc}") from exc + if not root: + raise CompareError(f"{args.zip} does not hold exactly one top-level folder") + outcome = compare_case( + "zip", + zip_bytes, + root, + strip_program(args.argv), + fastkit=fastkit, + work=work, + env=cli_env(os.environ, work), + ) + report(outcome) + return 0 if outcome.ok else 1 + + +def parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Compare web generator output with the fastkit CLI.", + usage="%(prog)s --assets DIR --cases JSON [options]\n" + " %(prog)s --zip FILE [--fastkit PATH] -- init --project-name ...", + ) + parser.add_argument("--assets", help="built assets (build_assets.py --out)") + parser.add_argument( + "--cases", help="cases file, e.g. tests/fixtures/web_generator/cases.json" + ) + parser.add_argument("--only", help="comma-separated case ids") + parser.add_argument( + "--node", default="node", help="Node.js executable (default: node)" + ) + parser.add_argument( + "--fastkit", default="fastkit", help="fastkit executable (default: fastkit)" + ) + parser.add_argument("--keep", help="keep the web and CLI outputs in this directory") + parser.add_argument( + "--zip", help="compare this downloaded zip with the command after --" + ) + parser.add_argument("argv", nargs="*", help=argparse.SUPPRESS) + args = parser.parse_args(argv) + if args.zip: + if not args.argv: + parser.error("--zip needs the page's command after --") + elif not (args.assets and args.cases): + parser.error("--assets and --cases are required (or --zip)") + elif args.argv: + parser.error("unexpected arguments: " + " ".join(args.argv)) + return args + + +def main(argv: Optional[Sequence[str]] = None) -> int: + args = parse_args(argv) + if args.keep: + if os.path.exists(args.keep) and os.listdir(args.keep): + print( + f"compare_with_cli: --keep directory {args.keep} is not empty", + file=sys.stderr, + ) + return 2 + work = os.path.abspath(args.keep) + os.makedirs(work, exist_ok=True) + cleanup = None + else: + cleanup = tempfile.TemporaryDirectory(prefix="fastkit-web-compare-") + work = os.path.realpath(cleanup.name) + try: + if args.zip: + return compare_one_zip(args, work) + return compare_all(args, work) + except CompareError as exc: + print(f"compare_with_cli: {exc}", file=sys.stderr) + return 1 + finally: + if cleanup is not None: + cleanup.cleanup() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/web_generator/generate.mjs b/scripts/web_generator/generate.mjs new file mode 100644 index 00000000..5d19f2f2 --- /dev/null +++ b/scripts/web_generator/generate.mjs @@ -0,0 +1,134 @@ +#!/usr/bin/env node +// Runs the web generator page's own core (docs/js/web-generator-core.mjs) +// under Node with the built assets, for each case of a cases file: +// +// node scripts/web_generator/generate.mjs --assets docs/en/assets/fastkit-generator \ +// --cases tests/fixtures/web_generator/cases.json --out [--only id,id] +// +// For every case it writes /.zip and /.json +// ({id, lang, argv, command_text, files, root, filename}). The check must +// report `ok`; any failing case makes the exit status 1. compare_with_cli.py +// runs this and compares the zips with the real `fastkit` CLI. + +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { parseArgs } from "node:util"; + +import { startGenerator } from "../../docs/js/web-generator-core.mjs"; + +// Node 18 has WebCrypto only under node:crypto; Node 20+ also has the global. +globalThis.crypto ??= (await import("node:crypto")).webcrypto; + +function usage(message) { + if (message) console.error(`generate.mjs: ${message}`); + console.error("usage: generate.mjs --assets --cases --out [--only id,id]"); + process.exit(2); +} + +let options; +try { + ({ values: options } = parseArgs({ + options: { + assets: { type: "string" }, + cases: { type: "string" }, + out: { type: "string" }, + only: { type: "string" }, + }, + })); +} catch (error) { + usage(error.message); +} +if (!options.assets || !options.cases || !options.out) usage("--assets, --cases and --out are required"); + +const ID_PATTERN = /^[A-Za-z0-9_.-]+$/; + +function loadCases(text) { + const data = JSON.parse(text); + const cases = Array.isArray(data) ? data : data.cases; + if (!Array.isArray(cases) || cases.length === 0) throw new Error("the cases file has no cases"); + const seen = new Set(); + for (const item of cases) { + if (!item || typeof item.id !== "string" || !ID_PATTERN.test(item.id)) { + throw new Error(`case id must match ${ID_PATTERN}: ${JSON.stringify(item && item.id)}`); + } + if (seen.has(item.id)) throw new Error(`duplicate case id: ${item.id}`); + seen.add(item.id); + if (!item.form || typeof item.form !== "object") throw new Error(`case ${item.id} has no form`); + } + return cases; +} + +async function readBytes(url) { + // Errors keep their `code` ("ENOENT" for a missing file), as the core expects. + return new Uint8Array(await readFile(fileURLToPath(url))); +} + +const assetsURL = pathToFileURL(path.resolve(options.assets) + path.sep).href; +let cases; +try { + cases = loadCases(await readFile(options.cases, "utf-8")); +} catch (error) { + console.error(`generate.mjs: ${options.cases}: ${error.message}`); + process.exit(1); +} +if (options.only !== undefined) { + const wanted = new Set(options.only.split(",").map((id) => id.trim()).filter(Boolean)); + if (wanted.size === 0) usage("--only names no case id"); + const unknown = [...wanted].filter((id) => !cases.some((c) => c.id === id)); + if (unknown.length) usage(`unknown case id: ${unknown.join(", ")}`); + cases = cases.filter((c) => wanted.has(c.id)); +} +await mkdir(options.out, { recursive: true }); + +const started = performance.now(); +let generator; +try { + generator = await startGenerator({ + assetsURL, + readBytes, + onStage: (stage) => console.error(`[web] loading ${stage}`), + }); +} catch (error) { + console.error(`generate.mjs: the generator did not start (${error.kind || "error"}): ${error.message}`); + process.exit(1); +} +console.error( + `[web] ready in ${Math.round(performance.now() - started)} ms ` + + `(fastkit ${generator.manifest.fastkit_version}, Pyodide ${generator.manifest.pyodide_version})`, +); + +let failures = 0; +for (const item of cases) { + const lang = item.lang || "en"; + const t0 = performance.now(); + try { + const checked = await generator.check(item.form, lang); + if (!checked.ok) { + throw new Error( + "check is not ok: " + + JSON.stringify({ problems: checked.problems, rule_errors: checked.rule_errors }), + ); + } + const { zip, meta } = await generator.build(item.form, lang); + await writeFile(path.join(options.out, `${item.id}.zip`), zip); + const record = { + id: item.id, + lang, + argv: checked.command, + command_text: checked.command_text, + files: checked.files, + root: meta.root, + filename: meta.filename, + }; + await writeFile(path.join(options.out, `${item.id}.json`), JSON.stringify(record, null, 2) + "\n"); + console.error(`[web] ${item.id}: ${meta.files.length} files in ${Math.round(performance.now() - t0)} ms`); + } catch (error) { + failures += 1; + const kind = error && error.kind ? ` (${error.kind})` : ""; + console.error(`[web] ${item.id}: FAILED${kind}: ${error && error.message ? error.message : error}`); + } +} + +generator.close(); +process.exit(failures ? 1 : 0); diff --git a/scripts/web_generator/pyodide.toml b/scripts/web_generator/pyodide.toml new file mode 100644 index 00000000..c2b0a1c4 --- /dev/null +++ b/scripts/web_generator/pyodide.toml @@ -0,0 +1,31 @@ +# Pyodide runtime served next to the web generator page (docs site). +# build_assets.py downloads the npm tarball once (cached in .cache/web-generator), +# checks it against `integrity` and copies `core_files` from it; the wheels of +# `packages` (and their dependencies) come from `wheel_base` and are checked +# against the sha256 values in the tarball's pyodide-lock.json. +# Changing `version` also needs the matching `tarball` and `integrity` +# (`npm view pyodide@ dist.tarball dist.integrity`). +version = "314.0.8" +tarball = "https://registry.npmjs.org/pyodide/-/pyodide-314.0.8.tgz" +integrity = "sha512-74Wq1kXOC+CCEzAfxuRAO701nAcCMLjf8NrwvWpu8S41dVMXwXmLQ05dYB+F4e46AdnGo0oq7YHSVUpHsoarLQ==" +wheel_base = "https://cdn.jsdelivr.net/pyodide/v314.0.8/full/" +packages = ["jinja2"] +core_files = [ + "pyodide.mjs", + "pyodide.asm.mjs", + "pyodide.asm.wasm", + "python_stdlib.zip", + "pyodide-lock.json", +] +license = "MPL-2.0" +source = "https://github.com/pyodide/pyodide" + +# Written to NOTICE.md next to the assets. Every package that `packages` +# resolves to (dependencies included) needs an entry. +[notices.jinja2] +license = "BSD-3-Clause" +source = "https://github.com/pallets/jinja" + +[notices.markupsafe] +license = "BSD-3-Clause" +source = "https://github.com/pallets/markupsafe" diff --git a/src/fastapi_fastkit/backend/doctor/known.py b/src/fastapi_fastkit/backend/doctor/known.py index fff64068..88ba54ab 100644 --- a/src/fastapi_fastkit/backend/doctor/known.py +++ b/src/fastapi_fastkit/backend/doctor/known.py @@ -1,83 +1,17 @@ # -------------------------------------------------------------------------- # Values fastkit itself has shipped as examples, in any version. # -# A project that still uses one of these runs with a secret everybody can -# read in fastkit's public repository. The set is collected from the -# templates' ``KNOWN_EXAMPLE_SECRET_KEYS``, the ``.env`` / ``.env.example`` -# templates and the ``fastkit init`` fragments, including the values of -# releases before v1.5.2 (``git log -p`` on the templates and fragments). -# ``tests/test_backends/test_doctor_checks.py`` fails when a template adds a -# new example key that is missing here. +# The sets live in ``fastapi_fastkit.core.known`` so generation can use them +# without importing the doctor package (which loads click and rich); this +# module keeps the old import path working. # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- - -#: Example secrets (SECRET_KEY, session keys, MCP API key placeholders). -KNOWN_EXAMPLE_SECRETS = frozenset( - { - # .env templates and KNOWN_EXAMPLE_SECRET_KEYS (every version) - "changethis", - "changethis-please-generate-a-real-32-byte-key", - "changethis-please-use-openssl-rand-hex-32", - # fastapi-mcp settings default and the ``fastkit init`` JWT module - # before v1.5.2 - "your-secret-key-here-change-in-production", - "your-secret-key-here", - # ``fastkit init`` Session / OAuth2 modules before v1.5.2 - # (SESSION_SECRET_KEY default) - "change-me-in-production", - # fastapi-mcp .env template (commented example of MCP_API_KEY) - "your-mcp-api-key-here", - } -) - -#: Passwords of the hard-coded demo accounts fastapi-mcp shipped before -#: v1.5.2 (``user1`` / ``user2`` / ``admin``). -MCP_DEMO_PASSWORDS = frozenset({"password123", "password456", "admin123"}) - -#: ``.env`` variants meant to be committed (no real values). -ENV_EXAMPLE_NAMES = frozenset( - {".env.example", ".env.sample", ".env.template", ".env.dist", ".env.defaults"} -) - -#: Variables whose value is never a secret in a fastkit project. Only these -#: keep their value when ``.env.example`` is written from ``.env``, and -#: only when the value itself does not look like a secret. -NON_SECRET_ENV_NAMES = frozenset( - { - "ACCESS_TOKEN_EXPIRE_MINUTES", - "ALGORITHM", - "API_V1_PREFIX", - "API_V1_STR", - "BACKEND_CORS_ORIGINS", - "DEBUG", - "ENABLE_DEMO_USERS", - "ENV", - "ENVIRONMENT", - "FRONTEND_HOST", - "HOST", - "JWT_ALGORITHM", - "LLM_MAX_TOKENS", - "LLM_MODEL", - "LLM_PROVIDER", - "LLM_TEMPERATURE", - "LOG_FORMAT", - "LOG_LEVEL", - "MCP_DESCRIPTION", - "MCP_ENABLED", - "MCP_MOUNT_PATH", - "MCP_TITLE", - "PORT", - "POSTGRES_DB", - "POSTGRES_PORT", - "POSTGRES_SERVER", - "PROJECT_NAME", - "REFRESH_TOKEN_EXPIRE_DAYS", - "SESSION_MAX_AGE", - "TZ", - "VERSION", - "WORKERS", - } +from fastapi_fastkit.core.known import ( + ENV_EXAMPLE_NAMES, + KNOWN_EXAMPLE_SECRETS, + MCP_DEMO_PASSWORDS, + NON_SECRET_ENV_NAMES, ) __all__ = [ diff --git a/src/fastapi_fastkit/backend/interactive/validators.py b/src/fastapi_fastkit/backend/interactive/validators.py index 7d3dee6a..dee7cee1 100644 --- a/src/fastapi_fastkit/backend/interactive/validators.py +++ b/src/fastapi_fastkit/backend/interactive/validators.py @@ -1,145 +1,30 @@ # -------------------------------------------------------------------------- # Input validation utilities for interactive mode # -# Provides validation functions for: -# - Package names -# - Project names -# - Feature compatibility checking +# The functions live in ``fastapi_fastkit.utils.validation`` (no click/rich, +# so the generation path can use them); this module keeps the old import +# path working. # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- -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 - - -def validate_package_name(package: str) -> bool: - """ - Validate package name format. - - Checks if the package name follows basic PyPI package naming conventions. - Does not validate existence on PyPI (that will be added in v1.2.1+). - - Args: - package: Package name to validate - - Returns: - True if format is valid, False otherwise - """ - if not package or not isinstance(package, str): - return False - - # Remove version specifiers and extras for validation - package_name = re.split(r"[<>=!\[]", package)[0].strip() - - # Basic package name pattern: letters, numbers, hyphens, underscores, dots - # Must start with letter or number - pattern = r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$" - - return bool(re.match(pattern, package_name)) - - -def validate_project_name(name: str) -> Tuple[bool, Optional[str]]: - """ - Validate project name. - - Args: - name: Project name to validate - - Returns: - Tuple of (is_valid, error_message) - """ - if not name: - return False, "Project name cannot be empty" - - if not name.replace("_", "").replace("-", "").isalnum(): - return ( - False, - "Project name must contain only letters, numbers, hyphens, and underscores", - ) - - if name[0].isdigit(): - return False, "Project name cannot start with a number" - - # Check for Python keywords - import keyword - - if keyword.iskeyword(name): - return False, f"Project name '{name}' is a Python keyword" - - return True, None - - -def validate_email_format(email: str) -> bool: - """ - Validate email address format using utils/main.py REGEX pattern. - - Args: - email: Email address to validate - - Returns: - True if format is valid, False otherwise - """ - if not email: - return False - - return bool(re.match(EMAIL_REGEX, email)) - - -def validate_feature_compatibility( - config: Dict[str, Any], -) -> Tuple[bool, Optional[str]]: - """ - Check compatibility between selected features. - - 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 - - Returns: - Tuple of (is_compatible, warning_or_error_message) - """ - 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 - - -def sanitize_custom_packages(packages: List[str]) -> List[str]: - """ - Clean and deduplicate custom package list. - - Args: - packages: List of package names (possibly with duplicates or empty strings) - - Returns: - Cleaned list of unique package names - """ - if not packages: - return [] - - # Remove empty strings and strip whitespace - cleaned = [pkg.strip() for pkg in packages if pkg and pkg.strip()] - - # Remove duplicates while preserving order - seen = set() - unique_packages = [] - for pkg in cleaned: - pkg_lower = pkg.lower() - if pkg_lower not in seen: - seen.add(pkg_lower) - unique_packages.append(pkg) - - # Validate each package name - valid_packages = [pkg for pkg in unique_packages if validate_package_name(pkg)] - - return valid_packages +from fastapi_fastkit.utils.validation import ( + EMAIL_REGEX, + ProjectNameProblem, + project_name_problem, + sanitize_custom_packages, + validate_email_format, + validate_feature_compatibility, + validate_package_name, + validate_project_name, +) + +__all__ = [ + "EMAIL_REGEX", + "ProjectNameProblem", + "project_name_problem", + "sanitize_custom_packages", + "validate_email_format", + "validate_feature_compatibility", + "validate_package_name", + "validate_project_name", +] diff --git a/src/fastapi_fastkit/backend/main.py b/src/fastapi_fastkit/backend/main.py index 22e63be3..cdb191df 100644 --- a/src/fastapi_fastkit/backend/main.py +++ b/src/fastapi_fastkit/backend/main.py @@ -14,8 +14,6 @@ import tomllib from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence -import click - from fastapi_fastkit.backend.package_managers import PackageManagerFactory from fastapi_fastkit.backend.package_managers.pdm_manager import ( prepare_template_pyproject as prepare_pdm_pyproject, @@ -48,13 +46,15 @@ from fastapi_fastkit.core.settings import settings from fastapi_fastkit.utils.config_file import format_toml_value from fastapi_fastkit.utils.logging import debug_log, get_logger -from fastapi_fastkit.utils.main import ( - FASTKIT_DESCRIPTION_MARKER, - FASTKIT_TOOL_SECTION, +from fastapi_fastkit.utils.output import ( handle_exception, print_info, print_success, print_warning, +) +from fastapi_fastkit.utils.project_meta import ( + FASTKIT_DESCRIPTION_MARKER, + FASTKIT_TOOL_SECTION, read_fastkit_metadata, ) from fastapi_fastkit.utils.textio import ( @@ -2251,6 +2251,9 @@ def ask_create_project_folder(project_name: str) -> bool: :param project_name: Name of the project :return: True if user wants to create a folder, False otherwise """ + # Imported here: generation imports this module and must not load click. + import click + return click.confirm( f"\nCreate a new project folder named '{project_name}'?\n" f"Yes: Templates will be placed in './{project_name}/'\n" @@ -2298,6 +2301,8 @@ def deploy_template_files( project_dir = user_local copied = copy_and_convert_template(target_template, user_local, "") + import click + click.echo(message) return project_dir, message, copied diff --git a/src/fastapi_fastkit/backend/package_managers/base.py b/src/fastapi_fastkit/backend/package_managers/base.py index cb1cbe98..25e6e5a1 100644 --- a/src/fastapi_fastkit/backend/package_managers/base.py +++ b/src/fastapi_fastkit/backend/package_managers/base.py @@ -13,8 +13,7 @@ from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import settings from fastapi_fastkit.utils.logging import debug_log -from fastapi_fastkit.utils.main import ( - console, +from fastapi_fastkit.utils.output import ( handle_exception, print_error, print_warning, @@ -241,6 +240,9 @@ def _run_checked( timeout = timeout if timeout is not None else settings.get_subprocess_timeout() extra: Dict[str, Any] = {} if env is None else {"env": dict(env)} + # Imported here: generation imports this module and must not load rich. + from fastapi_fastkit.utils.main import console + try: with console.status(f"[bold green]{status_msg}"): result: subprocess.CompletedProcess[str] = subprocess.run( @@ -310,6 +312,8 @@ def _print_output_summary( if not lines: return + from fastapi_fastkit.utils.main import console + for line in lines[-max_lines:]: console.print(f"[dim] {line}[/dim]") diff --git a/src/fastapi_fastkit/backend/package_managers/pdm_manager.py b/src/fastapi_fastkit/backend/package_managers/pdm_manager.py index 7772fa56..7c0a02b8 100644 --- a/src/fastapi_fastkit/backend/package_managers/pdm_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/pdm_manager.py @@ -12,7 +12,7 @@ from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import DEFAULT_REQUIRES_PYTHON, settings from fastapi_fastkit.utils.logging import debug_log, get_logger -from fastapi_fastkit.utils.main import print_success +from fastapi_fastkit.utils.output import print_success from fastapi_fastkit.utils.platform import resolve_command from fastapi_fastkit.utils.textio import write_generated_text diff --git a/src/fastapi_fastkit/backend/package_managers/pip_manager.py b/src/fastapi_fastkit/backend/package_managers/pip_manager.py index e81a4205..7a260f08 100644 --- a/src/fastapi_fastkit/backend/package_managers/pip_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/pip_manager.py @@ -9,7 +9,7 @@ from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import settings from fastapi_fastkit.utils.logging import debug_log, get_logger -from fastapi_fastkit.utils.main import print_success +from fastapi_fastkit.utils.output import print_success from fastapi_fastkit.utils.textio import ( UNTRANSLATED, read_text_preserving_newlines, diff --git a/src/fastapi_fastkit/backend/package_managers/poetry_manager.py b/src/fastapi_fastkit/backend/package_managers/poetry_manager.py index b0e3d2a6..fe45ff0b 100644 --- a/src/fastapi_fastkit/backend/package_managers/poetry_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/poetry_manager.py @@ -13,8 +13,7 @@ from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import DEFAULT_POETRY_PYTHON, settings from fastapi_fastkit.utils.logging import debug_log, get_logger -from fastapi_fastkit.utils.main import ( - console, +from fastapi_fastkit.utils.output import ( handle_exception, print_success, print_warning, @@ -407,6 +406,9 @@ def create_virtual_environment(self) -> str: venv_timeout = settings.get_subprocess_timeout("venv") + # Imported here: generation imports this module and must not load rich. + from fastapi_fastkit.utils.main import console + try: with console.status("[bold green]Querying Poetry environment..."): result = subprocess.run( diff --git a/src/fastapi_fastkit/backend/package_managers/pyproject.py b/src/fastapi_fastkit/backend/package_managers/pyproject.py index a7025ca8..4d90ec06 100644 --- a/src/fastapi_fastkit/backend/package_managers/pyproject.py +++ b/src/fastapi_fastkit/backend/package_managers/pyproject.py @@ -31,6 +31,7 @@ from fastapi_fastkit.core.settings import DEFAULT_REQUIRES_PYTHON from fastapi_fastkit.utils.logging import debug_log +from fastapi_fastkit.utils.output import print_warning from fastapi_fastkit.utils.textio import ( read_text_preserving_newlines, write_text_preserving_newlines, @@ -1148,9 +1149,6 @@ def replace_dev_declarations( :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") @@ -1182,8 +1180,6 @@ def sync_pyproject_dev_file( :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 diff --git a/src/fastapi_fastkit/backend/package_managers/uv_manager.py b/src/fastapi_fastkit/backend/package_managers/uv_manager.py index 1a5785c7..ff8971a9 100644 --- a/src/fastapi_fastkit/backend/package_managers/uv_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/uv_manager.py @@ -9,7 +9,7 @@ from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import DEFAULT_REQUIRES_PYTHON, settings from fastapi_fastkit.utils.logging import debug_log, get_logger -from fastapi_fastkit.utils.main import print_success +from fastapi_fastkit.utils.output import print_success from fastapi_fastkit.utils.platform import resolve_command from fastapi_fastkit.utils.textio import write_generated_text diff --git a/src/fastapi_fastkit/backend/project_builder/config_generator.py b/src/fastapi_fastkit/backend/project_builder/config_generator.py index 4229985c..3649b148 100644 --- a/src/fastapi_fastkit/backend/project_builder/config_generator.py +++ b/src/fastapi_fastkit/backend/project_builder/config_generator.py @@ -34,7 +34,6 @@ from jinja2 import Environment, PackageLoader -from fastapi_fastkit.backend.doctor.known import KNOWN_EXAMPLE_SECRETS from fastapi_fastkit.backend.package_managers.pyproject import ( PyprojectMergeError, parse_toml, @@ -45,6 +44,7 @@ _binds_at_top_level, ) from fastapi_fastkit.core.exceptions import BackendExceptions +from fastapi_fastkit.core.known import KNOWN_EXAMPLE_SECRETS from fastapi_fastkit.core.settings import ( MULTI_SELECT_AXES, NONE_CHOICE, diff --git a/src/fastapi_fastkit/backend/project_builder/dependency_collector.py b/src/fastapi_fastkit/backend/project_builder/dependency_collector.py index 6e25cc4b..56e14aea 100644 --- a/src/fastapi_fastkit/backend/project_builder/dependency_collector.py +++ b/src/fastapi_fastkit/backend/project_builder/dependency_collector.py @@ -27,6 +27,7 @@ NONE_CHOICE, FeatureAxis, ) +from fastapi_fastkit.utils.validation import sanitize_custom_packages _SIMPLE_NAME_PATTERN = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$") @@ -203,11 +204,6 @@ def collect(self, config: Dict[str, Any]) -> DependencySet: Returns: The split, merged dependency set """ - # Imported here: the interactive package imports this module. - from fastapi_fastkit.backend.interactive.validators import ( - sanitize_custom_packages, - ) - catalog = load_catalog() selection = selection_from_config(config, catalog) runtime: List[str] = list(catalog.defaults.base_dependencies) diff --git a/src/fastapi_fastkit/backend/route_generators.py b/src/fastapi_fastkit/backend/route_generators.py index 497a9aa2..5bd7a972 100644 --- a/src/fastapi_fastkit/backend/route_generators.py +++ b/src/fastapi_fastkit/backend/route_generators.py @@ -29,7 +29,8 @@ ) from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import settings -from fastapi_fastkit.utils.main import print_warning, read_fastkit_metadata +from fastapi_fastkit.utils.output import print_warning +from fastapi_fastkit.utils.project_meta import read_fastkit_metadata from fastapi_fastkit.utils.textio import read_text_preserving_newlines ROUTE_LAYOUTS = ("classic-layer", "domain") diff --git a/src/fastapi_fastkit/backend/route_wiring.py b/src/fastapi_fastkit/backend/route_wiring.py index 5f18bf9a..d4e72ea1 100644 --- a/src/fastapi_fastkit/backend/route_wiring.py +++ b/src/fastapi_fastkit/backend/route_wiring.py @@ -7,7 +7,7 @@ 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.output import print_info, print_warning from fastapi_fastkit.utils.textio import read_text_preserving_newlines #: Content of an API router module ``addroute`` has to create. The anchors diff --git a/src/fastapi_fastkit/catalog/i18n/de.toml b/src/fastapi_fastkit/catalog/i18n/de.toml new file mode 100644 index 00000000..4e64da66 --- /dev/null +++ b/src/fastapi_fastkit/catalog/i18n/de.toml @@ -0,0 +1,387 @@ +[levels."hello"] +label = "Hello" +description = "Eine einzige main.py: 3 Endpunkte, Daten im Arbeitsspeicher und Tests." +read_first = "Lies `main.py` von oben nach unten: Jeder Kommentar verlinkt die Seite des FastAPI-Tutorials, die diesen Code erklärt." +extend = "Füge eine Ressource hinzu, indem du den vorhandenen Code nachahmst: Kopiere die Modelle `Item`, `create_item`, `read_item` und ihre Tests und benenne sie für `/users` um." + +[levels."single-file"] +label = "Einzelne Datei" +description = "Die ganze Anwendung in einem Modul, mit Einstellungen und Tests." +read_first = "Lies `src/main.py`: Die Einstellungen, die Anwendung und ihre Routen stehen in einem Modul." + +[levels."layered"] +label = "Schichten" +description = "Getrennte Schichten: Routen, CRUD, Schemas, Kernkonfiguration." +read_first = "Lies `src/main.py`, danach `src/api/routes/items.py`, `src/crud/items.py` und `src/schemas/items.py`." + +[levels."domain"] +label = "Domänen" +description = "Ein Paket pro Domäne, mit Router, Service und Repository." +read_first = "Lies `src/app/main.py`, danach in `src/app/domains/items/` die Dateien `router.py`, `service.py` und `repository.py`." + +[levels."production"] +label = "Produktion" +description = "Die Stufe Domänen plus PostgreSQL, Alembic, JWT, CI und Docker." +read_first = "Lies `src/app/main.py`, danach `src/app/domains/items/`; die README.md beschreibt jede ausgewählte Funktion." + +[presets."single-module"] +summary = "Alles in einem Modul; ideal für kleine Skripte und Prototypen." + +[presets."classic-layered"] +summary = "Aufteilung in Schichten: api/routes, crud, schemas, core (wie fastapi-default)." + +[presets."domain-starter"] +summary = "Domänenorientiert: src/app/domains// mit router/service/repository (empfohlen)." + +[templates."fastapi-hello"] +description = "Die kleinste FastAPI-Anwendung: drei Endpunkte, ein Modell und ihre Tests" +read_first = "Lies `main.py` von oben nach unten: Jeder Kommentar verlinkt die Seite des FastAPI-Tutorials, die diesen Code erklärt." +extend = "Füge eine Ressource hinzu, indem du den vorhandenen Code nachahmst: Kopiere die Modelle `Item`, `create_item`, `read_item` und ihre Tests und benenne sie für `/users` um." + +[templates."fastapi-single-module"] +description = "FastAPI-Vorlage mit einem einzigen Modul" +read_first = "Lies `src/main.py`: Die Einstellungen, die Anwendung und ihre Routen stehen in einem Modul." + +[templates."fastapi-default"] +description = "Einfaches FastAPI-Projekt" +read_first = "Lies `src/main.py`, danach `src/api/routes/items.py`, `src/crud/items.py` und `src/schemas/items.py`." + +[templates."fastapi-domain-starter"] +description = "FastAPI-Startvorlage mit Domänenstruktur" +read_first = "Lies `src/app/main.py`, danach in `src/app/domains/items/` die Dateien `router.py`, `service.py` und `repository.py`." + +[templates."fastapi-custom-response"] +description = "Asynchrone API zur Verwaltung von Items mit einem eigenen Antwortsystem" +read_first = "Lies `src/main.py`, danach `src/helper/responses.py` und `src/api/routes/items.py`, um den Aufbau der Antwort-Hülle zu sehen." + +[templates."fastapi-auth-jwt"] +description = "FastAPI mit JWT-Authentifizierung" +read_first = "Lies `src/app/main.py`, danach `src/app/domains/auth/` und `src/app/core/security.py`." + +[templates."fastapi-sqlmodel"] +description = "FastAPI mit SQLModel" +read_first = "Lies `src/app/main.py`, danach `src/app/domains/items/` und `src/app/db/session.py`; die README erklärt, wie du auf PostgreSQL oder MySQL umstellst." + +[templates."fastapi-mcp"] +description = "FastAPI-Projekt mit MCP" +read_first = "Lies `src/main.py`, danach `src/mcp_server/router.py` und `src/auth/`." + +[templates."fastapi-llm-agent"] +description = "FastAPI-Projekt mit einem LLM-Agenten" +read_first = "Lies `src/app/main.py`, danach `src/app/api/chat.py` und `src/app/llm/agent.py`." + +[package_managers."pip"] +description = "Standard-Paketmanager von Python" + +[package_managers."uv"] +description = "Schneller Python-Paketmanager" + +[package_managers."pdm"] +description = "Moderne Verwaltung von Python-Abhängigkeiten" + +[package_managers."poetry"] +description = "Verwaltung und Paketierung von Python-Abhängigkeiten" + +[axes."database"] +label = "Datenbank" +description = "Auswahl von Datenbank und ORM" + +[axes."database".options."PostgreSQL"] +summary = "PostgreSQL über asynchrones SQLAlchemy (asyncpg)" +guide = "Asynchrone SQLAlchemy-Engine mit einer Sitzung pro Anfrage (`SessionDep`) für PostgreSQL über asyncpg. Setze `DATABASE_URL` in `.env`; `GET /ready` prüft die Verbindung." + +[axes."database".options."MySQL"] +summary = "MySQL über asynchrones SQLAlchemy (aiomysql)" +guide = "Asynchrone SQLAlchemy-Engine mit einer Sitzung pro Anfrage (`SessionDep`) für MySQL über aiomysql. Setze `DATABASE_URL` in `.env`; `GET /ready` prüft die Verbindung." + +[axes."database".options."MongoDB"] +summary = "MongoDB über den asynchronen Client von PyMongo" +guide = "Asynchroner PyMongo-Client, der mit der Anwendung geöffnet und geschlossen wird. Setze `MONGODB_URL` in `.env`; `GET /ready` sendet einen Ping an den Server." + +[axes."database".options."Redis"] +summary = "Redis als Key-Value-Speicher (asyncio-Client von redis-py)" +guide = "Asyncio-Client von redis-py (`redis_client`), der mit der Anwendung geschlossen wird. Setze `REDIS_URL` in `.env`." + +[axes."database".options."SQLite"] +summary = "SQLite-Datei über asynchrones SQLAlchemy (aiosqlite), ohne Server" +guide = "Asynchrone SQLAlchemy-Engine mit einer Sitzung pro Anfrage (`SessionDep`) für eine SQLite-Datei über aiosqlite; ein Server ist nicht nötig. `DATABASE_URL` in `.env` gibt die Datei an." + +[axes."database".options."None"] +label = "Keine" +summary = "Keine Datenbank" + +[axes."authentication"] +label = "Authentifizierung" +description = "Authentifizierung und Autorisierung von Benutzern" + +[axes."authentication".options."JWT"] +summary = "OAuth2-Passwort-Flow mit JWT (für APIs empfohlen)" +guide = "OAuth2-Passwort-Flow: `POST /api/v1/auth/token` gibt ein mit `SECRET_KEY` signiertes JWT zurück, und die Abhängigkeit `CurrentUser` schützt deine Endpunkte." + +[axes."authentication".options."OAuth2"] +summary = "OAuth2 mit authlib" +guide = "Anmeldung mit Google oder GitHub über Authlib. Setze die Zugangsdaten `GOOGLE_*` oder `GITHUB_*` in `.env`, um einen Anbieter zu aktivieren." + +[axes."authentication".options."FastAPI-Users"] +summary = "Vollständige Benutzerverwaltung (JWT; nur SQL-Datenbanken)" +guide = "Registrierung, Anmeldung und Benutzerverwaltung mit FastAPI-Users, gespeichert in der SQL-Datenbank." + +[axes."authentication".options."Session-based"] +summary = "Klassische sitzungsbasierte Authentifizierung" +guide = "Die Anmeldung setzt ein signiertes Sitzungs-Cookie; die Abmeldung beendet alle Sitzungen des Kontos." + +[axes."authentication".options."None"] +label = "Keine" +summary = "Keine Authentifizierung" + +[axes."async_tasks"] +label = "Hintergrundaufgaben" +description = "Verarbeitung von Hintergrundaufgaben" + +[axes."async_tasks".options."Celery"] +guide = "Ein Celery-Worker und `/api/v1/tasks`-Endpunkte, die Aufgaben in eine Redis-Warteschlange stellen; starte den Worker neben der API." + +[axes."async_tasks".options."Dramatiq"] +guide = "Ein Dramatiq-Worker und `/api/v1/tasks`-Endpunkte, die Aufgaben in eine Redis-Warteschlange stellen; starte den Worker neben der API." + +[axes."async_tasks".options."None"] +label = "Keine" + +[axes."testing"] +label = "Tests" +description = "Test-Framework und Werkzeuge" + +[axes."testing".options."Basic"] +summary = "pytest + httpx zum Testen der API" +guide = "pytest mit einem Testmodul pro Funktion (In-Memory-SQLite bei SQL-Datenbanken)." + +[axes."testing".options."Coverage"] +summary = "Basis + Code-Coverage" +guide = "pytest mit einem Testmodul pro Funktion (In-Memory-SQLite bei SQL-Datenbanken); `pytest --cov` zeigt die Coverage an." + +[axes."testing".options."Advanced"] +summary = "Coverage + faker + factory-boy für Fixtures" +guide = "pytest mit einem Testmodul pro Funktion (In-Memory-SQLite bei SQL-Datenbanken); `pytest --cov` zeigt die Coverage an, und `tests/factories.py` enthält die Factories von faker und factory-boy." + +[axes."testing".options."None"] +label = "Keine" +summary = "Kein Test-Framework" + +[axes."caching"] +label = "Caching" +description = "Caching von Antworten und Daten" + +[axes."caching".options."Redis"] +guide = "Caching von Antworten mit fastapi-cache2 auf Redis; der Router unter `/api/v1/cache` zeigt den Decorator." + +[axes."caching".options."None"] +label = "Keines" + +[axes."monitoring"] +label = "Monitoring" +description = "Überwachung und Logging der Anwendung" + +[axes."monitoring".options."Loguru"] +summary = "Erweitertes Logging mit Loguru" +guide = "Loguru übernimmt die Log-Ausgabe der Anwendung und von Uvicorn." + +[axes."monitoring".options."OpenTelemetry"] +summary = "Verteiltes Tracing und Metriken" +guide = "Verfolgt jede Anfrage und exportiert die Spans über OTLP; setze die Exporter-Einstellungen in `.env`." + +[axes."monitoring".options."Prometheus"] +summary = "Prometheus-Metriken" +guide = "Stellt Anfrage-Metriken unter `/metrics` bereit." + +[axes."monitoring".options."None"] +label = "Keines" +summary = "Kein zusätzliches Monitoring" + +[axes."utilities"] +label = "Hilfsfunktionen" +description = "Zusätzliche Hilfsfunktionen und Middleware" + +[axes."utilities".options."Rate-Limiting"] +summary = "Anfragelimits der API pro Client (limits)" +guide = "Limits pro Client für jede Route (`RATE_LIMIT_DEFAULT`), strenger bei den Anmelde-Endpunkten, wenn eine Authentifizierung ausgewählt ist (`RATE_LIMIT_AUTH`); ein Client, der sein Limit überschreitet, erhält ein 429." + +[axes."utilities".options."WebSocket"] +summary = "Beispiel-Endpunkt für WebSocket (websockets)" +guide = "Ein WebSocket-Endpunkt unter `/ws` und `GET /api/v1/connections`." + +[axes."utilities".options."None"] +label = "Keine" + +[axes."migrations"] +label = "Migrationen" +description = "Migrationen des Datenbankschemas" + +[axes."migrations".options."Alembic"] +summary = "alembic.ini + asynchrone alembic/env.py + scripts/migrate.sh" +guide = "Alembic-Migrationen in `alembic/`: `alembic upgrade head` legt die Tabellen an, `alembic revision --autogenerate -m \"add orders\"` hält eine Modelländerung fest." + +[axes."migrations".options."None"] +label = "Keine" +summary = "Kein Migrationswerkzeug" + +[axes."tooling"] +label = "Entwicklerwerkzeuge" +description = "Entwicklerwerkzeuge und CI-Konfiguration" + +[axes."tooling".options."ruff"] +summary = "ruff + ruff-format-Konfiguration in pyproject.toml (ersetzt black/isort)" +guide = "ruff prüft und formatiert den Code: `ruff check .` und `ruff format .`." + +[axes."tooling".options."pre-commit"] +summary = ".pre-commit-config.yaml" +guide = "Führt die Prüfungen vor jedem Commit aus, sobald du `pre-commit install` ausgeführt hast." + +[axes."tooling".options."github-actions"] +summary = ".github/workflows/test.yml (Python 3.12)" +guide = "Führt die Tests bei Pushes auf `main` und bei jedem Pull Request aus." + +[axes."tooling".options."devcontainer"] +summary = ".devcontainer/devcontainer.json" +guide = "Öffnet das Projekt in einem Entwicklungscontainer mit dem passenden Python." + +[axes."tooling".options."makefile"] +summary = "Makefile mit install/test/lint/format/run" +guide = "Abkürzungen: `make install`, `make test`, `make lint`, `make format`, `make run`." + +[axes."tooling".options."None"] +label = "Keine" + +[axes."logging"] +label = "Logging" +description = "Format der Anwendungslogs" + +[axes."logging".options."structured"] +summary = "JSON-Logs + Korrelations-Middleware für X-Request-ID (nur Standardbibliothek)" +guide = "JSON-Logzeilen mit einer `X-Request-ID` pro Anfrage (aus der Anfrage übernommen oder neu erzeugt)." + +[axes."logging".options."None"] +label = "Keines" +summary = "Das einfache Text-Logging von Uvicorn" + +[axes."deployment"] +label = "Deployment" +description = "Dateien für das Deployment mit Containern" + +[axes."deployment".options."Docker"] +summary = "Erzeugt ein Dockerfile" +guide = "Baut das Image der Anwendung (`docker build -t .`); der Container liest seine Einstellungen aus der Umgebung, nie aus einer hineinkopierten `.env`." + +[axes."deployment".options."docker-compose"] +summary = "Erzeugt docker-compose.yml (schließt Docker ein)" +guide = "`docker compose up --build` startet die Anwendung mit ihren Diensten." + +[axes."deployment".options."None"] +label = "Keines" +summary = "Keine Deployment-Konfiguration" + +[rules."fastapi-users-needs-sql"] +message = "Die Authentifizierung 'FastAPI-Users' benötigt eine SQL-Datenbank ({allowed}), ausgewählt ist aber {selected}. Wähle eine dieser Datenbanken oder die Option 'JWT', die mit jeder Datenbank funktioniert." + +[rules."shared-redis"] +message = "Info: Redis wird sowohl für das Caching als auch für die Aufgabenwarteschlange verwendet (gemeinsame Abhängigkeit)." + +[concepts."first-steps"] +title = "Erste Schritte" + +[concepts."path-parameters"] +title = "Pfadparameter" + +[concepts."query-parameters"] +title = "Query-Parameter" + +[concepts."request-body"] +title = "Request Body" + +[concepts."response-model"] +title = "Response-Modell" + +[concepts."status-codes"] +title = "Response-Statuscodes" + +[concepts."handling-errors"] +title = "Fehlerbehandlung" + +[concepts."dependencies"] +title = "Abhängigkeiten" + +[concepts."dependencies-with-yield"] +title = "Abhängigkeiten mit yield" + +[concepts."bigger-applications"] +title = "Größere Anwendungen mit mehreren Dateien" + +[concepts."settings"] +title = "Einstellungen und Umgebungsvariablen" + +[concepts."lifespan"] +title = "Lifespan-Events" + +[concepts."sql-databases"] +title = "SQL-Datenbanken" + +[concepts."security-jwt"] +title = "OAuth2 mit Passwort und JWT-Tokens" + +[concepts."cors"] +title = "CORS" + +[concepts."middleware"] +title = "Middleware" + +[concepts."testing"] +title = "Tests" + +[concepts."background-tasks"] +title = "Hintergrundaufgaben" + +[concepts."websockets"] +title = "WebSockets" + +[concepts."deployment-docker"] +title = "FastAPI in Containern (Docker)" + +[concepts."async"] +title = "Nebenläufigkeit und async / await" + +[guide] +next_steps = "Nächste Schritte" +open = "Wechsle in den Projektordner." +install = "Erstelle die virtuelle Umgebung und installiere die Abhängigkeiten." +install_pip = "Erstelle eine virtuelle Umgebung, aktiviere sie und installiere die Abhängigkeiten." +install_into_venv = "Installiere die Abhängigkeiten in die virtuelle Umgebung, die fastkit erstellt hat." +activate = "Aktiviere die virtuelle Umgebung." +env = "Erstelle deine lokale Einstellungsdatei aus dem Beispiel und nimm sie aus der Versionskontrolle heraus." +env_written = "Prüfe .env: fastkit hat sie aus .env.example mit einem eindeutigen SECRET_KEY erstellt." +env_kept = "Deine vorhandene .env wurde beibehalten; vergleiche sie mit .env.example, um neue Einstellungen zu finden." +services = "Starte {services} und lass die URL-Einstellungen in .env darauf zeigen." +migrate = "Lege die Datenbanktabellen an." +worker = "Starte den Hintergrund-Worker in einem zweiten Terminal." +run = "Starte den Entwicklungsserver und öffne http://127.0.0.1:8000/docs." +run_readme_alternative = "Ist fastkit installiert, erledigt `fastkit runserver` dasselbe." +run_compose = "Du kannst es auch mit Docker Compose in Containern ausführen: `docker compose up --build`." +test = "Führe die Tests aus." +extend_classic = "Füge eine Ressource mit ihrer Route, ihren Schemas, ihrer Datenschicht und ihren Tests hinzu." +extend_domain = "Füge eine Domäne mit ihrem Router, ihren Schemas, ihrem Service, ihrem Repository und ihren Tests hinzu." +needs_fastkit = "Der Befehl setzt voraus, dass fastkit installiert ist." +next_level = "Wenn du mehr Struktur möchtest, erstelle ein Projekt auf der nächsten Stufe." +items_sql = "Die Beispiel-API `/items` speichert ihre Items in dieser Datenbank." +items_memory = "Die Beispiel-API `/items` hält ihre Items im Arbeitsspeicher: fastkit speichert sie nur bei PostgreSQL, MySQL und SQLite in der Datenbank." +items_file = "Die Beispiel-API `/items` hält ihre Items in der JSON-Datei `src/mocks/mock_items.json`, nicht in dieser Datenbank." +tables_alembic = "`alembic upgrade head` legt die Tabellen an." +tables_startup = "Die Tabellen werden beim Start der Anwendung angelegt (es sind keine Migrationen ausgewählt)." +compose_urls = "In den Containern stammen die URLs dieser Dienste aus `docker-compose.yml`; die URLs in `.env` sind für den Betrieb der Anwendung auf deinem Rechner gedacht." +compose_migrate = "Ein einmaliger `migrate`-Dienst wendet die Alembic-Migrationen an, bevor die Anwendung startet." +compose_sqlite = "Die SQLite-Datenbankdatei liegt im Volume `sqlite_data`." +read_single_file_split = "Lies `src/main.py` für die Anwendung und ihre Routen, danach `src/core/config.py` für die Einstellungen." +read_layered_sql_items = "Lies `src/main.py`, danach `src/api/routes/items.py`, `src/crud/items.py`, `src/models/items.py` und `src/schemas/items.py`." +single_file_split = "Deine Auswahl fügt Module hinzu, die die Einstellungen lesen, deshalb sind die Einstellungen von `src/main.py` nach `src/core/config.py` umgezogen; `src/main.py` behält die Anwendung und ihre Routen und bindet die Funktionen ein." +files = "Dateien" +settings = "Einstellungen" +learn_more = "Mehr erfahren" +selected_features = "Ausgewählte Funktionen" +same_in_readme = "Die README.md listet die Schritte für einen frisch ausgecheckten Stand des Projekts auf." diff --git a/src/fastapi_fastkit/catalog/i18n/es.toml b/src/fastapi_fastkit/catalog/i18n/es.toml new file mode 100644 index 00000000..32668c7f --- /dev/null +++ b/src/fastapi_fastkit/catalog/i18n/es.toml @@ -0,0 +1,387 @@ +[levels."hello"] +label = "Hello" +description = "Un solo main.py: 3 endpoints, datos en memoria y pruebas." +read_first = "Lee `main.py` de principio a fin: cada comentario enlaza la página del tutorial de FastAPI que explica ese código." +extend = "Añade un recurso imitando el código existente: copia los modelos `Item`, `create_item`, `read_item` y sus pruebas, y cámbiales el nombre para `/users`." + +[levels."single-file"] +label = "Un solo archivo" +description = "Toda la aplicación en un solo módulo, con configuración y pruebas." +read_first = "Lee `src/main.py`: la configuración, la aplicación y sus rutas están en un solo módulo." + +[levels."layered"] +label = "Por capas" +description = "Capas separadas: rutas, CRUD, esquemas y configuración del núcleo." +read_first = "Lee `src/main.py` y después `src/api/routes/items.py`, `src/crud/items.py` y `src/schemas/items.py`." + +[levels."domain"] +label = "Por dominios" +description = "Un paquete por dominio, con router, servicio y repositorio." +read_first = "Lee `src/app/main.py` y después, en `src/app/domains/items/`, `router.py`, `service.py` y `repository.py`." + +[levels."production"] +label = "Producción" +description = "El nivel por dominios más PostgreSQL, Alembic, JWT, CI y Docker." +read_first = "Lee `src/app/main.py` y después `src/app/domains/items/`; README.md describe cada funcionalidad seleccionada." + +[presets."single-module"] +summary = "Todo en un solo módulo; ideal para scripts pequeños y prototipos." + +[presets."classic-layered"] +summary = "División por capas: api/routes, crud, schemas y core (como fastapi-default)." + +[presets."domain-starter"] +summary = "Orientado a dominios: src/app/domains// con router/service/repository (recomendado)." + +[templates."fastapi-hello"] +description = "La aplicación FastAPI más pequeña: tres endpoints, un modelo y sus pruebas" +read_first = "Lee `main.py` de principio a fin: cada comentario enlaza la página del tutorial de FastAPI que explica ese código." +extend = "Añade un recurso imitando el código existente: copia los modelos `Item`, `create_item`, `read_item` y sus pruebas, y cámbiales el nombre para `/users`." + +[templates."fastapi-single-module"] +description = "Plantilla de FastAPI con un solo módulo" +read_first = "Lee `src/main.py`: la configuración, la aplicación y sus rutas están en un solo módulo." + +[templates."fastapi-default"] +description = "Proyecto FastAPI sencillo" +read_first = "Lee `src/main.py` y después `src/api/routes/items.py`, `src/crud/items.py` y `src/schemas/items.py`." + +[templates."fastapi-domain-starter"] +description = "Plantilla inicial de FastAPI por dominios" +read_first = "Lee `src/app/main.py` y después, en `src/app/domains/items/`, `router.py`, `service.py` y `repository.py`." + +[templates."fastapi-custom-response"] +description = "API asíncrona de gestión de ítems con un sistema de respuestas personalizado" +read_first = "Lee `src/main.py` y después `src/helper/responses.py` y `src/api/routes/items.py` para ver la estructura del envoltorio de respuesta." + +[templates."fastapi-auth-jwt"] +description = "FastAPI con autenticación JWT" +read_first = "Lee `src/app/main.py` y después `src/app/domains/auth/` y `src/app/core/security.py`." + +[templates."fastapi-sqlmodel"] +description = "FastAPI con SQLModel" +read_first = "Lee `src/app/main.py` y después `src/app/domains/items/` y `src/app/db/session.py`; el README explica cómo cambiar a PostgreSQL o MySQL." + +[templates."fastapi-mcp"] +description = "Proyecto FastAPI con MCP" +read_first = "Lee `src/main.py` y después `src/mcp_server/router.py` y `src/auth/`." + +[templates."fastapi-llm-agent"] +description = "Proyecto FastAPI con un agente LLM" +read_first = "Lee `src/app/main.py` y después `src/app/api/chat.py` y `src/app/llm/agent.py`." + +[package_managers."pip"] +description = "Gestor de paquetes estándar de Python" + +[package_managers."uv"] +description = "Gestor de paquetes de Python rápido" + +[package_managers."pdm"] +description = "Gestión moderna de dependencias de Python" + +[package_managers."poetry"] +description = "Gestión de dependencias y empaquetado de Python" + +[axes."database"] +label = "Base de datos" +description = "Elección de la base de datos y del ORM" + +[axes."database".options."PostgreSQL"] +summary = "PostgreSQL con SQLAlchemy asíncrono (asyncpg)" +guide = "Motor de SQLAlchemy asíncrono con una sesión por petición (`SessionDep`) para PostgreSQL mediante asyncpg. Define `DATABASE_URL` en `.env`; `GET /ready` comprueba la conexión." + +[axes."database".options."MySQL"] +summary = "MySQL con SQLAlchemy asíncrono (aiomysql)" +guide = "Motor de SQLAlchemy asíncrono con una sesión por petición (`SessionDep`) para MySQL mediante aiomysql. Define `DATABASE_URL` en `.env`; `GET /ready` comprueba la conexión." + +[axes."database".options."MongoDB"] +summary = "MongoDB con el cliente asíncrono de PyMongo" +guide = "Cliente asíncrono de PyMongo, que se abre y se cierra junto con la aplicación. Define `MONGODB_URL` en `.env`; `GET /ready` hace ping al servidor." + +[axes."database".options."Redis"] +summary = "Redis como almacén de clave-valor (cliente asyncio de redis-py)" +guide = "Cliente asyncio de redis-py (`redis_client`), que se cierra junto con la aplicación. Define `REDIS_URL` en `.env`." + +[axes."database".options."SQLite"] +summary = "Archivo SQLite con SQLAlchemy asíncrono (aiosqlite), sin necesidad de servidor" +guide = "Motor de SQLAlchemy asíncrono con una sesión por petición (`SessionDep`) para un archivo SQLite mediante aiosqlite; no hace falta servidor. `DATABASE_URL` en `.env` indica el archivo." + +[axes."database".options."None"] +label = "Ninguna" +summary = "Sin base de datos" + +[axes."authentication"] +label = "Autenticación" +description = "Autenticación y autorización de usuarios" + +[axes."authentication".options."JWT"] +summary = "Flujo de contraseña de OAuth2 con JWT (recomendado para APIs)" +guide = "Flujo de contraseña de OAuth2: `POST /api/v1/auth/token` devuelve un JWT firmado con `SECRET_KEY`, y la dependencia `CurrentUser` protege tus endpoints." + +[axes."authentication".options."OAuth2"] +summary = "OAuth2 con authlib" +guide = "Inicio de sesión con Google o GitHub mediante Authlib. Define las credenciales `GOOGLE_*` o `GITHUB_*` en `.env` para activar un proveedor." + +[axes."authentication".options."FastAPI-Users"] +summary = "Gestión completa de usuarios (JWT; solo bases de datos SQL)" +guide = "Registro, inicio de sesión y gestión de usuarios con FastAPI-Users, guardados en la base de datos SQL." + +[axes."authentication".options."Session-based"] +summary = "Autenticación tradicional basada en sesiones" +guide = "Al iniciar sesión se establece una cookie de sesión firmada; al cerrar sesión terminan todas las sesiones de la cuenta." + +[axes."authentication".options."None"] +label = "Ninguna" +summary = "Sin autenticación" + +[axes."async_tasks"] +label = "Tareas en segundo plano" +description = "Procesamiento de tareas en segundo plano" + +[axes."async_tasks".options."Celery"] +guide = "Un worker de Celery y endpoints `/api/v1/tasks` que encolan trabajos en Redis; ejecuta el worker junto a la API." + +[axes."async_tasks".options."Dramatiq"] +guide = "Un worker de Dramatiq y endpoints `/api/v1/tasks` que encolan trabajos en Redis; ejecuta el worker junto a la API." + +[axes."async_tasks".options."None"] +label = "Ninguna" + +[axes."testing"] +label = "Pruebas" +description = "Framework y herramientas de pruebas" + +[axes."testing".options."Basic"] +summary = "pytest + httpx para probar la API" +guide = "pytest con un módulo de pruebas por funcionalidad (SQLite en memoria para las bases de datos SQL)." + +[axes."testing".options."Coverage"] +summary = "Lo básico + cobertura de código" +guide = "pytest con un módulo de pruebas por funcionalidad (SQLite en memoria para las bases de datos SQL); `pytest --cov` informa de la cobertura." + +[axes."testing".options."Advanced"] +summary = "Cobertura + faker + factory-boy para los fixtures" +guide = "pytest con un módulo de pruebas por funcionalidad (SQLite en memoria para las bases de datos SQL); `pytest --cov` informa de la cobertura, y `tests/factories.py` contiene las factorías de faker y factory-boy." + +[axes."testing".options."None"] +label = "Ninguna" +summary = "Sin framework de pruebas" + +[axes."caching"] +label = "Caché" +description = "Caché de respuestas y de datos" + +[axes."caching".options."Redis"] +guide = "Caché de respuestas con fastapi-cache2 sobre Redis; el router de `/api/v1/cache` muestra el decorador." + +[axes."caching".options."None"] +label = "Ninguna" + +[axes."monitoring"] +label = "Monitorización" +description = "Monitorización y registro de la aplicación" + +[axes."monitoring".options."Loguru"] +summary = "Registro mejorado con Loguru" +guide = "Loguru se encarga de la salida de logs de la aplicación y de Uvicorn." + +[axes."monitoring".options."OpenTelemetry"] +summary = "Trazado distribuido y métricas" +guide = "Traza cada petición y exporta los spans por OTLP; define la configuración del exportador en `.env`." + +[axes."monitoring".options."Prometheus"] +summary = "Instrumentación de métricas con Prometheus" +guide = "Expone las métricas de las peticiones en `/metrics`." + +[axes."monitoring".options."None"] +label = "Ninguna" +summary = "Sin monitorización adicional" + +[axes."utilities"] +label = "Utilidades" +description = "Utilidades y middleware adicionales" + +[axes."utilities".options."Rate-Limiting"] +summary = "Límites de peticiones de la API por cliente (limits)" +guide = "Límites por cliente en todas las rutas (`RATE_LIMIT_DEFAULT`), más estrictos en los endpoints de inicio de sesión cuando se selecciona la autenticación (`RATE_LIMIT_AUTH`); un cliente que supera su límite recibe un 429." + +[axes."utilities".options."WebSocket"] +summary = "Endpoint WebSocket de ejemplo (websockets)" +guide = "Un endpoint WebSocket en `/ws` y `GET /api/v1/connections`." + +[axes."utilities".options."None"] +label = "Ninguna" + +[axes."migrations"] +label = "Migraciones" +description = "Migraciones del esquema de la base de datos" + +[axes."migrations".options."Alembic"] +summary = "alembic.ini + alembic/env.py asíncrono + scripts/migrate.sh" +guide = "Migraciones de Alembic en `alembic/`: `alembic upgrade head` crea las tablas y `alembic revision --autogenerate -m \"add orders\"` registra un cambio en los modelos." + +[axes."migrations".options."None"] +label = "Ninguna" +summary = "Sin herramienta de migraciones" + +[axes."tooling"] +label = "Herramientas de desarrollo" +description = "Herramientas de desarrollo y configuración de CI" + +[axes."tooling".options."ruff"] +summary = "Configuración de ruff + ruff-format en pyproject.toml (sustituye a black/isort)" +guide = "ruff revisa y formatea el código: `ruff check .` y `ruff format .`." + +[axes."tooling".options."pre-commit"] +summary = ".pre-commit-config.yaml" +guide = "Ejecuta las comprobaciones antes de cada commit una vez que ejecutas `pre-commit install`." + +[axes."tooling".options."github-actions"] +summary = ".github/workflows/test.yml (Python 3.12)" +guide = "Ejecuta las pruebas en cada push a `main` y en cada pull request." + +[axes."tooling".options."devcontainer"] +summary = ".devcontainer/devcontainer.json" +guide = "Abre el proyecto en un contenedor de desarrollo con la versión de Python adecuada." + +[axes."tooling".options."makefile"] +summary = "Makefile con install/test/lint/format/run" +guide = "Atajos: `make install`, `make test`, `make lint`, `make format`, `make run`." + +[axes."tooling".options."None"] +label = "Ninguna" + +[axes."logging"] +label = "Registro (logging)" +description = "Formato de los logs de la aplicación" + +[axes."logging".options."structured"] +summary = "Logs en JSON + middleware de correlación X-Request-ID (solo biblioteca estándar)" +guide = "Líneas de log en JSON con un `X-Request-ID` por petición (tomado de la petición o generado)." + +[axes."logging".options."None"] +label = "Ninguno" +summary = "Logs de texto plano predeterminados de Uvicorn" + +[axes."deployment"] +label = "Despliegue" +description = "Archivos de despliegue con contenedores" + +[axes."deployment".options."Docker"] +summary = "Genera un Dockerfile" +guide = "Construye la imagen de la aplicación (`docker build -t .`); el contenedor lee su configuración del entorno, nunca de un `.env` copiado." + +[axes."deployment".options."docker-compose"] +summary = "Genera docker-compose.yml (incluye Docker)" +guide = "`docker compose up --build` inicia la aplicación con sus servicios." + +[axes."deployment".options."None"] +label = "Ninguno" +summary = "Sin configuración de despliegue" + +[rules."fastapi-users-needs-sql"] +message = "La autenticación 'FastAPI-Users' necesita una base de datos SQL ({allowed}), pero se ha seleccionado {selected}. Elige una de esas bases de datos o la opción 'JWT', que funciona con todas." + +[rules."shared-redis"] +message = "Información: Redis se usará tanto para la caché como para la cola de tareas (dependencia compartida)." + +[concepts."first-steps"] +title = "Primeros pasos" + +[concepts."path-parameters"] +title = "Parámetros de ruta" + +[concepts."query-parameters"] +title = "Parámetros de consulta" + +[concepts."request-body"] +title = "Cuerpo de la petición" + +[concepts."response-model"] +title = "Modelo de respuesta" + +[concepts."status-codes"] +title = "Códigos de estado de la respuesta" + +[concepts."handling-errors"] +title = "Manejo de errores" + +[concepts."dependencies"] +title = "Dependencias" + +[concepts."dependencies-with-yield"] +title = "Dependencias con yield" + +[concepts."bigger-applications"] +title = "Aplicaciones más grandes con varios archivos" + +[concepts."settings"] +title = "Configuración y variables de entorno" + +[concepts."lifespan"] +title = "Eventos de lifespan" + +[concepts."sql-databases"] +title = "Bases de datos SQL" + +[concepts."security-jwt"] +title = "OAuth2 con contraseña y tokens JWT" + +[concepts."cors"] +title = "CORS" + +[concepts."middleware"] +title = "Middleware" + +[concepts."testing"] +title = "Pruebas" + +[concepts."background-tasks"] +title = "Tareas en segundo plano" + +[concepts."websockets"] +title = "WebSockets" + +[concepts."deployment-docker"] +title = "FastAPI en contenedores (Docker)" + +[concepts."async"] +title = "Concurrencia y async / await" + +[guide] +next_steps = "Próximos pasos" +open = "Ve a la carpeta del proyecto." +install = "Crea el entorno virtual e instala las dependencias." +install_pip = "Crea un entorno virtual, actívalo e instala las dependencias." +install_into_venv = "Instala las dependencias en el entorno virtual que creó fastkit." +activate = "Activa el entorno virtual." +env = "Crea tu archivo de configuración local a partir del ejemplo y mantenlo fuera del control de versiones." +env_written = "Revisa .env: fastkit lo creó a partir de .env.example con una SECRET_KEY única." +env_kept = "Se conservó tu .env existente; compáralo con .env.example para ver si hay configuraciones nuevas." +services = "Inicia {services} y haz que las URL de .env apunten a él." +migrate = "Crea las tablas de la base de datos." +worker = "Inicia el worker en segundo plano en una segunda terminal." +run = "Inicia el servidor de desarrollo y abre http://127.0.0.1:8000/docs." +run_readme_alternative = "Con fastkit instalado, `fastkit runserver` hace lo mismo." +run_compose = "También puedes ejecutarlo en contenedores con Docker Compose: `docker compose up --build`." +test = "Ejecuta las pruebas." +extend_classic = "Añade un recurso con su ruta, sus esquemas, su capa de datos y sus pruebas." +extend_domain = "Añade un dominio con su router, sus esquemas, su servicio, su repositorio y sus pruebas." +needs_fastkit = "El comando necesita que fastkit esté instalado." +next_level = "Cuando quieras más estructura, crea un proyecto del siguiente nivel." +items_sql = "La API de ejemplo `/items` guarda sus ítems en esta base de datos." +items_memory = "La API de ejemplo `/items` guarda sus ítems en memoria: fastkit los guarda en la base de datos solo con PostgreSQL, MySQL y SQLite." +items_file = "La API de ejemplo `/items` guarda sus ítems en el archivo JSON `src/mocks/mock_items.json`, no en esta base de datos." +tables_alembic = "`alembic upgrade head` crea las tablas." +tables_startup = "Las tablas se crean cuando se inicia la aplicación (no se seleccionaron migraciones)." +compose_urls = "En los contenedores, las URL de estos servicios vienen de `docker-compose.yml`; las URL de `.env` sirven para ejecutar la aplicación en tu máquina." +compose_migrate = "Un servicio `migrate` de una sola ejecución aplica las migraciones de Alembic antes de que se inicie la aplicación." +compose_sqlite = "El archivo de la base de datos SQLite se guarda en el volumen `sqlite_data`." +read_single_file_split = "Lee `src/main.py` para ver la aplicación y sus rutas, y después `src/core/config.py` para la configuración." +read_layered_sql_items = "Lee `src/main.py` y después `src/api/routes/items.py`, `src/crud/items.py`, `src/models/items.py` y `src/schemas/items.py`." +single_file_split = "Lo que seleccionaste añade módulos que leen la configuración, así que la configuración pasó de `src/main.py` a `src/core/config.py`; `src/main.py` conserva la aplicación y sus rutas, e incluye las funcionalidades." +files = "Archivos" +settings = "Configuración" +learn_more = "Más información" +selected_features = "Funcionalidades seleccionadas" +same_in_readme = "README.md enumera los pasos para una copia nueva del proyecto." diff --git a/src/fastapi_fastkit/catalog/i18n/fr.toml b/src/fastapi_fastkit/catalog/i18n/fr.toml new file mode 100644 index 00000000..c9865a36 --- /dev/null +++ b/src/fastapi_fastkit/catalog/i18n/fr.toml @@ -0,0 +1,387 @@ +[levels."hello"] +label = "Hello" +description = "Un seul main.py : 3 endpoints, des données en mémoire et des tests." +read_first = "Lisez `main.py` de haut en bas : chaque commentaire renvoie vers la page du tutoriel FastAPI qui explique ce code." +extend = "Ajoutez une ressource en imitant le code existant : copiez les modèles `Item`, `create_item`, `read_item` et leurs tests, puis renommez-les pour `/users`." + +[levels."single-file"] +label = "Fichier unique" +description = "Toute l'application dans un seul module, avec la configuration et les tests." +read_first = "Lisez `src/main.py` : la configuration, l'application et ses routes sont réunies dans un seul module." + +[levels."layered"] +label = "Par couches" +description = "Des couches séparées : routes, CRUD, schémas, configuration du noyau." +read_first = "Lisez `src/main.py`, puis `src/api/routes/items.py`, `src/crud/items.py` et `src/schemas/items.py`." + +[levels."domain"] +label = "Par domaines" +description = "Un paquet par domaine, avec routeur, service et dépôt." +read_first = "Lisez `src/app/main.py`, puis, dans `src/app/domains/items/`, `router.py`, `service.py` et `repository.py`." + +[levels."production"] +label = "Production" +description = "Le niveau par domaines, plus PostgreSQL, Alembic, JWT, CI et Docker." +read_first = "Lisez `src/app/main.py`, puis `src/app/domains/items/` ; README.md décrit chaque fonctionnalité sélectionnée." + +[presets."single-module"] +summary = "Tout dans un seul module ; idéal pour de petits scripts et des prototypes." + +[presets."classic-layered"] +summary = "Découpage par couches : api/routes, crud, schemas, core (comme fastapi-default)." + +[presets."domain-starter"] +summary = "Orienté domaines : src/app/domains// avec router/service/repository (recommandé)." + +[templates."fastapi-hello"] +description = "La plus petite application FastAPI : trois endpoints, un modèle et leurs tests" +read_first = "Lisez `main.py` de haut en bas : chaque commentaire renvoie vers la page du tutoriel FastAPI qui explique ce code." +extend = "Ajoutez une ressource en imitant le code existant : copiez les modèles `Item`, `create_item`, `read_item` et leurs tests, puis renommez-les pour `/users`." + +[templates."fastapi-single-module"] +description = "Modèle FastAPI à module unique" +read_first = "Lisez `src/main.py` : la configuration, l'application et ses routes sont réunies dans un seul module." + +[templates."fastapi-default"] +description = "Projet FastAPI simple" +read_first = "Lisez `src/main.py`, puis `src/api/routes/items.py`, `src/crud/items.py` et `src/schemas/items.py`." + +[templates."fastapi-domain-starter"] +description = "Modèle de départ FastAPI par domaines" +read_first = "Lisez `src/app/main.py`, puis, dans `src/app/domains/items/`, `router.py`, `service.py` et `repository.py`." + +[templates."fastapi-custom-response"] +description = "API asynchrone de gestion d'articles avec un système de réponses personnalisé" +read_first = "Lisez `src/main.py`, puis `src/helper/responses.py` et `src/api/routes/items.py` pour voir la structure de l'enveloppe de réponse." + +[templates."fastapi-auth-jwt"] +description = "FastAPI avec authentification JWT" +read_first = "Lisez `src/app/main.py`, puis `src/app/domains/auth/` et `src/app/core/security.py`." + +[templates."fastapi-sqlmodel"] +description = "FastAPI avec SQLModel" +read_first = "Lisez `src/app/main.py`, puis `src/app/domains/items/` et `src/app/db/session.py` ; le README explique comment passer à PostgreSQL ou à MySQL." + +[templates."fastapi-mcp"] +description = "Projet FastAPI avec MCP" +read_first = "Lisez `src/main.py`, puis `src/mcp_server/router.py` et `src/auth/`." + +[templates."fastapi-llm-agent"] +description = "Projet FastAPI avec un agent LLM" +read_first = "Lisez `src/app/main.py`, puis `src/app/api/chat.py` et `src/app/llm/agent.py`." + +[package_managers."pip"] +description = "Gestionnaire de paquets standard de Python" + +[package_managers."uv"] +description = "Gestionnaire de paquets Python rapide" + +[package_managers."pdm"] +description = "Gestion moderne des dépendances Python" + +[package_managers."poetry"] +description = "Gestion des dépendances et empaquetage Python" + +[axes."database"] +label = "Base de données" +description = "Choix de la base de données et de l'ORM" + +[axes."database".options."PostgreSQL"] +summary = "PostgreSQL avec SQLAlchemy asynchrone (asyncpg)" +guide = "Moteur SQLAlchemy asynchrone avec une session par requête (`SessionDep`) pour PostgreSQL via asyncpg. Définissez `DATABASE_URL` dans `.env` ; `GET /ready` vérifie la connexion." + +[axes."database".options."MySQL"] +summary = "MySQL avec SQLAlchemy asynchrone (aiomysql)" +guide = "Moteur SQLAlchemy asynchrone avec une session par requête (`SessionDep`) pour MySQL via aiomysql. Définissez `DATABASE_URL` dans `.env` ; `GET /ready` vérifie la connexion." + +[axes."database".options."MongoDB"] +summary = "MongoDB avec le client asynchrone de PyMongo" +guide = "Client asynchrone de PyMongo, ouvert et fermé avec l'application. Définissez `MONGODB_URL` dans `.env` ; `GET /ready` envoie un ping au serveur." + +[axes."database".options."Redis"] +summary = "Redis comme magasin clé-valeur (client asyncio de redis-py)" +guide = "Client asyncio de redis-py (`redis_client`), fermé avec l'application. Définissez `REDIS_URL` dans `.env`." + +[axes."database".options."SQLite"] +summary = "Fichier SQLite avec SQLAlchemy asynchrone (aiosqlite), sans serveur" +guide = "Moteur SQLAlchemy asynchrone avec une session par requête (`SessionDep`) pour un fichier SQLite via aiosqlite ; aucun serveur n'est nécessaire. `DATABASE_URL` dans `.env` indique le fichier." + +[axes."database".options."None"] +label = "Aucune" +summary = "Pas de base de données" + +[axes."authentication"] +label = "Authentification" +description = "Authentification et autorisation des utilisateurs" + +[axes."authentication".options."JWT"] +summary = "Flux par mot de passe OAuth2 avec JWT (recommandé pour les API)" +guide = "Flux par mot de passe OAuth2 : `POST /api/v1/auth/token` renvoie un JWT signé avec `SECRET_KEY`, et la dépendance `CurrentUser` protège vos endpoints." + +[axes."authentication".options."OAuth2"] +summary = "OAuth2 avec authlib" +guide = "Connexion avec Google ou GitHub via Authlib. Définissez les identifiants `GOOGLE_*` ou `GITHUB_*` dans `.env` pour activer un fournisseur." + +[axes."authentication".options."FastAPI-Users"] +summary = "Gestion complète des utilisateurs (JWT ; bases de données SQL uniquement)" +guide = "Inscription, connexion et gestion des utilisateurs avec FastAPI-Users, stockées dans la base de données SQL." + +[axes."authentication".options."Session-based"] +summary = "Authentification traditionnelle par session" +guide = "La connexion définit un cookie de session signé ; la déconnexion met fin à toutes les sessions du compte." + +[axes."authentication".options."None"] +label = "Aucune" +summary = "Pas d'authentification" + +[axes."async_tasks"] +label = "Tâches en arrière-plan" +description = "Traitement des tâches en arrière-plan" + +[axes."async_tasks".options."Celery"] +guide = "Un worker Celery et des endpoints `/api/v1/tasks` qui mettent des tâches en file d'attente dans Redis ; lancez le worker à côté de l'API." + +[axes."async_tasks".options."Dramatiq"] +guide = "Un worker Dramatiq et des endpoints `/api/v1/tasks` qui mettent des tâches en file d'attente dans Redis ; lancez le worker à côté de l'API." + +[axes."async_tasks".options."None"] +label = "Aucune" + +[axes."testing"] +label = "Tests" +description = "Framework et outils de test" + +[axes."testing".options."Basic"] +summary = "pytest + httpx pour tester l'API" +guide = "pytest avec un module de tests par fonctionnalité (SQLite en mémoire pour les bases de données SQL)." + +[axes."testing".options."Coverage"] +summary = "Le socle de base + la couverture de code" +guide = "pytest avec un module de tests par fonctionnalité (SQLite en mémoire pour les bases de données SQL) ; `pytest --cov` affiche la couverture." + +[axes."testing".options."Advanced"] +summary = "Couverture + faker + factory-boy pour les fixtures" +guide = "pytest avec un module de tests par fonctionnalité (SQLite en mémoire pour les bases de données SQL) ; `pytest --cov` affiche la couverture, et `tests/factories.py` contient les fabriques faker et factory-boy." + +[axes."testing".options."None"] +label = "Aucun" +summary = "Pas de framework de test" + +[axes."caching"] +label = "Cache" +description = "Cache des réponses et des données" + +[axes."caching".options."Redis"] +guide = "Mise en cache des réponses avec fastapi-cache2 sur Redis ; le routeur sous `/api/v1/cache` montre le décorateur." + +[axes."caching".options."None"] +label = "Aucun" + +[axes."monitoring"] +label = "Supervision" +description = "Supervision et journalisation de l'application" + +[axes."monitoring".options."Loguru"] +summary = "Journalisation enrichie avec Loguru" +guide = "Loguru prend en charge la sortie de logs de l'application et d'Uvicorn." + +[axes."monitoring".options."OpenTelemetry"] +summary = "Traçage distribué et métriques" +guide = "Trace chaque requête et exporte les spans via OTLP ; définissez les paramètres de l'exportateur dans `.env`." + +[axes."monitoring".options."Prometheus"] +summary = "Instrumentation de métriques Prometheus" +guide = "Expose les métriques des requêtes sur `/metrics`." + +[axes."monitoring".options."None"] +label = "Aucune" +summary = "Pas de supervision supplémentaire" + +[axes."utilities"] +label = "Utilitaires" +description = "Utilitaires et middlewares supplémentaires" + +[axes."utilities".options."Rate-Limiting"] +summary = "Limites de requêtes de l'API par client (limits)" +guide = "Des limites par client sur chaque route (`RATE_LIMIT_DEFAULT`), plus strictes sur les endpoints de connexion lorsque l'authentification est sélectionnée (`RATE_LIMIT_AUTH`) ; un client qui dépasse sa limite reçoit un 429." + +[axes."utilities".options."WebSocket"] +summary = "Exemple d'endpoint WebSocket (websockets)" +guide = "Un endpoint WebSocket sur `/ws` et `GET /api/v1/connections`." + +[axes."utilities".options."None"] +label = "Aucun" + +[axes."migrations"] +label = "Migrations" +description = "Migrations du schéma de la base de données" + +[axes."migrations".options."Alembic"] +summary = "alembic.ini + alembic/env.py asynchrone + scripts/migrate.sh" +guide = "Migrations Alembic dans `alembic/` : `alembic upgrade head` crée les tables, `alembic revision --autogenerate -m \"add orders\"` enregistre une modification des modèles." + +[axes."migrations".options."None"] +label = "Aucune" +summary = "Pas d'outil de migration" + +[axes."tooling"] +label = "Outils de développement" +description = "Outils de développement et configuration de la CI" + +[axes."tooling".options."ruff"] +summary = "Configuration ruff + ruff-format dans pyproject.toml (remplace black/isort)" +guide = "ruff analyse et formate le code : `ruff check .` et `ruff format .`." + +[axes."tooling".options."pre-commit"] +summary = ".pre-commit-config.yaml" +guide = "Exécute les vérifications avant chaque commit, une fois que vous avez lancé `pre-commit install`." + +[axes."tooling".options."github-actions"] +summary = ".github/workflows/test.yml (Python 3.12)" +guide = "Exécute les tests à chaque push sur `main` et à chaque pull request." + +[axes."tooling".options."devcontainer"] +summary = ".devcontainer/devcontainer.json" +guide = "Ouvre le projet dans un conteneur de développement avec la bonne version de Python." + +[axes."tooling".options."makefile"] +summary = "Makefile avec install/test/lint/format/run" +guide = "Raccourcis : `make install`, `make test`, `make lint`, `make format`, `make run`." + +[axes."tooling".options."None"] +label = "Aucun" + +[axes."logging"] +label = "Journalisation" +description = "Format des journaux de l'application" + +[axes."logging".options."structured"] +summary = "Logs JSON + middleware de corrélation X-Request-ID (bibliothèque standard uniquement)" +guide = "Des lignes de log JSON avec un `X-Request-ID` par requête (repris de la requête ou généré)." + +[axes."logging".options."None"] +label = "Aucune" +summary = "Journalisation en texte brut par défaut d'Uvicorn" + +[axes."deployment"] +label = "Déploiement" +description = "Fichiers de déploiement par conteneur" + +[axes."deployment".options."Docker"] +summary = "Génère un Dockerfile" +guide = "Construit l'image de l'application (`docker build -t .`) ; le conteneur lit sa configuration dans l'environnement, jamais dans un `.env` copié." + +[axes."deployment".options."docker-compose"] +summary = "Génère docker-compose.yml (inclut Docker)" +guide = "`docker compose up --build` démarre l'application avec ses services." + +[axes."deployment".options."None"] +label = "Aucun" +summary = "Pas de configuration de déploiement" + +[rules."fastapi-users-needs-sql"] +message = "L'authentification 'FastAPI-Users' nécessite une base de données SQL ({allowed}), mais vous avez sélectionné {selected}. Choisissez l'une de ces bases de données, ou l'option 'JWT', qui fonctionne avec toutes les bases." + +[rules."shared-redis"] +message = "Info : Redis sera utilisé à la fois pour le cache et pour la file de tâches (dépendance partagée)." + +[concepts."first-steps"] +title = "Premiers pas" + +[concepts."path-parameters"] +title = "Paramètres de chemin" + +[concepts."query-parameters"] +title = "Paramètres de requête" + +[concepts."request-body"] +title = "Corps de la requête" + +[concepts."response-model"] +title = "Modèle de réponse" + +[concepts."status-codes"] +title = "Codes d'état de la réponse" + +[concepts."handling-errors"] +title = "Gestion des erreurs" + +[concepts."dependencies"] +title = "Dépendances" + +[concepts."dependencies-with-yield"] +title = "Dépendances avec yield" + +[concepts."bigger-applications"] +title = "Applications plus grandes sur plusieurs fichiers" + +[concepts."settings"] +title = "Paramètres et variables d'environnement" + +[concepts."lifespan"] +title = "Événements lifespan" + +[concepts."sql-databases"] +title = "Bases de données SQL" + +[concepts."security-jwt"] +title = "OAuth2 avec mot de passe et jetons JWT" + +[concepts."cors"] +title = "CORS" + +[concepts."middleware"] +title = "Middleware" + +[concepts."testing"] +title = "Tests" + +[concepts."background-tasks"] +title = "Tâches en arrière-plan" + +[concepts."websockets"] +title = "WebSockets" + +[concepts."deployment-docker"] +title = "FastAPI dans des conteneurs (Docker)" + +[concepts."async"] +title = "Concurrence et async / await" + +[guide] +next_steps = "Étapes suivantes" +open = "Placez-vous dans le dossier du projet." +install = "Créez l'environnement virtuel et installez les dépendances." +install_pip = "Créez un environnement virtuel, activez-le et installez les dépendances." +install_into_venv = "Installez les dépendances dans l'environnement virtuel créé par fastkit." +activate = "Activez l'environnement virtuel." +env = "Créez votre fichier de configuration local à partir de l'exemple et gardez-le hors du contrôle de version." +env_written = "Relisez .env : fastkit l'a créé à partir de .env.example avec une SECRET_KEY unique." +env_kept = "Votre .env existant a été conservé ; comparez-le avec .env.example pour repérer les nouveaux paramètres." +services = "Démarrez {services} et faites pointer les URL de .env vers ce service." +migrate = "Créez les tables de la base de données." +worker = "Démarrez le worker en arrière-plan dans un second terminal." +run = "Démarrez le serveur de développement et ouvrez http://127.0.0.1:8000/docs." +run_readme_alternative = "Avec fastkit installé, `fastkit runserver` fait la même chose." +run_compose = "Vous pouvez aussi l'exécuter dans des conteneurs avec Docker Compose : `docker compose up --build`." +test = "Lancez les tests." +extend_classic = "Ajoutez une ressource avec sa route, ses schémas, sa couche de données et ses tests." +extend_domain = "Ajoutez un domaine avec son routeur, ses schémas, son service, son dépôt et ses tests." +needs_fastkit = "La commande nécessite que fastkit soit installé." +next_level = "Quand vous voulez plus de structure, créez un projet au niveau suivant." +items_sql = "L'API d'exemple `/items` stocke ses articles dans cette base de données." +items_memory = "L'API d'exemple `/items` garde ses articles en mémoire : fastkit ne les stocke dans la base de données qu'avec PostgreSQL, MySQL et SQLite." +items_file = "L'API d'exemple `/items` garde ses articles dans le fichier JSON `src/mocks/mock_items.json`, et non dans cette base de données." +tables_alembic = "`alembic upgrade head` crée les tables." +tables_startup = "Les tables sont créées au démarrage de l'application (aucune migration n'est sélectionnée)." +compose_urls = "Dans les conteneurs, les URL de ces services proviennent de `docker-compose.yml` ; les URL de `.env` servent à exécuter l'application sur votre machine." +compose_migrate = "Un service `migrate` à exécution unique applique les migrations Alembic avant le démarrage de l'application." +compose_sqlite = "Le fichier de la base de données SQLite est conservé dans le volume `sqlite_data`." +read_single_file_split = "Lisez `src/main.py` pour l'application et ses routes, puis `src/core/config.py` pour la configuration." +read_layered_sql_items = "Lisez `src/main.py`, puis `src/api/routes/items.py`, `src/crud/items.py`, `src/models/items.py` et `src/schemas/items.py`." +single_file_split = "Vos choix ajoutent des modules qui lisent la configuration ; elle est donc passée de `src/main.py` à `src/core/config.py`. `src/main.py` garde l'application et ses routes, et inclut les fonctionnalités." +files = "Fichiers" +settings = "Paramètres" +learn_more = "En savoir plus" +selected_features = "Fonctionnalités sélectionnées" +same_in_readme = "README.md liste les étapes pour une copie toute neuve du projet." diff --git a/src/fastapi_fastkit/catalog/i18n/ja.toml b/src/fastapi_fastkit/catalog/i18n/ja.toml new file mode 100644 index 00000000..f1512a15 --- /dev/null +++ b/src/fastapi_fastkit/catalog/i18n/ja.toml @@ -0,0 +1,387 @@ +[levels."hello"] +label = "Hello" +description = "main.py 1 ファイルに、エンドポイント 3 つ、メモリ上のデータ、テストが入っています。" +read_first = "`main.py` を上から下まで読んでみましょう。各コメントに、その部分を説明する FastAPI チュートリアルのページへのリンクがあります。" +extend = "既存のコードをまねてリソースを追加します。`Item` モデル、`create_item`、`read_item` とそのテストをコピーし、`/users` 用に名前を変えてください。" + +[levels."single-file"] +label = "単一ファイル" +description = "設定とテストを含むアプリ全体が 1 つのモジュールに入っています。" +read_first = "`src/main.py` を読みましょう。設定、アプリ、ルートが 1 つのモジュールにまとまっています。" + +[levels."layered"] +label = "レイヤー型" +description = "ルート、CRUD、スキーマ、コア設定がレイヤーごとに分かれています。" +read_first = "`src/main.py` を読み、続いて `src/api/routes/items.py`、`src/crud/items.py`、`src/schemas/items.py` を読みましょう。" + +[levels."domain"] +label = "ドメイン型" +description = "ドメインごとに、ルーター、サービス、リポジトリを持つパッケージが 1 つあります。" +read_first = "`src/app/main.py` を読み、続いて `src/app/domains/items/` の `router.py`、`service.py`、`repository.py` を読みましょう。" + +[levels."production"] +label = "プロダクション" +description = "ドメイン型に PostgreSQL、Alembic、JWT、CI、Docker を加えた構成です。" +read_first = "`src/app/main.py` を読み、続いて `src/app/domains/items/` を読みましょう。README.md には、選択した機能が 1 つずつ説明されています。" + +[presets."single-module"] +summary = "すべてを 1 つのモジュールにまとめた構成で、小さなスクリプトやプロトタイプに向いています。" + +[presets."classic-layered"] +summary = "api/routes、crud、schemas、core に分けたレイヤー構成です(fastapi-default と同じ方式)。" + +[presets."domain-starter"] +summary = "ドメイン中心の構成で、src/app/domains// の下に router/service/repository を置きます(推奨)。" + +[templates."fastapi-hello"] +description = "最小の FastAPI アプリです。エンドポイント 3 つ、モデル 1 つ、そのテストが入っています。" +read_first = "`main.py` を上から下まで読んでみましょう。各コメントに、その部分を説明する FastAPI チュートリアルのページへのリンクがあります。" +extend = "既存のコードをまねてリソースを追加します。`Item` モデル、`create_item`、`read_item` とそのテストをコピーし、`/users` 用に名前を変えてください。" + +[templates."fastapi-single-module"] +description = "FastAPI 単一モジュールのテンプレートです。" +read_first = "`src/main.py` を読みましょう。設定、アプリ、ルートが 1 つのモジュールにまとまっています。" + +[templates."fastapi-default"] +description = "シンプルな FastAPI プロジェクトです。" +read_first = "`src/main.py` を読み、続いて `src/api/routes/items.py`、`src/crud/items.py`、`src/schemas/items.py` を読みましょう。" + +[templates."fastapi-domain-starter"] +description = "FastAPI ドメインスターターです。" +read_first = "`src/app/main.py` を読み、続いて `src/app/domains/items/` の `router.py`、`service.py`、`repository.py` を読みましょう。" + +[templates."fastapi-custom-response"] +description = "カスタムレスポンスの仕組みを備えた、非同期のアイテム管理 API です。" +read_first = "`src/main.py` を読み、続いて `src/helper/responses.py` と `src/api/routes/items.py` を読むと、レスポンスのエンベロープの構造が分かります。" + +[templates."fastapi-auth-jwt"] +description = "JWT 認証を備えた FastAPI プロジェクトです。" +read_first = "`src/app/main.py` を読み、続いて `src/app/domains/auth/` と `src/app/core/security.py` を読みましょう。" + +[templates."fastapi-sqlmodel"] +description = "SQLModel を使う FastAPI プロジェクトです。" +read_first = "`src/app/main.py` を読み、続いて `src/app/domains/items/` と `src/app/db/session.py` を読みましょう。PostgreSQL や MySQL への切り替え方は README に書かれています。" + +[templates."fastapi-mcp"] +description = "MCP を使う FastAPI プロジェクトです。" +read_first = "`src/main.py` を読み、続いて `src/mcp_server/router.py` と `src/auth/` を読みましょう。" + +[templates."fastapi-llm-agent"] +description = "LLM エージェントを使う FastAPI プロジェクトです。" +read_first = "`src/app/main.py` を読み、続いて `src/app/api/chat.py` と `src/app/llm/agent.py` を読みましょう。" + +[package_managers."pip"] +description = "Python 標準のパッケージマネージャーです。" + +[package_managers."uv"] +description = "高速な Python パッケージマネージャーです。" + +[package_managers."pdm"] +description = "モダンな Python の依存関係管理ツールです。" + +[package_managers."poetry"] +description = "Python の依存関係管理とパッケージ化を行うツールです。" + +[axes."database"] +label = "データベース" +description = "データベースと ORM を選びます。" + +[axes."database".options."PostgreSQL"] +summary = "asyncpg を使う非同期 SQLAlchemy で PostgreSQL に接続します。" +guide = "asyncpg 経由で PostgreSQL に接続する非同期 SQLAlchemy エンジンと、リクエストごとのセッション(`SessionDep`)を用意します。`.env` に `DATABASE_URL` を設定してください。`GET /ready` で接続を確認できます。" + +[axes."database".options."MySQL"] +summary = "aiomysql を使う非同期 SQLAlchemy で MySQL に接続します。" +guide = "aiomysql 経由で MySQL に接続する非同期 SQLAlchemy エンジンと、リクエストごとのセッション(`SessionDep`)を用意します。`.env` に `DATABASE_URL` を設定してください。`GET /ready` で接続を確認できます。" + +[axes."database".options."MongoDB"] +summary = "PyMongo の非同期クライアントで MongoDB に接続します。" +guide = "アプリの起動時に開き、終了時に閉じる PyMongo の非同期クライアントを用意します。`.env` に `MONGODB_URL` を設定してください。`GET /ready` でサーバーに ping を送ります。" + +[axes."database".options."Redis"] +summary = "Redis をキーバリューストアとして使います(redis-py の asyncio クライアント)。" +guide = "アプリの終了時に閉じる redis-py の asyncio クライアント(`redis_client`)を用意します。`.env` に `REDIS_URL` を設定してください。" + +[axes."database".options."SQLite"] +summary = "aiosqlite を使う非同期 SQLAlchemy で SQLite ファイルに接続します。サーバーは不要です。" +guide = "aiosqlite 経由で SQLite ファイルに接続する非同期 SQLAlchemy エンジンと、リクエストごとのセッション(`SessionDep`)を用意します。サーバーは不要です。`.env` の `DATABASE_URL` でファイルを指定します。" + +[axes."database".options."None"] +label = "なし" +summary = "データベースを使いません。" + +[axes."authentication"] +label = "認証" +description = "ユーザー認証と認可を選びます。" + +[axes."authentication".options."JWT"] +summary = "JWT を使う OAuth2 パスワードフローです(API に推奨)。" +guide = "OAuth2 パスワードフローを用意します。`POST /api/v1/auth/token` は `SECRET_KEY` で署名した JWT を返し、`CurrentUser` 依存関係がエンドポイントを保護します。" + +[axes."authentication".options."OAuth2"] +summary = "authlib を使う OAuth2 です。" +guide = "Authlib を使って Google や GitHub でのログインを提供します。`.env` に `GOOGLE_*` または `GITHUB_*` の認証情報を設定すると、そのプロバイダーが有効になります。" + +[axes."authentication".options."FastAPI-Users"] +summary = "ユーザー管理機能一式です(JWT、SQL データベース専用)。" +guide = "FastAPI-Users による会員登録、ログイン、ユーザー管理を提供します。ユーザー情報は SQL データベースに保存されます。" + +[axes."authentication".options."Session-based"] +summary = "従来型のセッションベース認証です。" +guide = "ログインすると署名付きのセッション Cookie が設定され、ログアウトするとそのアカウントのすべてのセッションが終了します。" + +[axes."authentication".options."None"] +label = "なし" +summary = "認証を使いません。" + +[axes."async_tasks"] +label = "バックグラウンドタスク" +description = "バックグラウンドタスクの処理方式を選びます。" + +[axes."async_tasks".options."Celery"] +guide = "Celery ワーカーと、Redis にジョブを登録する `/api/v1/tasks` エンドポイントを用意します。ワーカーは API とは別に起動してください。" + +[axes."async_tasks".options."Dramatiq"] +guide = "Dramatiq ワーカーと、Redis にジョブを登録する `/api/v1/tasks` エンドポイントを用意します。ワーカーは API とは別に起動してください。" + +[axes."async_tasks".options."None"] +label = "なし" + +[axes."testing"] +label = "テスト" +description = "テストフレームワークとツールを選びます。" + +[axes."testing".options."Basic"] +summary = "API テスト用の pytest と httpx です。" +guide = "機能ごとにテストモジュールを置く pytest の構成です(SQL データベースではメモリ上の SQLite を使います)。" + +[axes."testing".options."Coverage"] +summary = "基本構成にコードカバレッジを加えます。" +guide = "機能ごとにテストモジュールを置く pytest の構成です(SQL データベースではメモリ上の SQLite を使います)。`pytest --cov` でカバレッジを確認できます。" + +[axes."testing".options."Advanced"] +summary = "カバレッジに、フィクスチャ用の faker と factory-boy を加えます。" +guide = "機能ごとにテストモジュールを置く pytest の構成です(SQL データベースではメモリ上の SQLite を使います)。`pytest --cov` でカバレッジを確認でき、`tests/factories.py` に faker と factory-boy のファクトリーがあります。" + +[axes."testing".options."None"] +label = "なし" +summary = "テストフレームワークを使いません。" + +[axes."caching"] +label = "キャッシュ" +description = "レスポンスとデータのキャッシュを選びます。" + +[axes."caching".options."Redis"] +guide = "Redis 上の fastapi-cache2 でレスポンスをキャッシュします。`/api/v1/cache` 以下のルーターにデコレーターの使い方の例があります。" + +[axes."caching".options."None"] +label = "なし" + +[axes."monitoring"] +label = "モニタリング" +description = "アプリケーションの監視とログを選びます。" + +[axes."monitoring".options."Loguru"] +summary = "Loguru でログを強化します。" +guide = "Loguru がアプリケーションと Uvicorn のログ出力を引き受けます。" + +[axes."monitoring".options."OpenTelemetry"] +summary = "分散トレーシングとメトリクスを提供します。" +guide = "すべてのリクエストをトレースし、生成したスパンを OTLP で送信します。送信の設定は `.env` で指定してください。" + +[axes."monitoring".options."Prometheus"] +summary = "Prometheus のメトリクス計測を提供します。" +guide = "リクエストのメトリクスを `/metrics` で公開します。" + +[axes."monitoring".options."None"] +label = "なし" +summary = "追加のモニタリングを使いません。" + +[axes."utilities"] +label = "ユーティリティ" +description = "追加のユーティリティとミドルウェアを選びます。" + +[axes."utilities".options."Rate-Limiting"] +summary = "クライアントごとに API のリクエスト数を制限します(limits)。" +guide = "すべてのルートにクライアントごとの制限(`RATE_LIMIT_DEFAULT`)を適用します。認証を選んだ場合、ログイン用エンドポイントにはより厳しい制限(`RATE_LIMIT_AUTH`)を適用します。制限を超えたクライアントには 429 が返ります。" + +[axes."utilities".options."WebSocket"] +summary = "WebSocket エンドポイントの例です(websockets)。" +guide = "`/ws` の WebSocket エンドポイントと `GET /api/v1/connections` を用意します。" + +[axes."utilities".options."None"] +label = "なし" + +[axes."migrations"] +label = "マイグレーション" +description = "データベーススキーマのマイグレーションを選びます。" + +[axes."migrations".options."Alembic"] +summary = "alembic.ini、非同期の alembic/env.py、scripts/migrate.sh を作ります。" +guide = "`alembic/` に Alembic のマイグレーションを用意します。`alembic upgrade head` でテーブルを作成し、`alembic revision --autogenerate -m \"add orders\"` でモデルの変更を記録します。" + +[axes."migrations".options."None"] +label = "なし" +summary = "マイグレーションツールを使いません。" + +[axes."tooling"] +label = "開発ツール" +description = "開発ツールと CI の設定を選びます。" + +[axes."tooling".options."ruff"] +summary = "pyproject.toml に ruff と ruff-format の設定を追加します(black と isort の代わり)。" +guide = "ruff がコードのチェックと整形を行います。`ruff check .` と `ruff format .` を使ってください。" + +[axes."tooling".options."pre-commit"] +summary = ".pre-commit-config.yaml を作ります。" +guide = "`pre-commit install` を実行すると、コミットのたびに先にチェックを実行します。" + +[axes."tooling".options."github-actions"] +summary = ".github/workflows/test.yml を作ります(Python 3.12)。" +guide = "`main` へのプッシュと、すべてのプルリクエストでテストを実行します。" + +[axes."tooling".options."devcontainer"] +summary = ".devcontainer/devcontainer.json を作ります。" +guide = "適切な Python が入った開発コンテナでプロジェクトを開きます。" + +[axes."tooling".options."makefile"] +summary = "install/test/lint/format/run を備えた Makefile を作ります。" +guide = "ショートカットとして `make install`、`make test`、`make lint`、`make format`、`make run` を用意します。" + +[axes."tooling".options."None"] +label = "なし" + +[axes."logging"] +label = "ログ" +description = "アプリケーションのログ形式を選びます。" + +[axes."logging".options."structured"] +summary = "JSON ログと X-Request-ID の相関ミドルウェアを提供します(標準ライブラリのみ)。" +guide = "リクエストごとに `X-Request-ID`(リクエストから取得、なければ生成)を付けた JSON のログ行を出力します。" + +[axes."logging".options."None"] +label = "なし" +summary = "Uvicorn 標準のプレーンテキストのログを使います。" + +[axes."deployment"] +label = "デプロイ" +description = "コンテナ用のデプロイファイルを選びます。" + +[axes."deployment".options."Docker"] +summary = "Dockerfile を作ります。" +guide = "アプリのイメージをビルドします(`docker build -t .`)。コンテナは、コピーされた `.env` ではなく環境変数から設定を読み込みます。" + +[axes."deployment".options."docker-compose"] +summary = "docker-compose.yml を作ります(Docker を含む)。" +guide = "`docker compose up --build` でアプリと必要なサービスを一緒に起動します。" + +[axes."deployment".options."None"] +label = "なし" +summary = "デプロイ設定を作りません。" + +[rules."fastapi-users-needs-sql"] +message = "認証 'FastAPI-Users' には SQL データベース({allowed})が必要ですが、{selected} が選択されています。それらのデータベースのいずれかを選ぶか、すべてのデータベースで動作する 'JWT' オプションを選んでください。" + +[rules."shared-redis"] +message = "情報: キャッシュとタスクキューの両方で Redis を使います(共有の依存関係)。" + +[concepts."first-steps"] +title = "最初の一歩" + +[concepts."path-parameters"] +title = "パスパラメータ" + +[concepts."query-parameters"] +title = "クエリパラメータ" + +[concepts."request-body"] +title = "リクエストボディ" + +[concepts."response-model"] +title = "レスポンスモデル" + +[concepts."status-codes"] +title = "レスポンスのステータスコード" + +[concepts."handling-errors"] +title = "エラー処理" + +[concepts."dependencies"] +title = "依存関係" + +[concepts."dependencies-with-yield"] +title = "yield を使う依存関係" + +[concepts."bigger-applications"] +title = "複数ファイルで作る大きなアプリケーション" + +[concepts."settings"] +title = "設定と環境変数" + +[concepts."lifespan"] +title = "Lifespan イベント" + +[concepts."sql-databases"] +title = "SQL データベース" + +[concepts."security-jwt"] +title = "パスワードと JWT トークンを使う OAuth2" + +[concepts."cors"] +title = "CORS" + +[concepts."middleware"] +title = "ミドルウェア" + +[concepts."testing"] +title = "テスト" + +[concepts."background-tasks"] +title = "バックグラウンドタスク" + +[concepts."websockets"] +title = "WebSocket" + +[concepts."deployment-docker"] +title = "コンテナでの FastAPI(Docker)" + +[concepts."async"] +title = "並行処理と async / await" + +[guide] +next_steps = "次のステップ" +open = "プロジェクトのフォルダーに移動します。" +install = "仮想環境を作成し、依存関係をインストールします。" +install_pip = "仮想環境を作成して有効化し、依存関係をインストールします。" +install_into_venv = "fastkit が作成した仮想環境に依存関係をインストールします。" +activate = "仮想環境を有効化します。" +env = "サンプルファイルからローカル用の設定ファイルを作成し、バージョン管理の対象から外します。" +env_written = ".env を確認してください。fastkit が .env.example をもとに、固有の SECRET_KEY を入れて作成しました。" +env_kept = "既存の .env はそのまま残しました。新しい設定がないか、.env.example と見比べてください。" +services = "{services} を起動し、.env の URL 設定がそれを指すようにします。" +migrate = "データベースのテーブルを作成します。" +worker = "2 つ目のターミナルでバックグラウンドワーカーを起動します。" +run = "開発サーバーを起動し、http://127.0.0.1:8000/docs を開きます。" +run_readme_alternative = "fastkit がインストールされていれば、`fastkit runserver` でも同じことができます。" +run_compose = "Docker Compose を使ってコンテナで実行することもできます。`docker compose up --build` を実行してください。" +test = "テストを実行します。" +extend_classic = "ルート、スキーマ、データ層、テストを備えたリソースを追加します。" +extend_domain = "ルーター、スキーマ、サービス、リポジトリ、テストを備えたドメインを追加します。" +needs_fastkit = "このコマンドには fastkit のインストールが必要です。" +next_level = "もっと構造を整えたくなったら、次のレベルでプロジェクトを作成します。" +items_sql = "サンプルの `/items` API は、このデータベースにアイテムを保存します。" +items_memory = "サンプルの `/items` API はアイテムをメモリ上に保持します。fastkit がアイテムをデータベースに保存するのは、PostgreSQL、MySQL、SQLite の場合だけです。" +items_file = "サンプルの `/items` API は、アイテムをこのデータベースではなく JSON ファイル `src/mocks/mock_items.json` に保持します。" +tables_alembic = "`alembic upgrade head` でテーブルを作成します。" +tables_startup = "テーブルはアプリの起動時に作成されます(マイグレーションを選択していないためです)。" +compose_urls = "コンテナ内では、これらのサービスの URL は `docker-compose.yml` から取得されます。`.env` の URL は、自分のマシンでアプリを実行するときに使います。" +compose_migrate = "アプリの起動前に、1 回限りの `migrate` サービスが Alembic のマイグレーションを適用します。" +compose_sqlite = "SQLite のデータベースファイルは `sqlite_data` ボリュームに保存されます。" +read_single_file_split = "アプリとルートは `src/main.py`、設定は `src/core/config.py` で確認しましょう。" +read_layered_sql_items = "`src/main.py` を読み、続いて `src/api/routes/items.py`、`src/crud/items.py`、`src/models/items.py`、`src/schemas/items.py` を読みましょう。" +single_file_split = "選択した機能が設定を読み込むモジュールを追加するため、設定を `src/main.py` から `src/core/config.py` に移しました。`src/main.py` にはアプリとルートが残り、機能もここで組み込みます。" +files = "ファイル" +settings = "設定" +learn_more = "詳しく見る" +selected_features = "選択した機能" +same_in_readme = "README.md には、プロジェクトを新しく取得した状態での手順が書かれています。" diff --git a/src/fastapi_fastkit/catalog/i18n/ko.toml b/src/fastapi_fastkit/catalog/i18n/ko.toml new file mode 100644 index 00000000..d46ef15b --- /dev/null +++ b/src/fastapi_fastkit/catalog/i18n/ko.toml @@ -0,0 +1,387 @@ +[levels."hello"] +label = "Hello" +description = "main.py 하나에 엔드포인트 3개, 메모리 데이터, 테스트가 들어 있습니다." +read_first = "`main.py`를 위에서 아래로 읽어 보세요. 각 주석에는 해당 코드를 설명하는 FastAPI 튜토리얼 페이지의 링크가 있습니다." +extend = "기존 코드를 본떠서 리소스를 추가하세요. `Item` 모델, `create_item`, `read_item`과 이들의 테스트를 복사한 다음 `/users`에 맞게 이름을 바꾸면 됩니다." + +[levels."single-file"] +label = "단일 파일" +description = "설정과 테스트를 포함한 앱 전체가 모듈 하나에 들어 있습니다." +read_first = "`src/main.py`를 읽어 보세요. 설정, 앱, 라우트가 모듈 하나에 모여 있습니다." + +[levels."layered"] +label = "계층형" +description = "라우트, CRUD, 스키마, 코어 설정이 계층별로 나뉘어 있습니다." +read_first = "`src/main.py`를 읽은 다음 `src/api/routes/items.py`, `src/crud/items.py`, `src/schemas/items.py`를 읽어 보세요." + +[levels."domain"] +label = "도메인형" +description = "도메인마다 라우터, 서비스, 리포지토리를 담은 패키지가 하나씩 있습니다." +read_first = "`src/app/main.py`를 읽은 다음 `src/app/domains/items/`의 `router.py`, `service.py`, `repository.py`를 읽어 보세요." + +[levels."production"] +label = "프로덕션" +description = "도메인형에 PostgreSQL, Alembic, JWT, CI, Docker를 더한 구성입니다." +read_first = "`src/app/main.py`를 읽은 다음 `src/app/domains/items/`를 읽어 보세요. README.md에 선택한 기능이 하나씩 설명되어 있습니다." + +[presets."single-module"] +summary = "모든 코드가 모듈 하나에 들어 있어서 작은 스크립트나 프로토타입에 알맞습니다." + +[presets."classic-layered"] +summary = "api/routes, crud, schemas, core로 나눈 계층형 구조입니다(fastapi-default와 같은 방식)." + +[presets."domain-starter"] +summary = "도메인 중심 구조로, src/app/domains// 아래에 router/service/repository를 둡니다(권장)." + +[templates."fastapi-hello"] +description = "가장 작은 FastAPI 앱입니다. 엔드포인트 3개, 모델 1개, 그 테스트가 들어 있습니다." +read_first = "`main.py`를 위에서 아래로 읽어 보세요. 각 주석에는 해당 코드를 설명하는 FastAPI 튜토리얼 페이지의 링크가 있습니다." +extend = "기존 코드를 본떠서 리소스를 추가하세요. `Item` 모델, `create_item`, `read_item`과 이들의 테스트를 복사한 다음 `/users`에 맞게 이름을 바꾸면 됩니다." + +[templates."fastapi-single-module"] +description = "FastAPI 단일 모듈 템플릿입니다." +read_first = "`src/main.py`를 읽어 보세요. 설정, 앱, 라우트가 모듈 하나에 모여 있습니다." + +[templates."fastapi-default"] +description = "간단한 FastAPI 프로젝트입니다." +read_first = "`src/main.py`를 읽은 다음 `src/api/routes/items.py`, `src/crud/items.py`, `src/schemas/items.py`를 읽어 보세요." + +[templates."fastapi-domain-starter"] +description = "FastAPI 도메인 스타터입니다." +read_first = "`src/app/main.py`를 읽은 다음 `src/app/domains/items/`의 `router.py`, `service.py`, `repository.py`를 읽어 보세요." + +[templates."fastapi-custom-response"] +description = "커스텀 응답 시스템을 갖춘 비동기 아이템 관리 API입니다." +read_first = "`src/main.py`를 읽은 다음 `src/helper/responses.py`와 `src/api/routes/items.py`를 읽으면 응답 envelope의 구조를 볼 수 있습니다." + +[templates."fastapi-auth-jwt"] +description = "JWT 인증을 갖춘 FastAPI 프로젝트입니다." +read_first = "`src/app/main.py`를 읽은 다음 `src/app/domains/auth/`와 `src/app/core/security.py`를 읽어 보세요." + +[templates."fastapi-sqlmodel"] +description = "SQLModel을 사용하는 FastAPI 프로젝트입니다." +read_first = "`src/app/main.py`를 읽은 다음 `src/app/domains/items/`와 `src/app/db/session.py`를 읽어 보세요. PostgreSQL이나 MySQL로 바꾸는 방법은 README에 설명되어 있습니다." + +[templates."fastapi-mcp"] +description = "MCP를 사용하는 FastAPI 프로젝트입니다." +read_first = "`src/main.py`를 읽은 다음 `src/mcp_server/router.py`와 `src/auth/`를 읽어 보세요." + +[templates."fastapi-llm-agent"] +description = "LLM 에이전트를 사용하는 FastAPI 프로젝트입니다." +read_first = "`src/app/main.py`를 읽은 다음 `src/app/api/chat.py`와 `src/app/llm/agent.py`를 읽어 보세요." + +[package_managers."pip"] +description = "Python 표준 패키지 관리자입니다." + +[package_managers."uv"] +description = "빠른 Python 패키지 관리자입니다." + +[package_managers."pdm"] +description = "최신 방식의 Python 의존성 관리 도구입니다." + +[package_managers."poetry"] +description = "Python 의존성 관리와 패키징을 함께 지원하는 도구입니다." + +[axes."database"] +label = "데이터베이스" +description = "데이터베이스와 ORM을 선택합니다." + +[axes."database".options."PostgreSQL"] +summary = "asyncpg 기반 비동기 SQLAlchemy로 PostgreSQL을 사용합니다." +guide = "asyncpg를 통해 PostgreSQL에 연결하는 비동기 SQLAlchemy 엔진과, 요청마다 만들어지는 세션(`SessionDep`)을 제공합니다. `.env`에 `DATABASE_URL`을 설정하세요. `GET /ready`가 연결 상태를 확인합니다." + +[axes."database".options."MySQL"] +summary = "aiomysql 기반 비동기 SQLAlchemy로 MySQL을 사용합니다." +guide = "aiomysql을 통해 MySQL에 연결하는 비동기 SQLAlchemy 엔진과, 요청마다 만들어지는 세션(`SessionDep`)을 제공합니다. `.env`에 `DATABASE_URL`을 설정하세요. `GET /ready`가 연결 상태를 확인합니다." + +[axes."database".options."MongoDB"] +summary = "PyMongo의 비동기 클라이언트로 MongoDB를 사용합니다." +guide = "앱이 시작될 때 열리고 종료될 때 닫히는 PyMongo 비동기 클라이언트를 제공합니다. `.env`에 `MONGODB_URL`을 설정하세요. `GET /ready`가 서버에 ping을 보냅니다." + +[axes."database".options."Redis"] +summary = "Redis를 키-값 저장소로 사용합니다(redis-py asyncio 클라이언트)." +guide = "앱이 종료될 때 닫히는 redis-py asyncio 클라이언트(`redis_client`)를 제공합니다. `.env`에 `REDIS_URL`을 설정하세요." + +[axes."database".options."SQLite"] +summary = "aiosqlite 기반 비동기 SQLAlchemy로 SQLite 파일을 사용하며, 서버가 필요 없습니다." +guide = "aiosqlite를 통해 SQLite 파일에 연결하는 비동기 SQLAlchemy 엔진과, 요청마다 만들어지는 세션(`SessionDep`)을 제공합니다. 서버는 필요 없습니다. `.env`의 `DATABASE_URL`에 파일을 지정합니다." + +[axes."database".options."None"] +label = "없음" +summary = "데이터베이스를 사용하지 않습니다." + +[axes."authentication"] +label = "인증" +description = "사용자 인증과 권한 부여를 선택합니다." + +[axes."authentication".options."JWT"] +summary = "JWT를 사용하는 OAuth2 패스워드 플로우입니다(API에 권장)." +guide = "OAuth2 패스워드 플로우를 제공합니다. `POST /api/v1/auth/token`은 `SECRET_KEY`로 서명한 JWT를 반환하고, `CurrentUser` 의존성이 엔드포인트를 보호합니다." + +[axes."authentication".options."OAuth2"] +summary = "authlib를 사용하는 OAuth2입니다." +guide = "Authlib로 Google이나 GitHub 계정 로그인을 제공합니다. `.env`에 `GOOGLE_*` 또는 `GITHUB_*` 인증 정보를 설정하면 해당 제공자가 활성화됩니다." + +[axes."authentication".options."FastAPI-Users"] +summary = "완전한 사용자 관리 기능입니다(JWT, SQL 데이터베이스 전용)." +guide = "FastAPI-Users의 회원 가입, 로그인, 사용자 관리 기능을 제공하며, 사용자 정보는 SQL 데이터베이스에 저장됩니다." + +[axes."authentication".options."Session-based"] +summary = "전통적인 세션 기반 인증입니다." +guide = "로그인하면 서명된 세션 쿠키가 설정되고, 로그아웃하면 해당 계정의 모든 세션이 종료됩니다." + +[axes."authentication".options."None"] +label = "없음" +summary = "인증을 사용하지 않습니다." + +[axes."async_tasks"] +label = "백그라운드 작업" +description = "백그라운드 작업 처리를 선택합니다." + +[axes."async_tasks".options."Celery"] +guide = "Celery 워커와, Redis에 작업을 등록하는 `/api/v1/tasks` 엔드포인트를 제공합니다. 워커는 API와 별도로 실행해야 합니다." + +[axes."async_tasks".options."Dramatiq"] +guide = "Dramatiq 워커와, Redis에 작업을 등록하는 `/api/v1/tasks` 엔드포인트를 제공합니다. 워커는 API와 별도로 실행해야 합니다." + +[axes."async_tasks".options."None"] +label = "없음" + +[axes."testing"] +label = "테스트" +description = "테스트 프레임워크와 도구를 선택합니다." + +[axes."testing".options."Basic"] +summary = "API 테스트를 위한 pytest와 httpx입니다." +guide = "기능마다 테스트 모듈이 하나씩 있는 pytest 설정입니다(SQL 데이터베이스는 메모리 SQLite를 사용합니다)." + +[axes."testing".options."Coverage"] +summary = "기본 구성에 코드 커버리지를 더합니다." +guide = "기능마다 테스트 모듈이 하나씩 있는 pytest 설정입니다(SQL 데이터베이스는 메모리 SQLite를 사용합니다). `pytest --cov`로 커버리지를 확인할 수 있습니다." + +[axes."testing".options."Advanced"] +summary = "커버리지에 픽스처용 faker와 factory-boy를 더합니다." +guide = "기능마다 테스트 모듈이 하나씩 있는 pytest 설정입니다(SQL 데이터베이스는 메모리 SQLite를 사용합니다). `pytest --cov`로 커버리지를 확인할 수 있고, `tests/factories.py`에 faker와 factory-boy 팩토리가 있습니다." + +[axes."testing".options."None"] +label = "없음" +summary = "테스트 프레임워크를 사용하지 않습니다." + +[axes."caching"] +label = "캐싱" +description = "응답과 데이터 캐싱을 선택합니다." + +[axes."caching".options."Redis"] +guide = "Redis에서 동작하는 fastapi-cache2로 응답을 캐싱합니다. `/api/v1/cache` 아래의 라우터에서 데코레이터 사용법을 볼 수 있습니다." + +[axes."caching".options."None"] +label = "없음" + +[axes."monitoring"] +label = "모니터링" +description = "애플리케이션 모니터링과 로깅을 선택합니다." + +[axes."monitoring".options."Loguru"] +summary = "Loguru로 로깅을 강화합니다." +guide = "Loguru가 애플리케이션과 Uvicorn의 로그 출력을 대신 처리합니다." + +[axes."monitoring".options."OpenTelemetry"] +summary = "분산 추적과 메트릭을 제공합니다." +guide = "모든 요청을 추적하고, 생성된 스팬(span)을 OTLP로 내보냅니다. 내보내기 설정은 `.env`에서 지정하세요." + +[axes."monitoring".options."Prometheus"] +summary = "Prometheus 메트릭 계측을 제공합니다." +guide = "요청 메트릭을 `/metrics`에서 제공합니다." + +[axes."monitoring".options."None"] +label = "없음" +summary = "추가 모니터링을 사용하지 않습니다." + +[axes."utilities"] +label = "유틸리티" +description = "추가 유틸리티와 미들웨어를 선택합니다." + +[axes."utilities".options."Rate-Limiting"] +summary = "클라이언트별 API 요청 횟수를 제한합니다(limits)." +guide = "모든 라우트에 클라이언트별 제한(`RATE_LIMIT_DEFAULT`)을 적용하며, 인증을 선택한 경우 로그인 엔드포인트에는 더 엄격한 제한(`RATE_LIMIT_AUTH`)을 적용합니다. 제한을 넘긴 클라이언트는 429 응답을 받습니다." + +[axes."utilities".options."WebSocket"] +summary = "WebSocket 엔드포인트 예제입니다(websockets)." +guide = "`/ws`의 WebSocket 엔드포인트와 `GET /api/v1/connections`를 제공합니다." + +[axes."utilities".options."None"] +label = "없음" + +[axes."migrations"] +label = "마이그레이션" +description = "데이터베이스 스키마 마이그레이션을 선택합니다." + +[axes."migrations".options."Alembic"] +summary = "alembic.ini, 비동기 alembic/env.py, scripts/migrate.sh를 만듭니다." +guide = "`alembic/`에 Alembic 마이그레이션을 구성합니다. `alembic upgrade head`는 테이블을 만들고, `alembic revision --autogenerate -m \"add orders\"`는 모델 변경을 기록합니다." + +[axes."migrations".options."None"] +label = "없음" +summary = "마이그레이션 도구를 사용하지 않습니다." + +[axes."tooling"] +label = "개발자 도구" +description = "개발자 도구와 CI 설정을 선택합니다." + +[axes."tooling".options."ruff"] +summary = "pyproject.toml에 ruff와 ruff-format 설정을 추가합니다(black과 isort를 대체)." +guide = "ruff가 코드를 검사하고 포맷합니다. `ruff check .`와 `ruff format .`를 사용하세요." + +[axes."tooling".options."pre-commit"] +summary = ".pre-commit-config.yaml을 만듭니다." +guide = "`pre-commit install`을 실행하면 커밋할 때마다 검사를 먼저 실행합니다." + +[axes."tooling".options."github-actions"] +summary = ".github/workflows/test.yml을 만듭니다(Python 3.12)." +guide = "`main` 브랜치에 푸시할 때와 풀 리퀘스트가 올라올 때마다 테스트를 실행합니다." + +[axes."tooling".options."devcontainer"] +summary = ".devcontainer/devcontainer.json을 만듭니다." +guide = "알맞은 Python이 설치된 개발 컨테이너에서 프로젝트를 엽니다." + +[axes."tooling".options."makefile"] +summary = "install/test/lint/format/run 명령을 담은 Makefile을 만듭니다." +guide = "단축 명령으로 `make install`, `make test`, `make lint`, `make format`, `make run`을 제공합니다." + +[axes."tooling".options."None"] +label = "없음" + +[axes."logging"] +label = "로깅" +description = "애플리케이션 로그 형식을 선택합니다." + +[axes."logging".options."structured"] +summary = "JSON 로그와 X-Request-ID 상관관계 미들웨어를 제공합니다(표준 라이브러리만 사용)." +guide = "요청마다 `X-Request-ID`(요청에서 가져오거나 새로 생성)를 담은 JSON 로그를 한 줄씩 출력합니다." + +[axes."logging".options."None"] +label = "없음" +summary = "Uvicorn의 기본 일반 텍스트 로그를 사용합니다." + +[axes."deployment"] +label = "배포" +description = "컨테이너 배포 파일을 선택합니다." + +[axes."deployment".options."Docker"] +summary = "Dockerfile을 만듭니다." +guide = "앱 이미지를 빌드합니다(`docker build -t .`). 컨테이너는 복사된 `.env`가 아니라 환경 변수에서 설정을 읽습니다." + +[axes."deployment".options."docker-compose"] +summary = "docker-compose.yml을 만듭니다(Docker 포함)." +guide = "`docker compose up --build`로 앱과 필요한 서비스를 함께 시작합니다." + +[axes."deployment".options."None"] +label = "없음" +summary = "배포 설정을 만들지 않습니다." + +[rules."fastapi-users-needs-sql"] +message = "인증 'FastAPI-Users'에는 SQL 데이터베이스({allowed})가 필요하지만 {selected}이(가) 선택되었습니다. 해당 데이터베이스 중 하나를 선택하거나, 모든 데이터베이스에서 동작하는 'JWT' 옵션을 선택하세요." + +[rules."shared-redis"] +message = "안내: 캐싱과 작업 큐에서 Redis를 함께 사용합니다(공유 의존성)." + +[concepts."first-steps"] +title = "첫걸음" + +[concepts."path-parameters"] +title = "경로 매개변수" + +[concepts."query-parameters"] +title = "쿼리 매개변수" + +[concepts."request-body"] +title = "요청 본문" + +[concepts."response-model"] +title = "응답 모델" + +[concepts."status-codes"] +title = "응답 상태 코드" + +[concepts."handling-errors"] +title = "오류 처리" + +[concepts."dependencies"] +title = "의존성" + +[concepts."dependencies-with-yield"] +title = "yield를 사용하는 의존성" + +[concepts."bigger-applications"] +title = "여러 파일로 구성하는 대규모 애플리케이션" + +[concepts."settings"] +title = "설정과 환경 변수" + +[concepts."lifespan"] +title = "Lifespan 이벤트" + +[concepts."sql-databases"] +title = "SQL 데이터베이스" + +[concepts."security-jwt"] +title = "패스워드와 JWT 토큰을 사용하는 OAuth2" + +[concepts."cors"] +title = "CORS" + +[concepts."middleware"] +title = "미들웨어" + +[concepts."testing"] +title = "테스트" + +[concepts."background-tasks"] +title = "백그라운드 작업" + +[concepts."websockets"] +title = "WebSocket" + +[concepts."deployment-docker"] +title = "컨테이너 환경의 FastAPI(Docker)" + +[concepts."async"] +title = "동시성과 async / await" + +[guide] +next_steps = "다음 단계" +open = "프로젝트 폴더로 이동합니다." +install = "가상 환경을 만들고 의존성을 설치합니다." +install_pip = "가상 환경을 만들어 활성화한 다음 의존성을 설치합니다." +install_into_venv = "fastkit이 만든 가상 환경에 의존성을 설치합니다." +activate = "가상 환경을 활성화합니다." +env = "예제 파일로 로컬 설정 파일을 만들고, 버전 관리에서 제외합니다." +env_written = ".env를 확인하세요. fastkit이 .env.example을 바탕으로 고유한 SECRET_KEY를 넣어 만들었습니다." +env_kept = "기존 .env는 그대로 두었습니다. .env.example과 비교해서 새로 추가된 설정이 있는지 확인하세요." +services = "{services}을(를) 시작하고, .env의 URL 설정이 해당 서비스를 가리키도록 수정합니다." +migrate = "데이터베이스 테이블을 만듭니다." +worker = "두 번째 터미널에서 백그라운드 워커를 시작합니다." +run = "개발 서버를 시작하고 http://127.0.0.1:8000/docs를 엽니다." +run_readme_alternative = "fastkit이 설치되어 있다면 `fastkit runserver`로도 같은 작업을 할 수 있습니다." +run_compose = "Docker Compose로 컨테이너에서 실행할 수도 있습니다. `docker compose up --build`를 사용하세요." +test = "테스트를 실행합니다." +extend_classic = "라우트, 스키마, 데이터 계층, 테스트를 갖춘 리소스를 추가합니다." +extend_domain = "라우터, 스키마, 서비스, 리포지토리, 테스트를 갖춘 도메인을 추가합니다." +needs_fastkit = "이 명령을 사용하려면 fastkit이 설치되어 있어야 합니다." +next_level = "구조를 더 갖추고 싶다면 다음 단계의 프로젝트를 새로 만드세요." +items_sql = "예제 `/items` API는 이 데이터베이스에 아이템을 저장합니다." +items_memory = "예제 `/items` API는 아이템을 메모리에 보관합니다. fastkit이 아이템을 데이터베이스에 저장하는 경우는 PostgreSQL, MySQL, SQLite뿐입니다." +items_file = "예제 `/items` API는 이 데이터베이스가 아니라 JSON 파일 `src/mocks/mock_items.json`에 아이템을 보관합니다." +tables_alembic = "`alembic upgrade head`가 테이블을 만듭니다." +tables_startup = "앱이 시작될 때 테이블이 만들어집니다(마이그레이션을 선택하지 않았기 때문입니다)." +compose_urls = "컨테이너 안에서는 이 서비스들의 URL을 `docker-compose.yml`에서 가져옵니다. `.env`의 URL은 내 컴퓨터에서 앱을 실행할 때 사용합니다." +compose_migrate = "앱이 시작되기 전에 일회성 `migrate` 서비스가 Alembic 마이그레이션을 적용합니다." +compose_sqlite = "SQLite 데이터베이스 파일은 `sqlite_data` 볼륨에 보관됩니다." +read_single_file_split = "앱과 라우트는 `src/main.py`에서, 설정은 `src/core/config.py`에서 읽어 보세요." +read_layered_sql_items = "`src/main.py`를 읽은 다음 `src/api/routes/items.py`, `src/crud/items.py`, `src/models/items.py`, `src/schemas/items.py`를 읽어 보세요." +single_file_split = "선택한 기능이 설정을 읽는 모듈을 추가하기 때문에, 설정을 `src/main.py`에서 `src/core/config.py`로 옮겼습니다. `src/main.py`에는 앱과 라우트가 남아 있고, 기능도 여기에서 포함합니다." +files = "파일" +settings = "설정" +learn_more = "더 알아보기" +selected_features = "선택한 기능" +same_in_readme = "README.md에는 프로젝트를 새로 내려받았을 때 따라야 할 단계가 정리되어 있습니다." diff --git a/src/fastapi_fastkit/catalog/i18n/zh.toml b/src/fastapi_fastkit/catalog/i18n/zh.toml new file mode 100644 index 00000000..fa904dc0 --- /dev/null +++ b/src/fastapi_fastkit/catalog/i18n/zh.toml @@ -0,0 +1,387 @@ +[levels."hello"] +label = "Hello" +description = "只有一个 main.py:3 个端点、内存数据和测试。" +read_first = "从上到下阅读 `main.py`。每条注释都附有讲解对应代码的 FastAPI 教程页面链接。" +extend = "照着现有代码添加资源:复制 `Item` 模型、`create_item`、`read_item` 及其测试,再改名为适用于 `/users` 的版本。" + +[levels."single-file"] +label = "单文件" +description = "整个应用放在一个模块中,包含配置和测试。" +read_first = "阅读 `src/main.py`:配置、应用和路由都在这一个模块里。" + +[levels."layered"] +label = "分层" +description = "按层拆分:路由、CRUD、模式、核心配置。" +read_first = "先阅读 `src/main.py`,再阅读 `src/api/routes/items.py`、`src/crud/items.py` 和 `src/schemas/items.py`。" + +[levels."domain"] +label = "领域" +description = "每个领域一个包,包含路由器、服务和仓库。" +read_first = "先阅读 `src/app/main.py`,再阅读 `src/app/domains/items/` 中的 `router.py`、`service.py` 和 `repository.py`。" + +[levels."production"] +label = "生产" +description = "在领域级别的基础上增加 PostgreSQL、Alembic、JWT、CI 和 Docker。" +read_first = "先阅读 `src/app/main.py`,再阅读 `src/app/domains/items/`。README.md 会逐项介绍所选的功能。" + +[presets."single-module"] +summary = "所有代码放在一个模块中,适合小脚本和原型。" + +[presets."classic-layered"] +summary = "分层结构:api/routes、crud、schemas、core(与 fastapi-default 相同)。" + +[presets."domain-starter"] +summary = "面向领域的结构:在 src/app/domains// 下放置 router/service/repository(推荐)。" + +[templates."fastapi-hello"] +description = "最小的 FastAPI 应用:3 个端点、1 个模型及其测试" +read_first = "从上到下阅读 `main.py`。每条注释都附有讲解对应代码的 FastAPI 教程页面链接。" +extend = "照着现有代码添加资源:复制 `Item` 模型、`create_item`、`read_item` 及其测试,再改名为适用于 `/users` 的版本。" + +[templates."fastapi-single-module"] +description = "FastAPI 单模块模板" +read_first = "阅读 `src/main.py`:配置、应用和路由都在这一个模块里。" + +[templates."fastapi-default"] +description = "简单的 FastAPI 项目" +read_first = "先阅读 `src/main.py`,再阅读 `src/api/routes/items.py`、`src/crud/items.py` 和 `src/schemas/items.py`。" + +[templates."fastapi-domain-starter"] +description = "FastAPI 领域起步模板" +read_first = "先阅读 `src/app/main.py`,再阅读 `src/app/domains/items/` 中的 `router.py`、`service.py` 和 `repository.py`。" + +[templates."fastapi-custom-response"] +description = "带有自定义响应系统的异步条目管理 API" +read_first = "先阅读 `src/main.py`,再阅读 `src/helper/responses.py` 和 `src/api/routes/items.py`,了解响应 envelope 的结构。" + +[templates."fastapi-auth-jwt"] +description = "带 JWT 认证的 FastAPI 项目" +read_first = "先阅读 `src/app/main.py`,再阅读 `src/app/domains/auth/` 和 `src/app/core/security.py`。" + +[templates."fastapi-sqlmodel"] +description = "使用 SQLModel 的 FastAPI 项目" +read_first = "先阅读 `src/app/main.py`,再阅读 `src/app/domains/items/` 和 `src/app/db/session.py`。如何切换到 PostgreSQL 或 MySQL,README 中有说明。" + +[templates."fastapi-mcp"] +description = "使用 MCP 的 FastAPI 项目" +read_first = "先阅读 `src/main.py`,再阅读 `src/mcp_server/router.py` 和 `src/auth/`。" + +[templates."fastapi-llm-agent"] +description = "使用 LLM 智能体的 FastAPI 项目" +read_first = "先阅读 `src/app/main.py`,再阅读 `src/app/api/chat.py` 和 `src/app/llm/agent.py`。" + +[package_managers."pip"] +description = "Python 标准包管理器" + +[package_managers."uv"] +description = "快速的 Python 包管理器" + +[package_managers."pdm"] +description = "现代的 Python 依赖管理工具" + +[package_managers."poetry"] +description = "Python 依赖管理与打包工具" + +[axes."database"] +label = "数据库" +description = "选择数据库和 ORM。" + +[axes."database".options."PostgreSQL"] +summary = "通过异步 SQLAlchemy(asyncpg)使用 PostgreSQL。" +guide = "提供通过 asyncpg 连接 PostgreSQL 的异步 SQLAlchemy 引擎,以及每个请求独立的会话(`SessionDep`)。在 `.env` 中设置 `DATABASE_URL`;`GET /ready` 会检查连接。" + +[axes."database".options."MySQL"] +summary = "通过异步 SQLAlchemy(aiomysql)使用 MySQL。" +guide = "提供通过 aiomysql 连接 MySQL 的异步 SQLAlchemy 引擎,以及每个请求独立的会话(`SessionDep`)。在 `.env` 中设置 `DATABASE_URL`;`GET /ready` 会检查连接。" + +[axes."database".options."MongoDB"] +summary = "通过 PyMongo 的异步客户端使用 MongoDB。" +guide = "提供随应用启动而打开、随应用关闭而关闭的 PyMongo 异步客户端。在 `.env` 中设置 `MONGODB_URL`;`GET /ready` 会向服务器发送 ping。" + +[axes."database".options."Redis"] +summary = "将 Redis 用作键值存储(redis-py 的 asyncio 客户端)。" +guide = "提供随应用关闭而关闭的 redis-py asyncio 客户端(`redis_client`)。在 `.env` 中设置 `REDIS_URL`。" + +[axes."database".options."SQLite"] +summary = "通过异步 SQLAlchemy(aiosqlite)使用 SQLite 文件,无需服务器。" +guide = "提供通过 aiosqlite 连接 SQLite 文件的异步 SQLAlchemy 引擎,以及每个请求独立的会话(`SessionDep`);无需服务器。`.env` 中的 `DATABASE_URL` 指定数据库文件。" + +[axes."database".options."None"] +label = "无" +summary = "不使用数据库。" + +[axes."authentication"] +label = "认证" +description = "选择用户认证和授权方式。" + +[axes."authentication".options."JWT"] +summary = "使用 JWT 的 OAuth2 密码流程(推荐用于 API)。" +guide = "提供 OAuth2 密码流程:`POST /api/v1/auth/token` 返回用 `SECRET_KEY` 签名的 JWT,`CurrentUser` 依赖项负责保护你的端点。" + +[axes."authentication".options."OAuth2"] +summary = "使用 authlib 的 OAuth2。" +guide = "通过 Authlib 提供 Google 或 GitHub 登录。在 `.env` 中设置 `GOOGLE_*` 或 `GITHUB_*` 凭据即可启用对应的提供方。" + +[axes."authentication".options."FastAPI-Users"] +summary = "完整的用户管理功能(JWT,仅支持 SQL 数据库)。" +guide = "提供 FastAPI-Users 的注册、登录和用户管理功能,用户数据存储在 SQL 数据库中。" + +[axes."authentication".options."Session-based"] +summary = "传统的基于会话的认证。" +guide = "登录时设置带签名的会话 Cookie,退出登录时结束该账号的所有会话。" + +[axes."authentication".options."None"] +label = "无" +summary = "不使用认证。" + +[axes."async_tasks"] +label = "后台任务" +description = "选择后台任务的处理方式。" + +[axes."async_tasks".options."Celery"] +guide = "提供 Celery 工作进程,以及把任务放入 Redis 队列的 `/api/v1/tasks` 端点;工作进程需要与 API 分开运行。" + +[axes."async_tasks".options."Dramatiq"] +guide = "提供 Dramatiq 工作进程,以及把任务放入 Redis 队列的 `/api/v1/tasks` 端点;工作进程需要与 API 分开运行。" + +[axes."async_tasks".options."None"] +label = "无" + +[axes."testing"] +label = "测试" +description = "选择测试框架和工具。" + +[axes."testing".options."Basic"] +summary = "用于 API 测试的 pytest 和 httpx。" +guide = "pytest 配置,每个功能一个测试模块(SQL 数据库使用内存中的 SQLite)。" + +[axes."testing".options."Coverage"] +summary = "在基础配置上增加代码覆盖率。" +guide = "pytest 配置,每个功能一个测试模块(SQL 数据库使用内存中的 SQLite);`pytest --cov` 会报告覆盖率。" + +[axes."testing".options."Advanced"] +summary = "在覆盖率的基础上增加用于夹具的 faker 和 factory-boy。" +guide = "pytest 配置,每个功能一个测试模块(SQL 数据库使用内存中的 SQLite);`pytest --cov` 会报告覆盖率,`tests/factories.py` 中有 faker 和 factory-boy 工厂。" + +[axes."testing".options."None"] +label = "无" +summary = "不使用测试框架。" + +[axes."caching"] +label = "缓存" +description = "选择响应和数据缓存。" + +[axes."caching".options."Redis"] +guide = "使用基于 Redis 的 fastapi-cache2 缓存响应;`/api/v1/cache` 下的路由器演示了装饰器的用法。" + +[axes."caching".options."None"] +label = "无" + +[axes."monitoring"] +label = "监控" +description = "选择应用监控和日志。" + +[axes."monitoring".options."Loguru"] +summary = "使用 Loguru 增强日志。" +guide = "由 Loguru 接管应用和 Uvicorn 的日志输出。" + +[axes."monitoring".options."OpenTelemetry"] +summary = "分布式追踪和指标。" +guide = "追踪每个请求,并通过 OTLP 导出 span;导出设置在 `.env` 中配置。" + +[axes."monitoring".options."Prometheus"] +summary = "Prometheus 指标采集。" +guide = "在 `/metrics` 提供请求指标。" + +[axes."monitoring".options."None"] +label = "无" +summary = "不使用额外的监控。" + +[axes."utilities"] +label = "实用工具" +description = "选择额外的实用工具和中间件。" + +[axes."utilities".options."Rate-Limiting"] +summary = "按客户端限制 API 请求频率(limits)。" +guide = "对每个路由按客户端设置限制(`RATE_LIMIT_DEFAULT`);选择认证后,登录端点的限制更严格(`RATE_LIMIT_AUTH`)。超出限制的客户端会收到 429。" + +[axes."utilities".options."WebSocket"] +summary = "WebSocket 端点示例(websockets)。" +guide = "提供 `/ws` 处的 WebSocket 端点和 `GET /api/v1/connections`。" + +[axes."utilities".options."None"] +label = "无" + +[axes."migrations"] +label = "迁移" +description = "选择数据库表结构迁移。" + +[axes."migrations".options."Alembic"] +summary = "生成 alembic.ini、异步的 alembic/env.py 和 scripts/migrate.sh。" +guide = "在 `alembic/` 中提供 Alembic 迁移:`alembic upgrade head` 创建数据表,`alembic revision --autogenerate -m \"add orders\"` 记录模型的变更。" + +[axes."migrations".options."None"] +label = "无" +summary = "不使用迁移工具。" + +[axes."tooling"] +label = "开发工具" +description = "选择开发工具和 CI 配置。" + +[axes."tooling".options."ruff"] +summary = "在 pyproject.toml 中加入 ruff 和 ruff-format 配置(取代 black 和 isort)。" +guide = "ruff 负责检查并格式化代码:`ruff check .` 和 `ruff format .`。" + +[axes."tooling".options."pre-commit"] +summary = "生成 .pre-commit-config.yaml。" +guide = "运行 `pre-commit install` 之后,每次提交前都会先运行检查。" + +[axes."tooling".options."github-actions"] +summary = "生成 .github/workflows/test.yml(Python 3.12)。" +guide = "推送到 `main` 以及每个拉取请求都会运行测试。" + +[axes."tooling".options."devcontainer"] +summary = "生成 .devcontainer/devcontainer.json。" +guide = "在装有合适 Python 版本的开发容器中打开项目。" + +[axes."tooling".options."makefile"] +summary = "包含 install/test/lint/format/run 的 Makefile。" +guide = "提供快捷命令:`make install`、`make test`、`make lint`、`make format`、`make run`。" + +[axes."tooling".options."None"] +label = "无" + +[axes."logging"] +label = "日志" +description = "选择应用的日志格式。" + +[axes."logging".options."structured"] +summary = "JSON 日志和 X-Request-ID 关联中间件(仅使用标准库)。" +guide = "输出 JSON 日志行,每个请求带有一个 `X-Request-ID`(取自请求,没有则自动生成)。" + +[axes."logging".options."None"] +label = "无" +summary = "使用 Uvicorn 默认的纯文本日志。" + +[axes."deployment"] +label = "部署" +description = "选择容器部署文件。" + +[axes."deployment".options."Docker"] +summary = "生成 Dockerfile。" +guide = "构建应用镜像(`docker build -t .`);容器从环境变量读取设置,而不是读取复制进去的 `.env`。" + +[axes."deployment".options."docker-compose"] +summary = "生成 docker-compose.yml(包含 Docker)。" +guide = "`docker compose up --build` 会启动应用及其所需的服务。" + +[axes."deployment".options."None"] +label = "无" +summary = "不生成部署配置。" + +[rules."fastapi-users-needs-sql"] +message = "认证 'FastAPI-Users' 需要 SQL 数据库({allowed}),但当前选择的是 {selected}。请选择其中一种数据库,或选择适用于所有数据库的 'JWT' 选项。" + +[rules."shared-redis"] +message = "提示:缓存和任务队列都将使用 Redis(共享依赖)。" + +[concepts."first-steps"] +title = "第一步" + +[concepts."path-parameters"] +title = "路径参数" + +[concepts."query-parameters"] +title = "查询参数" + +[concepts."request-body"] +title = "请求体" + +[concepts."response-model"] +title = "响应模型" + +[concepts."status-codes"] +title = "响应状态码" + +[concepts."handling-errors"] +title = "错误处理" + +[concepts."dependencies"] +title = "依赖项" + +[concepts."dependencies-with-yield"] +title = "使用 yield 的依赖项" + +[concepts."bigger-applications"] +title = "多文件的大型应用" + +[concepts."settings"] +title = "设置和环境变量" + +[concepts."lifespan"] +title = "Lifespan 事件" + +[concepts."sql-databases"] +title = "SQL 数据库" + +[concepts."security-jwt"] +title = "使用密码和 JWT 令牌的 OAuth2" + +[concepts."cors"] +title = "CORS" + +[concepts."middleware"] +title = "中间件" + +[concepts."testing"] +title = "测试" + +[concepts."background-tasks"] +title = "后台任务" + +[concepts."websockets"] +title = "WebSocket" + +[concepts."deployment-docker"] +title = "容器中的 FastAPI(Docker)" + +[concepts."async"] +title = "并发与 async / await" + +[guide] +next_steps = "后续步骤" +open = "进入项目文件夹。" +install = "创建虚拟环境并安装依赖。" +install_pip = "创建虚拟环境,激活它,然后安装依赖。" +install_into_venv = "把依赖安装到 fastkit 创建的虚拟环境中。" +activate = "激活虚拟环境。" +env = "用示例文件创建本地设置文件,并让它不受版本控制。" +env_written = "请检查 .env:fastkit 根据 .env.example 生成了它,并写入了唯一的 SECRET_KEY。" +env_kept = "已保留你原有的 .env;请对照 .env.example 查看有没有新增的设置。" +services = "启动 {services},并让 .env 中的 URL 设置指向它。" +migrate = "创建数据库表。" +worker = "在第二个终端中启动后台工作进程。" +run = "启动开发服务器,并打开 http://127.0.0.1:8000/docs。" +run_readme_alternative = "如果已安装 fastkit,运行 `fastkit runserver` 也能达到同样的效果。" +run_compose = "也可以用 Docker Compose 在容器中运行:`docker compose up --build`。" +test = "运行测试。" +extend_classic = "添加一个资源,包括它的路由、模式、数据层和测试。" +extend_domain = "添加一个领域,包括它的路由器、模式、服务、仓库和测试。" +needs_fastkit = "该命令需要先安装 fastkit。" +next_level = "如果想要更完整的结构,请创建下一个级别的项目。" +items_sql = "示例 `/items` API 把条目存储在这个数据库中。" +items_memory = "示例 `/items` API 把条目保存在内存中:只有选择 PostgreSQL、MySQL 和 SQLite 时,fastkit 才会把条目存入数据库。" +items_file = "示例 `/items` API 把条目保存在 JSON 文件 `src/mocks/mock_items.json` 中,而不是这个数据库中。" +tables_alembic = "`alembic upgrade head` 会创建数据表。" +tables_startup = "数据表会在应用启动时创建(因为没有选择迁移)。" +compose_urls = "在容器中,这些服务的 URL 来自 `docker-compose.yml`;`.env` 中的 URL 用于在你自己的机器上运行应用。" +compose_migrate = "应用启动之前,一次性的 `migrate` 服务会应用 Alembic 迁移。" +compose_sqlite = "SQLite 数据库文件保存在 `sqlite_data` 卷中。" +read_single_file_split = "阅读 `src/main.py` 了解应用和路由,再阅读 `src/core/config.py` 了解设置。" +read_layered_sql_items = "先阅读 `src/main.py`,再阅读 `src/api/routes/items.py`、`src/crud/items.py`、`src/models/items.py` 和 `src/schemas/items.py`。" +single_file_split = "你选择的功能新增了读取设置的模块,因此设置已从 `src/main.py` 移到 `src/core/config.py`;`src/main.py` 保留应用和路由,并引入这些功能。" +files = "文件" +settings = "设置" +learn_more = "了解更多" +selected_features = "已选功能" +same_in_readme = "README.md 列出了全新检出该项目后需要执行的步骤。" diff --git a/src/fastapi_fastkit/core/known.py b/src/fastapi_fastkit/core/known.py new file mode 100644 index 00000000..ddc1d0e0 --- /dev/null +++ b/src/fastapi_fastkit/core/known.py @@ -0,0 +1,91 @@ +# -------------------------------------------------------------------------- +# Values fastkit itself has shipped as examples, in any version. +# +# A project that still uses one of these runs with a secret everybody can +# read in fastkit's public repository. The set is collected from the +# templates' ``KNOWN_EXAMPLE_SECRET_KEYS``, the ``.env`` / ``.env.example`` +# templates and the ``fastkit init`` fragments, including the values of +# releases before v1.5.2 (``git log -p`` on the templates and fragments). +# ``tests/test_backends/test_doctor_checks.py`` fails when a template adds a +# new example key that is missing here. +# +# Shared by ``fastkit doctor`` and generation (which refuses to write these +# values); ``fastapi_fastkit.backend.doctor.known`` re-exports the names. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- + +#: Example secrets (SECRET_KEY, session keys, MCP API key placeholders). +KNOWN_EXAMPLE_SECRETS = frozenset( + { + # .env templates and KNOWN_EXAMPLE_SECRET_KEYS (every version) + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + # fastapi-mcp settings default and the ``fastkit init`` JWT module + # before v1.5.2 + "your-secret-key-here-change-in-production", + "your-secret-key-here", + # ``fastkit init`` Session / OAuth2 modules before v1.5.2 + # (SESSION_SECRET_KEY default) + "change-me-in-production", + # fastapi-mcp .env template (commented example of MCP_API_KEY) + "your-mcp-api-key-here", + } +) + +#: Passwords of the hard-coded demo accounts fastapi-mcp shipped before +#: v1.5.2 (``user1`` / ``user2`` / ``admin``). +MCP_DEMO_PASSWORDS = frozenset({"password123", "password456", "admin123"}) + +#: ``.env`` variants meant to be committed (no real values). +ENV_EXAMPLE_NAMES = frozenset( + {".env.example", ".env.sample", ".env.template", ".env.dist", ".env.defaults"} +) + +#: Variables whose value is never a secret in a fastkit project. Only these +#: keep their value when ``.env.example`` is written from ``.env``, and +#: only when the value itself does not look like a secret. +NON_SECRET_ENV_NAMES = frozenset( + { + "ACCESS_TOKEN_EXPIRE_MINUTES", + "ALGORITHM", + "API_V1_PREFIX", + "API_V1_STR", + "BACKEND_CORS_ORIGINS", + "DEBUG", + "ENABLE_DEMO_USERS", + "ENV", + "ENVIRONMENT", + "FRONTEND_HOST", + "HOST", + "JWT_ALGORITHM", + "LLM_MAX_TOKENS", + "LLM_MODEL", + "LLM_PROVIDER", + "LLM_TEMPERATURE", + "LOG_FORMAT", + "LOG_LEVEL", + "MCP_DESCRIPTION", + "MCP_ENABLED", + "MCP_MOUNT_PATH", + "MCP_TITLE", + "PORT", + "POSTGRES_DB", + "POSTGRES_PORT", + "POSTGRES_SERVER", + "PROJECT_NAME", + "REFRESH_TOKEN_EXPIRE_DAYS", + "SESSION_MAX_AGE", + "TZ", + "VERSION", + "WORKERS", + } +) + +__all__ = [ + "ENV_EXAMPLE_NAMES", + "KNOWN_EXAMPLE_SECRETS", + "MCP_DEMO_PASSWORDS", + "NON_SECRET_ENV_NAMES", +] diff --git a/src/fastapi_fastkit/generation/browser.py b/src/fastapi_fastkit/generation/browser.py new file mode 100644 index 00000000..c27cf35d --- /dev/null +++ b/src/fastapi_fastkit/generation/browser.py @@ -0,0 +1,973 @@ +# -------------------------------------------------------------------------- +# The web generator page's Python side. +# +# The documentation site's web generator runs this module under Pyodide: +# it turns the page's form into a ``ProjectChoice`` (the same object the +# CLI flags and the guided dialogue produce), reports problems and rule +# feedback in the page language, lists the files ``plan`` expects, builds +# the equivalent ``fastkit init`` command line and generates the project +# into a deterministic zip. +# +# Standard library, the catalog and the generation layer only (no click, +# rich or subprocess calls), so it runs in the browser. Not exported from +# ``fastapi_fastkit.generation``, which keeps that import light. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import io +import json +import os +import re +import shlex +import shutil +import stat +import tempfile +import time +import zipfile +from dataclasses import dataclass +from dataclasses import field as dataclass_field +from typing import Any, Callable, Iterable, Literal, Mapping, Optional, Sequence + +from fastapi_fastkit import __version__ +from fastapi_fastkit.catalog import LANGUAGES, Axis, Catalog, evaluate, load_catalog +from fastapi_fastkit.generation.errors import GenerationError +from fastapi_fastkit.generation.guide import ( + Environment, + FeatureSection, + Step, + feature_sections, + next_steps, +) +from fastapi_fastkit.generation.levels import ( + ProjectChoice, + choice_spec, + database_choices, + default_database, + default_selection, + effective_selection, + raw_selection, + uses_template_mode, +) +from fastapi_fastkit.generation.pipeline import generate, plan +from fastapi_fastkit.generation.secrets import SecretFactory +from fastapi_fastkit.generation.spec import FeatureValue, ProjectInfo +from fastapi_fastkit.utils.filemodes import is_executable_path +from fastapi_fastkit.utils.validation import ( + project_name_problem, + validate_email_format, + validate_package_name, +) + +#: Version of the form object the page sends (``form["schema"]``). +FORM_SCHEMA = 1 + +#: Web-only input limits (characters; counts for ``extra_packages``). They +#: are stricter than the CLI, never looser. +LIMITS: dict[str, int] = { + "project_name": 64, + "author": 200, + "author_email": 254, + "description": 500, + "extra_packages": 20, + "extra_package": 100, +} + +#: Every key a form may have. +FORM_KEYS: tuple[str, ...] = ( + "schema", + "project_name", + "level", + "database", + "customise", + "features", + "package_manager", + "author", + "author_email", + "description", + "extra_packages", +) + +#: The database axis; the form sets it with ``database``, not as a feature. +_DATABASE = "database" + +#: The file holding the generated secret. +_ENV_FILE = ".env" + +#: Values a POSIX shell (bash, zsh) takes as they are. ``%`` is left out +#: although POSIX shells do not care, so the line never looks like a cmd +#: variable. +_BARE_VALUE = re.compile(r"[A-Za-z0-9_@+=:,./-]+") + +#: Characters a double-quoted value cannot carry as they are in bash and +#: zsh (expansion, escapes, history). +_NOT_IN_DOUBLE_QUOTES = frozenset('"$`\\!') + +#: Values PowerShell passes on as they are: no ``@`` (splatting), ``,`` +#: (array), ``$``, backtick, quotes, ``;``, ``&``, ``|``, redirections, +#: parentheses, braces, ``#`` or ``%``. +_BARE_POWERSHELL_VALUE = re.compile(r"[A-Za-z0-9_+=:./-]+") + +#: Characters PowerShell reads as a single quote; doubled inside a +#: single-quoted string. +_POWERSHELL_SINGLE_QUOTES = frozenset("'‘’‚‛") + +#: A Windows drive prefix (``C:``) at the start of a zip entry name. +_DRIVE = re.compile(r"^[A-Za-z]:") + +#: Zip timestamp: ``(year, month, day, hour, minute, second)``. +DateTime = tuple[int, int, int, int, int, int] + + +@dataclass(frozen=True) +class FormProblem: + """One problem with a form field; the page shows it in its language.""" + + #: Form key (``project_name``, ``level``, ``features``, ...; ``form`` + #: for the form as a whole). + field: str + #: ``empty``, ``characters``, ``digit``, ``keyword``, ``too_long``, + #: ``type``, ``schema``, ``unknown_field``, ``unknown_level``, + #: ``unknown_database``, ``unknown_axis``, ``unknown_option``, + #: ``unknown_package_manager``, ``not_offered``, ``email``, ``package``, + #: ``too_many``. + code: str + #: Values for the message placeholders (``max``, ``package``, ...). + params: Mapping[str, str] = dataclass_field(default_factory=dict) + + def as_dict(self) -> dict[str, Any]: + """The problem as JSON-ready data.""" + return {"field": self.field, "code": self.code, "params": dict(self.params)} + + +class FormError(ValueError): + """A form that cannot become a project choice; ``problems`` says why.""" + + def __init__(self, problems: Iterable[FormProblem]) -> None: + self.problems: tuple[FormProblem, ...] = tuple(problems) + super().__init__( + "; ".join(f"{problem.field}: {problem.code}" for problem in self.problems) + ) + + +def _language(lang: str) -> str: + """A catalog language; anything unknown reads as English.""" + return lang if lang in LANGUAGES else "en" + + +def _json_value(value: FeatureValue) -> Any: + return list(value) if isinstance(value, tuple) else value + + +def _json_selection(selection: Mapping[str, FeatureValue]) -> dict[str, Any]: + return {key: _json_value(value) for key, value in selection.items()} + + +def _form_axes(catalog: Catalog) -> tuple[Axis, ...]: + """The axes the form asks: feature axes except the database, then + ``deployment`` (catalog order).""" + return tuple(axis for axis in catalog.axes if axis.id != _DATABASE) + + +# ------------------------------------------------------------------ +# Form model +# ------------------------------------------------------------------ + + +def form_model(lang: str = "en") -> dict[str, Any]: + """ + Everything the page needs to draw the form before Python is loaded + (the docs build writes it to ``model-.json``). + + :param lang: Catalog language for labels and descriptions + :return: JSON-ready mapping (see the stage-5 notes for its keys) + """ + catalog = load_catalog(_language(lang)) + database_axis = catalog.axis(_DATABASE) + preset_levels = [level for level in catalog.levels if level.preset is not None] + return { + "schema": FORM_SCHEMA, + "lang": catalog.lang, + "fastkit_version": __version__, + "defaults": { + "level": catalog.defaults.level, + "package_manager": catalog.defaults.package_manager, + }, + "limits": dict(LIMITS), + "levels": [ + { + "id": level.id, + "label": level.label, + "description": level.description, + "asks_database": level.asks_database, + "has_features": level.preset is not None, + "default_database": ( + default_database(level.id) if level.asks_database else None + ), + } + for level in catalog.levels + ], + "databases": [ + { + "id": option.id, + "label": option.label, + "summary": option.summary, + "sql": "sql" in option.tags, + } + for option in database_axis.options + ], + "axes": [ + { + "id": axis.id, + "label": axis.label, + "description": axis.description, + "multi": axis.multi, + "options": [ + {"id": option.id, "label": option.label, "summary": option.summary} + for option in axis.offered + ], + "none": axis.options[-1].id, + "none_label": axis.options[-1].label, + } + for axis in _form_axes(catalog) + ], + "defaults_by": { + level.id: { + database: { + key: _json_value(value) + for key, value in default_selection(level.id, database).items() + if key != _DATABASE + } + for database in database_choices(level.id) + } + for level in preset_levels + }, + "package_managers": [ + {"id": manager.id, "description": manager.description} + for manager in catalog.package_managers + ], + "guide": { + "next_steps": catalog.guide["next_steps"], + "same_in_readme": catalog.guide["same_in_readme"], + }, + } + + +# ------------------------------------------------------------------ +# Form -> choice +# ------------------------------------------------------------------ + + +class _Problems: + """Collects problems while a form is read.""" + + def __init__(self) -> None: + self.items: list[FormProblem] = [] + + def add(self, field: str, code: str, /, **params: str) -> None: + self.items.append(FormProblem(field, code, params)) + + +def _text( + form: Mapping[str, Any], key: str, problems: _Problems, *, strip: bool = True +) -> Optional[str]: + """A string field ("" when missing or null); ``None`` after a problem.""" + value = form.get(key) + if value is None: + return "" + if not isinstance(value, str): + problems.add(key, "type", expected="string") + return None + text = value.strip() if strip else value + if len(text) > LIMITS[key]: + problems.add(key, "too_long", max=str(LIMITS[key])) + return None + return text + + +def _project_name(form: Mapping[str, Any], problems: _Problems) -> str: + """The name as given (the CLI uses ``--project-name`` verbatim).""" + value = form.get("project_name") + if value is None: + value = "" + if not isinstance(value, str): + problems.add("project_name", "type", expected="string") + return "" + problem = project_name_problem(value) + if problem is not None: + problems.add("project_name", problem, name=value) + elif len(value) > LIMITS["project_name"]: + problems.add("project_name", "too_long", max=str(LIMITS["project_name"])) + return value + + +def _is_unset(value: Any) -> bool: + if value is None or value == "None": + return True + if isinstance(value, (list, tuple)): + return all(item == "None" for item in value) + return False + + +def _database( + form: Mapping[str, Any], level_id: Optional[str], problems: _Problems +) -> Optional[str]: + value = form.get("database") + if value is None: + return None + if not isinstance(value, str): + problems.add("database", "type", expected="string") + return None + if level_id is None: + return None + choices = database_choices(level_id) + if not choices: + if value != "None": + problems.add("database", "not_offered", level=level_id) + return None + if value not in choices: + problems.add("database", "unknown_database", database=value) + return None + return value + + +def _axis_answer(axis: Axis, value: Any, problems: _Problems) -> Optional[FeatureValue]: + """One feature answer in selection form; ``None`` after a problem.""" + if axis.multi: + items = [value] if isinstance(value, str) else value + if not isinstance(items, (list, tuple)) or not all( + isinstance(item, str) for item in items + ): + problems.add("features", "type", axis=axis.id, expected="list") + return None + unknown = [item for item in items if item not in axis.choice_ids] + for item in dict.fromkeys(unknown): + problems.add("features", "unknown_option", axis=axis.id, option=item) + if unknown: + return None + none_id = axis.options[-1].id + return tuple( + choice + for choice in axis.choice_ids + if choice in items and choice != none_id + ) + if not isinstance(value, str): + problems.add("features", "type", axis=axis.id, expected="string") + return None + if value not in axis.choice_ids: + problems.add("features", "unknown_option", axis=axis.id, option=value) + return None + return value + + +def _features( + form: Mapping[str, Any], + catalog: Catalog, + level_id: Optional[str], + has_features: bool, + problems: _Problems, +) -> dict[str, FeatureValue]: + raw = form.get("features") + if raw is None: + return {} + if not isinstance(raw, Mapping): + problems.add("features", "type", expected="object") + return {} + if level_id is None: + return {} + if not has_features: + if any(not _is_unset(value) for value in raw.values()): + problems.add("features", "not_offered", level=level_id) + return {} + allowed = {axis.id: axis for axis in _form_axes(catalog)} + answers: dict[str, FeatureValue] = {} + for key, value in raw.items(): + axis = allowed.get(key) if isinstance(key, str) else None + if axis is None: + problems.add("features", "unknown_axis", axis=str(key)) + continue + answer = _axis_answer(axis, value, problems) + if answer is not None: + answers[axis.id] = answer + return answers + + +def _package_manager( + form: Mapping[str, Any], catalog: Catalog, problems: _Problems +) -> str: + default = catalog.defaults.package_manager + value = form.get("package_manager") + if value is None: + return default + known = [manager.id for manager in catalog.package_managers] + if not isinstance(value, str): + problems.add("package_manager", "type", expected="string") + elif value not in known: + problems.add( + "package_manager", "unknown_package_manager", package_manager=value + ) + else: + return value + return default + + +def _has_space_or_control(text: str) -> bool: + """Whitespace (any kind) or a non-printable character anywhere.""" + return any(char.isspace() or not char.isprintable() for char in text) + + +def _extra_packages( + form: Mapping[str, Any], + level_id: Optional[str], + has_features: bool, + problems: _Problems, +) -> tuple[str, ...]: + """Stripped, empty entries dropped, duplicates (any case) removed.""" + raw = form.get("extra_packages") + if raw is None: + return () + if not isinstance(raw, (list, tuple)) or not all( + isinstance(item, str) for item in raw + ): + problems.add("extra_packages", "type", expected="list") + return () + packages: dict[str, str] = {} + for item in raw: + package = item.strip() + if package: + packages.setdefault(package.lower(), package) + chosen = tuple(packages.values()) + if not chosen: + return () + if level_id is not None and not has_features: + problems.add("extra_packages", "not_offered", level=level_id) + return () + if len(chosen) > LIMITS["extra_packages"]: + problems.add("extra_packages", "too_many", max=str(LIMITS["extra_packages"])) + for package in chosen: + if len(package) > LIMITS["extra_package"]: + problems.add( + "extra_packages", + "too_long", + max=str(LIMITS["extra_package"]), + package=package, + ) + elif _has_space_or_control(package) or not validate_package_name(package): + # The shared validator checks only the name part; a newline + # after a version specifier would add a line to the + # dependency files. + problems.add("extra_packages", "package", package=package) + return chosen + + +def choice_from_form(form: Mapping[str, Any]) -> ProjectChoice: + """ + Read the page's form into a level choice. + + With ``customise`` false the form means the CLI's "No" to the customise + question: no feature answers, the default package manager, an empty + identity and no extra packages (those fields are then ignored, not + checked). + + :param form: The form object (see :data:`FORM_KEYS`) + :return: The choice ``fastkit init`` gets from :func:`command_line` + :raises FormError: With every problem found + """ + if not isinstance(form, Mapping): + raise FormError([FormProblem("form", "type", {"expected": "object"})]) + problems = _Problems() + catalog = load_catalog() + for key in form: + if key not in FORM_KEYS: + problems.add(str(key), "unknown_field", field=str(key)) + schema = form.get("schema", FORM_SCHEMA) + if type(schema) is not int or schema != FORM_SCHEMA: + problems.add("schema", "schema", expected=str(FORM_SCHEMA)) + + name = _project_name(form, problems) + + level_value = form.get("level") + level_id: Optional[str] = None + has_features = False + if level_value is None: + level_value = catalog.defaults.level + if not isinstance(level_value, str): + problems.add("level", "type", expected="string") + elif level_value not in [level.id for level in catalog.levels]: + problems.add("level", "unknown_level", level=level_value) + else: + level_id = level_value + has_features = catalog.level(level_id).preset is not None + + database = _database(form, level_id, problems) + + customise = form.get("customise", False) + if customise is None: + customise = False + if not isinstance(customise, bool): + problems.add("customise", "type", expected="boolean") + customise = False + + features: dict[str, FeatureValue] = {} + package_manager = catalog.defaults.package_manager + author: Optional[str] = "" + author_email: Optional[str] = "" + description: Optional[str] = "" + extra: tuple[str, ...] = () + if customise: + features = _features(form, catalog, level_id, has_features, problems) + package_manager = _package_manager(form, catalog, problems) + author = _text(form, "author", problems) + author_email = _text(form, "author_email", problems) + if author_email and not validate_email_format(author_email): + problems.add("author_email", "email", email=author_email) + description = _text(form, "description", problems) + extra = _extra_packages(form, level_id, has_features, problems) + + if problems.items: + raise FormError(problems.items) + return ProjectChoice( + project=ProjectInfo( + name=name, + author=author or "", + author_email=author_email or "", + description=description or "", + ), + level=level_id, + database=database, + features=features or None, + package_manager=package_manager, + custom_packages=extra, + ) + + +# ------------------------------------------------------------------ +# Command line +# ------------------------------------------------------------------ + + +def _comparable(value: FeatureValue) -> Any: + return frozenset(value) if isinstance(value, tuple) else value + + +def _flag_value(axis: Axis, value: FeatureValue) -> str: + if isinstance(value, tuple): + return ",".join(value) if value else axis.options[-1].id + return value + + +def command_line(choice: ProjectChoice) -> list[str]: + """ + The ``fastkit init`` arguments (after ``fastkit``) that create the same + project with ``--no-venv``. + + ``--database`` appears when it differs from the level's default, one + ``--feature`` per axis whose answer differs from the level's default + selection (catalog order), ``--author`` / ``--author-email`` / + ``--description`` only when not empty; ``--package-manager`` always. + + :raises ChoiceError: For an unknown level, database or feature key + """ + project = choice.project + argv = ["init", "--project-name", project.name] + if choice.template is not None and choice.level is None: + argv += ["--template", choice.template] + argv += ["--package-manager", choice.package_manager] + else: + catalog = load_catalog() + level_id = str(choice.level) + argv += ["--level", level_id, "--package-manager", choice.package_manager] + if ( + database_choices(level_id) + and choice.database is not None + and choice.database != default_database(level_id) + ): + argv += ["--database", choice.database] + selection = raw_selection(choice) + if selection: + defaults = default_selection(level_id, choice.database) + for axis in _form_axes(catalog): + value = selection[axis.id] + if _comparable(value) != _comparable(defaults[axis.id]): + argv += ["--feature", f"{axis.id}={_flag_value(axis, value)}"] + for package in choice.custom_packages: + argv += ["--extra-package", package] + for flag, value in ( + ("--author", project.author), + ("--author-email", project.author_email), + ("--description", project.description), + ): + if value: + argv += [flag, value] + return argv + ["--no-venv", "-y"] + + +def _quoted(value: str) -> str: + if _BARE_VALUE.fullmatch(value): + return value + if not _NOT_IN_DOUBLE_QUOTES.intersection(value): + return f'"{value}"' + return shlex.quote(value) + + +def _powershell_quoted(value: str) -> str: + if _BARE_POWERSHELL_VALUE.fullmatch(value): + return value + escaped = "".join( + char * 2 if char in _POWERSHELL_SINGLE_QUOTES else char for char in value + ) + return f"'{escaped}'" + + +def shell_text(argv: Sequence[str], *, windows: bool = False) -> str: + """ + ``argv`` as one ``fastkit ...`` line to copy into a shell. + + POSIX (bash, zsh; the default): a value of letters, digits and + ``_@+=:,./-`` stays bare; anything else is double-quoted unless it + holds ``"``, ``$``, a backtick, ``\\`` or ``!``, which get POSIX single + quotes (:func:`shlex.quote`). + + ``windows=True`` gives the PowerShell line: a value of letters, digits + and ``_+=:./-`` stays bare; anything else is single-quoted, with every + single quote (``'`` and its typographic forms) doubled. Single quotes + expand nothing in PowerShell. + """ + quote = _powershell_quoted if windows else _quoted + return " ".join(["fastkit", *(quote(arg) for arg in argv)]) + + +# ------------------------------------------------------------------ +# Checking a form +# ------------------------------------------------------------------ + + +def check_form(form: Mapping[str, Any], lang: str = "en") -> dict[str, Any]: + """ + Everything the page shows while a person fills in the form. + + :param form: The form object + :param lang: Language of the rule errors and notes + :return: ``{"ok", "problems", "rule_errors", "notes", "selection", + "implied", "template_mode", "files", "command", "command_text", + "command_text_windows", "identity_note"}``; ``ok`` is true when the + project can be generated; ``command_text`` is for bash / zsh, + ``command_text_windows`` for PowerShell + """ + catalog = load_catalog(_language(lang)) + result: dict[str, Any] = { + "ok": False, + "problems": [], + "rule_errors": [], + "notes": [], + "selection": None, + "implied": {}, + "template_mode": None, + "files": [], + "command": [], + "command_text": "", + "command_text_windows": "", + "identity_note": False, + } + try: + choice = choice_from_form(form) + except FormError as e: + result["problems"] = [problem.as_dict() for problem in e.problems] + return result + + project = choice.project + try: + argv = command_line(choice) + result["command"] = argv + result["command_text"] = shell_text(argv) + result["command_text_windows"] = shell_text(argv, windows=True) + result["identity_note"] = not (project.author and project.author_email) + selection = raw_selection(choice) + notes: tuple[str, ...] = () + if selection: + outcome = evaluate(selection, catalog) + if outcome.errors: + result["rule_errors"] = list(outcome.errors) + result["selection"] = _json_selection(selection) + return result + result["selection"] = _json_selection(effective_selection(choice)) + result["implied"] = { + axis_id: list(values) for axis_id, values in outcome.implied.items() + } + notes = outcome.notes + template_mode = uses_template_mode(choice) + result["template_mode"] = template_mode + result["notes"] = [] if template_mode else list(notes) + spec = choice_spec(choice) + with tempfile.TemporaryDirectory(prefix="fastkit-web-") as scratch: + files = plan(spec, os.path.join(scratch, project.name)).files + except GenerationError as e: + result["rule_errors"] = [str(e)] + return result + result["files"] = list(files) + result["ok"] = True + return result + + +# ------------------------------------------------------------------ +# Zip +# ------------------------------------------------------------------ + + +def _check_entry_name(name: str, root: str) -> None: + """ + :raises ValueError: When ``name`` is not a safe entry under ``root`` + """ + reason = "" + if "\0" in name: + reason = "contains NUL" + elif "\\" in name: + reason = "contains a backslash" + elif name.startswith("/"): + reason = "is absolute" + elif _DRIVE.match(name): + reason = "starts with a drive letter" + elif any(part in ("", ".", "..") for part in name.split("/")): + reason = "has an empty, '.' or '..' segment" + elif not root or not name.startswith(root + "/"): + reason = f"is not inside '{root}/'" + if reason: + raise ValueError(f"Unsafe zip entry name {name!r}: it {reason}.") + + +def _zip_bytes( + root: str, + entries: Iterable[tuple[str, bytes]], + *, + date_time: Optional[DateTime] = None, +) -> bytes: + """ + A zip of ``(relpath, content)`` entries under ``root/``, sorted by + relpath; modes come from the name (``*.sh`` 0755, else 0644). + + :raises ValueError: For an unsafe or duplicate entry name + """ + stamp = date_time or time.localtime()[:6] + buffer = io.BytesIO() + seen: set[str] = set() + with zipfile.ZipFile(buffer, "w") as archive: + for relpath, content in sorted(entries, key=lambda entry: entry[0]): + name = f"{root}/{relpath}" + _check_entry_name(name, root) + if name in seen: + raise ValueError(f"Duplicate zip entry name {name!r}.") + seen.add(name) + info = zipfile.ZipInfo(name, date_time=stamp) + info.create_system = 3 + info.compress_type = zipfile.ZIP_DEFLATED + mode = 0o755 if is_executable_path(relpath) else 0o644 + info.external_attr = (stat.S_IFREG | mode) << 16 + archive.writestr(info, content) + return buffer.getvalue() + + +def zip_project( + project_dir: str, root: str, *, date_time: Optional[DateTime] = None +) -> bytes: + """ + Zip every regular file under ``project_dir`` as ``/``. + + Entries are sorted by POSIX relpath and deflated; there are no directory + entries. Modes come from the file name, not from the file system, so + every platform (and Pyodide's in-memory file system) gives the same zip. + + :param project_dir: The generated project + :param root: Top-level folder inside the zip (the project name) + :param date_time: Entry timestamp; defaults to the local time now + :raises ValueError: For an unsafe entry name + """ + entries: list[tuple[str, bytes]] = [] + for current, _dirs, files in os.walk(project_dir): + for file_name in files: + path = os.path.join(current, file_name) + if os.path.islink(path) or not os.path.isfile(path): + continue + relpath = os.path.relpath(path, project_dir).replace(os.sep, "/") + with open(path, "rb") as f: + entries.append((relpath, f.read())) + return _zip_bytes(root, entries, date_time=date_time) + + +# ------------------------------------------------------------------ +# Building +# ------------------------------------------------------------------ + + +def _steps(steps: Iterable[Step]) -> list[dict[str, Any]]: + return [ + { + "id": step.id, + "text": step.text, + "commands": [ + {"text": command.text, "windows": command.windows} + for command in step.commands + ], + } + for step in steps + ] + + +def _sections(sections: Iterable[FeatureSection]) -> list[dict[str, Any]]: + return [ + { + "key": section.key, + "heading": section.heading, + "text": section.text, + "files": list(section.files), + "settings": list(section.settings), + "link": section.link, + } + for section in sections + ] + + +def build( + form: Mapping[str, Any], + lang: str = "en", + *, + secret_factory: SecretFactory, + date_time: Optional[DateTime] = None, + work_dir: Optional[str] = None, +) -> tuple[bytes, dict[str, Any]]: + """ + Generate the form's project and zip it. + + The project is generated into a fresh temporary directory (inside + ``work_dir`` when given), which is removed afterwards, also on failure. + + :param form: The form object + :param lang: Language of the next steps and feature sections + :param secret_factory: Source of ``SECRET_KEY`` values for ``.env`` + :param date_time: Zip entry timestamp (default: now) + :param work_dir: Directory for the temporary project + :return: ``(zip bytes, meta)``; meta keys: ``filename``, ``root``, + ``files``, ``command``, ``command_text`` (bash / zsh), + ``command_text_windows`` (PowerShell), ``next_steps``, ``next_steps_windows``, + ``feature_sections``, ``messages`` + :raises FormError: For an invalid form + :raises GenerationError: When the choice cannot be generated + (``ChoiceError`` for a rule error) or generation fails + """ + catalog = load_catalog(_language(lang)) + choice = choice_from_form(form) + spec = choice_spec(choice) + name = choice.project.name + scratch = tempfile.mkdtemp(prefix="fastkit-web-", dir=work_dir) + try: + project_dir = os.path.join(scratch, name) + result = generate(spec, project_dir, secret_factory=secret_factory) + archive = zip_project(project_dir, name, date_time=date_time) + finally: + shutil.rmtree(scratch, ignore_errors=True) + + with zipfile.ZipFile(io.BytesIO(archive)) as written: + files = [info.filename[len(name) + 1 :] for info in written.infolist()] + env_file: Literal["written", "absent"] = ( + "written" if _ENV_FILE in files else "absent" + ) + + def steps_for(windows: bool) -> list[dict[str, Any]]: + environment = Environment( + folder=name, venv="none", env_file=env_file, windows=windows + ) + return _steps(next_steps(result.facts, environment, catalog=catalog)) + + argv = command_line(choice) + meta: dict[str, Any] = { + "filename": f"{name}.zip", + "root": name, + "files": files, + "command": argv, + "command_text": shell_text(argv), + "command_text_windows": shell_text(argv, windows=True), + "next_steps": steps_for(False), + "next_steps_windows": steps_for(True), + "feature_sections": _sections(feature_sections(result.facts, catalog=catalog)), + "messages": [ + {"level": message.level, "text": message.text, "title": message.title} + for message in result.messages + ], + } + return archive, meta + + +# ------------------------------------------------------------------ +# JavaScript entry points +# ------------------------------------------------------------------ + + +def _parsed(form_json: str) -> Any: + try: + return json.loads(form_json) + except ValueError: + return None + + +def check_json(form_json: str, lang: str) -> str: + """:func:`check_form` with JSON in and out (invalid JSON is a ``form`` + problem).""" + return json.dumps(check_form(_parsed(form_json), lang), ensure_ascii=False) + + +def build_for_js( + form_json: str, lang: str, secret: Callable[[], str] +) -> tuple[bytes, str]: + """ + :func:`build` for the page's worker. + + :param form_json: The form as JSON + :param lang: Language of the next steps and feature sections + :param secret: Returns one ``SECRET_KEY`` value per call + :return: ``(zip bytes, meta JSON)``; meta has ``"ok": true`` and + :func:`build`'s keys, or ``"ok": false`` and ``"error": {"kind": + "form" | "generation", "message", "problems", "messages"}`` with + empty zip bytes. Other exceptions propagate (the page's + ``internal`` kind). + """ + try: + archive, meta = build( + _parsed(form_json), lang, secret_factory=lambda: str(secret()) + ) + except FormError as e: + error: dict[str, Any] = { + "kind": "form", + "message": str(e), + "problems": [problem.as_dict() for problem in e.problems], + "messages": [], + } + return b"", json.dumps({"ok": False, "error": error}, ensure_ascii=False) + except GenerationError as e: + error = { + "kind": "generation", + "message": str(e), + "problems": [], + "messages": [ + {"level": message.level, "text": message.text, "title": message.title} + for message in e.messages + ], + } + return b"", json.dumps({"ok": False, "error": error}, ensure_ascii=False) + return archive, json.dumps({"ok": True, **meta}, ensure_ascii=False) + + +__all__ = [ + "FORM_KEYS", + "FORM_SCHEMA", + "LIMITS", + "DateTime", + "FormError", + "FormProblem", + "build", + "build_for_js", + "check_form", + "check_json", + "choice_from_form", + "command_line", + "form_model", + "shell_text", + "zip_project", +] diff --git a/src/fastapi_fastkit/generation/dependencies.py b/src/fastapi_fastkit/generation/dependencies.py index 3add3406..68841dd8 100644 --- a/src/fastapi_fastkit/generation/dependencies.py +++ b/src/fastapi_fastkit/generation/dependencies.py @@ -42,8 +42,9 @@ 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.output import print_success from fastapi_fastkit.utils.textio import read_text_preserving_newlines +from fastapi_fastkit.utils.validation import sanitize_custom_packages #: Files that can hold a project's dependency declarations. DEPENDENCY_FILES: tuple[str, ...] = ( @@ -77,11 +78,6 @@ def classify(requirements: Iterable[str]) -> DependencySet: 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)) diff --git a/src/fastapi_fastkit/generation/levels.py b/src/fastapi_fastkit/generation/levels.py index 69f2a830..34004fb4 100644 --- a/src/fastapi_fastkit/generation/levels.py +++ b/src/fastapi_fastkit/generation/levels.py @@ -202,19 +202,20 @@ def _check_feature_keys(features: Mapping[str, Any]) -> None: raise ChoiceError(f"Unknown feature '{key}'. Allowed: {', '.join(allowed)}") -def effective_selection(choice: ProjectChoice) -> dict[str, FeatureValue]: +def raw_selection(choice: ProjectChoice) -> dict[str, FeatureValue]: """ - The selection a level choice generates: :func:`default_selection` with - the explicit answers applied and the catalog's ``implies`` rules - resolved (``docker-compose`` adds ``Docker``). An explicit + The selection a level choice asks for, before the catalog rules: + :func:`default_selection` with the explicit answers applied. An explicit ``migrations`` answer wins over the SQL adjustment. Multi axes are tuples in catalog order. + Evaluate it with :func:`fastapi_fastkit.catalog.evaluate` and a + translated catalog to get the rule errors and notes in another + language (the browser page does). + A template choice or a template level has no selection (``{}``). - :raises ChoiceError: For an unknown level, database or feature key, or - when a catalog ``requires`` rule fails (the rule messages joined by - ``" | "``) + :raises ChoiceError: For an unknown level, database or feature key """ if choice.template is not None and choice.level is None: return {} @@ -231,7 +232,25 @@ def effective_selection(choice: ProjectChoice) -> dict[str, FeatureValue]: for axis in catalog.axes: if axis.multi: selection[axis.id] = _multi_value(axis, selection[axis.id]) + return selection + + +def effective_selection(choice: ProjectChoice) -> dict[str, FeatureValue]: + """ + The selection a level choice generates: :func:`raw_selection` with the + catalog's ``implies`` rules resolved (``docker-compose`` adds + ``Docker``). Multi axes are tuples in catalog order. + + A template choice or a template level has no selection (``{}``). + :raises ChoiceError: For an unknown level, database or feature key, or + when a catalog ``requires`` rule fails (the rule messages joined by + ``" | "``) + """ + selection = raw_selection(choice) + if not selection: + return {} + catalog = _catalog() outcome = evaluate(selection, catalog) if outcome.errors: raise ChoiceError(" | ".join(outcome.errors)) @@ -608,6 +627,7 @@ def choice_from_config( "dropped_dependencies_warning", "effective_selection", "level_ids", + "raw_selection", "selection_notes", "uses_template_mode", ] diff --git a/src/fastapi_fastkit/generation/pipeline.py b/src/fastapi_fastkit/generation/pipeline.py index c3dca32c..2db316ef 100644 --- a/src/fastapi_fastkit/generation/pipeline.py +++ b/src/fastapi_fastkit/generation/pipeline.py @@ -76,8 +76,8 @@ 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 +from fastapi_fastkit.utils.output import print_info, print_success, print_warning from fastapi_fastkit.utils.textio import ( read_text_preserving_newlines, write_text_preserving_newlines, diff --git a/src/fastapi_fastkit/utils/config_file.py b/src/fastapi_fastkit/utils/config_file.py index 47d99016..5afd0830 100644 --- a/src/fastapi_fastkit/utils/config_file.py +++ b/src/fastapi_fastkit/utils/config_file.py @@ -20,15 +20,15 @@ import tomllib from typing import Any, Dict, List, Tuple -from fastapi_fastkit.backend.interactive.validators import ( - validate_email_format, - validate_project_name, -) from fastapi_fastkit.backend.project_builder.config_schema import ( ConfigSchemaError, normalize_project_config, validate_project_config_schema, ) +from fastapi_fastkit.utils.validation import ( + validate_email_format, + validate_project_name, +) JSON_EXTENSIONS: Tuple[str, ...] = (".json",) TOML_EXTENSIONS: Tuple[str, ...] = (".toml",) @@ -178,8 +178,8 @@ def validate_project_config( """ Validate a loaded configuration against the interactive-mode rules. - Reuses ``interactive.validators`` so a file-driven run is held to exactly - the same standard as an answered prompt. + Reuses the interactive validators (``utils.validation``) so a file-driven + run is held to exactly the same standard as an answered prompt. :param config: Configuration dictionary :param check_combinations: Also apply the feature combination rules; diff --git a/src/fastapi_fastkit/utils/logging.py b/src/fastapi_fastkit/utils/logging.py index cb70307c..2c44c2ed 100644 --- a/src/fastapi_fastkit/utils/logging.py +++ b/src/fastapi_fastkit/utils/logging.py @@ -13,9 +13,6 @@ from functools import lru_cache from typing import Dict, Optional -from rich.console import Console -from rich.logging import RichHandler - from fastapi_fastkit.core.settings import FastkitConfig @@ -107,6 +104,11 @@ def setup_logging( :param terminal_width: Optional terminal width for Rich console :return: DebugOutputCapture instance if debug mode is enabled, None otherwise """ + # Imported here: the generation path imports this module and must not + # load rich. + from rich.console import Console + from rich.logging import RichHandler + logger = logging.getLogger("fastapi-fastkit") console = Console(width=terminal_width) if terminal_width else None formatter = logging.Formatter("%(message)s") diff --git a/src/fastapi_fastkit/utils/main.py b/src/fastapi_fastkit/utils/main.py index 0cb38912..0d0a9ce5 100644 --- a/src/fastapi_fastkit/utils/main.py +++ b/src/fastapi_fastkit/utils/main.py @@ -5,7 +5,6 @@ # -------------------------------------------------------------------------- import os import re -import tomllib import traceback from typing import Any, Dict, Optional @@ -20,18 +19,30 @@ from fastapi_fastkit.utils.logging import debug_log, get_logger from fastapi_fastkit.utils.messages import emit -logger = get_logger(__name__) - -# Email validation regex pattern -REGEX = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b" +# Moved to ``utils.project_meta`` (no click/rich); re-exported for callers +# that import them from here. +from fastapi_fastkit.utils.project_meta import ( + FASTKIT_DESCRIPTION_MARKER as FASTKIT_DESCRIPTION_MARKER, +) +from fastapi_fastkit.utils.project_meta import ( + FASTKIT_TOOL_SECTION as FASTKIT_TOOL_SECTION, +) +from fastapi_fastkit.utils.project_meta import ( + _pyproject_marks_fastkit as _pyproject_marks_fastkit, +) +from fastapi_fastkit.utils.project_meta import ( + _pyproject_text_marks_fastkit as _pyproject_text_marks_fastkit, +) +from fastapi_fastkit.utils.project_meta import is_fastkit_project as is_fastkit_project +from fastapi_fastkit.utils.project_meta import ( + read_fastkit_metadata as read_fastkit_metadata, +) +from fastapi_fastkit.utils.validation import EMAIL_REGEX +logger = get_logger(__name__) -# Canonical identity markers used to distinguish FastAPI-fastkit-managed -# projects from unrelated FastAPI projects in the user workspace. Kept as -# module-level constants so templates, metadata injection, and detection -# logic all reference the same strings. -FASTKIT_DESCRIPTION_MARKER = "[FastAPI-fastkit templated]" -FASTKIT_TOOL_SECTION = "fastapi-fastkit" # the [tool.] table key +# Email validation regex pattern (defined in ``utils.validation``) +REGEX = EMAIL_REGEX def get_optimal_console_size() -> tuple[int, int]: @@ -282,119 +293,3 @@ def validate_email(ctx: Context, param: Any, value: Any) -> Any: print_error(f"Incorrect email address given: {e}") value = click.prompt(param.prompt) return validate_email(ctx, param, value) - - -def is_fastkit_project(project_dir: str) -> bool: - """ - Check if the project was created/managed by FastAPI-fastkit. - - Detection precedence (any single match is sufficient): - - 1. ``pyproject.toml`` with ``[tool.fastapi-fastkit].managed = true`` - (machine-readable marker; set by ``fastkit`` during project generation). - 2. ``pyproject.toml`` ``[project].description`` contains the - ``[FastAPI-fastkit templated]`` marker (case-insensitive). - 3. ``setup.py`` contains ``fastapi-fastkit`` (case-insensitive) — preserves - the legacy detection path for projects generated before the pyproject - marker existed. - - :param project_dir: Path to the project directory - :return: True if the project was created with fastkit, False otherwise - """ - if _pyproject_marks_fastkit(os.path.join(project_dir, "pyproject.toml")): - return True - - setup_py = os.path.join(project_dir, "setup.py") - if os.path.exists(setup_py): - try: - with open(setup_py, "r", encoding="utf-8") as f: - content = f.read() - if FASTKIT_TOOL_SECTION in content.lower(): - return True - except (OSError, UnicodeDecodeError): - pass - - return False - - -def _pyproject_marks_fastkit(pyproject_path: str) -> bool: - """Return True if ``pyproject.toml`` carries a FastAPI-fastkit marker. - - Tries structured TOML parsing first (authoritative), falling back to a - plain-text scan if the file is malformed so detection still works on - hand-edited or partially written pyproject files. - """ - if not os.path.exists(pyproject_path): - return False - - try: - with open(pyproject_path, "rb") as f: - data = tomllib.load(f) - except (OSError, tomllib.TOMLDecodeError, UnicodeDecodeError): - return _pyproject_text_marks_fastkit(pyproject_path) - - tool_section = data.get("tool", {}).get(FASTKIT_TOOL_SECTION, {}) - if isinstance(tool_section, dict) and tool_section.get("managed") is True: - return True - - description = data.get("project", {}).get("description", "") - if ( - isinstance(description, str) - and FASTKIT_DESCRIPTION_MARKER.lower() in description.lower() - ): - return True - - return False - - -def _pyproject_text_marks_fastkit(pyproject_path: str) -> bool: - """Fallback plain-text scan for malformed pyproject files.""" - try: - with open(pyproject_path, "r", encoding="utf-8") as f: - content = f.read().lower() - except (OSError, UnicodeDecodeError): - return False - - if f"[tool.{FASTKIT_TOOL_SECTION}]" in content: - return True - if FASTKIT_DESCRIPTION_MARKER.lower() in content: - return True - return False - - -def read_fastkit_metadata(project_dir: str) -> Dict[str, Any]: - """Read the ``[tool.fastapi-fastkit]`` block of a generated project. - - The block is the shared contract between generation (``init`` / - ``startdemo``) and the commands that operate on an existing project - (``runserver``, ``addroute``): it records the template, preset, - package manager, selected features and — most importantly — the - ``app_module`` entrypoint, so those commands no longer have to - re-derive the layout heuristically. - - :param project_dir: Path to the generated project directory - :return: The metadata mapping, or an empty dict when the project has no - readable ``pyproject.toml`` / no fastkit block. - """ - pyproject_path = os.path.join(project_dir, "pyproject.toml") - if not os.path.exists(pyproject_path): - return {} - - try: - with open(pyproject_path, "rb") as f: - data = tomllib.load(f) - except (OSError, tomllib.TOMLDecodeError, UnicodeDecodeError) as e: - debug_log( - f"Could not read fastkit metadata from {pyproject_path}: {e}", "warning" - ) - return {} - - tool_section = data.get("tool", {}) - if not isinstance(tool_section, dict): - return {} - - metadata = tool_section.get(FASTKIT_TOOL_SECTION, {}) - if not isinstance(metadata, dict): - return {} - - return dict(metadata) diff --git a/src/fastapi_fastkit/utils/messages.py b/src/fastapi_fastkit/utils/messages.py index 3ff03430..591ef6b4 100644 --- a/src/fastapi_fastkit/utils/messages.py +++ b/src/fastapi_fastkit/utils/messages.py @@ -3,8 +3,9 @@ # # 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 +# ``fastapi_fastkit.utils.output`` (click/rich-free, used by the generation +# path) and in ``fastapi_fastkit.utils.main`` (the rich renderer) 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). diff --git a/src/fastapi_fastkit/utils/output.py b/src/fastapi_fastkit/utils/output.py new file mode 100644 index 00000000..964f9927 --- /dev/null +++ b/src/fastapi_fastkit/utils/output.py @@ -0,0 +1,103 @@ +# -------------------------------------------------------------------------- +# Message helpers for code that also runs without a terminal. +# +# Same signatures as the ``print_*`` helpers in ``fastapi_fastkit.utils.main`` +# (minus the ``console`` argument). Each one hands its message to +# :func:`~fastapi_fastkit.utils.messages.emit` first; while generation +# captures messages it is recorded there and nothing else is imported. +# Otherwise the rich renderer in ``utils.main`` draws it, imported on first +# use, so importing this module never loads click or rich (the generation +# path and the browser build depend on that). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from typing import Optional + +from fastapi_fastkit.utils.logging import debug_log +from fastapi_fastkit.utils.messages import emit + + +def print_info(message: str, title: str = "Info") -> None: + """ + Show an info message, or record it while messages are captured. + + :param message: Info message to display + :param title: Title for the info panel + """ + if emit("info", message, title): + return + from fastapi_fastkit.utils import main + + main.print_info(message, title) + + +def print_success(message: str, title: str = "Success") -> None: + """ + Show a success message, or record it while messages are captured. + + :param message: Success message to display + :param title: Title for the success panel + """ + if emit("success", message, title): + return + from fastapi_fastkit.utils import main + + main.print_success(message, title) + + +def print_warning(message: str, title: str = "Warning") -> None: + """ + Show a warning message, or record it while messages are captured. + + :param message: Warning message to display + :param title: Title for the warning panel + """ + if emit("warning", message, title): + return + from fastapi_fastkit.utils import main + + main.print_warning(message, title) + + +def print_error( + message: str, title: str = "Error", show_traceback: bool = False +) -> None: + """ + Show an error message, or record it while messages are captured. + + :param message: Error message to display + :param title: Title for the error panel + :param show_traceback: Whether to show the stack trace in debug mode + """ + if emit("error", message, title): + return + from fastapi_fastkit.utils import main + + main.print_error(message, title, show_traceback=show_traceback) + + +def handle_exception(e: Exception, message: Optional[str] = None) -> None: + """ + Report an exception the way ``utils.main.handle_exception`` does. + + The message goes through :func:`print_error` (with the stack trace in + debug mode), so a captured run records it instead of drawing a panel. + + :param e: The exception that occurred + :param message: Optional custom error message + """ + error_msg = message or f"Error: {str(e)}" + + # Log exception for debugging purposes (internal logging) + debug_log(f"Exception occurred: {error_msg}", "error") + + print_error(error_msg, show_traceback=True) + + +__all__ = [ + "handle_exception", + "print_error", + "print_info", + "print_success", + "print_warning", +] diff --git a/src/fastapi_fastkit/utils/project_meta.py b/src/fastapi_fastkit/utils/project_meta.py new file mode 100644 index 00000000..83d1ca76 --- /dev/null +++ b/src/fastapi_fastkit/utils/project_meta.py @@ -0,0 +1,145 @@ +# -------------------------------------------------------------------------- +# Detection and metadata of fastkit-generated projects. +# +# Standard library only (no click/rich), so the generation path and the +# browser build can import it. ``fastapi_fastkit.utils.main`` re-exports +# these names for the code that imported them from there. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import tomllib +from typing import Any, Dict + +from fastapi_fastkit.utils.logging import debug_log +from fastapi_fastkit.utils.textio import read_text_preserving_newlines + +# Canonical identity markers used to distinguish FastAPI-fastkit-managed +# projects from unrelated FastAPI projects in the user workspace. Kept as +# module-level constants so templates, metadata injection, and detection +# logic all reference the same strings. +FASTKIT_DESCRIPTION_MARKER = "[FastAPI-fastkit templated]" +FASTKIT_TOOL_SECTION = "fastapi-fastkit" # the [tool.] table key + + +def is_fastkit_project(project_dir: str) -> bool: + """ + Check if the project was created/managed by FastAPI-fastkit. + + Detection precedence (any single match is sufficient): + + 1. ``pyproject.toml`` with ``[tool.fastapi-fastkit].managed = true`` + (machine-readable marker; set by ``fastkit`` during project generation). + 2. ``pyproject.toml`` ``[project].description`` contains the + ``[FastAPI-fastkit templated]`` marker (case-insensitive). + 3. ``setup.py`` contains ``fastapi-fastkit`` (case-insensitive) — preserves + the legacy detection path for projects generated before the pyproject + marker existed. + + :param project_dir: Path to the project directory + :return: True if the project was created with fastkit, False otherwise + """ + if _pyproject_marks_fastkit(os.path.join(project_dir, "pyproject.toml")): + return True + + setup_py = os.path.join(project_dir, "setup.py") + if os.path.exists(setup_py): + try: + content, _newline = read_text_preserving_newlines(setup_py) + if FASTKIT_TOOL_SECTION in content.lower(): + return True + except (OSError, UnicodeDecodeError): + pass + + return False + + +def _pyproject_marks_fastkit(pyproject_path: str) -> bool: + """Return True if ``pyproject.toml`` carries a FastAPI-fastkit marker. + + Tries structured TOML parsing first (authoritative), falling back to a + plain-text scan if the file is malformed so detection still works on + hand-edited or partially written pyproject files. + """ + if not os.path.exists(pyproject_path): + return False + + try: + with open(pyproject_path, "rb") as f: + data = tomllib.load(f) + except (OSError, tomllib.TOMLDecodeError, UnicodeDecodeError): + return _pyproject_text_marks_fastkit(pyproject_path) + + tool_section = data.get("tool", {}).get(FASTKIT_TOOL_SECTION, {}) + if isinstance(tool_section, dict) and tool_section.get("managed") is True: + return True + + description = data.get("project", {}).get("description", "") + if ( + isinstance(description, str) + and FASTKIT_DESCRIPTION_MARKER.lower() in description.lower() + ): + return True + + return False + + +def _pyproject_text_marks_fastkit(pyproject_path: str) -> bool: + """Fallback plain-text scan for malformed pyproject files.""" + try: + text, _newline = read_text_preserving_newlines(pyproject_path) + except (OSError, UnicodeDecodeError): + return False + + content = text.lower() + if f"[tool.{FASTKIT_TOOL_SECTION}]" in content: + return True + if FASTKIT_DESCRIPTION_MARKER.lower() in content: + return True + return False + + +def read_fastkit_metadata(project_dir: str) -> Dict[str, Any]: + """Read the ``[tool.fastapi-fastkit]`` block of a generated project. + + The block is the shared contract between generation (``init`` / + ``startdemo``) and the commands that operate on an existing project + (``runserver``, ``addroute``): it records the template, preset, + package manager, selected features and — most importantly — the + ``app_module`` entrypoint, so those commands no longer have to + re-derive the layout heuristically. + + :param project_dir: Path to the generated project directory + :return: The metadata mapping, or an empty dict when the project has no + readable ``pyproject.toml`` / no fastkit block. + """ + pyproject_path = os.path.join(project_dir, "pyproject.toml") + if not os.path.exists(pyproject_path): + return {} + + try: + with open(pyproject_path, "rb") as f: + data = tomllib.load(f) + except (OSError, tomllib.TOMLDecodeError, UnicodeDecodeError) as e: + debug_log( + f"Could not read fastkit metadata from {pyproject_path}: {e}", "warning" + ) + return {} + + tool_section = data.get("tool", {}) + if not isinstance(tool_section, dict): + return {} + + metadata = tool_section.get(FASTKIT_TOOL_SECTION, {}) + if not isinstance(metadata, dict): + return {} + + return dict(metadata) + + +__all__ = [ + "FASTKIT_DESCRIPTION_MARKER", + "FASTKIT_TOOL_SECTION", + "is_fastkit_project", + "read_fastkit_metadata", +] diff --git a/src/fastapi_fastkit/utils/validation.py b/src/fastapi_fastkit/utils/validation.py new file mode 100644 index 00000000..6cbad816 --- /dev/null +++ b/src/fastapi_fastkit/utils/validation.py @@ -0,0 +1,188 @@ +# -------------------------------------------------------------------------- +# Input validation shared by the CLI, config files and the generation path +# +# Provides validation functions for: +# - Package names +# - Project names +# - Email addresses +# - Feature compatibility checking +# +# Standard library and the catalog only (no click/rich), so the generation +# path and the browser build can import it. +# ``fastapi_fastkit.backend.interactive.validators`` re-exports these names. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import keyword +import re +from typing import Any, Dict, List, Literal, Optional, Tuple + +from fastapi_fastkit.catalog import evaluate, selection_from_config + +#: Email pattern used by every email check (``utils.main.REGEX`` is an alias). +EMAIL_REGEX = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b" + +#: Why a project name is rejected (see :func:`project_name_problem`). +ProjectNameProblem = Literal["empty", "characters", "digit", "keyword"] + + +def validate_package_name(package: str) -> bool: + """ + Validate package name format. + + Checks if the package name follows basic PyPI package naming conventions. + Does not validate existence on PyPI (that will be added in v1.2.1+). + + Args: + package: Package name to validate + + Returns: + True if format is valid, False otherwise + """ + if not package or not isinstance(package, str): + return False + + # Remove version specifiers and extras for validation + package_name = re.split(r"[<>=!\[]", package)[0].strip() + + # Basic package name pattern: letters, numbers, hyphens, underscores, dots + # Must start with letter or number + pattern = r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$" + + return bool(re.match(pattern, package_name)) + + +def project_name_problem(name: str) -> Optional[ProjectNameProblem]: + """ + Classify why a project name is rejected. + + The checks run in this order and the first failing one is returned: + ``"empty"`` (empty string), ``"characters"`` (anything other than + letters, digits, ``_`` and ``-``; letters as ``str.isalnum`` sees them), + ``"digit"`` (starts with a digit), ``"keyword"`` (a Python keyword). + + Args: + name: Project name to check + + Returns: + The problem code, or None when the name is valid + """ + if not name: + return "empty" + if not name.replace("_", "").replace("-", "").isalnum(): + return "characters" + if name[0].isdigit(): + return "digit" + if keyword.iskeyword(name): + return "keyword" + return None + + +def validate_project_name(name: str) -> Tuple[bool, Optional[str]]: + """ + Validate project name. + + Args: + name: Project name to validate + + Returns: + Tuple of (is_valid, error_message) + """ + problem = project_name_problem(name) + if problem is None: + return True, None + if problem == "empty": + return False, "Project name cannot be empty" + if problem == "characters": + return ( + False, + "Project name must contain only letters, numbers, hyphens, and underscores", + ) + if problem == "digit": + return False, "Project name cannot start with a number" + return False, f"Project name '{name}' is a Python keyword" + + +def validate_email_format(email: str) -> bool: + """ + Validate email address format using :data:`EMAIL_REGEX`. + + Args: + email: Email address to validate + + Returns: + True if format is valid, False otherwise + """ + if not email: + return False + + return bool(re.match(EMAIL_REGEX, email)) + + +def validate_feature_compatibility( + config: Dict[str, Any], +) -> Tuple[bool, Optional[str]]: + """ + Check compatibility between selected features. + + 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 + + Returns: + Tuple of (is_compatible, warning_or_error_message) + """ + 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 + + +def sanitize_custom_packages(packages: List[str]) -> List[str]: + """ + Clean and deduplicate custom package list. + + Args: + packages: List of package names (possibly with duplicates or empty strings) + + Returns: + Cleaned list of unique package names + """ + if not packages: + return [] + + # Remove empty strings and strip whitespace + cleaned = [pkg.strip() for pkg in packages if pkg and pkg.strip()] + + # Remove duplicates while preserving order + seen = set() + unique_packages = [] + for pkg in cleaned: + pkg_lower = pkg.lower() + if pkg_lower not in seen: + seen.add(pkg_lower) + unique_packages.append(pkg) + + # Validate each package name + valid_packages = [pkg for pkg in unique_packages if validate_package_name(pkg)] + + return valid_packages + + +__all__ = [ + "EMAIL_REGEX", + "ProjectNameProblem", + "project_name_problem", + "sanitize_custom_packages", + "validate_email_format", + "validate_feature_compatibility", + "validate_package_name", + "validate_project_name", +] diff --git a/tests/fixtures/web_generator/cases.json b/tests/fixtures/web_generator/cases.json new file mode 100644 index 00000000..c62ccf99 --- /dev/null +++ b/tests/fixtures/web_generator/cases.json @@ -0,0 +1,312 @@ +[ + { + "id": "01-hello", + "form": { + "schema": 1, + "project_name": "hello_app", + "level": "hello" + }, + "native": true, + "covers": "hello level, template mode" + }, + { + "id": "02-single-file", + "form": { + "schema": 1, + "project_name": "single_app", + "level": "single-file" + }, + "covers": "single-file template mode" + }, + { + "id": "03-layered", + "form": { + "schema": 1, + "project_name": "layered_app", + "level": "layered" + }, + "covers": "layered template mode" + }, + { + "id": "04-domain", + "form": { + "schema": 1, + "project_name": "domain_app", + "level": "domain" + }, + "native": true, + "covers": "domain template mode" + }, + { + "id": "05-production", + "form": { + "schema": 1, + "project_name": "prod_app", + "level": "production" + }, + "native": true, + "covers": "production bundle" + }, + { + "id": "06-domain-postgresql", + "form": { + "schema": 1, + "project_name": "domain_app", + "level": "domain", + "database": "PostgreSQL" + }, + "covers": "database axis, SQL items, sqlite-for-tests rule" + }, + { + "id": "07-domain-mysql", + "form": { + "schema": 1, + "project_name": "domain_app", + "level": "domain", + "database": "MySQL" + }, + "covers": "database axis, SQL items, sqlite-for-tests rule" + }, + { + "id": "08-domain-sqlite", + "form": { + "schema": 1, + "project_name": "domain_app", + "level": "domain", + "database": "SQLite" + }, + "native": true, + "covers": "database axis, SQL items, sqlite-for-tests rule" + }, + { + "id": "09-domain-mongodb", + "form": { + "schema": 1, + "project_name": "domain_app", + "level": "domain", + "database": "MongoDB" + }, + "covers": "database axis, SQL items, sqlite-for-tests rule" + }, + { + "id": "10-domain-redis", + "form": { + "schema": 1, + "project_name": "domain_app", + "level": "domain", + "database": "Redis" + }, + "covers": "database axis, SQL items, sqlite-for-tests rule" + }, + { + "id": "11-domain-none", + "form": { + "schema": 1, + "project_name": "domain_app", + "level": "domain", + "database": "None" + }, + "covers": "database axis, SQL items, sqlite-for-tests rule" + }, + { + "id": "12-single-file-sqlite", + "form": { + "schema": 1, + "project_name": "single_app", + "level": "single-file", + "database": "SQLite" + }, + "native": true, + "covers": "single-file settings split" + }, + { + "id": "13-layered-postgresql", + "form": { + "schema": 1, + "project_name": "layered_app", + "level": "layered", + "database": "PostgreSQL" + }, + "native": true, + "covers": "SQL items, classic layout" + }, + { + "id": "14-production-pip", + "form": { + "schema": 1, + "project_name": "prod_app", + "level": "production", + "customise": true, + "package_manager": "pip" + }, + "covers": "dependency files per package manager" + }, + { + "id": "15-production-pdm", + "form": { + "schema": 1, + "project_name": "prod_app", + "level": "production", + "customise": true, + "package_manager": "pdm" + }, + "covers": "dependency files per package manager" + }, + { + "id": "16-production-poetry", + "form": { + "schema": 1, + "project_name": "prod_app", + "level": "production", + "customise": true, + "package_manager": "poetry" + }, + "native": true, + "covers": "dependency files per package manager" + }, + { + "id": "17-production-sqlite", + "form": { + "schema": 1, + "project_name": "prod_app", + "level": "production", + "database": "SQLite" + }, + "covers": "migrations kept with SQLite" + }, + { + "id": "18-production-mongodb", + "form": { + "schema": 1, + "project_name": "prod_app", + "level": "production", + "database": "MongoDB" + }, + "covers": "bundled Alembic dropped for a non-SQL database" + }, + { + "id": "19-domain-everything", + "form": { + "schema": 1, + "project_name": "full_app", + "level": "domain", + "database": "PostgreSQL", + "customise": true, + "features": { + "authentication": "JWT", + "utilities": [ + "Rate-Limiting", + "WebSocket" + ], + "logging": "structured", + "monitoring": "OpenTelemetry", + "migrations": "Alembic", + "tooling": [ + "ruff", + "pre-commit", + "github-actions", + "makefile" + ], + "deployment": [ + "docker-compose" + ] + } + }, + "native": true, + "covers": "most fragments, docker-compose implies Docker" + }, + { + "id": "20-domain-sqlite-users-celery", + "form": { + "schema": 1, + "project_name": "tasks_app", + "level": "domain", + "database": "SQLite", + "customise": true, + "features": { + "authentication": "FastAPI-Users", + "async_tasks": "Celery", + "caching": "Redis" + } + }, + "covers": "requires rule passes, shared-redis note" + }, + { + "id": "21-layered-multi-axes", + "form": { + "schema": 1, + "project_name": "layered_app", + "level": "layered", + "customise": true, + "features": { + "testing": "Coverage", + "tooling": [ + "devcontainer" + ], + "deployment": [ + "Docker" + ] + } + }, + "covers": "multi axes, a touched axis left at its default" + }, + { + "id": "22-single-file-extra-packages", + "form": { + "schema": 1, + "project_name": "extra_app", + "level": "single-file", + "customise": true, + "extra_packages": [ + "orjson", + "httpx2>=0.1" + ] + }, + "native": true, + "covers": "--extra-package" + }, + { + "id": "23-domain-identity", + "form": { + "schema": 1, + "project_name": "identity_app", + "level": "domain", + "customise": true, + "author": "Zoë \"Q\" O'Brien", + "author_email": "zoe@example.com", + "description": "Reads $HOME and says hi!" + }, + "native": true, + "covers": "identity flags, shlex quoting fallback" + }, + { + "id": "24-hello-unicode-name", + "form": { + "schema": 1, + "project_name": "café_api", + "level": "hello" + }, + "native": true, + "covers": "UTF-8 zip names" + }, + { + "id": "25-hello-ko", + "form": { + "schema": 1, + "project_name": "hello_app", + "level": "hello" + }, + "lang": "ko", + "covers": "translated catalog never reaches the files" + }, + { + "id": "26-production-customise-untouched", + "form": { + "schema": 1, + "project_name": "prod_app", + "level": "production", + "customise": true + }, + "covers": "customise opened, nothing touched: same as case 05" + } +] diff --git a/tests/test_catalog/test_i18n.py b/tests/test_catalog/test_i18n.py index 8f1efc8e..4d4c7372 100644 --- a/tests/test_catalog/test_i18n.py +++ b/tests/test_catalog/test_i18n.py @@ -212,5 +212,5 @@ def test_strings_toml_parses_back_to_the_skeleton(self) -> None: 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",) +def test_every_docs_language_is_available() -> None: + assert available_languages() == ("en", "ko", "ja", "zh", "es", "fr", "de") diff --git a/tests/test_catalog/test_loader.py b/tests/test_catalog/test_loader.py index 298707c6..5e7eb8e3 100644 --- a/tests/test_catalog/test_loader.py +++ b/tests/test_catalog/test_loader.py @@ -47,8 +47,17 @@ 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") + def test_language_without_overlay_falls_back_to_english( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + monkeypatch.setattr( + loader_module, "_overlay_file", lambda lang: tmp_path / f"{lang}.toml" + ) + loader_module._load.cache_clear() + try: + catalog = load_catalog("ko") + finally: + loader_module._load.cache_clear() assert catalog.lang == "ko" assert catalog.axis("database").label == "Database" @@ -423,8 +432,8 @@ def test_error_names_the_entry(self, minimal_catalog_text: str) -> None: class TestLanguages: - def test_only_english_ships_in_stage_two(self) -> None: - assert loader_module.available_languages() == ("en",) + def test_every_docs_language_ships_an_overlay(self) -> None: + assert loader_module.available_languages() == LANGUAGES def test_invalid_overlay_toml_is_reported( self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path diff --git a/tests/test_catalog/test_overlays.py b/tests/test_catalog/test_overlays.py new file mode 100644 index 00000000..d8ae4108 --- /dev/null +++ b/tests/test_catalog/test_overlays.py @@ -0,0 +1,134 @@ +# -------------------------------------------------------------------------- +# Test cases for the shipped translation overlays (catalog/i18n/.toml) +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import tomllib +from typing import Any, Dict, Mapping, Tuple + +import pytest + +from fastapi_fastkit.catalog import ( + available_languages, + load_catalog, + translatable_strings, +) +from fastapi_fastkit.catalog.loader import LANGUAGES, resource_root + +Path = Tuple[str, ...] + +OVERLAY_LANGUAGES = LANGUAGES[1:] +ENGLISH = load_catalog() + + +def _flatten(table: Mapping[str, Any], prefix: Path = ()) -> Dict[Path, str]: + result: Dict[Path, str] = {} + for key, value in table.items(): + if isinstance(value, Mapping): + result.update(_flatten(value, prefix + (key,))) + else: + result[prefix + (key,)] = value + return result + + +ENGLISH_STRINGS = _flatten(translatable_strings(ENGLISH)) + +#: Texts that may equal the English text in every language: a proper name, +#: an acronym or a bare file name, none of which is translated. +ALLOWED_EVERYWHERE = frozenset( + { + ("levels", "hello", "label"), # the level's name, as typed in `--level` + ("concepts", "cors", "title"), # acronym + ("axes", "tooling", "options", "pre-commit", "summary"), # file name + ("axes", "tooling", "options", "github-actions", "summary"), # file name + ("axes", "tooling", "options", "devcontainer", "summary"), # file name + } +) + +#: Further texts that may equal English because the language uses the same +#: word (a loanword that FastAPI's own documentation does not translate). +_LOANWORDS: Dict[str, frozenset[Path]] = { + "es": frozenset( + {("concepts", "middleware", "title"), ("concepts", "websockets", "title")} + ), + "fr": frozenset( + { + ("concepts", "middleware", "title"), + ("concepts", "websockets", "title"), + ("levels", "production", "label"), + ("axes", "migrations", "label"), + } + ), + "de": frozenset( + { + ("concepts", "middleware", "title"), + ("concepts", "websockets", "title"), + ("axes", "caching", "label"), + ("axes", "monitoring", "label"), + ("axes", "logging", "label"), + ("axes", "deployment", "label"), + } + ), +} + + +def _overlay(lang: str) -> Dict[Path, str]: + text = resource_root().joinpath("i18n", f"{lang}.toml").read_bytes() + return _flatten(tomllib.loads(text.decode("utf-8"))) + + +def test_all_six_languages_are_available() -> None: + assert available_languages() == ("en",) + OVERLAY_LANGUAGES + assert len(OVERLAY_LANGUAGES) == 6 + + +@pytest.mark.parametrize("lang", OVERLAY_LANGUAGES) +class TestOverlay: + def test_loads_with_the_requested_language(self, lang: str) -> None: + catalog = load_catalog(lang) + + assert catalog.lang == lang + assert catalog.level("hello").description != "" + + def test_translates_every_string(self, lang: str) -> None: + overlay = _overlay(lang) + + assert set(overlay) == set(ENGLISH_STRINGS) + assert all(text.strip() for text in overlay.values()) + + def test_translated_catalog_matches_the_overlay(self, lang: str) -> None: + # Nothing is silently left in English by the loader. + translated = _flatten(translatable_strings(load_catalog(lang))) + + assert translated == _overlay(lang) + + def test_only_allowed_texts_equal_english(self, lang: str) -> None: + allowed = ALLOWED_EVERYWHERE | _LOANWORDS.get(lang, frozenset()) + overlay = _overlay(lang) + + same = {path for path, text in overlay.items() if text == ENGLISH_STRINGS[path]} + + assert same <= allowed, sorted(same - allowed) + + def test_placeholders_match_english(self, lang: str) -> None: + import string + + def names(text: str) -> set[str]: + return { + field + for _, field, _, _ in string.Formatter().parse(text) + if field is not None + } + + for path, text in _overlay(lang).items(): + assert names(text) == names(ENGLISH_STRINGS[path]), path + + def test_code_spans_and_urls_are_kept(self, lang: str) -> None: + import re + + pattern = re.compile(r"`[^`]*`|https?://[0-9A-Za-z./:_-]*[0-9A-Za-z/]") + for path, text in _overlay(lang).items(): + english = ENGLISH_STRINGS[path] + assert sorted(pattern.findall(text)) == sorted( + pattern.findall(english) + ), path diff --git a/tests/test_docs/__init__.py b/tests/test_docs/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_docs/test_web_generator_page.py b/tests/test_docs/test_web_generator_page.py new file mode 100644 index 00000000..db7a18ef --- /dev/null +++ b/tests/test_docs/test_web_generator_page.py @@ -0,0 +1,330 @@ +# -------------------------------------------------------------------------- +# Test cases for the web generator page files: the locale pages, the page +# strings, the JavaScript modules, the stylesheet and the mkdocs.yml entries. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import json +import re +from pathlib import Path +from typing import Dict, List, Set + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +DOCS = ROOT / "docs" +JS = DOCS / "js" +STRINGS = JS / "web-generator-strings" +CSS = DOCS / "css" / "web-generator.css" +LOCALES = ("en", "ko", "ja", "zh", "es", "fr", "de") +JS_FILES = ( + JS / "web-generator.mjs", + JS / "web-generator-worker.mjs", + JS / "web-generator-core.mjs", +) + +MOUNT_LINE = '
' +SCRIPT_LINE = '' +PLACEHOLDER = re.compile(r"\{(\w+)\}") + + +def _read(path: Path) -> str: + return path.read_text(encoding="utf-8") + + +def _pages() -> List[Path]: + return [ + DOCS / lang / "start" / "web-generator.md" + for lang in LOCALES + if (DOCS / lang / "start" / "web-generator.md").is_file() + ] + + +def _strings(path: Path) -> Dict[str, str]: + data = json.loads(_read(path)) + assert isinstance(data, dict) + return data + + +def _string_files() -> List[Path]: + return sorted(STRINGS.glob("*.json")) + + +def _strip_js_comments(source: str) -> str: + source = re.sub(r"/\*.*?\*/", "", source, flags=re.S) + return re.sub(r"(^|[^:\"'\\])//[^\n]*", r"\1", source) + + +# ------------------------------------------------------------------ +# Locale pages +# ------------------------------------------------------------------ + + +def test_english_page_exists() -> None: + assert (DOCS / "en" / "start" / "web-generator.md").is_file() + + +@pytest.mark.parametrize("page", _pages(), ids=lambda p: p.parts[-3]) +def test_page_has_mount_noscript_and_module_script(page: Path) -> None: + text = _read(page) + lines = text.splitlines() + assert text.startswith("---\nhide:\n - toc\n---\n") + assert lines.count(MOUNT_LINE) == 1 + assert lines.count(SCRIPT_LINE) == 1 + start = lines.index(MOUNT_LINE) + end = lines.index("
", start) + block = lines[start : end + 1] + # A blank line would end the raw HTML block in Markdown. + assert all(line.strip() for line in block) + inner = "\n".join(block) + assert inner.count("") == 1 + assert '' in inner + assert re.search(r'

[^<]+

', inner) + # Shown by the script when even its strings cannot be loaded; must stay + # hidden until then and needs no strings file. + failed = re.findall(r'', inner) + if page.parts[-3] == "en" or failed: + assert len(failed) == 1 + assert "fastkit init" in failed[0] + assert '
' in failed[0] + assert lines.index(SCRIPT_LINE) == end + 1 + # No inline event handlers. + assert not re.search(r"\son[a-z]+\s*=", text) + + +# ------------------------------------------------------------------ +# Strings +# ------------------------------------------------------------------ + + +def test_english_strings_are_non_empty_text() -> None: + english = _strings(STRINGS / "en.json") + assert english + for key, value in english.items(): + assert re.fullmatch(r"[a-z][a-z0-9_]*", key), key + assert isinstance(value, str) and value.strip(), key + + +@pytest.mark.parametrize("path", _string_files(), ids=lambda p: p.stem) +def test_every_strings_file_has_english_keys_and_placeholders(path: Path) -> None: + assert path.stem in LOCALES + english = _strings(STRINGS / "en.json") + strings = _strings(path) + assert set(strings) == set(english) + for key, text in english.items(): + assert isinstance(strings[key], str) and strings[key].strip(), key + assert set(PLACEHOLDER.findall(strings[key])) == set( + PLACEHOLDER.findall(text) + ), key + + +def test_strings_have_no_markup() -> None: + for path in _string_files(): + for key, text in _strings(path).items(): + assert "<" not in text and ">" not in text.replace(">=", ""), (path, key) + + +def test_ui_uses_exactly_the_english_keys() -> None: + english: Set[str] = set(_strings(STRINGS / "en.json")) + source = _strip_js_comments(_read(JS / "web-generator.mjs")) + called = set(re.findall(r"\bt\(\s*\"([a-z0-9_]+)\"", source)) + assert called, "no t() calls found" + assert called <= english, sorted(called - english) + literals = set(re.findall(r"\"([a-z][a-z0-9_]*)\"", source)) + unused = english - literals + assert not unused, sorted(unused) + + +# ------------------------------------------------------------------ +# JavaScript modules +# ------------------------------------------------------------------ + + +@pytest.mark.parametrize("path", JS_FILES, ids=lambda p: p.name) +def test_js_requests_stay_on_the_docs_site(path: Path) -> None: + source = _read(path) + assert not re.search(r"https?://", source), "absolute URL in " + path.name + assert not re.search(r"[\"'`]//", source), "protocol-relative URL in " + path.name + code = _strip_js_comments(source) + for match in re.finditer(r"\bimport\(\s*([^)]*)\)", code): + argument = match.group(1).strip() + assert argument.startswith(("assetsURL", '"node:')), argument + for match in re.finditer(r"\bnew Worker\(\s*([^;]*)", code): + assert match.group(1).startswith( + 'new URL("./' + ) and "import.meta.url" in match.group(1) + for match in re.finditer(r"\bfetch\(\s*([^,)]*)", code): + # fetch() only receives URLs built by the module (assetsURL, + # import.meta.url); never a literal. + assert re.fullmatch(r"[A-Za-z_]\w*", match.group(1).strip()), match.group(1) + for match in re.finditer(r"\bnew URL\(\s*([^)]*)\)", code): + argument = match.group(1) + assert re.match(r"\"(\./|\.\./|assets/|en\.json)|[A-Za-z_]", argument), argument + + +@pytest.mark.parametrize("path", JS_FILES, ids=lambda p: p.name) +def test_js_never_injects_html(path: Path) -> None: + code = _strip_js_comments(_read(path)) + for pattern in ( + "innerHTML", + "outerHTML", + "insertAdjacentHTML", + "document.write", + "eval(", + ): + assert pattern not in code, pattern + assert not re.search(r"setAttribute\(\s*\"on", code) + + +def test_core_module_has_no_dom_access() -> None: + code = _strip_js_comments(_read(JS / "web-generator-core.mjs")) + for name in ("document", "window", "self", "localStorage", "navigator"): + assert not re.search(r"\b%s\b" % name, code), name + for export in ( + "startGenerator", + "GeneratorError", + "makeSecret", + "sha256Hex", + "MANIFEST_SCHEMA", + ): + assert re.search( + r"export (async function|function|class|const) %s\b" % export, code + ), export + + +def test_worker_uses_the_core() -> None: + code = _read(JS / "web-generator-worker.mjs") + assert 'from "./web-generator-core.mjs"' in code + + +# ------------------------------------------------------------------ +# Stylesheet +# ------------------------------------------------------------------ + + +def test_stylesheet_is_scoped_and_themed() -> None: + css = re.sub(r"/\*.*?\*/", "", _read(CSS), flags=re.S) + # Drop keyframe bodies; their "selectors" are percentages. + css = re.sub(r"@keyframes[^{]*\{(?:[^{}]*\{[^{}]*\})*[^{}]*\}", "", css) + preludes = re.findall(r"([^{}]+)\{", css) + assert preludes + for prelude in preludes: + prelude = prelude.strip() + if prelude.startswith("@"): + continue + for selector in prelude.split(","): + assert ".fkg" in selector, selector + assert "prefers-reduced-motion" in css + assert '[data-md-color-scheme="slate"] .fkg' in css + # Colours come from Material's variables, except the error colour pair. + colours = re.findall(r"#[0-9a-fA-F]{3,8}\b", css) + assert len(colours) <= 2, colours + + +# ------------------------------------------------------------------ +# mkdocs.yml +# ------------------------------------------------------------------ + + +def _mkdocs() -> str: + return _read(ROOT / "mkdocs.yml") + + +def test_nav_lists_the_page_after_home() -> None: + lines = [line.rstrip() for line in _mkdocs().splitlines()] + home = lines.index(" - Home: index.md") + assert lines[home + 1] == " - Web Generator: start/web-generator.md" + + +def test_stylesheet_is_in_extra_css_and_script_is_not_global() -> None: + text = _mkdocs() + extra_css = text.split("extra_css:", 1)[1].split("extra_javascript:", 1)[0] + assert " - css/web-generator.css" in [ + line.rstrip() for line in extra_css.splitlines() + ] + extra_js = text.split("extra_javascript:", 1)[1] + assert "web-generator" not in extra_js + + +def test_every_locale_translates_the_nav_entry() -> None: + text = _mkdocs() + blocks = re.split(r"\n\s*- locale: ", text)[1:] + found = {} + for block in blocks: + locale = block.split(None, 1)[0] + match = re.search(r"^\s+Web Generator: (.+?)\s*$", block, flags=re.M) + found[locale] = match.group(1) if match else None + assert set(found) == set(LOCALES) + for locale in LOCALES[1:]: + assert found[locale] and found[locale] != "Web Generator", locale + + +# ------------------------------------------------------------------ +# Asset names shared with scripts/web_generator/build_assets.py +# ------------------------------------------------------------------ + + +def test_notice_link_names_the_file_build_assets_writes() -> None: + script = _read(ROOT / "scripts" / "web_generator" / "build_assets.py") + written = set(re.findall(r"\"(NOTICE\.[a-z]+)\"", script)) + assert len(written) == 1, written + linked = set( + re.findall( + r"assetsURL \+ \"(NOTICE\.[a-z]+)\"", _read(JS / "web-generator.mjs") + ) + ) + assert linked == written + + +# ------------------------------------------------------------------ +# Behaviour pinned in the UI source (review findings) +# ------------------------------------------------------------------ + + +def _method(source: str, name: str) -> str: + """The body of a class method ``name(...) {`` up to the next method.""" + match = re.search( + r"\n (?:async )?%s\([^)]*\) \{\n(.*?)\n \}\n" % name, source, flags=re.S + ) + assert match, name + return match.group(1) + + +def test_an_edit_invalidates_checks_in_flight() -> None: + source = _read(JS / "web-generator.mjs") + assert "this.checkSeq += 1" in _method(source, "scheduleCheck") + run_check = _method(source, "runCheck") + # runCheck uses the sequence of the edit that scheduled it and drops a + # result when the form changed since the request was sent. + assert "++this.checkSeq" not in run_check + assert "JSON.stringify(this.formData())" in run_check + + +def test_generate_builds_only_the_checked_form() -> None: + source = _read(JS / "web-generator.mjs") + assert "checkedCurrentForm()" in _method(source, "blockedReason") + generate = _method(source, "generate") + assert "const form = this.lastForm;" in generate + assert 'this.request("build", this.formData())' not in generate + + +def test_worker_crash_is_not_overwritten_by_late_rejections() -> None: + source = _read(JS / "web-generator.mjs") + crashed = _method(source, "workerCrashed") + assert crashed.index('this.phase = "failed"') < crashed.index("pending.reject") + assert 'this.phase !== "ready"' in _method(source, "generate") + assert 'this.phase === "ready"' in _method(source, "runCheck") + + +def test_windows_toggle_switches_the_command_box() -> None: + source = _read(JS / "web-generator.mjs") + show = _method(source, "showCommand") + assert "command_text_windows" in show and "command_text" in show + assert "this.commandCode.textContent" in _method(source, "copyCommand") + assert "this.showCommand()" in _method(source, "setWindows") + + +def test_core_keeps_the_package_loading_error() -> None: + code = _read(JS / "web-generator-core.mjs") + assert "errorCallback() {}" not in code + assert re.search(r"errorCallback\(message\)", code) diff --git a/tests/test_generation/test_browser.py b/tests/test_generation/test_browser.py new file mode 100644 index 00000000..1d16af83 --- /dev/null +++ b/tests/test_generation/test_browser.py @@ -0,0 +1,1195 @@ +# -------------------------------------------------------------------------- +# The web generator page's Python side (generation/browser.py): form +# parsing and problems, the form model, checks, the command line, the zip +# and the build entry points. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import io +import json +import os +import stat +import time +import zipfile +from pathlib import Path +from typing import Any, Dict, List, Optional + +import pytest + +from fastapi_fastkit import __version__ +from fastapi_fastkit.catalog import evaluate, load_catalog +from fastapi_fastkit.generation import ( + ChoiceError, + GenerationError, + ProjectChoice, + ProjectInfo, + browser, + choice_spec, + plan, + seeded_secret_factory, +) +from fastapi_fastkit.generation.levels import raw_selection +from fastapi_fastkit.utils import platform + +CATALOG = load_catalog() +STAMP = (2026, 12, 3, 10, 20, 30) + + +def form(**fields: Any) -> Dict[str, Any]: + """A form with a valid name; ``fields`` override or add keys.""" + return {"schema": 1, "project_name": "app", **fields} + + +def problems_of(data: Any) -> List[Dict[str, Any]]: + with pytest.raises(browser.FormError) as caught: + browser.choice_from_form(data) + return [problem.as_dict() for problem in caught.value.problems] + + +def codes(data: Any) -> List[tuple[str, str]]: + return [(problem["field"], problem["code"]) for problem in problems_of(data)] + + +# ------------------------------------------------------------------ form + + +def test_minimal_form_is_hello_with_defaults() -> None: + choice = browser.choice_from_form({"project_name": "app"}) + assert choice == ProjectChoice( + project=ProjectInfo(name="app"), level="hello", package_manager="uv" + ) + + +def test_customised_form_becomes_a_full_choice() -> None: + choice = browser.choice_from_form( + form( + level="domain", + database="SQLite", + customise=True, + features={ + "authentication": "JWT", + "tooling": ["makefile", "None", "ruff"], + "deployment": "Docker", + }, + package_manager="pdm", + author=" Jane Doe ", + author_email=" jane@example.com ", + description=" A demo ", + extra_packages=[" orjson ", "", "ORJSON", "httpx>=0.28"], + ) + ) + assert choice == ProjectChoice( + project=ProjectInfo("app", "Jane Doe", "jane@example.com", "A demo"), + level="domain", + database="SQLite", + features={ + "authentication": "JWT", + "tooling": ("ruff", "makefile"), + "deployment": ("Docker",), + }, + package_manager="pdm", + custom_packages=("orjson", "httpx>=0.28"), + ) + + +def test_closed_customise_ignores_the_customise_fields() -> None: + choice = browser.choice_from_form( + form( + level="production", + customise=False, + features={"colour": "red"}, + package_manager="conda", + author_email="not an email", + extra_packages=["bad pkg"], + ) + ) + assert choice.features is None + assert choice.package_manager == "uv" + assert choice.project == ProjectInfo("app") + assert choice.custom_packages == () + + +@pytest.mark.parametrize( + "data", + [None, [], "app", 3], + ids=["null", "list", "string", "number"], +) +def test_a_form_must_be_an_object(data: Any) -> None: + assert problems_of(data) == [ + {"field": "form", "code": "type", "params": {"expected": "object"}} + ] + + +def test_unknown_fields_and_schema() -> None: + assert codes(form(colour="red")) == [("colour", "unknown_field")] + assert problems_of(form(schema=2)) == [ + {"field": "schema", "code": "schema", "params": {"expected": "1"}} + ] + assert codes(form(schema=True)) == [("schema", "schema")] + assert browser.choice_from_form({"project_name": "app"}).level == "hello" + + +@pytest.mark.parametrize( + "name, code", + [ + (None, "empty"), + ("", "empty"), + ("my app", "characters"), + (" app", "characters"), + ("app/x", "characters"), + ("1app", "digit"), + ("class", "keyword"), + ("a" * 65, "too_long"), + (7, "type"), + ], +) +def test_project_name_problems(name: Any, code: str) -> None: + assert codes({"project_name": name}) == [("project_name", code)] + + +def test_project_name_problem_params() -> None: + assert problems_of({"project_name": "class"})[0]["params"] == {"name": "class"} + assert problems_of({"project_name": "a" * 65})[0]["params"] == {"max": "64"} + assert browser.choice_from_form({"project_name": "a" * 64}).project.name == "a" * 64 + assert browser.choice_from_form({"project_name": "café_api"}).project.name == ( + "café_api" + ) + + +def test_level_problems() -> None: + assert codes(form(level=5)) == [("level", "type")] + assert problems_of(form(level="expert")) == [ + {"field": "level", "code": "unknown_level", "params": {"level": "expert"}} + ] + # Fields that depend on the level are not judged against an unknown one. + assert codes( + form( + level="expert", + database="Oracle", + customise=True, + features={"authentication": "JWT"}, + extra_packages=["orjson"], + ) + ) == [("level", "unknown_level")] + + +def test_database_problems() -> None: + assert codes(form(level="domain", database=3)) == [("database", "type")] + assert problems_of(form(level="domain", database="Oracle")) == [ + { + "field": "database", + "code": "unknown_database", + "params": {"database": "Oracle"}, + } + ] + assert problems_of(form(level="hello", database="SQLite")) == [ + {"field": "database", "code": "not_offered", "params": {"level": "hello"}} + ] + assert ( + browser.choice_from_form(form(level="hello", database="None")).database is None + ) + assert ( + browser.choice_from_form(form(level="domain", database=None)).database is None + ) + assert browser.choice_from_form(form(level="domain", database="None")).database == ( + "None" + ) + + +def test_customise_must_be_a_boolean() -> None: + assert codes(form(customise="yes")) == [("customise", "type")] + assert codes(form(customise=1)) == [("customise", "type")] + assert browser.choice_from_form(form(customise=None)).package_manager == "uv" + + +@pytest.mark.parametrize( + "features, expected", + [ + ([], [("features", "type", {"expected": "object"})]), + ({"database": "SQLite"}, [("features", "unknown_axis", {"axis": "database"})]), + ({"colour": "red"}, [("features", "unknown_axis", {"axis": "colour"})]), + ( + {"authentication": ["JWT"]}, + [("features", "type", {"axis": "authentication", "expected": "string"})], + ), + ( + {"authentication": "Kerberos"}, + [ + ( + "features", + "unknown_option", + {"axis": "authentication", "option": "Kerberos"}, + ) + ], + ), + ( + {"tooling": {"ruff": True}}, + [("features", "type", {"axis": "tooling", "expected": "list"})], + ), + ( + {"tooling": ["ruff", 1]}, + [("features", "type", {"axis": "tooling", "expected": "list"})], + ), + ( + {"tooling": ["ruff", "black", "black"]}, + [("features", "unknown_option", {"axis": "tooling", "option": "black"})], + ), + ], + ids=[ + "not-object", + "database", + "unknown-axis", + "list-on-single", + "unknown-single", + "object-on-multi", + "non-string-item", + "unknown-multi", + ], +) +def test_feature_problems(features: Any, expected: List[Any]) -> None: + found = problems_of(form(level="domain", customise=True, features=features)) + assert [(p["field"], p["code"], p["params"]) for p in found] == expected + + +def test_features_on_hello() -> None: + assert problems_of( + form(level="hello", customise=True, features={"authentication": "JWT"}) + ) == [{"field": "features", "code": "not_offered", "params": {"level": "hello"}}] + choice = browser.choice_from_form( + form( + level="hello", + customise=True, + features={"authentication": "None", "tooling": ["None"], "utilities": []}, + ) + ) + assert choice.features is None + + +def test_multi_features_accept_built_in_options_and_a_single_string() -> None: + choice = browser.choice_from_form( + form( + level="layered", + customise=True, + features={"utilities": ["WebSocket", "CORS"], "deployment": "None"}, + ) + ) + assert choice.features == {"utilities": ("CORS", "WebSocket"), "deployment": ()} + + +def test_package_manager_problems() -> None: + assert codes(form(customise=True, package_manager=1)) == [ + ("package_manager", "type") + ] + assert problems_of(form(customise=True, package_manager="conda")) == [ + { + "field": "package_manager", + "code": "unknown_package_manager", + "params": {"package_manager": "conda"}, + } + ] + for manager in ("pip", "uv", "pdm", "poetry"): + choice = browser.choice_from_form(form(customise=True, package_manager=manager)) + assert choice.package_manager == manager + assert browser.choice_from_form(form(customise=True)).package_manager == "uv" + + +@pytest.mark.parametrize("key", ["author", "author_email", "description"]) +def test_identity_text_problems(key: str) -> None: + limit = browser.LIMITS[key] + assert problems_of(form(customise=True, **{key: "a" * (limit + 1)})) == [ + {"field": key, "code": "too_long", "params": {"max": str(limit)}} + ] + assert codes(form(customise=True, **{key: 5})) == [(key, "type")] + # Surrounding spaces do not count. + padded = " " * 10 + "x" * min(limit, 5) + " " * 10 + browser.choice_from_form( + form(customise=True, **{key: padded if key != "author_email" else ""}) + ) + + +def test_author_email_must_look_like_an_email() -> None: + assert problems_of(form(customise=True, author_email="jane")) == [ + {"field": "author_email", "code": "email", "params": {"email": "jane"}} + ] + assert browser.choice_from_form(form(customise=True, author_email="")).project == ( + ProjectInfo("app") + ) + + +def test_extra_package_problems() -> None: + domain = {"level": "domain", "customise": True} + assert codes(form(**domain, extra_packages="orjson")) == [ + ("extra_packages", "type") + ] + assert codes(form(**domain, extra_packages=["orjson", 1])) == [ + ("extra_packages", "type") + ] + assert problems_of(form(**domain, extra_packages=["bad pkg"])) == [ + {"field": "extra_packages", "code": "package", "params": {"package": "bad pkg"}} + ] + long_name = "a" * 101 + assert problems_of(form(**domain, extra_packages=[long_name])) == [ + { + "field": "extra_packages", + "code": "too_long", + "params": {"max": "100", "package": long_name}, + } + ] + many = [f"pkg{index}" for index in range(21)] + assert problems_of(form(**domain, extra_packages=many)) == [ + {"field": "extra_packages", "code": "too_many", "params": {"max": "20"}} + ] + assert browser.choice_from_form( + form(**domain, extra_packages=many[:20]) + ).custom_packages == tuple(many[:20]) + assert ( + browser.choice_from_form( + form(**domain, extra_packages=["", " "]) + ).custom_packages + == () + ) + + +@pytest.mark.parametrize( + "package", + [ + "requests>=1\nevil", + "requests>=1\revil", + "requests>=1\tevil", + "requests >=1", + "requests>=1 ; os_name=='nt'", + "requests\x00", + "requests>=1\x1b[0m", + "requests>=1\u2028evil", + ], + ids=[ + "newline", + "cr", + "tab", + "inner-space", + "marker-space", + "nul", + "escape", + "line-sep", + ], +) +def test_extra_packages_with_spaces_or_control_characters(package: str) -> None: + assert problems_of( + form(level="domain", customise=True, extra_packages=[f" {package} "]) + ) == [ + {"field": "extra_packages", "code": "package", "params": {"package": package}} + ] + + +def test_extra_packages_on_hello() -> None: + assert problems_of(form(customise=True, extra_packages=["orjson"])) == [ + {"field": "extra_packages", "code": "not_offered", "params": {"level": "hello"}} + ] + assert browser.choice_from_form(form(customise=True, extra_packages=[" "])) == ( + ProjectChoice(project=ProjectInfo("app"), level="hello") + ) + + +def test_every_problem_is_reported_at_once() -> None: + found = codes( + { + "project_name": "1app", + "level": "domain", + "database": "Oracle", + "customise": True, + "author_email": "jane", + "extra_packages": ["bad pkg"], + "colour": "red", + } + ) + assert sorted(found) == sorted( + [ + ("colour", "unknown_field"), + ("project_name", "digit"), + ("database", "unknown_database"), + ("author_email", "email"), + ("extra_packages", "package"), + ] + ) + + +def test_form_error_text_and_problem_dict() -> None: + error = browser.FormError( + [ + browser.FormProblem("project_name", "empty"), + browser.FormProblem("author_email", "email", {"email": "x"}), + ] + ) + assert isinstance(error, ValueError) + assert str(error) == "project_name: empty; author_email: email" + assert error.problems[1].as_dict() == { + "field": "author_email", + "code": "email", + "params": {"email": "x"}, + } + assert browser.FormProblem("level", "type").params == {} + + +# ------------------------------------------------------------ form model + + +@pytest.mark.parametrize("lang", ["en", "ko"]) +def test_form_model_shape(lang: str) -> None: + model = browser.form_model(lang) + catalog = load_catalog(lang) + assert json.loads(json.dumps(model, ensure_ascii=False)) == model + assert list(model) == [ + "schema", + "lang", + "fastkit_version", + "defaults", + "limits", + "levels", + "databases", + "axes", + "defaults_by", + "package_managers", + "guide", + ] + assert model["schema"] == browser.FORM_SCHEMA == 1 + assert model["lang"] == lang + assert model["fastkit_version"] == __version__ + assert model["defaults"] == {"level": "hello", "package_manager": "uv"} + assert model["limits"] == browser.LIMITS + + levels = {level["id"]: level for level in model["levels"]} + assert list(levels) == [level.id for level in catalog.levels] + assert levels["hello"] == { + "id": "hello", + "label": catalog.level("hello").label, + "description": catalog.level("hello").description, + "asks_database": False, + "has_features": False, + "default_database": None, + } + assert levels["production"]["default_database"] == "PostgreSQL" + assert levels["domain"]["default_database"] == "None" + assert levels["domain"]["has_features"] is True + + databases = model["databases"] + assert [db["id"] for db in databases] == list(catalog.axis("database").choice_ids) + assert {db["id"] for db in databases if db["sql"]} == { + "PostgreSQL", + "MySQL", + "SQLite", + } + + axes = {axis["id"]: axis for axis in model["axes"]} + assert "database" not in axes + assert model["axes"][-1]["id"] == "deployment" + utilities = axes["utilities"] + assert utilities["multi"] is True + assert [option["id"] for option in utilities["options"]] == [ + "Rate-Limiting", + "WebSocket", + ] + assert utilities["none"] == "None" + assert utilities["label"] == catalog.axis("utilities").label + assert utilities["none_label"] == catalog.axis("utilities").options[-1].label + assert axes["authentication"]["options"][0] == { + "id": "JWT", + "label": catalog.axis("authentication").option("JWT").label, + "summary": catalog.axis("authentication").option("JWT").summary, + } + + defaults_by = model["defaults_by"] + assert list(defaults_by) == ["single-file", "layered", "domain", "production"] + assert list(defaults_by["domain"]) == list(catalog.axis("database").choice_ids) + production = defaults_by["production"] + assert production["PostgreSQL"]["migrations"] == "Alembic" + assert production["MongoDB"]["migrations"] == "None" + assert production["PostgreSQL"]["deployment"] == ["Docker", "docker-compose"] + assert "database" not in production["SQLite"] + assert defaults_by["layered"]["None"]["tooling"] == [] + + assert [pm["id"] for pm in model["package_managers"]] == [ + manager.id for manager in catalog.package_managers + ] + assert model["guide"] == { + "next_steps": catalog.guide["next_steps"], + "same_in_readme": catalog.guide["same_in_readme"], + } + + +def test_unknown_language_reads_as_english() -> None: + assert browser.form_model("xx") == browser.form_model("en") + assert browser.check_form(form(), "xx") == browser.check_form(form(), "en") + + +# ----------------------------------------------------------------- check + + +def test_check_template_mode() -> None: + result = browser.check_form(form()) + choice = browser.choice_from_form(form()) + assert result["ok"] is True + assert result["problems"] == [] and result["rule_errors"] == [] + assert result["notes"] == [] + assert result["selection"] is None and result["implied"] == {} + assert result["template_mode"] is True + assert result["command"] == browser.command_line(choice) + assert result["command_text"] == browser.shell_text(result["command"]) + assert result["command_text_windows"] == browser.shell_text( + result["command"], windows=True + ) + assert result["identity_note"] is True + assert "main.py" in result["files"] + + +def test_check_files_equal_plan(tmp_path: Path) -> None: + data = form(level="domain", database="PostgreSQL") + result = browser.check_form(data) + spec = choice_spec(browser.choice_from_form(data)) + assert result["files"] == list(plan(spec, str(tmp_path / "app")).files) + assert result["template_mode"] is False + assert result["selection"]["database"] == "PostgreSQL" + + +def test_untouched_preset_level_is_template_mode() -> None: + result = browser.check_form(form(level="layered", customise=True, features={})) + assert result["ok"] and result["template_mode"] is True + assert result["selection"]["tooling"] == [] + + +def test_check_notes_implied_values_and_identity() -> None: + result = browser.check_form( + form( + level="domain", + database="SQLite", + customise=True, + features={ + "caching": "Redis", + "async_tasks": "Celery", + "deployment": ["docker-compose"], + }, + author="Jane", + author_email="jane@example.com", + ) + ) + assert result["ok"] + assert result["notes"] == [CATALOG.rule("shared-redis").message] + assert result["implied"] == {"deployment": ["Docker"]} + assert result["selection"]["deployment"] == ["Docker", "docker-compose"] + assert result["identity_note"] is False + assert "docker-compose.yml" in result["files"] + assert "--feature" in result["command"] + assert "deployment=docker-compose" in result["command"] + + +@pytest.mark.parametrize("lang", ["en", "ko"]) +def test_rule_errors_come_in_the_page_language(lang: str) -> None: + data = form( + level="domain", + database="MongoDB", + customise=True, + features={"authentication": "FastAPI-Users"}, + ) + result = browser.check_form(data, lang) + choice = browser.choice_from_form(data) + expected = evaluate(raw_selection(choice), load_catalog(lang)).errors + assert result["ok"] is False + assert result["rule_errors"] == list(expected) and expected + assert result["selection"]["authentication"] == "FastAPI-Users" + assert result["template_mode"] is None + assert result["files"] == [] + assert result["command"][-2:] == ["--no-venv", "-y"] + + +def test_check_reports_form_problems() -> None: + result = browser.check_form({"project_name": ""}) + assert result["ok"] is False + assert result["problems"] == [ + {"field": "project_name", "code": "empty", "params": {"name": ""}} + ] + assert result["command"] == [] and result["command_text"] == "" + assert result["command_text_windows"] == "" + + +def test_check_turns_generation_errors_into_rule_errors( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def broken_plan(*args: Any, **kwargs: Any) -> None: + raise GenerationError("template is broken") + + monkeypatch.setattr(browser, "plan", broken_plan) + result = browser.check_form(form()) + assert result["ok"] is False + assert result["rule_errors"] == ["template is broken"] + assert result["files"] == [] + + +# ---------------------------------------------------------- command line + + +def argv_for(**fields: Any) -> List[str]: + return browser.command_line(browser.choice_from_form(form(**fields))) + + +def test_command_for_hello() -> None: + assert argv_for() == [ + "init", + "--project-name", + "app", + "--level", + "hello", + "--package-manager", + "uv", + "--no-venv", + "-y", + ] + + +def test_command_database_flag() -> None: + assert "--database" not in argv_for(level="production") + assert "--database" not in argv_for(level="production", database="PostgreSQL") + assert "--database" not in argv_for(level="domain", database="None") + argv = argv_for(level="production", database="SQLite") + assert argv[argv.index("--database") + 1] == "SQLite" + argv = argv_for(level="production", database="None") + assert argv[argv.index("--database") + 1] == "None" + + +def feature_flags(argv: List[str]) -> List[str]: + return [argv[i + 1] for i, arg in enumerate(argv) if arg == "--feature"] + + +def test_command_feature_flags() -> None: + # Untouched or touched with the default value: no flag. + assert feature_flags(argv_for(level="production", customise=True)) == [] + assert ( + feature_flags( + argv_for( + level="layered", + customise=True, + features={"testing": "Coverage", "tooling": []}, + ) + ) + == [] + ) + # Different values, in catalog axis order, multi values in catalog order. + assert feature_flags( + argv_for( + level="domain", + customise=True, + features={ + "deployment": ["docker-compose"], + "tooling": ["makefile", "ruff"], + "authentication": "JWT", + }, + ) + ) == ["authentication=JWT", "tooling=ruff,makefile", "deployment=docker-compose"] + # An emptied multi axis and a removed single axis say None. + assert feature_flags( + argv_for( + level="production", + customise=True, + features={"tooling": [], "authentication": "None"}, + ) + ) == ["authentication=None", "tooling=None"] + + +def test_command_compares_with_the_database_defaults() -> None: + # production + MongoDB drops Alembic by default; asking for it is a flag. + assert feature_flags(argv_for(level="production", database="MongoDB")) == [] + assert feature_flags( + argv_for( + level="production", + database="MongoDB", + customise=True, + features={"migrations": "Alembic"}, + ) + ) == ["migrations=Alembic"] + + +def test_command_extra_packages_and_identity() -> None: + argv = argv_for( + level="single-file", + customise=True, + package_manager="pip", + extra_packages=["orjson", "httpx2>=0.1"], + author="Jane Doe", + author_email="jane@example.com", + description="A demo", + ) + assert argv == [ + "init", + "--project-name", + "app", + "--level", + "single-file", + "--package-manager", + "pip", + "--extra-package", + "orjson", + "--extra-package", + "httpx2>=0.1", + "--author", + "Jane Doe", + "--author-email", + "jane@example.com", + "--description", + "A demo", + "--no-venv", + "-y", + ] + only_author = argv_for(customise=True, author="Jane") + assert "--author" in only_author + assert "--author-email" not in only_author and "--description" not in only_author + + +def test_command_for_a_template_choice() -> None: + choice = ProjectChoice( + project=ProjectInfo("app", author="Jane"), + template="fastapi-sqlmodel", + package_manager="pdm", + ) + assert browser.command_line(choice) == [ + "init", + "--project-name", + "app", + "--template", + "fastapi-sqlmodel", + "--package-manager", + "pdm", + "--author", + "Jane", + "--no-venv", + "-y", + ] + + +#: value -> (bash / zsh form, PowerShell form) +QUOTING = [ + ("plain", "plain", "plain"), + ("tooling=ruff,pre-commit", "tooling=ruff,pre-commit", "'tooling=ruff,pre-commit'"), + ("jane@example.com", "jane@example.com", "'jane@example.com'"), + ("C:/x.y+z", "C:/x.y+z", "C:/x.y+z"), + ("httpx2>=0.1", '"httpx2>=0.1"', "'httpx2>=0.1'"), + ("Jane Doe", '"Jane Doe"', "'Jane Doe'"), + ("O'Brien", '"O\'Brien"', "'O''Brien'"), + ('Zoë "Q"', "'Zoë \"Q\"'", "'Zoë \"Q\"'"), + ('Zoë "Q" O\'Brien', "'Zoë \"Q\" O'\"'\"'Brien'", "'Zoë \"Q\" O''Brien'"), + ("it\u2019s", '"it\u2019s"', "'it\u2019\u2019s'"), + ("Reads $HOME", "'Reads $HOME'", "'Reads $HOME'"), + ("%USERNAME%", '"%USERNAME%"', "'%USERNAME%'"), + ("a`b`", "'a`b`'", "'a`b`'"), + ("a&b", '"a&b"', "'a&b'"), + ("a|b;c(d)", '"a|b;c(d)"', "'a|b;c(d)'"), + ("x^y", '"x^y"', "'x^y'"), + ("@splat", "@splat", "'@splat'"), + ("hi!", "'hi!'", "'hi!'"), + ("C:\\x", "'C:\\x'", "'C:\\x'"), + ("", '""', "''"), + ("café_api", '"café_api"', "'café_api'"), + ("프로젝트", '"프로젝트"', "'프로젝트'"), +] + + +@pytest.mark.parametrize( + "value, posix, powershell", QUOTING, ids=[str(i) for i in range(len(QUOTING))] +) +def test_shell_text_quoting(value: str, posix: str, powershell: str) -> None: + argv = ["init", "--author", value] + assert browser.shell_text(argv) == f"fastkit init --author {posix}" + assert browser.shell_text(argv, windows=True) == ( + f"fastkit init --author {powershell}" + ) + + +@pytest.mark.parametrize("value, posix, powershell", QUOTING) +def test_posix_form_reads_back_with_shlex( + value: str, posix: str, powershell: str +) -> None: + import shlex + + assert shlex.split(browser.shell_text(["--author", value])) == [ + "fastkit", + "--author", + value, + ] + + +def test_bare_values_carry_no_shell_specials() -> None: + specials = set("%^&|<>()!$`'\"\\;#{}[]*?~ ") + for value in ("ab" + char for char in specials): + assert browser.shell_text([value]) != f"fastkit {value}", value + assert browser.shell_text([value], windows=True) != f"fastkit {value}", value + + +# ------------------------------------------------------------------- zip + + +def make_tree(root: Path, files: Dict[str, bytes]) -> None: + for relpath, content in files.items(): + path = root.joinpath(*relpath.split("/")) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + + +def read_zip(data: bytes) -> List[zipfile.ZipInfo]: + with zipfile.ZipFile(io.BytesIO(data)) as archive: + assert archive.testzip() is None + return archive.infolist() + + +def test_zip_project_names_order_modes_and_time(tmp_path: Path) -> None: + files = { + "src/main.py": b"print('hi')\n", + "scripts/test.sh": b"#!/bin/sh\n", + ".env": b"SECRET_KEY=x\n", + "README.md": "café\n".encode("utf-8"), + "a/b/c/deep.txt": b"deep", + } + make_tree(tmp_path / "proj", files) + (tmp_path / "proj" / "empty_dir").mkdir() + data = browser.zip_project(str(tmp_path / "proj"), "café_api", date_time=STAMP) + infos = read_zip(data) + names = [info.filename for info in infos] + assert names == sorted(f"café_api/{relpath}" for relpath in files) + with zipfile.ZipFile(io.BytesIO(data)) as archive: + for relpath, content in files.items(): + assert archive.read(f"café_api/{relpath}") == content + for info in infos: + mode = info.external_attr >> 16 + assert stat.S_ISREG(mode) + expected = 0o755 if info.filename.endswith(".sh") else 0o644 + assert stat.S_IMODE(mode) == expected + assert info.date_time == STAMP + assert info.create_system == 3 + assert info.compress_type == zipfile.ZIP_DEFLATED + assert info.flag_bits & 0x800 or info.filename.isascii() + + +def test_zip_modes_come_from_names_not_the_file_system(tmp_path: Path) -> None: + make_tree(tmp_path / "proj", {"run.sh": b"x", "tool": b"y"}) + if not platform.is_windows(): + os.chmod(tmp_path / "proj" / "run.sh", 0o600) + os.chmod(tmp_path / "proj" / "tool", 0o755) + infos = read_zip(browser.zip_project(str(tmp_path / "proj"), "p", date_time=STAMP)) + modes = {info.filename: stat.S_IMODE(info.external_attr >> 16) for info in infos} + assert modes == {"p/run.sh": 0o755, "p/tool": 0o644} + + +@pytest.mark.skipif(platform.is_windows(), reason="symlinks need privileges on Windows") +def test_zip_skips_symlinks(tmp_path: Path) -> None: + make_tree(tmp_path / "proj", {"real.txt": b"x"}) + os.symlink(tmp_path / "proj" / "real.txt", tmp_path / "proj" / "link.txt") + infos = read_zip(browser.zip_project(str(tmp_path / "proj"), "p", date_time=STAMP)) + assert [info.filename for info in infos] == ["p/real.txt"] + + +def test_zip_time_defaults_to_now(monkeypatch: pytest.MonkeyPatch) -> None: + now = time.struct_time((2027, 1, 2, 3, 4, 6, 5, 2, 0)) + monkeypatch.setattr(browser.time, "localtime", lambda *args: now) + infos = read_zip(browser._zip_bytes("p", [("a.txt", b"x")])) + assert infos[0].date_time == (2027, 1, 2, 3, 4, 6) + + +@pytest.mark.parametrize( + "root, relpath, reason", + [ + ("p", "../x", "segment"), + ("p", "a/../b", "segment"), + ("p", "a//b", "segment"), + ("p", "./a", "segment"), + ("p", "a/", "segment"), + ("", "abs", "absolute"), + ("C:", "x", "drive letter"), + ("p", "a\\b", "backslash"), + ("p", "a\0b", "NUL"), + ("..", "x", "segment"), + ], +) +def test_zip_refuses_unsafe_names(root: str, relpath: str, reason: str) -> None: + with pytest.raises(ValueError, match=reason): + browser._zip_bytes(root, [(relpath, b"x")], date_time=STAMP) + + +def test_zip_refuses_names_outside_the_root_and_duplicates() -> None: + with pytest.raises(ValueError, match="not inside 'p/'"): + browser._check_entry_name("q/x", "p") + with pytest.raises(ValueError, match="not inside"): + browser._check_entry_name("x", "") + browser._check_entry_name("p/x/y.txt", "p") + with pytest.raises(ValueError, match="Duplicate"): + browser._zip_bytes("p", [("a", b"1"), ("a", b"2")], date_time=STAMP) + + +def test_zip_project_refuses_a_backslash_file_name(tmp_path: Path) -> None: + if platform.is_windows(): + pytest.skip("a backslash is a separator on Windows") + make_tree(tmp_path / "proj", {"a\\b.txt": b"x"}) + with pytest.raises(ValueError, match="backslash"): + browser.zip_project(str(tmp_path / "proj"), "p", date_time=STAMP) + + +# ----------------------------------------------------------------- build + + +def env_secret(data: bytes, name: str) -> Optional[str]: + with zipfile.ZipFile(io.BytesIO(data)) as archive: + text = archive.read(f"{name}/.env").decode("utf-8") + for line in text.splitlines(): + if line.startswith("SECRET_KEY="): + return line.split("=", 1)[1] + return None + + +def test_build_hello(tmp_path: Path) -> None: + data, meta = browser.build( + form(), + secret_factory=seeded_secret_factory("s"), + date_time=STAMP, + work_dir=str(tmp_path), + ) + assert os.listdir(tmp_path) == [] + assert list(meta) == [ + "filename", + "root", + "files", + "command", + "command_text", + "command_text_windows", + "next_steps", + "next_steps_windows", + "feature_sections", + "messages", + ] + assert meta["filename"] == "app.zip" and meta["root"] == "app" + assert meta["files"] == [info.filename[4:] for info in read_zip(data)] + assert meta["files"] == browser.check_form(form())["files"] + assert ".env" not in meta["files"] + assert meta["feature_sections"] == [] + steps = meta["next_steps"] + assert steps[0] == { + "id": "open", + "text": CATALOG.guide["open"], + "commands": [{"text": "cd app", "windows": None}], + } + ids = [step["id"] for step in steps] + assert "env" not in ids and "run" in ids + assert [step["id"] for step in meta["next_steps_windows"]] == ids + assert all( + set(message) == {"level", "text", "title"} for message in meta["messages"] + ) + + +def test_build_features_mode_uses_the_secret_factory(tmp_path: Path) -> None: + data, meta = browser.build( + form(level="production"), + secret_factory=seeded_secret_factory("seed"), + date_time=STAMP, + work_dir=str(tmp_path), + ) + assert env_secret(data, "app") == seeded_secret_factory("seed")() + assert ".env" in meta["files"] + env_step = next(step for step in meta["next_steps"] if step["id"] == "env") + assert env_step["text"] == CATALOG.guide["env_written"] + keys = [section["key"] for section in meta["feature_sections"]] + assert "database:PostgreSQL" in keys and "deployment:docker-compose" in keys + section = meta["feature_sections"][0] + assert set(section) == {"key", "heading", "text", "files", "settings", "link"} + assert isinstance(section["files"], list) + modes = { + info.filename: stat.S_IMODE(info.external_attr >> 16) for info in read_zip(data) + } + assert all( + mode == (0o755 if name.endswith(".sh") else 0o644) + for name, mode in modes.items() + ) + + +def test_build_texts_follow_the_language(tmp_path: Path) -> None: + _, meta = browser.build( + form(level="domain", database="SQLite"), + "ko", + secret_factory=seeded_secret_factory("s"), + work_dir=str(tmp_path), + ) + ko = load_catalog("ko") + assert meta["next_steps"][0]["text"] == ko.guide["open"] + assert meta["feature_sections"][0]["heading"].startswith(ko.axis("database").label) + + +def test_build_without_work_dir_cleans_up(monkeypatch: pytest.MonkeyPatch) -> None: + created: List[str] = [] + real = browser.tempfile.mkdtemp + + def recording(*args: Any, **kwargs: Any) -> str: + path = real(*args, **kwargs) + created.append(path) + return path + + monkeypatch.setattr(browser.tempfile, "mkdtemp", recording) + browser.build(form(), secret_factory=seeded_secret_factory("s")) + assert len(created) == 1 and not os.path.exists(created[0]) + + +def test_build_removes_the_work_dir_on_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def failing(spec: Any, target: str, **kwargs: Any) -> None: + os.makedirs(target) + Path(target, "half.txt").write_text("x", encoding="utf-8") + raise GenerationError("disk full") + + monkeypatch.setattr(browser, "generate", failing) + with pytest.raises(GenerationError, match="disk full"): + browser.build( + form(), secret_factory=seeded_secret_factory("s"), work_dir=str(tmp_path) + ) + assert os.listdir(tmp_path) == [] + + +def test_build_refuses_bad_forms_and_rule_errors(tmp_path: Path) -> None: + with pytest.raises(browser.FormError): + browser.build({"project_name": ""}, secret_factory=seeded_secret_factory("s")) + with pytest.raises(ChoiceError, match="FastAPI-Users"): + browser.build( + form( + level="domain", + database="MongoDB", + customise=True, + features={"authentication": "FastAPI-Users"}, + ), + secret_factory=seeded_secret_factory("s"), + work_dir=str(tmp_path), + ) + assert os.listdir(tmp_path) == [] + + +# --------------------------------------------------------------- JS side + + +def test_check_json_round_trip() -> None: + data = form(level="domain", customise=True, features={"authentication": "JWT"}) + text = browser.check_json(json.dumps(data), "en") + assert json.loads(text) == browser.check_form(data, "en") + assert "\\u" not in browser.check_json(json.dumps(form(project_name="café")), "en") + + +def test_check_json_with_invalid_json() -> None: + result = json.loads(browser.check_json("{not json", "en")) + assert result["ok"] is False + assert result["problems"] == [ + {"field": "form", "code": "type", "params": {"expected": "object"}} + ] + + +def test_build_for_js_success() -> None: + calls: List[int] = [] + + def secret() -> str: + calls.append(1) + return "s" * 43 + + data, meta_json = browser.build_for_js( + json.dumps(form(level="domain", database="SQLite")), "en", secret + ) + meta = json.loads(meta_json) + assert meta["ok"] is True + assert meta["root"] == "app" + assert meta["files"] == [info.filename[4:] for info in read_zip(data)] + assert env_secret(data, "app") == "s" * 43 + assert calls + + +def test_build_for_js_form_error() -> None: + data, meta_json = browser.build_for_js( + json.dumps({"project_name": "1x"}), "en", str + ) + assert data == b"" + meta = json.loads(meta_json) + assert meta == { + "ok": False, + "error": { + "kind": "form", + "message": "project_name: digit", + "problems": [ + {"field": "project_name", "code": "digit", "params": {"name": "1x"}} + ], + "messages": [], + }, + } + + +def test_build_for_js_generation_error(monkeypatch: pytest.MonkeyPatch) -> None: + data, meta_json = browser.build_for_js( + json.dumps( + form( + level="domain", + database="MongoDB", + customise=True, + features={"authentication": "FastAPI-Users"}, + ) + ), + "en", + str, + ) + assert data == b"" + error = json.loads(meta_json)["error"] + assert error["kind"] == "generation" and "FastAPI-Users" in error["message"] + assert error["problems"] == [] and error["messages"] == [] + + from fastapi_fastkit.utils.messages import Message + + def failing(*args: Any, **kwargs: Any) -> None: + raise GenerationError("broken", [Message("warning", "careful", "Warning")]) + + monkeypatch.setattr(browser, "generate", failing) + _, meta_json = browser.build_for_js(json.dumps(form()), "en", str) + assert json.loads(meta_json)["error"]["messages"] == [ + {"level": "warning", "text": "careful", "title": "Warning"} + ] + + +# ---------------------------------------------------------- import guard + + +def test_browser_imports_only_the_browser_safe_modules() -> None: + """The module runs in Pyodide: stdlib, the catalog, the generation layer + and the two stdlib-only utils.""" + import ast + + path = Path(browser.__file__) + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + allowed_stdlib = { + "dataclasses", + "io", + "json", + "os", + "re", + "shlex", + "shutil", + "stat", + "tempfile", + "time", + "typing", + "zipfile", + } + allowed = ( + "fastapi_fastkit.catalog", + "fastapi_fastkit.generation", + "fastapi_fastkit.utils.validation", + "fastapi_fastkit.utils.filemodes", + ) + imported: List[str] = [] + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported.extend(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + assert node.level == 0 + imported.append(node.module or "") + offenders = [ + name + for name in imported + if name not in allowed_stdlib + and name != "fastapi_fastkit" + and not any(name == p or name.startswith(p + ".") for p in allowed) + ] + assert imported and offenders == [] diff --git a/tests/test_generation/test_browser_parity.py b/tests/test_generation/test_browser_parity.py new file mode 100644 index 00000000..03778b01 --- /dev/null +++ b/tests/test_generation/test_browser_parity.py @@ -0,0 +1,201 @@ +# -------------------------------------------------------------------------- +# The web generator's zip equals ``fastkit init ``. +# +# For the cases of ``tests/fixtures/web_generator/cases.json`` marked +# ``"native": true``, ``browser.build`` (natively, not in Pyodide) is +# compared with the CLI run of the command line the page shows: file set, +# bytes (``.env`` SECRET_KEY values masked after a shape check), modes, +# zip hygiene and the next steps. The Pyodide side of the same comparison +# runs in CI (scripts/web_generator/compare_with_cli.py) for every case. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import io +import json +import os +import re +import stat +import tomllib +import zipfile +from dataclasses import replace +from pathlib import Path +from typing import Any, Dict, List + +import pytest +from click.testing import CliRunner + +from fastapi_fastkit.cli import fastkit_cli +from fastapi_fastkit.commands import init as init_command +from fastapi_fastkit.generation import browser, seeded_secret_factory +from fastapi_fastkit.generation.guide import next_steps +from fastapi_fastkit.utils import platform +from fastapi_fastkit.utils.filemodes import is_executable_path + +CASES_FILE = ( + Path(__file__).resolve().parents[1] / "fixtures" / "web_generator" / "cases.json" +) +CASES: List[Dict[str, Any]] = json.loads(CASES_FILE.read_text(encoding="utf-8")) +NATIVE = [case for case in CASES if case.get("native")] + +#: ``SECRET_KEY=`` lines (as backend/main.py writes them) and the value shape. +SECRET_LINE = re.compile(rb"^([ \t]*(?:export[ \t]+)?SECRET_KEY[ \t]*=)(.*)$", re.M) +SECRET_VALUE = re.compile(rb"[A-Za-z0-9_-]{43}") + + +def masked_env(content: bytes) -> bytes: + """``.env`` with every SECRET_KEY value replaced, after checking its shape.""" + + def mask(match: "re.Match[bytes]") -> bytes: + assert SECRET_VALUE.fullmatch(match.group(2)), match.group(0) + return match.group(1) + b"" + + masked, count = SECRET_LINE.subn(mask, content) + assert count >= 1 + return masked + + +def regular_files(root: Path) -> Dict[str, Path]: + """POSIX relpath -> path of every regular file under ``root``.""" + found: Dict[str, Path] = {} + for current, _dirs, files in os.walk(root): + for name in files: + path = Path(current) / name + if path.is_file() and not path.is_symlink(): + found[path.relative_to(root).as_posix()] = path + return found + + +def run_cli(workspace: Path, argv: List[str]) -> Any: + previous = os.getcwd() + os.chdir(workspace) + try: + return CliRunner().invoke(fastkit_cli, argv) + finally: + os.chdir(previous) + + +def step_dicts(steps: Any) -> List[Dict[str, Any]]: + return [ + { + "id": step.id, + "text": step.text, + "commands": [ + {"text": command.text, "windows": command.windows} + for command in step.commands + ], + } + for step in steps + ] + + +def test_cases_file_has_the_designed_cases() -> None: + ids = [case["id"] for case in CASES] + assert len(CASES) == 26 + assert len(set(ids)) == 26 + assert 9 <= len(NATIVE) <= 13 + for case in CASES: + assert set(case) <= {"id", "form", "lang", "native", "covers"} + assert browser.check_form(case["form"], case.get("lang", "en"))["ok"], case + + +def test_untouched_customise_gives_the_production_command() -> None: + by_id = {case["id"]: case for case in CASES} + plain = browser.check_form(by_id["05-production"]["form"]) + opened = browser.check_form(by_id["26-production-customise-untouched"]["form"]) + assert opened["command"] == plain["command"] + assert "--feature" not in plain["command"] + + +@pytest.mark.parametrize("case", NATIVE, ids=[case["id"] for case in NATIVE]) +def test_web_zip_equals_cli_project( + case: Dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + form, lang = case["form"], case.get("lang", "en") + name = form["project_name"] + check = browser.check_form(form, lang) + assert check["ok"], check + archive, meta = browser.build( + form, + lang, + secret_factory=seeded_secret_factory(case["id"]), + work_dir=str(tmp_path), + ) + assert os.listdir(tmp_path) == [] + + # The CLI side: the page's own command line; git identity is empty + # (tests/conftest.py), so omitted identity flags stay empty there too. + reported: List[Any] = [] + monkeypatch.setattr(init_command, "report_next_steps", reported.append) + workspace = tmp_path / "cli" + workspace.mkdir() + result = run_cli(workspace, check["command"]) + assert result.exit_code == 0, result.output + assert sorted(os.listdir(workspace)) == [name] + cli_files = regular_files(workspace / name) + + # 6. zip hygiene + with zipfile.ZipFile(io.BytesIO(archive)) as zipped: + infos = zipped.infolist() + names = [info.filename for info in infos] + assert names == sorted(names) + assert len(set(names)) == len(names) + for info in infos: + assert info.filename.startswith(f"{name}/") + assert "\\" not in info.filename and ".." not in info.filename.split("/") + assert not info.filename.startswith("/") + assert info.compress_type == zipfile.ZIP_DEFLATED + assert info.create_system == 3 + contents = { + info.filename[len(name) + 1 :]: ( + zipped.read(info), + info.external_attr >> 16, + ) + for info in infos + } + + # 1. layout + assert set(contents) == set(cli_files) + assert meta["files"] == sorted(cli_files) + assert meta["filename"] == f"{name}.zip" and meta["root"] == name + + # 2. bytes (.env masked) and 3. modes + for relpath, path in cli_files.items(): + web_bytes, web_mode = contents[relpath] + cli_bytes = path.read_bytes() + if relpath == ".env": + web_bytes, cli_bytes = masked_env(web_bytes), masked_env(cli_bytes) + assert web_bytes == cli_bytes, relpath + assert stat.S_ISREG(web_mode), relpath + expected = 0o755 if is_executable_path(relpath) else 0o644 + assert stat.S_IMODE(web_mode) == expected, relpath + if not platform.is_windows(): + cli_executable = bool(path.stat().st_mode & stat.S_IXUSR) + assert cli_executable == (expected == 0o755), relpath + + # 5. identity: the CLI wrote what the command line says (equal bytes + # above make the zip say the same) + project = tomllib.loads( + (workspace / name / "pyproject.toml").read_text(encoding="utf-8") + )["project"] + customised = bool(form.get("customise")) + author = form.get("author", "").strip() if customised else "" + email = form.get("author_email", "").strip() if customised else "" + if author or email: + assert project["authors"] == [{"name": author, "email": email}] + else: + assert "authors" not in project + description = form.get("description", "").strip() if customised else "" + if description: + assert description in project["description"] + + # 7. next steps (English) equal the CLI run's "no venv" steps + assert len(reported) == 1 + scaffolded = reported[0] + environment = replace(scaffolded.environment, windows=False) + expected_steps = step_dicts(next_steps(scaffolded.generation.facts, environment)) + if lang == "en": + assert meta["next_steps"] == expected_steps + else: + assert [step["id"] for step in meta["next_steps"]] == [ + step["id"] for step in expected_steps + ] diff --git a/tests/test_generation/test_import_boundary.py b/tests/test_generation/test_import_boundary.py new file mode 100644 index 00000000..280661d2 --- /dev/null +++ b/tests/test_generation/test_import_boundary.py @@ -0,0 +1,279 @@ +# -------------------------------------------------------------------------- +# The generation path imports and runs without click and rich. +# +# The browser build loads only fastkit, jinja2 and markupsafe, so nothing the +# generation API imports may pull in click or rich (or the CLI-only packages +# ``utils.main``, ``backend.interactive`` and ``backend.doctor``, which load +# them). Each check runs in a fresh interpreter whose import system refuses +# ``rich`` and ``click``; the static test in ``test_no_side_effects.py`` only +# sees direct imports, this one follows every transitive import. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import json +import os +import subprocess +import sys +import textwrap +from pathlib import Path +from typing import Any, Dict, List + +import pytest + +import fastapi_fastkit + +#: Directory that holds the ``fastapi_fastkit`` package being tested. +PACKAGE_PARENT = str(Path(fastapi_fastkit.__file__).resolve().parent.parent) + +#: Modules that load click or rich and must stay out of the generation path. +CLI_ONLY_MODULES = ( + "fastapi_fastkit.utils.main", + "fastapi_fastkit.backend.interactive", + "fastapi_fastkit.backend.doctor", +) + +#: Installs the blocker; every child script starts with it. ``argv[1]`` is +#: the package parent (``-I`` ignores ``PYTHONPATH``), ``argv[2]`` a scratch +#: directory. +PRELUDE = textwrap.dedent(""" + import importlib.abc + import json + import os + import subprocess + import sys + + sys.path.insert(0, sys.argv[1]) + WORK = sys.argv[2] + BLOCKED = ("rich", "click") + + + class Blocker(importlib.abc.MetaPathFinder): + def find_spec(self, name, path, target=None): + if name.split(".")[0] in BLOCKED: + raise ImportError(f"blocked import of {name}") + return None + + + sys.meta_path.insert(0, Blocker()) + for name in list(sys.modules): + if name.split(".")[0] in BLOCKED: + del sys.modules[name] + + + def _no_subprocess(*args, **kwargs): + raise AssertionError(f"subprocess started during generation: {args!r}") + + + for _name in ("run", "Popen", "call", "check_call", "check_output"): + setattr(subprocess, _name, _no_subprocess) + + try: + import rich # noqa: F401 + except ImportError: + pass + else: + raise AssertionError("the blocker did not stop 'import rich'") + + report = {} + """) + +#: Ends every child script: which CLI-only or blocked modules got loaded. +EPILOGUE = textwrap.dedent(""" + report["loaded"] = sorted( + name + for name in sys.modules + if name.split(".")[0] in BLOCKED + or name.startswith(tuple(json.loads(os.environ["FASTKIT_CLI_ONLY"]))) + ) + print("REPORT " + json.dumps(report, sort_keys=True)) + """) + +#: Generates every level for every package manager. +GENERATION_SCRIPT = textwrap.dedent(""" + import fastapi_fastkit.generation as generation + import fastapi_fastkit.generation.guide as guide + from fastapi_fastkit.generation import ( + ProjectChoice, + ProjectInfo, + choice_spec, + generate, + plan, + seeded_secret_factory, + ) + + CASES = [ + ("hello", {}), + ("single-file", {"database": "SQLite"}), + ("layered", {"database": "PostgreSQL"}), + ("domain", {"database": "MySQL", "features": {"authentication": "JWT"}}), + ("production", {}), + ] + MANAGERS = ["uv", "pip", "pdm", "poetry"] + + results = [] + for level, extra in CASES: + for manager in MANAGERS: + name = f"{level.replace('-', '_')}_{manager}" + choice = ProjectChoice( + project=ProjectInfo(name, "Ada", "ada@example.com", "boundary"), + level=level, + package_manager=manager, + **extra, + ) + spec = choice_spec(choice) + target = os.path.join(WORK, name) + planned = plan(spec, target) + result = generate( + spec, target, secret_factory=seeded_secret_factory(name) + ) + on_disk = sorted( + os.path.relpath(os.path.join(root, file), target).replace(os.sep, "/") + for root, _dirs, files in os.walk(target) + for file in files + ) + steps = guide.next_steps( + result.facts, + guide.Environment( + folder=name, venv="none", env_file="absent", windows=False + ), + ) + sections = guide.feature_sections(result.facts) + results.append( + { + "case": name, + "files": len(result.files), + "plan_matches": list(planned.files) == list(result.files), + "disk_matches": on_disk == list(result.files), + "steps": len(steps), + "sections": len(sections), + "template": result.template, + } + ) + report["results"] = results + """) + +#: Drives the browser module's form API (WP2's ``generation/browser.py``). +BROWSER_SCRIPT = textwrap.dedent(""" + import io + import zipfile + + from fastapi_fastkit.generation import browser, seeded_secret_factory + + def form(level, **values): + data = { + "schema": browser.FORM_SCHEMA, + "project_name": "browser_" + level.replace("-", "_"), + "level": level, + "database": None, + "customise": False, + "features": {}, + "package_manager": "uv", + "author": "", + "author_email": "", + "description": "", + "extra_packages": [], + } + data.update(values) + return data + + results = [] + for level in ("hello", "production"): + checked = browser.check_form(form(level)) + archive, meta = browser.build( + form(level), secret_factory=seeded_secret_factory(level), work_dir=WORK + ) + names = zipfile.ZipFile(io.BytesIO(archive)).namelist() + results.append( + { + "level": level, + "ok": checked["ok"], + "files": len(checked["files"]), + "zip_entries": len(names), + "meta_files": len(meta["files"]), + } + ) + report["model_levels"] = len(browser.form_model("en")["levels"]) + report["results"] = results + """) + + +def _run_blocked(script: str, work_dir: Path) -> Dict[str, Any]: + """Run ``script`` in an isolated interpreter with rich/click blocked.""" + env = dict(os.environ) + env["FASTKIT_CLI_ONLY"] = json.dumps(list(CLI_ONLY_MODULES)) + env.pop("PYTEST_CURRENT_TEST", None) + completed = subprocess.run( + [ + sys.executable, + "-I", + "-c", + PRELUDE + script + EPILOGUE, + PACKAGE_PARENT, + str(work_dir), + ], + capture_output=True, + encoding="utf-8", + errors="replace", + env=env, + timeout=600, + check=False, + ) + assert completed.returncode == 0, ( + f"child failed ({completed.returncode})\n" + f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}" + ) + lines = [ + line for line in completed.stdout.splitlines() if line.startswith("REPORT ") + ] + assert len(lines) == 1, completed.stdout + report: Dict[str, Any] = json.loads(lines[0][len("REPORT ") :]) + return report + + +def test_generation_imports_and_runs_without_click_or_rich(tmp_path: Path) -> None: + report = _run_blocked(GENERATION_SCRIPT, tmp_path) + + assert report["loaded"] == [] + results: List[Dict[str, Any]] = report["results"] + assert len(results) == 20 + for result in results: + assert result["files"] > 0, result + assert result["plan_matches"], result + assert result["disk_matches"], result + assert result["steps"] > 0, result + by_case = {result["case"]: result for result in results} + # hello and the template levels have no feature sections; domain with + # JWT and the production bundle have some. + assert by_case["hello_uv"]["sections"] == 0 + assert by_case["domain_uv"]["sections"] > 0 + assert by_case["production_poetry"]["sections"] > 0 + + +def test_generation_imports_without_cli_only_modules(tmp_path: Path) -> None: + script = textwrap.dedent(""" + import fastapi_fastkit.generation + import fastapi_fastkit.generation.guide + import fastapi_fastkit.utils.output + import fastapi_fastkit.utils.project_meta + import fastapi_fastkit.utils.validation + import fastapi_fastkit.core.known + """) + report = _run_blocked(script, tmp_path) + + assert report["loaded"] == [] + + +def test_browser_module_runs_without_click_or_rich(tmp_path: Path) -> None: + report = _run_blocked(BROWSER_SCRIPT, tmp_path) + + assert report["loaded"] == [] + assert report["model_levels"] >= 5 + for result in report["results"]: + assert result["ok"], result + assert result["files"] == result["zip_entries"] == result["meta_files"] + + +def test_blocked_import_is_reported(tmp_path: Path) -> None: + """The harness itself fails loudly when the child imports click or rich.""" + with pytest.raises(AssertionError, match="blocked import of (click|rich)"): + _run_blocked("import fastapi_fastkit.utils.main\n", tmp_path) diff --git a/tests/test_generation/test_levels.py b/tests/test_generation/test_levels.py index 99ab73ac..cb243b02 100644 --- a/tests/test_generation/test_levels.py +++ b/tests/test_generation/test_levels.py @@ -11,7 +11,7 @@ import pytest import fastapi_fastkit.generation.levels as levels_module -from fastapi_fastkit.catalog import Rule, load_catalog +from fastapi_fastkit.catalog import Rule, evaluate, load_catalog from fastapi_fastkit.core.settings import FastkitConfig from fastapi_fastkit.generation import ( ChoiceError, @@ -33,6 +33,7 @@ spec_from_config, uses_template_mode, ) +from fastapi_fastkit.generation.levels import raw_selection from fastapi_fastkit.generation.spec import validate_spec CATALOG = load_catalog() @@ -893,6 +894,69 @@ def test_validate_spec_checks_the_level() -> None: ) +# ------------------------------------------------------------ raw selection + + +def test_raw_selection_of_templates_and_hello_is_empty() -> None: + assert ( + raw_selection(ProjectChoice(project=PROJECT, template="fastapi-default")) == {} + ) + assert raw_selection(ProjectChoice(project=PROJECT, level="hello")) == {} + + +def test_raw_selection_applies_answers_without_the_rules() -> None: + choice = ProjectChoice( + project=PROJECT, + level="domain", + database="MongoDB", + features={ + "authentication": "FastAPI-Users", + "deployment": ("docker-compose",), + "tooling": ("makefile", "None", "ruff"), + }, + ) + raw = raw_selection(choice) + assert raw == dict( + BASE_SELECTION, + database="MongoDB", + authentication="FastAPI-Users", + deployment=("docker-compose",), + tooling=("ruff", "makefile"), + ) + # The requires rule fails and Docker is not implied yet: that is the + # caller's evaluate(). + outcome = evaluate(raw, CATALOG) + assert outcome.errors and outcome.implied == {"deployment": ("Docker",)} + with pytest.raises(ChoiceError): + effective_selection(choice) + + +def test_effective_selection_is_the_raw_selection_with_implications() -> None: + choice = ProjectChoice( + project=PROJECT, + level="production", + database="MongoDB", + features={"migrations": "Alembic", "deployment": ("docker-compose",)}, + ) + raw = raw_selection(choice) + assert raw["migrations"] == "Alembic" + assert raw["deployment"] == ("docker-compose",) + assert effective_selection(choice) == dict( + raw, deployment=("Docker", "docker-compose") + ) + + +def test_raw_selection_rejects_unknown_answers() -> None: + with pytest.raises(ChoiceError, match="Unknown feature 'colour'"): + raw_selection( + ProjectChoice(project=PROJECT, level="domain", features={"colour": "red"}) + ) + with pytest.raises(ChoiceError, match="Unknown database 'Oracle'"): + raw_selection(ProjectChoice(project=PROJECT, level="domain", database="Oracle")) + with pytest.raises(ChoiceError, match="Unknown level"): + raw_selection(ProjectChoice(project=PROJECT, level="expert")) + + # ------------------------------------------------------------- import guard diff --git a/tests/test_scripts/__init__.py b/tests/test_scripts/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_scripts/test_web_generator_scripts.py b/tests/test_scripts/test_web_generator_scripts.py new file mode 100644 index 00000000..7bdb84f0 --- /dev/null +++ b/tests/test_scripts/test_web_generator_scripts.py @@ -0,0 +1,1499 @@ +# -------------------------------------------------------------------------- +# Offline tests of the web generator build and comparison scripts. +# +# scripts/web_generator/ is not a package: each script is loaded from its +# file. Nothing here touches the network, Node or Pyodide; downloads go +# through fake fetch functions and the tarball, lock and zips are built here. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import base64 +import hashlib +import importlib.util +import io +import json +import os +import stat +import sys +import tarfile +import zipfile +from pathlib import Path +from types import ModuleType +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple + +import pytest + +SCRIPTS = Path(__file__).resolve().parents[2] / "scripts" / "web_generator" + + +def _load(name: str) -> ModuleType: + module_name = f"web_generator_{name}" + if module_name in sys.modules: + return sys.modules[module_name] + spec = importlib.util.spec_from_file_location(module_name, SCRIPTS / f"{name}.py") + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + spec.loader.exec_module(module) + return module + + +build_assets = _load("build_assets") +compare = _load("compare") +compare_with_cli = _load("compare_with_cli") +check_site = _load("check_site") + +SECRET_A = "A" * 40 + "_-9" +SECRET_B = "b" * 43 +CORE = [ + "pyodide.mjs", + "pyodide.asm.mjs", + "pyodide.asm.wasm", + "python_stdlib.zip", + "pyodide-lock.json", +] + + +# ---------------------------------------------------------------- helpers + + +def _sri(data: bytes, algorithm: str = "sha512") -> str: + return ( + f"{algorithm}-" + + base64.b64encode(hashlib.new(algorithm, data).digest()).decode() + ) + + +def _tarball( + files: Dict[str, bytes], + *, + links: Iterable[Tuple[str, str]] = (), + dirs: Iterable[str] = (), +) -> bytes: + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as archive: + for name, data in files.items(): + info = tarfile.TarInfo(name) + info.size = len(data) + archive.addfile(info, io.BytesIO(data)) + for name, target in links: + info = tarfile.TarInfo(name) + info.type = tarfile.SYMTYPE + info.linkname = target + archive.addfile(info) + for name in dirs: + info = tarfile.TarInfo(name) + info.type = tarfile.DIRTYPE + archive.addfile(info) + return buffer.getvalue() + + +JINJA = b"jinja2 wheel bytes" +MARKUPSAFE = b"markupsafe wheel bytes" + + +def _lock(**overrides: Any) -> Dict[str, Any]: + lock: Dict[str, Any] = { + "info": {"python": "3.14.2"}, + "packages": { + "jinja2": { + "name": "Jinja2", + "version": "3.1.6", + "file_name": "jinja2-3.1.6-py3-none-any.whl", + "sha256": hashlib.sha256(JINJA).hexdigest(), + "depends": ["markupsafe"], + }, + "markupsafe": { + "name": "MarkupSafe", + "version": "3.0.3", + "file_name": "markupsafe-3.0.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl", + "sha256": hashlib.sha256(MARKUPSAFE).hexdigest(), + "depends": [], + }, + }, + } + lock.update(overrides) + return lock + + +def _pyodide_tarball(lock: Optional[Dict[str, Any]] = None) -> bytes: + files = {f"package/{name}": f"core {name}".encode() for name in CORE} + files["package/pyodide-lock.json"] = json.dumps(lock or _lock()).encode() + files["package/README.md"] = b"not copied" + return _tarball(files) + + +def _config(tar_bytes: bytes, **overrides: Any) -> Any: + values: Dict[str, Any] = dict( + version="314.0.8", + tarball="https://registry.npmjs.org/pyodide/-/pyodide-314.0.8.tgz", + integrity=_sri(tar_bytes), + wheel_base="https://cdn.jsdelivr.net/pyodide/v314.0.8/full/", + packages=["jinja2"], + core_files=list(CORE), + license="MPL-2.0", + source="https://github.com/pyodide/pyodide", + notices={ + "jinja2": { + "license": "BSD-3-Clause", + "source": "https://github.com/pallets/jinja", + }, + "markupsafe": { + "license": "BSD-3-Clause", + "source": "https://github.com/pallets/markupsafe", + }, + }, + ) + values.update(overrides) + return build_assets.PyodideConfig(**values) + + +class FakeFetch: + def __init__(self, files: Dict[str, bytes]) -> None: + self.files = files + self.calls: List[str] = [] + + def __call__(self, url: str) -> bytes: + self.calls.append(url) + return self.files[url] + + +def _fetch_for(tar_bytes: bytes) -> FakeFetch: + base = "https://cdn.jsdelivr.net/pyodide/v314.0.8/full/" + return FakeFetch( + { + "https://registry.npmjs.org/pyodide/-/pyodide-314.0.8.tgz": tar_bytes, + base + "jinja2-3.1.6-py3-none-any.whl": JINJA, + base + + "markupsafe-3.0.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl": MARKUPSAFE, + } + ) + + +def _zip( + entries: Iterable[Tuple[str, bytes]], + *, + mode: int = 0o644, + modes: Optional[Dict[str, int]] = None, + compress_type: int = zipfile.ZIP_DEFLATED, + create_system: int = 3, + file_type: int = stat.S_IFREG, +) -> bytes: + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + for name, data in entries: + info = zipfile.ZipInfo(name, date_time=(2026, 12, 3, 12, 0, 0)) + info.compress_type = compress_type + info.create_system = create_system + info.external_attr = (file_type | (modes or {}).get(name, mode)) << 16 + archive.writestr(info, data) + return buffer.getvalue() + + +def _tree(files: Dict[str, bytes], modes: Optional[Dict[str, int]] = None) -> Any: + return compare.Tree( + files=dict(files), modes={rel: (modes or {}).get(rel, 0o644) for rel in files} + ) + + +# ---------------------------------------------------------------- build_assets: config + + +class TestConfig: + def test_repository_config_loads(self) -> None: + config = build_assets.load_config() + assert config.version == "314.0.8" + assert config.tarball.endswith(f"pyodide-{config.version}.tgz") + assert config.wheel_base.endswith(f"/v{config.version}/full/") + assert config.integrity.startswith("sha512-") + assert config.packages == ["jinja2"] + assert "pyodide-lock.json" in config.core_files + assert set(config.notices) >= {"jinja2", "markupsafe"} + + def test_missing_key(self, tmp_path: Path) -> None: + path = tmp_path / "pyodide.toml" + path.write_text('version = "1"\n', encoding="utf-8") + with pytest.raises(build_assets.BuildError, match="missing or invalid key"): + build_assets.load_config(str(path)) + + @pytest.mark.parametrize( + "change, message", + [ + ({"core_files": ["../evil.js"]}, "plain file name"), + ({"wheel_base": "https://cdn.example/full"}, "must end with '/'"), + ], + ) + def test_invalid_values( + self, tmp_path: Path, change: Dict[str, Any], message: str + ) -> None: + values: Dict[str, Any] = { + "version": "1", + "tarball": "https://registry.npmjs.org/x.tgz", + "integrity": "sha512-x", + "wheel_base": "https://cdn.example/full/", + "packages": ["jinja2"], + "core_files": ["pyodide.mjs"], + "license": "MPL-2.0", + "source": "https://example.org", + } + values.update(change) + lines = [f"{key} = {json.dumps(value)}" for key, value in values.items()] + path = tmp_path / "pyodide.toml" + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + with pytest.raises(build_assets.BuildError, match=message): + build_assets.load_config(str(path)) + + +# ---------------------------------------------------------------- build_assets: integrity + + +class TestIntegrity: + def test_matching_sha512(self) -> None: + build_assets.check_integrity(b"data", _sri(b"data"), "x") + + def test_matching_sha256(self) -> None: + build_assets.check_integrity(b"data", _sri(b"data", "sha256"), "x") + + def test_mismatch(self) -> None: + with pytest.raises(build_assets.BuildError, match="the tarball does not match"): + build_assets.check_integrity(b"other", _sri(b"data"), "the tarball") + + @pytest.mark.parametrize("value", ["md5-abc", "sha512", "abc"]) + def test_unsupported(self, value: str) -> None: + with pytest.raises(build_assets.BuildError, match="unsupported integrity"): + build_assets.check_integrity(b"data", value, "x") + + def test_sha256_check(self) -> None: + build_assets.check_sha256(b"x", hashlib.sha256(b"x").hexdigest().upper(), "f") + with pytest.raises(build_assets.BuildError, match="f does not match"): + build_assets.check_sha256(b"y", hashlib.sha256(b"x").hexdigest(), "f") + + +# ---------------------------------------------------------------- build_assets: tarball + + +class TestExtractCore: + def test_copies_only_core_files(self, tmp_path: Path) -> None: + written = build_assets.extract_core(_pyodide_tarball(), CORE, str(tmp_path)) + assert written == CORE + assert sorted(os.listdir(tmp_path)) == sorted(CORE) + assert (tmp_path / "pyodide.mjs").read_bytes() == b"core pyodide.mjs" + + @pytest.mark.parametrize( + "name", + [ + "package/../evil.mjs", + "/etc/passwd", + "../package/pyodide.mjs", + "C:/evil", + "package\\x", + ], + ) + def test_unsafe_member_path_refused(self, tmp_path: Path, name: str) -> None: + tar = _tarball({"package/pyodide.mjs": b"x", name: b"evil"}) + with pytest.raises(build_assets.BuildError, match="unsafe path"): + build_assets.extract_core(tar, ["pyodide.mjs"], str(tmp_path / "out")) + assert not (tmp_path / "out").exists() + + def test_symlink_refused(self, tmp_path: Path) -> None: + tar = _tarball({}, links=[("package/pyodide.mjs", "/etc/passwd")]) + with pytest.raises( + build_assets.BuildError, match="link in the Pyodide tarball" + ): + build_assets.extract_core(tar, ["pyodide.mjs"], str(tmp_path)) + + def test_link_elsewhere_refused(self, tmp_path: Path) -> None: + tar = _tarball( + {"package/pyodide.mjs": b"x"}, links=[("package/other", "pyodide.mjs")] + ) + with pytest.raises(build_assets.BuildError, match="link"): + build_assets.extract_core(tar, ["pyodide.mjs"], str(tmp_path)) + + def test_directory_named_like_core_file(self, tmp_path: Path) -> None: + tar = _tarball({}, dirs=["package/pyodide.mjs"]) + with pytest.raises(build_assets.BuildError, match="not a regular file"): + build_assets.extract_core(tar, ["pyodide.mjs"], str(tmp_path)) + + def test_missing_core_file(self, tmp_path: Path) -> None: + tar = _tarball({"package/pyodide.mjs": b"x"}) + with pytest.raises( + build_assets.BuildError, + match="missing in the Pyodide tarball: python_stdlib.zip", + ): + build_assets.extract_core( + tar, ["pyodide.mjs", "python_stdlib.zip"], str(tmp_path) + ) + + def test_not_a_tarball(self, tmp_path: Path) -> None: + with pytest.raises(build_assets.BuildError, match="cannot be read"): + build_assets.extract_core(b"not a tarball", CORE, str(tmp_path)) + + +# ---------------------------------------------------------------- build_assets: lock + + +class TestResolvePackages: + def test_dependencies_first(self) -> None: + entries = build_assets.resolve_packages(_lock(), ["jinja2"]) + assert [e["key"] for e in entries] == ["markupsafe", "jinja2"] + assert entries[1]["file_name"] == "jinja2-3.1.6-py3-none-any.whl" + + def test_names_are_case_insensitive_and_deduplicated(self) -> None: + entries = build_assets.resolve_packages(_lock(), ["Jinja2", "markupsafe"]) + assert [e["key"] for e in entries] == ["markupsafe", "jinja2"] + + def test_unknown_package(self) -> None: + with pytest.raises( + build_assets.BuildError, match="'rich' is not in pyodide-lock.json" + ): + build_assets.resolve_packages(_lock(), ["rich"]) + + def test_unknown_dependency(self) -> None: + lock = _lock() + lock["packages"]["jinja2"]["depends"] = ["nothere"] + with pytest.raises(build_assets.BuildError, match="nothere"): + build_assets.resolve_packages(lock, ["jinja2"]) + + def test_cycle(self) -> None: + lock = _lock() + lock["packages"]["markupsafe"]["depends"] = ["jinja2"] + with pytest.raises(build_assets.BuildError, match="cycle"): + build_assets.resolve_packages(lock, ["jinja2"]) + + def test_no_packages_table(self) -> None: + with pytest.raises(build_assets.BuildError, match="no packages table"): + build_assets.resolve_packages({"info": {}}, ["jinja2"]) + + +# ---------------------------------------------------------------- build_assets: downloads + + +class TestDownloads: + BASE = "https://cdn.jsdelivr.net/pyodide/v314.0.8/full/" + + def test_other_host_refused(self) -> None: + fetch = FakeFetch({}) + with pytest.raises( + build_assets.BuildError, match="refusing to download from evil.example" + ): + build_assets.fetch_checked( + "https://evil.example/x.whl", "cdn.jsdelivr.net", fetch, lambda d: None + ) + assert fetch.calls == [] + + @pytest.mark.parametrize( + "url", ["http://cdn.jsdelivr.net/x.whl", "file:///etc/passwd", "https:///x"] + ) + def test_non_https_refused(self, url: str) -> None: + with pytest.raises(build_assets.BuildError, match="non-https"): + build_assets.fetch_checked( + url, "cdn.jsdelivr.net", FakeFetch({}), lambda d: None + ) + + @pytest.mark.parametrize( + "file_name", + ["../x.whl", "https://evil.example/x.whl", "sub/x.whl", "", "..", "a\\b.whl"], + ) + def test_lock_file_name_cannot_change_host_or_path(self, file_name: str) -> None: + with pytest.raises(build_assets.BuildError, match="unexpected file name"): + build_assets.wheel_url(self.BASE, file_name) + + def test_wheel_url(self) -> None: + assert build_assets.wheel_url(self.BASE, "a-1.whl") == self.BASE + "a-1.whl" + + def test_cache_hit_skips_download(self, tmp_path: Path) -> None: + cached = tmp_path / "cache" / "x.whl" + cached.parent.mkdir() + cached.write_bytes(b"good") + fetch = FakeFetch({}) + data = build_assets.cached_or_fetch( + str(cached), + self.BASE + "x.whl", + "cdn.jsdelivr.net", + fetch, + lambda d: build_assets.check_sha256( + d, hashlib.sha256(b"good").hexdigest(), "x" + ), + ) + assert data == b"good" and fetch.calls == [] + + def test_damaged_cache_is_replaced(self, tmp_path: Path) -> None: + cached = tmp_path / "cache" / "x.whl" + cached.parent.mkdir() + cached.write_bytes(b"damaged") + fetch = FakeFetch({self.BASE + "x.whl": b"good"}) + data = build_assets.cached_or_fetch( + str(cached), + self.BASE + "x.whl", + "cdn.jsdelivr.net", + fetch, + lambda d: build_assets.check_sha256( + d, hashlib.sha256(b"good").hexdigest(), "x" + ), + ) + assert data == b"good" and len(fetch.calls) == 1 + assert cached.read_bytes() == b"good" + assert not (tmp_path / "cache" / "x.whl.part").exists() + + def test_bad_download_is_not_cached(self, tmp_path: Path) -> None: + cached = tmp_path / "cache" / "x.whl" + fetch = FakeFetch({self.BASE + "x.whl": b"tampered"}) + with pytest.raises(build_assets.BuildError, match="does not match"): + build_assets.cached_or_fetch( + str(cached), + self.BASE + "x.whl", + "cdn.jsdelivr.net", + fetch, + lambda d: build_assets.check_sha256( + d, hashlib.sha256(b"good").hexdigest(), "x" + ), + ) + assert not cached.exists() + + def test_package_wheel_sha_mismatch(self, tmp_path: Path) -> None: + tar = _pyodide_tarball() + fetch = _fetch_for(tar) + fetch.files[self.BASE + "jinja2-3.1.6-py3-none-any.whl"] = b"tampered" + entries = build_assets.resolve_packages(_lock(), ["jinja2"]) + with pytest.raises( + build_assets.BuildError, + match="jinja2-3.1.6-py3-none-any.whl does not match", + ): + build_assets.fetch_package_wheels( + entries, _config(tar), str(tmp_path), fetch, None + ) + + def test_package_without_sha(self, tmp_path: Path) -> None: + lock = _lock() + del lock["packages"]["markupsafe"]["sha256"] + entries = build_assets.resolve_packages(lock, ["jinja2"]) + with pytest.raises(build_assets.BuildError, match="no sha256"): + build_assets.fetch_package_wheels( + entries, _config(b""), str(tmp_path), FakeFetch({}), None + ) + + +# ---------------------------------------------------------------- build_assets: wheel and output + + +class TestWheelAndOutput: + def test_resolve_wheel_glob(self, tmp_path: Path) -> None: + wheel = tmp_path / "fastapi_fastkit-2.0.0-py3-none-any.whl" + wheel.write_bytes(b"w") + assert build_assets.resolve_wheel_arg( + str(tmp_path / "fastapi_fastkit-*.whl") + ) == str(wheel) + assert build_assets.resolve_wheel_arg(str(wheel)) == str(wheel) + + def test_resolve_wheel_none_or_several(self, tmp_path: Path) -> None: + with pytest.raises(build_assets.BuildError, match="matched nothing"): + build_assets.resolve_wheel_arg(str(tmp_path / "fastapi_fastkit-*.whl")) + with pytest.raises(build_assets.BuildError, match="matched nothing"): + build_assets.resolve_wheel_arg(str(tmp_path / "missing.whl")) + for version in ("1.0.0", "2.0.0"): + (tmp_path / f"fastapi_fastkit-{version}-py3-none-any.whl").write_bytes(b"w") + with pytest.raises(build_assets.BuildError, match="exactly one"): + build_assets.resolve_wheel_arg(str(tmp_path / "fastapi_fastkit-*.whl")) + + def test_wheel_version(self) -> None: + assert ( + build_assets.wheel_version("dist/fastapi_fastkit-2.0.0-py3-none-any.whl") + == "2.0.0" + ) + assert ( + build_assets.wheel_version("FastAPI_fastkit-2.0.0rc1-py3-none-any.whl") + == "2.0.0rc1" + ) + with pytest.raises(build_assets.BuildError, match="not a fastapi_fastkit"): + build_assets.wheel_version("fastapi_fastkit-2.0.0.tar.gz") + + def test_version_mismatch(self) -> None: + build_assets.check_installed_version( + "fastapi_fastkit-2.0.0-py3-none-any.whl", "2.0.0" + ) + with pytest.raises( + build_assets.BuildError, + match="installed fastapi_fastkit is 1.9.0 but the wheel is 2.0.0", + ): + build_assets.check_installed_version( + "fastapi_fastkit-2.0.0-py3-none-any.whl", "1.9.0" + ) + + def test_out_dir_with_other_files_is_refused(self, tmp_path: Path) -> None: + (tmp_path / "keep.txt").write_text("x", encoding="utf-8") + with pytest.raises(build_assets.BuildError, match="refusing to clear"): + build_assets.prepare_out_dir(str(tmp_path)) + assert (tmp_path / "keep.txt").exists() + + def test_out_dir_that_is_a_file(self, tmp_path: Path) -> None: + target = tmp_path / "out" + target.write_text("x", encoding="utf-8") + with pytest.raises(build_assets.BuildError, match="not a directory"): + build_assets.prepare_out_dir(str(target)) + + def test_empty_dir_is_marked(self, tmp_path: Path) -> None: + build_assets.prepare_out_dir(str(tmp_path)) + assert sorted(os.listdir(tmp_path)) == [build_assets.MARKER, "pyodide"] + assert (tmp_path / build_assets.MARKER).read_text(encoding="utf-8") == ( + build_assets.MARKER_TEXT + ) + + def test_marked_dir_is_cleared_after_a_failed_build(self, tmp_path: Path) -> None: + out = tmp_path / "out" + build_assets.prepare_out_dir(str(out)) + (out / "pyodide" / "pyodide.mjs").write_bytes(b"half-written") + # No manifest.json: the build stopped before writing it. + build_assets.prepare_out_dir(str(out)) + assert sorted(os.listdir(out)) == [build_assets.MARKER, "pyodide"] + assert os.listdir(out / "pyodide") == [] + + def test_earlier_unmarked_build_is_replaced(self, tmp_path: Path) -> None: + out = tmp_path / "out" + out.mkdir() + manifest = build_assets.build_manifest( + fastkit_version="2.0.0", + commit="local", + wheel="fastapi_fastkit-2.0.0-py3-none-any.whl", + wheel_sha256="0" * 64, + pyodide_version="314.0.8", + packages=["jinja2"], + ) + (out / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8") + (out / "fastapi_fastkit-1.0.0-py3-none-any.whl").write_bytes(b"old") + build_assets.prepare_out_dir(str(out)) + assert sorted(os.listdir(out)) == [build_assets.MARKER, "pyodide"] + + @pytest.mark.parametrize( + "manifest", + [ + "{}", + '{"schema": 1}', + "[1]", + "not json", + json.dumps( + { + "schema": 2, + "fastkit_version": "x", + "commit": "x", + "wheel": "x", + "wheel_sha256": "x", + "pyodide_version": "x", + "packages": [], + } + ), + ], + ) + def test_foreign_manifest_is_not_enough( + self, tmp_path: Path, manifest: str + ) -> None: + (tmp_path / "manifest.json").write_text(manifest, encoding="utf-8") + (tmp_path / "keep.txt").write_text("x", encoding="utf-8") + with pytest.raises(build_assets.BuildError, match="refusing to clear"): + build_assets.prepare_out_dir(str(tmp_path)) + assert (tmp_path / "keep.txt").exists() + + def test_marker_must_be_a_file(self, tmp_path: Path) -> None: + (tmp_path / build_assets.MARKER).mkdir() + with pytest.raises(build_assets.BuildError, match="refusing to clear"): + build_assets.prepare_out_dir(str(tmp_path)) + + +class TestBuild: + def _build(self, tmp_path: Path, **overrides: Any) -> Any: + tar = overrides.pop("tar", None) or _pyodide_tarball() + wheel = tmp_path / "dist" / "fastapi_fastkit-2.0.0-py3-none-any.whl" + wheel.parent.mkdir(exist_ok=True) + wheel.write_bytes(b"fastkit wheel") + kwargs: Dict[str, Any] = dict( + wheel=str(wheel), + out=str(tmp_path / "out"), + cache_dir=str(tmp_path / "cache"), + commit="abc123", + config=_config(tar), + fetch=_fetch_for(tar), + installed_version="2.0.0", + languages=["en", "ko"], + form_model=lambda lang: { + "schema": 1, + "lang": lang, + "label": "레벨" if lang == "ko" else "Level", + }, + ) + kwargs.update(overrides) + return build_assets.build(**kwargs) + + def test_writes_every_asset(self, tmp_path: Path) -> None: + result = self._build(tmp_path) + out = tmp_path / "out" + expected = sorted( + [f"pyodide/{n}" for n in CORE] + + [ + "pyodide/jinja2-3.1.6-py3-none-any.whl", + "pyodide/markupsafe-3.0.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl", + "fastapi_fastkit-2.0.0-py3-none-any.whl", + "model-en.json", + "model-ko.json", + "NOTICE.txt", + "manifest.json", + ] + ) + assert sorted(result.files) == expected + on_disk = sorted( + os.path.relpath(os.path.join(d, f), out).replace(os.sep, "/") + for d, _, fs in os.walk(out) + for f in fs + ) + assert on_disk == sorted(expected + [build_assets.MARKER]) + + manifest = json.loads((out / "manifest.json").read_text(encoding="utf-8")) + assert manifest == { + "schema": 1, + "fastkit_version": "2.0.0", + "commit": "abc123", + "wheel": "fastapi_fastkit-2.0.0-py3-none-any.whl", + "wheel_sha256": hashlib.sha256(b"fastkit wheel").hexdigest(), + "pyodide_version": "314.0.8", + "packages": ["jinja2"], + } + model = (out / "model-ko.json").read_bytes() + assert "레벨".encode() in model # ensure_ascii=False + assert json.loads(model) == {"schema": 1, "lang": "ko", "label": "레벨"} + notice = (out / "NOTICE.txt").read_text(encoding="utf-8") + for text in ( + "Pyodide 314.0.8: MPL-2.0", + "CPython 3.14.2", + "Jinja2 3.1.6", + "MarkupSafe 3.0.3", + "BSD-3-Clause", + "FastAPI-fastkit 2.0.0: MIT", + ): + assert text in notice + + def test_second_build_uses_the_cache(self, tmp_path: Path) -> None: + tar = _pyodide_tarball() + first = _fetch_for(tar) + self._build(tmp_path, tar=tar, fetch=first) + assert len(first.calls) == 3 + second = FakeFetch({}) + self._build(tmp_path, tar=tar, fetch=second) + assert second.calls == [] + + def test_tampered_tarball(self, tmp_path: Path) -> None: + tar = _pyodide_tarball() + fetch = _fetch_for(tar) + fetch.files["https://registry.npmjs.org/pyodide/-/pyodide-314.0.8.tgz"] = ( + b"tampered" + ) + with pytest.raises( + build_assets.BuildError, match="Pyodide tarball does not match" + ): + self._build(tmp_path, tar=tar, fetch=fetch) + assert not (tmp_path / "out").exists() + + def test_version_mismatch_stops_before_downloading(self, tmp_path: Path) -> None: + fetch = FakeFetch({}) + with pytest.raises(build_assets.BuildError, match="installed fastapi_fastkit"): + self._build(tmp_path, fetch=fetch, installed_version="1.0.0") + assert fetch.calls == [] + + def test_lock_for_another_version(self, tmp_path: Path) -> None: + tar = _pyodide_tarball(_lock(info={"python": "3.14.2", "version": "0.1.0"})) + with pytest.raises(build_assets.BuildError, match="for Pyodide 0.1.0"): + self._build(tmp_path, tar=tar) + + def test_lock_must_be_a_core_file(self, tmp_path: Path) -> None: + tar = _pyodide_tarball() + config = _config(tar, core_files=["pyodide.mjs"]) + with pytest.raises( + build_assets.BuildError, + match="pyodide-lock.json must be one of the core files", + ): + self._build(tmp_path, tar=tar, config=config) + + def test_package_without_notice(self, tmp_path: Path) -> None: + tar = _pyodide_tarball() + config = _config( + tar, notices={"jinja2": {"license": "BSD-3-Clause", "source": "x"}} + ) + with pytest.raises(build_assets.BuildError, match=r"\[notices.markupsafe\]"): + self._build(tmp_path, tar=tar, config=config) + + def test_without_cache(self, tmp_path: Path) -> None: + self._build(tmp_path, cache_dir=None) + assert not (tmp_path / "cache").exists() + + def test_parse_args_defaults(self) -> None: + args = build_assets.parse_args(["--wheel", "w.whl", "--out", "o"]) + assert args.cache == os.path.join(".cache", "web-generator") + assert args.commit == "local" and not args.no_cache + + +# ---------------------------------------------------------------- compare: secrets + + +class TestMaskSecrets: + def test_masks_valid_values(self) -> None: + # fastkit writes the key right after "=", also after "export" and spaces. + data = f"APP=1\nSECRET_KEY={SECRET_A}\n export SECRET_KEY ={SECRET_B}\n# SECRET_KEY=x\n".encode() + masked, problems = compare.mask_secrets(data, "web") + assert problems == [] + assert ( + masked + == b"APP=1\nSECRET_KEY=\n export SECRET_KEY =\n# SECRET_KEY=x\n" + ) + + @pytest.mark.parametrize( + "value", ["short", SECRET_A + "x", "A" * 42 + "+", "change-me", ""] + ) + def test_wrong_shape(self, value: str) -> None: + _, problems = compare.mask_secrets(f"SECRET_KEY={value}\n".encode(), "CLI") + assert problems == [ + f"CLI .env: SECRET_KEY value is not 43 base64url characters (length {len(value)})" + ] + + def test_not_utf8(self) -> None: + data, problems = compare.mask_secrets(b"\xff\xfe", "web") + assert data == b"\xff\xfe" and problems == ["web .env is not UTF-8"] + + +# ---------------------------------------------------------------- compare: trees + + +class TestCompareTrees: + def test_equal(self) -> None: + files = {"main.py": b"x\n", "scripts/run.sh": b"#!/bin/sh\n"} + modes = {"scripts/run.sh": 0o755} + assert compare.compare_trees(_tree(files, modes), _tree(files, modes)) == [] + + def test_env_secrets_are_masked(self) -> None: + web = _tree({".env": f"SECRET_KEY={SECRET_A}\nDEBUG=1\n".encode()}) + cli = _tree({".env": f"SECRET_KEY={SECRET_B}\nDEBUG=1\n".encode()}) + assert compare.compare_trees(web, cli) == [] + + def test_env_with_bad_secret(self) -> None: + web = _tree({".env": b"SECRET_KEY=placeholder\n"}) + cli = _tree({".env": f"SECRET_KEY={SECRET_B}\n".encode()}) + out = compare.compare_trees(web, cli) + assert out == [ + ".env: web .env: SECRET_KEY value is not 43 base64url characters (length 11)" + ] + + def test_env_other_line_differs(self) -> None: + web = _tree({".env": f"SECRET_KEY={SECRET_A}\nDEBUG=1\n".encode()}) + cli = _tree({".env": f"SECRET_KEY={SECRET_B}\nDEBUG=0\n".encode()}) + out = compare.compare_trees(web, cli) + assert out[0] == ".env: content differs" + assert " -DEBUG=0" in out and " +DEBUG=1" in out + assert not any(SECRET_A in line or SECRET_B in line for line in out) + + @pytest.mark.parametrize("rel", [".env.example", "deploy/.env", "src/.env"]) + def test_secret_outside_root_env_is_not_masked(self, rel: str) -> None: + web = _tree({rel: f"SECRET_KEY={SECRET_A}\n".encode()}) + cli = _tree({rel: f"SECRET_KEY={SECRET_B}\n".encode()}) + assert compare.compare_trees(web, cli)[0] == f"{rel}: content differs" + + def test_is_env_file(self) -> None: + assert compare.is_env_file(".env") + assert not compare.is_env_file("sub/.env") + assert not compare.is_env_file(".env.example") + + def test_missing_and_extra_files(self) -> None: + web = _tree({"a.py": b"", "web_only.py": b""}) + cli = _tree({"a.py": b"", "cli_only.py": b""}) + assert compare.compare_trees(web, cli) == [ + "cli_only.py: only in the CLI project", + "web_only.py: only in the web zip", + ] + + def test_mode_differs(self) -> None: + files = {"scripts/run.sh": b"#!/bin/sh\n"} + out = compare.compare_trees( + _tree(files, {"scripts/run.sh": 0o644}), + _tree(files, {"scripts/run.sh": 0o755}), + ) + assert out == [ + "scripts/run.sh: mode 644 in the web zip, 755 in the CLI project" + ] + + def test_diff_is_limited(self) -> None: + web = _tree({"big.txt": "".join(f"web {i}\n" for i in range(100)).encode()}) + cli = _tree({"big.txt": "".join(f"cli {i}\n" for i in range(100)).encode()}) + out = compare.compare_trees(web, cli) + assert out[0] == "big.txt: content differs" + assert out[1] == " --- cli/big.txt" and out[2] == " +++ web/big.txt" + assert len(out) == 1 + 40 + 1 + assert out[-1].startswith(" ... (") and out[-1].endswith(" more diff lines)") + + def test_binary_difference(self) -> None: + out = compare.compare_trees( + _tree({"x.bin": b"\xff\x00"}), _tree({"x.bin": b"\xff\x01\x02"}) + ) + assert out == [ + "x.bin: content differs", + " binary content differs (2 vs 3 bytes)", + ] + + def test_line_ending_difference(self) -> None: + out = compare.compare_trees( + _tree({"a.txt": b"x\r\n"}), _tree({"a.txt": b"x\n"}) + ) + assert out == [ + "a.txt: content differs", + " line endings or final newline differ", + ] + + +# ---------------------------------------------------------------- compare: zip hygiene + + +class TestZipProblems: + def test_clean_zip(self) -> None: + data = _zip( + [("demo/README.md", b"r"), ("demo/scripts/run.sh", b"s")], + modes={"demo/scripts/run.sh": 0o755}, + ) + assert compare.zip_problems(data, "demo") == [] + tree = compare.read_zip(data, "demo") + assert tree.files == {"README.md": b"r", "scripts/run.sh": b"s"} + assert tree.modes == {"README.md": 0o644, "scripts/run.sh": 0o755} + assert compare.zip_root(data) == "demo" + + def test_utf8_names(self) -> None: + data = _zip([("café_api/README.md", b"r")]) + assert compare.zip_problems(data, "café_api") == [] + with zipfile.ZipFile(io.BytesIO(data)) as archive: + assert archive.namelist() == ["café_api/README.md"] + + def test_unsorted(self) -> None: + data = _zip([("demo/b", b""), ("demo/a", b"")]) + assert compare.zip_problems(data, "demo") == ["entries are not sorted by name"] + + def test_duplicate(self) -> None: + with pytest.warns(UserWarning): + data = _zip([("demo/a", b"1"), ("demo/a", b"2")]) + assert compare.zip_problems(data, "demo") == ["demo/a: duplicate entry"] + + @pytest.mark.parametrize( + "name, reason", + [ + ("demo/../evil", "'..' segment in name"), + ("/demo/evil", "absolute name"), + ("demo\\evil", "backslash in name"), + ("C:demo/evil", "drive letter in name"), + ], + ) + def test_unsafe_names(self, name: str, reason: str) -> None: + problems = compare.zip_problems(_zip([(name, b"")]), "demo") + assert problems == [f"{name!r}: {reason}"] + + def test_unsafe_name_reason_for_empty_and_nul(self) -> None: + assert compare.unsafe_name_reason("") == "empty name" + assert compare.unsafe_name_reason("demo/a\x00b") == "NUL in name" + assert compare.unsafe_name_reason("demo/a") is None + + def test_outside_root_and_directories(self) -> None: + data = _zip( + [("demo/", b""), ("demo/sub/", b""), ("other/a", b"")], + file_type=stat.S_IFDIR, + mode=0o755, + ) + problems = compare.zip_problems(data, "demo") + assert "demo/: not under demo/" in problems + assert "demo/: directory entry" in problems + assert "demo/sub/: directory entry" in problems + assert "other/a: not under demo/" in problems + + def test_stored_entries(self) -> None: + data = _zip([("demo/a", b"x")], compress_type=zipfile.ZIP_STORED) + assert compare.zip_problems(data, "demo") == ["demo/a: not deflated"] + + def test_wrong_system(self) -> None: + data = _zip([("demo/a", b"x")], create_system=0) + assert compare.zip_problems(data, "demo") == [ + "demo/a: create_system 0, expected 3" + ] + + def test_symlink_entry(self) -> None: + data = _zip([("demo/a", b"target")], file_type=stat.S_IFLNK, mode=0o777) + assert compare.zip_problems(data, "demo") == [ + "demo/a: not a regular file (mode 120777)" + ] + + def test_unexpected_mode(self) -> None: + data = _zip([("demo/.env", b"x")], mode=0o600) + assert compare.zip_problems(data, "demo") == [ + "demo/.env: mode 600, expected 755 or 644" + ] + + def test_empty_and_broken(self) -> None: + assert compare.zip_problems(_zip([]), "demo") == ["the zip is empty"] + assert compare.zip_problems(b"nope", "demo")[0].startswith("not a zip file") + + def test_zip_root_ambiguous(self) -> None: + assert compare.zip_root(_zip([("a/x", b""), ("b/x", b"")])) == "" + + +# ---------------------------------------------------------------- compare: directory side + + +class TestReadDir: + def test_reads_files_recursively(self, tmp_path: Path) -> None: + (tmp_path / "src").mkdir() + (tmp_path / "src" / "main.py").write_bytes(b"m") + (tmp_path / "README.md").write_bytes(b"r") + tree, problems = compare.read_dir(str(tmp_path)) + assert problems == [] + assert tree.files == {"README.md": b"r", "src/main.py": b"m"} + + @pytest.mark.skipif(os.name == "nt", reason="POSIX file modes") + def test_modes_and_links(self, tmp_path: Path) -> None: + script = tmp_path / "run.sh" + script.write_bytes(b"#!/bin/sh\n") + script.chmod(0o755) + (tmp_path / "plain").write_bytes(b"") + os.symlink("plain", tmp_path / "link") + (tmp_path / "dir").mkdir() + os.symlink("dir", tmp_path / "dirlink") + tree, problems = compare.read_dir(str(tmp_path)) + assert tree.modes == {"plain": 0o644, "run.sh": 0o755} + assert sorted(problems) == [ + "dirlink: not a regular file in the CLI project", + "link: not a regular file in the CLI project", + ] + + def test_compare_zip_with_dir(self, tmp_path: Path) -> None: + project = tmp_path / "demo" + project.mkdir() + (project / ".env").write_bytes(f"SECRET_KEY={SECRET_B}\n".encode()) + (project / "main.py").write_bytes(b"print(1)\n") + data = _zip( + [ + ("demo/.env", f"SECRET_KEY={SECRET_A}\n".encode()), + ("demo/main.py", b"print(1)\n"), + ] + ) + assert compare.compare_zip_with_dir(data, "demo", str(project)) == [] + (project / "main.py").write_bytes(b"print(2)\n") + out = compare.compare_zip_with_dir(data, "demo", str(project)) + assert out[0] == "main.py: content differs" + + def test_compare_broken_zip_with_dir(self, tmp_path: Path) -> None: + out = compare.compare_zip_with_dir(b"nope", "demo", str(tmp_path)) + assert len(out) == 1 and out[0].startswith("not a zip file") + + +# ---------------------------------------------------------------- compare_with_cli + + +FAKE_FASTKIT = """ +import os, sys +args = sys.argv[1:] +if "--fail" in args: + print("boom", file=sys.stderr) + sys.exit(3) +name = args[args.index("--project-name") + 1] +os.makedirs(os.path.join(name, "scripts")) +with open(os.path.join(name, "main.py"), "wb") as f: + f.write(b"print(1)\\n") +with open(os.path.join(name, ".env"), "wb") as f: + f.write(b"SECRET_KEY=" + b"c" * 43 + b"\\n") +if "--stray" in args: + open("stray.txt", "w").close() +assert os.environ["GIT_CONFIG_NOSYSTEM"] == "1" +assert os.path.getsize(os.environ["GIT_CONFIG_GLOBAL"]) == 0 +assert "VIRTUAL_ENV" not in os.environ +""" + + +def _web_zip(root: str = "demo") -> bytes: + return _zip( + [ + (f"{root}/.env", f"SECRET_KEY={SECRET_A}\n".encode()), + (f"{root}/main.py", b"print(1)\n"), + ] + ) + + +class TestCompareWithCli: + @pytest.fixture + def fake(self, tmp_path: Path) -> List[str]: + script = tmp_path / "fake_fastkit.py" + script.write_text(FAKE_FASTKIT, encoding="utf-8") + return [str(script)] + + def _env(self, tmp_path: Path) -> Dict[str, str]: + base = dict(os.environ, VIRTUAL_ENV="/somewhere", GIT_DIR="/x") + return compare_with_cli.cli_env(base, str(tmp_path / "work")) + + def test_cli_env(self, tmp_path: Path) -> None: + env = self._env(tmp_path) + work = str(tmp_path / "work") + assert env["HOME"] == os.path.join(work, "home") and os.path.isdir(env["HOME"]) + assert os.path.getsize(env["GIT_CONFIG_GLOBAL"]) == 0 + assert env["GIT_CONFIG_NOSYSTEM"] == "1" and env["NO_COLOR"] == "1" + assert env["GIT_CEILING_DIRECTORIES"] == work + assert "VIRTUAL_ENV" not in env and "GIT_DIR" not in env + + def test_cli_env_drops_identity_and_python_paths(self, tmp_path: Path) -> None: + dropped = { + "PYTHONPATH": "/other/fastkit", + "PYTHONHOME": "/py", + "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": "user.name", + "GIT_CONFIG_VALUE_0": "Someone", + "GIT_CONFIG_PARAMETERS": "'user.email'='a@b.c'", + "GIT_AUTHOR_NAME": "A", + "GIT_AUTHOR_EMAIL": "a@b.c", + "GIT_COMMITTER_NAME": "C", + "GIT_COMMITTER_EMAIL": "c@b.c", + "EMAIL": "e@b.c", + "git_author_name": "lower-case on Windows", + } + base = {"PATH": os.environ.get("PATH", ""), "KEEP_ME": "1", **dropped} + env = compare_with_cli.cli_env(base, str(tmp_path / "work")) + assert not set(dropped) & set(env) + assert env["KEEP_ME"] == "1" and env["PATH"] == base["PATH"] + + def test_strip_program(self) -> None: + assert compare_with_cli.strip_program(["fastkit", "init", "-y"]) == [ + "init", + "-y", + ] + assert compare_with_cli.strip_program(["init", "-y"]) == ["init", "-y"] + with pytest.raises( + compare_with_cli.CompareError, match="expected a `fastkit init" + ): + compare_with_cli.strip_program(["fastkit", "startdemo"]) + with pytest.raises(compare_with_cli.CompareError): + compare_with_cli.strip_program([]) + + def test_equal_case(self, tmp_path: Path, fake: List[str]) -> None: + outcome = compare_with_cli.compare_case( + "hello", + _web_zip(), + "demo", + fake + ["init", "--project-name", "demo"], + fastkit=sys.executable, + work=str(tmp_path / "work"), + env=self._env(tmp_path), + planned=["main.py", ".env"], + ) + assert outcome.ok, outcome.problems + assert outcome.file_count == 2 + + def test_cli_failure(self, tmp_path: Path, fake: List[str]) -> None: + outcome = compare_with_cli.compare_case( + "x", + _web_zip(), + "demo", + fake + ["init", "--project-name", "demo", "--fail"], + fastkit=sys.executable, + work=str(tmp_path / "work"), + env=self._env(tmp_path), + ) + assert outcome.problems[0] == "fastkit exited with status 3" + assert " boom" in outcome.problems + + def test_cli_not_found(self, tmp_path: Path) -> None: + problems = compare_with_cli.run_cli( + str(tmp_path / "missing-fastkit"), + ["init"], + str(tmp_path / "cwd"), + self._env(tmp_path), + ) + assert problems[0].startswith("fastkit could not be started") + + def test_stray_files_in_workspace(self, tmp_path: Path, fake: List[str]) -> None: + outcome = compare_with_cli.compare_case( + "x", + _web_zip(), + "demo", + fake + ["init", "--project-name", "demo", "--stray"], + fastkit=sys.executable, + work=str(tmp_path / "work"), + env=self._env(tmp_path), + ) + assert outcome.problems == [ + "the CLI workspace holds ['demo', 'stray.txt'], expected ['demo']" + ] + + def test_differences_and_plan_mismatch( + self, tmp_path: Path, fake: List[str] + ) -> None: + web = _zip( + [ + ("demo/.env", f"SECRET_KEY={SECRET_A}\n".encode()), + ("demo/main.py", b"print(2)\n"), + ] + ) + outcome = compare_with_cli.compare_case( + "x", + web, + "demo", + fake + ["init", "--project-name", "demo"], + fastkit=sys.executable, + work=str(tmp_path / "work"), + env=self._env(tmp_path), + planned=["main.py", "README.md"], + ) + assert outcome.problems[0] == "main.py: content differs" + assert outcome.problems[-1] == ( + "the page's file list differs from the zip (not listed: ['.env'], not in zip: ['README.md'])" + ) + + def test_broken_web_zip(self, tmp_path: Path, fake: List[str]) -> None: + outcome = compare_with_cli.compare_case( + "x", + b"nope", + "demo", + fake + ["init", "--project-name", "demo"], + fastkit=sys.executable, + work=str(tmp_path / "work"), + env=self._env(tmp_path), + ) + assert len(outcome.problems) == 1 and outcome.problems[0].startswith( + "not a zip file" + ) + + def test_report(self, capsys: pytest.CaptureFixture[str]) -> None: + compare_with_cli.report(compare_with_cli.CaseOutcome("a", [], 3)) + compare_with_cli.report(compare_with_cli.CaseOutcome("b", ["x: differs"], 0)) + assert ( + capsys.readouterr().out == "ok a (3 files)\nFAIL b\n x: differs\n" + ) + + def test_parse_args(self, capsys: pytest.CaptureFixture[str]) -> None: + args = compare_with_cli.parse_args(["--assets", "a", "--cases", "c.json"]) + assert args.node == "node" and args.fastkit == "fastkit" and args.argv == [] + args = compare_with_cli.parse_args( + ["--zip", "d.zip", "--", "fastkit", "init", "--project-name", "d"] + ) + assert args.argv == ["fastkit", "init", "--project-name", "d"] + for bad in ( + ["--assets", "a"], + ["--zip", "d.zip"], + ["--assets", "a", "--cases", "c", "extra"], + ): + with pytest.raises(SystemExit): + compare_with_cli.parse_args(bad) + + def test_missing_node(self, tmp_path: Path) -> None: + cases = tmp_path / "cases.json" + cases.write_text(json.dumps([{"id": "a", "form": {}}]), encoding="utf-8") + code = compare_with_cli.main( + [ + "--assets", + "a", + "--cases", + str(cases), + "--node", + str(tmp_path / "no-node"), + ] + ) + assert code == 1 + + def test_missing_cases_file( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + code = compare_with_cli.main( + ["--assets", "a", "--cases", str(tmp_path / "missing.json")] + ) + assert code == 1 + assert "cannot read the cases file" in capsys.readouterr().err + + def test_parse_only(self) -> None: + assert compare_with_cli.parse_only(None) is None + assert compare_with_cli.parse_only(" 01-hello , ,02-x ") == ["01-hello", "02-x"] + for text in ("", ",", " , "): + with pytest.raises(compare_with_cli.CompareError, match="names no case id"): + compare_with_cli.parse_only(text) + + def test_select_cases(self) -> None: + cases = [{"id": "a"}, {"id": "b"}] + assert compare_with_cli.select_cases(cases, None) == cases + assert compare_with_cli.select_cases(cases, ["b"]) == [{"id": "b"}] + with pytest.raises(compare_with_cli.CompareError, match="unknown case id: c"): + compare_with_cli.select_cases(cases, ["b", "c"]) + + @pytest.mark.parametrize("content", ["[]", '{"cases": []}', "{}", "not json"]) + def test_cases_file_without_cases(self, tmp_path: Path, content: str) -> None: + cases = tmp_path / "cases.json" + cases.write_text(content, encoding="utf-8") + with pytest.raises(compare_with_cli.CompareError): + compare_with_cli.load_cases(str(cases)) + assert compare_with_cli.main(["--assets", "a", "--cases", str(cases)]) == 1 + + @pytest.mark.parametrize("only", [",", " ", "nope", "hello,nope"]) + def test_bad_only_fails_before_running( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, only: str + ) -> None: + cases = tmp_path / "cases.json" + cases.write_text(json.dumps([{"id": "hello", "form": {}}]), encoding="utf-8") + + def no_generate(*args: Any) -> None: + raise AssertionError("generate.mjs must not run") + + monkeypatch.setattr(compare_with_cli, "run_generate", no_generate) + args = ["--assets", "a", "--cases", str(cases), "--only", only] + assert compare_with_cli.main(args) == 1 + + def test_generate_failure(self, tmp_path: Path) -> None: + # Python cannot run generate.mjs, which stands in for a failing Node run. + with pytest.raises(compare_with_cli.CompareError, match="generate.mjs failed"): + compare_with_cli.run_generate( + sys.executable, "a", "c.json", str(tmp_path), "x" + ) + + def test_zip_mode(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + seen: Dict[str, Any] = {} + + def fake_run_cli( + fastkit: str, argv: List[str], cwd: str, env: Dict[str, str] + ) -> List[str]: + seen["argv"] = argv + os.makedirs(os.path.join(cwd, "demo")) + Path(cwd, "demo", "main.py").write_bytes(b"print(1)\n") + Path(cwd, "demo", ".env").write_bytes(f"SECRET_KEY={SECRET_B}\n".encode()) + return [] + + monkeypatch.setattr(compare_with_cli, "run_cli", fake_run_cli) + zip_path = tmp_path / "demo.zip" + zip_path.write_bytes(_web_zip()) + keep = tmp_path / "keep" + argv = [ + "--zip", + str(zip_path), + "--fastkit", + sys.executable, + "--keep", + str(keep), + "--", + ] + code = compare_with_cli.main( + argv + ["fastkit", "init", "--project-name", "demo"] + ) + assert code == 0 + assert seen["argv"] == ["init", "--project-name", "demo"] + assert (keep / "cli" / "zip" / "demo" / "main.py").exists() + assert ( + compare_with_cli.main(argv + ["init"]) == 2 + ) # --keep is not empty any more + + def test_zip_mode_rejects_bad_zips(self, tmp_path: Path) -> None: + bad = tmp_path / "bad.zip" + bad.write_bytes(b"nope") + two = tmp_path / "two.zip" + two.write_bytes(_zip([("a/x", b""), ("b/x", b"")])) + for path in (bad, two): + assert ( + compare_with_cli.main( + ["--zip", str(path), "--fastkit", sys.executable, "--", "init"] + ) + == 1 + ) + + def test_compare_all( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + ) -> None: + cases = tmp_path / "cases.json" + cases.write_text( + json.dumps([{"id": "hello", "form": {}}, {"id": "skipped", "form": {}}]), + encoding="utf-8", + ) + + def fake_generate( + node: str, assets: str, cases_path: str, out: str, only: Optional[str] + ) -> None: + assert only == "hello" + os.makedirs(out) + Path(out, "hello.zip").write_bytes(_web_zip()) + record = { + "argv": ["init", "--project-name", "demo"], + "root": "demo", + "files": [".env", "main.py"], + } + Path(out, "hello.json").write_text(json.dumps(record), encoding="utf-8") + + def fake_run_cli( + fastkit: str, argv: List[str], cwd: str, env: Dict[str, str] + ) -> List[str]: + os.makedirs(os.path.join(cwd, "demo")) + Path(cwd, "demo", "main.py").write_bytes(b"print(1)\n") + Path(cwd, "demo", ".env").write_bytes(f"SECRET_KEY={SECRET_B}\n".encode()) + return [] + + monkeypatch.setattr(compare_with_cli, "run_generate", fake_generate) + monkeypatch.setattr(compare_with_cli, "run_cli", fake_run_cli) + args = [ + "--assets", + "a", + "--cases", + str(cases), + "--only", + " hello ,", + "--node", + sys.executable, + "--fastkit", + sys.executable, + ] + assert compare_with_cli.main(args) == 0 + assert capsys.readouterr().out == "ok hello (2 files)\n1 of 1 cases equal\n" + + +# ---------------------------------------------------------------- check_site + + +def _site(tmp_path: Path, languages: Iterable[str] = check_site.LANGUAGES) -> Path: + site = tmp_path / "site" + assets = site / "assets" / "fastkit-generator" + (assets / "pyodide").mkdir(parents=True) + wheel = b"wheel" + (assets / "fastapi_fastkit-2.0.0-py3-none-any.whl").write_bytes(wheel) + manifest = { + "schema": 1, + "fastkit_version": "2.0.0", + "commit": "abc", + "wheel": "fastapi_fastkit-2.0.0-py3-none-any.whl", + "wheel_sha256": hashlib.sha256(wheel).hexdigest(), + "pyodide_version": build_assets.load_config().version, + "packages": ["jinja2"], + } + (assets / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8") + (assets / "NOTICE.txt").write_text("notice", encoding="utf-8") + for name in build_assets.load_config().core_files: + (assets / "pyodide" / name).write_bytes(b"core") + (assets / "pyodide" / "pyodide-lock.json").write_text( + json.dumps(_lock()), encoding="utf-8" + ) + for entry in _lock()["packages"].values(): + (assets / "pyodide" / entry["file_name"]).write_bytes(b"w") + for lang in check_site.LANGUAGES: + (assets / f"model-{lang}.json").write_text("{}", encoding="utf-8") + for lang in languages: + base = site if lang == "en" else site / lang + page = base / "start" / "web-generator" / "index.html" + page.parent.mkdir(parents=True) + page.write_text( + '
\n' + '\n', + encoding="utf-8", + ) + (base / "js").mkdir(exist_ok=True) + (base / "js" / "web-generator.mjs").write_text("// page", encoding="utf-8") + return site + + +class TestCheckSite: + def test_clean_site( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + site = _site(tmp_path) + assert check_site.check_site(str(site)) == [] + assert check_site.main([str(site)]) == 0 + assert "ok (en, ko, ja, zh, es, fr, de)" in capsys.readouterr().out + + def test_subset_of_languages(self, tmp_path: Path) -> None: + site = _site(tmp_path, languages=["en"]) + assert check_site.main([str(site), "--languages", "en"]) == 0 + assert check_site.main([str(site)]) == 1 + + def test_not_a_directory(self, tmp_path: Path) -> None: + assert check_site.check_site(str(tmp_path / "nope")) == [ + f"{tmp_path / 'nope'} is not a directory" + ] + + def test_assets_copied_per_locale(self, tmp_path: Path) -> None: + site = _site(tmp_path) + copy = site / "ko" / "assets" / "fastkit-generator" + copy.mkdir(parents=True) + (copy / "manifest.json").write_text("{}", encoding="utf-8") + problems = check_site.check_site(str(site)) + assert len(problems) == 1 and problems[0].startswith( + "expected one asset directory" + ) + + def test_missing_assets(self, tmp_path: Path) -> None: + site = _site(tmp_path) + assets = site / "assets" / "fastkit-generator" + (assets / "model-ko.json").unlink() + (assets / "pyodide" / "pyodide.asm.wasm").unlink() + ( + assets + / "pyodide" + / "markupsafe-3.0.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl" + ).unlink() + problems = check_site.check_site(str(site)) + assert sorted(problems) == sorted( + [ + "missing asset: assets/fastkit-generator/model-ko.json", + "missing asset: assets/fastkit-generator/pyodide/pyodide.asm.wasm", + "missing asset: assets/fastkit-generator/pyodide/" + "markupsafe-3.0.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl", + ] + ) + + def test_no_assets_at_all(self, tmp_path: Path) -> None: + site = _site(tmp_path) + (site / "assets" / "fastkit-generator" / "manifest.json").unlink() + problems = check_site.check_site(str(site)) + assert problems == [ + "expected one asset directory at assets/fastkit-generator/, found manifests: none" + ] + + def test_manifest_problems(self, tmp_path: Path) -> None: + site = _site(tmp_path) + assets = site / "assets" / "fastkit-generator" + manifest = json.loads((assets / "manifest.json").read_text(encoding="utf-8")) + manifest.update(schema=2, pyodide_version="0.1", packages=["jinja2", "rich"]) + (assets / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8") + (assets / manifest["wheel"]).write_bytes(b"changed") + problems = check_site.check_site(str(site)) + assert "manifest schema is 2, expected 1" in problems + assert any(p.startswith("manifest names Pyodide 0.1") for p in problems) + assert ( + "fastapi_fastkit-2.0.0-py3-none-any.whl does not match wheel_sha256 in the manifest" + in problems + ) + assert ( + "package 'rich' from the manifest is not in pyodide-lock.json" in problems + ) + + def test_missing_wheel(self, tmp_path: Path) -> None: + site = _site(tmp_path) + ( + site + / "assets" + / "fastkit-generator" + / "fastapi_fastkit-2.0.0-py3-none-any.whl" + ).unlink() + problems = check_site.check_site(str(site)) + assert problems == [ + "the wheel named in the manifest is missing: 'fastapi_fastkit-2.0.0-py3-none-any.whl'" + ] + + def test_page_problems(self, tmp_path: Path) -> None: + site = _site(tmp_path) + (site / "ko" / "start" / "web-generator" / "index.html").write_text( + "

nothing

", encoding="utf-8" + ) + (site / "ja" / "start" / "web-generator" / "index.html").write_text( + '
', + encoding="utf-8", + ) + (site / "zh" / "js" / "web-generator.mjs").unlink() + (site / "de" / "start" / "web-generator" / "index.html").unlink() + problems = check_site.check_site(str(site)) + ko_page = os.path.join("ko", "start", "web-generator", "index.html") + assert f'ko: {ko_page} has no id="fastkit-generator" element' in problems + assert f"ko: {ko_page} has no module script for web-generator.mjs" in problems + assert any( + p.startswith("ja: ") and "expected a relative path" in p for p in problems + ) + assert any( + p.startswith("zh: ") and "which is not in the site" in p for p in problems + ) + assert any(p.startswith("de: page missing") for p in problems) + assert check_site.main([str(site)]) == 1 diff --git a/tests/test_utils_output.py b/tests/test_utils_output.py new file mode 100644 index 00000000..1dfd89df --- /dev/null +++ b/tests/test_utils_output.py @@ -0,0 +1,297 @@ +# -------------------------------------------------------------------------- +# Click/rich-free helpers used by the generation path: the message facade +# (utils/output.py), the moved validators, project metadata and known +# example values, and the re-exports that keep the old import paths. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from pathlib import Path +from typing import Callable, Optional +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.utils import output +from fastapi_fastkit.utils.messages import Message, capture_messages +from fastapi_fastkit.utils.validation import ( + EMAIL_REGEX, + project_name_problem, + validate_project_name, +) + +HELPERS = [ + ("info", output.print_info, "Info"), + ("success", output.print_success, "Success"), + ("warning", output.print_warning, "Warning"), + ("error", output.print_error, "Error"), +] + + +class TestOutputHelpers: + @pytest.mark.parametrize("level,helper,title", HELPERS) + def test_captured_message_is_recorded_not_printed( + self, level: str, helper: Callable[..., None], title: str + ) -> None: + with patch("fastapi_fastkit.utils.main.console.print") as printed: + with capture_messages() as messages: + helper("hello") + helper("custom", title="T") + + printed.assert_not_called() + assert messages == [ + Message(level, "hello", title), # type: ignore[arg-type] + Message(level, "custom", "T"), # type: ignore[arg-type] + ] + + @pytest.mark.parametrize("level,helper,title", HELPERS) + def test_uncaptured_message_goes_to_the_rich_renderer( + self, level: str, helper: Callable[..., None], title: str + ) -> None: + target = f"fastapi_fastkit.utils.main.print_{level}" + with patch(target) as renderer: + helper("hello") + + args, kwargs = renderer.call_args + assert args == ("hello", title) + if level == "error": + assert kwargs == {"show_traceback": False} + + @pytest.mark.parametrize("level,helper,title", HELPERS) + def test_uncaptured_message_draws_a_panel( + self, level: str, helper: Callable[..., None], title: str + ) -> None: + with patch("fastapi_fastkit.utils.main.console.print") as printed: + helper("visible message") + + printed.assert_called_once() + panel = printed.call_args.args[0] + assert panel.title == title + assert "visible message" in str(panel.renderable) + + def test_print_error_passes_show_traceback(self) -> None: + with patch("fastapi_fastkit.utils.main.print_error") as renderer: + output.print_error("boom", "Oops", show_traceback=True) + + renderer.assert_called_once_with("boom", "Oops", show_traceback=True) + + +class TestHandleException: + def test_custom_message_is_rendered_with_traceback(self) -> None: + with patch("fastapi_fastkit.utils.main.print_error") as renderer: + output.handle_exception(ValueError("bad"), "Custom failure") + + renderer.assert_called_once_with("Custom failure", "Error", show_traceback=True) + + def test_default_message_names_the_exception(self) -> None: + with patch("fastapi_fastkit.utils.main.print_error") as renderer: + output.handle_exception(ValueError("bad")) + + renderer.assert_called_once_with("Error: bad", "Error", show_traceback=True) + + def test_captured_exception_is_recorded(self) -> None: + with patch("fastapi_fastkit.utils.main.console.print") as printed: + with capture_messages() as messages: + output.handle_exception(RuntimeError("down")) + + printed.assert_not_called() + assert messages == [Message("error", "Error: down", "Error")] + + def test_matches_the_rich_helper(self) -> None: + from fastapi_fastkit.utils import main + + with capture_messages() as facade: + output.handle_exception(KeyError("k"), None) + with capture_messages() as original: + main.handle_exception(KeyError("k"), None) + + assert facade == original + + def test_logs_the_exception(self) -> None: + with patch("fastapi_fastkit.utils.output.debug_log") as logged: + with capture_messages(): + output.handle_exception(ValueError("bad"), "Custom failure") + + logged.assert_called_once_with("Exception occurred: Custom failure", "error") + + +class TestProjectNameProblem: + @pytest.mark.parametrize( + "name,expected", + [ + ("", "empty"), + ("my project", "characters"), + ("my.project", "characters"), + ("a/b", "characters"), + (" padded", "characters"), + ("-", "characters"), + ("1project", "digit"), + ("class", "keyword"), + ("None", "keyword"), + ("my_project", None), + ("my-project", None), + ("Project2", None), + ("café_api", None), + ], + ) + def test_codes(self, name: str, expected: Optional[str]) -> None: + assert project_name_problem(name) == expected + + @pytest.mark.parametrize( + "name,message", + [ + ("", "Project name cannot be empty"), + ( + "bad name", + "Project name must contain only letters, numbers, hyphens, " + "and underscores", + ), + ("9lives", "Project name cannot start with a number"), + ("import", "Project name 'import' is a Python keyword"), + ], + ) + def test_validate_project_name_keeps_its_messages( + self, name: str, message: str + ) -> None: + assert validate_project_name(name) == (False, message) + + def test_validate_project_name_accepts_valid_names(self) -> None: + assert validate_project_name("good_name") == (True, None) + + +class TestReExports: + @pytest.mark.parametrize( + "name", + [ + "EMAIL_REGEX", + "project_name_problem", + "sanitize_custom_packages", + "validate_email_format", + "validate_feature_compatibility", + "validate_package_name", + "validate_project_name", + ], + ) + def test_interactive_validators(self, name: str) -> None: + from fastapi_fastkit.backend.interactive import validators + from fastapi_fastkit.utils import validation + + assert getattr(validators, name) is getattr(validation, name) + assert name in validators.__all__ + + @pytest.mark.parametrize( + "name", + [ + "ENV_EXAMPLE_NAMES", + "KNOWN_EXAMPLE_SECRETS", + "MCP_DEMO_PASSWORDS", + "NON_SECRET_ENV_NAMES", + ], + ) + def test_doctor_known(self, name: str) -> None: + from fastapi_fastkit.backend.doctor import known as doctor_known + from fastapi_fastkit.core import known + + assert getattr(doctor_known, name) is getattr(known, name) + assert doctor_known.__all__ == known.__all__ + + @pytest.mark.parametrize( + "name", + [ + "FASTKIT_DESCRIPTION_MARKER", + "FASTKIT_TOOL_SECTION", + "is_fastkit_project", + "read_fastkit_metadata", + "_pyproject_marks_fastkit", + "_pyproject_text_marks_fastkit", + ], + ) + def test_utils_main_project_meta(self, name: str) -> None: + from fastapi_fastkit.utils import main, project_meta + + assert getattr(main, name) is getattr(project_meta, name) + + def test_utils_main_email_regex(self) -> None: + from fastapi_fastkit.utils import main + + assert main.REGEX == EMAIL_REGEX + + +class TestProjectMeta: + def test_reads_the_tool_block(self, tmp_path: Path) -> None: + from fastapi_fastkit.utils.project_meta import ( + is_fastkit_project, + read_fastkit_metadata, + ) + + (tmp_path / "pyproject.toml").write_text( + '[project]\nname = "x"\n\n' + '[tool.fastapi-fastkit]\nmanaged = true\napp_module = "main:app"\n', + encoding="utf-8", + newline="\n", + ) + + assert is_fastkit_project(str(tmp_path)) + assert read_fastkit_metadata(str(tmp_path)) == { + "managed": True, + "app_module": "main:app", + } + + def test_malformed_pyproject_gives_empty_metadata(self, tmp_path: Path) -> None: + from fastapi_fastkit.utils.project_meta import read_fastkit_metadata + + (tmp_path / "pyproject.toml").write_text( + "[tool.fastapi-fastkit\n", encoding="utf-8", newline="\n" + ) + + assert read_fastkit_metadata(str(tmp_path)) == {} + + +class TestProjectMetaTextScans: + """The text scans read through ``utils.textio``; line endings and bad + bytes behave as before.""" + + @pytest.mark.parametrize("newline", ["\n", "\r\n", "\r"]) + def test_setup_py_marker_with_any_line_ending( + self, tmp_path: Path, newline: str + ) -> None: + from fastapi_fastkit.utils.project_meta import is_fastkit_project + + text = newline.join(["from setuptools import setup", "# FastAPI-fastkit", ""]) + (tmp_path / "setup.py").write_bytes(text.encode("utf-8")) + + assert is_fastkit_project(str(tmp_path)) + + def test_undecodable_setup_py_is_not_a_project(self, tmp_path: Path) -> None: + from fastapi_fastkit.utils.project_meta import is_fastkit_project + + (tmp_path / "setup.py").write_bytes(b"\xff\xfe fastapi-fastkit") + + assert not is_fastkit_project(str(tmp_path)) + + @pytest.mark.parametrize("newline", ["\n", "\r\n"]) + def test_malformed_pyproject_text_marker( + self, tmp_path: Path, newline: str + ) -> None: + from fastapi_fastkit.utils.project_meta import is_fastkit_project + + text = newline.join( + ["[project", "[tool.fastapi-fastkit]", "managed = true", ""] + ) + (tmp_path / "pyproject.toml").write_bytes(text.encode("utf-8")) + + assert is_fastkit_project(str(tmp_path)) + + def test_undecodable_malformed_pyproject(self, tmp_path: Path) -> None: + from fastapi_fastkit.utils.project_meta import _pyproject_text_marks_fastkit + + path = tmp_path / "pyproject.toml" + path.write_bytes(b"[tool.fastapi-fastkit\xff") + + assert not _pyproject_text_marks_fastkit(str(path)) + + +def test_core_known_holds_the_example_secrets() -> None: + from fastapi_fastkit.core import known + + assert isinstance(known.KNOWN_EXAMPLE_SECRETS, frozenset) + assert "changethis" in known.KNOWN_EXAMPLE_SECRETS diff --git a/uv.lock b/uv.lock index a6cbb786..9228ee89 100644 --- a/uv.lock +++ b/uv.lock @@ -6,6 +6,24 @@ resolution-markers = [ "python_full_version < '3.15'", ] +[[package]] +name = "aiofiles" +version = "25.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/41/c3/534eac40372d8ee36ef40df62ec129bee4fdb5ad9706e58a29be53b2c970/aiofiles-25.1.0.tar.gz", hash = "sha256:a8d728f0a29de45dc521f18f07297428d56992a742f0cd2701ba86e44d23d5b2", size = 46354, upload-time = "2025-10-09T20:51:04.358Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/8a/340a1555ae33d7354dbca4faa54948d76d89a27ceef032c8c3bc661d003e/aiofiles-25.1.0-py3-none-any.whl", hash = "sha256:abe311e527c862958650f9438e859c1fa7568a141b22abcd015e120e86a85695", size = 14668, upload-time = "2025-10-09T20:51:03.174Z" }, +] + +[[package]] +name = "annotated-doc" +version = "0.0.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0b/7d/bdbf3062e5dae31da8b3de1e3269110beb93d268df4a7f6d22b167c6cee0/annotated_doc-0.0.7.tar.gz", hash = "sha256:0a30ef8f5322a4173720ae6712dc9a5e58f5a19868f3f167b4b5778db066c2b5", size = 10764, upload-time = "2026-11-18T11:06:55.181Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5e/b1/9530d6bee606979d54501adcc767d958a38929827f11a524b0d93429d2ad/annotated_doc-0.0.7-py3-none-any.whl", hash = "sha256:6bc31bbbec6dfaaedc1676dbc11dbda96fe22a2b5c400e9ebad113fec44a9dc6", size = 5286, upload-time = "2026-11-18T11:06:54.096Z" }, +] + [[package]] name = "annotated-types" version = "0.7.0" @@ -372,6 +390,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/55/e2/2537ebcff11c1ee1ff17d8d0b6f4db75873e3b0fb32c2d4a2ee31ecb310a/docstring_parser-0.17.0-py3-none-any.whl", hash = "sha256:cf2569abd23dce8099b300f9b4fa8191e9582dda731fd533daf54c4551658708", size = 36896, upload-time = "2025-07-21T07:35:00.684Z" }, ] +[[package]] +name = "fastapi" +version = "0.165.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-doc" }, + { name = "anyio" }, + { name = "opentelemetry-api" }, + { name = "pydantic" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/27/f9/e7820ef181026fea100bde02d811445bf8e883362d7092b6928767147056/fastapi-0.165.0.tar.gz", hash = "sha256:dd94d4128319c1e1d50535ab023ab698f850a4d2822f0e181747b46f4ff3c0ab", size = 557984, upload-time = "2026-11-18T19:15:37.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c4/c1/3b74c030262a1b38b1fee180f80b4007bbc11c9ac12028cb18c7bcecaec9/fastapi-0.165.0-py3-none-any.whl", hash = "sha256:896f48462042bb4f162147eb8fac7e858753dc1f486765709baf105d70e4fc5b", size = 159475, upload-time = "2026-11-18T19:15:35.345Z" }, +] + [[package]] name = "fastapi-fastkit" source = { editable = "." } @@ -411,6 +447,13 @@ docs = [ { name = "types-pyyaml" }, { name = "urllib3" }, ] +test-runtime = [ + { name = "aiofiles" }, + { name = "fastapi" }, + { name = "httpx" }, + { name = "pydantic-settings" }, + { name = "pyyaml" }, +] translation = [ { name = "anthropic" }, { name = "anyio" }, @@ -451,6 +494,13 @@ docs = [ { name = "types-pyyaml", specifier = ">=6.0.12.20250915" }, { name = "urllib3", specifier = ">=2.8.0" }, ] +test-runtime = [ + { name = "aiofiles", specifier = ">=25.1.0" }, + { name = "fastapi", specifier = ">=0.141.1" }, + { name = "httpx", specifier = ">=0.28.1" }, + { name = "pydantic-settings", specifier = ">=2.15.0" }, + { name = "pyyaml", specifier = ">=6.0.3" }, +] translation = [ { name = "anthropic", specifier = ">=0.74.0" }, { name = "anyio", specifier = ">=4.14.2" }, @@ -1050,6 +1100,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/55/4f/dbc0c124c40cb390508a82770fb9f6e3ed162560181a85089191a851c59a/openai-2.8.1-py3-none-any.whl", hash = "sha256:c6c3b5a04994734386e8dad3c00a393f56d3b68a27cd2e8acae91a59e4122463", size = 1022688, upload-time = "2025-11-17T22:39:57.675Z" }, ] +[[package]] +name = "opentelemetry-api" +version = "1.45.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c1/6f/232335085d0f5b1fd61fcbae1099a2d433ac4d0e5ab5f8423a1a9861a8d8/opentelemetry_api-1.45.3.tar.gz", hash = "sha256:3b8b2769fffe5118a310c93639da9c02cbbcfde488866c721b0e7bc0d67a4ab5", size = 73279, upload-time = "2026-12-01T09:38:28.314Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/20/9cae605f31522831fdda12161c543b011295177d5179dcf48b3f3d89913c/opentelemetry_api-1.45.3-py3-none-any.whl", hash = "sha256:7b9fcabfdfda5167446caa86641f085915fc1eb7ea9cbd23038c861f6a3c02bf", size = 60336, upload-time = "2026-12-01T09:38:07.013Z" }, +] + [[package]] name = "packaging" version = "26.3" @@ -1197,6 +1259,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f7/07/34573da085946b6a313d7c42f82f16e8920bfd730665de2d11c0c37a74b5/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76d0819de158cd855d1cbb8fcafdf6f5cf1eb8e470abe056d5d161106e38062b", size = 2139017, upload-time = "2025-11-04T13:42:59.471Z" }, ] +[[package]] +name = "pydantic-settings" +version = "2.16.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "python-dotenv" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/59/28/227c843eedd29bd78e132e5aafa420d83154b10465c312f9c21ff2eaf77d/pydantic_settings-2.16.3.tar.gz", hash = "sha256:10e36f616623ebb586c05ca3d3cd22927146869db413d4f14c20c514442a1337", size = 311716, upload-time = "2026-11-13T11:18:30.102Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4c/26/3e68379ca313b6aa58e11fbd8b28d5c6f1b9f4428d70222ba021a76797ec/pydantic_settings-2.16.3-py3-none-any.whl", hash = "sha256:d1db16a2d34006323a1b42c0640898da58adfbad7ec30baaa9e2b18aafc08999", size = 82679, upload-time = "2026-11-13T11:18:28.73Z" }, +] + [[package]] name = "pygments" version = "2.20.0" @@ -1273,6 +1350,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/60/91/1aa70d3dfcab0dbcf88a2cbc3bce7f7c69562287a90216e617eaa4937e25/python_discovery-1.6.4-py3-none-any.whl", hash = "sha256:530179cc51a1816d512b15635b3dc931295ae12efb183783ad31190a5d425d2b", size = 39385, upload-time = "2026-10-19T01:45:13.668Z" }, ] +[[package]] +name = "python-dotenv" +version = "1.2.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/74/26/2fbeedb218a787a5eea551c7532cac4e009f83d689dd2faa0d0353473f86/python_dotenv-1.2.4.tar.gz", hash = "sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0", size = 60824, upload-time = "2026-10-01T05:36:10Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/d1/38f3a3405989a89ac18390803e70c6ad7c7760da4f9b83cbeca0c44a0c72/python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc", size = 23266, upload-time = "2026-10-01T05:36:08.633Z" }, +] + [[package]] name = "pytokens" version = "0.4.1" @@ -1440,6 +1526,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" }, ] +[[package]] +name = "starlette" +version = "1.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/48/bb/3d8757f21e9a53d9035c9eb039a777047139a16bfdbedfc7a58241c3d914/starlette-1.10.0.tar.gz", hash = "sha256:b8399098d4c1e3522734f7235dc79b1fc967f96cf139c81e0fa30479e0685f9b", size = 2734356, upload-time = "2026-10-24T15:04:12.342Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/2e/947cfe02def9371c07cd5bf5b6b61c829e9aecb9904db02a66cfafbc1eec/starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4", size = 80571, upload-time = "2026-10-24T15:04:10.371Z" }, +] + [[package]] name = "tqdm" version = "4.67.1" From a5e82e232332dbd1e01fcbd3036c40e8fe672543 Mon Sep 17 00:00:00 2001 From: bnbong Date: Thu, 3 Dec 2026 22:49:18 +0900 Subject: [PATCH 2/2] [FIX] keep commas inside package requirements, accept ~=, fix zip name check on Windows --- docs/js/web-generator-core.mjs | 53 ++++++- docs/js/web-generator.mjs | 4 +- scripts/web_generator/compare.py | 15 +- src/fastapi_fastkit/utils/validation.py | 4 +- tests/fixtures/web_generator/cases.json | 5 +- tests/fs_names.py | 43 +++++ .../test_interactive_validators.py | 22 +++ tests/test_catalog/test_loader.py | 1 + tests/test_docs/test_web_generator_page.py | 147 ++++++++++++++++++ tests/test_generation/test_browser.py | 9 ++ tests/test_generation/test_browser_parity.py | 25 +++ tests/test_generation/test_dependencies.py | 10 ++ .../test_web_generator_scripts.py | 41 ++++- 13 files changed, 369 insertions(+), 10 deletions(-) create mode 100644 tests/fs_names.py diff --git a/docs/js/web-generator-core.mjs b/docs/js/web-generator-core.mjs index 15e83b0e..38a7b6e6 100644 --- a/docs/js/web-generator-core.mjs +++ b/docs/js/web-generator-core.mjs @@ -1,6 +1,7 @@ // Runs the fastkit generator in Pyodide. Environment-neutral on purpose: no // DOM access, so the docs page's worker and the Node CI runner -// (scripts/web_generator/generate.mjs) execute exactly this code. +// (scripts/web_generator/generate.mjs) execute exactly this code. The page +// also takes its pure form helpers (splitExtraPackages) from here. export const MANIFEST_SCHEMA = 1; @@ -32,6 +33,56 @@ export async function sha256Hex(bytes) { return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join(""); } +// A comma followed by one of these continues the version specifier +// ("httpx>=0.27,<1") instead of starting a new package. +const VERSION_OPERATOR = /^[<>=!~]/; +const SPACE = /\s/; + +// The extra packages field: entries separated by commas, spaces or newlines. +// A comma inside [extras] or before a version operator stays in its entry, +// and spaces there are dropped, because the Python check rejects an entry +// with inner spaces: "pydantic[email, timezone]>=2, <3" is one entry, +// "pydantic[email,timezone]>=2,<3". +export function splitExtraPackages(text) { + const source = String(text); + const entries = []; + let current = ""; + let depth = 0; + const next = (from) => { + let index = from; + while (index < source.length && SPACE.test(source[index])) index += 1; + return index; + }; + const flush = () => { + if (current) entries.push(current); + current = ""; + }; + for (let index = 0; index < source.length; index += 1) { + const char = source[index]; + if (SPACE.test(char)) { + if (depth > 0) continue; + const after = next(index); + // Spaces before a comma: the comma decides. + if (source[after] !== ",") flush(); + index = after - 1; + } else if (char === "," && depth === 0) { + const after = next(index + 1); + if (current && VERSION_OPERATOR.test(source.slice(after))) { + current += ","; + index = after - 1; + } else { + flush(); + } + } else { + if (char === "[") depth += 1; + else if (char === "]" && depth > 0) depth -= 1; + current += char; + } + } + flush(); + return entries; +} + function isMissing(error) { return Boolean(error) && (error.status === 404 || error.code === "ENOENT"); } diff --git a/docs/js/web-generator.mjs b/docs/js/web-generator.mjs index c6dbf1c1..5dca37ce 100644 --- a/docs/js/web-generator.mjs +++ b/docs/js/web-generator.mjs @@ -7,6 +7,8 @@ // Material's "navigation.instant" feature is enabled one day, mount() must be // called again on each page change (Material's document$ observable). +import { splitExtraPackages } from "./web-generator-core.mjs"; + const LANGUAGES = ["en", "ko", "ja", "zh", "es", "fr", "de"]; const FORM_SCHEMA = 1; const CHECK_DELAY_MS = 200; @@ -517,7 +519,7 @@ class Generator { form.author = this.fields.author.value; form.author_email = this.fields.author_email.value; form.description = this.fields.description.value; - form.extra_packages = this.fields.extra_packages.value.split(",").map((item) => item.trim()).filter(Boolean); + form.extra_packages = splitExtraPackages(this.fields.extra_packages.value); return form; } diff --git a/scripts/web_generator/compare.py b/scripts/web_generator/compare.py index e620a776..9626b913 100644 --- a/scripts/web_generator/compare.py +++ b/scripts/web_generator/compare.py @@ -58,6 +58,16 @@ def unsafe_name_reason(name: str) -> Optional[str]: return None +def stored_name(info: zipfile.ZipInfo) -> str: + """The entry name as stored in the zip, before zipfile normalises it. + + ``ZipInfo.filename`` is cut at the first NUL and, on Windows, has every + backslash turned into "/" (``os.sep``), which would hide exactly the + names :func:`unsafe_name_reason` looks for. + """ + return info.orig_filename + + def zip_problems(data: bytes, root: str) -> List[str]: """Hygiene problems of a web zip whose entries must all live under ``root/``.""" problems: List[str] = [] @@ -67,14 +77,13 @@ def zip_problems(data: bytes, root: str) -> List[str]: return [f"not a zip file: {exc}"] with archive: infos = archive.infolist() - names = [info.filename for info in infos] + names = [stored_name(info) for info in infos] if not infos: problems.append("the zip is empty") if names != sorted(names): problems.append("entries are not sorted by name") seen: set[str] = set() - for info in infos: - name = info.filename + for info, name in zip(infos, names): if name in seen: problems.append(f"{name}: duplicate entry") seen.add(name) diff --git a/src/fastapi_fastkit/utils/validation.py b/src/fastapi_fastkit/utils/validation.py index 6cbad816..f48a45f6 100644 --- a/src/fastapi_fastkit/utils/validation.py +++ b/src/fastapi_fastkit/utils/validation.py @@ -42,8 +42,8 @@ def validate_package_name(package: str) -> bool: if not package or not isinstance(package, str): return False - # Remove version specifiers and extras for validation - package_name = re.split(r"[<>=!\[]", package)[0].strip() + # Remove version specifiers (``~=`` included) and extras for validation + package_name = re.split(r"[<>=!~\[]", package)[0].strip() # Basic package name pattern: letters, numbers, hyphens, underscores, dots # Must start with letter or number diff --git a/tests/fixtures/web_generator/cases.json b/tests/fixtures/web_generator/cases.json index c62ccf99..5a1a4927 100644 --- a/tests/fixtures/web_generator/cases.json +++ b/tests/fixtures/web_generator/cases.json @@ -259,11 +259,12 @@ "customise": true, "extra_packages": [ "orjson", - "httpx2>=0.1" + "httpx2>=0.1", + "tenacity>=9.0,<10" ] }, "native": true, - "covers": "--extra-package" + "covers": "--extra-package, a multi-clause specifier" }, { "id": "23-domain-identity", diff --git a/tests/fs_names.py b/tests/fs_names.py new file mode 100644 index 00000000..12dcd4f5 --- /dev/null +++ b/tests/fs_names.py @@ -0,0 +1,43 @@ +# -------------------------------------------------------------------------- +# File names the running file system encoding cannot hold. +# +# A project directory is named after the project, so a test that writes +# ``café_api`` to disk needs a file system encoding that can encode "é". +# Linux under a C locale with UTF-8 mode off (PYTHONUTF8=0, the CI +# encoding-guard job) uses ASCII for file names; neither ``fastkit init`` nor +# ``browser.build`` can create such a directory there, so the test is +# skipped instead of failing on the environment. macOS and Windows always +# encode file names as UTF-8. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import sys +from typing import Optional + +import pytest + + +def unencodable_name_reason(name: str) -> Optional[str]: + """Why ``name`` cannot be a file name here, or ``None`` when it can. + + ``sys.getfilesystemencoding()`` is read at call time (``os.fsencode`` + captures it at import), and the check is strict: no error handler may + replace or escape a character the encoding lacks. + """ + encoding = sys.getfilesystemencoding() + try: + name.encode(encoding) + except UnicodeEncodeError: + return ( + f"{name!r} cannot be a file name under the file system encoding " + f"{encoding!r} (a non-UTF-8 C locale); the CLI could not create " + "this project directory either" + ) + return None + + +def skip_unless_encodable_name(name: str) -> None: + """Skip the running test when ``name`` cannot be written to disk here.""" + reason = unencodable_name_reason(name) + if reason: + pytest.skip(reason) diff --git a/tests/test_backends/test_interactive_validators.py b/tests/test_backends/test_interactive_validators.py index 6c792f21..877b64d8 100644 --- a/tests/test_backends/test_interactive_validators.py +++ b/tests/test_backends/test_interactive_validators.py @@ -84,6 +84,28 @@ def test_valid_package_name_with_version_and_extras(self) -> None: # then assert result is True + @pytest.mark.parametrize( + "package_name", + ["httpx~=0.27", "httpx[http2]~=0.27", "httpx~=0.27,<1", "httpx>=0.27,!=0.27.1"], + ) + def test_valid_package_name_with_compatible_release( + self, package_name: str + ) -> None: + """Test validation of package names with ``~=`` and multiple clauses.""" + # when + result = validate_package_name(package_name) + + # then + assert result is True + + def test_invalid_package_name_only_an_operator(self) -> None: + """Test validation fails when no name comes before ``~=``.""" + # when + result = validate_package_name("~=0.27") + + # then + assert result is False + def test_invalid_package_name_empty_string(self) -> None: """Test validation fails for empty string.""" # given diff --git a/tests/test_catalog/test_loader.py b/tests/test_catalog/test_loader.py index 5e7eb8e3..4382c0c5 100644 --- a/tests/test_catalog/test_loader.py +++ b/tests/test_catalog/test_loader.py @@ -121,6 +121,7 @@ class TestNames: ("requirement", "name"), [ ("sqlalchemy[asyncio]>=2", "sqlalchemy"), + ("httpx~=0.27", "httpx"), ("Foo_Bar.baz", "foo-bar-baz"), (" pytest ; python_version>'3'", "pytest"), ("-r requirements.txt", "-r requirements-txt"), diff --git a/tests/test_docs/test_web_generator_page.py b/tests/test_docs/test_web_generator_page.py index db7a18ef..0f51ee2e 100644 --- a/tests/test_docs/test_web_generator_page.py +++ b/tests/test_docs/test_web_generator_page.py @@ -6,11 +6,16 @@ # -------------------------------------------------------------------------- import json import re +import shlex +import shutil +import subprocess from pathlib import Path from typing import Dict, List, Set import pytest +from fastapi_fastkit.generation import browser + ROOT = Path(__file__).resolve().parents[2] DOCS = ROOT / "docs" JS = DOCS / "js" @@ -186,6 +191,7 @@ def test_core_module_has_no_dom_access() -> None: "makeSecret", "sha256Hex", "MANIFEST_SCHEMA", + "splitExtraPackages", ): assert re.search( r"export (async function|function|class|const) %s\b" % export, code @@ -328,3 +334,144 @@ def test_core_keeps_the_package_loading_error() -> None: code = _read(JS / "web-generator-core.mjs") assert "errorCallback() {}" not in code assert re.search(r"errorCallback\(message\)", code) + + +# ------------------------------------------------------------------ +# The extra packages field (splitExtraPackages in the core module) +# ------------------------------------------------------------------ + +#: Field text -> the form's ``extra_packages``. Commas inside [extras] and +#: before a version operator stay in the entry; spaces there are dropped. +EXTRA_PACKAGES = [ + ("orjson, httpx", ["orjson", "httpx"]), + ("httpx>=0.27,<1", ["httpx>=0.27,<1"]), + ("httpx>=0.27, <1", ["httpx>=0.27,<1"]), + ("httpx>=0.27 , <1", ["httpx>=0.27,<1"]), + ("httpx>=0.27, !=0.27.1", ["httpx>=0.27,!=0.27.1"]), + ("httpx~=0.27, <1", ["httpx~=0.27,<1"]), + ("pydantic[email,timezone]", ["pydantic[email,timezone]"]), + ("pydantic[email, timezone]", ["pydantic[email,timezone]"]), + ( + "pydantic[email,timezone]>=2,<3, orjson", + ["pydantic[email,timezone]>=2,<3", "orjson"], + ), + ("orjson\nhttpx\r\n fastapi-users", ["orjson", "httpx", "fastapi-users"]), + ("orjson httpx", ["orjson", "httpx"]), + ("", []), + (" , ,", []), + (",orjson,, httpx,", ["orjson", "httpx"]), +] +#: Broken input stays in entries the Python check then names. +EXTRA_PACKAGES_INVALID = [ + (",<1", ["<1"]), +] +#: Splitting only: the Python check accepts an unclosed "[" (it reads only +#: the name part), which is not the page's call. +EXTRA_PACKAGES_SPLIT_ONLY = [ + ("pydantic[email, orjson", ["pydantic[email,orjson"]), +] + + +def test_extra_packages_field_uses_the_core_parser() -> None: + source = _read(JS / "web-generator.mjs") + assert 'import { splitExtraPackages } from "./web-generator-core.mjs";' in source + form_data = _method(source, "formData") + assert ( + "form.extra_packages = splitExtraPackages(this.fields.extra_packages.value);" + in form_data + ) + assert '.split(",")' not in form_data + + +@pytest.fixture(scope="module") +def split_by_node() -> Dict[str, List[str]]: + node = shutil.which("node") + if node is None: + pytest.skip("Node.js is not installed") + script = ( + "import { readFileSync } from 'node:fs';" + "import { pathToFileURL } from 'node:url';" + "const [core] = process.argv.slice(1);" + "const { splitExtraPackages } = await import(pathToFileURL(core).href);" + "const texts = JSON.parse(readFileSync(0, 'utf8'));" + "const out = Object.fromEntries(texts.map((t) => [t, splitExtraPackages(t)]));" + "process.stdout.write(JSON.stringify(out));" + ) + result = subprocess.run( + [node, "--input-type=module", "-e", script, str(JS / "web-generator-core.mjs")], + input=json.dumps( + [ + text + for text, _ in EXTRA_PACKAGES + + EXTRA_PACKAGES_INVALID + + EXTRA_PACKAGES_SPLIT_ONLY + ] + ), + capture_output=True, + encoding="utf-8", + timeout=60, + check=False, + ) + assert result.returncode == 0, result.stderr + return json.loads(result.stdout) + + +@pytest.mark.parametrize( + "text, expected", + EXTRA_PACKAGES + EXTRA_PACKAGES_INVALID + EXTRA_PACKAGES_SPLIT_ONLY, +) +def test_split_extra_packages_under_node( + text: str, expected: List[str], split_by_node: Dict[str, List[str]] +) -> None: + assert split_by_node[text] == expected + + +def _extra_packages_form(packages: List[str]) -> Dict[str, object]: + return { + "schema": 1, + "project_name": "extra_app", + "level": "single-file", + "customise": True, + "extra_packages": packages, + } + + +@pytest.mark.parametrize( + "packages", [expected for _, expected in EXTRA_PACKAGES if expected] +) +def test_split_extra_packages_pass_the_python_check(packages: List[str]) -> None: + check = browser.check_form(_extra_packages_form(packages)) + assert check["ok"], check["problems"] + assert check["command"].count("--extra-package") == len(packages) + # The bash command line gives back each entry as one argument. + shown = shlex.split(check["command_text"]) + assert shown.count("--extra-package") == len(packages) + for package in packages: + assert shown[shown.index(package) - 1] == "--extra-package" + + +@pytest.mark.parametrize("text, packages", EXTRA_PACKAGES_INVALID) +def test_broken_extra_packages_fail_the_python_check( + text: str, packages: List[str] +) -> None: + check = browser.check_form(_extra_packages_form(packages)) + assert not check["ok"] + assert check["problems"] == [ + { + "field": "extra_packages", + "code": "package", + "params": {"package": packages[0]}, + } + ] + + +def test_multi_constraint_requirement_is_quoted_for_both_shells() -> None: + check = browser.check_form( + _extra_packages_form(["httpx>=0.27,<1", "pydantic[email,timezone]>=2,<3"]) + ) + assert check["ok"], check["problems"] + bash, powershell = check["command_text"], check["command_text_windows"] + assert '--extra-package "httpx>=0.27,<1"' in bash + assert '--extra-package "pydantic[email,timezone]>=2,<3"' in bash + assert "--extra-package 'httpx>=0.27,<1'" in powershell + assert "--extra-package 'pydantic[email,timezone]>=2,<3'" in powershell diff --git a/tests/test_generation/test_browser.py b/tests/test_generation/test_browser.py index 1d16af83..ada4bc94 100644 --- a/tests/test_generation/test_browser.py +++ b/tests/test_generation/test_browser.py @@ -381,6 +381,15 @@ def test_extra_packages_with_spaces_or_control_characters(package: str) -> None: ] +def test_compatible_release_extra_package_is_accepted() -> None: + check = browser.check_form( + form(level="single-file", customise=True, extra_packages=["httpx~=0.27"]) + ) + assert check["ok"], check["problems"] + command = check["command"] + assert command[command.index("httpx~=0.27") - 1] == "--extra-package" + + def test_extra_packages_on_hello() -> None: assert problems_of(form(customise=True, extra_packages=["orjson"])) == [ {"field": "extra_packages", "code": "not_offered", "params": {"level": "hello"}} diff --git a/tests/test_generation/test_browser_parity.py b/tests/test_generation/test_browser_parity.py index 03778b01..f22a7e3e 100644 --- a/tests/test_generation/test_browser_parity.py +++ b/tests/test_generation/test_browser_parity.py @@ -30,6 +30,7 @@ from fastapi_fastkit.generation.guide import next_steps from fastapi_fastkit.utils import platform from fastapi_fastkit.utils.filemodes import is_executable_path +from tests.fs_names import skip_unless_encodable_name, unencodable_name_reason CASES_FILE = ( Path(__file__).resolve().parents[1] / "fixtures" / "web_generator" / "cases.json" @@ -106,12 +107,36 @@ def test_untouched_customise_gives_the_production_command() -> None: assert "--feature" not in plain["command"] +@pytest.mark.parametrize( + "encoding, skipped", + [("utf-8", False), ("ascii", True), ("cp1252", False), ("cp949", True)], +) +def test_unencodable_project_names_are_skipped( + encoding: str, skipped: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + # The CI encoding-guard job (C locale, PYTHONUTF8=0) uses ASCII file + # names; macOS and Windows never do, so the encoding is patched here. + assert "café_api" in {case["form"]["project_name"] for case in NATIVE} + monkeypatch.setattr("sys.getfilesystemencoding", lambda: encoding) + reason = unencodable_name_reason("café_api") + assert (reason is not None) is skipped + if skipped: + assert reason is not None and repr(encoding) in reason + with pytest.raises(pytest.skip.Exception, match="cannot be a file name"): + skip_unless_encodable_name("café_api") + else: + skip_unless_encodable_name("café_api") + assert unencodable_name_reason("hello_app") is None + + @pytest.mark.parametrize("case", NATIVE, ids=[case["id"] for case in NATIVE]) def test_web_zip_equals_cli_project( case: Dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: form, lang = case["form"], case.get("lang", "en") name = form["project_name"] + # Both sides write a directory named after the project. + skip_unless_encodable_name(name) check = browser.check_form(form, lang) assert check["ok"], check archive, meta = browser.build( diff --git a/tests/test_generation/test_dependencies.py b/tests/test_generation/test_dependencies.py index 106a8f43..4a929f6d 100644 --- a/tests/test_generation/test_dependencies.py +++ b/tests/test_generation/test_dependencies.py @@ -18,6 +18,7 @@ ) from fastapi_fastkit.backend.project_builder.dependency_collector import ( DependencySet, + merge_requirements, ) from fastapi_fastkit.core.settings import FastkitConfig from fastapi_fastkit.generation import GenerationSpec, ProjectInfo @@ -28,6 +29,7 @@ render_dependency_files, requirement_name, resolve_dependencies, + sanitized_custom_packages, sync_pyproject_dev_declarations, template_dependencies, ) @@ -316,6 +318,14 @@ def test_has_specifier() -> None: assert not has_specifier("sqlalchemy[asyncio]") +def test_compatible_release_names_the_package() -> None: + # ``~=`` ends the name part everywhere a requirement is split. + assert requirement_name("httpx~=0.27") == "httpx" + assert has_specifier("httpx~=0.27") + assert sanitized_custom_packages(["httpx~=0.27", "HTTPX~=0.27"]) == ["httpx~=0.27"] + assert merge_requirements(["httpx~=0.27", "httpx[http2]"]) == ["httpx[http2]~=0.27"] + + def test_httpx2_stays_runtime_with_oauth2() -> None: deps = resolve_dependencies(_features(authentication="OAuth2", testing="Basic")) diff --git a/tests/test_scripts/test_web_generator_scripts.py b/tests/test_scripts/test_web_generator_scripts.py index 7bdb84f0..832e1758 100644 --- a/tests/test_scripts/test_web_generator_scripts.py +++ b/tests/test_scripts/test_web_generator_scripts.py @@ -183,6 +183,9 @@ def _zip( with zipfile.ZipFile(buffer, "w") as archive: for name, data in entries: info = zipfile.ZipInfo(name, date_time=(2026, 12, 3, 12, 0, 0)) + # The constructor cuts the name at a NUL and, on Windows, turns + # each backslash into "/"; the name set afterwards is stored as is. + info.filename = name info.compress_type = compress_type info.create_system = create_system info.external_attr = (file_type | (modes or {}).get(name, mode)) << 16 @@ -190,6 +193,19 @@ def _zip( return buffer.getvalue() +class _WindowsSeparators: + """A view of ``os`` with Windows path separators, for ``zipfile.os``.""" + + sep = "\\" + altsep = "/" + + def __init__(self, real: ModuleType) -> None: + self._real = real + + def __getattr__(self, name: str) -> Any: + return getattr(self._real, name) + + def _tree(files: Dict[str, bytes], modes: Optional[Dict[str, int]] = None) -> Any: return compare.Tree( files=dict(files), modes={rel: (modes or {}).get(rel, 0o644) for rel in files} @@ -883,9 +899,32 @@ def test_duplicate(self) -> None: ], ) def test_unsafe_names(self, name: str, reason: str) -> None: - problems = compare.zip_problems(_zip([(name, b"")]), "demo") + data = _zip([(name, b"")]) + assert name.encode("ascii") in data # stored exactly, on every OS + problems = compare.zip_problems(data, "demo") assert problems == [f"{name!r}: {reason}"] + def test_nul_in_stored_name(self) -> None: + data = _zip([("demo/a\x00b", b"")]) + assert b"demo/a\x00b" in data + assert compare.zip_problems(data, "demo") == ["'demo/a\\x00b': NUL in name"] + + @pytest.mark.parametrize( + "name, reason", + [("demo\\evil", "backslash in name"), ("demo/a\x00b", "NUL in name")], + ) + def test_unsafe_names_under_windows_separators( + self, name: str, reason: str, monkeypatch: pytest.MonkeyPatch + ) -> None: + # zipfile reads os.sep / os.altsep at call time; Windows has "\\" + # and "/". Only zipfile's view of os changes, so pytest is unaffected. + windows_os = _WindowsSeparators(os) + monkeypatch.setattr(zipfile, "os", windows_os) + assert zipfile.ZipInfo("demo\\evil").filename == "demo/evil" + data = _zip([(name, b"")]) + assert name.encode("ascii") in data + assert compare.zip_problems(data, "demo") == [f"{name!r}: {reason}"] + def test_unsafe_name_reason_for_empty_and_nul(self) -> None: assert compare.unsafe_name_reason("") == "empty name" assert compare.unsafe_name_reason("demo/a\x00b") == "NUL in name"