PY-23104 Inline multiline "name as alias" pairs in optimize imports

This commit is contained in:
Mikhail Golubev
2017-03-15 21:53:28 +03:00
parent b882f53851
commit 87d31be6c5
4 changed files with 28 additions and 1 deletions

View File

@@ -206,7 +206,7 @@ public class PyImportOptimizer implements ImportOptimizer {
if (myPySettings.OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS) {
Collections.sort(newStatementElements, IMPORT_ELEMENT_COMPARATOR);
}
final String importedNames = StringUtil.join(newStatementElements, PsiElement::getText, ", ");
final String importedNames = StringUtil.join(newStatementElements, ImportSorter::getNormalizedImportElementText, ", ");
final PyFromImportStatement combinedImport = generator.createFromImportStatement(langLevel, source, importedNames, null);
ContainerUtil.map2LinkedSet(newStatementElements, e -> (PyImportStatementBase)e.getParent()).forEach(affected -> {
myNewImportToLineComments.putValues(combinedImport, precedingComments.get(affected));
@@ -222,6 +222,12 @@ public class PyImportOptimizer implements ImportOptimizer {
}
return result;
}
@NotNull
private static String getNormalizedImportElementText(@NotNull PyImportElement element) {
// Remove comments, line feeds and backslashes
return element.getText().replaceAll("#.*", "").replaceAll("[\\s\\\\]+", " ");
}
@NotNull
private static List<PsiComment> collectPrecedingLineComments(@NotNull PyImportStatementBase statement) {

View File

@@ -0,0 +1,3 @@
from collections import deque as d, OrderedDict as od, namedtuple # comment 1; comment 2
print(d, od, namedtuple)

View File

@@ -0,0 +1,12 @@
from collections import (
deque \
# comment 1
as d,
OrderedDict as
# comment 2
od,
)
from collections import namedtuple
print(d, od, namedtuple)

View File

@@ -267,6 +267,12 @@ public class PyOptimizeImportsTest extends PyTestCase {
doTest();
}
// PY-23104
public void testMultilineImportElementsInCombinedFromImports() {
getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true;
doTest();
}
private void doTest() {
myFixture.configureByFile(getTestName(true) + ".py");
OptimizeImportsAction.actionPerformedImpl(DataManager.getInstance().getDataContext(myFixture.getEditor().getContentComponent()));