@walvka-code/proj-doc-builder 0.0.0-stage → 4.5.2
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 +290 -3
- package/README.zh-CN.md +258 -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 +59 -4
- package/skills/proj-doc-builder/SKILL.md +412 -0
- package/skills/proj-doc-builder/references/audit_script.md +103 -0
- package/skills/proj-doc-builder/references/batch-generation.md +55 -0
- package/skills/proj-doc-builder/references/checklist.md +90 -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 +212 -0
- package/skills/proj-doc-builder/tests/claims.json +76 -0
- package/skills/proj-doc-builder/tests/conftest.py +23 -0
- package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
- package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
- package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
- package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
- package/skills/proj-doc-builder/tests/test_load_docs.py +353 -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 +812 -0
- package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
- package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
- package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
- package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
- package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
- package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
- package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
- package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
- package/skills/proj-doc-builder/tests/test_validate_doc.py +712 -0
- package/skills/proj-doc-builder/tools/_paths.py +39 -0
- package/skills/proj-doc-builder/tools/core/claude_doc_index.py +504 -0
- package/skills/proj-doc-builder/tools/core/compute_link.py +239 -0
- package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
- package/skills/proj-doc-builder/tools/core/project_docs_contract.py +2725 -0
- package/skills/proj-doc-builder/tools/phase4/__init__.py +82 -0
- package/skills/proj-doc-builder/tools/phase4/cas_storage.py +25 -0
- package/skills/proj-doc-builder/tools/phase4/engine.py +35 -0
- package/skills/proj-doc-builder/tools/phase4/journal.py +29 -0
- package/skills/proj-doc-builder/tools/phase4/platform_handles.py +27 -0
- package/skills/proj-doc-builder/tools/phase4_exit.py +8565 -0
- package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
- package/skills/proj-doc-builder/tools/pipeline/sync_project_docs.py +5531 -0
- package/skills/proj-doc-builder/tools/reader/load_docs.py +654 -0
- package/skills/proj-doc-builder/tools/scan/link_check.py +203 -0
- package/skills/proj-doc-builder/tools/scan/normalize_markers.py +211 -0
- package/skills/proj-doc-builder/tools/scan/scan_dirs.py +2735 -0
- package/skills/proj-doc-builder/tools/validate/validate_doc.py +1911 -0
|
@@ -0,0 +1,789 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Reference batch document generator consuming sync_project_docs --scaffold-dump JSON.
|
|
3
|
+
|
|
4
|
+
Completes the 4-step zero-to-docs workflow:
|
|
5
|
+
1. sync_project_docs.py --init
|
|
6
|
+
2. sync_project_docs.py --dry-run --scaffold-dump scaffold.json
|
|
7
|
+
3. gen_docs_from_scaffold.py --scaffold scaffold.json --project-root .
|
|
8
|
+
4. sync_project_docs.py --apply
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
import sys as _bootstrap_sys
|
|
13
|
+
from pathlib import Path as _bootstrap_path
|
|
14
|
+
_bootstrap_sys.dont_write_bytecode = True
|
|
15
|
+
_bootstrap_sys.path.insert(0, str(_bootstrap_path(__file__).resolve().parents[1]))
|
|
16
|
+
import _paths # noqa: E402
|
|
17
|
+
_paths.install()
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import ast
|
|
21
|
+
import json
|
|
22
|
+
import re
|
|
23
|
+
import sys
|
|
24
|
+
from datetime import datetime, timezone
|
|
25
|
+
from pathlib import Path, PurePosixPath
|
|
26
|
+
from typing import Any, Mapping, Sequence
|
|
27
|
+
|
|
28
|
+
TOOLS_DIR = Path(__file__).resolve().parent
|
|
29
|
+
if str(TOOLS_DIR) not in sys.path:
|
|
30
|
+
sys.path.insert(0, str(TOOLS_DIR))
|
|
31
|
+
|
|
32
|
+
import project_docs_contract as contract
|
|
33
|
+
|
|
34
|
+
GENERATOR_VERSION = "4.5"
|
|
35
|
+
_ARCHIVE_SEGMENTS = frozenset({"archive", "archives", "legacy", "deprecated", "old", "backup", "backups"})
|
|
36
|
+
|
|
37
|
+
_ROLE_BY_SUFFIX: dict[str, str] = {
|
|
38
|
+
".py": "Python 源码",
|
|
39
|
+
".pyi": "Python 类型存根",
|
|
40
|
+
".c": "C 源码",
|
|
41
|
+
".h": "C/C++ 头文件",
|
|
42
|
+
".cpp": "C++ 源码",
|
|
43
|
+
".hpp": "C++ 头文件",
|
|
44
|
+
".rs": "Rust 源码",
|
|
45
|
+
".js": "JavaScript 脚本",
|
|
46
|
+
".mjs": "ES 模块脚本",
|
|
47
|
+
".ts": "TypeScript 源码",
|
|
48
|
+
".json": "JSON 配置/数据",
|
|
49
|
+
".toml": "TOML 配置",
|
|
50
|
+
".yaml": "YAML 配置",
|
|
51
|
+
".yml": "YAML 配置",
|
|
52
|
+
".md": "Markdown 说明",
|
|
53
|
+
".sh": "Shell 脚本",
|
|
54
|
+
".ps1": "PowerShell 脚本",
|
|
55
|
+
".bat": "批处理脚本",
|
|
56
|
+
".cmake": "CMake 构建脚本",
|
|
57
|
+
".txt": "文本说明",
|
|
58
|
+
".csv": "CSV 数据表",
|
|
59
|
+
".sql": "SQL 脚本",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _utc_now() -> str:
|
|
64
|
+
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _file_role(filename: str) -> str:
|
|
68
|
+
lower = filename.casefold()
|
|
69
|
+
if lower == "__init__.py":
|
|
70
|
+
return "包入口"
|
|
71
|
+
if lower == "readme.md":
|
|
72
|
+
return "目录说明"
|
|
73
|
+
if lower in {"cmakelists.txt", "makefile"}:
|
|
74
|
+
return "构建配置"
|
|
75
|
+
if lower.startswith("test_") and lower.endswith(".py"):
|
|
76
|
+
return "单元测试"
|
|
77
|
+
suffix = Path(filename).suffix.casefold()
|
|
78
|
+
return _ROLE_BY_SUFFIX.get(suffix, "项目文件")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _is_archive_path(rel_path: str) -> bool:
|
|
82
|
+
parts = [p.casefold() for p in PurePosixPath(rel_path).parts if p]
|
|
83
|
+
return any(p in _ARCHIVE_SEGMENTS for p in parts)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _extract_py_file_summary(file_path: Path) -> tuple[str, list[tuple[str, str, str]]]:
|
|
87
|
+
"""Return (one-line summary, [(symbol, kind, filename)]) for a Python file."""
|
|
88
|
+
symbols: list[tuple[str, str, str]] = []
|
|
89
|
+
if not file_path.is_file():
|
|
90
|
+
return "源码文件", symbols
|
|
91
|
+
try:
|
|
92
|
+
text = file_path.read_text(encoding="utf-8", errors="ignore")
|
|
93
|
+
tree = ast.parse(text, filename=file_path.name)
|
|
94
|
+
except (OSError, SyntaxError, ValueError):
|
|
95
|
+
return "Python 源码文件", symbols
|
|
96
|
+
|
|
97
|
+
doc = ast.get_docstring(tree)
|
|
98
|
+
first_line = doc.strip().splitlines()[0].strip() if doc and doc.strip() else ""
|
|
99
|
+
|
|
100
|
+
for node in tree.body:
|
|
101
|
+
if isinstance(node, ast.ClassDef) and not node.name.startswith("_"):
|
|
102
|
+
symbols.append((node.name, "类", file_path.name))
|
|
103
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and not node.name.startswith("_"):
|
|
104
|
+
symbols.append((node.name, "函数", file_path.name))
|
|
105
|
+
elif isinstance(node, ast.Assign):
|
|
106
|
+
for target in node.targets:
|
|
107
|
+
if isinstance(target, ast.Name) and not target.id.startswith("_"):
|
|
108
|
+
symbols.append((target.id, "常量/变量", file_path.name))
|
|
109
|
+
elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
|
|
110
|
+
if not node.target.id.startswith("_"):
|
|
111
|
+
symbols.append((node.target.id, "常量/变量", file_path.name))
|
|
112
|
+
elif isinstance(node, ast.ImportFrom):
|
|
113
|
+
for alias in node.names:
|
|
114
|
+
exported = alias.asname or alias.name
|
|
115
|
+
if exported != "*" and not exported.startswith("_"):
|
|
116
|
+
symbols.append((exported, "导出符号", file_path.name))
|
|
117
|
+
|
|
118
|
+
if first_line:
|
|
119
|
+
summary = first_line[:60].replace("|", "/")
|
|
120
|
+
elif symbols:
|
|
121
|
+
names = ", ".join(f"`{s[0]}`" for s in symbols[:3])
|
|
122
|
+
summary = f"定义或导出 {names}"
|
|
123
|
+
else:
|
|
124
|
+
summary = f"位于目录中的 `{file_path.name}` 实现"
|
|
125
|
+
return summary, symbols
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _describe_file(source_dir: Path, filename: str) -> tuple[str, list[tuple[str, str, str]]]:
|
|
129
|
+
file_path = source_dir / filename
|
|
130
|
+
if filename.casefold().endswith(".py"):
|
|
131
|
+
return _extract_py_file_summary(file_path)
|
|
132
|
+
if filename.casefold().endswith(".md") and file_path.is_file():
|
|
133
|
+
try:
|
|
134
|
+
for line in file_path.read_text(encoding="utf-8", errors="ignore").splitlines():
|
|
135
|
+
stripped = line.strip()
|
|
136
|
+
if stripped.startswith("#"):
|
|
137
|
+
heading = stripped.lstrip("#").strip()[:60].replace("|", "/")
|
|
138
|
+
if heading:
|
|
139
|
+
return f"文档标题:{heading}", []
|
|
140
|
+
except OSError:
|
|
141
|
+
pass
|
|
142
|
+
if file_path.is_file():
|
|
143
|
+
keys = _config_keys_summary(file_path)
|
|
144
|
+
if keys:
|
|
145
|
+
return "顶层键:" + "、".join(f"`{key}`" for key in keys), []
|
|
146
|
+
if filename.casefold().endswith(".txt"):
|
|
147
|
+
head = _read_text_head(file_path, 200)
|
|
148
|
+
first = next((ln.strip() for ln in head.splitlines() if ln.strip()), "")
|
|
149
|
+
if first:
|
|
150
|
+
return f"文本首行:{first[:60].replace('|', '/')}", []
|
|
151
|
+
return "非文本或未解析数据文件,未自动分析结构", []
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _read_text_head(file_path: Path, limit: int = 65536) -> str:
|
|
155
|
+
try:
|
|
156
|
+
return file_path.read_text(encoding="utf-8", errors="ignore")[:limit]
|
|
157
|
+
except OSError:
|
|
158
|
+
return ""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _config_keys_summary(file_path: Path) -> list[str]:
|
|
162
|
+
"""Return up to five top-level keys/columns for config-like text files."""
|
|
163
|
+
text = _read_text_head(file_path)
|
|
164
|
+
if not text.strip():
|
|
165
|
+
return []
|
|
166
|
+
suffix = file_path.suffix.casefold()
|
|
167
|
+
if suffix == ".json":
|
|
168
|
+
try:
|
|
169
|
+
payload = json.loads(text)
|
|
170
|
+
except (json.JSONDecodeError, ValueError):
|
|
171
|
+
return []
|
|
172
|
+
if isinstance(payload, Mapping):
|
|
173
|
+
return [str(key) for key in list(payload)[:5]]
|
|
174
|
+
return []
|
|
175
|
+
if suffix in {".yaml", ".yml", ".toml", ".ini", ".cfg"}:
|
|
176
|
+
keys = re.findall(r"^([A-Za-z_][\w.\-]*)\s*[:=]", text, flags=re.MULTILINE)
|
|
177
|
+
return list(dict.fromkeys(keys))[:5]
|
|
178
|
+
if suffix == ".csv":
|
|
179
|
+
lines = text.splitlines()
|
|
180
|
+
if lines:
|
|
181
|
+
return [cell.strip() for cell in lines[0].split(",")[:5] if cell.strip()]
|
|
182
|
+
return []
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _extension_mix(inv_files: Sequence[str]) -> str:
|
|
186
|
+
"""Return a compact suffix histogram such as ``12 个 .py、3 个 .md``."""
|
|
187
|
+
|
|
188
|
+
counts: dict[str, int] = {}
|
|
189
|
+
for name in inv_files:
|
|
190
|
+
suffix = PurePosixPath(name).suffix.casefold() or "无扩展名"
|
|
191
|
+
counts[suffix] = counts.get(suffix, 0) + 1
|
|
192
|
+
ordered = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:3]
|
|
193
|
+
return "、".join(f"{count} 个 {suffix}" for suffix, count in ordered)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _directory_role(
|
|
197
|
+
inv_files: Sequence[str],
|
|
198
|
+
inv_subdirs: Sequence[str],
|
|
199
|
+
*,
|
|
200
|
+
is_boundary: bool,
|
|
201
|
+
is_archive: bool,
|
|
202
|
+
profile: str,
|
|
203
|
+
is_root: bool = False,
|
|
204
|
+
) -> str:
|
|
205
|
+
"""Derive a one-line role used in ``# <name> — <role>`` and the overview."""
|
|
206
|
+
|
|
207
|
+
if is_root:
|
|
208
|
+
# 仓库根的角色是「整个仓库的入口」,不能被根目录里偶然存在的脚本带偏
|
|
209
|
+
return f"仓库根({len(inv_files)} 个直接文件、{len(inv_subdirs)} 个顶层子目录)"
|
|
210
|
+
if is_archive:
|
|
211
|
+
return "历史归档目录"
|
|
212
|
+
if profile == "placeholder":
|
|
213
|
+
return "占位目录(待补充实现)"
|
|
214
|
+
if is_boundary:
|
|
215
|
+
return "边界子工程(含独立 CLAUDE.md)"
|
|
216
|
+
lowered = [name.casefold() for name in inv_files]
|
|
217
|
+
if "__init__.py" in lowered:
|
|
218
|
+
py_count = sum(1 for name in lowered if name.endswith(".py"))
|
|
219
|
+
return f"Python 包({py_count} 个模块文件)"
|
|
220
|
+
py_files = [name for name in lowered if name.endswith(".py")]
|
|
221
|
+
if py_files and len(py_files) * 2 >= max(1, len(lowered)):
|
|
222
|
+
test_files = [name for name in py_files if name.startswith("test_")]
|
|
223
|
+
if len(test_files) * 2 >= len(py_files):
|
|
224
|
+
return f"测试用例目录({len(py_files)} 个测试脚本)"
|
|
225
|
+
return f"Python 脚本目录({len(py_files)} 个脚本)"
|
|
226
|
+
counts: dict[str, int] = {}
|
|
227
|
+
for name in lowered:
|
|
228
|
+
suffix = PurePosixPath(name).suffix
|
|
229
|
+
counts[suffix] = counts.get(suffix, 0) + 1
|
|
230
|
+
if counts:
|
|
231
|
+
suffix, count = max(counts.items(), key=lambda kv: (kv[1], kv[0]))
|
|
232
|
+
total = sum(counts.values())
|
|
233
|
+
if suffix and count * 2 >= total:
|
|
234
|
+
if suffix == ".md":
|
|
235
|
+
return f"文档目录({count} 篇 Markdown)"
|
|
236
|
+
if suffix in {".c", ".h"}:
|
|
237
|
+
return f"C 源码目录({count} 个 C/头文件)"
|
|
238
|
+
if suffix in {".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".csv"}:
|
|
239
|
+
return f"配置与数据目录({count} 个配置文件)"
|
|
240
|
+
if inv_subdirs:
|
|
241
|
+
return f"分组目录({len(inv_subdirs)} 个子目录)"
|
|
242
|
+
return "项目目录"
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _normalize_filter_key(raw: str) -> str:
|
|
246
|
+
cleaned = raw.strip().replace("\\", "/").strip("/")
|
|
247
|
+
if cleaned.startswith("project_docs/"):
|
|
248
|
+
cleaned = cleaned[len("project_docs/"):]
|
|
249
|
+
if cleaned.endswith(".md"):
|
|
250
|
+
cleaned = cleaned[:-3]
|
|
251
|
+
if cleaned in {"", ".", "index"}:
|
|
252
|
+
return ""
|
|
253
|
+
return cleaned.casefold()
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def generate_document_from_scaffold(
|
|
257
|
+
item: Mapping[str, Any],
|
|
258
|
+
project_root: Path,
|
|
259
|
+
*,
|
|
260
|
+
timestamp: str | None = None,
|
|
261
|
+
valid_doc_paths: set[str] | None = None,
|
|
262
|
+
title_prefix: str = "",
|
|
263
|
+
) -> str:
|
|
264
|
+
"""Render one Markdown document from a scaffold entry conforming to validate_doc."""
|
|
265
|
+
|
|
266
|
+
rel_path = str(item.get("path", "") or "")
|
|
267
|
+
display_name = rel_path or project_root.name or "项目根目录"
|
|
268
|
+
short_name = PurePosixPath(rel_path).name if rel_path else project_root.name
|
|
269
|
+
title_name = f"{title_prefix}{short_name}" if title_prefix else short_name
|
|
270
|
+
profile = str(item.get("recommended_profile", "standard"))
|
|
271
|
+
is_boundary = bool(item.get("is_boundary", False))
|
|
272
|
+
inv_files = list(item.get("inventory_files") or [])
|
|
273
|
+
inv_subdirs = list(item.get("inventory_subdirs") or [])
|
|
274
|
+
links = item.get("precomputed_links") if isinstance(item.get("precomputed_links"), Mapping) else {}
|
|
275
|
+
synced_at = timestamp or _utc_now()
|
|
276
|
+
source_dir = project_root.joinpath(*PurePosixPath(rel_path).parts) if rel_path else project_root
|
|
277
|
+
is_archive = _is_archive_path(rel_path)
|
|
278
|
+
|
|
279
|
+
breadcrumb = (
|
|
280
|
+
" > ".join([*PurePosixPath(rel_path).parts[:-1], f"**{short_name}**"])
|
|
281
|
+
if rel_path
|
|
282
|
+
else f"**{short_name}**"
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
if profile == "placeholder":
|
|
286
|
+
# Placeholder directories must use ⬜ status (check_5 enforces this
|
|
287
|
+
# for placeholder profile, regardless of archive flag).
|
|
288
|
+
status_line = "⬜ 占位 — 目录已建立,当前无直接业务文件,待后续实现。"
|
|
289
|
+
role = "占位目录(待补充实现)"
|
|
290
|
+
placeholder_file_rows = [
|
|
291
|
+
f"| `{fname}` | {_file_role(fname)} |"
|
|
292
|
+
for fname in inv_files
|
|
293
|
+
]
|
|
294
|
+
lines = [
|
|
295
|
+
f"# {title_name} — {role}",
|
|
296
|
+
"",
|
|
297
|
+
f"**导航**: {breadcrumb}",
|
|
298
|
+
"",
|
|
299
|
+
"<!-- AUTO-GENERATED v3.0: folder-doc START -->",
|
|
300
|
+
"",
|
|
301
|
+
"## 概述",
|
|
302
|
+
"",
|
|
303
|
+
f"`{display_name}` 当前为占位目录,尚未包含直接源码文件或子目录。",
|
|
304
|
+
"",
|
|
305
|
+
"## 文件清单",
|
|
306
|
+
"",
|
|
307
|
+
"| 文件 | 用途 |",
|
|
308
|
+
"|------|------|",
|
|
309
|
+
]
|
|
310
|
+
lines.extend(placeholder_file_rows)
|
|
311
|
+
lines.extend(
|
|
312
|
+
[
|
|
313
|
+
"",
|
|
314
|
+
"## 系统角色",
|
|
315
|
+
"",
|
|
316
|
+
f"`{display_name}` 在当前项目结构中保留为占位模块节点,待后续补充实际源码或数据文件。",
|
|
317
|
+
"",
|
|
318
|
+
"## 状态",
|
|
319
|
+
"",
|
|
320
|
+
status_line,
|
|
321
|
+
"",
|
|
322
|
+
"<!-- AUTO-GENERATED v3.0: folder-doc END -->",
|
|
323
|
+
f"<!-- Last synced: {synced_at} by proj-doc-builder v{GENERATOR_VERSION} -->",
|
|
324
|
+
"",
|
|
325
|
+
]
|
|
326
|
+
)
|
|
327
|
+
return "\n".join(lines)
|
|
328
|
+
|
|
329
|
+
# Standard profile
|
|
330
|
+
file_rows: list[tuple[str, str, str]] = []
|
|
331
|
+
all_symbols: list[tuple[str, str, str]] = []
|
|
332
|
+
for fname in inv_files:
|
|
333
|
+
desc, syms = _describe_file(source_dir, fname)
|
|
334
|
+
file_rows.append((fname, _file_role(fname), desc))
|
|
335
|
+
all_symbols.extend(syms)
|
|
336
|
+
|
|
337
|
+
file_count = len(inv_files)
|
|
338
|
+
subdir_count = len(inv_subdirs)
|
|
339
|
+
role = _directory_role(
|
|
340
|
+
inv_files,
|
|
341
|
+
inv_subdirs,
|
|
342
|
+
is_boundary=is_boundary,
|
|
343
|
+
is_archive=is_archive,
|
|
344
|
+
profile=profile,
|
|
345
|
+
is_root=(not rel_path),
|
|
346
|
+
)
|
|
347
|
+
extension_mix = _extension_mix(inv_files)
|
|
348
|
+
sample_names = ", ".join(f"`{name}`" for name in (inv_files[:3] or inv_subdirs[:3]))
|
|
349
|
+
parent_path = PurePosixPath(rel_path).parent
|
|
350
|
+
parent_name = parent_path.name if rel_path and str(parent_path) not in {"", "."} else ""
|
|
351
|
+
parent_info = links.get("parent") if isinstance(links.get("parent"), Mapping) else None
|
|
352
|
+
parent_rel = str(parent_info.get("relative_link", "")) if parent_info else ""
|
|
353
|
+
parent_doc = str(parent_info.get("doc_path", "")) if parent_info else ""
|
|
354
|
+
parent_link_ok = bool(parent_rel) and (valid_doc_paths is None or parent_doc in valid_doc_paths)
|
|
355
|
+
parent_label = parent_name or project_root.name
|
|
356
|
+
|
|
357
|
+
overview_sentences = [
|
|
358
|
+
f"`{display_name}` 是项目源码树中的{role},当前包含 {file_count} 个直接文件与 {subdir_count} 个直接子目录。",
|
|
359
|
+
(
|
|
360
|
+
f"直接文件以 {extension_mix} 为主,代表性文件包括 {sample_names}。"
|
|
361
|
+
if sample_names and extension_mix
|
|
362
|
+
else (
|
|
363
|
+
f"直接子目录包括 {sample_names}。"
|
|
364
|
+
if sample_names
|
|
365
|
+
else "当前目录没有直接文件或子目录。"
|
|
366
|
+
)
|
|
367
|
+
),
|
|
368
|
+
(
|
|
369
|
+
"目录内含独立的 `CLAUDE.md` 说明文件,本文档仅记录边界层摘要,不展开内部子目录。"
|
|
370
|
+
if is_boundary
|
|
371
|
+
else (
|
|
372
|
+
f"上级目录为 `{parent_label}`,本目录为 {subdir_count} 个子目录与 "
|
|
373
|
+
f"{file_count} 个直接文件提供归属边界。"
|
|
374
|
+
)
|
|
375
|
+
),
|
|
376
|
+
(
|
|
377
|
+
f"定位上,它由 `{parent_label}` 按需引入,不自行调度其他子系统。"
|
|
378
|
+
if not is_boundary
|
|
379
|
+
else f"定位上,它由 `{parent_label}` 直接承载,不再向下展开内部实现。"
|
|
380
|
+
),
|
|
381
|
+
(
|
|
382
|
+
"输入来自上游模块的调用与配置参数,不主动轮询外部服务。"
|
|
383
|
+
if not is_boundary
|
|
384
|
+
else "输入来自上级流程一次性传入的路径与清单参数。"
|
|
385
|
+
),
|
|
386
|
+
f"输出为可供 AI 直接读取的目录描述、文件清单与关键符号索引。",
|
|
387
|
+
(
|
|
388
|
+
"边界上不与同级目录共享可变状态,跨目录协作通过上级模块完成。"
|
|
389
|
+
if not is_boundary
|
|
390
|
+
else "边界上仅描述本层文件,子目录内部另有独立文档承载。"
|
|
391
|
+
),
|
|
392
|
+
"失败模式为源文件缺失或指纹不同步,此时以状态标记提示漂移而非静默通过。",
|
|
393
|
+
]
|
|
394
|
+
|
|
395
|
+
if not rel_path:
|
|
396
|
+
# 仓库根:'项目源码树中的仓库根' 这种自指读起来没有信息,直接说它是入口
|
|
397
|
+
overview_sentences[0] = (
|
|
398
|
+
f"`{display_name}` 是项目总入口,仓库根下直接有 {file_count} 个文件"
|
|
399
|
+
f"并组织 {subdir_count} 个顶层子目录。"
|
|
400
|
+
)
|
|
401
|
+
overview_sentences[2] = "上游无父模块,全部子系统都在本仓库内展开。"
|
|
402
|
+
|
|
403
|
+
lines = [
|
|
404
|
+
f"# {title_name} — {role}",
|
|
405
|
+
"",
|
|
406
|
+
f"**导航**: {breadcrumb}",
|
|
407
|
+
"",
|
|
408
|
+
"<!-- AUTO-GENERATED v3.0: folder-doc START -->",
|
|
409
|
+
"",
|
|
410
|
+
"## 概述",
|
|
411
|
+
"",
|
|
412
|
+
"".join(overview_sentences),
|
|
413
|
+
]
|
|
414
|
+
if is_boundary:
|
|
415
|
+
lines.extend(["", "> **边界目录**:本目录有独立的 CLAUDE.md,此处仅列概要。"])
|
|
416
|
+
|
|
417
|
+
lines.extend(
|
|
418
|
+
[
|
|
419
|
+
"",
|
|
420
|
+
"## 系统角色",
|
|
421
|
+
"",
|
|
422
|
+
(
|
|
423
|
+
f"`{display_name}` 是 `{parent_label}` 下的一个目录模块({role}),"
|
|
424
|
+
f"向上游依赖父级目录的配置与调度输入,向下游为 {subdir_count} 个直接子目录提供归属边界,"
|
|
425
|
+
f"并在本目录内组织 {file_count} 个直接文件的输入与输出。"
|
|
426
|
+
),
|
|
427
|
+
"",
|
|
428
|
+
"## 文件清单",
|
|
429
|
+
"",
|
|
430
|
+
]
|
|
431
|
+
)
|
|
432
|
+
if file_rows:
|
|
433
|
+
lines.extend(
|
|
434
|
+
[
|
|
435
|
+
"| 文件名 | 角色 | 关键内容 |",
|
|
436
|
+
"|--------|------|----------|",
|
|
437
|
+
]
|
|
438
|
+
)
|
|
439
|
+
for fname, role, desc in file_rows:
|
|
440
|
+
lines.append(f"| `{fname}` | {role} | {desc} |")
|
|
441
|
+
else:
|
|
442
|
+
lines.append("本目录无直接源码文件,职责由下级子目录承接。")
|
|
443
|
+
|
|
444
|
+
if inv_subdirs and not is_boundary:
|
|
445
|
+
children_meta = links.get("children") if isinstance(links.get("children"), list) else []
|
|
446
|
+
child_by_name = {
|
|
447
|
+
str(c.get("name")): c
|
|
448
|
+
for c in children_meta
|
|
449
|
+
if isinstance(c, Mapping) and isinstance(c.get("name"), str)
|
|
450
|
+
}
|
|
451
|
+
lines.extend(
|
|
452
|
+
[
|
|
453
|
+
"",
|
|
454
|
+
"## 子目录",
|
|
455
|
+
"",
|
|
456
|
+
"| 目录 | 定位 | 文档 |",
|
|
457
|
+
"|------|------|------|",
|
|
458
|
+
]
|
|
459
|
+
)
|
|
460
|
+
for subdir in inv_subdirs:
|
|
461
|
+
meta = child_by_name.get(subdir)
|
|
462
|
+
doc_cell = "待补充"
|
|
463
|
+
if meta and meta.get("relative_link"):
|
|
464
|
+
target_doc = str(meta.get("doc_path", ""))
|
|
465
|
+
if valid_doc_paths is None or target_doc in valid_doc_paths:
|
|
466
|
+
doc_cell = f"[{subdir}.md]({meta['relative_link']})"
|
|
467
|
+
lines.append(f"| `{subdir}/` | `{short_name}` 下属子目录 | {doc_cell} |")
|
|
468
|
+
|
|
469
|
+
# Key symbols section when __init__.py exists and we extracted >= 3 unique symbols
|
|
470
|
+
if "__init__.py" in inv_files:
|
|
471
|
+
deduped: list[tuple[str, str, str]] = []
|
|
472
|
+
seen_names: set[str] = set()
|
|
473
|
+
for sym_name, sym_kind, sym_file in all_symbols:
|
|
474
|
+
if sym_name not in seen_names:
|
|
475
|
+
seen_names.add(sym_name)
|
|
476
|
+
deduped.append((sym_name, sym_kind, sym_file))
|
|
477
|
+
if len(deduped) >= 3:
|
|
478
|
+
lines.extend(
|
|
479
|
+
[
|
|
480
|
+
"",
|
|
481
|
+
"## 关键符号",
|
|
482
|
+
"",
|
|
483
|
+
"| 符号 | 类型 | 来源文件 | 说明 |",
|
|
484
|
+
"|------|------|----------|------|",
|
|
485
|
+
]
|
|
486
|
+
)
|
|
487
|
+
for sym_name, sym_kind, sym_file in deduped[:12]:
|
|
488
|
+
lines.append(f"| `{sym_name}` | {sym_kind} | `{sym_file}` | `{short_name}` 公开{sym_kind} |")
|
|
489
|
+
|
|
490
|
+
lines.extend(
|
|
491
|
+
[
|
|
492
|
+
"",
|
|
493
|
+
"## 依赖关系",
|
|
494
|
+
"",
|
|
495
|
+
"| 方向 | 模块 | 关系 | 文档 |",
|
|
496
|
+
"|------|------|------|------|",
|
|
497
|
+
]
|
|
498
|
+
)
|
|
499
|
+
dep_rows_added = 0
|
|
500
|
+
if parent_link_ok:
|
|
501
|
+
parent_name = PurePosixPath(parent_doc).name
|
|
502
|
+
lines.append(
|
|
503
|
+
f"| ⬆ 上游 | `{parent_name[:-3]}` | 承接上级目录的模块组织与配置输入 | [{parent_name}]({parent_rel}) |"
|
|
504
|
+
)
|
|
505
|
+
dep_rows_added += 1
|
|
506
|
+
children_meta = links.get("children") if isinstance(links.get("children"), list) else []
|
|
507
|
+
if not is_boundary:
|
|
508
|
+
for child_meta in children_meta[:3]:
|
|
509
|
+
if not isinstance(child_meta, Mapping):
|
|
510
|
+
continue
|
|
511
|
+
c_rel = str(child_meta.get("relative_link", ""))
|
|
512
|
+
c_doc = str(child_meta.get("doc_path", ""))
|
|
513
|
+
c_name = str(child_meta.get("name", ""))
|
|
514
|
+
if c_rel and c_name and (valid_doc_paths is None or c_doc in valid_doc_paths):
|
|
515
|
+
lines.append(
|
|
516
|
+
f"| ⬇ 下游 | `{c_name}` | 向下协调子目录 `{c_name}/` 实现与数据流转 | [{c_name}.md]({c_rel}) |"
|
|
517
|
+
)
|
|
518
|
+
dep_rows_added += 1
|
|
519
|
+
if dep_rows_added == 0 and rel_path:
|
|
520
|
+
depth = len(PurePosixPath(rel_path).parts) - 1
|
|
521
|
+
index_rel = ("../" * depth) + "index.md"
|
|
522
|
+
if valid_doc_paths is None or "project_docs/index.md" in valid_doc_paths:
|
|
523
|
+
lines.append(
|
|
524
|
+
f"| ⬆ 上游 | `index` | 承接项目顶层模块组织与配置输入 | [index.md]({index_rel}) |"
|
|
525
|
+
)
|
|
526
|
+
dep_rows_added += 1
|
|
527
|
+
if dep_rows_added == 0:
|
|
528
|
+
tests_meta = links.get("tests") if isinstance(links.get("tests"), Mapping) else None
|
|
529
|
+
t_rel = str(tests_meta.get("relative_link", "")) if tests_meta else ""
|
|
530
|
+
t_doc = str(tests_meta.get("doc_path", "")) if tests_meta else ""
|
|
531
|
+
if t_rel and (valid_doc_paths is None or t_doc in valid_doc_paths):
|
|
532
|
+
lines.append(
|
|
533
|
+
f"| ↔ 协作 | `tests` | 与项目测试套件协同验证本目录行为 | [tests.md]({t_rel}) |"
|
|
534
|
+
)
|
|
535
|
+
else:
|
|
536
|
+
lines.append(
|
|
537
|
+
f"| ⬆ 上游 | `{short_name}` | 依赖项目根配置与运行环境输入 | 待补充 |"
|
|
538
|
+
)
|
|
539
|
+
|
|
540
|
+
# --- v4.5: 数据与状态 / 性能与资源特征 / 变更与迁移注意 三节 ---
|
|
541
|
+
_state_ext = (".json", ".toml", ".yaml", ".yml", ".db", ".sqlite", ".state", ".lock")
|
|
542
|
+
_state_files = [
|
|
543
|
+
fname
|
|
544
|
+
for fname in inv_files
|
|
545
|
+
if fname.lower().endswith(_state_ext)
|
|
546
|
+
or any(tok in fname.lower() for tok in ("state", "config", "manifest"))
|
|
547
|
+
]
|
|
548
|
+
lines.extend(["", "## 数据与状态", ""])
|
|
549
|
+
if _state_files:
|
|
550
|
+
listed = "、".join(f"`{name}`" for name in _state_files[:5])
|
|
551
|
+
lines.append(
|
|
552
|
+
f"本目录直接持有以下配置/状态载体:{listed}。"
|
|
553
|
+
"这些文件由本目录或上层工具在运行期读取或写入;"
|
|
554
|
+
"跨进程协调通过 `project_docs` 契约定义的路径约定,"
|
|
555
|
+
"未在本目录内引入独立进程锁或 journal。"
|
|
556
|
+
)
|
|
557
|
+
else:
|
|
558
|
+
lines.append(
|
|
559
|
+
"本节不适用:本目录为纯源码/文档目录,不直接读写持久化文件,"
|
|
560
|
+
"也无跨进程共享状态或独立锁。"
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
lines.extend(["", "## 性能与资源特征", ""])
|
|
564
|
+
if file_count or subdir_count:
|
|
565
|
+
lines.append(
|
|
566
|
+
f"本目录直接文件 {file_count} 个、直接子目录 {subdir_count} 个。"
|
|
567
|
+
"文档同步按文件清单线性遍历,单目录开销与直接文件数成正比"
|
|
568
|
+
f"(当前量级 O({max(file_count, 1)}));"
|
|
569
|
+
"符号提取对 Python 文件做单次 AST 解析,无跨目录递归常驻 worker。"
|
|
570
|
+
)
|
|
571
|
+
else:
|
|
572
|
+
lines.append(
|
|
573
|
+
"本节不适用:本目录无直接文件与子目录,不产生可测量的运行期开销。"
|
|
574
|
+
)
|
|
575
|
+
|
|
576
|
+
lines.extend(["", "## 变更与迁移注意", ""])
|
|
577
|
+
lines.append(
|
|
578
|
+
f"本文档遵循 doc_contract_version={contract.DOC_CONTRACT_VERSION},"
|
|
579
|
+
f"由 proj-doc-builder v{GENERATOR_VERSION} 按当前源码快照生成。"
|
|
580
|
+
"契约升级时通过 `--upgrade-plan` 报告差异,再用 `--migrate-manifest` 迁移;"
|
|
581
|
+
"本目录无独立的对外 API 契约变化记录,迁移仅同步文档结构与文件清单。"
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
if is_archive:
|
|
585
|
+
status_text = "📦 历史存档 — 归档内容与历史记录快照,仅供追溯参考。"
|
|
586
|
+
elif file_count > 0 or subdir_count > 0:
|
|
587
|
+
status_text = "✅ 完整 — 目录结构与文件清单已按当前源码快照同步生成。"
|
|
588
|
+
else:
|
|
589
|
+
status_text = "🔶 开发中 — 目录结构已建立,内容持续补充中。"
|
|
590
|
+
|
|
591
|
+
lines.extend(
|
|
592
|
+
[
|
|
593
|
+
"",
|
|
594
|
+
"## 状态",
|
|
595
|
+
"",
|
|
596
|
+
status_text,
|
|
597
|
+
"",
|
|
598
|
+
"<!-- AUTO-GENERATED v3.0: folder-doc END -->",
|
|
599
|
+
f"<!-- Last synced: {synced_at} by proj-doc-builder v{GENERATOR_VERSION} -->",
|
|
600
|
+
"",
|
|
601
|
+
]
|
|
602
|
+
)
|
|
603
|
+
return "\n".join(lines)
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _compute_title_prefixes(scaffold: Sequence[Any]) -> dict[str, str]:
|
|
607
|
+
"""Return ``{rel_path: prefix}`` so identical ``name — role`` titles stay unique.
|
|
608
|
+
|
|
609
|
+
A prefix is only assigned to directories whose bare title collides with another
|
|
610
|
+
directory. The shortest trailing path segments that disambiguate the whole group
|
|
611
|
+
are used, so titles stay readable instead of always carrying a full path.
|
|
612
|
+
"""
|
|
613
|
+
|
|
614
|
+
entries: list[tuple[str, str, str, tuple[str, ...]]] = []
|
|
615
|
+
for item in scaffold:
|
|
616
|
+
if not isinstance(item, Mapping):
|
|
617
|
+
continue
|
|
618
|
+
rel_path = str(item.get("path", "") or "")
|
|
619
|
+
if not rel_path:
|
|
620
|
+
continue
|
|
621
|
+
short_name = PurePosixPath(rel_path).name
|
|
622
|
+
profile = str(item.get("recommended_profile", "standard"))
|
|
623
|
+
inv_files = list(item.get("inventory_files") or [])
|
|
624
|
+
inv_subdirs = list(item.get("inventory_subdirs") or [])
|
|
625
|
+
role = _directory_role(
|
|
626
|
+
inv_files,
|
|
627
|
+
inv_subdirs,
|
|
628
|
+
is_boundary=bool(item.get("is_boundary", False)),
|
|
629
|
+
is_archive=_is_archive_path(rel_path),
|
|
630
|
+
profile=profile,
|
|
631
|
+
is_root=(not rel_path),
|
|
632
|
+
)
|
|
633
|
+
entries.append((rel_path, short_name, role, PurePosixPath(rel_path).parts[:-1]))
|
|
634
|
+
|
|
635
|
+
groups: dict[tuple[str, str], list[tuple[str, tuple[str, ...]]]] = {}
|
|
636
|
+
for rel_path, short_name, role, parents in entries:
|
|
637
|
+
groups.setdefault((short_name, role), []).append((rel_path, parents))
|
|
638
|
+
|
|
639
|
+
prefixes: dict[str, str] = {}
|
|
640
|
+
for (short_name, _role), members in groups.items():
|
|
641
|
+
if len(members) < 2:
|
|
642
|
+
continue
|
|
643
|
+
for depth in range(1, 7):
|
|
644
|
+
candidate_prefixes = {
|
|
645
|
+
rel_path: "/".join(parents[-depth:]) + "/" if depth <= len(parents) else ""
|
|
646
|
+
for rel_path, parents in members
|
|
647
|
+
}
|
|
648
|
+
if len(set(candidate_prefixes.values())) == len(members):
|
|
649
|
+
for rel_path, prefix in candidate_prefixes.items():
|
|
650
|
+
if prefix:
|
|
651
|
+
prefixes[rel_path] = prefix
|
|
652
|
+
break
|
|
653
|
+
return prefixes
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def generate_from_scaffold_file(
|
|
657
|
+
scaffold_path: Path,
|
|
658
|
+
project_root: Path,
|
|
659
|
+
*,
|
|
660
|
+
paths_filter: Sequence[str] | None = None,
|
|
661
|
+
overwrite: bool = False,
|
|
662
|
+
dry_run: bool = False,
|
|
663
|
+
timestamp: str | None = None,
|
|
664
|
+
) -> dict[str, Any]:
|
|
665
|
+
raw = scaffold_path.read_text(encoding="utf-8")
|
|
666
|
+
payload = json.loads(raw)
|
|
667
|
+
scaffold = payload.get("scaffold") if isinstance(payload, Mapping) else None
|
|
668
|
+
if not isinstance(scaffold, list):
|
|
669
|
+
raise ValueError(f"scaffold file does not contain a 'scaffold' list: {scaffold_path}")
|
|
670
|
+
|
|
671
|
+
allowed_keys = {_normalize_filter_key(p) for p in paths_filter} if paths_filter else None
|
|
672
|
+
valid_doc_paths: set[str] = {
|
|
673
|
+
str(item["doc_path"])
|
|
674
|
+
for item in scaffold
|
|
675
|
+
if isinstance(item, Mapping) and isinstance(item.get("doc_path"), str)
|
|
676
|
+
}
|
|
677
|
+
docs_root = project_root / "project_docs"
|
|
678
|
+
if docs_root.is_dir():
|
|
679
|
+
for existing in contract.discover_active_markdown_paths(docs_root):
|
|
680
|
+
valid_doc_paths.add(f"project_docs/{existing}")
|
|
681
|
+
|
|
682
|
+
written: list[str] = []
|
|
683
|
+
skipped_existing: list[str] = []
|
|
684
|
+
ts = timestamp or _utc_now()
|
|
685
|
+
|
|
686
|
+
# Pre-compute H1 disambiguation prefixes for same-name directories
|
|
687
|
+
# sharing the same role (avoids duplicate `# name — role` titles).
|
|
688
|
+
title_prefixes = _compute_title_prefixes(scaffold)
|
|
689
|
+
|
|
690
|
+
for item in scaffold:
|
|
691
|
+
if not isinstance(item, Mapping):
|
|
692
|
+
continue
|
|
693
|
+
rel_path = str(item.get("path", "") or "")
|
|
694
|
+
doc_path_str = str(item.get("doc_path", "") or "")
|
|
695
|
+
if not doc_path_str.startswith("project_docs/"):
|
|
696
|
+
continue
|
|
697
|
+
if allowed_keys is not None:
|
|
698
|
+
key = _normalize_filter_key(rel_path)
|
|
699
|
+
doc_key = _normalize_filter_key(doc_path_str)
|
|
700
|
+
if key not in allowed_keys and doc_key not in allowed_keys:
|
|
701
|
+
continue
|
|
702
|
+
|
|
703
|
+
rel_doc = doc_path_str[len("project_docs/"):]
|
|
704
|
+
target = docs_root.joinpath(*PurePosixPath(rel_doc).parts)
|
|
705
|
+
if target.exists() and not overwrite:
|
|
706
|
+
skipped_existing.append(doc_path_str)
|
|
707
|
+
continue
|
|
708
|
+
|
|
709
|
+
content = generate_document_from_scaffold(
|
|
710
|
+
item,
|
|
711
|
+
project_root,
|
|
712
|
+
timestamp=ts,
|
|
713
|
+
valid_doc_paths=valid_doc_paths,
|
|
714
|
+
title_prefix=title_prefixes.get(rel_path, ""),
|
|
715
|
+
)
|
|
716
|
+
if not dry_run:
|
|
717
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
718
|
+
contract.atomic_write_utf8(target, content)
|
|
719
|
+
written.append(doc_path_str)
|
|
720
|
+
|
|
721
|
+
return {
|
|
722
|
+
"ok": True,
|
|
723
|
+
"dry_run": dry_run,
|
|
724
|
+
"overwrite": overwrite,
|
|
725
|
+
"scaffold_path": scaffold_path.as_posix(),
|
|
726
|
+
"project_root": project_root.as_posix(),
|
|
727
|
+
"written_count": len(written),
|
|
728
|
+
"skipped_existing_count": len(skipped_existing),
|
|
729
|
+
"written": written,
|
|
730
|
+
"skipped_existing": skipped_existing,
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def _parse_paths_arg(values: Sequence[str] | None) -> list[str] | None:
|
|
735
|
+
if not values:
|
|
736
|
+
return None
|
|
737
|
+
out: list[str] = []
|
|
738
|
+
for raw in values:
|
|
739
|
+
for part in raw.split(","):
|
|
740
|
+
cleaned = part.strip()
|
|
741
|
+
if cleaned:
|
|
742
|
+
out.append(cleaned)
|
|
743
|
+
return out or None
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
747
|
+
parser = argparse.ArgumentParser(
|
|
748
|
+
description="Batch-generate project_docs/*.md from a sync_project_docs --scaffold-dump JSON file"
|
|
749
|
+
)
|
|
750
|
+
parser.add_argument("--scaffold", required=True, help="path to scaffold JSON from --scaffold-dump")
|
|
751
|
+
parser.add_argument("--project-root", default=".", help="project root directory")
|
|
752
|
+
parser.add_argument(
|
|
753
|
+
"--paths",
|
|
754
|
+
nargs="+",
|
|
755
|
+
help="optional directory or doc paths to filter (space- or comma-separated)",
|
|
756
|
+
)
|
|
757
|
+
parser.add_argument(
|
|
758
|
+
"--overwrite",
|
|
759
|
+
action="store_true",
|
|
760
|
+
help="overwrite existing project_docs/*.md files (default skips existing)",
|
|
761
|
+
)
|
|
762
|
+
parser.add_argument(
|
|
763
|
+
"--dry-run",
|
|
764
|
+
action="store_true",
|
|
765
|
+
help="preview which files would be generated without writing",
|
|
766
|
+
)
|
|
767
|
+
parser.add_argument("--json", action="store_true", help="emit one JSON object")
|
|
768
|
+
args = parser.parse_args(argv)
|
|
769
|
+
|
|
770
|
+
result = generate_from_scaffold_file(
|
|
771
|
+
Path(args.scaffold).resolve(),
|
|
772
|
+
Path(args.project_root).resolve(),
|
|
773
|
+
paths_filter=_parse_paths_arg(args.paths),
|
|
774
|
+
overwrite=args.overwrite,
|
|
775
|
+
dry_run=args.dry_run,
|
|
776
|
+
)
|
|
777
|
+
if args.json:
|
|
778
|
+
sys.stdout.write(contract.stable_json_dumps(result))
|
|
779
|
+
else:
|
|
780
|
+
action = "拟生成" if args.dry_run else "已生成"
|
|
781
|
+
print(
|
|
782
|
+
f"gen_docs_from_scaffold: {action} {result['written_count']} 份文档,"
|
|
783
|
+
f"跳过已存在 {result['skipped_existing_count']} 份。"
|
|
784
|
+
)
|
|
785
|
+
return 0
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
if __name__ == "__main__":
|
|
789
|
+
raise SystemExit(main())
|