Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: update issue template and sync published release version
myhloli77698670a5bc
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 2cbb8a0c..81915f8d 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -2,9 +2,7 @@ name: 🐛 Bug Reportdescription: Create a bug report for MinerU | MinerU 的 Bug 反馈labels: bug-# We omit `title: "..."` so that the field defaults to blank. If we set it to-# empty string, Github seems to reject this .yml file.-+# 不设置默认标题,让反馈者直接描述具体问题。body:- type: markdownattributes:@@ -15,88 +13,92 @@ body: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) to see if a similar bug report already exists.+ 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,确认是否已有类似反馈。options:- - label: I have searched the MinerU [Readme](https://github.com/opendatalab/MinerU) and found no similar bug report.+ - label: I have searched the MinerU [README](https://github.com/opendatalab/MinerU) for similar reports. | 我已搜索 README。required: true- - label: I have searched the MinerU [Issues](https://github.com/opendatalab/MinerU/issues) and found no similar bug report.+ - 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) and found no similar bug report.+ - label: I have searched the MinerU [Discussions](https://github.com/opendatalab/MinerU/discussions) for similar reports. | 我已搜索 Discussions。required: true- type: checkboxesattributes:- label: 🤖 Consult the online AI assistant for assistance | 在线 AI 助手咨询+ label: 🤖 Online AI assistant (optional) | 在线 AI 助手咨询(可选)description: >- This [online AI assistant](https://deepwiki.com/opendatalab/MinerU) is specifically trained to help with MinerU and related topics! It's available 24/7 and ready to provide insights.+ You may consult the [online AI assistant](https://deepwiki.com/opendatalab/MinerU) before reporting.+ 提交前也可以咨询在线 AI 助手,此项不影响提交。options:- - label: I have consulted the [online AI assistant](https://deepwiki.com/opendatalab/MinerU) but was unable to obtain a solution to the issue.- required: true+ - label: I consulted the online AI assistant but could not find a solution. | 我已咨询在线 AI 助手,但未找到解决方案。+ required: false- type: textareaid: descriptionattributes:label: Description of the bug | 错误描述description: |- Provide console output with error messages and/or screenshots of the bug. | 请提供详细报错信息或者截图- placeholder: |- 💡 ProTip! Include as much information as possible (screenshots, logs, tracebacks etc.) to receive the most helpful response.+ Describe the expected and actual behavior. Include relevant logs, full tracebacks, or screenshots.+ 请说明预期结果与实际结果,并提供相关日志、完整报错堆栈或截图。validations:required: true-+- type: textareaid: reproduceattributes:label: How to reproduce the bug | 如何复现-- # Should not word-wrap this description here.description: |- If you have questions about the parsing results or encounter errors during execution: | 如对解析结果有疑问或在运行中出现报错等异常:- * Provide a minimal reproducible example. | 请提供一个最小可复现的demo。- * The demo should include the complete steps, code, and the PDF file to be parsed. | demo需要包含完整的操作步骤,代码,以及需要解析的PDF文件。- * When reporting parsing result anomalies and runtime errors, reproducible PDF files are essential. If the document is too large or confidential, you can print the problematic page(s) via the browser and submit the corresponding example file.- * 在反馈解析结果异常和运行时报错时,可复现的PDF文件是必不可少的,如文档过大或涉密,您可通过浏览器打印出出现问题的某一页或某几页再提交相应的示例文件。--- For problems when building or installing MinerU: | 在构建或安装 MinerU 时遇到的问题:- * Give the **exact** build/install commands that were run. | 提供**确切**的构建/安装命令。- * Give the **complete** output from these commands. | 提供这些命令的**完整**输出。-+ 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.+ * 请提供确切的安装或构建命令及其完整输出,无需提供文档样例。validations:required: true-# - type: markdown-# attributes:-# value: |-# # The information below is required.-+ - type: dropdown+ id: usage_entry+ attributes:+ label: Usage entry | 使用入口+ options:+ - mineru CLI+ - mineru-kit CLI+ - Python SDK+ - API / Router+ - WebUI+ - Installation / build | 安装或构建+ - Other / unknown | 其他或不清楚+ validations:+ required: true- type: dropdownid: os_modeattributes:- label: Operating System Mode | 操作系统类型- #multiple: true+ label: Operating system | 操作系统类型options:- -- Windows- Linux- - MacOS+ - macOS+ - Other / unknown | 其他或不清楚validations:required: true- type: textareaid: os_name_versionattributes:- label: Operating System Version| 操作系统版本- #multiple: true+ label: Operating system version | 操作系统版本description: |- * 如果您使用的是Linux系统,请提供Linux系统的**发行版名称**和**版本号**来帮助开发人员排查问题。- * If you are using a Linux system, please provide the Linux distribution and version number to help developers troubleshoot the issue.- * 如果您使用的是Windows或MacOS系统,请提供操作系统的**版本号**来帮助开发人员排查问题。- * If you are using a Windows or MacOS system, please provide the version number of the operating system to help developers troubleshoot the issue.- * 例如:Ubuntu 22.04, CentOS 7.9, MacOS 15.1, Windows 11- * For example: Ubuntu 22.04, CentOS 7.9, MacOS 15.1, Windows 11.-+ 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.validations:required: true@@ -104,54 +106,69 @@ body:id: python_versionattributes:label: Python version | Python 版本- #multiple: true- # Need quotes around `3.10` otherwise it is treated as a number and shows as `3.1`.+ description: Python >=3.10,<3.15; see python --version. | 支持 Python >=3.10,<3.15,可通过 python --version 查看。options:- -+ - "3.14"- "3.13"- "3.12"- "3.11"- "3.10"+ - Other / unknown | 其他或不清楚validations:required: true- - type: dropdown+ - type: textareaid: software_versionattributes:- label: Software version | 软件版本 (mineru --version)- #multiple: false- options:- -- - "`<2.2.0`"- - "`2.2.x`"- - "`>=2.5`"- - "4.0.0.dev20260625"- - "4.0.0.dev20260626"+ label: MinerU version | MinerU 版本+ # BEGIN MINERU_LATEST_STABLE_VERSION+ description: |+ Latest stable release: 4.0.12 | 最新正式版本:4.0.12+ 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 版本>validations:required: true- type: dropdown- id: backend_name+ id: tierattributes:- label: Backend name | 解析后端- #multiple: false+ label: Parsing tier | 解析档位+ description: Include --tier or the API/SDK tier value. | 请填写 --tier 或 API/SDK 的 tier 值。options:- -- - "vlm"- - "pipeline"+ - flash+ - basic+ - standard+ - advanced+ - Default selection | 未显式指定+ - Not applicable / unknown | 不适用或不清楚validations:required: true- type: dropdown- id: device_mode+ id: parse_modeattributes:- label: Device mode | 设备模式- #multiple: true+ label: OCR / parsing mode (optional) | OCR / 解析模式(可选)+ description: Include --ocr-mode or the API/SDK parsing mode if known. | 如已知,请填写 --ocr-mode 或 API/SDK 的解析模式。options:- -- - cpu- - cuda- - mps- - npu- validations:- required: true+ - auto+ - txt+ - ocr+ - Not applicable / unknown | 不适用或不清楚++ - type: textarea+ id: device_mode+ attributes:+ label: Device and inference environment (optional) | 设备与推理环境(可选)+ description: |+ For local inference, include the device (cpu, cuda, mps, npu, xpu, etc.), GPU model and memory, and relevant driver versions.+ 本地推理请填写设备(cpu、cuda、mps、npu、xpu 等)、GPU 型号和显存,以及相关驱动版本。+ Include the small model backend (onnx / torch) and VLM engine (llama-cpp / vllm / lmdeploy / mlx) when applicable.+ 如涉及模型,请填写小模型后端(onnx / torch)与 VLM 引擎(llama-cpp / vllm / lmdeploy / mlx)。+ For remote inference, state the service/deployment and server environment if known.+ 远程推理请说明服务或部署方式,以及已知的服务端环境。diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.ymlindex 69d7da57..3f915b3f 100644--- a/.github/workflows/python-package.yml+++ b/.github/workflows/python-package.yml@@ -153,3 +153,59 @@ jobs:- name: Publish distribution to PyPIuses: pypa/gh-action-pypi-publish@release/v1++ sync-issue-template:+ needs: [ publish ]+ if: startsWith(github.ref, 'refs/tags/') && needs.publish.result == 'success'+ runs-on: ubuntu-latest+ env:+ RELEASE_BRANCH: ${{ github.event.repository.default_branch }}+ RELEASE_TAG: ${{ github.ref_name }}+ steps:+ - name: Checkout default branch+ uses: actions/checkout@v6+ with:+ ref: ${{ github.event.repository.default_branch }}+ fetch-depth: 0+ token: ${{ secrets.RELEASE_TOKEN }}++ - name: Download published wheel+ uses: actions/download-artifact@v7+ with:+ name: wheel-file+ path: ${{ runner.temp }}/mineru-issue-template-dist++ - name: Set up Python+ uses: actions/setup-python@v6+ with:+ python-version: "3.12"++ - name: Set up uv+ uses: astral-sh/setup-uv@v7++ - name: Sync and commit latest stable version hint+ shell: bash+ env:+ RELEASE_WHEEL_DIR: ${{ runner.temp }}/mineru-issue-template-dist+ run: |+ git config --local user.name "github-actions[bot]"+ git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"+ for attempt in 1 2 3; do+ # 此 job 的独立 checkout 每次基于最新分支重新生成,避免覆盖并发提交。+ git fetch origin "$RELEASE_BRANCH"+ git reset --hard FETCH_HEAD+ 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."+ exit 0+ fi+ git commit -m "chore: sync latest stable release in issue template"+ if git push origin "HEAD:$RELEASE_BRANCH"; then+ exit 0+ fi+ echo "Push attempt $attempt failed; regenerating from the latest default branch."+ done+ echo "::error::Could not synchronize the issue template after three push attempts."+ exit 1diff --git a/scripts/sync_issue_template_version.py b/scripts/sync_issue_template_version.pynew file mode 100644index 00000000..fd93b221--- /dev/null+++ b/scripts/sync_issue_template_version.py@@ -0,0 +1,130 @@+# Copyright (c) Opendatalab. All rights reserved.+# /// script+# requires-python = ">=3.10"+# dependencies = ["packaging", "PyYAML>=6,<7"]+# ///+"""依据已发布 wheel 的元数据更新 issue 表单中的最新正式版本提示。"""++from __future__ import annotations++import argparse+import re+import sys+from collections.abc import Sequence+from email import policy+from email.parser import BytesParser+from pathlib import Path+from zipfile import BadZipFile, ZipFile++import yaml+from packaging.utils import canonicalize_name+from packaging.version import Version++__all__ = ["main", "read_wheel_version", "sync_template_version", "update_template_version"]++BEGIN_MARKER = "# BEGIN MINERU_LATEST_STABLE_VERSION"+END_MARKER = "# END MINERU_LATEST_STABLE_VERSION"+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")+++def read_wheel_version(wheel_path: Path) -> Version:+ """读取唯一 MinerU wheel 的 METADATA,不安装软件包或导入 MinerU。"""+ if wheel_path.is_dir():+ wheels = sorted(wheel_path.glob("*.whl"))+ if len(wheels) != 1:+ raise ValueError(f"Expected exactly one wheel in {wheel_path}, found {len(wheels)}.")+ wheel_path = wheels[0]+ if wheel_path.suffix != ".whl":+ raise ValueError(f"Expected a .whl file, got {wheel_path}.")+ with ZipFile(wheel_path) as wheel:+ metadata_files = [name for name in wheel.namelist() if re.fullmatch(r"[^/]+\.dist-info/METADATA", name)]+ if len(metadata_files) != 1:+ raise ValueError(f"Expected exactly one METADATA file in {wheel_path}.")+ metadata = BytesParser(policy=policy.default).parsebytes(wheel.read(metadata_files[0]))+ names = metadata.get_all("Name", [])+ versions = metadata.get_all("Version", [])+ if len(names) != 1 or canonicalize_name(str(names[0])) != "mineru":+ raise ValueError("Wheel METADATA must identify the mineru distribution exactly once.")+ if len(versions) != 1:+ raise ValueError("Wheel METADATA must contain exactly one Version field.")+ return Version(str(versions[0]))+++def update_template_version(source: str, version: Version) -> str:+ """校验版本提示的归属与标记,只替换该区块的版本号并阻止提示回退。"""+ 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.")+ 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.")+ 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:+ """先验证产物版本与发版标签一致,完成全部校验后才写入模板。"""+ 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).")+ return False+ template_path.write_bytes(updated.encode("utf-8"))+ print(f"Updated latest stable release hint to {version} in {template_path}.")+ return True+++def main(argv: Sequence[str] | None = None) -> int:+ """解析发版同步参数,并将产物或模板异常转换为明确的失败退出码。"""+ 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("--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"))+ args = parser.parse_args(argv)+ try:+ sync_template_version(args.wheel, args.template, args.tag)+ except (ValueError, OSError, BadZipFile, yaml.YAMLError) as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/unittest/test_issue_template_release_sync.py b/tests/unittest/test_issue_template_release_sync.pynew file mode 100644index 00000000..70a33df4--- /dev/null+++ b/tests/unittest/test_issue_template_release_sync.py@@ -0,0 +1,342 @@+"""用模拟发布产物与临时 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++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 template_path(tmp_path: Path) -> Path:+ """复制真实模板,确保同步测试不会写入仓库中的表单。"""+ target = tmp_path / "bug_report.yml"+ target.write_bytes(TEMPLATE.read_bytes())+ 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.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++[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 not fields["device_mode"].get("validations", {}).get("required", False)+ 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 / "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}") == TEMPLATE.read_text(encoding="utf-8").strip()