refactor(sync-run): add DI seams and extract helpers

Add 4 injectable parameters (session, history, reporter,
download_all_fn) to sync_run() with backward-compatible defaults.
Extract _print_verbose_config() and _resolve_history_path() helpers.
Refactor _make_download_fn() to take explicit params instead of
closing over enclosing scope.

Tests can now pass fakes via parameters instead of mock.patch.

Closes #44
This commit is contained in:
AlexKucera committed 2026-06-05 22:28:37 +02:00
1 parent a66c98d973
commit 5cc3fce0a3
4 files changed
+526 -54

No files matched your search

+70 -54
View File
@@ -30,6 +30,38 @@ from librofm_downloader.session import AuthError, LibroFmSession
console = Console()
def _print_verbose_config(config, history_path: str, secrets_path: str | None) -> None:
"""Print resolved config details when verbose mode is on."""
console.print("[dim]\u2500\u2500 config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500[/dim]")
cfg_display = config._config_path if config._config_path else "(built-in defaults)"
secrets_display = secrets_path
if secrets_path is None:
resolved_secrets = _resolve_config_file("secrets.yaml")
secrets_display = resolved_secrets or "(not found)"
console.print(f" config: {cfg_display}")
console.print(f" secrets: {secrets_display}")
console.print(f" history: {history_path}")
console.print(f" format: {config.format}")
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}")
def _resolve_history_path(history_path: str | None) -> str:
"""Resolve history file path: explicit \u2192 XDG search \u2192 XDG default."""
if history_path is not None:
return history_path
resolved = _resolve_config_file("download_history.json")
if resolved is not None:
return str(resolved)
from os import environ
home = Path(environ.get("HOME", "~")).expanduser()
xdg_dir = home / ".config" / "librofm-downloader"
xdg_dir.mkdir(parents=True, exist_ok=True)
return str(xdg_dir / "download_history.json")
@dataclass(frozen=True)
class SyncRunResult:
"""Structured result from a full sync run.
@@ -63,6 +95,10 @@ def sync_run(
rename_chapters: bool = False,
*,
select_mode: bool = False,
session: LibroFmSession | None = None,
history: DownloadHistory | None = None,
reporter: DownloadReporter | None = None,
download_all_fn: Callable | None = None,
) -> SyncRunResult:
"""Main pipeline: load config → auth → fetch library → filter → download → summary.
@@ -81,17 +117,7 @@ def sync_run(
try:
# 0. Resolve history path (XDG → CWD, default to XDG location)
if history_path is None:
resolved = _resolve_config_file("download_history.json")
if resolved is not None:
history_path = str(resolved)
else:
from os import environ
home = Path(environ.get("HOME", "~")).expanduser()
xdg_dir = home / ".config" / "librofm-downloader"
xdg_dir.mkdir(parents=True, exist_ok=True)
history_path = str(xdg_dir / "download_history.json")
history_path = _resolve_history_path(history_path)
# 1. Load config
try:
@@ -110,22 +136,7 @@ def sync_run(
return SyncRunResult(fatal_error=f"Config error: {exc}")
if verbose:
console.print("[dim]── config ──────────────────────────────────────[/dim]")
cfg_display = config._config_path if config._config_path else "(built-in defaults)"
# Determine resolved secrets path
secrets_display = secrets_path
if secrets_path is None:
resolved_secrets = _resolve_config_file("secrets.yaml")
secrets_display = resolved_secrets or "(not found)"
console.print(f" config: {cfg_display}")
console.print(f" secrets: {secrets_display}")
console.print(f" history: {history_path}")
console.print(f" format: {config.format}")
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}")
_print_verbose_config(config, history_path, secrets_path)
# Resolve workers: CLI flag (>0?) → config.workers → default 3
resolved_workers = workers if workers > 0 else config.workers
@@ -135,23 +146,26 @@ def sync_run(
# Resolve rename_chapters: CLI flag (True?) → config.rename_chapters
resolved_rename_chapters = rename_chapters or config.rename_chapters
# 2. Authenticate
if verbose:
console.print("[dim]── auth ────────────────────────────────────────[/dim]")
# 2. Authenticate (or use injected session)
if session is not None:
client = session
else:
if verbose:
console.print("[dim]── auth ────────────────────────────────────────[/dim]")
client = LibroFmSession(
username=config.username,
password=config.password,
)
client = LibroFmSession(
username=config.username,
password=config.password,
)
try:
client.authenticate()
except AuthError as exc:
console.print(f"[red]Authentication failed:[/red] {exc}")
return SyncRunResult(fatal_error=f"Authentication failed: {exc}")
try:
client.authenticate()
except AuthError as exc:
console.print(f"[red]Authentication failed:[/red] {exc}")
return SyncRunResult(fatal_error=f"Authentication failed: {exc}")
if verbose:
console.print(" [green]✓[/green] authenticated")
if verbose:
console.print(" [green]✓[/green] authenticated")
# 3. Fetch library
if verbose:
@@ -170,7 +184,8 @@ def sync_run(
if verbose:
console.print("[dim]── filtering ───────────────────────────────────[/dim]")
history = DownloadHistory(history_path)
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:
new_books = new_books[:limit]
@@ -189,33 +204,33 @@ def sync_run(
return SyncRunResult()
# 6. Download loop with TTY-aware reporting
reporter = DownloadReporter()
if reporter is None:
reporter = DownloadReporter()
cancel_event = threading.Event()
# cancel_event passed explicitly via closure to download_book() (Issue #39)
console.print(f"\n[bold]{len(new_books)} book(s) to download:[/bold]\n")
# --- Download loop (parallel via orchestrator — Issue #16) ---
def _make_download_fn():
_rc = resolved_rename_chapters # capture resolved value
_ce = cancel_event # capture for closure (Issue #39 — explicit param, not via reporter)
def _make_download_fn(
_config, _client, _history, _reporter, _cancel_event, _rename_chapters,
):
def _download_fn(
book: Book, *, progress: Callable[[int], None] | None = None
):
# Build output plan for this book (paths + format strategy)
plan = resolve_output_plan(
book,
config.output_dir,
config=config,
format_strategy=config.format,
_config.output_dir,
config=_config,
format_strategy=_config.format,
)
result = download_book(book, client, plan, reporter, progress=progress, rename_chapters=_rc, cancel_event=_ce)
result = download_book(book, _client, plan, _reporter, progress=progress, rename_chapters=_rename_chapters, cancel_event=_cancel_event)
# Write history as caller (no longer inside download_book)
if result.status == "downloaded":
_write_history(
history, book, result.format or "m4b", str(result.path)
_history, book, result.format or "m4b", str(result.path)
)
# Return Path | None for backward compat with orchestrator
@@ -225,10 +240,11 @@ def sync_run(
return _download_fn
result = download_all_books(
_download_all = download_all_fn or download_all_books
result = _download_all(
new_books,
workers=resolved_workers,
download_fn=_make_download_fn(),
download_fn=_make_download_fn(config, client, history, reporter, cancel_event, resolved_rename_chapters),
reporter=reporter,
cancel_event=cancel_event,
)