Search in sources :

Example 56 with QualifiedName

use of com.intellij.psi.util.QualifiedName in project intellij-community by JetBrains.

the class AddImportHelper method addOrUpdateFromImportStatement.

/**
   * Adds new {@link PyFromImportStatement} in file or append {@link PyImportElement} to
   * existing from import statement.
   *
   * @param file     module where import will be added
   * @param from     import source (reference after {@code from} keyword)
   * @param name     imported name (identifier after {@code import} keyword)
   * @param asName   optional alias (identifier after {@code as} keyword)
   * @param priority optional import priority used to sort imports
   * @param anchor   place where the imported name was used. It will be used to determine proper block where new import should be inserted,
   *                 e.g. inside conditional block or try/except statement. Also if anchor is another import statement, new import statement
   *                 will be inserted right after it.
   * @return whether import was actually added
   * @see #addFromImportStatement
   */
public static boolean addOrUpdateFromImportStatement(@NotNull PsiFile file, @NotNull String from, @NotNull String name, @Nullable String asName, @Nullable ImportPriority priority, @Nullable PsiElement anchor) {
    final List<PyFromImportStatement> existingImports = ((PyFile) file).getFromImports();
    for (PyFromImportStatement existingImport : existingImports) {
        if (existingImport.isStarImport()) {
            continue;
        }
        final QualifiedName qName = existingImport.getImportSourceQName();
        if (qName != null && qName.toString().equals(from) && existingImport.getRelativeLevel() == 0) {
            for (PyImportElement el : existingImport.getImportElements()) {
                final QualifiedName importedQName = el.getImportedQName();
                if (importedQName != null && StringUtil.equals(name, importedQName.toString()) && StringUtil.equals(asName, el.getAsName())) {
                    return false;
                }
            }
            final PyElementGenerator generator = PyElementGenerator.getInstance(file.getProject());
            final PyImportElement importElement = generator.createImportElement(LanguageLevel.forElement(file), name, asName);
            existingImport.add(importElement);
            // May need to add parentheses, trailing comma, etc.
            CodeStyleManager.getInstance(file.getProject()).reformat(existingImport);
            return true;
        }
    }
    addFromImportStatement(file, from, name, asName, priority, anchor);
    return true;
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName)

Example 57 with QualifiedName

use of com.intellij.psi.util.QualifiedName in project intellij-community by JetBrains.

the class AddImportHelper method addImport.

/**
   * Adds either {@link PyFromImportStatement} or {@link PyImportStatement}
   * to specified target depending on user preferences and whether it's possible to import element via "from" form of import
   * (e.g. consider top level module).
   *
   * @param target  element import is pointing to
   * @param file    file where import will be inserted
   * @param element used to determine where to insert import
   * @see PyCodeInsightSettings#PREFER_FROM_IMPORT
   * @see #addImportStatement
   * @see #addOrUpdateFromImportStatement
   */
public static void addImport(final PsiNamedElement target, final PsiFile file, final PyElement element) {
    final boolean useQualified = !PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT;
    final PsiFileSystemItem toImport = target instanceof PsiFileSystemItem ? ((PsiFileSystemItem) target).getParent() : target.getContainingFile();
    if (toImport == null)
        return;
    final ImportPriority priority = getImportPriority(file, toImport);
    final QualifiedName qName = QualifiedNameFinder.findCanonicalImportPath(target, element);
    if (qName == null)
        return;
    String path = qName.toString();
    if (target instanceof PsiFileSystemItem && qName.getComponentCount() == 1) {
        addImportStatement(file, path, null, priority, element);
    } else {
        final QualifiedName toImportQName = QualifiedNameFinder.findCanonicalImportPath(toImport, element);
        if (toImportQName == null)
            return;
        if (useQualified) {
            addImportStatement(file, path, null, priority, element);
            final PyElementGenerator elementGenerator = PyElementGenerator.getInstance(file.getProject());
            final String targetName = PyUtil.getElementNameWithoutExtension(target);
            element.replace(elementGenerator.createExpressionFromText(LanguageLevel.forElement(target), toImportQName + "." + targetName));
        } else {
            final String name = target.getName();
            if (name != null)
                addOrUpdateFromImportStatement(file, toImportQName.toString(), name, null, priority, element);
        }
    }
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName)

Example 58 with QualifiedName

use of com.intellij.psi.util.QualifiedName in project intellij-community by JetBrains.

the class PyFromImportStatementImpl method getFullyQualifiedObjectNames.

