Search in sources :

Example 46 with PsiFile

use of com.intellij.psi.PsiFile in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoTestFunctionCompletionProvider method addCompletions.

@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
    Project project = parameters.getPosition().getProject();
    PsiFile file = parameters.getOriginalFile();
    PsiDirectory containingDirectory = file.getContainingDirectory();
    if (file instanceof GoFile && containingDirectory != null) {
        CompletionResultSet resultSet = result.withPrefixMatcher(new CamelHumpMatcher(result.getPrefixMatcher().getPrefix(), false));
        Collection<String> allPackageFunctionNames = collectAllFunctionNames(containingDirectory);
        Set<String> allTestFunctionNames = collectAllTestNames(allPackageFunctionNames, project, (GoFile) file);
        String fileNameWithoutTestPrefix = StringUtil.trimEnd(file.getName(), GoConstants.TEST_SUFFIX_WITH_EXTENSION) + ".go";
        GlobalSearchScope packageScope = GoPackageUtil.packageScope(containingDirectory, ((GoFile) file).getCanonicalPackageName());
        GlobalSearchScope scope = new GoUtil.ExceptTestsScope(packageScope);
        IdFilter idFilter = GoIdFilter.getFilesFilter(scope);
        for (String functionName : allPackageFunctionNames) {
            GoFunctionIndex.process(functionName, project, scope, idFilter, declaration -> {
                addVariants(declaration, functionName, fileNameWithoutTestPrefix, allTestFunctionNames, resultSet);
                return false;
            });
        }
        Collection<String> methodKeys = ContainerUtil.newTroveSet();
        StubIndex.getInstance().processAllKeys(GoMethodIndex.KEY, new CancellableCollectProcessor<>(methodKeys), scope, idFilter);
        for (String key : methodKeys) {
            Processor<GoMethodDeclaration> processor = declaration -> {
                GoMethodDeclarationStubElementType.calcTypeText(declaration);
                String typeText = key.substring(Math.min(key.indexOf('.') + 1, key.length()));
                String methodName = declaration.getName();
                if (methodName != null) {
                    if (!declaration.isPublic() || declaration.isBlank()) {
                        return true;
                    }
                    String lookupString = !typeText.isEmpty() ? StringUtil.capitalize(typeText) + "_" + methodName : methodName;
                    addVariants(declaration, lookupString, fileNameWithoutTestPrefix, allTestFunctionNames, resultSet);
                }
                return true;
            };
            GoMethodIndex.process(key, project, scope, idFilter, processor);
        }
    }
}
Also used : com.goide.psi(com.goide.psi) Document(com.intellij.openapi.editor.Document) GoMethodIndex(com.goide.stubs.index.GoMethodIndex) GotestGenerateAction(com.goide.runconfig.testing.frameworks.gotest.GotestGenerateAction) IdFilter(com.intellij.util.indexing.IdFilter) StubIndex(com.intellij.psi.stubs.StubIndex) ContainerUtil(com.intellij.util.containers.ContainerUtil) GoTestFunctionType(com.goide.runconfig.testing.GoTestFunctionType) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) GoMethodDeclarationStubElementType(com.goide.stubs.types.GoMethodDeclarationStubElementType) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) GoElementFactory(com.goide.psi.impl.GoElementFactory) CamelHumpMatcher(com.intellij.codeInsight.completion.impl.CamelHumpMatcher) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) ProcessingContext(com.intellij.util.ProcessingContext) GoFunctionIndex(com.goide.stubs.index.GoFunctionIndex) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) LookupElement(com.intellij.codeInsight.lookup.LookupElement) StringUtil(com.intellij.openapi.util.text.StringUtil) Collection(java.util.Collection) GoUtil(com.goide.util.GoUtil) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Set(java.util.Set) UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator) com.intellij.codeInsight.completion(com.intellij.codeInsight.completion) GoIdFilter(com.goide.stubs.index.GoIdFilter) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) Processor(com.intellij.util.Processor) GoConstants(com.goide.GoConstants) PsiDirectory(com.intellij.psi.PsiDirectory) GoPackageUtil(com.goide.sdk.GoPackageUtil) NotNull(org.jetbrains.annotations.NotNull) IdFilter(com.intellij.util.indexing.IdFilter) GoIdFilter(com.goide.stubs.index.GoIdFilter) CamelHumpMatcher(com.intellij.codeInsight.completion.impl.CamelHumpMatcher) Project(com.intellij.openapi.project.Project) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) PsiDirectory(com.intellij.psi.PsiDirectory) PsiFile(com.intellij.psi.PsiFile)

Example 47 with PsiFile

use of com.intellij.psi.PsiFile in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoFmtCheckinFactory method createHandler.

