Datasets:
Download code/evaluation-code/ent400-a06a1576/tools/workspace/doc_refs.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 9.23 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/tools/workspace/doc_refs.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/ent400-a06a1576/tools/workspace/doc_refs.py
-
curl -L -o doc_refs.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/tools/workspace/doc_refs.py
9.23 kB
| #!/usr/bin/env python3 | |
| """文档和注释里对代码的引用、写死的计数,和现状对不上就报。 | |
| 扫 git 跟踪的 *.md 全文,和 *.py 的注释、语句级字符串(文档串);路径里带 archive 的不查。四条规则: | |
| - 引用写成“文件(名字)”,名字要在那个文件里存在;不许写“文件:行号”(行号一改代码就漂)。 | |
| 名字用“、”“,”分隔,可带“等”;不是标识符的(如“文件尾”)跳过。文件按写法找:先照仓库根、再照文档所在目录; | |
| 只写文件名的,文档所在目录下的优先,候选必须唯一且实路径位于仓库内。 | |
| 其他语言明确报未支持;仓库里找不到的文件当外部代码,不核名字。 | |
| - 以仓库顶层目录开头的 .py、.md、.sh 路径要存在(runs/ 不在检查范围内)。 | |
| - “N 个母题、子题、问法、版本(版)”要等于 catalog 现算的某个计数(CatalogReader.counts 和各 status 的版本数);退役登记按归档计数; | |
| 版数比最小的计数还小的是局部举例(如“3 版”),不核;编号、比例、分辨率、日期里的数(C2、35/112、128×128、09-30 版)不算; | |
| 带“旧、原先、原设计、当时、曾”或日期的行记的是当时的数,不核。 | |
| """ | |
| import ast | |
| import io | |
| import json | |
| import re | |
| import subprocess | |
| import sys | |
| import tokenize | |
| from pathlib import Path | |
| LINE_REF = re.compile(r"(?<![\w./-])[A-Za-z0-9_./-]+\.(?:py|js|ts|json|sh):\d+") | |
| NAMED_REF = re.compile(r"([A-Za-z0-9_./-]+\.(?:py|js|ts|sh))(([^)]*))") | |
| IDENT = re.compile(r"[A-Za-z_][\w.]*") | |
| PATH = re.compile(r"(?<![\w./~-])((?:[\w-]+/)+[\w.-]+\.(?:py|md|sh))\b") | |
| COUNT = re.compile(r"(?<![A-Za-z0-9_/×.-])(\d+)\s*个?\s*(母题|子题|问法|版本|版)(?![\w])") | |
| PAST = re.compile(r"旧|原先|原设计|原\d|当时|曾|(?<!\d)\d{1,2}-\d{2}(?!\d)") # 记历史的行:写的是当时的数 | |
| UNITS = {"版本": "版"} | |
| # 版数前面紧挨着口径名的,只认那个口径的数:现行、暂停按 availability,在册是 planned+v0,候选是 candidate | |
| SCOPES = re.compile(r"(现行|在册|候选|暂停|退役登记)[^\d,。;、]{0,6}$") | |
| def catalog_counts(root): | |
| """单位 -> 现算计数集合;目录从 CatalogReader 取,退役登记从归档取。""" | |
| sys.path.insert(0, str(root)) | |
| from spec.questions.core.catalog_reader import CatalogReader | |
| reader = CatalogReader(catalog=root / "spec/questions/catalog.json", v0=root / "spec/questions/v0.json") | |
| c = reader.counts() | |
| status = reader.version_status_counts() | |
| archive = json.loads((root / "spec/questions/archive/retired-20261109.json").read_text()) | |
| versions = {c["versions"], c["v0_versions"], c["versions_active"], c["versions_paused"], *status.values(), | |
| c["versions"] - status.get("candidate", 0)} | |
| return {"母题": {c["families"]}, "子题": {c["subtasks"]}, "问法": {c["forms"], c["v0_forms"]}, "版": versions, | |
| "版·现行": {c["versions_active"]}, "版·暂停": {c["versions_paused"]}, | |
| "版·在册": {status.get("planned", 0) + status.get("v0", 0)}, "版·候选": {status.get("candidate", 0)}, | |
| "版·退役登记": {len(archive["versions"])}} | |
| def py_texts(text): | |
| """.py 里的注释和语句级字符串(文档串),逐行给出 (行号, 文字)。""" | |
| prev = tokenize.NEWLINE | |
| try: | |
| for t in tokenize.generate_tokens(io.StringIO(text).readline): | |
| if t.type == tokenize.COMMENT or (t.type == tokenize.STRING and prev in (tokenize.NEWLINE, tokenize.NL, tokenize.INDENT, tokenize.DEDENT)): | |
| yield from enumerate(t.string.splitlines(), t.start[0]) | |
| if t.type not in (tokenize.COMMENT, tokenize.NL): | |
| prev = t.type | |
| except (tokenize.TokenError, SyntaxError): | |
| return | |
| def resolve(root, files, doc, written): | |
| root = root.resolve() | |
| def contained(paths): | |
| found = set() | |
| for path in paths: | |
| real = path.resolve() | |
| if not real.is_relative_to(root): | |
| raise ValueError('引用指向仓库外') | |
| if real.is_file(): | |
| found.add(real) | |
| return sorted(found) | |
| direct = contained((root / written, (root / doc).parent / written)) | |
| if direct: | |
| return direct | |
| same = [f for f in files if f == written or f.endswith("/" + written)] | |
| near = [f for f in same if f.startswith(str(Path(doc).parent) + "/")] | |
| return contained(root / f for f in (near or same)) | |
| def python_symbols(path): | |
| """按声明所在作用域收集绑定,不把注释、字符串或别的类的方法当符号。""" | |
| symbols = set() | |
| class Bindings(ast.NodeVisitor): | |
| scope = '' | |
| def declare(self, node): | |
| name = self.scope + node.name | |
| symbols.add(name) | |
| outer, self.scope = self.scope, name + '.' | |
| self.generic_visit(node) | |
| self.scope = outer | |
| visit_ClassDef = visit_FunctionDef = visit_AsyncFunctionDef = declare | |
| def visit_Name(self, node): | |
| if isinstance(node.ctx, ast.Store): | |
| symbols.add(self.scope + node.id) | |
| def visit_Attribute(self, node): | |
| if isinstance(node.ctx, ast.Store): | |
| symbols.add(self.scope + node.attr) | |
| self.generic_visit(node) | |
| def visit_Import(self, node): | |
| for alias in node.names: | |
| symbols.add(self.scope + (alias.asname or alias.name.split('.')[0])) | |
| def visit_ImportFrom(self, node): | |
| for alias in node.names: | |
| if alias.name != '*': | |
| symbols.add(self.scope + (alias.asname or alias.name)) | |
| Bindings().visit(ast.parse(path.read_text(), filename=str(path))) | |
| return symbols | {name.rsplit('.', 1)[-1] for name in symbols} | |
| def check(root, counts=None): | |
| root = Path(root) | |
| files = subprocess.run(["git", "ls-files"], cwd=root, capture_output=True, text=True, check=True).stdout.split() | |
| tracked, tops = set(files), {f.split("/")[0] for f in files if "/" in f} - {"runs"} | |
| counts = catalog_counts(root) if counts is None else counts | |
| bad, symbol_cache = [], {} | |
| for doc in files: | |
| if not doc.endswith((".md", ".py")) or "archive" in Path(doc).parts: | |
| continue | |
| text = (root / doc).read_text() | |
| for i, line in (enumerate(text.splitlines(), 1) if doc.endswith(".md") else py_texts(text)): | |
| line = line.replace("`", "") | |
| for p in PATH.findall(line): | |
| if p.split("/")[0] in tops and p not in tracked and not ((root / doc).parent / p).is_file(): | |
| bad.append((doc, i, p, "路径不存在")) | |
| for m in ([] if PAST.search(line) else COUNT.finditer(line)): | |
| n, unit = m.groups(); unit = UNITS.get(unit, unit) | |
| scope = SCOPES.search(line[:m.start()]) if unit == "版" else None | |
| if scope and unit + "·" + scope[1] in counts: | |
| allowed = counts[unit + "·" + scope[1]] | |
| if int(n) not in allowed: | |
| bad.append((doc, i, n + unit, f"catalog 现算的{scope[1]}版数是 {sorted(allowed)},写的数对不上")) | |
| continue | |
| allowed = counts.get(unit, set()) | |
| if allowed and int(n) not in allowed and not (unit == '版' and int(n) < min(allowed)): | |
| bad.append((doc, i, n + unit, f"catalog 现算的{unit}数是 {sorted(allowed)},写死的数过时了")) | |
| bad += [(doc, i, m, "写成了“文件:行号”,改成“文件(名字)”") for m in LINE_REF.findall(line)] | |
| for written, names in NAMED_REF.findall(line): | |
| names = [name.strip().removesuffix('等').strip() for name in re.split(r'[、,,]\s*', names)] | |
| names = [name for name in names if IDENT.fullmatch(name)] | |
| if not names: | |
| continue | |
| try: | |
| paths = resolve(root, files, doc, written) | |
| except ValueError as exc: | |
| bad.append((doc, i, written, str(exc))) | |
| continue | |
| if not paths: | |
| continue | |
| if len(paths) != 1: | |
| bad.append((doc, i, written, '同名文件不唯一,请写明确路径')) | |
| continue | |
| if paths[0].suffix != '.py': | |
| bad.append((doc, i, written, '此语言的符号检查尚不支持')) | |
| continue | |
| path = paths[0] | |
| if path not in symbol_cache: | |
| symbol_cache[path] = python_symbols(path) | |
| for name in names: | |
| if name.removeprefix(path.stem + '.') not in symbol_cache[path]: | |
| bad.append((doc, i, f"{written}({name})", "名字在文件里找不到")) | |
| return bad | |
| def main(): | |
| bad = check(sys.argv[1] if len(sys.argv) > 1 else ".") | |
| for doc, i, ref, why in bad: | |
| print(f"{doc}:{i}: {ref}: {why}") | |
| return 1 if bad else 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |