Rustfmt: proposal: groupping of imports

Created on 29 Aug 2018  路  4Comments  路  Source: rust-lang/rustfmt

In clang-format recently the grouping and sorting of includes was introduced.
see: clang-format search for IncludeCategories
Where one is able to specify via regex some index and based on that the sorting is applied.

Since rust has proper import and crates we dont need any regex driven categories to achieve sorting.

It would be nice if cargo-fmt not only sorted includes alphabetically but also groupped them.
something like:
1) std
2) alphabetically sorted 3rd party imports, so first uses from use a::b; and then use b::c etc.
3) alphabetically sorted workspace imports.
4) alphabetically sorted this crate imports.

Inserting blank lines between these groups above

a-imports feature-request

Most helpful comment

I would find a feature like this very useful, as I strongly prefer to sort my imports like the following:

// std
use std::io;

// crates
use regex::Regex;
use reqwest::Error;

// local modules
use foo::bar;

Which is indeed essentially the same as what @fulara detailed.

All 4 comments

I would find a feature like this very useful, as I strongly prefer to sort my imports like the following:

// std
use std::io;

// crates
use regex::Regex;
use reqwest::Error;

// local modules
use foo::bar;

Which is indeed essentially the same as what @fulara detailed.

This has been implemented in the IntelliJ IDEA Rust plugin for example. See Changelog #86:

  • Group imports by semantics while import optimization

Pre:

use url::Url;
use std::sync::Rc;
use valico::json_schema::Scope;
mod utils;
use crate::utils::Test;
use wasm_bindgen::prelude::*;

Post:

use std::sync::Rc;

use url::Url;
use valico::json_schema::Scope;
use wasm_bindgen::prelude::*;

use crate::utils::Test;

mod utils;

Mentioned plugin allows to use rustfmt as well, but I found this better. And of course there're collisions.

I think that something like this should be part of the rustfmt, so, we can avoid stuff like reordered imports, because team member has different IDE / editor / ... with custom formatting (like this plugin), etc.

Yes please impose an order so we don't have to have debates about what order it should be.

I'm not sure if a default format can be introduced outside of major version / edition bound, but being able to opt-in to an ordering in rustfmt.toml would be fantastic. At work we have a fairly large monorepo, and the only formatting issue that comes up is import ordering.

Also Rust Analyzer's "convert this into a use statement" action uses a different import format than the one I prefer, meaning that after using it requires further manual adjustments. If rustfmt was able to group imports it'd practically solve this issue.

Was this page helpful?
0 / 5 - 0 ratings