执行摘要
- 一句话:导入机械重构验证的 Claude Code skill
- 推荐动作:值得精读。该 PR 展示了如何通过工具强制保证重构的可复现性和可审计性,对于大型代码库的工程实践有借鉴意义。
verify_mechanical_refactor 函数中 git worktree + diff 校验的设计值得参考。
功能与动机
PR body 指明:该技能用于强化 sprint 的机械重构约定——每个文件拆分/函数移动/模块提取的提交必须附带一个可重现的转换脚本(gist),且该脚本(而非 diff)是 review 交付物。这使得机械重构可审计、可复现。
实现拆解
- 创建技能目录:在
.claude/skills/mechanical-refactor-verify/ 下存放两个文件。
- 编写核心工具函数(
mechanical_refactor_verify_utils.py):提供 exec_command 执行 shell 命令、git_add_and_commit 执行 git 提交、dedent 辅助缩进处理、以及 verify_mechanical_refactor 主函数,该函数基于 git worktree 创建独立工作副本,运行 transform 回调,diff 对比,如果结果非空则失败。
- 编写技能描述文档(
SKILL.md):定义技能名称、描述、调用方式,并给出完整的 transform 脚本模板和分步说明。
- 无其他变更:未修改
python/ 下任意源码,无测试配套,仅工具流程新增。
关键文件:
.claude/skills/mechanical-refactor-verify/mechanical_refactor_verify_utils.py(模块 工具脚本;类别 source;类型 core-logic;符号 exec_command, git_add_and_commit, dedent, verify_mechanical_refactor): 核心工具模块,提供 verify_mechanical_refactor 等函数,是技能的可执行逻辑。
.claude/skills/mechanical-refactor-verify/SKILL.md(模块 文档;类别 docs;类型 documentation;符号 transform): 技能描述和模板,定义工作流程,是开发者使用该技能的指引。
关键符号:exec_command, git_add_and_commit, dedent, verify_mechanical_refactor, transform
关键源码片段
.claude/skills/mechanical-refactor-verify/mechanical_refactor_verify_utils.py
核心工具模块,提供 verify_mechanical_refactor 等函数,是技能的可执行逻辑。
"""Utilities for mechanical refactor verification scripts.
See SKILL.md for usage and transform script template.
"""
import shlex
import subprocess
import sys
import tempfile
from collections.abc import Callable
from pathlib import Path
def exec_command(cmd: str, cwd: str | None = None, check: bool = True) -> str:
# 打印执行的命令,方便追踪
print(f" $ {cmd}", flush=True)
result = subprocess.run(
cmd,
shell=True,
cwd=cwd,
capture_output=True,
text=True,
)
if check and result.returncode != 0:
# 命令失败时打印 stderr 并直接退出
print(f"FAILED: {result.stderr}", file=sys.stderr)
sys.exit(1)
return result.stdout.strip()
def git_add_and_commit(message: str, cwd: str) -> None:
# 封装 git 提交,自动处理消息引号
exec_command(f"git add -A && git commit -m {shlex.quote(message)}", cwd=cwd)
def dedent(text: str, n: int) -> str:
"""Remove exactly n leading spaces from each line."""
lines = text.splitlines(keepends=True)
return "".join(line[n:] if line[:n] == " " * n else line for line in lines)
def verify_mechanical_refactor(
base_commit: str,
target_commit: str,
transform: "Callable[[Path], None]",
) -> None:
# 主验证流程:创建 worktree -> 运行 transform -> diff 校验
repo_root = exec_command("git rev-parse --show-toplevel")
worktree_dir = tempfile.mkdtemp(prefix="verify-mechanical-")
branch_name = f"verify-mechanical-{base_commit[:8]}"
try:
print(f"[1/4] Creating worktree at {base_commit[:8]}...")
exec_command(
f"git worktree add -b {branch_name} {worktree_dir} {base_commit}",
cwd=repo_root,
)
print("[2/4] Running transformation...")
transform(Path(worktree_dir))
print("[3/4] Running pre-commit...")
exec_command("pre-commit run --all-files", cwd=worktree_dir, check=False)
if exec_command("git status --porcelain", cwd=worktree_dir):
git_add_and_commit("pre-commit fixes", cwd=worktree_dir)
print(f"[4/4] Diffing against {target_commit[:8]}...")
diff = exec_command(
f"git diff {target_commit} -- .",
cwd=worktree_dir,
check=False,
)
if diff:
print(f"\nFAIL: diff is non-empty:\n{diff}")
sys.exit(1)
else:
print("\nPASS: transform reproduces the commit exactly.")
finally:
# 清理提示,不自动删除 worktree 以便调试
print(f"\nWorktree left at: {worktree_dir}")
print(f"Branch: {branch_name}")
print("To clean up manually:")
print(f" git worktree remove {worktree_dir} && git branch -D {branch_name}")
评论区精华
无 review 讨论。仅有一个来自 gemini-code-assist[bot] 的评论提醒 quota 限制,与 PR 内容无关。
风险与影响
- 风险:无直接风险。变更仅限于
.claude/skills/ 下的工具脚本和文档,不涉足任何运行时逻辑、配置或测试。技能本身仅当开发者显式调用 /mechanical-refactor-verify 时才生效,不会自动执行。潜在风险极小。
- 影响:影响范围:主要影响参与机械重构(文件拆分、函数移动、模块提取)的开发者,要求他们为每次机械提交附带可重现脚本。团队整体代码 review 流程将更可审计。影响程度:中低度,因为强制约束仅针对特定类型的重构,不影响日常功能开发。对用户无影响(非产品变更)。
- 风险标记:暂无
关联脉络
- PR #25449 Convert discarded-value ternary to a plain if statement: 属于同一重构链(mechanical refactor)中的小重构,此类提交受益于本 PR 的验证技能。
- PR #25448 Inline the trivial _build_model_config wrapper: 同样为机械重构(内联包装),本 PR 引入的技能可直接用于验证此类变更。
- PR #25444 Bundle Scheduler rank/size fields into a frozen ParallelState: 字段封装属于机械重构(字段迁移),本 PR 的技能可用于确保此类提取的可复现性。
参与讨论