94 lines
2.8 KiB
Python
94 lines
2.8 KiB
Python
# -*- coding: utf-8 -*-
|
|||
|
|
"""校验 Markdown 内部链接:目标文件是否存在、锚点是否命中。
|
||
|
|
|
||
|
|
Gitea 规则(实测):
|
||
|
|
标题 id = "user-content-" + anchor(标题原文)
|
||
|
|
anchor = 小写,保留字母数字汉字与下划线,空格变 -,其余字符全删
|
||
|
|
同文件链接写 #anchor —— Gitea 渲染时自动补 user-content-
|
||
|
|
跨文件链接写 file.md#user-content-anchor —— Gitea 不补,必须手写
|
||
|
|
|
||
|
|
用法:
|
||
|
|
python check_md_links.py <目录或文件> [更多...]
|
||
|
|
"""
|
||
|
|
import os
|
||
|
|
import re
|
||
|
|
import sys
|
||
|
|
|
||
|
|
|
||
|
|
def anchor(title):
|
||
|
|
out = []
|
||
|
|
for ch in title.lower():
|
||
|
|
if ch.isalnum() or ch == '_':
|
||
|
|
out.append(ch)
|
||
|
|
elif ch in ' \t':
|
||
|
|
out.append('-')
|
||
|
|
return ''.join(out)
|
||
|
|
|
||
|
|
|
||
|
|
def read(p):
|
||
|
|
with open(p, encoding='utf-8', newline='') as f:
|
||
|
|
return f.read().replace('\r\n', '\n')
|
||
|
|
|
||
|
|
|
||
|
|
def headings(txt):
|
||
|
|
return [m.group(1).strip()
|
||
|
|
for m in re.finditer(r'^#{1,6}\s+(.*)$', txt, re.M)]
|
||
|
|
|
||
|
|
|
||
|
|
def collect(paths):
|
||
|
|
files = []
|
||
|
|
for p in paths:
|
||
|
|
if os.path.isdir(p):
|
||
|
|
for fn in sorted(os.listdir(p)):
|
||
|
|
if fn.endswith('.md'):
|
||
|
|
files.append(os.path.join(p, fn))
|
||
|
|
else:
|
||
|
|
files.append(p)
|
||
|
|
return files
|
||
|
|
|
||
|
|
|
||
|
|
LINK = re.compile(r'\[([^\]]*)\]\(([^)\s]+)\)')
|
||
|
|
|
||
|
|
|
||
|
|
def main(paths):
|
||
|
|
files = collect(paths)
|
||
|
|
ids = {}
|
||
|
|
for p in files:
|
||
|
|
ids[os.path.abspath(p)] = {anchor(t) for t in headings(read(p))}
|
||
|
|
|
||
|
|
bad = 0
|
||
|
|
total = 0
|
||
|
|
for p in files:
|
||
|
|
base = os.path.dirname(p)
|
||
|
|
txt = read(p)
|
||
|
|
# 跳过围栏代码块中的链接
|
||
|
|
txt = re.sub(r'^```.*?^```', '', txt, flags=re.M | re.S)
|
||
|
|
for text, target in LINK.findall(txt):
|
||
|
|
if target.startswith(('http://', 'https://', 'mailto:')):
|
||
|
|
continue
|
||
|
|
total += 1
|
||
|
|
if '#' in target:
|
||
|
|
tfile, frag = target.split('#', 1)
|
||
|
|
else:
|
||
|
|
tfile, frag = target, None
|
||
|
|
tgt = os.path.abspath(os.path.join(base, tfile)) if tfile else os.path.abspath(p)
|
||
|
|
tag = '%s -> %s' % (os.path.basename(p), target)
|
||
|
|
if not os.path.exists(tgt):
|
||
|
|
print(' ✗ 文件不存在 %s' % tag)
|
||
|
|
bad += 1
|
||
|
|
continue
|
||
|
|
if frag is None:
|
||
|
|
continue
|
||
|
|
pure = frag[len('user-content-'):] if frag.startswith('user-content-') else frag
|
||
|
|
if pure not in ids.get(tgt, set()):
|
||
|
|
print(' ✗ 锚点未命中 %s' % tag)
|
||
|
|
bad += 1
|
||
|
|
print('检查 %d 个文件、%d 条内部链接,异常 %d 条' % (len(files), total, bad))
|
||
|
|
return 0 if bad == 0 else 1
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
if len(sys.argv) < 2:
|
||
|
|
raise SystemExit(__doc__)
|
||
|
|
raise SystemExit(main(sys.argv[1:]))
|