PY-23968 Simplify the implementation using PyFromImportStatement#addBefore

Previously not functioning because of the bugs in the implementation of
PyFromImportStatementImpl#addInternal.

GitOrigin-RevId: fb70b6472f50ad98e5ba0cadda453b081ca0d9f1
This commit is contained in:
Mikhail Golubev
2020-03-06 14:07:46 +00:00
committed by intellij-monorepo-bot
parent 5e814f0e78
commit 14203deb33
@@ -588,24 +588,20 @@ public class AddImportHelper {
final PythonCodeStyleService pyCodeStyle = PythonCodeStyleService.getInstance();
final boolean shouldSort = pyCodeStyle.isOptimizeImportsSortImports(file) && pyCodeStyle.isOptimizeImportsSortNamesInFromImports(file);
PyImportElement precedingNameElement = null;
PyImportElement followingNameElement = null;
for (PyImportElement existingNameElement : fromImport.getImportElements()) {
final String existingName = Objects.toString(existingNameElement.getImportedQName(), "");
if (name.equals(existingName) && Comparing.equal(asName, existingNameElement.getAsName())) {
return false;
}
if (shouldSort && nameComparator.compare(existingName, name) < 0) {
precedingNameElement = existingNameElement;
if (shouldSort && followingNameElement == null && nameComparator.compare(existingName, name) > 0) {
followingNameElement = existingNameElement;
}
}
final PyElementGenerator generator = PyElementGenerator.getInstance(fromImport.getProject());
final PyImportElement newNameElement = generator.createImportElement(LanguageLevel.forElement(fromImport), name, asName);
if (shouldSort) {
fromImport.addAfter(newNameElement, precedingNameElement);
}
else {
fromImport.add(newNameElement);
}
// addBefore(newNameElement, null) is the same as inserting at the end
fromImport.addBefore(newNameElement, followingNameElement);
// May need to add parentheses, trailing comma, etc.
CodeStyleManager.getInstance(fromImport.getProject()).reformat(fromImport);
return true;