Introducing a new way to review your PRs.

Read the announcement

keiyoushi / extensions-source

Source code of extensions in https://github.com/keiyoushi/extensions

View on GitHub

13 documents · Updated Nov 19, 2026

docs / lint-rules

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.newCall when the call is not enqueued, manual or redundant Referer, raw Cookie headers, browser-managed headers, add/addHeader for 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-thread Toast, 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 class DTOs, redundant @SerialName values, snake_case DTO properties without mapping, nullable DTO constructor parameters defaulted to null, injected local Json/ProtoBuf instances, direct Json.decodeFrom* calls, hand-built JSON media types, and manual JsonElement traversal through jsonObject/jsonPrimitive/jsonArray.
  • lint-rules/…/JsoupDetector.kt covers HTML parsing idioms. It reports select(q).first()/firstOrNull() instead of selectFirst(q), redundant Element.text().trim() or ownText().trim(), setUrlWithoutDomain(e.attr("href")) without abs:, Jsoup.parse(response.body.string()), and selectors containing generated CSS module/emotion/styled-components class names.
  • lint-rules/…/DateTimeDetector.kt pushes sources toward java.time and kotlin.time. It flags SimpleDateFormat, System.currentTimeMillis(), locale-sensitive DateTimeFormatter.ofPattern(...) calls without a Locale, 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*, redundant joinToString(", "), UTF-8 byte/string and hex formatting boilerplate, manual crypto primitives, swallowed parsing errors through runCatching fallbacks or empty catches, StringBuilder(), Page(i, "", imageUrl), Android debug logs, direct getSharedPreferences, • bullets in Markdown descriptions, generic Exception("HTTP $code"), and message-only custom exception classes.
  • lint-rules/…/SourceDetector.kt enforces source lifecycle and app contract invariants. It removes redundant supportsLatest = true overrides on direct KeiSource subclasses, warns on impossible fetchMangaUpdate flag guards, prevents returning an empty chapter list when fetchChapters is false, catches stored properties/lazy delegates eagerly derived from dynamic baseUrl or headers, rejects placeholder fallbacks for mandatory SManga/SChapter title/name/url fields, and discourages chapter sorting by chapter_number.
  • lint-rules/…/FlowDetector.kt checks source entry-point behavior. It expects getMangaByUrl results parsed from details paths to set initialized = true, prefers getMangaByUrl over single-item getMangasByUrl, rejects getImageUrl overrides that only throw, requires getImageRequest customizations to start from super.getImageRequest(page).newBuilder(), prefers emptyList() 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 explicit headers arguments 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.url values, chapter-name stripping of the manga title, hardcoded comparisons against the source’s own base-url host, URL extraction with string slicing, collapsed text() from parsed HTML fragments, hand-written Markdown description labels, reads of app preference keys such as show_nsfw_source, manual Next.js flight parsing, custom Turnstile solver classes, and whole-ZIP ZipInputStream reads.
  • lint-rules/…/BuildScriptDetector.kt is the Gradle DSL scanner for keiyoushi blocks. 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 single source { name } equal to the top-level name, deeplink host(...) calls that exactly restate all base URL hosts, and explicit source id assignments; KeiExplicitSourceId is 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

Path-routable coverage notes

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 PsiCompiledElement to 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.