@NotNull
@Override
public List<String> getFullyQualifiedObjectNames() {
    final QualifiedName source = getImportSourceQName();
    final String prefix = (source != null) ? (source.join(".") + '.') : "";
    final List<String> unqualifiedNames = PyImportStatementImpl.getImportElementNames(getImportElements());
    final List<String> result = new ArrayList<>(unqualifiedNames.size());
    for (final String unqualifiedName : unqualifiedNames) {
        result.add(prefix + unqualifiedName);
    }
    return result;
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName) ArrayList(java.util.ArrayList) NotNull(org.jetbrains.annotations.NotNull)

Example 59 with QualifiedName

use of com.intellij.psi.util.QualifiedName in project intellij-community by JetBrains.

the class PyUserSkeletonsUtil method getUserSkeletonForModuleQName.

@Nullable
public static PyFile getUserSkeletonForModuleQName(@NotNull String qName, @NotNull PsiElement foothold) {
    final Sdk sdk = PythonSdkType.findPythonSdk(foothold);
    if (sdk != null) {
        final Project project = foothold.getProject();
        final PythonSdkPathCache cache = PythonSdkPathCache.getInstance(project, sdk);
        final QualifiedName cacheQName = QualifiedName.fromDottedString(USER_SKELETONS_DIR + "." + qName);
        final List<PsiElement> results = cache.get(cacheQName);
        if (results != null) {
            final PsiElement element = results.isEmpty() ? null : results.get(0);
            if (element instanceof PyFile) {
                return (PyFile) element;
            }
        }
        final VirtualFile directory = getUserSkeletonsDirectory();
        if (directory != null) {
            final PsiDirectory psiDirectory = PsiManager.getInstance(project).findDirectory(directory);
            PsiElement fileSkeleton = PyResolveImportUtil.resolveModuleAt(QualifiedName.fromDottedString(qName), psiDirectory, PyResolveImportUtil.fromFoothold(foothold)).stream().findFirst().orElse(null);
            if (fileSkeleton instanceof PsiDirectory) {
                fileSkeleton = PyUtil.getPackageElement((PsiDirectory) fileSkeleton, foothold);
            }
            if (fileSkeleton instanceof PyFile) {
                cache.put(cacheQName, Collections.singletonList(fileSkeleton));
                return (PyFile) fileSkeleton;
            }
        }
        cache.put(cacheQName, Collections.<PsiElement>emptyList());
    }
    return null;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Project(com.intellij.openapi.project.Project) PsiDirectory(com.intellij.psi.PsiDirectory) QualifiedName(com.intellij.psi.util.QualifiedName) Sdk(com.intellij.openapi.projectRoots.Sdk) PsiElement(com.intellij.psi.PsiElement) Nullable(org.jetbrains.annotations.Nullable)

Example 60 with QualifiedName

use of com.intellij.psi.util.QualifiedName in project intellij-community by JetBrains.

the class PyPsiUtils method toPath.

@NotNull
public static String toPath(@Nullable PyQualifiedExpression expr) {
    if (expr != null) {
        final QualifiedName qName = expr.asQualifiedName();
        if (qName != null) {
            return qName.toString();
        }
        final String name = expr.getName();
        if (name != null) {
            return name;
        }
    }
    return "";
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

QualifiedName (com.intellij.psi.util.QualifiedName)63 Nullable (org.jetbrains.annotations.Nullable)22 NotNull (org.jetbrains.annotations.NotNull)17 VirtualFile (com.intellij.openapi.vfs.VirtualFile)9 Project (com.intellij.openapi.project.Project)8 ScopeOwner (com.jetbrains.python.codeInsight.controlflow.ScopeOwner)7 PsiElement (com.intellij.psi.PsiElement)6 ArrayList (java.util.ArrayList)5 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)4 Sdk (com.intellij.openapi.projectRoots.Sdk)3 PsiFile (com.intellij.psi.PsiFile)3 PsiDirectory (com.intellij.psi.PsiDirectory)2 PsiFileSystemItem (com.intellij.psi.PsiFileSystemItem)2 StringRef (com.intellij.util.io.StringRef)2 PyClass (com.jetbrains.python.psi.PyClass)2 PyFunction (com.jetbrains.python.psi.PyFunction)2 PyClassTypeImpl (com.jetbrains.python.psi.types.PyClassTypeImpl)2 TypeEvalContext (com.jetbrains.python.psi.types.TypeEvalContext)2 Instruction (com.intellij.codeInsight.controlflow.Instruction)1 InjectedLanguageManager (com.intellij.lang.injection.InjectedLanguageManager)1