39 lines
1.6 KiB
Python
39 lines
1.6 KiB
Python
import json
|
|
import pathlib
|
|
import typing
|
|
|
|
from failure import Failure
|
|
from file_writes import replace_json
|
|
|
|
|
|
# A failure only warns: claude still opens, and the human answers Claude Code's trust dialog.
|
|
def trust(config: pathlib.Path, roots: list[str], note: typing.Callable[[str], None]) -> None:
|
|
try:
|
|
with open(config, encoding="utf-8") as handle:
|
|
data = json.load(handle)
|
|
except (OSError, ValueError) as failure:
|
|
note(f"could not read {config}: {getattr(failure, 'strerror', failure)}")
|
|
return
|
|
marked = mark_trusted(data, roots)
|
|
if isinstance(marked, Failure):
|
|
note(f"could not read {config}: {marked.reason}")
|
|
return
|
|
updated, untrusted = marked
|
|
if not untrusted:
|
|
return
|
|
if unwritten := replace_json(config, updated, indent=2):
|
|
note(f"could not write {config}: {unwritten.reason}")
|
|
return
|
|
note("trusted for the interrupt: " + ", ".join(untrusted))
|
|
|
|
|
|
# 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, settings in projects.items() if not isinstance(settings, 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
|