You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

356 lines
19 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# -*- coding: utf-8 -*-
"""Аудит репозитория: ссылки, обращения к файлам, дубли, заглушки, обозначения стандартов.
Запуск (из корня проекта): python3 -I tools/check_repo.py [--external]
--external — дополнительно проверить внешние URL (последовательно, тайм-аут 20 с)
Выход: out/audit/audit.json и out/audit/audit.md; код возврата 1, если есть ошибки (битые ссылки и т. п.).
Что проверяется:
1. Markdown-ссылки и изображения [..](..), <img src>, <a href> во всех отслеживаемых .md — существование цели
(относительно файла), якоря #… (правило Gitea/GitHub для заголовков).
2. Обращения к файлам в `код`-вставках (путь с расширением) в .md и строках документации .py: файл должен
существовать относительно корня, папки документа, norm/ или norm/src/<группа>/; отдельно — пути с «…».
3. Дубли: одинаковые файлы (sha256); одинаковые абзацы/строки (≥ 80 символов) в разных местах .md.
4. Заглушки («дописывается», TODO, TBD, FIXME) и сдвоенные слова.
5. Обозначения стандартов: один номер — разные годы; «ГОСТ» и «ГОСТ Р» для одного номера.
"""
import collections
import hashlib
import json
import os
import re
import subprocess
import sys
import unicodedata
import urllib.parse
import urllib.request
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT = os.path.join(ROOT, "out", "audit")
GENERATED_AGGREGATE = re.compile(r"^out/report/.*\.md$") # собранная записка — сознательный дубль разделов
def tracked():
r = subprocess.run(["git", "-c", "core.quotePath=false", "ls-files"], cwd=ROOT, capture_output=True, text=True)
# собственный отчёт проверки (out/audit/) цитирует найденное — сам не проверяется
return [x for x in r.stdout.splitlines() if x and not x.startswith("out/audit/")]
def read(rel):
with open(os.path.join(ROOT, rel), encoding="utf-8", errors="replace") as f:
return f.read()
# ------------------------------------------------------------------------------------------- якоря
def slug(h):
"""Якорь заголовка по правилу goldmark/GitHub (Gitea): нижний регистр, без знаков, пробел → «-»."""
h = re.sub(r"<[^>]+>", "", h)
h = re.sub(r"[`*_]", "", h).strip().lower()
out = []
for ch in h:
cat = unicodedata.category(ch)
if ch in " -":
out.append("-" if ch == " " else "-")
elif cat[0] in ("L", "N") or ch == "_":
out.append(ch)
return "".join(out)
def anchors(rel, cache={}):
if rel not in cache:
a = set()
cnt = collections.Counter()
in_code = False
for line in read(rel).splitlines():
if line.strip().startswith("```"):
in_code = not in_code
continue
m = re.match(r"^(#{1,6})\s+(.*?)\s*#*\s*$", line)
if m and not in_code:
s = slug(m.group(2))
n = cnt[s]
a.add(s if n == 0 else "%s-%d" % (s, n))
cnt[s] += 1
cache[rel] = a
return cache[rel]
# ------------------------------------------------------------------------------------------- ссылки
LINK_RE = re.compile(r"(?<!\\)!?\[(?:[^\[\]]|\[[^\]]*\])*(?<!\\)\]\(\s*<?([^)\s>]+)>?(?:\s+\"[^\"]*\")?\s*\)")
HTML_RE = re.compile(r"(?:src|href)=\"([^\"]+)\"")
BARE_URL_RE = re.compile(r"https?://[^\s)<>\"'`|\]\[]+")
CODE_PATH_RE = re.compile(r"`([^`\s]*?/[^`\s]*?\.(?:png|pdf|md|py|json|tsv|htm|html|gif|txt|step|FCStd|dxf|sh|csv))`")
CODE_FILE_RE = re.compile(r"`([A-Za-z0-9_.\-]+\.(?:md|py|json|tsv|step|FCStd|sh))`")
def strip_code_blocks(text):
return re.sub(r"```.*?```", "", text, flags=re.S)
def check_links(files):
errs, ext = [], collections.defaultdict(set)
for rel in files:
if not rel.endswith(".md"):
continue
base = os.path.dirname(rel)
text = strip_code_blocks(read(rel))
targets = [(m.group(1), "md") for m in LINK_RE.finditer(text)] + [(m.group(1), "html") for m in HTML_RE.finditer(text)]
for t, kind in targets:
if t.startswith(("http://", "https://")):
ext[t.rstrip(".,;")].add(rel)
continue
if t.startswith("mailto:"):
continue
path, _, anc = t.partition("#")
path = urllib.parse.unquote(path)
tgt = os.path.normpath(os.path.join(base, path)) if path else rel
if path and not os.path.exists(os.path.join(ROOT, tgt)):
errs.append(dict(file=rel, link=t, problem="цель не найдена: %s" % tgt))
continue
if path and tgt.startswith(".."):
errs.append(dict(file=rel, link=t, problem="ссылка выходит за пределы репозитория"))
if path and os.path.exists(os.path.join(ROOT, tgt)) and tgt not in TRACKED and not os.path.isdir(os.path.join(ROOT, tgt)):
errs.append(dict(file=rel, link=t, problem="цель существует локально, но не в git: %s" % tgt))
if anc:
if tgt.endswith(".md") and os.path.exists(os.path.join(ROOT, tgt)):
if urllib.parse.unquote(anc).lower() not in anchors(tgt):
errs.append(dict(file=rel, link=t, problem="якорь не найден в %s" % tgt))
# «голые» адреса во всех текстовых файлах (манифесты, конспекты, комментарии кода)
for rel in files:
if not rel.endswith((".md", ".tsv", ".py", ".sh", ".json", ".txt", ".toml", ".cfg")) or rel.startswith("out/"):
continue
for m in BARE_URL_RE.finditer(read(rel)):
u = m.group(0).rstrip(".,;:")
# шаблоны с переменными оболочки и локальные адреса (RPC FreeCAD) — не внешние ссылки
if "${" in u or "$(" in u or re.match(r"https?://(127\.0\.0\.1|localhost)\b", u):
continue
ext[u].add(rel)
return errs, ext
def resolve_ref(rel, p):
"""Обращение к файлу из текста: варианты базы — корень, папка документа, norm/, norm/src/<группа>/."""
p = p.strip().rstrip(".,;:")
cands = [p, os.path.join(os.path.dirname(rel), p), os.path.join("norm", p)]
for g in GROUPS:
cands.append(os.path.join("norm", "src", g, p))
for c in cands:
c = os.path.normpath(c)
if os.path.exists(os.path.join(ROOT, c)):
return c
return None
def check_code_refs(files):
missing, ellipsis, local_only, ok = [], [], 0, 0
for rel in files:
if not (rel.endswith(".md") or rel.endswith(".py")):
continue
if GENERATED_AGGREGATE.match(rel):
continue
text = read(rel)
for m in list(CODE_PATH_RE.finditer(text)) + list(CODE_FILE_RE.finditer(text)):
p = m.group(1)
if p.startswith(("http://", "https://")) or any(x in p for x in ("*", "<", ">", "{", "}", "NNN", "0NN", "N.png", "XX")):
continue
if "…" in p or "..." in p.replace("../", ""):
d = os.path.dirname(p.split("…")[0]) if not p.startswith("…") else ""
base = [os.path.join("norm", d), d, os.path.join(os.path.dirname(rel), d)] if d else []
if not any(os.path.isdir(os.path.join(ROOT, b)) for b in base):
ellipsis.append(dict(file=rel, ref=p)) # «…/» в начале или неизвестная папка — двусмысленно
else:
ok += 1 # диапазон страниц в явной папке документа
continue
r = resolve_ref(rel, p)
if r is None:
missing.append(dict(file=rel, ref=p))
else:
ok += 1
if r not in TRACKED and not os.path.isdir(os.path.join(ROOT, r)):
local_only += 1
return missing, ellipsis, ok, local_only
# ------------------------------------------------------------------------------------------- дубли
def check_dups(files):
by_hash = collections.defaultdict(list)
for rel in files:
p = os.path.join(ROOT, rel)
if os.path.isfile(p):
with open(p, "rb") as f:
by_hash[hashlib.sha256(f.read()).hexdigest()].append(rel)
same_files = [v for v in by_hash.values() if len(v) > 1]
seen = collections.defaultdict(list)
for rel in files:
if not rel.endswith(".md") or GENERATED_AGGREGATE.match(rel):
continue
for i, line in enumerate(strip_code_blocks(read(rel)).splitlines(), 1):
s = re.sub(r"\s+", " ", line).strip()
if len(s) < 80 or set(s) <= set("|-: ") or s.startswith("|") or re.search(r"— (выполнено|НЕ ВЫПОЛНЕНО)", s):
continue # таблицы и строки проверок расчёта — структурные повторы
seen[s].append((rel, i))
dup_lines = [dict(text=k[:160], where=["%s:%d" % w for w in v]) for k, v in seen.items() if len(v) > 1]
return same_files, dup_lines
def check_text(files):
ph, doubles = [], []
for rel in files:
if not rel.endswith(".md") or GENERATED_AGGREGATE.match(rel):
continue
for i, line in enumerate(read(rel).splitlines(), 1):
if re.search(r"(?i)дописыва|\bTODO\b|\bTBD\b|\bFIXME\b", line):
ph.append(dict(file=rel, line=i, text=line.strip()[:160]))
for m in re.finditer(r"(?<![\w\-])([А-Яа-яЁёA-Za-z]{2,})\s+\1(?![\w\-])", line, flags=re.I):
doubles.append(dict(file=rel, line=i, word=m.group(0)))
return ph, doubles
# ------------------------------------------------------------------------------------------- стандарты
STD_RE = re.compile(r"(ГОСТ\s+Р|ГОСТ|СТ\s+ЦКБА|СТО\s+Газпром|ОСТ|ПНАЭ\s+Г|СП)\s*((?:\d+[.\-])*\d+)(?:[-–](\d{2,4}))?(?![\d.])")
def check_standards(files):
uses = collections.defaultdict(lambda: collections.defaultdict(set))
kinds = collections.defaultdict(set)
for rel in files:
if not (rel.endswith(".md") or rel.endswith(".py")) or GENERATED_AGGREGATE.match(rel):
continue
text_std = read(rel)
for m in STD_RE.finditer(text_std):
line_ctx = text_std[text_std.rfind("\n", 0, m.start()) + 1: text_std.find("\n", m.end())]
historical = bool(re.search(r"(?i)взамен|замен|отмен|исключ|устарел|прежн|старая|исх\. ред|изд\. 19|"
r"издани[ея] 19|→|действует ГОСТ Р|в РФ — ГОСТ Р|не существует|Заменён|\| Действует \|", line_ctx))
kind = re.sub(r"\s+", " ", m.group(1))
num, year = m.group(2), m.group(3)
if kind == "СТО Газпром":
parts = num.split("-")
if len(parts) >= 2 and re.fullmatch(r"(19|20)\d\d", parts[-1]):
num, year = "-".join(parts[:-1]), parts[-1]
elif year is None and re.search(r"-(\d{2}|\d{4})$", num) and kind in ("ГОСТ", "ГОСТ Р", "СТ ЦКБА"):
num, year = num.rsplit("-", 1)
if kind in ("ГОСТ", "ГОСТ Р") and "-" in num:
continue
if historical and year:
HIST[(kind, num)].add(year) # упоминание редакции в контексте замены — не конфликт
continue
key = num
kinds[key].add(kind)
uses[key][year or "—"].add(rel)
conflicts = []
for num, ys in sorted(uses.items()):
years = {y for y in ys if y != "—"}
if len(years) > 1 or len(kinds[num]) > 1:
conflicts.append(dict(number=num, kinds=sorted(kinds[num]),
years={y: sorted(v)[:6] for y, v in sorted(ys.items())}))
catalog = {num: dict(kinds=sorted(kinds[num]), years=sorted(ys)) for num, ys in sorted(uses.items())}
return conflicts, catalog
# ------------------------------------------------------------------------------------------- внешние URL
def check_external(ext):
for k in ("all_proxy", "ALL_PROXY", "http_proxy", "https_proxy"):
os.environ.pop(k, None)
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
res = []
for url in sorted(ext):
code, err = None, ""
for method in ("HEAD", "GET"):
try:
req = urllib.request.Request(url, method=method, headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 Chrome/126 Safari/537.36"})
with opener.open(req, timeout=20) as r:
code = r.status
break
except urllib.error.HTTPError as e:
code, err = e.code, str(e.reason)
if e.code not in (403, 405, 501):
break
except Exception as e:
code, err = None, type(e).__name__ + ": " + str(e)[:80]
res.append(dict(url=url, status=code, error=err, used_in=sorted(ext[url])[:4]))
return res
def main():
global TRACKED, GROUPS
files = tracked()
TRACKED = set(files)
GROUPS = sorted(d for d in os.listdir(os.path.join(ROOT, "norm", "src")) if os.path.isdir(os.path.join(ROOT, "norm", "src", d)))
link_errs, ext = check_links(files)
missing, ellipsis, ok_refs, local_only = check_code_refs(files)
same_files, dup_lines = check_dups(files)
ph, doubles = check_text(files)
conflicts, catalog = check_standards(files)
ext_res = check_external(ext) if "--external" in sys.argv else []
bad_ext = [r for r in ext_res if not (r["status"] and r["status"] < 400)]
rep = dict(files=len(files), link_errors=link_errs, external_total=len(ext), external_bad=bad_ext,
code_refs_ok=ok_refs, code_refs_local_only=local_only, code_refs_missing=missing,
code_refs_ellipsis=ellipsis, same_files=same_files, dup_lines=dup_lines, placeholders=ph,
doubled_words=doubles, standard_conflicts=conflicts, standards=catalog)
os.makedirs(OUT, exist_ok=True)
with open(os.path.join(OUT, "audit.json"), "w", encoding="utf-8") as f:
json.dump(rep, f, ensure_ascii=False, indent=1)
L = ["# Аудит репозитория", "",
"| Проверка | Результат |", "|---|---|",
"| Отслеживаемых файлов | %d |" % len(files),
"| Битые ссылки и якоря в .md | %d |" % len(link_errs),
"| Внешние URL (уникальных) | %d%s |" % (len(ext), "; недоступных: %d" % len(bad_ext) if ext_res else " (не проверялись)"),
"| Обращения к файлам в тексте: найдено / только локально (вне git) / не найдено / с «…» | %d / %d / %d / %d |"
% (ok_refs, local_only, len(missing), len(ellipsis)),
"| Одинаковые файлы | %d групп |" % len(same_files),
"| Повторяющиеся строки (≥ 80 символов) | %d |" % len(dup_lines),
"| Заглушки | %d |" % len(ph), "| Сдвоенные слова | %d |" % len(doubles),
"| Стандарты: обозначений / с разными годами или видом | %d / %d |" % (len(catalog), len(conflicts)), ""]
D = [] # подробности — в тот же audit.md
for name, items in (("Битые ссылки", link_errs), ("Не найдены файлы", missing), ("Пути с «…»", ellipsis),
("Заглушки", ph), ("Сдвоенные слова", doubles)):
if items:
D += ["## %s (%d)" % (name, len(items)), ""] + ["- `%s`" % json.dumps(x, ensure_ascii=False)[:230] for x in items] + [""]
if same_files:
D += ["## Одинаковые файлы", ""] + ["- " + ", ".join("`%s`" % f for f in g) for g in same_files] + [""]
if conflicts:
D += ["## Стандарты: один номер — разные годы/вид (%d)" % len(conflicts), ""]
D += ["- %s %s: %s" % ("/".join(c["kinds"]), c["number"], ", ".join(c["years"])) for c in conflicts] + [""]
if ext_res:
D += ["## Внешние URL: недоступные или с ошибкой (%d из %d)" % (len(bad_ext), len(ext_res)), ""]
if bad_ext:
D += ["| Код | Ошибка | URL | Где упоминается |", "|---|---|---|---|"]
D += ["| %s | %s | <%s> | %s |" % (r["status"] or "—", (r["error"] or "").replace("|", "/")[:60], r["url"],
", ".join("`%s`" % u for u in r["used_in"][:3])) for r in bad_ext]
else:
D += ["Все внешние адреса ответили кодом < 400."]
D += [""]
with open(os.path.join(OUT, "audit.md"), "w", encoding="utf-8") as f:
f.write("\n".join(L + D) + "\n")
print("\n".join(L))
for name, items in (("Битые ссылки", link_errs), ("Не найдены файлы", missing), ("Пути с «…»", ellipsis),
("Заглушки", ph), ("Сдвоенные слова", doubles)):
if items:
print("\n== %s (%d):" % (name, len(items)))
for x in items[:60]:
print(" ", json.dumps(x, ensure_ascii=False)[:230])
if same_files:
print("\n== Одинаковые файлы:")
for g in same_files:
print(" ", g)
if dup_lines:
print("\n== Повторяющиеся строки (%d):" % len(dup_lines))
for d in dup_lines[:40]:
print(" %s <- %s" % (d["text"][:110], ", ".join(d["where"][:4])))
if conflicts:
print("\n== Стандарты: разные годы/вид (%d):" % len(conflicts))
for c in conflicts:
print(" %s %s: %s" % ("/".join(c["kinds"]), c["number"], {y: v[:3] for y, v in c["years"].items()}))
if bad_ext:
print("\n== Недоступные внешние URL (%d):" % len(bad_ext))
for r in bad_ext:
print(" %s %s %s <- %s" % (r["status"], r["error"][:40], r["url"][:110], r["used_in"][:2]))
sys.exit(1 if (link_errs or missing) else 0)
TRACKED, GROUPS = set(), []
HIST = collections.defaultdict(set)
if __name__ == "__main__":
main()

Powered by TurnKey Linux.