Skip to content

Commit 182bf90

Browse files
shenxianpengclaude
andcommitted
fix(report): keep backticks and pipes in checked values from breaking the report
The failure table wrapped the checked value in a single pair of backticks and escaped nothing. A commit subject such as `fix: handle `None` | retry`, the kind of thing a fix or docs commit says all the time, closed the code span at its own backtick and split the row at its pipe: GitHub rendered four cells against a three-column header, showed a fragment as the value, and discarded the rule link in the fourth column, the one thing the reader needed. The details block had the same class of bug one size up: its fixed ```text fence was closed by any value quoting a fence, and the rest of the report, footer included, spilled out as prose. Add _markdown_code() for the value cell: a fence one backtick longer than the longest run inside the value, a space of padding when the value starts or ends with a backtick (GFM strips it), and `|` escaped, which GFM honours inside a code span in a table cell. _markdown_details() picks its fence the same way over the whole tree. The row for the subject above now reads | Commit 1/1 (5584f46) | ``fix: handle `None` \| retry`` | [CC001 message](...) | and splits into exactly three cells. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018xYa7m3qup5wyN5MaXFgf6
1 parent 05eb9ef commit 182bf90

2 files changed

Lines changed: 116 additions & 4 deletions

File tree

‎main.py‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
import json
1818
import os
19+
import re
1920
import subprocess
2021
import sys
2122
from dataclasses import dataclass, field
@@ -970,7 +971,7 @@ def _markdown_table(
970971
if not entries and not raw_failure:
971972
continue
972973
value = _scope_value(scope)
973-
value_display = f"`{value}`" if value else "\u2014"
974+
value_display = _markdown_code(value) if value else "\u2014"
974975
if raw_failure:
975976
links = "_output could not be parsed \u2014 see details_"
976977
else:
@@ -1017,12 +1018,40 @@ def _markdown_details(results: list[ScopeResult]) -> str:
10171018
_failed, total = _check_counts(results)
10181019
unit = "check" if total == 1 else "checks"
10191020
label = f"Show all {total} {unit}" if total else "Show details"
1020-
lines = ["<details>", f"<summary>{label}</summary>", "", "```text"]
1021-
lines.extend(_render_tree(results, include_docs=False))
1022-
lines.extend(["```", "", "</details>"])
1021+
body = _render_tree(results, include_docs=False)
1022+
# The tree quotes commit subjects, errors and suggestions as they are. A
1023+
# value with three backticks in it (a `docs:` commit showing a fence)
1024+
# would close a fixed ``` fence and spill the rest of the report out as
1025+
# prose, so the fence is one longer than any backtick run inside.
1026+
fence = "`" * max(3, _longest_backtick_run(body) + 1)
1027+
lines = ["<details>", f"<summary>{label}</summary>", "", f"{fence}text"]
1028+
lines.extend(body)
1029+
lines.extend([fence, "", "</details>"])
10231030
return "\n".join(lines)
10241031

10251032

