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

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

PackageStructureDetector.kt501 lines · 27.1 KiBRaw
1package com.vayunmathur.lint
2
3import com.android.tools.lint.client.api.UElementHandler
4import com.android.tools.lint.detector.api.Category
5import com.android.tools.lint.detector.api.Detector
6import com.android.tools.lint.detector.api.Implementation
7import com.android.tools.lint.detector.api.Issue
8import com.android.tools.lint.detector.api.JavaContext
9import com.android.tools.lint.detector.api.Scope
10import com.android.tools.lint.detector.api.Severity
11import com.android.tools.lint.detector.api.SourceCodeScanner
12import org.jetbrains.kotlin.psi.KtClass
13import org.jetbrains.kotlin.psi.KtFile
14import org.jetbrains.kotlin.psi.KtNamedFunction
15import org.jetbrains.kotlin.psi.KtProperty
16import org.jetbrains.kotlin.psi.KtTypeAlias
17import org.jetbrains.uast.UElement
18import org.jetbrains.uast.UFile
19
20/**
21 * Enforces the closed canonical package structure (§2) plus the closed root-FILE
22 * allow-list with strict per-file content contracts (§3.3).
23 *
24 * Each app's `src/main/java/com/vayunmathur/<app>/` may only contain the
25 * closed set of roots; anything else is a violation. The check derives
26 * `<app>` from the file's `package` declaration (source of truth, not file
27 * path) and inspects the first segment after `com.vayunmathur.<app>`.
28 *
29 * Files whose package is exactly `com.vayunmathur.<app>` (no sub-package) are
30 * further gated to the closed file allow-list: MainActivity.kt, Route.kt,
31 * Navigation.kt, *Application.kt — each with its exact content contract.
32 */
33class PackageStructureDetector : Detector(), SourceCodeScanner {
34
35 override fun getApplicableUastTypes(): List<Class<out UElement>> =
36 listOf(UFile::class.java)
37
38 override fun createUastHandler(context: JavaContext): UElementHandler =
39 object : UElementHandler() {
40 override fun visitFile(node: UFile) {
41 val packageName = node.packageName
42 if (packageName.isEmpty()) return
43 if (isJniException(node)) return
44 if (isExcluded(packageName)) return
45 if (!packageName.startsWith("com.vayunmathur.")) return
46
47 val result = deriveAppBaseAndSegment(packageName) ?: return
48 val segment = result.second
49 if (segment != null) {
50 if (segment in ALLOWED_ROOTS) return
51
52 // Unknown root — report.
53 val suggestion = aliasSuggestion(segment)
54 val allowedList = ALLOWED_ROOTS.sorted().joinToString(", ")
55 val message = buildString {
56 append("Package `")
57 append(packageName)
58 append("` is not in the canonical closed set. ")
59 append("Segment `")
60 append(segment)
61 append("` is not an allowed root. ")
62 append("Allowed roots: [")
63 append(allowedList)
64 append("].")
65 if (suggestion != null) {
66 append(" Did you mean `")
67 append(suggestion)
68 append("`? ")
69 }
70 append(" See docs/package-structure.md §2.")
71 append(" (If this is a JNI FQN exception, add the `// PACKAGE STRUCTURE EXCEPTION (JNI)` marker comment to the file.)")
72 }
73
74 context.report(
75 ISSUE,
76 node,
77 context.getLocation(node),
78 message,
79 )
80 return
81 }
82
83 // Root file (package == com.vayunmathur.<app>) — enforce closed root-file allow-list + contracts.
84 val fileName = context.file?.name
85 ?: (node.sourcePsi as? KtFile)?.name
86 ?: node.sourcePsi?.containingFile?.name
87 ?: ""
88 if (fileName.isEmpty()) return
89 if (fileName == "BuildConfig.java" || fileName == "BuildConfig.kt" || fileName == "R.java" || fileName == "R.kt") return
90
91 val violation = checkRootFileContract(node, fileName)
92 if (violation != null) {
93 context.report(
94 ISSUE,
95 node,
96 context.getLocation(node),
97 violation,
98 )
99 }
100 }
101 }
102
103 companion object {
104
105 private val ALLOWED_ROOTS = setOf(
106 "ui", "data", "domain", "platform", "network", "intents",
107 "service", "provider", "widget", "notifications", "auth", "sync", "telephony"
108 )
109
110 // Shared with OneComposablePerFileDetector via [LintPackageExclusions] so
111 // both app-structure lints skip the same non-app modules (shared library,
112 // e2ee crypto lib, sdk, games, tools, personal). See that file for the
113 // per-prefix rationale.
114 fun isExcluded(packageName: String): Boolean =
115 LintPackageExclusions.isExcluded(packageName)
116
117 // JNI carve-out: a handful of classes have their fully-qualified name frozen
118 // because the native side binds to it via RegisterNatives / C++ symbol mangling.
119 // Renaming or re-nesting them would break the JNI linkage, so they are exempt
120 // from the root-package / root-file contracts.
121 //
122 // Primary mechanism (self-documenting): any file carrying the marker comment
123 // below is skipped, so a future JNI file only needs to add the comment.
124 // Belt-and-suspenders: an explicit allow-set of the currently-frozen FQNs acts
125 // as a fallback in case the marker is ever accidentally dropped.
126 // Internal (not private) so ExceptionMarkerFormatDetector can validate the
127 // verbatim shape against the same constant instead of a copy.
128 internal const val JNI_MARKER = "// PACKAGE STRUCTURE EXCEPTION (JNI)"
129
130 private val JNI_EXEMPT_FQNS = setOf(
131 "com.vayunmathur.euicc.EuiccNative",
132 "com.vayunmathur.games.voxels.util.VoxelsNative",
133 "com.vayunmathur.measure.domain.MeasureNative",
134 "com.vayunmathur.passwords.util.KdbxNative",
135 "com.vayunmathur.share.protocol.ShareNative",
136 "com.vayunmathur.vpn.util.VpnNative",
137 "com.vayunmathur.web.shields.ShieldsNative",
138 )
139
140 fun isJniException(node: UFile): Boolean {
141 val ktFile = node.sourcePsi as? KtFile
142 if (ktFile != null && CommentOnlyMatcher.containsMarkerInComments(ktFile, JNI_MARKER)) return true
143 // Fall back to raw text for non-Kotlin sources, where the marker is
144 // still a comment but there is no KtFile to walk.
145 val text = if (ktFile == null) node.sourcePsi?.text else null
146 if (text != null && text.contains(JNI_MARKER)) return true
147 val pkg = node.packageName
148 return node.classes.any { clazz ->
149 val name = clazz.name ?: return@any false
150 "$pkg.$name" in JNI_EXEMPT_FQNS
151 }
152 }
153
154 /**
155 * Derives the app base package and the first segment after it.
156 * Returns null if the package does not start with `com.vayunmathur.`.
157 * Returns Pair(base, null) for root files (no extra segment).
158 *
159 * Source: plan §5.3 normative snippet.
160 */
161 private fun deriveAppBaseAndSegment(packageName: String): Pair<String, String?>? {
162 if (!packageName.startsWith("com.vayunmathur.")) return null
163 val remainder = packageName.removePrefix("com.vayunmathur.")
164 if (remainder.isEmpty()) return null
165 // An app module nested a level deeper is still an app, and its own roots are what the
166 // closed set applies to. Without this, `com.vayunmathur.cast.tv.platform` would be read
167 // as app `cast` with a root segment `tv`, which is not in the allow-list and never
168 // could be.
169 for (base in NESTED_APP_BASES) {
170 if (remainder == base) return Pair("com.vayunmathur.$base", null)
171 if (remainder.startsWith("$base.")) {
172 val segment = remainder.removePrefix("$base.").substringBefore('.')
173 return Pair("com.vayunmathur.$base", segment)
174 }
175 }
176 val dot = remainder.indexOf('.')
177 return if (dot == -1) {
178 Pair("com.vayunmathur.$remainder", null)
179 } else {
180 val app = remainder.substring(0, dot)
181 val segment = remainder.substring(dot + 1).substringBefore('.')
182 Pair("com.vayunmathur.$app", segment)
183 }
184 }
185
186 /**
187 * App modules whose package is two segments deep rather than one.
188 *
189 * `:cast:tv` is a second app in the `:cast` family - the Android TV receiver the phone casts
190 * to - and it is nested because `common-conventions-app` derives the namespace from the
191 * Gradle path, so `com.vayunmathur.cast.tv` requires the path `:cast:tv`. It is a full app
192 * and holds itself to the same closed root set as any other.
193 */
194 private val NESTED_APP_BASES = listOf("cast.tv")
195
196 // ---- root-file contracts (closed allow-list) ----
197
198 private fun checkRootFileContract(node: UFile, fileName: String): String? {
199 val ktFile = node.sourcePsi as? KtFile
200 return when {
201 fileName == "MainActivity.kt" -> checkMainActivity(ktFile, node)
202 fileName == "Route.kt" -> checkRoute(ktFile, node)
203 fileName == "Navigation.kt" -> checkNavigation(ktFile, node)
204 fileName.endsWith("Application.kt") -> checkApplication(ktFile, node, fileName)
205 else -> {
206 "File `$fileName` in app root package `${node.packageName}` is not in the closed root-file allow-list. " +
207 "Allowed root files: [MainActivity.kt, Route.kt, Navigation.kt, *Application.kt]. " +
208 "Move `$fileName` to a canonical folder (e.g. screens → ui/, ViewModels → platform/, repositories → data/). " +
209 "See plan §3.3, docs/package-structure.md §2."
210 }
211 }
212 }
213
214 private fun checkMainActivity(ktFile: KtFile?, node: UFile): String? {
215 if (ktFile != null) {
216 val decls = ktFile.declarations
217 var hasMainActivity = false
218 val extra = mutableListOf<String>()
219 for (decl in decls) {
220 when (decl) {
221 is KtClass -> {
222 val name = decl.name ?: "class"
223 if (name == "MainActivity") {
224 if (hasMainActivity) extra.add("class MainActivity (duplicate)")
225 else hasMainActivity = true
226 } else {
227 extra.add("class $name")
228 if (name == "Route") extra.add("(Route belongs in Route.kt)")
229 if (name == "Navigation") extra.add("(Navigation belongs in Navigation.kt)")
230 }
231 }
232 is KtNamedFunction -> {
233 val fname = decl.name ?: "fun"
234 extra.add("fun $fname")
235 if (decl.isComposable()) extra.add("(composable belongs in ui/)")
236 }
237 is KtProperty -> extra.add("val ${decl.name ?: "property"}")
238 is KtTypeAlias -> extra.add("typealias ${decl.name ?: "alias"}")
239 else -> extra.add(decl.javaClass.simpleName)
240 }
241 }
242 if (!hasMainActivity) {
243 val found = if (decls.isEmpty()) "empty file" else decls.joinToString { (it as? KtClass)?.name ?: (it as? KtNamedFunction)?.name ?: it.javaClass.simpleName }
244 return "MainActivity.kt must contain only the MainActivity class; expected `class MainActivity : ComponentActivity()` but found $found. " +
245 "Move other declarations to a canonical folder (Route belongs in Route.kt, Navigation belongs in Navigation.kt, screens → ui/, ViewModels → platform/). " +
246 "See plan §3.3."
247 }
248 if (extra.isNotEmpty()) {
249 val offending = extra.joinToString(", ")
250 return "MainActivity.kt must contain only the MainActivity class; move $offending to a canonical folder " +
251 "(Route belongs in Route.kt, Navigation belongs in Navigation.kt; screens → ui/, ViewModels → platform/, data → data/). " +
252 "See plan §3.3."
253 }
254 return null
255 }
256 return checkMainActivityUast(node)
257 }
258
259 private fun checkMainActivityUast(node: UFile): String? {
260 val classes = node.classes
261 val classNames = classes.mapNotNull { it.name }
262 val hasSynthetic = classNames.any { it.endsWith("Kt") }
263 val hasMainActivity = classNames.contains("MainActivity")
264 if (!hasMainActivity) {
265 return "MainActivity.kt must contain only the MainActivity class; expected `class MainActivity : ComponentActivity()` but found [${classNames.joinToString()}]. " +
266 "Move other declarations to a canonical folder. See plan §3.3."
267 }
268 val extraClasses = classNames.filter { it != "MainActivity" && !it.endsWith("Kt") }
269 val hasExtra = extraClasses.isNotEmpty() || hasSynthetic || hasTopLevelFunctions(node)
270 if (hasExtra) {
271 val offending = buildList {
272 addAll(extraClasses.map { "class $it" })
273 if (extraClasses.contains("Route")) add("(Route belongs in Route.kt)")
274 if (extraClasses.contains("Navigation")) add("(Navigation belongs in Navigation.kt)")
275 if (hasSynthetic || hasTopLevelFunctions(node)) add("top-level fun/val")
276 }.joinToString(", ")
277 return "MainActivity.kt must contain only the MainActivity class; move $offending to a canonical folder " +
278 "(Route belongs in Route.kt, Navigation belongs in Navigation.kt). See plan §3.3."
279 }
280 return null
281 }
282
283 private fun checkRoute(ktFile: KtFile?, node: UFile): String? {
284 if (ktFile != null) {
285 val decls = ktFile.declarations
286 if (decls.size != 1) {
287 val names = decls.mapNotNull { ktName(it) }.joinToString(", ")
288 val hasComposable = decls.any { it is KtNamedFunction && it.isComposable() }
289 val hint = if (hasComposable) " Remove @Composable functions (screens → ui/, Navigation → Navigation.kt)." else ""
290 return "Route.kt must contain only `sealed interface Route : NavKey` (+ nested route objects/classes); " +
291 "found ${decls.size} top-level declarations${if (names.isNotEmpty()) " [$names]" else ""}. " +
292 "Move extra declarations to a canonical folder.$hint Route belongs in Route.kt; Navigation belongs in Navigation.kt. See plan §3.3."
293 }
294 val sole = decls.first()
295 if (sole !is KtClass) {
296 return "Route.kt must contain only `sealed interface Route : NavKey` (+ nested route objects/classes); " +
297 "found ${sole.javaClass.simpleName} `${ktName(sole) ?: ""}`. " +
298 "Route belongs in Route.kt; Navigation belongs in Navigation.kt. See plan §3.3."
299 }
300 val name = sole.name
301 if (name != "Route") {
302 return "Route.kt must contain only `sealed interface Route : NavKey`; found `class $name` instead. " +
303 "Route belongs in Route.kt. See plan §3.3."
304 }
305 val isSealed = sole.text.contains("sealed")
306 val isInterface = sole.text.contains("interface")
307 val hasNavKey = sole.superTypeListEntries.any { it.text.contains("NavKey") }
308 if (!isSealed || !isInterface) {
309 return "Route.kt must contain `sealed interface Route : NavKey` (+ nested routes); " +
310 "found ${if (!isSealed) "non-sealed" else ""} ${if (!isInterface) "non-interface" else "interface"} `Route`. " +
311 "Route belongs in Route.kt. See plan §3.3."
312 }
313 if (!hasNavKey) {
314 return "Route.kt must declare `sealed interface Route : NavKey`; `Route` does not extend `NavKey`. " +
315 "Route belongs in Route.kt. See plan §3.3."
316 }
317 return null
318 }
319 val classes = node.classes
320 if (classes.size != 1 || classes.first().name != "Route") {
321 val names = classes.mapNotNull { it.name }.joinToString(", ")
322 return "Route.kt must contain only `sealed interface Route : NavKey` (+ nested route objects/classes); " +
323 "found [${names}]. Route belongs in Route.kt; Navigation belongs in Navigation.kt. See plan §3.3."
324 }
325 if (hasTopLevelFunctions(node)) {
326 return "Route.kt must contain only `sealed interface Route : NavKey` (+ nested routes); " +
327 "found top-level @Composable/fun declarations. Move composables to ui/ and Navigation to Navigation.kt. " +
328 "Route belongs in Route.kt. See plan §3.3."
329 }
330 return null
331 }
332
333 private fun checkNavigation(ktFile: KtFile?, node: UFile): String? {
334 if (ktFile != null) {
335 val decls = ktFile.declarations
336 if (decls.size != 1) {
337 val names = decls.mapNotNull { ktName(it) }.joinToString(", ")
338 val hasRoute = decls.any { it is KtClass && it.name == "Route" }
339 val routeHint = if (hasRoute) " Route belongs in Route.kt." else ""
340 return "Navigation.kt must contain only the top-level `@Composable fun Navigation(...)` nav graph; " +
341 "found ${decls.size} top-level declarations${if (names.isNotEmpty()) " [$names]" else ""}.$routeHint " +
342 "Move screen composables to ui/, Route to Route.kt, and helpers to domain/platform. Navigation belongs in Navigation.kt. See plan §3.3."
343 }
344 val sole = decls.first()
345 if (sole !is KtNamedFunction) {
346 val found = ktName(sole) ?: sole.javaClass.simpleName
347 val isRoute = sole is KtClass && sole.name == "Route"
348 val hint = if (isRoute) " Route belongs in Route.kt." else ""
349 return "Navigation.kt must contain only `@Composable fun Navigation(...)`; found `$found` instead.$hint " +
350 "Navigation belongs in Navigation.kt; screens belong in ui/. See plan §3.3."
351 }
352 if (sole.name != "Navigation") {
353 return "Navigation.kt must contain only `@Composable fun Navigation(...)`; found `fun ${sole.name}`. " +
354 "Navigation belongs in Navigation.kt. See plan §3.3."
355 }
356 if (!sole.isComposable()) {
357 return "Navigation.kt must contain `@Composable fun Navigation(...)`; `fun Navigation` is not annotated with @Composable. " +
358 "See plan §3.3."
359 }
360 return null
361 }
362 val hasComposableNav = node.classes.any { clazz ->
363 clazz.methods.any { m ->
364 val psi = m.sourcePsi as? KtNamedFunction
365 psi?.name == "Navigation" && psi.isComposable()
366 }
367 }
368 if (!hasComposableNav) {
369 val classNames = node.classes.mapNotNull { it.name }.joinToString(", ")
370 return "Navigation.kt must contain only `@Composable fun Navigation(...)`; found [${classNames}]. " +
371 "Navigation belongs in Navigation.kt; Route belongs in Route.kt. See plan §3.3."
372 }
373 if (node.classes.any { it.name == "Route" }) {
374 return "Navigation.kt must contain only `@Composable fun Navigation(...)`; found `Route` declaration. " +
375 "Route belongs in Route.kt. See plan §3.3."
376 }
377 if (node.classes.size > 1 || (hasTopLevelFunctions(node) && node.classes.flatMap { it.methods.toList() }.size > 1)) {
378 return "Navigation.kt must contain only `@Composable fun Navigation(...)`; found extra top-level declarations. " +
379 "Move screens to ui/ and helpers to domain/platform. See plan §3.3."
380 }
381 return null
382 }
383
384 private fun checkApplication(ktFile: KtFile?, node: UFile, fileName: String): String? {
385 val expectedClass = fileName.removeSuffix(".kt").removeSuffix(".java")
386 if (!expectedClass.endsWith("Application")) {
387 return "File `$fileName` in app root must be `*Application.kt` with an Application subclass; " +
388 "`$expectedClass` does not end with `Application`. Allowed root files: [MainActivity.kt, Route.kt, Navigation.kt, *Application.kt]. See plan §3.3."
389 }
390 if (ktFile != null) {
391 val decls = ktFile.declarations
392 if (decls.size != 1) {
393 val names = decls.mapNotNull { ktName(it) }.joinToString(", ")
394 return "$fileName must contain only `class $expectedClass : Application()`; " +
395 "found ${decls.size} top-level declarations${if (names.isNotEmpty()) " [$names]" else ""}. " +
396 "Move other declarations to a canonical folder. See plan §3.3."
397 }
398 val sole = decls.first()
399 if (sole !is KtClass) {
400 return "$fileName must contain only `class $expectedClass : Application()`; found ${sole.javaClass.simpleName}. See plan §3.3."
401 }
402 val name = sole.name
403 if (name != expectedClass) {
404 return "$fileName must contain `class $expectedClass : Application()`; found `class $name`. File name and class must match. See plan §3.3."
405 }
406 val extendsApplication = sole.superTypeListEntries.any { it.text.contains("Application") }
407 if (!extendsApplication) {
408 return "$fileName must declare `class $expectedClass : Application()`; `$expectedClass` does not extend `Application`. See plan §3.3."
409 }
410 return null
411 }
412 val realClasses = node.classes.filter { !(it.name ?: "").endsWith("Kt") }
413 if (realClasses.size != 1 || realClasses.first().name != expectedClass) {
414 val names = realClasses.mapNotNull { it.name }.joinToString(", ")
415 return "$fileName must contain only `class $expectedClass : Application()`; found [${names}]. See plan §3.3."
416 }
417 if (hasTopLevelFunctions(node)) {
418 return "$fileName must contain only `class $expectedClass : Application()`; found top-level fun/val. See plan §3.3."
419 }
420 return null
421 }
422
423 private fun hasTopLevelFunctions(node: UFile): Boolean {
424 for (clazz in node.classes) {
425 for (method in clazz.methods) {
426 val psi = method.sourcePsi as? KtNamedFunction ?: continue
427 if (psi.isTopLevel()) return true
428 }
429 }
430 return false
431 }
432
433 private fun KtNamedFunction.isTopLevel(): Boolean = parent is KtFile
434
435 private fun KtNamedFunction.isComposable(): Boolean =
436 annotationEntries.any { it.shortName?.asString() == "Composable" || it.text.contains("Composable") }
437
438 private fun ktName(decl: org.jetbrains.kotlin.psi.KtDeclaration): String? = when (decl) {
439 is KtClass -> decl.name
440 is KtNamedFunction -> decl.name
441 is KtProperty -> decl.name
442 is KtTypeAlias -> decl.name
443 else -> null
444 }
445
446 private val BANNED_ALIAS_MAP: Map<String, String> = mapOf(
447 "util" to "domain/ or platform/ (see litmus test in docs/package-structure.md §2.1)",
448 "api" to "network/",
449 "model" to "data/ (or data/model/ subpackage)",
450 "viewmodel" to "platform/",
451 "glance" to "widget/ (move glance/Foo → widget/glance/Foo)",
452 "composer" to "ui/composer/",
453 "shields" to "domain/shields/",
454 "syntax" to "domain/syntax/",
455 "ime" to "platform/ime/",
456 "tts" to "platform/tts/",
457 "imap" to "network/imap/",
458 "smtp" to "network/smtp/",
459 "saf" to "data/saf/",
460 "crypto" to "domain/crypto/",
461 "format" to "domain/format/",
462 "remote" to "network/remote/",
463 "sink" to "data/sink/",
464 )
465
466 private fun aliasSuggestion(badSegment: String): String? {
467 val mapped = BANNED_ALIAS_MAP[badSegment]
468 return when {
469 mapped != null -> mapped
470 else -> "Move under one of [data|network|domain|platform|...] per docs/package-structure.md §2.3"
471 }
472 }
473
474 val ISSUE: Issue = Issue.create(
475 id = "PackageStructure",
476 briefDescription = "Package not in canonical closed set",
477 explanation = """
478 Each app's `src/main/java/com/vayunmathur/<app>/` may only contain the closed \
479 set of roots: [ui, data, domain, platform, network, intents, service, provider, \
480 widget, notifications, auth, sync, telephony]. Any other top-level segment is a \
481 violation. Additionally, files whose package is exactly `com.vayunmathur.<app>` \
482 (app root) are restricted to a closed file allow-list: [MainActivity.kt (only \
483 class MainActivity), Route.kt (only sealed interface Route : NavKey), \
484 Navigation.kt (only @Composable fun Navigation(...)), *Application.kt (only the \
485 Application subclass)]. Any other root file, or a root file violating its content \
486 contract (e.g. Route inside MainActivity.kt, screens inside Navigation.kt, \
487 composables inside Route.kt), is also a violation. Re-nest the code under the \
488 closest canonical root per docs/package-structure.md §2.3, or amend the plan to \
489 add a new root. Shared library modules (com.vayunmathur.library*) are excluded \
490 from this check.
491 """.trimIndent(),
492 category = Category.CORRECTNESS,
493 priority = 8,
494 severity = Severity.ERROR,
495 implementation = Implementation(
496 PackageStructureDetector::class.java,
497 Scope.JAVA_FILE_SCOPE,
498 ),
499 )
500 }
501}