Implemented suppress lint intention action for android lint (KT-12020)

#KT-12020 Fixed
This commit is contained in:
Vyacheslav Gerasimov
2016-11-07 00:28:16 +03:00
parent 6a8f78d7c1
commit 60bc35b787
28 changed files with 427 additions and 3 deletions
@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.AbstractDataFlowValueRenderingTest
import org.jetbrains.kotlin.addImport.AbstractAddImportTest
import org.jetbrains.kotlin.android.*
import org.jetbrains.kotlin.android.configure.AbstractConfigureProjectTest
import org.jetbrains.kotlin.android.intentions.AbstractAndroidIntentionTest
import org.jetbrains.kotlin.android.intentions.AbstractAndroidResourceIntentionTest
import org.jetbrains.kotlin.android.quickfixes.AbstractAndroidQuickFixMultiFileTest
import org.jetbrains.kotlin.annotation.AbstractAnnotationProcessorBoxTest
@@ -1161,6 +1162,10 @@ fun main(args: Array<String>) {
testClass<AbstractKotlinLintTest>() {
model("android/lint", excludeParentDirs = true)
}
testClass<AbstractAndroidIntentionTest>() {
model("android/intentions", pattern = "^([\\w\\-_]+)\\.kt$")
}
}
testGroup("plugins/plugins-tests/tests", "plugins/android-extensions/android-extensions-jps/testData") {
@@ -0,0 +1,58 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.intentions
import com.android.SdkConstants
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.PathUtil
import org.jetbrains.android.inspections.klint.AndroidLintInspectionBase
import org.jetbrains.kotlin.android.KotlinAndroidTestCase
import org.jetbrains.kotlin.idea.test.DirectiveBasedActionUtils
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
abstract class AbstractAndroidIntentionTest : KotlinAndroidTestCase() {
fun doTest(path: String) {
val fileText = FileUtil.loadFile(File(path), true)
val intentionText = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// INTENTION_TEXT: ") ?: error("Empty intention text")
val mainInspectionClassName = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// INSPECTION_CLASS: ") ?: error("Empty inspection class name")
val inspectionClass = Class.forName(mainInspectionClassName).newInstance() as AndroidLintInspectionBase
myFixture.enableInspections(inspectionClass)
val sourceFile = myFixture.copyFileToProject(path, "src/${PathUtil.getFileName(path)}")
myFixture.configureFromExistingVirtualFile(sourceFile)
DirectiveBasedActionUtils.checkForUnexpectedErrors(myFixture.file as KtFile)
val intention = myFixture.getAvailableIntention(intentionText) ?: error("Failed to find intention")
myFixture.launchAction(intention)
myFixture.checkResultByFile(path + ".expected")
}
override fun createManifest() {
myFixture.copyFileToProject("idea/testData/android/AndroidManifest.xml", SdkConstants.FN_ANDROID_MANIFEST_XML)
}
override fun getTestDataPath() = KotlinTestUtils.getHomeDirectory()
}
@@ -0,0 +1,101 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.intentions;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TargetBackend;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("idea/testData/android/intentions")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class AndroidIntentionTestGenerated extends AbstractAndroidIntentionTest {
public void testAllFilesPresentInIntentions() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/android/intentions"), Pattern.compile("^([\\w\\-_]+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("idea/testData/android/intentions/suppressLint")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class SuppressLint extends AbstractAndroidIntentionTest {
@TestMetadata("activityMethod.kt")
public void testActivityMethod() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/intentions/suppressLint/activityMethod.kt");
doTest(fileName);
}
@TestMetadata("addToExistingAnnotation.kt")
public void testAddToExistingAnnotation() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/intentions/suppressLint/addToExistingAnnotation.kt");
doTest(fileName);
}
public void testAllFilesPresentInSuppressLint() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/android/intentions/suppressLint"), Pattern.compile("^([\\w\\-_]+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("constructorParameter.kt")
public void testConstructorParameter() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/intentions/suppressLint/constructorParameter.kt");
doTest(fileName);
}
@TestMetadata("destructuringDeclaration.kt")
public void testDestructuringDeclaration() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/intentions/suppressLint/destructuringDeclaration.kt");
doTest(fileName);
}
@TestMetadata("lambdaArgument.kt")
public void testLambdaArgument() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/intentions/suppressLint/lambdaArgument.kt");
doTest(fileName);
}
@TestMetadata("lambdaArgumentProperty.kt")
public void testLambdaArgumentProperty() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/intentions/suppressLint/lambdaArgumentProperty.kt");
doTest(fileName);
}
@TestMetadata("methodParameter.kt")
public void testMethodParameter() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/intentions/suppressLint/methodParameter.kt");
doTest(fileName);
}
@TestMetadata("propertyWithLambda.kt")
public void testPropertyWithLambda() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/intentions/suppressLint/propertyWithLambda.kt");
doTest(fileName);
}
@TestMetadata("simpleProperty.kt")
public void testSimpleProperty() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/intentions/suppressLint/simpleProperty.kt");
doTest(fileName);
}
}
}
@@ -0,0 +1,2 @@
@SuppressLint("SdCardPath")
val a = "/sdcard"
@@ -0,0 +1 @@
val a = "/sdcard"
@@ -0,0 +1,5 @@
<html>
<body>
This intention suppresses android lint warnings with @SuppressLint annotation added to closest parent declaration
</body>
</html>
@@ -0,0 +1,10 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
import android.app.Activity
import android.os.Environment
class MainActivity : Activity() {
fun getSdCard(fromEnvironment: Boolean) = if (fromEnvironment) Environment.getExternalStorageDirectory().path else "<caret>/sdcard"
}
@@ -0,0 +1,12 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Environment
class MainActivity : Activity() {
@SuppressLint("SdCardPath")
fun getSdCard(fromEnvironment: Boolean) = if (fromEnvironment) Environment.getExternalStorageDirectory().path else "/sdcard"
}
@@ -0,0 +1,12 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Environment
class MainActivity : Activity() {
@SuppressLint("Something")
fun getSdCard(fromEnvironment: Boolean) = if (fromEnvironment) Environment.getExternalStorageDirectory().path else "<caret>/sdcard"
}
@@ -0,0 +1,12 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Environment
class MainActivity : Activity() {
@SuppressLint("Something", "SdCardPath")
fun getSdCard(fromEnvironment: Boolean) = if (fromEnvironment) Environment.getExternalStorageDirectory().path else "/sdcard"
}
@@ -0,0 +1,4 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
class SdCard(val path: String = "<caret>/sdcard")
@@ -0,0 +1,6 @@
import android.annotation.SuppressLint
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
class SdCard(@SuppressLint("SdCardPath") val path: String = "/sdcard")
@@ -0,0 +1,9 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
fun foo() {
val (a: String, b: String) = "<caret>/sdcard"
}
operator fun CharSequence.component1(): String = "component1"
operator fun CharSequence.component2(): String = "component2"
@@ -0,0 +1,12 @@
import android.annotation.SuppressLint
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
@SuppressLint("SdCardPath")
fun foo() {
val (a: String, b: String) = "/sdcard"
}
operator fun CharSequence.component1(): String = "component1"
operator fun CharSequence.component2(): String = "component2"
@@ -0,0 +1,10 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
fun foo(l: Any) = l
fun bar() {
foo() {
"<caret>/sdcard"
}
}
@@ -0,0 +1,13 @@
import android.annotation.SuppressLint
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
fun foo(l: Any) = l
@SuppressLint("SdCardPath")
fun bar() {
foo() {
"<caret>/sdcard"
}
}
@@ -0,0 +1,6 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
fun foo(l: Any) = l
val bar = foo() { "<caret>/sdcard" }
@@ -0,0 +1,9 @@
import android.annotation.SuppressLint
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
fun foo(l: Any) = l
@SuppressLint("SdCardPath")
val bar = foo() { "/sdcard" }
@@ -0,0 +1,4 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
fun foo(path: String = "<caret>/sdcard") = path
@@ -0,0 +1,6 @@
import android.annotation.SuppressLint
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
fun foo(@SuppressLint("SdCardPath") path: String = "/sdcard") = path
@@ -0,0 +1,4 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
val getPath = { "<caret>/sdcard" }
@@ -0,0 +1,7 @@
import android.annotation.SuppressLint
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
@SuppressLint("SdCardPath")
val getPath = { "/sdcard" }
@@ -0,0 +1,4 @@
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
val path = "<caret>/sdcard"
@@ -0,0 +1,7 @@
import android.annotation.SuppressLint
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation
// INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection
@SuppressLint("SdCardPath")
val path = "/sdcard"
+2
View File
@@ -16,5 +16,7 @@
<orderEntry type="library" name="android-plugin" level="project" />
<orderEntry type="module" module-name="android-annotations" />
<orderEntry type="module" module-name="frontend" />
<orderEntry type="module" module-name="idea-analysis" />
<orderEntry type="module" module-name="idea-core" />
</component>
</module>
@@ -1,13 +1,10 @@
package org.jetbrains.android.inspections.klint;
import com.android.SdkConstants;
import com.android.tools.idea.gradle.util.Projects;
import com.android.tools.klint.client.api.IssueRegistry;
import com.android.tools.klint.client.api.LintDriver;
import com.android.tools.klint.client.api.LintRequest;
import com.android.tools.klint.detector.api.Issue;
import com.android.tools.klint.detector.api.Scope;
import com.android.utils.SdkUtils;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.daemon.DaemonBundle;
@@ -248,6 +245,7 @@ public class AndroidLintExternalAnnotator extends ExternalAnnotator<State, State
}
}
annotation.registerFix(new SuppressLintIntentionAction(id, startElement));
annotation.registerFix(new MyDisableInspectionFix(key));
annotation.registerFix(new MyEditInspectionToolsSettingsAction(key, inspection));
@@ -0,0 +1,105 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.inspections.klint
import com.android.SdkConstants.FQCN_SUPPRESS_LINT
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.android.util.AndroidBundle
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import javax.swing.Icon
class SuppressLintIntentionAction(val id: String, val element: PsiElement) : IntentionAction, Iconable {
private companion object {
val INTENTION_NAME_PREFIX = "AndroidKLint"
val SUPPRESS_LINT_MESSAGE = "android.lint.fix.suppress.lint.api.annotation"
val FQNAME_SUPPRESS_LINT = FqName(FQCN_SUPPRESS_LINT)
}
private val lintId = getLintId(id)
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = true
override fun getText(): String = AndroidBundle.message(SUPPRESS_LINT_MESSAGE, lintId)
override fun getFamilyName() = text
override fun getIcon(flags: Int): Icon? = AllIcons.Actions.Cancel
override fun startInWriteAction() = true
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (file !is KtFile) {
return
}
val annotationContainer = PsiTreeUtil.findFirstParent(element, true) { it.isSuppressLintTarget() } ?: return
if (!FileModificationService.getInstance().preparePsiElementForWrite(annotationContainer)) {
return
}
val argument = "\"$lintId\""
when (annotationContainer) {
is KtModifierListOwner -> annotationContainer.addAnnotation(
FQNAME_SUPPRESS_LINT,
argument,
whiteSpaceText = if (annotationContainer.isNewLineNeededForAnnotation()) "\n" else " ",
addToExistingAnnotation = { entry -> addArgumentToAnnotation(entry, argument) })
}
}
private fun addArgumentToAnnotation(entry: KtAnnotationEntry, argument: String): Boolean {
// add new arguments to an existing entry
val args = entry.valueArgumentList
val psiFactory = KtPsiFactory(entry)
val newArgList = psiFactory.createCallArguments("($argument)")
if (args == null) {
// new argument list
entry.addAfter(newArgList, entry.lastChild)
}
else if (args.arguments.isEmpty()) {
// replace '()' with a new argument list
args.replace(newArgList)
}
else if (args.arguments.none { it.textMatches(argument) }) {
args.addArgument(newArgList.arguments[0])
}
return true
}
private fun getLintId(intentionId: String) =
if (intentionId.startsWith(INTENTION_NAME_PREFIX)) intentionId.substring(INTENTION_NAME_PREFIX.length) else intentionId
private fun KtElement.isNewLineNeededForAnnotation() = !(this is KtParameter || this is KtTypeParameter)
private fun PsiElement.isSuppressLintTarget() = this is KtDeclaration &&
this !is KtDestructuringDeclaration &&
this !is KtFunctionLiteral
}