diff --git a/.github/workflows/translate-docs.yml b/.github/workflows/translate-docs.yml index a177e6f0..70c32453 100644 --- a/.github/workflows/translate-docs.yml +++ b/.github/workflows/translate-docs.yml @@ -8,12 +8,11 @@ on: required: false type: string api_provider: - description: 'AI API provider for translation' + description: 'AI API provider for translation (OpenAI-compatible)' required: true type: choice options: - openai - - anthropic default: openai specific_files: description: 'Specific files to translate (space-separated, relative to docs/en/). Example: index.md start/installation.md' @@ -51,35 +50,47 @@ jobs: with: python-version: '3.12' + # The package itself renders the generated blocks after translating. - name: Install dependencies run: | python -m pip install --upgrade pip - pip install openai anthropic + pip install . openai - name: Configure Git run: | git config --global user.name "github-actions[bot]" git config --global user.email "github-actions[bot]@users.noreply.github.com" + # The next step opens the pull request, so the script never does (--no-pr). - name: Run translation env: TRANSLATION_API_KEY: ${{ secrets.TRANSLATION_API_KEY }} + API_PROVIDER: ${{ inputs.api_provider }} + TARGET_LANGUAGE: ${{ inputs.target_language }} + SPECIFIC_FILES: ${{ inputs.specific_files }} run: | - ARGS="--api-provider ${{ inputs.api_provider }}" + ARGS=(--api-provider "$API_PROVIDER" --no-pr) - if [ -n "${{ inputs.target_language }}" ]; then - ARGS="$ARGS --target-lang ${{ inputs.target_language }}" + if [ -n "$TARGET_LANGUAGE" ]; then + ARGS+=(--target-lang "$TARGET_LANGUAGE") fi - if [ -n "${{ inputs.specific_files }}" ]; then - ARGS="$ARGS --files ${{ inputs.specific_files }}" + if [ -n "$SPECIFIC_FILES" ]; then + read -r -a FILES <<< "$SPECIFIC_FILES" + ARGS+=(--files "${FILES[@]}") fi - if [ "${{ inputs.create_pr }}" = "false" ]; then - ARGS="$ARGS --no-pr" - fi + python scripts/translate.py "${ARGS[@]}" - python scripts/translate.py $ARGS + - name: Render generated blocks + env: + TARGET_LANGUAGE: ${{ inputs.target_language }} + run: | + if [ -n "$TARGET_LANGUAGE" ]; then + python scripts/docs_blocks.py --lang "$TARGET_LANGUAGE" + else + python scripts/docs_blocks.py + fi - name: Create Pull Request if: inputs.create_pr == true diff --git a/CHANGELOG.md b/CHANGELOG.md index b819ca77..71ae6233 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,6 +115,7 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - The documentation is reorganised into Start, Learn, How-to, Reference and Contributing; the Learn track follows one project from `hello` to `production`, and old page addresses redirect to their new pages. - CLI reference tables and help texts are generated from the catalog and the CLI, and the configuration-file and environment-variable sections that described settings fastkit never read are removed. +- The documentation translation script leaves code and generated blocks untouched, skips hand-translated pages and fails when a page could not be translated; its workflow offers only the provider the script supports. ### Upgrade notes for existing projects diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7dfee21e..e8a9d8ab 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -111,7 +111,7 @@ Key commands for contributors: - `make serve-docs` - Serve documentation locally #### Translation -- `make translate` - Translate documentation (supports LANG, PROVIDER, MODEL parameters) +- `make translate` - Translate documentation (supports LANG and MODEL parameters) ### Development Workflow @@ -434,12 +434,12 @@ FastAPI-fastkit documentation supports multiple languages. Contributing translat ```bash pdm install -G docs -G translation -# Or: pip install mkdocs mkdocs-material mkdocs-static-i18n openai anthropic +# Or: pip install mkdocs mkdocs-material mkdocs-static-i18n openai ``` #### 2. Set Up API Key -Get an API key from OpenAI or Anthropic and set it as an environment variable: +Get an OpenAI API key (or a key for another OpenAI-compatible API, used with `--api-base-url`) and set it as an environment variable: ```bash export TRANSLATION_API_KEY="your-api-key-here" @@ -466,9 +466,8 @@ make translate # Translate to specific language make translate LANG=ko -# Specify API provider and model -make translate LANG=ko PROVIDER=github MODEL=gpt-4o-mini -make translate LANG=ko PROVIDER=openai MODEL=gpt-4 +# Specify the model +make translate LANG=ko MODEL=gpt-4 ``` #### Using Script Directly @@ -523,24 +522,14 @@ You can also translate manually: To add support for a new language: -1. **Update `scripts/translation_config.json`**: -```json -{ - "code": "pt", - "name": "Portuguese", - "native_name": "Português", - "enabled": true -} -``` - -2. **Update `mkdocs.yml`**: +1. **Update `mkdocs.yml`**: ```yaml - locale: pt name: Português build: true ``` -3. **Run translation**: +2. **Run translation**: ```bash python scripts/translate.py --target-lang pt ``` @@ -550,19 +539,14 @@ python scripts/translate.py --target-lang pt **Core Components:** - **`scripts/translate.py`**: AI-powered translation script - - Supports OpenAI GPT-4 and Anthropic Claude - - Preserves markdown formatting and code blocks + - Calls the OpenAI API, or another OpenAI-compatible API with `--api-base-url` + - Sends only the prose: code blocks and generated blocks stay unchanged - Creates GitHub PRs automatically - **`scripts/setup-i18n-structure.sh`**: Migration tool - Moves docs to language-specific directories - Creates symbolic links for shared assets -- **`scripts/translation_config.json`**: Configuration - - Language settings - - Translation options - - Quality check parameters - - **`.github/workflows/translate-docs.yml`**: GitHub Actions workflow - Automated translation on trigger - Manual workflow dispatch @@ -587,7 +571,7 @@ docs/ **Import Error:** ```bash -pip install openai anthropic +pip install openai ``` **API Key Error:** diff --git a/Makefile b/Makefile index 107461ef..79bd78f8 100644 --- a/Makefile +++ b/Makefile @@ -141,11 +141,10 @@ all: ## Run complete development workflow $(MAKE) build # Translation commands -translate: ## Translate documentation - Usage: make translate LANG=ko PROVIDER=github MODEL=gpt-4o-mini +translate: ## Translate documentation - Usage: make translate LANG=ko MODEL=gpt-4o-mini @echo "Starting translation..." @CMD="python scripts/translate.py"; \ if [ -n "$(LANG)" ]; then CMD="$$CMD --target-lang $(LANG)"; fi; \ - if [ -n "$(PROVIDER)" ]; then CMD="$$CMD --api-provider $(PROVIDER)"; fi; \ if [ -n "$(MODEL)" ]; then CMD="$$CMD --model $(MODEL)"; fi; \ echo "Running: $$CMD"; \ $$CMD diff --git a/docs/en/contributing/template-creation-guide.md b/docs/en/contributing/template-creation-guide.md index 772a1a9c..dc8578c1 100644 --- a/docs/en/contributing/template-creation-guide.md +++ b/docs/en/contributing/template-creation-guide.md @@ -109,7 +109,7 @@ app = FastAPI( `tests/test_templates/test_concept_comments.py` checks every rule in this section. -## Checks +## Checks {#checks} ### Inspect a template locally diff --git a/docs/en/contributing/translation-guide.md b/docs/en/contributing/translation-guide.md index 65f26e3c..1e64bea2 100644 --- a/docs/en/contributing/translation-guide.md +++ b/docs/en/contributing/translation-guide.md @@ -1,6 +1,6 @@ # Translation guide -The documentation is published in seven languages: English (`en`), Korean (`ko`), Japanese (`ja`), Chinese (`zh`), Spanish (`es`), French (`fr`) and German (`de`). This page explains what to translate, what stays in English, and how the generated tables, the catalog texts and the web generator page are translated. +The documentation is published in seven languages: English (`en`), Korean (`ko`), Japanese (`ja`), Chinese (`zh`), Spanish (`es`), French (`fr`) and German (`de`). This page explains what to translate, what stays in English, how the generated tables, the catalog texts and the web generator page are translated, and how the tests check a translation. ## English is the source @@ -8,17 +8,18 @@ Every page is written in English first, in `docs/en/`. Each language has the sam When a language has no file for a page, the site shows the English page in that language's menu. Treat that as a gap to fill, not as the normal state. -`CHANGELOG.md` stays in English. Each `docs//changelog.md` contains only `{!CHANGELOG.md!}`, which includes the English file. +`CHANGELOG.md` stays in English. Each `docs//changelog.md` contains only `\{!CHANGELOG.md!}`, which includes the English file. ## What stays in English -- Everything the command line prints or asks: prompts, messages, tables and help texts. Readers compare the page with their terminal. +- Everything the command line prints or asks: prompts, messages, tables, help texts and other output. Readers compare the page with their terminal. - Commands, options, file names, paths, code, configuration keys and package names, inside and outside code blocks. +- Code blocks. Every fenced block stays exactly as in English, comments and sample output included. - The `cli` generated blocks (the `--help` texts on the CLI reference page) and the check titles of the `doctor-checks` table. The script renders them in English in every language. - Text inside images. Images are shared files in `docs/img/`; every language uses the same image, so link to it and never make a translated copy. -- The template-id headings on the example projects page (`## fastapi-auth-jwt` and the others). Their anchors are redirect targets. +- Link targets and heading ids. Some headings end with an id such as `{#features}`, because other pages and redirects link to it. Translate the heading text and keep the id. The template-id headings on the example projects page (`## fastapi-auth-jwt {#fastapi-auth-jwt}` and the others) stay as they are. -Translate the prose around them, headings, admonition text and link texts. Keep relative links as they are: the paths are the same in every language. +Translate the prose around them, headings, admonition text, link texts and the alt text of every image. Keep relative links as they are: the paths are the same in every language. ## Generated blocks @@ -37,9 +38,9 @@ $ python scripts/docs_blocks.py --lang ko $ python scripts/docs_blocks.py --check ``` -Catalog blocks (`levels`, `features`, `rules`, `package-managers`, `examples`, `concepts`) take their texts from the catalog overlay of the page's language, described below. The fixed words of the tables, such as the column headings, come from the `HEADINGS` table at the top of `scripts/docs_blocks.py`; a language without an entry there gets the English words, so add one for yours. The `cli` blocks and the check titles in the `doctor-checks` table stay in English, because they are the command line's own text. +Catalog blocks (`levels`, `features`, `rules`, `package-managers`, `examples`, `concepts`) take their texts from the catalog overlay of the page's language, described below. The fixed words of the tables come from the `HEADINGS` table at the top of `scripts/docs_blocks.py`: column headings, short sentences such as `{when} needs {require}.`, and the punctuation and joins of lists (`separator`, `join_or`, `join_and`), so that a language such as Japanese can drop the spaces around them. A translated language needs an entry with every key of `en` and the same `{placeholders}`; a language without an entry gets the English words. The `cli` blocks and the check titles in the `doctor-checks` table stay in English, because they are the command line's own text. -## Catalog overlays +## Catalog overlays {#catalog-overlays} Level descriptions, feature labels and summaries, rule messages, concept titles and the Next steps texts come from the catalog. The English text is in `src/fastapi_fastkit/catalog/catalog.toml`; each language has an overlay at `src/fastapi_fastkit/catalog/i18n/.toml` with the same keys: @@ -97,27 +98,39 @@ A label that is not listed stays in English. When the English `nav` gets a new s ## Machine translation -`scripts/translate.py` sends English pages to an OpenAI-compatible API and writes the result to `docs//` at the same path. It needs the `translation` dependency group (`pdm install -G translation`) and an API key in `--api-key`, `TRANSLATION_API_KEY` or, with `--api-provider github`, `GITHUB_TOKEN`. +`scripts/translate.py` sends English pages to the OpenAI API and writes the result to `docs//` at the same path. Another OpenAI-compatible API works too: pass its address with `--api-base-url`. It needs the `translation` dependency group (`pdm install -G translation`) and an API key in `--api-key` or `TRANSLATION_API_KEY`. ```console $ python scripts/translate.py --help -usage: translate.py [-h] [--target-lang TARGET_LANG] - [--api-provider {openai,github}] [--api-key API_KEY] - [--api-base-url API_BASE_URL] [--model MODEL] [--no-pr] - [--files FILES [FILES ...]] [--docs-dir DOCS_DIR] - [--max-retries MAX_RETRIES] [--retry-delay RETRY_DELAY] +usage: translate.py [-h] [--target-lang TARGET_LANG] [--api-provider {openai}] + [--api-key API_KEY] [--api-base-url API_BASE_URL] + [--model MODEL] [--no-pr] [--files FILES [FILES ...]] + [--docs-dir DOCS_DIR] [--max-retries MAX_RETRIES] + [--retry-delay RETRY_DELAY] [--request-delay REQUEST_DELAY] ... ``` Use it with care: -- Without `--files` it translates every `.md` file under `docs/en/` and overwrites the existing translations. Pass the pages you mean with `--files` (paths relative to `docs/en/`), and leave out `start/web-generator.md`, whose rules are above. -- It translates the whole file, generated blocks included. Run `python scripts/docs_blocks.py --lang ` afterwards to restore them. +- Without `--files` it translates every `.md` file under `docs/en/` and overwrites the existing translations. Pass the pages you mean with `--files` (paths relative to `docs/en/`). +- It never translates `start/web-generator.md`, whose rules are above, or `changelog.md`. +- Code blocks, generated blocks and front matter are not sent to the API and come back unchanged, with the file's line endings. Run `python scripts/docs_blocks.py --lang ` afterwards to render the generated blocks in your language. +- When a page cannot be translated, for example because the answer lost one of the placeholder lines that stand for the code, the script writes the other pages and then exits with status 1. - Without `--no-pr` it creates a branch, commits, pushes and opens a pull request with `gh`, then switches to `main`. Pass `--no-pr` to review the files locally first. - A fluent speaker reviews every machine translation before it is merged. -`make translate LANG=ko PROVIDER=github MODEL=openai/gpt-4o-mini` runs the same script. +`make translate LANG=ko MODEL=gpt-4o-mini` runs the same script. The "Translate Documentation" workflow on GitHub runs it, renders the generated blocks and opens the pull request. + +## Translate a language + +A language is either pending, with its old 1.x pages still in place, or translated. The pending languages are listed in `PENDING_LOCALES` in `tests/test_docs/docs_support.py`. The pull request that translates a language: + +1. Translates every page of `docs/en/` into `docs//` at the same path, including the alt text of every image. +2. Deletes the pages of `docs//` that have no English page. Their old addresses redirect to the new pages. +3. Adds the language's entry to `HEADINGS` in `scripts/docs_blocks.py`, with every key of `en`. +4. Renders the generated blocks with `python scripts/docs_blocks.py --lang `. +5. Removes the language from `PENDING_LOCALES`, so that the checks below run for it. ## Check your translation @@ -127,4 +140,14 @@ $ python -m pytest tests/test_docs tests/test_catalog -q $ mkdocs build --strict -d site ``` +For every language that is not pending, `tests/test_docs/test_locale_parity.py` compares each page with the English page and names the page and the problem: + +- the same pages as `docs/en/`, no more and no fewer, and `changelog.md` identical to the English file; +- the same generated blocks in the same order, rendered for the language, and the same front matter; +- the same code blocks, with identical content; +- the same heading levels in the same order, the same heading ids, and the same admonitions and tabs (`!!!`, `???`, `===`) with their types; +- the same images in the same order, each with an alt text, and the same link targets; +- every link to a `#fragment` reaches a heading of that language's page; +- translated prose: a page that is the English text fails, and so does a sentence of four words or more left in English (outside tables). + The strict build fails on a link to a page that exists neither in your language nor in English. Open the built pages of your language and check the menu labels, the generated tables and the web generator page. diff --git a/docs/en/how-to/example-projects.md b/docs/en/how-to/example-projects.md index 1fc3c626..cccb3857 100644 --- a/docs/en/how-to/example-projects.md +++ b/docs/en/how-to/example-projects.md @@ -16,7 +16,7 @@ Besides the five levels, fastkit ships five example projects. Each one shows a s The endpoint lists come from the `/openapi.json` of each project, started with `uv run uvicorn` right after `uv sync`. Every example also answers `GET /health` with `{"status":"ok"}`, which the tables leave out. -## fastapi-custom-response +## fastapi-custom-response {#fastapi-custom-response} One response envelope for every JSON answer, errors included: `timestamp`, `status`, `code`, `path` and `message`. Exception handlers wrap `HTTPException`, validation errors and unhandled exceptions in the same envelope. The items live in a JSON file (`src/mocks/mock_items.json`), read and written asynchronously. It needs no setup beyond `uv sync`. The request after the table shows a 404 in the envelope. @@ -46,7 +46,7 @@ $ curl -s http://127.0.0.1:8000/api/v1/items/999 -## fastapi-auth-jwt +## fastapi-auth-jwt {#fastapi-auth-jwt} Accounts with access and refresh tokens. Refresh tokens rotate on every use, passwords are hashed with Argon2id, and dependencies guard routes by role and by scope. Users are stored with SQLModel; the login, register and refresh endpoints are rate limited. @@ -78,7 +78,7 @@ Setup: none for a first run. The app uses a local SQLite file (`DATABASE_URL=sql -## fastapi-sqlmodel +## fastapi-sqlmodel {#fastapi-sqlmodel} SQLModel over an async engine, Alembic migrations, a generic CRUD base class and paginated list endpoints. One `DATABASE_URL` selects SQLite, PostgreSQL or MySQL, and the tests stay on SQLite. @@ -115,7 +115,7 @@ For PostgreSQL or MySQL, the README section "Use PostgreSQL or MySQL" starts a l -## fastapi-mcp +## fastapi-mcp {#fastapi-mcp} A FastAPI app whose item endpoints are also MCP (Model Context Protocol) tools: `list_items`, `get_item`, `create_item`, `replace_item`, `update_item` and `delete_item`. Users log in with the OAuth2 password flow. Item reads are public; writes need the owner's token. @@ -155,7 +155,7 @@ Setup: the user store is empty until you plug in your own (`get_users_db()` in ` -## fastapi-llm-agent +## fastapi-llm-agent {#fastapi-llm-agent} A Claude chat agent that streams its reply over server-sent events and runs a tool-call loop with two bundled tools (`calculator`, `current_time`). Conversations are kept in memory behind an interface you can replace. The tests replace the Anthropic client with a scripted fake, so they need no key and no network. diff --git a/docs/en/how-to/scripts-and-config.md b/docs/en/how-to/scripts-and-config.md index 208d435e..1d851f06 100644 --- a/docs/en/how-to/scripts-and-config.md +++ b/docs/en/how-to/scripts-and-config.md @@ -84,7 +84,7 @@ description = "[FastAPI-fastkit templated]" An invalid value is reported (`Config key 'version' must be a PEP 440 version such as 1.0.0, got 'one'`) and nothing is written. -## Configurations saved by fastkit 1.x +## Configurations saved by fastkit 1.x {#configurations-saved-by-fastkit-1x} Files written by fastkit 1.x keep working. A `minimal` preset (or no preset) creates a `fastapi-single-module` project, and the CORS and Pagination utilities, which every project now includes, are accepted. For a 1.x file `old.json` with `"architecture_preset": "minimal"` and `"utilities": ["CORS", "Pagination"]`: diff --git a/docs/en/reference/cli.md b/docs/en/reference/cli.md index ba037b38..d5486bbd 100644 --- a/docs/en/reference/cli.md +++ b/docs/en/reference/cli.md @@ -308,7 +308,7 @@ Options: -## fastkit doctor +## fastkit doctor {#fastkit-doctor} Checks a generated project for known problems and fixes the safe ones. [Check and fix a project](../how-to/doctor.md) shows a full run. diff --git a/docs/en/reference/generated-projects.md b/docs/en/reference/generated-projects.md index 42574574..fc603414 100644 --- a/docs/en/reference/generated-projects.md +++ b/docs/en/reference/generated-projects.md @@ -2,7 +2,7 @@ This page describes what every project that `fastkit init` creates has in common: the HTTP API it serves, its settings, its dependency files, the metadata block that the other `fastkit` commands read, and the comments fastkit leaves in the code. The [Levels and features](levels-and-features.md) page lists where each level puts its files. -## HTTP API +## HTTP API {#http-api} The `layered`, `domain` and `production` levels serve the same example API, and every resource that `fastkit addroute` adds follows the same rules. These are the routes of a `domain` project: diff --git a/docs/en/reference/levels-and-features.md b/docs/en/reference/levels-and-features.md index 797b9db9..a91f2cd5 100644 --- a/docs/en/reference/levels-and-features.md +++ b/docs/en/reference/levels-and-features.md @@ -56,7 +56,7 @@ Middleware setup, such as `setup_logging(app)` for structured logging, goes abov fastkit changes a template's `main.py` only by adding import lines and single statements at the two comment lines. It does not rewrite template code or the template's lifespan: a feature that needs startup or shutdown work brings it in its own router. The one exception is `single-file`: when a generated module needs the settings, fastkit moves them from `src/main.py` to `src/core/config.py` and prints a note, because the module would otherwise import `src.main`. -## Features +## Features {#features} @@ -208,7 +208,7 @@ Container deployment files. Select with `--feature deployment=OPTION`; several o -## FastAPI concepts +## FastAPI concepts {#fastapi-concepts} diff --git a/pdm.lock b/pdm.lock index 4405950d..dbee4218 100644 --- a/pdm.lock +++ b/pdm.lock @@ -5,7 +5,7 @@ groups = ["default", "dev", "docs", "test-runtime", "translation"] strategy = ["inherit_metadata"] lock_version = "4.5.0" -content_hash = "sha256:56e8c86505c1513ca24b2552ede59133d1ee56c035124e1575e6a120a4229487" +content_hash = "sha256:917a194bf8ac260d4a23f6f0606a314e11d3b707e9b3943a6fe5fc55fe7b87e6" [[metadata.targets]] requires_python = ">=3.12" @@ -46,27 +46,6 @@ files = [ {file = "annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89"}, ] -[[package]] -name = "anthropic" -version = "0.96.0" -requires_python = ">=3.9" -summary = "The official Python library for the anthropic API" -groups = ["translation"] -dependencies = [ - "anyio<5,>=3.5.0", - "distro<2,>=1.7.0", - "docstring-parser<1,>=0.15", - "httpx<1,>=0.25.0", - "jiter<1,>=0.4.0", - "pydantic<3,>=1.9.0", - "sniffio", - "typing-extensions<5,>=4.14", -] -files = [ - {file = "anthropic-0.96.0-py3-none-any.whl", hash = "sha256:9a6e335a354602a521cd9e777e92bfd46ba6e115bf9bbfe6135311e8fb2015b2"}, - {file = "anthropic-0.96.0.tar.gz", hash = "sha256:9de947b737f39452f68aa520f1c2239d44119c9b73b0fb6d4e6ca80f00279ee6"}, -] - [[package]] name = "anyio" version = "4.15.1" @@ -542,17 +521,6 @@ files = [ {file = "distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed"}, ] -[[package]] -name = "docstring-parser" -version = "0.18.0" -requires_python = ">=3.8" -summary = "Parse Python docstrings in reST, Google and Numpydoc format" -groups = ["translation"] -files = [ - {file = "docstring_parser-0.18.0-py3-none-any.whl", hash = "sha256:b3fcbed555c47d8479be0796ef7e19c2670d428d72e96da63f3a40122860374b"}, - {file = "docstring_parser-0.18.0.tar.gz", hash = "sha256:292510982205c12b1248696f44959db3cdd1740237a968ea1e2e7a900eeb2015"}, -] - [[package]] name = "fastapi" version = "0.165.0" diff --git a/pyproject.toml b/pyproject.toml index bf71e822..b82a017c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -128,7 +128,6 @@ test-runtime = [ ] translation = [ "openai>=2.8.1", - "anthropic>=0.74.0", # anyio < 4.14.2 — TLSStream IDNA host-name encoding allows certificate spoofing (GHSA-82r6-8w77-94w6); transitive via httpx "anyio>=4.14.2", ] diff --git a/scripts/docs_blocks.py b/scripts/docs_blocks.py index a6d4c6f7..e305e021 100755 --- a/scripts/docs_blocks.py +++ b/scripts/docs_blocks.py @@ -40,8 +40,11 @@ CLOSE = "" FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})") -#: Fixed words of the rendered blocks, by language. Stage 7 adds the six -#: locales; a missing language or key falls back to English. +#: Fixed words and sentence patterns of the rendered blocks, by language. +#: Every language-dependent piece of a rendering is here, punctuation and +#: list joins included. A translated language has every key of "en" with +#: the same placeholders (tests/test_docs/test_locale_parity.py); a language +#: without an entry, or a missing key, falls back to English. HEADINGS: Dict[str, Dict[str, str]] = { "en": { "level": "Level", @@ -49,7 +52,7 @@ "template": "Template", "database_question": "Database question", "read_first": "Read first", - "preset": "preset", + "preset_template": "{template} (preset {preset})", "yes_default": "Yes (default: {default})", "no": "No", "option": "Option", @@ -71,8 +74,10 @@ "rule_adds": "{when} adds {packages}.", "rule_note": "{when}: {message}", "any": "any {axis}", - "or": "or", - "and": "and", + "selection": "{axis} {values}", + "separator": ", ", + "join_or": "{items} or {last}", + "join_and": "{items} and {last}", "dev_package": "{package} (dev)", "package_manager": "Package manager", "dependency_file": "Dependency file", @@ -191,8 +196,8 @@ def _code(value: str) -> str: return f"`{value}`" -def _codes(values: Sequence[str]) -> str: - return ", ".join(_code(v) for v in values) +def _codes(values: Sequence[str], lang: str) -> str: + return _text(lang, "separator").join(_code(v) for v in values) def _no_args(name: str, args: str) -> None: @@ -208,8 +213,8 @@ def render_levels(args: str, lang: str) -> str: for level in catalog.levels: if level.preset: preset = catalog.preset(level.preset) - template = ( - f"{_code(preset.template)} ({_text(lang, 'preset')} {_code(preset.id)})" + template = _text(lang, "preset_template").format( + template=_code(preset.template), preset=_code(preset.id) ) else: template = _code(level.template or "") @@ -265,8 +270,8 @@ def render_features(args: str, lang: str) -> str: [ _code(option.id), summary, - _codes(option.runtime), - _codes(option.dev), + _codes(option.runtime, lang), + _codes(option.dev, lang), link, ] ) @@ -280,7 +285,8 @@ def render_features(args: str, lang: str) -> str: def _join(values: Sequence[str], lang: str, word: str = "or") -> str: if len(values) < 2: return "".join(values) - return ", ".join(values[:-1]) + f" {_text(lang, word)} " + values[-1] + items = _text(lang, "separator").join(values[:-1]) + return _text(lang, f"join_{word}").format(items=items, last=values[-1]) def _selection( @@ -292,7 +298,8 @@ def _selection( if choices == ("*",): parts.append(_text(lang, "any").format(axis=label)) else: - parts.append(f"{label} {_join([_code(c) for c in choices], lang)}") + values = _join([_code(c) for c in choices], lang) + parts.append(_text(lang, "selection").format(axis=label, values=values)) return _join(parts, lang, "and") diff --git a/scripts/translate.py b/scripts/translate.py index dd2e0590..ce67d8de 100755 --- a/scripts/translate.py +++ b/scripts/translate.py @@ -9,12 +9,16 @@ # - Creating GitHub Pull Requests for review # # This script translate en/ directory materials to other languages. +# Fenced code, generated blocks and front matter never reach the API: they +# are replaced by placeholder lines and put back unchanged. Pages that are +# maintained by hand in each language (HAND_MAINTAINED) are skipped. # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import argparse import logging import os +import re import subprocess import sys import time @@ -23,12 +27,121 @@ from typing import List, Optional, Tuple sys.path.insert(0, str(Path(__file__).parent.parent / "src")) +sys.path.insert(0, str(Path(__file__).parent)) + +from docs_blocks import find_blocks # noqa: E402 -logging.basicConfig( - level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" -) logger = logging.getLogger(__name__) +#: API providers this script can call (any OpenAI-compatible endpoint, see +#: --api-base-url); the translate-docs workflow offers the same choices. +API_PROVIDERS = ("openai",) + +#: Pages under docs/en/ that are never machine-translated: the web +#: generator page is translated by hand (see the translation guide) and +#: changelog.md only includes CHANGELOG.md in every language. +HAND_MAINTAINED = ("start/web-generator.md", "changelog.md") + +#: A line that stands for a part of the page the API must not see. +KEEP_MARKER = "" + +#: A fence line; indented fences sit inside list items, admonitions and tabs. +FENCE = re.compile(r"^(\s*)(`{3,}|~{3,})(.*)$") + + +def _fence_end(lines: List[str], start: int) -> int: + """ + Index of the last line of the fence opened at ``start``: its closing + line, the line before the end of its container (a line indented less + than an indented fence), or the last line of the page. + """ + opening = FENCE.match(lines[start]) + assert opening is not None + indent, fence = len(opening.group(1)), opening.group(2) + end = start + 1 + while end < len(lines): + line = lines[end] + close = FENCE.match(line) + if ( + close + and close.group(2)[0] == fence[0] + and len(close.group(2)) >= len(fence) + and not close.group(3).strip() + ): + return end + if indent and line.strip() and len(line) - len(line.lstrip()) < indent: + end -= 1 + while end > start and not lines[end].strip(): + end -= 1 + return end + end += 1 + return len(lines) - 1 + + +def protect(text: str) -> Tuple[str, List[str]]: + """ + Replace the front matter, every fenced code block and every generated + block of a page by a placeholder line each. + + :return: the text to translate and the parts, in placeholder order + :raises docs_blocks.BlockError: on broken generated-block markers + """ + lines = text.replace("\r\n", "\n").split("\n") + starts = {block.start: block.end for block in find_blocks(text)} + out: List[str] = [] + kept: List[str] = [] + index = 0 + if lines[0] == "---" and "---" in lines[1:]: + index = lines.index("---", 1) + 1 + kept.append("\n".join(lines[:index])) + out.append(KEEP_MARKER.format(0)) + while index < len(lines): + line = lines[index] + end = starts.get(index) + match = FENCE.match(line) + if ( + end is None + and match + and not (match.group(2)[0] == "`" and "`" in match.group(3)) + ): + end = _fence_end(lines, index) + if end is None: + out.append(line) + index += 1 + continue + # The placeholder keeps the indentation, so that a fence stays + # inside its list item or admonition. + out.append( + line[: len(line) - len(line.lstrip())] + KEEP_MARKER.format(len(kept)) + ) + kept.append("\n".join(lines[index : end + 1])) + index = end + 1 + return "\n".join(out), kept + + +def restore(text: str, kept: List[str]) -> str: + """ + Put the protected parts back into a translated text. + + :raises ValueError: if a placeholder is missing, repeated or out of order + """ + lines = text.split("\n") + found = [ + (index, int(match.group(1))) + for index, line in enumerate(lines) + for match in [re.fullmatch(r"\s*\s*", line)] + if match + ] + if [number for _, number in found] != list(range(len(kept))): + raise ValueError( + "the translation lost, repeated or moved the placeholder lines " + f"of the code and generated blocks: {[n for _, n in found]}" + ) + for index, number in found: + # The part carries its own indentation. + lines[index] = kept[number] + return "\n".join(lines) + @dataclass class TranslationConfig: @@ -39,9 +152,9 @@ class TranslationConfig: default_factory=lambda: ["ko", "ja", "zh", "es", "fr", "de"] ) docs_dir: Path = Path(__file__).parent.parent / "docs" / source_lang - api_provider: str = "openai" # openai, github, etc. + api_provider: str = "openai" # one of API_PROVIDERS api_key: Optional[str] = None - api_base_url: Optional[str] = None # Custom API endpoint (e.g., GitHub Models) + api_base_url: Optional[str] = None # Another OpenAI-compatible endpoint model_name: str = "gpt-4o-mini" # Default model name create_pr: bool = True branch_prefix: str = "translation" @@ -89,8 +202,9 @@ def get_translation_prompt( 3. Maintain the same document structure 4. Keep the same level of technical detail 5. Use appropriate technical terminology for the target language -6. Preserve all code block language identifiers (```python, ```bash, etc.) +6. Keep every line of the form exactly as it is, on its own line 7. Keep all special formatting like admonitions, tables, etc. +8. Keep link targets, image paths and heading ids such as {{#features}} unchanged; translate link texts and image alt texts Source text: @@ -100,16 +214,13 @@ def get_translation_prompt( class OpenAITranslator(TranslationAPI): - """OpenAI API translator (compatible with GitHub Models API).""" + """OpenAI API translator (any OpenAI-compatible endpoint via base_url).""" # Approximate token limits for different models (conservative estimates) MODEL_TOKEN_LIMITS = { - "gpt-5": 3000, # GitHub Models gpt-5 has ~4000 limit, use 3000 for safety - "openai/gpt-5": 3000, + "gpt-5": 3000, "gpt-4o": 12000, - "openai/gpt-4o": 12000, "gpt-4o-mini": 12000, - "openai/gpt-4o-mini": 12000, } DEFAULT_TOKEN_LIMIT = 3000 # Conservative default @@ -117,7 +228,7 @@ def __init__( self, api_key: str, base_url: Optional[str] = None, - model_name: str = "openai/gpt-4o-mini", + model_name: str = "gpt-4o-mini", max_retries: int = 5, retry_delay: float = 60.0, request_delay: float = 2.0, @@ -237,7 +348,8 @@ def _translate_single_chunk( # Simplified prompt for continuation chunks prompt = f"""Continue translating the following text to {target_lang}. Maintain the same style and formatting as before. -IMPORTANT: Preserve all markdown formatting, code blocks, and technical terms. +IMPORTANT: Preserve all markdown formatting and technical terms, and keep every + line exactly as it is. Text: @@ -341,6 +453,8 @@ class DocumentTranslator: def __init__(self, config: TranslationConfig): self.config = config self.translator = self._initialize_translator() + #: Pages that could not be translated, over every call. + self.failed: List[Path] = [] def _initialize_translator(self) -> TranslationAPI: """Initialize the appropriate translation API.""" @@ -349,15 +463,10 @@ def _initialize_translator(self) -> TranslationAPI: "API key is required. Set via --api-key or environment variable." ) - if self.config.api_provider in ("openai", "github"): - # For GitHub Models, set default base_url if not provided - base_url = self.config.api_base_url - if self.config.api_provider == "github" and not base_url: - base_url = "https://models.github.ai/inference" - + if self.config.api_provider in API_PROVIDERS: return OpenAITranslator( api_key=self.config.api_key, - base_url=base_url, + base_url=self.config.api_base_url, model_name=self.config.model_name, max_retries=self.config.max_retries, retry_delay=self.config.retry_delay, @@ -377,14 +486,20 @@ def translate_file(self, file_path: Path, target_lang: str) -> Tuple[str, Path]: """Translate a single file.""" logger.info(f"Translating {file_path.name} to {target_lang}") - # Read source file - with open(file_path, "r", encoding="utf-8") as f: + # Read source file, keeping its line endings + with open(file_path, "r", encoding="utf-8", newline="") as f: content = f.read() + newline = "\r\n" if "\r\n" in content else "\n" - # Translate content - translated_content = self.translator.translate( - content, target_lang=target_lang, source_lang=self.config.source_lang + # Translate the prose only; code and generated blocks stay as they are + prose, kept = protect(content) + translated = self.translator.translate( + prose, target_lang=target_lang, source_lang=self.config.source_lang ) + translated_content = restore(translated.replace("\r\n", "\n"), kept) + if content.endswith(newline) and not translated_content.endswith("\n"): + translated_content += "\n" + translated_content = translated_content.replace("\n", newline) # Determine target path relative_path = file_path.relative_to(str(self.config.docs_dir)) @@ -396,7 +511,7 @@ def save_translation(self, content: str, target_path: Path) -> None: """Save translated content to file.""" target_path.parent.mkdir(parents=True, exist_ok=True) - with open(target_path, "w", encoding="utf-8") as f: + with open(target_path, "w", encoding="utf-8", newline="") as f: f.write(content) logger.info(f"Saved translation to {target_path}") @@ -411,6 +526,10 @@ def translate_all( translated_files = [] for file_path in file_paths: + relative = file_path.relative_to(self.config.docs_dir).as_posix() + if relative in HAND_MAINTAINED: + logger.info(f"Skipping {relative}: maintained by hand in each language") + continue try: translated_content, target_path = self.translate_file( file_path, target_lang @@ -419,6 +538,7 @@ def translate_all( translated_files.append(target_path) except Exception as e: logger.error(f"Failed to translate {file_path}: {e}") + self.failed.append(file_path) continue return translated_files @@ -487,7 +607,7 @@ def create_pull_request( return None -def main() -> None: +def main(argv: Optional[List[str]] = None) -> None: """Main entry point.""" parser = argparse.ArgumentParser( description="Translate FastAPI-fastkit documentation to multiple languages" @@ -500,25 +620,25 @@ def main() -> None: parser.add_argument( "--api-provider", type=str, - choices=["openai", "github"], + choices=API_PROVIDERS, default="openai", - help="AI API provider for translation (openai or github)", + help="AI API provider for translation (openai; see --api-base-url)", ) parser.add_argument( "--api-key", type=str, - help="API key for translation service. Can also be set via TRANSLATION_API_KEY (OpenAI) or GITHUB_TOKEN (GitHub) environment variable.", + help="API key for translation service. Can also be set via the TRANSLATION_API_KEY environment variable.", ) parser.add_argument( "--api-base-url", type=str, - help="Custom API base URL. Defaults to https://models.github.ai/inference for github provider.", + help="Base URL of another OpenAI-compatible API (default: OpenAI's).", ) parser.add_argument( "--model", type=str, default="gpt-4o-mini", - help="Model name to use for translation (default: gpt-4o-mini). For GitHub, use format like 'openai/gpt-4o-mini'.", + help="Model name to use for translation (default: gpt-4o-mini).", ) parser.add_argument( "--no-pr", action="store_true", help="Skip creating GitHub Pull Request" @@ -550,18 +670,17 @@ def main() -> None: help="Delay in seconds between consecutive API requests to avoid rate limits (default: 2.0)", ) - args = parser.parse_args() + args = parser.parse_args(argv) + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + ) - # Get API key from args or environment (support both TRANSLATION_API_KEY and GITHUB_TOKEN) + # Get API key from args or environment api_key = args.api_key or os.getenv("TRANSLATION_API_KEY") - if not api_key and args.api_provider == "github": - api_key = os.getenv("GITHUB_TOKEN") if not api_key: - env_var = ( - "GITHUB_TOKEN" if args.api_provider == "github" else "TRANSLATION_API_KEY" - ) logger.error( - f"API key is required. Provide via --api-key or {env_var} environment variable." + "API key is required. Provide via --api-key or TRANSLATION_API_KEY environment variable." ) sys.exit(1) @@ -589,12 +708,13 @@ def main() -> None: # Get file paths if specified file_paths = None + missing: List[Path] = [] if args.files: file_paths = [config.docs_dir / f for f in args.files] # Verify files exist - for fp in file_paths: - if not fp.exists(): - logger.warning(f"File not found: {fp}") + missing = [fp for fp in file_paths if not fp.exists()] + for fp in missing: + logger.error(f"File not found: {fp}") file_paths = [fp for fp in file_paths if fp.exists()] # Determine target languages @@ -618,6 +738,14 @@ def main() -> None: else: logger.warning(f"No files were translated to {lang}") + # A page that is missing or failed must not go unnoticed (the workflow + # would open a pull request without it). + if missing or translator.failed: + logger.error( + f"{len(missing) + len(translator.failed)} page(s) not translated: " + + ", ".join(str(fp) for fp in missing + translator.failed) + ) + sys.exit(1) logger.info("Translation process completed!") diff --git a/scripts/translation_config.json b/scripts/translation_config.json deleted file mode 100644 index ead87db4..00000000 --- a/scripts/translation_config.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "source_language": "en", - "target_languages": [ - { - "code": "ko", - "name": "Korean", - "native_name": "한국어", - "enabled": true - }, - { - "code": "ja", - "name": "Japanese", - "native_name": "日本語", - "enabled": true - }, - { - "code": "zh", - "name": "Chinese", - "native_name": "中文", - "enabled": true - }, - { - "code": "es", - "name": "Spanish", - "native_name": "Español", - "enabled": true - }, - { - "code": "fr", - "name": "French", - "native_name": "Français", - "enabled": true - }, - { - "code": "de", - "name": "German", - "native_name": "Deutsch", - "enabled": true - } - ], - "translation_settings": { - "default_api_provider": "openai", - "batch_size": 5, - "preserve_formatting": true, - "exclude_patterns": [ - "**/*.png", - "**/*.jpg", - "**/*.jpeg", - "**/*.gif", - "**/*.svg", - "**/*.ai", - "**/css/**", - "**/js/**" - ] - }, - "github_settings": { - "create_pr_by_default": true, - "branch_prefix": "translation", - "pr_labels": ["documentation", "translation"], - "auto_assign_reviewers": [] - }, - "quality_checks": { - "verify_code_blocks": true, - "verify_links": true, - "verify_formatting": true, - "min_translation_length_ratio": 0.5, - "max_translation_length_ratio": 2.0 - } -} diff --git a/tests/test_docs/docs_support.py b/tests/test_docs/docs_support.py index 1e02fb5f..c3515fba 100644 --- a/tests/test_docs/docs_support.py +++ b/tests/test_docs/docs_support.py @@ -16,6 +16,33 @@ DOCS = ROOT / "docs" EN = DOCS / "en" +#: Languages whose docs// still holds the 1.x pages. The parity checks +#: (test_locale_parity.py) run for every other language; a language's +#: translation pull request removes it from this tuple. +PENDING_LOCALES: Tuple[str, ...] = ("ko", "ja", "zh", "es", "fr", "de") + +#: Pages that are the same file in every language (changelog.md only +#: includes the English CHANGELOG.md). +SAME_IN_EVERY_LOCALE: Tuple[str, ...] = ("changelog.md",) + +#: English texts a translated page keeps unchanged, by page: table rows or +#: sentences that are the API's or a tool's own words. The parity checks +#: report any other English sentence of four words or more, and any table +#: row with such a cell, that a translated page leaves in English. Add an +#: entry here, reviewed, instead of rewording a text that must stay English. +UNCHANGED_IN_TRANSLATIONS: Dict[str, Tuple[str, ...]] = { + # Endpoint summaries as the example projects' OpenAPI documents show them. + "how-to/example-projects.md": ( + "| GET | `/api/v1/items/{item_id}` | Get item by ID |", + "| GET | `/api/v1/users/me/scopes` | Read Current User Scopes |", + "| POST | `/api/v1/auth/token` | Get an access token |", + "| GET | `/api/v1/users/me` | Get the current user |", + "| GET | `/api/v1/users` | List users (superusers only) |", + "| PATCH | `/api/v1/items/{item_id}` | Update some fields of an item |", + "| GET | `/api/v1/mcp-server` | Describe the MCP server |", + ), +} + def load_script(name: str, path: Path) -> ModuleType: """Import a script that is not part of a package from its file.""" @@ -39,6 +66,20 @@ def redirects() -> ModuleType: ) +def translate_script() -> ModuleType: + return load_script("fastkit_translate", ROOT / "scripts" / "translate.py") + + +def locales() -> Tuple[str, ...]: + """Every docs language except English.""" + return tuple(lang for lang in docs_blocks().LANGUAGES if lang != "en") + + +def converted_locales() -> Tuple[str, ...]: + """The languages whose pages must match the English ones.""" + return tuple(lang for lang in locales() if lang not in PENDING_LOCALES) + + def english_pages() -> List[str]: """Every Markdown page under docs/en, "/"-separated and relative to it.""" found = [] diff --git a/tests/test_docs/parity.py b/tests/test_docs/parity.py new file mode 100644 index 00000000..97769d84 --- /dev/null +++ b/tests/test_docs/parity.py @@ -0,0 +1,686 @@ +# -------------------------------------------------------------------------- +# Parity checks between a translated docs tree (docs//) and docs/en: +# the same pages, generated blocks, code blocks, headings, paragraphs, +# tables, admonitions, images, links and anchors, and prose that is +# actually translated. +# +# check_locale() returns one message per problem, each naming the page and +# telling the translator what to fix; an empty list means the language +# matches English. test_locale_parity.py runs it on every language that is +# not in docs_support.PENDING_LOCALES and on temporary trees. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import html +import os +import posixpath +import re +import unicodedata +from collections import Counter +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, Iterable, List, Mapping, Optional, Set, Tuple + +from .docs_support import SAME_IN_EVERY_LOCALE, UNCHANGED_IN_TRANSLATIONS, docs_blocks + +# A fence may be indented (inside a list item, an admonition or a tab). +_FENCE = re.compile(r"^(\s*)(`{3,}|~{3,})(.*)$") +_HEADING = re.compile(r"^(#{1,6})[ \t]+(.*?)[ \t]*$") +_ATTRS = re.compile(r"\s*\{:?([^{}]*)\}\s*$") +_ADMONITION = re.compile(r"^\s*(!!!|\?\?\?\+?|===\+?)(?=\s|$)(.*)$") +_LIST_ITEM = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+\S") +_CODE_SPAN = re.compile(r"(`+)(.+?)\1", re.S) +_IMAGE = re.compile(r"!\[([^\]]*)\]\(\s*]+)>?(?:\s+\"[^\"]*\")?\s*\)") +_LINK = re.compile(r"(?]+)>?(?:\s+\"[^\"]*\")?\s*\)") +_REF_LINK = re.compile(r"!?\[[^\]]*\]\[([^\]]*)\]") +_AUTOLINK = re.compile(r"<((?:https?|mailto):[^>\s]+)>") +_REF_DEFINITION = re.compile(r"^ {0,3}\[([^\]]+)\]:\s*?(?:\s|$)") +_HTML_IMG = re.compile(r"]*>", re.I) +_HTML_ATTR = re.compile(r"\b(href|src|alt|id)\s*=\s*(?:\"([^\"]*)\"|'([^']*)')", re.I) +_HTML_TAG = re.compile(r"<[^>]+>") +_SCHEME = re.compile(r"^(?:[a-z][a-z0-9+.-]*:|//)", re.I) +_WORD = re.compile(r"[^\W\d_][\w'’-]+") +_SENTENCE_END = re.compile(r"(?<=[.!?:;])\s+") +_IDCOUNT = re.compile(r"^(.*)_([0-9]+)$") + +#: An English sentence or table cell with at least this many words that +#: appears unchanged in a translated page counts as untranslated. +UNTRANSLATED_MIN_WORDS = 4 + + +def slug(text: str) -> str: + """ + The id Python-Markdown's toc extension gives a heading's text (mkdocs.yml + configures no other slugify): slugify of the rendered, unescaped text. + """ + text = _CODE_SPAN.sub(lambda m: m.group(2), text) + text = _IMAGE.sub("", text) + text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text) + text = _HTML_TAG.sub("", text) + text = re.sub(r"(\*{1,3}|_{1,3})(?=\S)(.+?)(?<=\S)\1(?!\w)", r"\2", text) + text = html.unescape(text) + text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode() + text = re.sub(r"[^\w\s-]", "", text).strip().lower() + return re.sub(r"[-\s]+", "-", text) + + +def unique(anchor: str, used: Set[str]) -> str: + """Python-Markdown's toc ``unique``: "_1", "_2"... for a taken or empty id.""" + while anchor in used or not anchor: + match = _IDCOUNT.match(anchor) + if match: + anchor = f"{match.group(1)}_{int(match.group(2)) + 1}" + else: + anchor = f"{anchor}_1" + used.add(anchor) + return anchor + + +@dataclass(frozen=True) +class Heading: + level: int + text: str + #: The ``{#id}`` of the heading, if it has one. + explicit_id: Optional[str] + + def __str__(self) -> str: + return "#" * self.level + " " + self.text + + +@dataclass(frozen=True) +class Fence: + info: str + body: str + #: 1-based line of the opening fence. + line: int + + +@dataclass(frozen=True) +class Row: + """A Markdown table row outside the generated blocks.""" + + text: str + cells: Tuple[str, ...] + + +@dataclass +class Page: + """What the parity checks compare, parsed from one Markdown page.""" + + error: str = "" + front_matter: str = "" + markers: List[str] = field(default_factory=list) + fences: List[Fence] = field(default_factory=list) + #: 1-based line of a fence that is never closed. + unclosed_fence: Optional[int] = None + headings: List[Heading] = field(default_factory=list) + admonitions: List[str] = field(default_factory=list) + #: (target, alt) of every image, in order. + images: List[Tuple[str, str]] = field(default_factory=list) + #: Link targets as written, in order. + links: List[str] = field(default_factory=list) + #: Reference-style links and definitions ("[text][ref]", "[ref]: url"). + reference_links: List[str] = field(default_factory=list) + #: Every id a link can point to (heading ids, HTML ids). + anchors: Set[str] = field(default_factory=set) + #: Text lines outside code blocks, generated blocks and front matter. + prose: List[str] = field(default_factory=list) + #: Paragraphs and list items (lines joined), outside tables. + blocks: List[str] = field(default_factory=list) + #: For each entry of ``blocks``: the number of headings above it. + block_sections: List[int] = field(default_factory=list) + rows: List[Row] = field(default_factory=list) + + +def _heading(line: str) -> Optional[Heading]: + match = _HEADING.match(line) + if not match: + return None + text = re.sub(r"\s+#+$", "", match.group(2)) + explicit_id = None + attrs = _ATTRS.search(text) + if attrs: + ids = re.findall(r"(?:^|\s)#([\w-]+)", attrs.group(1)) + if ids: + explicit_id = ids[-1] + text = text[: attrs.start()] + return Heading(len(match.group(1)), text.strip(), explicit_id) + + +def _cells(line: str) -> Tuple[str, ...]: + text = _CODE_SPAN.sub(lambda m: "CODE" * bool(m.group(2)), line.strip()) + text = text.replace("\\|", "") + if text.startswith("|"): + text = text[1:] + if text.endswith("|"): + text = text[:-1] + return tuple(cell.strip() for cell in text.split("|")) + + +def _indent(line: str) -> int: + return len(line) - len(line.lstrip()) + + +def parse_page(text: str) -> Page: + """Parse a page; ``Page.error`` is set when its block markers are broken.""" + page = Page() + text = text.replace("\r\n", "\n") + lines = text.split("\n") + skip: Set[int] = set() + if lines and lines[0] == "---" and "---" in lines[1:]: + end = lines.index("---", 1) + page.front_matter = "\n".join(lines[1:end]) + skip.update(range(end + 1)) + try: + blocks = docs_blocks().find_blocks(text) + except docs_blocks().BlockError as error: + page.error = str(error) + return page + # Every heading in page order, generated ones included: toc gives each + # one without an explicit id a unique id in this order. + all_headings: List[Tuple[int, Heading]] = [] + for block in blocks: + page.markers.append((block.name + " " + block.args).strip()) + skip.update(range(block.start, block.end + 1)) + for index in range(block.start + 1, block.end): + heading = _heading(lines[index]) + if heading: + all_headings.append((index, heading)) + + outside: List[str] = [] + fence: Optional[Tuple[str, str, int, List[str], int]] = None + in_block = False + index = 0 + while index < len(lines): + line = lines[index] + if index in skip: + in_block = False + index += 1 + continue + match = _FENCE.match(line) + if fence is not None: + marker, info, start, body, indent = fence + if ( + match + and match.group(2)[0] == marker[0] + and len(match.group(2)) >= len(marker) + and not match.group(3).strip() + ): + page.fences.append(Fence(info, "\n".join(body), start)) + fence = None + elif indent and line.strip() and _indent(line) < indent: + # The container (admonition, tab, list item) ends here, and + # the fence with it; read the line again outside the fence. + page.fences.append(Fence(info, "\n".join(body), start)) + fence = None + continue + else: + body.append(line[indent:] if line[:indent].isspace() else line) + index += 1 + continue + if match and not (match.group(2)[0] == "`" and "`" in match.group(3)): + fence = ( + match.group(2), + match.group(3).strip(), + index + 1, + [], + len(match.group(1)), + ) + in_block = False + index += 1 + continue + index += 1 + outside.append(line) + stripped = line.strip() + if not stripped: + in_block = False + continue + page.prose.append(stripped) + heading = _heading(line) + admonition = _ADMONITION.match(line) + if heading: + page.headings.append(heading) + all_headings.append((index - 1, heading)) + in_block = False + elif stripped.startswith("|"): + page.rows.append(Row(stripped, _cells(stripped))) + in_block = False + elif admonition: + kind = admonition.group(1).rstrip("+") + words = admonition.group(2).split() + if kind != "===" and words and not words[0].startswith('"'): + kind += " " + words[0] + page.admonitions.append(kind) + in_block = False + elif in_block and not _LIST_ITEM.match(line): + page.blocks[-1] += " " + stripped + else: + page.blocks.append(stripped) + page.block_sections.append(len(page.headings)) + in_block = True + definition = _REF_DEFINITION.match(line) + if definition: + page.reference_links.append(f"[{definition.group(1)}]:") + page.links.append(definition.group(2)) + if fence is not None: + page.unclosed_fence = fence[2] + + used = {h.explicit_id for _, h in all_headings if h.explicit_id} + page.anchors |= used + for _, heading in sorted(all_headings, key=lambda item: item[0]): + if not heading.explicit_id: + page.anchors.add(unique(slug(heading.text), used)) + + flat = _CODE_SPAN.sub("CODE", "\n".join(outside)) + for alt, target in _IMAGE.findall(flat): + page.images.append((target, alt.strip())) + page.links.extend(_LINK.findall(_IMAGE.sub("", flat))) + page.reference_links.extend(f"[{ref}]" for ref in _REF_LINK.findall(flat)) + page.links.extend(_AUTOLINK.findall(flat)) + for tag in re.findall(r"<[a-z][^>]*>", flat, flags=re.I): + attrs = { + name.lower(): double or single + for name, double, single in _HTML_ATTR.findall(tag) + } + if _HTML_IMG.match(tag): + page.images.append((attrs.get("src", ""), attrs.get("alt", "").strip())) + elif "href" in attrs: + page.links.append(attrs["href"]) + elif "src" in attrs: + page.links.append(attrs["src"]) + if attrs.get("id"): + page.anchors.add(attrs["id"]) + return page + + +def is_external(target: str) -> bool: + return bool(_SCHEME.match(target)) + + +def normalise(target: str, page: str) -> str: + """ + A link target as a path relative to the language root (``page`` is the + linking page, "/"-separated); external URLs stay as they are. + """ + if is_external(target): + return target + path, hash_, fragment = target.partition("#") + if not path: + resolved = page + else: + resolved = posixpath.normpath(posixpath.join(posixpath.dirname(page), path)) + if path.endswith("/"): + resolved += "/" + return resolved + (hash_ + fragment if hash_ else "") + + +def prose_words(line: str) -> List[str]: + """The words of a prose line, without code, link targets and HTML tags.""" + line = _CODE_SPAN.sub(" ", line) + line = re.sub(r"\]\([^)]*\)", "]", line) + line = _AUTOLINK.sub(" ", line) + line = _HTML_TAG.sub(" ", line) + line = re.sub(r"https?://\S+", " ", line) + return _WORD.findall(line) + + +def sentences(block: str) -> List[str]: + """The sentences of a paragraph or list item (never split inside code).""" + spans: List[str] = [] + + def mask(match: "re.Match[str]") -> str: + spans.append(match.group(0)) + return f"\x00{len(spans) - 1}\x00" + + masked = _CODE_SPAN.sub(mask, block) + return [ + re.sub("\x00(\\d+)\x00", lambda m: spans[int(m.group(1))], part) + for part in _SENTENCE_END.split(masked) + if part + ] + + +# ------------------------------------------------------------- comparing + + +def _first_difference(english: List[str], other: List[str]) -> str: + for index, (a, b) in enumerate(zip(english, other)): + if a != b: + return f"item {index + 1} is {b!r} here, {a!r} in English" + if len(english) > len(other): + return f"missing here: {english[len(other):]}" + return f"not in English: {other[len(english):]}" + + +def _section(page: Page, number: int) -> str: + if number == 0: + return "before the first heading" + return f"under heading {number} ('{page.headings[number - 1]}' in English)" + + +def _counts(page: Page) -> List[int]: + counts = [0] * (len(page.headings) + 1) + for section in page.block_sections: + counts[section] += 1 + return counts + + +def _structure(english: Page, other: Page, where: str, source: str) -> List[str]: + problems: List[str] = [] + levels = [str(h.level) for h in english.headings] + other_levels = [str(h.level) for h in other.headings] + if other_levels != levels: + problems.append( + f"{where}: headings differ from English (levels: " + f"{_first_difference(levels, other_levels)}); translate each heading " + f"of {source} at the same level, in the same order" + ) + else: + for number, (a, b) in enumerate(zip(english.headings, other.headings), 1): + if a.explicit_id != b.explicit_id: + problems.append( + f"{where}: heading {number} ('{a}' in English) has the id " + f"{b.explicit_id!r} here, {a.explicit_id!r} in English; keep " + f"each '{{#id}}' on the heading that translates its English " + f"heading" + ) + if len(other.blocks) != len(english.blocks): + detail = "" + if other_levels == levels: + mine, theirs = _counts(other), _counts(english) + first = next(n for n, (a, b) in enumerate(zip(mine, theirs)) if a != b) + detail = ( + f"; first difference {_section(english, first)}: " + f"{mine[first]} here, {theirs[first]} in English" + ) + problems.append( + f"{where}: {len(other.blocks)} paragraphs and list items, " + f"{len(english.blocks)} in English{detail}; translate each paragraph " + f"and list item of {source} as one paragraph or list item" + ) + cells = [str(len(row.cells)) for row in english.rows] + other_cells = [str(len(row.cells)) for row in other.rows] + if other_cells != cells: + problems.append( + f"{where}: tables differ from English (cells per row: " + f"{_first_difference(cells, other_cells)}); keep every table row of " + f"{source} with the same number of cells" + ) + return problems + + +def compare_page( + english: Page, other: Page, where: str, source: str, allowed: Iterable[str] = () +) -> List[str]: + """ + Problems of one translated page (``where``) against the English one; + ``allowed`` are English texts the page may keep unchanged. + """ + if other.error: + return [ + f"{where}: broken generated block markers ({other.error}); copy the " + f"marker lines from {source}" + ] + problems: List[str] = [] + if other.unclosed_fence is not None: + problems.append( + f"{where}: the code block opened at line {other.unclosed_fence} is " + f"never closed; close it as in {source}" + ) + if other.front_matter != english.front_matter: + problems.append( + f"{where}: the front matter differs from English; copy it from {source}" + ) + if other.markers != english.markers: + problems.append( + f"{where}: generated blocks differ from English " + f"({_first_difference(english.markers, other.markers)}); copy the " + f"'' lines of {source} in the same order" + ) + if len(other.fences) != len(english.fences): + problems.append( + f"{where}: {len(other.fences)} code blocks, {len(english.fences)} in " + f"English; keep every code block of {source}, and add none" + ) + else: + for number, (a, b) in enumerate(zip(english.fences, other.fences), 1): + if (a.info, a.body) != (b.info, b.body): + problems.append( + f"{where}: code block {number} (line {b.line}, ```{b.info}) " + f"differs from the English one (```{a.info}, line {a.line} of " + f"{source}); code blocks stay exactly as in English" + ) + problems.extend(_structure(english, other, where, source)) + if other.admonitions != english.admonitions: + problems.append( + f"{where}: admonitions and tabs differ from English " + f"({_first_difference(english.admonitions, other.admonitions)}); keep " + f"each '!!!', '???' and '===' line of {source} with its type" + ) + english_images = [target for target, _ in english.images] + other_images = [target for target, _ in other.images] + if other_images != english_images: + problems.append( + f"{where}: images differ from English " + f"({_first_difference(english_images, other_images)}); use the same " + f"image files, in the same order, as {source}" + ) + for target, alt in other.images: + if not alt: + problems.append( + f"{where}: image {target} has no alt text; translate the English " + f"alt text" + ) + if Counter(other.reference_links) != Counter(english.reference_links): + problems.append( + f"{where}: reference-style links differ from English " + f"({sorted(other.reference_links)} here, " + f"{sorted(english.reference_links)} in English); write links as " + f"[text](target) like {source}" + ) + page = where.split("/", 1)[1] + english_links = Counter(normalise(t, page) for t in english.links) + other_links = Counter(normalise(t, page) for t in other.links) + if english_links - other_links: + problems.append( + f"{where}: links of the English page are missing: " + f"{sorted((english_links - other_links).elements())}; keep every " + f"link of {source}, as often as it occurs there, with its target " + f"unchanged (translate only the link text)" + ) + if other_links - english_links: + problems.append( + f"{where}: links not on the English page: " + f"{sorted((other_links - english_links).elements())}; link the same " + f"targets as {source}, as often as it does" + ) + problems.extend(_untranslated(english, other, where, set(allowed))) + return problems + + +def _is_allowed(text: str, allowed: Set[str]) -> bool: + return any(text == entry or text in entry for entry in allowed) + + +def _untranslated( + english: Page, other: Page, where: str, allowed: Set[str] +) -> List[str]: + english_text = [line for line in english.prose if prose_words(line)] + if not english_text: + return [] + if [line for line in other.prose if prose_words(line)] == english_text: + return [f"{where}: the page is the English text; translate it"] + # Sentences are looked for in the page's text with the line breaks + # removed, so that rewrapping an English sentence does not hide it. + text = " ".join(" ".join(other.blocks).split()) + left = [ + sentence + for block in english.blocks + for sentence in sentences(" ".join(block.split())) + if len(prose_words(sentence)) >= UNTRANSLATED_MIN_WORDS + and sentence in text + and not _is_allowed(sentence, allowed) + ] + rows = {row.text for row in other.rows} + left.extend( + row.text + for row in english.rows + if row.text in rows + and any(len(prose_words(cell)) >= UNTRANSLATED_MIN_WORDS for cell in row.cells) + and not _is_allowed(row.text, allowed) + ) + if not left: + return [] + shown = "; ".join(repr(item[:70]) for item in left[:3]) + more = f" and {len(left) - 3} more" if len(left) > 3 else "" + count = ( + f"{len(left)} sentences or table rows are" + if len(left) > 1 + else ("1 sentence or table row is") + ) + return [ + f"{where}: {count} still in English ({shown}{more}); translate " + f"{'them' if len(left) > 1 else 'it'} (a text that must stay English " + f"goes into UNCHANGED_IN_TRANSLATIONS in tests/test_docs/docs_support.py)" + ] + + +# ------------------------------------------------------------- languages + + +def markdown_pages(root: Path) -> List[str]: + """Every Markdown page under ``root``, "/"-separated, symlinks not followed.""" + found = [] + for dirpath, dirnames, filenames in os.walk(root): + dirnames.sort() + for name in filenames: + if name.endswith(".md"): + rel = os.path.relpath(os.path.join(dirpath, name), root) + found.append(rel.replace(os.sep, "/")) + return sorted(found) + + +def _read(path: Path) -> str: + return path.read_bytes().decode("utf-8") + + +def fragment_problems(lang: str, pages: Mapping[str, Page]) -> List[str]: + """ + Links with a ``#fragment`` to a page of ``lang`` that lacks the anchor, + and internal links with a fragment that do not name a Markdown file. + """ + problems = [] + for name, page in sorted(pages.items()): + for target in page.links: + if is_external(target) or "#" not in target: + continue + path = target.partition("#")[0] + resolved, _, fragment = normalise(target, name).partition("#") + if path and not path.endswith(".md"): + problems.append( + f"{lang}/{name}: link '{target}' does not name a Markdown " + f"file; link the page's .md file, as docs/en does, so that " + f"its anchor can be checked" + ) + continue + if resolved not in pages: + continue + if fragment not in pages[resolved].anchors: + problems.append( + f"{lang}/{name}: link '{target}' points to an anchor that " + f"docs/{lang}/{resolved} lacks; keep the '{{#{fragment}}}' of " + f"the English heading" + ) + return problems + + +def check_locale(docs: Path, lang: str) -> List[str]: + """Every difference between ``docs/`` and ``docs/en`` a translator must fix.""" + english_root, root = docs / "en", docs / lang + english_names = markdown_pages(english_root) + names = markdown_pages(root) if root.is_dir() else [] + problems = [ + f"{lang}/{name}: missing; translate docs/en/{name}" + for name in english_names + if name not in names + ] + problems.extend( + f"{lang}/{name}: not an English page; delete it (old pages redirect " + f"to their new address)" + for name in names + if name not in english_names + ) + pages: Dict[str, Page] = {} + for name in english_names: + if name not in names: + continue + english_text, text = _read(english_root / name), _read(root / name) + where, source = f"{lang}/{name}", f"docs/en/{name}" + if name in SAME_IN_EVERY_LOCALE: + if text.replace("\r\n", "\n") != english_text.replace("\r\n", "\n"): + problems.append(f"{where}: must be the same file as {source}; copy it") + continue + pages[name] = parse_page(text) + problems.extend( + compare_page( + parse_page(english_text), + pages[name], + where, + source, + UNCHANGED_IN_TRANSLATIONS.get(name, ()), + ) + ) + problems.extend(fragment_problems(lang, pages)) + for problem in docs_blocks().run(str(docs), [lang]): + if problem.stale: + problems.append( + f"{problem.path}: generated block '{problem.name}' is not rendered " + f"for {lang}; run python scripts/docs_blocks.py --lang {lang}" + ) + elif problem.name: + problems.append( + f"{problem.path}: generated block '{problem.name}': " + f"{problem.reason}; copy the marker line from the English page" + ) + # Broken markers (no name) are reported with the page above. + return problems + + +def headings_problems( + lang: str, headings: Mapping[str, Mapping[str, str]], complete: bool = True +) -> List[str]: + """ + ``HEADINGS[lang]`` of scripts/docs_blocks.py against the English entry: + no unknown key, the same placeholders, and with ``complete`` every key. + """ + english = headings["en"] + entry = headings.get(lang) + if entry is None: + if not complete: + return [] + return [ + f"HEADINGS has no '{lang}' entry; add one to scripts/docs_blocks.py " + f"with every key of 'en'" + ] + problems = [ + f"HEADINGS['{lang}'] lacks '{key}'; translate HEADINGS['en']['{key}']" + for key in english + if complete and key not in entry + ] + problems.extend( + f"HEADINGS['{lang}'] has '{key}', which 'en' lacks; remove it" + for key in entry + if key not in english + ) + for key in english: + if key in entry: + want = set(re.findall(r"\{(\w+)\}", english[key])) + have = set(re.findall(r"\{(\w+)\}", entry[key])) + if want != have: + problems.append( + f"HEADINGS['{lang}']['{key}'] must use the placeholders " + f"{sorted(want)}, not {sorted(have)}" + ) + if not entry[key].strip(): + problems.append(f"HEADINGS['{lang}']['{key}'] is empty") + return problems diff --git a/tests/test_docs/test_generated_blocks.py b/tests/test_docs/test_generated_blocks.py index dd8fc224..0e41b7d3 100644 --- a/tests/test_docs/test_generated_blocks.py +++ b/tests/test_docs/test_generated_blocks.py @@ -183,12 +183,41 @@ def test_bad_blocks_are_refused(name: str, args: str, message: str) -> None: blocks.render(name, args, "en") -def test_missing_locale_headings_fall_back_to_english() -> None: - assert ( - blocks.render("package-managers", "", "de") - .split("\n")[1] - .startswith("| Package manager |") +def test_missing_locale_headings_fall_back_to_english( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setitem(blocks.HEADINGS, "de", {"check": "Prüfung"}) + header = blocks.render("package-managers", "", "de").split("\n")[1] + assert header.startswith("| Package manager |") + monkeypatch.delitem(blocks.HEADINGS, "de") + header = blocks.render("package-managers", "", "de").split("\n")[1] + assert header.startswith("| Package manager |") + + +def test_locale_headings_set_words_punctuation_and_joins( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Joins, separators and sentence patterns come from HEADINGS, so a + # language such as Japanese can drop the spaces around them. + monkeypatch.setitem( + blocks.HEADINGS, + "ja", + { + "separator": "、", + "join_or": "{items}または{last}", + "join_and": "{items}と{last}", + "selection": "{axis}が{values}", + "rule_requires": "{when}には{require}が必要です。", + "preset_template": "{template}(プリセット {preset})", + }, ) + rules = blocks.render("rules", "", "ja") + assert "`PostgreSQL`、`MySQL`または`SQLite`が必要です。" in rules + assert " or " not in rules and ", " not in rules + levels = blocks.render("levels", "", "ja") + assert "`fastapi-default`(プリセット `classic-layered`)" in levels + features = blocks.render("features", "", "ja") + assert "`, `" not in features # ------------------------------------------------- check and rewrite modes diff --git a/tests/test_docs/test_locale_parity.py b/tests/test_docs/test_locale_parity.py new file mode 100644 index 00000000..121877d9 --- /dev/null +++ b/tests/test_docs/test_locale_parity.py @@ -0,0 +1,781 @@ +# -------------------------------------------------------------------------- +# Test cases for translated docs: every language that is not pending +# (docs_support.PENDING_LOCALES) has the English pages with the same code, +# structure, images, links and anchors, translated prose and its own +# generated-block words. Temporary trees show that each check catches its +# problem; the English tree's anchors are checked so that links keep working +# once the headings are translated. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import re +from pathlib import Path +from typing import Callable, Dict, List + +import pytest + +from . import docs_support +from .docs_support import ( + DOCS, + EN, + PENDING_LOCALES, + SAME_IN_EVERY_LOCALE, + UNCHANGED_IN_TRANSLATIONS, + docs_blocks, + english_pages, + locales, + read, + redirects, +) +from .parity import ( + check_locale, + fragment_problems, + headings_problems, + is_external, + normalise, + parse_page, + sentences, + slug, +) + +blocks = docs_blocks() + + +# ------------------------------------------------------------ the docs tree + + +def test_pending_locales_are_docs_languages() -> None: + assert len(set(PENDING_LOCALES)) == len(PENDING_LOCALES) + assert set(PENDING_LOCALES) <= set(locales()) + assert "en" not in PENDING_LOCALES + + +@pytest.mark.parametrize("lang", locales()) +def test_translated_language_matches_english(lang: str) -> None: + if lang in PENDING_LOCALES: + pytest.skip(f"{lang} is not translated yet (PENDING_LOCALES)") + problems = check_locale(DOCS, lang) + assert not problems, "\n".join(problems) + + +@pytest.mark.parametrize("lang", locales()) +def test_generated_block_words_of_a_language(lang: str) -> None: + # A translated language has every word of the blocks; a pending one may + # have a partial entry, which must still use the English placeholders. + complete = lang not in PENDING_LOCALES + problems = headings_problems(lang, blocks.HEADINGS, complete=complete) + assert not problems, "\n".join(problems) + + +def test_english_fragment_links_resolve() -> None: + pages = {page: parse_page(read(EN / page)) for page in english_pages()} + assert fragment_problems("en", pages) == [] + + +def _linked_anchors() -> List[tuple[str, str, str]]: + """(linking page or 'REDIRECTS', target page, fragment) of the English docs.""" + found = [] + for page in english_pages(): + for target in parse_page(read(EN / page)).links: + if is_external(target) or "#" not in target: + continue + resolved, _, fragment = normalise(target, page).partition("#") + if resolved.endswith(".md"): + found.append((page, resolved, fragment)) + for new in redirects().REDIRECTS.values(): + path, _, fragment = new.partition("#") + if fragment: + found.append(("REDIRECTS", path + ".md", fragment)) + return found + + +def test_linked_english_headings_have_explicit_ids() -> None: + # A translated heading gets another automatic id; only an explicit + # "{#id}" survives translation, so every linked heading needs one. + assert _linked_anchors() + missing = [] + for source, target, fragment in _linked_anchors(): + ids = {h.explicit_id for h in parse_page(read(EN / target)).headings} + if fragment not in ids: + missing.append(f"{source} -> {target}#{fragment}") + assert not missing, missing + + +def test_english_pages_use_inline_links_and_close_every_fence() -> None: + # The parity checks compare inline links; a reference-style link in a + # translation is reported because English uses none. + found = [] + for page in english_pages(): + parsed = parse_page(read(EN / page)) + if parsed.reference_links: + found.append(f"{page}: {parsed.reference_links}") + if parsed.unclosed_fence is not None: + found.append(f"{page}: fence at line {parsed.unclosed_fence} not closed") + assert not found, found + + +def test_only_the_changelog_includes_a_file() -> None: + # mdx_include expands "{!file!}" even inside a code span; a page that + # shows the syntax writes "\\{!file!}". + found = [ + page + for page in english_pages() + if page not in SAME_IN_EVERY_LOCALE + and re.search(r"(? None: + stale = [] + for page, texts in UNCHANGED_IN_TRANSLATIONS.items(): + parsed = parse_page(read(EN / page)) + known = {row.text for row in parsed.rows} | { + sentence + for block in parsed.blocks + for sentence in sentences(" ".join(block.split())) + } + stale.extend(f"{page}: {text}" for text in texts if text not in known) + assert not stale, stale + + +def test_every_english_image_has_alt_text() -> None: + missing = [ + f"{page}: {target}" + for page in english_pages() + for target, alt in parse_page(read(EN / page)).images + if not alt + ] + assert not missing, missing + + +# ------------------------------------------------------------- the parser + + +def test_parse_page_reads_the_parts_that_must_match() -> None: + page = parse_page(EN_PAGE.replace("{en_block}", _body("en"))) + assert page.front_matter == "hide:\n - toc" + assert page.markers == ["concepts testing"] + assert [(f.info, f.body) for f in page.fences] == [ + ("console", "$ fastkit init"), + ('python title="main.py"', "app = FastAPI()"), + ] + assert [(h.level, h.text, h.explicit_id) for h in page.headings] == [ + (1, "Guide", None), + (2, "Run it", "run-it"), + (2, "The `[tool]` table", None), + ] + assert page.admonitions == ["!!! warning"] + assert page.images == [("../img/shot.png", "A terminal running fastkit init")] + assert set(page.links) == { + "other.md#details", + "#run-it", + "http://127.0.0.1:8000/docs", + } # the link inside the generated block is not the page's own + assert {"run-it", "the-tool-table", "guide"} <= page.anchors + + +def test_parse_page_counts_paragraphs_list_items_and_table_cells() -> None: + page = parse_page(EN_OTHER) + assert page.blocks == [ + "The details of every step are here.", + "- First, read the [guide](guide.md) from the top.", + "- Then run the [guide](guide.md) commands in order.", + "Run it:", + ] + assert page.block_sections == [2, 2, 2, 2] + assert [len(row.cells) for row in page.rows] == [2, 2, 2, 2] + assert page.rows[2].cells == ("CODE", "Creates a new project in a folder.") + assert [(f.info, f.body) for f in page.fences] == [("console", "$ fastkit doctor")] + assert page.links == ["guide.md", "guide.md"] + + +def test_parse_page_ids_follow_python_markdown_toc() -> None: + text = ( + "# Setup\n\n## Setup\n\n## 설치\n\n## 설치\n\n## Setup {#setup_1}\n\n" + "## **Bold** & `code`\n\n\n" + ) + page = parse_page(text) + assert page.anchors == { + "setup", + "setup_1", + "setup_2", + "_1", + "_2", + "bold-code", + "top", + } + + +def test_parse_page_reports_reference_links_and_unclosed_fences() -> None: + page = parse_page( + "# T\n\nSee [the guide][g].\n\n[g]: guide.md\n\n```python\nx = 1\n" + ) + assert page.reference_links == ["[g]:", "[g]"] + assert page.links == ["guide.md"] + assert page.unclosed_fence == 7 and page.fences == [] + + +def test_parse_page_ends_an_indented_fence_with_its_container() -> None: + text = "!!! note\n ```console\n $ fastkit doctor\n\nAfter the note.\n" + page = parse_page(text) + assert [(f.body, f.line) for f in page.fences] == [("$ fastkit doctor\n", 2)] + assert page.unclosed_fence is None + assert page.blocks == ["After the note."] + + +def test_parse_page_ignores_markers_and_links_inside_code() -> None: + text = ( + "# T\n\n" + "Use `[x](nowhere.md)` here.\n\n" + "```markdown\n\n[y](gone.md)\n```\n" + ) + page = parse_page(text) + assert page.markers == [] and page.links == [] + + +@pytest.mark.parametrize( + "heading, expected", + [ + ("Configurations saved by fastkit 1.x", "configurations-saved-by-fastkit-1x"), + ("The `[tool.fastapi-fastkit]` block", "the-toolfastapi-fastkit-block"), + ("[Link](x.md) text", "link-text"), + ("설치하기", ""), + ], +) +def test_slug_follows_python_markdown(heading: str, expected: str) -> None: + assert slug(heading) == expected + + +@pytest.mark.parametrize( + "target, page, expected", + [ + ("other.md", "how-to/a.md", "how-to/other.md"), + ("./other.md#x", "how-to/a.md", "how-to/other.md#x"), + ( + "../reference/cli.md#fastkit-init", + "how-to/a.md", + "reference/cli.md#fastkit-init", + ), + ("#top", "how-to/a.md", "how-to/a.md#top"), + ("../installation/", "start/web-generator.md", "installation/"), + ("https://example.com/a#b", "a.md", "https://example.com/a#b"), + ], +) +def test_normalise(target: str, page: str, expected: str) -> None: + assert normalise(target, page) == expected + + +# --------------------------------------------------------- temporary trees + +EN_PAGE = """--- +hide: + - toc +--- +# Guide + +Start the server and open the page in your browser. + +![A terminal running fastkit init](../img/shot.png) + +## Run it {#run-it} + +Run the command below in an empty folder first: + +```console +$ fastkit init +``` + +!!! warning + The command overwrites nothing and stops when the folder exists. + +See [the details](other.md#details) and [the steps above](#run-it), or +open in a browser window. + +## The `[tool]` table + +```python title="main.py" +app = FastAPI() +``` + + +{en_block} +""" + +KO_PAGE = """--- +hide: + - toc +--- +# 안내 + +서버를 시작하고 브라우저에서 페이지를 여세요. + +![fastkit init을 실행한 터미널](../img/shot.png) + +## 실행하기 {#run-it} + +먼저 빈 폴더에서 아래 명령을 실행하세요: + +```console +$ fastkit init +``` + +!!! warning + 이 명령은 아무것도 덮어쓰지 않으며, 폴더가 이미 있으면 멈춥니다. + +[자세한 내용](other.md#details)과 [위의 단계](#run-it)를 보거나, +브라우저 창에서 를 여세요. + +## `[tool]` 표 + +```python title="main.py" +app = FastAPI() +``` + + +{ko_block} +""" + +EN_OTHER = """# Other page + +## Details {#details} + +The details of every step are here. + +- First, read the [guide](guide.md) from the top. +- Then run the [guide](guide.md) commands in order. + +| Command | What it does | +|---|---| +| `fastkit init` | Creates a new project in a folder. | +| `fastkit doctor` | Checks the project. | + +!!! note + Run it: + + ```console + $ fastkit doctor + ``` +""" + +KO_OTHER = """# 다른 페이지 + +## 자세히 {#details} + +모든 단계의 자세한 내용이 여기 있습니다. + +- 먼저 [안내](guide.md)를 처음부터 읽으세요. +- 그다음 [안내](guide.md)의 명령을 순서대로 실행하세요. + +| 명령 | 하는 일 | +|---|---| +| `fastkit init` | 폴더에 새 프로젝트를 만듭니다. | +| `fastkit doctor` | 프로젝트를 검사합니다. | + +!!! note + 실행하세요: + + ```console + $ fastkit doctor + ``` +""" +CHANGELOG = "{!CHANGELOG.md!}\n" + + +def _write(root: Path, rel: str, text: str) -> None: + path = root.joinpath(*rel.split("/")) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(text.encode("utf-8")) + + +def _tree(tmp_path: Path, ko: Dict[str, str]) -> Path: + _write(tmp_path, "en/learn/guide.md", EN_PAGE.replace("{en_block}", _body("en"))) + _write(tmp_path, "en/learn/other.md", EN_OTHER) + _write(tmp_path, "en/changelog.md", CHANGELOG) + for rel, text in ko.items(): + _write(tmp_path, "ko/" + rel, text) + return tmp_path + + +def _body(lang: str) -> str: + return blocks.render("concepts", "testing", lang) + "\n" + + +def _good() -> Dict[str, str]: + return { + "learn/guide.md": KO_PAGE.replace("{ko_block}", _body("ko")), + "learn/other.md": KO_OTHER, + "changelog.md": CHANGELOG, + } + + +def test_good_translation_passes(tmp_path: Path) -> None: + assert check_locale(_tree(tmp_path, _good()), "ko") == [] + + +def test_crlf_translation_passes(tmp_path: Path) -> None: + pages = {rel: text.replace("\n", "\r\n") for rel, text in _good().items()} + assert check_locale(_tree(tmp_path, pages), "ko") == [] + + +def _guide(change: Callable[[str], str]) -> Dict[str, str]: + pages = _good() + pages["learn/guide.md"] = change(pages["learn/guide.md"]) + return pages + + +def _other(change: Callable[[str], str]) -> Dict[str, str]: + pages = _good() + pages["learn/other.md"] = change(pages["learn/other.md"]) + return pages + + +def _swap(old: str, new: str) -> Callable[[str], str]: + def change(text: str) -> str: + assert old in text, old + return text.replace(old, new, 1) + + return change + + +#: id -> (pages of the translated tree, text every expected message holds) +DEVIATIONS: Dict[str, tuple[Callable[[], Dict[str, str]], List[str]]] = { + "missing page": ( + lambda: {k: v for k, v in _good().items() if k != "learn/other.md"}, + ["ko/learn/other.md: missing; translate docs/en/learn/other.md"], + ), + "old page": ( + lambda: {**_good(), "user-guide/quick-start.md": "# 빠른 시작\n"}, + ["ko/user-guide/quick-start.md: not an English page; delete it"], + ), + "changelog differs": ( + lambda: {**_good(), "changelog.md": "# 변경 로그\n"}, + ["ko/changelog.md: must be the same file as docs/en/changelog.md"], + ), + "front matter": ( + lambda: _guide(_swap(" - toc\n", " - navigation\n")), + ["ko/learn/guide.md: the front matter differs from English"], + ), + "generated block args": ( + lambda: _guide(_swap("concepts testing -->", "concepts first-steps -->")), + [ + "ko/learn/guide.md: generated blocks differ from English " + "(item 1 is 'concepts first-steps' here, 'concepts testing' in English)", + "ko/learn/guide.md: generated block 'concepts' is not rendered for " + "ko; run python scripts/docs_blocks.py --lang ko", + ], + ), + "generated block not rendered for the language": ( + lambda: _guide(_swap(_body("ko"), _body("en"))), + [ + "ko/learn/guide.md: generated block 'concepts' is not rendered for " + "ko; run python scripts/docs_blocks.py --lang ko" + ], + ), + "broken markers": ( + lambda: _guide(_swap("\n", "")), + [ + "ko/learn/guide.md: broken generated block markers (line 31: block " + "'concepts' is not closed); copy the marker lines from " + "docs/en/learn/guide.md" + ], + ), + "code changed": ( + lambda: _guide(_swap("$ fastkit init\n", "$ fastkit init --name shop\n")), + [ + "ko/learn/guide.md: code block 1 (line 15, ```console) differs from " + "the English one (```console, line 15 of docs/en/learn/guide.md); " + "code blocks stay exactly as in English" + ], + ), + "code info string changed": ( + lambda: _guide(_swap('```python title="main.py"', "```python")), + ["ko/learn/guide.md: code block 2 (line 27, ```python) differs"], + ), + "code block dropped": ( + lambda: _guide(_swap('```python title="main.py"\napp = FastAPI()\n```\n', "")), + ["ko/learn/guide.md: 1 code blocks, 2 in English"], + ), + "heading level": ( + lambda: _guide(_swap("## `[tool]` 표", "### `[tool]` 표")), + [ + "ko/learn/guide.md: headings differ from English (levels: item 3 is " + "'3' here, '2' in English)" + ], + ), + "heading id dropped": ( + lambda: _guide(_swap("## 실행하기 {#run-it}", "## 실행하기")), + [ + "ko/learn/guide.md: heading 2 ('## Run it' in English) has the id " + "None here, 'run-it' in English; keep each '{#id}' on the heading " + "that translates its English heading", + "ko/learn/guide.md: link '#run-it' points to an anchor that " + "docs/ko/learn/guide.md lacks; keep the '{#run-it}'", + ], + ), + "linked heading id dropped on another page": ( + lambda: {**_good(), "learn/other.md": KO_OTHER.replace(" {#details}", "")}, + [ + "ko/learn/other.md: heading 2 ('## Details' in English) has the id None", + "ko/learn/guide.md: link 'other.md#details' points to an anchor that " + "docs/ko/learn/other.md lacks", + ], + ), + "admonition type": ( + lambda: _guide(_swap("!!! warning", "!!! note")), + [ + "ko/learn/guide.md: admonitions and tabs differ from English (item 1 " + "is '!!! note' here, '!!! warning' in English)" + ], + ), + "image target": ( + lambda: _guide(_swap("../img/shot.png", "../img/shot-ko.png")), + ["ko/learn/guide.md: images differ from English"], + ), + "image without alt text": ( + lambda: _guide(_swap("![fastkit init을 실행한 터미널]", "![]")), + ["ko/learn/guide.md: image ../img/shot.png has no alt text"], + ), + "relative link changed": ( + lambda: _guide(_swap("(other.md#details)", "(other.md)")), + [ + "ko/learn/guide.md: links of the English page are missing: " + "['learn/other.md#details']", + "ko/learn/guide.md: links not on the English page: ['learn/other.md']", + ], + ), + "external link changed": ( + lambda: _guide( + _swap("", "") + ), + [ + "links of the English page are missing: ['http://127.0.0.1:8000/docs']", + "links not on the English page: ['http://localhost:8000/docs']", + ], + ), + "page left in English": ( + lambda: { + **_good(), + "learn/other.md": EN_OTHER, + }, + ["ko/learn/other.md: the page is the English text; translate it"], + ), + "one sentence left in English": ( + lambda: _guide( + _swap( + "먼저 빈 폴더에서 아래 명령을 실행하세요:", + "Run the command below in an empty folder first:", + ) + ), + [ + "ko/learn/guide.md: 1 sentence or table row is still in English ('Run " + "the command below in an empty folder first:'); translate it" + ], + ), + "two sentences left in English": ( + lambda: _guide( + lambda text: text.replace( + "먼저 빈 폴더에서 아래 명령을 실행하세요:", + "Run the command below in an empty folder first:", + ).replace( + "서버를 시작하고 브라우저에서 페이지를 여세요.", + "Start the server and open the page in your browser.", + ) + ), + [ + "ko/learn/guide.md: 2 sentences or table rows are still in English " + "('Start the server" + ], + ), + "untranslated alt text": ( + lambda: _guide( + _swap("fastkit init을 실행한 터미널", "A terminal running fastkit init") + ), + [ + "ko/learn/guide.md: 1 sentence or table row is still in English ('![A " + "terminal running" + ], + ), + "English sentence rewrapped": ( + lambda: _guide( + _swap( + "먼저 빈 폴더에서 아래 명령을 실행하세요:", + "Run the command below\nin an empty folder first:", + ) + ), + [ + "ko/learn/guide.md: 1 sentence or table row is still in English ('Run " + "the command below in an empty folder first:')" + ], + ), + "heading id moved to another heading": ( + lambda: _guide( + lambda text: text.replace("## 실행하기 {#run-it}", "## 실행하기").replace( + "## `[tool]` 표", "## `[tool]` 표 {#run-it}" + ) + ), + [ + "ko/learn/guide.md: heading 2 ('## Run it' in English) has the id None " + "here, 'run-it' in English", + "ko/learn/guide.md: heading 3 ('## The `[tool]` table' in English) has " + "the id 'run-it' here, None in English", + ], + ), + "paragraph dropped": ( + lambda: _other(_swap("모든 단계의 자세한 내용이 여기 있습니다.\n\n", "")), + [ + "ko/learn/other.md: 3 paragraphs and list items, 4 in English; first " + "difference under heading 2 ('## Details' in English): 3 here, 4 in " + "English; translate each paragraph and list item of " + "docs/en/learn/other.md as one paragraph or list item" + ], + ), + "two list items merged": ( + lambda: _other(_swap("읽으세요.\n- 그다음", "읽으세요. 그다음")), + [ + "ko/learn/other.md: 3 paragraphs and list items, 4 in English; first " + "difference under heading 2" + ], + ), + "duplicate link dropped": ( + lambda: _other(_swap("[안내](guide.md)의", "안내의")), + [ + "ko/learn/other.md: links of the English page are missing: " + "['learn/guide.md']" + ], + ), + "reference-style link": ( + lambda: _other( + lambda text: text.replace("[안내](guide.md)를", "[안내][g]를").replace( + "\n\n| 명령", "\n\n[g]: guide.md\n\n| 명령" + ) + ), + [ + "ko/learn/other.md: reference-style links differ from English " + "(['[g]', '[g]:'] here, [] in English); write links as [text](target)", + "ko/learn/other.md: 5 paragraphs and list items, 4 in English", + ], + ), + "directory link with a fragment": ( + lambda: _guide(_swap("(other.md#details)", "(other/#details)")), + [ + "ko/learn/guide.md: links of the English page are missing: " + "['learn/other.md#details']", + "ko/learn/guide.md: links not on the English page: " + "['learn/other/#details']", + "ko/learn/guide.md: link 'other/#details' does not name a Markdown file", + ], + ), + "unclosed fence": ( + lambda: _guide(_swap("app = FastAPI()\n```\n", "app = FastAPI()\n")), + [ + "ko/learn/guide.md: the code block opened at line 27 is never closed", + "ko/learn/guide.md: generated blocks differ from English", + "ko/learn/guide.md: 1 code blocks, 2 in English", + ], + ), + "indented code changed": ( + lambda: _other(_swap(" $ fastkit doctor\n", " $ fastkit doctor --fix\n")), + ["ko/learn/other.md: code block 1 (line 18, ```console) differs"], + ), + "table row dropped": ( + lambda: _other(_swap("| `fastkit doctor` | 프로젝트를 검사합니다. |\n", "")), + [ + "ko/learn/other.md: tables differ from English (cells per row: missing " + "here: ['2']); keep every table row of docs/en/learn/other.md with the " + "same number of cells" + ], + ), + "table cells merged": ( + lambda: _other( + _swap("| `fastkit doctor` | 프로젝트를", "| `fastkit doctor` 프로젝트를") + ), + [ + "ko/learn/other.md: tables differ from English (cells per row: item 4 " + "is '1' here, '2' in English)" + ], + ), + "table row left in English": ( + lambda: _other( + _swap( + "폴더에 새 프로젝트를 만듭니다.", "Creates a new project in a folder." + ) + ), + [ + "ko/learn/other.md: 1 sentence or table row is still in English ('| " + "`fastkit init` | Creates a new project in a folder. |')" + ], + ), +} + + +@pytest.mark.parametrize("name", list(DEVIATIONS)) +def test_deviation_is_reported(tmp_path: Path, name: str) -> None: + pages, expected = DEVIATIONS[name] + problems = check_locale(_tree(tmp_path, pages()), "ko") + for text in expected: + assert any(text in problem for problem in problems), (text, problems) + assert len(problems) == len(expected), problems + + +def test_unchanged_texts_may_stay_english( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + pages = _other( + lambda text: text.replace( + "폴더에 새 프로젝트를 만듭니다.", "Creates a new project in a folder." + ).replace( + "모든 단계의 자세한 내용이 여기 있습니다.", + "The details of every step are here.", + ) + ) + monkeypatch.setitem( + docs_support.UNCHANGED_IN_TRANSLATIONS, + "learn/other.md", + ( + "| `fastkit init` | Creates a new project in a folder. |", + "The details of every step are here.", + ), + ) + assert check_locale(_tree(tmp_path, pages), "ko") == [] + + +def test_short_english_table_cells_may_stay(tmp_path: Path) -> None: + pages = _other(_swap("프로젝트를 검사합니다.", "Checks the project.")) + assert check_locale(_tree(tmp_path, pages), "ko") == [] + + +def test_missing_language_directory_lists_every_page(tmp_path: Path) -> None: + problems = check_locale(_tree(tmp_path, {}), "ko") + assert problems == [ + "ko/changelog.md: missing; translate docs/en/changelog.md", + "ko/learn/guide.md: missing; translate docs/en/learn/guide.md", + "ko/learn/other.md: missing; translate docs/en/learn/other.md", + ] + + +# ------------------------------------------------------- HEADINGS entries + + +def test_headings_entry_must_have_every_key_and_placeholder() -> None: + english = {"level": "Level", "any": "any {axis}", "or": "{items} or {last}"} + headings = { + "en": english, + "ko": {"level": "레벨", "any": "모든 {label}", "extra": "x"}, + } + assert headings_problems("ko", headings) == [ + "HEADINGS['ko'] lacks 'or'; translate HEADINGS['en']['or']", + "HEADINGS['ko'] has 'extra', which 'en' lacks; remove it", + "HEADINGS['ko']['any'] must use the placeholders ['axis'], not ['label']", + ] + assert headings_problems("ko", headings, complete=False) == [ + "HEADINGS['ko'] has 'extra', which 'en' lacks; remove it", + "HEADINGS['ko']['any'] must use the placeholders ['axis'], not ['label']", + ] + assert headings_problems("ja", headings) == [ + "HEADINGS has no 'ja' entry; add one to scripts/docs_blocks.py with " + "every key of 'en'" + ] + assert headings_problems("ja", headings, complete=False) == [] + headings["ko"] = {"level": " ", "any": "모든 {axis}", "or": "{items} 또는 {last}"} + assert headings_problems("ko", headings) == ["HEADINGS['ko']['level'] is empty"] diff --git a/tests/test_docs/test_redirects.py b/tests/test_docs/test_redirects.py index 4aa18cdb..bae0ca58 100644 --- a/tests/test_docs/test_redirects.py +++ b/tests/test_docs/test_redirects.py @@ -5,32 +5,19 @@ # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- -import re -import unicodedata from pathlib import Path from typing import Any, Dict, Set import pytest from .docs_support import EN, ROOT, read, redirects +from .parity import parse_page REDIRECTS: Dict[str, str] = redirects().REDIRECTS -def _slug(heading: str) -> str: - """The anchor Python-Markdown's toc extension gives a heading.""" - text = unicodedata.normalize("NFKD", heading).encode("ascii", "ignore").decode() - text = re.sub(r"[^\w\s-]", "", text).strip().lower() - return re.sub(r"[-\s]+", "-", text) - - def _anchors(page: Path) -> Set[str]: - anchors = set() - for line in read(page).splitlines(): - match = re.match(r"^#{1,6}\s+(.+?)\s*$", line) - if match: - anchors.add(_slug(match.group(1))) - return anchors + return parse_page(read(page)).anchors def test_hook_is_registered_in_mkdocs_yml() -> None: diff --git a/tests/test_docs/test_translate_script.py b/tests/test_docs/test_translate_script.py new file mode 100644 index 00000000..1531fd5e --- /dev/null +++ b/tests/test_docs/test_translate_script.py @@ -0,0 +1,291 @@ +# -------------------------------------------------------------------------- +# Test cases for scripts/translate.py: code, generated blocks and front +# matter never reach the API and come back unchanged, hand-maintained pages +# are skipped, and the providers agree with the translate-docs workflow. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import re +from pathlib import Path +from typing import List + +import pytest + +from .docs_support import EN, ROOT, docs_blocks, english_pages, read, translate_script + +translate = translate_script() +blocks = docs_blocks() + +PAGE = """--- +hide: + - toc +--- +# Title + +Some prose to translate. + +```console +$ fastkit init +``` + + + +- [Testing](https://fastapi.tiangolo.com/tutorial/testing/) + + + +More prose. +""" + + +class Prefixer(translate.TranslationAPI): + """Marks every line it translates, as an API would change them.""" + + def __init__(self) -> None: + super().__init__("key") + self.sent: List[str] = [] + + def translate(self, text: str, target_lang: str, source_lang: str = "en") -> str: + self.sent.append(text) + return "\n".join( + ( + line + if not line.strip() or "fastkit:keep" in line + else f"[{target_lang}] {line}" + ) + for line in text.split("\n") + ) + + +def test_protect_hides_front_matter_code_and_generated_blocks() -> None: + prose, kept = translate.protect(PAGE) + assert prose.split("\n")[:3] == [ + "", + "# Title", + "", + ] + assert "$ fastkit init" not in prose and "Testing" not in prose + assert "fastkit:generated" not in prose and "hide:" not in prose + assert kept[1] == "```console\n$ fastkit init\n```" + assert kept[2].startswith("") + assert kept[2].endswith("") + assert translate.restore(prose, kept) == PAGE + + +@pytest.mark.parametrize("page", english_pages()) +def test_every_english_page_survives_protect_and_restore(page: str) -> None: + text = read(EN / page) + prose, kept = translate.protect(text) + assert translate.restore(prose, kept) == text.replace("\r\n", "\n") + assert not blocks.find_blocks(prose) + assert not any(translate.FENCE.match(line) for line in prose.split("\n")) + + +INDENTED = """# Install + +!!! note + Run it: + + ```console + $ fastkit init + ``` + +=== "uv" + + ```console + $ uv tool install fastapi-fastkit + ``` + +- A list item with code: + + ```console + $ fastkit doctor + ``` + +!!! warning + ```console + $ fastkit runserver + +The note ended without a closing fence. +""" + + +def test_protect_hides_indented_fences() -> None: + prose, kept = translate.protect(INDENTED) + assert "$ " not in prose and "```" not in prose + assert len(kept) == 4 + assert kept[0] == " ```console\n $ fastkit init\n ```" + assert kept[3] == " ```console\n $ fastkit runserver" + assert "The note ended without a closing fence." in prose + assert " Run it:" in prose + assert " " in prose.split("\n") + assert translate.restore(prose, kept) == INDENTED + + +@pytest.mark.parametrize( + "change", + [ + lambda text: text.replace("\n", ""), + lambda text: text + "\n", + lambda text: text.replace("keep 1 -->", "keep 9 -->"), + ], + ids=["lost", "repeated", "changed"], +) +def test_restore_refuses_a_translation_that_lost_a_placeholder(change) -> None: + prose, kept = translate.protect(PAGE) + with pytest.raises(ValueError, match="placeholder lines"): + translate.restore(change(prose), kept) + + +def test_restore_accepts_indented_placeholders() -> None: + prose, kept = translate.protect(PAGE) + assert ( + translate.restore( + prose.replace("\n", "", translated) + return translated + + +def _main(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *files: str) -> int: + docs = tmp_path / "docs" + for rel, text in { + "learn/a.md": PAGE, + "learn/b.md": PAGE.replace("# Title", "# Broken page"), + }.items(): + path = docs.joinpath("en", *rel.split("/")) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(text.encode("utf-8")) + monkeypatch.setenv("TRANSLATION_API_KEY", "key") + monkeypatch.setattr(translate, "OpenAITranslator", Dropper) + argv = ["--target-lang", "ko", "--no-pr", "--docs-dir", str(docs)] + try: + translate.main(argv + (["--files", *files] if files else [])) + except SystemExit as error: + return int(error.code or 0) + return 0 + + +def test_main_exits_1_after_a_page_that_failed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + assert _main(tmp_path, monkeypatch) == 1 + ko = tmp_path / "docs" / "ko" / "learn" + assert (ko / "a.md").is_file() and not (ko / "b.md").exists() + + +def test_main_exits_1_for_a_requested_page_that_does_not_exist( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + assert _main(tmp_path, monkeypatch, "learn/a.md", "learn/nope.md") == 1 + assert (tmp_path / "docs" / "ko" / "learn" / "a.md").is_file() + + +def test_main_succeeds_when_every_page_is_translated( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + assert _main(tmp_path, monkeypatch, "learn/a.md") == 0 + assert (tmp_path / "docs" / "ko" / "learn" / "a.md").is_file()