Skip to content

Commit abdf725

Browse files
committed
Fix double comma when merge imports on second line
This fixes the a bug when merging imports from the second line when it already has a comma it would previously insert a comma. There's probably a better way to check for a COMMA. This also ends up with a weird indentation, but rust-fmt can easily deal with it so I'm not sure how to resolve that. Closes #3832
1 parent c388130 commit abdf725

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

crates/ra_assists/src/handlers/merge_imports.rs

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ use std::iter::successors;
33
use ra_syntax::{
44
algo::{neighbor, SyntaxRewriter},
55
ast::{self, edit::AstNodeEdit, make},
6-
AstNode, Direction, InsertPosition, SyntaxElement, T,
6+
AstNode, Direction, InsertPosition, NodeOrToken, SyntaxElement, SyntaxKind, SyntaxToken, Token,
7+
T,
78
};
89

910
use crate::{Assist, AssistCtx, AssistId};
@@ -72,9 +73,24 @@ fn try_merge_trees(old: &ast::UseTree, new: &ast::UseTree) -> Option<ast::UseTre
7273
let lhs = old.split_prefix(&lhs_prefix);
7374
let rhs = new.split_prefix(&rhs_prefix);
7475

76+
let mut should_insert_comma = true;
77+
78+
lhs.syntax()
79+
.last_child()
80+
.and_then(|child| child.children().last())
81+
.and_then(|last| last.next_sibling_or_token())
82+
.map(|next_sibling| {
83+
// FIXME: there's probably a better way to check if it's a COMMA
84+
if let NodeOrToken::Token(maybe_comma) = next_sibling {
85+
should_insert_comma = maybe_comma.to_string() != ",";
86+
}
87+
});
88+
7589
let mut to_insert: Vec<SyntaxElement> = Vec::new();
76-
to_insert.push(make::token(T![,]).into());
77-
to_insert.push(make::tokens::single_space().into());
90+
if should_insert_comma {
91+
to_insert.push(make::token(T![,]).into());
92+
to_insert.push(make::tokens::single_space().into());
93+
}
7894
to_insert.extend(
7995
rhs.use_tree_list()?
8096
.syntax()
@@ -247,4 +263,22 @@ use {
247263
",
248264
);
249265
}
266+
267+
#[test]
268+
fn test_double_comma() {
269+
check_assist(
270+
merge_imports,
271+
r"
272+
use hyper::service::make_service_fn;
273+
use hyper::<|>{
274+
StatusCode,
275+
};
276+
",
277+
r"
278+
use hyper::{<|>
279+
StatusCode,
280+
service::make_service_fn};
281+
",
282+
)
283+
}
250284
}

0 commit comments

Comments
 (0)