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

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

PackageStructureDetector.kt622 lines · 34.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 full segment path after `com.vayunmathur.<app>`:
28 * the first segment must be an allowed root, descendant segments must name
29 * features/capabilities rather than generic buckets, and `widget` is flat.
30 *
31 * Files whose package is exactly `com.vayunmathur.<app>` (no sub-package) are
32 * further gated to the closed file allow-list: MainActivity.kt, Route.kt,
33 * Navigation.kt, *Application.kt — each with its exact content contract.
34 */
35class PackageStructureDetector : Detector(), SourceCodeScanner {
36
37 override fun getApplicableUastTypes(): List<Class<out UElement>> =
38 listOf(UFile::class.java)
39
40 override fun createUastHandler(context: JavaContext): UElementHandler =
41 object : UElementHandler() {
42 override fun visitFile(node: UFile) {
43 val packageName = node.packageName
44 if (packageName.isEmpty()) return
45 if (isJniException(node)) return
46 if (isExcluded(packageName)) return
47 if (!packageName.startsWith("com.vayunmathur.")) return
48
49 val result = deriveAppBaseAndSegments(packageName) ?: return
50 val segments = result.second
51 val segment = segments.firstOrNull()
52 if (segment != null) {
53 if (segment in ALLOWED_ROOTS) {
54 val subpackageViolation = validateSubpackages(packageName, segments)
55 if (subpackageViolation != null) {
56 context.report(
57 ISSUE,
58 node,
59 context.getLocation(node),
60 subpackageViolation,
61 )
62 return
63 }
64 if (segment == "widget" && segments.size == 1) {
65 val widgetViolation = validateWidgetFile(node, packageName)
66 if (widgetViolation != null) {
67 context.report(
68 ISSUE,
69 node,
70 context.getLocation(node),
71 widgetViolation,
72 )
73 }
74 }
75 return
76 }
77
78 // Unknown root — report.
79 val suggestion = aliasSuggestion(segment)
80 val allowedList = ALLOWED_ROOTS.sorted().joinToString(", ")
81 val message = buildString {
82 append("Package `")
83 append(packageName)
84 append("` is not in the canonical closed set. ")
85 append("Segment `")
86 append(segment)
87 append("` is not an allowed root. ")
88 append("Allowed roots: [")
89 append(allowedList)
90 append("].")
91 if (suggestion != null) {
92 append(" Did you mean `")
93 append(suggestion)
94 append("`? ")
95 }
96 append(" See docs/package-structure.md §2.")
97 append(" (If this is a JNI FQN exception, add the `// PACKAGE STRUCTURE EXCEPTION (JNI)` marker comment to the file.)")
98 }
99
100 context.report(
101 ISSUE,
102 node,
103 context.getLocation(node),
104 message,
105 )
106 return
107 }
108
109 // Root file (package == com.vayunmathur.<app>) — enforce closed root-file allow-list + contracts.
110 val fileName = context.file?.name
111 ?: (node.sourcePsi as? KtFile)?.name
112 ?: node.sourcePsi?.containingFile?.name
113 ?: ""
114 if (fileName.isEmpty()) return
115 if (fileName == "BuildConfig.java" || fileName == "BuildConfig.kt" || fileName == "R.java" || fileName == "R.kt") return
116
117 val violation = checkRootFileContract(node, fileName)
118 if (violation != null) {
119 context.report(
120 ISSUE,
121 node,
122 context.getLocation(node),
123 violation,
124 )
125 }
126 }
127 }
128
129 companion object {
130
131 private val ALLOWED_ROOTS = setOf(
132 "ui", "data", "domain", "platform", "network", "intents",
133 "service", "provider", "widget", "notifications", "sync", "telephony"
134 )
135
136 // Shared with OneComposablePerFileDetector via [LintPackageExclusions] so
137 // both app-structure lints skip the same non-app modules (shared library,
138 // e2ee crypto lib, sdk, games, tools, personal). See that file for the
139 // per-prefix rationale.
140 fun isExcluded(packageName: String): Boolean =
141 LintPackageExclusions.isExcluded(packageName)
142
143 // JNI carve-out: a handful of classes have their fully-qualified name frozen
144 // because the native side binds to it via RegisterNatives / C++ symbol mangling.
145 // Renaming or re-nesting them would break the JNI linkage, so they are exempt
146 // from the root-package / root-file contracts.
147 //
148 // Primary mechanism (self-documenting): any file carrying the marker comment
149 // below is skipped, so a future JNI file only needs to add the comment.
150 // Belt-and-suspenders: an explicit allow-set of the currently-frozen FQNs acts
151 // as a fallback in case the marker is ever accidentally dropped.
152 // Internal (not private) so ExceptionMarkerFormatDetector can validate the
153 // verbatim shape against the same constant instead of a copy.
154 internal const val JNI_MARKER = "// PACKAGE STRUCTURE EXCEPTION (JNI)"
155
156 private val JNI_EXEMPT_FQNS = setOf(
157 "com.vayunmathur.euicc.EuiccNative",
158 "com.vayunmathur.games.voxels.util.VoxelsNative",
159 "com.vayunmathur.measure.domain.MeasureNative",
160 "com.vayunmathur.passwords.util.KdbxNative",
161 "com.vayunmathur.share.protocol.ShareNative",
162 "com.vayunmathur.vpn.util.VpnNative",
163 "com.vayunmathur.web.shields.ShieldsNative",
164 )
165
166 fun isJniException(node: UFile): Boolean {
167 val ktFile = node.sourcePsi as? KtFile
168 if (ktFile != null && CommentOnlyMatcher.containsMarkerInComments(ktFile, JNI_MARKER)) return true
169 // Fall back to raw text for non-Kotlin sources, where the marker is
170 // still a comment but there is no KtFile to walk.
171 val text = if (ktFile == null) node.sourcePsi?.text else null
172 if (text != null && text.contains(JNI_MARKER)) return true
173 val pkg = node.packageName
174 return node.classes.any { clazz ->
175 val name = clazz.name ?: return@any false
176 "$pkg.$name" in JNI_EXEMPT_FQNS
177 }
178 }
179
180 /**
181 * Derives the app base package and every segment after it.
182 * Returns null if the package does not start with `com.vayunmathur.`.
183 * Returns Pair(base, emptyList()) for root files (no extra segment).
184 */
185 private fun deriveAppBaseAndSegments(packageName: String): Pair<String, List<String>>? {
186 if (!packageName.startsWith("com.vayunmathur.")) return null
187 val remainder = packageName.removePrefix("com.vayunmathur.")
188 if (remainder.isEmpty()) return null
189 // An app module nested a level deeper is still an app, and its own roots are what the
190 // closed set applies to. Without this, `com.vayunmathur.cast.tv.platform` would be read
191 // as app `cast` with a root segment `tv`, which is not in the allow-list and never
192 // could be.
193 for (base in NESTED_APP_BASES) {
194 if (remainder == base) return Pair("com.vayunmathur.$base", emptyList())
195 if (remainder.startsWith("$base.")) {
196 val segments = remainder.removePrefix("$base.").split('.')
197 return Pair("com.vayunmathur.$base", segments)
198 }
199 }
200 val dot = remainder.indexOf('.')
201 return if (dot == -1) {
202 Pair("com.vayunmathur.$remainder", emptyList())
203 } else {
204 val app = remainder.substring(0, dot)
205 val segments = remainder.substring(dot + 1).split('.')
206 Pair("com.vayunmathur.$app", segments)
207 }
208 }
209
210 private val BANNED_DESCENDANT_SEGMENTS = setOf(
211 "api", "apis", "base", "common", "core", "feature", "features",
212 "glance", "helper", "helpers", "impl", "manager", "managers",
213 "misc", "presentation", "repository", "repositories", "screen",
214 "screens", "util", "utils", "view", "views", "viewmodel",
215 "viewmodels", "widget", "widgets",
216 )
217
218 /**
219 * One widget, one file: every file directly in the `widget` root must
220 * declare exactly one widget class (a `MaWidget` / `GlanceAppWidget`
221 * subclass, not merely its receiver) at top level, together with that
222 * widget's receiver (`MaWidgetReceiver` / `GlanceAppWidgetReceiver`
223 * for the same widget) in the same file. Zero or multiple widget
224 * classes, and a widget without its receiver alongside it, are
225 * violations. Helper-only files in `widget` are violations; widget
226 * helpers nest inside the widget class or its file, and non-Glance
227 * app helpers belong to their own canonical root.
228 * See docs/package-structure.md §3.2.
229 */
230 private fun validateWidgetFile(node: UFile, packageName: String): String? {
231 val ktFile = node.sourcePsi as? KtFile ?: return null
232 val topLevelClasses = ktFile.declarations.filterIsInstance<KtClass>()
233 fun KtClass.isWidgetClass(): Boolean = superTypeListEntries.any { entry ->
234 val text = entry.text
235 text.contains(Regex("""\bMaWidget\s*[<(]""")) ||
236 text.contains(Regex("""\bGlanceAppWidget\s*\("""))
237 }
238 fun KtClass.isReceiverClass(): Boolean = superTypeListEntries.any { entry ->
239 val text = entry.text
240 text.contains(Regex("""\bMaWidgetReceiver\s*[<(]""")) ||
241 text.contains(Regex("""\bGlanceAppWidgetReceiver\s*\("""))
242 }
243 val widgetClasses = topLevelClasses.filter { it.isWidgetClass() }
244 if (widgetClasses.size != 1) {
245 val found = if (widgetClasses.isEmpty()) {
246 "no widget class"
247 } else {
248 "${widgetClasses.size} widget classes " +
249 "[${widgetClasses.mapNotNull { it.name }.joinToString(", ")}]"
250 }
251 return "File in widget package `$packageName` declares $found at " +
252 "top level. One widget, one file: every file in `widget` must declare " +
253 "exactly one `MaWidget` subclass (with its receiver) at top level; " +
254 "helper-only files are forbidden — nest helpers inside the widget or move " +
255 "non-Glance app helpers to their canonical root. " +
256 "See docs/package-structure.md §3.2."
257 }
258 val widgetName = widgetClasses.single().name
259 val receiverClasses = topLevelClasses.filter { it.isReceiverClass() }
260 // Its receiver: a receiver whose supertype names this widget
261 // (e.g. `MaWidgetReceiver<PhotoGlanceWidget>(...)`, whose entry
262 // text also carries `widgetClass = PhotoGlanceWidget::class`).
263 // A bare `GlanceAppWidgetReceiver` subclass also counts.
264 val hasOwnReceiver = receiverClasses.any { clazz ->
265 clazz.superTypeListEntries.any { entry ->
266 val text = entry.text
267 (widgetName != null && text.contains(widgetName)) ||
268 text.contains(Regex("""\bGlanceAppWidgetReceiver\s*\("""))
269 }
270 }
271 if (!hasOwnReceiver) {
272 return "File in widget package `$packageName` declares widget " +
273 "`$widgetName` but not its receiver in the same file. One widget, " +
274 "one file: every file in `widget` must declare exactly one " +
275 "`MaWidget` subclass together with its `MaWidgetReceiver` for " +
276 "that widget at top level. See docs/package-structure.md §3.2."
277 }
278 return null
279 }
280
281 private fun validateSubpackages(packageName: String, segments: List<String>): String? {
282 val root = segments.firstOrNull() ?: return null
283 if (root == "widget" && segments.size > 1) {
284 return "Package `$packageName` fragments widget code below `widget`. " +
285 "Widget code must be directly in the flat `widget` root; Glance is an " +
286 "implementation detail, not a package boundary. Move the file to " +
287 "`${packageName.substringBefore(".widget")}.widget`. " +
288 "See docs/package-structure.md §3.2."
289 }
290 val banned = segments.drop(1).firstOrNull { it in BANNED_DESCENDANT_SEGMENTS }
291 if (banned != null) {
292 return "Package `$packageName` uses banned package segment `$banned` below " +
293 "root `$root`. Package segments name a responsibility, feature, provider, " +
294 "or protocol—not a generic bucket, class type, synonym, or UI toolkit. " +
295 "Move the file under the closest canonical responsibility in " +
296 "docs/package-structure.md §2–§4."
297 }
298 return null
299 }
300
301 /**
302 * App modules whose package is two segments deep rather than one.
303 *
304 * `:cast:tv` is a second app in the `:cast` family - the Android TV receiver the phone casts
305 * to - and it is nested because `common-conventions-app` derives the namespace from the
306 * Gradle path, so `com.vayunmathur.cast.tv` requires the path `:cast:tv`. It is a full app
307 * and holds itself to the same closed root set as any other.
308 */
309 private val NESTED_APP_BASES = listOf("cast.tv")
310
311 // ---- root-file contracts (closed allow-list) ----
312
313 private fun checkRootFileContract(node: UFile, fileName: String): String? {
314 val ktFile = node.sourcePsi as? KtFile
315 return when {
316 fileName == "MainActivity.kt" -> checkMainActivity(ktFile, node)
317 fileName == "Route.kt" -> checkRoute(ktFile, node)
318 fileName == "Navigation.kt" -> checkNavigation(ktFile, node)
319 fileName.endsWith("Application.kt") -> checkApplication(ktFile, node, fileName)
320 else -> {
321 "File `$fileName` in app root package `${node.packageName}` is not in the closed root-file allow-list. " +
322 "Allowed root files: [MainActivity.kt, Route.kt, Navigation.kt, *Application.kt]. " +
323 "Move `$fileName` to a canonical folder (e.g. screens → ui/, ViewModels → platform/, repositories → data/). " +
324 "See plan §3.3, docs/package-structure.md §2."
325 }
326 }
327 }
328
329 private fun checkMainActivity(ktFile: KtFile?, node: UFile): String? {
330 if (ktFile != null) {
331 val decls = ktFile.declarations
332 var hasMainActivity = false
333 val extra = mutableListOf<String>()
334 for (decl in decls) {
335 when (decl) {
336 is KtClass -> {
337 val name = decl.name ?: "class"
338 if (name == "MainActivity") {
339 if (hasMainActivity) extra.add("class MainActivity (duplicate)")
340 else hasMainActivity = true
341 } else {
342 extra.add("class $name")
343 if (name == "Route") extra.add("(Route belongs in Route.kt)")
344 if (name == "Navigation") extra.add("(Navigation belongs in Navigation.kt)")
345 }
346 }
347 is KtNamedFunction -> {
348 val fname = decl.name ?: "fun"
349 extra.add("fun $fname")
350 if (decl.isComposable()) extra.add("(composable belongs in ui/)")
351 }
352 is KtProperty -> extra.add("val ${decl.name ?: "property"}")
353 is KtTypeAlias -> extra.add("typealias ${decl.name ?: "alias"}")
354 else -> extra.add(decl.javaClass.simpleName)
355 }
356 }
357 if (!hasMainActivity) {
358 val found = if (decls.isEmpty()) "empty file" else decls.joinToString { (it as? KtClass)?.name ?: (it as? KtNamedFunction)?.name ?: it.javaClass.simpleName }
359 return "MainActivity.kt must contain only the MainActivity class; expected `class MainActivity : ComponentActivity()` but found $found. " +
360 "Move other declarations to a canonical folder (Route belongs in Route.kt, Navigation belongs in Navigation.kt, screens → ui/, ViewModels → platform/). " +
361 "See plan §3.3."
362 }
363 if (extra.isNotEmpty()) {
364 val offending = extra.joinToString(", ")
365 return "MainActivity.kt must contain only the MainActivity class; move $offending to a canonical folder " +
366 "(Route belongs in Route.kt, Navigation belongs in Navigation.kt; screens → ui/, ViewModels → platform/, data → data/). " +
367 "See plan §3.3."
368 }
369 return null
370 }
371 return checkMainActivityUast(node)
372 }
373
374 private fun checkMainActivityUast(node: UFile): String? {
375 val classes = node.classes
376 val classNames = classes.mapNotNull { it.name }
377 val hasSynthetic = classNames.any { it.endsWith("Kt") }
378 val hasMainActivity = classNames.contains("MainActivity")
379 if (!hasMainActivity) {
380 return "MainActivity.kt must contain only the MainActivity class; expected `class MainActivity : ComponentActivity()` but found [${classNames.joinToString()}]. " +
381 "Move other declarations to a canonical folder. See plan §3.3."
382 }
383 val extraClasses = classNames.filter { it != "MainActivity" && !it.endsWith("Kt") }
384 val hasExtra = extraClasses.isNotEmpty() || hasSynthetic || hasTopLevelFunctions(node)
385 if (hasExtra) {
386 val offending = buildList {
387 addAll(extraClasses.map { "class $it" })
388 if (extraClasses.contains("Route")) add("(Route belongs in Route.kt)")
389 if (extraClasses.contains("Navigation")) add("(Navigation belongs in Navigation.kt)")
390 if (hasSynthetic || hasTopLevelFunctions(node)) add("top-level fun/val")
391 }.joinToString(", ")
392 return "MainActivity.kt must contain only the MainActivity class; move $offending to a canonical folder " +
393 "(Route belongs in Route.kt, Navigation belongs in Navigation.kt). See plan §3.3."
394 }
395 return null
396 }
397
398 private fun checkRoute(ktFile: KtFile?, node: UFile): String? {
399 if (ktFile != null) {
400 val decls = ktFile.declarations
401 if (decls.size != 1) {
402 val names = decls.mapNotNull { ktName(it) }.joinToString(", ")
403 val hasComposable = decls.any { it is KtNamedFunction && it.isComposable() }
404 val hint = if (hasComposable) " Remove @Composable functions (screens → ui/, Navigation → Navigation.kt)." else ""
405 return "Route.kt must contain only `sealed interface Route : NavKey` (+ nested route objects/classes); " +
406 "found ${decls.size} top-level declarations${if (names.isNotEmpty()) " [$names]" else ""}. " +
407 "Move extra declarations to a canonical folder.$hint Route belongs in Route.kt; Navigation belongs in Navigation.kt. See plan §3.3."
408 }
409 val sole = decls.first()
410 if (sole !is KtClass) {
411 return "Route.kt must contain only `sealed interface Route : NavKey` (+ nested route objects/classes); " +
412 "found ${sole.javaClass.simpleName} `${ktName(sole) ?: ""}`. " +
413 "Route belongs in Route.kt; Navigation belongs in Navigation.kt. See plan §3.3."
414 }
415 val name = sole.name
416 if (name != "Route") {
417 return "Route.kt must contain only `sealed interface Route : NavKey`; found `class $name` instead. " +
418 "Route belongs in Route.kt. See plan §3.3."
419 }
420 val isSealed = sole.text.contains("sealed")
421 val isInterface = sole.text.contains("interface")
422 val hasNavKey = sole.superTypeListEntries.any { it.text.contains("NavKey") }
423 if (!isSealed || !isInterface) {
424 return "Route.kt must contain `sealed interface Route : NavKey` (+ nested routes); " +
425 "found ${if (!isSealed) "non-sealed" else ""} ${if (!isInterface) "non-interface" else "interface"} `Route`. " +
426 "Route belongs in Route.kt. See plan §3.3."
427 }
428 if (!hasNavKey) {
429 return "Route.kt must declare `sealed interface Route : NavKey`; `Route` does not extend `NavKey`. " +
430 "Route belongs in Route.kt. See plan §3.3."
431 }
432 return null
433 }
434 val classes = node.classes
435 if (classes.size != 1 || classes.first().name != "Route") {
436 val names = classes.mapNotNull { it.name }.joinToString(", ")
437 return "Route.kt must contain only `sealed interface Route : NavKey` (+ nested route objects/classes); " +
438 "found [${names}]. Route belongs in Route.kt; Navigation belongs in Navigation.kt. See plan §3.3."
439 }
440 if (hasTopLevelFunctions(node)) {
441 return "Route.kt must contain only `sealed interface Route : NavKey` (+ nested routes); " +
442 "found top-level @Composable/fun declarations. Move composables to ui/ and Navigation to Navigation.kt. " +
443 "Route belongs in Route.kt. See plan §3.3."
444 }
445 return null
446 }
447
448 private fun checkNavigation(ktFile: KtFile?, node: UFile): String? {
449 if (ktFile != null) {
450 val decls = ktFile.declarations
451 if (decls.size != 1) {
452 val names = decls.mapNotNull { ktName(it) }.joinToString(", ")
453 val hasRoute = decls.any { it is KtClass && it.name == "Route" }
454 val routeHint = if (hasRoute) " Route belongs in Route.kt." else ""
455 return "Navigation.kt must contain only the top-level `@Composable fun Navigation(...)` nav graph; " +
456 "found ${decls.size} top-level declarations${if (names.isNotEmpty()) " [$names]" else ""}.$routeHint " +
457 "Move screen composables to ui/, Route to Route.kt, and helpers to domain/platform. Navigation belongs in Navigation.kt. See plan §3.3."
458 }
459 val sole = decls.first()
460 if (sole !is KtNamedFunction) {
461 val found = ktName(sole) ?: sole.javaClass.simpleName
462 val isRoute = sole is KtClass && sole.name == "Route"
463 val hint = if (isRoute) " Route belongs in Route.kt." else ""
464 return "Navigation.kt must contain only `@Composable fun Navigation(...)`; found `$found` instead.$hint " +
465 "Navigation belongs in Navigation.kt; screens belong in ui/. See plan §3.3."
466 }
467 if (sole.name != "Navigation") {
468 return "Navigation.kt must contain only `@Composable fun Navigation(...)`; found `fun ${sole.name}`. " +
469 "Navigation belongs in Navigation.kt. See plan §3.3."
470 }
471 if (!sole.isComposable()) {
472 return "Navigation.kt must contain `@Composable fun Navigation(...)`; `fun Navigation` is not annotated with @Composable. " +
473 "See plan §3.3."
474 }
475 return null
476 }
477 val hasComposableNav = node.classes.any { clazz ->
478 clazz.methods.any { m ->
479 val psi = m.sourcePsi as? KtNamedFunction
480 psi?.name == "Navigation" && psi.isComposable()
481 }
482 }
483 if (!hasComposableNav) {
484 val classNames = node.classes.mapNotNull { it.name }.joinToString(", ")
485 return "Navigation.kt must contain only `@Composable fun Navigation(...)`; found [${classNames}]. " +
486 "Navigation belongs in Navigation.kt; Route belongs in Route.kt. See plan §3.3."
487 }
488 if (node.classes.any { it.name == "Route" }) {
489 return "Navigation.kt must contain only `@Composable fun Navigation(...)`; found `Route` declaration. " +
490 "Route belongs in Route.kt. See plan §3.3."
491 }
492 if (node.classes.size > 1 || (hasTopLevelFunctions(node) && node.classes.flatMap { it.methods.toList() }.size > 1)) {
493 return "Navigation.kt must contain only `@Composable fun Navigation(...)`; found extra top-level declarations. " +
494 "Move screens to ui/ and helpers to domain/platform. See plan §3.3."
495 }
496 return null
497 }
498
499 private fun checkApplication(ktFile: KtFile?, node: UFile, fileName: String): String? {
500 val expectedClass = fileName.removeSuffix(".kt").removeSuffix(".java")
501 if (!expectedClass.endsWith("Application")) {
502 return "File `$fileName` in app root must be `*Application.kt` with an Application subclass; " +
503 "`$expectedClass` does not end with `Application`. Allowed root files: [MainActivity.kt, Route.kt, Navigation.kt, *Application.kt]. See plan §3.3."
504 }
505 if (ktFile != null) {
506 val decls = ktFile.declarations
507 if (decls.size != 1) {
508 val names = decls.mapNotNull { ktName(it) }.joinToString(", ")
509 return "$fileName must contain only `class $expectedClass : Application()`; " +
510 "found ${decls.size} top-level declarations${if (names.isNotEmpty()) " [$names]" else ""}. " +
511 "Move other declarations to a canonical folder. See plan §3.3."
512 }
513 val sole = decls.first()
514 if (sole !is KtClass) {
515 return "$fileName must contain only `class $expectedClass : Application()`; found ${sole.javaClass.simpleName}. See plan §3.3."
516 }
517 val name = sole.name
518 if (name != expectedClass) {
519 return "$fileName must contain `class $expectedClass : Application()`; found `class $name`. File name and class must match. See plan §3.3."
520 }
521 val extendsApplication = sole.superTypeListEntries.any { it.text.contains("Application") }
522 if (!extendsApplication) {
523 return "$fileName must declare `class $expectedClass : Application()`; `$expectedClass` does not extend `Application`. See plan §3.3."
524 }
525 return null
526 }
527 val realClasses = node.classes.filter { !(it.name ?: "").endsWith("Kt") }
528 if (realClasses.size != 1 || realClasses.first().name != expectedClass) {
529 val names = realClasses.mapNotNull { it.name }.joinToString(", ")
530 return "$fileName must contain only `class $expectedClass : Application()`; found [${names}]. See plan §3.3."
531 }
532 if (hasTopLevelFunctions(node)) {
533 return "$fileName must contain only `class $expectedClass : Application()`; found top-level fun/val. See plan §3.3."
534 }
535 return null
536 }
537
538 private fun hasTopLevelFunctions(node: UFile): Boolean {
539 for (clazz in node.classes) {
540 for (method in clazz.methods) {
541 val psi = method.sourcePsi as? KtNamedFunction ?: continue
542 if (psi.isTopLevel()) return true
543 }
544 }
545 return false
546 }
547
548 private fun KtNamedFunction.isTopLevel(): Boolean = parent is KtFile
549
550 private fun KtNamedFunction.isComposable(): Boolean =
551 annotationEntries.any { it.shortName?.asString() == "Composable" || it.text.contains("Composable") }
552
553 private fun ktName(decl: org.jetbrains.kotlin.psi.KtDeclaration): String? = when (decl) {
554 is KtClass -> decl.name
555 is KtNamedFunction -> decl.name
556 is KtProperty -> decl.name
557 is KtTypeAlias -> decl.name
558 else -> null
559 }
560
561 private val BANNED_ALIAS_MAP: Map<String, String> = mapOf(
562 "util" to "domain/ or platform/ (see litmus test in docs/package-structure.md §2.1)",
563 "api" to "network/",
564 "model" to "data/ (or data/model/ subpackage)",
565 "viewmodel" to "platform/",
566 "widgets" to "widget/ (singular and flat)",
567 "glance" to "widget/ (flat; Glance is an implementation detail, not a package)",
568 "composer" to "ui/composer/",
569 "shields" to "domain/shields/",
570 "syntax" to "domain/syntax/",
571 "ime" to "platform/ime/",
572 "tts" to "platform/tts/",
573 "imap" to "network/imap/",
574 "smtp" to "network/smtp/",
575 "saf" to "data/saf/",
576 "crypto" to "domain/crypto/",
577 "format" to "domain/format/",
578 "remote" to "network/remote/",
579 "sink" to "data/sink/",
580 )
581
582 private fun aliasSuggestion(badSegment: String): String? {
583 val mapped = BANNED_ALIAS_MAP[badSegment]
584 return when {
585 mapped != null -> mapped
586 else -> "Move under one of [data|network|domain|platform|...] per docs/package-structure.md §2.3"
587 }
588 }
589
590 val ISSUE: Issue = Issue.create(
591 id = "PackageStructure",
592 briefDescription = "Package not in canonical closed set",
593 explanation = """
594 Each app's `src/main/java/com/vayunmathur/<app>/` may only contain the closed \
595 set of roots: [ui, data, domain, platform, network, intents, service, provider, \
596 widget, notifications, sync, telephony]. Any other top-level segment is a \
597 violation. Descendant segments must name a responsibility, feature, provider, \
598 or protocol; generic buckets and synonyms (`util`, `common`, `helper`, \
599 `manager`, `api`, `viewmodel`, `widgets`, …) are violations. `widget` is \
600 singular and flat: `widget.glance` and every other `widget.<child>` are \
601 violations because Glance is an implementation detail, not a package boundary. \
602 Additionally, files whose package is exactly `com.vayunmathur.<app>` \
603 (app root) are restricted to a closed file allow-list: [MainActivity.kt (only \
604 class MainActivity), Route.kt (only sealed interface Route : NavKey), \
605 Navigation.kt (only @Composable fun Navigation(...)), *Application.kt (only the \
606 Application subclass)]. Any other root file, or a root file violating its content \
607 contract (e.g. Route inside MainActivity.kt, screens inside Navigation.kt, \
608 composables inside Route.kt), is also a violation. Re-nest the code under the \
609 closest canonical root per docs/package-structure.md §2.3, or amend the plan to \
610 add a new root. Shared library modules (com.vayunmathur.library*) are excluded \
611 from this check.
612 """.trimIndent(),
613 category = Category.CORRECTNESS,
614 priority = 8,
615 severity = Severity.ERROR,
616 implementation = Implementation(
617 PackageStructureDetector::class.java,
618 Scope.JAVA_FILE_SCOPE,
619 ),
620 )
621 }
622}