lint: commit the four pilot detectors that already gate main
- Commit
ee4399f7c494a3dbb0a53b8f3f96639fbdc8c173- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 23:19 UTC (4 days ago)
- Parents
29bb3c8
The ModernAppsIssueRegistry already lists RouteScreenshotCoverage, DialogAsRoute, FixtureDeterminism and NoDeadClick in the fatal set, and every main-tree build has enforced them — but their detector sources (and tests) sat UNTRACKED on the main checkout. Clean worktrees silently lacked the four detectors, so worktree agents verified "lint green" against a weaker ruleset and their commits failed release lint when the parent ran it from the main tree. That asymmetry broke ./install all repeatedly today and is what blocked the latest push at the pre-push backstop. This commits the four detector sources + their tests + the registry/marker-format/AGENTS.md changes that describe them, so every checkout enforces the same rules. No detector logic changes. Also fixes the hooks: modules with no lint task at all (lint-rules, build-logic) are skipped rather than failing task selection.
Diff
.githooks/pre-commit
diff --git a/.githooks/pre-commit b/.githooks/pre-commitindex 9e21f264ef..7de0426caf 100755--- a/.githooks/pre-commit+++ b/.githooks/pre-commit@@ -29,9 +29,12 @@ for m in $mods; do g="$(echo "$m" | tr / :)" # settings.gradle.kts Gradle keys: wear apps nest as :clock:wear, not :clock-wear case "$m" in *-wear) g="${g%-wear}:wear" ;; esac- # Apps have a release variant; pure library modules do not.- if grep -q 'common-conventions-app\|android.application\|application' "$m/build.gradle.kts" 2>/dev/null; then- tasks="$tasks :${g}:lintVitalRelease"+ # Non-app modules: gate on :lint if the module has one, else skip (pure+ # infra like lint-rules/build-logic carries no lint task at all).+ if [ "$g" = "lint-rules" ] || [ "$g" = "build-logic" ]; then+ continue+ elif grep -Eq 'common-conventions-library|java-library|kotlin\("jvm"\)|org.jetbrains.kotlin.jvm' "$m/build.gradle.kts" 2>/dev/null; then+ tasks="$tasks :${g}:lint" else tasks="$tasks :${g}:lintVitalRelease" fi
.githooks/pre-push
diff --git a/.githooks/pre-push b/.githooks/pre-pushindex fc60170770..dbc0a6990a 100755--- a/.githooks/pre-push+++ b/.githooks/pre-push@@ -31,7 +31,14 @@ while read -r local_ref local_sha remote_ref remote_sha; do tasks="" for m in $mods; do [ -f "$m/build.gradle.kts" ] || continue- tasks="$tasks :$(echo "$m" | tr / :):lintVitalRelease"+ g="$(echo "$m" | tr / :)"+ case "$m" in *-wear) g="${g%-wear}:wear" ;; esac+ # Pure-JVM/library modules have no release variant — gate on :lint.+ if grep -Eq 'common-conventions-library|java-library|kotlin\("jvm"\)|org.jetbrains.kotlin.jvm' "$m/build.gradle.kts" 2>/dev/null; then+ tasks="$tasks :${g}:lint"+ else+ tasks="$tasks :${g}:lintVitalRelease"+ fi done if [ -n "$tasks" ]; then echo "pre-push: release lint backstop for:$tasks"
lint-rules/AGENTS.md
diff --git a/lint-rules/AGENTS.md b/lint-rules/AGENTS.mdindex 73854ba996..2fe606ce02 100644--- a/lint-rules/AGENTS.md+++ b/lint-rules/AGENTS.md@@ -11,7 +11,7 @@ ## Overview **Purpose:** Custom Android-lint detectors enforcing repo conventions at build time — the executable form of root `AGENTS.md` §2. Fatal detectors break the build; advisory ones warn.-**Blocking:** every Modern-Apps detector is fatal in the app and library conventions. That includes `ToastUsage` (no `Toast` — use messenger), `DirectComposeAnimation` (no raw animation at call sites), `FileLength`, `DirectAndroidLog` (no direct `android.util.Log`), `DirectBuildDatabase` (subclass `RoomRepository`), `OneComposablePerFile`, `PackageStructure` (closed roots and flat `widget`), `RawScaffoldInApp` (use `AppScaffold`), `ScaffoldLoading` (scaffold owns refresh indication; standalone loading icons in app UI flagged), `ScaffoldSearch` (scaffold owns screen-level search via its `search` parameter; standalone `CommonSearchBar`/`SearchBar`/`SearchBarInputField` and reliably search-identified text fields in app UI flagged, exception marker `// SCAFFOLD SEARCH EXCEPTION: <reason>` for dialog/sheet/drawer-local and expandable-overlay search), `Room2Usage` (Room 3 only), `WindowInsetsInReusableComponent` (no padding in `library.ui`), and the comment-hygiene detectors (`CommentedOutCode`, `ExceptionMarkerFormat`, `TodoEvasion` with `CommentOnlyMatcher`).+**Blocking:** every Modern-Apps detector is fatal in the app and library conventions. That includes `ToastUsage` (no `Toast` — use messenger), `DirectComposeAnimation` (no raw animation at call sites), `FileLength`, `DirectAndroidLog` (no direct `android.util.Log`), `DirectBuildDatabase` (subclass `RoomRepository`), `OneComposablePerFile`, `PackageStructure` (closed roots and flat `widget`), `RawScaffoldInApp` (use `AppScaffold`), `ScaffoldLoading` (scaffold owns refresh indication; standalone loading icons in app UI flagged), `ScaffoldSearch` (scaffold owns screen-level search via its `search` parameter; standalone `CommonSearchBar`/`SearchBar`/`SearchBarInputField` and reliably search-identified text fields in app UI flagged, exception marker `// SCAFFOLD SEARCH EXCEPTION: <reason>` for dialog/sheet/drawer-local and expandable-overlay search), `Room2Usage` (Room 3 only), `RouteScreenshotCoverage` (every `Route` leaf needs a screenshot capture), `DialogAsRoute` (dialogs are `Route` destinations with `DialogPage()` metadata, not `remember`-state-gated `AlertDialog`/`Dialog`/`ModalBottomSheet`/`ConfirmDialog`/`…Dialog` calls in screens; definitions under `ui/dialogs/` and unconditional route-entry hosts are legal, escape `// DIALOG LOCAL EXCEPTION: <reason>`), `WindowInsetsInReusableComponent` (no padding in `library.ui`), `FixtureDeterminism` (no relative-now/unseeded randomness in `src/test` + `src/screenshotTest` fixtures; named fixed constants or seeded `Random(seed)` instead, deadline/elapsed/freshness idioms in unit tests excluded, escape `// FIXTURE RELATIVE-TIME EXCEPTION: <reason>`), `NoDeadClick` (no empty/comment-only `onClick` on Button/IconButton/FAB/MenuItem/ListItem-clickable in `src/main` unless `enabled = false`; label chips excluded by widget type, escape `// DEAD CLICK EXCEPTION: <reason>` for drag handles), and the comment-hygiene detectors (`CommentedOutCode`, `ExceptionMarkerFormat`, `TodoEvasion` with `CommentOnlyMatcher`). **Entry points:** `ModernAppsIssueRegistry.kt` → the detector for your rule → `LintPackageExclusions.kt` for scope. **Gotchas:** New detectors need registry entries + severity decisions (fatal vs advisory is a deliberate call). Fix code to green modules, never relax config (`detekt.yml` rationale is inline per the root card). @@ -32,6 +32,10 @@ - com/vayunmathur/lint/ExceptionMarkerFormatDetector.kt — escape-hatch marker format - com/vayunmathur/lint/TodoEvasionDetector.kt — TODO discipline - com/vayunmathur/lint/CommentOnlyMatcher.kt — shared matcher for comment detectors+- com/vayunmathur/lint/RouteScreenshotCoverageDetector.kt — route screenshot coverage+- com/vayunmathur/lint/DialogAsRouteDetector.kt — dialogs-as-routes rule+- com/vayunmathur/lint/FixtureDeterminismDetector.kt — deterministic test/screenshot fixtures (disk scan of `src/test` + `src/screenshotTest` in `afterCheckProject`)+- com/vayunmathur/lint/NoDeadClickDetector.kt — empty click handlers on clickable widgets in `src/main` - com/vayunmathur/lint/LintPackageExclusions.kt — detector scoping ## Verify (this module only)
lint-rules/src/main/java/com/vayunmathur/lint/DialogAsRouteDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/DialogAsRouteDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/DialogAsRouteDetector.ktnew file mode 100644index 0000000000..612d271f30--- /dev/null+++ b/lint-rules/src/main/java/com/vayunmathur/lint/DialogAsRouteDetector.kt@@ -0,0 +1,293 @@+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.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 com.intellij.psi.PsiElement+import com.intellij.psi.PsiRecursiveElementVisitor+import org.jetbrains.kotlin.psi.KtCallExpression+import org.jetbrains.kotlin.psi.KtFile+import org.jetbrains.kotlin.psi.KtIfExpression+import org.jetbrains.kotlin.psi.KtNamedFunction+import org.jetbrains.kotlin.psi.KtProperty+import org.jetbrains.kotlin.psi.KtQualifiedExpression+import org.jetbrains.kotlin.psi.KtWhenExpression+import org.jetbrains.uast.UElement+import org.jetbrains.uast.UFile+import java.io.File++/**+ * Dialogs are navigation destinations, not local screen state.+ *+ * A dialog that matters — a confirmation, a picker with a result, a small+ * editor — is a `Route` with `DialogPage()` metadata (the communicate+ * `DeleteConversationDialog` shape): the identity it acts on travels in the+ * route arguments, Back / process death / screenshots all see it, and the+ * dialog content is a stateless composable the route entry renders+ * unconditionally. The opposite shape — a screen holding+ * `var showXDialog by remember { mutableStateOf(false) }` (or a nullable+ * `pending…` / `…Target` state) and rendering a dialog only when that state+ * says so — hides a screen change inside a composable, so it is flagged here.+ *+ * What is flagged, deliberately narrowly (precision over recall):+ * - a call to `AlertDialog`, `Dialog`, `ModalBottomSheet` or `ConfirmDialog`+ * (the library's dialog primitives), or to any composable whose simple+ * name ends in `Dialog` (the app's own dialog composables, e.g.+ * `RenameTagDialog`), when the call is *gated* by local remember-state:+ * it sits inside an `if` / `when` whose condition mentions a+ * `remember`/`rememberSaveable` state property of the same file, or inside+ * a `state?.let { … }` / qualified `let` on such a property. Route+ * constructions (`backStack.add(Route.XDialog(...))`) are navigation, not+ * invocations, and are never flagged.+ * - one level of indirection: a dialog primitive inside a helper composable+ * of the same file is flagged when every fact above holds for the helper's+ * own call sites — e.g. a private `Custom…Dialog` in a screen file that is+ * only ever invoked under `if (showCustomDialog)`. The helper's gated call+ * site is flagged too.+ *+ * What is never flagged:+ * - dialog *definitions*: files under `ui/dialogs/` (their internal+ * text-field / wheel state is dialog-local and stays), and the shared+ * library (`com.vayunmathur.library.*`), which builds the primitives.+ * - unconditional dialog calls — a `DialogPage()` route entry rendering its+ * dialog content, or a dialog host invoked straight from such an entry.+ * Being shown is decided by the back stack, not by remembered state.+ * - menus, dropdowns and other in-screen sub-state: only dialog calls match.+ * - non-`src/main` sources (screenshot captures, tests).+ *+ * A dialog that genuinely cannot be a route yet (a multi-step flow whose+ * intermediate state has no route/result shape) opts out per file with:+ * `// DIALOG LOCAL EXCEPTION: <reason>` — the shape is validated by+ * [ExceptionMarkerFormatDetector].+ */+class DialogAsRouteDetector : Detector(), SourceCodeScanner {++ override fun getApplicableUastTypes(): List<Class<out UElement>> =+ 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(APP_PACKAGE_PREFIX)) return+ if (ExceptionMarkerFormatDetector.isLintRulesPackage(packageName)) return+ if (LintPackageExclusions.isExcluded(packageName)) return+ if (isLibraryPackage(packageName)) return++ val file = context.file ?: return+ if (!isMainSource(file)) return+ if (isDialogDefinitionFile(file)) return++ val ktFile = node.sourcePsi as? KtFile ?: return+ if (CommentOnlyMatcher.containsMarkerInComments(ktFile, EXCEPTION_MARKER)) return++ val stateVars = stateProperties(ktFile)+ if (stateVars.isEmpty()) return++ val calls = mutableListOf<KtCallExpression>()+ ktFile.accept(object : PsiRecursiveElementVisitor() {+ override fun visitElement(element: PsiElement) {+ super.visitElement(element)+ if (element is KtCallExpression) calls += element+ }+ })++ for (call in calls) {+ val name = simpleCalleeName(call) ?: continue+ if (!isDialogCall(call, name)) continue+ val gated = isGated(call, stateVars) ||+ isGatedViaEnclosingFunction(call, calls, stateVars)+ if (!gated) continue+ context.report(+ ISSUE,+ node,+ Location.create(+ file,+ ktFile.text,+ call.textRange.startOffset,+ call.textRange.endOffset,+ ),+ "Dialog `$name` is gated by local remember-state here; dialogs are routes. " ++ "Add a dialog destination (a `Route.…Dialog` entry with `DialogPage()` " ++ "metadata, its arguments in the route, its content stateless under " ++ "`ui/dialogs/`) and push it from the click handler instead of holding " ++ "`show…` / pending-target state in the screen. Definitions under " ++ "`ui/dialogs/` and unconditional route-entry hosts are not flagged. " ++ "A flow that genuinely cannot be a route yet opts out per file with " ++ "`$EXCEPTION_MARKER <reason>`.",+ )+ }+ }+ }++ /** Names of `remember`/`rememberSaveable` state properties declared in [ktFile]. */+ private fun stateProperties(ktFile: KtFile): Set<String> {+ val names = mutableSetOf<String>()+ ktFile.accept(object : PsiRecursiveElementVisitor() {+ override fun visitElement(element: PsiElement) {+ super.visitElement(element)+ if (element !is KtProperty) return+ val delegate = element.delegateExpression?.text.orEmpty()+ val initializer = element.initializer?.text.orEmpty()+ val holdsState = (delegate.contains("remember") || initializer.contains("remember")) &&+ (delegate.contains("mutableState") || initializer.contains("mutableState"))+ if (holdsState) element.name?.let { names += it }+ }+ })+ return names+ }++ /** Simple callee name: `AlertDialog`, or `AddGroupDialog` for `foo.AddGroupDialog(...)`. */+ private fun simpleCalleeName(call: KtCallExpression): String? {+ val callee = call.calleeExpression ?: return null+ val text = callee.text.substringBefore('<').trim()+ return text.substringAfterLast('.').takeIf { it.isNotEmpty() }+ }++ private fun isDialogCall(call: KtCallExpression, name: String): Boolean {+ // Route constructions are navigation targets, not dialog invocations.+ val calleeText = call.calleeExpression?.text.orEmpty()+ if (calleeText.startsWith("Route.") || calleeText.contains(".Route.")) return false+ if (name in DIRECT_DIALOG_CALLS) return true+ return name.endsWith(DIALOG_SUFFIX) && name.length > DIALOG_SUFFIX.length+ }++ /**+ * True when [element] is lexically gated by one of [stateVars]: an+ * enclosing `if`/`when` condition mentions the variable, or the element+ * sits in the selector of a qualified expression (`state?.let { … }`)+ * whose receiver mentions it. The walk stops at the enclosing function.+ */+ private fun isGated(element: PsiElement, stateVars: Set<String>): Boolean {+ var current: PsiElement? = element.parent+ while (current != null && current !is KtNamedFunction && current !is KtFile) {+ when (current) {+ is KtIfExpression ->+ if (mentionsAny(current.condition?.text, stateVars)) return true+ is KtWhenExpression ->+ if (mentionsAny(current.subjectExpression?.text, stateVars)) return true+ is KtQualifiedExpression -> {+ // Only the selector side is gated by the receiver; the+ // receiver expression itself is not.+ if (current.selectorExpression != null &&+ isAncestorOf(current.selectorExpression!!, element) &&+ mentionsAny(current.receiverExpression.text, stateVars)+ ) return true+ }+ }+ current = current.parent+ }+ return false+ }++ /**+ * One level of indirection: [call] sits inside a function whose own call+ * sites (elsewhere in the file) are gated by remember-state — the shape of+ * a private `Custom…Dialog` helper invoked only under `if (show…)`.+ */+ private fun isGatedViaEnclosingFunction(+ call: KtCallExpression,+ allCalls: List<KtCallExpression>,+ stateVars: Set<String>,+ ): Boolean {+ var current: PsiElement? = call.parent+ var enclosing: KtNamedFunction? = null+ while (current != null && current !is KtFile) {+ if (current is KtNamedFunction) {+ enclosing = current+ break+ }+ current = current.parent+ }+ val function = enclosing ?: return false+ val functionName = function.name ?: return false+ return allCalls.any { site ->+ site != call &&+ !isAncestorOf(function, site) &&+ simpleCalleeName(site) == functionName &&+ isGated(site, stateVars)+ }+ }++ private fun isAncestorOf(ancestor: PsiElement, element: PsiElement): Boolean {+ var current: PsiElement? = element+ while (current != null) {+ if (current == ancestor) return true+ current = current.parent+ }+ return false+ }++ private fun mentionsAny(text: String?, stateVars: Set<String>): Boolean {+ if (text.isNullOrEmpty()) return false+ return stateVars.any { name ->+ Regex("""(?<![A-Za-z0-9_])${Regex.escape(name)}(?![A-Za-z0-9_])""").containsMatchIn(text)+ }+ }++ private fun isMainSource(file: File): Boolean {+ val path = file.path.replace('\\', '/')+ if (!path.contains("/src/")) return true+ return path.contains("/src/main/")+ }++ private fun isDialogDefinitionFile(file: File): Boolean =+ file.path.replace('\\', '/').contains("/ui/dialogs/")++ companion object {+ private const val APP_PACKAGE_PREFIX = "com.vayunmathur."+ private const val LIBRARY_PREFIX = "com.vayunmathur.library"+ private const val DIALOG_SUFFIX = "Dialog"++ const val EXCEPTION_MARKER = "// DIALOG LOCAL EXCEPTION:"++ private val DIRECT_DIALOG_CALLS = setOf(+ "AlertDialog",+ "Dialog",+ "ModalBottomSheet",+ "ConfirmDialog",+ )++ private fun isLibraryPackage(packageName: String): Boolean =+ packageName == LIBRARY_PREFIX || packageName.startsWith("$LIBRARY_PREFIX.")++ val ISSUE: Issue = Issue.create(+ id = "DialogAsRoute",+ briefDescription = "Dialog gated by local remember-state; dialogs are navigation routes",+ explanation = """+ A dialog is a navigation destination: a `Route.…Dialog` entry with \+ `DialogPage()` metadata, the identity it acts on in the route arguments, \+ and a stateless dialog composable under `ui/dialogs/` that the entry \+ renders unconditionally (the communicate `DeleteConversationDialog` \+ shape). Rendering `AlertDialog`, `Dialog`, `ModalBottomSheet`, \+ `ConfirmDialog`, or an app dialog composable (a call whose name ends in \+ `Dialog`) only when a `remember`/`rememberSaveable` state property of \+ the same file says so — an `if (show…)` block, a `pending…?.let { … }`, \+ or a same-file helper only ever invoked under such a gate — hides a \+ screen change inside a composable and is flagged here.++ Dialog definitions under `ui/dialogs/`, unconditional route-entry \+ hosts, route constructions (`backStack.add(Route.…Dialog(...))`), \+ menus/dropdowns and other in-screen sub-state, and non-`src/main` \+ sources are not flagged. A multi-step flow that genuinely cannot be \+ a route yet opts out per file with \+ `// DIALOG LOCAL EXCEPTION: <reason>`.+ """.trimIndent(),+ category = Category.CORRECTNESS,+ priority = 6,+ severity = Severity.ERROR,+ implementation = Implementation(+ DialogAsRouteDetector::class.java,+ Scope.JAVA_FILE_SCOPE,+ ),+ )+ }+}
lint-rules/src/main/java/com/vayunmathur/lint/ExceptionMarkerFormatDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/ExceptionMarkerFormatDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/ExceptionMarkerFormatDetector.ktindex 1c5bc4ba4b..2e4ce1bff0 100644--- a/lint-rules/src/main/java/com/vayunmathur/lint/ExceptionMarkerFormatDetector.kt+++ b/lint-rules/src/main/java/com/vayunmathur/lint/ExceptionMarkerFormatDetector.kt@@ -37,6 +37,14 @@ import java.io.File * (see [ScaffoldLoadingDetector]) * - `// SCAFFOLD SEARCH EXCEPTION: <reason>` with colon and non-empty reason * (see [ScaffoldSearchDetector])+ * - `// SCREENSHOT COVERAGE EXCEPTION: <Leaf>: <reason>` naming the exempt+ * route leaf and a non-empty reason (see [RouteScreenshotCoverageDetector])+ * - `// DIALOG LOCAL EXCEPTION: <reason>` with colon and non-empty reason+ * (see [DialogAsRouteDetector])+ * - `// FIXTURE RELATIVE-TIME EXCEPTION: <reason>` with colon and non-empty+ * reason (see [FixtureDeterminismDetector])+ * - `// DEAD CLICK EXCEPTION: <reason>` with colon and non-empty reason+ * (see [NoDeadClickDetector]) * * A reason may continue on immediately following `//` lines, which the shared * scaffold/animation markers use for multi-line justifications.@@ -161,6 +169,74 @@ class ExceptionMarkerFormatDetector : Detector(), SourceCodeScanner { return } + if (text.contains(SCREENSHOT_KEYWORD)) {+ if (!text.contains(SCREENSHOT_PREFIX)) {+ report(context, node, file, source, base + text.indexOf(SCREENSHOT_KEYWORD), SCREENSHOT_KEYWORD.length,+ "Malformed Screenshot Coverage exception marker: the colon is required and a marker " ++ "without it does NOT opt the route out. Use " ++ "`// SCREENSHOT COVERAGE EXCEPTION: <Leaf>: <reason>`.")+ return+ }+ val rest = text.substring(text.indexOf(SCREENSHOT_PREFIX) + SCREENSHOT_PREFIX.length)+ val leaf = rest.substringBefore(':').trim()+ val reason = rest.substringAfter(':', "").trim()+ if (leaf.isEmpty() || reason.isEmpty()) {+ report(context, node, file, source, base + text.indexOf(SCREENSHOT_PREFIX), SCREENSHOT_PREFIX.length,+ "Screenshot Coverage exception marker without a route or a reason. Use " ++ "`// SCREENSHOT COVERAGE EXCEPTION: <Leaf>: <reason>` so the opt-out names " ++ "the route it exempts and stays reviewable.")+ }+ return+ }++ if (text.contains(DIALOG_KEYWORD)) {+ if (!text.contains(DIALOG_PREFIX)) {+ report(context, node, file, source, base + text.indexOf(DIALOG_KEYWORD), DIALOG_KEYWORD.length,+ "Malformed Dialog Local exception marker: the colon is required and a marker without " ++ "it does NOT opt the file out. Use `// DIALOG LOCAL EXCEPTION: <reason>`.")+ return+ }+ val reason = reasonAfter(text, DIALOG_PREFIX)+ if (!hasReason(source, comments, index, reason)) {+ report(context, node, file, source, base + text.indexOf(DIALOG_PREFIX), DIALOG_PREFIX.length,+ "Exception marker without a reason. Append `: <reason>` to " ++ "`// DIALOG LOCAL EXCEPTION:` so the opt-out stays reviewable.")+ }+ return+ }++ if (text.contains(FIXTURE_KEYWORD)) {+ if (!text.contains(FIXTURE_PREFIX)) {+ report(context, node, file, source, base + text.indexOf(FIXTURE_KEYWORD), FIXTURE_KEYWORD.length,+ "Malformed Fixture Relative-Time exception marker: the colon is required and a marker without " ++ "it does NOT opt the file out. Use `// FIXTURE RELATIVE-TIME EXCEPTION: <reason>`.")+ return+ }+ val reason = reasonAfter(text, FIXTURE_PREFIX)+ if (!hasReason(source, comments, index, reason)) {+ report(context, node, file, source, base + text.indexOf(FIXTURE_PREFIX), FIXTURE_PREFIX.length,+ "Exception marker without a reason. Append `: <reason>` to " ++ "`// FIXTURE RELATIVE-TIME EXCEPTION:` so the opt-out stays reviewable.")+ }+ return+ }++ if (text.contains(DEAD_CLICK_KEYWORD)) {+ if (!text.contains(DEAD_CLICK_PREFIX)) {+ report(context, node, file, source, base + text.indexOf(DEAD_CLICK_KEYWORD), DEAD_CLICK_KEYWORD.length,+ "Malformed Dead Click exception marker: the colon is required and a marker without " ++ "it does NOT opt the file out. Use `// DEAD CLICK EXCEPTION: <reason>`.")+ return+ }+ val reason = reasonAfter(text, DEAD_CLICK_PREFIX)+ if (!hasReason(source, comments, index, reason)) {+ report(context, node, file, source, base + text.indexOf(DEAD_CLICK_PREFIX), DEAD_CLICK_PREFIX.length,+ "Exception marker without a reason. Append `: <reason>` to " ++ "`// DEAD CLICK EXCEPTION:` so the opt-out stays reviewable.")+ }+ return+ }+ if (text.contains(ANIMATION_KEYWORD)) { if (!text.contains(ANIMATION_PREFIX)) { report(context, node, file, source, base + text.indexOf(ANIMATION_KEYWORD), ANIMATION_KEYWORD.length,@@ -245,6 +321,14 @@ class ExceptionMarkerFormatDetector : Detector(), SourceCodeScanner { private const val TOAST_PREFIX = "// TOAST EXCEPTION:" private const val ANIMATION_KEYWORD = "RAW ANIMATION EXCEPTION" private const val ANIMATION_PREFIX = "// RAW ANIMATION EXCEPTION:"+ private const val SCREENSHOT_KEYWORD = "SCREENSHOT COVERAGE EXCEPTION"+ private const val SCREENSHOT_PREFIX = "// SCREENSHOT COVERAGE EXCEPTION:"+ private const val DIALOG_KEYWORD = "DIALOG LOCAL EXCEPTION"+ private const val DIALOG_PREFIX = "// DIALOG LOCAL EXCEPTION:"+ private const val FIXTURE_KEYWORD = "FIXTURE RELATIVE-TIME EXCEPTION"+ private const val FIXTURE_PREFIX = "// FIXTURE RELATIVE-TIME EXCEPTION:"+ private const val DEAD_CLICK_KEYWORD = "DEAD CLICK EXCEPTION"+ private const val DEAD_CLICK_PREFIX = "// DEAD CLICK EXCEPTION:" /** Adjacent `//` line: only whitespace and exactly one line break between comments. */ private val ADJACENT_LINE = Regex("^\\h*\\R\\h*$")
lint-rules/src/main/java/com/vayunmathur/lint/FixtureDeterminismDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/FixtureDeterminismDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/FixtureDeterminismDetector.ktnew file mode 100644index 0000000000..3eeffbd71e--- /dev/null+++ b/lint-rules/src/main/java/com/vayunmathur/lint/FixtureDeterminismDetector.kt@@ -0,0 +1,248 @@+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.uast.UElement+import org.jetbrains.uast.UFile+import java.io.File++/**+ * Fixture data must be deterministic: no relative-to-now timestamps and no+ * unseeded randomness in `src/test` or `src/screenshotTest`.+ *+ * A screenshot fixture that reads `Clock.System.now()` renders a different+ * golden every day; a unit-test fixture seeded from the wall clock or an+ * unseeded `Random` flakes or drifts the same way. Both source sets are+ * scanned from disk in [afterCheckProject] rather than from the visited+ * sources — like [RouteScreenshotCoverageDetector], because+ * `src/screenshotTest` is a screenshot-test source set, not a lint-analysed+ * one, so its files are not guaranteed a visit.+ *+ * Banned (in fixture code):+ * - `Clock.System.now()`, `LocalDate.now()`, `LocalDateTime.now()`,+ * `Instant.now()`, `System.currentTimeMillis()` — relative-to-now values.+ * - `Random()` / `java.util.Random()` with no seed, `Random.Default`, and+ * `UUID.randomUUID()` — unseeded randomness. `Random(<seed>)` is fine.+ *+ * Precision choices (deliberate; these are not fixtures):+ * - Comments and string literals are stripped before matching, so a KDoc+ * sentence mentioning `Clock.System.now()` is not a violation.+ * - In `src/test` only, the recognised time-*control* idioms are out of+ * scope: deadline/timeout polling (`deadline = System.currentTimeMillis()+ * + …`, `while (System.currentTimeMillis() < deadline)`, pump/await-until+ * helpers), elapsed-time measurement (a `started`/`before` stamp later+ * subtracted, or a subtraction on the same line), and freshness assertions+ * (`assertTrue(ts <= System.currentTimeMillis())`). They read the clock to+ * bound or verify real time, never to build fixture data. Screenshot+ * fixtures get no such exemption: a preview must never read the clock.+ * - `SecureRandom` is out of scope: cryptographic test fakes+ * (e.g. `FakeAndroidKeyStore`) must draw real key material; no assertion+ * may depend on its bytes.+ *+ * Fix: replace the value with a named fixed constant (e.g.+ * `private val FIXED_NOW = Instant.fromEpochMilliseconds(1_768_651_200_000L)`)+ * so the fixture reads as data. Code that genuinely must seed relative to+ * the system-under-test's own real clock (a repository that stamps "now"+ * internally, where a fixed past timestamp would turn fresh data stale)+ * opts out per file with:+ * `// FIXTURE RELATIVE-TIME EXCEPTION: <reason>`.+ */+class FixtureDeterminismDetector : Detector(), SourceCodeScanner {++ override fun getApplicableUastTypes(): List<Class<out UElement>> =+ listOf(UFile::class.java)++ override fun createUastHandler(context: JavaContext): UElementHandler =+ object : UElementHandler() {+ override fun visitFile(node: UFile) {+ // Nothing to collect per file: the scan runs from disk in+ // afterCheckProject (see class KDoc).+ }+ }++ override fun afterCheckProject(context: Context) {+ for (rootName in SOURCE_SETS) {+ val root = File(context.project.dir, rootName)+ if (!root.isDirectory) continue+ val screenshot = rootName.contains(SHOT_MARKER)+ root.walkTopDown()+ .filter { it.isFile && (it.extension == "kt" || it.extension == "java") }+ .forEach { scanFile(context, it, screenshot) }+ }+ }++ private fun scanFile(context: Context, file: File, screenshot: Boolean) {+ val raw = file.readText()+ if (raw.contains(EXCEPTION_MARKER)) return+ val cleaned = stripCommentsAndStrings(raw)+ var offset = 0+ for (line in cleaned.lineSequence()) {+ checkLine(context, file, raw, line, offset, screenshot)+ offset += line.length + 1+ }+ }++ private fun checkLine(+ context: Context,+ file: File,+ raw: String,+ line: String,+ lineStart: Int,+ screenshot: Boolean,+ ) {+ if (line.isBlank()) return+ if (!screenshot && isTimeControlIdiom(line)) return+ for ((label, pattern) in BANNED) {+ val match = pattern.find(line) ?: continue+ val start = lineStart + match.range.first+ if (!reported.add("${file.absolutePath}:$start:$label")) continue+ context.report(+ ISSUE,+ Location.create(file, raw, start, start + match.value.length),+ "Non-deterministic fixture: `$label` reads the wall clock / unseeded " ++ "randomness, so this fixture changes on every run. Replace it with a " ++ "named fixed constant (a fixed `Instant`/epoch-millis/date, a seeded " ++ "`Random(seed)`, or a fixed UUID). Code that must seed relative to the " ++ "system-under-test's real clock opts out per file with " ++ "`$EXCEPTION_MARKER <reason>`.",+ )+ }+ }++ companion object {+ const val EXCEPTION_MARKER = "// FIXTURE RELATIVE-TIME EXCEPTION:"++ /**+ * (file, start, label) already reported. Lint instantiates a detector+ * per scope (and per dependency project under checkDependencies), so+ * the dedup set must live on the companion to suppress per-scope+ * duplicate reports of the same hit within one lint JVM.+ */+ private val reported = mutableSetOf<String>()++ private val SOURCE_SETS = listOf("src/test", "src/screenshotTest")+ private const val SHOT_MARKER = "screenshotTest"++ /** Banned call shapes, matched against comment/string-stripped source. */+ private val BANNED: List<Pair<String, Regex>> = listOf(+ "Clock.System.now()" to Regex("""Clock\s*\.\s*System\s*\.\s*now\s*\("""),+ "LocalDateTime.now()" to Regex("""(?<!\w)LocalDateTime\s*\.\s*now\s*\("""),+ "LocalDate.now()" to Regex("""(?<!\w)LocalDate\s*\.\s*now\s*\("""),+ "Instant.now()" to Regex("""(?<!\w)Instant\s*\.\s*now\s*\("""),+ "System.currentTimeMillis()" to Regex("""System\s*\.\s*currentTimeMillis\s*\("""),+ "UUID.randomUUID()" to Regex("""UUID\s*\.\s*randomUUID\s*\("""),+ "Random() unseeded" to Regex("""(?<![\w.])Random\s*\(\s*\)|Random\s*\.\s*Default"""),+ )++ private val DEADLINE_WORDS = listOf("deadline", "pumpmainuntil", "await", "until(")+ private val ELAPSED_STARTERS =+ Regex("""\bval\s+(start|started|before|t0|begin|elapsed)\w*\s*=""")++ /**+ * The non-fixture time-control idioms of `src/test` (see class KDoc):+ * deadline/timeout polling, elapsed measurement, freshness asserts.+ * Line-based by design — a banned call spread over a statement that+ * only becomes a deadline several lines later is reported, and the+ * file marker is the escape for that rare shape.+ */+ internal fun isTimeControlIdiom(line: String): Boolean {+ val lower = line.lowercase()+ if (DEADLINE_WORDS.any { it in lower }) return true+ val trimmed = line.trimStart()+ if (trimmed.startsWith("while") || trimmed.startsWith("if (") || trimmed.startsWith("if(")) return true+ if ("assert" in lower || "check(" in lower || "require(" in lower) return true+ if (ELAPSED_STARTERS.containsMatchIn(line)) return true+ // Elapsed subtraction on one line: `now() - started` or+ // `started - now()` (an identifier on the other side). A numeric+ // offset (`now() - 60_000L`, `now() - 10.minutes`) is a+ // relative-to-now fixture value, not a measurement: still banned.+ return BANNED.any { (_, p) ->+ p.findAll(line).any { m ->+ val after = line.substring(m.range.last + 1).trimStart()+ .removePrefix(")").trimStart()+ val before = line.substring(0, m.range.first).trimEnd()+ (after.startsWith("-") && after.drop(1).trimStart().firstOrNull()?.isDigit() == false) ||+ (before.endsWith("-") && before.dropLast(1).trimEnd().lastOrNull()?.isDigit() == false)+ }+ }+ }++ /**+ * Blank out `//`/`/* */` comments and string/char literals (including+ * raw `"""` strings), preserving length and newlines so offsets in+ * the cleaned text still map onto the raw file.+ */+ internal fun stripCommentsAndStrings(text: String): String {+ val out = StringBuilder(text.length)+ var i = 0+ while (i < text.length) {+ val c = text[i]+ val next = text.getOrNull(i + 1)+ when {+ c == '/' && next == '/' -> {+ while (i < text.length && text[i] != '\n') { out.append(' '); i++ }+ }+ c == '/' && next == '*' -> {+ out.append(" "); i += 2+ while (i < text.length && !(text[i] == '*' && text.getOrNull(i + 1) == '/')) {+ out.append(if (text[i] == '\n') '\n' else ' '); i+++ }+ if (i < text.length) { out.append(" "); i += 2 }+ }+ c == '"' && text.startsWith("\"\"\"", i) -> {+ out.append(" "); i += 3+ while (i < text.length && !text.startsWith("\"\"\"", i)) {+ out.append(if (text[i] == '\n') '\n' else ' '); i+++ }+ if (i < text.length) { out.append(" "); i += 3 }+ }+ c == '"' || c == '\'' -> {+ out.append(' '); i+++ while (i < text.length && text[i] != c && text[i] != '\n') {+ if (text[i] == '\\' && i + 1 < text.length) { out.append(" "); i += 2 }+ else { out.append(' '); i++ }+ }+ if (i < text.length && text[i] == c) { out.append(' '); i++ }+ }+ else -> { out.append(c); i++ }+ }+ }+ return out.toString()+ }++ val ISSUE: Issue = Issue.create(+ id = "FixtureDeterminism",+ briefDescription = "Non-deterministic test/screenshot fixture (relative-now or unseeded randomness)",+ explanation = """+ Test and screenshot fixtures must be deterministic. Reading \+ `Clock.System.now()`, `LocalDate.now()`, `LocalDateTime.now()`, \+ `Instant.now()` or `System.currentTimeMillis()`, or drawing from an \+ unseeded `Random()`/`Random.Default`/`UUID.randomUUID()`, makes the \+ fixture a function of when it runs: screenshot goldens drift daily \+ and unit fixtures flake. Use a named fixed constant or a seeded \+ `Random(seed)` instead. In unit tests the time-control idioms \+ (deadline polling, elapsed measurement, freshness assertions) are \+ not fixtures and are not flagged; screenshot fixtures are flagged \+ unconditionally. A file that must seed relative to the \+ system-under-test's real clock opts out with \+ `// FIXTURE RELATIVE-TIME EXCEPTION: <reason>`.+ """.trimIndent(),+ category = Category.CORRECTNESS,+ priority = 6,+ severity = Severity.ERROR,+ implementation = Implementation(+ FixtureDeterminismDetector::class.java,+ Scope.JAVA_FILE_SCOPE,+ ),+ )+ }+}
lint-rules/src/main/java/com/vayunmathur/lint/ModernAppsIssueRegistry.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/ModernAppsIssueRegistry.kt b/lint-rules/src/main/java/com/vayunmathur/lint/ModernAppsIssueRegistry.ktindex 21e4f38fd8..501659bd3e 100644--- a/lint-rules/src/main/java/com/vayunmathur/lint/ModernAppsIssueRegistry.kt+++ b/lint-rules/src/main/java/com/vayunmathur/lint/ModernAppsIssueRegistry.kt@@ -24,6 +24,10 @@ class ModernAppsIssueRegistry : IssueRegistry() { ExceptionMarkerFormatDetector.ISSUE, TodoEvasionDetector.ISSUE, CommentedOutCodeDetector.ISSUE,+ RouteScreenshotCoverageDetector.ISSUE,+ DialogAsRouteDetector.ISSUE,+ FixtureDeterminismDetector.ISSUE,+ NoDeadClickDetector.ISSUE, ) override val api: Int = CURRENT_API
lint-rules/src/main/java/com/vayunmathur/lint/NoDeadClickDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/NoDeadClickDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/NoDeadClickDetector.ktnew file mode 100644index 0000000000..4cf9f60967--- /dev/null+++ b/lint-rules/src/main/java/com/vayunmathur/lint/NoDeadClickDetector.kt@@ -0,0 +1,249 @@+package com.vayunmathur.lint++import com.android.tools.lint.detector.api.Category+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.Scope+import com.android.tools.lint.detector.api.Severity+import com.android.tools.lint.detector.api.SourceCodeScanner+import com.intellij.psi.PsiMethod+import org.jetbrains.kotlin.psi.KtFile+import org.jetbrains.uast.UCallExpression+import org.jetbrains.uast.UExpression+import org.jetbrains.uast.ULambdaExpression+import org.jetbrains.uast.ULiteralExpression+import org.jetbrains.uast.getParentOfType++/**+ * No dead clicks: a clickable widget whose click handler does nothing.+ *+ * A `Button`/`IconButton`/FAB/menu item/list row that renders as tappable+ * but whose `onClick` lambda is empty (or comment-only) is a broken promise+ * in the UI: the user taps, nothing happens, and nothing in review or in a+ * screenshot shows it. This detector flags the empty handler at the call+ * site in `src/main`.+ *+ * Widget set (by simple call name, resolved against Compose/library+ * containers): `Button`, `TextButton`, `OutlinedButton`,+ * `FilledTonalButton`, `ElevatedButton`, the FAB family, `IconButton`,+ * `IconToggleButton`, `DropdownMenuItem`, `MenuItem`, `SegmentedButton`,+ * and the TV row family (`TvButton`, `TvListRow`, `ListItem`). A widget+ * call's `Modifier.clickable`/`combinedClickable` is covered the same way+ * when it sits in that call's modifier (the list-row shape), and a bare+ * `clickable`/`combinedClickable` call is flagged wherever it appears.+ *+ * Precision choices (deliberate):+ * - `enabled = false` in the same call opts out: a disabled widget with an+ * empty handler is honest — it does not promise a tap. (Busy-state+ * buttons and display rows use this.)+ * - Display-only label chips are excluded by widget type: `AssistChip`,+ * `FilterChip`, chips generally are simply not in the widget set — the+ * repo renders read-only labels with them and they carry no click+ * promise this rule polices. Fix those by demoting the chip, not here.+ * - A `clickable`/`combinedClickable` with a non-empty `onLongClick` is+ * not dead: long-press-only rows (copy-on-long-press) work.+ * - Only a literal empty/comment-only lambda is flagged. A handler passed+ * as a reference (`onClick = onOpen`, `onClick = actions::save`) or a+ * parameter default is never guessed at.+ *+ * Fix, in order of preference: wire the handler to the real action;+ * disable the widget honestly (`enabled = false`); or demote it to a+ * non-button container (a `Box`/`Icon` with the same modifier). The one+ * legitimate shape left — a drag handle grip that must look like a button+ * while the reorder modifier owns the gesture — opts out per file with:+ * `// DEAD CLICK EXCEPTION: <reason>`.+ */+class NoDeadClickDetector : Detector(), SourceCodeScanner {++ override fun getApplicableMethodNames(): List<String> = APPLICABLE.toList()++ override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {+ val name = method.name+ val file = context.file+ if (!file.path.replace('\\', '/').contains("/src/main/")) return+ val packageName = context.uastFile?.packageName ?: return+ if (!packageName.startsWith(APP_PACKAGE_PREFIX)) return++ val ktFile = context.uastFile?.sourcePsi as? KtFile+ if (ktFile != null && CommentOnlyMatcher.containsMarkerInComments(ktFile, EXCEPTION_MARKER)) return++ if (name in CLICKABLE_CALLS) {+ checkClickable(context, node, method, enclosingWidgetName(node) ?: name)+ return+ }+ if (name !in WIDGET_CALLS) return+ if (!isWidgetContainer(method)) return+ if (hasDisabledFalse(node, method)) return++ // A clickable in this widget's own modifier (the list-row shape).+ var flagged = false+ for (arg in node.valueArguments) {+ val click = findNestedClickable(arg) ?: continue+ if (isDeadClickable(click, null)) {+ report(context, click, name)+ flagged = true+ }+ }+ if (flagged) return++ val onClick = argumentFor(node, method, "onClick") ?: return+ if (isEmptyLambda(onClick)) {+ report(context, node, name)+ }+ }++ private fun checkClickable(context: JavaContext, node: UCallExpression, method: PsiMethod, widgetName: String) {+ if (!isDeadClickable(node, method)) return+ // Widget calls check their own modifier's clickable (above); do not+ // double-report the same lambda from both visits.+ val parentCall = node.getParentOfType<UCallExpression>(strict = true)+ if (parentCall != null && parentCall.methodName in WIDGET_CALLS) return+ report(context, node, widgetName)+ }++ private fun report(context: JavaContext, node: UCallExpression, widgetName: String) {+ context.report(+ ISSUE,+ node,+ context.getLocation(node),+ "Dead click: `$widgetName` renders as tappable but its click handler is " ++ "empty, so tapping it does nothing. Wire it to the real action, disable " ++ "it honestly (`enabled = false`), or demote it to a non-button " ++ "container. A drag-handle grip whose reorder modifier owns the gesture " ++ "opts out per file with `$EXCEPTION_MARKER <reason>`.",+ )+ }++ /** True for an empty/comment-only `onClick` with no working `onLongClick` and not disabled. */+ private fun isDeadClickable(node: UCallExpression, method: PsiMethod?): Boolean {+ if (method != null && hasDisabledFalse(node, method)) return false+ val onLongClick = method?.let { argumentFor(node, it, "onLongClick") } ?: argumentByName(node, "onLongClick")+ if (onLongClick != null && !isEmptyLambda(onLongClick) && !isNullLiteral(onLongClick)) return false+ val onClick = (method?.let { argumentFor(node, it, "onClick") } ?: argumentByName(node, "onClick"))+ // Trailing lambda: Modifier.clickable { … }+ ?: node.valueArguments.lastOrNull()?.takeIf { it is ULambdaExpression }+ ?: return false+ return isEmptyLambda(onClick)+ }++ /** The nearest enclosing widget call's name, for the message (list-row modifier shape). */+ private fun enclosingWidgetName(node: UCallExpression): String? {+ var parent = node.getParentOfType<UCallExpression>(strict = true)+ while (parent != null) {+ val n = parent.methodName+ if (n in WIDGET_CALLS) return n+ parent = parent.getParentOfType<UCallExpression>(strict = true)+ }+ return null+ }++ private fun findNestedClickable(expr: UExpression): UCallExpression? {+ if (expr is UCallExpression && expr.methodName in CLICKABLE_CALLS) return expr+ // Modifier chains are nested calls (`.clickable{}.then(…)` etc.):+ // walk the UAST subtree for the first clickable call.+ var found: UCallExpression? = null+ expr.accept(object : org.jetbrains.uast.visitor.AbstractUastVisitor() {+ override fun visitCallExpression(node: UCallExpression): Boolean {+ if (found == null && node !== expr && node.methodName in CLICKABLE_CALLS) {+ found = node+ }+ return super.visitCallExpression(node)+ }+ })+ return found+ }++ private fun hasDisabledFalse(node: UCallExpression, method: PsiMethod): Boolean {+ val enabled = argumentFor(node, method, "enabled") ?: return false+ return enabled is ULiteralExpression && enabled.value == false+ }++ private fun isNullLiteral(expr: UExpression): Boolean =+ expr is ULiteralExpression && expr.isNull++ /**+ * Empty or comment-only lambda. UAST drops comments from the lambda+ * body, so a comment-only lambda and `{}` both have no expressions;+ * a body holding only another lambda's braces still counts as work+ * only if it has expressions — checked recursively by UAST shape.+ */+ private fun isEmptyLambda(expr: UExpression): Boolean {+ val lambda = expr as? ULambdaExpression ?: return false+ val body = lambda.body as? org.jetbrains.uast.UBlockExpression ?: return false+ return body.expressions.isEmpty()+ }++ /** Argument by parameter name via the resolved method's parameter list. */+ private fun argumentFor(node: UCallExpression, method: PsiMethod, paramName: String): UExpression? {+ val index = method.parameterList.parameters.indexOfFirst { it.name == paramName }+ if (index < 0) return argumentByName(node, paramName)+ return node.getArgumentForParameter(index)+ }++ /**+ * Argument by source-level named-argument shape: lint's UAST keeps+ * named arguments in [org.jetbrains.uast.UNamedExpression] wrappers in+ * some shapes and plain values in others, so match on the argument's+ * own name when present and fall back to the last lambda (trailing).+ */+ private fun argumentByName(node: UCallExpression, paramName: String): UExpression? {+ for (arg in node.valueArguments) {+ val named = arg as? org.jetbrains.uast.UNamedExpression+ if (named?.name == paramName) return named.expression+ }+ return null+ }++ private fun isWidgetContainer(method: PsiMethod): Boolean {+ val containing = method.containingClass?.qualifiedName ?: return true+ return containing.contains("compose") ||+ containing.startsWith("com.vayunmathur.library") ||+ containing.contains("androidx.tv") ||+ containing.contains("androidx.wear")+ }++ companion object {+ private const val APP_PACKAGE_PREFIX = "com.vayunmathur."++ const val EXCEPTION_MARKER = "// DEAD CLICK EXCEPTION:"++ private val WIDGET_CALLS = setOf(+ "Button", "TextButton", "OutlinedButton", "FilledTonalButton", "ElevatedButton",+ "FloatingActionButton", "SmallFloatingActionButton", "LargeFloatingActionButton",+ "ExtendedFloatingActionButton", "SmallExtendedFloatingActionButton",+ "IconButton", "IconToggleButton",+ "DropdownMenuItem", "MenuItem", "SegmentedButton",+ "TvButton", "TvListRow", "ListItem",+ )++ private val CLICKABLE_CALLS = setOf("clickable", "combinedClickable")++ private val APPLICABLE = WIDGET_CALLS + CLICKABLE_CALLS++ val ISSUE: Issue = Issue.create(+ id = "NoDeadClick",+ briefDescription = "Clickable widget with an empty click handler",+ explanation = """+ A Button, IconButton, FAB, menu item, segmented button, TV row, \+ ListItem, or Modifier.clickable/combinedClickable whose onClick lambda \+ is empty (or comment-only) renders as tappable and does nothing when \+ tapped. Wire the handler to the real action, disable the widget \+ honestly with `enabled = false`, or demote it to a non-button \+ container. Display-only label chips are excluded by widget type, \+ `enabled = false` widgets are honest, and long-press-only rows with \+ a working onLongClick are not dead. A drag-handle grip whose reorder \+ modifier owns the gesture opts out per file with \+ `// DEAD CLICK EXCEPTION: <reason>`.+ """.trimIndent(),+ category = Category.CORRECTNESS,+ priority = 6,+ severity = Severity.ERROR,+ implementation = Implementation(+ NoDeadClickDetector::class.java,+ Scope.JAVA_FILE_SCOPE,+ ),+ )+ }+}
lint-rules/src/main/java/com/vayunmathur/lint/RouteScreenshotCoverageDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/RouteScreenshotCoverageDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/RouteScreenshotCoverageDetector.ktnew file mode 100644index 0000000000..6b7ad7169a--- /dev/null+++ b/lint-rules/src/main/java/com/vayunmathur/lint/RouteScreenshotCoverageDetector.kt@@ -0,0 +1,200 @@+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 = "<number>-<route-key>", group = "<bucket>")`, 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: <Leaf>: <reason>` 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<Leaf>()+ private val exemptions = mutableSetOf<String>()+ private var routePackage: String? = null++ override fun getApplicableUastTypes(): List<Class<out UElement>> =+ 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<KtClass>()+ .filter { it.name == ROUTE_NAME && it.hasModifier(KtTokens.SEALED_KEYWORD) }+ .forEach { route ->+ routePackage = packageName+ route.declarations+ .filterIsInstance<KtClassOrObject>()+ .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<String>, file: File) {+ val name = node.name ?: return+ val children = node.declarations.filterIsInstance<KtClassOrObject>()+ 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 " ++ "`\"<n>-$key\"` (group = its form-factor bucket) under `src/screenshotTest`, " ++ "or exempt it in Route.kt with `// SCREENSHOT COVERAGE EXCEPTION: ${leaf.name}: <reason>`.",+ )+ }+ }+ }++ 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 `<projectDir>/src/screenshotTest`.+ * Each preview counts for the longest route key it names.+ */+ internal fun capturesByRoute(projectDir: File, routeKeys: Set<String>): Map<String, List<String>> {+ val dir = File(projectDir, "src/screenshotTest")+ if (!dir.isDirectory) return emptyMap()+ val nameArg = Regex("""@Preview\(name\s*=\s*"([^"]+)"""")+ val byRoute = mutableMapOf<String, MutableList<String>>()+ 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 = "<number>-<route-key>", group = "<bucket>")`, 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: <Leaf>: <reason>`. \+ See docs/screenshot-coverage.md.+ """.trimIndent(),+ category = Category.CORRECTNESS,+ priority = 6,+ severity = Severity.ERROR,+ implementation = Implementation(+ RouteScreenshotCoverageDetector::class.java,+ Scope.JAVA_FILE_SCOPE,+ ),+ )+ }+}
lint-rules/src/test/java/com/vayunmathur/lint/DialogAsRouteDetectorTest.kt
diff --git a/lint-rules/src/test/java/com/vayunmathur/lint/DialogAsRouteDetectorTest.kt b/lint-rules/src/test/java/com/vayunmathur/lint/DialogAsRouteDetectorTest.ktnew file mode 100644index 0000000000..e86d59e8f1--- /dev/null+++ b/lint-rules/src/test/java/com/vayunmathur/lint/DialogAsRouteDetectorTest.kt@@ -0,0 +1,307 @@+package com.vayunmathur.lint++import com.android.tools.lint.checks.infrastructure.LintDetectorTest+import com.android.tools.lint.checks.infrastructure.TestFile+import com.android.tools.lint.checks.infrastructure.TestFiles.kotlin+import com.android.tools.lint.checks.infrastructure.TestMode+import com.android.tools.lint.detector.api.Detector+import com.android.tools.lint.detector.api.Issue+import org.junit.Test+import org.junit.runner.RunWith+import org.junit.runners.JUnit4++@RunWith(JUnit4::class)+class DialogAsRouteDetectorTest : LintDetectorTest() {++ override fun getDetector(): Detector = DialogAsRouteDetector()++ override fun getIssues(): List<Issue> = listOf(DialogAsRouteDetector.ISSUE)++ @Test+ fun gatedAlertDialogInScreenIsFlagged() {+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/main/java/com/vayunmathur/example/ui/ListScreen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import androidx.compose.runtime.mutableStateOf+ import androidx.compose.runtime.remember+ import com.vayunmathur.library.ui.AlertDialog+ @Composable fun ListScreen() {+ var showDeleteDialog by remember { mutableStateOf(false) }+ if (showDeleteDialog) {+ AlertDialog(onDismissRequest = { showDeleteDialog = false })+ }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun nullablePendingStateLetDialogIsFlagged() {+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/main/java/com/vayunmathur/example/ui/ListScreen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import androidx.compose.runtime.mutableStateOf+ import androidx.compose.runtime.remember+ import com.vayunmathur.library.ui.ConfirmDialog+ @Composable fun ListScreen() {+ var pendingName by remember { mutableStateOf<String?>(null) }+ pendingName?.let { name ->+ ConfirmDialog(title = name, confirmLabel = "Delete", onConfirm = {}, onDismiss = {})+ }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun customDialogComposableGatedByStateIsFlagged() {+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/main/java/com/vayunmathur/example/ui/ListScreen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import androidx.compose.runtime.mutableStateOf+ import androidx.compose.runtime.rememberSaveable+ @Composable fun ListScreen() {+ var renaming by rememberSaveable { mutableStateOf<String?>(null) }+ renaming?.let { tag ->+ RenameTagDialog(tag = tag, onDismiss = { renaming = null })+ }+ }+ @Composable fun RenameTagDialog(tag: String, onDismiss: () -> Unit) {}+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun gatedModalBottomSheetIsFlagged() {+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/main/java/com/vayunmathur/example/ui/ListScreen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import androidx.compose.runtime.mutableStateOf+ import androidx.compose.runtime.remember+ import com.vayunmathur.library.ui.ModalBottomSheet+ @Composable fun ListScreen() {+ var showSheet by remember { mutableStateOf(false) }+ if (showSheet) {+ ModalBottomSheet(onDismissRequest = { showSheet = false }) {}+ }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun dialogInsideSameFileHelperInvokedUnderGateIsFlagged() {+ // The helper's AlertDialog and its gated call site are both reported:+ // the definition does not become legal by moving one brace away.+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/main/java/com/vayunmathur/example/ui/EditScreen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import androidx.compose.runtime.mutableStateOf+ import androidx.compose.runtime.remember+ import com.vayunmathur.library.ui.AlertDialog+ @Composable fun EditScreen() {+ var showCustomDialog by remember { mutableStateOf(false) }+ if (showCustomDialog) {+ CustomReminderDialog(onDismiss = { showCustomDialog = false })+ }+ }+ @Composable private fun CustomReminderDialog(onDismiss: () -> Unit) {+ AlertDialog(onDismissRequest = onDismiss)+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(2)+ }++ @Test+ fun unconditionalDialogInRouteEntryIsClean() {+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/main/java/com/vayunmathur/example/ui/DialogEntries.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.ConfirmDialog+ @Composable fun DeleteDialogHost(onConfirm: () -> Unit, onDismiss: () -> Unit) {+ ConfirmDialog(title = "Delete?", confirmLabel = "Delete", onConfirm = onConfirm, onDismiss = onDismiss)+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun dialogDefinitionUnderDialogsPackageIsClean() {+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/main/java/com/vayunmathur/example/ui/dialogs/RenameDialog.kt",+ """+ package com.vayunmathur.example.ui.dialogs+ import androidx.compose.runtime.Composable+ import androidx.compose.runtime.mutableStateOf+ import androidx.compose.runtime.remember+ import com.vayunmathur.library.ui.AlertDialog+ @Composable fun RenameDialog(onDismiss: () -> Unit) {+ var showHelp by remember { mutableStateOf(false) }+ if (showHelp) {+ AlertDialog(onDismissRequest = { showHelp = false })+ }+ AlertDialog(onDismissRequest = onDismiss)+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun routeConstructionAndUnconditionalContentCallAreClean() {+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/main/java/com/vayunmathur/example/ui/ListScreen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import androidx.compose.runtime.mutableStateOf+ import androidx.compose.runtime.remember+ @Composable fun ListScreen(openDialog: () -> Unit) {+ var query by remember { mutableStateOf("") }+ if (query.isNotEmpty()) {+ HelperText(query)+ }+ }+ @Composable fun HelperText(text: String) {}+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun exceptionMarkerOptsOut() {+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/main/java/com/vayunmathur/example/ui/ListScreen.kt",+ """+ package com.vayunmathur.example.ui+ // DIALOG LOCAL EXCEPTION: multi-step transfer flow; route conversion is a separate change+ import androidx.compose.runtime.Composable+ import androidx.compose.runtime.mutableStateOf+ import androidx.compose.runtime.remember+ import com.vayunmathur.library.ui.AlertDialog+ @Composable fun ListScreen() {+ var showDialog by remember { mutableStateOf(false) }+ if (showDialog) {+ AlertDialog(onDismissRequest = { showDialog = false })+ }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun libraryPackageIsExempt() {+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/main/java/com/vayunmathur/library/ui/Internal.kt",+ """+ package com.vayunmathur.library.ui+ import androidx.compose.runtime.Composable+ import androidx.compose.runtime.mutableStateOf+ import androidx.compose.runtime.remember+ @Composable fun Internal() {+ var showDialog by remember { mutableStateOf(false) }+ if (showDialog) {+ AlertDialog(onDismissRequest = { showDialog = false })+ }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun screenshotTestSourceIsSkipped() {+ lint().files(UI_STUBS, STATE_STUBS, kotlin(+ "src/screenshotTest/kotlin/com/vayunmathur/example/ui/Previews.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import androidx.compose.runtime.mutableStateOf+ import androidx.compose.runtime.remember+ import com.vayunmathur.library.ui.AlertDialog+ @Composable fun PreviewDialog() {+ var showDialog by remember { mutableStateOf(true) }+ if (showDialog) {+ AlertDialog(onDismissRequest = { showDialog = false })+ }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ companion object {+ private val STATE_STUBS: TestFile = kotlin(+ "src/androidx/compose/runtime/StateStubs.kt",+ """+ package androidx.compose.runtime+ annotation class Composable+ interface State<T> { val value: T }+ class MutableState<T>(override var value: T) : State<T>+ fun <T> mutableStateOf(value: T): MutableState<T> = MutableState(value)+ fun <T> remember(calculation: () -> T): T = calculation()+ fun <T> rememberSaveable(calculation: () -> T): T = calculation()+ """.trimIndent(),+ )++ private val UI_STUBS: TestFile = kotlin(+ "src/com/vayunmathur/library/ui/UiStubs.kt",+ """+ package com.vayunmathur.library.ui+ import androidx.compose.runtime.Composable+ @Composable fun AlertDialog(onDismissRequest: () -> Unit) {}+ @Composable fun ConfirmDialog(title: String, confirmLabel: String, onConfirm: () -> Unit, onDismiss: () -> Unit) {}+ @Composable fun ModalBottomSheet(onDismissRequest: () -> Unit, content: @Composable () -> Unit) {}+ """.trimIndent(),+ )+ }+}++@RunWith(JUnit4::class)+class DialogLocalMarkerFormatTest : LintDetectorTest() {++ override fun getDetector(): Detector = ExceptionMarkerFormatDetector()++ override fun getIssues(): List<Issue> = listOf(ExceptionMarkerFormatDetector.ISSUE)++ @Test+ fun wellFormedDialogMarkerIsClean() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // DIALOG LOCAL EXCEPTION: multi-step flow, no route shape yet+ class Screen+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun dialogMarkerWithoutReasonIsFlagged() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // DIALOG LOCAL EXCEPTION:+ class Screen+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun dialogMarkerWithoutColonIsFlagged() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // DIALOG LOCAL EXCEPTION multi-step flow+ class Screen+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }+}
lint-rules/src/test/java/com/vayunmathur/lint/FixtureDeterminismDetectorTest.kt
diff --git a/lint-rules/src/test/java/com/vayunmathur/lint/FixtureDeterminismDetectorTest.kt b/lint-rules/src/test/java/com/vayunmathur/lint/FixtureDeterminismDetectorTest.ktnew file mode 100644index 0000000000..280ef10268--- /dev/null+++ b/lint-rules/src/test/java/com/vayunmathur/lint/FixtureDeterminismDetectorTest.kt@@ -0,0 +1,230 @@+package com.vayunmathur.lint++import com.android.tools.lint.checks.infrastructure.LintDetectorTest+import com.android.tools.lint.checks.infrastructure.TestFiles.kotlin+import com.android.tools.lint.checks.infrastructure.TestMode+import com.android.tools.lint.detector.api.Detector+import com.android.tools.lint.detector.api.Issue+import org.junit.Test+import org.junit.runner.RunWith+import org.junit.runners.JUnit4++@RunWith(JUnit4::class)+class FixtureDeterminismDetectorTest : LintDetectorTest() {++ override fun getDetector(): Detector = FixtureDeterminismDetector()++ override fun getIssues(): List<Issue> = listOf(FixtureDeterminismDetector.ISSUE)++ @Test+ fun screenshotRelativeNowIsFlagged() {+ lint().files(kotlin(+ "src/screenshotTest/kotlin/com/vayunmathur/example/ui/MetadataPreviews.kt",+ """+ package com.vayunmathur.example.ui+ import kotlin.time.Clock+ private val now = Clock.System.now()+ class MetadataPreviews+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun screenshotFixedConstantIsClean() {+ lint().files(kotlin(+ "src/screenshotTest/kotlin/com/vayunmathur/example/ui/MetadataPreviews.kt",+ """+ package com.vayunmathur.example.ui+ import kotlin.time.Instant+ private val FIXED_NOW = Instant.fromEpochMilliseconds(1_768_651_200_000L)+ class MetadataPreviews+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun unitFixtureRelativeNowIsFlagged() {+ lint().files(kotlin(+ "src/test/java/com/vayunmathur/example/FooTest.kt",+ """+ package com.vayunmathur.example+ class FooTest {+ val stamped = System.currentTimeMillis()+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun unitFixtureLocalDateNowIsFlagged() {+ lint().files(kotlin(+ "src/test/java/com/vayunmathur/example/FooTest.kt",+ """+ package com.vayunmathur.example+ import java.time.LocalDate+ class FooTest {+ val today = LocalDate.now()+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun deadlinePollingIsClean() {+ lint().files(kotlin(+ "src/test/java/com/vayunmathur/example/FooTest.kt",+ """+ package com.vayunmathur.example+ class FooTest {+ fun await() {+ val deadline = System.currentTimeMillis() + 5_000+ while (System.currentTimeMillis() < deadline) { Thread.sleep(50) }+ }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun elapsedMeasurementIsClean() {+ lint().files(kotlin(+ "src/test/java/com/vayunmathur/example/FooTest.kt",+ """+ package com.vayunmathur.example+ class FooTest {+ fun timed() {+ val started = System.currentTimeMillis()+ println(System.currentTimeMillis() - started)+ }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun relativeFixtureOffsetIsFlagged() {+ // now() - <numeric offset> builds a fixture timestamp, not a measurement.+ lint().files(kotlin(+ "src/test/java/com/vayunmathur/example/FooTest.kt",+ """+ package com.vayunmathur.example+ class FooTest {+ val state = System.currentTimeMillis() - 60_000L+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun unseededRandomAndUuidAreFlagged() {+ lint().files(kotlin(+ "src/test/java/com/vayunmathur/example/FooTest.kt",+ """+ package com.vayunmathur.example+ import java.util.UUID+ import kotlin.random.Random+ class FooTest {+ val a = Random()+ val b = UUID.randomUUID()+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(2)+ }++ @Test+ fun seededRandomIsClean() {+ lint().files(kotlin(+ "src/test/java/com/vayunmathur/example/FooTest.kt",+ """+ package com.vayunmathur.example+ import kotlin.random.Random+ class FooTest {+ val a = Random(42)+ val b = Random(seed = 7)+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun mentionInCommentAndStringIsClean() {+ lint().files(kotlin(+ "src/test/java/com/vayunmathur/example/FooTest.kt",+ """+ package com.vayunmathur.example+ // Never call Clock.System.now() in a fixture.+ class FooTest {+ val doc = "System.currentTimeMillis() is banned here"+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun exceptionMarkerOptsOut() {+ lint().files(kotlin(+ "src/test/java/com/vayunmathur/example/FooTest.kt",+ """+ package com.vayunmathur.example+ // FIXTURE RELATIVE-TIME EXCEPTION: seeds relative to the repository's own real-clock stamps+ class FooTest {+ val stamped = System.currentTimeMillis()+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun mainSourceIsOutOfScope() {+ lint().files(kotlin(+ "src/main/java/com/vayunmathur/example/Foo.kt",+ """+ package com.vayunmathur.example+ class Foo {+ val stamped = System.currentTimeMillis()+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }+}++@RunWith(JUnit4::class)+class FixtureMarkerFormatTest : LintDetectorTest() {++ override fun getDetector(): Detector = ExceptionMarkerFormatDetector()++ override fun getIssues(): List<Issue> = listOf(ExceptionMarkerFormatDetector.ISSUE)++ @Test+ fun wellFormedFixtureMarkerIsClean() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // FIXTURE RELATIVE-TIME EXCEPTION: SUT stamps real now internally+ class Foo+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun fixtureMarkerWithoutReasonIsFlagged() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // FIXTURE RELATIVE-TIME EXCEPTION:+ class Foo+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun fixtureMarkerWithoutColonIsFlagged() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // FIXTURE RELATIVE-TIME EXCEPTION SUT stamps real now+ class Foo+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }+}
lint-rules/src/test/java/com/vayunmathur/lint/NoDeadClickDetectorTest.kt
diff --git a/lint-rules/src/test/java/com/vayunmathur/lint/NoDeadClickDetectorTest.kt b/lint-rules/src/test/java/com/vayunmathur/lint/NoDeadClickDetectorTest.ktnew file mode 100644index 0000000000..b185d54a42--- /dev/null+++ b/lint-rules/src/test/java/com/vayunmathur/lint/NoDeadClickDetectorTest.kt@@ -0,0 +1,296 @@+package com.vayunmathur.lint++import com.android.tools.lint.checks.infrastructure.LintDetectorTest+import com.android.tools.lint.checks.infrastructure.TestFile+import com.android.tools.lint.checks.infrastructure.TestFiles.kotlin+import com.android.tools.lint.checks.infrastructure.TestMode+import com.android.tools.lint.detector.api.Detector+import com.android.tools.lint.detector.api.Issue+import org.junit.Test+import org.junit.runner.RunWith+import org.junit.runners.JUnit4++@RunWith(JUnit4::class)+class NoDeadClickDetectorTest : LintDetectorTest() {++ override fun getDetector(): Detector = NoDeadClickDetector()++ override fun getIssues(): List<Issue> = listOf(NoDeadClickDetector.ISSUE)++ @Test+ fun emptyButtonOnClickIsFlagged() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.Button+ import com.vayunmathur.library.ui.Text+ @Composable fun Screen() {+ Button(onClick = {}) { Text("Save") }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun commentOnlyOnClickIsFlagged() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.IconButton+ @Composable fun Screen() {+ IconButton(onClick = {+ // TODO: wire overflow menu+ }) { }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun wiredButtonIsClean() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.Button+ import com.vayunmathur.library.ui.Text+ @Composable fun Screen(save: () -> Unit) {+ Button(onClick = save) { Text("Save") }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun disabledButtonWithEmptyOnClickIsClean() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.Button+ import com.vayunmathur.library.ui.Text+ @Composable fun Screen() {+ Button(onClick = {}, enabled = false) { Text("Working…") }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun labelChipIsCleanByWidgetType() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.AssistChip+ import com.vayunmathur.library.ui.Text+ @Composable fun Screen() {+ AssistChip(onClick = {}, label = { Text("Due today") })+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun menuItemWithEmptyOnClickIsFlagged() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.DropdownMenuItem+ import com.vayunmathur.library.ui.Text+ @Composable fun Screen() {+ DropdownMenuItem(text = { Text("Info") }, onClick = {})+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun disabledMenuItemIsClean() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.DropdownMenuItem+ import com.vayunmathur.library.ui.Text+ @Composable fun Screen() {+ DropdownMenuItem(text = { Text("Synced") }, onClick = {}, enabled = false)+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun emptyClickableModifierIsFlagged() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.foundation.clickable+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.Box+ @Composable fun Screen() {+ Box(modifier = androidx.compose.ui.Modifier.clickable {})+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun longPressOnlyRowIsClean() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.foundation.combinedClickable+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.ListItem+ import com.vayunmathur.library.ui.Text+ @Composable fun Screen(copy: () -> Unit) {+ ListItem(+ headlineContent = { Text("Row") },+ modifier = androidx.compose.ui.Modifier.combinedClickable(onClick = {}, onLongClick = copy),+ )+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun listItemDeadClickableIsFlagged() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.foundation.clickable+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.ListItem+ import com.vayunmathur.library.ui.Text+ @Composable fun Screen() {+ ListItem(+ headlineContent = { Text("Row") },+ modifier = androidx.compose.ui.Modifier.clickable {},+ )+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun exceptionMarkerOptsOut() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/main/java/com/vayunmathur/example/ui/Screen.kt",+ """+ package com.vayunmathur.example.ui+ // DEAD CLICK EXCEPTION: drag-handle grip; the reorder modifier owns the gesture+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.IconButton+ @Composable fun Screen() {+ IconButton(onClick = {}) { }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun testSourceIsOutOfScope() {+ lint().files(UI_STUBS, COMPOSABLE_STUB, MODIFIER_STUB, FOUNDATION_STUB, kotlin(+ "src/test/java/com/vayunmathur/example/ui/ScreenTest.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import com.vayunmathur.library.ui.Button+ import com.vayunmathur.library.ui.Text+ @Composable fun Screen() {+ Button(onClick = {}) { Text("Save") }+ }+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ companion object {+ private val MODIFIER_STUB: TestFile = kotlin(+ "src/androidx/compose/ui/Modifier.kt",+ """+ package androidx.compose.ui+ open class Modifier {+ companion object : Modifier()+ fun then(other: Modifier): Modifier = other+ }+ """.trimIndent(),+ )++ private val FOUNDATION_STUB: TestFile = kotlin(+ "src/androidx/compose/foundation/Clickable.kt",+ """+ package androidx.compose.foundation+ import androidx.compose.ui.Modifier+ fun Modifier.clickable(enabled: Boolean = true, onClick: () -> Unit): Modifier = this+ fun Modifier.combinedClickable(enabled: Boolean = true, onClick: () -> Unit, onLongClick: (() -> Unit)? = null): Modifier = this+ """.trimIndent(),+ )++ private val COMPOSABLE_STUB: TestFile = kotlin(+ "src/androidx/compose/runtime/Composable.kt",+ """+ package androidx.compose.runtime+ annotation class Composable+ """.trimIndent(),+ )++ private val UI_STUBS: TestFile = kotlin(+ "src/com/vayunmathur/library/ui/UiStubs.kt",+ """+ package com.vayunmathur.library.ui+ import androidx.compose.runtime.Composable+ @Composable fun Button(onClick: () -> Unit, enabled: Boolean = true, content: @Composable () -> Unit) {}+ @Composable fun IconButton(onClick: () -> Unit, enabled: Boolean = true, content: @Composable () -> Unit) {}+ @Composable fun DropdownMenuItem(text: @Composable () -> Unit, onClick: () -> Unit, enabled: Boolean = true) {}+ @Composable fun AssistChip(onClick: () -> Unit, label: @Composable () -> Unit, enabled: Boolean = true) {}+ @Composable fun ListItem(headlineContent: @Composable () -> Unit, modifier: androidx.compose.ui.Modifier = androidx.compose.ui.Modifier) {}+ @Composable fun Box(modifier: androidx.compose.ui.Modifier = androidx.compose.ui.Modifier) {}+ @Composable fun Text(text: String) {}+ """.trimIndent(),+ )+ }+}++@RunWith(JUnit4::class)+class DeadClickMarkerFormatTest : LintDetectorTest() {++ override fun getDetector(): Detector = ExceptionMarkerFormatDetector()++ override fun getIssues(): List<Issue> = listOf(ExceptionMarkerFormatDetector.ISSUE)++ @Test+ fun wellFormedDeadClickMarkerIsClean() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // DEAD CLICK EXCEPTION: drag handle; reorder modifier owns the gesture+ class Foo+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun deadClickMarkerWithoutReasonIsFlagged() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // DEAD CLICK EXCEPTION:+ class Foo+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }+}
lint-rules/src/test/java/com/vayunmathur/lint/RouteScreenshotCoverageDetectorTest.kt
diff --git a/lint-rules/src/test/java/com/vayunmathur/lint/RouteScreenshotCoverageDetectorTest.kt b/lint-rules/src/test/java/com/vayunmathur/lint/RouteScreenshotCoverageDetectorTest.ktnew file mode 100644index 0000000000..798fc591b9--- /dev/null+++ b/lint-rules/src/test/java/com/vayunmathur/lint/RouteScreenshotCoverageDetectorTest.kt@@ -0,0 +1,238 @@+package com.vayunmathur.lint++import com.android.tools.lint.checks.infrastructure.LintDetectorTest+import com.android.tools.lint.checks.infrastructure.TestFile+import com.android.tools.lint.checks.infrastructure.TestMode+import com.android.tools.lint.checks.infrastructure.TestFiles.kotlin+import com.android.tools.lint.detector.api.Detector+import com.android.tools.lint.detector.api.Issue+import org.junit.Test+import org.junit.runner.RunWith+import org.junit.runners.JUnit4++@RunWith(JUnit4::class)+class RouteScreenshotCoverageDetectorTest : LintDetectorTest() {++ override fun getDetector(): Detector = RouteScreenshotCoverageDetector()++ override fun getIssues(): List<Issue> = listOf(RouteScreenshotCoverageDetector.ISSUE)++ @Test+ fun allRoutesCoveredIsClean() {+ lint().files(NAVKEY_STUB, PREVIEW_STUBS, COMPOSABLE_STUB, PREVIEWTEST_STUB, routeFile(), previews("1-feed", "2-story")).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun unmappedRouteIsFlagged() {+ lint().files(NAVKEY_STUB, PREVIEW_STUBS, COMPOSABLE_STUB, PREVIEWTEST_STUB, routeFile(), previews("1-feed")).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun variantSuffixStillCovers() {+ lint().files(NAVKEY_STUB, PREVIEW_STUBS, COMPOSABLE_STUB, PREVIEWTEST_STUB, routeFile(), previews("1-feed", "2-story-expanded")).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun longestRouteKeyWins() {+ // `1-call-logs` must cover CallLogs, not Call: Call stays unmapped.+ lint().files(+ NAVKEY_STUB, PREVIEW_STUBS, COMPOSABLE_STUB, PREVIEWTEST_STUB,+ kotlin(+ "src/main/java/com/vayunmathur/example/Route.kt",+ """+ package com.vayunmathur.example+ import com.vayunmathur.library.util.NavKey+ sealed interface Route : NavKey {+ data object Call : Route+ data object CallLogs : Route+ }+ """.trimIndent(),+ ),+ previews("1-call-logs"),+ ).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun nestedRouteLeafNeedsItsOwnCapture() {+ lint().files(+ NAVKEY_STUB, PREVIEW_STUBS, COMPOSABLE_STUB, PREVIEWTEST_STUB,+ kotlin(+ "src/main/java/com/vayunmathur/example/Route.kt",+ """+ package com.vayunmathur.example+ import com.vayunmathur.library.util.NavKey+ sealed interface Route : NavKey {+ data object Feed : Route+ sealed interface Registration : Route {+ data object Number : Registration+ data class Code(val cc: String) : Registration+ }+ }+ """.trimIndent(),+ ),+ previews("1-feed", "2-registration-number"),+ ).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun exceptionMarkerOptsRouteOut() {+ lint().files(+ NAVKEY_STUB, PREVIEW_STUBS, COMPOSABLE_STUB, PREVIEWTEST_STUB,+ kotlin(+ "src/main/java/com/vayunmathur/example/Route.kt",+ """+ package com.vayunmathur.example+ import com.vayunmathur.library.util.NavKey+ // SCREENSHOT COVERAGE EXCEPTION: Story: live call surface, cannot render in Layoutlib+ sealed interface Route : NavKey {+ data object Feed : Route+ data object Story : Route+ }+ """.trimIndent(),+ ),+ previews("1-feed"),+ ).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun exemptionNamingNoRouteIsFlagged() {+ lint().files(+ NAVKEY_STUB, PREVIEW_STUBS, COMPOSABLE_STUB, PREVIEWTEST_STUB,+ kotlin(+ "src/main/java/com/vayunmathur/example/Route.kt",+ """+ package com.vayunmathur.example+ import com.vayunmathur.library.util.NavKey+ // SCREENSHOT COVERAGE EXCEPTION: Nope: not a route+ sealed interface Route : NavKey {+ data object Feed : Route+ }+ """.trimIndent(),+ ),+ previews("1-feed"),+ ).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun noRouteIsClean() {+ lint().files(+ NAVKEY_STUB, PREVIEW_STUBS, COMPOSABLE_STUB, PREVIEWTEST_STUB,+ kotlin(+ "src/main/java/com/vayunmathur/example/Screen.kt",+ """+ package com.vayunmathur.example+ class Screen+ """.trimIndent(),+ ),+ ).testModes(TestMode.DEFAULT).run().expectClean()+ }++ private fun routeFile(): TestFile = kotlin(+ "src/main/java/com/vayunmathur/example/Route.kt",+ """+ package com.vayunmathur.example+ import com.vayunmathur.library.util.NavKey+ sealed interface Route : NavKey {+ data object Feed : Route+ data object Story : Route+ }+ """.trimIndent(),+ )++ private fun previews(vararg names: String): TestFile {+ val body = names.mapIndexed { index, name ->+ """+ @PreviewTest+ @Preview(name = "$name", group = "phone")+ @Composable fun Preview${index + 1}Shot$index() {}+ """.trimIndent()+ }.joinToString("\n")+ return kotlin(+ "src/screenshotTest/kotlin/com/vayunmathur/example/ui/MetadataPreviews.kt",+ """+ package com.vayunmathur.example.ui+ import androidx.compose.runtime.Composable+ import androidx.compose.ui.tooling.preview.Preview+ import com.android.tools.screenshot.PreviewTest+ class MetadataPreviews {+ $body+ }+ """.trimIndent(),+ )+ }++ companion object {+ private val NAVKEY_STUB: TestFile = kotlin(+ "src/main/java/com/vayunmathur/library/util/NavKey.kt",+ """+ package com.vayunmathur.library.util+ interface NavKey+ """.trimIndent(),+ )++ private val COMPOSABLE_STUB: TestFile = kotlin(+ "src/androidx/compose/runtime/Composable.kt",+ """+ package androidx.compose.runtime+ annotation class Composable+ """.trimIndent(),+ )++ private val PREVIEWTEST_STUB: TestFile = kotlin(+ "src/com/android/tools/screenshot/PreviewTest.kt",+ """+ package com.android.tools.screenshot+ annotation class PreviewTest+ """.trimIndent(),+ )++ private val PREVIEW_STUBS: TestFile = kotlin(+ "src/androidx/compose/ui/tooling/preview/Preview.kt",+ """+ package androidx.compose.ui.tooling.preview+ annotation class Preview(val name: String = "", val group: String = "")+ """.trimIndent(),+ )+ }+}++@RunWith(JUnit4::class)+class ScreenshotCoverageMarkerFormatTest : LintDetectorTest() {++ override fun getDetector(): Detector = ExceptionMarkerFormatDetector()++ override fun getIssues(): List<Issue> = listOf(ExceptionMarkerFormatDetector.ISSUE)++ @Test+ fun wellFormedScreenshotMarkerIsClean() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // SCREENSHOT COVERAGE EXCEPTION: Story: live call surface, cannot render in Layoutlib+ sealed interface Route+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectClean()+ }++ @Test+ fun screenshotMarkerWithoutRouteAndReasonIsFlagged() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // SCREENSHOT COVERAGE EXCEPTION:+ sealed interface Route+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }++ @Test+ fun screenshotMarkerWithoutColonIsFlagged() {+ lint().files(kotlin(+ """+ package com.vayunmathur.example+ // SCREENSHOT COVERAGE EXCEPTION Story: no colon after the marker+ sealed interface Route+ """.trimIndent(),+ )).testModes(TestMode.DEFAULT).run().expectErrorCount(1)+ }+}