33 releases (7 stable)
1.1.4 | Nov 25, 2024 |
---|---|
1.1.3 | Sep 23, 2024 |
1.1.2 | Aug 18, 2024 |
1.1.1 | Jul 25, 2024 |
0.0.16 | Mar 29, 2024 |
#63 in Cargo plugins
13,619 downloads per month
27KB
478 lines
Cargo Shear ✂️ 🐑
Detect and remove unused dependencies from Cargo.toml
in Rust projects.
Installation
cargo binstall cargo-shear
# OR
cargo install cargo-shear
Usage
cargo shear --fix
Ignore false positives
[!IMPORTANT]
cargo shear
cannot detect dependency usages from macros because it usessyn
to parse the files
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
- use the
cargo_metadata
crate to list all dependencies specified in[workspace.dependencies]
and[dependencies]
- iterate through all package targets (
lib
,bin
,example
,test
andbench
) to locate all Rust files - use
syn
to parse these Rust files and extract imports - find the difference between the imports and the package dependencies
Prior Arts
- est31/cargo-udeps
- it collects dependency usage by compiling your project and find them from the
target/
directory - does not seem to work anymore with the latest versions of
cargo
- does not work with cargo workspaces
- it collects dependency usage by compiling your project and find them from the
- bnjbvr/cargo-machete
- it collects dependency usage by running regex patterns on source code
- does not detect all usages of a dependency
- does not remove unused dependencies from the workspace root
- cargo and clippy
- There was intention to add similar features to cargo or clippy, but the progress is currently stagnant
- See https://github.com/rust-lang/rust/issues/57274 and https://github.com/rust-lang/rust-clippy/issues/4341
Trophy Cases
- -7 lines from oxc
- -59 lines from rspack
- -39 lines from rolldown
- -12 lines ast-grep commit1 commit2
- -66 lines biome
- -164 lines astral-sh/uv
- -86 lines reqsign
Sponsored By
Dependencies
~9–18MB
~241K SLoC