1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 @file:Suppress("UnstableApiUsage")
18 
19 package androidx.build.lint
20 
21 import com.android.tools.lint.client.api.UElementHandler
22 import com.android.tools.lint.detector.api.Category
23 import com.android.tools.lint.detector.api.Detector
24 import com.android.tools.lint.detector.api.Implementation
25 import com.android.tools.lint.detector.api.Incident
26 import com.android.tools.lint.detector.api.Issue
27 import com.android.tools.lint.detector.api.JavaContext
28 import com.android.tools.lint.detector.api.Scope
29 import com.android.tools.lint.detector.api.Severity
30 import org.jetbrains.uast.UAnnotation
31 
32 class BanKeepAnnotation : Detector(), Detector.UastScanner {
33 
getApplicableUastTypesnull34     override fun getApplicableUastTypes() = listOf(UAnnotation::class.java)
35 
36     override fun createUastHandler(context: JavaContext): UElementHandler {
37         return AnnotationChecker(context)
38     }
39 
40     private inner class AnnotationChecker(val context: JavaContext) : UElementHandler() {
visitAnnotationnull41         override fun visitAnnotation(node: UAnnotation) {
42             if (
43                 node.qualifiedName == "androidx.annotation.Keep" ||
44                     node.qualifiedName == "android.support.annotation.keep"
45             ) {
46                 val incident =
47                     Incident(context)
48                         .issue(ISSUE)
49                         .location(context.getNameLocation(node))
50                         .message("Uses @Keep annotation")
51                         .scope(node)
52                 context.report(incident)
53             }
54         }
55     }
56 
57     companion object {
58         val ISSUE =
59             Issue.create(
60                 "BanKeepAnnotation",
61                 "Uses @Keep annotation",
62                 "Use of @Keep annotation is not allowed, please use a conditional " +
63                     "keep rule in proguard-rules.pro.",
64                 Category.CORRECTNESS,
65                 5,
66                 Severity.ERROR,
67                 Implementation(BanKeepAnnotation::class.java, Scope.JAVA_FILE_SCOPE)
68             )
69     }
70 }
71