repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

quickshell/nugu/audit.sh

Raw
#!/bin/sh
set -eu

# Static guard for the named Nugu Quickshell config. It checks repository
# structure, not live user state, so it is safe to run before smoke tests and in
# review without touching ~/.config or user services.
config_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
repo_dir=$(CDPATH= cd -- "$config_dir/../.." && pwd -P)

python - "$config_dir" "$repo_dir" <<'PY'
from pathlib import Path
import re
import sys

config_dir = Path(sys.argv[1])
repo_dir = Path(sys.argv[2])
errors = []
warnings = []
qml_files = sorted(config_dir.glob("*.qml"))
code_by_file = {}
required_files = ("shell.qml", "Theme.qml", "nugu.json", "README.md", "audit.sh", "smoke.sh")

for name in required_files:
    if not (config_dir / name).exists():
        errors.append(f"missing required self-contained config file {name}")

if not qml_files:
    errors.append("no QML files found")

allowed_imports = ("QtQuick", "Quickshell")
for path in qml_files:
    text = path.read_text()
    rel = path.relative_to(config_dir)
    lines = text.splitlines()

    for number, line in enumerate(lines, 1):
        stripped = line.strip()
        if not stripped.startswith("import "):
            continue
        target = stripped.split(maxsplit=1)[1]
        if target == '"."':
            continue
        if target.startswith(allowed_imports):
            continue
        errors.append(f"{rel}:{number}: non-self-contained import {target}")

    early = lines[:40]
    if not any(line.strip().startswith("//") for line in early):
        errors.append(f"{rel}: missing early decision comment")

    code_lines = []
    for line in lines:
        code_lines.append(line.split("//", 1)[0])
    code = "\n".join(code_lines)
    code_by_file[rel] = code
    for forbidden in ("hyprlauncher", "hyprshutdown", "hyprctl notify"):
        if forbidden in code:
            errors.append(f"{rel}: executable dependency on retired companion marker {forbidden!r}")

    # Named-config self-containment: QML may use Quickshell/Qt resource APIs and
    # the Nugu HOME mode cache, but it must not bake in repo-relative or live
    # ~/.config paths. That keeps tests valid with a temporary XDG_CONFIG_HOME.
    for marker in ("../", "~/.config", "~/.local", "~/."):
        if marker in code:
            errors.append(f"{rel}: non-self-contained path marker {marker!r}")

    for match in re.finditer(r'Qt\.resolvedUrl\("([^"]+)"\)', code):
        target = match.group(1)
        if target != "nugu.json":
            errors.append(f"{rel}: unresolved local resource {target!r}; add it to audit inventory if intentional")

    if 'Quickshell.env("HOME")' in code and rel.as_posix() != "Theme.qml":
        errors.append(f"{rel}: HOME path access belongs in Theme.qml unless explicitly audited")

palette = config_dir / "nugu.json"
generated = repo_dir / "hypr" / "generated" / "nugu.json"
if not palette.exists():
    errors.append("missing bundled nugu.json")
elif generated.exists() and palette.read_text() != generated.read_text():
    errors.append("quickshell/nugu/nugu.json differs from hypr/generated/nugu.json")

# Keep executable dependencies explicit. Quickshell can replace companion UI,
# but system/session CLIs still exist at command boundaries until later parity
# phases remove or validate them. Unknown commands fail so new dependencies do
# not sneak into the self-contained config.
all_code = "\n".join(code_by_file.values())
external_commands = {
    "awk": "approved parser in shell snippet",
    "brightnessctl": "approved brightness backend",
    "cliphist": "transitional clipboard storage bridge",
    "cut": "approved parser in shell snippet",
    "grep": "approved parser in shell snippet",
    "head": "approved parser in shell snippet",
    "hyprctl": "approved Hyprland control until bind migration",
    "hyprlock": "approved session lock backend",
    "hyprpicker": "approved color picker backend",
    "hyprshot": "approved screenshot backend",
    "iwctl": "approved iwd status backend",
    "loginctl": "approved session lock helper",
    "makoctl": "transitional notification bridge",
    "nu": "approved terminal TUI shell",
    "playerctl": "approved MPRIS action helper",
    "satty": "approved screenshot annotation backend",
    "sed": "approved parser in shell snippet",
    "sh": "approved shell boundary for existing command pipelines",
    "systemctl": "approved gated power/session backend",
    "upower": "approved battery TUI backend",
    "uptime": "approved status backend",
    "uwsm": "approved session app launcher",
    "wezterm": "approved terminal launcher",
    "wl-copy": "approved clipboard output backend",
    "wpctl": "approved PipeWire action helper",
}

detected = []
for command, reason in sorted(external_commands.items()):
    if re.search(rf"(?<![A-Za-z0-9_-]){re.escape(command)}(?![A-Za-z0-9_-])", all_code):
        detected.append((command, reason))
        if reason.startswith("transitional"):
            warnings.append(f"transitional external bridge still present: {command}")

# This catches direct process-launch array heads that are not in the approved
# inventory. Shell snippets launched through `sh -c` are inventoried by known
# command names above; they remain explicit but are too free-form for a safe
# generic parser.
launch_patterns = (
    r'\.exec\(\["([A-Za-z0-9_.+-]+)"',
    r'detached\(\["([A-Za-z0-9_.+-]+)"',
    r'\.command\s*=\s*\["([A-Za-z0-9_.+-]+)"',
)
for pattern in launch_patterns:
    for match in re.finditer(pattern, all_code):
        candidate = match.group(1)
        if candidate not in external_commands:
            errors.append(f"unknown direct external command {candidate!r}; add it to audit inventory with a reason or remove it")

if errors:
    print("FAIL nugu quickshell audit")
    for error in errors:
        print(f"ERROR {error}")
    for warning in warnings:
        print(f"WARN {warning}")
    sys.exit(1)

print("PASS nugu quickshell audit")
print(f"qml_files={len(qml_files)}")
print("required_files=" + ",".join(required_files))
if detected:
    print("external_commands=" + ",".join(command for command, _reason in detected))
for warning in warnings:
    print(f"WARN {warning}")
PY