validate_plugin_package.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import re
  7. import sys
  8. from pathlib import Path
  9. from typing import Any
  10. import sync_plugin_version
  11. SCHEMA_VERSION = "webnovel-plugin-package-validator/v1"
  12. PLUGIN_NAME = "webnovel-writer"
  13. KEBAB_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
  14. SEMVER_RE = sync_plugin_version.VERSION_PATTERN
  15. LOCAL_ABSOLUTE_RE = re.compile(r"(?i)(?:[a-z]:\\users\\|/users/[^/\s]+/|/home/[^/\s]+/)")
  16. def _issue(
  17. code: str,
  18. *,
  19. message: str,
  20. severity: str = "error",
  21. path: str = "",
  22. repair: str = "",
  23. ) -> dict[str, str]:
  24. return {
  25. "code": code,
  26. "severity": severity,
  27. "message": message,
  28. "path": path,
  29. "repair": repair,
  30. }
  31. def _load_json(path: Path) -> tuple[dict[str, Any], str]:
  32. try:
  33. payload = json.loads(path.read_text(encoding="utf-8"))
  34. except FileNotFoundError:
  35. return {}, "missing"
  36. except json.JSONDecodeError as exc:
  37. return {}, f"invalid_json:{exc}"
  38. except OSError as exc:
  39. return {}, f"read_error:{exc}"
  40. if not isinstance(payload, dict):
  41. return {}, "not_object"
  42. return payload, ""
  43. def _frontmatter(path: Path) -> dict[str, str]:
  44. try:
  45. text = path.read_text(encoding="utf-8")
  46. except OSError:
  47. return {}
  48. if not text.startswith("---"):
  49. return {}
  50. end = text.find("\n---", 3)
  51. if end < 0:
  52. return {}
  53. result: dict[str, str] = {}
  54. for line in text[3:end].splitlines():
  55. if ":" not in line:
  56. continue
  57. key, _, value = line.partition(":")
  58. result[key.strip()] = value.strip()
  59. return result
  60. def _marketplace_plugin(payload: dict[str, Any]) -> dict[str, Any] | None:
  61. plugins = payload.get("plugins")
  62. if not isinstance(plugins, list):
  63. return None
  64. for item in plugins:
  65. if isinstance(item, dict) and item.get("name") == PLUGIN_NAME:
  66. return item
  67. return None
  68. def _is_plugin_root(root: Path) -> bool:
  69. return (root / ".claude-plugin" / "plugin.json").is_file()
  70. def _plugin_root(root: Path) -> Path:
  71. return root if _is_plugin_root(root) else root / PLUGIN_NAME
  72. def _repo_root(root: Path) -> Path:
  73. if _is_plugin_root(root) and (root.parent / ".claude-plugin" / "marketplace.json").is_file():
  74. return root.parent
  75. return root
  76. def _check_manifest(root: Path, issues: list[dict[str, str]]) -> tuple[str, str]:
  77. plugin_json = _plugin_root(root) / ".claude-plugin" / "plugin.json"
  78. payload, error = _load_json(plugin_json)
  79. if error:
  80. issues.append(_issue("manifest.plugin_json", message=error, path=str(plugin_json), repair="恢复 .claude-plugin/plugin.json。"))
  81. return "", ""
  82. name = str(payload.get("name") or "")
  83. version = str(payload.get("version") or "")
  84. if not KEBAB_RE.fullmatch(name):
  85. issues.append(_issue("manifest.name", message=f"invalid plugin name: {name}", path=str(plugin_json), repair="使用 kebab-case 插件名。"))
  86. if not SEMVER_RE.fullmatch(version):
  87. issues.append(_issue("manifest.version", message=f"invalid semver: {version}", path=str(plugin_json), repair="使用 X.Y.Z 版本号。"))
  88. if not str(payload.get("description") or "").strip():
  89. issues.append(_issue("manifest.description", message="plugin description missing", path=str(plugin_json), repair="补齐 description。"))
  90. return name, version
  91. def _check_marketplace(root: Path, plugin_version: str, issues: list[dict[str, str]]) -> None:
  92. marketplace = _repo_root(root) / ".claude-plugin" / "marketplace.json"
  93. payload, error = _load_json(marketplace)
  94. if error:
  95. severity = "warning" if _is_plugin_root(root) else "error"
  96. issues.append(
  97. _issue(
  98. "marketplace.json",
  99. message=error,
  100. severity=severity,
  101. path=str(marketplace),
  102. repair="在仓库根运行可校验 marketplace;插件根安装包可忽略该项。",
  103. )
  104. )
  105. return
  106. plugin = _marketplace_plugin(payload)
  107. if plugin is None:
  108. issues.append(_issue("marketplace.plugin", message=f"{PLUGIN_NAME} missing from marketplace", path=str(marketplace), repair="在 plugins[] 中加入 webnovel-writer。"))
  109. return
  110. if plugin.get("source") != "./webnovel-writer":
  111. issues.append(_issue("marketplace.source", message=f"unexpected source: {plugin.get('source')}", path=str(marketplace), repair="source 应为 ./webnovel-writer。"))
  112. marketplace_version = str(plugin.get("version") or "")
  113. if plugin_version and marketplace_version != plugin_version:
  114. issues.append(
  115. _issue(
  116. "version.marketplace",
  117. message=f"plugin.json={plugin_version}, marketplace.json={marketplace_version}",
  118. path=str(marketplace),
  119. repair="运行 sync_plugin_version.py --version X.Y.Z --release-notes ...。",
  120. )
  121. )
  122. def _check_readme_version(root: Path, plugin_version: str, issues: list[dict[str, str]]) -> None:
  123. if _is_plugin_root(root):
  124. candidates = [_repo_root(root) / "README.md", root / "README.md"]
  125. else:
  126. candidates = [root / "README.md", _plugin_root(root) / "README.md"]
  127. readme = next((candidate for candidate in candidates if candidate.is_file()), candidates[0])
  128. try:
  129. content = readme.read_text(encoding="utf-8")
  130. readme_version = sync_plugin_version.get_readme_current_version(content)
  131. except Exception as exc:
  132. issues.append(_issue("version.readme.parse", message=str(exc), path=str(readme), repair="保持 README 版本表格式与 sync_plugin_version.py 一致。"))
  133. return
  134. if plugin_version and readme_version != plugin_version:
  135. issues.append(
  136. _issue(
  137. "version.readme",
  138. message=f"plugin.json={plugin_version}, README.md={readme_version}",
  139. path=str(readme),
  140. repair="运行 sync_plugin_version.py --version X.Y.Z --release-notes ...。",
  141. )
  142. )
  143. def _check_frontmatter(root: Path, issues: list[dict[str, str]]) -> None:
  144. plugin_root = _plugin_root(root)
  145. for skill in sorted((plugin_root / "skills").glob("*/SKILL.md")):
  146. fm = _frontmatter(skill)
  147. for field in ("name", "description"):
  148. if not fm.get(field):
  149. issues.append(_issue("skill.frontmatter", message=f"skill missing {field}", path=str(skill), repair="按 plugin-dev skill-development 补齐 frontmatter。"))
  150. for agent in sorted((plugin_root / "agents").glob("*.md")):
  151. fm = _frontmatter(agent)
  152. for field in ("name", "description", "tools"):
  153. if not fm.get(field):
  154. issues.append(_issue("agent.frontmatter", message=f"agent missing {field}", path=str(agent), repair="按 plugin-dev agent-development 补齐 frontmatter。"))
  155. def _check_optional_assets(root: Path, issues: list[dict[str, str]]) -> None:
  156. plugin_root = _plugin_root(root)
  157. if not (plugin_root / "LICENSE").is_file():
  158. issues.append(_issue("license", message="LICENSE missing", severity="error", path=str(plugin_root / "LICENSE"), repair="恢复插件 LICENSE。"))
  159. dashboard_dist = plugin_root / "dashboard" / "frontend" / "dist"
  160. if not dashboard_dist.is_dir():
  161. issues.append(_issue("dashboard.dist", message="dashboard frontend dist missing", severity="warning", path=str(dashboard_dist), repair="发布前运行 dashboard 前端 build 并包含 dist。"))
  162. hooks_json = plugin_root / "hooks" / "hooks.json"
  163. if hooks_json.exists():
  164. payload, error = _load_json(hooks_json)
  165. if error:
  166. issues.append(_issue("hooks.schema", message=error, path=str(hooks_json), repair="修复 hooks/hooks.json。"))
  167. elif "description" not in payload or "hooks" not in payload:
  168. issues.append(_issue("hooks.wrapper", message="hooks.json should use plugin-dev wrapper format", path=str(hooks_json), repair="外层包含 description 与 hooks。"))
  169. def _check_portability(root: Path, issues: list[dict[str, str]]) -> None:
  170. plugin_root = _plugin_root(root)
  171. targets = list((plugin_root / "skills").glob("*/SKILL.md"))
  172. targets.extend((plugin_root / "agents").glob("*.md"))
  173. targets.extend((plugin_root / ".claude-plugin").glob("*.json"))
  174. hooks_root = plugin_root / "hooks"
  175. if hooks_root.is_dir():
  176. targets.extend(path for path in hooks_root.rglob("*") if path.suffix in {".json", ".py", ".sh", ".md"})
  177. for path in targets:
  178. try:
  179. text = path.read_text(encoding="utf-8")
  180. except OSError:
  181. continue
  182. if LOCAL_ABSOLUTE_RE.search(text):
  183. issues.append(
  184. _issue(
  185. "portability.local_absolute_path",
  186. message="local absolute path found in plugin component",
  187. severity="warning",
  188. path=str(path),
  189. repair="插件组件内使用 ${CLAUDE_PLUGIN_ROOT} 或相对路径。",
  190. )
  191. )
  192. def validate_package(root: str | Path | None = None, *, strict: bool = False) -> dict[str, Any]:
  193. repo_root = Path(root) if root is not None else Path(__file__).resolve().parent.parent.parent
  194. issues: list[dict[str, str]] = []
  195. _, plugin_version = _check_manifest(repo_root, issues)
  196. _check_marketplace(repo_root, plugin_version, issues)
  197. _check_readme_version(repo_root, plugin_version, issues)
  198. _check_frontmatter(repo_root, issues)
  199. _check_optional_assets(repo_root, issues)
  200. _check_portability(repo_root, issues)
  201. blocking = [
  202. item for item in issues if item["severity"] == "error" or (strict and item["severity"] == "warning")
  203. ]
  204. return {
  205. "schema_version": SCHEMA_VERSION,
  206. "ok": not blocking,
  207. "strict": strict,
  208. "root": str(repo_root),
  209. "error_count": sum(1 for item in issues if item["severity"] == "error"),
  210. "warning_count": sum(1 for item in issues if item["severity"] == "warning"),
  211. "issues": issues,
  212. }
  213. def format_report(report: dict[str, Any], output_format: str = "text") -> str:
  214. if output_format == "json":
  215. return json.dumps(report, ensure_ascii=False, indent=2)
  216. status = "OK" if report.get("ok") else "ERROR"
  217. lines = [
  218. f"{status} plugin package",
  219. f"errors: {report.get('error_count')} warnings: {report.get('warning_count')}",
  220. ]
  221. for item in report.get("issues") or []:
  222. lines.append(f"{item.get('severity', '').upper()} {item.get('code')}: {item.get('message')}")
  223. if item.get("path"):
  224. lines.append(f" path: {item.get('path')}")
  225. if item.get("repair"):
  226. lines.append(f" repair: {item.get('repair')}")
  227. return "\n".join(lines)
  228. def main() -> int:
  229. parser = argparse.ArgumentParser(description="Validate webnovel-writer plugin package metadata and components")
  230. parser.add_argument("--root", default="", help="仓库根目录,默认自动推断")
  231. parser.add_argument("--strict", action="store_true", help="warning 也视为失败")
  232. parser.add_argument("--format", choices=["text", "json"], default="text")
  233. args = parser.parse_args()
  234. report = validate_package(args.root or None, strict=args.strict)
  235. print(format_report(report, args.format))
  236. return 0 if report.get("ok") else 1
  237. if __name__ == "__main__":
  238. raise SystemExit(main())