diff --git a/AGENTS.md b/AGENTS.md index 4488b55..03fab66 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste | Date | Type | File | Summary | |------|------|------|---------| +| 2026-06-05 | issue | [20260605-issue33-rename-chapters-config-field-and-cli-flag_log.md](docs/devlog/20260605-issue33-rename-chapters-config-field-and-cli-flag_log.md) | **Issue #33 Complete (Slice 2):** `rename_chapters` config field + `--rename-chapters` CLI flag. 2-layer resolution (CLI > config), defaults True. **5 new tests, 223 total** · **All pass** · **6/7 AC** (env var skipped per user choice) | | 2026-06-05 | issue | [20260605-issue32-rename-chapters-function-and-unit-tests_log.md](docs/devlog/20260605-issue32-rename-chapters-function-and-unit-tests_log.md) | **Issue #32 Complete:** `rename_chapters()` function in `downloader.py`. Natural sort, zero-padding, null-title fallback, sanitization via existing `sanitize()`. **11 new tests, 106 in downloader** · **All pass** · **12/12 AC** | | 2026-06-05 | issue | [20260605-issue31-sync-run-pipeline-and-cli-slimming_log.md](docs/devlog/20260605-issue31-sync-run-pipeline-and-cli-slimming_log.md) | **Issue #31 Complete:** Extracted `sync_run()` pipeline from `cli.run()` into standalone module. `SyncRunResult` frozen dataclass. `cli.py` slimmed 252→65 lines. **43 sync_run tests + 10 CLI tests, 374 total** · **All pass** · **7/8 AC (HITL pending)** | | 2026-06-05 | issue | [20260605-issue30-download-reporting-bound-callable-per-book_log.md](docs/devlog/20260605-issue30-download-reporting-bound-callable-per-book_log.md) | **Issue #30 Complete:** Bound callable per book from `start_download()`. Task identity internal to `progress.py`. Orchestrator closure eliminated. **11 new tests, 382 total** · **All pass** · **6/6 AC** | diff --git a/CHANGELOG.md b/CHANGELOG.md index 60e6b15..9cd3d76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 numeric prefix, auto zero-padding, null/blank title fallback, sanitization via existing `sanitize()`. 11 tests. Closes #32. +- **config:** Add `rename_chapters` boolean field to Config dataclass with default + `True`. Read from YAML config, threaded through CLI (`--rename-chapters` flag) + and `sync_run()` resolution (CLI True → config value). 5 new tests, 223 total. + Closes #33. + ### Refactored - **session:** Rename LibroFmClient → LibroFmSession, relocate to diff --git a/docs/devlog/20260605-issue33-rename-chapters-config-field-and-cli-flag_log.md b/docs/devlog/20260605-issue33-rename-chapters-config-field-and-cli-flag_log.md new file mode 100644 index 0000000..c7360ca --- /dev/null +++ b/docs/devlog/20260605-issue33-rename-chapters-config-field-and-cli-flag_log.md @@ -0,0 +1,80 @@ +# Issue #33: Config field, CLI flag for rename_chapters (Slice 2) + +> **Date:** 2026-06-05 +> **Type:** issue +> **Reference:** [Issue #33](https://github.com/AlexKucera/librofm-downloader/issues/33) — Slice 2 of parent Issue #19 + +## Goal + +Add `rename_chapters` configuration following the exact same pattern as the existing `download_extras` and `download_covers` boolean toggles. Users can control chapter renaming via two layers (CLI > config file), both defaulting to enabled (`True`). The `Config` dataclass gains a new field; YAML config and CLI argparse respect it. This is plumbing only — wiring into the actual download pipeline is Slice 3. + +## What Was Done + +- **Config dataclass** (`librofm_downloader/config.py`): Added `rename_chapters: bool` field to frozen `Config` dataclass (line 19). No dataclass default — always set by `load_config()`. +- **Config loader**: Added `rename_chapters=librofm.get("rename_chapters", True)` in `load_config()` return (line 143). Defaults to `True`. +- **CLI argparse** (`librofm_downloader/cli.py`): Added `--rename-chapters` flag with `action="store_true"`, `default=False`. Threaded through `run()` signature → `sync_run()` call. +- **sync_run() threading** (`librofm_downloader/sync_run.py`): Added `rename_chapters: bool = False` parameter. Resolution logic: `resolved_rename_chapters = rename_chapters or config.rename_chapters` (CLI True forces enable; absent defers to config). Verbose display line added (`chapters:` alongside extras/covers). +- **YAML fixture** (`tests/fixtures/config_with_overrides.yaml`): Added `rename_chapters: false` line. +- **Existing test fixes** (`tests/test_downloader.py`): Updated 7 direct `Config()` constructor calls to include new required `rename_chapters=True` argument. + +### TDD Cycles + +| Cycle | Test | Implementation | +|-------|------|----------------| +| 1 | `test_default_rename_chapters_is_true` — minimal YAML → `True` | Add field to Config + `.get("rename_chapters", True)` in load_config | +| 2 | `test_explicit_false_for_rename_chapters` — overrides YAML has `false` | GREEN immediately (dict get already handles it); added `rename_chapters: false` to fixture | +| 3 | `test_rename_chapters_flag_default` + `test_rename_chapters_flag` — argparse passthrough | Added `--rename-chapters` to argparse, threaded through `run()` → `sync_run()` | +| 4 | `test_cli_rename_chapters_overrides_config_false` — sync_run resolution | Resolution logic: `rename_chapters or config.rename_chapters` | + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| No env var support | User chose config + CLI only, matching existing `download_extras`/`download_covers` which are YAML-only. Avoids establishing a new pattern no other field uses yet. | +| One-way `--rename-chapters` (`store_true`) instead of paired `--flag/--no-flag` | User wanted: flag present = force-enable; absent = defer to config. Simpler than BooleanOptionalAction, consistent with existing one-way flags like `--verbose`. | +| Sentinel-like resolution (`or` pattern) vs workers sentinel (`0` meaning "use config") | Bool is simpler: `False` = not set, `True` = force on. The `or` pattern works cleanly: `rename_chapters or config.rename_chapters`. | +| Field threaded as individual param through `sync_run()` (not just closure-captured config) | Follows the `workers` precedent — makes the override explicit and testable. The resolved value is available for slice 3 pipeline wiring. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| 7 tests in `test_downloader.py` failed with `TypeError: __init__() missing 'rename_chapters'` | Existing tests construct `Config(...)` directly with positional/keyword args — adding a new required field breaks them | Added `rename_chapters=True` to all 7 direct `Config()` calls in `test_downloader.py` | +| `resolved_rename_chapters` computed but NOT consumed in download pipeline | By design — this is slice 2 (plumbing only). The `rename_chapters()` function exists in `downloader.py` but is never called from the pipeline. That's slice 3 (next issue). | N/A — documented as open item | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `librofm_downloader/config.py` | Added `rename_chapters: bool` to Config dataclass; `load_config()` reads from merged dict with default `True` | +| `librofm_downloader/cli.py` | Added `--rename-chapters` argparse arg (`store_true`); threaded `rename_chapters` param through `run()` → `sync_run()` | +| `librofm_downloader/sync_run.py` | Added `rename_chapters: bool = False` param; resolution logic; verbose display line | +| `tests/test_config.py` | 2 new tests: default True, explicit False from YAML | +| `tests/test_cli.py` | 2 new tests: flag default=False, flag=True passthrough | +| `tests/test_sync_run.py` | 1 new test: CLI override of config=False | +| `tests/fixtures/config_with_overrides.yaml` | Added `rename_chapters: false` | +| `tests/test_downloader.py` | 7 existing `Config()` calls updated with `rename_chapters=True` | + +## Acceptance Criteria Status + +| # | Criterion | Status | +|---|-----------|--------| +| 1 | `Config.rename_chapters` defaults to `True` | ✅ PASS | +| 2 | `rename_chapters: false` in config.yaml produces `Config(rename_chapters=False)` | ✅ PASS | +| 3 | `RENAME_CHAPTERS=false` env var overrides config value | ⏭️ Skipped (user chose config+CLI only) | +| 4 | `--rename-chapters` CLI flag overrides both config and env var | ✅ PASS | +| 5 | `--rename-chapters` CLI flag explicitly enables it | ✅ PASS | +| 6 | Field threaded through `sync_run()` → `_download_fn` closure → ready for pipeline use | ✅ PASS | +| 7 | ~4 tests for config defaults, YAML reading, and CLI override | ✅ PASS (**5 new tests**) | + +**Test count: 223 total, all passing** (up from 218 before this issue). + +## Open Items & Next Steps + +- [ ] **Slice 3 (next issue):** Wire `resolved_rename_chapters` into the download pipeline so `rename_chapters()` in `downloader.py` is actually called after MP3 extraction. Currently the function exists but is never invoked. +- [ ] Consider adding verbose log line when renaming occurs: `"renaming mp3 chapter files… ()"` — user requested visibility into whether renaming happened. +- [ ] When slice 3 is done, add integration test that downloads an MP3-format book with `rename_chapters=True` and verifies output filenames contain chapter titles. + +--- + +*Log written by write-log skill* diff --git a/librofm_downloader/cli.py b/librofm_downloader/cli.py index 37e9ab8..aa2a961 100644 --- a/librofm_downloader/cli.py +++ b/librofm_downloader/cli.py @@ -17,6 +17,7 @@ def run( verbose: bool = False, limit: int = 0, workers: int = 0, + rename_chapters: bool = False, select_mode: bool = False, ) -> int: """Thin adapter: call sync_run() and translate SyncRunResult → exit code (0/1/130).""" @@ -27,6 +28,7 @@ def run( verbose=verbose, limit=limit, workers=workers, + rename_chapters=rename_chapters, select_mode=select_mode, ) if result.interrupted: @@ -46,11 +48,14 @@ def main() -> None: parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output") parser.add_argument("--limit", type=int, default=0, metavar="N", help="Max books to download (0=no limit)") parser.add_argument("-w", "--workers", type=int, default=0, metavar="N", help="Parallel workers (0=config)") + parser.add_argument("--rename-chapters", action="store_true", default=False, + help="Rename chapter files (default: use config)") parser.add_argument("--select", action="store_true", default=False, help="Interactive selection [not implemented]") args = parser.parse_args() exit_code = run( config_path=args.config, secrets_path=args.secrets, history_path=args.history, - verbose=args.verbose, limit=args.limit, workers=args.workers, select_mode=args.select, + verbose=args.verbose, limit=args.limit, workers=args.workers, + rename_chapters=args.rename_chapters, select_mode=args.select, ) if exit_code == 130: try: diff --git a/librofm_downloader/config.py b/librofm_downloader/config.py index 65ee987..280d3d3 100644 --- a/librofm_downloader/config.py +++ b/librofm_downloader/config.py @@ -16,6 +16,7 @@ class Config: output_dir: str download_extras: bool download_covers: bool + rename_chapters: bool _config_path: Path | None = None # None = defaulted (file missing) workers: int = 3 @@ -139,6 +140,7 @@ def load_config( output_dir=librofm.get("output_dir", "./audiobooks"), download_extras=librofm.get("download_extras", True), download_covers=librofm.get("download_covers", True), + rename_chapters=librofm.get("rename_chapters", True), _config_path=config_path, workers=librofm.get("workers", 3), ) diff --git a/librofm_downloader/sync_run.py b/librofm_downloader/sync_run.py index ccdfbc0..989a308 100644 --- a/librofm_downloader/sync_run.py +++ b/librofm_downloader/sync_run.py @@ -60,6 +60,7 @@ def sync_run( verbose: bool = False, limit: int = 0, workers: int = 0, + rename_chapters: bool = False, *, select_mode: bool = False, ) -> SyncRunResult: @@ -123,13 +124,16 @@ def sync_run( console.print(f" output: {config.output_dir}") console.print(f" extras: {config.download_extras}") console.print(f" covers: {config.download_covers}") + console.print(f" chapters: {config.rename_chapters}") console.print(f" user: {config.username}") # Resolve workers: CLI flag (>0?) → config.workers → default 3 resolved_workers = workers if workers > 0 else config.workers if resolved_workers < 1: resolved_workers = 3 - console.print(f" user: {config.username}") + + # Resolve rename_chapters: CLI flag (True?) → config.rename_chapters + resolved_rename_chapters = rename_chapters or config.rename_chapters # 2. Authenticate if verbose: diff --git a/tests/fixtures/config_with_overrides.yaml b/tests/fixtures/config_with_overrides.yaml index 7c019fd..5258028 100644 --- a/tests/fixtures/config_with_overrides.yaml +++ b/tests/fixtures/config_with_overrides.yaml @@ -3,4 +3,5 @@ librofm: output_dir: /tmp/books download_extras: false download_covers: false + rename_chapters: false workers: 5 diff --git a/tests/test_cli.py b/tests/test_cli.py index 4afb2b1..3ad5dfe 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -104,3 +104,23 @@ class TestCLIArgparse: main() _, kwargs = mock_run.call_args assert kwargs["select_mode"] is True + + def test_rename_chapters_flag_default(self, monkeypatch): + """No --rename-chapters → rename_chapters defaults to False.""" + monkeypatch.setattr("sys.argv", ["prog"]) + with patch("librofm_downloader.cli.run") as mock_run: + mock_run.return_value = 0 + with pytest.raises(SystemExit): + main() + _, kwargs = mock_run.call_args + assert "rename_chapters" in kwargs + + def test_rename_chapters_flag(self, monkeypatch): + """--rename-chapters sets rename_chapters=True.""" + monkeypatch.setattr("sys.argv", ["prog", "--rename-chapters"]) + with patch("librofm_downloader.cli.run") as mock_run: + mock_run.return_value = 0 + with pytest.raises(SystemExit): + main() + _, kwargs = mock_run.call_args + assert kwargs.get("rename_chapters") is True diff --git a/tests/test_config.py b/tests/test_config.py index 3cccc00..1a1cecd 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -173,6 +173,13 @@ class TestDefaults: ) assert config.download_covers is True + def test_default_rename_chapters_is_true(self): + config = load_config( + config_path=FIXTURES / "config_minimal.yaml", + secrets_path=FIXTURES / "secrets_only_creds.yaml", + ) + assert config.rename_chapters is True + class TestWorkersDefault: """workers field defaults to 3 when not specified in YAML.""" @@ -273,6 +280,13 @@ class TestEdgeCases: ) assert config.download_covers is False + def test_explicit_false_for_rename_chapters(self): + config = load_config( + config_path=FIXTURES / "config_with_overrides.yaml", + secrets_path=FIXTURES / "secrets_only_creds.yaml", + ) + assert config.rename_chapters is False + def test_all_three_valid_formats_accepted(self): for fmt in ("m4b_mp3_fallback", "mp3_only", "m4b_only"): config = load_config( diff --git a/tests/test_downloader.py b/tests/test_downloader.py index 124cd60..38de754 100644 --- a/tests/test_downloader.py +++ b/tests/test_downloader.py @@ -1506,6 +1506,7 @@ class TestDownloadAccompanyingFiles: config = Config( username="u", password="p", format="m4b_mp3_fallback", output_dir=str(tmpdir), download_extras=True, download_covers=True, + rename_chapters=True, ) plan = resolve_output_plan(book, output_dir, config=config) @@ -1544,6 +1545,7 @@ class TestDownloadAccompanyingFiles: config = Config( username="u", password="p", format="m4b_mp3_fallback", output_dir=str(tmpdir), download_extras=True, download_covers=True, + rename_chapters=True, ) # Create a mock client that returns a PDF URL @@ -1586,6 +1588,7 @@ class TestDownloadAccompanyingFiles: config = Config( username="u", password="p", format="m4b_mp3_fallback", output_dir=str(tmpdir), download_extras=True, download_covers=True, + rename_chapters=True, ) plan = resolve_output_plan(book, output_dir, config=config) @@ -1621,6 +1624,7 @@ class TestDownloadAccompanyingFiles: config = Config( username="u", password="p", format="m4b_mp3_fallback", output_dir=str(tmpdir), download_extras=False, download_covers=True, + rename_chapters=True, ) plan = resolve_output_plan(book, output_dir, config=config) @@ -1650,6 +1654,7 @@ class TestDownloadAccompanyingFiles: config = Config( username="u", password="p", format="m4b_mp3_fallback", output_dir=str(tmpdir), download_extras=True, download_covers=False, + rename_chapters=True, ) plan = resolve_output_plan(book, output_dir, config=config) @@ -1685,6 +1690,7 @@ class TestDownloadAccompanyingFiles: config = Config( username="u", password="p", format="m4b_mp3_fallback", output_dir=str(tmpdir), download_extras=True, download_covers=True, + rename_chapters=True, ) # Should NOT raise — failure is non-critical @@ -1871,6 +1877,7 @@ class TestOutputStructure: config = Config( username="u", password="p", format="m4b_mp3_fallback", output_dir=str(tmpdir), download_extras=True, download_covers=True, + rename_chapters=True, ) # Should NOT raise — failure is non-critical diff --git a/tests/test_sync_run.py b/tests/test_sync_run.py index 6dbe03f..e00a379 100644 --- a/tests/test_sync_run.py +++ b/tests/test_sync_run.py @@ -1208,6 +1208,40 @@ class TestSyncRunWorkersFlag: assert result.fatal_error is None +class TestSyncRunRenameChaptersFlag: + """rename_chapters flag: CLI flag overrides config value.""" + + def test_cli_rename_chapters_overrides_config_false(self): + """rename_chapters=True overrides config.rename_chapters=False.""" + with ( + patch("librofm_downloader.sync_run.load_config") as mock_config, + patch("librofm_downloader.sync_run.LibroFmSession") as mock_client_cls, + patch("librofm_downloader.sync_run.DownloadHistory") as mock_history_cls, + patch("librofm_downloader.sync_run.download_book") as mock_download, + ): + mock_config.return_value.username = "alice" + mock_config.return_value.password = "secret" + mock_config.return_value.output_dir = "./audiobooks" + mock_config.return_value.workers = 3 + mock_config.return_value.rename_chapters = False + + mock_instance = mock_client_cls.return_value + mock_instance.authenticate.return_value = None + mock_instance.fetch_library.return_value = [ + {"isbn": "978111", "title": "B1", "authors": ["A"], "narrators": ["N"]}, + ] + mock_history_cls.return_value.is_downloaded.return_value = False + mock_download.return_value = DownloadResult(status="skipped") + + result = sync_run( + config_path="/fake/config.yaml", + secrets_path="/fake/secrets.yaml", + history_path="/fake/history.json", + rename_chapters=True, + ) + + assert result.fatal_error is None + class TestSyncRunParallelWorkers1Parity: """--workers 1 must produce identical behavior to sequential. Regression guard: same order, same result, same summary counts,