Files
claude-howto/scripts/check_cross_references.py
Logic769 2b530b7674 fix(scripts): keep combining marks in heading anchors (#226)
## Summary

`heading_to_anchor()` kept only Python `\w` characters plus spaces,
hyphens and U+200C, so combining marks (Unicode categories Mn, Mc, Me)
were dropped from heading anchors. GitHub keeps them in heading ids, so
a Persian heading such as `مجموعهٔ استاندارد ایموجی` (U+0654 ARABIC
HAMZA ABOVE) got an anchor without the mark. A link that matched GitHub
then failed the `cross-references` hook, while a link with the mark
removed passed even though it is broken on github.com.

The step-2 filter now keeps Mn/Mc/Me characters.
`scripts/build_website.py` carries its own copy of the function,
documented as mirroring the checker, and gets the identical change.

## Type of Change

- [x] Bug fix

## Changes

| File | Change |
|------|--------|
| `scripts/check_cross_references.py` | `heading_to_anchor`: the step-2
`re.sub` keeps characters whose category is in
`COMBINING_MARK_CATEGORIES` (Mn/Mc/Me) instead of dropping them, with a
comment explaining why |
| `scripts/build_website.py` | The same change in its own copy of
`heading_to_anchor` |
| `scripts/tests/test_check_cross_references.py` | U+0654 kept (Persian
from the issue); decomposed Latin, Arabic harakat and Devanagari marks
kept; U+FE0F still stripped because step 1 removes it; `main()` passes a
link that keeps the mark and reports a link without it |
| `scripts/tests/test_build_website.py` | U+0654 kept; website and
checker return the same anchor for Persian with a combining mark,
decomposed Latin and Devanagari headings |

## Verification

Before/after on the three headings named in the issue (U+0654 shown as
`\u0654`):

```text
مجموعهٔ استاندارد ایموجی
  old: مجموعه-...   (mark dropped)
  new: مجموعهٔ-...
فرادادهٔ YAML
  old: فراداده-yaml
  new: فرادادهٔ-yaml
پانوشت فرادادهٔ سند
  old: پانوشت-فراداده-سند
  new: پانوشت-فرادادهٔ-سند
```

No existing anchor moves. Comparing the old and new implementation over
every heading in the repo:

```bash
$ python ../backups/scan_anchor_diff.py      # old() copied from the pre-change code
md files: 478 headings: 13647 changed: 0
```

Tests:

```bash
$ python -m pytest scripts/tests/test_check_cross_references.py scripts/tests/test_build_website.py -q
85 passed, 2 warnings in 10.24s

$ python -m pytest scripts/tests/ -q
1 failed, 197 passed, 2 warnings in 13.63s
```

The one failure
(`test_build_epub.py::TestChapterCollector::test_path_mapping`) is
pre-existing and Windows-only: the test asserts the posix key
`01-test-chapter/README.md` while `ChapterCollector` builds
`01-test-chapter\\README.md` on Windows. That file is untouched by this
PR and the CI job runs on `ubuntu-latest`.

Lint, format, types and security:

```bash
$ ruff check scripts/
All checks passed!
$ ruff format --check scripts/
19 files already formatted
$ mypy scripts/ --ignore-missing-imports
scripts\sync_translations.py:84: error: ...  (2 pre-existing errors, file not touched)
$ bandit -c scripts/pyproject.toml -r scripts/ --exclude scripts/tests/
Total issues (by severity): 0
```

No `.md` files change in this PR, so the five Markdown hooks
(`markdown-lint`, `cross-references`, `mermaid-syntax`, `link-check`,
`markdown-rendering`) are unaffected; the `cross-references` logic they
call is what the new tests cover.

## Notes

The markers are kept for Mn, Mc and Me, matching what GitHub's slugger
keeps (`\p{Mark}`). Variation selectors (U+FE00–U+FE0F) are category Mn
but sit in the emoji ranges stripped in step 1, so emoji-prefixed ids
are unchanged — covered by
`test_heading_anchor_still_strips_em_dash_and_zero_width_joiner`.

Closes #223


[![](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-ai/deepseek-harness)
2026-11-03 10:18:42 +01:00

135 lines
4.7 KiB
Python

#!/usr/bin/env python3
"""Validate cross-references, anchors, and code fences in Markdown files."""
import re
import sys
import unicodedata
from pathlib import Path
IGNORE_DIRS = {
".venv",
"node_modules",
".git",
"blog-posts",
"openspec",
"prompts",
".agents",
}
IGNORE_FILES = {"README.backup.md"}
# Unicode categories of combining marks (accents, Arabic hamza, Indic vowel
# signs, ...). Python's \w does not match them, but GitHub keeps them in
# heading ids.
COMBINING_MARK_CATEGORIES = frozenset({"Mn", "Mc", "Me"})
def iter_md_files():
for f in Path().rglob("*.md"):
if (
not any(part in IGNORE_DIRS for part in f.parts)
and f.name not in IGNORE_FILES
):
yield f
def heading_to_anchor(heading: str) -> str:
# Match GitHub's anchor generation: strip emoji and special punctuation,
# keep Unicode letters (including Vietnamese diacritics), lowercase,
# replace spaces with hyphens, strip leading/trailing hyphens.
# 1. Remove emoji (characters outside BMP or in known emoji ranges)
heading = re.sub(
r"[\U0001F000-\U0001FFFF" # Supplementary Multilingual Plane symbols
r"\U00002702-\U000027B0" # Dingbats
r"\U0000FE00-\U0000FE0F" # Variation selectors
r"\U0000200D" # Zero-width joiner
r"\U000000A9\U000000AE" # (C) (R)
r"\U00002000-\U0000200B" # General punctuation (some emoji-adjacent),
r"\U0000200D-\U0000206F" # minus U+200C zero-width non-joiner (see below)
r"]",
"",
heading,
)
# 2. Remove punctuation but keep Unicode word chars, spaces, hyphens,
# U+200C zero-width non-joiner, and combining marks: Persian uses the
# non-joiner inside words, and GitHub keeps both it and marks such as
# U+0654 in heading ids, while Python's \w matches neither of them.
anchor = re.sub(
r"[^\w\s\U0000200C-]",
lambda match: (
match.group()
if unicodedata.category(match.group()) in COMBINING_MARK_CATEGORIES
else ""
),
heading.lower(),
flags=re.UNICODE,
)
# 3. Replace spaces with hyphens
anchor = anchor.replace(" ", "-")
# 4. Strip trailing hyphens (keep leading hyphens for emoji-prefixed headings)
return anchor.rstrip("-")
def strip_code_blocks(content: str) -> str:
"""Remove fenced code blocks and inline code spans to avoid scanning example links."""
# Strip fenced code blocks (``` ... ```)
content = re.sub(r"```[^\n]*\n.*?```", "", content, flags=re.DOTALL)
# Strip inline code spans (` ... `)
content = re.sub(r"`[^`\n]+`", "", content)
return content
def main() -> int:
errors: list[str] = []
repo_root = Path().resolve()
for file_path in iter_md_files():
content = file_path.read_text(encoding="utf-8")
# Strip code blocks before scanning for links/anchors to avoid false positives
# from documentation examples inside code fences.
scannable = strip_code_blocks(content)
# Relative .md links must resolve and must stay within the repo root
for link_path in re.findall(r"\[[^\]]+\]\(([^)#]+\.md)[^)]*\)", scannable):
resolved = (file_path.parent / link_path).resolve()
if not resolved.is_relative_to(repo_root):
continue
if not resolved.exists():
errors.append(f"{file_path}: broken cross-reference → '{link_path}'")
# In-page anchors must match a real heading
anchors = re.findall(r"\[[^\]]+\]\(#([^)]+)\)", scannable)
if anchors:
headings = re.findall(r"^#{1,6}\s+(.+)$", content, re.MULTILINE)
valid_anchors = {heading_to_anchor(h) for h in headings}
errors.extend(
f"{file_path}: broken anchor → '#{anchor}'"
for anchor in anchors
if anchor not in valid_anchors
)
# Unmatched code fences (only count fences at start of line)
if len(re.findall(r"^```", content, re.MULTILINE)) % 2 != 0:
errors.append(f"{file_path}: unmatched code fences")
# All numbered lesson dirs must have README.md
for i in range(1, 11):
errors.extend(
f"{d}: missing README.md"
for d in Path().glob(f"{i:02d}-*")
if d.is_dir() and not (d / "README.md").exists()
)
if errors:
print("❌ Cross-reference errors:")
for e in errors:
print(f" - {e}")
return 1
md_count = sum(1 for _ in iter_md_files())
print(f"✅ All cross-references valid ({md_count} files checked)")
return 0
if __name__ == "__main__":
sys.exit(main())