Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

ci: streamline issue forms and release version choices

myhlolib00fbd4b0acb
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index d684d059..6e21fd07 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -1,181 +1,121 @@
-name: 🐛 Bug Report
-description: Create a bug report for MinerU | MinerU 的 Bug 反馈
+name: 🐛 Bug report (English)
+description: Report installation, runtime, or parsing problems
labels: bug
-# 不设置默认标题,让反馈者直接描述具体问题。
body:
- type: markdown
attributes:
value: |
- Thank you for submitting a MinerU 🐛 Bug Report! | 感谢您提交 MinerU 🐛 Bug 反馈!
+ [Documentation](https://opendatalab.github.io/MinerU/) · [Discussions](https://github.com/opendatalab/MinerU/discussions) · [AI assistant (optional)](https://deepwiki.com/opendatalab/MinerU)
- type: checkboxes
+ id: precheck
attributes:
- label: 🔎 Search before asking | 提交之前请先搜索
- description: >
- Please search the MinerU [README](https://github.com/opendatalab/MinerU),
- [Issues](https://github.com/opendatalab/MinerU/issues) and
- [Discussions](https://github.com/opendatalab/MinerU/discussions) for similar reports.
- 请先搜索 README、Issues 和 Discussions,确认是否已有类似反馈。
+ label: Before submitting
options:
- - label: I have searched the MinerU [README](https://github.com/opendatalab/MinerU) for similar reports. | 我已搜索 README。
+ - label: I searched existing [Issues](https://github.com/opendatalab/MinerU/issues) and [Discussions](https://github.com/opendatalab/MinerU/discussions) and found no matching report.
required: true
- - label: I have searched the MinerU [Issues](https://github.com/opendatalab/MinerU/issues) for similar reports. | 我已搜索 Issues。
- required: true
- - label: I have searched the MinerU [Discussions](https://github.com/opendatalab/MinerU/discussions) for similar reports. | 我已搜索 Discussions。
- required: true
-
- - type: checkboxes
- attributes:
- label: 🤖 Online AI assistant (optional) | 在线 AI 助手咨询(可选)
- description: >
- You may consult the [online AI assistant](https://deepwiki.com/opendatalab/MinerU) before reporting.
- 提交前也可以咨询在线 AI 助手,此项不影响提交。
- options:
- - label: I consulted the online AI assistant but could not find a solution. | 我已咨询在线 AI 助手,但未找到解决方案。
- required: false
- type: textarea
id: description
attributes:
- label: Description of the bug | 错误描述
- description: |
- Describe the expected and actual behavior. Include relevant logs, full tracebacks, or screenshots.
- 请说明预期结果与实际结果,并提供相关日志、完整报错堆栈或截图。
+ label: What went wrong?
+ description: Describe the expected and actual behavior, with relevant errors or screenshots.
+ placeholder: |
+ Expected:
+ Actual:
validations:
required: true
+ - type: markdown
+ attributes:
+ value: |
+ For parsing problems, attach the original document and identify the affected pages or regions.
+ A minimal anonymized sample is fine if it still reproduces the problem.
+ For installation/build problems, provide the commands and complete output; no document is needed.
+
- type: textarea
id: reproduce
attributes:
- label: How to reproduce the bug | 如何复现
- description: |
- For parsing or runtime problems: | 对于解析结果异常或运行问题:
- * Provide the original sample document (PDF, image, Office, EPUB, HTML, or another supported format).
- * 请提供原始样例文件,支持 PDF、图片、Office、EPUB、HTML 等格式。
- * Include complete commands or code, relevant configuration, input page ranges, and problematic pages or regions.
- * 请提供完整命令或代码、相关配置、输入页范围,以及出现问题的页码或区域。
- * If the document is large or confidential, provide a minimal anonymized sample in the original format that still reproduces the issue.
- * 文件过大或涉密时,请提供原格式的最小脱敏样例,并确认该样例仍能复现问题。
-
- For installation or build problems: | 对于安装或构建问题:
- * Include the exact installation/build commands and their complete output; a document sample is not needed.
- * 请提供确切的安装或构建命令及其完整输出,无需提供文档样例。
+ label: How to reproduce
+ description: Include commands or code, relevant configuration (including OCR mode if known), and reproduction steps.
validations:
required: true
- type: dropdown
id: usage_entry
attributes:
- label: Usage entry | 使用入口
+ label: Usage entry
options:
- mineru CLI
- mineru-kit CLI
- Python SDK
- API / Router
- WebUI
- - Installation / build | 安装或构建
- - Other / unknown | 其他或不清楚
+ - Installation / build
+ - Other / unknown
validations:
required: true
- type: dropdown
id: os_mode
attributes:
- label: Operating system | 操作系统类型
+ label: Operating system
options:
- Windows
- Linux
- macOS
- - Other / unknown | 其他或不清楚
- validations:
- required: true
-
- - type: textarea
- id: os_name_version
- attributes:
- label: Operating system version | 操作系统版本
- description: |
- Include the distribution and version, and indicate Docker/WSL or remote deployment if applicable.
- 请填写系统或发行版名称及版本;使用 Docker、WSL 或远程部署时,请一并说明。
- Examples | 示例:Ubuntu 24.04, macOS 15, Windows 11 / WSL Ubuntu 24.04.
+ - Other / unknown
validations:
required: true
- type: dropdown
- id: python_version
- attributes:
- label: Python version | Python 版本
- description: Python >=3.11,<3.15; see python --version. | 支持 Python >=3.11,<3.15,可通过 python --version 查看。
- options:
- - "3.14"
- - "3.13"
- - "3.12"
- - "3.11"
- - Other / unknown | 其他或不清楚
- validations:
- required: true
-
- - type: textarea
id: software_version
attributes:
- label: MinerU version | MinerU 版本
- # BEGIN MINERU_LATEST_STABLE_VERSION
- description: |
- Latest stable release: 4.1.1 | 最新正式版本:4.1.1
- Paste the output of mineru --version from the environment with the issue, including old or development versions.
- 请粘贴出现问题的环境中 mineru --version 的输出,旧版和开发版也请填写实际版本。
- If installation failed, state the version you attempted to install and that the command is unavailable.
- 如果安装失败,请说明尝试安装的版本以及该命令不可用的情况。
- # END MINERU_LATEST_STABLE_VERSION
- placeholder: |
- MinerU version: <your installed version / 实际安装版本>
- Python version: <your Python version / 实际 Python 版本>
+ label: MinerU version
+ description: Select your actual version, or the target version if installation failed.
+ # BEGIN MINERU_RECENT_RELEASES
+ options:
+ - "4.1.1"
+ - "4.1.0"
+ - "4.0.12"
+ - "4.0.11"
+ - "4.0.10"
+ - Other / development / unknown
+ default: 5
+ # END MINERU_RECENT_RELEASES
validations:
required: true
- type: dropdown
id: tier
attributes:
- label: Parsing tier | 解析档位
- description: Include --tier or the API/SDK tier value. | 请填写 --tier 或 API/SDK 的 tier 值。
+ label: Parsing tier (optional)
options:
- flash
- basic
- standard
- advanced
- - Default selection | 未显式指定
- - Not applicable / unknown | 不适用或不清楚
- validations:
- required: true
+ - Default selection
+ - Not applicable / unknown
- - type: dropdown
- id: parse_mode
+ - type: markdown
attributes:
- label: OCR / parsing mode (optional) | OCR / 解析模式(可选)
- description: Include --ocr-mode or the API/SDK parsing mode if known. | 如已知,请填写 --ocr-mode 或 API/SDK 的解析模式。
- options:
- - auto
- - txt
- - ocr
- - Not applicable / unknown | 不适用或不清楚
+ value: |
+ ### Environment diagnostics
+ Run this command where MinerU actually runs, including inside Docker/WSL or on the server:
+ ```shell
+ mineru-kit hardware info
+ ```
+ If installation failed, the command is unavailable, or you cannot access the server, explain why and provide known system, Python, device, backend, and deployment details.
+ Include the exact MinerU version here if you selected “Other / development / unknown”.
- type: textarea
id: device_mode
attributes:
- label: Hardware diagnostics | 硬件与运行环境诊断
- description: |
- Run `mineru-kit hardware info` in the environment where the issue occurs and paste the complete text output below.
- 请在出现问题的环境中运行 `mineru-kit hardware info`,并在下方粘贴完整文本输出。
- For Docker, WSL, or remote deployments, run the command where MinerU actually runs.
- 使用 Docker、WSL 或远程部署时,请在实际运行 MinerU 的环境中执行该命令。
- If installation failed, your version does not support the command, or you cannot access the server, explain why.
- 如果安装失败、旧版本不支持该命令或无法访问服务端,请说明原因。
- Include any available error output and known environment details (OS, Python/MinerU versions, device, and backend).
- 同时提供可获得的错误输出及已知环境信息(操作系统、Python/MinerU 版本、设备和推理后端)。
- placeholder: |
- Paste the complete output of mineru-kit hardware info here.
- 请在此粘贴 mineru-kit hardware info 的完整输出。
+ label: Diagnostic output
+ description: Paste the complete text output, or explain why it is unavailable and provide known environment details.
+ placeholder: Output of mineru-kit hardware info, or the reason it is unavailable.
render: text
validations:
required: true
diff --git a/.github/ISSUE_TEMPLATE/bug_report_zh.yml b/.github/ISSUE_TEMPLATE/bug_report_zh.yml
new file mode 100644
index 00000000..158f6776
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report_zh.yml
@@ -0,0 +1,120 @@
+name: 🐛 Bug 反馈(中文)
+description: 反馈安装、运行或解析结果问题
+labels: bug
+
+body:
+ - type: markdown
+ attributes:
+ value: |
+ [使用文档](https://opendatalab.github.io/MinerU/zh/) · [交流讨论](https://github.com/opendatalab/MinerU/discussions) · [AI 助手(可选)](https://deepwiki.com/opendatalab/MinerU)
+
+ - type: checkboxes
+ id: precheck
+ attributes:
+ label: 提交前确认
+ options:
+ - label: 我已搜索现有 [Issues](https://github.com/opendatalab/MinerU/issues) 和 [Discussions](https://github.com/opendatalab/MinerU/discussions),未找到相同问题。
+ required: true
+
+ - type: textarea
+ id: description
+ attributes:
+ label: 问题描述
+ description: 请说明预期结果与实际结果,并附上相关报错或截图。
+ placeholder: |
+ 预期结果:
+ 实际结果:
+ validations:
+ required: true
+
+ - type: markdown
+ attributes:
+ value: |
+ 解析问题请附原始文件,并注明问题页码或区域;也可提供仍能复现问题的最小脱敏样例。
+ 安装或构建问题只需提供完整命令和输出,无需文档样例。
+
+ - type: textarea
+ id: reproduce
+ attributes:
+ label: 如何复现
+ description: 请提供命令或代码、相关配置(如已知请注明 OCR 模式)和复现步骤。
+ validations:
+ required: true
+
+ - type: dropdown
+ id: usage_entry
+ attributes:
+ label: 使用入口
+ options:
+ - mineru CLI
+ - mineru-kit CLI
+ - Python SDK
+ - API / Router
+ - WebUI
+ - 安装或构建
+ - 其他或不清楚
+ validations:
+ required: true
+
+ - type: dropdown
+ id: os_mode
+ attributes:
+ label: 操作系统
+ options:
+ - Windows
+ - Linux
+ - macOS
+ - 其他或不清楚
+ validations:
+ required: true
+
+ - type: dropdown
+ id: software_version
+ attributes:
+ label: MinerU 版本
+ description: 请选择实际版本,安装失败时选择目标版本;其他版本请在环境诊断中说明。
+ # BEGIN MINERU_RECENT_RELEASES
+ options:
+ - "4.1.1"
+ - "4.1.0"
+ - "4.0.12"
+ - "4.0.11"
+ - "4.0.10"
+ - 其他 / 开发版 / 不清楚
+ default: 5
+ # END MINERU_RECENT_RELEASES
+ validations:
+ required: true
+
+ - type: dropdown
+ id: tier
+ attributes:
+ label: 解析档位(可选)
+ options:
+ - flash
+ - basic
+ - standard
+ - advanced
+ - 未显式指定
+ - 不适用或不清楚
+
+ - type: markdown
+ attributes:
+ value: |
+ ### 环境诊断
+ 请在 MinerU 实际运行的环境中执行;Docker、WSL 或远程部署应在容器、子系统或服务端执行:
+ ```shell
+ mineru-kit hardware info
+ ```
+ 若安装失败、命令不可用或无法访问服务端,请说明原因,并提供已知的系统、Python、设备、推理后端和部署方式。
+ 版本选择“其他 / 开发版 / 不清楚”时,请在此补充具体版本。
+
+ - type: textarea
+ id: device_mode
+ attributes:
+ label: 诊断输出
+ description: 请粘贴完整文本输出,或说明无法执行的原因并补充已知环境信息。
+ placeholder: mineru-kit hardware info 的完整输出,或无法执行的原因。
+ render: text
+ validations:
+ required: true
diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml
index 79dbef47..4a2df0de 100644
--- a/.github/workflows/cli.yml
+++ b/.github/workflows/cli.yml
@@ -26,6 +26,7 @@ jobs:
timeout-minutes: 5
outputs:
code: ${{ steps.changes.outputs.code }}
+ issue_templates: ${{ steps.changes.outputs.issue_templates }}
steps:
- uses: actions/checkout@v6
with:
@@ -40,7 +41,7 @@ jobs:
lint:
needs: changes
- if: needs.changes.outputs.code == 'true'
+ if: needs.changes.outputs.code == 'true' || needs.changes.outputs.issue_templates == 'true'
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
@@ -55,14 +56,17 @@ jobs:
- name: Install lightweight check tools
run: |
uv venv
- uv pip install ruff==0.14.2 pytest packaging
- - name: Check Python and CI helpers
+ uv pip install ruff==0.14.2 pytest packaging 'PyYAML>=6,<7'
+ - name: Check product Python
+ if: needs.changes.outputs.code == 'true'
run: |
uv run --no-project --no-sync python -m compileall -q mineru scripts tests
# 存量注解问题分批治理;全仓先阻止语法错误及未定义名称。
uv run --no-project --no-sync ruff check --select E9,F63,F7,F82 mineru scripts tests
- uv run --no-project --no-sync ruff check scripts/ci tests/ci
- uv run --no-project --no-sync ruff format --check scripts/ci tests/ci
+ - name: Check CI helpers and issue forms
+ run: |
+ uv run --no-project --no-sync ruff check scripts/ci tests/ci scripts/sync_issue_template_version.py
+ uv run --no-project --no-sync ruff format --check scripts/ci tests/ci scripts/sync_issue_template_version.py
uv run --no-project --no-sync python -m pytest -o addopts='' --confcutdir=tests/ci tests/ci
cli-test:
@@ -180,13 +184,18 @@ jobs:
env:
CHANGES_RESULT: ${{ needs.changes.result }}
CODE_CHANGED: ${{ needs.changes.outputs.code }}
+ ISSUE_TEMPLATES_CHANGED: ${{ needs.changes.outputs.issue_templates }}
LINT_RESULT: ${{ needs.lint.result }}
TEST_RESULT: ${{ needs.cli-test.result }}
TORCH_RESULT: ${{ needs.torch-test.result }}
run: |
test "$CHANGES_RESULT" = success
- if [[ "$CODE_CHANGED" == true ]]; then
+ if [[ "$CODE_CHANGED" == true || "$ISSUE_TEMPLATES_CHANGED" == true ]]; then
test "$LINT_RESULT" = success
+ else
+ test "$ISSUE_TEMPLATES_CHANGED" = false
+ fi
+ if [[ "$CODE_CHANGED" == true ]]; then
test "$TEST_RESULT" = success
test "$TORCH_RESULT" = success
else
diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml
index a70631d3..b44fe990 100644
--- a/.github/workflows/python-package.yml
+++ b/.github/workflows/python-package.yml
@@ -195,6 +195,8 @@ jobs:
shell: bash
env:
RELEASE_WHEEL_DIR: ${{ runner.temp }}/mineru-issue-template-dist
+ RELEASE_HISTORY: ${{ runner.temp }}/mineru-release-history.json
+ GH_TOKEN: ${{ github.token }}
run: |
git config --local user.name "github-actions[bot]"
git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
@@ -202,14 +204,15 @@ jobs:
# 此 job 的独立 checkout 每次基于最新分支重新生成,避免覆盖并发提交。
git fetch origin "$RELEASE_BRANCH"
git reset --hard FETCH_HEAD
+ gh api --paginate --slurp "repos/$GITHUB_REPOSITORY/releases?per_page=100" > "$RELEASE_HISTORY"
uv run --no-project --python 3.12 scripts/sync_issue_template_version.py \
- --wheel "$RELEASE_WHEEL_DIR" --tag "$RELEASE_TAG"
- git add -- .github/ISSUE_TEMPLATE/bug_report.yml
- if git diff --cached --quiet -- .github/ISSUE_TEMPLATE/bug_report.yml; then
- echo "Issue template already reflects the latest stable release."
+ --wheel "$RELEASE_WHEEL_DIR" --tag "$RELEASE_TAG" --releases-json "$RELEASE_HISTORY"
+ git add -- .github/ISSUE_TEMPLATE/bug_report.yml .github/ISSUE_TEMPLATE/bug_report_zh.yml
+ if git diff --cached --quiet -- .github/ISSUE_TEMPLATE/bug_report.yml .github/ISSUE_TEMPLATE/bug_report_zh.yml; then
+ echo "Issue templates already reflect the recent stable releases."
exit 0
fi
- git commit -m "chore: sync latest stable release in issue template"
+ git commit -m "chore: sync recent releases in issue templates"
if git push origin "HEAD:$RELEASE_BRANCH"; then
exit 0
fi
diff --git a/scripts/ci/changes.py b/scripts/ci/changes.py
index 6143f2de..1226d4c7 100644
--- a/scripts/ci/changes.py
+++ b/scripts/ci/changes.py
@@ -11,15 +11,24 @@ from typing import Any
def classify_paths(paths: list[str]) -> dict[str, bool]:
- """文档变更只构建文档,CI 公共脚本变更同时验证两个工作流。"""
+ """模板及同步脚本只做轻量校验;混合产品代码和工作流变更继续完整验证。"""
+ issue_paths = {
+ path
+ for path in paths
+ if path.startswith(".github/ISSUE_TEMPLATE/")
+ or path in {"scripts/sync_issue_template_version.py", "tests/ci/test_issue_template_release_sync.py"}
+ }
docs = any(
path.startswith("docs/")
or path.startswith("README")
or path in {"mkdocs.yml", ".github/workflows/mkdocs.yml", "scripts/ci/changes.py"}
for path in paths
)
- code = any(not (path.startswith(("docs/", "cmds/")) or path.endswith(".md") or path == "mkdocs.yml") for path in paths)
- return {"code": code, "docs": docs}
+ code = any(
+ path not in issue_paths and not (path.startswith(("docs/", "cmds/")) or path.endswith(".md") or path == "mkdocs.yml")
+ for path in paths
+ )
+ return {"code": code, "docs": docs, "issue_templates": bool(issue_paths)}
def changed_paths(event_name: str, event: dict[str, Any], head: str) -> list[str] | None:
@@ -49,7 +58,7 @@ def main() -> None:
"""把变化分类写入 Actions 输出,供始终存在的汇总检查决定跳过哪些任务。"""
event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8"))
paths = changed_paths(os.environ["GITHUB_EVENT_NAME"], event, os.environ["GITHUB_SHA"])
- changes = {"code": True, "docs": True} if paths is None else classify_paths(paths)
+ changes = {"code": True, "docs": True, "issue_templates": True} if paths is None else classify_paths(paths)
with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as output:
for name, changed in changes.items():
output.write(f"{name}={str(changed).lower()}\n")
diff --git a/scripts/sync_issue_template_version.py b/scripts/sync_issue_template_version.py
index 50c6b137..99e17440 100644
--- a/scripts/sync_issue_template_version.py
+++ b/scripts/sync_issue_template_version.py
@@ -3,11 +3,12 @@
# requires-python = ">=3.11"
# dependencies = ["packaging", "PyYAML>=6,<7"]
# ///
-"""依据已发布 wheel 的元数据更新 issue 表单中的最新正式版本提示。"""
+"""依据已发布 wheel 和 GitHub Release 列表同步中英文 issue 表单的最近正式版本。"""
from __future__ import annotations
import argparse
+import json
import re
import sys
from collections.abc import Sequence
@@ -19,19 +20,23 @@ from zipfile import BadZipFile, ZipFile
import yaml
from packaging.utils import canonicalize_name
from packaging.version import Version
+from yaml.nodes import MappingNode, Node, SequenceNode
-__all__ = ["main", "read_wheel_version", "sync_template_version", "update_template_version"]
+__all__ = ["main", "read_release_versions", "read_wheel_version", "sync_template_versions"]
-BEGIN_MARKER = "# BEGIN MINERU_LATEST_STABLE_VERSION"
-END_MARKER = "# END MINERU_LATEST_STABLE_VERSION"
+DEFAULT_TEMPLATES = (
+ Path(".github/ISSUE_TEMPLATE/bug_report.yml"),
+ Path(".github/ISSUE_TEMPLATE/bug_report_zh.yml"),
+)
+FALLBACK_OPTIONS = ("Other / development / unknown", "其他 / 开发版 / 不清楚")
+BEGIN_MARKER = "# BEGIN MINERU_RECENT_RELEASES"
+END_MARKER = "# END MINERU_RECENT_RELEASES"
REGION_PATTERN = re.compile(
rf"^ {{6}}{re.escape(BEGIN_MARKER)}\r?\n(?P<region>.*?)^ {{6}}{re.escape(END_MARKER)}\r?$",
re.MULTILINE | re.DOTALL,
)
-VERSION_LINE_PATTERN = re.compile(
- r"^ {8}Latest stable release: (?P<version>\S+) \| 最新正式版本:(?P=version)\r?$", re.MULTILINE
-)
TAG_PATTERN = re.compile(r"mineru-(.+)-released")
+MAX_VERSIONS = 5
def read_wheel_version(wheel_path: Path) -> Version:
@@ -57,69 +62,158 @@ def read_wheel_version(wheel_path: Path) -> Version:
return Version(str(versions[0]))
-def update_template_version(source: str, version: Version) -> str:
- """校验版本提示的归属与标记,只替换该区块的版本号并阻止提示回退。"""
+def read_release_versions(path: Path) -> tuple[Version, ...]:
+ """校验离线 Release 列表,按语义版本降序去重,排除草稿、预发布和无关标签。"""
+ releases = json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(releases, list):
+ raise ValueError("Release history must be a JSON array.")
+ # gh --paginate --slurp 返回分页数组;单页 REST 响应也可直接用于本地验证。
+ if all(isinstance(page, list) for page in releases):
+ releases = [release for page in releases for release in page]
+ versions: set[Version] = set()
+ for release in releases:
+ if (
+ not isinstance(release, dict)
+ or type(release.get("draft")) is not bool
+ or type(release.get("prerelease")) is not bool
+ or not isinstance(release.get("tag_name"), str)
+ ):
+ raise ValueError("Invalid GitHub Release record.")
+ if release["draft"] or release["prerelease"]:
+ continue
+ if not isinstance(release.get("published_at"), str) or not release["published_at"]:
+ raise ValueError("A public Release must have a publication timestamp.")
+ tag = TAG_PATTERN.fullmatch(release["tag_name"])
+ if tag is None:
+ continue
+ version = Version(tag[1])
+ if not version.is_prerelease and version.local is None:
+ versions.add(version)
+ if not versions:
+ raise ValueError("Release history contains no published stable MinerU version.")
+ return tuple(sorted(versions, reverse=True))
+
+
+def _mapping_entry(node: Node | None, key: str) -> tuple[Node, Node]:
+ """定位唯一 YAML 键及其源码位置,拒绝重复键或不符合预期的结构。"""
+ if not isinstance(node, MappingNode):
+ raise ValueError(f"Expected a mapping containing {key!r}.")
+ entries = [(name, value) for name, value in node.value if name.value == key]
+ if len(entries) != 1:
+ raise ValueError(f"Expected exactly one {key!r} key.")
+ return entries[0]
+
+
+def _prepare_template(source: str, versions: tuple[Version, ...]) -> tuple[str, tuple[Version, ...]]:
+ """严格绑定版本下拉框的选项区块,并保留区块外文案、兜底语言与原换行符。"""
if source.count(BEGIN_MARKER) != 1 or source.count(END_MARKER) != 1:
- raise ValueError("Template must contain exactly one pair of latest stable version markers.")
+ raise ValueError("Template must contain exactly one pair of recent release markers.")
region = REGION_PATTERN.search(source)
- if region is None:
- raise ValueError("Latest stable version markers must delimit a software_version description block.")
- lines = list(VERSION_LINE_PATTERN.finditer(region["region"]))
- if len(lines) != 1:
- raise ValueError("Latest stable version block must contain exactly one matching bilingual version line.")
+ if region is None or not region["region"].startswith(" options:"):
+ raise ValueError("Recent release markers must surround the options mapping.")
form = yaml.safe_load(source)
if not isinstance(form, dict) or not isinstance(form.get("body"), list):
raise ValueError("Template must be an issue form with a body array.")
- fields = [field for field in form["body"] if isinstance(field, dict) and field.get("id") == "software_version"]
- if len(fields) != 1 or fields[0].get("type") not in ("input", "textarea"):
- raise ValueError("Template must contain exactly one software_version text field.")
- attributes = fields[0].get("attributes")
- description = attributes.get("description") if isinstance(attributes, dict) else None
- if not isinstance(description, str) or lines[0][0].strip() not in description.splitlines():
- raise ValueError("Latest stable version line must belong to software_version.description.")
- current = Version(lines[0]["version"])
- if current.is_prerelease or current.local is not None:
- raise ValueError("The current latest stable version hint must be a public stable version.")
- if version.is_prerelease or version.local is not None or version <= current:
- return source
- updated_region = VERSION_LINE_PATTERN.sub(
- lambda match: f" Latest stable release: {version} | 最新正式版本:{version}"
- + ("\r" if match[0].endswith("\r") else ""),
- region["region"],
- count=1,
- )
- updated = source[: region.start("region")] + updated_region + source[region.end("region") :]
- yaml.safe_load(updated)
- return updated
-
-
-def sync_template_version(wheel_path: Path, template_path: Path, release_tag: str) -> bool:
- """先验证产物版本与发版标签一致,完成全部校验后才写入模板。"""
+ fields = [
+ (index, field)
+ for index, field in enumerate(form["body"])
+ if isinstance(field, dict) and field.get("id") == "software_version"
+ ]
+ if len(fields) != 1 or fields[0][1].get("type") != "dropdown":
+ raise ValueError("Template must contain exactly one software_version dropdown.")
+ index, field = fields[0]
+ attributes = field.get("attributes")
+ validations = field.get("validations")
+ if (
+ not isinstance(attributes, dict)
+ or attributes.get("multiple", False) is not False
+ or not isinstance(validations, dict)
+ or validations.get("required") is not True
+ ):
+ raise ValueError("Version selection must be required and single-select.")
+ options = attributes.get("options")
+ if (
+ not isinstance(options, list)
+ or not 2 <= len(options) <= MAX_VERSIONS + 1
+ or not all(isinstance(option, str) for option in options)
+ or options[-1] not in FALLBACK_OPTIONS
+ ):
+ raise ValueError("Expected up to five version strings followed by the localized fallback option.")
+ # GitHub 必填单选框会自动选择首项,显式选择兜底项以免误报最新版。
+ if type(attributes.get("default")) is not int or attributes["default"] != len(options) - 1:
+ raise ValueError("Version selection must default to the fallback option, never a release.")
+ current = tuple(Version(option) for option in options[:-1])
+ if any(version.is_prerelease or version.local is not None for version in current):
+ raise ValueError("Version choices must be public stable releases.")
+ if tuple(sorted(set(current), reverse=True)) != current:
+ raise ValueError("Version choices must be unique and sorted newest first.")
+ body_node = _mapping_entry(yaml.compose(source), "body")[1]
+ if not isinstance(body_node, SequenceNode):
+ raise ValueError("Issue form body must be a sequence.")
+ attributes_node = _mapping_entry(body_node.value[index], "attributes")[1]
+ options_key, _ = _mapping_entry(attributes_node, "options")
+ default_key, _ = _mapping_entry(attributes_node, "default")
+ if options_key.start_mark.index != region.start("region") + 6:
+ raise ValueError("Recent release markers must belong to software_version.attributes.options.")
+ if not region.start("region") <= default_key.start_mark.index < region.end("region"):
+ raise ValueError("The fallback default must belong to the marked version choices.")
+ if yaml.safe_load(region["region"]) != {"options": options, "default": len(options) - 1}:
+ raise ValueError("Recent release markers must contain only version options and their fallback default.")
+ if current == versions:
+ return source, current
+ newline = "\r\n" if "\r\n" in region[0] else "\n"
+ values = [*(str(version) for version in versions), options[-1]]
+ replacement = " options:" + newline
+ replacement += "".join(f" - {json.dumps(value, ensure_ascii=False)}{newline}" for value in values)
+ replacement += f" default: {len(versions)}{newline}"
+ return source[: region.start("region")] + replacement + source[region.end("region") :], current
+
+
+def sync_template_versions(wheel_path: Path, template_paths: Sequence[Path], release_tag: str, releases_path: Path) -> bool:
+ """验证所有输入后统一更新两种语言;陈旧列表不得回退任何模板的版本选择。"""
version = read_wheel_version(wheel_path)
tag = TAG_PATTERN.fullmatch(release_tag)
- if tag is None:
- raise ValueError("Expected release tag mineru-<version>-released.")
- if Version(tag[1]) != version:
- raise ValueError(f"Wheel version {version} does not match release tag {release_tag!r}.")
- source = template_path.read_bytes().decode("utf-8")
- updated = update_template_version(source, version)
- if updated == source:
- print(f"No template update needed for {version} (unchanged, older, or non-stable version).")
+ if tag is None or Version(tag[1]) != version:
+ raise ValueError("Release tag must be mineru-<wheel version>-released.")
+ released = read_release_versions(releases_path)
+ if version.is_prerelease or version.local is not None:
+ print(f"No template update needed for non-stable version {version}.")
+ return False
+ if version not in released:
+ raise ValueError("Published wheel version is missing from the Release history.")
+ recent = released[:MAX_VERSIONS]
+ paths = list(template_paths)
+ if not paths or len({path.resolve() for path in paths}) != len(paths):
+ raise ValueError("Provide distinct template paths.")
+ updates: list[tuple[Path, str, str, tuple[Version, ...]]] = []
+ for path in paths:
+ source = path.read_bytes().decode("utf-8")
+ updated, current = _prepare_template(source, recent)
+ updates.append((path, source, updated, current))
+ if any(recent < current for _, _, _, current in updates):
+ print("No template update: Release history is older than the checked-out choices.")
return False
- template_path.write_bytes(updated.encode("utf-8"))
- print(f"Updated latest stable release hint to {version} in {template_path}.")
- return True
+ changed = False
+ for path, source, updated, _ in updates:
+ if updated != source:
+ path.write_bytes(updated.encode("utf-8"))
+ changed = True
+ print(f"Updated recent release choices in {path}.")
+ if not changed:
+ print("Recent release choices are already current.")
+ return changed
def main(argv: Sequence[str] | None = None) -> int:
- """解析发版同步参数,并将产物或模板异常转换为明确的失败退出码。"""
+ """解析多模板同步参数,将 Release、产物及模板异常转换为明确的失败退出码。"""
parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--wheel", type=Path, required=True, help="Released wheel file or directory containing one wheel.")
+ parser.add_argument("--wheel", type=Path, required=True, help="Published wheel file or directory.")
parser.add_argument("--tag", required=True, help="Release tag, in the form mineru-<version>-released.")
- parser.add_argument("--template", type=Path, default=Path(".github/ISSUE_TEMPLATE/bug_report.yml"))
+ parser.add_argument("--releases-json", type=Path, required=True, help="GitHub Releases JSON, including slurped pages.")
+ parser.add_argument("--template", type=Path, action="append", help="Repeat to override the default English/Chinese forms.")
args = parser.parse_args(argv)
try:
- sync_template_version(args.wheel, args.template, args.tag)
+ sync_template_versions(args.wheel, args.template or DEFAULT_TEMPLATES, args.tag, args.releases_json)
except (ValueError, OSError, BadZipFile, yaml.YAMLError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
diff --git a/tests/ci/test_checks.py b/tests/ci/test_checks.py
index 394eed89..2edaa743 100644
--- a/tests/ci/test_checks.py
+++ b/tests/ci/test_checks.py
@@ -10,6 +10,7 @@ from pathlib import Path
from zipfile import ZipFile
import pytest
+import yaml
from packaging.version import Version
from scripts.ci.changes import changed_paths, classify_paths
@@ -42,24 +43,32 @@ def repository(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
@pytest.mark.parametrize(
- ("paths", "code", "docs"),
+ ("paths", "code", "docs", "issue_templates"),
[
- (["docs/next/api/tasks.md"], False, True),
- (["docs/requirements.txt"], False, True),
- (["docs/images/example.png"], False, True),
- (["README_zh-CN.md"], False, True),
- (["mkdocs.yml"], False, True),
- (["mineru/parser/base.py"], True, False),
- (["scripts/http_task_example.py"], True, False),
- (["scripts/ci/changes.py"], True, True),
- ([".github/workflows/cli.yml"], True, False),
- (["docs/index.md", "mineru/config.py"], True, True),
- ([], False, False),
+ (["docs/next/api/tasks.md"], False, True, False),
+ (["docs/requirements.txt"], False, True, False),
+ (["docs/images/example.png"], False, True, False),
+ (["README_zh-CN.md"], False, True, False),
+ (["mkdocs.yml"], False, True, False),
+ (["mineru/parser/base.py"], True, False, False),
+ (["scripts/http_task_example.py"], True, False, False),
+ (["scripts/ci/changes.py"], True, True, False),
+ ([".github/workflows/cli.yml"], True, False, False),
+ ([".github/workflows/python-package.yml"], True, False, False),
+ (["docs/index.md", "mineru/config.py"], True, True, False),
+ ([".github/ISSUE_TEMPLATE/bug_report.yml"], False, False, True),
+ ([".github/ISSUE_TEMPLATE/bug_report_zh.yml", ".github/ISSUE_TEMPLATE/config.yml"], False, False, True),
+ (["scripts/sync_issue_template_version.py"], False, False, True),
+ (["tests/ci/test_issue_template_release_sync.py"], False, False, True),
+ ([".github/ISSUE_TEMPLATE/bug_report.yml", "mineru/config.py"], True, False, True),
+ ([".github/ISSUE_TEMPLATE/bug_report.yml", "docs/index.md"], False, True, True),
+ ([".github/ISSUE_TEMPLATE/bug_report.yml", ".github/workflows/cli.yml"], True, False, True),
+ ([], False, False, False),
],
)
-def test_change_classification(paths: list[str], code: bool, docs: bool) -> None:
+def test_change_classification(paths: list[str], code: bool, docs: bool, issue_templates: bool) -> None:
"""真实产品、文档资源和公共分流脚本分别触发所需检查。"""
- assert classify_paths(paths) == {"code": code, "docs": docs}
+ assert classify_paths(paths) == {"code": code, "docs": docs, "issue_templates": issue_templates}
def test_rename_out_of_code_is_not_misclassified_as_docs_only(repository: Path) -> None:
@@ -71,7 +80,7 @@ def test_rename_out_of_code_is_not_misclassified_as_docs_only(repository: Path)
head = git(repository, "rev-parse", "HEAD")
paths = changed_paths("pull_request", {"pull_request": {"base": {"sha": base}}}, head)
assert paths == ["docs/version.md", "mineru/version.py"]
- assert classify_paths(paths) == {"code": True, "docs": True}
+ assert classify_paths(paths) == {"code": True, "docs": True, "issue_templates": False}
@pytest.mark.parametrize("event", [{"before": "0" * 40}, {"ref": "refs/tags/mineru-4.0.12-released"}])
@@ -101,7 +110,7 @@ def test_changes_script_writes_outputs_for_docs_only_push(repository: Path, tmp_
"GITHUB_OUTPUT": str(output),
},
)
- assert output.read_text() == "code=false\ndocs=true\n"
+ assert output.read_text() == "code=false\ndocs=true\nissue_templates=false\n"
@pytest.mark.parametrize("tag", ["mineru-4.0.13-released", "mineru-4.0.11-released", "v4.0.12", "mineru-bad-released"])
@@ -167,3 +176,101 @@ def test_release_cli_records_exact_commit_and_rejects_dirty_source(repository: P
(repository / "mineru/version.py").write_text('__version__ = "4.0.13"\n', encoding="utf-8")
assert subprocess.run(command, capture_output=True).returncode != 0
assert json.loads((repository / "release.json").read_text()) == record
+
+
+ ("event_name", "event"),
+ [
+ ("workflow_dispatch", {}),
+ ("workflow_call", {}),
+ ("push", {"before": "0" * 40, "ref": "refs/heads/new"}),
+ ("push", {"ref": "refs/tags/mineru-4.1.1-released"}),
+ ("push", {"before": "1" * 40, "ref": "refs/heads/main"}),
+ ],
+)
+def test_unknown_differences_and_release_events_enable_all_checks(
+ repository: Path, tmp_path: Path, event_name: str, event: dict[str, str]
+) -> None:
+ """真实 CLI 对首次推送、发布、手动调用和取不到基点的提交保持完整验证。"""
+ payload = tmp_path / "event.json"
+ payload.write_text(json.dumps(event), encoding="utf-8")
+ output = tmp_path / "outputs"
+ result = subprocess.run(
+ [sys.executable, str(ROOT / "scripts/ci/changes.py")],
+ capture_output=True,
+ text=True,
+ check=True,
+ env={
+ **os.environ,
+ "GITHUB_EVENT_NAME": event_name,
+ "GITHUB_EVENT_PATH": str(payload),
+ "GITHUB_SHA": git(repository, "rev-parse", "HEAD"),
+ "GITHUB_OUTPUT": str(output),
+ },
+ )
+ assert json.loads(result.stdout) == {"code": True, "docs": True, "issue_templates": True}
+
+
+def test_real_template_version_push_only_selects_lightweight_checks(repository: Path, tmp_path: Path) -> None:
+ """以真实版本选项提交验证自动发布后的 push 分流,而非仅匹配提交名称或作者。"""
+ template = repository / ".github/ISSUE_TEMPLATE/bug_report.yml"
+ template.parent.mkdir(parents=True)
+ template.write_text('options: ["4.1.0"]\n', encoding="utf-8")
+ git(repository, "add", ".")
+ git(repository, "commit", "-m", "seed form")
+ base = git(repository, "rev-parse", "HEAD")
+ template.write_text('options: ["4.1.1", "4.1.0"]\n', encoding="utf-8")
+ git(repository, "add", ".")
+ git(repository, "commit", "-m", "sync recent releases")
+ paths = changed_paths("push", {"before": base, "ref": "refs/heads/master"}, git(repository, "rev-parse", "HEAD"))
+ assert paths == [".github/ISSUE_TEMPLATE/bug_report.yml"]
+ assert classify_paths(paths) == {"code": False, "docs": False, "issue_templates": True}
+
+
+ ("code", "forms", "lint", "tests", "torch", "success"),
+ [
+ ("false", "true", "success", "skipped", "skipped", True),
+ ("false", "true", "failure", "skipped", "skipped", False),
+ ("false", "true", "cancelled", "skipped", "skipped", False),
+ ("false", "true", "skipped", "skipped", "skipped", False),
+ ("true", "true", "success", "success", "success", True),
+ ("true", "false", "success", "failure", "success", False),
+ ("true", "false", "success", "success", "failure", False),
+ ("false", "false", "skipped", "skipped", "skipped", True),
+ ("false", "", "skipped", "skipped", "skipped", False),
+ ],
+)
+def test_ci_result_requires_lightweight_and_applicable_full_checks(
+ code: str, forms: str, lint: str, tests: str, torch: str, success: bool
+) -> None:
+ """执行真实汇总脚本,模板校验失败或取消也不能被矩阵跳过状态掩盖。"""
+ workflow = yaml.safe_load((ROOT / ".github/workflows/cli.yml").read_text(encoding="utf-8"))
+ script = workflow["jobs"]["ci-result"]["steps"][0]["run"]
+ result = subprocess.run(
+ ["bash", "-e", "-o", "pipefail", "-c", script],
+ capture_output=True,
+ check=False,
+ env={
+ **os.environ,
+ "CHANGES_RESULT": "success",
+ "CODE_CHANGED": code,
+ "ISSUE_TEMPLATES_CHANGED": forms,
+ "LINT_RESULT": lint,
+ "TEST_RESULT": tests,
+ "TORCH_RESULT": torch,
+ },
+ )
+ assert (result.returncode == 0) is success
+
+
+def test_template_checks_have_no_product_dependency_installation() -> None:
+ """轻量入口使用独立测试目录;产品扫描和两个推理测试任务仍受 code 标记约束。"""
+ jobs = yaml.safe_load((ROOT / ".github/workflows/cli.yml").read_text(encoding="utf-8"))["jobs"]
+ assert jobs["lint"]["if"] == "needs.changes.outputs.code == 'true' || needs.changes.outputs.issue_templates == 'true'"
+ assert jobs["cli-test"]["if"] == jobs["torch-test"]["if"] == "needs.changes.outputs.code == 'true'"
+ product = next(step for step in jobs["lint"]["steps"] if step.get("name") == "Check product Python")
+ assert product["if"] == "needs.changes.outputs.code == 'true'"
+ lightweight = "\n".join(step.get("run", "") for step in jobs["lint"]["steps"] if "if" not in step)
+ assert "--confcutdir=tests/ci tests/ci" in lightweight
+ assert "PyYAML" in lightweight and "'.[test]'" not in lightweight and "compileall" not in lightweight
diff --git a/tests/ci/test_issue_template_release_sync.py b/tests/ci/test_issue_template_release_sync.py
new file mode 100644
index 00000000..e0227e3a
--- /dev/null
+++ b/tests/ci/test_issue_template_release_sync.py
@@ -0,0 +1,605 @@
+"""用模拟发行记录、wheel 和本地 Git 仓库验证表单同步,不导入 MinerU 或访问网络。"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+from zipfile import ZipFile
+
+import pytest
+import yaml
+from packaging.version import Version
+
+from scripts.sync_issue_template_version import read_release_versions
+
+ROOT = Path(__file__).resolve().parents[2]
+TEMPLATE = ROOT / ".github" / "ISSUE_TEMPLATE" / "bug_report.yml"
+TEMPLATES = (TEMPLATE, TEMPLATE.with_name("bug_report_zh.yml"))
+SCRIPT = ROOT / "scripts" / "sync_issue_template_version.py"
+WORKFLOW = ROOT / ".github" / "workflows" / "python-package.yml"
+TEMPLATE_RELATIVE = TEMPLATE.relative_to(ROOT)
+BASELINE = ("4.0.12", "4.0.11", "4.0.10", "4.0.9", "4.0.8")
+REGION = re.compile(r"(?<=# BEGIN MINERU_RECENT_RELEASES\n).*?(?= # END MINERU_RECENT_RELEASES)", re.DOTALL)
+
+
+def _baseline_template(template: Path = TEMPLATE) -> str:
+ """保留实际语言和表单结构,用固定起始版本隔离后续正式发版。"""
+ source = template.read_text(encoding="utf-8")
+ form = yaml.safe_load(source)
+ field = next(item for item in form["body"] if item.get("id") == "software_version")
+ fallback = field["attributes"]["options"][-1]
+ options = " options:\n" + "".join(
+ " - " + json.dumps(value, ensure_ascii=False) + "\n" for value in (*BASELINE, fallback)
+ )
+ options += f" default: {len(BASELINE)}\n"
+ updated, count = REGION.subn(options, source)
+ assert count == 1
+ return updated
+
+
+def template_path(tmp_path: Path) -> Path:
+ """复制固定版本的英文表单,所有变更限制在临时目录。"""
+ target = tmp_path / TEMPLATE.name
+ target.write_text(_baseline_template(), encoding="utf-8")
+ return target
+
+
+def _wheel(directory: Path, metadata: str = "Name: mineru\nVersion: 4.0.13\n") -> Path:
+ """构造最小发行产物,只保留脚本读取的包名和版本元数据。"""
+ directory.mkdir(parents=True, exist_ok=True)
+ target = directory / "mineru-test-py3-none-any.whl"
+ with ZipFile(target, "w") as archive:
+ archive.writestr("mineru-test.dist-info/METADATA", metadata)
+ return target
+
+
+def _release(version: str, **changes: object) -> dict[str, object]:
+ """构造与 GitHub Release API 相同的发布身份和状态字段。"""
+ return {
+ "tag_name": f"mineru-{version}-released",
+ "draft": False,
+ "prerelease": False,
+ "published_at": "2026-10-29T00:00:00Z",
+ **changes,
+ }
+
+
+def _history(path: Path, versions: tuple[str, ...] = ("4.0.13", *BASELINE)) -> Path:
+ """保存离线版本历史,测试和工作流替身都不请求真实 GitHub。"""
+ path.write_text(json.dumps([_release(version) for version in versions]), encoding="utf-8")
+ return path
+
+
+def _options(path: Path) -> list[str]:
+ """从完整表单读取实际下拉值,避免只验证版本字符串出现。"""
+ form = yaml.safe_load(path.read_text(encoding="utf-8"))
+ return next(field["attributes"]["options"] for field in form["body"] if field.get("id") == "software_version")
+
+
+def _run_sync(
+ wheel: Path, template: Path | list[Path], tag: str = "mineru-4.0.13-released", history: Path | None = None
+) -> subprocess.CompletedProcess[str]:
+ """执行真实同步 CLI,覆盖参数、版本读取、多模板预校验与错误退出。"""
+ history = history or _history(wheel.parent / "releases.json")
+ command = [sys.executable, str(SCRIPT), "--wheel", str(wheel), "--tag", tag, "--releases-json", str(history)]
+ for path in [template] if isinstance(template, Path) else template:
+ command.extend(("--template", str(path)))
+ return subprocess.run(command, capture_output=True, text=True, timeout=15, check=False)
+
+
+def test_release_history_uses_semantic_order_and_only_public_stable_versions(tmp_path: Path) -> None:
+ """乱序、重复和发布时间均不能改变语义排序,草稿及非正式版本被排除。"""
+ history = tmp_path / "history.json"
+ records = [
+ _release("4.0.9"),
+ _release("4.0.100"),
+ _release("4.0.12"),
+ _release("4.0.12"),
+ _release("9.0.0", draft=True, published_at=None),
+ _release("8.0.0", prerelease=True),
+ _release("7.0.0rc1"),
+ _release("7.0.0.dev1"),
+ _release("7.0.0+local"),
+ _release("unused", tag_name="unrelated-tag"),
+ ]
+ history.write_text(json.dumps(records), encoding="utf-8")
+ assert read_release_versions(history) == tuple(map(Version, ("4.0.100", "4.0.12", "4.0.9")))
+
+
+def test_paginated_release_history_includes_versions_from_every_page(tmp_path: Path) -> None:
+ """使用 gh 分页输出的真实形状,跨页去重并按版本号而非分页位置排序。"""
+ history = tmp_path / "pages.json"
+ history.write_text(json.dumps([[_release("4.0.9")], [_release("4.0.12"), _release("4.0.9")]]), encoding="utf-8")
+ assert read_release_versions(history) == (Version("4.0.12"), Version("4.0.9"))
+
+
+ "payload",
+ [
+ {},
+ [],
+ [None],
+ [{"tag_name": "mineru-4.0.13-released"}],
+ [_release("4.0.13", draft="false")],
+ [_release("4.0.13", published_at=None)],
+ [_release("invalid")],
+ [_release("4.0.13", draft=True)],
+ ],
+)
+def test_invalid_release_history_fails_without_writing(template_path: Path, payload: object) -> None:
+ """空列表、API 错误响应及损坏记录不能修改模板或伪造版本。"""
+ history = template_path.parent / "invalid-history.json"
+ history.write_text(json.dumps(payload), encoding="utf-8")
+ original = template_path.read_bytes()
+ result = _run_sync(_wheel(template_path.parent), template_path, history=history)
+ assert result.returncode == 1 and "error:" in result.stderr
+ assert template_path.read_bytes() == original
+
+
[email protected]("failure", ["invalid-json", "missing-file", "missing-release"])
+def test_unavailable_release_data_fails_without_writing(template_path: Path, failure: str) -> None:
+ """无效 JSON、读取失败或不包含当前发布的历史不能修改模板。"""
+ history = template_path.parent / "history.json"
+ if failure == "invalid-json":
+ history.write_text("{", encoding="utf-8")
+ elif failure == "missing-release":
+ _history(history, BASELINE)
+ original = template_path.read_bytes()
+ assert _run_sync(_wheel(template_path.parent), template_path, history=history).returncode == 1
+ assert template_path.read_bytes() == original
+
+
[email protected]("template", TEMPLATES, ids=["en", "zh"])
[email protected]("newline", ["\n", "\r\n"])
+def test_update_keeps_five_versions_fallback_and_unrelated_text(tmp_path: Path, template: Path, newline: str) -> None:
+ """两种语言均保留兜底、换行和无关文本,重复执行不触碰文件。"""
+ target = tmp_path / template.name
+ source = _baseline_template(template) + "# Unrelated version: 4.0.12\n"
+ target.write_bytes(source.replace("\n", newline).encode("utf-8"))
+ original = target.read_bytes()
+ fallback = _options(target)[-1]
+ wheel = _wheel(tmp_path)
+ result = _run_sync(wheel, target)
+ assert result.returncode == 0, result.stderr
+ assert _options(target) == ["4.0.13", *BASELINE[:4], fallback]
+ before = original.decode("utf-8").split("# BEGIN MINERU_RECENT_RELEASES")
+ after = target.read_bytes().decode("utf-8").split("# BEGIN MINERU_RECENT_RELEASES")
+ assert before[0] == after[0]
+ assert before[1].split("# END MINERU_RECENT_RELEASES")[1] == after[1].split("# END MINERU_RECENT_RELEASES")[1]
+ if newline == "\r\n":
+ assert b"\n" not in target.read_bytes().replace(b"\r\n", b"")
+ modified = target.stat().st_mtime_ns
+ assert _run_sync(wheel, target).returncode == 0
+ assert target.stat().st_mtime_ns == modified
+
+
+def test_default_command_updates_both_forms_from_current_repository(tmp_path: Path) -> None:
+ """不传模板参数时使用真实默认路径,同时更新两种语言。"""
+ original_versions = _options(TEMPLATE)[:-1]
+ latest = Version(original_versions[0])
+ version = f"{latest.major}.{latest.minor}.{latest.micro + 1}"
+ for template in TEMPLATES:
+ target = tmp_path / template.relative_to(ROOT)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(template.read_bytes())
+ history = _history(tmp_path / "history.json", (version, *original_versions))
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(SCRIPT),
+ "--wheel",
+ str(_wheel(tmp_path, f"Name: mineru\nVersion: {version}\n")),
+ "--tag",
+ f"mineru-{version}-released",
+ "--releases-json",
+ str(history),
+ ],
+ cwd=tmp_path,
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=15,
+ )
+ assert result.returncode == 0, result.stderr
+ for template in TEMPLATES:
+ assert _options(tmp_path / template.relative_to(ROOT))[:-1] == [version, *original_versions[:4]]
+
+
+def test_old_release_replay_uses_latest_history_without_rollback(template_path: Path) -> None:
+ """旧发布采用最新历史;陈旧快照则保留现有选择,不能回退任何选项。"""
+ assert _run_sync(_wheel(template_path.parent), template_path).returncode == 0
+ original = template_path.read_bytes()
+ old_wheel = _wheel(template_path.parent, "Name: mineru\nVersion: 4.0.12\n")
+ assert _run_sync(old_wheel, template_path, "mineru-4.0.12-released").returncode == 0
+ assert template_path.read_bytes() == original
+ stale = _history(template_path.parent / "stale.json", BASELINE)
+ assert _run_sync(old_wheel, template_path, "mineru-4.0.12-released", stale).returncode == 0
+ assert template_path.read_bytes() == original
+
+
[email protected]("version", ["5.0.0a1", "5.0.0rc1", "5.0.0.dev1", "4.0.13+local"])
+def test_non_stable_publication_does_not_change_forms(template_path: Path, version: str) -> None:
+ """预发布和本地版本不进入正式版本选择。"""
+ original = template_path.read_bytes()
+ result = _run_sync(
+ _wheel(template_path.parent, f"Name: mineru\nVersion: {version}\n"), template_path, f"mineru-{version}-released"
+ )
+ assert result.returncode == 0, result.stderr
+ assert template_path.read_bytes() == original
+
+
+ ("old", "new"),
+ [
+ ("# END MINERU_RECENT_RELEASES", "# missing marker"),
+ ("# BEGIN MINERU_RECENT_RELEASES", "# BEGIN MINERU_RECENT_RELEASES\n # BEGIN MINERU_RECENT_RELEASES"),
+ (" # END MINERU_RECENT_RELEASES", " # END MINERU_RECENT_RELEASES"),
+ ('"4.0.12"', '"5.0.0rc1"'),
+ ('"4.0.11"', '"4.0.12"'),
+ ("id: software_version", "id: wrong_field"),
+ (" - type: dropdown\n id: software_version", " - type: textarea\n id: software_version"),
+ ("id: device_mode", "id: software_version"),
+ (" label: MinerU version", " label: MinerU version\n default: 0"),
+ ("Other / development / unknown", "invalid fallback"),
+ (" default: 5", " default: 0"),
+ ("name: 🐛 Bug report (English)", "name: [invalid yaml"),
+ ],
+)
+def test_invalid_template_fails_before_any_template_is_written(tmp_path: Path, old: str, new: str) -> None:
+ """第二份模板损坏也必须在第一份写入前失败,避免只同步一种语言。"""
+ first, second = tmp_path / "first.yml", tmp_path / "second.yml"
+ first.write_text(_baseline_template(TEMPLATES[1]), encoding="utf-8")
+ original = _baseline_template()
+ assert old in original
+ second.write_text(original.replace(old, new), encoding="utf-8")
+ before = [path.read_bytes() for path in (first, second)]
+ result = _run_sync(_wheel(tmp_path), [first, second])
+ assert result.returncode == 1, result.stdout
+ assert [path.read_bytes() for path in (first, second)] == before
+
+
+def test_identical_options_in_wrong_field_cannot_claim_markers(template_path: Path) -> None:
+ """即使另一个字段选项完全相同,源码位置也必须属于真正的版本字段。"""
+ source = template_path.read_text(encoding="utf-8")
+ start = source.index(" - type: dropdown\n id: software_version")
+ end = source.index(" - type: dropdown\n id: tier", start)
+ original_field = source[start:end]
+ unmarked = original_field.replace(" # BEGIN MINERU_RECENT_RELEASES\n", "").replace(
+ " # END MINERU_RECENT_RELEASES\n", ""
+ )
+ source = source[:start] + unmarked + original_field.replace("id: software_version", "id: decoy") + source[end:]
+ template_path.write_text(source, encoding="utf-8")
+ before = template_path.read_bytes()
+ assert _run_sync(_wheel(template_path.parent), template_path).returncode == 1
+ assert template_path.read_bytes() == before
+
+
+def test_issue_forms_are_equivalent_and_keep_unavailable_environment_fallbacks() -> None:
+ """两种语言保留七项数据和一次确认,旧版、开发版及安装失败用户仍可如实反馈。"""
+ structures = []
+ for template in TEMPLATES:
+ form = yaml.safe_load(template.read_text(encoding="utf-8"))
+ fields = {field["id"]: field for field in form["body"] if "id" in field}
+ assert list(fields) == [
+ "precheck",
+ "description",
+ "reproduce",
+ "usage_entry",
+ "os_mode",
+ "software_version",
+ "tier",
+ "device_mode",
+ ]
+ assert len([field for field in form["body"] if field["type"] == "checkboxes"]) == 1
+ assert len(fields["precheck"]["attributes"]["options"]) == 1
+ assert fields["precheck"]["attributes"]["options"][0]["required"] is True
+ structure = []
+ for field_id, field in fields.items():
+ attrs = field["attributes"]
+ required = field.get("validations", {}).get("required", False)
+ if field_id != "precheck":
+ assert required == (field_id != "tier")
+ assert "value" not in attrs and "\n" not in attrs.get("description", "")
+ if field["type"] == "dropdown":
+ options = attrs["options"]
+ assert len(options) == len(set(options)) and all(isinstance(value, str) for value in options)
+ if field_id == "software_version":
+ assert attrs["default"] == len(options) - 1
+ else:
+ assert "default" not in attrs
+ structure.append((field_id, field["type"], required))
+ assert "render" not in fields["reproduce"]["attributes"]
+ assert fields["software_version"]["type"] == "dropdown"
+ assert len(fields["software_version"]["attributes"]["options"]) == 6
+ assert fields["tier"]["attributes"]["options"][:4] == ["flash", "basic", "standard", "advanced"]
+ assert fields["device_mode"]["attributes"]["render"] == "text"
+ assert "mineru-kit hardware info" in fields["device_mode"]["attributes"]["placeholder"]
+ markdown = "\n".join(field["attributes"]["value"] for field in form["body"] if field["type"] == "markdown")
+ assert "mineru-kit hardware info" in markdown and "Docker" in markdown and "WSL" in markdown
+ if template == TEMPLATE:
+ assert "Installation / build" in fields["usage_entry"]["attributes"]["options"]
+ assert all(word in markdown for word in ("anonymized", "installation failed", "cannot access the server"))
+ else:
+ assert "安装或构建" in fields["usage_entry"]["attributes"]["options"]
+ assert all(word in markdown for word in ("脱敏", "安装失败", "无法访问服务端"))
+ structures.append(structure)
+ assert structures[0] == structures[1]
+ assert _options(TEMPLATES[0])[:-1] == _options(TEMPLATES[1])[:-1]
+
+
+def test_all_issue_template_yaml_and_chooser_links_are_valid() -> None:
+ """模板目录的配置与新增表单都需经过基础校验,不能只验证两个已知文件。"""
+ names = []
+ for path in sorted(TEMPLATE.parent.iterdir()):
+ if path.suffix not in {".yml", ".yaml"}:
+ continue
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
+ assert isinstance(data, dict), path
+ if path.name == "config.yml":
+ assert isinstance(data["blank_issues_enabled"], bool)
+ for link in data["contact_links"]:
+ assert all(isinstance(link[key], str) and link[key].strip() for key in ("name", "about", "url"))
+ assert link["url"].startswith("https://")
+ continue
+ assert all(isinstance(data[key], str) and data[key].strip() for key in ("name", "description"))
+ names.append(data["name"])
+ assert isinstance(data["body"], list) and data["body"]
+ ids = []
+ for field in data["body"]:
+ assert field["type"] in {"markdown", "input", "textarea", "dropdown", "checkboxes", "upload"}
+ attributes = field["attributes"]
+ assert isinstance(attributes, dict)
+ label = "value" if field["type"] == "markdown" else "label"
+ assert isinstance(attributes[label], str) and attributes[label].strip()
+ if "id" in field:
+ assert re.fullmatch(r"[A-Za-z0-9_-]+", field["id"])
+ ids.append(field["id"])
+ assert len(ids) == len(set(ids))
+ assert len(names) == len(set(names))
+
+
+ "metadata",
+ [
+ "Name: other-project\nVersion: 4.0.13\n",
+ "Version: 4.0.13\n",
+ "Name: mineru\n",
+ "Name: mineru\nVersion: invalid\n",
+ "Name: mineru\nVersion: 4.0.13\nVersion: 4.0.14\n",
+ "Name: mineru\nName: other-project\nVersion: 4.0.13\n",
+ ],
+)
+def test_invalid_metadata_fails_without_writing(template_path: Path, metadata: str) -> None:
+ """缺失、重复或不属于 MinerU 的发行元数据必须失败并保留原文件。"""
+ original = template_path.read_bytes()
+ result = _run_sync(_wheel(template_path.parent, metadata), template_path)
+ assert result.returncode == 1
+ assert "error:" in result.stderr
+ assert template_path.read_bytes() == original
+
+
[email protected]("tag", ["mineru-4.0.14-released", "v4.0.13", "mineru-invalid-released"])
+def test_invalid_or_mismatched_tag_fails_without_writing(template_path: Path, tag: str) -> None:
+ """不接受标签与发布产物不一致或格式非法的同步请求。"""
+ original = template_path.read_bytes()
+ result = _run_sync(_wheel(template_path.parent), template_path, tag)
+ assert result.returncode == 1
+ assert template_path.read_bytes() == original
+
+
[email protected]("failure", ["corrupt", "missing-metadata", "multiple-metadata", "no-wheel", "multiple-wheels"])
+def test_ambiguous_or_broken_artifact_fails_without_writing(template_path: Path, failure: str) -> None:
+ """损坏或含有多种候选产物的目录不能被当成唯一发布 wheel。"""
+ original = template_path.read_bytes()
+ directory = template_path.parent / "dist"
+ wheel_path = _wheel(directory)
+ if failure == "corrupt":
+ wheel_path.write_bytes(b"invalid zip")
+ elif failure == "missing-metadata":
+ with ZipFile(wheel_path, "w") as wheel:
+ wheel.writestr("unrelated.txt", "missing metadata")
+ elif failure == "multiple-metadata":
+ with ZipFile(wheel_path, "a") as wheel:
+ wheel.writestr("other.dist-info/METADATA", "Name: other\nVersion: 4.0.13\n")
+ elif failure == "no-wheel":
+ wheel_path.unlink()
+ else:
+ shutil.copyfile(wheel_path, directory / "another.whl")
+ result = _run_sync(directory, template_path)
+ assert result.returncode == 1
+ assert template_path.read_bytes() == original
+
+
+def _workflow_script() -> str:
+ """直接读取发版 job 的运行脚本,让集成测试执行 CI 中的原始逻辑。"""
+ job = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"]["sync-issue-template"]
+ return next(step["run"] for step in job["steps"] if "run" in step)
+
+
+def test_workflow_sync_requires_successful_tag_publication() -> None:
+ """同步必须依赖发布成功,使用默认分支、发布产物和既有写入凭据。"""
+ job = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"]["sync-issue-template"]
+ assert job["needs"] == ["publish"]
+ assert "startsWith(github.ref, 'refs/tags/')" in job["if"]
+ assert "needs.publish.result == 'success'" in job["if"]
+ checkout = next(step for step in job["steps"] if step.get("uses", "").startswith("actions/checkout@"))
+ assert checkout["with"]["ref"] == "${{ github.event.repository.default_branch }}"
+ assert checkout["with"]["token"] == "${{ secrets.RELEASE_TOKEN }}"
+ download = next(step for step in job["steps"] if step.get("uses", "").startswith("actions/download-artifact@"))
+ assert download["with"]["name"] == "wheel-file"
+ assert job["env"]["RELEASE_TAG"] == "${{ github.ref_name }}"
+ assert "${{" not in _workflow_script()
+ assert "gh api --paginate --slurp" in _workflow_script()
+ assert "--jq" not in _workflow_script()
+
+
+def _git(directory: Path, *args: str) -> str:
+ """只在临时仓库调用 Git,返回输出便于断言提交与远端状态。"""
+ return subprocess.run(
+ ["git", "-C", str(directory), *args], capture_output=True, text=True, check=True, timeout=15
+ ).stdout.strip()
+
+
+def release_checkout(tmp_path: Path) -> Path:
+ """建立本地 bare 远端和专用 checkout,模拟机器人同步而不访问 GitHub。"""
+ remote = tmp_path / "remote.git"
+ remote.mkdir()
+ _git(remote, "init", "--bare", "--initial-branch=master")
+ checkout = tmp_path / "checkout"
+ _git(tmp_path, "clone", str(remote), str(checkout))
+ _git(checkout, "config", "user.name", "Release sync test")
+ _git(checkout, "config", "user.email", "[email protected]")
+ for source in (*TEMPLATES, SCRIPT):
+ target = checkout / source.relative_to(ROOT)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(source, target)
+ for template in TEMPLATES:
+ (checkout / template.relative_to(ROOT)).write_text(_baseline_template(template), encoding="utf-8")
+ (checkout / "untouched.txt").write_text("preserve unrelated content\n", encoding="utf-8")
+ _git(checkout, "add", ".")
+ _git(checkout, "commit", "-m", "seed release template")
+ _git(checkout, "push", "origin", "HEAD:master")
+ return checkout
+
+
+def _workflow_environment(tmp_path: Path) -> dict[str, str]:
+ """替换 uv 启动器以复用测试 Python,避免 Git 集成测试下载依赖。"""
+ binaries = tmp_path / "bin"
+ binaries.mkdir()
+ launcher = binaries / "uv"
+ launcher.write_text("#!/bin/sh\nshift 4\n" + f'exec {shlex.quote(sys.executable)} "$@"\n', encoding="utf-8")
+ launcher.chmod(0o755)
+ gh = binaries / "gh"
+ gh.write_text(
+ '#!/bin/sh\nif [ "$SIMULATE_RELEASE_FETCH_FAILURE" = 1 ]; then exit 1; fi\ncat "$SYNC_RELEASE_HISTORY_FIXTURE"\n',
+ encoding="utf-8",
+ )
+ gh.chmod(0o755)
+ history = _history(tmp_path / "release-history-fixture.json")
+ wheel = _wheel(tmp_path / "published-dist")
+ return {
+ **os.environ,
+ "PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}",
+ "RELEASE_HISTORY": str(tmp_path / "downloaded-history.json"),
+ "SYNC_RELEASE_HISTORY_FIXTURE": str(history),
+ "GITHUB_REPOSITORY": "test/MinerU",
+ "RELEASE_BRANCH": "master",
+ "RELEASE_TAG": "mineru-4.0.13-released",
+ "RELEASE_WHEEL_DIR": str(wheel.parent),
+ }
+
+
+def _run_workflow(checkout: Path, env: dict[str, str]) -> subprocess.CompletedProcess[str]:
+ """执行 CI 同步步骤本身,保留与 Actions 相同的失败终止行为。"""
+ return subprocess.run(
+ ["bash", "-e", "-o", "pipefail", "-c", _workflow_script()],
+ cwd=checkout,
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ )
+
+
+def test_workflow_only_commits_template_and_repeated_run_is_noop(release_checkout: Path, tmp_path: Path) -> None:
+ """真实提交只能包含表单,重复同步不能新增机器人提交。"""
+ env = _workflow_environment(tmp_path)
+ result = _run_workflow(release_checkout, env)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert set(_git(release_checkout, "show", "--format=", "--name-only", "HEAD").splitlines()) == {
+ str(template.relative_to(ROOT)) for template in TEMPLATES
+ }
+ for template in TEMPLATES:
+ assert _options(release_checkout / template.relative_to(ROOT))[:-1] == ["4.0.13", *BASELINE[:4]]
+ committed = _git(release_checkout, "rev-parse", "HEAD")
+ repeated = _run_workflow(release_checkout, env)
+ assert repeated.returncode == 0, repeated.stdout + repeated.stderr
+ assert _git(release_checkout, "rev-parse", "HEAD") == committed
+ assert _git(release_checkout, "status", "--porcelain") == ""
+
+
[email protected]("newer_remote_version", [False, True])
+def test_workflow_retry_preserves_concurrent_commits(
+ release_checkout: Path, tmp_path: Path, newer_remote_version: bool
+) -> None:
+ """首次推送前模拟他人提交,验证重新生成能保留修改且不会回退较新版本。"""
+ real_git = shutil.which("git")
+ assert real_git is not None
+ competing = tmp_path / "competing"
+ _git(tmp_path, "clone", str(tmp_path / "remote.git"), str(competing))
+ _git(competing, "config", "user.name", "Concurrent test")
+ _git(competing, "config", "user.email", "[email protected]")
+ (competing / "concurrent.txt").write_text("keep this concurrent commit\n", encoding="utf-8")
+ competing_template = competing / TEMPLATE_RELATIVE
+ source = competing_template.read_text(encoding="utf-8") + "# Concurrent form edit\n"
+ if newer_remote_version:
+ source = source.replace("4.0.12", "4.0.14")
+ competing_template.write_text(source, encoding="utf-8")
+ _git(competing, "add", ".")
+ _git(competing, "commit", "-m", "concurrent default branch update")
+ env = _workflow_environment(tmp_path)
+ wrapper = tmp_path / "bin" / "git"
+ wrapper.write_text(
+ "#!/bin/sh\n"
+ 'if [ "$1" = push ] && [ ! -e "$SYNC_RACE_FLAG" ]; then\n'
+ ' touch "$SYNC_RACE_FLAG"\n'
+ ' "$REAL_GIT" -C "$COMPETING_CHECKOUT" push origin HEAD:master || exit 1\n'
+ ' if [ -n "$CONCURRENT_RELEASE_HISTORY" ]; then cp "$CONCURRENT_RELEASE_HISTORY" "$SYNC_RELEASE_HISTORY_FIXTURE"; fi\n'
+ "fi\n"
+ 'exec "$REAL_GIT" "$@"\n',
+ encoding="utf-8",
+ )
+ wrapper.chmod(0o755)
+ env.update(REAL_GIT=real_git, COMPETING_CHECKOUT=str(competing), SYNC_RACE_FLAG=str(tmp_path / "race-injected"))
+ if newer_remote_version:
+ env["CONCURRENT_RELEASE_HISTORY"] = str(_history(tmp_path / "new-history.json", ("4.0.14", "4.0.13", *BASELINE)))
+ result = _run_workflow(release_checkout, env)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert "Push attempt 1 failed" in result.stdout
+ updated = (release_checkout / TEMPLATE_RELATIVE).read_text(encoding="utf-8")
+ expected_version = "4.0.14" if newer_remote_version else "4.0.13"
+ for template in TEMPLATES:
+ assert _options(release_checkout / template.relative_to(ROOT))[0] == expected_version
+ assert "# Concurrent form edit" in updated
+ assert (release_checkout / "concurrent.txt").read_text(encoding="utf-8") == "keep this concurrent commit\n"
+ assert _git(release_checkout, "rev-parse", "HEAD") == _git(release_checkout, "rev-parse", "origin/master")
+
+
+def test_workflow_reports_failure_after_three_rejected_pushes(release_checkout: Path, tmp_path: Path) -> None:
+ """模拟持续拒绝推送,确认重试有界且以失败退出而非误报同步成功。"""
+ real_git = shutil.which("git")
+ assert real_git is not None
+ env = _workflow_environment(tmp_path)
+ wrapper = tmp_path / "bin" / "git"
+ wrapper.write_text(
+ '#!/bin/sh\nif [ "$1" = push ]; then\n echo push >> "$PUSH_ATTEMPTS"\n exit 1\nfi\nexec "$REAL_GIT" "$@"\n',
+ encoding="utf-8",
+ )
+ wrapper.chmod(0o755)
+ attempts = tmp_path / "push-attempts"
+ env.update(REAL_GIT=real_git, PUSH_ATTEMPTS=str(attempts))
+ result = _run_workflow(release_checkout, env)
+ assert result.returncode == 1
+ assert "::error::Could not synchronize the issue template after three push attempts." in result.stdout
+ assert attempts.read_text(encoding="utf-8").splitlines() == ["push", "push", "push"]
+ assert _git(release_checkout, "show", f"origin/master:{TEMPLATE_RELATIVE}") == _baseline_template().strip()
+
+
+def test_release_list_download_failure_does_not_commit(release_checkout: Path, tmp_path: Path) -> None:
+ """GitHub 列表读取失败时终止同步,保留远端和本地两份模板。"""
+ env = _workflow_environment(tmp_path)
+ env["SIMULATE_RELEASE_FETCH_FAILURE"] = "1"
+ head = _git(release_checkout, "rev-parse", "HEAD")
+ result = _run_workflow(release_checkout, env)
+ assert result.returncode != 0
+ assert _git(release_checkout, "rev-parse", "HEAD") == head
+ assert _git(release_checkout, "status", "--porcelain") == ""
diff --git a/tests/unittest/test_issue_template_release_sync.py b/tests/unittest/test_issue_template_release_sync.py
deleted file mode 100644
index 632aa396..00000000
--- a/tests/unittest/test_issue_template_release_sync.py
+++ /dev/null
@@ -1,384 +0,0 @@
-"""用模拟发布产物与临时 Git 仓库验证 issue 模板同步,无需发布或安装 MinerU。"""
-
-from __future__ import annotations
-
-import os
-import re
-import shlex
-import shutil
-import subprocess
-import sys
-from pathlib import Path
-from zipfile import ZipFile
-
-import pytest
-import yaml
-from packaging.version import Version
-
-ROOT = Path(__file__).resolve().parents[2]
-TEMPLATE = ROOT / ".github" / "ISSUE_TEMPLATE" / "bug_report.yml"
-SCRIPT = ROOT / "scripts" / "sync_issue_template_version.py"
-WORKFLOW = ROOT / ".github" / "workflows" / "python-package.yml"
-TEMPLATE_RELATIVE = TEMPLATE.relative_to(ROOT)
-
-
-def _baseline_template() -> str:
- """保留真实表单结构,只固定测试起始版本,避免正式发版改变升级和重试场景。"""
- source, count = re.subn(
- r"(?m)^( Latest stable release: )\S+( \| 最新正式版本:)\S+$",
- r"\g<1>4.0.12\g<2>4.0.12",
- TEMPLATE.read_text(encoding="utf-8"),
- )
- assert count == 1
- return source
-
-
-def template_path(tmp_path: Path) -> Path:
- """复制固定版本的真实模板,确保同步测试不会写入仓库中的表单。"""
- target = tmp_path / "bug_report.yml"
- target.write_text(_baseline_template(), encoding="utf-8")
- return target
-
-
-def _wheel(directory: Path, metadata: str = "Name: mineru\nVersion: 4.0.13\n") -> Path:
- """构造只含发行元数据的模拟 wheel,隔离模型依赖和网络访问。"""
- directory.mkdir(parents=True, exist_ok=True)
- target = directory / "mineru-test-py3-none-any.whl"
- with ZipFile(target, "w") as wheel:
- wheel.writestr("mineru-test.dist-info/METADATA", metadata)
- return target
-
-
-def _run_sync(wheel: Path, template: Path, tag: str = "mineru-4.0.13-released") -> subprocess.CompletedProcess[str]:
- """通过真实脚本入口执行同步,覆盖参数解析、错误退出和文件写入。"""
- return subprocess.run(
- [sys.executable, str(SCRIPT), "--wheel", str(wheel), "--template", str(template), "--tag", tag],
- capture_output=True,
- text=True,
- timeout=15,
- check=False,
- )
-
-
[email protected]("version", ["4.0.13", "4.0.100"])
[email protected]("newline", ["\n", "\r\n"])
-def test_new_release_preserves_other_text_and_line_endings(template_path: Path, version: str, newline: str) -> None:
- """验证 PEP 440 升级、注释保留、换行保留和重复运行不写文件。"""
- source = template_path.read_text(encoding="utf-8") + "# Unrelated version example: 4.0.12\n"
- original = source.replace("\n", newline).encode("utf-8")
- template_path.write_bytes(original)
- wheel = _wheel(template_path.parent, f"Name: mineru\nVersion: {version}\n")
- result = _run_sync(wheel, template_path, f"mineru-{version}-released")
- assert result.returncode == 0, result.stderr
- expected = original.replace(
- "Latest stable release: 4.0.12 | 最新正式版本:4.0.12".encode(),
- f"Latest stable release: {version} | 最新正式版本:{version}".encode(),
- )
- assert template_path.read_bytes() == expected
- modified = template_path.stat().st_mtime_ns
- repeated = _run_sync(wheel, template_path, f"mineru-{version}-released")
- assert repeated.returncode == 0, repeated.stderr
- assert template_path.stat().st_mtime_ns == modified
-
-
-def test_current_repository_template_can_advance(tmp_path: Path) -> None:
- """直接验证未归一化的当前表单仍能升级,防止固定夹具掩盖真实模板漂移。"""
- source = TEMPLATE.read_text(encoding="utf-8")
- hint = re.search(r"(?m)^ Latest stable release: (?P<version>\S+) \| 最新正式版本:(?P=version)$", source)
- assert hint is not None
- current = Version(hint["version"])
- version = f"{current.major}.{current.minor}.{current.micro + 1}"
- template = tmp_path / "current-template.yml"
- template.write_text(source, encoding="utf-8")
- result = _run_sync(_wheel(tmp_path, f"Name: mineru\nVersion: {version}\n"), template, f"mineru-{version}-released")
- assert result.returncode == 0, result.stderr
- replacement = f" Latest stable release: {version} | 最新正式版本:{version}"
- assert template.read_text(encoding="utf-8") == source[: hint.start()] + replacement + source[hint.end() :]
-
-
[email protected]("version", ["4.0.12", "4.0.11", "4.0.9", "5.0.0a1", "5.0.0rc1", "5.0.0.dev1", "4.0.13+local"])
-def test_older_and_non_stable_versions_do_not_change_hint(template_path: Path, version: str) -> None:
- """旧版回放、预发布和本地开发构建不能覆盖正式版本提示。"""
- original = template_path.read_bytes()
- wheel = _wheel(template_path.parent, f"Name: mineru\nVersion: {version}\n")
- result = _run_sync(wheel, template_path, f"mineru-{version}-released")
- assert result.returncode == 0, result.stderr
- assert template_path.read_bytes() == original
-
-
- "metadata",
- [
- "Name: other-project\nVersion: 4.0.13\n",
- "Version: 4.0.13\n",
- "Name: mineru\n",
- "Name: mineru\nVersion: invalid\n",
- "Name: mineru\nVersion: 4.0.13\nVersion: 4.0.14\n",
- "Name: mineru\nName: other-project\nVersion: 4.0.13\n",
- ],
-)
-def test_invalid_metadata_fails_without_writing(template_path: Path, metadata: str) -> None:
- """缺失、重复或不属于 MinerU 的发行元数据必须失败并保留原文件。"""
- original = template_path.read_bytes()
- result = _run_sync(_wheel(template_path.parent, metadata), template_path)
- assert result.returncode == 1
- assert "error:" in result.stderr
- assert template_path.read_bytes() == original
-
-
[email protected]("tag", ["mineru-4.0.14-released", "v4.0.13", "mineru-invalid-released"])
-def test_invalid_or_mismatched_tag_fails_without_writing(template_path: Path, tag: str) -> None:
- """不接受标签与发布产物不一致或格式非法的同步请求。"""
- original = template_path.read_bytes()
- result = _run_sync(_wheel(template_path.parent), template_path, tag)
- assert result.returncode == 1
- assert template_path.read_bytes() == original
-
-
[email protected]("failure", ["corrupt", "missing-metadata", "multiple-metadata", "no-wheel", "multiple-wheels"])
-def test_ambiguous_or_broken_artifact_fails_without_writing(template_path: Path, failure: str) -> None:
- """损坏或含有多种候选产物的目录不能被当成唯一发布 wheel。"""
- original = template_path.read_bytes()
- directory = template_path.parent / "dist"
- wheel_path = _wheel(directory)
- if failure == "corrupt":
- wheel_path.write_bytes(b"invalid zip")
- elif failure == "missing-metadata":
- with ZipFile(wheel_path, "w") as wheel:
- wheel.writestr("unrelated.txt", "missing metadata")
- elif failure == "multiple-metadata":
- with ZipFile(wheel_path, "a") as wheel:
- wheel.writestr("other.dist-info/METADATA", "Name: other\nVersion: 4.0.13\n")
- elif failure == "no-wheel":
- wheel_path.unlink()
- else:
- shutil.copyfile(wheel_path, directory / "another.whl")
- result = _run_sync(directory, template_path)
- assert result.returncode == 1
- assert template_path.read_bytes() == original
-
-
- ("old", "new"),
- [
- ("# END MINERU_LATEST_STABLE_VERSION", "# missing marker"),
- (
- "# BEGIN MINERU_LATEST_STABLE_VERSION",
- "# BEGIN MINERU_LATEST_STABLE_VERSION\n # BEGIN MINERU_LATEST_STABLE_VERSION",
- ),
- (" # END MINERU_LATEST_STABLE_VERSION", " # END MINERU_LATEST_STABLE_VERSION"),
- ("最新正式版本:4.0.12", "最新正式版本:4.0.11"),
- ("4.0.12", "5.0.0rc1"),
- ("id: software_version", "id: wrong_field"),
- (" - type: textarea\n id: software_version", " - type: [textarea]\n id: software_version"),
- ("id: device_mode", "id: software_version"),
- ("name: 🐛 Bug Report", "name: [invalid yaml"),
- ],
-)
-def test_invalid_template_fails_without_writing(template_path: Path, old: str, new: str) -> None:
- """损坏的标记、版本、字段归属和 YAML 在写入前被拒绝。"""
- source = template_path.read_text(encoding="utf-8").replace(old, new)
- template_path.write_text(source, encoding="utf-8")
- original = template_path.read_bytes()
- result = _run_sync(_wheel(template_path.parent), template_path)
- assert result.returncode == 1
- assert template_path.read_bytes() == original
-
-
-def test_issue_form_accepts_installation_and_current_product_reports() -> None:
- """真实表单覆盖当前入口,安装失败也可以填写所有必填环境字段。"""
- form = yaml.safe_load(TEMPLATE.read_text(encoding="utf-8"))
- ids = [field["id"] for field in form["body"] if "id" in field]
- assert len(ids) == len(set(ids))
- assert all(re.fullmatch(r"[A-Za-z0-9_-]+", field_id) for field_id in ids)
- fields = {field["id"]: field for field in form["body"] if "id" in field}
- for field in form["body"]:
- if field["type"] == "dropdown":
- options = field["attributes"]["options"]
- assert all(isinstance(option, str) and option.strip() for option in options)
- assert len(options) == len(set(options))
- assert "default" not in field["attributes"]
- assert fields["software_version"]["type"] == "textarea"
- assert fields["software_version"]["validations"]["required"] is True
- assert "value" not in fields["software_version"]["attributes"]
- assert "installation failed" in fields["software_version"]["attributes"]["description"]
- assert "3.14" in fields["python_version"]["attributes"]["options"]
- assert fields["tier"]["attributes"]["options"][:4] == ["flash", "basic", "standard", "advanced"]
- assert fields["parse_mode"]["attributes"]["options"][:3] == ["auto", "txt", "ocr"]
- assert not fields["parse_mode"].get("validations", {}).get("required", False)
- assert fields["device_mode"]["type"] == "textarea"
- assert fields["device_mode"]["validations"]["required"] is True
- diagnostics = fields["device_mode"]["attributes"]
- assert diagnostics["render"] == "text"
- assert "value" not in diagnostics
- assert "mineru-kit hardware info" in diagnostics["placeholder"]
- assert "mineru-kit hardware info" in diagnostics["description"]
- for guidance in (
- "installation failed",
- "does not support the command",
- "cannot access the server",
- "error output",
- "known environment",
- ):
- assert guidance in diagnostics["description"]
- assert "Installation / build | 安装或构建" in fields["usage_entry"]["attributes"]["options"]
- ai_field = next(field for field in form["body"] if "🤖" in field["attributes"].get("label", ""))
- assert all(option.get("required", False) is False for option in ai_field["attributes"]["options"])
-
-
-def _workflow_script() -> str:
- """直接读取发版 job 的运行脚本,让集成测试执行 CI 中的原始逻辑。"""
- job = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"]["sync-issue-template"]
- return next(step["run"] for step in job["steps"] if "run" in step)
-
-
-def test_workflow_sync_requires_successful_tag_publication() -> None:
- """同步必须依赖发布成功,使用默认分支、发布产物和既有写入凭据。"""
- job = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"]["sync-issue-template"]
- assert job["needs"] == ["publish"]
- assert "startsWith(github.ref, 'refs/tags/')" in job["if"]
- assert "needs.publish.result == 'success'" in job["if"]
- checkout = next(step for step in job["steps"] if step.get("uses", "").startswith("actions/checkout@"))
- assert checkout["with"]["ref"] == "${{ github.event.repository.default_branch }}"
- assert checkout["with"]["token"] == "${{ secrets.RELEASE_TOKEN }}"
- download = next(step for step in job["steps"] if step.get("uses", "").startswith("actions/download-artifact@"))
- assert download["with"]["name"] == "wheel-file"
- assert job["env"]["RELEASE_TAG"] == "${{ github.ref_name }}"
- assert "${{" not in _workflow_script()
-
-
-def _git(directory: Path, *args: str) -> str:
- """只在临时仓库调用 Git,返回输出便于断言提交与远端状态。"""
- return subprocess.run(
- ["git", "-C", str(directory), *args], capture_output=True, text=True, check=True, timeout=15
- ).stdout.strip()
-
-
-def release_checkout(tmp_path: Path) -> Path:
- """建立本地 bare 远端和专用 checkout,模拟机器人同步而不访问 GitHub。"""
- remote = tmp_path / "remote.git"
- remote.mkdir()
- _git(remote, "init", "--bare", "--initial-branch=master")
- checkout = tmp_path / "checkout"
- _git(tmp_path, "clone", str(remote), str(checkout))
- _git(checkout, "config", "user.name", "Release sync test")
- _git(checkout, "config", "user.email", "[email protected]")
- for source in (TEMPLATE, SCRIPT):
- target = checkout / source.relative_to(ROOT)
- target.parent.mkdir(parents=True, exist_ok=True)
- shutil.copyfile(source, target)
- (checkout / TEMPLATE_RELATIVE).write_text(_baseline_template(), encoding="utf-8")
- (checkout / "untouched.txt").write_text("preserve unrelated content\n", encoding="utf-8")
- _git(checkout, "add", ".")
- _git(checkout, "commit", "-m", "seed release template")
- _git(checkout, "push", "origin", "HEAD:master")
- return checkout
-
-
-def _workflow_environment(tmp_path: Path) -> dict[str, str]:
- """替换 uv 启动器以复用测试 Python,避免 Git 集成测试下载依赖。"""
- binaries = tmp_path / "bin"
- binaries.mkdir()
- launcher = binaries / "uv"
- launcher.write_text("#!/bin/sh\nshift 4\n" + f'exec {shlex.quote(sys.executable)} "$@"\n', encoding="utf-8")
- launcher.chmod(0o755)
- wheel = _wheel(tmp_path / "published-dist")
- return {
- **os.environ,
- "PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}",
- "RELEASE_BRANCH": "master",
- "RELEASE_TAG": "mineru-4.0.13-released",
- "RELEASE_WHEEL_DIR": str(wheel.parent),
- }
-
-
-def _run_workflow(checkout: Path, env: dict[str, str]) -> subprocess.CompletedProcess[str]:
- """执行 CI 同步步骤本身,保留与 Actions 相同的失败终止行为。"""
- return subprocess.run(
- ["bash", "-e", "-o", "pipefail", "-c", _workflow_script()],
- cwd=checkout,
- env=env,
- capture_output=True,
- text=True,
- timeout=30,
- check=False,
- )
-
-
-def test_workflow_only_commits_template_and_repeated_run_is_noop(release_checkout: Path, tmp_path: Path) -> None:
- """真实提交只能包含表单,重复同步不能新增机器人提交。"""
- env = _workflow_environment(tmp_path)
- result = _run_workflow(release_checkout, env)
- assert result.returncode == 0, result.stdout + result.stderr
- assert _git(release_checkout, "show", "--format=", "--name-only", "HEAD") == str(TEMPLATE_RELATIVE)
- assert "4.0.13" in (release_checkout / TEMPLATE_RELATIVE).read_text(encoding="utf-8")
- committed = _git(release_checkout, "rev-parse", "HEAD")
- repeated = _run_workflow(release_checkout, env)
- assert repeated.returncode == 0, repeated.stdout + repeated.stderr
- assert _git(release_checkout, "rev-parse", "HEAD") == committed
- assert _git(release_checkout, "status", "--porcelain") == ""
-
-
[email protected]("newer_remote_version", [False, True])
-def test_workflow_retry_preserves_concurrent_commits(
- release_checkout: Path, tmp_path: Path, newer_remote_version: bool
-) -> None:
- """首次推送前模拟他人提交,验证重新生成能保留修改且不会回退较新版本。"""
- real_git = shutil.which("git")
- assert real_git is not None
- competing = tmp_path / "competing"
- _git(tmp_path, "clone", str(tmp_path / "remote.git"), str(competing))
- _git(competing, "config", "user.name", "Concurrent test")
- _git(competing, "config", "user.email", "[email protected]")
- (competing / "concurrent.txt").write_text("keep this concurrent commit\n", encoding="utf-8")
- competing_template = competing / TEMPLATE_RELATIVE
- source = competing_template.read_text(encoding="utf-8") + "# Concurrent form edit\n"
- if newer_remote_version:
- source = source.replace("4.0.12", "4.0.14")
- competing_template.write_text(source, encoding="utf-8")
- _git(competing, "add", ".")
- _git(competing, "commit", "-m", "concurrent default branch update")
- env = _workflow_environment(tmp_path)
- wrapper = tmp_path / "bin" / "git"
- wrapper.write_text(
- "#!/bin/sh\n"
- 'if [ "$1" = push ] && [ ! -e "$SYNC_RACE_FLAG" ]; then\n'
- ' touch "$SYNC_RACE_FLAG"\n'
- ' "$REAL_GIT" -C "$COMPETING_CHECKOUT" push origin HEAD:master || exit 1\n'
- "fi\n"
- 'exec "$REAL_GIT" "$@"\n',
- encoding="utf-8",
- )
- wrapper.chmod(0o755)
- env.update(REAL_GIT=real_git, COMPETING_CHECKOUT=str(competing), SYNC_RACE_FLAG=str(tmp_path / "race-injected"))
- result = _run_workflow(release_checkout, env)
- assert result.returncode == 0, result.stdout + result.stderr
- assert "Push attempt 1 failed" in result.stdout
- updated = (release_checkout / TEMPLATE_RELATIVE).read_text(encoding="utf-8")
- expected_version = "4.0.14" if newer_remote_version else "4.0.13"
- assert f"Latest stable release: {expected_version}" in updated
- assert "# Concurrent form edit" in updated
- assert (release_checkout / "concurrent.txt").read_text(encoding="utf-8") == "keep this concurrent commit\n"
- assert _git(release_checkout, "rev-parse", "HEAD") == _git(release_checkout, "rev-parse", "origin/master")
-
-
-def test_workflow_reports_failure_after_three_rejected_pushes(release_checkout: Path, tmp_path: Path) -> None:
- """模拟持续拒绝推送,确认重试有界且以失败退出而非误报同步成功。"""
- real_git = shutil.which("git")
- assert real_git is not None
- env = _workflow_environment(tmp_path)
- wrapper = tmp_path / "bin" / "git"
- wrapper.write_text(
- '#!/bin/sh\nif [ "$1" = push ]; then\n echo push >> "$PUSH_ATTEMPTS"\n exit 1\nfi\nexec "$REAL_GIT" "$@"\n',
- encoding="utf-8",
- )
- wrapper.chmod(0o755)
- attempts = tmp_path / "push-attempts"
- env.update(REAL_GIT=real_git, PUSH_ATTEMPTS=str(attempts))
- result = _run_workflow(release_checkout, env)
- assert result.returncode == 1
- assert "::error::Could not synchronize the issue template after three push attempts." in result.stdout
- assert attempts.read_text(encoding="utf-8").splitlines() == ["push", "push", "push"]
- assert _git(release_checkout, "show", f"origin/master:{TEMPLATE_RELATIVE}") == _baseline_template().strip()