From 5966908e814dd6a9e7c90514c102dc2486929d36 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:30:40 +0100 Subject: [PATCH 1/3] doc-check: symlinks through folders, untouched symlink budgets, fences (#947) - The removal scan walks each untouched symlink and link name by name on the base tree and the checkout, through folder symlinks, and runs when the change removes a path or changes a symlink. It blames only what resolved on the base and names the path the change removed or the symlink it changed; what already pointed to no file on the base (a loop too) stays unblamed. - --base also checks an untouched symlink whose target (or a symlink on the way) the change touched, under the symlink's own budget, as --all does. - Inline code starts only at a whole run of backticks. - A fence on a list item's own line ("- ```sh") opens a fence in the item. - Indented code (in a list item or at the margin, after a blank line) is skipped, as CommonMark reads it. - Reading the base tree fails closed (exit 2) when git fails. Fixes #947 Co-Authored-By: Claude Opus 5.5 --- fork-ci/actions/doc-check/README.md | 15 +- fork-ci/actions/doc-check/doc_check.py | 197 +++++++++++++++----- fork-ci/actions/doc-check/doc_check.test.py | 184 ++++++++++++++++++ 3 files changed, 343 insertions(+), 53 deletions(-) diff --git a/fork-ci/actions/doc-check/README.md b/fork-ci/actions/doc-check/README.md index a0ddb9fd5dd6e..92924d8cab216 100644 --- a/fork-ci/actions/doc-check/README.md +++ b/fork-ci/actions/doc-check/README.md @@ -7,12 +7,15 @@ action fails a pull request that: - puts an instruction file over its **size budget** (lines or bytes; above `warn_at` of a budget it only warns, and says when this change moved the file past it); - writes **history** into an instruction file (a changelog block, an "is live on" claim, a dated "Updated" banner); -- has a **broken relative link** in a Markdown file it adds or changes (code fences, opened as CommonMark does, and inline code - skipped; `/x` is from the repository root, as GitHub reads it; a link that leaves the repository is broken), or deletes or renames a - file that another Markdown file still links to; +- has a **broken relative link** in a Markdown file it adds or changes (code blocks, fenced or indented, read as + CommonMark does, and inline code skipped; `/x` is from the repository root, as GitHub reads it; a link that leaves + the repository is broken), or deletes or renames a file, or removes or retargets a symlink, so that a link in + another Markdown file no longer resolves (through folder symlinks too); - has a checked file that is **not UTF-8** or cannot be read, or is a **symlink** out of the repository, into `.git` or to no file (a symlink is checked as the file it points to and reported once when its target is checked - too; sizes are the bytes on disk, CRLF included), or deletes, renames or moves away the file a symlink points to; + too; sizes are the bytes on disk, CRLF included), or deletes, renames or moves away the file a symlink points to + (or a folder or symlink on its way). An untouched symlink is checked again, under its own budget, when the change + touches the file it reads, so `--base` and `--all` agree on it; - **adds** a file whose name looks like a dated report, handoff or review (those go in the pull request or an issue). The general rules this enforces, and the rest of the agent rules, are in @@ -87,5 +90,5 @@ workflow file, so a change that edits the step or removes it is stopped only by ## Not covered - Anchors (`#section`) and queries (`?plain=1`) are not checked, and neither are backticked paths in the text. -- A broken link that was already on the base in a file the change does not touch is not this change's: `mode: all` - finds those. +- A broken link or a symlink to no file (a loop too) that was already on the base in a file the change does not + touch is not this change's: `mode: all` finds those. diff --git a/fork-ci/actions/doc-check/doc_check.py b/fork-ci/actions/doc-check/doc_check.py index 9e8273d2f42f8..213c8bb14ffa6 100644 --- a/fork-ci/actions/doc-check/doc_check.py +++ b/fork-ci/actions/doc-check/doc_check.py @@ -4,14 +4,17 @@ * size budgets (lines and bytes) for instruction files, matched by glob, first match wins; above `warn_at` of a budget a WARN line that never fails; * no history in instruction files (changelog blocks, "is live on" claims, dated "Updated" banners); - * every relative link resolves to a file or folder in the repository (code fences, opened as CommonMark does, and - inline code are skipped; `/x` is from the repository root, as GitHub reads it; a link that leaves the repository is broken); with --base, a - file the change deletes or renames away must have no link left to it in any file the config selects; + * every relative link resolves to a file or folder in the repository (code blocks, fenced or indented, read as + CommonMark does, and inline code are skipped; `/x` is from the repository root, as GitHub reads it; a link that + leaves the repository is broken); with --base, no file the config selects may be left with a link that resolved on + the base and does not now because the change removed a path or changed a symlink on its way; * a newly added file whose name looks like a dated report, handoff or review belongs in the pull request or an issue, not in the repository; * a checked file is UTF-8 text that can be read (anything else fails, and its size is still checked); a symlink is - checked as the file it points to, which must be in the repository and not in .git (with --base, a change that - removes the file an untouched symlink points to fails). Sizes are the bytes on disk (CRLF included). + checked as the file it points to, which must be in the repository and not in .git (with --base, an untouched + symlink is checked too when the change touches the file it reads or a symlink on the way, and fails when the + change removes or retargets a path it went through; one that already pointed to no file on the base, a loop + too, is not this change's). Sizes are the bytes on disk (CRLF included). The rules come from the project's JSON config (README "Config"); every key is optional and a missing, empty or `{}` config means the defaults. With --base the config is read at the base commit, never from the checkout, so a change @@ -25,7 +28,7 @@ Run from the repository root. Exit 0: no problem (warnings allowed); 1: a rule is broken; 2: the config, git or the base could not be read. Read-only and stateless: a re-run gives the same output. """ -import argparse, json, os, re, subprocess, sys +import argparse, json, os, re, stat, subprocess, sys from urllib.parse import unquote DEFAULT_CONFIG = '.github/doc-check.json' @@ -56,9 +59,10 @@ # CommonMark: a fence opens or closes with 0-3 spaces of indent, counted from the content of the list item it is in. FENCE = re.compile(r'(`{3,}|~{3,})') LIST_ITEM = re.compile(r'([-*+]|\d{1,9}[.)])(?=[ \t]|$)') -INLINE_CODE = re.compile(r'(`+)(?!`).*?(?= len(fence) and not body[len(m.group(1)):].strip(): fence = None continue - if m and not (m.group(1)[0] == '`' and '`' in body[len(m.group(1)):]): - fence, fence_col = m.group(1), col + was_blank, blank = blank, not body + if body: + code = indent - col >= 4 and (code or was_blank) + if code: + continue + if body and indent - col <= 3 and opens_fence(body): + fence, fence_col = opens_fence(body), col continue item = LIST_ITEM.match(body) if body and indent - col <= 3 else None if item: rest = body[item.end():] gap = len(rest) - len(rest.lstrip(' ')) items.append(indent + item.end() + (gap if rest.strip() and 1 <= gap <= 4 else 1)) + if rest.strip() and gap <= 4 and opens_fence(rest.lstrip(' ')): + fence, fence_col = opens_fence(rest.lstrip(' ')), items[-1] if fence is None: for lm in LINK.finditer(INLINE_CODE.sub('', line)): target = re.split(r'[#?]', lm.group(1) or lm.group(2), maxsplit=1)[0] @@ -285,20 +304,21 @@ def selected(rules, path): def changed_files(base): - """(merge base, [(path, added)], [removed]): the files the change adds or modifies (a rename's new name counts as - added, and a change of type, such as a file turned into a symlink, as modified), and those it deletes (a rename's - old name).""" + """(merge base, [(path, added)], [removed], {relinked}): the files the change adds or modifies (a rename's new name + counts as added, and a change of type, such as a file turned into a symlink, as modified), those it deletes (a + rename's old name), and the symlinks it modifies (retargeted, or a file turned into a symlink or back).""" mb = git('merge-base', base, 'HEAD') if mb is None or not mb.strip(): raise ConfigError(f'no merge base of {base} and HEAD (check out with fetch-depth: 0)') mb = mb.strip() - out = git('diff', '--name-status', '--no-renames', '--diff-filter=AMTD', '-z', mb, 'HEAD') + out = git('diff', '--raw', '--no-renames', '--diff-filter=AMTD', '-z', mb, 'HEAD') if out is None: raise ConfigError(f'git diff {mb}..HEAD failed') parts = out.split('\0') - pairs = [(parts[i], parts[i + 1]) for i in range(0, len(parts) - 1, 2)] - return (mb, [(path, kind == 'A') for kind, path in pairs if kind != 'D'], - [path for kind, path in pairs if kind == 'D']) + rows = [(parts[i].split(), parts[i + 1]) for i in range(0, len(parts) - 1, 2)] # :old new sha sha kind, path + return (mb, [(path, f[4] == 'A') for f, path in rows if f[4] != 'D'], + [path for f, path in rows if f[4] == 'D'], + {path for f, path in rows if f[4] in ('M', 'T') and '120000' in (f[0][1:], f[1])}) def read_doc(path, root='.'): @@ -346,39 +366,110 @@ def base_doc(mb, path): return None -def removed_target(path, gone, root='.'): - """The path a symlink names (hop by hop, inside the repository) that the change removed, or None.""" - for _ in range(40): - target = os.path.normpath(os.path.join(os.path.dirname(path), os.readlink(path))) - rel = os.path.relpath(os.path.join(root, target), root) - if rel in gone or any(g.startswith(rel + os.sep) for g in gone): - return rel - if rel.split(os.sep)[0] == '..' or not os.path.islink(os.path.join(root, rel)): - return None - path = rel +def resolve(path, entry): + """Walk a repository path name by name as the file system does, following symlinks in the repository (a folder + symlink on the way too): (kind, [each path walked]). entry(path) is (kind, symlink text) with kind 'file', 'dir', + 'link', None (no such path) or '?' (cannot tell). kind None: no such path, out of the repository or a loop.""" + if '\0' in path: + return None, [] + parts, done, walked, hops, kind = path.split('/'), [], [], 0, 'dir' + while parts: + name = parts.pop(0) + if name in ('', '.'): + continue + if kind == 'file': # a file is no folder + return None, walked + if name == '..': + if not done: + return None, walked + done.pop() + continue + cur = '/'.join(done + [name]) + walked.append(cur) + kind, target = entry(cur) + if kind == 'link': + hops += 1 + if hops > 40 or target.startswith('/'): + return None, walked + parts = target.split('/') + parts + kind = 'dir' + continue + if kind in (None, '?'): + return kind, walked + done.append(name) + return kind, walked + + +def head_entry(root='.'): + """entry() for resolve() on the checkout.""" + def entry(path): + try: + st = os.lstat(os.path.join(root, path)) + except (OSError, ValueError): + return None, None + if stat.S_ISLNK(st.st_mode): + return 'link', os.readlink(os.path.join(root, path)) + return ('dir' if stat.S_ISDIR(st.st_mode) else 'file'), None + return entry + + +def base_entry(mb): + """entry() for resolve() on the merge base's tree; git failing is an error, never a pass.""" + seen = {} + def entry(path): + if path not in seen: + out = git('ls-tree', '-z', mb, '--', path) + if out is None: + raise ConfigError(f'git ls-tree {mb} failed') + if not out: + seen[path] = (None, None) + else: + mode, kind, rest = out.split(' ', 2) + if mode == '120000': + target = git('cat-file', 'blob', rest.split('\t', 1)[0]) + if target is None: + raise ConfigError(f'git cat-file failed on {path} at {mb}') + seen[path] = ('link', target) + else: # a submodule ('commit') cannot be told + seen[path] = {'blob': ('file', None), 'tree': ('dir', None)}.get(kind, ('?', None)) + return seen[path] + return entry + + +def broken_by(walked, gone, relinked): + """What this change did to the paths a name walked through on the base, or None: it removed the last one (or + emptied that folder), or removed or changed a symlink on the way.""" + if walked and (walked[-1] in gone or any(g.startswith(walked[-1] + '/') for g in gone)): + return f'this change removed {walked[-1]}' + for p in reversed(walked): + if p in gone: + return f'this change removed {p}' + if p in relinked: + return f'this change changed the symlink {p}' return None -def links_to_removed(rules, removed, checked, root='.'): - """Problems, in selected tracked files this run did not check, for a symlink to a file the change removed, and - (links on) for links to a file the change removed (or into a folder it emptied) that no longer resolve.""" +def links_to_removed(rules, tracked, removed, relinked, checked, mb, root='.'): + """Problems, in selected tracked files this run did not check, for a symlink and (links on) a link that points to + no file now but resolved on the base (through the same path, folder symlinks included), when the change removed a + path or changed a symlink on the way. What was already broken on the base is not this change's.""" gone = {os.path.normpath(p) for p in removed} - if not gone: + if not gone and not relinked: return [] - out = git('ls-files', '-z') - if out is None: - raise ConfigError('git ls-files failed (run from the repository root)') + base = base_entry(mb) probs = [] - for path in out.split('\0'): + for path in tracked: if not path or path in checked or not selected(rules, path): continue if not (os.path.isfile(path) or os.path.islink(path)): continue text, links_from, problem = read_doc(path, root) if text is None: - hit = os.path.islink(path) and removed_target(path, gone, root) - if hit: - probs.append((path, None, f'{problem}: this change removed {hit}')) + if os.path.islink(path): + kind, walked = resolve(path, base) + why = kind == 'file' and broken_by(walked, gone, relinked) + if why: + probs.append((path, None, f'{problem}: {why}')) continue if not rules['links']: continue @@ -386,9 +477,10 @@ def links_to_removed(rules, removed, checked, root='.'): full = link_path(links_from or path, target, root) if full is None or broken_link(links_from or path, target, root) is None: continue - rel = os.path.relpath(full, root) - if rel in gone or any(g.startswith(rel + os.sep) for g in gone): - probs.append((path, no, f'broken link {target}: this change removed {rel}')) + kind, walked = resolve(os.path.relpath(full, root), base) + why = kind in ('file', 'dir') and broken_by(walked, gone, relinked) + if why: + probs.append((path, no, f'broken link {target}: {why}')) return probs @@ -411,10 +503,20 @@ def main(argv=None): if not a.base.strip(): raise ConfigError('--base is empty: give the base commit, or use --all') rules, note = load_config(a.config, a.base) - mb, files, removed = changed_files(a.base) + mb, files, removed, relinked = changed_files(a.base) + out = git('ls-files', '-z') + if out is None: + raise ConfigError('git ls-files failed (run from the repository root)') + tracked = [f for f in out.split('\0') if f] + # An untouched symlink that reads a file this change touched (its target, or a symlink on the way) is + # checked too, as --all checks it; one that points to no file now is the removal scan's. + changed = {p for p, _ in files} | set(removed) + head = head_entry() + files += [(p, False) for p in tracked if p not in changed and os.path.islink(p) and selected(rules, p) + and changed & set(resolve(p, head)[1]) and read_doc(p)[0] is not None] else: rules, note = load_config(a.config) - mb, removed = None, [] + mb, removed, relinked, tracked = None, [], set(), [] if a.all: out = git('ls-files', '-z') if out is None: @@ -454,7 +556,8 @@ def main(argv=None): probs += p warns += w try: - probs += links_to_removed(rules, removed, checked) + if mb is not None: + probs += links_to_removed(rules, tracked, removed, relinked, checked, mb) except ConfigError as e: print(f'doc_check: ERROR {shown(e)}') return 2 diff --git a/fork-ci/actions/doc-check/doc_check.test.py b/fork-ci/actions/doc-check/doc_check.test.py index aebf222c275aa..9985185caad0f 100644 --- a/fork-ci/actions/doc-check/doc_check.test.py +++ b/fork-ci/actions/doc-check/doc_check.test.py @@ -267,6 +267,46 @@ def test_a_fence_opens_only_with_0_to_3_spaces_of_indent(self): self.assertIn('DOC docs/a.md:10: broken link nope.md', out) self.assertIn('1 problem(s)', out) + def test_an_unmatched_backtick_run_hides_no_link(self): + # #947 item 3: inline code never starts in the middle of a run of backticks, so a run with no closing run of + # the same length is text and the link after it is still checked. + for text in ['`` [g](nope.md) `\n', 'close it with ``` and see [g](nope.md) and `x`\n']: + with self.subTest(text=text): + self.write({'docs/a.md': text}) + code, out = self.run_check('--files', 'docs/a.md') + self.assertEqual(code, 1, out) + self.assertIn('DOC docs/a.md:1: broken link nope.md: no such file', out) + + def test_a_fence_on_a_list_items_own_line(self): + # #947 item 4: "- ```sh" opens a fence in the item, so its closing line closes it (and opens nothing). + for marker in ['-', '1.', '10)']: + pad = ' ' * (len(marker) + 1) + text = f'{marker} ```sh\n{pad}[in](nope.md)\n{pad}```\n{pad}[after](nope.md)\n' + with self.subTest(text=text): + self.write({'docs/a.md': text}) + code, out = self.run_check('--files', 'docs/a.md') + self.assertEqual(code, 1, out) + self.assertIn('DOC docs/a.md:4: broken link nope.md', out) + self.assertIn('1 problem(s)', out) # not the fenced one + + def test_a_link_in_indented_code_is_skipped(self): + # #947 item 5: as CommonMark reads it, a line 4 or more past its list item's content (or the margin), after a + # blank line, is indented code: no link. Without the blank line it continues the paragraph: a link. + for text in ['- item\n\n ```\n [in](nope.md)\n ```\n\n [after](nope.md)\n', + '1. item\n\n [in](nope.md)\n\n [in](nope.md)\n[after](nope.md)\n', + 'Shown:\n\n [in](nope.md)\n\t[in](nope.md)\n\n[after](nope.md)\n']: + with self.subTest(text=text): + self.write({'docs/a.md': text}) + code, out = self.run_check('--files', 'docs/a.md') + self.assertEqual(code, 1, out) + self.assertIn(f'DOC docs/a.md:{text.count(chr(10))}: broken link nope.md', out) + self.assertIn('1 problem(s)', out) + for text in ['- item\n [in](nope.md)\n', 'para\n [in](nope.md)\n']: + with self.subTest(text=text): + self.write({'docs/a.md': text}) + code, out = self.run_check('--files', 'docs/a.md') + self.assertIn('DOC docs/a.md:2: broken link nope.md', out) + def test_a_link_that_is_no_path_is_a_broken_link_not_a_traceback(self): self.commit({'docs/a.md': '[nul](x%00.md)\n', 'docs/b.md': 'b\n'}) base = self.branch({'docs/b.md': None}) # the removed-link scan reads the untouched a.md @@ -334,6 +374,150 @@ def test_a_symlink_already_dangling_on_the_base_is_not_this_change(self): self.assertEqual(code, 0, out) + def through_a_folder_symlink(self, how, want, link=False): + """#947 item 1. Base: real/A.md, docs -> real, an untouched CLAUDE.md -> docs/A.md (or, link: an untouched + a.md that links to docs/A.md); the change touches only real/ or docs.""" + self.commit({'real/A.md': 'rules\n', 'a.md': '[a](docs/A.md)\n' if link else 'a\n'}) + os.symlink('real', 'docs') + if not link: + os.symlink('docs/A.md', 'CLAUDE.md') + self.commit({}) + self.git('checkout', '-q', '-b', 'change') + how() + self.git('add', '-A') + self.git('commit', '-q', '-m', 'change') + code, out = self.run_check('--base', 'main') + self.assertEqual(code, 1, out) + self.assertIn(want, out) + self.assertIn('1 problem(s)', out) + + def test_the_target_of_an_untouched_symlink_through_a_folder_symlink_deleted_or_renamed(self): + want = 'DOC CLAUDE.md: a symlink that points to no file: make it a file: this change removed real/A.md' + self.through_a_folder_symlink(lambda: os.remove('real/A.md'), want) + + def test_the_target_of_an_untouched_symlink_through_a_folder_symlink_renamed(self): + want = 'DOC CLAUDE.md: a symlink that points to no file: make it a file: this change removed real/A.md' + self.through_a_folder_symlink(lambda: os.rename('real', 'real2'), want) + + def test_a_folder_symlink_retargeted_to_nothing_or_out_of_the_repository(self): + def to(target): + def how(): + os.remove('docs') + os.symlink(target, 'docs') + return how + with open(os.path.join(self.tmp.name, 'A.md'), 'w') as f: + f.write('x\n') + for target, why in [('nowhere', 'points to no file'), (self.tmp.name, 'points outside the repository')]: + with self.subTest(target=target): + self.setUp() + self.through_a_folder_symlink(to(target), f'DOC CLAUDE.md: a symlink that {why}: make it a file: ' + 'this change changed the symlink docs') + + def test_a_folder_symlink_removed(self): + self.through_a_folder_symlink(lambda: os.remove('docs'), + 'DOC CLAUDE.md: a symlink that points to no file: make it a file: ' + 'this change removed docs') + + def test_a_link_through_a_folder_symlink(self): + self.through_a_folder_symlink(lambda: os.remove('real/A.md'), + 'DOC a.md:1: broken link docs/A.md: this change removed real/A.md', link=True) + self.setUp() + def how(): + os.remove('docs') + os.symlink('nowhere', 'docs') + self.through_a_folder_symlink(how, 'DOC a.md:1: broken link docs/A.md: this change changed the symlink docs', + link=True) + + def test_already_dangling_on_the_base_or_a_loop_through_a_changed_symlink_is_not_this_change(self): + # docs -> real is retargeted to real2 (which has A.md); CLAUDE.md -> docs/missing.md pointed to no file on the + # base already, a.md's link too, and loop.md loops on both sides. + self.commit({'real/A.md': 'a\n', 'real2/A.md': 'a\n', 'a.md': '[m](docs/missing.md) [l](loop.md)\n'}) + os.symlink('real', 'docs') + os.symlink('docs/missing.md', 'CLAUDE.md') + os.symlink('loop.md', 'loop.md') + os.symlink('docs/A.md', 'AGENTS.md') + self.commit({}) + base = self.git('rev-parse', 'HEAD') + self.git('checkout', '-q', '-b', 'change') + os.remove('docs') + os.symlink('real2', 'docs') + os.remove('real/A.md') + self.commit({}) + code, out = self.run_check('--base', base) + self.assertEqual(code, 0, out) + + + def test_git_failing_on_the_base_tree_is_an_error_not_a_pass(self): + self.commit({'real/A.md': 'a\n', 'a.md': '[a](docs/A.md)\n'}) + os.symlink('real', 'docs') + self.commit({}) + base = self.branch({'real/A.md': None}) + real_git = DC.git + with mock.patch.object(DC, 'git', lambda *a: None if a[0] == 'ls-tree' else real_git(*a)): + code, out = self.run_check('--base', base) + self.assertEqual(code, 2, out) + self.assertIn('git ls-tree', out) + +class SymlinkParity(Repo): + """#947 item 2 and the state question: --base fails a change exactly when it makes --all fail an untouched symlink + (the same line); what was already broken on the base fails --all only.""" + + def both(self, base_files, links, how, fails=True): + self.commit(base_files) + for name, target in links.items(): + os.symlink(target, name) + self.commit({}) + self.git('checkout', '-q', '-b', 'change') + how() + self.git('add', '-A') + self.git('commit', '-q', '-m', 'change') + code_base, out_base = self.run_check('--base', 'main') + code_all, out_all = self.run_check('--all') + self.assertEqual(code_all, 1, out_all) + self.assertIn('DOC CLAUDE.md:', out_all) + if fails: + self.assertEqual(code_base, 1, out_base) + line_all = re.search(r'DOC CLAUDE\.md: [^:\n]*', out_all).group(0) + self.assertIn(line_all, out_base) + else: + self.assertEqual(code_base, 0, out_base) + return out_base + + def test_an_untouched_symlink_is_judged_by_its_own_budget_when_its_target_grows(self): + out = self.both({'AGENTS.md': lines(30)}, {'CLAUDE.md': 'AGENTS.md'}, + lambda: self.write({'AGENTS.md': lines(61)})) + self.assertIn('DOC CLAUDE.md: 61 lines / 671 B, budget 40 lines', out) + self.assertNotIn('DOC AGENTS.md', out) + + def test_an_untouched_symlink_through_a_retargeted_folder_symlink(self): + def how(): + os.remove('docs') + os.symlink('big', 'docs') + out = self.both({'small/A.md': lines(5), 'big/A.md': lines(61)}, {'docs': 'small', 'CLAUDE.md': 'docs/A.md'}, + how) + self.assertIn('DOC CLAUDE.md: 61 lines', out) + + def test_a_symlink_retargeted_removed_half_way_or_looped(self): + def retarget(name, target): + def how(): + os.remove(name) + os.symlink(target, name) + return how + cases = [('retargeted', retarget('docs', 'nowhere')), + ('removed half-way', lambda: os.remove('X.md')), + ('looped', retarget('docs', 'docs'))] + for name, how in cases: + with self.subTest(name): + self.setUp() + self.both({'real/A.md': 'a\n'}, {'docs': 'real', 'X.md': 'docs/A.md', 'CLAUDE.md': 'X.md'}, how) + + def test_already_dangling_on_the_base_fails_all_only(self): + for links in [{'CLAUDE.md': 'missing.md'}, {'CLAUDE.md': 'loop.md', 'loop.md': 'loop.md'}]: + with self.subTest(links=links): + self.setUp() + self.both({'docs/b.md': 'b\n'}, links, lambda: os.remove('docs/b.md'), fails=False) + + class FailClosed(Repo): """#908: what used to pass unchecked now fails: a symlink to a large file, a byte that is not UTF-8, CRLF size.""" From 6ff61714361b271fd5076a9b7068e9211d2acc2a Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:48:05 +0100 Subject: [PATCH 2/3] doc-check: lazy lines keep a list item open, every marker counts (#1020) Round 1 of the code review. A line that continues a list item's paragraph without indent (lazy) no longer ends the item, and in "- - item" each marker opens an item, so the item's next paragraph is never read as indented code. A lazy line opens nothing; an empty item or one numbered from 2 cannot interrupt a paragraph; "- - -" is a thematic break; indented code needs a blank line only after a paragraph. Tests: the reviewer's two cases and the variants found against commonmark.js, a deleted doc named ":(top)A.md" (GIT_LITERAL_PATHSPECS), and a test name that says only what it tests. Co-Authored-By: Claude Opus 5.5 --- fork-ci/actions/doc-check/doc_check.py | 57 +++++++++++++++------ fork-ci/actions/doc-check/doc_check.test.py | 41 ++++++++++++++- 2 files changed, 80 insertions(+), 18 deletions(-) diff --git a/fork-ci/actions/doc-check/doc_check.py b/fork-ci/actions/doc-check/doc_check.py index 213c8bb14ffa6..e19a1e915225b 100644 --- a/fork-ci/actions/doc-check/doc_check.py +++ b/fork-ci/actions/doc-check/doc_check.py @@ -59,6 +59,8 @@ # CommonMark: a fence opens or closes with 0-3 spaces of indent, counted from the content of the list item it is in. FENCE = re.compile(r'(`{3,}|~{3,})') LIST_ITEM = re.compile(r'([-*+]|\d{1,9}[.)])(?=[ \t]|$)') +THEMATIC = re.compile(r'([-*_])(?:[ \t]*\1){2,}[ \t]*$') # "- - -" is a thematic break, not a list item +HEADING = re.compile(r'#{1,6}(?=[ \t]|$)') INLINE_CODE = re.compile(r'(?')) + + def link_lines(text): """(line number, target) of each link outside code blocks. As in CommonMark, a fence opens with 0-3 spaces of indent (a tab is 4) counted from the content column of the list item it is in (on the item's own line too), and - a fence in a list item ends with the item; a line 4 or more past that column after a blank line (or in such a - block) is indented code.""" + a fence in a list item ends with the item; a line 4 or more past that column is indented code unless it goes on + with a paragraph. A line less indented than an item's content ends the item, unless it continues the + item's paragraph (a lazy line); each marker of a line like "- - item" opens an item.""" fence, fence_col, items = None, 0, [] # items: the content columns of the open list items - code, blank = False, True # in indented code; the line before was blank (or none) + code, para = False, False # in indented code; the line before is paragraph text (lazy lines go on) for no, line in enumerate(text.split('\n'), 1): wide = line.expandtabs(4) body = wide.lstrip(' ') @@ -214,29 +223,43 @@ def link_lines(text): if body and fence is not None and indent < fence_col: fence = None # the list item the fence was in has ended if body: - while items and indent < items[-1]: - items.pop() + kept = len(items) + while kept and indent < items[kept - 1]: + kept -= 1 + in_para = para and kept == len(items) # the line is in the paragraph's own block + # a lazy line goes on with the paragraph of an item it is not indented into: text, nothing opens + lazy = para and kept < len(items) and not (indent - (items[kept - 1] if kept else 0) <= 3 + and starts_block(body)) + if not lazy: + del items[kept:] col = fence_col if fence is not None else (items[-1] if items else 0) m = FENCE.match(body) if body and indent - col <= 3 else None if fence is not None: if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not body[len(m.group(1)):].strip(): fence = None continue - was_blank, blank = blank, not body if body: - code = indent - col >= 4 and (code or was_blank) - if code: + code = indent - col >= 4 and (code or not para) # indented code cannot interrupt a paragraph + if code or not body: + para = False continue - if body and indent - col <= 3 and opens_fence(body): - fence, fence_col = opens_fence(body), col + text_only = lazy or indent - col > 3 # 4 or more in and not code: the paragraph goes on too + if not text_only and opens_fence(body): + fence, fence_col, para = opens_fence(body), col, False continue - item = LIST_ITEM.match(body) if body and indent - col <= 3 else None - if item: - rest = body[item.end():] - gap = len(rest) - len(rest.lstrip(' ')) - items.append(indent + item.end() + (gap if rest.strip() and 1 <= gap <= 4 else 1)) - if rest.strip() and gap <= 4 and opens_fence(rest.lstrip(' ')): - fence, fence_col = opens_fence(rest.lstrip(' ')), items[-1] + at, rest = indent, '' if text_only else body + while rest and not THEMATIC.match(rest) and LIST_ITEM.match(rest): + item = LIST_ITEM.match(rest) + after = rest[item.end():] + if in_para and (not after.strip() or item.group(1)[0].isdigit() and int(item.group(1)[:-1]) != 1): + break # an empty item, or a numbered one not at 1, cannot interrupt a paragraph: text + in_para = False + gap = len(after) - len(after.lstrip(' ')) + items.append(at + item.end() + (gap if after.strip() and gap <= 4 else 1)) + at, rest = items[-1], after.lstrip(' ') if gap <= 4 else '' + if rest and opens_fence(rest): + fence, fence_col = opens_fence(rest), items[-1] + para = text_only or bool(rest) and fence is None and not (THEMATIC.match(rest) or HEADING.match(rest)) if fence is None: for lm in LINK.finditer(INLINE_CODE.sub('', line)): target = re.split(r'[#?]', lm.group(1) or lm.group(2), maxsplit=1)[0] diff --git a/fork-ci/actions/doc-check/doc_check.test.py b/fork-ci/actions/doc-check/doc_check.test.py index 9985185caad0f..8705fb9affb74 100644 --- a/fork-ci/actions/doc-check/doc_check.test.py +++ b/fork-ci/actions/doc-check/doc_check.test.py @@ -307,6 +307,37 @@ def test_a_link_in_indented_code_is_skipped(self): code, out = self.run_check('--files', 'docs/a.md') self.assertIn('DOC docs/a.md:2: broken link nope.md', out) + def test_a_list_item_stays_open_on_a_lazy_line_and_every_marker_on_a_line_counts(self): + # #1020 round 1: an unindented line that continues an item's paragraph (lazy) keeps the item open, and in + # "- - item" both markers open an item, so the item's next paragraph is text, not indented code: a link. A + # lazy line opens nothing; an empty item or one numbered from 2 cannot interrupt a paragraph; a line 4 in + # after a closed list is code, so "10." opens a list. (commonmark.js 0.31.2 reads each case so.) + for text in ['1. Step one that wraps\nonto the next line.\n\n More about step one, see [g](nope.md).\n', + '- item\nlazy\n\n [x](nope.md)\n', + '1. a\n - b\nlazy\n\n [x](nope.md)\n', + '- - nested item\n\n more text [x](nope.md)\n', + '1. - item\n\n [x](nope.md)\n', + '- - item\nlazy\n\n [x](nope.md)\n', + 'para\n2) ```\n [x](nope.md)\n', + ' 1. [g](a.md)\n ```sh\n 1. [x](nope.md)\n', + ' * ```\n ```sh\n 10. text\n\n - text [x](nope.md)\n', + 'para\n-\n [x](nope.md)\n']: + with self.subTest(text=text): + self.write({'docs/a.md': text}) + code, out = self.run_check('--files', 'docs/a.md') + self.assertEqual(code, 1, out) + self.assertIn(f'DOC docs/a.md:{text.count(chr(10))}: broken link nope.md', out) + # A heading, a thematic break or a fence is no lazy line: it ends the item, and "- - -" is a thematic + # break, not three items; the indented line after it is code (no blank needed after a heading or a fence). + for text in ['- item\n# heading\n\n [in](nope.md)\n', '- item\n---\n\n [in](nope.md)\n', + '- item\n```\n```\n\n [in](nope.md)\n', '- - -\n\n [in](nope.md)\n', + '- item\n\nnot lazy\n\n [in](nope.md)\n', '# h\n [in](nope.md)\n', + '```\n```\n [in](nope.md)\n']: + with self.subTest(text=text): + self.write({'docs/a.md': text}) + code, out = self.run_check('--files', 'docs/a.md') + self.assertEqual(code, 0, out) + def test_a_link_that_is_no_path_is_a_broken_link_not_a_traceback(self): self.commit({'docs/a.md': '[nul](x%00.md)\n', 'docs/b.md': 'b\n'}) base = self.branch({'docs/b.md': None}) # the removed-link scan reads the untouched a.md @@ -339,6 +370,14 @@ def test_an_old_broken_link_in_an_untouched_file_is_not_this_change(self): code, out = self.run_check('--base', base) self.assertEqual(code, 0, out) + def test_a_deleted_doc_named_like_a_pathspec_magic_word(self): + # GIT_LITERAL_PATHSPECS: git reads ":(top)A.md" as the name it is, not as "A.md" from the top. + self.commit({'a.md': '[a](%3A%28top%29A.md)\n', ':(top)A.md': 'a\n'}) + base = self.branch({':(top)A.md': None}) + code, out = self.run_check('--base', base) + self.assertEqual(code, 1, out) + self.assertIn('DOC a.md:1: broken link %3A%28top%29A.md: this change removed :(top)A.md', out) + def untouched_symlink_loses_its_target(self, how): """Base: docs/AGENTS.md and CLAUDE.md -> docs/AGENTS.md; the change touches only the target.""" self.commit({'docs/AGENTS.md': 'rules\n'}) @@ -391,7 +430,7 @@ def through_a_folder_symlink(self, how, want, link=False): self.assertIn(want, out) self.assertIn('1 problem(s)', out) - def test_the_target_of_an_untouched_symlink_through_a_folder_symlink_deleted_or_renamed(self): + def test_the_target_of_an_untouched_symlink_through_a_folder_symlink_deleted(self): want = 'DOC CLAUDE.md: a symlink that points to no file: make it a file: this change removed real/A.md' self.through_a_folder_symlink(lambda: os.remove('real/A.md'), want) From 4e85c9397b9f74790f4cda0f1bbf256ebcb67db9 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:57:14 +0000 Subject: [PATCH 3/3] doc-check: a line after a block quote opens what it would open outside it The checker does not model block quotes, so a ">" line counted as a paragraph that the next line continues: "2." right below a quote was read as text and its indented content as code, which hid a broken link. Such a line goes on with the quote's paragraph only lazily, so it now opens what it would open outside the quote; an indented line after it stays lazy text. Found by the narrow check on #1020; commonmark.js 0.31.2 agrees. Co-Authored-By: Claude Opus 5.5 --- fork-ci/actions/doc-check/doc_check.py | 8 ++++++-- fork-ci/actions/doc-check/doc_check.test.py | 11 +++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/fork-ci/actions/doc-check/doc_check.py b/fork-ci/actions/doc-check/doc_check.py index e19a1e915225b..62d53e02ef0ac 100644 --- a/fork-ci/actions/doc-check/doc_check.py +++ b/fork-ci/actions/doc-check/doc_check.py @@ -216,6 +216,7 @@ def link_lines(text): item's paragraph (a lazy line); each marker of a line like "- - item" opens an item.""" fence, fence_col, items = None, 0, [] # items: the content columns of the open list items code, para = False, False # in indented code; the line before is paragraph text (lazy lines go on) + quote = False # that paragraph is in a block quote, which this checker does not model for no, line in enumerate(text.split('\n'), 1): wide = line.expandtabs(4) body = wide.lstrip(' ') @@ -226,7 +227,9 @@ def link_lines(text): kept = len(items) while kept and indent < items[kept - 1]: kept -= 1 - in_para = para and kept == len(items) # the line is in the paragraph's own block + # the line is in the paragraph's own block; a line without ">" after a quote's paragraph goes on with it + # only lazily, so it opens what it would open outside the quote ("2." too) + in_para = para and kept == len(items) and not quote # a lazy line goes on with the paragraph of an item it is not indented into: text, nothing opens lazy = para and kept < len(items) and not (indent - (items[kept - 1] if kept else 0) <= 3 and starts_block(body)) @@ -241,7 +244,7 @@ def link_lines(text): if body: code = indent - col >= 4 and (code or not para) # indented code cannot interrupt a paragraph if code or not body: - para = False + para = quote = False continue text_only = lazy or indent - col > 3 # 4 or more in and not code: the paragraph goes on too if not text_only and opens_fence(body): @@ -260,6 +263,7 @@ def link_lines(text): if rest and opens_fence(rest): fence, fence_col = opens_fence(rest), items[-1] para = text_only or bool(rest) and fence is None and not (THEMATIC.match(rest) or HEADING.match(rest)) + quote = rest.startswith('>') if rest else quote and text_only if fence is None: for lm in LINK.finditer(INLINE_CODE.sub('', line)): target = re.split(r'[#?]', lm.group(1) or lm.group(2), maxsplit=1)[0] diff --git a/fork-ci/actions/doc-check/doc_check.test.py b/fork-ci/actions/doc-check/doc_check.test.py index 8705fb9affb74..34744753b39ff 100644 --- a/fork-ci/actions/doc-check/doc_check.test.py +++ b/fork-ci/actions/doc-check/doc_check.test.py @@ -338,6 +338,17 @@ def test_a_list_item_stays_open_on_a_lazy_line_and_every_marker_on_a_line_counts code, out = self.run_check('--files', 'docs/a.md') self.assertEqual(code, 0, out) + def test_a_block_quote_line_is_no_paragraph_the_next_line_goes_on(self): + # #1020 narrow check: this checker does not model block quotes, so a ">" line must not count as a paragraph + # that the next line continues: "2." right below a quote opens an item (commonmark.js 0.31.2 renders the link). + for text in ['> **Note:** this needs a recent runtime.\n2. Run it.\n\n See [setup](nope.md) for flags.\n', + '> quote\n [x](nope.md)\n']: + with self.subTest(text=text): + self.write({'docs/a.md': text}) + code, out = self.run_check('--files', 'docs/a.md') + self.assertEqual(code, 1, out) + self.assertIn(f'DOC docs/a.md:{text.count(chr(10))}: broken link nope.md', out) + def test_a_link_that_is_no_path_is_a_broken_link_not_a_traceback(self): self.commit({'docs/a.md': '[nul](x%00.md)\n', 'docs/b.md': 'b\n'}) base = self.branch({'docs/b.md': None}) # the removed-link scan reads the untouched a.md