gpt4 book ai didi

android - 在运行 lint 检测器之前收集特定类

转载 作者:行者123 更新时间:2023-12-02 13:50:21 27 4
gpt4 key购买 nike

我想编写一个 lint 检查,以确保将 @ContributesAndroidInjector 添加到所有需要它的 fragment 中。

有没有办法在调用 visitClass(node: UClass) 之前收集所有用 @Module 注解的类?
现在我已经手动添加了列表中的所有模块(请参阅代码示例),但这对我来说不是正确的解决方案,因为添加新模块时我需要不断更新我的检测器。

探测器:

class MissingContributorDetector : Detector(), Detector.UastScanner {
override fun getApplicableUastTypes(): List<Class<out UElement>> {
return listOf(UClass::class.java)
}

override fun createUastHandler(context: JavaContext) = Visitor(context)

class Visitor(private val context: JavaContext) : UElementHandler() {

private val returnTypes: List<String>

init {
returnTypes = MODULES.mapNotNull { context.evaluator.findClass(it) }
.flatMap { it.methods.toList() }
.filter { it.hasAnnotation(DAGGER_MODULE_ANNOTATION) }
.mapNotNull { it.returnType }
.mapNotNull { PsiUtil.resolveClassInType(it)?.qualifiedName }
}

override fun visitClass(node: UClass) {
// logic to determine if there is an issue
}
}

companion object {
private val MODULES = listOf(
"com.dagger.module.ModuleOne",
"com.dagger.module.ModuleTwo",
"com.dagger.module.ModuleThree",
)
}
}

模块:

@Module
abstract class ModuleOne {

@ContributesAndroidInjector
abstract fun contributesFragment(): HomeFragment
}

最佳答案

Is there a way to gather all classes that are annotated with @Module before visitClass(node: UClass) is called?

检测器可以编写为执行两次传递。第一遍将收集数据结构中的所有类,该数据结构将在第二遍期间可供检测器使用。在此方案中,将在第一次和第二次传递期间为每个类调用 visitClass()

MissingContributorDetector.kt

/*
Process this lint check in two passes. The fist pass collects all the classes that have
the @Module annotation. The second pass does the actual check but has a the class list
produced in the first pass at its disposal.
*/
class MissingContributorDetector : Detector(), Detector.UastScanner {
private val mModuleClasses: MutableList<UClass> = ArrayList()

override fun getApplicableUastTypes(): List<Class<out UElement>> {
return listOf(UClass::class.java)
}

override fun createUastHandler(context: JavaContext) = Visitor(context)

// Cues up the second phase for the actual lint check.
override fun afterCheckEachProject(context: Context) {
super.afterCheckEachProject(context)
if (context.phase == 1) { // Rescan classes
context.requestRepeat(this, MissingContributorIssue.implementation.scope)
}
}

inner class Visitor(private val context: JavaContext) : UElementHandler() {
// Search for classes that are annotated with @Module
override fun visitClass(node: UClass) {
if (context.phase == 1) { // Just collect class names
if (hasAnnotation(node.annotations, DAGGER_MODULE_ANNOTATION_QUALIFIED_NAME)) {
// Build the class list that will be used during the second pass.
mModuleClasses.add(node)
}
} else { // phase 2
// Do whatever processing is necessary. Here we just check for
// @ContributesAndroidInjector on each method in a class annotated with @Module.
// The mModuleClasses structure is fully populated from the first pass.
if (mModuleClasses.contains(node)) {
node.methods.forEach { checkMethodForContributesAndroidInjector(it) }
}
}
}

// Check for @ContributesAndroidInjector on non-constructor methods
private fun checkMethodForContributesAndroidInjector(node: UMethod) {
if (node.isConstructor ||
!isFragmentReturnType(node) ||
hasAnnotation(node.annotations, DAGGER_CONTRIBUTESANDROIDINJECTOR_QUALIFIED_NAME)) {
return
}
context.report(
MissingContributorIssue,
node,
context.getNameLocation(node),
MissingContributorIssue.getExplanation(TextFormat.TEXT)
)
}

private fun isFragmentReturnType(node: UMethod): Boolean {
val returnTypeRef = node.returnTypeReference
return returnTypeRef?.getQualifiedName() == HOME_FRAGMENT
}

private fun hasAnnotation(annotations: List<UAnnotation>, toCheck: String): Boolean {
return annotations.any { it.qualifiedName == toCheck }
}

}

companion object {
const val DAGGER_MODULE_ANNOTATION_QUALIFIED_NAME = "dagger.Module"
const val DAGGER_CONTRIBUTESANDROIDINJECTOR_QUALIFIED_NAME = "dagger.android.ContributesAndroidInjector"
const val HOME_FRAGMENT = "com.dagger.module.HomeFragment"

val MissingContributorIssue: Issue = Issue.create(
id = "MissingContributesAndroidInjector",
briefDescription = "Must specify @ContributesAndroidInjector",
implementation = Implementation(
MissingContributorDetector::class.java,
Scope.JAVA_FILE_SCOPE),
explanation = "Method must be annotated with @ContributesAndroidInjector if enclosing class is annotated with @Module.",
category = Category.CORRECTNESS,
priority = 1,
severity = Severity.FATAL
)
}
}
<小时/><小时/>

