private void addImportStatement(ImportCandidateHolder item) { final Project project = myTarget.getProject(); final PyElementGenerator gen = PyElementGenerator.getInstance(project); AddImportHelper.ImportPriority priority = AddImportHelper.getImportPriority(myTarget, item.getFile()); PsiFile file = myTarget.getContainingFile(); InjectedLanguageManager manager = InjectedLanguageManager.getInstance(project); if (manager.isInjectedFragment(file)) { file = manager.getTopLevelFile(myTarget); } // We are trying to import top-level module or package which thus cannot be qualified if (isRoot(item.getFile())) { if (myImportLocally) { AddImportHelper.addLocalImportStatement(myTarget, myName); } else { AddImportHelper.addImportStatement(file, myName, item.getAsName(), priority, null); } } else { final QualifiedName path = item.getPath(); final String qualifiedName = path != null ? path.toString() : ""; if (myUseQualifiedImport) { String nameToImport = qualifiedName; if (item.getImportable() instanceof PsiFileSystemItem) { nameToImport += "." + myName; } if (myImportLocally) { AddImportHelper.addLocalImportStatement(myTarget, nameToImport); } else { AddImportHelper.addImportStatement(file, nameToImport, item.getAsName(), priority, null); } myTarget.replace( gen.createExpressionFromText( LanguageLevel.forElement(myTarget), qualifiedName + "." + myName)); } else { if (myImportLocally) { AddImportHelper.addLocalFromImportStatement(myTarget, qualifiedName, myName); } else { AddImportHelper.addFromImportStatement( file, qualifiedName, myName, item.getAsName(), priority, null); } } } }
/** * Alters either target (by qualifying a name) or source (by explicitly importing the name). * * @return true if action succeeded */ public boolean execute() { // check if the tree is sane PsiDocumentManager.getInstance(myTarget.getProject()).commitAllDocuments(); if (!myTarget.isValid()) return false; if ((myTarget instanceof PyQualifiedExpression) && ((((PyQualifiedExpression) myTarget).isQualified()))) return false; // we cannot be qualified for (ImportCandidateHolder item : mySources) { if (!item.getImportable().isValid()) return false; if (!item.getFile().isValid()) return false; if (item.getImportElement() != null && !item.getImportElement().isValid()) return false; } if (mySources.isEmpty()) { return false; } // act if (mySources.size() > 1) { selectSourceAndDo(); } else doWriteAction(mySources.get(0)); return true; }