Search in sources :

Example 1 with GoImportSpec

use of com.goide.psi.GoImportSpec in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoInvalidPackageImportInspection method checkFile.

@Override
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) {
    Module module = ModuleUtilCore.findModuleForPsiElement(file);
    VirtualFile sdkHome = GoSdkUtil.getSdkSrcDir(file.getProject(), module);
    boolean supportsVendoring = GoVendoringUtil.isVendoringEnabled(module);
    String sdkVersion = GoSdkService.getInstance(file.getProject()).getSdkVersion(module);
    boolean supportsInternalPackages = GoVendoringUtil.supportsInternalPackages(sdkVersion);
    boolean supportsInternalPackagesInSdk = sdkHome != null && GoVendoringUtil.supportsSdkInternalPackages(sdkVersion);
    for (GoImportSpec importSpec : file.getImports()) {
        if (importSpec.isCImport()) {
            PsiElement dot = importSpec.getDot();
            if (dot != null) {
                problemsHolder.registerProblem(importSpec, "Cannot rename import `C`", new GoDeleteImportSpecAlias(), new GoDeleteImportQuickFix());
            }
            PsiElement identifier = importSpec.getIdentifier();
            if (identifier != null) {
                problemsHolder.registerProblem(importSpec, "Cannot import 'builtin' package", new GoDeleteImportSpecAlias(), new GoDeleteImportQuickFix());
            }
            continue;
        }
        PsiDirectory resolve = importSpec.getImportString().resolve();
        if (resolve != null) {
            if (GoPackageUtil.isBuiltinPackage(resolve)) {
                problemsHolder.registerProblem(importSpec, "Cannot import 'builtin' package", new GoDeleteImportQuickFix());
            }
            Collection<String> packagesInDirectory = GoPackageUtil.getAllPackagesInDirectory(resolve, module, true);
            if (packagesInDirectory.isEmpty()) {
                problemsHolder.registerProblem(importSpec, "'" + resolve.getVirtualFile().getPath() + "' has no buildable Go source files", new GoDeleteImportQuickFix());
                continue;
            }
            if (!GoTestFinder.isTestFile(file) && packagesInDirectory.size() == 1 && packagesInDirectory.contains(GoConstants.MAIN)) {
                problemsHolder.registerProblem(importSpec, "'" + importSpec.getPath() + "' is a program, not an importable package", new GoDeleteImportQuickFix());
                continue;
            }
            if (packagesInDirectory.size() > 1) {
                problemsHolder.registerProblem(importSpec, "Found several packages [" + StringUtil.join(packagesInDirectory, ", ") + "] in '" + resolve.getVirtualFile().getPath() + "'", new GoDeleteImportQuickFix());
                continue;
            }
            VirtualFile contextFile = file.getVirtualFile();
            VirtualFile resolvedFile = resolve.getVirtualFile();
            boolean resolvedToSdk = sdkHome != null && VfsUtilCore.isAncestor(sdkHome, resolvedFile, false);
            boolean validateInternal = supportsInternalPackages || supportsInternalPackagesInSdk && resolvedToSdk;
            if (supportsVendoring || validateInternal || resolvedToSdk) {
                Set<VirtualFile> sourceRoots = GoSdkUtil.getSourcesPathsToLookup(file.getProject(), module);
                for (PsiReference reference : importSpec.getImportString().getReferences()) {
                    if (reference instanceof GoImportReference) {
                        String canonicalText = reference.getCanonicalText();
                        if (resolvedToSdk && GoConstants.TESTDATA_NAME.equals(canonicalText)) {
                            problemsHolder.registerProblem(importSpec, "Use of testdata package from SDK is not allowed", new GoDeleteImportQuickFix());
                            break;
                        } else if (validateInternal && GoConstants.INTERNAL.equals(canonicalText)) {
                            if (GoSdkUtil.isUnreachableInternalPackage(resolvedFile, contextFile, sourceRoots)) {
                                problemsHolder.registerProblem(importSpec, "Use of internal package is not allowed", new GoDeleteImportQuickFix());
                                break;
                            }
                        } else if (supportsVendoring && GoConstants.VENDOR.equals(canonicalText)) {
                            if (GoSdkUtil.isUnreachableVendoredPackage(resolvedFile, contextFile, sourceRoots)) {
                                problemsHolder.registerProblem(importSpec, "Use of vendored package is not allowed", new GoDeleteImportQuickFix(), GoDisableVendoringInModuleQuickFix.create(module));
                                break;
                            } else {
                                String vendoredImportPath = GoSdkUtil.getImportPath(resolve, true);
                                if (vendoredImportPath != null) {
                                    problemsHolder.registerProblem(importSpec, "Must be imported as '" + vendoredImportPath + "'", new GoReplaceImportPath(vendoredImportPath), new GoDeleteImportQuickFix(), GoDisableVendoringInModuleQuickFix.create(module));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        } else {
            for (PsiReference reference : importSpec.getImportString().getReferences()) {
                if (reference instanceof GoImportReference) {
                    if (((GoImportReference) reference).getFileReferenceSet().isAbsolutePathReference()) {
                        problemsHolder.registerProblem(importSpec, "Cannot import absolute path", new GoDeleteImportQuickFix());
                        break;
                    }
                }
            }
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) GoDeleteImportQuickFix(com.goide.quickfix.GoDeleteImportQuickFix) GoImportSpec(com.goide.psi.GoImportSpec) PsiReference(com.intellij.psi.PsiReference) PsiDirectory(com.intellij.psi.PsiDirectory) Module(com.intellij.openapi.module.Module) PsiElement(com.intellij.psi.PsiElement) GoImportReference(com.goide.psi.impl.imports.GoImportReference)

Example 2 with GoImportSpec

use of com.goide.psi.GoImportSpec in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoPathUseScope method contains.

@Override
public boolean contains(@NotNull VirtualFile referenceFile) {
    VirtualFile referenceDirectory = referenceFile.isDirectory() ? referenceFile : referenceFile.getParent();
    if (referenceDirectory == null) {
        return false;
    }
    VirtualFile declarationDirectory = myDeclarationFile.getParent();
    if (referenceDirectory.equals(declarationDirectory)) {
        return true;
    }
    Project project = ObjectUtils.assertNotNull(getProject());
    PsiManager psiManager = PsiManager.getInstance(project);
    PsiFile referencePsiFile = psiManager.findFile(referenceFile);
    Module module = referencePsiFile != null ? ModuleUtilCore.findModuleForPsiElement(referencePsiFile) : null;
    GoPathScopeHelper scopeHelper = GoPathScopeHelper.fromReferenceFile(project, module, referenceFile);
    if (!scopeHelper.couldBeReferenced(myDeclarationFile, referenceFile)) {
        return false;
    }
    if (!myFilterByImportList) {
        return true;
    }
    if (!(referencePsiFile instanceof GoFile)) {
        // it's some injection or cross-reference, so we cannot check its imports
        return true;
    }
    PsiFile declarationPsiFile = psiManager.findFile(myDeclarationFile);
    if (declarationPsiFile instanceof GoFile) {
        String importPath = ((GoFile) declarationPsiFile).getImportPath(scopeHelper.isVendoringEnabled());
        Map<String, GoImportSpec> importedPackagesMap = ((GoFile) referencePsiFile).getImportedPackagesMap();
        if (importedPackagesMap.containsKey(importPath)) {
            return true;
        }
        if (hasRelativeImportOfTargetPackage(importedPackagesMap.keySet(), referenceDirectory, declarationDirectory)) {
            return true;
        }
        for (GoFile packageFile : GoPackageUtil.getAllPackageFiles(referencePsiFile.getContainingDirectory(), null)) {
            if (packageFile != referencePsiFile && referencePsiFile.getOriginalFile() != packageFile) {
                Map<String, GoImportSpec> packagesMap = packageFile.getImportedPackagesMap();
                if (packagesMap.containsKey(importPath)) {
                    return true;
                }
                if (hasRelativeImportOfTargetPackage(packagesMap.keySet(), referenceDirectory, declarationDirectory)) {
                    return true;
                }
            }
        }
    }
    return false;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Project(com.intellij.openapi.project.Project) GoFile(com.goide.psi.GoFile) GoImportSpec(com.goide.psi.GoImportSpec) PsiManager(com.intellij.psi.PsiManager) PsiFile(com.intellij.psi.PsiFile) Module(com.intellij.openapi.module.Module)

Example 3 with GoImportSpec

use of com.goide.psi.GoImportSpec in project go-lang-idea-plugin by go-lang-plugin-org.

the class GotestGenerateAction method importTestingPackageIfNeeded.

@NotNull
public static String importTestingPackageIfNeeded(@NotNull GoFile file) {
    GoImportSpec alreadyImportedPackage = file.getImportedPackagesMap().get(GoConstants.TESTING_PATH);
    String qualifier = GoPsiImplUtil.getImportQualifierToUseInFile(alreadyImportedPackage, GoConstants.TESTING_PATH);
    if (qualifier != null) {
        return qualifier;
    }
    String localName = UniqueNameGenerator.generateUniqueName(GoConstants.TESTING_PATH, file.getImportMap().keySet());
    file.addImport(GoConstants.TESTING_PATH, !GoConstants.TESTING_PATH.equals(localName) ? localName : null);
    return localName;
}
Also used : GoImportSpec(com.goide.psi.GoImportSpec) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with GoImportSpec

use of com.goide.psi.GoImportSpec in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoUnusedImportInspection method checkFile.

@Override
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) {
    MultiMap<String, GoImportSpec> importMap = file.getImportMap();
    for (PsiElement importIdentifier : GoImportOptimizer.findRedundantImportIdentifiers(importMap)) {
        problemsHolder.registerProblem(importIdentifier, "Redundant alias", ProblemHighlightType.LIKE_UNUSED_SYMBOL, OPTIMIZE_QUICK_FIX);
    }
    Set<GoImportSpec> duplicatedEntries = GoImportOptimizer.findDuplicatedEntries(importMap);
    for (GoImportSpec duplicatedImportSpec : duplicatedEntries) {
        problemsHolder.registerProblem(duplicatedImportSpec, "Redeclared import", ProblemHighlightType.GENERIC_ERROR, OPTIMIZE_QUICK_FIX);
    }
    for (Map.Entry<String, Collection<GoImportSpec>> specs : importMap.entrySet()) {
        Iterator<GoImportSpec> imports = specs.getValue().iterator();
        GoImportSpec originalImport = imports.next();
        if (originalImport.isDot() || originalImport.isForSideEffects()) {
            continue;
        }
        while (imports.hasNext()) {
            GoImportSpec redeclaredImport = imports.next();
            if (!duplicatedEntries.contains(redeclaredImport)) {
                LocalQuickFix[] quickFixes = FindManager.getInstance(redeclaredImport.getProject()).canFindUsages(redeclaredImport) ? new LocalQuickFix[] { new GoRenameQuickFix(redeclaredImport) } : LocalQuickFix.EMPTY_ARRAY;
                problemsHolder.registerProblem(redeclaredImport, "Redeclared import", ProblemHighlightType.GENERIC_ERROR, quickFixes);
            }
        }
    }
    if (importMap.containsKey(".")) {
        if (!problemsHolder.isOnTheFly() || ApplicationManager.getApplication().isUnitTestMode())
            resolveAllReferences(file);
    }
    MultiMap<String, GoImportSpec> unusedImportsMap = GoImportOptimizer.filterUnusedImports(file, importMap);
    Set<GoImportSpec> unusedImportSpecs = ContainerUtil.newHashSet(unusedImportsMap.values());
    for (PsiElement importEntry : unusedImportSpecs) {
        GoImportSpec spec = GoImportOptimizer.getImportSpec(importEntry);
        if (spec != null && spec.getImportString().resolve() != null) {
            problemsHolder.registerProblem(spec, "Unused import", ProblemHighlightType.GENERIC_ERROR, OPTIMIZE_QUICK_FIX, IMPORT_FOR_SIDE_EFFECTS_QUICK_FIX);
        }
    }
}
Also used : GoRenameQuickFix(com.goide.quickfix.GoRenameQuickFix) GoImportSpec(com.goide.psi.GoImportSpec) Collection(java.util.Collection) Map(java.util.Map) MultiMap(com.intellij.util.containers.MultiMap) PsiElement(com.intellij.psi.PsiElement)

Example 5 with GoImportSpec

use of com.goide.psi.GoImportSpec in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoDeleteImportQuickFix method applyFix.

@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    PsiElement element = PsiTreeUtil.getNonStrictParentOfType(descriptor.getPsiElement(), GoImportSpec.class);
    PsiFile file = element != null ? element.getContainingFile() : null;
    if (!(file instanceof GoFile))
        return;
    WriteCommandAction.runWriteCommandAction(project, () -> ((GoFile) file).deleteImport((GoImportSpec) element));
}
Also used : GoFile(com.goide.psi.GoFile) GoImportSpec(com.goide.psi.GoImportSpec) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement)

Aggregations

GoImportSpec (com.goide.psi.GoImportSpec)5 PsiElement (com.intellij.psi.PsiElement)3 GoFile (com.goide.psi.GoFile)2 Module (com.intellij.openapi.module.Module)2 VirtualFile (com.intellij.openapi.vfs.VirtualFile)2 PsiFile (com.intellij.psi.PsiFile)2 GoImportReference (com.goide.psi.impl.imports.GoImportReference)1 GoDeleteImportQuickFix (com.goide.quickfix.GoDeleteImportQuickFix)1 GoRenameQuickFix (com.goide.quickfix.GoRenameQuickFix)1 Project (com.intellij.openapi.project.Project)1 PsiDirectory (com.intellij.psi.PsiDirectory)1 PsiManager (com.intellij.psi.PsiManager)1 PsiReference (com.intellij.psi.PsiReference)1 MultiMap (com.intellij.util.containers.MultiMap)1 Collection (java.util.Collection)1 Map (java.util.Map)1 NotNull (org.jetbrains.annotations.NotNull)1