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

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

FileLengthDetector.kt135 lines · 6.2 KiBRaw
1package com.vayunmathur.lint
2
3import com.android.tools.lint.client.api.UElementHandler
4import com.android.tools.lint.detector.api.Category
5import com.android.tools.lint.detector.api.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.KtFile
13import org.jetbrains.uast.UElement
14import org.jetbrains.uast.UFile
15
16/**
17 * Caps Kotlin file length: 350 lines for files in a `ui` package, 800
18 * everywhere else.
19 *
20 * Oversized screen files are where brace-imbalance bugs hide (a stray `}` in
21 * a 900-line file breaks the whole module and the compiler points at the
22 * tail, not the cause) and where "one public composable per file" silently
23 * rots into grab-bags of private helpers. Splitting a screen into its pane
24 * components keeps each file reviewable and keeps diffs scoped.
25 *
26 * Test and screenshot sources are exempt — fixtures and literal-state
27 * previews are long by nature — as are generated files and the shared
28 * non-app modules in [LintPackageExclusions].
29 *
30 * Two further carve-outs live in [LENGTH_EXEMPT_FILES]: files that are long
31 * *by design* rather than by accretion — registries, shims and vendored
32 * third-party code that must stay whole to stay reviewable.
33 */
34class FileLengthDetector : Detector(), SourceCodeScanner {
35
36 override fun getApplicableUastTypes(): List<Class<out UElement>> = 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 (!packageName.startsWith("com.vayunmathur.")) return
44 if (LintPackageExclusions.isExcluded(packageName)) return
45
46 val fileName = context.file?.name
47 ?: (node.sourcePsi as? KtFile)?.name
48 ?: return
49 if (!fileName.endsWith(".kt")) return
50 if (fileName == "BuildConfig.kt" || fileName == "R.kt") return
51 if (fileName in LENGTH_EXEMPT_FILES) return
52
53 // Test, on-device-test and screenshot-preview sources are
54 // fixtures by nature; capping them would punish literal state.
55 // Vendored third-party code stays whole to stay diffable upstream.
56 val path = context.file?.path.orEmpty()
57 if (isVendored(path)) return
58 if (path.contains("/src/test/") || path.contains("/src/androidTest/") ||
59 path.contains("/src/screenshotTest/") ||
60 path.contains("\\src\\test\\") || path.contains("\\src\\androidTest\\") ||
61 path.contains("\\src\\screenshotTest\\")
62 ) {
63 return
64 }
65
66 val ktFile = node.sourcePsi as? KtFile ?: return
67 val lineCount = ktFile.text.lineSequence().count()
68 val isUi = packageName.split('.').contains("ui")
69 val limit = if (isUi) UI_LIMIT else OTHER_LIMIT
70 if (lineCount <= limit) return
71
72 context.report(
73 ISSUE,
74 node,
75 context.getLocation(node),
76 "File `$fileName` has $lineCount lines (limit $limit for " +
77 (if (isUi) "`ui` package files" else "non-`ui` files") + "). " +
78 "Split it — extract pane/section components into their own " +
79 "files under ui/, ui/components/, or ui/dialogs/ — so each " +
80 "file stays reviewable and brace errors stay local.",
81 )
82 }
83 }
84
85 companion object {
86 const val UI_LIMIT = 350
87 const val OTHER_LIMIT = 800
88
89 /**
90 * Files exempt by name: long by design, not by accretion.
91 *
92 * - `Icons.kt` / `MaterialComponents.kt` — the `library/ui` shim is
93 * one-function-per-symbol by design (same reason it is excluded from
94 * `OneComposablePerFile`); splitting it would scatter the registry.
95 * - `OdfSerializer.kt` / `OoxmlExporter.kt` — serializer registries;
96 * the format logic they enumerate must stay beside its dispatch.
97 * - `KeyboardService.kt` — the IME service; input-method lifecycle
98 * plus candidates plus gestures in one place is the platform norm.
99 * - `extractor/` (`youpipe/extractor`) — vendored NewPipe code, kept
100 * whole to stay diffable against upstream.
101 */
102 val LENGTH_EXEMPT_FILES: Set<String> = setOf(
103 "Icons.kt",
104 "MaterialComponents.kt",
105 "OdfSerializer.kt",
106 "OoxmlExporter.kt",
107 "KeyboardService.kt",
108 )
109
110 /** True if the file lives under a vendored third-party tree. */
111 fun isVendored(path: String): Boolean =
112 path.contains("/youpipe/extractor/") || path.contains("\\youpipe\\extractor\\")
113
114 val ISSUE: Issue = Issue.create(
115 id = "FileLength",
116 briefDescription = "Kotlin file exceeds the line limit",
117 explanation = """
118 Kotlin files in a `ui` package are limited to $UI_LIMIT lines; all \
119 other Kotlin sources to $OTHER_LIMIT lines. Oversized screen files \
120 hide brace-imbalance breakage (the compiler points at the tail, not \
121 the cause) and rot into grab-bags of helpers. Extract pane and \
122 section components into their own files under ui/, ui/components/, \
123 or ui/dialogs/. Test, androidTest and screenshotTest sources are \
124 exempt.
125 """.trimIndent(),
126 category = Category.PRODUCTIVITY,
127 priority = 5,
128 severity = Severity.ERROR,
129 implementation = Implementation(
130 FileLengthDetector::class.java,
131 Scope.JAVA_FILE_SCOPE,
132 ),
133 )
134 }
135}