SKILL.md
只读
名称
code-simplifier
描述
审查 RTK Rust 代码,进行惯用简化。检测过度设计、不必要的分配、冗长模式。在不改变行为的前提下应用 Rust 惯用法。
RTK 代码简化器
审查并简化 RTK 中的 Rust 代码,同时尊重项目的约束。
约束(绝不简化掉)
LazyLock正则表达式——即使“更简单”也不能移到函数内部- 每个
?上的.context()——冗长但必须保留 - 回退到原始命令——即使看起来像死代码也绝不删除
- 退出码传播——绝不简化为
Ok(()) #[cfg(test)] mod tests——绝不删除测试模块
简化模式
1. 迭代器链代替手动循环
// ❌ 冗长
let mut result = Vec::new();
for line in input.lines() {
let trimmed = line.trim();
if !trimmed.is_empty() && trimmed.starts_with("error") {
result.push(trimmed.to_string());
}
}
// ✅ 惯用
let result: Vec<String> = input.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty() && l.starts_with("error"))
.map(str::to_string)
.collect();
2. 字符串构建
// ❌ 冗长的 push 循环
let mut out = String::new();
for (i, line) in lines.iter().enumerate() {
out.push_str(line);
if i < lines.len() - 1 {
out.push('\n');
}
}
// ✅ join
let out = lines.join("\n");
3. Option/Result 链式调用
// ❌ 嵌套 match
let result = match maybe_value {
Some(v) => match transform(v) {
Ok(r) => r,
Err(_) => default,
},
None => default,
};
// ✅ 链式
let result = maybe_value
.and_then(|v| transform(v).ok())
.unwrap_or(default);
4. 结构体解构
// ❌ 重复字段访问
fn process(args: &MyArgs) -> String {
format!("{} {}", args.command, args.subcommand)
}
// ✅ 解构
fn process(&MyArgs { ref command, ref subcommand, .. }: &MyArgs) -> String {
format!("{} {}", command, subcommand)
}
5. 提前返回代替嵌套
// ❌ 深度嵌套
fn filter(input: &str) -> Option<String> {
if !input.is_empty() {
if let Some(line) = input.lines().next() {
if line.starts_with("error") {
return Some(line.to_string());
}
}
}
None
}
// ✅ 提前返回
fn filter(input: &str) -> Option<String> {
if input.is_empty() { return None; }
let line = input.lines().next()?;
if !line.starts_with("error") { return None; }
Some(line.to_string())
}
6. 避免冗余克隆
// ❌ 不必要的克隆
fn filter_output(input: &str) -> String {
let s = input.to_string(); // 无意义的克隆
s.lines().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")
}
// ✅ 直接使用 &str
fn filter_output(input: &str) -> String {
input.lines().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")
}
7. 使用 if let 处理单变体 match
// ❌ 为单个变体使用完整 match
match output {
Ok(s) => process(&s),
Err(_) => {},
}
// ✅ if let(但在 RTK 中仍需处理错误——不要静默丢弃)
if let Ok(s) = output {
process(&s);
}
// 注意:在 RTK 过滤器中,始终使用 eprintln! + 回退处理 Err
RTK 特定检查
简化后运行以下检查:
# 验证无回归
cargo fmt --all && cargo clippy --all-targets && cargo test
# 验证函数中没有新的正则表达式
grep -n "Regex::new" src/<file>.rs
# 固定、复用的模式应放在 `LazyLock<Regex>` 静态变量中
# 验证生产代码中没有新的 unwrap
grep -n "\.unwrap()" src/<file>.rs
# 应只出现在 #[cfg(test)] 块内
不要简化什么
static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(...).unwrap());—— 这里的.unwrap()是可接受的,因为它是初始化时.context("description")?链——冗长但必需- 回退匹配分支
Err(e) => { eprintln!(...); raw_output }—— 看起来冗余但它是安全网 std::process::exit(code)在 run() 末尾——看起来可以简化为Ok(())但实际上不能




