Search in sources :

Example 1 with LintRequest

use of com.android.tools.lint.client.api.LintRequest in project android by JetBrains.

the class TemplateTest method assertLintsCleanly.

private static void assertLintsCleanly(@NotNull Project project, @NotNull Severity maxSeverity, @NotNull Set<Issue> ignored) throws Exception {
    BuiltinIssueRegistry registry = new LintIdeIssueRegistry();
    Map<Issue, Map<File, List<ProblemData>>> map = new HashMap<>();
    LintIdeClient client = LintIdeClient.forBatch(project, map, new AnalysisScope(project), registry.getIssues());
    LintDriver driver = new LintDriver(registry, client);
    List<Module> modules = Arrays.asList(ModuleManager.getInstance(project).getModules());
    LintRequest request = new LintIdeRequest(client, project, null, modules, false);
    EnumSet<Scope> scope = EnumSet.allOf(Scope.class);
    scope.remove(Scope.CLASS_FILE);
    scope.remove(Scope.ALL_CLASS_FILES);
    scope.remove(Scope.JAVA_LIBRARIES);
    request.setScope(scope);
    driver.analyze(request);
    if (!map.isEmpty()) {
        for (Map<File, List<ProblemData>> fileListMap : map.values()) {
            for (Map.Entry<File, List<ProblemData>> entry : fileListMap.entrySet()) {
                File file = entry.getKey();
                List<ProblemData> problems = entry.getValue();
                for (ProblemData problem : problems) {
                    Issue issue = problem.getIssue();
                    if (ignored.contains(issue)) {
                        continue;
                    }
                    if (issue.getDefaultSeverity().compareTo(maxSeverity) < 0) {
                        fail("Found lint issue " + issue.getId() + " with severity " + issue.getDefaultSeverity() + " in " + file + " at " + problem.getTextRange() + ": " + problem.getMessage());
                    }
                }
            }
        }
    }
}
Also used : Issue(com.android.tools.lint.detector.api.Issue) LintIdeClient(com.android.tools.idea.lint.LintIdeClient) ProblemData(org.jetbrains.android.inspections.lint.ProblemData) AnalysisScope(com.intellij.analysis.AnalysisScope) LintRequest(com.android.tools.lint.client.api.LintRequest) Scope(com.android.tools.lint.detector.api.Scope) AnalysisScope(com.intellij.analysis.AnalysisScope) BuiltinIssueRegistry(com.android.tools.lint.checks.BuiltinIssueRegistry) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) VfsUtilCore.virtualToIoFile(com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile) File(java.io.File) LintIdeIssueRegistry(com.android.tools.idea.lint.LintIdeIssueRegistry) LintIdeRequest(com.android.tools.idea.lint.LintIdeRequest) LintDriver(com.android.tools.lint.client.api.LintDriver)

Example 2 with LintRequest

use of com.android.tools.lint.client.api.LintRequest in project android by JetBrains.

the class UnusedResourcesProcessor method computeUnusedMap.

@NotNull
private Map<Issue, Map<File, List<ProblemData>>> computeUnusedMap() {
    Map<Issue, Map<File, List<ProblemData>>> map = Maps.newHashMap();
    List<Issue> issues = Lists.newArrayListWithExpectedSize(2);
    issues.add(UnusedResourceDetector.ISSUE);
    if (myIncludeIds) {
        issues.add(UnusedResourceDetector.ISSUE_IDS);
    }
    AnalysisScope scope = new AnalysisScope(myProject);
    boolean unusedWasEnabled = UnusedResourceDetector.ISSUE.isEnabledByDefault();
    boolean unusedIdsWasEnabled = UnusedResourceDetector.ISSUE_IDS.isEnabledByDefault();
    UnusedResourceDetector.ISSUE.setEnabledByDefault(true);
    UnusedResourceDetector.ISSUE_IDS.setEnabledByDefault(myIncludeIds);
    try {
        LintIdeClient client = LintIdeClient.forBatch(myProject, map, scope, issues);
        LintRequest request = new LintIdeRequest(client, myProject, null, Arrays.asList(myModules), false);
        request.setScope(Scope.ALL);
        LintDriver lint = new LintDriver(new LintIdeIssueRegistry(), client);
        lint.analyze(request);
    } finally {
        UnusedResourceDetector.ISSUE.setEnabledByDefault(unusedWasEnabled);
        UnusedResourceDetector.ISSUE_IDS.setEnabledByDefault(unusedIdsWasEnabled);
    }
    return map;
}
Also used : AnalysisScope(com.intellij.analysis.AnalysisScope) LintRequest(com.android.tools.lint.client.api.LintRequest) Issue(com.android.tools.lint.detector.api.Issue) LintIdeClient(com.android.tools.idea.lint.LintIdeClient) Map(java.util.Map) LintIdeRequest(com.android.tools.idea.lint.LintIdeRequest) LintIdeIssueRegistry(com.android.tools.idea.lint.LintIdeIssueRegistry) ProblemData(org.jetbrains.android.inspections.lint.ProblemData) LintDriver(com.android.tools.lint.client.api.LintDriver) NotNull(org.jetbrains.annotations.NotNull)

