Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Z4nzu
GitHub Repository: Z4nzu/hackingtool
Path: blob/master/config.py
2370 views
1
import json
2
import logging
3
from pathlib import Path
4
from typing import Any
5
6
from constants import USER_CONFIG_FILE, USER_TOOLS_DIR, DEFAULT_CONFIG
7
8
logger = logging.getLogger(__name__)
9
10
11
def load() -> dict[str, Any]:
12
"""Load config from disk, merging with defaults for any missing keys."""
13
if USER_CONFIG_FILE.exists():
14
try:
15
on_disk = json.loads(USER_CONFIG_FILE.read_text())
16
return {**DEFAULT_CONFIG, **on_disk}
17
except (json.JSONDecodeError, OSError) as exc:
18
logger.warning("Config file unreadable (%s), using defaults.", exc)
19
return dict(DEFAULT_CONFIG)
20
21
22
def save(cfg: dict[str, Any]) -> None:
23
"""Write config to disk, creating parent directories if needed."""
24
USER_CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
25
USER_CONFIG_FILE.write_text(json.dumps(cfg, indent=2, sort_keys=True))
26
27
28
def get_tools_dir() -> Path:
29
"""
30
Return the directory where external tools are stored.
31
Creates it if it does not exist.
32
Always an absolute path — never relies on process CWD.
33
"""
34
cfg = load()
35
tools_dir = Path(cfg.get("tools_dir", str(USER_TOOLS_DIR))).expanduser().resolve()
36
tools_dir.mkdir(parents=True, exist_ok=True)
37
return tools_dir
38
39
40
def get_sudo_cmd() -> str:
41
"""Return 'doas' if available, else 'sudo'. Never hardcode 'sudo'."""
42
import shutil
43
return "doas" if shutil.which("doas") else "sudo"
44