Files
claude-config/bin/loop_claude/claude_code/trust.py
T

39 lines
1.7 KiB
Python

import json
import pathlib
import sys
from failure import Failure
from files.writes import replace_json
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
def trust(config: pathlib.Path, roots: list[str]) -> None:
try:
with open(config, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError) as failure:
print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr)
return
marked = mark_trusted(data, roots)
if isinstance(marked, Failure):
print(f"could not read {config}: {marked.reason}", file=sys.stderr)
return
updated, untrusted = marked
if not untrusted:
return
if unwritten := replace_json(config, updated, indent=2):
print(f"could not write {config}: {unwritten.reason}", file=sys.stderr)
return
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure:
if not isinstance(config, dict) or not isinstance(projects := config.get("projects", {}), dict):
return Failure('not an object whose "projects" is an object')
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}
return {**config, "projects": {**projects, **marked}}, untrusted