Detect and remove unused dependencies from Cargo.toml in Rust projects.
# Install from pre-built binaries.
cargo binstall cargo-shear
# Build from source.
cargo install cargo-shear
# Install from brew.
brew install cargo-shearcargo shear --fixImportant
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 --fixThe --expand flag uses cargo expand, which requires nightly and is significantly slower.
False positives can be ignored by adding them to the package's Cargo.toml:
[package.metadata.cargo-shear]
ignored = ["crate-name"]or in the workspace Cargo.toml:
[workspace.metadata.cargo-shear]
ignored = ["crate-name"]Otherwise please report the issue as a bug.
- name: Install cargo-binstall
  uses: cargo-bins/cargo-binstall@main
- name: Install cargo-shear
  run: cargo binstall --no-confirm cargo-shear
- run: cargo shearThe 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).
 
With --fix:
- 0 if found no unused dependencies so no fixes were performed,
 - 1 if removed some unused dependencies. Useful for running 
cargo checkaftercargo-shearchangedCargo.toml. 
GitHub Actions Job Example:
- name: cargo-shear
  shell: bash
  run: |
    if ! cargo shear --fix; then
      cargo check
    fi
- use the 
cargo_metadatacrate to list all dependencies specified in[workspace.dependencies]and[dependencies] - iterate through all package targets (
lib,bin,example,testandbench) to locate all Rust files - use 
synto parse these Rust files and extract imports 
- alternatively, use the 
--expandoption withcargo expandto first expand macros and then parse the expanded code (though this is significantly slower). 
- find the difference between the imports and the package dependencies
 
- 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 rust-lang/rust#57274 and rust-lang/rust-clippy#4341