97 lines
3.0 KiB
Python
97 lines
3.0 KiB
Python
from __future__ import annotations
|
|
|
|
import argparse
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from .document_resources import analyze_document, resolve_local_reference
|
|
|
|
|
|
@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:
|
|
source = markdown_path.read_text(encoding="utf-8")
|
|
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 analyze_document(source).references:
|
|
resolved = resolve_local_reference(markdown_path, reference.url)
|
|
if resolved is not None and not resolved.exists():
|
|
issues.append(LinkIssue(markdown_path, reference.line, reference.url, resolved, "本地目标不存在"))
|
|
|
|
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())
|