Detect and remove unused dependencies from Cargo.toml
in Rust projects.
Does not work with transitive dependencies from macros (need to manually ignore).
cargo binstall cargo-shear
# OR
cargo install cargo-shear
cargo shear --fix
- name: Install cargo-binstall
uses: cargo-bins/cargo-binstall@main
- name: Install cargo-shear
run: cargo binstall --no-confirm cargo-shear
- run: cargo shear
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).
Add to package's Cargo.toml
[package.metadata.cargo-shear]
ignored = ["crate"]
- use the
cargo_metadata
crate to list all dependencies specified in[workspace.dependencies]
and[dependencies]
- iterate through all package targets to locate all Rust files
- use
syn
to parse these Rust files and extract imports - identify the difference between the imports and the package dependencies
- -7 lines from oxc
- -59 lines from rspack
- -39 lines from rolldown
- -12 lines ast-grep commit1 commit2
- -66 lines biome
- make the reporting more granular for
[dependencies]
,[dev-dependencies]
and[build-dependencies]
- add tests
- print things nicely