Example 3 with LintRequest

use of com.android.tools.lint.client.api.LintRequest in project android by JetBrains.

the class AndroidLintGlobalInspectionContext method performPreRunActivities.

@Override
public void performPreRunActivities(@NotNull List<Tools> globalTools, @NotNull List<Tools> localTools, @NotNull final GlobalInspectionContext context) {
    final Project project = context.getProject();
    // Running a single inspection that's not lint? If so don't run lint
    if (localTools.isEmpty() && globalTools.size() == 1) {
        Tools tool = globalTools.get(0);
        if (!tool.getShortName().startsWith(LINT_INSPECTION_PREFIX)) {
            return;
        }
    }
    if (!ProjectFacetManager.getInstance(project).hasFacets(AndroidFacet.ID)) {
        return;
    }
    List<Issue> issues = AndroidLintExternalAnnotator.getIssuesFromInspections(project, null);
    if (issues.size() == 0) {
        return;
    }
    // If running a single check by name, turn it on if it's off by default.
    if (localTools.isEmpty() && globalTools.size() == 1) {
        Tools tool = globalTools.get(0);
        String id = tool.getShortName().substring(LINT_INSPECTION_PREFIX.length());
        Issue issue = new LintIdeIssueRegistry().getIssue(id);
        if (issue != null && !issue.isEnabledByDefault()) {
            issues = Collections.singletonList(issue);
            issue.setEnabledByDefault(true);
            // And turn it back off again in cleanup
            myEnabledIssue = issue;
        }
    }
    final Map<Issue, Map<File, List<ProblemData>>> problemMap = new HashMap<>();
    AnalysisScope scope = context.getRefManager().getScope();
    if (scope == null) {
        scope = AndroidLintLintBaselineInspection.ourRerunScope;
        if (scope == null) {
            return;
        }
    }
    final LintIdeClient client = LintIdeClient.forBatch(project, problemMap, scope, issues);
    final LintDriver lint = new LintDriver(new LintIdeIssueRegistry(), client);
    final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    if (indicator != null) {
        ProgressWrapper.unwrap(indicator).setText("Running Android Lint");
    }
    EnumSet<Scope> lintScope;
    //noinspection ConstantConditions
    if (!LintIdeProject.SUPPORT_CLASS_FILES) {
        lintScope = EnumSet.copyOf(Scope.ALL);
        // Can't run class file based checks
        lintScope.remove(Scope.CLASS_FILE);
        lintScope.remove(Scope.ALL_CLASS_FILES);
        lintScope.remove(Scope.JAVA_LIBRARIES);
    } else {
        lintScope = Scope.ALL;
    }
    List<VirtualFile> files = null;
    final List<Module> modules = Lists.newArrayList();
    int scopeType = scope.getScopeType();
    switch(scopeType) {
        case AnalysisScope.MODULE:
            {
                SearchScope searchScope = ReadAction.compute(scope::toSearchScope);
                if (searchScope instanceof ModuleWithDependenciesScope) {
                    ModuleWithDependenciesScope s = (ModuleWithDependenciesScope) searchScope;
                    if (!s.isSearchInLibraries()) {
                        modules.add(s.getModule());
                    }
                }
                break;
            }
        case AnalysisScope.FILE:
        case AnalysisScope.VIRTUAL_FILES:
        case AnalysisScope.UNCOMMITTED_FILES:
            {
                files = Lists.newArrayList();
                SearchScope searchScope = scope.toSearchScope();
                if (searchScope instanceof LocalSearchScope) {
                    final LocalSearchScope localSearchScope = (LocalSearchScope) searchScope;
                    final PsiElement[] elements = localSearchScope.getScope();
                    final List<VirtualFile> finalFiles = files;
                    ApplicationManager.getApplication().runReadAction(() -> {
                        for (PsiElement element : elements) {
                            if (element instanceof PsiFile) {
                                // should be the case since scope type is FILE
                                Module module = ModuleUtilCore.findModuleForPsiElement(element);
                                if (module != null && !modules.contains(module)) {
                                    modules.add(module);
                                }
                                VirtualFile virtualFile = ((PsiFile) element).getVirtualFile();
                                if (virtualFile != null) {
                                    if (virtualFile instanceof StringsVirtualFile) {
                                        StringsVirtualFile f = (StringsVirtualFile) virtualFile;
                                        if (!modules.contains(f.getFacet().getModule())) {
                                            modules.add(f.getFacet().getModule());
                                        }
                                    } else {
                                        finalFiles.add(virtualFile);
                                    }
                                }
                            }
                        }
                    });
                } else {
                    final List<VirtualFile> finalList = files;
                    scope.accept(new PsiElementVisitor() {

                        @Override
                        public void visitFile(PsiFile file) {
                            VirtualFile virtualFile = file.getVirtualFile();
                            if (virtualFile != null) {
                                finalList.add(virtualFile);
                            }
                        }
                    });
                }
                if (files.isEmpty()) {
                    files = null;
                } else {
                    // Lint will compute it lazily based on actual files in the request
                    lintScope = null;
                }
                break;
            }
        case AnalysisScope.PROJECT:
            {
                modules.addAll(Arrays.asList(ModuleManager.getInstance(project).getModules()));
                break;
            }
        case AnalysisScope.CUSTOM:
        case AnalysisScope.MODULES:
        case AnalysisScope.DIRECTORY:
            {
                // Handled by the getNarrowedComplementaryScope case below
                break;
            }
        case AnalysisScope.INVALID:
            break;
        default:
            Logger.getInstance(this.getClass()).warn("Unexpected inspection scope " + scope + ", " + scopeType);
    }
    if (modules.isEmpty()) {
        for (Module module : ModuleManager.getInstance(project).getModules()) {
            if (scope.containsModule(module)) {
                modules.add(module);
            }
        }
        if (modules.isEmpty() && files != null) {
            for (VirtualFile file : files) {
                Module module = ModuleUtilCore.findModuleForFile(file, project);
                if (module != null && !modules.contains(module)) {
                    modules.add(module);
                }
            }
        }
        if (modules.isEmpty()) {
            AnalysisScope narrowed = scope.getNarrowedComplementaryScope(project);
            for (Module module : ModuleManager.getInstance(project).getModules()) {
                if (narrowed.containsModule(module)) {
                    modules.add(module);
                }
            }
        }
    }
    LintRequest request = new LintIdeRequest(client, project, files, modules, false);
    request.setScope(lintScope);
    // Baseline analysis?
    myBaseline = null;
    for (Module module : modules) {
        AndroidModuleModel model = AndroidModuleModel.get(module);
        if (model != null) {
            GradleVersion version = model.getModelVersion();
            if (version != null && version.isAtLeast(2, 3, 0, "beta", 2, true)) {
                LintOptions options = model.getAndroidProject().getLintOptions();
                try {
                    File baselineFile = options.getBaselineFile();
                    if (baselineFile != null && !AndroidLintLintBaselineInspection.ourSkipBaselineNextRun) {
                        if (!baselineFile.isAbsolute()) {
                            String path = module.getProject().getBasePath();
                            if (path != null) {
                                baselineFile = new File(FileUtil.toSystemDependentName(path), baselineFile.getPath());
                            }
                        }
                        myBaseline = new LintBaseline(client, baselineFile);
                        lint.setBaseline(myBaseline);
                        if (!baselineFile.isFile()) {
                            myBaseline.setWriteOnClose(true);
                        } else if (AndroidLintLintBaselineInspection.ourUpdateBaselineNextRun) {
                            myBaseline.setRemoveFixed(true);
                            myBaseline.setWriteOnClose(true);
                        }
                    }
                } catch (Throwable unsupported) {
                // During 2.3 development some builds may have this method, others may not
                }
            }
            break;
        }
    }
    lint.analyze(request);
    AndroidLintLintBaselineInspection.clearNextRunState();
    myResults = problemMap;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) StringsVirtualFile(com.android.tools.idea.editors.strings.StringsVirtualFile) Issue(com.android.tools.lint.detector.api.Issue) HashMap(com.intellij.util.containers.HashMap) LintOptions(com.android.builder.model.LintOptions) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) AnalysisScope(com.intellij.analysis.AnalysisScope) LintRequest(com.android.tools.lint.client.api.LintRequest) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) PsiFile(com.intellij.psi.PsiFile) GradleVersion(com.android.ide.common.repository.GradleVersion) PsiElement(com.intellij.psi.PsiElement) LintDriver(com.android.tools.lint.client.api.LintDriver) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) ModuleWithDependenciesScope(com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope) Tools(com.intellij.codeInspection.ex.Tools) LintBaseline(com.android.tools.lint.client.api.LintBaseline) com.android.tools.idea.lint(com.android.tools.idea.lint) Project(com.intellij.openapi.project.Project) ModuleWithDependenciesScope(com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Scope(com.android.tools.lint.detector.api.Scope) AnalysisScope(com.intellij.analysis.AnalysisScope) StringsVirtualFile(com.android.tools.idea.editors.strings.StringsVirtualFile) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) Module(com.intellij.openapi.module.Module) HashMap(com.intellij.util.containers.HashMap) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) StringsVirtualFile(com.android.tools.idea.editors.strings.StringsVirtualFile)

