Skip to content

Commit cdb13be

Browse files
committed
fix(cli): render remaining interpolated console output literally
Several other console lines still interpolated user-controlled values into Rich markup strings: report and baseline output paths, shipped-baseline paths, transitive scan warnings, and recursive progress and summary lines. Bracketed paths or URLs lost their brackets or raised MarkupError. Route them through a shared _literal_line helper (with _error_line and a new _warning_line built on it) or plain Text objects, passing values through visible_terminal_text. Signed-off-by: Farzam Fallahy <[email protected]>
1 parent e16dcf7 commit cdb13be

2 files changed

Lines changed: 132 additions & 18 deletions

File tree

‎src/skillspector/cli.py‎

Lines changed: 42 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,21 @@ def _ensure_utf8_streams() -> None:
123123
err_console = Console(stderr=True)
124124

125125

126-
def _error_line(message: object) -> Text:
127-
"""Render an error line literally: no Rich markup, emoji or control characters."""
126+
def _literal_line(label: str, style: str, message: object) -> Text:
127+
"""Render a labelled line literally: no Rich markup, emoji or control characters."""
128128
lines = str(message).split("\n")
129129
body = "\n".join(_visible_terminal_text(line) for line in lines)
130-
return Text.assemble(("Error:", "red"), " ", body)
130+
return Text.assemble((f"{label}:", style), " ", body)
131+
132+
133+
def _error_line(message: object) -> Text:
134+
"""Render an error line literally."""
135+
return _literal_line("Error", "red", message)
136+
137+
138+
def _warning_line(message: object) -> Text:
139+
"""Render a warning line literally."""
140+
return _literal_line("Warning", "yellow", message)
131141

132142

