This pull request introduces the highly anticipated MP3 chapter renaming feature and includes a significant architectural refactoring pass to enhance code quality, testability, and maintainability.
New Feature: Chapter Renaming
Implements rename_chapters(): Adds a core function to rename extracted MP3 files using chapter titles from the download manifest, including natural sorting, zero-padding, and sanitization. (Closes#32)
Configurability: Introduces a rename_chapters configuration field and --rename-chapters CLI flag for user control, with support for 2-layer resolution (CLI > config). (Closes#33)
Pipeline Integration: Wires the rename_chapters() function directly into the download pipeline, ensuring automatic execution after MP3 extraction. Adds user-visible feedback through the reporter. (Closes#34)
Comprehensive Testing: Includes extensive unit and integration tests covering various scenarios, including special characters, single-track and 100+ chapter padding, and format strategy interactions. (Closes#35)
Architectural Refinements
Enhanced Testability: Refactors sync_run() into an injectable pipeline, accepting optional session, history, reporter, and download_all_fn parameters with real-construction defaults. Extracts _print_verbose_config and _resolve_history_path helpers. (Closes#44)
Improved Encapsulation & Modularity:
Relocates _write_history() from downloader.py to history.py, ensuring persistence logic resides in its dedicated module. (Closes#40)
Decouples cancellation state by removing cancel_event from progress reporter classes, passing it explicitly through the parameter chain instead. (Closes#39)
Exposes a public session.transport property on LibroFmSession, eliminating direct access to private internal attributes in downloader.py. (Closes#38)
Code Consolidation:
Extracts a _stream_to_file() helper to centralize the chunked-download loop logic, reducing duplication across download_m4b(), download_zip_part(), _download_cover(), and _download_pdf(). (Closes#41)
Consolidates post-download finalization steps (chapter renaming, accompanying file downloads) into a new _finalize_download() helper, simplifying the download_book() format branches.
Data Model Streamlining: Refactors SyncRunResult to use composition (wrapping OrchestratorResult) instead of duplicating fields, reducing structural redundancy and preventing potential drift. (Closes#45)
Dead Code Elimination: Excises the deprecated client.py re-export shim and its duplicate test_client.py file. Migrates unique rate-limiter tests to test_session.py. (Closes#37)
Test Suite Overhaul
Performs a significant cleanup pass, reorganizing test files to align with production modules.
Deletes 13 duplicate path test classes from test_downloader.py and removes a duplicate TestParallelProgressCallbackWiring class.
Moves integration-style pipeline tests from test_progress.py to test_sync_run.py.
Rescues an orphaned test method by wrapping it in a new class, ensuring no unique tests are lost. (Closes#43)
Adds 40+ new tests across various modules to cover newly introduced features and refactored logic.
This pull request introduces the highly anticipated MP3 chapter renaming feature and includes a significant architectural refactoring pass to enhance code quality, testability, and maintainability.
### New Feature: Chapter Renaming
- **Implements `rename_chapters()`:** Adds a core function to rename extracted MP3 files using chapter titles from the download manifest, including natural sorting, zero-padding, and sanitization. (Closes #32)
- **Configurability:** Introduces a `rename_chapters` configuration field and `--rename-chapters` CLI flag for user control, with support for 2-layer resolution (CLI > config). (Closes #33)
- **Pipeline Integration:** Wires the `rename_chapters()` function directly into the download pipeline, ensuring automatic execution after MP3 extraction. Adds user-visible feedback through the reporter. (Closes #34)
- **Comprehensive Testing:** Includes extensive unit and integration tests covering various scenarios, including special characters, single-track and 100+ chapter padding, and format strategy interactions. (Closes #35)
### Architectural Refinements
- **Enhanced Testability:** Refactors `sync_run()` into an injectable pipeline, accepting optional `session`, `history`, `reporter`, and `download_all_fn` parameters with real-construction defaults. Extracts `_print_verbose_config` and `_resolve_history_path` helpers. (Closes #44)
- **Improved Encapsulation & Modularity:**
- Relocates `_write_history()` from `downloader.py` to `history.py`, ensuring persistence logic resides in its dedicated module. (Closes #40)
- Decouples cancellation state by removing `cancel_event` from progress reporter classes, passing it explicitly through the parameter chain instead. (Closes #39)
- Exposes a public `session.transport` property on `LibroFmSession`, eliminating direct access to private internal attributes in `downloader.py`. (Closes #38)
- **Code Consolidation:**
- Extracts a `_stream_to_file()` helper to centralize the chunked-download loop logic, reducing duplication across `download_m4b()`, `download_zip_part()`, `_download_cover()`, and `_download_pdf()`. (Closes #41)
- Consolidates post-download finalization steps (chapter renaming, accompanying file downloads) into a new `_finalize_download()` helper, simplifying the `download_book()` format branches.
- **Data Model Streamlining:** Refactors `SyncRunResult` to use composition (wrapping `OrchestratorResult`) instead of duplicating fields, reducing structural redundancy and preventing potential drift. (Closes #45)
- **Dead Code Elimination:** Excises the deprecated `client.py` re-export shim and its duplicate `test_client.py` file. Migrates unique rate-limiter tests to `test_session.py`. (Closes #37)
### Test Suite Overhaul
- Performs a significant cleanup pass, reorganizing test files to align with production modules.
- Deletes 13 duplicate path test classes from `test_downloader.py` and removes a duplicate `TestParallelProgressCallbackWiring` class.
- Moves integration-style pipeline tests from `test_progress.py` to `test_sync_run.py`.
- Rescues an orphaned test method by wrapping it in a new class, ensuring no unique tests are lost. (Closes #43)
- Adds 40+ new tests across various modules to cover newly introduced features and refactored logic.
This PR introduces MP3 chapter renaming (rename_chapters()) with config and CLI integration, and performs a substantial architectural cleanup: relocating _write_history to history.py, decoupling cancel_event from reporters, exposing a public session.transport property, extracting a _stream_to_file helper, composing SyncRunResult over OrchestratorResult, and excising the deprecated client.py shim.
Chapter renaming: rename_chapters() uses natural sorting, zero-padded numbering, and title sanitization; wired into download_book() via a new _finalize_download() helper; guarded by format == \"mp3\" so M4B paths are unaffected.
Injectable pipeline: sync_run() now accepts optional session, history, reporter, and download_all_fn for testing without mocking; helpers _print_verbose_config and _resolve_history_path extracted.
Test overhaul: 13 duplicate path test classes removed, 40+ new tests added, orphaned test rescued, pipeline tests moved from test_progress.py to test_sync_run.py.
Confidence Score: 4/5
Safe to merge with one fix needed: the CLI rename_chapters flag cannot override the config in both directions.
The --rename-chapters flag uses store_true paired with rename_chapters or config.rename_chapters. Because config defaults to True, any user without an explicit false in their config gets renaming regardless of whether they passed the CLI flag — and there is no --no-rename-chapters to override it. The stated CLI > config resolution only works when the CLI value is True; it cannot disable renaming that the config enables. All other architectural changes are clean and well-tested.
librofm_downloader/sync_run.py line 162 (resolution logic) and librofm_downloader/cli.py (missing --no-rename-chapters argument).
Important Files Changed
Filename
Overview
librofm_downloader/sync_run.py
New injectable pipeline with rename_chapters resolution; the CLI override logic is one-directional and cannot disable renaming when config defaults to true.
librofm_downloader/downloader.py
Extracts _stream_to_file helper, adds rename_chapters() function and _finalize_download consolidation; Callable now imported from typing at line 29, resolving previous annotation concern.
librofm_downloader/cli.py
Adds --rename-chapters flag (store_true); clean thin adapter; no issues in isolation.
librofm_downloader/config.py
Adds rename_chapters field to Config dataclass with default True; clean implementation.
librofm_downloader/history.py
_write_history relocated from downloader.py; logic unchanged, correctly placed with HistoryEntry and DownloadHistory.
librofm_downloader/progress.py
Adds chapter_renamed() to both reporter classes; cancel_event decoupled from reporter state as intended.
librofm_downloader/session.py
Adds public transport property backed by construction-time stored reference, avoiding httpx private API; clean implementation.
librofm_downloader/client.py
Deprecated re-export shim deleted; tests migrated to test_session.py.
tests/test_downloader.py
Removes 13 duplicate path test classes, adds rename_chapters unit and integration tests; comprehensive coverage of edge cases.
tests/test_sync_run.py
New test file for injectable pipeline; pipeline integration tests migrated from test_progress.py.
Sequence Diagram
sequenceDiagram
participant CLI as cli.py
participant SR as sync_run()
participant DL as download_book()
participant FD as _finalize_download()
participant RC as rename_chapters()
participant AF as download_accompanying_files()
CLI->>SR: "run(rename_chapters=False|True)"
SR->>SR: "resolved = cli_flag OR config.rename_chapters"
SR->>DL: "download_book(..., rename_chapters=resolved)"
alt "format == mp3_only or mp3 fallback"
DL->>FD: "_finalize_download(format=mp3, rename_chapters=resolved)"
alt "rename_chapters == True"
FD->>RC: rename_chapters(output_dir, tracks, title)
RC-->>FD: count renamed
FD->>FD: reporter.chapter_renamed(count, title, example)
end
else "format == m4b"
DL->>FD: "_finalize_download(format=m4b)"
Note over FD: rename skipped (format != mp3)
end
FD->>AF: download_accompanying_files(book, plan)
FD-->>DL: DownloadResult(downloaded)
DL-->>SR: DownloadResult
SR->>SR: _write_history(history, book, fmt, path)
SR-->>CLI: SyncRunResult
<h3>Greptile Summary</h3>
This PR introduces MP3 chapter renaming (`rename_chapters()`) with config and CLI integration, and performs a substantial architectural cleanup: relocating `_write_history` to `history.py`, decoupling `cancel_event` from reporters, exposing a public `session.transport` property, extracting a `_stream_to_file` helper, composing `SyncRunResult` over `OrchestratorResult`, and excising the deprecated `client.py` shim.
- **Chapter renaming**: `rename_chapters()` uses natural sorting, zero-padded numbering, and title sanitization; wired into `download_book()` via a new `_finalize_download()` helper; guarded by `format == \"mp3\"` so M4B paths are unaffected.
- **Injectable pipeline**: `sync_run()` now accepts optional `session`, `history`, `reporter`, and `download_all_fn` for testing without mocking; helpers `_print_verbose_config` and `_resolve_history_path` extracted.
- **Test overhaul**: 13 duplicate path test classes removed, 40+ new tests added, orphaned test rescued, pipeline tests moved from `test_progress.py` to `test_sync_run.py`.
<h3>Confidence Score: 4/5</h3>
Safe to merge with one fix needed: the CLI rename_chapters flag cannot override the config in both directions.
The --rename-chapters flag uses store_true paired with rename_chapters or config.rename_chapters. Because config defaults to True, any user without an explicit false in their config gets renaming regardless of whether they passed the CLI flag — and there is no --no-rename-chapters to override it. The stated CLI > config resolution only works when the CLI value is True; it cannot disable renaming that the config enables. All other architectural changes are clean and well-tested.
librofm_downloader/sync_run.py line 162 (resolution logic) and librofm_downloader/cli.py (missing --no-rename-chapters argument).
<h3>Important Files Changed</h3>
| Filename | Overview |
|----------|----------|
| librofm_downloader/sync_run.py | New injectable pipeline with rename_chapters resolution; the CLI override logic is one-directional and cannot disable renaming when config defaults to true. |
| librofm_downloader/downloader.py | Extracts _stream_to_file helper, adds rename_chapters() function and _finalize_download consolidation; Callable now imported from typing at line 29, resolving previous annotation concern. |
| librofm_downloader/cli.py | Adds --rename-chapters flag (store_true); clean thin adapter; no issues in isolation. |
| librofm_downloader/config.py | Adds rename_chapters field to Config dataclass with default True; clean implementation. |
| librofm_downloader/history.py | _write_history relocated from downloader.py; logic unchanged, correctly placed with HistoryEntry and DownloadHistory. |
| librofm_downloader/progress.py | Adds chapter_renamed() to both reporter classes; cancel_event decoupled from reporter state as intended. |
| librofm_downloader/session.py | Adds public transport property backed by construction-time stored reference, avoiding httpx private API; clean implementation. |
| librofm_downloader/client.py | Deprecated re-export shim deleted; tests migrated to test_session.py. |
| tests/test_downloader.py | Removes 13 duplicate path test classes, adds rename_chapters unit and integration tests; comprehensive coverage of edge cases. |
| tests/test_sync_run.py | New test file for injectable pipeline; pipeline integration tests migrated from test_progress.py. |
</details>
<h3>Sequence Diagram</h3>
```mermaid
sequenceDiagram
participant CLI as cli.py
participant SR as sync_run()
participant DL as download_book()
participant FD as _finalize_download()
participant RC as rename_chapters()
participant AF as download_accompanying_files()
CLI->>SR: "run(rename_chapters=False|True)"
SR->>SR: "resolved = cli_flag OR config.rename_chapters"
SR->>DL: "download_book(..., rename_chapters=resolved)"
alt "format == mp3_only or mp3 fallback"
DL->>FD: "_finalize_download(format=mp3, rename_chapters=resolved)"
alt "rename_chapters == True"
FD->>RC: rename_chapters(output_dir, tracks, title)
RC-->>FD: count renamed
FD->>FD: reporter.chapter_renamed(count, title, example)
end
else "format == m4b"
DL->>FD: "_finalize_download(format=m4b)"
Note over FD: rename skipped (format != mp3)
end
FD->>AF: download_accompanying_files(book, plan)
FD-->>DL: DownloadResult(downloaded)
DL-->>SR: DownloadResult
SR->>SR: _write_history(history, book, fmt, path)
SR-->>CLI: SyncRunResult
```
<!-- greptile_other_comments_section -->
<sub>Reviews (2): Last reviewed commit: ["docs(downloader): note rename\_chapters p..."](https://github.com/alexkucera/librofm-downloader/commit/8619b400f2dc3c4fda9d1e952b1da9b05985c43a) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=35989481)</sub>
When resuming a download (resume_from > 0), downloaded is initialised to resume_from (the bytes already on disk), but content_length is read from the Range response's Content-Length header, which represents only the remaining bytes. The first progress(downloaded, total=content_length) call therefore passes a downloaded value that immediately exceeds total — e.g., if 60 MB is already written and 40 MB remain, the first update reports 68 MB completed against a 40 MB total (170%), breaking any progress bar.
The total passed to progress should be resume_from + content_length so it reflects the full expected file size.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Resume + progress total mismatch**
When resuming a download (`resume_from > 0`), `downloaded` is initialised to `resume_from` (the bytes already on disk), but `content_length` is read from the Range response's `Content-Length` header, which represents only the *remaining* bytes. The first `progress(downloaded, total=content_length)` call therefore passes a `downloaded` value that immediately exceeds `total` — e.g., if 60 MB is already written and 40 MB remain, the first update reports 68 MB completed against a 40 MB total (170%), breaking any progress bar.
The total passed to progress should be `resume_from + content_length` so it reflects the full expected file size.
The parameter name rename_chapters: bool shadows the module-level rename_chapters() function in _finalize_download's scope. This currently works because the actual function call is delegated to _rename_and_log, which has its own clean scope. However, if any future code inside _finalize_download tries to call rename_chapters(...) directly it will receive a TypeError (bool is not callable) with no obvious error message. Consider renaming the parameter to avoid the collision.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> The parameter name `rename_chapters: bool` shadows the module-level `rename_chapters()` function in `_finalize_download`'s scope. This currently works because the actual function call is delegated to `_rename_and_log`, which has its own clean scope. However, if any future code inside `_finalize_download` tries to call `rename_chapters(...)` directly it will receive a `TypeError` (bool is not callable) with no obvious error message. Consider renaming the parameter to avoid the collision.
```suggestion
def _finalize_download(
result_path: Path,
format: str,
book: "Book",
plan: "OutputPlan",
session: "LibroFmSession",
transport: httpx.BaseTransport | None = None,
*,
should_rename_chapters: bool = False,
```
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
The transport property reaches into httpx.Client._transport, a private attribute that is not part of httpx's public API. It has already been renamed/restructured across httpx versions, so this accessor may silently break on an httpx upgrade. Consider storing the transport reference directly at construction time instead.
@property
def transport(self) -> httpx.BaseTransport | None:
"""Return the underlying httpx transport for streaming downloads."""
return self._transport
# (Store the injected transport at __init__ time: self._transport = transport)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> The `transport` property reaches into `httpx.Client._transport`, a private attribute that is not part of httpx's public API. It has already been renamed/restructured across httpx versions, so this accessor may silently break on an httpx upgrade. Consider storing the transport reference directly at construction time instead.
```suggestion
@property
def transport(self) -> httpx.BaseTransport | None:
"""Return the underlying httpx transport for streaming downloads."""
return self._transport
# (Store the injected transport at __init__ time: self._transport = transport)
```
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Re: rename_chapters parameter shadowing the module-level function
Acknowledged and intentionally left as-is with a clarifying comment (lines 328–330).
The parameter name is consistent across the full pipeline — cli.run() → sync_run() → download_book() → _finalize_download() — all use rename_chapters:
bool. Renaming it only here (e.g. to should_rename_chapters) would create a naming inconsistency across ~100 references in 7+ files for a cosmetic improvement.
The shadowing is safe: _finalize_download only uses it as a boolean flag in a conditional check. The actual rename_chapters() function call lives inside _rename_and_log(), which has its own scope and no collision. Added an inline comment to make this explicit for future readers.
Re: rename_chapters parameter shadowing the module-level function
Acknowledged and intentionally left as-is with a clarifying comment (lines 328–330).
The parameter name is consistent across the full pipeline — cli.run() → sync_run() → download_book() → _finalize_download() — all use rename_chapters:
bool. Renaming it only here (e.g. to should_rename_chapters) would create a naming inconsistency across ~100 references in 7+ files for a cosmetic improvement.
The shadowing is safe: _finalize_download only uses it as a boolean flag in a conditional check. The actual rename_chapters() function call lives inside _rename_and_log(), which has its own scope and no collision. Added an inline comment to make this explicit for future readers.
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
This pull request introduces the highly anticipated MP3 chapter renaming feature and includes a significant architectural refactoring pass to enhance code quality, testability, and maintainability.
New Feature: Chapter Renaming
rename_chapters(): Adds a core function to rename extracted MP3 files using chapter titles from the download manifest, including natural sorting, zero-padding, and sanitization. (Closes #32)rename_chaptersconfiguration field and--rename-chaptersCLI flag for user control, with support for 2-layer resolution (CLI > config). (Closes #33)rename_chapters()function directly into the download pipeline, ensuring automatic execution after MP3 extraction. Adds user-visible feedback through the reporter. (Closes #34)Architectural Refinements
sync_run()into an injectable pipeline, accepting optionalsession,history,reporter, anddownload_all_fnparameters with real-construction defaults. Extracts_print_verbose_configand_resolve_history_pathhelpers. (Closes #44)_write_history()fromdownloader.pytohistory.py, ensuring persistence logic resides in its dedicated module. (Closes #40)cancel_eventfrom progress reporter classes, passing it explicitly through the parameter chain instead. (Closes #39)session.transportproperty onLibroFmSession, eliminating direct access to private internal attributes indownloader.py. (Closes #38)_stream_to_file()helper to centralize the chunked-download loop logic, reducing duplication acrossdownload_m4b(),download_zip_part(),_download_cover(), and_download_pdf(). (Closes #41)_finalize_download()helper, simplifying thedownload_book()format branches.SyncRunResultto use composition (wrappingOrchestratorResult) instead of duplicating fields, reducing structural redundancy and preventing potential drift. (Closes #45)client.pyre-export shim and its duplicatetest_client.pyfile. Migrates unique rate-limiter tests totest_session.py. (Closes #37)Test Suite Overhaul
test_downloader.pyand removes a duplicateTestParallelProgressCallbackWiringclass.test_progress.pytotest_sync_run.py.Greptile Summary
This PR introduces MP3 chapter renaming (
rename_chapters()) with config and CLI integration, and performs a substantial architectural cleanup: relocating_write_historytohistory.py, decouplingcancel_eventfrom reporters, exposing a publicsession.transportproperty, extracting a_stream_to_filehelper, composingSyncRunResultoverOrchestratorResult, and excising the deprecatedclient.pyshim.rename_chapters()uses natural sorting, zero-padded numbering, and title sanitization; wired intodownload_book()via a new_finalize_download()helper; guarded byformat == \"mp3\"so M4B paths are unaffected.sync_run()now accepts optionalsession,history,reporter, anddownload_all_fnfor testing without mocking; helpers_print_verbose_configand_resolve_history_pathextracted.test_progress.pytotest_sync_run.py.Confidence Score: 4/5
Safe to merge with one fix needed: the CLI rename_chapters flag cannot override the config in both directions.
The --rename-chapters flag uses store_true paired with rename_chapters or config.rename_chapters. Because config defaults to True, any user without an explicit false in their config gets renaming regardless of whether they passed the CLI flag — and there is no --no-rename-chapters to override it. The stated CLI > config resolution only works when the CLI value is True; it cannot disable renaming that the config enables. All other architectural changes are clean and well-tested.
librofm_downloader/sync_run.py line 162 (resolution logic) and librofm_downloader/cli.py (missing --no-rename-chapters argument).
Important Files Changed
Sequence Diagram
Reviews (2): Last reviewed commit: "docs(downloader): note rename_chapters p..." | Re-trigger Greptile
When resuming a download (
resume_from > 0),downloadedis initialised toresume_from(the bytes already on disk), butcontent_lengthis read from the Range response'sContent-Lengthheader, which represents only the remaining bytes. The firstprogress(downloaded, total=content_length)call therefore passes adownloadedvalue that immediately exceedstotal— e.g., if 60 MB is already written and 40 MB remain, the first update reports 68 MB completed against a 40 MB total (170%), breaking any progress bar.The total passed to progress should be
resume_from + content_lengthso it reflects the full expected file size.@@ -505,0 +568,4 @@new_name = f"{num:0{width}d} - {sanitized_book} - {sanitized_chapter}.mp3"new_path = output_dir / new_namemp3_file.rename(new_path)renamed += 1rename_chapters: boolshadows the module-levelrename_chapters()function in_finalize_download's scope. This currently works because the actual function call is delegated to_rename_and_log, which has its own clean scope. However, if any future code inside_finalize_downloadtries to callrename_chapters(...)directly it will receive aTypeError(bool is not callable) with no obvious error message. Consider renaming the parameter to avoid the collision.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
transportproperty reaches intohttpx.Client._transport, a private attribute that is not part of httpx's public API. It has already been renamed/restructured across httpx versions, so this accessor may silently break on an httpx upgrade. Consider storing the transport reference directly at construction time instead.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
@@ -505,0 +568,4 @@new_name = f"{num:0{width}d} - {sanitized_book} - {sanitized_chapter}.mp3"new_path = output_dir / new_namemp3_file.rename(new_path)renamed += 1Re: rename_chapters parameter shadowing the module-level function
Acknowledged and intentionally left as-is with a clarifying comment (lines 328–330).
The parameter name is consistent across the full pipeline — cli.run() → sync_run() → download_book() → _finalize_download() — all use rename_chapters:
bool. Renaming it only here (e.g. to should_rename_chapters) would create a naming inconsistency across ~100 references in 7+ files for a cosmetic improvement.
The shadowing is safe: _finalize_download only uses it as a boolean flag in a conditional check. The actual rename_chapters() function call lives inside _rename_and_log(), which has its own scope and no collision. Added an inline comment to make this explicit for future readers.