]> git.lizzy.rs Git - rust.git/blob - crates/ra_assists/src/split_import.rs
051bc6fecf2ab9b8b5b58c915fd2318959eec003
[rust.git] / crates / ra_assists / src / split_import.rs
1 use hir::db::HirDatabase;
2 use ra_syntax::{
3     TextUnit, AstNode, SyntaxKind::COLONCOLON,
4     ast,
5     algo::generate,
6 };
7
8 use crate::{AssistCtx, Assist};
9
10 pub(crate) fn split_import(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
11     let colon_colon = ctx.leaf_at_offset().find(|leaf| leaf.kind() == COLONCOLON)?;
12     let path = colon_colon.parent().and_then(ast::Path::cast)?;
13     let top_path = generate(Some(path), |it| it.parent_path()).last()?;
14
15     let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast);
16     if use_tree.is_none() {
17         return None;
18     }
19
20     let l_curly = colon_colon.range().end();
21     let r_curly = match top_path.syntax().parent().and_then(ast::UseTree::cast) {
22         Some(tree) => tree.syntax().range().end(),
23         None => top_path.syntax().range().end(),
24     };
25
26     ctx.build("split import", |edit| {
27         edit.target(colon_colon.range());
28         edit.insert(l_curly, "{");
29         edit.insert(r_curly, "}");
30         edit.set_cursor(l_curly + TextUnit::of_str("{"));
31     })
32 }
33
34 #[cfg(test)]
35 mod tests {
36     use super::*;
37     use crate::helpers::{check_assist, check_assist_target};
38
39     #[test]
40     fn test_split_import() {
41         check_assist(
42             split_import,
43             "use crate::<|>db::RootDatabase;",
44             "use crate::{<|>db::RootDatabase};",
45         )
46     }
47
48     #[test]
49     fn split_import_works_with_trees() {
50         check_assist(
51             split_import,
52             "use algo:<|>:visitor::{Visitor, visit}",
53             "use algo::{<|>visitor::{Visitor, visit}}",
54         )
55     }
56
57     #[test]
58     fn split_import_target() {
59         check_assist_target(split_import, "use algo::<|>visitor::{Visitor, visit}", "::");
60     }
61 }