feat(selector): add interactive book selection module

New selector.py with select_books() and _format_row().
Questionary checkbox prompt, all unchecked by default,
confirmation summary + y/N, original order preservation,
Ctrl+C propagation via unsafe_ask(). 9 tests.

Closes #47
This commit is contained in:
AlexKucera committed 2026-06-06 11:55:08 +02:00
1 parent 48ec81d92d
commit 37f10f9b49
7 files changed
+244 -2

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 --> <!-- write-log: session-log-index -->
| Date | Type | File | Summary | | Date | Type | File | Summary |
|------|------|------|---------| |------|------|------|---------|
| 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-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** | | 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** |
| 2026-06-05 | issue | [20260605-issue43-test-reorganization-cleanup-pass_log.md](docs/devlog/20260605-issue43-test-reorganization-cleanup-pass_log.md) | **Issue #43 Complete:** Test reorganization cleanup. Deleted 13 dup path classes from downloader, moved 2 integration classes progress→sync_run, removed duplicate `TestParallelProgressCallbackWiring`, rescued orphaned method. **−470 net test lines, 374 tests** · **168/168 pass on modified files** · **5/5 AC** | | 2026-06-05 | issue | [20260605-issue43-test-reorganization-cleanup-pass_log.md](docs/devlog/20260605-issue43-test-reorganization-cleanup-pass_log.md) | **Issue #43 Complete:** Test reorganization cleanup. Deleted 13 dup path classes from downloader, moved 2 integration classes progress→sync_run, removed duplicate `TestParallelProgressCallbackWiring`, rescued orphaned method. **−470 net test lines, 374 tests** · **168/168 pass on modified files** · **5/5 AC** |
@@ -51,7 +52,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # GitNexus — Code Intelligence
This project is indexed by GitNexus as **librofm-downloader** (2023 symbols, 3834 relationships, 13 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. 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.
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first. > If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
+9
View File
@@ -6,6 +6,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased] ## [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.
### Fixed ### Fixed
- **downloader:** Fix progress bar exceeding 100% on resumed downloads. - **downloader:** Fix progress bar exceeding 100% on resumed downloads.
+1 -1
View File
@@ -1,7 +1,7 @@
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # GitNexus — Code Intelligence
This project is indexed by GitNexus as **librofm-downloader** (2023 symbols, 3834 relationships, 13 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. 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.
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first. > If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
@@ -0,0 +1,54 @@
# Issue #47: Interactive Book Selection — selector.py Module
> **Date:** 2026-06-06
> **Type:** issue
> **Reference:** [GitHub #47](https://github.com/AlexKucera/librofm-downloader/issues/47)
## Goal
Create `librofm_downloader/selector.py` with `select_books(books) -> list[Book]` — an interactive checkbox prompt using `questionary` that lets users pick which books to download. Includes `_format_row(book, index) -> str` helper for display formatting.
## What Was Done
- Added `questionary>=2.1.1` to `dependencies` in `pyproject.toml`
- Created `librofm_downloader/selector.py` with two functions:
- `_format_row(book, index)` — formats Book into `"N. Title — Author [Series #N]"` display string
- `select_books(books)` — opens questionary checkbox (all unchecked by default), zero-selection message, confirmation summary + y/N prompt, returns selected Books in original input order
- Created `tests/test_selector.py` with 9 TDD tests covering all acceptance criteria
- Used `unsafe_ask()` on the checkbox to propagate `KeyboardInterrupt` (instead of `.ask()` which catches it and returns `None`)
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Use `unsafe_ask()` for checkbox, `.ask()` for confirm | `questionary.Question.ask()` catches `KeyboardInterrupt` and returns `None`. Issue requires Ctrl+C during checkbox to propagate upstream to `sync_run`. Confirm prompt can safely swallow Ctrl+C (returns `None` → falsy → empty list). |
| Map display rows → Book via dict lookup | `questionary.checkbox().ask()` returns the choice strings, not indices. Build a `row_to_book` dict to map chosen strings back to Book objects. |
| Return in original input order via `id(b)` set | User may toggle checkboxes in any order. Filter original list by `id(b) in selected_set` to preserve input ordering. |
| Pin `questionary>=2.1.1` (not `>=1.10`) | `questionary 2.1.0` crashes with `prompt_toolkit>=3.0.50` due to `_fix_unecessary_blank_lines` accessing changed internal layout API (`VSplit.content` removed). Fixed in 2.1.1. |
| Test via `mock.patch("librofm_downloader.selector.questionary")` | Patch at the import site, not globally. Mock `checkbox().unsafe_ask()` and `confirm().ask()` return values to avoid real TUI rendering. Test external behavior (inputs→outputs), not which questionary methods were called. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| `AttributeError: 'VSplit' object has no attribute 'content'` on interactive test | `questionary 2.1.0` incompatible with `prompt_toolkit>=3.0.50`. Internal `_fix_unecessary_blank_lines` accesses removed `VSplit.content` attribute. | Upgraded to `questionary>=2.1.1`, pinned in `pyproject.toml` |
| Test mock returned `["C", "A"]` but impl expected formatted row strings | Mock values must match what `questionary.checkbox().unsafe_ask()` actually returns — the choice strings as provided to `choices=` parameter. | Changed mock to return `["3. C — Author", "1. A — Author"]` matching `_format_row` output |
| 11 pre-existing failures in `test_path.py` | `Config.__init__()` missing `rename_chapters` argument — unrelated to this issue | Not addressed (pre-existing, out of scope) |
## Files Changed
| File | Change Summary |
|------|---------------|
| `pyproject.toml` | Added `questionary>=2.1.1` to `dependencies` |
| `librofm_downloader/selector.py` | New module: `_format_row()` + `select_books()` |
| `tests/test_selector.py` | New test file: 9 tests (3 formatting + 6 selection flow) |
## Open Items & Next Steps
- [ ] Wire `select_books()` into `sync_run.py` pipeline (guarded by `--select` flag) — future issue
- [ ] 11 pre-existing `test_path.py` failures need fixing (Config missing `rename_chapters`)
- [ ] User interactive testing still pending (TUI requires real terminal)
---
*Log written by write-log skill*
+56
View File
@@ -0,0 +1,56 @@
"""Interactive book selection via questionary checkbox prompt.
Public API: select_books(books) -> list[Book]
Internal helper: _format_row(book, index) -> str
"""
import questionary
from librofm_downloader.book import Book
def _format_row(book: Book, index: int) -> str:
"""Format a Book into a display string for the checkbox prompt.
Format: "N. Title — First Author [Series #N]"
Series suffix omitted when absent. Author falls back to "Unknown".
"""
author = book.authors[0] if book.authors else "Unknown"
base = f"{index}. {book.title} — {author}"
if book.series and book.series_num is not None:
base += f" [{book.series} #{book.series_num}]"
return base
def select_books(books: list[Book]) -> list[Book]:
"""Present an interactive checkbox prompt and return selected Books.
Returns selected Books in their original input order.
Returns empty list on zero selection or confirmation rejection.
Propagates KeyboardInterrupt from the checkbox prompt.
"""
rows = [_format_row(b, i + 1) for i, b in enumerate(books)]
chosen = questionary.checkbox(
"Select books to download:",
choices=rows,
).unsafe_ask()
if not chosen:
print("No books selected. Exiting.")
return []
# Map display rows back to Book objects
row_to_book = {row: book for row, book in zip(rows, books)}
selected = [row_to_book[row] for row in chosen]
# Confirmation prompt
print(f"{len(selected)} book(s) selected for download:")
for book in selected:
print(f" - {book.title}")
if not questionary.confirm("Proceed with download?", default=False).ask():
return []
# Return in original input order
selected_set = {id(b) for b in selected}
return [b for b in books if id(b) in selected_set]
+1
View File
@@ -12,6 +12,7 @@ requires-python = ">=3.11"
dependencies = [ dependencies = [
"httpx>=0.27", "httpx>=0.27",
"pyyaml>=6.0", "pyyaml>=6.0",
"questionary>=2.1.1",
"rich>=13.0", "rich>=13.0",
] ]
+121
View File
@@ -0,0 +1,121 @@
"""Tests for selector.py — interactive book selection."""
import unittest.mock as mock
from librofm_downloader.book import Book
from librofm_downloader.selector import _format_row, select_books
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _book(title, authors=None, **kw):
"""Convenience Book factory for tests."""
return Book(
title=title,
authors=authors or ["Author"],
narrators=[],
isbn=kw.pop("isbn", "0000"),
**kw,
)
# ---------------------------------------------------------------------------
# _format_row
# ---------------------------------------------------------------------------
def test_format_row_with_series():
book = Book(
title="The Way of Kings",
authors=["Brandon Sanderson"],
narrators=["Michael Kramer"],
isbn="9780765365279",
series="Stormlight Archive",
series_num=1,
)
assert _format_row(book, 3) == "3. The Way of Kings — Brandon Sanderson [Stormlight Archive #1]"
def test_format_row_without_series():
book = Book(
title="Project Hail Mary",
authors=["Andy Weir"],
narrators=["Ray Porter"],
isbn="9780593135204",
)
assert _format_row(book, 1) == "1. Project Hail Mary — Andy Weir"
def test_format_row_no_authors_falls_back_to_unknown():
book = Book(
title="Mystery Book",
authors=[],
narrators=[],
isbn="0000000000",
)
assert _format_row(book, 5) == "5. Mystery Book — Unknown"
# ---------------------------------------------------------------------------
# select_books
# ---------------------------------------------------------------------------
def test_select_books_returns_selected_in_original_order():
books = [_book("A"), _book("B"), _book("C"), _book("D")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.return_value = ["3. C — Author", "1. A — Author"]
q.confirm.return_value.ask.return_value = True
result = select_books(books)
assert [b.title for b in result] == ["A", "C"]
def test_select_books_returns_empty_on_zero_selection(capsys):
books = [_book("A"), _book("B")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.return_value = []
result = select_books(books)
assert result == []
assert "No books selected" in capsys.readouterr().out
def test_select_books_returns_empty_on_confirm_rejection():
books = [_book("A"), _book("B")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.return_value = ["1. A — Author"]
q.confirm.return_value.ask.return_value = False # N / bare Enter
result = select_books(books)
assert result == []
def test_select_books_returns_books_on_confirm_acceptance(capsys):
books = [_book("Alpha"), _book("Beta")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.return_value = ["2. Beta — Author"]
q.confirm.return_value.ask.return_value = True # y/Y
result = select_books(books)
assert [b.title for b in result] == ["Beta"]
out = capsys.readouterr().out
assert "1 book(s) selected" in out
assert "- Beta" in out
def test_select_books_propagates_keyboard_interrupt():
books = [_book("A")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.side_effect = KeyboardInterrupt
try:
select_books(books)
except KeyboardInterrupt:
pass # expected
else:
raise AssertionError("Should have propagated KeyboardInterrupt")
def test_select_books_single_book_library():
books = [_book("Solo")]
with mock.patch("librofm_downloader.selector.questionary") as q:
q.checkbox.return_value.unsafe_ask.return_value = ["1. Solo — Author"]
q.confirm.return_value.ask.return_value = True
result = select_books(books)
assert [b.title for b in result] == ["Solo"]