141 lines
5.0 KiB
Python
141 lines
5.0 KiB
Python
from __future__ import annotations
|
|
|
|
import argparse
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from html.parser import HTMLParser
|
|
from urllib.parse import unquote, urlsplit
|
|
from .document_resources import analyze_document, resolve_local_reference
|
|
from .document_tree import discover_documents
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class LinkIssue:
|
|
source: Path
|
|
line_number: int
|
|
target: str
|
|
resolved_path: Path
|
|
message: str
|
|
|
|
|
|
def discover_markdown_files(project_root: Path) -> list[Path]:
|
|
return [entry.path for entry in discover_documents(project_root, ("markdown",))]
|
|
|
|
|
|
def check_documents(project_root: Path, sources=None, cancel=None, progress=None) -> list[LinkIssue]:
|
|
root = project_root.resolve()
|
|
issues: list[LinkIssue] = []
|
|
|
|
cache, sources = {}, sources or {}
|
|
for markdown_path in discover_markdown_files(root):
|
|
from .export_jobs import check_cancelled
|
|
check_cancelled(cancel)
|
|
if progress:
|
|
progress(f"正在检查:{markdown_path.relative_to(root)}")
|
|
issues.extend(check_markdown_file(markdown_path, sources=sources, cache=cache))
|
|
|
|
return issues
|
|
|
|
|
|
class _HtmlAnchors(HTMLParser):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.anchors = set()
|
|
|
|
def handle_starttag(self, tag, attrs):
|
|
for name, value in attrs:
|
|
if value and (name == "id" or (name == "name" and tag == "a")):
|
|
self.anchors.add(value)
|
|
|
|
|
|
def document_anchors(analysis) -> set[str]:
|
|
parser = _HtmlAnchors()
|
|
anchors = set()
|
|
for token in analysis.tokens:
|
|
if token.attrGet("id"):
|
|
anchors.add(token.attrGet("id"))
|
|
for item in [token, *(token.children or [])]:
|
|
if item.type in {"html_inline", "html_block"}:
|
|
parser.feed(item.content)
|
|
return anchors | parser.anchors
|
|
|
|
|
|
def check_markdown_file(markdown_path: Path, *, sources=None, cache=None) -> list[LinkIssue]:
|
|
issues: list[LinkIssue] = []
|
|
sources = sources or {}
|
|
cache = {} if cache is None else cache
|
|
def load(path):
|
|
if path not in cache:
|
|
text = sources[path] if path in sources else path.read_text(encoding="utf-8-sig")
|
|
cache[path] = analyze_document(text)
|
|
return cache[path]
|
|
try:
|
|
analysis = load(markdown_path)
|
|
except (OSError, UnicodeDecodeError) as error:
|
|
return [
|
|
LinkIssue(
|
|
source=markdown_path,
|
|
line_number=0,
|
|
target=str(markdown_path),
|
|
resolved_path=markdown_path,
|
|
message=f"无法读取文件:{error}",
|
|
)
|
|
]
|
|
|
|
for reference in analysis.references:
|
|
try:
|
|
url = urlsplit(reference.url)
|
|
resolved = resolve_local_reference(markdown_path, reference.url)
|
|
except ValueError:
|
|
issues.append(LinkIssue(markdown_path, reference.line, reference.url, markdown_path, "链接格式无效"))
|
|
continue
|
|
if resolved is not None and not resolved.exists():
|
|
issues.append(LinkIssue(markdown_path, reference.line, reference.url, resolved, "本地目标不存在"))
|
|
continue
|
|
if reference.image or not url.fragment or url.scheme not in {"", "file"} or url.netloc and url.scheme != "file":
|
|
continue
|
|
target = resolved or markdown_path
|
|
if target.suffix.lower() not in {".md", ".markdown", ".html", ".htm", ".xhtml"} or not target.is_file():
|
|
continue
|
|
try:
|
|
if unquote(url.fragment) not in document_anchors(load(target)):
|
|
issues.append(LinkIssue(markdown_path, reference.line, reference.url, target, "章节锚点不存在"))
|
|
except (OSError, UnicodeError):
|
|
issues.append(LinkIssue(markdown_path, reference.line, reference.url, target, "无法读取链接目标"))
|
|
|
|
return issues
|
|
|
|
|
|
def _extract_targets(source: str) -> list[str]:
|
|
return [reference.url for reference in analyze_document(source).references]
|
|
|
|
|
|
def _resolve_local_target(markdown_path: Path, target: str) -> Path | None:
|
|
return resolve_local_reference(markdown_path, target)
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(description="检查 MDHelper 文档中的本地链接和媒体引用。")
|
|
parser.add_argument("project_root", nargs="?", default=".", help="项目根目录,默认使用当前目录。")
|
|
args = parser.parse_args(argv)
|
|
|
|
root = Path(args.project_root).resolve()
|
|
issues = check_documents(root)
|
|
if not issues:
|
|
print("文档检查通过:未发现缺失的本地链接或媒体。")
|
|
return 0
|
|
|
|
print(f"发现 {len(issues)} 个文档引用问题:")
|
|
for issue in issues:
|
|
try:
|
|
source = issue.source.relative_to(root)
|
|
except ValueError:
|
|
source = issue.source
|
|
print(f"- {source}:{issue.line_number} {issue.message}: {issue.target}")
|
|
print(f" -> {issue.resolved_path}")
|
|
return 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|