Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / lint-rules / src / main / java / com / vayunmathur / lint / RouteScreenshotCoverageDetector.kt

RouteScreenshotCoverageDetector.kt200 lines · 9.2 KiBRaw
1package com.vayunmathur.lint
2
3import com.android.tools.lint.client.api.UElementHandler
4import com.android.tools.lint.detector.api.Category
5import com.android.tools.lint.detector.api.Context
6import com.android.tools.lint.detector.api.Detector
7import com.android.tools.lint.detector.api.Implementation
8import com.android.tools.lint.detector.api.Issue
9import com.android.tools.lint.detector.api.JavaContext
10import com.android.tools.lint.detector.api.Location
11import com.android.tools.lint.detector.api.Scope
12import com.android.tools.lint.detector.api.Severity
13import com.android.tools.lint.detector.api.SourceCodeScanner
14import org.jetbrains.kotlin.lexer.KtTokens
15import org.jetbrains.kotlin.psi.KtClass
16import org.jetbrains.kotlin.psi.KtClassOrObject
17import org.jetbrains.kotlin.psi.KtFile
18import org.jetbrains.uast.UElement
19import org.jetbrains.uast.UFile
20import java.io.File
21
22/**
23 * Every navigation route needs a screenshot.
24 *
25 * Collects the leaf destinations of the module's canonical
26 * `sealed interface Route : NavKey` (the [PackageStructureDetector] shape:
27 * `Route.kt` holding only that interface plus nested route objects/classes)
28 * and the capture names in `src/screenshotTest`, and errors once per route
29 * with no capture. A capture names its route as
30 * `@Preview(name = "<number>-<route-key>", group = "<bucket>")`, where the
31 * route key is the kebab-case leaf name (`Story`, `DeleteConversationDialog`,
32 * `WhatsAppRegistration.Code` → `story`, `delete-conversation-dialog`,
33 * `whatsapp-registration-code`); a `-…` suffix is a variant of the same
34 * route (`4-feed-expanded` still covers `Feed`), and each preview counts
35 * for the longest route key it names (`3-call-logs` covers `CallLogs`,
36 * never `Call`). Dialog destinations are routes like any other.
37 *
38 * A route that genuinely cannot be rendered (a live WebRTC call, a WebView
39 * sign-in, a Keystore-session wizard step) is exempted per route with
40 * `// SCREENSHOT COVERAGE EXCEPTION: <Leaf>: <reason>` in `Route.kt` — the
41 * marker shape is validated by [ExceptionMarkerFormatDetector], and an
42 * exemption naming no real route is itself an error here, so gaps stay
43 * explicit and reviewable instead of silent. Modules with no `Route`
44 * (libraries, games, tools — see [LintPackageExclusions]) are skipped.
45 *
46 * The captures are read from disk in [afterCheckProject] rather than from
47 * the visited sources: `src/screenshotTest` is a screenshot-test source
48 * set, not a lint-analysed one, so its files are not guaranteed a visit.
49 */
50class RouteScreenshotCoverageDetector : Detector(), SourceCodeScanner {
51
52 private data class Leaf(
53 val name: String,
54 val file: File,
55 val startOffset: Int,
56 val endOffset: Int,
57 )
58
59 private val leaves = mutableListOf<Leaf>()
60 private val exemptions = mutableSetOf<String>()
61 private var routePackage: String? = null
62
63 override fun getApplicableUastTypes(): List<Class<out UElement>> =
64 listOf(UFile::class.java)
65
66 override fun createUastHandler(context: JavaContext): UElementHandler =
67 object : UElementHandler() {
68 override fun visitFile(node: UFile) {
69 val packageName = node.packageName
70 if (packageName.isEmpty()) return
71 if (!packageName.startsWith("com.vayunmathur.")) return
72 if (ExceptionMarkerFormatDetector.isLintRulesPackage(packageName)) return
73 if (LintPackageExclusions.isExcluded(packageName)) return
74 val ktFile = node.sourcePsi as? KtFile ?: return
75 collectExemptions(ktFile)
76 ktFile.declarations
77 .filterIsInstance<KtClass>()
78 .filter { it.name == ROUTE_NAME && it.hasModifier(KtTokens.SEALED_KEYWORD) }
79 .forEach { route ->
80 routePackage = packageName
81 route.declarations
82 .filterIsInstance<KtClassOrObject>()
83 .forEach { collectLeaves(it, emptyList(), context.file) }
84 }
85 }
86 }
87
88 private fun collectExemptions(ktFile: KtFile) {
89 for (comment in CommentOnlyMatcher.commentsIn(ktFile)) {
90 val text = comment.text
91 if (!text.contains(EXCEPTION_PREFIX)) continue
92 val leaf = text.substringAfter(EXCEPTION_PREFIX).substringBefore(':').trim()
93 if (leaf.isNotEmpty()) exemptions += leaf
94 }
95 }
96
97 private fun collectLeaves(node: KtClassOrObject, path: List<String>, file: File) {
98 val name = node.name ?: return
99 val children = node.declarations.filterIsInstance<KtClassOrObject>()
100 if (children.isEmpty()) {
101 leaves += Leaf(
102 name = (path + name).joinToString("."),
103 file = file,
104 startOffset = node.textRange.startOffset,
105 endOffset = node.textRange.endOffset,
106 )
107 } else {
108 children.forEach { collectLeaves(it, path + name, file) }
109 }
110 }
111
112 override fun afterCheckProject(context: Context) {
113 if (leaves.isEmpty()) return
114 val leafNames = leaves.map { it.name }.toSet()
115 for (leaf in exemptions - leafNames) {
116 context.report(
117 ISSUE,
118 Location.create(leaves.first().file),
119 "Screenshot coverage exemption names no such route: `$leaf`. " +
120 "Remove the `// SCREENSHOT COVERAGE EXCEPTION: $leaf: …` marker or fix the route name.",
121 )
122 }
123 val captures = capturesByRoute(context.project.dir, leafNames.map(::routeKey).toSet())
124 for (leaf in leaves) {
125 if (leaf.name in exemptions) continue
126 val key = routeKey(leaf.name)
127 if (captures[key].isNullOrEmpty()) {
128 context.report(
129 ISSUE,
130 Location.create(leaf.file, leaf.file.readText(), leaf.startOffset, leaf.endOffset),
131 "Route `${leaf.name}` has no screenshot capture. Add a `@Preview` named " +
132 "`\"<n>-$key\"` (group = its form-factor bucket) under `src/screenshotTest`, " +
133 "or exempt it in Route.kt with `// SCREENSHOT COVERAGE EXCEPTION: ${leaf.name}: <reason>`.",
134 )
135 }
136 }
137 }
138
139 companion object {
140 internal const val ROUTE_NAME = "Route"
141 internal const val EXCEPTION_PREFIX = "// SCREENSHOT COVERAGE EXCEPTION:"
142
143 /** `WhatsAppRegistration.Code` → `whatsapp-registration-code`. */
144 internal fun routeKey(leafName: String): String =
145 leafName.split('.').joinToString("-") { segment ->
146 buildString {
147 segment.forEachIndexed { index, c ->
148 if (c.isUpperCase() && index > 0) append('-')
149 append(c.lowercaseChar())
150 }
151 }
152 }
153
154 /**
155 * Route key → preview names under `<projectDir>/src/screenshotTest`.
156 * Each preview counts for the longest route key it names.
157 */
158 internal fun capturesByRoute(projectDir: File, routeKeys: Set<String>): Map<String, List<String>> {
159 val dir = File(projectDir, "src/screenshotTest")
160 if (!dir.isDirectory) return emptyMap()
161 val nameArg = Regex("""@Preview\(name\s*=\s*"([^"]+)"""")
162 val byRoute = mutableMapOf<String, MutableList<String>>()
163 dir.walkTopDown()
164 .filter { it.isFile && it.extension == "kt" }
165 .forEach { file ->
166 nameArg.findAll(file.readText()).forEach { match ->
167 val previewName = match.groupValues[1]
168 val named = previewName.replace(Regex("""^\d+-"""), "")
169 val route = routeKeys
170 .filter { key -> named == key || named.startsWith("$key-") }
171 .maxByOrNull { it.length }
172 if (route != null) byRoute.getOrPut(route) { mutableListOf() } += previewName
173 }
174 }
175 return byRoute
176 }
177
178 val ISSUE: Issue = Issue.create(
179 id = "RouteScreenshotCoverage",
180 briefDescription = "Route has no screenshot capture",
181 explanation = """
182 Every route needs at least one screenshot: each leaf destination of the \
183 module's `sealed interface Route` must have a capture in `src/screenshotTest` \
184 named `@Preview(name = "<number>-<route-key>", group = "<bucket>")`, where the \
185 route key is the kebab-case leaf name (a `-…` suffix is a variant of the same \
186 route). Dialog destinations are routes like any other. A route that cannot be \
187 rendered (live call, WebView sign-in, Keystore-session wizard) is exempted per \
188 route in `Route.kt` with `// SCREENSHOT COVERAGE EXCEPTION: <Leaf>: <reason>`. \
189 See docs/screenshot-coverage.md.
190 """.trimIndent(),
191 category = Category.CORRECTNESS,
192 priority = 6,
193 severity = Severity.ERROR,
194 implementation = Implementation(
195 RouteScreenshotCoverageDetector::class.java,
196 Scope.JAVA_FILE_SCOPE,
197 ),
198 )
199 }
200}