-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
77 lines (58 loc) · 2.11 KB
/
Copy pathconfig.py
File metadata and controls
77 lines (58 loc) · 2.11 KB
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
"""API key storage and retrieval for the Querit CLI."""
from __future__ import annotations
import json
import os
from pathlib import Path
CONFIG_DIR = Path.home() / ".querit"
CONFIG_FILE = CONFIG_DIR / "config.json"
# Override base URL via environment variable if needed
BASE_URL = os.environ.get("QUERIT_BASE_URL", "https://api.querit.ai")
def _read_config() -> dict:
if CONFIG_FILE.exists():
try:
return json.loads(CONFIG_FILE.read_text())
except (json.JSONDecodeError, OSError):
return {}
return {}
def _write_config(data: dict) -> None:
old_umask = os.umask(0o077)
try:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
CONFIG_DIR.chmod(0o700)
CONFIG_FILE.write_text(json.dumps(data, indent=2) + "\n")
CONFIG_FILE.chmod(0o600)
finally:
os.umask(old_umask)
def save_api_key(api_key: str) -> None:
config = _read_config()
config["api_key"] = api_key
_write_config(config)
def clear_credentials() -> None:
if CONFIG_FILE.exists():
CONFIG_FILE.unlink()
def get_api_key() -> str | None:
"""Resolve the API key with precedence: env var > config file."""
key = os.environ.get("QUERIT_API_KEY")
if key:
return key
return _read_config().get("api_key")
def get_api_key_or_exit() -> str:
"""Get the API key or print an error and exit."""
import sys
key = get_api_key()
if not key:
from rich.console import Console
console = Console(stderr=True)
console.print(" [#FAA2FB]> Error:[/#FAA2FB] No Querit API key found.")
console.print()
console.print(" Set your API key using one of:")
console.print(" [#00C2C2]querit login --api-key YOUR_KEY[/#00C2C2]")
console.print(" [dim]export QUERIT_API_KEY=YOUR_KEY[/dim]")
console.print()
console.print(" Get a key at [link=https://www.querit.ai]querit.ai[/link]")
sys.exit(3)
return key
def get_client():
"""Return an authenticated QueritClient."""
from querit_cli.client import QueritClient
return QueritClient(api_key=get_api_key_or_exit())