133143
_PROGRESS_TREE_MAX_PATHS = 200
@@ -386,9 +396,9 @@ def _write_result(
386396
if output:
387397
write_text_no_follow(output, report_body)
388398
if format == FormatChoice.terminal:
389-
console.print(f"\n[green]Report saved to:[/green] {output}")
399+
console.print(Text.assemble("\n", _literal_line("Report saved to", "green", output)))
390400
else:
391-
console.print(f"Report saved to: {output}")
401+
console.print(_literal_line("Report saved to", "", output))
392402
else:
393403
if format == FormatChoice.terminal:
394404
console.print(report_body, markup=False, emoji=False)
@@ -748,7 +758,7 @@ def scan(
748758
report = json.dumps(result, indent=2)
749759
if output:
750760
write_text_no_follow(output, report)
751-
console.print(f"Report saved to: {output}")
761+
console.print(_literal_line("Report saved to", "", output))
752762
else:
753763
print(report)
754764
if fail_on_findings and result["findings"]:
@@ -870,23 +880,27 @@ def scan(
870880
if shipped is not None:
871881
if use_shipped_baseline:
872882
baseline = shipped
873-
err_console.print(f"[yellow]Applying author-shipped baseline:[/yellow] {shipped}")
883+
err_console.print(_literal_line("Applying author-shipped baseline", "yellow", shipped))
874884
err_console.print(
875885
"[dim]Suppressed findings do not count toward the risk score; "
876886
"use --show-suppressed to list them.[/dim]"
877887
)
878888
else:
879889
err_console.print(
880-
f"[yellow]Shipped baseline detected (not applied):[/yellow] {shipped}"
890+
_literal_line("Shipped baseline detected (not applied)", "yellow", shipped)
881891
)
882892
err_console.print(
883893
"[dim]Review it, then re-run with --use-shipped-baseline to apply its "
884894
"suppressions. Findings and risk score are unaffected until you opt in.[/dim]"
885895
)
886896
elif use_shipped_baseline and baseline is None:
887897
err_console.print(
888-
f"[dim]--use-shipped-baseline: no shipped baseline found in {resolved_path}; "
889-
"scanning without a baseline.[/dim]"
898+
Text(
899+
_visible_terminal_text(
900+
f"--use-shipped-baseline: no shipped baseline found in {resolved_path}; scanning without a baseline."
901+
),
902+
style="dim",
903+
)
890904
)
891905

892906
result = None
@@ -2413,7 +2427,7 @@ def _scan_transitive(
24132427
if format in _MACHINE_READABLE_FORMATS or format is FormatChoice.markdown:
24142428
logger.warning("Transitive scan failed for %s", target)
24152429
else:
2416-
console.print(f"[yellow]Warning:[/yellow] Transitive scan failed for {target}")
2430+
console.print(_warning_line(f"Transitive scan failed for {target}"))
24172431
finally:
24182432
if child_result is not None:
24192433
cleanup_result(child_result)
@@ -3010,7 +3024,11 @@ def _scan_multi_skill(
30103024
aggregate_limitations.extend(shared_transitive_traversal.truncation_reasons)
30113025
break
30123026
progress_console.print(
3013-
f" [{i}/{len(skills)}] Scanning [bold]{skill.name}[/bold] ({skill.relative_path}/)"
3027+
Text.assemble(
3028+
f" [{i}/{len(skills)}] Scanning ",
3029+
(_visible_terminal_text(str(skill.name)), "bold"),
3030+
f" ({_visible_terminal_text(str(skill.relative_path))}/)",
3031+
)
30143032
)
30153033
result: dict[str, object] | None = None
30163034
try:
@@ -3165,15 +3183,19 @@ def _scan_multi_skill(
31653183
for skill, result in zip(processed_skills, results, strict=True):
31663184
if "error" in result:
31673185
progress_console.print(
3168-
f" {skill.name:<30} {'ERROR':<8} {'—':<12} {'—':<10} {'error':<10}"
3186+
Text(
3187+
f" {_visible_terminal_text(str(skill.name)):<30} {'ERROR':<8} {'—':<12} {'—':<10} {'error':<10}"
3188+
)
31693189
)
31703190
continue
31713191
score = result.get("risk_score", 0)
31723192
severity = result.get("risk_severity", "LOW")
31733193
finding_count = len(effective_findings(result))
31743194
execution = "failed" if result.get("execution_successful") is False else "successful"
31753195
progress_console.print(
3176-
f" {skill.name:<30} {score:<8} {severity:<12} {finding_count:<10} {execution:<10}"
3196+
Text(
3197+
f" {_visible_terminal_text(str(skill.name)):<30} {score:<8} {severity:<12} {finding_count:<10} {execution:<10}"
3198+
)
31773199
)
31783200
if output_omitted_skill_count:
31793201
progress_console.print(
@@ -3300,7 +3322,7 @@ def _scan_multi_skill(
33003322
_ensure_recursive_output_bound(rendered)
33013323
if output is not None:
33023324
write_text_no_follow(output, rendered)
3303-
progress_console.print(f"[green]Combined report saved to:[/green] {output}")
3325+
progress_console.print(_literal_line("Combined report saved to", "green", output))
33043326
else:
33053327
sys.stdout.write(rendered)
33063328
elif format == FormatChoice.sarif:
@@ -3328,7 +3350,7 @@ def _scan_multi_skill(
33283350
_ensure_recursive_output_bound(rendered)
33293351
if output is not None:
33303352
write_text_no_follow(output, rendered)
3331-
progress_console.print(f"[green]Combined report saved to:[/green] {output}")
3353+
progress_console.print(_literal_line("Combined report saved to", "green", output))
33323354
else:
33333355
sys.stdout.write(rendered)
33343356
else:
@@ -3361,7 +3383,7 @@ def _scan_multi_skill(
33613383
_ensure_recursive_output_bound(rendered)
33623384
if output is not None:
33633385
write_text_no_follow(output, rendered)
3364-
progress_console.print(f"[green]Combined report saved to:[/green] {output}")
3386+
progress_console.print(_literal_line("Combined report saved to", "green", output))
33653387
elif format is FormatChoice.terminal:
33663388
console.print(rendered, markup=False, emoji=False)
33673389
else:
@@ -3523,7 +3545,9 @@ def baseline(
35233545
else:
35243546
dump_baseline(data, output)
35253547
console.print(
3526-
f"[green]Wrote baseline with {len(findings)} suppressed finding(s) to:[/green] {output}"
3548+
_literal_line(
3549+
f"Wrote baseline with {len(findings)} suppressed finding(s) to", "green", output
3550+
)
35273551
)
35283552
except typer.Exit:
35293553
raise

‎tests/unit/test_cli.py‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7891,3 +7891,93 @@ def fake_run(**_kwargs: object) -> None:
78917891
result = runner.invoke(app, ["mcp"])
78927892
assert result.exit_code != 0
78937893
assert "skillspector[mcp]" in result.output
7894+
7895+
7896+
def test_warning_line_renders_message_literally() -> None:
7897+
message = (
7898+
"Transitive scan failed for https://raw.githubusercontent.com/acme/tools/main/setup[/x].sh"
7899+
)
7900+
assert cli_module._warning_line(message).plain == f"Warning: {message}"
7901+
7902+
7903+
def test_literal_line_keeps_label_style_and_literal_path() -> None:
7904+
line = cli_module._literal_line("Report saved to", "green", Path("out[b].json"))
7905+
assert line.plain == "Report saved to: out[b].json"
7906+
assert line.spans[0].style == "green"
7907+
7908+
7909+
def test_transitive_child_failure_warning_shows_bracketed_url_literally(
7910+
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
7911+
) -> None:
7912+
skill = tmp_path / "skill"
7913+
skill.mkdir()
7914+
(skill / "SKILL.md").write_text(
7915+
"---\nname: demo\ndescription: d\n---\n# Demo\n\n"
7916+
"Run https://raw.githubusercontent.com/acme/tools/main/setup[/x].sh first.\n"
7917+
)
7918+
real_scan_for_source = cli._run_graph_scan_for_source
7919+
child_inputs: list[str] = []
7920+
7921+
def scan_for_source(**kwargs: Any) -> dict[str, object]:
7922+
if kwargs["input_path"] == str(skill):
7923+
return real_scan_for_source(**kwargs)
7924+
child_inputs.append(kwargs["input_path"])
7925+
raise RuntimeError("child scan failed")
7926+
7927+
monkeypatch.setattr(cli, "_run_graph_scan_for_source", scan_for_source)
7928+
cli._scan_skill(
7929+
input_path=str(skill),
7930+
format=FormatChoice.terminal,
7931+
no_llm=True,
7932+
baseline=None,
7933+
yara_rules_dir=None,
7934+
verbose=False,
7935+
show_suppressed=False,
7936+
transitive_enabled=True,
7937+
transitive_depth=1,
7938+
transitive_allow_prefix=None,
7939+
transitive_deny_prefix=None,
7940+
)
7941+
assert child_inputs, "the root should have reached a transitive child scan"
7942+
shown = "".join(capsys.readouterr().out.split())
7943+
assert "Transitivescanfailedfor" in shown
7944+
assert "setup[/x].sh" in shown
7945+
7946+
7947+
def test_recursive_scan_shows_bracketed_skill_names_literally(
7948+
tmp_path: Path, capsys: pytest.CaptureFixture[str]
7949+
) -> None:
7950+
# Detection sanitizes names, so build the directories directly to exercise the print path.
7951+
skills = []
7952+
for name in ("one[bold]x", "two"):
7953+
skill = tmp_path / name
7954+
skill.mkdir()
7955+
(skill / "SKILL.md").write_text(
7956+
"---\nname: demo\ndescription: d\n---\n# Demo\n\nSummarize the supplied text.\n"
7957+
)
7958+
skills.append(SkillDirectory(skill, name, name))
7959+
7960+
_scan_multi_skill(
7961+
MultiSkillDetectionResult(is_multi_skill=True, skills=skills),
7962+
FormatChoice.terminal,
7963+
None,
7964+
no_llm=True,
7965+
)
7966+
7967+
captured = capsys.readouterr()
7968+
shown = "".join((captured.out + captured.err).split())
7969+
assert "Scanningone[bold]x(one[bold]x/)" in shown
7970+
7971+
7972+
def test_scan_report_saved_message_shows_bracketed_path_literally(tmp_path: Path) -> None:
7973+
skill = tmp_path / "skill"
7974+
skill.mkdir()
7975+
(skill / "SKILL.md").write_text(
7976+
"---\nname: demo\ndescription: d\n---\n# Demo\n\nSummarize the supplied text.\n"
7977+
)
7978+
report = tmp_path / "out[b].json"
7979+
result = runner.invoke(
7980+
app, ["scan", str(skill), "--format", "json", "--no-llm", "-o", str(report)]
7981+
)
7982+
assert "out[b].json" in "".join(result.output.split())
7983+
assert report.exists()

0 commit comments

Comments
 (0)