How do I remove unused dependencies in Cargo.toml?
Asked Answered
T

3

20

How do I find out the dependencies in Cargo.toml that are unused? How can I remove them automatically?

Transpacific answered 2/5, 2022 at 5:12 Comment(3)
It seems like github.com/est31/cargo-udeps and/or github.com/Bromeon/cargo-machete are your best betsSnitch
Looks like cargo-machete is gone now.Suit
You can use this cargo-machete crate instead.Electroballistics
T
25

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
Transpacific answered 2/5, 2022 at 5:34 Comment(0)
J
5

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.

Jotunheim answered 6/6 at 20:17 Comment(0)
S
0

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
Scissel answered 5/8 at 2:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.