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

Modern-Apps.git / build.gradle.kts

build.gradle.kts439 lines · 21.5 KiBRaw
1// Top-level build file where you can add configuration options common to all sub-projects/modules.
2plugins {
3 alias(libs.plugins.android.application) apply false
4 alias(libs.plugins.kotlin.compose) apply false
5 alias(libs.plugins.android.library) apply false
6 alias(libs.plugins.kotlin.serialization) apply false
7 alias(libs.plugins.ksp) apply false
8 alias(libs.plugins.protobuf) apply false
9 // Dependency-update report: ./gradlew dependencyUpdates lists what is outdated
10 // across the version catalog. Report-only; it never changes a version by itself.
11 alias(libs.plugins.versions)
12}
13
14// Repairs corrupted translations contributed via Weblate where the <xliff:g> markup
15// was escaped (e.g. "&lt;xliff:g ...&gt;%1$s&lt;/xliff:g&gt;"). When escaped, Android
16// renders the markup literally in the UI instead of only the placeholder. This task
17// unwraps such occurrences back to their inner placeholder (e.g. "%1$s"). See issue #477.
18tasks.register("fixStrings") {
19 group = "translation"
20 description = "Fixes translated strings where <xliff:g> markup was escaped and shows up literally in the UI (#477)."
21 val projectRoot = rootDir
22 doLast {
23 val escapedXliff = Regex(
24 "&lt;\\s*xliff:g\\b.*?&gt;(.*?)&lt;\\s*/\\s*xliff:g\\s*&gt;",
25 RegexOption.DOT_MATCHES_ALL,
26 )
27 var filesChanged = 0
28 var replacements = 0
29 projectRoot.walkTopDown()
30 .onEnter { it.name != "build" && it.name != ".git" }
31 .filter { it.isFile && it.name == "strings.xml" }
32 .forEach { file ->
33 val original = file.readText()
34 var count = 0
35 val fixed = escapedXliff.replace(original) { match ->
36 count++
37 match.groupValues[1]
38 }
39 if (count > 0) {
40 file.writeText(fixed)
41 filesChanged++
42 replacements += count
43 println("fixStrings: fixed $count occurrence(s) in ${file.relativeTo(projectRoot)}")
44 }
45 }
46 println("fixStrings: done. Fixed $replacements occurrence(s) across $filesChanged file(s).")
47 }
48}
49
50// Store listings are generated from metadata_data/<module-key>.md by the release build,
51// which takes line 1
52// as the short description and the whole file as the full description. Play and F-Droid cap a
53// summary at 80 characters, and nothing else in the build looks at these files, so the format
54// is enforced here. Required shape, exactly:
55//
56// 1 a summary, at most 80 characters
57// 2 blank
58// 3 Features:
59// 4+ one or more "- " bullets
60// blank
61// a connectivity line: "100% offline", "Requires internet",
62// "Internet required only for initial asset downloads", or
63// "Internet only used for: <feature(s)>" - the last only when the app still mostly
64// works without a connection.
65tasks.register("checkMetadata") {
66 group = "verification"
67 description = "Checks every app module has a metadata_data/*.md store listing in the required format."
68 val projectRoot = rootDir
69 doLast {
70 val fixedConnectivity = listOf(
71 "100% offline",
72 "Requires internet",
73 "Internet required only for initial asset downloads",
74 )
75 val connectivityPrefix = "Internet only used for: "
76
77 // Declared inside the task action rather than as a script-level function so the
78 // action does not capture a reference to the build script, which the configuration
79 // cache cannot serialize.
80 val problemsIn = { lines: List<String> ->
81 // summary, blank, "Features:", one bullet, blank, connectivity
82 if (lines.size < 6) {
83 listOf("has only ${lines.size} line(s); the format needs at least 6")
84 } else {
85 val problems = mutableListOf<String>()
86 val summary = lines[0]
87 if (summary.isBlank()) {
88 problems += "line 1 (the short description) is empty"
89 } else if (summary.length > 80) {
90 problems += "line 1 is ${summary.length} characters; the summary caps at 80"
91 }
92 if (lines[1].isNotEmpty()) {
93 problems += "line 2 must be blank, but is \"${lines[1]}\""
94 }
95 if (lines[2] != "Features:") {
96 problems += "line 3 must be \"Features:\", but is \"${lines[2]}\""
97 }
98
99 val connectivity = lines.last()
100 if (connectivity in fixedConnectivity) {
101 // fine
102 } else if (connectivity.startsWith(connectivityPrefix)) {
103 if (connectivity.removePrefix(connectivityPrefix).isBlank()) {
104 problems += "\"$connectivityPrefix\" must name the feature(s) using the internet"
105 }
106 } else {
107 problems += "the last line must be one of " +
108 fixedConnectivity.joinToString(", ") { "\"$it\"" } +
109 " or \"$connectivityPrefix<feature(s)>\", but is \"$connectivity\""
110 }
111 if (lines[lines.size - 2].isNotEmpty()) {
112 problems += "the last line must be preceded by a blank line"
113 }
114
115 val bullets = lines.subList(3, lines.size - 2)
116 if (bullets.isEmpty()) problems += "there must be at least one feature bullet"
117 bullets.forEachIndexed { index, line ->
118 if (!line.startsWith("- ")) {
119 problems += "line ${index + 4} must be a \"- \" bullet, but is \"$line\""
120 } else if (line.removePrefix("- ").isBlank()) {
121 problems += "line ${index + 4} is an empty feature bullet"
122 }
123 }
124 problems
125 }
126 }
127
128 val metadataDir = File(projectRoot, "metadata_data")
129
130 // Module detection by grepping for the bare string
131 // "common-conventions-app", which also matches library/map, where it appears only in a
132 // comment. Matching the plugin application instead keeps this list to real apps.
133 // analysis/ and personal/ hold gitignored experiments with copied app build files;
134 // they are never published, so skip them (same exclusions as release-build.sh).
135 val appPlugin = Regex("""id\("common-conventions-app"\)""")
136 val moduleKeys = projectRoot.walkTopDown()
137 .onEnter {
138 it.name != "build" && it.name != ".git" &&
139 it.name != "analysis" && it.name != "personal"
140 }
141 .filter { it.isFile && it.name == "build.gradle.kts" }
142 .filter { appPlugin.containsMatchIn(it.readText()) }
143 .map { it.parentFile.relativeTo(projectRoot).invariantSeparatorsPath.replace('/', '-') }
144 .toSortedSet()
145
146 val problems = mutableListOf<String>()
147 for (key in moduleKeys) {
148 val file = File(metadataDir, "$key.md")
149 if (!file.isFile) {
150 problems += "$key.md: missing; every app module needs a store listing"
151 continue
152 }
153 problemsIn(file.readLines()).forEach { problems += "$key.md: $it" }
154 }
155
156 val listings = metadataDir.listFiles { f: File -> f.isFile && f.extension == "md" }
157 ?.map { it.nameWithoutExtension }
158 .orEmpty()
159 (listings - moduleKeys).sorted().forEach {
160 problems += "$it.md: does not match any app module, so it is never published"
161 }
162
163 problems.forEach { println("checkMetadata: $it") }
164 if (problems.isNotEmpty()) {
165 throw GradleException(
166 "checkMetadata: ${problems.size} problem(s) across ${moduleKeys.size} app module(s).",
167 )
168 }
169 println("checkMetadata: ${moduleKeys.size} store listing(s) are correctly formatted.")
170 }
171}
172
173// Guards issue #884: no library/SDK module may depend on another library
174// module that declares Android permissions, or those permissions silently
175// merge into every consuming app (pdf gained network access this way). A
176// second list pins the remaining permission-free lib→lib edges, so a new
177// edge (permission-free today, permission-declaring tomorrow) fails until
178// it is reviewed and documented here.
179// Runs standalone (`./gradlew verifyLibraryBoundaries`) and from ./check.
180// Configuration-cache compatible: the action captures only string literals
181// (project root path + both lists) and does all file IO at execution time.
182tasks.register("verifyLibraryBoundaries") {
183 group = "verification"
184 description = "Fails if a library/SDK module depends on another library module " +
185 "that declares Android permissions (directly or transitively), or on a " +
186 "library module outside the documented permission-free edge list."
187 val projectRoot = rootDir
188 // Permission-declaring modules: nothing in library/* or sdk/* may depend on
189 // these (directly or transitively). Declared here rather than inferred so a
190 // module that newly gains a permission fails loudly instead of silently
191 // widening the blast radius. No exceptions: map and downloadservice declare
192 // INTERNET themselves exactly so they need no edge into network.
193 val permissionDeclaringModules = setOf(
194 ":library:network",
195 ":library:map",
196 ":library:downloadservice",
197 )
198 // The only permitted lib→lib edges (all permission-free; each is justified
199 // in its module's AGENTS.md Deps line):
200 // - many modules → :library (shared nav/DTO/Room base; declares nothing)
201 // - :library:room → :library (DbBackupCodec SPI)
202 // - :library:biometric → :library (DatabaseHelper keystore)
203 // - :library:work → :library (reminder notification resources)
204 // - :library:widgets → :library (Log facade only)
205 // - :library:downloadservice → :library (DataStoreUtils)
206 // - :library:ui → :library (shell + nav base)
207 // - :library:avatar → :library:ui, :library:carhost → :library:ui,
208 // :library:tv → :library:ui (Compose shell; ui is permission-free)
209 // - :library:tv → :library (base DTOs alongside the ui shell)
210 // - :library:ocr → :library:ml (on-device OCR runs on the ml runtime)
211 // - :sdk:controller → :library:e2ee-p2p, :cast:protocol → :library:e2ee-p2p
212 // (Hkdf key schedule + E2EE handshake; e2ee-p2p declares nothing)
213 // - :library → :sdk:games (achievement contract in the shared base)
214 // - :auto:protocol → :library (shared DTOs)
215 // - :library:everysync-core → :library:e2ee-p2p (E2EE sync transport)
216 // - :sdk:openassistant → (none)
217 val allowedLibraryEdges = setOf(
218 ":library" to ":sdk:games",
219 ":auto:protocol" to ":library",
220 ":library:everysync-core" to ":library:e2ee-p2p",
221 ":library:avatar" to ":library:ui",
222 ":library:biometric" to ":library",
223 ":library:carhost" to ":library:ui",
224 ":library:downloadservice" to ":library",
225 ":library:ocr" to ":library:ml",
226 ":library:room" to ":library",
227 ":library:tv" to ":library",
228 ":library:tv" to ":library:ui",
229 ":library:ui" to ":library",
230 ":library:widgets" to ":library",
231 ":library:work" to ":library",
232 ":sdk:controller" to ":library:e2ee-p2p",
233 ":cast:protocol" to ":library:e2ee-p2p",
234 )
235 doLast {
236 val projectRef = Regex("""project\(["'](:[A-Za-z0-9:_\-]+)["']\)""")
237 val permissionRef = Regex("""<uses-permission[^>]*android:name="([^"]+)"""")
238 val manifestOf = { moduleDir: File ->
239 File(moduleDir, "src/main/AndroidManifest.xml").takeIf { it.isFile }
240 }
241 val permissionsOf = { moduleDir: File ->
242 val manifest = manifestOf(moduleDir)
243 if (manifest == null) {
244 emptySet()
245 } else {
246 permissionRef.findAll(manifest.readText()).map { it.groupValues[1] }.toSet()
247 }
248 }
249 // Library modules = anything applying the library/KMP convention plugin
250 // (apps apply common-conventions-app and may depend on libraries freely).
251 // aosp-stubs is compile-only; log is added to every library by the
252 // convention plugin and declares nothing.
253 val skipDirs = setOf(".git", ".gradle", ".kotlin", "build", "build-logic", "analysis",
254 "personal", "target", "third_party", "node_modules", "scripts", "firmware")
255 val libraryPlugin = Regex("""id\("common-conventions-(library|kmp)"\)""")
256 val libraryDirs = projectRoot.walkTopDown()
257 .maxDepth(3)
258 .onEnter { it == projectRoot || it.name !in skipDirs }
259 .filter { it.isDirectory && it != projectRoot }
260 .filter {
261 val build = File(it, "build.gradle.kts")
262 build.isFile && libraryPlugin.containsMatchIn(build.readText())
263 }
264 .filter {
265 val rel = it.relativeTo(projectRoot).invariantSeparatorsPath
266 rel != "library/aosp-stubs" && rel != "library/log"
267 }
268 .toList()
269 val gradlePathOf = { dir: File ->
270 ":" + dir.relativeTo(projectRoot).invariantSeparatorsPath.replace('/', ':')
271 }
272 val dirOf = { gradlePath: String ->
273 File(projectRoot, gradlePath.trimStart(':').replace(':', '/'))
274 }
275 val directDeps = libraryDirs.associate { dir ->
276 val text = File(dir, "build.gradle.kts").readText()
277 gradlePathOf(dir) to projectRef.findAll(text).map { it.groupValues[1] }.toSet()
278 }
279 val violations = mutableListOf<String>()
280 for ((module, deps) in directDeps) {
281 val seen = mutableSetOf<String>()
282 val queue = ArrayDeque(deps)
283 while (queue.isNotEmpty()) {
284 val dep = queue.removeFirst()
285 if (!seen.add(dep)) continue
286 val depDir = dirOf(dep)
287 if (!depDir.isDirectory) continue
288 val perms = permissionsOf(depDir)
289 // Belt and braces: the declared set fails fast on known
290 // permission modules, while the manifest scan catches a module
291 // that newly gains a permission without updating the set.
292 if (dep in permissionDeclaringModules || perms.isNotEmpty()) {
293 val why = if (perms.isNotEmpty()) {
294 "which declares " + perms.sorted().joinToString(", ")
295 } else {
296 "which is a permission-declaring module"
297 }
298 violations += "$module depends on $dep, $why"
299 }
300 directDeps[dep]?.let { queue.addAll(it) }
301 }
302 for (dep in deps) {
303 if ((module to dep) !in allowedLibraryEdges) {
304 violations += "$module depends on $dep, which is not in the " +
305 "documented permission-free edge list — review and document " +
306 "it in verifyLibraryBoundaries (root build.gradle.kts) first"
307 }
308 }
309 }
310 violations.forEach { println("verifyLibraryBoundaries: VIOLATION: $it") }
311 if (violations.isNotEmpty()) {
312 throw GradleException(
313 "verifyLibraryBoundaries: ${violations.size} permission-leaking " +
314 "library edge(s). Move the permission-needing code into the " +
315 "consuming app (or the permission-declaring module) instead of " +
316 "depending across libraries — see issue #884.",
317 )
318 }
319 println(
320 "verifyLibraryBoundaries: ${libraryDirs.size} library module(s) checked, " +
321 "no permission-leaking edges.",
322 )
323 }
324}
325
326// Jacoco XML summaries land under build/reports/coverage after unit or instrumented runs,
327// while manual runs drop .ec files under build/outputs/coverage-manual. This task only reads
328// existing outputs, so it never triggers test execution.
329tasks.register("coverageSummary") {
330 group = "verification"
331 description = "Sums per-module Jacoco report.xml counters " +
332 "into a per-module + total table (unit + instrumented + manual .ec inventory)."
333 val projectRoot = rootDir
334 doLast {
335 val reportMarker = "build/reports/coverage/"
336 // analysis/ holds gitignored reference-app checkouts, not modules.
337 val skipDirs = setOf(".git", "analysis")
338 val reports = projectRoot.walkTopDown()
339 .onEnter { it.name !in skipDirs }
340 .filter { it.isFile && it.name == "report.xml" }
341 .filter { it.relativeTo(projectRoot).invariantSeparatorsPath.contains(reportMarker) }
342 .toList()
343 if (reports.isEmpty()) {
344 println("coverageSummary: no coverage data yet, run ./test")
345 }
346 val factory = javax.xml.parsers.DocumentBuilderFactory.newInstance()
347 factory.isValidating = false
348 factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
349 val docBuilder = factory.newDocumentBuilder()
350 val coveredByModule = mutableMapOf<String, MutableMap<String, LongArray>>()
351 val moduleKeyFor = { file: File, marker: String ->
352 val rel = file.relativeTo(projectRoot).invariantSeparatorsPath
353 val modulePath = rel.substringBefore("/$marker").trim()
354 if (modulePath.isEmpty()) "root" else modulePath.replace('/', '-')
355 }
356 for (report in reports) {
357 val key = moduleKeyFor(report, reportMarker)
358 val counts = coveredByModule.getOrPut(key) { mutableMapOf() }
359 val doc = report.inputStream().use { docBuilder.parse(it) }
360 // Only the root <report> element's own counters: getElementsByTagName
361 // returns every nested package/class/method counter too, which would
362 // multiply-count the same instructions.
363 val root = doc.documentElement
364 val nodes = root.childNodes
365 for (i in 0 until nodes.length) {
366 val element = nodes.item(i) as? org.w3c.dom.Element ?: continue
367 if (element.tagName != "counter") continue
368 val type = element.getAttribute("type")
369 if (type != "INSTRUCTION" && type != "BRANCH" && type != "LINE") {
370 if (type != "METHOD") continue
371 }
372 val slot = counts.getOrPut(type) { longArrayOf(0L, 0L) }
373 slot[0] += element.getAttribute("covered").toLongOrNull() ?: 0L
374 slot[1] += element.getAttribute("missed").toLongOrNull() ?: 0L
375 }
376 }
377 val pct = { covered: Long, total: Long ->
378 if (total > 0) "%.1f".format(covered * 100.0 / total) else "100.0"
379 }
380 val lineFor = { counts: Map<String, LongArray> ->
381 val instr = counts["INSTRUCTION"] ?: longArrayOf(0L, 0L)
382 val branch = counts["BRANCH"] ?: longArrayOf(0L, 0L)
383 val line = counts["LINE"] ?: longArrayOf(0L, 0L)
384 val instrTotal = instr[0] + instr[1]
385 val branchTotal = branch[0] + branch[1]
386 val lineTotal = line[0] + line[1]
387 "instr ${pct(instr[0], instrTotal)}% (${instr[0]}/$instrTotal), " +
388 "branch ${pct(branch[0], branchTotal)}%, line ${pct(line[0], lineTotal)}%"
389 }
390 for (key in coveredByModule.keys.sorted()) {
391 println("coverageSummary: $key: ${lineFor(coveredByModule.getValue(key))}")
392 }
393 if (coveredByModule.isNotEmpty()) {
394 val total = mutableMapOf<String, LongArray>()
395 for (counts in coveredByModule.values) {
396 for ((type, slot) in counts) {
397 val acc = total.getOrPut(type) { longArrayOf(0L, 0L) }
398 acc[0] += slot[0]
399 acc[1] += slot[1]
400 }
401 }
402 println("coverageSummary: TOTAL: ${lineFor(total)}")
403 }
404 val ecMarker = "build/outputs/coverage-manual/"
405 val ecFiles = projectRoot.walkTopDown()
406 .onEnter { it.name !in skipDirs }
407 .filter { it.isFile && it.extension == "ec" }
408 .filter { it.relativeTo(projectRoot).invariantSeparatorsPath.contains(ecMarker) }
409 .sortedBy { it.relativeTo(projectRoot).invariantSeparatorsPath }
410 .toList()
411 if (ecFiles.isEmpty()) {
412 println("coverageSummary: no manual .ec files yet")
413 } else {
414 for (ec in ecFiles) {
415 val key = moduleKeyFor(ec, ecMarker)
416 val rel = ec.relativeTo(projectRoot).invariantSeparatorsPath
417 println("coverageSummary: ec $key: $rel (${ec.length()} bytes)")
418 }
419 }
420 val testedModules = projectRoot.walkTopDown()
421 .onEnter { it.name != ".git" && it.name != "build" && it.name != "analysis" }
422 .filter { it.isDirectory && (it.name == "test" || it.name == "androidTest") }
423 .filter { it.parentFile != null && it.parentFile.name == "src" }
424 .map {
425 val rel = it.relativeTo(projectRoot).invariantSeparatorsPath
426 val modulePath = rel.substringBefore("/src/")
427 if (modulePath.isEmpty()) "root" else modulePath.replace('/', '-')
428 }
429 .toSortedSet()
430 val gaps = (testedModules - coveredByModule.keys).sorted()
431 if (gaps.isEmpty()) {
432 println("coverageSummary: no coverage gaps.")
433 } else {
434 for (key in gaps) {
435 println("coverageSummary: no report for $key (has src/test or src/androidTest)")
436 }
437 }
438 }
439}