Skip to content

Commit 2c3e9ab

Browse files
committed
fix(batch): preserve literal terminal names and whitespace
Signed-off-by: yashrajbasav <[email protected]>
1 parent b92e02d commit 2c3e9ab

4 files changed

Lines changed: 24 additions & 15 deletions

File tree

‎contrib/batch_scan/batch_scan.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ def _main_impl() -> None:
144144
except ImportError:
145145
Console = None # type: ignore[assignment] # noqa: N806
146146

147-
c = Console() if Console is not None else None
147+
c = Console(emoji=False) if Console is not None else None
148148

149149
def display(value: object) -> str:
150150
text = _terminal_text(value)

‎contrib/batch_scan/reports.py‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,11 @@ def _format_terminal(results: list[dict[str, object]]) -> str:
9393
from rich.markup import escape
9494
from rich.panel import Panel
9595
from rich.table import Table
96+
from rich.text import Text
9697
except ImportError:
9798
return _format_terminal_plain(results)
9899

99-
capture = Console(record=True, force_terminal=True, width=80, file=StringIO())
100+
capture = Console(record=True, force_terminal=True, width=80, file=StringIO(), emoji=False)
100101
total = len(results)
101102

102103
critical = _count_sev(results, "CRITICAL")
@@ -182,15 +183,15 @@ def _format_terminal(results: list[dict[str, object]]) -> str:
182183
lr = _lr_icon(sev, lang)
183184

184185
if r.get("error"):
185-
table.add_row(escape(_terminal_text(name)), "-", "ERR", "[red]ERROR[/red]", "—", escape(_terminal_text(lang)))
186+
table.add_row(Text(_terminal_text(name)), "-", "ERR", "[red]ERROR[/red]", "—", Text(_terminal_text(lang)))
186187
else:
187188
table.add_row(
188-
escape(_terminal_text(name)),
189+
Text(_terminal_text(name)),
189190
lr,
190191
f"[{color}]{score}/100[/{color}]",
191192
f"[{color}]{escape(_terminal_text(sev))}[/{color}]",
192193
str(issues),
193-
escape(_terminal_text(lang)),
194+
Text(_terminal_text(lang)),
194195
)
195196
capture.print(table)
196197
capture.print()
@@ -239,7 +240,7 @@ def _lr_icon(severity: str, language: str) -> str:
239240

240241

241242
def _print_source_breakdown(c, results: list[dict[str, object]]) -> None:
242-
from rich.markup import escape
243+
from rich.text import Text
243244

244245
group_stats: dict[str, dict[str, int]] = defaultdict(
245246
lambda: {"total": 0, "CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0}
@@ -255,19 +256,20 @@ def _print_source_breakdown(c, results: list[dict[str, object]]) -> None:
255256
c.print("[bold]Source Breakdown:[/bold]")
256257
for group in sorted(group_stats):
257258
st = group_stats[group]
258-
parts = [f" {escape(_terminal_text(group)):<30s} {st['total']:>4d} skills"]
259+
prefix = Text(f" {_terminal_text(group):<30s} {st['total']:>4d} skills")
260+
parts = []
259261
if st["CRITICAL"]:
260262
parts.append(f"[bold red]{st['CRITICAL']} CRITICAL[/bold red]")
261263
if st["HIGH"]:
262264
parts.append(f"[red]{st['HIGH']} HIGH[/red]")
263265
if st["MEDIUM"]:
264266
parts.append(f"[yellow]{st['MEDIUM']} MEDIUM[/yellow]")
265-
c.print(", ".join(parts))
267+
c.print(prefix + Text.from_markup((", " + ", ".join(parts)) if parts else ""))
266268
c.print()
267269

268270

269271
def _print_language_breakdown(c, results: list[dict[str, object]]) -> None:
270-
from rich.markup import escape
272+
from rich.text import Text
271273

272274
lang_stats: dict[str, int] = defaultdict(int)
273275
lang_non_en: set[str] = set()
@@ -285,15 +287,15 @@ def _print_language_breakdown(c, results: list[dict[str, object]]) -> None:
285287
c.print(f" {lang:<6s} {count:>4d} skills (static + LLM coverage: full)")
286288
else:
287289
c.print(
288-
f" {escape(_terminal_text(lang)):<6s} {count:>4d} skills "
289-
f"[yellow](static: partial, LLM: full)[/yellow]"
290+
Text(f" {_terminal_text(lang):<6s} {count:>4d} skills ")
291+
+ Text("(static: partial, LLM: full)", style="yellow")
290292
)
291293
c.print()
292294

293295

294296
def _terminal_text(value: object) -> str:
295297
"""Keep an untrusted console field on one line without terminal controls."""
296-
return " ".join("".join(c for c in str(value) if c.isprintable() or c in "\r\n\t").split())
298+
return " ".join("".join(c for c in str(value) if c.isprintable() or c.isspace()).split())
297299

298300

299301
def _format_terminal_plain(results: list[dict[str, object]]) -> str:

‎tests/test_batch_scan_reports.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,9 @@ def test_batch_markdown_code_preserves_literal_values(value: str, table_cell: bo
130130
[
131131
("[/bad]", "[/bad]"),
132132
("[bold]x[/bold]", "[bold]x[/bold]"),
133+
("技能\u3000名称\u00a0x", "技能 名称 x"),
134+
("x:smile:", "x:smile:"),
135+
("tail\\", "tail\\"),
133136
("a\r\nb\x1b[31m\x00c\u202ed", "a b[31mcd"),
134137
],
135138
)
@@ -150,16 +153,20 @@ def test_terminal_batch_fields_are_literal_and_control_free(formatter, payload,
150153
rendered = formatter([entry])
151154

152155
assert expected in rendered
156+
if payload.endswith("\\"):
157+
assert payload + "\\" not in rendered
153158
assert "90/100" in rendered
154159
assert "CRITICAL" in rendered
155160
assert not any(character in rendered for character in ("\x1b", "\x00", "\r", "\u202e"))
156161

157162

158163
def test_terminal_batch_breakdown_fields_are_literal():
159164
entries = [
160-
{"skill": {"name": "one", "source_group": "[/bad]", "language": "[bold]x[/bold]"}},
165+
{"skill": {"name": "one", "source_group": "[/bad]\\", "language": "[bold]x[/bold]\\"}},
161166
{"skill": {"name": "two", "source_group": "other", "language": "en"}},
162167
]
163168
rendered = _format_terminal(entries)
164169
assert "[/bad]" in rendered
165170
assert "[bold]x[/bold]" in rendered
171+
assert "[/bad]\\\\" not in rendered
172+
assert "[bold]x[/bold]\\\\" not in rendered

‎tests/test_batch_scan_security.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ def without_rich(name, *args, **kwargs):
229229
return original_import(name, *args, **kwargs)
230230

231231
monkeypatch.setattr(builtins, "__import__", without_rich)
232-
name = "[/bad]\n\x1b[31mchild"
232+
name = "[/bad]\n\x1b[31mchild:smile:"
233233
entry = {
234234
"skill": {"name": name, "language": "en"},
235235
"risk_assessment": {"score": 90, "severity": "CRITICAL"},
@@ -248,7 +248,7 @@ def without_rich(name, *args, **kwargs):
248248

249249
assert exited.value.code == (2 if has_error else 1)
250250
rendered = capsys.readouterr().out
251-
assert "[/bad] [31mchild" in rendered
251+
assert "[/bad] [31mchild:smile:" in rendered
252252
assert "\x1b" not in rendered
253253
if has_error:
254254
assert "[/bad] [31mfailed" in rendered

0 commit comments

Comments
 (0)