Code Simplifier

rtk-ai/rtk/.claude/skills/code-simplifier

作者 rtk-aie4f05094d613无许可证82K 个星标收录于 2026年10月8日更新于 2026年10月8日仓库今天更新

Review RTK Rust code for idiomatic simplification. Detects over-engineering, unnecessary allocations, verbose patterns. Applies Rust idioms without changing behavior.

AI 生成的概览

审查 RTK 项目中的 Rust 代码,在不改变行为的前提下应用符合习惯用法的简化。

功能
该技能指导智能体审查 RTK 中的 Rust 代码,将冗长或过度设计的写法改写为符合习惯用法的等价形式。它列出七种简化模式,包括用迭代器链替代手写循环、用 join 替代 push 循环、Option/Result 链式调用、结构体解构、提前返回、避免多余克隆,以及对单一变体匹配使用 if let。它还列出绝不能被简化掉的项目约束,并建议使用 cargo fmt、clippy 和 test 等命令进行验证。
适用场景
当 RTK 中的 Rust 代码被描述为冗长、过度设计或需要重构为习惯用法时使用。它适用于在保持行为不变的前提下简化代码或使其更符合习惯用法的请求。
运行要求
仅为指令,不附带脚本。需要访问 RTK 的 Rust 代码库,具备读取、搜索和编辑文件的能力,以及用于建议验证命令的 Rust 工具链(cargo、rustfmt、clippy)。

RTK Code Simplifier

Review and simplify Rust code in RTK while respecting the project's constraints.

Constraints (never simplify away)

  • LazyLock regex — cannot be moved inside functions even if "simpler"
  • .context() on every ? — verbose but mandatory
  • Fallback to raw command — never remove even if it looks like dead code
  • Exit code propagation — never simplify to Ok(())
  • #[cfg(test)] mod tests — never remove test modules

Simplification Patterns

1. Iterator chains over manual loops

rust
// ❌ Verboselet 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());    }}
// ✅ Idiomaticlet result: Vec<String> = input.lines()    .map(|l| l.trim())    .filter(|l| !l.is_empty() && l.starts_with("error"))    .map(str::to_string)    .collect();

2. String building

rust
// ❌ Verbose push looplet mut out = String::new();for (i, line) in lines.iter().enumerate() {    out.push_str(line);    if i < lines.len() - 1 {        out.push('\n');    }}
// ✅ joinlet out = lines.join("\n");

3. Option/Result chaining

rust
// ❌ Nested matchlet result = match maybe_value {    Some(v) => match transform(v) {        Ok(r) => r,        Err(_) => default,    },    None => default,};
// ✅ Chainedlet result = maybe_value    .and_then(|v| transform(v).ok())    .unwrap_or(default);

4. Struct destructuring

rust
// ❌ Repeated field accessfn process(args: &MyArgs) -> String {    format!("{} {}", args.command, args.subcommand)}
// ✅ Destructurefn process(&MyArgs { ref command, ref subcommand, .. }: &MyArgs) -> String {    format!("{} {}", command, subcommand)}

5. Early returns over nesting

rust
// ❌ Deeply nestedfn 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}
// ✅ Early returnfn 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. Avoid redundant clones

rust
// ❌ Unnecessary clonefn filter_output(input: &str) -> String {    let s = input.to_string();  // Pointless clone    s.lines().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")}
// ✅ Work with &strfn filter_output(input: &str) -> String {    input.lines().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")}

7. Use if let for single-variant match

rust
// ❌ Full match for one variantmatch output {    Ok(s) => process(&s),    Err(_) => {},}
// ✅ if let (but still handle errors in RTK — don't silently drop)if let Ok(s) = output {    process(&s);}// Note: in RTK filters, always handle Err with eprintln! + fallback

RTK-Specific Checks

Run these after simplification:

bash
# Verify no regressionscargo fmt --all && cargo clippy --all-targets && cargo test
# Verify no new regex in functionsgrep -n "Regex::new" src/<file>.rs# Fixed, reused patterns should be in `LazyLock<Regex>` statics
# Verify no new unwrap in productiongrep -n "\.unwrap()" src/<file>.rs# Should only appear inside #[cfg(test)] blocks

What NOT to Simplify

  • static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(...).unwrap()); — the .unwrap() here is acceptable, it's init-time
  • .context("description")? chains — verbose but required
  • The fallback match arm Err(e) => { eprintln!(...); raw_output } — looks redundant but is the safety net
  • std::process::exit(code) at end of run() — looks like it could be Ok(())but it isn't

来源与署名

来源:rtk-ai/rtk位于.claude/skills/code-simplifier提交e4f0509

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架