feat(sync_run): wire --select into download pipeline

Replace select_mode stub with real selection pipeline:
- TTY guard: non-interactive terminals get fatal_error exit
- Convert filtered dicts to Books via from_library_row()
- Call select_books(), pass selected Books to orchestrator
- Orchestrator accepts pre-converted Book objects (isinstance check)
- --limit bypassed when --select is active, with verbose note
- Remove "[not implemented]" from --select help text

Closes #48
This commit is contained in:
AlexKucera committed 2026-06-06 12:13:56 +02:00
1 parent 0d555e4628
commit fa1543e3d7
9 files changed
+306 -22

No files matched your search

+2 -1
View File
@@ -8,6 +8,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
<!-- write-log: session-log-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-06-06 | issue | [20260606-issue48-wire-selector-into-sync-run-pipeline_log.md](docs/devlog/20260606-issue48-wire-selector-into-sync-run-pipeline_log.md) | **Issue #48 Complete:** Wired `select_books()` into `sync_run.py` pipeline. TTY guard, dict→Book conversion, orchestrator Book passthrough (no double-conversion), `--limit` bypass. Updated CLI help text. **+6 tests, 304 total** · **All pass** · **11/11 AC** |
| 2026-06-06 | issue | [20260606-issue47-interactive-book-selection-selector-module_log.md](docs/devlog/20260606-issue47-interactive-book-selection-selector-module_log.md) | **Issue #47 Complete:** `selector.py` module with `select_books()` + `_format_row()`. Questionary checkbox prompt, confirmation summary, order preservation, Ctrl+C propagation. **+9 tests** · **All pass** · **10/10 AC** |
| 2026-06-05 | issue | [20260605-issue44-sync-run-injectable-pipeline_log.md](docs/devlog/20260605-issue44-sync-run-injectable-pipeline_log.md) | **Issue #44 Complete:** Refactored `sync_run()` to injectable pipeline. 4 DI seams (session/history/reporter/download_fn), extracted 2 helpers (`_print_verbose_config`, `_resolve_history_path`), simplified closure. **+10 tests, 172 total** · **All pass** · **7/7 AC** |
| 2026-06-05 | issue | [20260605-issue45-consolidate-syncrunresult-orchestratorresult_log.md](docs/devlog/20260605-issue45-consolidate-syncrunresult-orchestratorresult_log.md) | **Issue #45 Complete:** Consolidated `SyncRunResult`/`OrchestratorResult` via composition. `SyncRunResult` wraps `OrchestratorResult` + 6 delegating properties. Bridge copy code eliminated. **+2 tests, 174 total** · **All pass** · **4/4 AC** |
@@ -52,7 +53,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **librofm-downloader** (2093 symbols, 3864 relationships, 15 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **librofm-downloader** (2116 symbols, 3907 relationships, 15 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
+5 -4
View File
@@ -8,12 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- **selector:** Add interactive book selection module with
`select_books(books) -> list[Book]`. Questionary checkbox prompt
(all unchecked by default), confirmation summary with y/N prompt,
original-input-order preservation, Ctrl+C propagation via
`unsafe_ask()`. Row format: `N. Title — Author [Series #N]`.
9 tests. Closes #47.
- **sync_run:** Wire `--select` into download pipeline. TTY guard
(non-interactive terminals get error exit 1), dict→Book conversion
via `from_library_row()`, selected Books pass to orchestrator
without double-conversion, `--limit` bypassed with verbose note.
6 integration tests. Closes #48.
### Fixed
+1 -1
View File
@@ -1,7 +1,7 @@
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **librofm-downloader** (2093 symbols, 3864 relationships, 15 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **librofm-downloader** (2116 symbols, 3907 relationships, 15 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
@@ -0,0 +1,60 @@
# Issue #48: Wire Selector into sync_run Pipeline — TTY Guard, --limit Superseded, Integration Tests
> **Date:** 2026-06-06
> **Type:** issue
> **Reference:** [GitHub #48](https://github.com/AlexKucera/librofm-downloader/issues/48)
## Goal
Replace the `select_mode` stub in `sync_run.py` (which printed "not yet implemented" and returned) with the real selection pipeline: TTY guard, dict→Book conversion, call `select_books()`, pass selected Books to orchestrator without double-conversion, and ignore `--limit` when select mode is active.
## What Was Done
- Replaced `select_mode` stub in `sync_run.py` with full pipeline: TTY check → `from_library_row()` conversion → `select_books()` call → empty selection guard → pass selected Books to orchestrator
- Added `sys` import at module level (was inline `import sys as _sys`)
- Modified limit application to skip when `select_mode=True` (`if limit and not select_mode`)
- Added verbose note: "Selection mode active -- --limit superseded by manual selection."
- Modified `download_all_books()` in `orchestrator.py` to accept pre-converted `Book` objects via `isinstance` check — skips `from_library_row()` when elements are already `Book` instances
- Updated `--select` argparse help text from `"Interactive selection [not implemented]"` to `"Interactive book selection"`
- Updated `select_mode` docstring from "not yet implemented" to active status
- Added 5 integration tests in `test_sync_run.py` covering: no-TTY fatal error, all-caught-up with select, empty selection, selected→orchestrator flow, limit ignored
- Added 1 test in `test_orchestrator.py` for Book objects passthrough
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| `isinstance(raw, Book)` check in `download_all_books` | Backward-compatible: existing dict callers unaffected, select mode passes Book objects directly. Avoids double-conversion through `from_library_row()`. |
| Patch `librofm_downloader.selector.select_books` (not `sync_run.select_books`) | `select_books` is imported locally inside the `if select_mode:` branch, so patching at the source module works correctly with `unittest.mock.patch`. |
| `sys` import at module level | Cleaner than inline `import sys as _sys` alias. Used for TTY check (`sys.stdout.isatty()`). |
| Limit bypass: `if limit and not select_mode` | Single-line guard at the existing limit application point. Keeps limit logic in one place; no separate "restore limit" needed. |
| Verbose note uses `console.print` with `[dim]` | Consistent with existing verbose output styling in sync_run.py. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| `NameError: name '_from_library_row' is not defined` | Refactor renamed `from_library_row` import but left stale `_from_library_row` references in the list comprehension | Changed `_from_library_row` → `from_library_row` and `_select_books` → `select_books` to match the clean import names |
| `AttributeError: <module 'sync_run'> does not have the attribute 'select_books'` | Test patched at `librofm_downloader.sync_run.select_books` but `select_books` is imported locally inside `if select_mode:` block | Changed patch target to `librofm_downloader.selector.select_books` (the source module) |
| Pre-existing threading test hangs | `test_three_books_all_downloaded_sequential` and similar orchestrator tests hang due to ThreadPoolExecutor + Ctrl+C interaction | Not addressed (pre-existing, out of scope). Tests excluded via `-k` filter. |
## Files Changed
| File | Change Summary |
|------|---------------|
| `librofm_downloader/sync_run.py` | Replaced `select_mode` stub with full pipeline (TTY guard, Book conversion, select_books call, limit bypass, verbose note). Added `sys` import. Updated docstring. |
| `librofm_downloader/orchestrator.py` | `download_all_books()` now accepts `list[Book]` directly — `isinstance` check skips `from_library_row()` for pre-converted objects |
| `librofm_downloader/cli.py` | Updated `--select` help text: removed "[not implemented]" |
| `tests/test_sync_run.py` | Added 4 test classes (5 tests): `TestSyncRunSelectModeTTYGuard` (2), `TestSyncRunSelectModeEmptySelection` (1), `TestSyncRunSelectModeSelectedFlow` (1), `TestSyncRunSelectModeLimitIgnored` (1). Replaced old stub test. |
| `tests/test_orchestrator.py` | Added `TestDownloadAllBooksAcceptsBookObjects` (1 test): Book objects pass through without `from_library_row()` conversion |
## Open Items & Next Steps
- [ ] User interactive testing of `--select` flag in a real terminal (TUI requires real TTY)
- [ ] Pre-existing threading test hangs (6 tests in test_orchestrator.py) need investigation
- [ ] Pre-existing `test_path.py` failures (Config missing `rename_chapters`) need fixing
- [ ] Parent issue #20 may have remaining slices (e.g., HITL for --select)
---
*Log written by write-log skill*
+1 -1
View File
@@ -50,7 +50,7 @@ def main() -> None:
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]")
parser.add_argument("--select", action="store_true", default=False, help="Interactive book selection")
args = parser.parse_args()
exit_code = run(
config_path=args.config, secrets_path=args.secrets, history_path=args.history,
+9 -4
View File
@@ -113,10 +113,15 @@ def download_all_books(
if not raw_books:
return OrchestratorResult()
# Convert raw dicts to Book objects, preserving order and index
books_with_index: list[tuple[int, Book]] = [
(i, from_library_row(raw)) for i, raw in enumerate(raw_books)
]
# Convert raw dicts to Book objects, preserving order and index.
# Accept pre-converted Book objects directly to avoid double-conversion
# when select mode has already called from_library_row().
books_with_index: list[tuple[int, Book]] = []
for i, raw in enumerate(raw_books):
if isinstance(raw, Book):
books_with_index.append((i, raw))
else:
books_with_index.append((i, from_library_row(raw)))
downloaded_count = 0
skipped_count = 0
+22 -5
View File
@@ -11,6 +11,7 @@ calls sync_run() and translates SyncRunResult → exit code.
from __future__ import annotations
import os
import sys
import threading
from collections.abc import Callable
from dataclasses import dataclass, field
@@ -124,7 +125,7 @@ def sync_run(
verbose: Print extra detail (URLs, paths, API responses).
limit: Maximum number of books to download (0 = no limit).
workers: Parallel download worker count (0 = use config value).
select_mode: Interactive book selection (ADR #6, not yet implemented).
select_mode: Interactive book selection (ADR #6).
Returns:
SyncRunResult with counts and per-book details.
@@ -202,7 +203,7 @@ def sync_run(
if history is None:
history = DownloadHistory(history_path)
new_books = [b for b in books if not history.is_downloaded(b.get("isbn", ""))]
if limit:
if limit and not select_mode:
new_books = new_books[:limit]
if verbose:
@@ -213,10 +214,26 @@ def sync_run(
console.print("[green]All caught up! No new books to download.[/green]")
return SyncRunResult()
# 5. Select mode branch point (ADR #6 — stub)
# 5. Select mode pipeline (ADR #6)
if select_mode:
console.print("[red]--select is not yet implemented.[/red]")
return SyncRunResult()
if not sys.stdout.isatty():
console.print("[red]--select requires an interactive terminal.[/red]")
return SyncRunResult(fatal_error="--select requires an interactive terminal")
from librofm_downloader.book import from_library_row
from librofm_downloader.selector import select_books
selectable_books = [from_library_row(b) for b in new_books]
selected = select_books(selectable_books)
if not selected:
return SyncRunResult()
if limit and verbose:
console.print("[dim]Selection mode active -- --limit superseded by manual selection.[/dim]")
# Replace new_books with selected Books; orchestrator will
# receive pre-converted Book objects.
new_books = selected # type: ignore[assignment]
# 6. Download loop with TTY-aware reporting
if reporter is None:
+26 -1
View File
@@ -951,4 +951,29 @@ class TestOrchestratorUsesBoundCallback:
# The callables must be exactly the ones the reporter created
assert cb_a in reporter._callables
assert cb_b in reporter._callables
assert cb_b in reporter._callables
class TestDownloadAllBooksAcceptsBookObjects:
"""download_all_books accepts pre-converted Book objects (no double-conversion)."""
def test_book_objects_skip_from_library_row(self):
"""Passing Book objects directly works — no need to convert via from_library_row."""
book_a = Book(title="Book A", authors=["Auth"], narrators=[], isbn="111")
book_b = Book(title="Book B", authors=["Auth"], narrators=[], isbn="222")
books = [book_a, book_b]
downloaded: list[Book] = []
def fake_download_fn(book: Book, progress=None):
downloaded.append(book)
return Path(f"/tmp/{book.isbn}.m4b")
reporter = FakeReporter()
result = download_all_books(
books, workers=1, download_fn=fake_download_fn, reporter=reporter,
)
assert result.downloaded_count == 2
assert result.failed_count == 0
assert downloaded == [book_a, book_b]
+180 -5
View File
@@ -66,11 +66,41 @@ class TestSyncRunExists:
assert result.interrupted is False
class TestSyncRunSelectMode:
"""Select mode (ADR #6) branch point — stub, returns empty result."""
class TestSyncRunSelectModeTTYGuard:
"""Select mode requires interactive terminal — no TTY → fatal_error."""
def test_select_mode_returns_not_implemented_result(self):
"""select_mode=True → empty SyncRunResult (not yet implemented)."""
def test_no_tty_returns_fatal_error(self):
"""select_mode=True + no TTY → SyncRunResult(fatal_error) with clear message."""
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("sys.stdout.isatty", return_value=False),
):
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_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
mock_instance.fetch_library.return_value = [
{"isbn": "9781234567890", "title": "A Book"},
]
mock_history_cls.return_value.is_downloaded.return_value = False
result = sync_run(
verbose=False, limit=0, workers=0, select_mode=True,
)
assert isinstance(result, SyncRunResult)
assert result.fatal_error is not None
assert "--select requires an interactive terminal" in result.fatal_error
def test_all_caught_up_with_select_mode(self):
"""select_mode=True + no new books → 'All caught up!' + exit 0 (same as non-select)."""
with (
patch("librofm_downloader.sync_run.load_config") as mock_config,
patch("librofm_downloader.sync_run.LibroFmSession") as mock_client_cls,
@@ -83,10 +113,45 @@ class TestSyncRunSelectMode:
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
# All books already downloaded
mock_instance.fetch_library.return_value = [
{"isbn": "9781234567890", "title": "A Book"},
]
mock_history_cls.return_value.is_downloaded.return_value = True
result = sync_run(
verbose=False, limit=0, workers=0, select_mode=True,
)
assert isinstance(result, SyncRunResult)
assert result.fatal_error is None
assert result.interrupted is False
assert result.downloaded_count == 0
class TestSyncRunSelectModeEmptySelection:
"""select_books() returns empty → clean exit 0, no downloads attempted."""
def test_empty_selection_returns_clean_result(self):
"""select_books() returns [] → SyncRunResult with no error, no downloads."""
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.selector.select_books", return_value=[]),
patch("sys.stdout.isatty", return_value=True),
):
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_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
mock_instance.fetch_library.return_value = [
{"isbn": "9781234567890", "title": "A Book"},
]
mock_history_cls.return_value.is_downloaded.return_value = False
result = sync_run(
@@ -94,10 +159,120 @@ class TestSyncRunSelectMode:
)
assert isinstance(result, SyncRunResult)
assert result.downloaded_count == 0
assert result.fatal_error is None
assert result.interrupted is False
assert result.downloaded_count == 0
class TestSyncRunSelectModeSelectedFlow:
"""Selected Books flow to orchestrator correctly (no double-conversion)."""
def test_selected_books_passed_to_orchestrator(self):
"""select_books() returns subset → those Books reach download_all_books."""
from librofm_downloader.book import Book
from librofm_downloader.orchestrator import OrchestratorResult
book_a = Book(title="Book A", authors=["Author"], narrators=[], isbn="111")
book_b = Book(title="Book B", authors=["Author"], narrators=[], isbn="222")
# select_books returns only book_a (user deselected book_b)
selected = [book_a]
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.selector.select_books", return_value=selected),
patch("librofm_downloader.sync_run.download_all_books") as mock_download,
patch("librofm_downloader.sync_run.DownloadReporter") as mock_reporter_cls,
patch("sys.stdout.isatty", return_value=True),
):
mock_config.return_value.username = "alice"
mock_config.return_value.password = "secret"
mock_config.return_value.output_dir = "./audiobooks"
mock_config.return_value.format = "m4b_mp3_fallback"
mock_config.return_value.workers = 3
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
mock_instance.fetch_library.return_value = [
{"isbn": "111", "title": "Book A"},
{"isbn": "222", "title": "Book B"},
]
mock_history_cls.return_value.is_downloaded.return_value = False
mock_download.return_value = OrchestratorResult(downloaded_count=1)
result = sync_run(
verbose=False, limit=0, workers=0, select_mode=True,
)
# Verify orchestrator received only the selected Book objects
assert mock_download.called
call_args = mock_download.call_args
raw_books_arg = call_args[1]["raw_books"] if "raw_books" in call_args[1] else call_args[0][0]
assert len(raw_books_arg) == 1
# The argument should be a Book object (not a dict)
assert isinstance(raw_books_arg[0], Book)
assert raw_books_arg[0].isbn == "111"
assert result.downloaded_count == 1
assert result.fatal_error is None
class TestSyncRunSelectModeLimitIgnored:
"""--limit is ignored when --select is active."""
def test_limit_not_applied_with_select_mode(self, capsys):
"""select_mode=True + limit=1 → all books still available for selection."""
from librofm_downloader.book import Book
from librofm_downloader.orchestrator import OrchestratorResult
book_a = Book(title="Book A", authors=["Auth"], narrators=[], isbn="111")
book_b = Book(title="Book B", authors=["Auth"], narrators=[], isbn="222")
book_c = Book(title="Book C", authors=["Auth"], narrators=[], isbn="333")
# select_books returns all 3 (user selected all)
selected = [book_a, book_b, book_c]
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.selector.select_books", return_value=selected),
patch("librofm_downloader.sync_run.download_all_books") as mock_download,
patch("librofm_downloader.sync_run.DownloadReporter") as mock_reporter_cls,
patch("sys.stdout.isatty", return_value=True),
):
mock_config.return_value.username = "alice"
mock_config.return_value.password = "secret"
mock_config.return_value.output_dir = "./audiobooks"
mock_config.return_value.format = "m4b_mp3_fallback"
mock_config.return_value.workers = 3
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
mock_instance.fetch_library.return_value = [
{"isbn": "111", "title": "Book A"},
{"isbn": "222", "title": "Book B"},
{"isbn": "333", "title": "Book C"},
]
mock_history_cls.return_value.is_downloaded.return_value = False
mock_download.return_value = OrchestratorResult(downloaded_count=3)
result = sync_run(
verbose=True, limit=1, workers=0, select_mode=True,
)
# All 3 books should reach the selector (limit not applied)
select_call_args = mock_download.call_args
raw_books_arg = select_call_args[1]["raw_books"] if "raw_books" in select_call_args[1] else select_call_args[0][0]
assert len(raw_books_arg) == 3
# Verbose note should be printed about limit being superseded
output = capsys.readouterr().out
assert "--limit" in output.lower() or "superseded" in output.lower()
class TestSyncRunInterrupted:
"""Ctrl+C / interrupted path returns SyncRunResult(interrupted=True)."""