feat: improve CLI UTF-8 support and enhance JSON output validation in bridge.py

This commit is contained in:
catlog22
2026-03-17 15:30:16 +08:00
parent 0f02b75be1
commit 34749d2fad
3 changed files with 25 additions and 16 deletions

View File

@@ -23,9 +23,18 @@ log = logging.getLogger("codexlens_search.bridge")
# Helpers
# ---------------------------------------------------------------------------
def _ensure_utf8_stdio() -> None:
"""Force UTF-8 encoding on stdout/stderr (Windows defaults to GBK/cp936)."""
if sys.platform == "win32":
for stream_name in ("stdout", "stderr"):
stream = getattr(sys, stream_name)
if hasattr(stream, "reconfigure"):
stream.reconfigure(encoding="utf-8", errors="replace")
def _json_output(data: dict | list) -> None:
"""Print JSON to stdout with flush."""
print(json.dumps(data, ensure_ascii=False), flush=True)
print(json.dumps(data, ensure_ascii=True), flush=True)
def _error_exit(message: str, code: int = 1) -> None:
@@ -363,6 +372,7 @@ def _build_parser() -> argparse.ArgumentParser:
def main() -> None:
"""CLI entry point."""
_ensure_utf8_stdio()
parser = _build_parser()
args = parser.parse_args()

View File

@@ -91,7 +91,8 @@ class TestJsonHelpers:
def test_json_output_unicode(self, capsys):
_json_output({"msg": "中文测试"})
out = capsys.readouterr().out.strip()
assert "中文测试" in out
parsed = json.loads(out)
assert parsed["msg"] == "中文测试"
def test_error_exit(self):
with pytest.raises(SystemExit) as exc_info: