How do I find out the dependencies in Cargo.toml that are unused? How can I remove them automatically?
One option is to use cargo-udeps.
You can install it via command:
cargo install cargo-udeps --locked
Then, to find unused dependencies in production target:
cargo +nightly udeps
To find unused dev dependencies:
cargo +nightly udeps --all-targets
cargo-udeps
requires the nightly compiler, which might introduce potential instability or compatibility issues.
I recommend to use machete. It works with the stable Rust compiler and eliminates the risk of potentially unstable nightly builds. It offers a fast and convenient way to identify potential unused dependencies. Also, it can be configured to ignore specific dependencies or provide more detailed information.
Install machete:
cargo install cargo-machete
Find unused dependencies in the project:
cargo machete --with-metadata
To fix unused dependencies:
cargo machete --fix
--with-metadata uses cargo-metadata to figure out the dependencies' names.
May be useful if some dependencies are renamed from their
own Cargo.toml file (e.g. xml-rs which gets renamed xml).
Try it if you get false positives!
--skip-target-dir don't analyze anything contained in any target/ directories
encountered.
--fix rewrite the Cargo.toml files to automatically remove unused
dependencies. Note: all dependencies flagged by
cargo-machete will be removed, including false positives.
--version print version.
cargo-shear
does this very nicely and can be used with the stable toolchain.
Install:
cargo install cargo-shear
Check if there are any unused dependencies
cargo shear
To fix (remove) an unused dependency:
cargo shear --fix
© 2022 - 2024 — McMap. All rights reserved.