Example 4 with LintRequest

use of com.android.tools.lint.client.api.LintRequest in project android by JetBrains.

the class AndroidLintExternalAnnotator method doAnnotate.

@Override
public State doAnnotate(final State state) {
    final LintIdeClient client = LintIdeClient.forEditor(state);
    try {
        final LintDriver lint = new LintDriver(new LintIdeIssueRegistry(), client);
        EnumSet<Scope> scope;
        VirtualFile mainFile = state.getMainFile();
        final FileType fileType = mainFile.getFileType();
        String name = mainFile.getName();
        if (fileType == StdFileTypes.XML) {
            if (name.equals(ANDROID_MANIFEST_XML)) {
                scope = Scope.MANIFEST_SCOPE;
            } else {
                scope = Scope.RESOURCE_FILE_SCOPE;
            }
        } else if (fileType == StdFileTypes.JAVA) {
            scope = Scope.JAVA_FILE_SCOPE;
        } else if (name.equals(OLD_PROGUARD_FILE) || name.equals(FN_PROJECT_PROGUARD_FILE)) {
            scope = EnumSet.of(Scope.PROGUARD_FILE);
        } else if (fileType == GroovyFileType.GROOVY_FILE_TYPE) {
            scope = Scope.GRADLE_SCOPE;
        } else if (fileType == StdFileTypes.PROPERTIES) {
            scope = Scope.PROPERTY_SCOPE;
        } else {
            // #collectionInformation above should have prevented this
            assert false;
            return state;
        }
        Project project = state.getModule().getProject();
        if (project.isDisposed()) {
            return state;
        }
        List<VirtualFile> files = Collections.singletonList(mainFile);
        LintRequest request = new LintIdeRequest(client, project, files, Collections.singletonList(state.getModule()), true);
        request.setScope(scope);
        lint.analyze(request);
    } finally {
        Disposer.dispose(client);
    }
    return state;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) LintRequest(com.android.tools.lint.client.api.LintRequest) Project(com.intellij.openapi.project.Project) Scope(com.android.tools.lint.detector.api.Scope) GroovyFileType(org.jetbrains.plugins.groovy.GroovyFileType) FileType(com.intellij.openapi.fileTypes.FileType) LintDriver(com.android.tools.lint.client.api.LintDriver)

