Search in sources :

Example 6 with AnalysisScope

use of com.intellij.analysis.AnalysisScope in project intellij-community by JetBrains.

the class RunInspectionAction method runInspection.

public static void runInspection(@NotNull final Project project, @NotNull String shortName, @Nullable VirtualFile virtualFile, PsiElement psiElement, PsiFile psiFile) {
    final PsiElement element = psiFile == null ? psiElement : psiFile;
    final InspectionProfile currentProfile = InspectionProjectProfileManager.getInstance(project).getCurrentProfile();
    final InspectionToolWrapper toolWrapper = element != null ? currentProfile.getInspectionTool(shortName, element) : currentProfile.getInspectionTool(shortName, project);
    LOGGER.assertTrue(toolWrapper != null, "Missed inspection: " + shortName);
    final InspectionManagerEx managerEx = (InspectionManagerEx) InspectionManager.getInstance(project);
    final Module module = virtualFile != null ? ModuleUtilCore.findModuleForFile(virtualFile, project) : null;
    AnalysisScope analysisScope = null;
    if (psiFile != null) {
        analysisScope = new AnalysisScope(psiFile);
    } else {
        if (virtualFile != null && virtualFile.isDirectory()) {
            final PsiDirectory psiDirectory = PsiManager.getInstance(project).findDirectory(virtualFile);
            if (psiDirectory != null) {
                analysisScope = new AnalysisScope(psiDirectory);
            }
        }
        if (analysisScope == null && virtualFile != null) {
            analysisScope = new AnalysisScope(project, Arrays.asList(virtualFile));
        }
        if (analysisScope == null) {
            analysisScope = new AnalysisScope(project);
        }
    }
    final AnalysisUIOptions options = AnalysisUIOptions.getInstance(project);
    final FileFilterPanel fileFilterPanel = new FileFilterPanel();
    fileFilterPanel.init(options);
    final AnalysisScope initialAnalysisScope = analysisScope;
    final BaseAnalysisActionDialog dialog = new BaseAnalysisActionDialog("Run '" + toolWrapper.getDisplayName() + "'", AnalysisScopeBundle.message("analysis.scope.title", InspectionsBundle.message("inspection.action.noun")), project, analysisScope, module != null ? module.getName() : null, true, options, psiElement) {

        private InspectionToolWrapper myUpdatedSettingsToolWrapper;

        @Nullable
        @Override
        protected JComponent getAdditionalActionSettings(Project project) {
            final JPanel fileFilter = fileFilterPanel.getPanel();
            if (toolWrapper.getTool().createOptionsPanel() != null) {
                JPanel additionPanel = new JPanel();
                additionPanel.setLayout(new BoxLayout(additionPanel, BoxLayout.Y_AXIS));
                additionPanel.add(fileFilter);
                //new InheritOptionsForToolPanel(toolWrapper.getShortName(), project);
                myUpdatedSettingsToolWrapper = copyToolWithSettings(toolWrapper);
                additionPanel.add(new TitledSeparator(IdeBundle.message("goto.inspection.action.choose.inherit.settings.from")));
                JComponent optionsPanel = myUpdatedSettingsToolWrapper.getTool().createOptionsPanel();
                LOGGER.assertTrue(optionsPanel != null);
                if (UIUtil.hasScrollPane(optionsPanel)) {
                    additionPanel.add(optionsPanel);
                } else {
                    additionPanel.add(ScrollPaneFactory.createScrollPane(optionsPanel, SideBorder.NONE));
                }
                return additionPanel;
            } else {
                return fileFilter;
            }
        }

        @NotNull
        @Override
        public AnalysisScope getScope(@NotNull AnalysisUIOptions uiOptions, @NotNull AnalysisScope defaultScope, @NotNull Project project, Module module) {
            final AnalysisScope scope = super.getScope(uiOptions, defaultScope, project, module);
            final GlobalSearchScope filterScope = fileFilterPanel.getSearchScope();
            if (filterScope == null) {
                return scope;
            }
            scope.setFilter(filterScope);
            return scope;
        }

        private AnalysisScope getScope() {
            return getScope(options, initialAnalysisScope, project, module);
        }

        private InspectionToolWrapper getToolWrapper() {
            return myUpdatedSettingsToolWrapper == null ? toolWrapper : myUpdatedSettingsToolWrapper;
        }

        @NotNull
        @Override
        protected Action[] createActions() {
            final List<Action> actions = new ArrayList<>();
            final boolean hasFixAll = toolWrapper.getTool() instanceof CleanupLocalInspectionTool;
            actions.add(new AbstractAction(hasFixAll ? AnalysisScopeBundle.message("action.analyze.verb") : CommonBundle.getOkButtonText()) {

                {
                    putValue(DEFAULT_ACTION, Boolean.TRUE);
                }

                @Override
                public void actionPerformed(ActionEvent e) {
                    RunInspectionIntention.rerunInspection(getToolWrapper(), managerEx, getScope(), null);
                    close(DialogWrapper.OK_EXIT_CODE);
                }
            });
            if (hasFixAll) {
                actions.add(new AbstractAction("Fix All") {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        InspectionToolWrapper wrapper = getToolWrapper();
                        InspectionProfileImpl cleanupToolProfile = RunInspectionIntention.createProfile(wrapper, managerEx, null);
                        managerEx.createNewGlobalContext(false).codeCleanup(getScope(), cleanupToolProfile, "Cleanup by " + wrapper.getDisplayName(), null, false);
                        close(DialogWrapper.OK_EXIT_CODE);
                    }
                });
            }
            actions.add(getCancelAction());
            if (SystemInfo.isMac) {
                Collections.reverse(actions);
            }
            return actions.toArray(new Action[actions.size()]);
        }
    };
    dialog.showAndGet();
}
Also used : InspectionProfileImpl(com.intellij.codeInspection.ex.InspectionProfileImpl) ActionEvent(java.awt.event.ActionEvent) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) ArrayList(java.util.ArrayList) NotNull(org.jetbrains.annotations.NotNull) BaseAnalysisActionDialog(com.intellij.analysis.BaseAnalysisActionDialog) AnalysisScope(com.intellij.analysis.AnalysisScope) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) AnalysisUIOptions(com.intellij.analysis.AnalysisUIOptions) InspectionProfile(com.intellij.codeInspection.InspectionProfile) InspectionManagerEx(com.intellij.codeInspection.ex.InspectionManagerEx) Project(com.intellij.openapi.project.Project) CleanupLocalInspectionTool(com.intellij.codeInspection.CleanupLocalInspectionTool) TitledSeparator(com.intellij.ui.TitledSeparator) Module(com.intellij.openapi.module.Module) InspectionToolWrapper(com.intellij.codeInspection.ex.InspectionToolWrapper)

