use of com.intellij.codeInspection.InspectionProfile in project intellij-community by JetBrains.
the class DaemonRespondToChangesTest method testPostHighlightingPassRunsOnEveryPsiModification.
public void testPostHighlightingPassRunsOnEveryPsiModification() throws Exception {
PsiFile x = createFile("X.java", "public class X { public static void ffffffffffffff(){} }");
PsiFile use = createFile("Use.java", "public class Use { { <caret>X.ffffffffffffff(); } }");
configureByExistingFile(use.getVirtualFile());
InspectionProfile profile = InspectionProjectProfileManager.getInstance(myProject).getCurrentProfile();
HighlightDisplayKey myDeadCodeKey = HighlightDisplayKey.find(UnusedDeclarationInspectionBase.SHORT_NAME);
if (myDeadCodeKey == null) {
myDeadCodeKey = HighlightDisplayKey.register(UnusedDeclarationInspectionBase.SHORT_NAME, UnusedDeclarationInspectionBase.DISPLAY_NAME);
}
UnusedDeclarationInspectionBase myDeadCodeInspection = new UnusedDeclarationInspectionBase(true);
enableInspectionTool(myDeadCodeInspection);
assert profile.isToolEnabled(myDeadCodeKey, myFile);
Editor xEditor = createEditor(x.getVirtualFile());
List<HighlightInfo> xInfos = filter(CodeInsightTestFixtureImpl.instantiateAndRun(x, xEditor, new int[0], false), HighlightSeverity.WARNING);
HighlightInfo info = ContainerUtil.find(xInfos, xInfo -> xInfo.getDescription().equals("Method 'ffffffffffffff()' is never used"));
assertNull(xInfos.toString(), info);
Editor useEditor = myEditor;
List<HighlightInfo> useInfos = filter(CodeInsightTestFixtureImpl.instantiateAndRun(use, useEditor, new int[0], false), HighlightSeverity.ERROR);
assertEmpty(useInfos);
type('/');
type('/');
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
xInfos = filter(CodeInsightTestFixtureImpl.instantiateAndRun(x, xEditor, new int[0], false), HighlightSeverity.WARNING);
info = ContainerUtil.find(xInfos, xInfo -> xInfo.getDescription().equals("Method 'ffffffffffffff()' is never used"));
assertNotNull(xInfos.toString(), info);
}
use of com.intellij.codeInspection.InspectionProfile in project android by JetBrains.
the class AndroidLintUtil method getHighlighLevelAndInspection.
@Nullable
public static Pair<AndroidLintInspectionBase, HighlightDisplayLevel> getHighlighLevelAndInspection(@NotNull Project project, @NotNull Issue issue, @NotNull PsiElement context) {
final String inspectionShortName = AndroidLintInspectionBase.getInspectionShortNameByIssue(project, issue);
if (inspectionShortName == null) {
return null;
}
final HighlightDisplayKey key = HighlightDisplayKey.find(inspectionShortName);
if (key == null) {
return null;
}
final InspectionProfile profile = InspectionProjectProfileManager.getInstance(context.getProject()).getCurrentProfile();
if (!profile.isToolEnabled(key, context)) {
if (!issue.isEnabledByDefault()) {
// Lint will skip issues (and not report them) for issues that have been disabled,
// except for those issues that are explicitly enabled via Gradle. Therefore, if
// we get this far, lint has found this issue to be explicitly enabled, so we let
// that setting override a local enabled/disabled state in the IDE profile.
} else {
return null;
}
}
final AndroidLintInspectionBase inspection = (AndroidLintInspectionBase) profile.getUnwrappedTool(inspectionShortName, context);
if (inspection == null)
return null;
final HighlightDisplayLevel errorLevel = profile.getErrorLevel(key, context);
return Pair.create(inspection, errorLevel != null ? errorLevel : HighlightDisplayLevel.WARNING);
}
use of com.intellij.codeInspection.InspectionProfile in project android by JetBrains.
the class AndroidLintInspectionToolProviderTest method checkAllLintChecksRegistered.
@SuppressWarnings("deprecation")
public static boolean checkAllLintChecksRegistered(Project project) throws Exception {
if (ourDone) {
return true;
}
ourDone = true;
// For some reason, I can't just use
// AndroidLintInspectionBase.getInspectionShortNameByIssue
// to iterate the available inspections from unit tests; at runtime this will enumerate all
// the available inspections, but from unit tests (even when extending IdeaTestCase) it's empty.
// So instead we take advantage of the knowledge that all our inspections are named in a particular
// way from the lint issue id's, so we can use reflection to find the classes.
// This won't catch cases if we declare a class there and forget to register in the plugin, but
// it's better than nothing.
Set<String> registered = Sets.newHashSetWithExpectedSize(200);
Set<Issue> quickfixes = Sets.newLinkedHashSetWithExpectedSize(200);
final LintIdeIssueRegistry fullRegistry = new LintIdeIssueRegistry();
List<Issue> allIssues = fullRegistry.getIssues();
for (Issue issue : allIssues) {
if (!isRelevant(issue)) {
continue;
}
String className = "com.android.tools.idea.lint.AndroidLint" + issue.getId() + "Inspection";
try {
Class<?> c = Class.forName(className);
if (AndroidLintInspectionBase.class.isAssignableFrom(c) && ((c.getModifiers() & Modifier.ABSTRACT) == 0)) {
AndroidLintInspectionBase provider = (AndroidLintInspectionBase) c.newInstance();
registered.add(provider.getIssue().getId());
boolean hasQuickFix = true;
try {
provider.getClass().getDeclaredMethod("getQuickFixes", String.class);
} catch (NoSuchMethodException e1) {
try {
provider.getClass().getDeclaredMethod("getQuickFixes", PsiElement.class, PsiElement.class, String.class);
} catch (NoSuchMethodException e2) {
hasQuickFix = false;
}
}
if (hasQuickFix) {
quickfixes.add(provider.getIssue());
}
}
} catch (ClassNotFoundException ignore) {
}
}
final List<Issue> missing = new ArrayList<>();
for (Issue issue : allIssues) {
if (!isRelevant(issue) || registered.contains(issue.getId())) {
continue;
}
// When enabled, adjust this to register class based registrations
assertFalse(LintIdeProject.SUPPORT_CLASS_FILES);
Implementation implementation = issue.getImplementation();
if (implementation.getScope().contains(Scope.CLASS_FILE) || implementation.getScope().contains(Scope.ALL_CLASS_FILES) || implementation.getScope().contains(Scope.JAVA_LIBRARIES)) {
boolean isOk = false;
for (EnumSet<Scope> analysisScope : implementation.getAnalysisScopes()) {
if (!analysisScope.contains(Scope.CLASS_FILE) && !analysisScope.contains(Scope.ALL_CLASS_FILES) && !analysisScope.contains(Scope.JAVA_LIBRARIES)) {
isOk = true;
break;
}
}
if (!isOk) {
System.out.println("Skipping issue " + issue + " because it requires classfile analysis. Consider rewriting in IDEA.");
continue;
}
}
final String inspectionShortName = AndroidLintInspectionBase.getInspectionShortNameByIssue(project, issue);
if (inspectionShortName == null) {
missing.add(issue);
continue;
}
// ELSE: compare severity, enabledByDefault, etc, message, etc
final HighlightDisplayKey key = HighlightDisplayKey.find(inspectionShortName);
if (key == null) {
//fail("No highlight display key for inspection " + inspectionShortName + " for issue " + issue);
System.out.println("No highlight display key for inspection " + inspectionShortName + " for issue " + issue);
continue;
}
final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
HighlightDisplayLevel errorLevel = profile.getErrorLevel(key, null);
Severity s;
if (errorLevel == HighlightDisplayLevel.WARNING || errorLevel == HighlightDisplayLevel.WEAK_WARNING) {
s = Severity.WARNING;
} else if (errorLevel == HighlightDisplayLevel.ERROR || errorLevel == HighlightDisplayLevel.NON_SWITCHABLE_ERROR) {
s = Severity.ERROR;
} else if (errorLevel == HighlightDisplayLevel.DO_NOT_SHOW) {
s = Severity.IGNORE;
} else if (errorLevel == HighlightDisplayLevel.INFO) {
s = Severity.INFORMATIONAL;
} else {
//fail("Unexpected error level " + errorLevel);
System.out.println("Unexpected error level " + errorLevel);
continue;
}
Severity expectedSeverity = issue.getDefaultSeverity();
if (expectedSeverity == Severity.FATAL) {
expectedSeverity = Severity.ERROR;
}
if (expectedSeverity != s) {
System.out.println("Wrong severity for " + issue + "; expected " + expectedSeverity + ", got " + s);
}
}
// Spit out registration information for the missing elements
if (!missing.isEmpty()) {
missing.sort((issue1, issue2) -> String.CASE_INSENSITIVE_ORDER.compare(issue1.getId(), issue2.getId()));
StringBuilder sb = new StringBuilder(1000);
sb.append("Missing registration for ").append(missing.size()).append(" issues (out of a total issue count of ").append(allIssues.size()).append(")");
sb.append("\nAdd to android/src/META-INF/android-plugin.xml (and please try to preserve the case insensitive alphabetical order):\n");
for (Issue issue : missing) {
sb.append(" <globalInspection hasStaticDescription=\"true\" shortName=\"");
sb.append(LINT_INSPECTION_PREFIX);
String id = issue.getId();
sb.append(id);
sb.append("\" displayName=\"");
sb.append(XmlUtils.toXmlAttributeValue(issue.getBriefDescription(TextFormat.TEXT)));
sb.append("\" groupKey=\"").append(getCategoryBundleKey(issue.getCategory())).append("\" bundle=\"messages.AndroidBundle\" enabledByDefault=\"");
sb.append(issue.isEnabledByDefault());
sb.append("\" level=\"");
sb.append(issue.getDefaultSeverity() == Severity.ERROR || issue.getDefaultSeverity() == Severity.FATAL ? "ERROR" : issue.getDefaultSeverity() == Severity.WARNING ? "WARNING" : "INFO");
sb.append("\" implementationClass=\"com.android.tools.idea.lint.AndroidLint");
sb.append(id);
sb.append("Inspection\"/>\n");
}
sb.append("\nAdd to com.android.tools.idea.lint:\n");
for (Issue issue : missing) {
String id = issue.getId();
String detectorClass = getDetectorClass(issue).getName();
String detectorName = getDetectorClass(issue).getSimpleName();
String issueName = getIssueFieldName(issue);
String messageKey = getMessageKey(issue);
//noinspection StringConcatenationInsideStringBufferAppend
sb.append("/*\n" + " * Copyright (C) 2016 The Android Open Source Project\n" + " *\n" + " * Licensed under the Apache License, Version 2.0 (the \"License\");\n" + " * you may not use this file except in compliance with the License.\n" + " * You may obtain a copy of the License at\n" + " *\n" + " * http://www.apache.org/licenses/LICENSE-2.0\n" + " *\n" + " * Unless required by applicable law or agreed to in writing, software\n" + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + " * See the License for the specific language governing permissions and\n" + " * limitations under the License.\n" + " */\n" + "package com.android.tools.idea.lint;\n" + "\n" + "import " + detectorClass + ";\n" + "import org.jetbrains.android.inspections.lint.AndroidLintInspectionBase;\n" + "import org.jetbrains.android.util.AndroidBundle;\n" + "\n" + "public class AndroidLint" + id + "Inspection extends AndroidLintInspectionBase {\n" + " public AndroidLint" + id + "Inspection() {\n" + " super(AndroidBundle.message(\"android.lint.inspections." + messageKey + "\"), " + detectorName + "." + issueName + ");\n" + " }\n" + "}\n");
}
sb.append("\nAdd to AndroidBundle.properties:\n");
for (Issue issue : missing) {
String messageKey = getMessageKey(issue);
sb.append("android.lint.inspections.").append(messageKey).append("=").append(escapePropertyValue(getBriefDescription(issue))).append("\n");
}
sb.append("\nAdded registrations for ").append(missing.size()).append(" issues (out of a total issue count of ").append(allIssues.size()).append(")\n");
System.out.println("*IF* necessary, add these category descriptors to AndroidBundle.properties:\n");
Set<Category> categories = Sets.newHashSet();
for (Issue issue : missing) {
categories.add(issue.getCategory());
}
List<Category> sorted = Lists.newArrayList(categories);
Collections.sort(sorted);
for (Category category : sorted) {
sb.append(getCategoryBundleKey(category)).append('=').append(escapePropertyValue(("Android > Lint > " + category.getFullName()).replace(":", " > "))).append("\n");
}
System.out.println(sb.toString());
return false;
} else if (LIST_ISSUES_WITH_QUICK_FIXES) {
System.out.println("The following inspections have quickfixes (used for Reporter.java):\n");
List<String> fields = Lists.newArrayListWithExpectedSize(quickfixes.size());
Set<String> imports = Sets.newHashSetWithExpectedSize(quickfixes.size());
// These two are handled by the ResourceTypeInspection's quickfixes; they're
// not handled by lint per se, but on the command line (in HTML reports) they're
// flagged by lint, so include them in the list
quickfixes.add(SupportAnnotationDetector.CHECK_PERMISSION);
quickfixes.add(SupportAnnotationDetector.MISSING_PERMISSION);
quickfixes.add(SupportAnnotationDetector.CHECK_RESULT);
for (Issue issue : quickfixes) {
String detectorName = getDetectorClass(issue).getName();
imports.add(detectorName);
int index = detectorName.lastIndexOf('.');
if (index != -1) {
detectorName = detectorName.substring(index + 1);
}
String issueName = getIssueFieldName(issue);
fields.add(detectorName + "." + issueName);
}
Collections.sort(fields);
List<String> sortedImports = Lists.newArrayList(imports);
Collections.sort(sortedImports);
for (String cls : sortedImports) {
System.out.println("import " + cls + ";");
}
System.out.println();
System.out.println("sStudioFixes = Sets.newHashSet(\n " + Joiner.on(",\n ").join(fields) + "\n);\n");
}
return true;
}
use of com.intellij.codeInspection.InspectionProfile in project intellij-community by JetBrains.
the class LocalInspectionToolWrapper method findTool2RunInBatch.
@Nullable
public static InspectionToolWrapper findTool2RunInBatch(@NotNull Project project, @Nullable PsiElement element, @NotNull String name) {
final InspectionProfile inspectionProfile = InspectionProjectProfileManager.getInstance(project).getCurrentProfile();
final InspectionToolWrapper toolWrapper = element == null ? inspectionProfile.getInspectionTool(name, project) : inspectionProfile.getInspectionTool(name, element);
return findTool2RunInBatch(project, element, inspectionProfile, toolWrapper);
}
use of com.intellij.codeInspection.InspectionProfile in project intellij-community by JetBrains.
the class WholeFileLocalInspectionsPassFactory method projectOpened.
@Override
public void projectOpened() {
final ProfileChangeAdapter myProfilesListener = new ProfileChangeAdapter() {
@Override
public void profileChanged(InspectionProfile profile) {
myFileToolsCache.clear();
}
@Override
public void profileActivated(InspectionProfile oldProfile, @Nullable InspectionProfile profile) {
myFileToolsCache.clear();
}
};
myProfileManager.addProfileChangeListener(myProfilesListener, myProject);
Disposer.register(myProject, myFileToolsCache::clear);
}
Aggregations