关于 code-refactor
用于跨文件执行代码重构的技能。较小范围使用原生搜索和编辑工具,涉及 10 个或更多文件时切换到 code-execution。
主要功能
- 01搜索代码匹配项
- 02跨文件替换模式
- 03按文件数量选择执行方式
- 04编辑后验证修改
- 05支持标识符和 API 更新
适用场景
- 01在项目中重命名标识符
- 02替换已弃用的代码模式
- 03更新多个文件中的 API 调用
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mhattingpete/ claude-skills-marketplace --skill code-refactor安装后在 Claude Code 中输入/code-refactor确认已加载。
详细介绍
代码重构
在多个文件中系统地重构代码。处理 10 个及以上文件时自动切换到执行模式(节省 90% 的 token)。
模式选择
- 1–9 个文件:使用原生工具(Grep + Edit,并设置 replace_all)
- 10 个及以上文件:自动使用
code-execution技能
执行示例(50 个文件):
from api.code_transform import rename_identifier
result = rename_identifier('.', 'oldName', 'newName', '**/*.py')
# Returns: {'files_modified': 50, 'total_replacements': 247}
# ~500 tokens vs ~25,000 tokens traditional
适用场景
- “将 [identifier] 重命名为 [new_name]”
- “将所有 [pattern] 替换为 [replacement]”
- “重构为使用 [new_pattern]”
- “更新所有对 [function/API] 的调用”
- “将 [old_pattern] 转换为 [new_pattern]”
核心工作流(原生模式)
1. 查找所有匹配项
Grep(pattern="getUserData", output_mode="files_with_matches") # Find files
Grep(pattern="getUserData", output_mode="content", -n=true, -B=2, -A=2) # Verify with context
2. 替换所有实例
Edit(
file_path="src/api.js",
old_string="getUserData",
new_string="fetchUserData",
replace_all=true
)
3. 验证更改
Grep(pattern="getUserData", output_mode="files_with_matches") # Should return none
工作流示例
重命名函数
- 查找:
Grep(pattern="getUserData", output_mode="files_with_matches") - 计数:“在 5 个文件中找到 15 个匹配项”
- 在每个文件中使用
replace_all=true进行替换 - 验证:重新运行 Grep
- 建议:运行测试
替换已弃用模式
- 查找:
Grep(pattern="\\bvar\\s+\\w+", output_mode="content", -n=true) - 分析:检查变量是否会被重新赋值(let)或为常量(const)
- 替换:
Edit(old_string="var count = 0", new_string="let count = 0") - 验证:
npm run lint
更新 API 调用
- 查找:
Grep(pattern="/api/auth/login", output_mode="content", -n=true) - 替换:
Edit(old_string="'/api/auth/login'", new_string="'/api/v2/authentication/login'", replace_all=true) - 测试:建议运行集成测试
最佳实践
规划:
- 先查找所有实例
- 查看每个匹配项的上下文
- 告知用户影响范围
- 考虑边缘情况(字符串、注释)
安全流程:
- 搜索 → 查找全部
- 分析 → 确认是否合适
- 告知 → 告诉用户影响范围
- 执行 → 进行更改
- 验证 → 确认更改已应用
- 测试 → 建议运行测试
边缘情况:
- 字符串/注释:询问是否应更新
- 导出的 API:警告可能存在的破坏性更改
- 区分大小写:明确说明
工具参考
使用 replace_all 的 Edit:
replace_all=true:替换所有匹配项replace_all=false:仅替换第一个匹配项(若有多个匹配项则失败)- 必须完全匹配(空格、引号)
Grep 模式:
-n=true:显示行号-B=N, -A=N:显示上下文行-i=true:不区分大小写type="py":按文件类型筛选
集成
- test-fixing:重构后修复损坏的测试
- code-transfer:迁移重构后的代码
- feature-planning:规划大型重构
评论
支持 Markdown