Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix: preserve user config when init cannot parse existing JSON (#94)
CyanoTex88ea2a742d07
diff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.pyindex 6d2944fba..ee9d8b7a1 100644--- a/packages/cli/src/repowise/cli/mcp_config.py+++ b/packages/cli/src/repowise/cli/mcp_config.py@@ -6,6 +6,8 @@ import jsonimport sysfrom pathlib import Path+import click+def _claude_desktop_config_path() -> Path | None:"""Return the Claude Desktop config path for this OS, or None if unsupported."""@@ -66,10 +68,7 @@ def save_root_mcp_config(repo_path: Path) -> Path:new_entry = generate_mcp_config(repo_path)["mcpServers"]if config_path.exists():- try:- existing = json.loads(config_path.read_text(encoding="utf-8"))- except (json.JSONDecodeError, OSError):- existing = {}+ existing = _load_existing_config(config_path)servers = dict(existing.get("mcpServers", {}))servers.update(new_entry)existing["mcpServers"] = servers@@ -88,10 +87,7 @@ def _merge_mcp_entry(config_path: Path, new_entry: dict) -> bool:"""try:if config_path.exists():- try:- existing = json.loads(config_path.read_text(encoding="utf-8"))- except (json.JSONDecodeError, OSError):- existing = {}+ existing = _load_existing_config(config_path)else:config_path.parent.mkdir(parents=True, exist_ok=True)existing = {}@@ -105,6 +101,28 @@ def _merge_mcp_entry(config_path: Path, new_entry: dict) -> bool:return False+def _load_existing_config(config_path: Path) -> dict:+ """Load an existing JSON config without silently replacing bad content."""+ try:+ existing = json.loads(config_path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as exc:+ raise click.ClickException(+ f"Cannot update {config_path}: existing file is not valid JSON. "+ "Fix or remove it and retry; no changes were written."+ ) from exc+ except OSError as exc:+ raise click.ClickException(+ f"Cannot update {config_path}: existing file could not be read. "+ "Fix the file permissions and retry; no changes were written."+ ) from exc+ if not isinstance(existing, dict):+ raise click.ClickException(+ f"Cannot update {config_path}: existing file must contain a JSON object. "+ "Fix or remove it and retry; no changes were written."+ )+ return existing++def register_with_claude_desktop(repo_path: Path) -> Path | None:"""Add repowise MCP server to Claude Desktop's config.@@ -171,10 +189,7 @@ def install_claude_code_hooks() -> Path | None:try:if settings_path.exists():- try:- existing = json.loads(settings_path.read_text(encoding="utf-8"))- except (json.JSONDecodeError, OSError):- existing = {}+ existing = _load_existing_config(settings_path)else:settings_path.parent.mkdir(parents=True, exist_ok=True)existing = {}@@ -191,9 +206,7 @@ def install_claude_code_hooks() -> Path | None:if not _has_repowise_hook(post_hooks):post_hooks.append(post_hook_entry)- settings_path.write_text(- json.dumps(existing, indent=2) + "\n", encoding="utf-8"- )+ settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")return settings_pathexcept OSError:return Nonediff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.pynew file mode 100644index 000000000..f0b1cedc5--- /dev/null+++ b/tests/unit/cli/test_mcp_config.py@@ -0,0 +1,154 @@+import json+import re+from pathlib import Path++import click+import pytest++from repowise.cli import mcp_config+++def _repowise_entry(repo_path: Path) -> dict:+ return mcp_config.generate_mcp_config(repo_path)["mcpServers"]+++def test_save_root_mcp_config_creates_missing_file(tmp_path: Path) -> None:+ config_path = mcp_config.save_root_mcp_config(tmp_path)++ saved = json.loads(config_path.read_text(encoding="utf-8"))+ assert "repowise" in saved["mcpServers"]+++def test_save_root_mcp_config_merges_valid_existing_file(tmp_path: Path) -> None:+ config_path = tmp_path / ".mcp.json"+ config_path.write_text(+ json.dumps(+ {+ "mcpServers": {"other": {"command": "other"}},+ "custom": {"preserved": True},+ }+ ),+ encoding="utf-8",+ )++ mcp_config.save_root_mcp_config(tmp_path)++ saved = json.loads(config_path.read_text(encoding="utf-8"))+ assert saved["mcpServers"]["other"] == {"command": "other"}+ assert "repowise" in saved["mcpServers"]+ assert saved["custom"] == {"preserved": True}+++def test_save_root_mcp_config_rejects_invalid_existing_file(tmp_path: Path) -> None:+ config_path = tmp_path / ".mcp.json"+ original = '{\n "mcpServers": {},\n}\n'+ config_path.write_text(original, encoding="utf-8")++ with pytest.raises(click.ClickException, match=re.escape(str(config_path))):+ mcp_config.save_root_mcp_config(tmp_path)++ assert config_path.read_text(encoding="utf-8") == original+++def test_merge_mcp_entry_creates_missing_file(tmp_path: Path) -> None:+ config_path = tmp_path / "settings.json"++ assert mcp_config._merge_mcp_entry(config_path, _repowise_entry(tmp_path))++ saved = json.loads(config_path.read_text(encoding="utf-8"))+ assert "repowise" in saved["mcpServers"]+++def test_merge_mcp_entry_merges_valid_existing_file(tmp_path: Path) -> None:+ config_path = tmp_path / "settings.json"+ config_path.write_text(+ json.dumps(+ {+ "mcpServers": {"existing": {"command": "existing"}},+ "permissions": {"allow": ["Bash(git status:*)"]},+ }+ ),+ encoding="utf-8",+ )++ assert mcp_config._merge_mcp_entry(config_path, _repowise_entry(tmp_path))++ saved = json.loads(config_path.read_text(encoding="utf-8"))+ assert saved["mcpServers"]["existing"] == {"command": "existing"}+ assert "repowise" in saved["mcpServers"]+ assert saved["permissions"] == {"allow": ["Bash(git status:*)"]}+++def test_merge_mcp_entry_rejects_invalid_existing_file(tmp_path: Path) -> None:+ config_path = tmp_path / "settings.json"+ original = '{\n "permissions": {},\n}\n'+ config_path.write_text(original, encoding="utf-8")++ with pytest.raises(click.ClickException, match=re.escape(str(config_path))):+ mcp_config._merge_mcp_entry(config_path, _repowise_entry(tmp_path))++ assert config_path.read_text(encoding="utf-8") == original+++def test_install_claude_code_hooks_creates_missing_file(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(Path, "home", lambda: tmp_path)++ settings_path = mcp_config.install_claude_code_hooks()++ assert settings_path == tmp_path / ".claude" / "settings.json"+ saved = json.loads(settings_path.read_text(encoding="utf-8"))+ assert "PreToolUse" in saved["hooks"]+ assert "PostToolUse" in saved["hooks"]+++def test_install_claude_code_hooks_merges_valid_existing_file(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ settings_path = tmp_path / ".claude" / "settings.json"+ settings_path.parent.mkdir(parents=True)+ settings_path.write_text(+ json.dumps(+ {+ "permissions": {"allow": ["Bash(git status:*)"]},+ "hooks": {+ "PreToolUse": [+ {+ "matcher": "Read",+ "hooks": [{"type": "command", "command": "echo read"}],+ }+ ]+ },+ }+ ),+ encoding="utf-8",+ )++ assert mcp_config.install_claude_code_hooks() == settings_path++ saved = json.loads(settings_path.read_text(encoding="utf-8"))+ assert saved["permissions"] == {"allow": ["Bash(git status:*)"]}+ assert saved["hooks"]["PreToolUse"][0]["matcher"] == "Read"+ assert any(+ hook["command"] == "repowise augment"+ for entry in saved["hooks"]["PreToolUse"]+ for hook in entry["hooks"]+ )+ assert "PostToolUse" in saved["hooks"]+++def test_install_claude_code_hooks_rejects_invalid_existing_file(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ settings_path = tmp_path / ".claude" / "settings.json"+ settings_path.parent.mkdir(parents=True)+ original = '{\n "permissions": {},\n}\n'+ settings_path.write_text(original, encoding="utf-8")++ with pytest.raises(click.ClickException, match=re.escape(str(settings_path))):+ mcp_config.install_claude_code_hooks()++ assert settings_path.read_text(encoding="utf-8") == original