Answer principles round 2: 0 🔴, 1 🟡; main parses and checks settings.json, so cleaned takes a dict and never raises

This commit is contained in:
2026-10-21 22:14:24 +02:00
parent d08a128d0f
commit b7261987ad
3 changed files with 23 additions and 24 deletions
+3 -2
View File
@@ -17,8 +17,9 @@ class Settings(unittest.TestCase):
# The index, not the working file: the working file holds this machine's model in Claude Code's key order. # The index, not the working file: the working file holds this machine's model in Claude Code's key order.
stored = git("show", ":settings.json", cwd=str(ROOT)) stored = git("show", ":settings.json", cwd=str(ROOT))
self.assertIsInstance(stored, str, stored) self.assertIsInstance(stored, str, stored)
self.assertNotIn("model", json.loads(stored)) fix = f"commit settings.json with the filter on: {INSTALL}"
self.assertEqual(stored, cleaned(stored), f"commit settings.json with the filter on: {INSTALL}") self.assertNotIn("model", json.loads(stored), fix)
self.assertEqual(stored, cleaned(json.loads(stored)), fix)
def test_the_readme_installs_the_filter_git_attributes_names_for_the_root_settings_only(self): def test_the_readme_installs_the_filter_git_attributes_names_for_the_root_settings_only(self):
self.assertEqual("/settings.json filter=settings\n", (ROOT / ".gitattributes").read_text(encoding="utf-8")) self.assertEqual("/settings.json filter=settings\n", (ROOT / ".gitattributes").read_text(encoding="utf-8"))
+11 -10
View File
@@ -2,29 +2,30 @@
"""Git's clean filter for settings.json: drop "model" and sort every key. """Git's clean filter for settings.json: drop "model" and sort every key.
Claude Code rewrites settings.json, in its own key order, whenever a model is Claude Code rewrites settings.json, in its own key order, whenever a model is
picked or a plugin installed. Each machine owns its model, so git stores the picked or a plugin installed. Each machine owns its model, so neither the
file without it, and neither write reaches a commit. model nor Claude Code's key order reaches a commit.
""" """
import json import json
import sys import sys
def cleaned(written: str) -> str: def cleaned(settings: dict[str, object]) -> str:
"""settings.json as git stores it: without "model", every key sorted. ValueError where it holds no JSON object.""" """settings.json as git stores it: without "model", every key sorted."""
settings = json.loads(written) kept = {key: value for key, value in settings.items() if key != "model"}
if not isinstance(settings, dict): return json.dumps(kept, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
raise ValueError("settings.json holds no JSON object")
settings.pop("model", None)
return json.dumps(settings, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
def main() -> int: def main() -> int:
# On a non-zero exit git warns and stores the file as written. # On a non-zero exit git warns and stores the file as written.
try: try:
sys.stdout.write(cleaned(sys.stdin.read())) settings = json.loads(sys.stdin.read())
except ValueError as error: except ValueError as error:
print(f"settings_filter.py: {error}", file=sys.stderr) print(f"settings_filter.py: {error}", file=sys.stderr)
return 1 return 1
if not isinstance(settings, dict):
print("settings_filter.py: settings.json holds no JSON object", file=sys.stderr)
return 1
sys.stdout.write(cleaned(settings))
return 0 return 0
+9 -12
View File
@@ -18,24 +18,21 @@ PICKED = json.dumps({"theme": "dark", "model": "opus[1m]", "env": {}}, indent=2)
class Clean(unittest.TestCase): class Clean(unittest.TestCase):
def test_drops_the_model_and_sorts_every_key(self): def test_drops_the_model_and_sorts_every_key(self):
written = '{"theme": "dark", "model": "opus[1m]", "env": {"B": "1", "A": "2"}}' written = {"theme": "dark", "model": "opus[1m]", "env": {"B": "1", "A": "2"}}
self.assertEqual(cleaned(written), '{\n "env": {\n "A": "2",\n "B": "1"\n },\n "theme": "dark"\n}\n') self.assertEqual(cleaned(written), '{\n "env": {\n "A": "2",\n "B": "1"\n },\n "theme": "dark"\n}\n')
def test_keeps_text_outside_ascii(self): def test_keeps_text_outside_ascii(self):
self.assertEqual(cleaned('{"name": "Lilleman på Larv"}'), '{\n "name": "Lilleman på Larv"\n}\n') self.assertEqual(cleaned({"name": "Lilleman på Larv"}), '{\n "name": "Lilleman på Larv"\n}\n')
def test_refuses_json_that_is_no_object(self): def test_a_file_that_holds_no_json_object_exits_1_naming_the_tool(self):
with self.assertRaises(ValueError): for written in ("{", "[]"):
cleaned("[]") ran = subprocess.run([sys.executable, FILTER], input=written, capture_output=True, text=True)
self.assertEqual((ran.returncode, ran.stdout), (1, ""), written)
def test_a_broken_file_exits_1_naming_the_tool(self): self.assertIn("settings_filter.py: ", ran.stderr)
ran = subprocess.run([sys.executable, FILTER], input="{", capture_output=True, text=True)
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn("settings_filter.py: ", ran.stderr)
class Checkout(unittest.TestCase): class Checkout(unittest.TestCase):
"""A repo as README → Install leaves it, at tag v1, and v2, which leaves settings.json alone.""" """A repo as README → Install leaves it, checked out at tag v1; tag v2 doesn't change settings.json."""
def setUp(self): def setUp(self):
temp = tempfile.TemporaryDirectory() temp = tempfile.TemporaryDirectory()
@@ -48,7 +45,7 @@ class Checkout(unittest.TestCase):
(self.repo / ".gitattributes").write_text((ROOT / ".gitattributes").read_text()) (self.repo / ".gitattributes").write_text((ROOT / ".gitattributes").read_text())
self.git("config", "filter.settings.clean", "bin/settings_filter.py") self.git("config", "filter.settings.clean", "bin/settings_filter.py")
self.settings = self.repo / "settings.json" self.settings = self.repo / "settings.json"
self.settings.write_text(cleaned('{"env": {}, "theme": "dark"}')) self.settings.write_text(cleaned({"env": {}, "theme": "dark"}))
(self.repo / ".claude").mkdir() (self.repo / ".claude").mkdir()
(self.repo / ".claude" / "settings.json").write_text('{\n "model": "claude-opus-5-5"\n}\n') (self.repo / ".claude" / "settings.json").write_text('{\n "model": "claude-opus-5-5"\n}\n')
self.git("add", ".") self.git("add", ".")