]> git.lizzy.rs Git - rust.git/commitdiff
Fix double comma when merge imports on second line
authorIceSentry <c.giguere42@gmail.com>
Mon, 13 Apr 2020 01:29:14 +0000 (21:29 -0400)
committerIceSentry <c.giguere42@gmail.com>
Mon, 13 Apr 2020 01:29:14 +0000 (21:29 -0400)
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

crates/ra_assists/src/handlers/merge_imports.rs

index 0958f52f1f7bafe7d5707beefdf354f6c8d1e9b6..ab1fb2a0b82c0f71d07202970a8b2337f6ea60bb 100644 (file)
@@ -3,7 +3,8 @@
 use ra_syntax::{
     algo::{neighbor, SyntaxRewriter},
     ast::{self, edit::AstNodeEdit, make},
-    AstNode, Direction, InsertPosition, SyntaxElement, T,
+    AstNode, Direction, InsertPosition, NodeOrToken, SyntaxElement, SyntaxKind, SyntaxToken, Token,
+    T,
 };
 
 use crate::{Assist, AssistCtx, AssistId};
@@ -72,9 +73,24 @@ fn try_merge_trees(old: &ast::UseTree, new: &ast::UseTree) -> Option<ast::UseTre
     let lhs = old.split_prefix(&lhs_prefix);
     let rhs = new.split_prefix(&rhs_prefix);
 
+    let mut should_insert_comma = true;
+
+    lhs.syntax()
+        .last_child()
+        .and_then(|child| child.children().last())
+        .and_then(|last| last.next_sibling_or_token())
+        .map(|next_sibling| {
+            // FIXME: there's probably a better way to check if it's a COMMA
+            if let NodeOrToken::Token(maybe_comma) = next_sibling {
+                should_insert_comma = maybe_comma.to_string() != ",";
+            }
+        });
+
     let mut to_insert: Vec<SyntaxElement> = Vec::new();
-    to_insert.push(make::token(T![,]).into());
-    to_insert.push(make::tokens::single_space().into());
+    if should_insert_comma {
+        to_insert.push(make::token(T![,]).into());
+        to_insert.push(make::tokens::single_space().into());
+    }
     to_insert.extend(
         rhs.use_tree_list()?
             .syntax()
@@ -247,4 +263,22 @@ fn works_with_trailing_comma() {
 ",
         );
     }
+
+    #[test]
+    fn test_double_comma() {
+        check_assist(
+            merge_imports,
+            r"
+use hyper::service::make_service_fn;
+use hyper::<|>{
+    StatusCode,
+};
+",
+            r"
+use hyper::{<|>
+    StatusCode,
+service::make_service_fn};
+",
+        )
+    }
 }