"""GitHub PAT configuration for DEPosit collection scripts. Never commit personal access tokens. Provide credentials via: 1. Environment variables (recommended for CI) 2. A local ``.env`` file (copy from ``.env.example``; not committed) 3. ``--token`` / ``--tokens`` CLI flags where supported Variables: GITHUB_TOKEN_SE4DE — project-specific name (preferred) GITHUB_TOKEN — standard name GITHUB_TOKENS — comma-separated PATs for rate-limit rotation """ from __future__ import annotations import argparse import os import sys from pathlib import Path PACKAGE_ROOT = Path(__file__).resolve().parents[1] def load_dotenv(path: Path | None = None) -> None: """Load KEY=VALUE pairs from .env into os.environ (does not override existing).""" path = path or PACKAGE_ROOT / ".env" if not path.is_file(): return for raw in path.read_text(encoding="utf-8").splitlines(): line = raw.strip() if not line or line.startswith("#") or "=" not in line: continue key, _, value = line.partition("=") key = key.strip() value = value.strip().strip("'").strip('"') if key and key not in os.environ: os.environ[key] = value def load_tokens() -> list[str]: """Return all configured PATs (may be empty).""" load_dotenv() found: list[str] = [] for env in ("GITHUB_TOKEN_SE4DE", "GITHUB_TOKEN"): value = os.environ.get(env, "").strip() if value and value not in found: found.append(value) for part in os.environ.get("GITHUB_TOKENS", "").split(","): part = part.strip() if part and part not in found: found.append(part) return found def build_authorization_headers(tokens: list[str]) -> list[dict[str, str]]: return [ {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} for token in tokens ] def resolve_token(cli_token: str | None = None, cli_tokens: str | None = None) -> str | None: """Single PAT: CLI overrides environment.""" if cli_token and cli_token.strip(): return cli_token.strip() if cli_tokens: parts = [p.strip() for p in cli_tokens.split(",") if p.strip()] if parts: return parts[0] tokens = load_tokens() return tokens[0] if tokens else None def require_github_tokens( cli_token: str | None = None, cli_tokens: str | None = None, ) -> list[str]: """Return PAT list or exit with instructions.""" if cli_token and cli_token.strip(): return [cli_token.strip()] if cli_tokens: parts = [p.strip() for p in cli_tokens.split(",") if p.strip()] if parts: return parts tokens = load_tokens() if not tokens: _exit_missing_token() return tokens def primary_token(cli_token: str | None = None, cli_tokens: str | None = None) -> str: token = resolve_token(cli_token, cli_tokens) if not token: _exit_missing_token() return token def init_rest_client_auth( cli_token: str | None = None, cli_tokens: str | None = None, ) -> tuple[list[str], list[dict[str, str]]]: """Used by REST collection scripts with token rotation.""" tokens = require_github_tokens(cli_token, cli_tokens) return tokens, build_authorization_headers(tokens) def add_github_token_args(parser: argparse.ArgumentParser) -> None: group = parser.add_argument_group("GitHub authentication") group.add_argument( "--token", metavar="PAT", help="GitHub personal access token (overrides environment)", ) group.add_argument( "--tokens", metavar="PAT1,PAT2", help="Comma-separated PATs for rate-limit rotation (overrides environment)", ) def _exit_missing_token() -> None: print("GitHub token required for API collection.", file=sys.stderr) print(" Option A: copy .env.example to .env and set GITHUB_TOKEN_SE4DE", file=sys.stderr) print(" Option B: $env:GITHUB_TOKEN_SE4DE = '' (PowerShell)", file=sys.stderr) print(" Option C: pass --token on scripts that support it", file=sys.stderr) sys.exit(1)