Example 7 with AnalysisScope

use of com.intellij.analysis.AnalysisScope in project intellij-community by JetBrains.

the class RunInspectionIntention method invoke.

@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    final Module module = file != null ? ModuleUtilCore.findModuleForPsiElement(file) : null;
    AnalysisScope analysisScope = new AnalysisScope(project);
    if (file != null) {
        final VirtualFile virtualFile = file.getVirtualFile();
        if (file.isPhysical() && virtualFile != null && virtualFile.isInLocalFileSystem()) {
            analysisScope = new AnalysisScope(file);
        }
    }
    selectScopeAndRunInspection(myShortName, analysisScope, module, file, project);
}
Also used : AnalysisScope(com.intellij.analysis.AnalysisScope) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Module(com.intellij.openapi.module.Module)

Example 8 with AnalysisScope

use of com.intellij.analysis.AnalysisScope in project intellij-community by JetBrains.

the class InspectionApplication method run.

private void run() {
    File tmpDir = null;
    try {
        myProjectPath = myProjectPath.replace(File.separatorChar, '/');
        VirtualFile vfsProject = LocalFileSystem.getInstance().findFileByPath(myProjectPath);
        if (vfsProject == null) {
            logError(InspectionsBundle.message("inspection.application.file.cannot.be.found", myProjectPath));
            printHelp();
        }
        logMessage(1, InspectionsBundle.message("inspection.application.opening.project"));
        final ConversionService conversionService = ConversionService.getInstance();
        if (conversionService.convertSilently(myProjectPath, createConversionListener()).openingIsCanceled()) {
            gracefulExit();
            return;
        }
        myProject = ProjectUtil.openOrImport(myProjectPath, null, false);
        if (myProject == null) {
            logError("Unable to open project");
            gracefulExit();
            return;
        }
        ApplicationManager.getApplication().runWriteAction(() -> VirtualFileManager.getInstance().refreshWithoutFileWatcher(false));
        PatchProjectUtil.patchProject(myProject);
        logMessageLn(1, InspectionsBundle.message("inspection.done"));
        logMessage(1, InspectionsBundle.message("inspection.application.initializing.project"));
        InspectionProfileImpl inspectionProfile = loadInspectionProfile();
        if (inspectionProfile == null)
            return;
        final InspectionManagerEx im = (InspectionManagerEx) InspectionManager.getInstance(myProject);
        im.createNewGlobalContext(true).setExternalProfile(inspectionProfile);
        im.setProfile(inspectionProfile.getName());
        final AnalysisScope scope;
        if (mySourceDirectory == null) {
            final String scopeName = System.getProperty("idea.analyze.scope");
            final NamedScope namedScope = scopeName != null ? NamedScopesHolder.getScope(myProject, scopeName) : null;
            scope = namedScope != null ? new AnalysisScope(GlobalSearchScopesCore.filterScope(myProject, namedScope), myProject) : new AnalysisScope(myProject);
        } else {
            mySourceDirectory = mySourceDirectory.replace(File.separatorChar, '/');
            VirtualFile vfsDir = LocalFileSystem.getInstance().findFileByPath(mySourceDirectory);
            if (vfsDir == null) {
                logError(InspectionsBundle.message("inspection.application.directory.cannot.be.found", mySourceDirectory));
                printHelp();
            }
            PsiDirectory psiDirectory = PsiManager.getInstance(myProject).findDirectory(vfsDir);
            scope = new AnalysisScope(psiDirectory);
        }
        logMessageLn(1, InspectionsBundle.message("inspection.done"));
        if (!myRunWithEditorSettings) {
            logMessageLn(1, InspectionsBundle.message("inspection.application.chosen.profile.log.message", inspectionProfile.getName()));
        }
        InspectionsReportConverter reportConverter = getReportConverter(myOutputFormat);
        if (reportConverter == null && myOutputFormat != null && myOutputFormat.endsWith(".xsl")) {
            // xslt converter
            reportConverter = new XSLTReportConverter(myOutputFormat);
        }
        final String resultsDataPath;
        if (// use default xml converter(if null( or don't store default xml report in tmp dir
        (reportConverter == null || !reportConverter.useTmpDirForRawData()) && myOutPath != null) {
            // and don't use STDOUT stream
            resultsDataPath = myOutPath;
        } else {
            try {
                tmpDir = FileUtil.createTempDirectory("inspections", "data");
                resultsDataPath = tmpDir.getPath();
            } catch (IOException e) {
                LOG.error(e);
                System.err.println("Cannot create tmp directory.");
                System.exit(1);
                return;
            }
        }
        final List<File> inspectionsResults = new ArrayList<>();
        ProgressManager.getInstance().runProcess(() -> {
            if (!GlobalInspectionContextUtil.canRunInspections(myProject, false)) {
                gracefulExit();
                return;
            }
            im.createNewGlobalContext(true).launchInspectionsOffline(scope, resultsDataPath, myRunGlobalToolsOnly, inspectionsResults);
            logMessageLn(1, "\n" + InspectionsBundle.message("inspection.capitalized.done") + "\n");
            if (!myErrorCodeRequired) {
                closeProject();
            }
        }, new ProgressIndicatorBase() {

            private String lastPrefix = "";

            private int myLastPercent = -1;

            @Override
            public void setText(String text) {
                if (myVerboseLevel == 0)
                    return;
                if (myVerboseLevel == 1) {
                    String prefix = getPrefix(text);
                    if (prefix == null)
                        return;
                    if (prefix.equals(lastPrefix)) {
                        logMessage(1, ".");
                        return;
                    }
                    lastPrefix = prefix;
                    logMessageLn(1, "");
                    logMessageLn(1, prefix);
                    return;
                }
                if (myVerboseLevel == 3) {
                    if (!isIndeterminate() && getFraction() > 0) {
                        final int percent = (int) (getFraction() * 100);
                        if (myLastPercent == percent)
                            return;
                        String prefix = getPrefix(text);
                        myLastPercent = percent;
                        String msg = (prefix != null ? prefix : InspectionsBundle.message("inspection.display.name")) + " " + percent + "%";
                        logMessageLn(2, msg);
                    }
                    return;
                }
                logMessageLn(2, text);
            }
        });
        final String descriptionsFile = resultsDataPath + File.separatorChar + DESCRIPTIONS + XML_EXTENSION;
        describeInspections(descriptionsFile, myRunWithEditorSettings ? null : inspectionProfile.getName(), inspectionProfile);
        inspectionsResults.add(new File(descriptionsFile));
        // convert report
        if (reportConverter != null) {
            try {
                reportConverter.convert(resultsDataPath, myOutPath, im.createNewGlobalContext(true).getTools(), inspectionsResults);
            } catch (InspectionsReportConverter.ConversionException e) {
                logError("\n" + e.getMessage());
                printHelp();
            }
        }
    } catch (IOException e) {
        LOG.error(e);
        logError(e.getMessage());
        printHelp();
    } catch (Throwable e) {
        LOG.error(e);
        logError(e.getMessage());
        gracefulExit();
    } finally {
        // delete tmp dir
        if (tmpDir != null) {
            FileUtil.delete(tmpDir);
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) IOException(java.io.IOException) AnalysisScope(com.intellij.analysis.AnalysisScope) NamedScope(com.intellij.psi.search.scope.packageSet.NamedScope) ProgressIndicatorBase(com.intellij.openapi.progress.util.ProgressIndicatorBase) ConversionService(com.intellij.conversion.ConversionService) PsiDirectory(com.intellij.psi.PsiDirectory) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 9 with AnalysisScope

use of com.intellij.analysis.AnalysisScope in project intellij-community by JetBrains.

the class ShowModuleDependenciesAction method actionPerformed.

@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    if (project == null)
        return;
    Module[] modules = LangDataKeys.MODULE_CONTEXT_ARRAY.getData(e.getDataContext());
    if (modules == null) {
        PsiElement element = CommonDataKeys.PSI_FILE.getData(e.getDataContext());
        Module module = element != null ? ModuleUtilCore.findModuleForPsiElement(element) : null;
        if (module != null && ModuleManager.getInstance(project).getModules().length > 1) {
            MyModuleOrProjectScope dlg = new MyModuleOrProjectScope(module.getName());
            if (!dlg.showAndGet()) {
                return;
            }
            if (!dlg.useProjectScope()) {
                modules = new Module[] { module };
            }
        }
    }
    ModulesDependenciesPanel panel = new ModulesDependenciesPanel(project, modules);
    AnalysisScope scope = modules != null ? new AnalysisScope(modules) : new AnalysisScope(project);
    Content content = ContentFactory.SERVICE.getInstance().createContent(panel, scope.getDisplayName(), false);
    content.setDisposer(panel);
    panel.setContent(content);
    DependenciesAnalyzeManager.getInstance(project).addContent(content);
}
Also used : AnalysisScope(com.intellij.analysis.AnalysisScope) Project(com.intellij.openapi.project.Project) Content(com.intellij.ui.content.Content) Module(com.intellij.openapi.module.Module) PsiElement(com.intellij.psi.PsiElement)

Example 10 with AnalysisScope

use of com.intellij.analysis.AnalysisScope in project intellij-community by JetBrains.

the class UnusedParametersInspection method queryExternalUsagesRequests.

protected boolean queryExternalUsagesRequests(@NotNull final RefManager manager, @NotNull final GlobalJavaInspectionContext globalContext, @NotNull final ProblemDescriptionsProcessor processor) {
    final Project project = manager.getProject();
    for (RefElement entryPoint : globalContext.getEntryPointsManager(manager).getEntryPoints()) {
        processor.ignoreElement(entryPoint);
    }
    final PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(project);
    final AnalysisScope scope = manager.getScope();
    manager.iterate(new RefJavaVisitor() {

        @Override
        public void visitElement(@NotNull RefEntity refEntity) {
            if (refEntity instanceof RefMethod) {
                RefMethod refMethod = (RefMethod) refEntity;
                final PsiModifierListOwner element = refMethod.getElement();
                if (element instanceof PsiMethod) {
                    //implicit constructors are invisible
                    PsiMethod psiMethod = (PsiMethod) element;
                    if (!refMethod.isStatic() && !refMethod.isConstructor() && !PsiModifier.PRIVATE.equals(refMethod.getAccessModifier())) {
                        final ArrayList<RefParameter> unusedParameters = getUnusedParameters(refMethod);
                        if (unusedParameters.isEmpty())
                            return;
                        PsiMethod[] derived = OverridingMethodsSearch.search(psiMethod).toArray(PsiMethod.EMPTY_ARRAY);
                        for (final RefParameter refParameter : unusedParameters) {
                            if (refMethod.isAbstract() && derived.length == 0) {
                                refParameter.parameterReferenced(false);
                                processor.ignoreElement(refParameter);
                            } else {
                                int idx = refParameter.getIndex();
                                final boolean[] found = { false };
                                for (int i = 0; i < derived.length && !found[0]; i++) {
                                    if (scope == null || !scope.contains(derived[i])) {
                                        final PsiParameter[] parameters = derived[i].getParameterList().getParameters();
                                        if (parameters.length >= idx)
                                            continue;
                                        PsiParameter psiParameter = parameters[idx];
                                        ReferencesSearch.search(psiParameter, helper.getUseScope(psiParameter), false).forEach(new PsiReferenceProcessorAdapter(new PsiReferenceProcessor() {

                                            @Override
                                            public boolean execute(PsiReference element) {
                                                refParameter.parameterReferenced(false);
                                                processor.ignoreElement(refParameter);
                                                found[0] = true;
                                                return false;
                                            }
                                        }));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    });
    return false;
}
Also used : ArrayList(java.util.ArrayList) PsiSearchHelper(com.intellij.psi.search.PsiSearchHelper) AnalysisScope(com.intellij.analysis.AnalysisScope) Project(com.intellij.openapi.project.Project) PsiReferenceProcessor(com.intellij.psi.search.PsiReferenceProcessor) PsiReferenceProcessorAdapter(com.intellij.psi.search.PsiReferenceProcessorAdapter)

Aggregations

AnalysisScope (com.intellij.analysis.AnalysisScope)56 Module (com.intellij.openapi.module.Module)14 VirtualFile (com.intellij.openapi.vfs.VirtualFile)13 JavaAnalysisScope (com.intellij.analysis.JavaAnalysisScope)12 Project (com.intellij.openapi.project.Project)12 NotNull (org.jetbrains.annotations.NotNull)10 PsiPackage (com.intellij.psi.PsiPackage)8 File (java.io.File)8 CyclicDependenciesBuilder (com.intellij.cyclicDependencies.CyclicDependenciesBuilder)7 PsiElement (com.intellij.psi.PsiElement)6 LocalSearchScope (com.intellij.psi.search.LocalSearchScope)6 Nullable (org.jetbrains.annotations.Nullable)6 AnalysisUIOptions (com.intellij.analysis.AnalysisUIOptions)5 BaseAnalysisActionDialog (com.intellij.analysis.BaseAnalysisActionDialog)5 PsiFile (com.intellij.psi.PsiFile)4 SearchScope (com.intellij.psi.search.SearchScope)4 HashMap (com.intellij.util.containers.HashMap)4 LintDriver (com.android.tools.lint.client.api.LintDriver)3 LintRequest (com.android.tools.lint.client.api.LintRequest)3 Issue (com.android.tools.lint.detector.api.Issue)3