"""Configuration CLI commands.""" import os import sys from pathlib import Path from typing import Optional import typer import yaml from rich.console import Console from rich.table import Table CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]} app = typer.Typer( no_args_is_help=True, help="Manage nvdb configuration (API keys, settings)", context_settings=CONTEXT_SETTINGS, epilog="Examples:\n" " nvdb config show\n" " nvdb config set-api-key YOUR_API_KEY\n" " nvdb config clear", ) # Console for stderr (status messages, errors) console = Console(stderr=True) CONFIG_DIR = Path.home() / ".config" / "nvd" CONFIG_FILE = CONFIG_DIR / "config.yaml" def load_config() -> dict: """Load configuration from file.""" if not CONFIG_FILE.exists(): return {} with open(CONFIG_FILE) as f: return yaml.safe_load(f) or {} def save_config(config: dict) -> None: """Save configuration to file.""" CONFIG_DIR.mkdir(parents=True, exist_ok=True) with open(CONFIG_FILE, "w") as f: yaml.dump(config, f) @app.command("set-api-key") def set_api_key( api_key: str = typer.Argument(..., help="Your NVD API key"), ) -> None: """Set the NVD API key in config file.""" config = load_config() config["api_key"] = api_key save_config(config) console.print(f"[green]API key saved to {CONFIG_FILE}[/green]") console.print("[yellow]Tip: You can also set the NVD_API_KEY environment variable[/yellow]") @app.command("show") def show_config() -> None: """Show current configuration.""" config = load_config() env_api_key = os.getenv("NVD_API_KEY") table = Table(title="NVD API Configuration", show_header=True, header_style="bold magenta") table.add_column("Setting", style="cyan") table.add_column("Value", style="green") table.add_column("Source", style="yellow") if config.get("api_key"): masked_key = config["api_key"][:8] + "..." if len(config["api_key"]) > 8 else "***" table.add_row("API Key", masked_key, f"Config file ({CONFIG_FILE})") elif env_api_key: masked_key = env_api_key[:8] + "..." if len(env_api_key) > 8 else "***" table.add_row("API Key", masked_key, "Environment variable") else: table.add_row("API Key", "Not set", "N/A") console.print(table) if not config.get("api_key") and not env_api_key: console.print("\n[yellow]No API key configured. Using unauthenticated access (5 req/30s)[/yellow]") console.print("[blue]Set an API key for higher rate limits (50 req/30s):[/blue]") console.print(" nvdb config set-api-key YOUR_KEY") console.print(" or export NVD_API_KEY=YOUR_KEY") @app.command("clear") def clear_config() -> None: """Clear saved configuration.""" if CONFIG_FILE.exists(): CONFIG_FILE.unlink() console.print("[green]Configuration cleared[/green]") else: console.print("[yellow]No configuration file found[/yellow]")