Android: Add inspection & quickfix to convert findViewById to api 26

#KT-19940 Fixed Target Version 1.1.5
This commit is contained in:
Vyacheslav Gerasimov
2017-08-30 18:19:58 +03:00
parent be900a76d8
commit 5220dfc0ad
15 changed files with 303 additions and 13 deletions
@@ -0,0 +1,79 @@
/*
* Copyright 2010-2017 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.inspection
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.android.facet.AndroidFacet
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.KtPsiUtil.isUnsafeCast
import org.jetbrains.kotlin.psi.psiUtil.addTypeArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
class TypeParameterFindViewByIdInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
val compileSdk = AndroidFacet.getInstance(session.file)?.androidModuleInfo?.buildSdkVersion?.apiLevel
if (compileSdk == null || compileSdk < 26) {
return KtVisitorVoid()
}
return object : KtVisitorVoid() {
override fun visitCallExpression(expression: KtCallExpression) {
super.visitCallExpression(expression)
if (expression.calleeExpression?.text != "findViewById" || expression.typeArguments.isNotEmpty()) {
return
}
val parentCast = (expression.parent as? KtBinaryExpressionWithTypeRHS)?.takeIf { isUnsafeCast(it) } ?: return
val typeText = parentCast.right?.getTypeTextWithoutQuestionMark() ?: return
val callableDescriptor = expression.getResolvedCall(expression.analyze())?.resultingDescriptor ?: return
if (callableDescriptor.name.asString() != "findViewById" || callableDescriptor.typeParameters.size != 1) {
return
}
holder.registerProblem(
parentCast,
"Can be converted to findViewById<$typeText>(...)",
ConvertCastToFindViewByIdWithTypeParameter())
}
}
}
class ConvertCastToFindViewByIdWithTypeParameter : LocalQuickFix {
override fun getFamilyName(): String = "Convert cast to findViewById with type parameter"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val cast = descriptor.psiElement as? KtBinaryExpressionWithTypeRHS ?: return
val typeText = cast.right?.getTypeTextWithoutQuestionMark() ?: return
val call = cast.left as? KtCallExpression ?: return
val newCall = call.copy() as KtCallExpression
val typeArgument = KtPsiFactory(call).createTypeArgument(typeText)
newCall.addTypeArgument(typeArgument)
cast.replace(newCall)
}
}
companion object {
fun KtTypeReference.getTypeTextWithoutQuestionMark(): String? =
(typeElement as? KtNullableType)?.innerType?.text ?: typeElement?.text
}
}
@@ -34,6 +34,6 @@ public class TestUtils {
@NonNull
public static String getLatestAndroidPlatform() {
return "android-25";
return "android-26";
}
}
@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.android.lint
import com.intellij.codeInspection.InspectionProfileEntry
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
import com.intellij.util.PathUtil
import org.jetbrains.android.inspections.klint.AndroidLintInspectionBase
@@ -53,7 +54,7 @@ abstract class AbstractKotlinLintTest : KotlinAndroidTestCase() {
myFixture.enableInspections(*inspectionClassNames.map { className ->
val inspectionClass = Class.forName(className)
inspectionClass.newInstance() as AndroidLintInspectionBase
inspectionClass.newInstance() as InspectionProfileEntry
}.toTypedArray())
val additionalResourcesDir = File(ktFile.parentFile, getTestName(true))
@@ -76,6 +77,6 @@ abstract class AbstractKotlinLintTest : KotlinAndroidTestCase() {
myFixture.copyFileToProject("${PathUtil.getParentPath(path)}/$dependencyFile", "src/$dependencyTargetPath")
}
myFixture.checkHighlighting(true, false, false)
myFixture.checkHighlighting(true, false, true)
}
}
@@ -66,6 +66,12 @@ public class KotlinLintTestGenerated extends AbstractKotlinLintTest {
doTest(fileName);
}
@TestMetadata("findViewById.kt")
public void testFindViewById() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/lint/findViewById.kt");
doTest(fileName);
}
@TestMetadata("javaPerformance.kt")
public void testJavaPerformance() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/lint/javaPerformance.kt");
@@ -36,6 +36,27 @@ public class AndroidLintQuickfixTestGenerated extends AbstractAndroidLintQuickfi
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/android/lintQuickfix"), Pattern.compile("^([\\w\\-_]+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("idea/testData/android/lintQuickfix/findViewById")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class FindViewById extends AbstractAndroidLintQuickfixTest {
public void testAllFilesPresentInFindViewById() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/android/lintQuickfix/findViewById"), Pattern.compile("^([\\w\\-_]+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("nullableType.kt")
public void testNullableType() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/lintQuickfix/findViewById/nullableType.kt");
doTest(fileName);
}
@TestMetadata("simple.kt")
public void testSimple() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/android/lintQuickfix/findViewById/simple.kt");
doTest(fileName);
}
}
@TestMetadata("idea/testData/android/lintQuickfix/parcelable")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)