Custom lint rules
Overview
The lint-rules module packages Keiyoushi-specific Android lint checks as a Kotlin/JVM lint jar. lint-rules/build.gradle.kts compiles the checks against Java 17, pins the Kotlin API/language level to 2.1 because lint loads the jar with its own older Kotlin stdlib, and publishes the registry through the jar manifest attribute Lint-Registry-v2 = keiyoushi.lint.KeiIssueRegistry. The service loader file at lint-rules/src/main/resources/META-INF/services/com.android.tools.lint.client.api.IssueRegistry points at the same registry class for lint discovery.
lint-rules/…/KeiIssueRegistry.kt is the module entry point. It concatenates the issue lists exported by every detector and declares the vendor metadata (keiyoushi-lint-rules) plus CURRENT_API and minApi = 14. Most source checks use helpers in lint-rules/…/Util.kt: issue<T>() creates Java-file-scoped issues in the shared Keiyoushi category, constants name the repository’s important API types (HttpSource, KeiSource, SManga, SChapter, OkHttp Interceptor), and UAST helpers normalize receiver chains, string values, call locations, named arguments, enclosing methods, and interceptor contexts.
Repository-specific source constraints are enforced by combining lint UAST with nearby extension build scripts. Util.kt defines BuildScript, which walks upward from the checked source file to the nearest build.gradle.kts, reads the keiyoushi { source { ... } } text, and exposes whether the module is a theme, whether baseUrl can change through mirrors(...) or custom(...), and which hosts appear in base URLs and mirrors. SourceDetector and ContentDetector use this to distinguish safe static constants from source code that must keep working under mirrors, custom URLs, themes, or fetchBaseUrls.
Detector and rule catalog
- lint-rules/…/NetworkDetector.kt enforces network helper usage and browser-like request behavior. It flags suspend
OkHttpClient.newCall/Call.Factory.newCallwhen the call is not enqueued, manual or redundantReferer, rawCookieheaders, browser-managed headers,add/addHeaderfor single-valued headers,headers.newBuilder()on a source’s default headers, response bodies read with.string()and immediately parsed outside interceptors,HttpUrl.toString()passed to Keiyoushi request helpers, off-UI-threadToast, hardcoded desktop user agents, and manual Cloudflare challenge checks. - lint-rules/…/JsonDetector.kt keeps serialization code on the shared repository conventions. It flags
@Serializable data classDTOs, redundant@SerialNamevalues, snake_case DTO properties without mapping, nullable DTO constructor parameters defaulted tonull, injected localJson/ProtoBufinstances, directJson.decodeFrom*calls, hand-built JSON media types, and manualJsonElementtraversal throughjsonObject/jsonPrimitive/jsonArray. - lint-rules/…/JsoupDetector.kt covers HTML parsing idioms. It reports
select(q).first()/firstOrNull()instead ofselectFirst(q), redundantElement.text().trim()orownText().trim(),setUrlWithoutDomain(e.attr("href"))withoutabs:,Jsoup.parse(response.body.string()), and selectors containing generated CSS module/emotion/styled-components class names. - lint-rules/…/DateTimeDetector.kt pushes sources toward
java.timeandkotlin.time. It flagsSimpleDateFormat,System.currentTimeMillis(), locale-sensitiveDateTimeFormatter.ofPattern(...)calls without aLocale, and quoted'Z'offset literals in date patterns. - lint-rules/…/KotlinIdiomDetector.kt collects Kotlin and extension-style rules. It reports regexes compiled inside functions and double-escaped regex strings,
filterIsInstance<T>().first*, redundantjoinToString(", "), UTF-8 byte/string and hex formatting boilerplate, manual crypto primitives, swallowed parsing errors throughrunCatchingfallbacks or empty catches,StringBuilder(),Page(i, "", imageUrl), Android debug logs, directgetSharedPreferences,•bullets in Markdown descriptions, genericException("HTTP $code"), and message-only custom exception classes. - lint-rules/…/SourceDetector.kt enforces source lifecycle and app contract invariants. It removes redundant
supportsLatest = trueoverrides on directKeiSourcesubclasses, warns on impossiblefetchMangaUpdateflag guards, prevents returning an empty chapter list whenfetchChaptersis false, catches stored properties/lazy delegates eagerly derived from dynamicbaseUrlorheaders, rejects placeholder fallbacks for mandatorySManga/SChaptertitle/name/url fields, and discourages chapter sorting bychapter_number. - lint-rules/…/FlowDetector.kt checks source entry-point behavior. It expects
getMangaByUrlresults parsed from details paths to setinitialized = true, prefersgetMangaByUrlover single-itemgetMangasByUrl, rejectsgetImageUrloverrides that only throw, requiresgetImageRequestcustomizations to start fromsuper.getImageRequest(page).newBuilder(), prefersemptyList()over throwing for empty page lists, forbids per-entry requests in listing methods, flags client-side paging of a complete list, rejects random ordering in listing flows, and removes explicitheadersarguments when Keiyoushi network helpers already use the source defaults. - lint-rules/…/ContentDetector.kt protects stored model content and parsing conventions. It flags absolute or fragment-bearing stored
SManga.url/SChapter.urlvalues, chapter-name stripping of the manga title, hardcoded comparisons against the source’s own base-url host, URL extraction with string slicing, collapsedtext()from parsed HTML fragments, hand-written Markdown description labels, reads of app preference keys such asshow_nsfw_source, manual Next.js flight parsing, custom Turnstile solver classes, and whole-ZIPZipInputStreamreads. - lint-rules/…/BuildScriptDetector.kt is the Gradle DSL scanner for
keiyoushiblocks. It tracks top-level extension names, per-source names/languages/base-url hosts, mirrors/custom hosts, deeplink hosts, and explicit source ids. It reports language suffixes in source/extension names, a singlesource { name }equal to the top-level name, deeplinkhost(...)calls that exactly restate all base URL hosts, and explicit sourceidassignments;KeiExplicitSourceIdis disabled by default because it is only reviewable in the context of a new versus renamed source. - lint-rules/…/IconDetector.kt is a binary resource scanner for extension icons. It checks res/…/ic_launcher.png dimensions for mdpi through xxxhdpi, validates the xxxhdpi icon’s square-generator shape, reports missing density icons unless a themed extension inherits all icons from
lib-multisrc/<theme>/res, and errors on leftover res/web_hi_res_512.png.
How tests are structured
lint-rules/…/DetectorsTest.kt tests source-code detectors with Android lint’s test infrastructure. The local check(issue, code, vararg extra) helper builds a synthetic Kotlin file at src/…/Test.kt, adds all shared stubs from Stubs.all, scopes lint to a single issue, allows a missing SDK, and disables test modes that are not meaningful for ktlint-formatted extension sources. The test file is organized by detector regions and asserts warning counts, error counts for hard rules, and quick-fix diffs where detectors provide fixes.
lint-rules/…/Stubs.kt supplies only the API surface the detectors need to resolve symbols: OkHttp, Jsoup, kotlinx serialization/json, Tachiyomi model/source classes, KeiSource, Keiyoushi network helpers, Android Toast/Log/Context, and Injekt. When a source detector depends on build-script context, individual tests pass a synthetic build.gradle.kts via source(...) so BuildScript reads the same path layout lint would see in an extension module.
lint-rules/…/ResourcesTest.kt covers non-UAST detectors. The gradle(...) helper runs BuildScriptDetector against Kotlin script snippets, while icon tests create synthetic PNG resources with LintDetectorTest.image(...) and enable useTestProjectImplementation(true) so binary/resource project traversal behaves like an extension module. The icon tests cover valid generated squares, themed icon inheritance from lib-multisrc, missing or wrong density sizes, malformed shapes, borders, and leftover high-resolution generator output.
Integration points with build logic
The lint jar is discoverable in two ways: lint-rules/build.gradle.kts writes the Lint-Registry-v2 manifest attribute, and lint-rules/src/main/resources/META-INF/services/com.android.tools.lint.client.api.IssueRegistry registers keiyoushi.lint.KeiIssueRegistry for service loading. Any new detector must export an ISSUES list and be appended to KeiIssueRegistry.issues; otherwise the detector may compile and test locally but will not run from the packaged lint jar.
Most detectors use issue<T>() from Util.kt, which hardcodes Scope.JAVA_FILE_SCOPE. Detectors that do not scan Java/Kotlin files define their own implementations: BuildScriptDetector.kt creates Gradle-scoped issues with Scope.GRADLE_SCOPE, and IconDetector.kt creates binary-resource-scoped issues with Scope.BINARY_RESOURCE_FILE_SCOPE. If a detector changes scanning scope, verify that its Implementation scope matches the callbacks it implements.
The module’s repository-specific constraints depend on extension build files using the expected keiyoushi { source { ... } }, baseUrl { mirrors/custom }, deeplink { host(...) }, and theme = "..." shapes. BuildScriptDetector.kt parses Gradle through lint’s DSL callbacks, but Util.kt’s BuildScript uses simple text reads and regular expressions for nearby build.gradle.kts files; source checks that rely on mirrors, custom URLs, base-url hosts, or theme inheritance can miss cases if the build DSL shape changes without updating BuildScript.
Coupling
- If a detector adds, removes, or renames an issue in any lint-rules/…/*.kt file, also update lint-rules/…/KeiIssueRegistry.kt when the detector list changes and the relevant tests in DetectorsTest.kt or ResourcesTest.kt; issue objects are the public registration surface for lint.
- If source model or helper type names change, update the constants in lint-rules/…/Util.kt and the stubs in lint-rules/…/Stubs.kt; detectors resolve fully qualified names rather than importing production code.
- If the extension Gradle DSL changes, check both lint-rules/…/BuildScriptDetector.kt and lint-rules/…/Util.kt; the Gradle scanner and the text-based
BuildScripthelper parse overlapping but separate views of the same build logic. - If icon resource naming or theme inheritance changes, update lint-rules/…/IconDetector.kt and ResourcesTest.kt; the detector looks for exact res/…/ic_launcher.png, res/web_hi_res_512.png,
kei.plugins.extension, andlib-multisrc/<theme>/respaths.
Path-routable coverage notes
- lint-rules/build.gradle.kts,
lint-rules/src/main/resources/META-INF/services/com.android.tools.lint.client.api.IssueRegistry, and lint-rules/…/KeiIssueRegistry.kt route to lint-jar packaging and registry discovery. - lint-rules/…/Util.kt routes to shared lint helpers, type-name constants, UAST utilities, interceptor detection, and nearest-build-script parsing.
- lint-rules/…/NetworkDetector.kt, JsonDetector.kt, JsoupDetector.kt, DateTimeDetector.kt, KotlinIdiomDetector.kt, SourceDetector.kt, FlowDetector.kt, and ContentDetector.kt route to Kotlin/source detectors for extension source code.
- lint-rules/…/BuildScriptDetector.kt routes to Gradle
keiyoushiDSL checks. - lint-rules/…/IconDetector.kt routes to binary resource and extension icon checks.
- lint-rules/…/DetectorsTest.kt routes to UAST detector tests, ResourcesTest.kt to Gradle/resource detector tests, and Stubs.kt to the synthetic APIs those tests resolve against.
Risks
- lint-rules/…/Util.kt, SourceDetector.kt, and ContentDetector.kt read build.gradle.kts as text and look for literal fragments such as
mirrors(,custom(, URL regex matches, and nearest parent build files. If build scripts start computing URLs indirectly or move source declarations away from nearby modules, dynamic-base-url and host-comparison checks can silently stop firing. - lint-rules/…/FlowDetector.kt inspects method bodies and reachable methods by source text and UAST resolution, deliberately skipping
PsiCompiledElementto avoid decompilation crashes. If a source delegates details/listing behavior into compiled theme code, flow checks can miss duplicate details fetches, random listing order, or per-item listing requests. - lint-rules/…/IconDetector.kt validates icon shape with sampled pixels and fixed alpha/color-distance thresholds. Icons produced by a different generator or antialiasing profile can be false positives even when dimensions are correct, while malformed icons that avoid the sampled points can pass.