mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
chore(skills): add plain-prose skill and prose-check linter (#5684)
* chore(skills): add plain-prose skill and prose-check linter A skill for clipped sentences in API descriptions, docstrings, comments, en_US strings and error messages, run in pr-ready before humanizer. A stdlib tool extracts the prose a diff adds for batched review, and a Trunk linter enforces the rules a regex can decide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(skills): run pr-ready reviews in parallel subagents Simplify, polish, prose and the security audit run as background agents over the same range while code-review runs in the main session, since it fans out reviewers of its own. Their commits land in step order, and the verification gate runs once on the merged branch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(skills): route errors go in responses, not docstrings Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(prose-check): address Greptile review - Expand directory arguments into their source files. - Accept paths after --diff (parse_intermixed_args). - Extract positional messages of raised exceptions and logger calls. - Point each locale unit at its own key, not the first key with that name. - Run the Trunk linter on the pinned Python runtime. - Trim the module docstring to one sentence; usage lives in the skill. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
committed by
GitHub
parent
e06e0e4010
commit
b1ce1afb29
180
.claude/skills/plain-prose/SKILL.md
Normal file
180
.claude/skills/plain-prose/SKILL.md
Normal file
@@ -0,0 +1,180 @@
|
||||
---
|
||||
name: plain-prose
|
||||
description: Make every sentence a reader sees in RomM read on the first pass, without the code open. Catches compression rather than AI tells - clipped conditionals ("Unset, keeps the value"), "X, else Y" chains, dropped subjects ("Only the fields sent change"), label fragments where a sentence belongs ("Exact artist.", "Rom internal id."), slash lists and internal slang. Covers API descriptions, docstrings, comments, en_US UI strings and error messages, over a diff or the whole codebase, with backend/tools/prose_check.py to extract the prose and a Trunk check for the rules a regex can decide. Use before opening a PR, when reviewing reader-facing text, or when asked to clean up wording across an area.
|
||||
---
|
||||
|
||||
# Plain prose
|
||||
|
||||
Short is good. Clipped is not. A sentence is clipped when the writer dropped the
|
||||
words a reader needs to parse it: the subject, the verb, the "if", the "or". The
|
||||
writer still has the code in their head and doesn't notice. The reader has only
|
||||
the sentence.
|
||||
|
||||
The test for every sentence: **would someone reading the API docs, the UI or the
|
||||
file cold understand it on the first pass?** If they would have to reread it or
|
||||
open the code, rewrite it.
|
||||
|
||||
`humanizer` looks for AI tells. This skill looks for compression. A string can
|
||||
pass one and fail the other, so run both: this one first, then `humanizer`.
|
||||
|
||||
## Where it applies
|
||||
|
||||
| Surface | Sentence or label? |
|
||||
| ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Route docstrings, schema field docstrings, `description=` on `Query`, `PathVar`, `Path`, `Header`, `Form`, `Field` | Sentences. They are the public API docs. |
|
||||
| `HTTPException(detail=...)`, raised error messages, log messages | Sentences. |
|
||||
| Docstrings and comments | Sentences, kept to one or two lines (`AGENTS.md`). Fix clipping with whole words, then cut content if it no longer fits. |
|
||||
| `frontend/src/locales/en_US/*.json` | Labels are fragments by design: buttons, titles, menu items, column headers, chips ("Add labels", "Achievements"). Text that ends in a period, and keys ending in `-desc`, `-hint`, `-help`, `-tooltip`, `-empty`, `-subtitle`, `-error`, `-warning`, `-confirm` or `-message`, are sentences. |
|
||||
|
||||
Leave alone: identifiers and code in backticks, lint and type directives,
|
||||
commented-out code, provider text quoted verbatim, test fixtures, other locales
|
||||
(`en_US` is the source; see `frontend-i18n`), and `__generated__` files, which
|
||||
you regenerate instead.
|
||||
|
||||
## What to fix
|
||||
|
||||
Each example below is a string rewritten on #5660 or flagged on `master`.
|
||||
|
||||
**1. Clipped conditionals.** A state word, a comma, then the result.
|
||||
`prose_check` flags these.
|
||||
|
||||
- "Unset keeps the current value." becomes "Leave it out to keep the current value."
|
||||
- "Left out, the push expects..." becomes "If left out, the server uses..."
|
||||
- "Off, the chevron only keeps its..." becomes "When it is off, the chevron..."
|
||||
|
||||
**2. "X, else Y" chains.** `prose_check` flags these too.
|
||||
|
||||
- "The device to clear, else the client token's." becomes "The device to clear. Defaults to the client token's device."
|
||||
- "the latest save's screenshot, else the title screen, else the first gameplay screenshot" becomes "the screenshot of the latest save, or else the title screen, or else the first gameplay screenshot"
|
||||
|
||||
**3. A missing subject, object or verb.**
|
||||
|
||||
- "Update a device. Only the fields sent change." becomes "Update a device. Fields left out of the request keep their current values."
|
||||
- "The code is used up and the previous secret is replaced." becomes "The code cannot be used again, and the token's previous secret stops working."
|
||||
- "No hash returns 400" becomes "Returns 400 if no hash is given"
|
||||
- "Needs `device_id`." becomes "Requires `device_id`."
|
||||
|
||||
**4. A label where a sentence belongs.** Mostly field and parameter descriptions.
|
||||
|
||||
- "Exact artist." becomes "Only tracks by this artist, matched exactly."
|
||||
- "Page size limit" becomes "The maximum number of items per page."
|
||||
- "asc or desc." becomes "The sort direction, `asc` or `desc`."
|
||||
- "Rom internal id." becomes "The ID of the rom." (`prose_check` flags "internal id")
|
||||
|
||||
**5. Slash lists in prose.** "title/artist/album/duration" becomes "`title`,
|
||||
`artist`, `album` or `duration`" for values, or "title, artist or album" for
|
||||
words. Paths, MIME types and `and/or` stay.
|
||||
|
||||
**6. Internal slang.** Words that mean something only inside the code:
|
||||
"the row" (say what it is), "picks", "comes free" ("is filled in at no extra
|
||||
cost"), "the named device" ("the device given in `device_id`"), "minus any"
|
||||
("excluding any"), "a stale device" ("a device with an outdated copy"), "the
|
||||
watcher" ("the file watcher").
|
||||
|
||||
**7. Verb-free noun stacks.** "Platform-native identity, e.g. SLUS-20152."
|
||||
becomes "The game's ID on its own platform, such as `SLUS-20152`."
|
||||
|
||||
**8. Pronouns with two candidates.** "It looks up the title when no name is
|
||||
given." Does "it" mean the barcode or the server? Write "The barcode of a
|
||||
physical game, used to look up its title when no name is given."
|
||||
|
||||
Keep a short sentence when it is complete: "Delete a device." is fine.
|
||||
|
||||
## One phrasing per idea
|
||||
|
||||
API text repeats the same ideas. Use the same words each time.
|
||||
|
||||
| Idea | Phrasing |
|
||||
| --------------------- | ---------------------------------------------------------- |
|
||||
| An ID parameter | The ID of the rom. |
|
||||
| An optional parameter | If left out, ... / Leave it out to keep the current value. |
|
||||
| A partial update | Fields left out of the request keep their current values. |
|
||||
| A default | Defaults to 50. |
|
||||
| A filter | Only tracks from this year or later. |
|
||||
| A request boolean | Whether to include each rom's `files`. |
|
||||
| A response boolean | True when at least one provider has matched the rom. |
|
||||
| A route error | See below. |
|
||||
| A parameter error | An unknown or expired code returns 404. |
|
||||
| A nullable field | Null when `with_total` is false. |
|
||||
| An example | such as `snes` (not "e.g.") |
|
||||
|
||||
A route's error statuses go in `responses=` on its decorator, not in its
|
||||
docstring. FastAPI lists them in the Responses table, and the schema carries
|
||||
them as data:
|
||||
|
||||
```python
|
||||
@protected_route(
|
||||
router.get,
|
||||
"/pkgj/psvita/games",
|
||||
[Scope.ROMS_READ],
|
||||
responses={
|
||||
status.HTTP_404_NOT_FOUND: {
|
||||
"description": "The library has no PlayStation Vita platform."
|
||||
}
|
||||
},
|
||||
)
|
||||
def pkgj_psv_games_feed(request: Request) -> Response:
|
||||
"""Get the PKGj feed of PlayStation Vita games as tab-separated text."""
|
||||
```
|
||||
|
||||
Give each entry a `description`, since an empty `{}` shows only "Not Found".
|
||||
Keep an error in a parameter's description when that parameter causes it, as
|
||||
in the table. A hidden rom, platform or firmware answers like a missing one,
|
||||
so describe the 404 as "No rom the caller can see matches", never as "the rom
|
||||
is hidden".
|
||||
|
||||
Route and schema docstrings take no `Args:`, `Returns:` or `Raises:` blocks.
|
||||
FastAPI and Pydantic publish the docstring verbatim, so those sections reach
|
||||
the API docs as plain text.
|
||||
|
||||
## How to run it
|
||||
|
||||
**1. Mechanical rules.** `trunk check` runs `prose-check` (defined in
|
||||
`.trunk/trunk.yaml`) on changed files and reports only new issues. Fix what it
|
||||
flags first.
|
||||
|
||||
**2. Extract the prose.** One JSON line per prose unit, with its path, line,
|
||||
kind (`comment`, `docstring`, `description`, `detail`, `error`, `log`,
|
||||
`locale:<key>`...) and text. A directory expands to the source files under it:
|
||||
|
||||
```bash
|
||||
python3 backend/tools/prose_check.py extract --diff origin/master... > /tmp/prose.jsonl
|
||||
python3 backend/tools/prose_check.py extract backend/endpoints/roms/ # an area, whole files
|
||||
```
|
||||
|
||||
`--diff` keeps only the units that overlap lines added since the base. Give it
|
||||
paths too, before or after the option, to limit the diff to them.
|
||||
|
||||
**3. Review.** Read every unit against "What to fix". Up to about 150 units,
|
||||
do it yourself. Beyond that, split the JSONL into batches of about 100 by file,
|
||||
and give each batch to a subagent with this file's path and the instruction to
|
||||
return only the units that need a change, as `path`, `line`, the old text and
|
||||
the new text. A subagent proposes; you apply and check, because it cannot see
|
||||
the other batches and drifts from the phrasing table.
|
||||
|
||||
**4. Apply.** Edit the source, never the extract. Then:
|
||||
|
||||
- API text: regenerate the frontend types. With no server running, dump the
|
||||
schema with `backend/tools/dump_openapi.py` and feed it to the `openapi`
|
||||
command from the `generate` script in `frontend/package.json`. The generated
|
||||
diff must be comment-only.
|
||||
- `en_US` text: follow `frontend-i18n`.
|
||||
- `trunk fmt && trunk check`, and `backend/tests/endpoints/test_openapi_docs.py`
|
||||
when API text changed.
|
||||
|
||||
**5. Run `humanizer`** over the same prose.
|
||||
|
||||
For a codebase-wide pass, go one area at a time (a router, a component folder,
|
||||
a locale file), one PR each, so a reviewer can read the rewrites.
|
||||
|
||||
## Adding a rule to `prose_check`
|
||||
|
||||
Keep the script stdlib only: Trunk runs it on the Python runtime pinned in
|
||||
`.trunk/trunk.yaml`, with no project dependencies installed.
|
||||
|
||||
A regex rule fails CI, so it has to be right almost every time. Before adding
|
||||
one, run it over the whole codebase (`python3 backend/tools/prose_check.py
|
||||
check $(git ls-files 'backend/*.py' 'frontend/src/*.ts' 'frontend/src/*.vue')`)
|
||||
and read every hit. Add it only if nearly all of them are real, with a passing
|
||||
and a failing case in `backend/tests/tools/test_prose_check.py`. Everything
|
||||
else belongs in "What to fix" above.
|
||||
@@ -1,14 +1,15 @@
|
||||
---
|
||||
name: pr-ready
|
||||
description: Run the pre-submit gauntlet (security-audit, code-review, simplify, review-polish, humanizer) over a change before opening or merging a PR.
|
||||
description: Run the pre-submit gauntlet (security-audit, code-review, simplify, review-polish, plain-prose, humanizer) over a change before opening or merging a PR.
|
||||
argument-hint: "[PR number | branch | nothing for the current branch]"
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# PR-ready gauntlet
|
||||
|
||||
Run the review passes RomM applies to every non-trivial PR, in this order,
|
||||
over one fixed range. Do not skip a step or reorder them.
|
||||
Run the review passes RomM applies to every non-trivial PR over one fixed
|
||||
range. They run in parallel and land in this order. Do not skip a step or
|
||||
reorder the commits.
|
||||
|
||||
## Target
|
||||
|
||||
@@ -66,8 +67,9 @@ its source branch, so on a fork you cannot write to, the summary is the
|
||||
deliverable and the commits are not.
|
||||
|
||||
Skip the branch when the target is already the current one. There, uncommitted
|
||||
work counts as part of the change under review: commit or stash anything
|
||||
unrelated first, so each step's edits stay attributable.
|
||||
work counts as part of the change under review: commit it, since the agents'
|
||||
worktrees see only commits, and stash anything unrelated, so each step's edits
|
||||
stay attributable.
|
||||
|
||||
## Steps
|
||||
|
||||
@@ -75,31 +77,86 @@ unrelated first, so each step's edits stay attributable.
|
||||
verdict; `needs attention` is a finding for step 2, not a stop.
|
||||
2. **`code-review` at `xhigh` with `--fix`**, targeting the resolved target
|
||||
rather than "the current diff", so it sees the whole change.
|
||||
3. **`simplify`**, after the correctness fixes so it can simplify those too.
|
||||
4. **`review-polish`**: its verification gate has to cover everything the
|
||||
earlier steps rewrote.
|
||||
5. **`humanizer`** last, over the prose `$BASE..HEAD` adds or changes (not
|
||||
`$RANGE`, so it covers what steps 2 to 4 committed). See "Step 5 scope" below.
|
||||
3. **`simplify`**, so it can simplify the correctness fixes too.
|
||||
4. **`review-polish`**: §A to §D shape the code, and the §E verification gate
|
||||
has to cover everything the earlier steps rewrote.
|
||||
5. **`plain-prose`, then `humanizer`**, over the prose `$RANGE` adds or changes,
|
||||
and again over what step 2 adds. See "Prose scope" below.
|
||||
|
||||
Commit after each step that changes files, naming the step in the message. A bad
|
||||
Each step that changes files ends in its own commit, named after the step. A bad
|
||||
automated fix is then one `git revert` away instead of tangled with the other
|
||||
passes.
|
||||
|
||||
Finish with one consolidated summary rather than per-step transcripts: the
|
||||
security verdict, what steps 2 to 5 changed by area, which checks ran and their
|
||||
results, and anything still needing a human decision.
|
||||
## Running the steps in parallel
|
||||
|
||||
The summary also carries what the PR description needs and the transcripts hold: the
|
||||
screenshots step 4 captured, which the PR body references and `gh ... --attach` uploads
|
||||
under the `Screenshots` heading, and the `mermaid` block for a change that moved a
|
||||
On a trusted ref, run the reviews at the same time over the same `$RANGE`,
|
||||
then merge their commits in step order. On an untrusted ref, step 1 runs alone
|
||||
first (see above), and the rest follow only on a clean verdict.
|
||||
|
||||
**Fan out.** The checkout must be at `$TARGET` with a clean tree, because each
|
||||
agent's worktree starts from `HEAD`. In one message, start these background
|
||||
agents with the Agent tool:
|
||||
|
||||
| Agent | Isolation | Does |
|
||||
| ---------- | ---------------- | ----------------------------------------------------------- |
|
||||
| `security` | none (read-only) | Step 1. Returns the verdict and findings. |
|
||||
| `simplify` | `worktree` | Step 3 over `$RANGE`. |
|
||||
| `polish` | `worktree` | Step 4 §A to §D only. Not §E. |
|
||||
| `prose` | `worktree` | Step 5 over `$BASE`. Also returns the PR description edits. |
|
||||
|
||||
Then run step 2 in this session while they work. `code-review` and
|
||||
`security-audit` fan out reviewers of their own, and a subagent cannot start
|
||||
subagents, so step 2 stays here and the `security` agent runs the audit's
|
||||
direct pass. If it returns `needs attention` on an area, deepen that area here
|
||||
after step 2.
|
||||
|
||||
The agents never see step 2's fixes, so catch up on them while you wait. Right
|
||||
after step 2's commit, `prose_check.py extract --diff $TARGET` lists exactly
|
||||
the prose step 2 added: run step 5 over it. Run `simplify` over step 2's commit
|
||||
too when it changed more than about 50 lines. Commit each as its step.
|
||||
|
||||
Each agent's prompt carries:
|
||||
|
||||
- `$BASE`, `$RANGE` and `$TARGET`, and the step to run. It invokes the skill
|
||||
with the Skill tool, or reads its `SKILL.md` for `humanizer` (see "Prose
|
||||
scope").
|
||||
- Stay inside the files `$RANGE` touches. Commit once, named after the step
|
||||
(`pr-ready: simplify`). Never push.
|
||||
- Run only the tests its edits affect, with a `ROMM_TEST_DB_TAG` of its own name.
|
||||
No browser pass, no Storybook, no §E gate.
|
||||
- Return the commit sha, or "no changes", and a short list of what it changed.
|
||||
|
||||
A `malicious` verdict from the `security` agent stops the run when it arrives:
|
||||
stop the other agents, reset the branch to `$TARGET`, and report.
|
||||
|
||||
**Merge in step order.** When every agent is back, cherry-pick the `simplify`,
|
||||
`polish` and `prose` commits onto step 2's commits, in that order. On a
|
||||
conflict, keep the earlier step's hunk, then reapply the later step's intent by
|
||||
hand if it still applies. Never resolve with `-X theirs` or `-X ours` across a
|
||||
whole commit.
|
||||
|
||||
**Verify once.** Run `review-polish` §E on the merged branch: the checks for
|
||||
what the whole range touched, the browser pass for a UI change, and the
|
||||
screenshots and `mermaid` block §F asks for.
|
||||
|
||||
Finish with one consolidated summary rather than per-agent transcripts: the
|
||||
security verdict, what steps 2 to 5 changed by area, which checks ran and their
|
||||
results, any conflict you resolved by hand, and anything still needing a human
|
||||
decision. It also carries what the PR description needs: the `prose` agent's
|
||||
edits, the screenshots §E captured, which `gh ... --attach` uploads under the
|
||||
`Screenshots` heading, and the `mermaid` block for a change that moved a
|
||||
boundary.
|
||||
|
||||
The whole gauntlet in one session is a lot of context. For a very large diff,
|
||||
run the steps in separate sessions against the same `$RANGE`.
|
||||
The agents keep their transcripts out of this session, so even a large diff
|
||||
fits in one run.
|
||||
|
||||
## Step 5 scope
|
||||
## Prose scope
|
||||
|
||||
Read `.claude/skills/humanizer/SKILL.md` and apply it rather than invoking the
|
||||
First apply `.claude/skills/plain-prose/SKILL.md` to the units
|
||||
`python3 backend/tools/prose_check.py extract --diff $BASE` lists. It covers the
|
||||
API descriptions and `en_US` strings that `humanizer` skips below.
|
||||
|
||||
Then read `.claude/skills/humanizer/SKILL.md` and apply it rather than invoking the
|
||||
skill, since a personal install of the same name would load instead. In file
|
||||
mode it edits the Markdown paragraphs the range touches, and comments and
|
||||
docstrings on added lines. Skip locale files, paths in the `.trunk/trunk.yaml`
|
||||
|
||||
@@ -29,6 +29,9 @@ rationale, and it gets cut. Cut it yourself.
|
||||
an `Args:`/`Returns:` block when the signature needs it. If you wrote three or
|
||||
more lines of prose, you are explaining, not commenting.
|
||||
|
||||
**Short, not clipped.** Each sentence that stays is complete: no "Unset, X",
|
||||
"X, else Y" or "Only the fields sent change". `plain-prose` has the patterns.
|
||||
|
||||
**Delete outright:**
|
||||
|
||||
- **Change history and migration notes.** "Replaces the manual pattern: ...",
|
||||
|
||||
@@ -43,6 +43,7 @@ lint:
|
||||
- black@26.10.1
|
||||
- checkov@3.4.5
|
||||
- git-diff-check
|
||||
- prose-check
|
||||
- isort@9.0.2
|
||||
- osv-scanner@2.7.1
|
||||
- prettier@3.10.1:
|
||||
@@ -115,6 +116,25 @@ lint:
|
||||
- graphql
|
||||
- vue
|
||||
- prettier_supported_configs
|
||||
# The regex-decidable rules of the plain-prose skill, run on comments,
|
||||
# docstrings, API descriptions and en_US strings.
|
||||
- name: prose-check
|
||||
files: [python, typescript, vue, json]
|
||||
description: Flags clipped sentences in comments and reader-facing text
|
||||
runtime: python
|
||||
commands:
|
||||
- name: lint
|
||||
output: regex
|
||||
parse_regex: (?P<path>.*):(?P<line>\d+):(?P<col>\d+):\s+\[(?P<code>[^\]]+)\]\s+(?P<message>.*)
|
||||
run: python3 ${workspace}/backend/tools/prose_check.py check ${target}
|
||||
success_codes: [0, 1]
|
||||
batch: true
|
||||
cache_results: true
|
||||
read_output_from: stdout
|
||||
environment:
|
||||
- name: PATH
|
||||
list: ["${env.PATH}"]
|
||||
known_good_version: ""
|
||||
actions:
|
||||
disabled:
|
||||
- trunk-check-pre-push
|
||||
|
||||
152
backend/tests/tools/test_prose_check.py
Normal file
152
backend/tests/tools/test_prose_check.py
Normal file
@@ -0,0 +1,152 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from tools.prose_check import Prose, main, units, violations
|
||||
|
||||
PYTHON_SOURCE = '''"""Module docstring."""
|
||||
|
||||
from fastapi import Query
|
||||
|
||||
# Two comment lines that
|
||||
# form one sentence.
|
||||
LIMIT = Query(description="The ID of the rom.") # noqa: E501
|
||||
|
||||
|
||||
def handler():
|
||||
raise ValueError(detail=f"No rom {LIMIT}.")
|
||||
'''
|
||||
|
||||
SCRIPT_SOURCE = """// A line comment.
|
||||
const url = "https://example.com"; // Trailing comment.
|
||||
/** A block
|
||||
* comment. */
|
||||
// eslint-disable-next-line no-console
|
||||
"""
|
||||
|
||||
|
||||
def _codes(text: str) -> list[str]:
|
||||
return [rule.code for rule, _ in violations(Prose("x.py", 1, 1, "comment", text))]
|
||||
|
||||
|
||||
def test_python_units_cover_docstrings_descriptions_details_and_comments(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
path = tmp_path / "module.py"
|
||||
path.write_text(PYTHON_SOURCE)
|
||||
|
||||
found = {(unit.kind, unit.text) for unit in units(path)}
|
||||
|
||||
assert found == {
|
||||
("docstring", "Module docstring."),
|
||||
("comment", "Two comment lines that\nform one sentence."),
|
||||
("description", "The ID of the rom."),
|
||||
("detail", "No rom {}."),
|
||||
}
|
||||
|
||||
|
||||
def test_script_units_skip_urls_and_directives(tmp_path: Path) -> None:
|
||||
path = tmp_path / "module.ts"
|
||||
path.write_text(SCRIPT_SOURCE)
|
||||
|
||||
found = sorted(unit.text for unit in units(path))
|
||||
|
||||
assert found == ["A block\ncomment.", "A line comment.", "Trailing comment."]
|
||||
|
||||
|
||||
def test_locale_units_read_en_us_values_only(tmp_path: Path) -> None:
|
||||
en_us = tmp_path / "frontend/src/locales/en_US"
|
||||
en_us.mkdir(parents=True)
|
||||
(en_us / "rom.json").write_text(
|
||||
'{\n "title": "Title",\n "nested": {"hint": "A hint."}\n}\n'
|
||||
)
|
||||
fr_fr = tmp_path / "frontend/src/locales/fr_FR"
|
||||
fr_fr.mkdir(parents=True)
|
||||
(fr_fr / "rom.json").write_text('{"title": "Titre"}')
|
||||
|
||||
found = [(u.kind, u.line) for u in units(en_us / "rom.json")]
|
||||
|
||||
assert found == [("locale:title", 2), ("locale:nested.hint", 3)]
|
||||
assert list(units(fr_fr / "rom.json")) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("text", "codes"),
|
||||
[
|
||||
("The device to clear, else the client token's.", ["else-chain"]),
|
||||
("Left out, the server picks one.", ["clipped-conditional"]),
|
||||
("The ID of the rom. Unset, every rom matches.", ["clipped-conditional"]),
|
||||
("Rom internal id.", ["internal-id"]),
|
||||
("Absent, empty and over-long hashes all mean unknown.", []),
|
||||
("If left out, the server picks one, or else the first.", []),
|
||||
("The ID of the rom.", []),
|
||||
],
|
||||
)
|
||||
def test_rules(text: str, codes: list[str]) -> None:
|
||||
assert _codes(text) == codes
|
||||
|
||||
|
||||
def test_check_reports_path_line_and_rule(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
path = tmp_path / "module.py"
|
||||
path.write_text("X = 1\n\n# Fine.\n# Left out, the default\n# applies.\n")
|
||||
|
||||
status = main(["check", str(path)])
|
||||
|
||||
assert status == 1
|
||||
assert capsys.readouterr().out == (
|
||||
f"{path.as_posix()}:4:1: [clipped-conditional] "
|
||||
"Clipped conditional. Write 'If left out, ...' or 'When it is empty, ...'.\n"
|
||||
)
|
||||
|
||||
|
||||
def test_python_units_cover_raised_and_logged_messages(tmp_path: Path) -> None:
|
||||
path = tmp_path / "module.py"
|
||||
path.write_text(
|
||||
'def f(log):\n log.error("Scan failed.")\n'
|
||||
' print("Not prose.")\n raise ValueError(f"No rom {log}.")\n'
|
||||
)
|
||||
|
||||
found = {(unit.kind, unit.line, unit.text) for unit in units(path)}
|
||||
|
||||
assert found == {("log", 2, "Scan failed."), ("error", 4, "No rom {}.")}
|
||||
|
||||
|
||||
def test_locale_units_point_to_their_own_key(tmp_path: Path) -> None:
|
||||
en_us = tmp_path / "frontend/src/locales/en_US"
|
||||
en_us.mkdir(parents=True)
|
||||
(en_us / "rom.json").write_text(
|
||||
'{\n "a": {\n "hint": "A."\n },\n "b": {\n "hint": "B."\n }\n}\n'
|
||||
)
|
||||
|
||||
found = [(u.kind, u.line) for u in units(en_us / "rom.json")]
|
||||
|
||||
assert found == [("locale:a.hint", 3), ("locale:b.hint", 6)]
|
||||
|
||||
|
||||
def test_extract_expands_directories(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
(tmp_path / "pkg").mkdir()
|
||||
(tmp_path / "pkg" / "module.py").write_text("# A comment.\n")
|
||||
(tmp_path / "pkg" / "notes.txt").write_text("# Not source.\n")
|
||||
|
||||
assert main(["extract", str(tmp_path)]) == 0
|
||||
assert '"text": "A comment."' in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_paths_may_follow_diff(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
path = tmp_path / "module.py"
|
||||
path.write_text("# Left out, the default applies.\n")
|
||||
monkeypatch.setattr(
|
||||
"tools.prose_check.added_lines", lambda base: {path.as_posix(): {1}}
|
||||
)
|
||||
|
||||
assert main(["check", "--diff", "origin/master...", str(path)]) == 1
|
||||
|
||||
|
||||
def test_check_passes_clean_files(tmp_path: Path) -> None:
|
||||
path = tmp_path / "module.py"
|
||||
path.write_text("# If left out, the default applies.\n")
|
||||
|
||||
assert main(["check", str(path)]) == 0
|
||||
317
backend/tools/prose_check.py
Normal file
317
backend/tools/prose_check.py
Normal file
@@ -0,0 +1,317 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Find the prose in source files and check it for clipped sentences."""
|
||||
|
||||
import argparse
|
||||
import ast
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import subprocess # nosec B404 - runs only `git diff` with a fixed argv
|
||||
import sys
|
||||
import tokenize
|
||||
from collections.abc import Iterable, Iterator
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
|
||||
# Keyword arguments whose string value is reader-facing text.
|
||||
TEXT_KEYWORDS = frozenset({"description", "detail", "summary", "help"})
|
||||
LOG_METHODS = frozenset({"debug", "info", "warning", "error", "exception", "critical"})
|
||||
SUFFIXES = frozenset({".py", ".ts", ".vue", ".js", ".mts", ".json"})
|
||||
# Comments that are tool syntax, not prose.
|
||||
DIRECTIVE = re.compile(
|
||||
r"^(noqa|type:|pragma|fmt:|isort:|nosec|pylint:|mypy:|ruff:|eslint|prettier-ignore|"
|
||||
r"@ts-|istanbul|c8 |v8 |trunk-ignore|!)"
|
||||
)
|
||||
LOCALE_GLOB = "frontend/src/locales/en_US/"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Prose:
|
||||
path: str
|
||||
line: int
|
||||
end_line: int
|
||||
kind: str
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Rule:
|
||||
code: str
|
||||
pattern: re.Pattern[str]
|
||||
message: str
|
||||
|
||||
|
||||
RULES = (
|
||||
Rule(
|
||||
"else-chain",
|
||||
re.compile(r",\s+else\s+(the|its|a|an|it|to|on|for|from)\b"),
|
||||
"Clipped 'X, else Y'. Write 'or else', 'otherwise', or a second sentence.",
|
||||
),
|
||||
Rule(
|
||||
"clipped-conditional",
|
||||
re.compile(
|
||||
r"(?:^|[.;:]\s+)(Unset|Left out|Omitted|Absent|Missing|Empty|Null|"
|
||||
r"Off|Set|Given|Passed),\s+(the|it|its|a|an|every|each|no|this|that|"
|
||||
r"they|we|you)\b"
|
||||
),
|
||||
"Clipped conditional. Write 'If left out, ...' or 'When it is empty, ...'.",
|
||||
),
|
||||
Rule(
|
||||
"internal-id",
|
||||
re.compile(r"\binternal id\b", re.IGNORECASE),
|
||||
"Write 'The ID of the <thing>.' instead of '<Thing> internal id.'",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _python_units(path: str, source: str) -> Iterator[Prose]:
|
||||
try:
|
||||
tree = ast.parse(source)
|
||||
except SyntaxError:
|
||||
return
|
||||
raised = {id(n.exc) for n in ast.walk(tree) if isinstance(n, ast.Raise)}
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):
|
||||
if isinstance(node.value.value, str):
|
||||
yield Prose(
|
||||
path,
|
||||
node.lineno,
|
||||
node.end_lineno or node.lineno,
|
||||
"docstring",
|
||||
node.value.value,
|
||||
)
|
||||
elif isinstance(node, ast.Call):
|
||||
yield from _message_unit(path, node, raised)
|
||||
for kw in node.keywords:
|
||||
if kw.arg not in TEXT_KEYWORDS:
|
||||
continue
|
||||
text = _literal_text(kw.value)
|
||||
if text:
|
||||
yield Prose(
|
||||
path,
|
||||
kw.value.lineno,
|
||||
kw.value.end_lineno or kw.value.lineno,
|
||||
kw.arg,
|
||||
text,
|
||||
)
|
||||
yield from _merge_comments(path, _python_comments(source))
|
||||
|
||||
|
||||
def _message_unit(path: str, call: ast.Call, raised: set[int]) -> Iterator[Prose]:
|
||||
"""Yield the positional message of a raised exception or a logger call."""
|
||||
if id(call) in raised:
|
||||
kind = "error"
|
||||
elif isinstance(call.func, ast.Attribute) and call.func.attr in LOG_METHODS:
|
||||
kind = "log"
|
||||
else:
|
||||
return
|
||||
text = _literal_text(call.args[0]) if call.args else ""
|
||||
if text:
|
||||
arg = call.args[0]
|
||||
yield Prose(path, arg.lineno, arg.end_lineno or arg.lineno, kind, text)
|
||||
|
||||
|
||||
def _literal_text(node: ast.expr) -> str:
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||
return node.value
|
||||
if isinstance(node, ast.JoinedStr):
|
||||
return "".join(
|
||||
(
|
||||
v.value
|
||||
if isinstance(v, ast.Constant) and isinstance(v.value, str)
|
||||
else "{}"
|
||||
)
|
||||
for v in node.values
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
def _python_comments(source: str) -> Iterator[tuple[int, int, str]]:
|
||||
try:
|
||||
for tok in tokenize.generate_tokens(io.StringIO(source).readline):
|
||||
if tok.type == tokenize.COMMENT:
|
||||
yield tok.start[0], tok.start[1], tok.string.lstrip("#").strip()
|
||||
except (tokenize.TokenError, SyntaxError):
|
||||
return
|
||||
|
||||
|
||||
LINE_COMMENT = re.compile(r"(?:^|\s)//\s?(.*)$")
|
||||
BLOCK_COMMENT = re.compile(r"/\*\*?([\s\S]*?)\*/|<!--([\s\S]*?)-->")
|
||||
|
||||
|
||||
def _script_units(path: str, source: str) -> Iterator[Prose]:
|
||||
lines = source.splitlines()
|
||||
line_comments = []
|
||||
for number, line in enumerate(lines, 1):
|
||||
match = LINE_COMMENT.search(line)
|
||||
if match:
|
||||
line_comments.append((number, match.start(), match.group(1).strip()))
|
||||
yield from _merge_comments(path, iter(line_comments))
|
||||
for match in BLOCK_COMMENT.finditer(source):
|
||||
body = match.group(1) if match.group(1) is not None else match.group(2)
|
||||
text = "\n".join(part.strip().lstrip("*").strip() for part in body.splitlines())
|
||||
if text.strip() and not DIRECTIVE.match(text.strip()):
|
||||
start = source.count("\n", 0, match.start()) + 1
|
||||
end = source.count("\n", 0, match.end()) + 1
|
||||
yield Prose(path, start, end, "comment", text)
|
||||
|
||||
|
||||
def _merge_comments(
|
||||
path: str, comments: Iterator[tuple[int, int, str]]
|
||||
) -> Iterator[Prose]:
|
||||
"""Join consecutive line comments at one indent into a single unit."""
|
||||
block: list[tuple[int, int, str]] = []
|
||||
for comment in comments:
|
||||
if DIRECTIVE.match(comment[2]):
|
||||
continue
|
||||
if block and (comment[0] != block[-1][0] + 1 or comment[1] != block[0][1]):
|
||||
yield _comment_block(path, block)
|
||||
block = []
|
||||
block.append(comment)
|
||||
if block:
|
||||
yield _comment_block(path, block)
|
||||
|
||||
|
||||
def _comment_block(path: str, block: list[tuple[int, int, str]]) -> Prose:
|
||||
# Newlines keep each comment line's offset, so a match maps to its line.
|
||||
text = "\n".join(c[2] for c in block)
|
||||
return Prose(path, block[0][0], block[-1][0], "comment", text)
|
||||
|
||||
|
||||
def _locale_units(path: str, source: str) -> Iterator[Prose]:
|
||||
try:
|
||||
data = json.loads(source)
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
lines = _string_lines(source)
|
||||
for key, value in _flatten(data):
|
||||
number = lines.get(key, 1)
|
||||
yield Prose(path, number, number, f"locale:{key}", value)
|
||||
|
||||
|
||||
JSON_TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|[{}\[\],]')
|
||||
JSON_COLON = re.compile(r"\s*:")
|
||||
|
||||
|
||||
def _string_lines(source: str) -> dict[str, int]:
|
||||
"""Map each dotted key with a string value to the line that holds the value."""
|
||||
found: dict[str, int] = {}
|
||||
stack: list[str | None] = []
|
||||
key: str | None = None
|
||||
line, last = 1, 0
|
||||
for match in JSON_TOKEN.finditer(source):
|
||||
line += source.count("\n", last, match.start())
|
||||
last = match.start()
|
||||
piece = match.group()
|
||||
if piece in ("{", "["):
|
||||
stack.append(key)
|
||||
key = None
|
||||
elif piece in ("}", "]"):
|
||||
if stack:
|
||||
stack.pop()
|
||||
key = None
|
||||
elif piece == ",":
|
||||
key = None
|
||||
elif JSON_COLON.match(source, match.end()):
|
||||
key = json.loads(piece)
|
||||
elif key is not None:
|
||||
found[".".join([k for k in stack if k is not None] + [key])] = line
|
||||
return found
|
||||
|
||||
|
||||
def _flatten(data: object, prefix: str = "") -> Iterator[tuple[str, str]]:
|
||||
if isinstance(data, dict):
|
||||
for key, value in data.items():
|
||||
yield from _flatten(value, f"{prefix}{key}.")
|
||||
elif isinstance(data, str):
|
||||
yield prefix.rstrip("."), data
|
||||
|
||||
|
||||
def units(path: Path) -> Iterator[Prose]:
|
||||
source = path.read_text(encoding="utf-8", errors="ignore")
|
||||
name = path.as_posix()
|
||||
if path.suffix == ".py":
|
||||
yield from _python_units(name, source)
|
||||
elif path.suffix in {".ts", ".vue", ".js", ".mts"}:
|
||||
yield from _script_units(name, source)
|
||||
elif path.suffix == ".json" and LOCALE_GLOB in name:
|
||||
yield from _locale_units(name, source)
|
||||
|
||||
|
||||
def added_lines(base: str) -> dict[str, set[int]]:
|
||||
"""Map each file to the line numbers that `git diff <base>` adds to it."""
|
||||
diff = subprocess.run( # nosec B603 B607 - git from PATH, no shell
|
||||
["git", "diff", "-U0", "--no-color", base],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout
|
||||
added: dict[str, set[int]] = {}
|
||||
current = ""
|
||||
for line in diff.splitlines():
|
||||
if line.startswith("+++ "):
|
||||
current = line[6:] if line.startswith("+++ b/") else ""
|
||||
elif line.startswith("@@") and current:
|
||||
match = re.search(r"\+(\d+)(?:,(\d+))?", line)
|
||||
if match:
|
||||
start, count = int(match.group(1)), int(match.group(2) or 1)
|
||||
added.setdefault(current, set()).update(range(start, start + count))
|
||||
return added
|
||||
|
||||
|
||||
def violations(unit: Prose) -> Iterator[tuple[Rule, int]]:
|
||||
for rule in RULES:
|
||||
for match in rule.pattern.finditer(unit.text):
|
||||
# Group 1 is the flagged word; the match may start on the line before.
|
||||
start = match.start(1) if match.groups() else match.start()
|
||||
offset = unit.text.count("\n", 0, start)
|
||||
yield rule, unit.line + offset
|
||||
|
||||
|
||||
def _files(paths: Iterable[str]) -> Iterator[Path]:
|
||||
for name in paths:
|
||||
path = Path(name)
|
||||
if path.is_dir():
|
||||
yield from sorted(
|
||||
p for p in path.rglob("*") if p.suffix in SUFFIXES and p.is_file()
|
||||
)
|
||||
elif path.is_file():
|
||||
yield path
|
||||
|
||||
|
||||
def _select(paths: Iterable[str], base: str | None) -> Iterator[Prose]:
|
||||
touched = added_lines(base) if base else None
|
||||
candidates = list(touched) if touched is not None and not paths else list(paths)
|
||||
for path in _files(candidates):
|
||||
name = path.as_posix()
|
||||
for unit in units(path):
|
||||
if touched is None or any(
|
||||
n in touched.get(name, ()) for n in range(unit.line, unit.end_line + 1)
|
||||
):
|
||||
yield unit
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("mode", choices=("extract", "check"))
|
||||
parser.add_argument("paths", nargs="*")
|
||||
parser.add_argument(
|
||||
"--diff",
|
||||
metavar="BASE",
|
||||
help="Only units on lines added since BASE, such as `origin/master...`.",
|
||||
)
|
||||
args = parser.parse_intermixed_args(argv)
|
||||
|
||||
found = False
|
||||
for unit in _select(args.paths, args.diff):
|
||||
if args.mode == "extract":
|
||||
print(json.dumps(asdict(unit), ensure_ascii=False))
|
||||
continue
|
||||
for rule, line in violations(unit):
|
||||
found = True
|
||||
print(f"{unit.path}:{line}:1: [{rule.code}] {rule.message}")
|
||||
return 1 if found else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user