SuperAPI AI 工具集

cargo-machete

编程与开发

查看项目

更新于 11-11 01:09

技能介绍

用途

cargo-machete 是一个用 Rust 编写的快速工具,用于检测 Rust 项目中未使用的依赖:它分析代码库,找出在 Cargo.toml 中声明但代码实际未使用的依赖,以便保持 Cargo.toml 整洁并提升构建速度。

主要能力

  • 检测未使用依赖,并报告仅部分使用的特性(如 tokio 的未使用 feature)。
  • 支持检查当前目录或指定目录。
  • 支持工作区检查(--workspace)、按成员选择(-p)与排除(--exclude)。
  • --with-metadata 输出更详细的元数据信息。
  • --fix 可自动从 Cargo.toml 移除未使用依赖。
  • 支持通过 .cargo-machete.toml 或 Cargo.toml 行内注释(# machete:ignore)处理误报。

使用方式

安装:

cargo install cargo-machete
cargo machete --version

基本用法:

cargo machete                 # 检查当前目录
cargo machete /path/to/project
cargo machete --with-metadata
cargo machete --fix           # 自动移除未使用依赖
cargo machete --workspace

忽略误报:创建 .cargo-machete.toml(含 [ignore] dependencies、[ignore.my_crate] 等段落),或在 Cargo.toml 中使用 # machete:ignore 行内注释。

适用场景

  • 审计依赖、清理 Cargo.toml。
  • 在 CI 中做快速依赖检查(示例使用 GitHub Actions 或 taiki-e/install-action 安装并运行)。
  • 与 pre-commit、Makefile 及 cargo outdated、cargo audit、cargo deny 等工具组合使用。

限制

  • 准确度良好但非完美,存在误报,常见于仅用于 build.rs、examples、重导出(re-export)以及 proc-macro 派生宏场景;需人工核实或配置忽略。
  • 相比 cargo-udeps,准确度稍低,但速度更快且可在稳定版 Rust 上运行。
  • 使用 --fix 前建议先检查输出,修复后运行 cargo check --all-targets 验证。