Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(tooling): 接管 Dependabot 升级时只套分支自己的改动,不再抹掉 master 新加的依赖

longmeidaoc9c639fd9118
diff --git a/scripts/adopt_dependency_bump.py b/scripts/adopt_dependency_bump.py
index e8f01fb1d..e0290ec20 100644
--- a/scripts/adopt_dependency_bump.py
+++ b/scripts/adopt_dependency_bump.py
@@ -10,7 +10,7 @@ lucide-static 1.38.0 → 1.40.0 的 PR #4)。`frontend/package.json` 同理,
`dependabot/**` 推回重算的产物得靠 `pull_request_target` 或一个 PAT,两条都是给 CI 加
提权面。所以接管在本地做——凭据是你自己的,CI 一行都不用改。它做完这些:
-1. 取那个 PR 的 head 分支,只把 manifest 与 lock 签出到当前分支;
+1. 取那个 PR 的 head 分支,把它对 manifest 与 lock 的改动三方合并套到当前分支;
2. `npm ci --ignore-scripts` 后重算这份清单对应的派生产物;
3. 列出真实改动的文件,`--apply` 时只暂存这些并提交。
@@ -53,14 +53,15 @@ RECIPES = {
}
-def run(command: tuple[str, ...] | list[str], *, capture: bool = True) -> str:
+def run(command: tuple[str, ...] | list[str], *, capture: bool = True,
+ root: Path = ROOT) -> str:
"""在仓库根目录跑一条命令,失败即抛。
第一个词过一遍 `shutil.which`:Windows 上 `npm` 是 `npm.cmd`,而 `CreateProcess`
不查 `PATHEXT`,照字面传就是 FileNotFoundError。
"""
executable = shutil.which(command[0]) or command[0]
- result = subprocess.run([executable, *command[1:]], cwd=ROOT, capture_output=capture,
+ result = subprocess.run([executable, *command[1:]], cwd=root, capture_output=capture,
text=True, encoding="utf-8", errors="replace", check=False)
if result.returncode != 0:
detail = (result.stderr or result.stdout or "").strip() if capture else ""
@@ -104,6 +105,29 @@ def branch_changes(branch: str) -> list[str]:
if line]
+def bring_over(branch: str, manifests: tuple[str, ...], *, root: Path = ROOT) -> None:
+ """把那个分支对清单的改动套到工作区,不暂存。
+
+ 套的是它自合并基以来的 diff,不是整份文件:分支的清单停在几天前的 master 上,
+ 整份签出会把这几天 master 往清单里加的依赖一并抹掉(实际发生过:#20 的
+ `frontend/package.json` 没有后来加进来的 `sonner`)。两边改到同一行时 `--3way`
+ 报冲突并退出非零,由 `run` 抛出来。补丁先落成文件再给 `git apply`:Windows 上文本
+ 模式的 stdin 会把 `\\n` 写成 `\\r\\n`,补丁就对不上了。
+ """
+ patch = run(("git", "diff", "--merge-base", "HEAD", f"origin/{branch}", "--", *manifests),
+ root=root)
+ if not patch:
+ return
+ path = root / "build" / "adopt.patch"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(patch, encoding="utf-8", newline="\n")
+ try:
+ run(("git", "apply", "--3way", str(path)), root=root)
+ finally:
+ path.unlink()
+ run(("git", "reset", "--quiet", "--", *manifests), root=root)
+
+
def working_changes() -> list[str]:
return [line for line in run(("git", "diff", "--name-only", "HEAD")).splitlines() if line]
@@ -171,8 +195,7 @@ def main(argv: list[str] | None = None) -> int:
branch = args.branch or head_branch(args.pr)
run(("git", "fetch", "origin", branch))
key, recipe = recipe_for(branch_changes(branch))
- run(("git", "checkout", f"origin/{branch}", "--", *recipe["manifests"]))
- run(("git", "reset", "--quiet", "--", *recipe["manifests"]))
+ bring_over(branch, recipe["manifests"])
versions = manifest_versions(key)
for command in recipe["commands"]:
run(command, capture=False)
diff --git a/tests/test_dependency_policy.py b/tests/test_dependency_policy.py
index 4ad6e47d2..058f00851 100644
--- a/tests/test_dependency_policy.py
+++ b/tests/test_dependency_policy.py
@@ -4,11 +4,14 @@ import ast
import json
from pathlib import Path
import re
+import subprocess
import sys
+import tempfile
import tomllib
import unittest
from scripts import adopt_dependency_bump as adopt
+from tests.support.gitrepo import seed_repository
ROOT = Path(__file__).resolve().parents[1]
@@ -181,6 +184,49 @@ class DependencyPolicyTests(unittest.TestCase):
with self.assertRaisesRegex(RuntimeError, "同时改了"):
adopt.recipe_for(["package.json", "frontend/package.json"])
+ def test_the_takeover_keeps_what_master_added_to_the_manifest_after_the_fork(self):
+ """接管套的是分支自己的改动,分叉后 master 往清单里加的依赖原样留着。
+
+ Dependabot 的分支停在几天前的 master 上;整份签出它的清单,就把这几天新加的
+ 依赖抹掉了。两边改到同一行时要报出来,不能静默挑一边。
+ """
+ def manifest(a: str, extra: str = "") -> bytes:
+ names = "".join(f' "{name}": "1",\n' for name in "bcdefg")
+ return (f'{{\n "dependencies": {{\n "a": "{a}",\n{names}{extra}'
+ ' "h": "1"\n }\n}\n').encode("utf-8")
+
+ def git(repo: Path, *args: str) -> None:
+ subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True)
+
+ def fork(repo: Path, *, branch_a: str, master_a: str, master_extra: str) -> None:
+ # 仓库靠 .gitattributes 固定 LF;临时仓库没有它,开发机的全局 autocrlf 会让
+ # 三方合并写回 CRLF。
+ git(repo, "config", "core.autocrlf", "false")
+ git(repo, "checkout", "-q", "-b", "dep")
+ (repo / "package.json").write_bytes(manifest(branch_a))
+ git(repo, "commit", "-q", "-am", "bump a")
+ git(repo, "update-ref", "refs/remotes/origin/dep", "dep")
+ git(repo, "checkout", "-q", "master")
+ (repo / "package.json").write_bytes(manifest(master_a, master_extra))
+ git(repo, "commit", "-q", "-am", "master moves on")
+
+ with tempfile.TemporaryDirectory() as holder:
+ repo = seed_repository(Path(holder).resolve() / "clean",
+ {"package.json": manifest("1")}, "base")
+ fork(repo, branch_a="2", master_a="1", master_extra=' "sonner": "2.0.8",\n')
+ adopt.bring_over("dep", ("package.json",), root=repo)
+ self.assertEqual((repo / "package.json").read_bytes(),
+ manifest("2", ' "sonner": "2.0.8",\n'))
+ staged = subprocess.run(["git", "-C", str(repo), "diff", "--cached", "--name-only"],
+ check=True, capture_output=True, text=True).stdout
+ self.assertEqual(staged, "", "接管只改工作区,暂存留给 --apply")
+
+ repo = seed_repository(Path(holder).resolve() / "clash",
+ {"package.json": manifest("1")}, "base")
+ fork(repo, branch_a="2", master_a="3", master_extra="")
+ with self.assertRaises(RuntimeError):
+ adopt.bring_over("dep", ("package.json",), root=repo)
+
def test_the_takeover_commit_message_passes_the_readme_impact_gate(self):
"""`README-Impact` 与 `Co-Authored-By` 必须同一个 trailer 块、中间不空行。