I'm looking for a tool I can run to clean up "use" declarations in my project. This would mean removing unused imports, switching the imports to a canonical form, sorting them alphabetically, etc. Does something like this exist?
At least some of this tasks are performed by rustfmt, AFAIK.
Yeah, besides the unused declarations thing, rustfmt does all of these.
cargo fix is a tool for automatically fixing some things in Rust. It fixes unused imports warnings by removing them. Make sure to enable the warnings you want to have fixed (remove any
allow directives in the code). Not every warning can be automatically fixed, but
cargo fix can do quite a lot.
$ cargo build ... warning: unused import: `std::collections::HashMap` --> src\lib.rs:119:5 | 119 | use std::collections::HashMap; | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default warning: 1 warning emitted $ cargo fix --lib ... Fixing src\lib.rs (1 fix) Finished dev [unoptimized + debuginfo] target(s) in 8.73s $ git diff diff --git src/lib.rs src/lib.rs index 70bce0ed..0e03ee49 100644 --- src/lib.rs +++ src/lib.rs @@ -116,7 +116,7 @@ pub mod doc; use std::marker::PhantomData; use std::sync::Arc; -use std::collections::HashMap; + pub use crate::dimension::dim::*;
For merging imports, if you're OK with using nighlty rustfmt, you can make a
rustfmt.toml file with:
merge_imports = true
cargo fmt will merge imports, and sort them. Otherwise it will only sort the imports and won't merge different ones.
Running that and
cargo fix should work. I usually
git add -A and then
cargo fix --allow-staged (usually
cargo fix can only be run on a clean commit).
cargo fix --all-features definitely does not remove unused imports for me... I still get couple dozen unused import warnings after running it.
too bad merge_imports = true isn't default setting.
i have to define my own setting and not use the 'standard' formatting guidelines.