mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 19:16:18 +01:00
Compare commits
No commits in common. "5029d4685b33896c19e7d92195593d0fc25e8ae4" and "197cf67b7f2c7ea479bfa1a9dd5ad2095a577ada" have entirely different histories.
5029d4685b
...
197cf67b7f
@ -1,90 +0,0 @@
|
||||
# Python split recipes for the 250-line cap
|
||||
|
||||
Settled empirically while clearing `python_pkg/wsg_grabber`. Every rule here
|
||||
cost at least one failed gate run or one revert to learn — do not re-derive
|
||||
them. Referenced from `refactor_claude_todo_resume.md`.
|
||||
|
||||
## The re-export form
|
||||
|
||||
When a split moves a **public** name out of a module that callers/tests still
|
||||
reach through the old path, the re-export must be marked with `__all__`:
|
||||
|
||||
```python
|
||||
from python_pkg.pkg._new_module import show_logs, summarise
|
||||
|
||||
__all__ = ["build_parser", "main", ..., "show_logs", "summarise"]
|
||||
```
|
||||
|
||||
The PEP 484 alias form `from x import y as y` **does not work here**: ruff
|
||||
raises `PLC0414` (useless-import-alias), auto-fixes it away, and then removes
|
||||
the now-"unused" import under `F401` — silently breaking `cli.summarise`.
|
||||
Verified on `wsg_grabber/cli.py`; `__all__` passes ruff + mypy + pylint clean.
|
||||
|
||||
Splits that only move **private** helpers (leading `_`, no external caller)
|
||||
need no shim at all — check with grep first, as in `catalog.py`.
|
||||
|
||||
`__all__` only needs the **re-exported** names, not every public name in the
|
||||
module — names defined locally stay reachable either way. Verified against the
|
||||
full gate on `store.py`.
|
||||
|
||||
**`__all__` does not save you from ruff's `TC001`.** It suppresses `F401`, but
|
||||
a re-exported class used only in annotations gets rewritten into the
|
||||
`TYPE_CHECKING` block, which lints perfectly and raises `AttributeError` at
|
||||
import time. This nearly shipped a broken `ui.Callbacks` that `cli.py`
|
||||
constructs. A class that must be reachable at runtime from module X stays
|
||||
_defined_ in module X. **Always finish a re-export split with**
|
||||
|
||||
```bash
|
||||
PYTHONPATH=. python3 -c "from python_pkg.pkg import mod; mod.TheName"
|
||||
```
|
||||
|
||||
Two other things the gate will not catch for you:
|
||||
|
||||
- **Check what the tests patch before choosing a seam.** `test_ui.py` does
|
||||
`patch.object(ui, "tk", fake)`, so every line touching `tkinter` had to stay
|
||||
in `ui.py`; moving widget construction out errored 22 tests. Grep the test
|
||||
file for `patch.object(<module>` first and treat those names as pinned.
|
||||
- **Tests that call private methods pin them too** — `test_player.py` calls
|
||||
`mpv._note_errors(...)`, so that method stayed as a one-line delegate to the
|
||||
moved implementation.
|
||||
|
||||
**Budget the new import block and `__all__` before deciding a two-way split is
|
||||
enough.** Five splits so far landed 2–16 lines over the cap after the first cut
|
||||
and needed a further seam; the header costs 10–20 lines that the arithmetic on
|
||||
function sizes does not show.
|
||||
|
||||
Splitting a **class**: if tests call private methods as bound attributes
|
||||
(`worker._fetch_thread(...)` — grep the tests first), module-level functions
|
||||
will not do; use mixins. The shape that passes every gate with **no
|
||||
suppression** (settled on `downloader.py`, do not re-derive):
|
||||
|
||||
```python
|
||||
# _worker_base.py
|
||||
class WorkerBase(ABC):
|
||||
_deps: WorkerDeps # bare annotations for read-only attributes
|
||||
_downloaded: int = 0 # real default for any attribute the mixin ASSIGNS
|
||||
|
||||
@abstractmethod
|
||||
def _publish(self, event: DownloadEvent) -> None:
|
||||
"""Supplied by the concrete Worker."""
|
||||
```
|
||||
|
||||
Both mixins inherit `WorkerBase`; `Worker(ScanMixin, DownloadMixin)`. Why not
|
||||
the obvious alternatives:
|
||||
|
||||
- Naming a class `*Mixin` does **not** get you pylint's `no-member` exemption
|
||||
here — `ignored-checks-for-mixins` is not configured for it. Don't rely on it.
|
||||
- `raise NotImplementedError` stub bodies are **uncovered lines** under the
|
||||
100% branch gate.
|
||||
- `if TYPE_CHECKING: def _publish(...) -> None: ...` satisfies mypy but leaves
|
||||
pylint reporting `no-member`.
|
||||
- A bare annotation (`_downloaded: int`) is not enough for an attribute the
|
||||
mixin assigns to (`+= 1`); pylint wants a real default.
|
||||
|
||||
Watch the MRO: `Worker(ScanMixin, DownloadMixin)` means ScanMixin wins any
|
||||
name collision.
|
||||
|
||||
Coverage: `meta/pyproject.toml` sets `source = ["python_pkg"]`, so a new
|
||||
sibling module is measured automatically. Confirmed: new modules show up in
|
||||
the report at 100% rather than being silently skipped. Add no new branches
|
||||
(no `if TYPE_CHECKING` guards beyond what moved, no defensive `try/except`).
|
||||
@ -1,17 +0,0 @@
|
||||
{
|
||||
"title": "Split wsg_grabber/tests/test_review.py under the 250-line cap",
|
||||
"objective": "Bring python_pkg/wsg_grabber/tests/test_review.py (297 lines) under the repo-wide 250-line cap by splitting it along the same seams the source was split on, without losing or weakening a single test.",
|
||||
"acceptance_criteria": [
|
||||
"test_review.py, test_review_render.py, test_review_undo.py and conftest.py are each at most 250 lines.",
|
||||
"The wsg_grabber suite still reports exactly 277 passing tests -- the same count as before the split, proving no test was dropped or silently skipped.",
|
||||
"The package keeps 100% branch coverage of the wsg_grabber source modules.",
|
||||
"No test body is modified, weakened, or deleted; the split only moves whole test functions and shares their two fixture builders.",
|
||||
"No suppression is added and no coverage exclusion is introduced."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing what any test asserts.",
|
||||
"Splitting the other wsg_grabber test files -- separate commits.",
|
||||
"Converting the shared builders into pytest fixtures, which would change every call site."
|
||||
],
|
||||
"verifier": "python3 -m pytest python_pkg/wsg_grabber/tests/ -q (expects exactly 277 passed), plus pre-commit run --files on the four touched files, plus bash ~/utils/scripts/check_file_length.sh --all for the cap."
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
{
|
||||
"intent": "Bring python_pkg/wsg_grabber/tests/test_review.py under the 250-line file cap by splitting it along the same seams the source module was split on, keeping the test count identical.",
|
||||
"scope": [
|
||||
"python_pkg/wsg_grabber/tests/test_review.py",
|
||||
"python_pkg/wsg_grabber/tests/test_review_render.py (new)",
|
||||
"python_pkg/wsg_grabber/tests/test_review_undo.py (new)",
|
||||
"python_pkg/wsg_grabber/tests/conftest.py",
|
||||
"Non-goal: no assertion changes, no test removed or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"Moved the rendering tests (emptiness, status_line, filename_line, title_line, render) into test_review_render.py, mirroring the source split into review._render.",
|
||||
"Moved the undo tests into test_review_undo.py, mirroring review._undo.",
|
||||
"Moved the two shared fixture builders _item and _reviewed into the existing conftest.py as item/reviewed, and imported them from the three test modules. Sharing them rather than copying keeps jscpd's 2% duplication gate happy.",
|
||||
"test_review.py 297 -> 112 lines; test_review_render.py 102; test_review_undo.py 79; conftest.py 91."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "python3 -m pytest python_pkg/wsg_grabber/tests/ -q",
|
||||
"result": "pass",
|
||||
"evidence": "277 passed in 15.16s -- exactly the count before the split, so no test was dropped or silently skipped by the move. Two intermediate runs failed first (4 failed, then 1 failed) because the extracted module was missing model imports and Path; those were real NameErrors surfaced by running the suite, fixed, and re-verified."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files python_pkg/wsg_grabber/tests/test_review.py python_pkg/wsg_grabber/tests/test_review_render.py python_pkg/wsg_grabber/tests/test_review_undo.py python_pkg/wsg_grabber/tests/conftest.py",
|
||||
"result": "pass",
|
||||
"evidence": "All quality hooks pass; only the evidence and contract artifact hooks remained, which this file and the paired contract satisfy."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"The shared builders went into conftest.py rather than a _helpers.py because the name-tests-test hook requires every other file under tests/ to match test_*.py. A _helpers.py was written first and rejected by that hook; python_pkg/syncyomi_guard/tests/conftest.py is the existing precedent for plain shared builders living in conftest.",
|
||||
"conftest.py now mixes autouse path isolation with fixture builders. The module docstring says so explicitly."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; test_review.py returns to its 297-line form, the two new modules are deleted and conftest.py loses the builders.",
|
||||
"After rollback, run python3 -m pytest python_pkg/wsg_grabber/tests/ -q and confirm it still reports 277 passed."
|
||||
]
|
||||
}
|
||||
@ -1,40 +0,0 @@
|
||||
{
|
||||
"intent": "Bring python_pkg/wsg_grabber/ui.py under the 250-line file cap by moving the screen-updating and state-transition halves of ReviewWindow into a mixin, while leaving every line that touches tkinter in ui.py.",
|
||||
"scope": [
|
||||
"python_pkg/wsg_grabber/ui.py",
|
||||
"python_pkg/wsg_grabber/_display.py (new)",
|
||||
"Non-goal: no behaviour change, no test changes, no change to the ReviewCommand contract"
|
||||
],
|
||||
"changes": [
|
||||
"Added DisplayMixin in _display.py holding apply, _play, _verdict, on_undo, on_quit, drain, refresh, tick and attach_player -- the methods that reach widgets only through self._widgets and never touch the tkinter module itself.",
|
||||
"ui.py keeps Callbacks, Widgets, _build, _bind_keys, video_wid, on_keep, on_pass, shutdown and run, and is now `class ReviewWindow(DisplayMixin)`.",
|
||||
"Deleted the four _key_* adapters (_key_keep/_key_pass/_key_undo/_key_quit); each only discarded Tk's event argument and forwarded, so _bind_keys now binds lambdas directly. No test referenced them.",
|
||||
"ui.py 398 -> 242 lines; _display.py 179."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "python3 -m pytest python_pkg/wsg_grabber/tests/ -q --cov=python_pkg.wsg_grabber --cov-report=term-missing",
|
||||
"result": "pass",
|
||||
"evidence": "277 passed in 15.15s. ui.py 93 stmts / 12 branches 100%; _display.py 76 stmts / 18 branches 100%."
|
||||
},
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -c \"from python_pkg.wsg_grabber import ui; ui.Callbacks; ui.Widgets\"",
|
||||
"result": "pass",
|
||||
"evidence": "Both resolve at runtime. This check exists because an intermediate version moved Callbacks to its own module and ruff's TC001 rewrote the re-export into a TYPE_CHECKING-only import, which passes every linter but makes ui.Callbacks raise AttributeError at runtime -- and cli.py constructs it."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files python_pkg/wsg_grabber/ui.py python_pkg/wsg_grabber/_display.py",
|
||||
"result": "pass",
|
||||
"evidence": "Only the expected 'no staged evidence artifact' failure remained, which this file satisfies. ruff, ruff format, mypy, pylint, bandit and the coverage-gated pytest all pass with no suppression."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Widget construction deliberately stays in ui.py. test_ui.py fakes the toolkit with patch.object(ui, 'tk', fake), so moving _build to another module makes 22 tests error with \"module ui does not have the attribute 'tk'\". An earlier attempt did exactly that and was reverted rather than adapting the tests, which are out of scope.",
|
||||
"Unlike F401, ruff's TC001 is NOT suppressed by listing a name in __all__. A cross-module re-export of a type-annotation-only name cannot be kept at runtime that way; define such classes in the module that must expose them.",
|
||||
"ReviewWindow now inherits from an ABC whose abstract methods (shutdown) are satisfied by ui.py. Removing shutdown from ui.py would fail at instantiation rather than at lint time."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; ui.py returns to its 398-line form and _display.py is deleted.",
|
||||
"After rollback, run python3 -m pytest python_pkg/wsg_grabber/tests/ -q to confirm 277 tests still pass."
|
||||
]
|
||||
}
|
||||
@ -1,179 +0,0 @@
|
||||
"""Applying a rendered command to the screen.
|
||||
|
||||
Split out of :mod:`python_pkg.wsg_grabber.ui` to keep it under the 250-line
|
||||
cap. Note what is *not* here: creating widgets. ``ui`` is the only module that
|
||||
imports ``tkinter``, and ``test_ui.py`` fakes the toolkit with
|
||||
``patch.object(ui, "tk", ...)``, so construction has to stay there. These two
|
||||
methods only ever reach widgets through ``self._widgets``, so they move freely.
|
||||
|
||||
A mixin rather than free functions because both read and write the window's
|
||||
playback bookkeeping and ``apply`` is part of ReviewWindow's public surface.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.wsg_grabber import logs, review
|
||||
from python_pkg.wsg_grabber.constants import POLL_INTERVAL_MS
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
import queue
|
||||
|
||||
from python_pkg.wsg_grabber._callbacks import Callbacks
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
DownloadEvent,
|
||||
ReviewCommand,
|
||||
Verdict,
|
||||
)
|
||||
from python_pkg.wsg_grabber.player import Player
|
||||
from python_pkg.wsg_grabber.review import SessionState
|
||||
from python_pkg.wsg_grabber.ui import Widgets
|
||||
|
||||
|
||||
class DisplayMixin(ABC):
|
||||
"""The screen-updating half of :class:`~.ui.ReviewWindow`."""
|
||||
|
||||
_widgets: Widgets
|
||||
_callbacks: Callbacks
|
||||
_player: Player | None
|
||||
_playing: Path | None
|
||||
_state: SessionState
|
||||
_after_id: str | None
|
||||
_events: queue.SimpleQueue[DownloadEvent]
|
||||
|
||||
@abstractmethod
|
||||
def shutdown(self) -> None:
|
||||
"""Close the player and tear the window down."""
|
||||
|
||||
def apply(self, command: ReviewCommand) -> None:
|
||||
"""Carry out a rendered command.
|
||||
|
||||
Args:
|
||||
command: What to show and do.
|
||||
"""
|
||||
if command.play is not None:
|
||||
self._play(command.play)
|
||||
if command.stop and self._player is not None and self._playing is not None:
|
||||
self._playing = None
|
||||
self._player.stop()
|
||||
self._widgets.status.configure(text=command.status)
|
||||
self._widgets.filename.configure(text=command.filename)
|
||||
self._widgets.root.title(command.title)
|
||||
if command.verdicts_enabled:
|
||||
self._widgets.keep.configure(state="normal")
|
||||
self._widgets.skip.configure(state="normal")
|
||||
else:
|
||||
self._widgets.keep.configure(state="disabled")
|
||||
self._widgets.skip.configure(state="disabled")
|
||||
if command.undo_enabled:
|
||||
self._widgets.undo.configure(state="normal")
|
||||
else:
|
||||
self._widgets.undo.configure(state="disabled")
|
||||
if command.quit_app:
|
||||
self.shutdown()
|
||||
|
||||
def _play(self, path: Path) -> None:
|
||||
"""Show a video, unless it is already the one playing.
|
||||
|
||||
The already-playing guard is essential rather than an optimisation:
|
||||
``refresh`` runs on every tick, so without it ``loadfile`` would be sent
|
||||
several times a second and the video would restart continuously instead
|
||||
of ever playing.
|
||||
|
||||
A file can also vanish between being downloaded and being reviewed.
|
||||
Handing mpv a dead path would leave the reviewer stuck on a black
|
||||
frame, so the item is dropped and the next one shown instead.
|
||||
|
||||
Args:
|
||||
path: Video to play.
|
||||
"""
|
||||
if self._player is None:
|
||||
logs.debug("review.play_skipped", reason="no player", file=path.name)
|
||||
return
|
||||
if path == self._playing:
|
||||
logs.debug("review.play_skipped", reason="already playing", file=path.name)
|
||||
return
|
||||
if not path.exists():
|
||||
logs.warning("review.file_missing", file=path.name, path=str(path))
|
||||
self._state = self._callbacks.missing(self._state)
|
||||
self.refresh()
|
||||
return
|
||||
# Recorded BEFORE the new load, so a frozen-looking session shows what
|
||||
# mpv was doing with the file it was supposedly already playing.
|
||||
logs.event(
|
||||
"review.show",
|
||||
file=path.name,
|
||||
previous=self._playing.name if self._playing else None,
|
||||
player_alive=self._player.is_alive(),
|
||||
mpv_before=self._player.probe(),
|
||||
)
|
||||
self._playing = path
|
||||
self._player.play(path)
|
||||
|
||||
def _verdict(self, choice: Verdict) -> None:
|
||||
"""Apply a verdict and redraw.
|
||||
|
||||
Args:
|
||||
choice: What the user decided.
|
||||
"""
|
||||
before = self._state.current
|
||||
self._state = self._callbacks.commit(self._state, choice)
|
||||
after = self._state.current
|
||||
logs.event(
|
||||
"review.verdict",
|
||||
choice=choice.value,
|
||||
on=before.orig_name if before else None,
|
||||
on_file=before.path.name if before else None,
|
||||
next_file=after.path.name if after else None,
|
||||
queued=len(self._state.pending),
|
||||
kept=self._state.kept,
|
||||
passed=self._state.passed,
|
||||
)
|
||||
self.refresh()
|
||||
|
||||
def on_undo(self) -> None:
|
||||
"""Take back the last verdict and show that video again."""
|
||||
before = self._state.current
|
||||
self._state = self._callbacks.undo(self._state)
|
||||
after = self._state.current
|
||||
logs.event(
|
||||
"review.undo",
|
||||
was_showing=before.orig_name if before else None,
|
||||
now_showing=after.orig_name if after else None,
|
||||
kept=self._state.kept,
|
||||
passed=self._state.passed,
|
||||
remaining_undos=self._state.undoable,
|
||||
)
|
||||
self.refresh()
|
||||
|
||||
def on_quit(self) -> None:
|
||||
"""Begin shutting down."""
|
||||
self._state = review.on_quit(self._state)
|
||||
self.refresh()
|
||||
|
||||
def tick(self) -> None:
|
||||
"""Drain the worker's events, redraw, and schedule the next tick."""
|
||||
self.drain()
|
||||
self.refresh()
|
||||
self._after_id = self._widgets.root.after(POLL_INTERVAL_MS, self.tick)
|
||||
|
||||
def drain(self) -> None:
|
||||
"""Fold every queued worker event into the session state."""
|
||||
while not self._events.empty():
|
||||
self._state = review.on_event(self._state, self._events.get_nowait())
|
||||
|
||||
def refresh(self) -> None:
|
||||
"""Re-render from the current state."""
|
||||
self.apply(review.render(self._state))
|
||||
|
||||
def attach_player(self, player: Player) -> None:
|
||||
"""Adopt a player and show the first video.
|
||||
|
||||
Args:
|
||||
player: The video player to drive.
|
||||
"""
|
||||
self._player = player
|
||||
self.refresh()
|
||||
@ -13,10 +13,6 @@ would corrupt live user data, so redirection is autouse and belt-and-braces:
|
||||
|
||||
``tests/test_paths.py`` adds a static check that no module captures a home
|
||||
directory at import time, so layer 3 stays true as the package grows.
|
||||
|
||||
Also holds the fixture builders the reviewer test modules share. They live
|
||||
here rather than in a ``_helpers.py`` because the ``name-tests-test`` hook
|
||||
requires every other file under ``tests/`` to be named ``test_*.py``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -25,8 +21,6 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.wsg_grabber.models import ReviewedItem, ReviewItem, Verdict
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolate_paths(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
@ -51,35 +45,3 @@ def isolate_paths(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda _cls: home))
|
||||
|
||||
return home
|
||||
|
||||
|
||||
def item(name: str = "a") -> ReviewItem:
|
||||
"""Build a ReviewItem.
|
||||
|
||||
Args:
|
||||
name: Distinguishes items within a test.
|
||||
|
||||
Returns:
|
||||
ReviewItem: Fixture value.
|
||||
"""
|
||||
return ReviewItem(
|
||||
md5=f"{name}-md5",
|
||||
path=Path(f"/incoming/{name}.webm"),
|
||||
orig_name=f"{name}.webm",
|
||||
fsize=2 * 1024 * 1024,
|
||||
width=480,
|
||||
height=360,
|
||||
)
|
||||
|
||||
|
||||
def reviewed(item: ReviewItem, choice: Verdict = Verdict.SKIP) -> ReviewedItem:
|
||||
"""Build the record a verdict would have persisted.
|
||||
|
||||
Args:
|
||||
item: The reviewed video.
|
||||
choice: What was decided.
|
||||
|
||||
Returns:
|
||||
ReviewedItem: Reversible verdict.
|
||||
"""
|
||||
return ReviewedItem(item=item, choice=choice, reviewed_name=item.path.name)
|
||||
|
||||
@ -6,17 +6,39 @@ specified by these tests and none of them need a display.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from python_pkg.wsg_grabber import review
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
Downloaded,
|
||||
Emptiness,
|
||||
FileReady,
|
||||
Indexed,
|
||||
ReviewedItem,
|
||||
ReviewItem,
|
||||
ScanFinished,
|
||||
Verdict,
|
||||
WorkerFailed,
|
||||
)
|
||||
from python_pkg.wsg_grabber.tests.conftest import item as _item
|
||||
|
||||
|
||||
def _item(name: str = "a") -> ReviewItem:
|
||||
"""Build a ReviewItem.
|
||||
|
||||
Args:
|
||||
name: Distinguishes items within a test.
|
||||
|
||||
Returns:
|
||||
ReviewItem: Fixture value.
|
||||
"""
|
||||
return ReviewItem(
|
||||
md5=f"{name}-md5",
|
||||
path=Path(f"/incoming/{name}.webm"),
|
||||
orig_name=f"{name}.webm",
|
||||
fsize=2 * 1024 * 1024,
|
||||
width=480,
|
||||
height=360,
|
||||
)
|
||||
|
||||
|
||||
def test_the_first_download_goes_straight_on_screen() -> None:
|
||||
@ -110,3 +132,166 @@ def test_events_fold_into_the_state() -> None:
|
||||
|
||||
state = review.on_event(state, WorkerFailed(message="no route to host"))
|
||||
assert state.error == "no route to host"
|
||||
|
||||
|
||||
def test_emptiness_distinguishes_waiting_from_exhausted() -> None:
|
||||
state = review.initial_state(0, [])
|
||||
assert review.emptiness(state) is Emptiness.WAITING
|
||||
|
||||
state = review.on_event(state, ScanFinished())
|
||||
assert review.emptiness(state) is Emptiness.EXHAUSTED
|
||||
|
||||
state = review.on_new_files(state, [_item("a")])
|
||||
assert review.emptiness(state) is Emptiness.NOT_EMPTY
|
||||
|
||||
|
||||
def test_status_line_reports_progress() -> None:
|
||||
state = review.initial_state(9028, [_item("a")])
|
||||
state = review.on_event(state, Downloaded(count=12))
|
||||
state = review.on_verdict(state, Verdict.KEEP)
|
||||
line = review.status_line(state)
|
||||
assert "kept 1" in line
|
||||
assert "passed 0" in line
|
||||
assert "downloaded 12/9028" in line
|
||||
|
||||
|
||||
def test_status_line_omits_the_total_before_indexing() -> None:
|
||||
state = review.initial_state(0, [_item("a")])
|
||||
assert "/0" not in review.status_line(state)
|
||||
|
||||
|
||||
def test_status_line_shows_the_two_empty_moods() -> None:
|
||||
state = review.initial_state(0, [])
|
||||
assert "waiting for downloads" in review.status_line(state)
|
||||
assert "all caught up" in review.status_line(
|
||||
review.on_event(state, ScanFinished()),
|
||||
)
|
||||
|
||||
|
||||
def test_a_worker_failure_takes_over_the_status_line() -> None:
|
||||
state = review.on_event(review.initial_state(0, []), WorkerFailed(message="boom"))
|
||||
assert review.status_line(state) == "downloader stopped: boom"
|
||||
|
||||
|
||||
def test_filename_line_describes_the_current_video() -> None:
|
||||
state = review.initial_state(1, [_item("a")])
|
||||
line = review.filename_line(state)
|
||||
assert "a.webm" in line
|
||||
assert "480x360" in line
|
||||
assert "2.0 MiB" in line
|
||||
|
||||
|
||||
def test_filename_line_has_a_placeholder_when_idle() -> None:
|
||||
assert review.filename_line(review.initial_state(0, [])) == "—"
|
||||
|
||||
|
||||
def test_title_line_carries_the_tally() -> None:
|
||||
state = review.initial_state(1, [_item("a")])
|
||||
state = review.on_verdict(state, Verdict.KEEP)
|
||||
assert review.title_line(state) == "/wsg/ — kept 1, passed 0"
|
||||
|
||||
|
||||
def test_render_drives_the_window_completely() -> None:
|
||||
state = review.initial_state(5, [_item("a")])
|
||||
command = review.render(state)
|
||||
assert command.play == Path("/incoming/a.webm")
|
||||
assert not command.stop
|
||||
assert command.verdicts_enabled
|
||||
assert not command.quit_app
|
||||
assert command.status == review.status_line(state)
|
||||
assert command.title == review.title_line(state)
|
||||
assert command.filename == review.filename_line(state)
|
||||
|
||||
|
||||
def test_render_stops_playback_when_nothing_is_queued() -> None:
|
||||
command = review.render(review.initial_state(0, []))
|
||||
assert command.play is None
|
||||
assert command.stop
|
||||
assert not command.verdicts_enabled
|
||||
|
||||
|
||||
def test_render_signals_quit_and_disables_the_buttons() -> None:
|
||||
state = review.on_quit(review.initial_state(1, [_item("a")]))
|
||||
command = review.render(state)
|
||||
assert command.quit_app
|
||||
assert not command.verdicts_enabled
|
||||
|
||||
|
||||
def _reviewed(item: ReviewItem, choice: Verdict = Verdict.SKIP) -> ReviewedItem:
|
||||
"""Build the record a verdict would have persisted.
|
||||
|
||||
Args:
|
||||
item: The reviewed video.
|
||||
choice: What was decided.
|
||||
|
||||
Returns:
|
||||
ReviewedItem: Reversible verdict.
|
||||
"""
|
||||
return ReviewedItem(item=item, choice=choice, reviewed_name=item.path.name)
|
||||
|
||||
|
||||
def test_undo_availability_comes_from_the_index_not_memory() -> None:
|
||||
"""The count is seeded from the index, so undo survives a restart."""
|
||||
resumed = review.initial_state(5, [_item("a")], undoable=3)
|
||||
assert review.can_undo(resumed)
|
||||
assert "u undoes (3)" in review.status_line(resumed)
|
||||
assert not review.can_undo(review.initial_state(5, [_item("a")]))
|
||||
|
||||
|
||||
def test_a_recorded_verdict_can_be_undone() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(2, [first, _item("b")])
|
||||
state = review.on_verdict(state, Verdict.SKIP)
|
||||
assert review.can_undo(state)
|
||||
|
||||
state = review.on_undo(state, _reviewed(first))
|
||||
assert state.current is not None
|
||||
assert state.current.md5 == "a-md5"
|
||||
assert state.passed == 0
|
||||
assert [item.md5 for item in state.pending] == ["b-md5"]
|
||||
assert not review.can_undo(state)
|
||||
|
||||
|
||||
def test_undo_restores_the_keep_counter() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(1, [first])
|
||||
state = review.on_verdict(state, Verdict.KEEP)
|
||||
assert state.kept == 1
|
||||
assert review.on_undo(state, _reviewed(first, Verdict.KEEP)).kept == 0
|
||||
|
||||
|
||||
def test_undo_works_when_the_queue_has_run_dry() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(1, [first])
|
||||
state = review.on_verdict(state, Verdict.SKIP)
|
||||
assert state.current is None
|
||||
state = review.on_undo(state, _reviewed(first))
|
||||
assert state.current is not None
|
||||
assert state.current.md5 == "a-md5"
|
||||
|
||||
|
||||
def test_forget_last_drops_one_undo_without_restoring() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(1, [first])
|
||||
state = review.on_verdict(state, Verdict.SKIP)
|
||||
dropped = review.forget_last(state)
|
||||
assert not review.can_undo(dropped)
|
||||
assert dropped.passed == 1
|
||||
assert review.forget_last(dropped).undoable == 0
|
||||
|
||||
|
||||
def test_the_status_line_advertises_undo_once_it_is_possible() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(1, [first])
|
||||
assert "u undoes" not in review.status_line(state)
|
||||
state = review.on_verdict(state, Verdict.SKIP)
|
||||
assert "u undoes (1)" in review.status_line(state)
|
||||
|
||||
|
||||
def test_render_enables_undo_only_when_something_can_be_undone() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(1, [first])
|
||||
assert not review.render(state).undo_enabled
|
||||
state = review.on_verdict(state, Verdict.KEEP)
|
||||
assert review.render(state).undo_enabled
|
||||
assert not review.render(review.on_quit(state)).undo_enabled
|
||||
|
||||
@ -1,102 +0,0 @@
|
||||
"""Tests for what the reviewer puts on screen.
|
||||
|
||||
Split from ``test_review.py`` to keep every file under the 250-line cap; these
|
||||
cover the pure state-to-text functions that now live in ``review._render``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from python_pkg.wsg_grabber import review
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
Downloaded,
|
||||
Emptiness,
|
||||
ScanFinished,
|
||||
Verdict,
|
||||
WorkerFailed,
|
||||
)
|
||||
from python_pkg.wsg_grabber.tests.conftest import item as _item
|
||||
|
||||
|
||||
def test_emptiness_distinguishes_waiting_from_exhausted() -> None:
|
||||
state = review.initial_state(0, [])
|
||||
assert review.emptiness(state) is Emptiness.WAITING
|
||||
|
||||
state = review.on_event(state, ScanFinished())
|
||||
assert review.emptiness(state) is Emptiness.EXHAUSTED
|
||||
|
||||
state = review.on_new_files(state, [_item("a")])
|
||||
assert review.emptiness(state) is Emptiness.NOT_EMPTY
|
||||
|
||||
|
||||
def test_status_line_reports_progress() -> None:
|
||||
state = review.initial_state(9028, [_item("a")])
|
||||
state = review.on_event(state, Downloaded(count=12))
|
||||
state = review.on_verdict(state, Verdict.KEEP)
|
||||
line = review.status_line(state)
|
||||
assert "kept 1" in line
|
||||
assert "passed 0" in line
|
||||
assert "downloaded 12/9028" in line
|
||||
|
||||
|
||||
def test_status_line_omits_the_total_before_indexing() -> None:
|
||||
state = review.initial_state(0, [_item("a")])
|
||||
assert "/0" not in review.status_line(state)
|
||||
|
||||
|
||||
def test_status_line_shows_the_two_empty_moods() -> None:
|
||||
state = review.initial_state(0, [])
|
||||
assert "waiting for downloads" in review.status_line(state)
|
||||
assert "all caught up" in review.status_line(
|
||||
review.on_event(state, ScanFinished()),
|
||||
)
|
||||
|
||||
|
||||
def test_a_worker_failure_takes_over_the_status_line() -> None:
|
||||
state = review.on_event(review.initial_state(0, []), WorkerFailed(message="boom"))
|
||||
assert review.status_line(state) == "downloader stopped: boom"
|
||||
|
||||
|
||||
def test_filename_line_describes_the_current_video() -> None:
|
||||
state = review.initial_state(1, [_item("a")])
|
||||
line = review.filename_line(state)
|
||||
assert "a.webm" in line
|
||||
assert "480x360" in line
|
||||
assert "2.0 MiB" in line
|
||||
|
||||
|
||||
def test_filename_line_has_a_placeholder_when_idle() -> None:
|
||||
assert review.filename_line(review.initial_state(0, [])) == "—"
|
||||
|
||||
|
||||
def test_title_line_carries_the_tally() -> None:
|
||||
state = review.initial_state(1, [_item("a")])
|
||||
state = review.on_verdict(state, Verdict.KEEP)
|
||||
assert review.title_line(state) == "/wsg/ — kept 1, passed 0"
|
||||
|
||||
|
||||
def test_render_drives_the_window_completely() -> None:
|
||||
state = review.initial_state(5, [_item("a")])
|
||||
command = review.render(state)
|
||||
assert command.play == Path("/incoming/a.webm")
|
||||
assert not command.stop
|
||||
assert command.verdicts_enabled
|
||||
assert not command.quit_app
|
||||
assert command.status == review.status_line(state)
|
||||
assert command.title == review.title_line(state)
|
||||
assert command.filename == review.filename_line(state)
|
||||
|
||||
|
||||
def test_render_stops_playback_when_nothing_is_queued() -> None:
|
||||
command = review.render(review.initial_state(0, []))
|
||||
assert command.play is None
|
||||
assert command.stop
|
||||
assert not command.verdicts_enabled
|
||||
|
||||
|
||||
def test_render_signals_quit_and_disables_the_buttons() -> None:
|
||||
state = review.on_quit(review.initial_state(1, [_item("a")]))
|
||||
command = review.render(state)
|
||||
assert command.quit_app
|
||||
assert not command.verdicts_enabled
|
||||
@ -1,79 +0,0 @@
|
||||
"""Tests for taking a verdict back.
|
||||
|
||||
Split from ``test_review.py`` to keep every file under the 250-line cap; these
|
||||
cover the group that now lives in ``review._undo``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from python_pkg.wsg_grabber import review
|
||||
from python_pkg.wsg_grabber.models import Verdict
|
||||
from python_pkg.wsg_grabber.tests.conftest import item as _item
|
||||
from python_pkg.wsg_grabber.tests.conftest import reviewed as _reviewed
|
||||
|
||||
|
||||
def test_undo_availability_comes_from_the_index_not_memory() -> None:
|
||||
"""The count is seeded from the index, so undo survives a restart."""
|
||||
resumed = review.initial_state(5, [_item("a")], undoable=3)
|
||||
assert review.can_undo(resumed)
|
||||
assert "u undoes (3)" in review.status_line(resumed)
|
||||
assert not review.can_undo(review.initial_state(5, [_item("a")]))
|
||||
|
||||
|
||||
def test_a_recorded_verdict_can_be_undone() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(2, [first, _item("b")])
|
||||
state = review.on_verdict(state, Verdict.SKIP)
|
||||
assert review.can_undo(state)
|
||||
|
||||
state = review.on_undo(state, _reviewed(first))
|
||||
assert state.current is not None
|
||||
assert state.current.md5 == "a-md5"
|
||||
assert state.passed == 0
|
||||
assert [item.md5 for item in state.pending] == ["b-md5"]
|
||||
assert not review.can_undo(state)
|
||||
|
||||
|
||||
def test_undo_restores_the_keep_counter() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(1, [first])
|
||||
state = review.on_verdict(state, Verdict.KEEP)
|
||||
assert state.kept == 1
|
||||
assert review.on_undo(state, _reviewed(first, Verdict.KEEP)).kept == 0
|
||||
|
||||
|
||||
def test_undo_works_when_the_queue_has_run_dry() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(1, [first])
|
||||
state = review.on_verdict(state, Verdict.SKIP)
|
||||
assert state.current is None
|
||||
state = review.on_undo(state, _reviewed(first))
|
||||
assert state.current is not None
|
||||
assert state.current.md5 == "a-md5"
|
||||
|
||||
|
||||
def test_forget_last_drops_one_undo_without_restoring() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(1, [first])
|
||||
state = review.on_verdict(state, Verdict.SKIP)
|
||||
dropped = review.forget_last(state)
|
||||
assert not review.can_undo(dropped)
|
||||
assert dropped.passed == 1
|
||||
assert review.forget_last(dropped).undoable == 0
|
||||
|
||||
|
||||
def test_the_status_line_advertises_undo_once_it_is_possible() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(1, [first])
|
||||
assert "u undoes" not in review.status_line(state)
|
||||
state = review.on_verdict(state, Verdict.SKIP)
|
||||
assert "u undoes (1)" in review.status_line(state)
|
||||
|
||||
|
||||
def test_render_enables_undo_only_when_something_can_be_undone() -> None:
|
||||
first = _item("a")
|
||||
state = review.initial_state(1, [first])
|
||||
assert not review.render(state).undo_enabled
|
||||
state = review.on_verdict(state, Verdict.KEEP)
|
||||
assert review.render(state).undo_enabled
|
||||
assert not review.render(review.on_quit(state)).undo_enabled
|
||||
@ -24,18 +24,18 @@ from dataclasses import dataclass
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.wsg_grabber import logs
|
||||
from python_pkg.wsg_grabber._display import DisplayMixin
|
||||
from python_pkg.wsg_grabber import logs, review
|
||||
from python_pkg.wsg_grabber.constants import (
|
||||
CONTROL_BAR_HEIGHT_PX,
|
||||
KEEP_KEYS,
|
||||
PASS_KEYS,
|
||||
POLL_INTERVAL_MS,
|
||||
QUIT_KEYS,
|
||||
UNDO_KEYS,
|
||||
WINDOW_HEIGHT_PX,
|
||||
WINDOW_WIDTH_PX,
|
||||
)
|
||||
from python_pkg.wsg_grabber.models import Verdict
|
||||
from python_pkg.wsg_grabber.models import ReviewCommand, Verdict
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
@ -74,14 +74,8 @@ class Widgets:
|
||||
undo: tk.Button
|
||||
|
||||
|
||||
class ReviewWindow(DisplayMixin):
|
||||
"""Presents downloaded videos one at a time for a keep/pass decision.
|
||||
|
||||
The screen-updating and state-transition halves live in _display to keep
|
||||
this module under the 250-line cap. Widget construction stays here: this
|
||||
is the only module that imports tkinter, and the tests fake the toolkit
|
||||
by patching ``ui.tk``.
|
||||
"""
|
||||
class ReviewWindow:
|
||||
"""Presents downloaded videos one at a time for a keep/pass decision."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@ -189,13 +183,13 @@ class ReviewWindow(DisplayMixin):
|
||||
def _bind_keys(self) -> None:
|
||||
"""Bind the keyboard shortcuts onto the toplevel."""
|
||||
for sequence in KEEP_KEYS:
|
||||
self._widgets.root.bind(sequence, lambda _event: self.on_keep())
|
||||
self._widgets.root.bind(sequence, self._key_keep)
|
||||
for sequence in PASS_KEYS:
|
||||
self._widgets.root.bind(sequence, lambda _event: self.on_pass())
|
||||
self._widgets.root.bind(sequence, self._key_pass)
|
||||
for sequence in UNDO_KEYS:
|
||||
self._widgets.root.bind(sequence, lambda _event: self.on_undo())
|
||||
self._widgets.root.bind(sequence, self._key_undo)
|
||||
for sequence in QUIT_KEYS:
|
||||
self._widgets.root.bind(sequence, lambda _event: self.on_quit())
|
||||
self._widgets.root.bind(sequence, self._key_quit)
|
||||
|
||||
def video_wid(self) -> int:
|
||||
"""Return the X11 id of the video frame.
|
||||
@ -206,6 +200,47 @@ class ReviewWindow(DisplayMixin):
|
||||
self._widgets.root.update()
|
||||
return int(self._widgets.video.winfo_id())
|
||||
|
||||
def attach_player(self, player: Player) -> None:
|
||||
"""Adopt a player and show the first video.
|
||||
|
||||
Args:
|
||||
player: The video player to drive.
|
||||
"""
|
||||
self._player = player
|
||||
self.refresh()
|
||||
|
||||
def _key_keep(self, _event: object) -> None:
|
||||
"""Handle a keep keypress.
|
||||
|
||||
Args:
|
||||
_event: Tk event, unused.
|
||||
"""
|
||||
self.on_keep()
|
||||
|
||||
def _key_pass(self, _event: object) -> None:
|
||||
"""Handle a pass keypress.
|
||||
|
||||
Args:
|
||||
_event: Tk event, unused.
|
||||
"""
|
||||
self.on_pass()
|
||||
|
||||
def _key_undo(self, _event: object) -> None:
|
||||
"""Handle an undo keypress.
|
||||
|
||||
Args:
|
||||
_event: Tk event, unused.
|
||||
"""
|
||||
self.on_undo()
|
||||
|
||||
def _key_quit(self, _event: object) -> None:
|
||||
"""Handle a quit keypress.
|
||||
|
||||
Args:
|
||||
_event: Tk event, unused.
|
||||
"""
|
||||
self.on_quit()
|
||||
|
||||
def on_keep(self) -> None:
|
||||
"""Keep the current video."""
|
||||
self._verdict(Verdict.KEEP)
|
||||
@ -214,6 +249,127 @@ class ReviewWindow(DisplayMixin):
|
||||
"""Pass on the current video."""
|
||||
self._verdict(Verdict.SKIP)
|
||||
|
||||
def _verdict(self, choice: Verdict) -> None:
|
||||
"""Apply a verdict and redraw.
|
||||
|
||||
Args:
|
||||
choice: What the user decided.
|
||||
"""
|
||||
before = self._state.current
|
||||
self._state = self._callbacks.commit(self._state, choice)
|
||||
after = self._state.current
|
||||
logs.event(
|
||||
"review.verdict",
|
||||
choice=choice.value,
|
||||
on=before.orig_name if before else None,
|
||||
on_file=before.path.name if before else None,
|
||||
next_file=after.path.name if after else None,
|
||||
queued=len(self._state.pending),
|
||||
kept=self._state.kept,
|
||||
passed=self._state.passed,
|
||||
)
|
||||
self.refresh()
|
||||
|
||||
def on_undo(self) -> None:
|
||||
"""Take back the last verdict and show that video again."""
|
||||
before = self._state.current
|
||||
self._state = self._callbacks.undo(self._state)
|
||||
after = self._state.current
|
||||
logs.event(
|
||||
"review.undo",
|
||||
was_showing=before.orig_name if before else None,
|
||||
now_showing=after.orig_name if after else None,
|
||||
kept=self._state.kept,
|
||||
passed=self._state.passed,
|
||||
remaining_undos=self._state.undoable,
|
||||
)
|
||||
self.refresh()
|
||||
|
||||
def on_quit(self) -> None:
|
||||
"""Begin shutting down."""
|
||||
self._state = review.on_quit(self._state)
|
||||
self.refresh()
|
||||
|
||||
def tick(self) -> None:
|
||||
"""Drain the worker's events, redraw, and schedule the next tick."""
|
||||
self.drain()
|
||||
self.refresh()
|
||||
self._after_id = self._widgets.root.after(POLL_INTERVAL_MS, self.tick)
|
||||
|
||||
def drain(self) -> None:
|
||||
"""Fold every queued worker event into the session state."""
|
||||
while not self._events.empty():
|
||||
self._state = review.on_event(self._state, self._events.get_nowait())
|
||||
|
||||
def refresh(self) -> None:
|
||||
"""Re-render from the current state."""
|
||||
self.apply(review.render(self._state))
|
||||
|
||||
def apply(self, command: ReviewCommand) -> None:
|
||||
"""Carry out a rendered command.
|
||||
|
||||
Args:
|
||||
command: What to show and do.
|
||||
"""
|
||||
if command.play is not None:
|
||||
self._play(command.play)
|
||||
if command.stop and self._player is not None and self._playing is not None:
|
||||
self._playing = None
|
||||
self._player.stop()
|
||||
self._widgets.status.configure(text=command.status)
|
||||
self._widgets.filename.configure(text=command.filename)
|
||||
self._widgets.root.title(command.title)
|
||||
if command.verdicts_enabled:
|
||||
self._widgets.keep.configure(state="normal")
|
||||
self._widgets.skip.configure(state="normal")
|
||||
else:
|
||||
self._widgets.keep.configure(state="disabled")
|
||||
self._widgets.skip.configure(state="disabled")
|
||||
if command.undo_enabled:
|
||||
self._widgets.undo.configure(state="normal")
|
||||
else:
|
||||
self._widgets.undo.configure(state="disabled")
|
||||
if command.quit_app:
|
||||
self.shutdown()
|
||||
|
||||
def _play(self, path: Path) -> None:
|
||||
"""Show a video, unless it is already the one playing.
|
||||
|
||||
The already-playing guard is essential rather than an optimisation:
|
||||
``refresh`` runs on every tick, so without it ``loadfile`` would be sent
|
||||
several times a second and the video would restart continuously instead
|
||||
of ever playing.
|
||||
|
||||
A file can also vanish between being downloaded and being reviewed.
|
||||
Handing mpv a dead path would leave the reviewer stuck on a black
|
||||
frame, so the item is dropped and the next one shown instead.
|
||||
|
||||
Args:
|
||||
path: Video to play.
|
||||
"""
|
||||
if self._player is None:
|
||||
logs.debug("review.play_skipped", reason="no player", file=path.name)
|
||||
return
|
||||
if path == self._playing:
|
||||
logs.debug("review.play_skipped", reason="already playing", file=path.name)
|
||||
return
|
||||
if not path.exists():
|
||||
logs.warning("review.file_missing", file=path.name, path=str(path))
|
||||
self._state = self._callbacks.missing(self._state)
|
||||
self.refresh()
|
||||
return
|
||||
# Recorded BEFORE the new load, so a frozen-looking session shows what
|
||||
# mpv was doing with the file it was supposedly already playing.
|
||||
logs.event(
|
||||
"review.show",
|
||||
file=path.name,
|
||||
previous=self._playing.name if self._playing else None,
|
||||
player_alive=self._player.is_alive(),
|
||||
mpv_before=self._player.probe(),
|
||||
)
|
||||
self._playing = path
|
||||
self._player.play(path)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Cancel the tick, stop the worker and destroy the window."""
|
||||
logs.event(
|
||||
|
||||
@ -6,23 +6,20 @@
|
||||
|
||||
## Where things stand
|
||||
|
||||
**184 files** over 250 lines (was 198). All work so far is committed and pushed
|
||||
to `main`; the tree is clean. The three unrelated edits an earlier handoff
|
||||
warned about (`README.md`, the two `analysis_options.yaml`) are no longer
|
||||
present.
|
||||
**192 files** over 250 lines (was 198). All work so far is committed and pushed
|
||||
to `main`; `git status` is clean apart from pre-existing unrelated edits to
|
||||
`README.md`, `billsplit/analysis_options.yaml`, `focus_owner/analysis_options.yaml`
|
||||
— **leave those three alone, they are not yours.**
|
||||
|
||||
Done already (do not redo):
|
||||
|
||||
- `~/utils`: `plans/` + `sessions/` exempted from the cap (`specs/` still capped)
|
||||
- `17b20e5` new `no-inline-python` pre-commit hook + its one violation
|
||||
- `004b4b0` `CLAUDE.md` 259 → 141
|
||||
- `72a5e28` + `73b85f5` `poker-stakes/` tracked, then 4 violations → 0
|
||||
- `77c6d9f`…`d86965f` **every `wsg_grabber` source file** — `catalog` 251→175,
|
||||
`cli` 282→247, `review` 330→196, `net` 335→109, `store` 382→202,
|
||||
`downloader` 420→238, `player` 373→235, `ui` 398→242
|
||||
- `e03fbd1` `wsg_grabber/tests/test_review.py` 297 → 112 + two new modules
|
||||
|
||||
`git log --oneline --grep='250-line cap'` is the authoritative list.
|
||||
| Commit | What |
|
||||
| --------- | -------------------------------------------------------------------- |
|
||||
| `~/utils` | `plans/` + `sessions/` exempted from the cap (`specs/` still capped) |
|
||||
| `17b20e5` | New `no-inline-python` pre-commit hook + the one violation fixed |
|
||||
| `004b4b0` | `CLAUDE.md` 259 → 141 lines |
|
||||
| `72a5e28` | `poker-stakes/` tracked in git (58 files) |
|
||||
| `73b85f5` | `poker-stakes/` 4 violations → 0 |
|
||||
|
||||
## The live worklist
|
||||
|
||||
@ -32,19 +29,11 @@ Do not work from a list in this file — it goes stale. Run:
|
||||
bash ~/utils/scripts/check_file_length.sh --all
|
||||
```
|
||||
|
||||
**Every count in this file is a snapshot and will be wrong by the time you read
|
||||
it. Run the script.** As of `ac02a23` the shape was `linux_configuration` 84,
|
||||
`python_pkg` 41, `phone_focus_mode` 13, `kcd2_dice_solver` 12, `focus_owner`
|
||||
11, `billsplit` 6, `reverse_survivors`/`meta`/`docs` 4 each,
|
||||
`.github`/`bucket_catch` 2 each — quoted only to tell you where the bulk sits,
|
||||
never to work from.
|
||||
|
||||
Within `python_pkg`: `brother_printer` 15, `code_tutor` 13, `wsg_grabber` 6
|
||||
(tests only), then singles.
|
||||
|
||||
**Do the source files in a package before its tests.** Proven on `wsg_grabber`:
|
||||
the test files then split along seams the source already established, instead
|
||||
of you inventing a new boundary for them.
|
||||
Current distribution: `linux_configuration` 84, `python_pkg` 50,
|
||||
`phone_focus_mode` 13, `kcd2_dice_solver` 12, `focus_owner` 11, `billsplit` 6,
|
||||
`reverse_survivors`/`meta`/`docs` 4 each, `.github`/`bucket_catch` 2 each.
|
||||
**48 of them are near-misses at 251–300 lines** — highest count-drop per unit
|
||||
of effort, do these first.
|
||||
|
||||
## Decisions already made (do not re-ask)
|
||||
|
||||
@ -83,13 +72,67 @@ Plus `.github/workflows/file-length.yml` modelled on
|
||||
`.utils`), scoped to changed files. Then prove it fails: stage a deliberately
|
||||
251-line file, confirm `git commit` aborts, delete it.
|
||||
|
||||
## Python split recipes
|
||||
## The Python re-export form — settled empirically, do not re-derive
|
||||
|
||||
`docs/python-split-recipes.md` holds the settled Python rules: the `__all__`
|
||||
re-export form, the `TC001` trap that lints clean and breaks at runtime, the
|
||||
mixin shape for splitting a class, what the tests pin in place, and the
|
||||
coverage behaviour of new sibling modules. **Read it before the first Python
|
||||
split** — each rule there cost a failed gate run or a revert to establish.
|
||||
When a split moves a **public** name out of a module that callers/tests still
|
||||
reach through the old path, the re-export must be marked with `__all__`:
|
||||
|
||||
```python
|
||||
from python_pkg.pkg._new_module import show_logs, summarise
|
||||
|
||||
__all__ = ["build_parser", "main", ..., "show_logs", "summarise"]
|
||||
```
|
||||
|
||||
The PEP 484 alias form `from x import y as y` **does not work here**: ruff
|
||||
raises `PLC0414` (useless-import-alias), auto-fixes it away, and then removes
|
||||
the now-"unused" import under `F401` — silently breaking `cli.summarise`.
|
||||
Verified on `wsg_grabber/cli.py`; `__all__` passes ruff + mypy + pylint clean.
|
||||
|
||||
Splits that only move **private** helpers (leading `_`, no external caller)
|
||||
need no shim at all — check with grep first, as in `catalog.py`.
|
||||
|
||||
`__all__` only needs the **re-exported** names, not every public name in the
|
||||
module — names defined locally stay reachable either way. Verified against the
|
||||
full gate on `store.py`. Worth ~5–8 lines on every file with this shape, which
|
||||
matters: three splits so far landed 2–6 lines over the cap and needed a second
|
||||
seam. **Budget the new import block and `__all__` before deciding a two-way
|
||||
split is enough.**
|
||||
|
||||
Splitting a **class**: if tests call private methods as bound attributes
|
||||
(`worker._fetch_thread(...)` — grep the tests first), module-level functions
|
||||
will not do; use mixins. The shape that passes every gate with **no
|
||||
suppression** (settled on `downloader.py`, do not re-derive):
|
||||
|
||||
```python
|
||||
# _worker_base.py
|
||||
class WorkerBase(ABC):
|
||||
_deps: WorkerDeps # bare annotations for read-only attributes
|
||||
_downloaded: int = 0 # real default for any attribute the mixin ASSIGNS
|
||||
|
||||
@abstractmethod
|
||||
def _publish(self, event: DownloadEvent) -> None:
|
||||
"""Supplied by the concrete Worker."""
|
||||
```
|
||||
|
||||
Both mixins inherit `WorkerBase`; `Worker(ScanMixin, DownloadMixin)`. Why not
|
||||
the obvious alternatives:
|
||||
|
||||
- Naming a class `*Mixin` does **not** get you pylint's `no-member` exemption
|
||||
here — `ignored-checks-for-mixins` is not configured for it. Don't rely on it.
|
||||
- `raise NotImplementedError` stub bodies are **uncovered lines** under the
|
||||
100% branch gate.
|
||||
- `if TYPE_CHECKING: def _publish(...) -> None: ...` satisfies mypy but leaves
|
||||
pylint reporting `no-member`.
|
||||
- A bare annotation (`_downloaded: int`) is not enough for an attribute the
|
||||
mixin assigns to (`+= 1`); pylint wants a real default.
|
||||
|
||||
Watch the MRO: `Worker(ScanMixin, DownloadMixin)` means ScanMixin wins any
|
||||
name collision.
|
||||
|
||||
Coverage: `meta/pyproject.toml` sets `source = ["python_pkg"]`, so a new
|
||||
sibling module is measured automatically. Confirmed: new modules show up in
|
||||
the report at 100% rather than being silently skipped. Add no new branches
|
||||
(no `if TYPE_CHECKING` guards beyond what moved, no defensive `try/except`).
|
||||
|
||||
## Split recipes
|
||||
|
||||
@ -100,19 +143,7 @@ split** — each rule there cost a failed gate run or a revert to establish.
|
||||
API stable by re-exporting.
|
||||
- **TS/Dart** — extract components; re-export from the original path so no
|
||||
importer changes.
|
||||
- **Tests** — split by describe/test-group. Coverage must not drop, and
|
||||
**verify by the pass _count_, not a green run**: a split that loses a whole
|
||||
module still reports "passed".
|
||||
In `python_pkg`, shared fixture builders go in the package's
|
||||
**`tests/conftest.py`** — the `name-tests-test` hook rejects any other
|
||||
non-`test_*.py` file under `tests/`, so a `_helpers.py` will fail the gate.
|
||||
`python_pkg/syncyomi_guard/tests/conftest.py` is the precedent, and
|
||||
`meta/pyproject.toml` omits `*/tests/*` from coverage by path so nothing
|
||||
there is counted as production code (the opposite of the `poker-stakes`
|
||||
trap below). Prefer one shared conftest over another `partN` file: the repo
|
||||
already carries four, and each new one that redeclares the same fixture
|
||||
scaffolding pushes jscpd toward its 2% duplication threshold — which only
|
||||
fires on the real `git commit`.
|
||||
- **Tests** — split by describe/test-group. Coverage must not drop.
|
||||
|
||||
Never game the cap: no one-lining, no deleting tests, no moving code into an
|
||||
exempt extension, no suppressions.
|
||||
|
||||
Loading…
Reference in New Issue
Block a user