fix(block-ci): preserve escapes and context when masking code

This commit is contained in:
pingqiu committed 2026-12-05 07:35:17 -08:00
1 parent 30e7ead741
commit 36d91b0cea
2 files changed
+46 -3

No files matched your search

@@ -90,6 +90,20 @@ class DocLinksTests(unittest.TestCase):
broken = [(line, target) for _, line, target in links.broken_links(root)]
self.assertEqual(broken, expected)
def test_escaped_backticks_do_not_hide_links(self):
cases = [
("\\`\n[real](real.md)\n\\`", [(2, "real.md")]),
("\\\\`[code](hidden.md)`\n[after](after.md)", [(2, "after.md")]),
("`[code](hidden.md)\\`\n[after](after.md)", [(2, "after.md")]),
]
for text, expected in cases:
with self.subTest(text=text):
self.assertEqual(list(links.link_targets(text)), expected)
def test_masked_code_preserves_reference_line_context(self):
text = "Use `code\nmore`[r]: gone.md\n\n[r]: real.md\n"
self.assertEqual(list(links.link_targets(text)), [(4, "real.md")])
def test_main_exit_status(self):
out = io.StringIO()
with tempfile.TemporaryDirectory() as root, contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
+32 -3
View File
@@ -10,16 +10,45 @@ import urllib.parse
SKIP_DIRS = {".git", "node_modules", "vendor"}
FENCE = re.compile(r"^\s*(`{3,}|~{3,})(.*)$")
# Both delimiters must be complete runs; a shorter run cannot close inside one.
INLINE_CODE = re.compile(r"(?<!`)(`+)(?!`).+?(?<!`)\1(?!`)", re.S)
BACKTICKS = re.compile(r"`+")
INLINE_LINK = re.compile(r"!?\[(?:[^\[\]]|\[[^\[\]]*\])*\]\(\s*(<[^>\n]*>|(?:[^\s()]|\([^\s()]*\))+)")
REFERENCE = re.compile(r"^[ \t]{0,3}\[[^\]]+\]:\s*(<[^>]*>|\S+)", re.M)
SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
def mask_code_spans(text):
runs = list(BACKTICKS.finditer(text))
masked = list(text)
i = 0
while i < len(runs):
opening = runs[i]
start = opening.start()
# Only prose escapes delimiters; backslashes inside code are literal.
preceding = start
while preceding > 0 and text[preceding - 1] == "\\":
preceding -= 1
if (start - preceding) % 2:
start += 1
width = opening.end() - start
if not width:
i += 1
continue
closing = next((j for j in range(i + 1, len(runs))
if len(runs[j].group()) == width), None)
if closing is None:
i += 1
continue
# Keep columns and non-whitespace line context as well as line numbers.
for pos in range(start, runs[closing].end()):
if text[pos] != "\n":
masked[pos] = "x"
i = closing + 1
return "".join(masked)
def paragraph_targets(first, lines):
# A link label may wrap, so links are matched per paragraph.
text = INLINE_CODE.sub(lambda m: "\n" * m.group().count("\n"), "\n".join(lines))
text = mask_code_spans("\n".join(lines))
found = [(m.start(), m.group(1)) for regex in (INLINE_LINK, REFERENCE) for m in regex.finditer(text)]
for pos, target in sorted(found):
yield first + text.count("\n", 0, pos), target