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:
1 parent
090132f39e
commit
3ba9f25903
6 files changed
+308
-14
No files matched your search
@@ -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(
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user