use of com.jetbrains.python.codeInsight.imports.PyImportOptimizer in project intellij-community by JetBrains.
the class PyMoveFileHandler method retargetUsages.
@Override
public void retargetUsages(List<UsageInfo> usages, Map<PsiElement, PsiElement> oldToNewMap) {
final Set<PsiFile> updatedFiles = new HashSet<>();
for (UsageInfo usage : usages) {
final PsiElement usageElement = usage.getElement();
if (usageElement != null) {
final PsiNamedElement movedElement = usageElement.getCopyableUserData(REFERENCED_ELEMENT);
usageElement.putCopyableUserData(REFERENCED_ELEMENT, null);
if (movedElement != null) {
final PsiFile usageFile = usageElement.getContainingFile();
final PyImportStatementBase importStmt = PsiTreeUtil.getParentOfType(usageElement, PyImportStatementBase.class);
// TODO: Retarget qualified expressions in docstrings
if (importStmt != null) {
if (usageFile.getUserData(ORIGINAL_FILE_LOCATION) != null) {
// Leave relative imports as they are after #updateRelativeImportsInModule
final TypeEvalContext typeEvalContext = TypeEvalContext.userInitiated(usageFile.getProject(), usageFile);
final PyResolveContext resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(typeEvalContext);
if (ContainerUtil.getFirstItem(PyUtil.multiResolveTopPriority(usageElement, resolveContext)) == movedElement) {
continue;
}
}
updatedFiles.add(usageFile);
final boolean usageInsideImportElement = PsiTreeUtil.getParentOfType(usageElement, PyImportElement.class) != null;
if (usageInsideImportElement) {
// or simple unqualified import of the module (import module).
if (PyClassRefactoringUtil.updateUnqualifiedImportOfElement(importStmt, movedElement)) {
continue;
}
}
final QualifiedName newElementName = QualifiedNameFinder.findCanonicalImportPath(movedElement, usageElement);
if (importStmt instanceof PyFromImportStatement) {
if (!usageInsideImportElement) {
replaceRelativeImportSourceWithQualifiedExpression((PyFromImportStatement) importStmt, newElementName);
}
} else {
replaceWithQualifiedExpression(usageElement, newElementName);
}
} else if (usageElement instanceof PyReferenceExpression) {
updatedFiles.add(usageFile);
if (((PyReferenceExpression) usageElement).isQualified()) {
final QualifiedName newQualifiedName = QualifiedNameFinder.findCanonicalImportPath(movedElement, usageElement);
replaceWithQualifiedExpression(usageElement, newQualifiedName);
} else {
final QualifiedName newName = QualifiedName.fromComponents(PyClassRefactoringUtil.getOriginalName(movedElement));
replaceWithQualifiedExpression(usageElement, newName);
}
}
}
}
}
if (!updatedFiles.isEmpty()) {
final PyImportOptimizer optimizer = new PyImportOptimizer();
for (PsiFile file : updatedFiles) {
final boolean injectedFragment = InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file);
if (!injectedFragment) {
optimizer.processFile(file).run();
}
}
}
}
Aggregations