feat(config): add XDG path resolution with CWD fallback

Add _resolve_config_file() searching ~/.config/librofm-downloader/
then CWD. Wire into load_config() so None triggers search. Missing
config.yaml is non-fatal (prints notice, uses defaults); missing
secrets.yaml raises ConfigError listing searched paths. All OS
exceptions wrapped as domain errors. XDG dir auto-created.

Closes #22
This commit is contained in:
AlexKucera committed 2026-06-04 10:00:52 +02:00
1 parent 090132f39e
commit 3ba9f25903
6 files changed
+308 -14

No files matched your search

+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-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** |
| 2026-06-03 | issue | [20260603-output-polish-progress-bars-and-failure-isolation-issue8_log.md](docs/devlog/20260603-output-polish-progress-bars-and-failure-isolation-issue8_log.md) | **Issue #8 Complete:** TTY-aware download reporting — rich progress bars (interactive) + plain log lines (cron). Per-book failure isolation. Content-Length → live %/ETA/speed. **18 new tests, 156 total** · **8/8 AC** |
+8
View File
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- **config (closes #22):** XDG config path resolution with CWD fallback.
`_resolve_config_file()` searches `~/.config/librofm-downloader/` then CWD.
`load_config(None, None)` triggers search; missing config.yaml is non-fatal
(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.
### Documentation
- **docs site (closes #10):** MkDocs documentation with 8 pages — Quickstart,
Configuration Reference, Secrets, Path Patterns, Format Strategies, CLI Usage,
@@ -0,0 +1,63 @@
# Issue #22: XDG config path resolution with CWD fallback
> **Date:** 2026-06-04
> **Type:** issue
> **Reference:** [GitHub #22](https://github.com/AlexKucera/librofm-downloader/issues/22) · Parent [#21](https://github.com/AlexKucera/librofm-downloader/issues/21)
## Goal
Build a path resolution engine for config files that searches `~/.config/librofm-downloader/` (XDG) first, then falls back to CWD. Wire it into `load_config()` so passing `None` for either path triggers search. Missing `config.yaml` is non-fatal (defaulted Config). Missing `secrets.yaml` is fatal (domain error listing searched paths). All OS exceptions caught internally → domain errors only. CLI should print a notice when running on built-in defaults.
## What Was Done
- Added `_resolve_config_file(filename)` to `config.py` — searches XDG (`~/.config/librofm-downloader/`) then CWD, auto-creates XDG dir, returns `Path | None`
- Modified `load_config()` signature to accept `Path | str | None` for both params; `None` triggers resolver
- Missing `config.yaml` path → `config_yaml = {}` (all fields get built-in defaults from `.get()` calls)
- Missing `secrets.yaml` path → raises `ConfigError` listing both searched locations in order
- All `FileNotFoundError`/`OSError` from file I/O caught and re-raised as `ConfigError`
- Added `_config_path: Path | None = None` field to `Config` dataclass — sentinel for "used defaults"
- CLI `run()` and argparse defaults changed from `"config.yaml"`/`"secrets.yaml"` to `None` so resolver activates
- CLI prints `[yellow]config.yaml not found. Using built-in defaults.[/yellow]` when `_config_path is None`
- 9 new tests across `TestResolveConfigFile` (5) and `TestLoadConfigWithResolution` (4)
- **181 total tests pass** (was 172)
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| `_config_path` private field on `Config` for defaults signal | Non-breaking: existing code ignores it, CLI can check it. Frozen dataclass prevents mutation. Alternatives: return tuple (breaks signature), raise warning (invisible). |
| `ConfigError` for missing secrets (not `FileNotFoundError`) | AC requires no OS exceptions leak to callers. Domain error lists searched paths so user knows where to put the file. |
| Missing config → empty dict, not exception | AC says non-fatal. All `Config` fields have sensible defaults via `.get()`. Credentials come from secrets only. |
| CLI defaults to `None` (not filename strings) | Original defaults of `"config.yaml"` bypassed the resolver entirely — `load_config` only searches when it receives `None`. |
| XDG dir auto-created on every resolution call | AC requires it. `mkdir(parents=True, exist_ok=True)` is idempotent and cheap. Ensures the dir exists for users to drop files into. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| `ConfigError` not imported in test file | New test class used `ConfigError` but only subclasses were imported | Added `ConfigError` to the import block |
| Test created `config/` instead of `.config/` | Test XDG path used `"config"` without leading dot, but implementation uses `.config` | Fixed test to use `tmp_path / ".config" / "librofm-downloader"` |
| `environ.get("HOME", "~").expanduser()` — `AttributeError` | Called `.expanduser()` on a `str`, not `Path` | Changed to `Path(environ.get("HOME", "~")).expanduser()` |
| `mkdir()` called after `chdir()` in test | Test ordered `monkeypatch.chdir()` before creating the CWD directory | Reordered: `mkdir()` first, then `chdir()` |
| CLI showed `Config error: Cannot read config file 'config.yaml': [Errno 2]` | CLI argparse defaults were `"config.yaml"` strings — `load_config` received a path, not `None`, so resolver never ran | Changed CLI and argparse defaults to `None` |
| Duplicate `InvalidFormatError` class + orphaned docstring | Edit operation merged old code into new location | Removed duplicate, kept single definition |
| Extra `"` in docstring → `SyntaxError` | Corrupted edit left 4 closing quotes instead of 3 | Fixed to `"""Invalid audio format value."""` |
## Files Changed
| File | Change Summary |
|------|---------------|
| `librofm_downloader/config.py` | Added `_resolve_config_file()`, modified `load_config()` to accept `None`, added `_config_path` field to `Config`, wrapped I/O in try/except for domain errors |
| `librofm_downloader/cli.py` | Changed `run()` and argparse defaults from `"config.yaml"`/`"secrets.yaml"` to `None`, added "using built-in defaults" notice |
| `tests/test_config.py` | Added `ConfigError` + `_resolve_config_file` imports, 9 new tests in `TestResolveConfigFile` and `TestLoadConfigWithResolution` |
## Open Items & Next Steps
- [ ] Update CLI `--help` text to mention XDG search behavior
- [ ] Consider adding `XDG_CONFIG_HOME` override (currently hardcoded to `~/.config`)
- [ ] Update README/docs to document XDG config location and CWD fallback
- [ ] GitNexus index needs rebuild (`npx gitnexus analyze`) after these changes
---
*Log written by write-log skill*
+6 -4
View File
@@ -15,8 +15,8 @@ console = Console()
def run(
config_path: str = "config.yaml",
secrets_path: str = "secrets.yaml",
config_path: str | None = None,
secrets_path: str | None = None,
history_path: str = "download_history.json",
verbose: bool = False,
limit: int = 0,
@@ -43,6 +43,8 @@ def run(
# 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]")
except ConfigError as exc:
console.print(f"[red]Config error:[/red] {exc}")
return 1
@@ -188,8 +190,8 @@ if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Download audiobooks from Libro.fm")
parser.add_argument("--config", default="config.yaml", help="Path to config.yaml")
parser.add_argument("--secrets", default="secrets.yaml", help="Path to secrets.yaml")
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("-v", "--verbose", action="store_true", help="Verbose output (URLs, sizes, tracebacks)")
parser.add_argument(
+73 -9
View File
@@ -16,6 +16,7 @@ class Config:
output_dir: str
download_extras: bool
download_covers: bool
_config_path: Path | None = None # None = defaulted (file missing)
class ConfigError(Exception):
@@ -34,19 +35,82 @@ class InvalidFormatError(ConfigError):
"""Invalid audio format value."""
def load_config(config_path: Path | str, secrets_path: Path | str) -> Config:
"""Load config.yaml + secrets.yaml, merge, validate, and return Config."""
config_path = Path(config_path)
secrets_path = Path(secrets_path)
def _resolve_config_file(filename: str) -> Path | None:
"""Resolve a config file by searching XDG then CWD.
with config_path.open() as f:
config_yaml = yaml.safe_load(f) or {}
Searches ``~/.config/librofm-downloader/`` first, then falls back to
the current working directory. Auto-creates the XDG parent directory
on demand.
Returns:
Resolved :class:`Path` if found, ``None`` if absent from both locations.
"""
from os import environ # noqa: S405 – we only read HOME
home = Path(environ.get("HOME", "~")).expanduser()
xdg_path = home / ".config" / "librofm-downloader" / filename
xdg_path.parent.mkdir(parents=True, exist_ok=True)
if xdg_path.is_file():
return xdg_path.resolve()
cwd_path = Path(filename).resolve()
if cwd_path.is_file():
return cwd_path
return None
def load_config(
config_path: Path | str | None,
secrets_path: Path | str | None,
) -> Config:
"""Load config.yaml + secrets.yaml, merge, validate, and return Config.
When either path is ``None``, searches XDG then CWD via
:func:`_resolve_config_file`. Missing config.yaml is non-fatal
(returns fully-defaulted :class:`Config`). Missing secrets.yaml is
fatal (raises :class:`ConfigError`).
"""
# Resolve None paths → search XDG then CWD
if config_path is None:
config_path = _resolve_config_file("config.yaml")
if secrets_path is None:
secrets_path = _resolve_config_file("secrets.yaml")
# Load config.yaml (non-fatal if missing)
config_yaml: dict = {}
if config_path is not None:
try:
with Path(config_path).open() as f:
config_yaml = yaml.safe_load(f) or {}
except (FileNotFoundError, OSError) as exc:
raise ConfigError(
f"Cannot read config file '{config_path}': {exc}"
) from exc
# Reject credentials in config.yaml
_check_no_credentials_in_config(config_yaml)
with secrets_path.open() as f:
secrets_yaml = yaml.safe_load(f) or {}
# Load secrets.yaml (fatal if missing)
if secrets_path is None:
searched = [
"~/.config/librofm-downloader/secrets.yaml",
"./secrets.yaml",
]
raise ConfigError(
f"Missing secrets.yaml. Searched: {' → '.join(searched)}. "
f"Create one with your Libro.fm username and password."
)
try:
with Path(secrets_path).open() as f:
secrets_yaml = yaml.safe_load(f) or {}
except (FileNotFoundError, OSError) as exc:
raise ConfigError(
f"Cannot read secrets file '{secrets_path}': {exc}"
) from exc
# Deep-merge secrets over config
merged = _deep_merge(config_yaml, secrets_yaml)
@@ -66,9 +130,9 @@ def load_config(config_path: Path | str, secrets_path: Path | str) -> Config:
output_dir=librofm.get("output_dir", "./audiobooks"),
download_extras=librofm.get("download_extras", True),
download_covers=librofm.get("download_covers", True),
_config_path=config_path,
)
def _deep_merge(base: dict, override: dict) -> dict:
"""Recursively merge override into base. Override wins on conflict."""
result = base.copy()
+157 -1
View File
@@ -6,6 +6,12 @@ import pytest
from librofm_downloader.config import (
load_config,
_resolve_config_file,
Config,
ConfigError,
CredentialsInConfigError,
load_config,
_resolve_config_file,
Config,
CredentialsInConfigError,
MissingFieldError,
@@ -230,4 +236,154 @@ class TestEdgeCases:
)
# config_minimal has no format, so it gets default
# We just verify it doesn't raise for valid formats
assert config.format in ("m4b_mp3_fallback", "mp3_only", "m4b_only")
assert config.format in ("m4b_mp3_fallback", "mp3_only", "m4b_only")
class TestResolveConfigFile:
"""XDG-then-CWD path resolution for config files."""
def test_returns_path_when_file_in_xdg(self, tmp_path, monkeypatch):
"""File found in XDG dir → returns resolved Path."""
xdg_dir = tmp_path / ".config" / "librofm-downloader"
xdg_dir.mkdir(parents=True)
(xdg_dir / "config.yaml").write_text("librofm:\n format: m4b_only\n")
(tmp_path / "cwd").mkdir(exist_ok=True)
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(tmp_path / "cwd") # CWD has no file
result = _resolve_config_file("config.yaml")
assert result is not None
assert result.name == "config.yaml"
assert "librofm-downloader" in str(result)
def test_returns_path_when_file_only_in_cwd(self, tmp_path, monkeypatch):
"""File only in CWD (not XDG) → returns CWD Path."""
(tmp_path / "config.yaml").write_text("librofm:\n format: mp3_only\n")
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(tmp_path) # CWD has the file, XDG is empty
result = _resolve_config_file("config.yaml")
assert result is not None
assert result.name == "config.yaml"
# Should be resolved from CWD, not XDG
assert ".config" not in str(result)
def test_xdg_wins_when_both_present(self, tmp_path, monkeypatch):
"""File in both XDG and CWD → XDG path takes priority."""
xdg_dir = tmp_path / ".config" / "librofm-downloader"
xdg_dir.mkdir(parents=True)
(xdg_dir / "config.yaml").write_text("xdg_version\n")
(tmp_path / "config.yaml").write_text("cwd_version\n")
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(tmp_path)
result = _resolve_config_file("config.yaml")
assert result is not None
assert "librofm-downloader" in str(result) # XDG path
assert result.read_text() == "xdg_version\n"
def test_returns_none_when_file_absent_from_both(self, tmp_path, monkeypatch):
"""File missing from XDG and CWD → returns None."""
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(tmp_path)
result = _resolve_config_file("config.yaml")
assert result is None
def test_xdg_directory_auto_created(self, tmp_path, monkeypatch):
"""XDG parent dir is created even when file is absent."""
xdg_parent = tmp_path / ".config" / "librofm-downloader"
assert not xdg_parent.exists()
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(tmp_path)
_resolve_config_file("config.yaml")
assert xdg_parent.is_dir()
class TestLoadConfigWithResolution:
"""load_config wired to _resolve_config_file for None paths."""
def test_secrets_only_returns_defaulted_config(self, tmp_path, monkeypatch):
"""config.yaml missing, secrets.yaml present → defaulted Config + creds."""
xdg_dir = tmp_path / ".config" / "librofm-downloader"
xdg_dir.mkdir(parents=True)
(xdg_dir / "secrets.yaml").write_text(
"librofm:\n username: alice\n password: s3cret\n"
)
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(tmp_path)
config = load_config(None, None)
# Credentials from secrets
assert config.username == "alice"
assert config.password == "s3cret"
# Built-in defaults (config.yaml was missing)
assert config.format == "m4b_mp3_fallback"
assert config.output_dir == "./audiobooks"
assert config.download_extras is True
assert config.download_covers is True
def test_neither_file_raises_error_with_searched_paths(self, tmp_path, monkeypatch):
"""Both files missing → ConfigError listing every path searched."""
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(tmp_path)
with pytest.raises(ConfigError) as exc_info:
load_config(None, None)
msg = str(exc_info.value)
assert "secrets.yaml" in msg
assert "librofm-downloader" in msg or ".config" in msg
def test_explicit_config_path_bypasses_search(self, tmp_path, monkeypatch):
"""Explicit config path → used as-is; secrets still searches if None."""
# Explicit config file
explicit_config = tmp_path / "my_config.yaml"
explicit_config.write_text(
"librofm:\n format: mp3_only\n output_dir: ./custom\n"
)
# Secrets only in XDG
xdg_dir = tmp_path / ".config" / "librofm-downloader"
xdg_dir.mkdir(parents=True)
(xdg_dir / "secrets.yaml").write_text(
"librofm:\n username: bob\n password: p4ss\n"
)
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(tmp_path)
config = load_config(explicit_config, None)
assert config.format == "mp3_only" # from explicit config
assert config.output_dir == "./custom" # from explicit config
assert config.username == "bob" # from resolved secrets
def test_missing_config_provides_detectable_signal(self, tmp_path, monkeypatch):
"""Missing config.yaml → caller can detect defaults were used."""
xdg_dir = tmp_path / ".config" / "librofm-downloader"
xdg_dir.mkdir(parents=True)
(xdg_dir / "secrets.yaml").write_text(
"librofm:\n username: carol\n password: pw\n"
)
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(tmp_path)
config = load_config(None, None)
# Signal: _config_path is None when config.yaml was missing
assert config._config_path is None