@Override
@NotNull
public CheckinHandler createHandler(@NotNull CheckinProjectPanel panel, @NotNull CommitContext commitContext) {
    return new CheckinHandler() {

        @Override
        public RefreshableOnComponent getBeforeCheckinConfigurationPanel() {
            JCheckBox checkBox = new JCheckBox("Go fmt");
            return new RefreshableOnComponent() {

                @Override
                @NotNull
                public JComponent getComponent() {
                    JPanel panel = new JPanel(new BorderLayout());
                    panel.add(checkBox, BorderLayout.WEST);
                    return panel;
                }

                @Override
                public void refresh() {
                }

                @Override
                public void saveState() {
                    PropertiesComponent.getInstance(panel.getProject()).setValue(GO_FMT, Boolean.toString(checkBox.isSelected()));
                }

                @Override
                public void restoreState() {
                    checkBox.setSelected(enabled(panel));
                }
            };
        }

        @Override
        public ReturnResult beforeCheckin(@Nullable CommitExecutor executor, PairConsumer<Object, Object> additionalDataConsumer) {
            if (enabled(panel)) {
                Ref<Boolean> success = Ref.create(true);
                FileDocumentManager.getInstance().saveAllDocuments();
                for (PsiFile file : getPsiFiles()) {
                    VirtualFile virtualFile = file.getVirtualFile();
                    new GoFmtFileAction().doSomething(virtualFile, ModuleUtilCore.findModuleForPsiElement(file), file.getProject(), "Go fmt", true, result -> {
                        if (!result)
                            success.set(false);
                    });
                }
                if (!success.get()) {
                    return showErrorMessage(executor);
                }
            }
            return super.beforeCheckin();
        }

        @NotNull
        private ReturnResult showErrorMessage(@Nullable CommitExecutor executor) {
            String[] buttons = new String[] { "&Details...", commitButtonMessage(executor, panel), CommonBundle.getCancelButtonText() };
            int answer = Messages.showDialog(panel.getProject(), "<html><body>GoFmt returned non-zero code on some of the files.<br/>" + "Would you like to commit anyway?</body></html>\n", "Go Fmt", null, buttons, 0, 1, UIUtil.getWarningIcon());
            if (answer == Messages.OK) {
                return ReturnResult.CLOSE_WINDOW;
            }
            if (answer == Messages.NO) {
                return ReturnResult.COMMIT;
            }
            return ReturnResult.CANCEL;
        }

        @NotNull
        private List<PsiFile> getPsiFiles() {
            Collection<VirtualFile> files = panel.getVirtualFiles();
            List<PsiFile> psiFiles = ContainerUtil.newArrayList();
            PsiManager manager = PsiManager.getInstance(panel.getProject());
            for (VirtualFile file : files) {
                PsiFile psiFile = manager.findFile(file);
                if (psiFile instanceof GoFile) {
                    psiFiles.add(psiFile);
                }
            }
            return psiFiles;
        }
    };
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) GoFile(com.goide.psi.GoFile) PsiManager(com.intellij.psi.PsiManager) CheckinHandler(com.intellij.openapi.vcs.checkin.CheckinHandler) CommitExecutor(com.intellij.openapi.vcs.changes.CommitExecutor) PairConsumer(com.intellij.util.PairConsumer) RefreshableOnComponent(com.intellij.openapi.vcs.ui.RefreshableOnComponent) PsiFile(com.intellij.psi.PsiFile) Nullable(org.jetbrains.annotations.Nullable) NotNull(org.jetbrains.annotations.NotNull)

Example 48 with PsiFile

use of com.intellij.psi.PsiFile in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoExcludePathLookupActionProvider method fillActions.

@Override
public void fillActions(LookupElement element, Lookup lookup, Consumer<LookupElementAction> consumer) {
    PsiElement psiElement = element.getPsiElement();
    PsiFile file = psiElement != null && psiElement.isValid() ? psiElement.getContainingFile() : null;
    String importPath = file instanceof GoFile ? ((GoFile) file).getImportPath(false) : null;
    if (importPath != null) {
        Project project = psiElement.getProject();
        for (String path : getPaths(importPath)) {
            consumer.consume(new ExcludePathAction(project, path));
        }
        consumer.consume(new EditExcludedAction(project));
    }
}
Also used : GoFile(com.goide.psi.GoFile) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement)

Example 49 with PsiFile

use of com.intellij.psi.PsiFile in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoImportPackageQuickFix method getImportPathVariantsToImport.