1033+
def _longest_backtick_run(lines: list[str]) -> int:
1034+
"""Length of the longest run of consecutive backticks across ``lines``."""
1035+
return max((len(m) for line in lines for m in re.findall(r"`+", line)), default=0)
1036+
1037+
1038+
def _markdown_code(value: str) -> str:
1039+
"""A code span that survives a GFM table cell.
1040+
1041+
The value is user text (a commit subject, a branch name, an author) and
1042+
commonly quotes code. A bare ```` `{value}` ```` breaks twice on that: a
1043+
backtick inside closes the span early, and an unescaped ``|`` splits the
1044+
cell, pushing the rule link into a fourth column the table drops. So the
1045+
span uses one more backtick than the longest run inside the value, pads
1046+
with a space when the value starts or ends with a backtick (GFM strips
1047+
one on each side, so the padding is invisible), and escapes ``|``, which
1048+
GFM honours even inside a code span when the span sits in a table cell.
1049+
"""
1050+
fence = "`" * (_longest_backtick_run([value]) + 1)
1051+
pad = " " if value.startswith("`") or value.endswith("`") else ""
1052+
return f"{fence}{pad}{value.replace('|', chr(92) + '|')}{pad}{fence}"
1053+
1054+
10261055
def _scope_value(scope: ScopeResult, max_len: int = 60) -> str:
10271056
"""First non-empty check value for a scope, trimmed to a single line.
10281057
@@ -1197,6 +1226,11 @@ def _scope_value(scope: ScopeResult, max_len: int = 60) -> str:
11971226
# - Values are capped at 60 characters with a literal "..." suffix, except on a
11981227
# failing scope, where the details block prints the value in full — it is the
11991228
# one value the reader has to act on and the cap can hide the reason.
1229+
# - The Checked value cell is a code span whose backtick fence is longer than
1230+
# any backtick run in the value, with `|` escaped, so a subject that quotes
1231+
# code cannot close the span or split the row; the details fence likewise
1232+
# grows past any backtick run in the tree. Reading the raw Markdown, expect
1233+
# ``fix: handle `None` \| retry`` rather than `fix: handle `None` | retry`.
12001234
# - The step log renders the same tree (_render_scopes); it adds the docs URL,
12011235
# which the Markdown report already carries on the rule ID in the table.
12021236
# - The whole report, marker to footer, is also written verbatim to the

‎main_test.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2588,6 +2588,84 @@ def test_add_job_summary_returns_success_for_a_skipped_run(self):
25882588
self.assertEqual(rc, 0)
25892589

25902590

2591+
class TestMarkdownEscaping(unittest.TestCase):
2592+
"""User text in the report must not break the Markdown that carries it.
2593+
2594+
Commit subjects quote code, branch names and author names may contain
2595+
pipes; the table cell and the fenced details block have to survive both.
2596+
The checks below come from a real ``commit-check --format json`` run on
2597+
the subject ``fix: handle `None` | retry`` (all rules pass on it, so the
2598+
CC001 outcome is flipped to make a table row).
2599+
"""
2600+
2601+
#: Splits a table row on the pipes that are cell separators, not on the
2602+
#: escaped ones inside a cell.
2603+
CELL_SEPARATOR = re.compile(r"(?<!\\)\|")
2604+
2605+
def _scope(self, value: str) -> main.ScopeResult:
2606+
return main.ScopeResult(
2607+
label="Commit 1/1",
2608+
sha=SHA_B,
2609+
checks=[
2610+
make_check(
2611+
"message",
2612+
status="fail",
2613+
rule_id="CC001",
2614+
value=value,
2615+
error="The commit message should follow Conventional Commits.",
2616+
docs_url="https://commit-check.com/rules/#cc001",
2617+
),
2618+
make_check("subject_imperative", rule_id="CC003", value=value),
2619+
],
2620+
)
2621+
2622+
def test_markdown_code_wraps_backticks_and_escapes_pipes(self):
2623+
cases = {
2624+
"plain": "`plain`",
2625+
"a|b": "`a\\|b`",
2626+
"fix: handle `None` | retry": "``fix: handle `None` \\| retry``",
2627+
"`x`": "`` `x` ``",
2628+
"``x``": "``` ``x`` ```",
2629+
"x`": "`` x` ``",
2630+
}
2631+
for value, expected in cases.items():
2632+
with self.subTest(value=value):
2633+
self.assertEqual(main._markdown_code(value), expected)
2634+
2635+
def test_table_row_with_backticks_and_a_pipe_keeps_three_cells(self):
2636+
table = main._markdown_table([self._scope("fix: handle `None` | retry")])
2637+
row = table.splitlines()[2]
2638+
# Strip the outer pipes before counting: "| a | b | c |" -> 3 cells.
2639+
cells = self.CELL_SEPARATOR.split(row.strip().strip("|"))
2640+
self.assertEqual(len(cells), 3, row)
2641+
self.assertEqual(cells[1].strip(), "``fix: handle `None` \\| retry``")
2642+
self.assertEqual(
2643+
cells[2].strip(), "[CC001 message](https://commit-check.com/rules/#cc001)"
2644+
)
2645+
2646+
def test_truncated_value_with_an_unbalanced_backtick_still_closes(self):
2647+
"""The 60-char cap can cut inside a backtick run; the fence is chosen
2648+
after truncation, so the span still closes at the right place."""
2649+
value = "fix: " + "`x`, " * 20
2650+
truncated = main._scope_value(self._scope(value))
2651+
self.assertTrue(truncated.endswith("`x..."), truncated) # cut mid-span
2652+
cell = main._markdown_code(truncated)
2653+
self.assertEqual(cell, f"``{truncated}``")
2654+
2655+
def test_details_fence_outgrows_a_triple_backtick_in_the_value(self):
2656+
details = main._markdown_details([self._scope("docs: show ``` usage")])
2657+
lines = details.splitlines()
2658+
self.assertEqual(lines[3], "````text")
2659+
self.assertEqual(lines[-3], "````")
2660+
self.assertIn("value: docs: show ``` usage", details)
2661+
2662+
def test_details_fence_stays_three_backticks_for_ordinary_values(self):
2663+
details = main._markdown_details([pass_scope(value="feat: add `login`")])
2664+
lines = details.splitlines()
2665+
self.assertEqual(lines[3], "```text")
2666+
self.assertEqual(lines[-3], "```")
2667+
2668+
25912669
class TestSkipRenderingEdgeCases(unittest.TestCase):
25922670
def test_failure_table_omits_skipped_scopes(self):
25932671
"""A skipped scope has no failed checks, so it must not get a row.

0 commit comments

Comments
 (0)