@walvka-code/proj-doc-builder 0.0.0-stage → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +271 -2
- package/README.zh-CN.md +240 -0
- package/cordis.patch.yml +8 -0
- package/icon.svg +11 -0
- package/index.js +164 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +55 -4
- package/skills/proj-doc-builder/SKILL.md +350 -0
- package/skills/proj-doc-builder/references/audit_script.md +96 -0
- package/skills/proj-doc-builder/references/checklist.md +80 -0
- package/skills/proj-doc-builder/references/exclusions.md +79 -0
- package/skills/proj-doc-builder/references/linking.md +83 -0
- package/skills/proj-doc-builder/references/migration.md +32 -0
- package/skills/proj-doc-builder/references/phase4.md +200 -0
- package/skills/proj-doc-builder/references/templates.md +172 -0
- package/skills/proj-doc-builder/tests/__pycache__/conftest.cpython-314-pytest-9.0.3.pyc +0 -0
- package/skills/proj-doc-builder/tests/__pycache__/test_claude_doc_index.cpython-314-pytest-9.0.3.pyc +0 -0
- package/skills/proj-doc-builder/tests/__pycache__/test_link_tools.cpython-314-pytest-9.0.3.pyc +0 -0
- package/skills/proj-doc-builder/tests/__pycache__/test_load_docs.cpython-314-pytest-9.0.3.pyc +0 -0
- package/skills/proj-doc-builder/tests/__pycache__/test_normalize_markers.cpython-314-pytest-9.0.3.pyc +0 -0
- package/skills/proj-doc-builder/tests/__pycache__/test_phase4_exit.cpython-314-pytest-9.0.3.pyc +0 -0
- package/skills/proj-doc-builder/tests/__pycache__/test_project_docs_contract.cpython-314-pytest-9.0.3.pyc +0 -0
- package/skills/proj-doc-builder/tests/__pycache__/test_scan_dirs.cpython-314-pytest-9.0.3.pyc +0 -0
- package/skills/proj-doc-builder/tests/__pycache__/test_sync_project_docs.cpython-314-pytest-9.0.3.pyc +0 -0
- package/skills/proj-doc-builder/tests/conftest.py +11 -0
- package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
- package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
- package/skills/proj-doc-builder/tests/test_load_docs.py +248 -0
- package/skills/proj-doc-builder/tests/test_normalize_markers.py +120 -0
- package/skills/proj-doc-builder/tests/test_phase4_exit.py +3895 -0
- package/skills/proj-doc-builder/tests/test_project_docs_contract.py +781 -0
- package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
- package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
- package/skills/proj-doc-builder/tests/test_validate_doc.py +555 -0
- package/skills/proj-doc-builder/tools/__pycache__/claude_doc_index.cpython-314.pyc +0 -0
- package/skills/proj-doc-builder/tools/__pycache__/compute_link.cpython-314.pyc +0 -0
- package/skills/proj-doc-builder/tools/__pycache__/link_check.cpython-314.pyc +0 -0
- package/skills/proj-doc-builder/tools/__pycache__/load_docs.cpython-314.pyc +0 -0
- package/skills/proj-doc-builder/tools/__pycache__/normalize_markers.cpython-314.pyc +0 -0
- package/skills/proj-doc-builder/tools/__pycache__/phase4_exit.cpython-314.pyc +0 -0
- package/skills/proj-doc-builder/tools/__pycache__/project_docs_contract.cpython-314.pyc +0 -0
- package/skills/proj-doc-builder/tools/__pycache__/scan_dirs.cpython-314.pyc +0 -0
- package/skills/proj-doc-builder/tools/__pycache__/sync_project_docs.cpython-314.pyc +0 -0
- package/skills/proj-doc-builder/tools/claude_doc_index.py +298 -0
- package/skills/proj-doc-builder/tools/compute_link.py +233 -0
- package/skills/proj-doc-builder/tools/link_check.py +152 -0
- package/skills/proj-doc-builder/tools/load_docs.py +380 -0
- package/skills/proj-doc-builder/tools/normalize_markers.py +205 -0
- package/skills/proj-doc-builder/tools/phase4/__init__.py +57 -0
- package/skills/proj-doc-builder/tools/phase4/cas_storage.py +18 -0
- package/skills/proj-doc-builder/tools/phase4/engine.py +20 -0
- package/skills/proj-doc-builder/tools/phase4/journal.py +22 -0
- package/skills/proj-doc-builder/tools/phase4/platform_handles.py +20 -0
- package/skills/proj-doc-builder/tools/phase4_exit.py +8459 -0
- package/skills/proj-doc-builder/tools/project_docs_contract.py +2318 -0
- package/skills/proj-doc-builder/tools/scan_dirs.py +2405 -0
- package/skills/proj-doc-builder/tools/sync_project_docs.py +3639 -0
- package/skills/proj-doc-builder/tools/validate_doc.py +1299 -0
|
@@ -0,0 +1,1299 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Validate one generated ``project_docs`` document against its source directory.
|
|
3
|
+
|
|
4
|
+
The validator keeps the historical positional document argument and
|
|
5
|
+
``--source-dir``/``--strict``/``--json`` options, while adding explicit roots and
|
|
6
|
+
standard/placeholder profiles. Structural (critical) failures always produce a
|
|
7
|
+
non-zero CLI status; ``--strict`` also makes editorial failures fatal.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import ast
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path, PurePosixPath, PureWindowsPath
|
|
19
|
+
from typing import Any, Sequence
|
|
20
|
+
from urllib.parse import unquote
|
|
21
|
+
|
|
22
|
+
from project_docs_contract import (
|
|
23
|
+
LinkDisposition,
|
|
24
|
+
PathValidationError,
|
|
25
|
+
ProjectDocsContractError,
|
|
26
|
+
StrictUtf8Error,
|
|
27
|
+
parse_markdown_links,
|
|
28
|
+
read_utf8,
|
|
29
|
+
stable_json_dumps,
|
|
30
|
+
validate_manifest_relative_path,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
EXIT_OK = 0
|
|
34
|
+
EXIT_VALIDATION_FAILED = 1
|
|
35
|
+
EXIT_CRITICAL_ERROR = 2
|
|
36
|
+
RESULT_SCHEMA_VERSION = 1
|
|
37
|
+
|
|
38
|
+
PROFILE_AUTO = "auto"
|
|
39
|
+
PROFILE_STANDARD = "standard"
|
|
40
|
+
PROFILE_PLACEHOLDER = "placeholder"
|
|
41
|
+
PROFILES = (PROFILE_AUTO, PROFILE_STANDARD, PROFILE_PLACEHOLDER)
|
|
42
|
+
|
|
43
|
+
BANNED_WORDS = [
|
|
44
|
+
"工具文件",
|
|
45
|
+
"辅助函数",
|
|
46
|
+
"辅助功能",
|
|
47
|
+
"杂项",
|
|
48
|
+
"其他文件",
|
|
49
|
+
"各种工具",
|
|
50
|
+
"一些常量",
|
|
51
|
+
"一些函数",
|
|
52
|
+
"一些类",
|
|
53
|
+
"杂项文件",
|
|
54
|
+
"核心业务逻辑与基础设施功能",
|
|
55
|
+
"规范化的接口抽象、数据处理、状态维护以及执行支持",
|
|
56
|
+
"协同工作,确保整个生命周期的确定性、高可用与高一致性运行",
|
|
57
|
+
"接受全流程自动化测试与验证",
|
|
58
|
+
]
|
|
59
|
+
STATUS_ICONS = ("✅", "🔶", "⬜")
|
|
60
|
+
# Kept for callers that imported this historical module-level constant.
|
|
61
|
+
PY_EXTENSIONS = {".py", ".pyx", ".pyi"}
|
|
62
|
+
EXCLUDED_SOURCE_DIRS = {
|
|
63
|
+
".git",
|
|
64
|
+
".svn",
|
|
65
|
+
".venv",
|
|
66
|
+
"__pycache__",
|
|
67
|
+
".pytest_cache",
|
|
68
|
+
".mypy_cache",
|
|
69
|
+
".hypothesis",
|
|
70
|
+
"node_modules",
|
|
71
|
+
".lingma",
|
|
72
|
+
".deepseek",
|
|
73
|
+
".vscode",
|
|
74
|
+
".idea",
|
|
75
|
+
".settings",
|
|
76
|
+
".dsh",
|
|
77
|
+
"Debug",
|
|
78
|
+
"test_reports",
|
|
79
|
+
"_extract",
|
|
80
|
+
"target",
|
|
81
|
+
"project_docs",
|
|
82
|
+
"sub_plan",
|
|
83
|
+
}
|
|
84
|
+
CRITICAL_CHECK_IDS = frozenset({1, 4, 5, 8, 9})
|
|
85
|
+
|
|
86
|
+
_TABLE_SEPARATOR_RE = re.compile(r"^:?-{3,}:?$")
|
|
87
|
+
_INVALID_PERCENT_RE = re.compile(r"%(?![0-9A-Fa-f]{2})")
|
|
88
|
+
_URI_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
|
|
89
|
+
_LINK_CELL_RE = re.compile(
|
|
90
|
+
r"^\s*\[([^\]\r\n]*)\]\(\s*"
|
|
91
|
+
r"(<[^>\r\n]*>|[^\s)]+)"
|
|
92
|
+
r"(?:\s+(?:\"[^\"\r\n]*\"|'[^'\r\n]*'|\([^()\r\n]*\)))?\s*\)\s*$"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass(frozen=True)
|
|
97
|
+
class _ValidationContext:
|
|
98
|
+
doc_path: Path
|
|
99
|
+
docs_root: Path
|
|
100
|
+
doc_relative: str
|
|
101
|
+
project_root: Path
|
|
102
|
+
source_dir: Path | None
|
|
103
|
+
source_files: tuple[str, ...] | None
|
|
104
|
+
source_subdirs: tuple[str, ...] | None
|
|
105
|
+
profile: str
|
|
106
|
+
profile_mismatch: str | None = None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True)
|
|
110
|
+
class _TableRow:
|
|
111
|
+
cells: tuple[str, ...]
|
|
112
|
+
raw: str
|
|
113
|
+
line_number: int
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass(frozen=True)
|
|
117
|
+
class _ManifestRow:
|
|
118
|
+
name: str
|
|
119
|
+
row: _TableRow
|
|
120
|
+
link_target: str | None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _section(content: str, heading: str) -> str | None:
|
|
124
|
+
"""Extract a level-two Markdown section by its exact heading."""
|
|
125
|
+
|
|
126
|
+
pattern = rf"^##[ \t]+{re.escape(heading)}[ \t]*\r?\n(.*?)(?=^##[ \t]+|\Z)"
|
|
127
|
+
match = re.search(pattern, content, re.MULTILINE | re.DOTALL)
|
|
128
|
+
return match.group(1).strip() if match else None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _section_any(content: str, headings: Sequence[str]) -> str | None:
|
|
132
|
+
for heading in headings:
|
|
133
|
+
section_text = _section(content, heading)
|
|
134
|
+
if section_text is not None:
|
|
135
|
+
return section_text
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _strip_markdown(text: str) -> str:
|
|
140
|
+
text = re.sub(r"```.*?```", " ", text, flags=re.DOTALL)
|
|
141
|
+
text = re.sub(r"<!--.*?-->", " ", text, flags=re.DOTALL)
|
|
142
|
+
text = re.sub(r"!\[([^\]]*)\]\([^)]+\)", r"\1", text)
|
|
143
|
+
text = re.sub(r"\[([^\]]*)\]\([^)]+\)", r"\1", text)
|
|
144
|
+
text = re.sub(r"`([^`]*)`", r"\1", text)
|
|
145
|
+
text = re.sub(r"^[ \t]*(?:>|[-*+]\s+|\d+[.)]\s+)", "", text, flags=re.MULTILINE)
|
|
146
|
+
text = text.replace("**", "").replace("__", "").replace("~~", "")
|
|
147
|
+
return re.sub(r"\s+", " ", text).strip()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _sentence_count(text: str) -> int:
|
|
151
|
+
clean = _strip_markdown(text)
|
|
152
|
+
if not clean:
|
|
153
|
+
return 0
|
|
154
|
+
fragments = re.split(r"(?:[。!?!?]+|(?<!\d)\.(?!\d)(?=\s|$|[)\)\"\'”’]))", clean)
|
|
155
|
+
return sum(1 for fragment in fragments if re.search(r"[\w㐀-鿿]", fragment))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _split_table_cells(line: str) -> tuple[str, ...] | None:
|
|
159
|
+
stripped = line.strip()
|
|
160
|
+
if not stripped.startswith("|"):
|
|
161
|
+
return None
|
|
162
|
+
if stripped.endswith("|"):
|
|
163
|
+
stripped = stripped[1:-1]
|
|
164
|
+
else:
|
|
165
|
+
stripped = stripped[1:]
|
|
166
|
+
cells = tuple(
|
|
167
|
+
part.replace(r"\|", "|").strip() for part in re.split(r"(?<!\\)\|", stripped)
|
|
168
|
+
)
|
|
169
|
+
return cells if cells else None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _unwrap_formatting(value: str) -> str:
|
|
173
|
+
value = value.strip()
|
|
174
|
+
changed = True
|
|
175
|
+
while changed:
|
|
176
|
+
changed = False
|
|
177
|
+
for marker in ("**", "__"):
|
|
178
|
+
if value.startswith(marker) and value.endswith(marker) and len(value) >= 4:
|
|
179
|
+
value = value[len(marker) : -len(marker)].strip()
|
|
180
|
+
changed = True
|
|
181
|
+
if value.startswith("`") and value.endswith("`") and value.count("`") == 2:
|
|
182
|
+
value = value[1:-1].strip()
|
|
183
|
+
return value
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _cell_label_and_target(cell: str) -> tuple[str, str | None]:
|
|
187
|
+
value = cell.strip()
|
|
188
|
+
for marker in ("**", "__"):
|
|
189
|
+
if value.startswith(marker) and value.endswith(marker):
|
|
190
|
+
value = value[len(marker) : -len(marker)].strip()
|
|
191
|
+
match = _LINK_CELL_RE.fullmatch(value)
|
|
192
|
+
if match is not None:
|
|
193
|
+
return _unwrap_formatting(match.group(1)), match.group(2)
|
|
194
|
+
return _unwrap_formatting(value), None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _table_rows(section_text: str, headers: set[str]) -> list[_TableRow]:
|
|
198
|
+
rows: list[_TableRow] = []
|
|
199
|
+
for line_number, line in enumerate(section_text.splitlines(), 1):
|
|
200
|
+
cells = _split_table_cells(line)
|
|
201
|
+
if not cells:
|
|
202
|
+
continue
|
|
203
|
+
if all(_TABLE_SEPARATOR_RE.fullmatch(cell.replace(" ", "")) for cell in cells):
|
|
204
|
+
continue
|
|
205
|
+
first_label, _ = _cell_label_and_target(cells[0])
|
|
206
|
+
if first_label.strip() in headers:
|
|
207
|
+
continue
|
|
208
|
+
rows.append(_TableRow(cells=cells, raw=line, line_number=line_number))
|
|
209
|
+
return rows
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _manifest_rows(
|
|
213
|
+
section_text: str,
|
|
214
|
+
*,
|
|
215
|
+
kind: str,
|
|
216
|
+
headers: set[str],
|
|
217
|
+
) -> tuple[list[_ManifestRow], list[str]]:
|
|
218
|
+
manifest_rows: list[_ManifestRow] = []
|
|
219
|
+
issues: list[str] = []
|
|
220
|
+
for row in _table_rows(section_text, headers):
|
|
221
|
+
label, target = _cell_label_and_target(row.cells[0])
|
|
222
|
+
if kind == "file":
|
|
223
|
+
if not label or label in {".", ".."} or "/" in label or "\\" in label:
|
|
224
|
+
issues.append(f"表格第 {row.line_number} 行文件名无效: {label!r}")
|
|
225
|
+
continue
|
|
226
|
+
name = label
|
|
227
|
+
else:
|
|
228
|
+
if not label.endswith("/"):
|
|
229
|
+
issues.append(
|
|
230
|
+
f"表格第 {row.line_number} 行子目录必须以 / 结尾: {label!r}"
|
|
231
|
+
)
|
|
232
|
+
continue
|
|
233
|
+
name = label[:-1]
|
|
234
|
+
if not name or name in {".", ".."} or "/" in name or "\\" in name:
|
|
235
|
+
issues.append(f"表格第 {row.line_number} 行子目录名无效: {label!r}")
|
|
236
|
+
continue
|
|
237
|
+
manifest_rows.append(_ManifestRow(name=name, row=row, link_target=target))
|
|
238
|
+
return manifest_rows, issues
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _is_below(path: Path, root: Path) -> bool:
|
|
242
|
+
try:
|
|
243
|
+
path.relative_to(root)
|
|
244
|
+
return True
|
|
245
|
+
except ValueError:
|
|
246
|
+
return False
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _path_text(value: str | os.PathLike[str], label: str) -> str:
|
|
250
|
+
raw = os.fspath(value)
|
|
251
|
+
if not isinstance(raw, str):
|
|
252
|
+
raise PathValidationError(f"{label}必须是文本路径")
|
|
253
|
+
if not raw or "\0" in raw:
|
|
254
|
+
raise PathValidationError(f"{label}为空或包含 NUL")
|
|
255
|
+
return raw
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _resolve_directory(value: str | os.PathLike[str], label: str) -> Path:
|
|
259
|
+
raw = _path_text(value, label)
|
|
260
|
+
try:
|
|
261
|
+
resolved = Path(raw).resolve(strict=True)
|
|
262
|
+
except (OSError, RuntimeError) as exc:
|
|
263
|
+
raise PathValidationError(f"{label}不存在或不可解析: {raw}") from exc
|
|
264
|
+
if not resolved.is_dir():
|
|
265
|
+
raise PathValidationError(f"{label}不是目录: {raw}")
|
|
266
|
+
return resolved
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _infer_docs_root(candidate: Path) -> Path:
|
|
270
|
+
lexical = candidate if candidate.is_absolute() else Path.cwd() / candidate
|
|
271
|
+
lexical = lexical.absolute()
|
|
272
|
+
for parent in lexical.parents:
|
|
273
|
+
if parent.name == "project_docs" and parent.is_dir():
|
|
274
|
+
return parent.resolve(strict=True)
|
|
275
|
+
|
|
276
|
+
default_root = Path.cwd() / "project_docs"
|
|
277
|
+
if default_root.is_dir():
|
|
278
|
+
resolved_default = default_root.resolve(strict=True)
|
|
279
|
+
try:
|
|
280
|
+
candidate.resolve(strict=False).relative_to(resolved_default)
|
|
281
|
+
return resolved_default
|
|
282
|
+
except (OSError, RuntimeError, ValueError):
|
|
283
|
+
pass
|
|
284
|
+
raise PathValidationError(
|
|
285
|
+
"文档必须位于可识别的 project_docs 根目录内;请显式传入 --project-docs"
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _candidate_under_root(raw: str, root: Path) -> Path:
|
|
290
|
+
supplied = Path(raw)
|
|
291
|
+
if supplied.is_absolute():
|
|
292
|
+
return supplied
|
|
293
|
+
|
|
294
|
+
cwd_candidate = Path.cwd() / supplied
|
|
295
|
+
try:
|
|
296
|
+
if _is_below(cwd_candidate.resolve(strict=False), root):
|
|
297
|
+
return cwd_candidate
|
|
298
|
+
except (OSError, RuntimeError):
|
|
299
|
+
pass
|
|
300
|
+
|
|
301
|
+
portable = raw.replace("\\", "/")
|
|
302
|
+
pure = PurePosixPath(portable)
|
|
303
|
+
if pure.parts and pure.parts[0] == root.name:
|
|
304
|
+
pure = PurePosixPath(*pure.parts[1:])
|
|
305
|
+
return root.joinpath(*pure.parts)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _resolve_document(
|
|
309
|
+
doc_path: str | os.PathLike[str],
|
|
310
|
+
project_docs_dir: str | os.PathLike[str] | None,
|
|
311
|
+
) -> tuple[Path, Path, str]:
|
|
312
|
+
raw = _path_text(doc_path, "文档路径")
|
|
313
|
+
root = (
|
|
314
|
+
_resolve_directory(project_docs_dir, "project_docs 根目录")
|
|
315
|
+
if project_docs_dir is not None
|
|
316
|
+
else _infer_docs_root(Path(raw))
|
|
317
|
+
)
|
|
318
|
+
candidate = _candidate_under_root(raw, root)
|
|
319
|
+
try:
|
|
320
|
+
lexical_resolved = candidate.resolve(strict=False)
|
|
321
|
+
except (OSError, RuntimeError) as exc:
|
|
322
|
+
raise PathValidationError(f"文档不可解析: {raw}") from exc
|
|
323
|
+
if not _is_below(lexical_resolved, root):
|
|
324
|
+
raise PathValidationError(f"文档路径越界: {raw}")
|
|
325
|
+
try:
|
|
326
|
+
resolved = candidate.resolve(strict=True)
|
|
327
|
+
except FileNotFoundError:
|
|
328
|
+
raise
|
|
329
|
+
except (OSError, RuntimeError) as exc:
|
|
330
|
+
raise PathValidationError(f"文档不可解析: {raw}") from exc
|
|
331
|
+
if not resolved.is_file():
|
|
332
|
+
raise PathValidationError(f"文档不是普通文件: {raw}")
|
|
333
|
+
if not _is_below(resolved, root):
|
|
334
|
+
raise PathValidationError(f"文档路径越界: {raw}")
|
|
335
|
+
relative = resolved.relative_to(root).as_posix()
|
|
336
|
+
validate_manifest_relative_path(relative)
|
|
337
|
+
return resolved, root, relative
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _resolve_source_directory(
|
|
341
|
+
source_dir: str | os.PathLike[str],
|
|
342
|
+
project_root: Path,
|
|
343
|
+
docs_root: Path,
|
|
344
|
+
) -> Path:
|
|
345
|
+
raw = _path_text(source_dir, "源目录")
|
|
346
|
+
supplied = Path(raw)
|
|
347
|
+
candidate = supplied if supplied.is_absolute() else Path.cwd() / supplied
|
|
348
|
+
try:
|
|
349
|
+
cwd_resolved = candidate.resolve(strict=True)
|
|
350
|
+
except (OSError, RuntimeError):
|
|
351
|
+
cwd_resolved = None
|
|
352
|
+
|
|
353
|
+
if supplied.is_absolute():
|
|
354
|
+
try:
|
|
355
|
+
lexical_resolved = supplied.resolve(strict=False)
|
|
356
|
+
except (OSError, RuntimeError) as exc:
|
|
357
|
+
raise PathValidationError(f"源目录不可解析: {raw}") from exc
|
|
358
|
+
if not _is_below(lexical_resolved, project_root):
|
|
359
|
+
raise PathValidationError(f"源目录越过项目根目录: {raw}")
|
|
360
|
+
elif cwd_resolved is None or not _is_below(cwd_resolved, project_root):
|
|
361
|
+
portable = PurePosixPath(raw.replace("\\", "/"))
|
|
362
|
+
if portable.parts and portable.parts[0] == project_root.name:
|
|
363
|
+
portable = PurePosixPath(*portable.parts[1:])
|
|
364
|
+
candidate = project_root.joinpath(*portable.parts)
|
|
365
|
+
|
|
366
|
+
try:
|
|
367
|
+
resolved = candidate.resolve(strict=True)
|
|
368
|
+
except (OSError, RuntimeError) as exc:
|
|
369
|
+
raise PathValidationError(f"源目录不存在或不可解析: {raw}") from exc
|
|
370
|
+
if not resolved.is_dir():
|
|
371
|
+
raise PathValidationError(f"源目录不是目录: {raw}")
|
|
372
|
+
if not _is_below(resolved, project_root):
|
|
373
|
+
raise PathValidationError(f"源目录越过项目根目录: {raw}")
|
|
374
|
+
if _is_below(resolved, docs_root):
|
|
375
|
+
raise PathValidationError(f"源目录不能位于 project_docs 内: {raw}")
|
|
376
|
+
return resolved
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _source_inventory(
|
|
380
|
+
source_dir: Path, project_root: Path
|
|
381
|
+
) -> tuple[tuple[str, ...], tuple[str, ...]]:
|
|
382
|
+
files: list[str] = []
|
|
383
|
+
subdirs: list[str] = []
|
|
384
|
+
try:
|
|
385
|
+
entries = sorted(source_dir.iterdir(), key=lambda item: item.name)
|
|
386
|
+
except OSError as exc:
|
|
387
|
+
raise PathValidationError(f"无法读取源目录: {source_dir}") from exc
|
|
388
|
+
|
|
389
|
+
for entry in entries:
|
|
390
|
+
name = entry.name
|
|
391
|
+
if name.startswith("."):
|
|
392
|
+
continue
|
|
393
|
+
try:
|
|
394
|
+
resolved = entry.resolve(strict=True)
|
|
395
|
+
except (OSError, RuntimeError) as exc:
|
|
396
|
+
raise PathValidationError(f"源目录项不可解析: {entry}") from exc
|
|
397
|
+
if not _is_below(resolved, project_root):
|
|
398
|
+
raise PathValidationError(f"源目录项越过项目根目录: {entry}")
|
|
399
|
+
if resolved.is_file():
|
|
400
|
+
if source_dir == project_root and name.casefold() == "claude.md":
|
|
401
|
+
continue
|
|
402
|
+
files.append(name)
|
|
403
|
+
elif resolved.is_dir() and name not in EXCLUDED_SOURCE_DIRS:
|
|
404
|
+
subdirs.append(name)
|
|
405
|
+
return tuple(files), tuple(subdirs)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _content_is_placeholder(content: str) -> bool:
|
|
409
|
+
status = _section(content, "状态") or ""
|
|
410
|
+
return "⬜" in status or "占位目录" in content or "当前为占位" in content
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _source_is_placeholder(
|
|
414
|
+
files: tuple[str, ...] | None,
|
|
415
|
+
subdirs: tuple[str, ...] | None,
|
|
416
|
+
) -> bool | None:
|
|
417
|
+
if files is None or subdirs is None:
|
|
418
|
+
return None
|
|
419
|
+
return not subdirs and set(files).issubset({"__init__.py"})
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _select_profile(
|
|
423
|
+
requested: str,
|
|
424
|
+
content: str,
|
|
425
|
+
files: tuple[str, ...] | None,
|
|
426
|
+
subdirs: tuple[str, ...] | None,
|
|
427
|
+
) -> tuple[str, str | None]:
|
|
428
|
+
if requested not in PROFILES:
|
|
429
|
+
raise ValueError(f"未知 profile: {requested!r}")
|
|
430
|
+
source_placeholder = _source_is_placeholder(files, subdirs)
|
|
431
|
+
mismatch: str | None = None
|
|
432
|
+
|
|
433
|
+
if requested == PROFILE_AUTO:
|
|
434
|
+
if source_placeholder is not None:
|
|
435
|
+
profile = PROFILE_PLACEHOLDER if source_placeholder else PROFILE_STANDARD
|
|
436
|
+
else:
|
|
437
|
+
profile = (
|
|
438
|
+
PROFILE_PLACEHOLDER
|
|
439
|
+
if _content_is_placeholder(content)
|
|
440
|
+
else PROFILE_STANDARD
|
|
441
|
+
)
|
|
442
|
+
else:
|
|
443
|
+
profile = requested
|
|
444
|
+
|
|
445
|
+
if profile == PROFILE_PLACEHOLDER and source_placeholder is False:
|
|
446
|
+
mismatch = "placeholder profile 与含实质文件或子目录的源目录不一致"
|
|
447
|
+
return profile, mismatch
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _build_context(
|
|
451
|
+
doc_path: str | os.PathLike[str],
|
|
452
|
+
source_dir: str | os.PathLike[str] | None,
|
|
453
|
+
*,
|
|
454
|
+
profile: str,
|
|
455
|
+
project_docs_dir: str | os.PathLike[str] | None,
|
|
456
|
+
project_root: str | os.PathLike[str] | None,
|
|
457
|
+
) -> tuple[_ValidationContext, str]:
|
|
458
|
+
resolved_doc, docs_root, relative_doc = _resolve_document(
|
|
459
|
+
doc_path, project_docs_dir
|
|
460
|
+
)
|
|
461
|
+
content = read_utf8(resolved_doc)
|
|
462
|
+
|
|
463
|
+
resolved_project_root = (
|
|
464
|
+
_resolve_directory(project_root, "项目根目录")
|
|
465
|
+
if project_root is not None
|
|
466
|
+
else docs_root.parent
|
|
467
|
+
)
|
|
468
|
+
if not _is_below(docs_root, resolved_project_root):
|
|
469
|
+
raise PathValidationError("project_docs 根目录越过项目根目录")
|
|
470
|
+
|
|
471
|
+
resolved_source: Path | None = None
|
|
472
|
+
source_files: tuple[str, ...] | None = None
|
|
473
|
+
source_subdirs: tuple[str, ...] | None = None
|
|
474
|
+
if source_dir is not None:
|
|
475
|
+
resolved_source = _resolve_source_directory(
|
|
476
|
+
source_dir,
|
|
477
|
+
resolved_project_root,
|
|
478
|
+
docs_root,
|
|
479
|
+
)
|
|
480
|
+
source_files, source_subdirs = _source_inventory(
|
|
481
|
+
resolved_source,
|
|
482
|
+
resolved_project_root,
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
selected_profile, mismatch = _select_profile(
|
|
486
|
+
profile,
|
|
487
|
+
content,
|
|
488
|
+
source_files,
|
|
489
|
+
source_subdirs,
|
|
490
|
+
)
|
|
491
|
+
return (
|
|
492
|
+
_ValidationContext(
|
|
493
|
+
doc_path=resolved_doc,
|
|
494
|
+
docs_root=docs_root,
|
|
495
|
+
doc_relative=relative_doc,
|
|
496
|
+
project_root=resolved_project_root,
|
|
497
|
+
source_dir=resolved_source,
|
|
498
|
+
source_files=source_files,
|
|
499
|
+
source_subdirs=source_subdirs,
|
|
500
|
+
profile=selected_profile,
|
|
501
|
+
profile_mismatch=mismatch,
|
|
502
|
+
),
|
|
503
|
+
content,
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _legacy_inventory(
|
|
508
|
+
source_dir: str | os.PathLike[str] | None,
|
|
509
|
+
) -> tuple[tuple[str, ...], tuple[str, ...]] | None:
|
|
510
|
+
if source_dir is None:
|
|
511
|
+
return None
|
|
512
|
+
source = _resolve_directory(source_dir, "源目录")
|
|
513
|
+
return _source_inventory(source, source)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _inventory_for_check(
|
|
517
|
+
source_dir: str | os.PathLike[str] | None,
|
|
518
|
+
context: _ValidationContext | None,
|
|
519
|
+
) -> tuple[tuple[str, ...], tuple[str, ...]] | None:
|
|
520
|
+
if context is not None:
|
|
521
|
+
if context.source_files is None or context.source_subdirs is None:
|
|
522
|
+
return None
|
|
523
|
+
return context.source_files, context.source_subdirs
|
|
524
|
+
return _legacy_inventory(source_dir)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _duplicates(values: Sequence[str]) -> list[str]:
|
|
528
|
+
seen: set[str] = set()
|
|
529
|
+
duplicates: set[str] = set()
|
|
530
|
+
for value in values:
|
|
531
|
+
if value in seen:
|
|
532
|
+
duplicates.add(value)
|
|
533
|
+
seen.add(value)
|
|
534
|
+
return sorted(duplicates)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _decode_source_link_target(target: str, context: _ValidationContext) -> Path:
|
|
538
|
+
cleaned = target.strip()
|
|
539
|
+
if cleaned.startswith("<") or cleaned.endswith(">"):
|
|
540
|
+
if not (cleaned.startswith("<") and cleaned.endswith(">")):
|
|
541
|
+
raise PathValidationError("文件链接的尖括号不匹配")
|
|
542
|
+
cleaned = cleaned[1:-1].strip()
|
|
543
|
+
path_text = cleaned.partition("#")[0].partition("?")[0]
|
|
544
|
+
if not path_text or _INVALID_PERCENT_RE.search(path_text):
|
|
545
|
+
raise PathValidationError("文件链接为空或包含非法百分号转义")
|
|
546
|
+
try:
|
|
547
|
+
decoded = unquote(path_text, encoding="utf-8", errors="strict")
|
|
548
|
+
except UnicodeDecodeError as exc:
|
|
549
|
+
raise PathValidationError("文件链接包含非 UTF-8 转义") from exc
|
|
550
|
+
if (
|
|
551
|
+
"\0" in decoded
|
|
552
|
+
or "\\" in decoded
|
|
553
|
+
or decoded.startswith("/")
|
|
554
|
+
or decoded.startswith("//")
|
|
555
|
+
or _URI_SCHEME_RE.match(decoded)
|
|
556
|
+
or PureWindowsPath(decoded).drive
|
|
557
|
+
):
|
|
558
|
+
raise PathValidationError("文件链接不是安全的项目内相对路径")
|
|
559
|
+
try:
|
|
560
|
+
resolved = context.doc_path.parent.joinpath(
|
|
561
|
+
*PurePosixPath(decoded).parts
|
|
562
|
+
).resolve(strict=True)
|
|
563
|
+
except (OSError, RuntimeError) as exc:
|
|
564
|
+
raise PathValidationError("文件链接目标不存在或不可解析") from exc
|
|
565
|
+
if not _is_below(resolved, context.project_root):
|
|
566
|
+
raise PathValidationError("文件链接目标越过项目根目录")
|
|
567
|
+
return resolved
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _validate_file_row_links(
|
|
571
|
+
rows: Sequence[_ManifestRow],
|
|
572
|
+
context: _ValidationContext,
|
|
573
|
+
) -> list[str]:
|
|
574
|
+
if context.source_dir is None:
|
|
575
|
+
return []
|
|
576
|
+
issues: list[str] = []
|
|
577
|
+
for item in rows:
|
|
578
|
+
if item.link_target is None:
|
|
579
|
+
continue
|
|
580
|
+
try:
|
|
581
|
+
actual_target = _decode_source_link_target(item.link_target, context)
|
|
582
|
+
expected_target = (context.source_dir / item.name).resolve(strict=True)
|
|
583
|
+
except (OSError, ProjectDocsContractError, ValueError) as exc:
|
|
584
|
+
issues.append(f"文件 {item.name!r} 的链接无效: {exc}")
|
|
585
|
+
continue
|
|
586
|
+
if actual_target != expected_target:
|
|
587
|
+
issues.append(f"文件 {item.name!r} 的链接未指向对应源码文件")
|
|
588
|
+
return issues
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def check_1_file_table(
|
|
592
|
+
content: str,
|
|
593
|
+
source_dir: str | os.PathLike[str] | None,
|
|
594
|
+
*,
|
|
595
|
+
context: _ValidationContext | None = None,
|
|
596
|
+
) -> tuple[bool, str]:
|
|
597
|
+
"""Check that the file manifest exactly matches immediate source files."""
|
|
598
|
+
|
|
599
|
+
section_text = _section(content, "文件清单")
|
|
600
|
+
if section_text is None:
|
|
601
|
+
return False, "缺少 ## 文件清单 段"
|
|
602
|
+
inventory = _inventory_for_check(source_dir, context)
|
|
603
|
+
if inventory is None:
|
|
604
|
+
return False, "未提供源目录,无法精确核验文件清单"
|
|
605
|
+
|
|
606
|
+
rows, issues = _manifest_rows(
|
|
607
|
+
section_text,
|
|
608
|
+
kind="file",
|
|
609
|
+
headers={"文件", "文件名"},
|
|
610
|
+
)
|
|
611
|
+
actual_files = set(inventory[0])
|
|
612
|
+
listed_names = [row.name for row in rows]
|
|
613
|
+
duplicate_names = _duplicates(listed_names)
|
|
614
|
+
missing = sorted(actual_files - set(listed_names))
|
|
615
|
+
extra = sorted(set(listed_names) - actual_files)
|
|
616
|
+
if duplicate_names:
|
|
617
|
+
issues.append(f"重复文件: {', '.join(duplicate_names)}")
|
|
618
|
+
if missing:
|
|
619
|
+
issues.append(f"遗漏文件: {', '.join(missing)}")
|
|
620
|
+
if extra:
|
|
621
|
+
issues.append(f"多余文件: {', '.join(extra)}")
|
|
622
|
+
if context is not None:
|
|
623
|
+
issues.extend(_validate_file_row_links(rows, context))
|
|
624
|
+
if issues:
|
|
625
|
+
return False, "; ".join(issues)
|
|
626
|
+
return True, f"文件清单与源目录精确一致({len(actual_files)} 个文件)"
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def check_2_overview(
|
|
630
|
+
content: str,
|
|
631
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
632
|
+
*,
|
|
633
|
+
context: _ValidationContext | None = None,
|
|
634
|
+
) -> tuple[bool, str]:
|
|
635
|
+
"""Check profile-specific overview requirements."""
|
|
636
|
+
|
|
637
|
+
del source_dir
|
|
638
|
+
section_text = _section(content, "概述")
|
|
639
|
+
if not section_text:
|
|
640
|
+
return False, "缺少 ## 概述 段"
|
|
641
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
642
|
+
sentences = _sentence_count(section_text)
|
|
643
|
+
if profile == PROFILE_PLACEHOLDER:
|
|
644
|
+
if sentences < 1 or "占位" not in _strip_markdown(section_text):
|
|
645
|
+
return False, "placeholder 概述需明确说明占位状态"
|
|
646
|
+
return True, f"placeholder 概述 {sentences} 句话"
|
|
647
|
+
if not 3 <= sentences <= 4:
|
|
648
|
+
return False, f"标准概述为 {sentences} 句话(需 3–4 句)"
|
|
649
|
+
return True, f"标准概述 {sentences} 句话"
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def _valid_placeholder_role_link(
|
|
653
|
+
section_text: str,
|
|
654
|
+
context: _ValidationContext | None,
|
|
655
|
+
) -> tuple[bool, str | None]:
|
|
656
|
+
if context is None:
|
|
657
|
+
return False, None
|
|
658
|
+
links = parse_markdown_links(
|
|
659
|
+
section_text,
|
|
660
|
+
source_doc=context.doc_path,
|
|
661
|
+
docs_root=context.docs_root,
|
|
662
|
+
)
|
|
663
|
+
if not links:
|
|
664
|
+
return False, None
|
|
665
|
+
for link in links:
|
|
666
|
+
if link.disposition is LinkDisposition.INVALID:
|
|
667
|
+
return False, f"系统角色链接不安全: {link.raw_target}"
|
|
668
|
+
if link.disposition is LinkDisposition.LOCAL_DOCUMENT and link.exists is False:
|
|
669
|
+
return False, f"系统角色链接不存在: {link.raw_target}"
|
|
670
|
+
return (
|
|
671
|
+
any(
|
|
672
|
+
link.disposition is LinkDisposition.LOCAL_DOCUMENT and link.exists
|
|
673
|
+
for link in links
|
|
674
|
+
),
|
|
675
|
+
None,
|
|
676
|
+
)
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def check_3_system_role(
|
|
680
|
+
content: str,
|
|
681
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
682
|
+
*,
|
|
683
|
+
context: _ValidationContext | None = None,
|
|
684
|
+
) -> tuple[bool, str]:
|
|
685
|
+
"""Check that system-role prose is substantive for its profile."""
|
|
686
|
+
|
|
687
|
+
del source_dir
|
|
688
|
+
section_text = _section(content, "系统角色")
|
|
689
|
+
if not section_text:
|
|
690
|
+
return False, "缺少 ## 系统角色 段"
|
|
691
|
+
clean = _strip_markdown(section_text)
|
|
692
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
693
|
+
if profile == PROFILE_PLACEHOLDER:
|
|
694
|
+
has_valid_link, link_error = _valid_placeholder_role_link(section_text, context)
|
|
695
|
+
if link_error:
|
|
696
|
+
return False, link_error
|
|
697
|
+
if has_valid_link or len(clean) >= 8:
|
|
698
|
+
return True, "placeholder 系统角色已提供简要定位或父文档链接"
|
|
699
|
+
return False, "placeholder 系统角色为空或缺少有效父文档链接"
|
|
700
|
+
|
|
701
|
+
if len(clean) < 50:
|
|
702
|
+
return False, f"系统角色过于简短({len(clean)} 字符,需 >= 50)"
|
|
703
|
+
architecture_terms = (
|
|
704
|
+
"子系统",
|
|
705
|
+
"协议栈",
|
|
706
|
+
"模块",
|
|
707
|
+
"组件",
|
|
708
|
+
"算法",
|
|
709
|
+
"固件",
|
|
710
|
+
"PC 端",
|
|
711
|
+
"测试层",
|
|
712
|
+
"数据层",
|
|
713
|
+
"接口层",
|
|
714
|
+
)
|
|
715
|
+
relation_terms = (
|
|
716
|
+
"上游",
|
|
717
|
+
"下游",
|
|
718
|
+
"依赖",
|
|
719
|
+
"调用",
|
|
720
|
+
"协作",
|
|
721
|
+
"输入",
|
|
722
|
+
"输出",
|
|
723
|
+
"数据流",
|
|
724
|
+
"提供",
|
|
725
|
+
"使用",
|
|
726
|
+
"传递",
|
|
727
|
+
"导出",
|
|
728
|
+
"被",
|
|
729
|
+
)
|
|
730
|
+
if not any(term in clean for term in architecture_terms):
|
|
731
|
+
return False, "系统角色未说明所属子系统、协议层或模块"
|
|
732
|
+
if not any(term in clean for term in relation_terms):
|
|
733
|
+
return False, "系统角色未说明输入输出、依赖或上下游协作关系"
|
|
734
|
+
return True, f"系统角色包含实质架构定位与协作关系({len(clean)} 字符)"
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def _expected_child_doc(context: _ValidationContext, child_name: str) -> str:
|
|
738
|
+
if context.doc_relative in ("index.md", ""):
|
|
739
|
+
return f"{child_name}.md"
|
|
740
|
+
current_without_suffix = context.doc_relative[: -len(".md")]
|
|
741
|
+
return PurePosixPath(current_without_suffix, f"{child_name}.md").as_posix()
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
def _validate_subdir_links(
|
|
745
|
+
rows: Sequence[_ManifestRow],
|
|
746
|
+
context: _ValidationContext,
|
|
747
|
+
) -> list[str]:
|
|
748
|
+
issues: list[str] = []
|
|
749
|
+
for item in rows:
|
|
750
|
+
links = parse_markdown_links(
|
|
751
|
+
item.row.raw,
|
|
752
|
+
source_doc=context.doc_path,
|
|
753
|
+
docs_root=context.docs_root,
|
|
754
|
+
)
|
|
755
|
+
if len(links) != 1:
|
|
756
|
+
issues.append(f"子目录 {item.name!r} 必须且只能有一个 Markdown 文档链接")
|
|
757
|
+
continue
|
|
758
|
+
link = links[0]
|
|
759
|
+
expected = _expected_child_doc(context, item.name)
|
|
760
|
+
if link.disposition is LinkDisposition.INVALID:
|
|
761
|
+
issues.append(f"子目录 {item.name!r} 链接不安全: {link.reason}")
|
|
762
|
+
elif link.disposition is not LinkDisposition.LOCAL_DOCUMENT:
|
|
763
|
+
issues.append(f"子目录 {item.name!r} 未链接本地 Markdown 文档")
|
|
764
|
+
elif link.project_relative_path != expected:
|
|
765
|
+
issues.append(
|
|
766
|
+
f"子目录 {item.name!r} 链接目标错误: "
|
|
767
|
+
f"{link.project_relative_path!r},应为 {expected!r}"
|
|
768
|
+
)
|
|
769
|
+
elif link.exists is not True:
|
|
770
|
+
issues.append(f"子目录 {item.name!r} 文档不存在: {expected}")
|
|
771
|
+
return issues
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def check_4_subdir_table(
|
|
775
|
+
content: str,
|
|
776
|
+
source_dir: str | os.PathLike[str] | None,
|
|
777
|
+
*,
|
|
778
|
+
context: _ValidationContext | None = None,
|
|
779
|
+
) -> tuple[bool, str]:
|
|
780
|
+
"""Check source subdirectories and their exact Markdown document links."""
|
|
781
|
+
|
|
782
|
+
inventory = _inventory_for_check(source_dir, context)
|
|
783
|
+
if inventory is None:
|
|
784
|
+
return False, "未提供源目录,无法精确核验子目录清单"
|
|
785
|
+
actual_subdirs = set(inventory[1])
|
|
786
|
+
section_text = _section_any(content, ("子目录", "子目录清单"))
|
|
787
|
+
if section_text is None:
|
|
788
|
+
if actual_subdirs:
|
|
789
|
+
return False, f"有 {len(actual_subdirs)} 个子目录但缺少 ## 子目录 段"
|
|
790
|
+
return True, "N/A(源目录无子目录)"
|
|
791
|
+
|
|
792
|
+
rows, issues = _manifest_rows(
|
|
793
|
+
section_text,
|
|
794
|
+
kind="subdir",
|
|
795
|
+
headers={"子目录", "目录"},
|
|
796
|
+
)
|
|
797
|
+
listed_names = [row.name for row in rows]
|
|
798
|
+
duplicate_names = _duplicates(listed_names)
|
|
799
|
+
missing = sorted(actual_subdirs - set(listed_names))
|
|
800
|
+
extra = sorted(set(listed_names) - actual_subdirs)
|
|
801
|
+
if duplicate_names:
|
|
802
|
+
issues.append(f"重复子目录: {', '.join(duplicate_names)}")
|
|
803
|
+
if missing:
|
|
804
|
+
issues.append(f"遗漏子目录: {', '.join(missing)}")
|
|
805
|
+
if extra:
|
|
806
|
+
issues.append(f"多余子目录: {', '.join(extra)}")
|
|
807
|
+
if context is not None:
|
|
808
|
+
issues.extend(_validate_subdir_links(rows, context))
|
|
809
|
+
elif actual_subdirs:
|
|
810
|
+
issues.append("缺少文档上下文,无法精确核验子目录 Markdown 链接")
|
|
811
|
+
if issues:
|
|
812
|
+
return False, "; ".join(issues)
|
|
813
|
+
if not actual_subdirs:
|
|
814
|
+
return True, "N/A(源目录无子目录)"
|
|
815
|
+
return True, f"子目录清单及链接精确一致({len(actual_subdirs)} 个子目录)"
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def check_5_status(
|
|
819
|
+
content: str,
|
|
820
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
821
|
+
*,
|
|
822
|
+
context: _ValidationContext | None = None,
|
|
823
|
+
) -> tuple[bool, str]:
|
|
824
|
+
"""Check status marker and profile consistency."""
|
|
825
|
+
|
|
826
|
+
del source_dir
|
|
827
|
+
section_text = _section(content, "状态")
|
|
828
|
+
if not section_text:
|
|
829
|
+
return False, "缺少 ## 状态 段"
|
|
830
|
+
if context is not None and context.profile_mismatch:
|
|
831
|
+
return False, context.profile_mismatch
|
|
832
|
+
icons = [icon for icon in STATUS_ICONS if icon in section_text]
|
|
833
|
+
if len(icons) != 1:
|
|
834
|
+
return False, "状态段必须且只能包含一个有效图标(✅/🔶/⬜)"
|
|
835
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
836
|
+
icon = icons[0]
|
|
837
|
+
if profile == PROFILE_PLACEHOLDER and icon != "⬜":
|
|
838
|
+
return False, "placeholder profile 必须使用 ⬜ 占位状态"
|
|
839
|
+
if profile == PROFILE_STANDARD and icon == "⬜":
|
|
840
|
+
return False, "standard profile 不能使用 ⬜ 占位状态"
|
|
841
|
+
return True, f"状态与 {profile} profile 一致: {icon}"
|
|
842
|
+
|
|
843
|
+
|
|
844
|
+
def _extract_ast_symbols(source_file: Path) -> set[str]:
|
|
845
|
+
try:
|
|
846
|
+
source_code = source_file.read_text(encoding="utf-8")
|
|
847
|
+
tree = ast.parse(source_code, filename=str(source_file))
|
|
848
|
+
except Exception:
|
|
849
|
+
return set()
|
|
850
|
+
symbols: set[str] = set()
|
|
851
|
+
for node in ast.walk(tree):
|
|
852
|
+
if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
853
|
+
symbols.add(node.name)
|
|
854
|
+
elif isinstance(node, ast.Assign):
|
|
855
|
+
for target in node.targets:
|
|
856
|
+
if isinstance(target, ast.Name):
|
|
857
|
+
symbols.add(target.id)
|
|
858
|
+
elif isinstance(node, ast.AnnAssign):
|
|
859
|
+
if isinstance(node.target, ast.Name):
|
|
860
|
+
symbols.add(node.target.id)
|
|
861
|
+
return symbols
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
def check_6_symbol_table(
|
|
865
|
+
content: str,
|
|
866
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
867
|
+
*,
|
|
868
|
+
context: _ValidationContext | None = None,
|
|
869
|
+
) -> tuple[bool, str]:
|
|
870
|
+
"""Check key symbols and verify their AST presence in source files."""
|
|
871
|
+
|
|
872
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
873
|
+
if profile == PROFILE_PLACEHOLDER:
|
|
874
|
+
return True, "N/A(placeholder 不强制关键符号)"
|
|
875
|
+
|
|
876
|
+
inventory = _inventory_for_check(source_dir, context)
|
|
877
|
+
is_python_package = inventory is not None and "__init__.py" in inventory[0]
|
|
878
|
+
if not is_python_package:
|
|
879
|
+
return True, "N/A(非 Python 包)"
|
|
880
|
+
section_text = _section(content, "关键符号")
|
|
881
|
+
if not section_text:
|
|
882
|
+
return False, "Python 包目录缺少 ## 关键符号 段"
|
|
883
|
+
rows = _table_rows(section_text, {"符号", "名称"})
|
|
884
|
+
symbol_names: list[str] = []
|
|
885
|
+
issues: list[str] = []
|
|
886
|
+
|
|
887
|
+
for row in rows:
|
|
888
|
+
label, _ = _cell_label_and_target(row.cells[0])
|
|
889
|
+
if not label:
|
|
890
|
+
continue
|
|
891
|
+
symbol_names.append(label)
|
|
892
|
+
|
|
893
|
+
# AST-level reality verification when source files are present
|
|
894
|
+
if (
|
|
895
|
+
context is not None
|
|
896
|
+
and context.source_dir is not None
|
|
897
|
+
and len(row.cells) >= 3
|
|
898
|
+
):
|
|
899
|
+
loc = _unwrap_formatting(row.cells[2])
|
|
900
|
+
file_part = loc.split(":")[0].strip()
|
|
901
|
+
if file_part.endswith(".py"):
|
|
902
|
+
source_file = context.source_dir / file_part
|
|
903
|
+
if source_file.is_file():
|
|
904
|
+
ast_symbols = _extract_ast_symbols(source_file)
|
|
905
|
+
clean_name = label.split("(")[0].strip()
|
|
906
|
+
root_name = clean_name.split(".")[0].strip()
|
|
907
|
+
if (
|
|
908
|
+
ast_symbols
|
|
909
|
+
and clean_name not in ast_symbols
|
|
910
|
+
and root_name not in ast_symbols
|
|
911
|
+
):
|
|
912
|
+
issues.append(f"符号 {label!r} 未在 {file_part} 的 AST 定义中找到")
|
|
913
|
+
else:
|
|
914
|
+
issues.append(f"关键符号定义位置文件 {file_part!r} 在源目录中不存在")
|
|
915
|
+
|
|
916
|
+
if issues:
|
|
917
|
+
return False, "; ".join(issues)
|
|
918
|
+
if len(symbol_names) < 3:
|
|
919
|
+
return False, f"Python 包关键符号仅 {len(symbol_names)} 个(需 >= 3)"
|
|
920
|
+
return True, f"关键符号 {len(symbol_names)} 个"
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def check_7_no_banned_words(
|
|
924
|
+
content: str,
|
|
925
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
926
|
+
*,
|
|
927
|
+
context: _ValidationContext | None = None,
|
|
928
|
+
) -> tuple[bool, str]:
|
|
929
|
+
"""Check that vague banned terms are absent."""
|
|
930
|
+
|
|
931
|
+
del source_dir, context
|
|
932
|
+
found: list[str] = []
|
|
933
|
+
lines = content.splitlines()
|
|
934
|
+
for word in BANNED_WORDS:
|
|
935
|
+
for line_number, line in enumerate(lines, 1):
|
|
936
|
+
if word in line:
|
|
937
|
+
found.append(f"'{word}' (L{line_number})")
|
|
938
|
+
break
|
|
939
|
+
if found:
|
|
940
|
+
return False, f"发现禁止词: {', '.join(found)}"
|
|
941
|
+
return True, "无禁止词"
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def check_8_breadcrumb(
|
|
945
|
+
content: str,
|
|
946
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
947
|
+
*,
|
|
948
|
+
context: _ValidationContext | None = None,
|
|
949
|
+
) -> tuple[bool, str]:
|
|
950
|
+
"""Check breadcrumb navigation before the first level-two section."""
|
|
951
|
+
|
|
952
|
+
del source_dir, context
|
|
953
|
+
intro = re.split(r"^##[ \t]+", content, maxsplit=1, flags=re.MULTILINE)[0]
|
|
954
|
+
if re.search(r"^\s*\*\*导航\*\*\s*:", intro, re.MULTILINE):
|
|
955
|
+
return True, "面包屑导航存在"
|
|
956
|
+
if re.search(r"^\s*>?\s*面包屑\s*:", intro, re.MULTILINE):
|
|
957
|
+
return True, "面包屑导航存在(兼容旧格式)"
|
|
958
|
+
return False, "缺少文档开头的面包屑导航 (**导航**: ...)"
|
|
959
|
+
|
|
960
|
+
|
|
961
|
+
def _dependency_row_issue(
|
|
962
|
+
row: _TableRow, context: _ValidationContext | None
|
|
963
|
+
) -> str | None:
|
|
964
|
+
if len(row.cells) < 3:
|
|
965
|
+
return f"依赖关系表第 {row.line_number} 行列数不足"
|
|
966
|
+
direction = _strip_markdown(row.cells[0])
|
|
967
|
+
if not re.match(r"^(?:⬆|⬇|↔)", direction):
|
|
968
|
+
return f"依赖关系表第 {row.line_number} 行缺少方向标记"
|
|
969
|
+
module = _strip_markdown(row.cells[1])
|
|
970
|
+
relationship = _strip_markdown(row.cells[2])
|
|
971
|
+
empty_values = {"", "-", "—", "无", "N/A", "n/a", "TODO", "待补充"}
|
|
972
|
+
if module in empty_values:
|
|
973
|
+
return f"依赖关系表第 {row.line_number} 行模块名无实质内容"
|
|
974
|
+
if relationship in empty_values or len(relationship) < 6:
|
|
975
|
+
return f"依赖关系表第 {row.line_number} 行关系说明不够具体"
|
|
976
|
+
|
|
977
|
+
if context is None:
|
|
978
|
+
if not re.search(r"\[[^\]]+\]\([^)]+\)", row.raw):
|
|
979
|
+
return f"依赖关系表第 {row.line_number} 行缺少 Markdown 文档链接"
|
|
980
|
+
return None
|
|
981
|
+
|
|
982
|
+
links = parse_markdown_links(
|
|
983
|
+
row.raw,
|
|
984
|
+
source_doc=context.doc_path,
|
|
985
|
+
docs_root=context.docs_root,
|
|
986
|
+
)
|
|
987
|
+
invalid = [link for link in links if link.disposition is LinkDisposition.INVALID]
|
|
988
|
+
if invalid:
|
|
989
|
+
return f"依赖关系表第 {row.line_number} 行包含不安全链接: {invalid[0].reason}"
|
|
990
|
+
local_links = [
|
|
991
|
+
link for link in links if link.disposition is LinkDisposition.LOCAL_DOCUMENT
|
|
992
|
+
]
|
|
993
|
+
if len(local_links) != 1:
|
|
994
|
+
return f"依赖关系表第 {row.line_number} 行必须且只能有一个本地文档链接"
|
|
995
|
+
link = local_links[0]
|
|
996
|
+
if link.exists is not True:
|
|
997
|
+
return f"依赖关系表第 {row.line_number} 行链接目标不存在: {link.raw_target}"
|
|
998
|
+
if link.project_relative_path == context.doc_relative:
|
|
999
|
+
return f"依赖关系表第 {row.line_number} 行不能仅链接当前文档"
|
|
1000
|
+
return None
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
def check_9_dependency_table(
|
|
1004
|
+
content: str,
|
|
1005
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1006
|
+
*,
|
|
1007
|
+
context: _ValidationContext | None = None,
|
|
1008
|
+
) -> tuple[bool, str]:
|
|
1009
|
+
"""Check a substantive dependency table and its safe local document links."""
|
|
1010
|
+
|
|
1011
|
+
del source_dir
|
|
1012
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
1013
|
+
if profile == PROFILE_PLACEHOLDER:
|
|
1014
|
+
return True, "N/A(placeholder 不强制依赖关系表)"
|
|
1015
|
+
section_text = _section(content, "依赖关系")
|
|
1016
|
+
if not section_text:
|
|
1017
|
+
return False, "缺少 ## 依赖关系 段"
|
|
1018
|
+
rows = _table_rows(section_text, {"方向"})
|
|
1019
|
+
if not rows:
|
|
1020
|
+
return False, "依赖关系表为空或不是 Markdown 表格"
|
|
1021
|
+
issues = [
|
|
1022
|
+
issue
|
|
1023
|
+
for row in rows
|
|
1024
|
+
if (issue := _dependency_row_issue(row, context)) is not None
|
|
1025
|
+
]
|
|
1026
|
+
if issues:
|
|
1027
|
+
return False, "; ".join(issues)
|
|
1028
|
+
return True, f"依赖关系 {len(rows)} 条,说明及链接均有效"
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
CHECKS = [
|
|
1032
|
+
(1, "file_manifest_table", "文件清单表格", check_1_file_table),
|
|
1033
|
+
(2, "overview_min_3", "概述 3–4 句", check_2_overview),
|
|
1034
|
+
(3, "system_role", "系统角色段", check_3_system_role),
|
|
1035
|
+
(4, "subdir_table", "子目录表", check_4_subdir_table),
|
|
1036
|
+
(5, "status_marker", "状态标记", check_5_status),
|
|
1037
|
+
(6, "symbol_table", "关键符号表", check_6_symbol_table),
|
|
1038
|
+
(7, "no_banned_words", "无禁止词", check_7_no_banned_words),
|
|
1039
|
+
(8, "breadcrumb", "面包屑导航", check_8_breadcrumb),
|
|
1040
|
+
(9, "dependency_table", "依赖关系表", check_9_dependency_table),
|
|
1041
|
+
]
|
|
1042
|
+
|
|
1043
|
+
|
|
1044
|
+
def _display_path(value: str | os.PathLike[str] | None) -> str | None:
|
|
1045
|
+
if value is None:
|
|
1046
|
+
return None
|
|
1047
|
+
try:
|
|
1048
|
+
return os.fspath(value)
|
|
1049
|
+
except TypeError:
|
|
1050
|
+
return repr(value)
|
|
1051
|
+
|
|
1052
|
+
|
|
1053
|
+
def _not_run_checks(reason: str) -> list[dict[str, Any]]:
|
|
1054
|
+
return [
|
|
1055
|
+
{
|
|
1056
|
+
"id": check_id,
|
|
1057
|
+
"name": name,
|
|
1058
|
+
"label": label,
|
|
1059
|
+
"severity": "critical" if check_id in CRITICAL_CHECK_IDS else "advisory",
|
|
1060
|
+
"result": "N/A",
|
|
1061
|
+
"detail": f"未执行: {reason}",
|
|
1062
|
+
}
|
|
1063
|
+
for check_id, name, label, _ in CHECKS
|
|
1064
|
+
]
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
def _critical_result(
|
|
1068
|
+
doc_path: str | os.PathLike[str],
|
|
1069
|
+
source_dir: str | os.PathLike[str] | None,
|
|
1070
|
+
requested_profile: str,
|
|
1071
|
+
*,
|
|
1072
|
+
error_code: str,
|
|
1073
|
+
message: str,
|
|
1074
|
+
) -> dict[str, Any]:
|
|
1075
|
+
profile = (
|
|
1076
|
+
requested_profile
|
|
1077
|
+
if requested_profile in {PROFILE_STANDARD, PROFILE_PLACEHOLDER}
|
|
1078
|
+
else None
|
|
1079
|
+
)
|
|
1080
|
+
checks = _not_run_checks(message)
|
|
1081
|
+
return {
|
|
1082
|
+
"schema_version": RESULT_SCHEMA_VERSION,
|
|
1083
|
+
"file": _display_path(doc_path),
|
|
1084
|
+
"source_dir": _display_path(source_dir),
|
|
1085
|
+
"requested_profile": requested_profile,
|
|
1086
|
+
"profile": profile,
|
|
1087
|
+
"checks": checks,
|
|
1088
|
+
"passed": 0,
|
|
1089
|
+
"failed": 0,
|
|
1090
|
+
"na": len(checks),
|
|
1091
|
+
"critical_failed": 1,
|
|
1092
|
+
"critical": True,
|
|
1093
|
+
"qualified": False,
|
|
1094
|
+
"ok": False,
|
|
1095
|
+
"error_code": error_code,
|
|
1096
|
+
"error": message,
|
|
1097
|
+
"errors": [message],
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
def _invalid_link_errors(content: str, context: _ValidationContext) -> list[str]:
|
|
1102
|
+
errors: list[str] = []
|
|
1103
|
+
for link in parse_markdown_links(
|
|
1104
|
+
content,
|
|
1105
|
+
source_doc=context.doc_path,
|
|
1106
|
+
docs_root=context.docs_root,
|
|
1107
|
+
):
|
|
1108
|
+
if link.disposition is LinkDisposition.INVALID:
|
|
1109
|
+
errors.append(f"不安全 Markdown 链接 {link.raw_target!r}: {link.reason}")
|
|
1110
|
+
return sorted(set(errors))
|
|
1111
|
+
|
|
1112
|
+
|
|
1113
|
+
def validate_doc(
|
|
1114
|
+
doc_path: str | os.PathLike[str],
|
|
1115
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1116
|
+
*,
|
|
1117
|
+
profile: str = PROFILE_AUTO,
|
|
1118
|
+
project_docs_dir: str | os.PathLike[str] | None = None,
|
|
1119
|
+
project_root: str | os.PathLike[str] | None = None,
|
|
1120
|
+
) -> dict[str, Any]:
|
|
1121
|
+
"""Run all checks and always return the same complete result structure."""
|
|
1122
|
+
|
|
1123
|
+
try:
|
|
1124
|
+
context, content = _build_context(
|
|
1125
|
+
doc_path,
|
|
1126
|
+
source_dir,
|
|
1127
|
+
profile=profile,
|
|
1128
|
+
project_docs_dir=project_docs_dir,
|
|
1129
|
+
project_root=project_root,
|
|
1130
|
+
)
|
|
1131
|
+
except FileNotFoundError:
|
|
1132
|
+
return _critical_result(
|
|
1133
|
+
doc_path,
|
|
1134
|
+
source_dir,
|
|
1135
|
+
profile,
|
|
1136
|
+
error_code="document-not-found",
|
|
1137
|
+
message="file not found",
|
|
1138
|
+
)
|
|
1139
|
+
except StrictUtf8Error as exc:
|
|
1140
|
+
return _critical_result(
|
|
1141
|
+
doc_path,
|
|
1142
|
+
source_dir,
|
|
1143
|
+
profile,
|
|
1144
|
+
error_code="invalid-utf8",
|
|
1145
|
+
message=str(exc),
|
|
1146
|
+
)
|
|
1147
|
+
except (OSError, ValueError, ProjectDocsContractError) as exc:
|
|
1148
|
+
return _critical_result(
|
|
1149
|
+
doc_path,
|
|
1150
|
+
source_dir,
|
|
1151
|
+
profile,
|
|
1152
|
+
error_code="path-or-input-error",
|
|
1153
|
+
message=str(exc),
|
|
1154
|
+
)
|
|
1155
|
+
|
|
1156
|
+
critical_errors = _invalid_link_errors(content, context)
|
|
1157
|
+
results: list[dict[str, Any]] = []
|
|
1158
|
+
for check_id, name, label, function in CHECKS:
|
|
1159
|
+
try:
|
|
1160
|
+
passed, detail = function(content, source_dir, context=context)
|
|
1161
|
+
except (
|
|
1162
|
+
Exception
|
|
1163
|
+
) as exc: # A broken check must be reported, never hide the rest.
|
|
1164
|
+
passed = False
|
|
1165
|
+
detail = f"检查异常: {type(exc).__name__}: {exc}"
|
|
1166
|
+
status = (
|
|
1167
|
+
"N/A"
|
|
1168
|
+
if passed and detail.startswith("N/A")
|
|
1169
|
+
else ("PASS" if passed else "FAIL")
|
|
1170
|
+
)
|
|
1171
|
+
results.append(
|
|
1172
|
+
{
|
|
1173
|
+
"id": check_id,
|
|
1174
|
+
"name": name,
|
|
1175
|
+
"label": label,
|
|
1176
|
+
"severity": (
|
|
1177
|
+
"critical" if check_id in CRITICAL_CHECK_IDS else "advisory"
|
|
1178
|
+
),
|
|
1179
|
+
"result": status,
|
|
1180
|
+
"detail": detail,
|
|
1181
|
+
}
|
|
1182
|
+
)
|
|
1183
|
+
|
|
1184
|
+
passed_count = sum(result["result"] == "PASS" for result in results)
|
|
1185
|
+
failed_count = sum(result["result"] == "FAIL" for result in results)
|
|
1186
|
+
na_count = sum(result["result"] == "N/A" for result in results)
|
|
1187
|
+
critical_check_failures = sum(
|
|
1188
|
+
result["result"] == "FAIL" and result["severity"] == "critical"
|
|
1189
|
+
for result in results
|
|
1190
|
+
)
|
|
1191
|
+
critical_failed = critical_check_failures + len(critical_errors)
|
|
1192
|
+
qualified = failed_count == 0 and not critical_errors
|
|
1193
|
+
|
|
1194
|
+
return {
|
|
1195
|
+
"schema_version": RESULT_SCHEMA_VERSION,
|
|
1196
|
+
"file": _display_path(doc_path),
|
|
1197
|
+
"source_dir": _display_path(source_dir),
|
|
1198
|
+
"requested_profile": profile,
|
|
1199
|
+
"profile": context.profile,
|
|
1200
|
+
"checks": results,
|
|
1201
|
+
"passed": passed_count,
|
|
1202
|
+
"failed": failed_count,
|
|
1203
|
+
"na": na_count,
|
|
1204
|
+
"critical_failed": critical_failed,
|
|
1205
|
+
"critical": critical_failed > 0,
|
|
1206
|
+
"qualified": qualified,
|
|
1207
|
+
"ok": qualified,
|
|
1208
|
+
"error_code": "unsafe-markdown-link" if critical_errors else None,
|
|
1209
|
+
"error": critical_errors[0] if critical_errors else None,
|
|
1210
|
+
"errors": critical_errors,
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
|
|
1214
|
+
def _parser() -> argparse.ArgumentParser:
|
|
1215
|
+
parser = argparse.ArgumentParser(
|
|
1216
|
+
description="Validate a project_docs document against its source directory"
|
|
1217
|
+
)
|
|
1218
|
+
parser.add_argument("doc", help="Path to the .md document to validate")
|
|
1219
|
+
parser.add_argument(
|
|
1220
|
+
"--source-dir",
|
|
1221
|
+
"--source_dir",
|
|
1222
|
+
"-s",
|
|
1223
|
+
dest="source_dir",
|
|
1224
|
+
help="Corresponding source directory for exact inventory comparison",
|
|
1225
|
+
)
|
|
1226
|
+
parser.add_argument(
|
|
1227
|
+
"--project-docs",
|
|
1228
|
+
"--docs-root",
|
|
1229
|
+
dest="project_docs",
|
|
1230
|
+
help="Trusted project_docs root (otherwise inferred from the document path)",
|
|
1231
|
+
)
|
|
1232
|
+
parser.add_argument(
|
|
1233
|
+
"--project-root",
|
|
1234
|
+
help="Trusted project root used to bound the source directory",
|
|
1235
|
+
)
|
|
1236
|
+
parser.add_argument(
|
|
1237
|
+
"--profile",
|
|
1238
|
+
choices=PROFILES,
|
|
1239
|
+
default=PROFILE_AUTO,
|
|
1240
|
+
help="Validation profile (default: auto)",
|
|
1241
|
+
)
|
|
1242
|
+
parser.add_argument(
|
|
1243
|
+
"--strict",
|
|
1244
|
+
action="store_true",
|
|
1245
|
+
help="Exit non-zero for advisory as well as critical check failures",
|
|
1246
|
+
)
|
|
1247
|
+
parser.add_argument("--json", action="store_true", help="Write only JSON to stdout")
|
|
1248
|
+
return parser
|
|
1249
|
+
|
|
1250
|
+
|
|
1251
|
+
def _result_exit_code(result: dict[str, Any], *, strict: bool) -> int:
|
|
1252
|
+
if result["error_code"] is not None:
|
|
1253
|
+
return EXIT_CRITICAL_ERROR
|
|
1254
|
+
if result["critical_failed"]:
|
|
1255
|
+
return EXIT_VALIDATION_FAILED
|
|
1256
|
+
if strict and result["failed"]:
|
|
1257
|
+
return EXIT_VALIDATION_FAILED
|
|
1258
|
+
return EXIT_OK
|
|
1259
|
+
|
|
1260
|
+
|
|
1261
|
+
def _configure_stdout_utf8() -> None:
|
|
1262
|
+
reconfigure = getattr(sys.stdout, "reconfigure", None)
|
|
1263
|
+
if callable(reconfigure):
|
|
1264
|
+
reconfigure(encoding="utf-8", errors="strict")
|
|
1265
|
+
|
|
1266
|
+
|
|
1267
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
1268
|
+
args = _parser().parse_args(argv)
|
|
1269
|
+
_configure_stdout_utf8()
|
|
1270
|
+
result = validate_doc(
|
|
1271
|
+
args.doc,
|
|
1272
|
+
args.source_dir,
|
|
1273
|
+
profile=args.profile,
|
|
1274
|
+
project_docs_dir=args.project_docs,
|
|
1275
|
+
project_root=args.project_root,
|
|
1276
|
+
)
|
|
1277
|
+
exit_code = _result_exit_code(result, strict=args.strict)
|
|
1278
|
+
|
|
1279
|
+
if args.json:
|
|
1280
|
+
print(stable_json_dumps(result), end="")
|
|
1281
|
+
return exit_code
|
|
1282
|
+
|
|
1283
|
+
print(f"=== {result['file']} ===")
|
|
1284
|
+
if result["error"]:
|
|
1285
|
+
print(f"ERROR [{result['error_code']}]: {result['error']}", file=sys.stderr)
|
|
1286
|
+
for check in result["checks"]:
|
|
1287
|
+
icon = {"PASS": "✅", "FAIL": "❌", "N/A": "⬜"}[check["result"]]
|
|
1288
|
+
print(f" {icon} #{check['id']} {check['label']}: {check['detail']}")
|
|
1289
|
+
print(" ---")
|
|
1290
|
+
print(
|
|
1291
|
+
f" PASS: {result['passed']} FAIL: {result['failed']} "
|
|
1292
|
+
f"N/A: {result['na']} CRITICAL: {result['critical_failed']}"
|
|
1293
|
+
)
|
|
1294
|
+
print(f" Profile: {result['profile']} Qualified: {result['qualified']}")
|
|
1295
|
+
return exit_code
|
|
1296
|
+
|
|
1297
|
+
|
|
1298
|
+
if __name__ == "__main__":
|
|
1299
|
+
raise SystemExit(main())
|