Initial MDHelper implementation
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
from urllib.request import url2pathname
|
||||
|
||||
|
||||
EXTERNAL_SCHEMES = {"http", "https", "mailto", "tel", "data", "qrc"}
|
||||
MARKDOWN_LINK_PATTERN = re.compile(r"!?\[[^\]]*]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
|
||||
HTML_LINK_PATTERN = re.compile(r"""(?:src|href)=["']([^"']+)["']""", flags=re.IGNORECASE)
|
||||
|
||||
|
||||
@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]:
|
||||
files: set[Path] = set()
|
||||
|
||||
for pattern in ("*.md", "*.markdown"):
|
||||
files.update(path.resolve() for path in project_root.glob(pattern) if path.is_file())
|
||||
|
||||
docs_root = project_root / "docs"
|
||||
if docs_root.exists():
|
||||
for pattern in ("*.md", "*.markdown"):
|
||||
files.update(path.resolve() for path in docs_root.rglob(pattern) if path.is_file())
|
||||
|
||||
return sorted(files)
|
||||
|
||||
|
||||
def check_documents(project_root: Path) -> list[LinkIssue]:
|
||||
root = project_root.resolve()
|
||||
issues: list[LinkIssue] = []
|
||||
|
||||
for markdown_path in discover_markdown_files(root):
|
||||
issues.extend(check_markdown_file(markdown_path))
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def check_markdown_file(markdown_path: Path) -> list[LinkIssue]:
|
||||
issues: list[LinkIssue] = []
|
||||
try:
|
||||
lines = markdown_path.read_text(encoding="utf-8").splitlines()
|
||||
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 line_number, line in enumerate(lines, start=1):
|
||||
for target in _extract_targets(line):
|
||||
resolved = _resolve_local_target(markdown_path, target)
|
||||
if resolved is not None and not resolved.exists():
|
||||
issues.append(
|
||||
LinkIssue(
|
||||
source=markdown_path,
|
||||
line_number=line_number,
|
||||
target=target,
|
||||
resolved_path=resolved,
|
||||
message="本地目标不存在",
|
||||
)
|
||||
)
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def _extract_targets(line: str) -> list[str]:
|
||||
targets = MARKDOWN_LINK_PATTERN.findall(line)
|
||||
targets.extend(HTML_LINK_PATTERN.findall(line))
|
||||
return [target.strip().strip("<>") for target in targets if target.strip()]
|
||||
|
||||
|
||||
def _resolve_local_target(markdown_path: Path, target: str) -> Path | None:
|
||||
parsed = urlsplit(target)
|
||||
if parsed.scheme in EXTERNAL_SCHEMES or parsed.path.startswith("#"):
|
||||
return None
|
||||
if parsed.scheme and parsed.scheme != "file":
|
||||
return None
|
||||
if not parsed.path:
|
||||
return None
|
||||
|
||||
if parsed.scheme == "file":
|
||||
return Path(url2pathname(unquote(parsed.path))).resolve()
|
||||
|
||||
return (markdown_path.parent / unquote(parsed.path)).resolve()
|
||||
|
||||
|
||||
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())
|
||||
Reference in New Issue
Block a user