From 01b14f19265c3074f474345f763f677f94f5ed46 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Thu, 4 Jun 2026 10:32:31 +0200 Subject: [PATCH] feat(cli): wire XDG path resolution into CLI layer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit History path now defaults to None and resolves via XDG→CWD search, falling back to XDG location when not found. Missing config message lists searched paths. --verbose shows resolved paths for all three files. Explicit --config/--secrets/--history bypass resolution. Closes #23 --- AGENTS.md | 1 + CHANGELOG.md | 6 + ...ssue23-wire-xdg-resolution-into-cli_log.md | 52 ++++ librofm_downloader/cli.py | 41 +++- tests/test_cli.py | 225 +++++++++++++++++- 5 files changed, 315 insertions(+), 10 deletions(-) create mode 100644 docs/devlog/20260604-issue23-wire-xdg-resolution-into-cli_log.md diff --git a/AGENTS.md b/AGENTS.md index fe96f18..07325e0 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-04 | issue | [20260604-issue23-wire-xdg-resolution-into-cli_log.md](docs/devlog/20260604-issue23-wire-xdg-resolution-into-cli_log.md) | **Issue #23 Complete:** Wire XDG resolution into CLI — history path XDG default, verbose resolved paths, searched-paths message. **7 new tests, 188 total** · **10/10 AC** | | 2026-06-04 | issue | [20260604-issue22-xdg-config-path-resolution-with-cwd-fallback_log.md](docs/devlog/20260604-issue22-xdg-config-path-resolution-with-cwd-fallback_log.md) | **Issue #22 Complete:** XDG→CWD path resolution, `load_config(None, None)` search, missing-config notice, OS→domain error wrapping. **9 new tests, 181 total** · **8/8 AC** | | 2026-06-03 | issue | [20260603-issue10-documentation-site-and-readme_log.md](docs/devlog/20260603-issue10-documentation-site-and-readme_log.md) | **Issue #10 Complete:** MkDocs site (8 pages) + polished README. Material theme, flat URLs. **11/11 AC** · **172 tests pass** | | 2026-06-03 | slice | [20260603-slice-6b-summary-exit-codes-and-integration-tests-issue9_log.md](docs/devlog/20260603-slice-6b-summary-exit-codes-and-integration-tests-issue9_log.md) | **Issue #9 Complete:** Enhanced summary (failed/skipped book details) + graceful Ctrl+C (exit 130) + 3 integration tests. **12 new tests, 168 total** · **15/15 AC** | diff --git a/CHANGELOG.md b/CHANGELOG.md index d72f622..1b5bf48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 (prints notice, uses built-in defaults); missing secrets.yaml raises domain error listing searched paths. All OS exceptions wrapped as `ConfigError`. XDG directory auto-created on demand. +- **cli (closes #23):** Wire XDG path resolution into CLI layer. + History path defaults to `None` (resolves XDG → CWD, falls back to XDG + location). Missing config message now lists searched paths. `--verbose` + shows resolved file paths for config, secrets, and history. Explicit + `--config`/`--secrets`/`--history` flags bypass search. Clean exit 1 + with no traceback when secrets missing from all locations. ### Documentation - **docs site (closes #10):** MkDocs documentation with 8 pages — Quickstart, diff --git a/docs/devlog/20260604-issue23-wire-xdg-resolution-into-cli_log.md b/docs/devlog/20260604-issue23-wire-xdg-resolution-into-cli_log.md new file mode 100644 index 0000000..50f2393 --- /dev/null +++ b/docs/devlog/20260604-issue23-wire-xdg-resolution-into-cli_log.md @@ -0,0 +1,52 @@ +# Issue #23: Wire XDG Path Resolution into CLI Layer + +> **Date:** 2026-06-04 +> **Type:** issue +> **Reference:** [GitHub #23](https://github.com/AlexKucera/librofm-downloader/issues/23) · Parent [#21](https://github.com/AlexKucera/librofm-downloader/issues/21) + +## Goal + +Wire the path resolver from Issue #22 into the CLI layer so that running `librofm-downloader` with no flags finds config/secrets/history via XDG→CWD search. History path defaults to XDG location. Missing config prints searched paths. Verbose mode shows resolved file locations. Explicit CLI flags bypass search entirely. + +## What Was Done + +- Changed `run()` parameter `history_path` default from `"download_history.json"` to `None` so the resolver activates +- Added history path resolution block in `run()`: calls `_resolve_config_file("download_history.json")` (XDG→CWD search); falls back to `~/.config/librofm-downloader/download_history.json` if not found anywhere +- Imported `_resolve_config_file` from `config.py` into `cli.py` +- Enhanced missing-config message to list searched paths: `"config.yaml not found in ~/.config/librofm-downloader/config.yaml → ./config.yaml. Using built-in defaults."` +- Added verbose resolved-paths display after config load showing `config`, `secrets`, `history` with actual resolved filesystem paths (not input args) +- Changed argparse `--history` default from `"download_history.json"` to `None` with updated help text +- 7 new tests across 3 test classes: `TestCLIHistoryResolution` (3), `TestCLIConfigResolutionMessages` (2), `TestCLIMissingFilesErrors` (2) +- **188 tests pass** (was 181 → +7 new) +- **All 10 acceptance criteria met** + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| History resolves before config load | History path is needed by `DownloadHistory.__init__()`, which happens before downloads; resolving early avoids expanding `load_config`'s responsibility | +| History defaults to XDG location (not CWD) when not found | Consistent with XDG-first resolution strategy; CWD is only a read fallback, not a default-write location | +| Verbose block moved to after config load | The actual resolved paths aren't known until after `load_config` runs and `_resolve_config_file` has been called; showing paths before resolution would display `None` | +| `_resolve_config_file` reused for history | Same XDG→CWD search logic; no need for a separate history resolver | +| Verbose re-calls `_resolve_config_file` for secrets display | At that point `secrets_path` is already consumed by `load_config`; re-resolving is cheap (two `is_file()` checks) and avoids threading the resolved path through | + +## Gotchas & Fixes + +*None* — all 7 vertical slices passed cleanly on first implementation attempt. No test failures requiring iteration. + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `librofm_downloader/cli.py` | `history_path` default → `None`; XDG resolution for history path; verbose resolved-paths display; argparse `--history` default → `None`; enhanced missing-config message with searched paths; imported `_resolve_config_file` | +| `tests/test_cli.py` | 7 new tests: `TestCLIHistoryResolution` (3), `TestCLIConfigResolutionMessages` (2), `TestCLIMissingFilesErrors` (2) | + +## Open Items & Next Steps + +- [ ] Update CLI `--help` text to mention XDG search behavior for `--history` +- [ ] Update README/docs to document XDG config location and history defaults +- [ ] GitNexus index needs rebuild (`npx gitnexus analyze`) after these changes + +--- + +*Log written by write-log skill* diff --git a/librofm_downloader/cli.py b/librofm_downloader/cli.py index 77895d5..a798cb2 100644 --- a/librofm_downloader/cli.py +++ b/librofm_downloader/cli.py @@ -5,7 +5,7 @@ from pathlib import Path from rich.console import Console -from librofm_downloader.config import load_config, ConfigError +from librofm_downloader.config import load_config, ConfigError, _resolve_config_file from librofm_downloader.client import LibroFmClient, AuthError from librofm_downloader.history import DownloadHistory from librofm_downloader.downloader import Book, download_book @@ -17,7 +17,7 @@ console = Console() def run( config_path: str | None = None, secrets_path: str | None = None, - history_path: str = "download_history.json", + history_path: str | None = None, verbose: bool = False, limit: int = 0, ) -> int: @@ -34,22 +34,45 @@ def run( """ try: - if verbose: - console.print("[dim]── config ──────────────────────────────────────[/dim]") - console.print(f" config: {config_path}") - console.print(f" secrets: {secrets_path}") - console.print(f" history: {history_path}") + # 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") # 1. Load config try: config = load_config(config_path, secrets_path) if config._config_path is None: - console.print("[yellow]config.yaml not found. Using built-in defaults.[/yellow]") + searched = [ + "~/.config/librofm-downloader/config.yaml", + "./config.yaml", + ] + console.print( + f"[yellow]config.yaml not found in {' → '.join(searched)}. " + f"Using built-in defaults.[/yellow]" + ) except ConfigError as exc: console.print(f"[red]Config error:[/red] {exc}") return 1 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}") @@ -192,7 +215,7 @@ if __name__ == "__main__": parser = argparse.ArgumentParser(description="Download audiobooks from Libro.fm") parser.add_argument("--config", default=None, help="Path to config.yaml (default: search XDG then CWD)") parser.add_argument("--secrets", default=None, help="Path to secrets.yaml (default: search XDG then CWD)") - parser.add_argument("--history", default="download_history.json", help="Path to download history JSON") + parser.add_argument("--history", default=None, help="Path to download history JSON (default: search XDG then CWD)") parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output (URLs, sizes, tracebacks)") parser.add_argument( "--limit", diff --git a/tests/test_cli.py b/tests/test_cli.py index 93548a1..bf68b1b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -605,4 +605,227 @@ class TestAllBooksFailExitCode: # Individual failures are NOT fatal → exit 0 assert exit_code == 0 - assert mock_download.call_count == 3 \ No newline at end of file + assert mock_download.call_count == 3 + + +# --------------------------------------------------------------------------- +# Issue #23: XDG path resolution wired into CLI +# --------------------------------------------------------------------------- + + +class TestCLIHistoryResolution: + """History path resolves via XDG → CWD when not explicitly provided.""" + + def test_history_defaults_to_xdg_location(self, tmp_path, monkeypatch): + """run() with history_path=None → history resolves to XDG path.""" + xdg_dir = tmp_path / ".config" / "librofm-downloader" + xdg_dir.mkdir(parents=True) + (xdg_dir / "download_history.json").write_text("{}") + + cwd = tmp_path / "cwd" + cwd.mkdir() + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.chdir(cwd) + + with ( + patch("librofm_downloader.cli.load_config") as mock_config, + patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, + ): + mock_config.return_value.username = "alice" + mock_config.return_value.password = "secret" + mock_config.return_value._config_path = None + mock_config.return_value.output_dir = "./audiobooks" + + mock_instance = mock_client_cls.return_value + mock_instance.authenticate.return_value = "tok" + mock_instance.fetch_library.return_value = [] + + exit_code = run( + config_path=None, + secrets_path=None, + history_path=None, + ) + + assert exit_code == 0 + + # Verify DownloadHistory received the XDG path + history_arg = mock_history_cls.call_args[0][0] + assert "librofm-downloader" in str(history_arg) + assert "download_history.json" in str(history_arg) + + def test_history_defaults_to_xdg_when_not_found_anywhere(self, tmp_path, monkeypatch): + """No download_history.json anywhere → defaults to XDG location.""" + cwd = tmp_path / "cwd" + cwd.mkdir() + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.chdir(cwd) + + with ( + patch("librofm_downloader.cli.load_config") as mock_config, + patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, + ): + mock_config.return_value.username = "alice" + mock_config.return_value.password = "secret" + mock_config.return_value._config_path = None + mock_config.return_value.output_dir = "./audiobooks" + + mock_instance = mock_client_cls.return_value + mock_instance.authenticate.return_value = "tok" + mock_instance.fetch_library.return_value = [] + + exit_code = run(history_path=None) + + assert exit_code == 0 + + # Should default to XDG location even though file doesn't exist + history_arg = mock_history_cls.call_args[0][0] + assert "librofm-downloader" in str(history_arg) + assert ".config" in str(history_arg) + assert "download_history.json" in str(history_arg) + + def test_explicit_history_path_bypasses_resolution(self, tmp_path, monkeypatch): + """Explicit --history flag uses the exact path provided.""" + with ( + patch("librofm_downloader.cli.load_config") as mock_config, + patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls, + ): + mock_config.return_value.username = "alice" + mock_config.return_value.password = "secret" + mock_config.return_value._config_path = None + mock_config.return_value.output_dir = "./audiobooks" + + mock_instance = mock_client_cls.return_value + mock_instance.authenticate.return_value = "tok" + mock_instance.fetch_library.return_value = [] + + exit_code = run(history_path="/custom/my_history.json") + + assert exit_code == 0 + + history_arg = mock_history_cls.call_args[0][0] + assert str(history_arg) == "/custom/my_history.json" + + + +class TestCLIConfigResolutionMessages: + """CLI messages about config resolution.""" + + def test_missing_config_message_includes_searched_paths(self, tmp_path, monkeypatch, capsys): + """config.yaml not found → message lists XDG and CWD paths.""" + xdg_dir = tmp_path / ".config" / "librofm-downloader" + xdg_dir.mkdir(parents=True) + (xdg_dir / "secrets.yaml").write_text( + "librofm:\n username: alice\n password: secret\n" + ) + + cwd = tmp_path / "cwd" + cwd.mkdir() + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.chdir(cwd) + + with ( + patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.download_book"), + ): + mock_instance = mock_client_cls.return_value + mock_instance.authenticate.return_value = "tok" + mock_instance.fetch_library.return_value = [] + + exit_code = run(config_path=None, secrets_path=None, history_path=None) + + assert exit_code == 0 + output = capsys.readouterr().out + assert "config.yaml not found" in output + assert ".config" in output or "librofm-downloader" in output + assert "Using built-in defaults" in output + + def test_verbose_shows_resolved_paths(self, tmp_path, monkeypatch, capsys): + """--verbose shows the actual resolved file paths after loading config.""" + xdg_dir = tmp_path / ".config" / "librofm-downloader" + xdg_dir.mkdir(parents=True) + (xdg_dir / "secrets.yaml").write_text( + "librofm:\n username: alice\n password: secret\n" + ) + (xdg_dir / "download_history.json").write_text("{}") + + cwd = tmp_path / "cwd" + cwd.mkdir() + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.chdir(cwd) + + with ( + patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.download_book"), + ): + mock_instance = mock_client_cls.return_value + mock_instance.authenticate.return_value = "tok" + mock_instance.fetch_library.return_value = [] + + exit_code = run( + config_path=None, + secrets_path=None, + history_path=None, + verbose=True, + ) + + assert exit_code == 0 + output = capsys.readouterr().out.lower() + # Verbose should show the resolved XDG paths + assert "secrets" in output + assert "history" in output + assert "librofm-downloader" in output + + + +class TestCLIMissingFilesErrors: + """Error handling when files are missing.""" + + def test_empty_home_clean_secrets_error(self, tmp_path, monkeypatch, capsys): + """No files anywhere → clean error about missing secrets, exit 1.""" + cwd = tmp_path / "cwd" + cwd.mkdir() + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.chdir(cwd) + + exit_code = run(config_path=None, secrets_path=None, history_path=None) + + assert exit_code == 1 + output = capsys.readouterr().out + assert "secrets.yaml" in output + assert "Traceback" not in output + + def test_only_secrets_in_xdg_works(self, tmp_path, monkeypatch, capsys): + """Secrets in XDG only → defaults work, 'using built-in defaults' message visible.""" + xdg_dir = tmp_path / ".config" / "librofm-downloader" + xdg_dir.mkdir(parents=True) + (xdg_dir / "secrets.yaml").write_text( + "librofm:\n username: alice\n password: secret\n" + ) + + cwd = tmp_path / "cwd" + cwd.mkdir() + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.chdir(cwd) + + with ( + patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls, + patch("librofm_downloader.cli.download_book"), + ): + mock_instance = mock_client_cls.return_value + mock_instance.authenticate.return_value = "tok" + mock_instance.fetch_library.return_value = [] + + exit_code = run(config_path=None, secrets_path=None, history_path=None) + + assert exit_code == 0 + output = capsys.readouterr().out + assert "Using built-in defaults" in output \ No newline at end of file