package com.vayunmathur.lint import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Context import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Location import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.uast.UElement import org.jetbrains.uast.UFile import java.io.File /** * Every navigation route needs a screenshot. * * Collects the leaf destinations of the module's canonical * `sealed interface Route : NavKey` (the [PackageStructureDetector] shape: * `Route.kt` holding only that interface plus nested route objects/classes) * and the capture names in `src/screenshotTest`, and errors once per route * with no capture. A capture names its route as * `@Preview(name = "-", group = "")`, where the * route key is the kebab-case leaf name (`Story`, `DeleteConversationDialog`, * `WhatsAppRegistration.Code` → `story`, `delete-conversation-dialog`, * `whatsapp-registration-code`); a `-…` suffix is a variant of the same * route (`4-feed-expanded` still covers `Feed`), and each preview counts * for the longest route key it names (`3-call-logs` covers `CallLogs`, * never `Call`). Dialog destinations are routes like any other. * * A route that genuinely cannot be rendered (a live WebRTC call, a WebView * sign-in, a Keystore-session wizard step) is exempted per route with * `// SCREENSHOT COVERAGE EXCEPTION: : ` in `Route.kt` — the * marker shape is validated by [ExceptionMarkerFormatDetector], and an * exemption naming no real route is itself an error here, so gaps stay * explicit and reviewable instead of silent. Modules with no `Route` * (libraries, games, tools — see [LintPackageExclusions]) are skipped. * * The captures are read from disk in [afterCheckProject] rather than from * the visited sources: `src/screenshotTest` is a screenshot-test source * set, not a lint-analysed one, so its files are not guaranteed a visit. */ class RouteScreenshotCoverageDetector : Detector(), SourceCodeScanner { private data class Leaf( val name: String, val file: File, val startOffset: Int, val endOffset: Int, ) private val leaves = mutableListOf() private val exemptions = mutableSetOf() private var routePackage: String? = null override fun getApplicableUastTypes(): List> = listOf(UFile::class.java) override fun createUastHandler(context: JavaContext): UElementHandler = object : UElementHandler() { override fun visitFile(node: UFile) { val packageName = node.packageName if (packageName.isEmpty()) return if (!packageName.startsWith("com.vayunmathur.")) return if (ExceptionMarkerFormatDetector.isLintRulesPackage(packageName)) return if (LintPackageExclusions.isExcluded(packageName)) return val ktFile = node.sourcePsi as? KtFile ?: return collectExemptions(ktFile) ktFile.declarations .filterIsInstance() .filter { it.name == ROUTE_NAME && it.hasModifier(KtTokens.SEALED_KEYWORD) } .forEach { route -> routePackage = packageName route.declarations .filterIsInstance() .forEach { collectLeaves(it, emptyList(), context.file) } } } } private fun collectExemptions(ktFile: KtFile) { for (comment in CommentOnlyMatcher.commentsIn(ktFile)) { val text = comment.text if (!text.contains(EXCEPTION_PREFIX)) continue val leaf = text.substringAfter(EXCEPTION_PREFIX).substringBefore(':').trim() if (leaf.isNotEmpty()) exemptions += leaf } } private fun collectLeaves(node: KtClassOrObject, path: List, file: File) { val name = node.name ?: return val children = node.declarations.filterIsInstance() if (children.isEmpty()) { leaves += Leaf( name = (path + name).joinToString("."), file = file, startOffset = node.textRange.startOffset, endOffset = node.textRange.endOffset, ) } else { children.forEach { collectLeaves(it, path + name, file) } } } override fun afterCheckProject(context: Context) { if (leaves.isEmpty()) return val leafNames = leaves.map { it.name }.toSet() for (leaf in exemptions - leafNames) { context.report( ISSUE, Location.create(leaves.first().file), "Screenshot coverage exemption names no such route: `$leaf`. " + "Remove the `// SCREENSHOT COVERAGE EXCEPTION: $leaf: …` marker or fix the route name.", ) } val captures = capturesByRoute(context.project.dir, leafNames.map(::routeKey).toSet()) for (leaf in leaves) { if (leaf.name in exemptions) continue val key = routeKey(leaf.name) if (captures[key].isNullOrEmpty()) { context.report( ISSUE, Location.create(leaf.file, leaf.file.readText(), leaf.startOffset, leaf.endOffset), "Route `${leaf.name}` has no screenshot capture. Add a `@Preview` named " + "`\"-$key\"` (group = its form-factor bucket) under `src/screenshotTest`, " + "or exempt it in Route.kt with `// SCREENSHOT COVERAGE EXCEPTION: ${leaf.name}: `.", ) } } } companion object { internal const val ROUTE_NAME = "Route" internal const val EXCEPTION_PREFIX = "// SCREENSHOT COVERAGE EXCEPTION:" /** `WhatsAppRegistration.Code` → `whatsapp-registration-code`. */ internal fun routeKey(leafName: String): String = leafName.split('.').joinToString("-") { segment -> buildString { segment.forEachIndexed { index, c -> if (c.isUpperCase() && index > 0) append('-') append(c.lowercaseChar()) } } } /** * Route key → preview names under `/src/screenshotTest`. * Each preview counts for the longest route key it names. */ internal fun capturesByRoute(projectDir: File, routeKeys: Set): Map> { val dir = File(projectDir, "src/screenshotTest") if (!dir.isDirectory) return emptyMap() val nameArg = Regex("""@Preview\(name\s*=\s*"([^"]+)"""") val byRoute = mutableMapOf>() dir.walkTopDown() .filter { it.isFile && it.extension == "kt" } .forEach { file -> nameArg.findAll(file.readText()).forEach { match -> val previewName = match.groupValues[1] val named = previewName.replace(Regex("""^\d+-"""), "") val route = routeKeys .filter { key -> named == key || named.startsWith("$key-") } .maxByOrNull { it.length } if (route != null) byRoute.getOrPut(route) { mutableListOf() } += previewName } } return byRoute } val ISSUE: Issue = Issue.create( id = "RouteScreenshotCoverage", briefDescription = "Route has no screenshot capture", explanation = """ Every route needs at least one screenshot: each leaf destination of the \ module's `sealed interface Route` must have a capture in `src/screenshotTest` \ named `@Preview(name = "-", group = "")`, where the \ route key is the kebab-case leaf name (a `-…` suffix is a variant of the same \ route). Dialog destinations are routes like any other. A route that cannot be \ rendered (live call, WebView sign-in, Keystore-session wizard) is exempted per \ route in `Route.kt` with `// SCREENSHOT COVERAGE EXCEPTION: : `. \ See docs/screenshot-coverage.md. """.trimIndent(), category = Category.CORRECTNESS, priority = 6, severity = Severity.ERROR, implementation = Implementation( RouteScreenshotCoverageDetector::class.java, Scope.JAVA_FILE_SCOPE, ), ) } }