Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/semble/cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import argparse
import asyncio
import codecs
import io
import json
import logging
Expand Down Expand Up @@ -172,7 +173,9 @@ def _load_index(paths: list[str], content: list[ContentType]) -> tuple[SembleInd
def _print_results(out: dict, output_format: str) -> None:
"""Print a format_results() payload as JSON or as human-readable text."""
if output_format == "json":
print(json.dumps(out))
# Legacy encodings may reject or alter non-ASCII characters, so keep their JSON ASCII-only.
ensure_ascii = not codecs.lookup(sys.stdout.encoding or "ascii").name.startswith("utf")
print(json.dumps(out, ensure_ascii=ensure_ascii))
Comment thread
Pringled marked this conversation as resolved.
Resolved
elif "error" in out:
print(out["error"])
else:
Expand Down
8 changes: 4 additions & 4 deletions src/semble/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ async def search(
return str(exc)
results = index.search(query, top_k=top_k, max_snippet_lines=max_snippet_lines)
if not results:
return json.dumps({"error": "No results found."})
return json.dumps(format_results(query, results, max_snippet_lines, index.sources))
return json.dumps({"error": "No results found."}, ensure_ascii=False)
return json.dumps(format_results(query, results, max_snippet_lines, index.sources), ensure_ascii=False)

@server.tool()
async def find_related(
Expand Down Expand Up @@ -166,9 +166,9 @@ async def find_related(
)
results = index.find_related(chunk, top_k=top_k, max_snippet_lines=max_snippet_lines)
if not results:
return json.dumps({"error": f"No related chunks found for {file_path}:{line}."})
return json.dumps({"error": f"No related chunks found for {file_path}:{line}."}, ensure_ascii=False)
label = f"Chunks related to {file_path}:{line}"
return json.dumps(format_results(label, results, max_snippet_lines, index.sources))
return json.dumps(format_results(label, results, max_snippet_lines, index.sources), ensure_ascii=False)

return server

Expand Down
26 changes: 25 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import hashlib
import io
import json
import signal
import sys
Expand All @@ -10,8 +11,9 @@

import pytest

from semble.cli import _cli_main, _maybe_save_index, _run_clear, main
from semble.cli import _cli_main, _maybe_save_index, _print_results, _run_clear, main
from semble.types import ContentType, SearchResult
from semble.utils import format_results
from semble.version import __version__
from tests.conftest import make_chunk

Expand Down Expand Up @@ -156,6 +158,28 @@ def test_main_dispatches_to_cli(
assert "query text" in capsys.readouterr().out


@pytest.mark.parametrize(
("encoding", "expected"),
[
("utf-8", "café 咖啡"),
("cp65001", "café 咖啡"),
("cp1251", r"caf\u00e9 \u5496\u5561"),
],
)
def test_print_results_json_respects_stdout_encoding(
encoding: str, expected: str, monkeypatch: pytest.MonkeyPatch
) -> None:
"""CLI JSON uses literal Unicode for UTF streams and ASCII escapes otherwise."""
payload = format_results("cafe", [SearchResult(chunk=make_chunk('return "café 咖啡"', "example.py"), score=0.9)])
stdout = io.TextIOWrapper(io.BytesIO(), encoding=encoding)
monkeypatch.setattr(sys, "stdout", stdout)
_print_results(payload, "json")
stdout.flush()
text = stdout.buffer.getvalue().decode(encoding)
assert expected in text
assert json.loads(text) == payload


@pytest.mark.parametrize(
("argv", "expected_stdout", "expect_system_exit"),
[
Expand Down
10 changes: 5 additions & 5 deletions tests/test_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,11 +297,11 @@ async def test_tool_index_failure(cache: _IndexCache, tool: str, args: dict[str,
[
pytest.param(
"search",
{"query": "bar", "repo": "/some/path"},
{"query": "cafe", "repo": "/some/path"},
"search",
[SearchResult(chunk=make_chunk("def bar(): pass", "src/bar.py"), score=0.9)],
[SearchResult(chunk=make_chunk('def cafe():\n return "café 咖啡"', "example.py"), score=0.9)],
None,
["bar", "0.9"],
["example.py", "0.9", "café 咖啡"],
id="search_with_results",
),
pytest.param(
Expand All @@ -317,9 +317,9 @@ async def test_tool_index_failure(cache: _IndexCache, tool: str, args: dict[str,
"find_related",
{"file_path": "src/foo.py", "line": 1, "repo": "/some/path"},
"find_related",
[SearchResult(chunk=make_chunk("class Foo: pass", "src/foo.py"), score=0.8)],
[SearchResult(chunk=make_chunk('def cafe():\n return "café 咖啡"', "example.py"), score=0.8)],
[make_chunk("class Foo: pass", "src/foo.py")],
["src/foo.py:1", "0.8"],
["example.py", "src/foo.py:1", "0.8", "café 咖啡"],
id="find_related_with_results",
),
pytest.param(
Expand Down