50 releases (24 stable)

Uses new Rust 2024

new 1.2.6 Apr 25, 2025
1.1.11 Mar 18, 2025
1.1.4 Nov 25, 2024
1.1.1 Jul 25, 2024
0.0.16 Mar 29, 2024

#34 in Cargo plugins

Download history 4355/week @ 2025-01-08 3467/week @ 2025-01-15 2953/week @ 2025-01-22 2899/week @ 2025-01-29 4083/week @ 2025-02-05 3897/week @ 2025-02-12 3933/week @ 2025-02-19 4550/week @ 2025-02-26 4102/week @ 2025-03-05 4854/week @ 2025-03-12 4068/week @ 2025-03-19 4193/week @ 2025-03-26 4975/week @ 2025-04-02 4506/week @ 2025-04-09 5943/week @ 2025-04-16 4944/week @ 2025-04-23

21,148 downloads per month
Used in cargo-preflight

MIT license

37KB
591 lines

Cargo Shear ✂️ 🐑

Detect and remove unused dependencies from Cargo.toml in Rust projects.

Installation

# Install from pre-built binaries.
cargo binstall cargo-shear

# Build from source.
cargo install cargo-shear

# Install from brew.
brew install cargo-shear

Usage

cargo shear --fix

Limitation

[!IMPORTANT] cargo shear cannot detect "hidden" imports from macro expansions without the --expand flag (nightly only). This is because cargo shear uses syn to parse files and does not expand macros by default.

To expand macros:

cargo shear --expand --fix

The --expand flag uses cargo expand, which requires nightly and is significantly slower.

Ignore false positives

False positives can be ignored by adding them to the package's Cargo.toml:

[package.metadata.cargo-shear]
ignored = ["crate"]

or in workspace's Cargo.toml:

[workspace.metadata.cargo-shear]
ignored = ["crate"]

Otherwise please report the issue as a bug.

CI

- name: Install cargo-binstall
  uses: cargo-bins/cargo-binstall@main

- name: Install cargo-shear
  run: cargo binstall --no-confirm cargo-shear

- run: cargo shear

Exit Code (for CI)

The exit code gives an indication whether unused dependencies have been found:

  • 0 if found no unused dependencies,
  • 1 if it found at least one unused dependency,
  • 2 if there was an error during processing (in which case there's no indication whether any unused dependency was found or not).

Technique

  1. use the cargo_metadata crate to list all dependencies specified in [workspace.dependencies] and [dependencies]
  2. iterate through all package targets (lib, bin, example, test and bench) to locate all Rust files
  3. use syn to parse these Rust files and extract imports
  • alternatively, use the --expand option with cargo expand to first expand macros and then parse the expanded code (though this is significantly slower).
  1. find the difference between the imports and the package dependencies

Prior Arts

Trophy Cases

Sponsored By

My sponsors

Dependencies

~7–15MB
~189K SLoC