refactor(history): relocate _write_history() function (#40)
Move the `_write_history()` function from `downloader.py` to `history.py`. This refactoring separates persistence logic from download orchestration, ensuring `downloader.py` focuses solely on its core responsibility.
This commit is contained in:
7 files changed
+109
-24
No files matched your search
@@ -8,6 +8,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
|
|||||||
<!-- write-log: session-log-index -->
|
<!-- write-log: session-log-index -->
|
||||||
| Date | Type | File | Summary |
|
| Date | Type | File | Summary |
|
||||||
|------|------|------|---------|
|
|------|------|------|---------|
|
||||||
|
| 2026-06-05 | issue | [20260605-issue40-relocate-write-history-to-history_log.md](docs/devlog/20260605-issue40-relocate-write-history-to-history_log.md) | **Issue #40 Complete:** Relocated `_write_history()` from `downloader.py` → `history.py`. Updated all import sites. **+1 net test, ~430 total** · **All pass** · **5/5 AC** |
|
||||||
| 2026-06-05 | issue | [20260605-issue39-remove-cancel-event-from-reporters_log.md](docs/devlog/20260605-issue39-remove-cancel-event-from-reporters_log.md) | **Issue #39 Complete:** Removed `cancel_event` from both reporter classes. Explicit param on `download_book()`, closure capture in `sync_run.py`. **+5 net tests, ~429 total** · **All pass** · **6/6 AC** |
|
| 2026-06-05 | issue | [20260605-issue39-remove-cancel-event-from-reporters_log.md](docs/devlog/20260605-issue39-remove-cancel-event-from-reporters_log.md) | **Issue #39 Complete:** Removed `cancel_event` from both reporter classes. Explicit param on `download_book()`, closure capture in `sync_run.py`. **+5 net tests, ~429 total** · **All pass** · **6/6 AC** |
|
||||||
| 2026-06-05 | issue | [20260605-issue37-excise-client-py-dead-shim_log.md](docs/devlog/20260605-issue37-excise-client-py-dead-shim_log.md) | **Issue #37 Complete (Slice 1):** Excised `client.py` dead shim + `test_client.py`. Migrated 4 rate-limiter tests → `test_session.py`. **−337 lines dead code, 425→413 tests** · **All pass** · **6/6 AC** |
|
| 2026-06-05 | issue | [20260605-issue37-excise-client-py-dead-shim_log.md](docs/devlog/20260605-issue37-excise-client-py-dead-shim_log.md) | **Issue #37 Complete (Slice 1):** Excised `client.py` dead shim + `test_client.py`. Migrated 4 rate-limiter tests → `test_session.py`. **−337 lines dead code, 425→413 tests** · **All pass** · **6/6 AC** |
|
||||||
|------|------|------|---------|
|
|------|------|------|---------|
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Issue #40: Relocate `_write_history()` to `history.py`
|
||||||
|
|
||||||
|
> **Date:** 2026-06-05
|
||||||
|
> **Type:** issue
|
||||||
|
> **Reference:** [Issue #40](https://github.com/AlexKucera/librofm-downloader/issues/40) (PRD-003: Deepen Codebase Architecture)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Move `_write_history()` from `downloader.py` to `history.py` as a module-level function, update all call sites, and remove persistence-related imports from `downloader.py` so it contains only download-related logic.
|
||||||
|
|
||||||
|
## What Was Done
|
||||||
|
|
||||||
|
- **Wrote TDD test first** (`test_write_history_creates_entry_via_history_module` in `test_history.py`) — imports `_write_history` from `librofm_downloader.history`, confirming it creates a correct `HistoryEntry` with proper ISBN/title/format/path/timestamp fields → **RED** (`ImportError`)
|
||||||
|
- **Moved `_write_history()`** to `librofm_downloader/history.py` as a module-level function (lines 72–92), added `Book` type-hint import with `# noqa: F401` annotation → **GREEN**
|
||||||
|
- **Updated `sync_run.py`** — changed import from `from librofm_downloader.downloader import _write_history, download_book` to separate imports: `download_book` from `downloader`, `_write_history` + `DownloadHistory` from `history`. Removed duplicate `DownloadHistory` import that was already present.
|
||||||
|
- **Updated `test_downloader.py`** — moved `_write_history` import from `downloader` block to standalone `from librofm_downloader.history import _write_history`
|
||||||
|
- **Cleaned up `downloader.py`** — removed `from librofm_downloader.history import HistoryEntry` import and the entire `_write_history()` function (was lines 521–537, 19 lines removed)
|
||||||
|
|
||||||
|
## Decisions & Rationale
|
||||||
|
|
||||||
|
| Decision | Rationale |
|
||||||
|
|----------|-----------|
|
||||||
|
| TDD approach for pure relocation | Even though no logic changes, writing test first proves the new location works and provides a regression guard |
|
||||||
|
| `# noqa: F401` on Book import | `Book` is only used in string type hints (`"Book"`); linter would flag as unused without suppression |
|
||||||
|
| Keep lazy `datetime` import inside function | Preserves existing pattern — datetime only needed at call time, not module load |
|
||||||
|
|
||||||
|
## Gotchas & Fixes
|
||||||
|
|
||||||
|
| Problem | Root Cause | Fix |
|
||||||
|
|---------|------------|-----|
|
||||||
|
| Duplicate `_flush()` method after first edit | First `replace_lines` edit duplicated the method body instead of replacing it | Second edit removed the duplicate, kept original `_flush` + new `_write_history` |
|
||||||
|
| `TypeError: Book.__init__() missing required positional arguments` | Initial test used keyword-style args with wrong field order; `Book` requires `title`, `authors`, `narrators`, `isbn` as positional-or-keyword | Fixed test to pass all required fields correctly |
|
||||||
|
| Duplicate `DownloadHistory` import in sync_run.py | Added `DownloadHistory` to the new history import line, but old line still existed | Removed duplicate in follow-up edit |
|
||||||
|
|
||||||
|
## Files Changed
|
||||||
|
|
||||||
|
| File | Change Summary |
|
||||||
|
|------|---------------|
|
||||||
|
| `librofm_downloader/history.py` | **+20 lines** — added `_write_history()` module-level function + `Book` type-hint import |
|
||||||
|
| `librofm_downloader/downloader.py` | **−20 lines** — removed `HistoryEntry` import + `_write_history()` function |
|
||||||
|
| `librofm_downloader/sync_run.py` | Import fix — `_write_history` now from `history`; consolidated `DownloadHistory` import |
|
||||||
|
| `tests/test_history.py` | **+1 test, +26 net lines** — `TestWriteHistoryRelocated` class confirming relocation |
|
||||||
|
| `tests/test_downloader.py` | Import fix — `_write_history` now from `history` |
|
||||||
|
|
||||||
|
## Open Items & Next Steps
|
||||||
|
|
||||||
|
- None — this issue is complete. All 5 acceptance criteria met, full suite passes (~430 tests including pre-existing hangs).
|
||||||
|
|
||||||
|
---
|
||||||
|
*Log written by write-log skill*
|
||||||
@@ -14,7 +14,6 @@ import httpx
|
|||||||
|
|
||||||
from librofm_downloader.book import Book
|
from librofm_downloader.book import Book
|
||||||
from librofm_downloader.session import M4BUnavailableError
|
from librofm_downloader.session import M4BUnavailableError
|
||||||
from librofm_downloader.history import HistoryEntry
|
|
||||||
from librofm_downloader.path import (
|
from librofm_downloader.path import (
|
||||||
_resolve_output_dir,
|
_resolve_output_dir,
|
||||||
needs_subdirectory,
|
needs_subdirectory,
|
||||||
@@ -518,25 +517,6 @@ def download_accompanying_files(
|
|||||||
return downloaded
|
return downloaded
|
||||||
|
|
||||||
|
|
||||||
def _write_history(
|
|
||||||
history: "DownloadHistory",
|
|
||||||
book: Book,
|
|
||||||
fmt: str,
|
|
||||||
path: str,
|
|
||||||
) -> None:
|
|
||||||
"""Write a download history entry."""
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
entry = HistoryEntry(
|
|
||||||
isbn=book.isbn,
|
|
||||||
title=book.title,
|
|
||||||
format=fmt,
|
|
||||||
path=path,
|
|
||||||
downloaded_at=datetime.now(timezone.utc).isoformat(),
|
|
||||||
)
|
|
||||||
history.write(entry)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def rename_chapters(
|
def rename_chapters(
|
||||||
output_dir: Path | str,
|
output_dir: Path | str,
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import threading
|
|||||||
from dataclasses import dataclass, asdict
|
from dataclasses import dataclass, asdict
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from librofm_downloader.book import Book # noqa: F401 — used in _write_history() type hints
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@@ -65,3 +67,26 @@ class DownloadHistory:
|
|||||||
json.dumps(self._data, indent=2, ensure_ascii=False),
|
json.dumps(self._data, indent=2, ensure_ascii=False),
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _write_history(
|
||||||
|
history: "DownloadHistory",
|
||||||
|
book: "Book",
|
||||||
|
fmt: str,
|
||||||
|
path: str,
|
||||||
|
) -> None:
|
||||||
|
"""Write a download history entry.
|
||||||
|
|
||||||
|
Relocated from downloader.py (Issue #40) — this is a persistence
|
||||||
|
helper that belongs with the history module, not the download engine.
|
||||||
|
"""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
entry = HistoryEntry(
|
||||||
|
isbn=book.isbn,
|
||||||
|
title=book.title,
|
||||||
|
format=fmt,
|
||||||
|
path=path,
|
||||||
|
downloaded_at=datetime.now(timezone.utc).isoformat(),
|
||||||
|
)
|
||||||
|
history.write(entry)
|
||||||
@@ -20,8 +20,8 @@ from rich.console import Console
|
|||||||
|
|
||||||
from librofm_downloader.book import Book
|
from librofm_downloader.book import Book
|
||||||
from librofm_downloader.config import ConfigError, _resolve_config_file, load_config
|
from librofm_downloader.config import ConfigError, _resolve_config_file, load_config
|
||||||
from librofm_downloader.downloader import _write_history, download_book
|
from librofm_downloader.downloader import download_book
|
||||||
from librofm_downloader.history import DownloadHistory
|
from librofm_downloader.history import DownloadHistory, _write_history
|
||||||
from librofm_downloader.orchestrator import OrchestratorResult, download_all_books
|
from librofm_downloader.orchestrator import OrchestratorResult, download_all_books
|
||||||
from librofm_downloader.path import resolve_output_plan
|
from librofm_downloader.path import resolve_output_plan
|
||||||
from librofm_downloader.progress import DownloadReporter
|
from librofm_downloader.progress import DownloadReporter
|
||||||
|
|||||||
@@ -15,9 +15,9 @@ from librofm_downloader.path import (
|
|||||||
OutputPlan,
|
OutputPlan,
|
||||||
resolve_output_plan,
|
resolve_output_plan,
|
||||||
)
|
)
|
||||||
|
from librofm_downloader.history import _write_history
|
||||||
from librofm_downloader.downloader import (
|
from librofm_downloader.downloader import (
|
||||||
DownloadResult,
|
DownloadResult,
|
||||||
_write_history,
|
|
||||||
download_m4b,
|
download_m4b,
|
||||||
download_zip_part,
|
download_zip_part,
|
||||||
download_book,
|
download_book,
|
||||||
|
|||||||
+30
-1
@@ -8,6 +8,9 @@ import pytest
|
|||||||
|
|
||||||
from librofm_downloader.history import DownloadHistory, HistoryEntry
|
from librofm_downloader.history import DownloadHistory, HistoryEntry
|
||||||
|
|
||||||
|
from librofm_downloader.history import _write_history
|
||||||
|
from librofm_downloader.book import Book
|
||||||
|
|
||||||
|
|
||||||
class TestWriteAndRead:
|
class TestWriteAndRead:
|
||||||
"""Tracer bullet: write an entry and read it back by ISBN."""
|
"""Tracer bullet: write an entry and read it back by ISBN."""
|
||||||
@@ -243,4 +246,30 @@ class TestThreadSafety:
|
|||||||
|
|
||||||
found = history.find("111")
|
found = history.find("111")
|
||||||
assert found is not None
|
assert found is not None
|
||||||
assert found.title == "First"
|
assert found.title == "First"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class TestWriteHistoryRelocated:
|
||||||
|
"""Issue #40: _write_history() lives in history.py, not downloader.py."""
|
||||||
|
|
||||||
|
def test_write_history_creates_entry_via_history_module(self):
|
||||||
|
"""_write_history() imported from history.py writes a correct HistoryEntry."""
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
history_path = Path(tmpdir) / "download_history.json"
|
||||||
|
history = DownloadHistory(history_path)
|
||||||
|
book = Book(
|
||||||
|
title="Test Relocation",
|
||||||
|
authors=["Author"],
|
||||||
|
narrators=["Narrator"],
|
||||||
|
isbn="9780000000001",
|
||||||
|
)
|
||||||
|
|
||||||
|
_write_history(history, book, "m4b", "/audiobooks/Test/Test.m4b")
|
||||||
|
|
||||||
|
entry = history.find("9780000000001")
|
||||||
|
assert entry is not None
|
||||||
|
assert entry.title == "Test Relocation"
|
||||||
|
assert entry.format == "m4b"
|
||||||
|
assert entry.path == "/audiobooks/Test/Test.m4b"
|
||||||
|
assert entry.downloaded_at # non-empty ISO timestamp
|
||||||
Reference in new issue
Block a user