只需一次通过的旧答案

可以编写检测器来查看每个类,并仅选择那些用 @Module 注释的类。选择类后,可以检查每个返回 HomeFragment 的方法是否有 @ContributesAndroidInjector 注释。然后可以添加和扫描类,而无需更新模块列表。

MissingContributorDetector.kt

class MissingContributorDetector : Detector(), Detector.UastScanner {

override fun getApplicableUastTypes(): List<Class<out UElement>> {
return listOf(UClass::class.java)
}

override fun createUastHandler(context: JavaContext) = Visitor(context)

class Visitor(private val context: JavaContext) : UElementHandler() {

// Search for classes that are annotated with @Module
override fun visitClass(node: UClass) {
if (hasAnnotation(node.annotations, DAGGER_MODULE_ANNOTATION_QUALIFIED_NAME)) {
node.methods.forEach { checkMethodForContributesAndroidInjector(it) }
}
}

// Check for @ContributesAndroidInjector on non-constructor methods
private fun checkMethodForContributesAndroidInjector(node: UMethod) {
if (node.isConstructor ||
!isFragmentReturnType(node) ||
hasAnnotation(node.annotations, DAGGER_CONTRIBUTESANDROIDINJECTOR_QUALIFIED_NAME)) {
return
}

context.report(
MissingContributorIssue.ISSUE,
node,
context.getNameLocation(node),
MissingContributorIssue.ISSUE.getExplanation(TextFormat.TEXT)
)
}

private fun isFragmentReturnType(node: UMethod): Boolean {
val returnTypeRef = node.returnTypeReference
return returnTypeRef?.getQualifiedName() == HOME_FRAGMENT
}

private fun hasAnnotation(annotations: List<UAnnotation>, toCheck: String): Boolean {
return annotations.any { it.qualifiedName == toCheck }
}
}

object MissingContributorIssue {
private const val ID = "MissingContributesAndroidInjector"
private const val DESCRIPTION = "Must specify @ContributesAndroidInjector"
private const val EXPLANATION = ("Method must be annotated with @ContributesAndroidInjector if enclosing class is annotated with @Module.")
private val CATEGORY: Category = Category.CORRECTNESS
private const val PRIORITY = 1
private val SEVERITY = Severity.FATAL
val ISSUE: Issue = Issue.create(
ID,
DESCRIPTION,
EXPLANATION,
CATEGORY,
PRIORITY,
SEVERITY,
Implementation(
MissingContributorDetector::class.java,
Scope.JAVA_FILE_SCOPE)
)
}

companion object {
const val DAGGER_MODULE_ANNOTATION_QUALIFIED_NAME = "dagger.Module"
const val DAGGER_CONTRIBUTESANDROIDINJECTOR_QUALIFIED_NAME = "dagger.android.ContributesAndroidInjector"
const val HOME_FRAGMENT = "com.dagger.module.HomeFragment"
}
}

用于测试此检测器的文件:

ModuleOne.kt

@Module  
abstract class ModuleOne {

@ContributesAndroidInjector
abstract fun isAnnotated(): HomeFragment

abstract fun shouldBeAnnotated(): HomeFragment

abstract fun notAnnotated()
}

abstract class ModuleTwo {

abstract fun okIsNotAnnotated(): HomeFragment
}

显示标记项目的 lint 报告:

enter image description here

关于android - 在运行 lint 检测器之前收集特定类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59028731/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com