Peach: Local-first video metadata scraper and media manager.
feat(github): 命令行提交的 issue 按模板补上类型,照搬开发规则写的自动关闭
longmeidaofdf2189b2f97
diff --git a/.github/labels.json b/.github/labels.jsonindex 9a823b742..8bb18b555 100644--- a/.github/labels.json+++ b/.github/labels.json@@ -24,5 +24,6 @@{"name": "area:metadata", "color": "5319e7", "description": "刮削、来源及元数据编目 / Scraping, sources and metadata cataloging"},{"name": "area:tooling", "color": "bfd4f2", "description": "测试、构建、持续集成与开发工具 / Tests, builds, CI and developer tooling"},{"name": "status:needs-info", "color": "d876e3", "description": "缺少定位所需信息;见维护者具体问题 / Missing information; see maintainer questions"},- {"name": "status:needs-verification", "color": "fbca04", "description": "修复版本已发布,等待目标环境验证 / Fix released; awaiting verification"}+ {"name": "status:needs-verification", "color": "fbca04", "description": "修复版本已发布,等待目标环境验证 / Fix released; awaiting verification"},+ {"name": "status:needs-template", "color": "e4e669", "description": "未按模板填写,已自动关闭;补齐章节后重开 / Missing template sections; closed until filled in"}]diff --git a/.github/workflows/issue-intake.yml b/.github/workflows/issue-intake.ymlnew file mode 100644index 000000000..2bb6d6166--- /dev/null+++ b/.github/workflows/issue-intake.yml@@ -0,0 +1,66 @@+name: Issue 模板检查++on:+ issues:+ types: [opened, edited]+ workflow_dispatch:+ inputs:+ issue_number:+ description: 只输出判定、不改动的 issue 编号+ required: true++permissions:+ contents: read+ issues: write++concurrency:+ group: issue-intake-${{ github.event.issue.number || inputs.issue_number }}+ cancel-in-progress: false++jobs:+ intake:+ if: github.repository == 'peach-mitao/peach'+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@v7+ with:+ ref: master+ persist-credentials: false+ - uses: actions/setup-python@v7+ with:+ python-version: '3.14'+ - name: 判定并处理+ env:+ GH_TOKEN: ${{ github.token }}+ GH_REPO: ${{ github.repository }}+ NUMBER: ${{ github.event.issue.number || inputs.issue_number }}+ DRY_RUN: ${{ github.event_name == 'workflow_dispatch' }}+ PYTHONUTF8: '1'+ run: |+ event="$GITHUB_EVENT_PATH"+ if [ "$DRY_RUN" = true ]; then+ event="$RUNNER_TEMP/event.json"+ gh api "repos/$GH_REPO/issues/$NUMBER" | jq '{action: "opened", issue: .}' > "$event"+ fi+ verdict=$(python scripts/issue_intake.py --event "$event")+ echo "#$NUMBER: $verdict"+ if [ "$DRY_RUN" = true ]; then+ exit 0+ fi+ read -r action kind <<< "$verdict"+ case "$action" in+ type)+ gh issue edit "$NUMBER" --type "$kind"+ ;;+ close)+ python scripts/issue_intake.py --notice > "$RUNNER_TEMP/notice.md"+ gh issue comment "$NUMBER" --body-file "$RUNNER_TEMP/notice.md"+ gh issue edit "$NUMBER" --add-label status:needs-template+ gh issue close "$NUMBER" --reason "not planned"+ ;;+ reopen)+ gh issue reopen "$NUMBER"+ gh issue edit "$NUMBER" --remove-label status:needs-template --type "$kind"+ ;;+ esacdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 00a3daa5d..8f84dba82 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -17,9 +17,9 @@ Issue 按 [`.github/ISSUE_TEMPLATE/`](.github/ISSUE_TEMPLATE/) 的模板写:gh issue create --repo peach-mitao/peach --title "<标题>" --type Bug --body-file <填好的模板>```-建议把 `Bug` 换成 `Feature`;没有设置类型的权限时省略 `--type`,由维护者补上。正文写给维护者和其他用户看,用通用技术说法;`AGENTS.md` 与技能里的术语和交付格式只用于改代码,不用于 issue。+建议把 `Bug` 换成 `Feature`;没有设置类型的权限时省略 `--type`,按模板章节写的 issue 会自动补上类型。正文写给维护者和其他用户看,用通用技术说法;`AGENTS.md` 与技能里的术语和交付格式只用于改代码,不用于 issue。没有模板章节、又套用这些内部用语的 issue 会被自动关闭,按模板补齐后自动重开。-Write issues with the templates in [`.github/ISSUE_TEMPLATE/`](.github/ISSUE_TEMPLATE/): `bug_report.md` for bugs, `feature_request.md` for features. Keep the template headings in order and fill in each one; drop optional sections you have nothing for, and put extra material such as a root-cause analysis after the template sections. The web form under New issue is the easiest path. When an AI tool or the command line submits the issue, copy the template file, remove the leading `---` block and the `<!-- -->` comments, fill it in, and submit it with the command above; use `--type Feature` for features, and leave out `--type` if you lack permission to set it. Write for maintainers and other users in plain technical language; the terms and delivery format in `AGENTS.md` and the skills are for code changes, not issues.+Write issues with the templates in [`.github/ISSUE_TEMPLATE/`](.github/ISSUE_TEMPLATE/): `bug_report.md` for bugs, `feature_request.md` for features. Keep the template headings in order and fill in each one; drop optional sections you have nothing for, and put extra material such as a root-cause analysis after the template sections. The web form under New issue is the easiest path. When an AI tool or the command line submits the issue, copy the template file, remove the leading `---` block and the `<!-- -->` comments, fill it in, and submit it with the command above; use `--type Feature` for features, and leave out `--type` if you lack permission to set it: issues that follow a template get their type automatically. Write for maintainers and other users in plain technical language; the terms and delivery format in `AGENTS.md` and the skills are for code changes, not issues. Issues that skip the template sections and use those internal terms are closed automatically, and reopen once the sections are filled in.公开截图、录屏和附件使用不含露骨画面的演示资料,并遮盖隐私信息;不要上传影片、封面原图或数据库。公开内容与素材许可要求见[文档规范](docs/WRITING.md#公开与私有记录)。diff --git a/scripts/issue_intake.py b/scripts/issue_intake.pynew file mode 100644index 000000000..172bf0c27--- /dev/null+++ b/scripts/issue_intake.py@@ -0,0 +1,105 @@+"""外部 issue 的模板检查:让命令行和 API 提交的 issue 与网页模板提交的结果一致。++网页「New issue」按模板提交时会带上模板的 Issue Type;用 `gh` 或 API 提交则不经过模板。+作者不是维护者、也没有 Issue Type 的新 issue 按下列规则处理:正文含有某个模板的章节,+补上那个模板的 Issue Type;缺少模板章节又套用了 `AGENTS.md` 与技能里的交付用语,关闭;+按模板补齐章节后重开并补上类型。GitHub 写操作由 `.github/workflows/issue-intake.yml` 完成,+本脚本只输出 `keep`、`close`、`type <类型>` 或 `reopen <类型>`。+"""+from __future__ import annotations++import argparse+import json+from pathlib import Path+import re+import sys++ROOT = Path(__file__).resolve().parents[1]+TEMPLATES = ROOT / ".github/ISSUE_TEMPLATE"+LABEL = "status:needs-template"+MAINTAINERS = frozenset({"OWNER", "MEMBER", "COLLABORATOR"})+# 智能体规则里的交付用语,用户自己描述问题时很少写到。+INTERNAL_TERMS = ("账本", "真相字段", "影响面", "落库", "复核产物", "兼容投影", "授权边界",+ "合成样本", "验收", "交接", "明确不做", "分批交付", "隔离工作树")+HEADING = re.compile(r"^ {0,3}#{1,6}\s*(.+?)\s*#*\s*$", re.M)+TYPE_LINE = re.compile(r"^type:\s*(\S+)\s*$", re.M)+OPTIONAL = re.compile(r"[((][^))]*[))]")+NOTICE = """\+这条 issue 没有按模板填写,已自动关闭。请编辑正文,补上模板的章节(缺陷:问题描述、复现步骤、运行环境;\+建议:使用场景、期望的行为),用通用技术说法描述问题;补齐后会自动重新打开。也可以从 \+[New issue](https://github.com/peach-mitao/peach/issues/new/choose) 重新选择模板提交,或按 \+[参与 Peach](https://github.com/peach-mitao/peach/blob/master/CONTRIBUTING.md#开-issue) 里的命令用 `gh` 提交。++This issue was closed automatically because it does not follow an issue template. Edit it to add the \+template sections (bug: What happened, Steps to reproduce, Environment; feature: Use case, Desired \+behavior) in plain technical language, and it will reopen. You can also pick a template from \+[New issue](https://github.com/peach-mitao/peach/issues/new/choose), or submit with `gh` as shown in \+[CONTRIBUTING](https://github.com/peach-mitao/peach/blob/master/CONTRIBUTING.md#开-issue).+"""++Template = tuple[str, list[tuple[str, ...]]]+++def load_templates(directory: Path = TEMPLATES) -> list[Template]:+ """每个模板的 Issue Type 与章节名;标题里的中英文用「/」分开,括号里的「可选」不参与匹配。"""+ templates = []+ for path in sorted(directory.glob("*.md")):+ text = path.read_text(encoding="utf-8")+ kind = TYPE_LINE.search(text.split("---", 2)[1] if text.startswith("---") else "")+ sections = [tuple(OPTIONAL.sub("", part).strip().casefold()+ for part in title.split("/") if OPTIONAL.sub("", part).strip())+ for title in HEADING.findall(text)]+ if kind and sections:+ templates.append((kind.group(1), sections))+ return templates+++def matched_type(body: str, templates: list[Template] | None = None) -> str | None:+ """正文命中某个模板的至少两个章节时返回该模板的 Issue Type;只有一个章节的模板命中一个即可。"""+ titles = [title.casefold() for title in HEADING.findall(body or "")]+ for kind, sections in load_templates() if templates is None else templates:+ hits = sum(any(name in title for title in titles for name in names) for names in sections)+ if hits >= min(2, len(sections)):+ return kind+ return None+++def internal_terms(body: str) -> list[str]:+ return [term for term in INTERNAL_TERMS if term in (body or "")]+++def verdict(payload: dict, templates: list[Template] | None = None) -> str:+ issue = payload.get("issue") or {}+ if issue.get("pull_request") or (issue.get("user") or {}).get("type") == "Bot" \+ or issue.get("author_association") in MAINTAINERS:+ return "keep"+ body = issue.get("body") or ""+ action = payload.get("action")+ labels = {label.get("name") for label in issue.get("labels") or []}+ kind = matched_type(body, templates)+ if action == "edited" and issue.get("state") == "closed" and LABEL in labels:+ return f"reopen {kind}" if kind else "keep"+ if action not in {"opened", "edited"} or issue.get("state") == "closed" or issue.get("type"):+ return "keep"+ if kind:+ return f"type {kind}"+ return "close" if action == "opened" and internal_terms(body) else "keep"+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ group = parser.add_mutually_exclusive_group(required=True)+ group.add_argument("--event", type=Path, help="GitHub issues 事件载荷文件")+ group.add_argument("--notice", action="store_true", help="输出关闭时的说明")+ args = parser.parse_args(argv)+ if hasattr(sys.stdout, "reconfigure"):+ sys.stdout.reconfigure(encoding="utf-8")+ if args.notice:+ sys.stdout.write(NOTICE)+ return 0+ print(verdict(json.loads(args.event.read_text(encoding="utf-8"))))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex b9cb5aae8..f87c9796f 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -112,7 +112,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_seed_pack.py", "test_seed_followup.py", "test_seed_corrections.py"),"tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_server.py", "test_diagnostics.py", "test_error_reporting.py", "test_remote_reporting.py", "test_reporting_*.py", "test_library_sharing.py", "test_library_diagnostics.py", "test_script_policy.py","test_scan.py", "test_record_rehome.py", "test_wants.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_clouddrive_proxy.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py",- "test_agent_worktree.py", "test_check_public_text.py", "test_star_history.py", "test_test_evidence.py", "test_test_history.py", "test_test_environment.py", "test_dependency_policy.py",+ "test_agent_worktree.py", "test_check_public_text.py", "test_issue_intake.py", "test_star_history.py", "test_test_evidence.py", "test_test_history.py", "test_test_environment.py", "test_dependency_policy.py","test_version_bump.py", "test_changelog.py", "test_release_due.py", "test_release_candidate.py", "test_media_build_cache.py", "test_runner_launcher.py","test_restart_windows_tray.py", "test_deploy_windows_tray.py", "test_runtime_prepare.py","test_buildinfo.py", "test_versioning.py", "test_macos_standalone.py",@@ -567,7 +567,7 @@ def special_scopes(path: str, kind: str) -> tuple[str, ...] | None:if path.startswith(".github/workflows/"):return ("tooling",) if path in {".github/workflows/project-board.yml", ".github/workflows/docker.yml",- ".github/workflows/star-history.yml",+ ".github/workflows/star-history.yml", ".github/workflows/issue-intake.yml",} else ("full",)if path.rsplit("/", 1)[-1] == "conftest.py" or any(path.startswith(p) for p in FULL_ONLY_PREFIXES):return ("full",)diff --git a/tests/test_issue_intake.py b/tests/test_issue_intake.pynew file mode 100644index 000000000..a864b4f50--- /dev/null+++ b/tests/test_issue_intake.py@@ -0,0 +1,79 @@+"""外部 issue 模板检查的判定;GitHub 写操作在工作流里,这里只验证脚本给出的结论。"""+from __future__ import annotations++import io+import json+import sys+import tempfile+import unittest+from contextlib import redirect_stdout+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "scripts"))+import issue_intake # noqa: E402++JARGON_BODY = "## 目标\n\n导入资料,不做真实账本写入。\n\n## 授权边界\n\n测试使用合成样本。\n"+FEATURE_BODY = "## 使用场景 / Use case\n\n想按女优查看全部作品。\n\n## 期望的行为 / Desired behavior\n\n列出作品。\n"+BUG_BODY = "### 问题描述\n\n闪退\n\n### Environment\n\nWindows 11\n"+++def event(action="opened", body=JARGON_BODY, **issue):+ return {"action": action, "issue": {"body": body, "author_association": "NONE",+ "user": {"type": "User"}, "type": None, "state": "open",+ "labels": [], **issue}}+++class IssueIntakeTests(unittest.TestCase):+ def test_templates_supply_issue_type_and_bilingual_section_names(self):+ templates = dict(issue_intake.load_templates())+ self.assertIn(("问题描述", "what happened"), templates["Bug"])+ self.assertIn(("使用场景", "use case"), templates["Feature"])+ self.assertIn(("补充", "additional context"), templates["Feature"])++ def test_command_line_issue_that_follows_a_template_gets_its_type(self):+ self.assertEqual(issue_intake.verdict(event(body=FEATURE_BODY + "\n不写入账本。\n")), "type Feature")+ self.assertEqual(issue_intake.verdict(event(body=BUG_BODY)), "type Bug")+ self.assertEqual(issue_intake.verdict(event("edited", BUG_BODY)), "type Bug")++ def test_untyped_issue_without_sections_in_rule_jargon_is_closed(self):+ self.assertEqual(issue_intake.verdict(event()), "close")+ self.assertEqual(issue_intake.verdict(event("edited")), "keep")++ def test_web_form_issues_and_plain_free_text_are_left_alone(self):+ for payload in (event(type={"name": "Feature"}),+ event(body=FEATURE_BODY, type={"name": "Feature"}),+ event(body="希望垃圾文件可以批量删除")):+ with self.subTest(body=payload["issue"]["body"][:12]):+ self.assertEqual(issue_intake.verdict(payload), "keep")++ def test_maintainers_bots_and_pull_requests_are_exempt(self):+ for issue in ({"author_association": "MEMBER"}, {"author_association": "OWNER"},+ {"author_association": "COLLABORATOR"}, {"user": {"type": "Bot"}},+ {"pull_request": {"url": "x"}}):+ with self.subTest(issue=issue):+ self.assertEqual(issue_intake.verdict(event(**issue)), "keep")++ def test_closed_issue_reopens_with_its_type_once_the_sections_are_filled_in(self):+ closed = {"state": "closed", "labels": [{"name": issue_intake.LABEL}]}+ self.assertEqual(issue_intake.verdict(event("edited", FEATURE_BODY, **closed)), "reopen Feature")+ self.assertEqual(issue_intake.verdict(event("edited", JARGON_BODY, **closed)), "keep")+ self.assertEqual(issue_intake.verdict(event("edited", FEATURE_BODY, state="closed")), "keep")++ def test_cli_reads_the_event_file_and_prints_the_notice(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "event.json"+ path.write_text(json.dumps(event(), ensure_ascii=False), encoding="utf-8")+ out = io.StringIO()+ with redirect_stdout(out):+ self.assertEqual(issue_intake.main(["--event", str(path)]), 0)+ self.assertEqual(out.getvalue().strip(), "close")+ out = io.StringIO()+ with redirect_stdout(out):+ issue_intake.main(["--notice"])+ self.assertIn("issues/new/choose", out.getvalue())+ self.assertIn("This issue was closed automatically", out.getvalue())+++if __name__ == "__main__":+ unittest.main()