wrds-download

TUI/CLI tool for browsing and downloading WRDS data
Log | Files | Refs | README

config.py (1607B)


      1 """Credentials file I/O — reads/writes ~/.config/wrds-dl/credentials."""
      2 
      3 from __future__ import annotations
      4 
      5 import os
      6 from pathlib import Path
      7 
      8 
      9 def credentials_path() -> Path:
     10     """Return the path to the credentials file, respecting $XDG_CONFIG_HOME."""
     11     base = os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config"
     12     return Path(base) / "wrds-dl" / "credentials"
     13 
     14 
     15 def load_credentials() -> tuple[str, str, str]:
     16     """Read PGUSER, PGPASSWORD, PGDATABASE from the credentials file.
     17 
     18     Returns (user, password, database). Missing values are empty strings.
     19     """
     20     user = password = database = ""
     21     path = credentials_path()
     22     if not path.is_file():
     23         return user, password, database
     24 
     25     for line in path.read_text().splitlines():
     26         line = line.strip()
     27         if not line or line.startswith("#"):
     28             continue
     29         key, _, val = line.partition("=")
     30         key, val = key.strip(), val.strip()
     31         if key == "PGUSER":
     32             user = val
     33         elif key == "PGPASSWORD":
     34             password = val
     35         elif key == "PGDATABASE":
     36             database = val
     37     return user, password, database
     38 
     39 
     40 def apply_credentials() -> None:
     41     """Load credentials from config and set env vars for any values not already set."""
     42     user, password, database = load_credentials()
     43     if not os.environ.get("PGUSER") and user:
     44         os.environ["PGUSER"] = user
     45     if not os.environ.get("PGPASSWORD") and password:
     46         os.environ["PGPASSWORD"] = password
     47     if not os.environ.get("PGDATABASE") and database:
     48         os.environ["PGDATABASE"] = database