@NotNull
public static List<String> getImportPathVariantsToImport(@NotNull String packageName, @NotNull PsiElement context) {
    PsiFile contextFile = context.getContainingFile();
    Set<String> imported = contextFile instanceof GoFile ? ((GoFile) contextFile).getImportedPackagesMap().keySet() : Collections.emptySet();
    Project project = context.getProject();
    PsiDirectory parentDirectory = contextFile != null ? contextFile.getParent() : null;
    String testTargetPackage = GoTestFinder.getTestTargetPackage(contextFile);
    Module module = contextFile != null ? ModuleUtilCore.findModuleForPsiElement(contextFile) : null;
    boolean vendoringEnabled = GoVendoringUtil.isVendoringEnabled(module);
    GlobalSearchScope scope = GoUtil.goPathResolveScope(context);
    Collection<GoFile> packages = StubIndex.getElements(GoPackagesIndex.KEY, packageName, project, scope, GoFile.class);
    return sorted(skipNulls(map2Set(packages, file -> {
        if (parentDirectory != null && parentDirectory.isEquivalentTo(file.getParent())) {
            if (testTargetPackage == null || !testTargetPackage.equals(file.getPackageName())) {
                return null;
            }
        }
        if (!GoPsiImplUtil.canBeAutoImported(file, false, module)) {
            return null;
        }
        String importPath = file.getImportPath(vendoringEnabled);
        return !imported.contains(importPath) ? importPath : null;
    })), new MyImportsComparator(context, vendoringEnabled));
}
Also used : GoFile(com.goide.psi.GoFile) Project(com.intellij.openapi.project.Project) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) PsiDirectory(com.intellij.psi.PsiDirectory) PsiFile(com.intellij.psi.PsiFile) Module(com.intellij.openapi.module.Module) NotNull(org.jetbrains.annotations.NotNull)

Example 50 with PsiFile

use of com.intellij.psi.PsiFile in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoImportPackageQuickFix method doAutoImportOrShowHint.

public boolean doAutoImportOrShowHint(@NotNull Editor editor, boolean showHint) {
    PsiElement element = getStartElement();
    if (element == null || !element.isValid())
        return false;
    PsiReference reference = getReference(element);
    if (reference == null || reference.resolve() != null)
        return false;
    List<String> packagesToImport = getImportPathVariantsToImport(element);
    if (packagesToImport.isEmpty()) {
        return false;
    }
    PsiFile file = element.getContainingFile();
    String firstPackageToImport = getFirstItem(packagesToImport);
    // autoimport on trying to fix
    if (packagesToImport.size() == 1) {
        if (GoCodeInsightSettings.getInstance().isAddUnambiguousImportsOnTheFly() && !LaterInvocator.isInModalContext() && (ApplicationManager.getApplication().isUnitTestMode() || DaemonListeners.canChangeFileSilently(file))) {
            CommandProcessor.getInstance().runUndoTransparentAction(() -> perform(file, firstPackageToImport));
            return true;
        }
    }
    // show hint on failed autoimport
    if (showHint) {
        if (ApplicationManager.getApplication().isUnitTestMode())
            return false;
        if (HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true))
            return false;
        if (!GoCodeInsightSettings.getInstance().isShowImportPopup())
            return false;
        TextRange referenceRange = reference.getRangeInElement().shiftRight(element.getTextRange().getStartOffset());
        HintManager.getInstance().showQuestionHint(editor, ShowAutoImportPass.getMessage(packagesToImport.size() > 1, getFirstItem(packagesToImport)), referenceRange.getStartOffset(), referenceRange.getEndOffset(), () -> {
            if (file.isValid() && !editor.isDisposed()) {
                perform(packagesToImport, file, editor);
            }
            return true;
        });
        return true;
    }
    return false;
}
Also used : PsiReference(com.intellij.psi.PsiReference) PsiFile(com.intellij.psi.PsiFile) TextRange(com.intellij.openapi.util.TextRange) LocalQuickFixAndIntentionActionOnPsiElement(com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement) PsiElement(com.intellij.psi.PsiElement)

Aggregations

PsiFile (com.intellij.psi.PsiFile)1785 VirtualFile (com.intellij.openapi.vfs.VirtualFile)496 PsiElement (com.intellij.psi.PsiElement)468 Project (com.intellij.openapi.project.Project)267 Nullable (org.jetbrains.annotations.Nullable)267 NotNull (org.jetbrains.annotations.NotNull)248 Document (com.intellij.openapi.editor.Document)181 Editor (com.intellij.openapi.editor.Editor)168 XmlFile (com.intellij.psi.xml.XmlFile)126 PsiDirectory (com.intellij.psi.PsiDirectory)114 PsiDocumentManager (com.intellij.psi.PsiDocumentManager)109 Module (com.intellij.openapi.module.Module)108 TextRange (com.intellij.openapi.util.TextRange)88 ArrayList (java.util.ArrayList)84 XmlTag (com.intellij.psi.xml.XmlTag)68 File (java.io.File)58 PsiManager (com.intellij.psi.PsiManager)56 PsiClass (com.intellij.psi.PsiClass)51 List (java.util.List)46 Language (com.intellij.lang.Language)45