aboutsummaryrefslogtreecommitdiffstats
path: root/src/nvd/cli/commands/config.py
blob: 46da59776c39df6c947dce0b6617fc361416f5e5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""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]")