Example 5 with LintRequest

use of com.android.tools.lint.client.api.LintRequest in project android by JetBrains.

the class LintIdeUtils method getPsiFile.

/**
   * Returns the {@link PsiFile} associated with a given lint {@link Context}
   *
   * @param context the context to look up the file for
   * @return the corresponding {@link PsiFile}, or null
   */
@Nullable
public static PsiFile getPsiFile(@NonNull Context context) {
    LintRequest request = context.getDriver().getRequest();
    Project project = ((LintIdeRequest) request).getProject();
    if (project.isDisposed()) {
        return null;
    }
    VirtualFile file = VfsUtil.findFileByIoFile(context.file, false);
    if (file == null) {
        return null;
    }
    return AndroidPsiUtils.getPsiFileSafely(project, file);
}
Also used : LintRequest(com.android.tools.lint.client.api.LintRequest) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Project(com.intellij.openapi.project.Project) Nullable(com.android.annotations.Nullable)

Aggregations

LintRequest (com.android.tools.lint.client.api.LintRequest)5 LintDriver (com.android.tools.lint.client.api.LintDriver)4 VirtualFile (com.intellij.openapi.vfs.VirtualFile)4 Issue (com.android.tools.lint.detector.api.Issue)3 Scope (com.android.tools.lint.detector.api.Scope)3 AnalysisScope (com.intellij.analysis.AnalysisScope)3 Project (com.intellij.openapi.project.Project)3 LintIdeClient (com.android.tools.idea.lint.LintIdeClient)2 LintIdeIssueRegistry (com.android.tools.idea.lint.LintIdeIssueRegistry)2 LintIdeRequest (com.android.tools.idea.lint.LintIdeRequest)2 Module (com.intellij.openapi.module.Module)2 File (java.io.File)2 ProblemData (org.jetbrains.android.inspections.lint.ProblemData)2 Nullable (com.android.annotations.Nullable)1 LintOptions (com.android.builder.model.LintOptions)1 GradleVersion (com.android.ide.common.repository.GradleVersion)1 StringsVirtualFile (com.android.tools.idea.editors.strings.StringsVirtualFile)1 AndroidModuleModel (com.android.tools.idea.gradle.project.model.AndroidModuleModel)1 com.android.tools.idea.lint (com.android.tools.idea.lint)1 BuiltinIssueRegistry (com.android.tools.lint.checks.BuiltinIssueRegistry)1