From 6087dbba5eb4126c2bfa2888801b9a4c648cbec6 Mon Sep 17 00:00:00 2001 From: Eric Amorde Date: Wed, 4 Nov 2026 11:00:15 -0800 Subject: [PATCH 1/4] Add stat filters to Tech Debt Initiatives A Tech Debt Initiative can now count part of a stat. `remainingFilter` and `completedFilter` take a `StatFilter`: `extras` conditions for code references, or a `details` condition for numeric and boolean stats. Each filtered stat is published at build time as a derived stat, `tdi____remaining` or `tdi____completed`, so it gets totals, history, the web report and per-stat JSON/SARIF exports like any other stat. Derived stats are left out of the aggregate stats.sarif. `effectiveRemainingStatKey` and `effectiveCompletedStatKey` name the stat to read for an initiative and are written to tdi_config.json. Invalid filters fail the report, and the invert task now reruns when initiatives change. The examples project gains a filtered initiative. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + examples/build.gradle.kts | 107 +++++++ gradle/libs.versions.toml | 1 + invert-gradle-plugin/build.gradle.kts | 2 + .../internal/report/InvertReportWriter.kt | 46 ++- .../report/TechDebtInitiativeStats.kt | 155 ++++++++++ .../invert/internal/tasks/InvertTask.kt | 11 + .../report/TechDebtInitiativeStatsTest.kt | 291 ++++++++++++++++++ .../squareup/invert/models/StatFiltersTest.kt | 153 +++++++++ .../invert/models/TechDebtInitiativeTest.kt | 118 +++++++ .../com/squareup/invert/models/StatFilter.kt | 82 +++++ .../invert/models/js/TechDebtInitiative.kt | 57 +++- .../invert/models/utils/StatFilters.kt | 124 ++++++++ 13 files changed, 1150 insertions(+), 4 deletions(-) create mode 100644 invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt create mode 100644 invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt create mode 100644 invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/StatFiltersTest.kt create mode 100644 invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt create mode 100644 invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt create mode 100644 invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 5281b748..30e3896f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Change Log +## Unreleased + +* Tech Debt Initiatives can count part of a stat. `TechDebtInitiative.remainingFilter` and `completedFilter` take a `StatFilter`: `extras` conditions for code references, or a `details` condition for numeric and boolean stats. Each filtered stat is published at build time as a derived stat, `tdi____remaining` or `tdi____completed`, which gets totals, history, the web report and the per-stat JSON and SARIF exports like any other stat. It is left out of the aggregate `stats.sarif`. +* `TechDebtInitiative.effectiveRemainingStatKey` and `effectiveCompletedStatKey` name the stat to read for an initiative (the derived stat when filtered), and are written to `tdi_config.json`. Consumers that show or export initiative numbers should read these instead of `remainingStatKey` and `completedStatKey`. +* Invalid filters fail the report: an extra that the stat does not declare, a condition that does not apply to the stat type, an empty or invalid matcher, a duplicate initiative id, or a derived key that a collected stat already uses. +* Changing `techDebtInitiatives` now reruns the `invert` task. + ## Version 0.0.16 * Stream JSON report serialization directly to output files to reduce peak heap usage for large reports. diff --git a/examples/build.gradle.kts b/examples/build.gradle.kts index e9077c9f..0b72f88e 100644 --- a/examples/build.gradle.kts +++ b/examples/build.gradle.kts @@ -27,6 +27,71 @@ plugins { id("com.squareup.invert") } +/** + * Collects every Kotlin import as a code reference, with two extras that Tech Debt Initiatives + * can filter on: + * - `package`: the imported package, e.g. `io.ktor.client` for `io.ktor.client.*` or + * `io.ktor.client.HttpClient`. + * - `wildcard`: `true` for `*` imports, otherwise `false`. + */ +class KotlinImportsStatCollector : com.squareup.invert.StatCollector { + private val importRegex = Regex("""^import\s+([\w.]+?)(\.\*|\.\w+)?(\s+as\s+\w+)?\s*$""") + + override fun collect( + invertCollectContext: com.squareup.invert.InvertCollectContext, + ): List? { + val codeReferences = invertCollectContext.moduleDir.resolve("src") + .walkTopDown() + .filter { it.isFile && it.extension == "kt" } + .flatMap { sourceFile -> + val filePath = sourceFile.relativeTo(invertCollectContext.gitCloneDir).path + sourceFile.readLines().asSequence().mapIndexedNotNull { index, line -> + val match = importRegex.matchEntire(line.trim()) ?: return@mapIndexedNotNull null + val (path, lastSegment) = match.destructured + val isWildcard = lastSegment == ".*" + com.squareup.invert.models.Stat.CodeReferencesStat.CodeReference( + filePath = filePath, + startLine = index + 1, + endLine = index + 1, + code = line.trim(), + extras = mapOf( + "package" to path, + "wildcard" to isWildcard.toString(), + ), + ) + } + } + .toList() + if (codeReferences.isEmpty()) return null + return listOf( + com.squareup.invert.CollectedStat( + metadata = com.squareup.invert.models.StatMetadata( + key = "kotlin_imports", + title = "Kotlin Imports", + description = "Every Kotlin import, with its package and whether it is a wildcard import.", + dataType = com.squareup.invert.models.StatDataType.CODE_REFERENCES, + category = "Imports", + extras = listOf( + com.squareup.invert.models.ExtraMetadata( + key = "package", + type = com.squareup.invert.models.ExtraDataType.STRING, + description = "Imported package", + ), + com.squareup.invert.models.ExtraMetadata( + key = "wildcard", + type = com.squareup.invert.models.ExtraDataType.BOOLEAN, + description = "Wildcard import", + ), + ), + ), + stat = com.squareup.invert.models.Stat.CodeReferencesStat(codeReferences), + ) + ) + } + + override fun getName(): String = "kotlin-imports" +} + invert { ownershipCollector(com.squareup.invert.owners.GitHubCodeOwnersInvertOwnershipCollector) addStatCollector( @@ -43,6 +108,48 @@ invert { filePredicate = { it.extension == "kt" || it.extension == "kts" }, ) ) + addStatCollector(KotlinImportsStatCollector()) + + // Tech Debt Initiatives. After `./gradlew :invert`, open build/reports/invert/index.html and + // view one with `?page=stat_breakdown&remaining=&completed=`. + // json/tdi_config.json lists each initiative's effective keys. + + // A burndown of an existing stat, without filters. + addTechDebtInitiative( + com.squareup.invert.models.js.TechDebtInitiative( + id = "remove_wildcard_imports", + title = "Remove Wildcard Imports", + descriptionMarkdown = "Replace every wildcard import with explicit imports.", + unit = "Imports", + completedStatKey = null, + remainingStatKey = "wildcard-imports", + ) + ) + + // Both stats filtered from one stat, by extras. These are published as the derived stats + // `tdi__explicit_ktor_imports__remaining` and `tdi__explicit_ktor_imports__completed`. + addTechDebtInitiative( + com.squareup.invert.models.js.TechDebtInitiative( + id = "explicit_ktor_imports", + title = "Explicit Ktor Imports", + descriptionMarkdown = "Import Ktor declarations explicitly instead of with `io.ktor.*` wildcards.", + unit = "Imports", + completedStatKey = "kotlin_imports", + remainingStatKey = "kotlin_imports", + remainingFilter = com.squareup.invert.models.StatFilter( + extras = mapOf( + "package" to com.squareup.invert.models.ValueMatcher.regex("""^io\.ktor(\.|$)"""), + "wildcard" to com.squareup.invert.models.ValueMatcher.equalTo("true"), + ), + ), + completedFilter = com.squareup.invert.models.StatFilter( + extras = mapOf( + "package" to com.squareup.invert.models.ValueMatcher.regex("""^io\.ktor(\.|$)"""), + "wildcard" to com.squareup.invert.models.ValueMatcher.equalTo("true").negated(), + ), + ), + ) + ) } /** diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5b8802c1..e26bff46 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -27,6 +27,7 @@ detekt-sarif4k = { module = "io.github.detekt.sarif4k:sarif4k", version.ref = "s javax-inject = { module = "javax.inject:javax.inject", version.ref = "javax-inject" } kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" } +gson = { module = "com.google.code.gson:gson", version = "2.11.0" } kotlin-compiler-embeddable = { module = "org.jetbrains.kotlin:kotlin-compiler-embeddable", version.ref = "kotlin" } kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core", version.ref = "kotlinx-serialization" } diff --git a/invert-gradle-plugin/build.gradle.kts b/invert-gradle-plugin/build.gradle.kts index 2cb10995..cb1be5b9 100644 --- a/invert-gradle-plugin/build.gradle.kts +++ b/invert-gradle-plugin/build.gradle.kts @@ -60,6 +60,8 @@ dependencies { } testImplementation(libs.kotlin.test) + // Consumers parse tdi_config.json with Gson; tests check the models stay compatible. + testImplementation(libs.gson) } kotlin { diff --git a/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/InvertReportWriter.kt b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/InvertReportWriter.kt index e555c30d..b85f1fb2 100644 --- a/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/InvertReportWriter.kt +++ b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/InvertReportWriter.kt @@ -20,6 +20,8 @@ import com.squareup.invert.models.ExtraMetadata import com.squareup.invert.models.ModulePath import com.squareup.invert.models.OwnerName import com.squareup.invert.models.Stat +import com.squareup.invert.models.StatDataType +import com.squareup.invert.models.StatKey import com.squareup.invert.models.StatMetadata import com.squareup.invert.models.js.CollectedStatTotalsJsReportModel import com.squareup.invert.models.js.HistoricalData @@ -39,6 +41,30 @@ class InvertReportWriter( historicalData: Set, techDebtInitiatives: List, aggregateStatsSarifReportEnabled: Boolean = true, + ) { + // Publish filtered TDI stats as derived stats, before anything reads the collected stats. + val tdiStats = TechDebtInitiativeStats.addDerivedStats( + collectedData = collectedData, + techDebtInitiatives = techDebtInitiatives, + logger = invertLogger, + ) + writeProjectDataWithDerivedStats( + reportMetadata = reportMetadata, + collectedData = tdiStats.collectedData, + derivedStatKeys = tdiStats.derivedStatKeys, + historicalData = historicalData, + techDebtInitiatives = techDebtInitiatives, + aggregateStatsSarifReportEnabled = aggregateStatsSarifReportEnabled, + ) + } + + private fun writeProjectDataWithDerivedStats( + reportMetadata: MetadataJsReportModel, + collectedData: InvertCombinedCollectedData, + derivedStatKeys: Set, + historicalData: Set, + techDebtInitiatives: List, + aggregateStatsSarifReportEnabled: Boolean, ) { val collectedOwners: Set = collectedData.collectedOwners val collectedStats: Set = collectedData.collectedStats @@ -81,8 +107,14 @@ class InvertReportWriter( if (aggregateStatsSarifReportEnabled) { // Include all stats into one SARIF report. + // Derived TDI stats repeat findings of their source stats, so they are left out here. InvertSarifReportWriter(invertLogger, rootBuildReportsDir).createInvertSarifReport( - allProjectsStatsData = allProjectsStatsData + allProjectsStatsData = allProjectsStatsData.copy( + statInfos = allProjectsStatsData.statInfos - derivedStatKeys, + statsByModule = allProjectsStatsData.statsByModule.mapValues { (_, stats) -> + stats - derivedStatKeys + }, + ) ) } else { invertLogger.info("Skipping aggregate stats.sarif generation.") @@ -106,6 +138,7 @@ class InvertReportWriter( writeIndividualCodeReferenceStatFiles( reportDirectory = rootBuildReportsDir, aggregatedCollectedData = collectedData, + writeEvenIfEmptyStatKeys = derivedStatKeys, ) // Write TDI config if we have specified any via extension. @@ -152,9 +185,14 @@ class InvertReportWriter( } } + /** + * @param writeEvenIfEmptyStatKeys Stats to export even when they have no code references, so that + * a finished initiative reads as 0 rather than missing. + */ private fun writeIndividualCodeReferenceStatFiles( reportDirectory: File, aggregatedCollectedData: InvertCombinedCollectedData, + writeEvenIfEmptyStatKeys: Set, ) { val allStatMetadatas = aggregatedCollectedData.collectedStats.flatMap { it.statInfos.values }.distinct() @@ -195,7 +233,11 @@ class InvertReportWriter( } } } - if (allCodeReferencesForStatWithProjectPathExtra.isNotEmpty()) { + val isCodeReferencesStat = statMetadata.dataType == StatDataType.CODE_REFERENCES + if ( + allCodeReferencesForStatWithProjectPathExtra.isNotEmpty() || + (isCodeReferencesStat && statKey in writeEvenIfEmptyStatKeys) + ) { InvertJsonReportWriter.writeJsonFile( description = "All CodeReferences for ${statMetadata.key}", jsonOutputFile = InvertFileUtils.outputFile( diff --git a/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt new file mode 100644 index 00000000..b7fa4f3e --- /dev/null +++ b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt @@ -0,0 +1,155 @@ +package com.squareup.invert.internal.report + +import com.squareup.invert.internal.models.InvertCombinedCollectedData +import com.squareup.invert.logging.InvertLogger +import com.squareup.invert.models.Stat +import com.squareup.invert.models.StatFilter +import com.squareup.invert.models.StatKey +import com.squareup.invert.models.StatMetadata +import com.squareup.invert.models.js.TechDebtInitiative +import com.squareup.invert.models.js.TechDebtInitiative.StatRole +import com.squareup.invert.models.utils.StatFilters + +/** + * Publishes the filtered stats of [TechDebtInitiative]s ([TechDebtInitiative.remainingFilter] and + * [TechDebtInitiative.completedFilter]) as derived stats. + * + * A derived stat is added to every module that has its source stat, so it flows through totals, + * history, the web report and the per-stat exports exactly like a collected stat. + */ +internal object TechDebtInitiativeStats { + + /** [StatMetadata.category] of derived stats. */ + const val CATEGORY = "Tech Debt Initiatives" + + class Result( + val collectedData: InvertCombinedCollectedData, + /** Keys of the derived stats that were added. */ + val derivedStatKeys: Set, + ) + + private class DerivedStat( + val tdi: TechDebtInitiative, + val role: StatRole, + val sourceStatKey: StatKey, + val filter: StatFilter, + ) { + val key: StatKey = TechDebtInitiative.derivedStatKey(tdi.id, role) + } + + /** + * @throws IllegalArgumentException if any filter is invalid, listing every problem found. + */ + fun addDerivedStats( + collectedData: InvertCombinedCollectedData, + techDebtInitiatives: List, + logger: InvertLogger, + ): Result { + val errors = mutableListOf() + val derivedStats = techDebtInitiatives.flatMap { tdi -> + listOfNotNull( + tdi.remainingFilter?.let { DerivedStat(tdi, StatRole.REMAINING, tdi.remainingStatKey, it) }, + tdi.completedFilter?.let { filter -> + val completedStatKey = tdi.completedStatKey + if (completedStatKey == null) { + errors.add("TDI '${tdi.id}' has a completedFilter but no completedStatKey.") + null + } else { + DerivedStat(tdi, StatRole.COMPLETED, completedStatKey, filter) + } + }, + ) + } + if (derivedStats.isEmpty()) { + throwIfAny(errors) + return Result(collectedData, emptySet()) + } + + val collectedStatInfos: Map = collectedData.collectedStats + .flatMap { it.statInfos.values } + .associateBy { it.key } + + derivedStats.groupBy { it.key }.filterValues { it.size > 1 }.forEach { (key, duplicates) -> + errors.add( + "Derived stat key '$key' is produced more than once " + + "(TDI ids: ${duplicates.joinToString { it.tdi.id }}). TDI ids must be unique." + ) + } + + val derivedMetadataByKey = mutableMapOf() + val transformsBySourceKey = mutableMapOf Stat>>>() + derivedStats.distinctBy { it.key }.forEach { derivedStat -> + val tdiId = derivedStat.tdi.id + val roleName = derivedStat.role.keySuffix + if (derivedStat.key in collectedStatInfos) { + errors.add( + "TDI '$tdiId' derived stat key '${derivedStat.key}' is already used by a collected stat." + ) + return@forEach + } + val sourceMetadata = collectedStatInfos[derivedStat.sourceStatKey] + if (sourceMetadata == null) { + logger.warn( + "TDI '$tdiId': $roleName stat '${derivedStat.sourceStatKey}' was not collected, " + + "so derived stat '${derivedStat.key}' was not created." + ) + return@forEach + } + val filterErrors = StatFilters.validate(derivedStat.filter, sourceMetadata) + if (filterErrors.isNotEmpty()) { + errors.addAll(filterErrors.map { "TDI '$tdiId' ${roleName}Filter: $it" }) + return@forEach + } + + val derivedMetadata = sourceMetadata.copy( + key = derivedStat.key, + title = "${derivedStat.tdi.title} (${derivedStat.role.displayName})", + description = buildString { + append(sourceMetadata.description) + append("\n\nFiltered from `${derivedStat.sourceStatKey}` for Tech Debt Initiative ") + append("`$tdiId` (${derivedStat.role.displayName}).") + }, + category = CATEGORY, + ) + derivedMetadataByKey[derivedStat.key] = derivedMetadata + transformsBySourceKey.getOrPut(derivedStat.sourceStatKey) { mutableListOf() } + .add(derivedMetadata to StatFilters.transform(derivedStat.filter)) + } + + throwIfAny(errors) + + val updatedCollectedStats = collectedData.collectedStats.map { project -> + val addedStatInfos = project.statInfos.keys + .flatMap { sourceKey -> transformsBySourceKey[sourceKey].orEmpty() } + .associate { (derivedMetadata, _) -> derivedMetadata.key to derivedMetadata } + val addedStats = project.stats.entries.flatMap { (sourceKey, stat) -> + transformsBySourceKey[sourceKey].orEmpty().map { (derivedMetadata, transform) -> + derivedMetadata.key to transform(stat) + } + }.toMap() + if (addedStatInfos.isEmpty() && addedStats.isEmpty()) { + project + } else { + project.copy( + statInfos = project.statInfos + addedStatInfos, + stats = project.stats + addedStats, + ) + } + }.toSet() + + logger.info( + "Added ${derivedMetadataByKey.size} derived Tech Debt Initiative stat(s): " + + derivedMetadataByKey.keys.sorted().joinToString() + ) + return Result( + collectedData = collectedData.copy(collectedStats = updatedCollectedStats), + derivedStatKeys = derivedMetadataByKey.keys, + ) + } + + private fun throwIfAny(errors: List) { + require(errors.isEmpty()) { + "Invalid Tech Debt Initiative filters:\n" + errors.joinToString("\n") { " - $it" } + } + } +} diff --git a/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/tasks/InvertTask.kt b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/tasks/InvertTask.kt index 1cb05ced..c1a18a0e 100644 --- a/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/tasks/InvertTask.kt +++ b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/tasks/InvertTask.kt @@ -20,6 +20,7 @@ import com.squareup.invert.logging.GradleInvertLogger import com.squareup.invert.logging.InvertLogger import com.squareup.invert.models.ExtraDataType import com.squareup.invert.models.ExtraMetadata +import com.squareup.invert.models.InvertSerialization import com.squareup.invert.models.ModulePath import com.squareup.invert.models.OwnerName import com.squareup.invert.models.Stat @@ -63,6 +64,10 @@ abstract class InvertTask : DefaultTask() { @get:Internal abstract var techDebtInitiatives: List? + /** [techDebtInitiatives] as JSON, so that changing an initiative (or its filters) reruns the task. */ + @get:Input + abstract val techDebtInitiativesJson: Property + @get:Internal abstract var ownershipCollector: InvertOwnershipCollector? @@ -184,6 +189,12 @@ abstract class InvertTask : DefaultTask() { this.historicalDataFileProperty.set(extension.getHistoricalDataFilePath()) this.statCollectors = extension.getStatCollectors().toList() this.techDebtInitiatives = extension.getTechDebtInitiatives().toList() + this.techDebtInitiativesJson.set( + InvertSerialization.InvertJson.encodeToString( + ListSerializer(TechDebtInitiative.serializer()), + this.techDebtInitiatives.orEmpty(), + ) + ) this.ownershipCollector = extension.getOwnershipCollector() this.aggregateStatsSarifReportEnabled.set(extension.isAggregateStatsSarifReportEnabled()) diff --git a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt new file mode 100644 index 00000000..8bf64e3f --- /dev/null +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt @@ -0,0 +1,291 @@ +package com.squareup.invert.internal.report + +import com.squareup.invert.internal.AggregatedCodeReferences +import com.squareup.invert.internal.models.CollectedOwnershipForProject +import com.squareup.invert.internal.models.CollectedStatsForProject +import com.squareup.invert.internal.models.InvertCombinedCollectedData +import com.squareup.invert.logging.InvertLogger +import com.squareup.invert.models.ExtraDataType +import com.squareup.invert.models.ExtraMetadata +import com.squareup.invert.models.InvertSerialization.InvertJson +import com.squareup.invert.models.Stat +import com.squareup.invert.models.Stat.CodeReferencesStat.CodeReference +import com.squareup.invert.models.StatDataType +import com.squareup.invert.models.StatFilter +import com.squareup.invert.models.StatMetadata +import com.squareup.invert.models.ValueMatcher +import com.squareup.invert.models.js.AllOwners +import com.squareup.invert.models.js.BuildSystem +import com.squareup.invert.models.js.CollectedStatTotalsJsReportModel +import com.squareup.invert.models.js.MetadataJsReportModel +import com.squareup.invert.models.js.TechDebtInitiative +import com.squareup.invert.models.js.TechDebtInitiativeConfig +import java.io.File +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class TechDebtInitiativeStatsTest { + + private lateinit var testDir: File + private val warnings = mutableListOf() + private val logger = object : InvertLogger { + override fun lifecycle(message: String) {} + override fun info(message: String) {} + override fun warn(message: String) { + warnings.add(message) + } + } + + private val screensMetadata = StatMetadata( + key = "legacy_screens", + description = "Legacy Screens", + dataType = StatDataType.CODE_REFERENCES, + category = "Screens", + extras = listOf(ExtraMetadata(key = "kind", type = ExtraDataType.STRING, description = "Kind")), + ) + + private val testCountMetadata = StatMetadata( + key = "test_count", + description = "Test Count", + dataType = StatDataType.NUMERIC, + ) + + private val dialogsTdi = TechDebtInitiative( + id = "legacy_dialogs", + title = "Legacy Dialogs", + descriptionMarkdown = "Remove legacy dialogs", + unit = "Screens", + completedStatKey = null, + remainingStatKey = screensMetadata.key, + remainingFilter = StatFilter(extras = mapOf("kind" to ValueMatcher.equalTo("dialog"))), + ) + + private val derivedKey = "tdi__legacy_dialogs__remaining" + + @BeforeTest + fun setup() { + testDir = File("build/test-reports/tdi-stats-test-${System.nanoTime()}") + testDir.mkdirs() + } + + @AfterTest + fun cleanup() { + testDir.deleteRecursively() + } + + @Test + fun `derived stat holds only matching code references in each module`() { + val result = TechDebtInitiativeStats.addDerivedStats(collectedData(), listOf(dialogsTdi), logger) + + assertEquals(setOf(derivedKey), result.derivedStatKeys) + val byModule = result.collectedData.collectedStats.associateBy { it.path } + assertEquals( + listOf("app/A.kt"), + (byModule.getValue(":app").stats.getValue(derivedKey) as Stat.CodeReferencesStat).value.map { it.filePath }, + ) + assertEquals( + emptyList(), + (byModule.getValue(":lib").stats.getValue(derivedKey) as Stat.CodeReferencesStat).value, + "A module with the source stat but no matches keeps an empty derived stat", + ) + assertFalse(derivedKey in byModule.getValue(":none").stats, "No source stat, no derived stat") + + val derivedMetadata = byModule.getValue(":app").statInfos.getValue(derivedKey) + assertEquals(StatDataType.CODE_REFERENCES, derivedMetadata.dataType) + assertEquals("Legacy Dialogs (Remaining)", derivedMetadata.title) + assertEquals(TechDebtInitiativeStats.CATEGORY, derivedMetadata.category) + assertEquals(screensMetadata.extras, derivedMetadata.extras) + assertTrue(derivedMetadata.description.contains("`legacy_screens`")) + } + + @Test + fun `initiatives without filters add nothing`() { + val data = collectedData() + val result = TechDebtInitiativeStats.addDerivedStats( + data, + listOf(dialogsTdi.copy(remainingFilter = null)), + logger, + ) + assertEquals(emptySet(), result.derivedStatKeys) + assertEquals(data, result.collectedData) + } + + @Test + fun `derived numeric stat zeroes modules whose details do not match`() { + val tdi = dialogsTdi.copy( + id = "unit_tests", + remainingStatKey = testCountMetadata.key, + remainingFilter = StatFilter(details = ValueMatcher.equalTo("unit")), + ) + val result = TechDebtInitiativeStats.addDerivedStats(collectedData(), listOf(tdi), logger) + val byModule = result.collectedData.collectedStats.associateBy { it.path } + assertEquals(Stat.NumericStat(3, "unit"), byModule.getValue(":app").stats["tdi__unit_tests__remaining"]) + assertEquals(Stat.NumericStat(0, "ui"), byModule.getValue(":lib").stats["tdi__unit_tests__remaining"]) + } + + @Test + fun `invalid filters fail with every problem listed`() { + val error = assertFailsWith { + TechDebtInitiativeStats.addDerivedStats( + collectedData(), + listOf( + dialogsTdi.copy(remainingFilter = StatFilter(extras = mapOf("knid" to ValueMatcher.equalTo("dialog")))), + dialogsTdi.copy(id = "no_completed", completedFilter = dialogsTdi.remainingFilter), + ), + logger, + ) + } + val message = error.message.orEmpty() + assertTrue(message.contains("TDI 'legacy_dialogs' remainingFilter: Extra 'knid' is not declared"), message) + assertTrue(message.contains("TDI 'no_completed' has a completedFilter but no completedStatKey"), message) + } + + @Test + fun `duplicate initiative ids fail`() { + val error = assertFailsWith { + TechDebtInitiativeStats.addDerivedStats(collectedData(), listOf(dialogsTdi, dialogsTdi), logger) + } + assertTrue(error.message.orEmpty().contains("produced more than once"), error.message) + } + + @Test + fun `derived key used by a collected stat fails`() { + val data = collectedData(extraStats = mapOf(screensMetadata.copy(key = derivedKey) to Stat.CodeReferencesStat(emptyList()))) + val error = assertFailsWith { + TechDebtInitiativeStats.addDerivedStats(data, listOf(dialogsTdi), logger) + } + assertTrue(error.message.orEmpty().contains("already used by a collected stat"), error.message) + } + + @Test + fun `missing source stat warns and is skipped`() { + val result = TechDebtInitiativeStats.addDerivedStats( + collectedData(), + listOf(dialogsTdi.copy(remainingStatKey = "not_collected")), + logger, + ) + assertEquals(emptySet(), result.derivedStatKeys) + assertTrue(warnings.single().contains("'not_collected' was not collected"), warnings.toString()) + } + + @Test + fun `writeProjectData publishes totals, exports and effective keys for derived stats`() { + InvertReportWriter(logger, testDir).writeProjectData( + reportMetadata = metadata(), + collectedData = collectedData(), + historicalData = emptySet(), + techDebtInitiatives = listOf(dialogsTdi), + ) + + val totals = InvertJson.decodeFromString( + CollectedStatTotalsJsReportModel.serializer(), + File(testDir, "json/stat_totals.json").readText(), + ).statTotals + assertEquals(3, totals.getValue("legacy_screens").total) + assertEquals(1, totals.getValue(derivedKey).total) + assertEquals(mapOf("team1" to 1), totals.getValue(derivedKey).totalByOwner) + + val exported = InvertJson.decodeFromString( + AggregatedCodeReferences.serializer(), + File(testDir, "json/code_references_$derivedKey.json").readText(), + ) + assertEquals(listOf("app/A.kt"), exported.values.map { it.filePath }) + assertTrue(File(testDir, "sarif/code_references_$derivedKey.sarif").isFile) + + val aggregateSarif = testDir.walk().single { it.name == "stats.sarif" } + assertTrue(aggregateSarif.readText().contains("legacy_screens")) + assertFalse(aggregateSarif.readText().contains(derivedKey), "Derived stats repeat source findings") + + val tdiConfig = InvertJson.decodeFromString( + TechDebtInitiativeConfig.serializer(), + File(testDir, "json/tdi_config.json").readText(), + ) + assertEquals(derivedKey, tdiConfig.tdis.single().effectiveRemainingStatKey) + assertTrue(File(testDir, "json/tdi_config.json").readText().contains("\"effectiveRemainingStatKey\"")) + } + + @Test + fun `writeProjectData exports a derived stat with no matches`() { + val tdi = dialogsTdi.copy(remainingFilter = StatFilter(extras = mapOf("kind" to ValueMatcher.equalTo("none")))) + InvertReportWriter(logger, testDir).writeProjectData( + reportMetadata = metadata(), + collectedData = collectedData(), + historicalData = emptySet(), + techDebtInitiatives = listOf(tdi), + ) + + val totals = InvertJson.decodeFromString( + CollectedStatTotalsJsReportModel.serializer(), + File(testDir, "json/stat_totals.json").readText(), + ).statTotals + assertEquals(0, totals.getValue(derivedKey).total, "A finished initiative reads 0, not missing") + assertTrue(File(testDir, "json/code_references_$derivedKey.json").isFile) + assertTrue(File(testDir, "sarif/code_references_$derivedKey.sarif").isFile) + } + + private fun collectedData( + extraStats: Map = emptyMap(), + ): InvertCombinedCollectedData { + fun project(path: String, stats: Map) = CollectedStatsForProject( + path = path, + statInfos = stats.keys.associateBy { it.key }, + stats = stats.mapKeys { it.key.key }, + ) + return InvertCombinedCollectedData( + collectedConfigurations = emptySet(), + collectedDependencies = emptySet(), + collectedOwners = setOf( + CollectedOwnershipForProject(path = ":app", ownerName = "team1"), + CollectedOwnershipForProject(path = ":lib", ownerName = "team2"), + ), + collectedStats = setOf( + project( + ":app", + mapOf( + screensMetadata to Stat.CodeReferencesStat( + listOf(reference("app/A.kt", "dialog"), reference("app/B.kt", "layout")) + ), + testCountMetadata to Stat.NumericStat(3, "unit"), + ) + extraStats, + ), + project( + ":lib", + mapOf( + screensMetadata to Stat.CodeReferencesStat(listOf(reference("lib/C.kt", null))), + testCountMetadata to Stat.NumericStat(5, "ui"), + ), + ), + project(":none", emptyMap()), + ), + collectedPlugins = emptySet(), + ) + } + + private fun reference(filePath: String, kind: String?) = CodeReference( + filePath = filePath, + startLine = 1, + endLine = 1, + extras = listOfNotNull(kind?.let { "kind" to it }).toMap(), + ) + + private fun metadata() = MetadataJsReportModel( + artifactRepositories = emptyList(), + branchName = "main", + buildSystem = BuildSystem.GRADLE, + currentTime = 0, + currentTimeFormatted = "", + latestCommitGitSha = "abc123", + latestCommitTime = 0, + latestCommitTimeFormatted = "", + tagName = null, + timezoneId = "UTC", + remoteRepoGit = "git@github.com:test/test.git", + remoteRepoUrl = "https://github.com/test/test", + owners = AllOwners(ownerToDetails = emptyMap()), + ) +} diff --git a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/StatFiltersTest.kt b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/StatFiltersTest.kt new file mode 100644 index 00000000..829402ac --- /dev/null +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/StatFiltersTest.kt @@ -0,0 +1,153 @@ +package com.squareup.invert.models + +import com.squareup.invert.models.Stat.CodeReferencesStat.CodeReference +import com.squareup.invert.models.utils.StatFilters +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class StatFiltersTest { + + private val codeReferencesMetadata = StatMetadata( + key = "legacy_screens", + description = "Legacy Screens", + dataType = StatDataType.CODE_REFERENCES, + extras = listOf( + ExtraMetadata(key = "kind", type = ExtraDataType.STRING, description = "Kind"), + ExtraMetadata(key = "gated", type = ExtraDataType.BOOLEAN, description = "Gated"), + ), + ) + + private val numericMetadata = StatMetadata( + key = "test_count", + description = "Test Count", + dataType = StatDataType.NUMERIC, + ) + + @Test + fun `ONE_OF matches any listed value and never a missing value`() { + val matches = StatFilters.predicate(ValueMatcher.oneOf("dialog", "card")) + assertTrue(matches("dialog")) + assertTrue(matches("card")) + assertFalse(matches("layout")) + assertFalse(matches(null)) + } + + @Test + fun `REGEX finds a match anywhere unless anchored`() { + assertTrue(StatFilters.predicate(ValueMatcher.regex("Dialog"))("LegacyDialogScreen")) + assertFalse(StatFilters.predicate(ValueMatcher.regex("^Dialog$"))("LegacyDialogScreen")) + assertTrue(StatFilters.predicate(ValueMatcher.regex("^x", "Screen$"))("LegacyDialogScreen")) + assertFalse(StatFilters.predicate(ValueMatcher.regex("Dialog"))(null)) + } + + @Test + fun `PRESENT matches any value, including empty`() { + val matches = StatFilters.predicate(ValueMatcher.present()) + assertTrue(matches("")) + assertTrue(matches("anything")) + assertFalse(matches(null)) + } + + @Test + fun `negate inverts the result, so a missing value matches`() { + val matches = StatFilters.predicate(ValueMatcher.equalTo("dialog").negated()) + assertFalse(matches("dialog")) + assertTrue(matches("layout")) + assertTrue(matches(null)) + assertFalse(StatFilters.predicate(ValueMatcher.present().negated())("x")) + } + + @Test + fun `transform keeps only code references whose extras all match`() { + val references = listOf( + reference("a.kt", "kind" to "dialog", "gated" to "true"), + reference("b.kt", "kind" to "dialog", "gated" to "false"), + reference("c.kt", "kind" to "layout", "gated" to "true"), + reference("d.kt"), + ) + val filter = StatFilter( + extras = mapOf( + "kind" to ValueMatcher.equalTo("dialog"), + "gated" to ValueMatcher.equalTo("true"), + ), + ) + + val result = StatFilters.transform(filter)(Stat.CodeReferencesStat(references)) + + assertEquals(listOf("a.kt"), (result as Stat.CodeReferencesStat).value.map { it.filePath }) + } + + @Test + fun `transform zeroes basic stats whose details do not match`() { + val transform = StatFilters.transform(StatFilter(details = ValueMatcher.regex("^unit"))) + + assertEquals(Stat.NumericStat(5, "unit tests"), transform(Stat.NumericStat(5, "unit tests"))) + assertEquals(Stat.NumericStat(0, "ui tests"), transform(Stat.NumericStat(7, "ui tests"))) + assertEquals(Stat.NumericStat(0, null), transform(Stat.NumericStat(7, null))) + assertEquals(Stat.BooleanStat(false, "ui"), transform(Stat.BooleanStat(true, "ui"))) + assertEquals(Stat.BooleanStat(true, "unit"), transform(Stat.BooleanStat(true, "unit"))) + } + + @Test + fun `validate accepts a filter on declared extras`() { + val filter = StatFilter(extras = mapOf("kind" to ValueMatcher.equalTo("dialog"))) + assertEquals(emptyList(), StatFilters.validate(filter, codeReferencesMetadata)) + } + + @Test + fun `validate rejects extras that the stat does not declare`() { + val filter = StatFilter(extras = mapOf("knid" to ValueMatcher.equalTo("dialog"))) + val errors = StatFilters.validate(filter, codeReferencesMetadata) + assertEquals(1, errors.size) + assertTrue(errors.single().contains("'knid' is not declared"), errors.single()) + assertTrue(errors.single().contains("gated, kind"), errors.single()) + } + + @Test + fun `validate rejects conditions that do not apply to the stat type`() { + assertEquals( + 2, + StatFilters.validate(StatFilter(details = ValueMatcher.present()), codeReferencesMetadata).size, + "details on code references, and no extras", + ) + assertEquals( + 2, + StatFilters.validate( + StatFilter(extras = mapOf("kind" to ValueMatcher.present())), + numericMetadata, + ).size, + "extras on a numeric stat, and no details", + ) + assertTrue( + StatFilters.validate( + StatFilter(details = ValueMatcher.present()), + numericMetadata.copy(dataType = StatDataType.STRING), + ).single().contains("STRING") + ) + } + + @Test + fun `validate rejects empty and invalid matchers`() { + val errors = StatFilters.validate( + StatFilter( + extras = mapOf( + "kind" to ValueMatcher(MatchOp.ONE_OF), + "gated" to ValueMatcher.regex("(unclosed"), + ), + ), + codeReferencesMetadata, + ) + assertEquals(2, errors.size, errors.toString()) + assertTrue(errors.any { it.contains("ONE_OF needs at least one value") }) + assertTrue(errors.any { it.contains("Invalid regular expression '(unclosed'") }) + } + + private fun reference(filePath: String, vararg extras: Pair) = CodeReference( + filePath = filePath, + startLine = 1, + endLine = 1, + extras = extras.toMap(), + ) +} diff --git a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt new file mode 100644 index 00000000..75b27de6 --- /dev/null +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt @@ -0,0 +1,118 @@ +package com.squareup.invert.models + +import com.google.gson.Gson +import com.squareup.invert.models.InvertSerialization.InvertJson +import com.squareup.invert.models.js.TechDebtInitiative +import com.squareup.invert.models.js.TechDebtInitiativeConfig +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull + +class TechDebtInitiativeTest { + + private val unfiltered = TechDebtInitiative( + id = "kotlin", + title = "Migrate to Kotlin", + descriptionMarkdown = "", + unit = "Files", + completedStatKey = "kotlin_files", + remainingStatKey = "java_files", + ) + + private val filtered = unfiltered.copy( + id = "kotlin_payments", + remainingFilter = StatFilter(extras = mapOf("team" to ValueMatcher.oneOf("payments", "checkout"))), + completedFilter = StatFilter(extras = mapOf("team" to ValueMatcher.equalTo("payments").negated())), + ) + + @Test + fun `effective keys are the source keys without filters`() { + assertEquals("java_files", unfiltered.effectiveRemainingStatKey) + assertEquals("kotlin_files", unfiltered.effectiveCompletedStatKey) + } + + @Test + fun `effective keys are derived keys with filters`() { + assertEquals("tdi__kotlin_payments__remaining", filtered.effectiveRemainingStatKey) + assertEquals("tdi__kotlin_payments__completed", filtered.effectiveCompletedStatKey) + assertEquals( + "java_files", + filtered.copy(remainingFilter = null).effectiveRemainingStatKey, + "copy() recomputes the effective keys", + ) + } + + @Test + fun `effective completed key is null without a completed stat`() { + assertNull(filtered.copy(completedStatKey = null).effectiveCompletedStatKey) + } + + @Test + fun `tdi_config json includes effective keys and filter defaults`() { + val json = InvertJson.encodeToJsonElement( + TechDebtInitiativeConfig.serializer(), + TechDebtInitiativeConfig(listOf(unfiltered, filtered)), + ) + val (first, second) = json.jsonObject.getValue("tdis").jsonArray.map { it.jsonObject } + + assertEquals("java_files", first.getValue("effectiveRemainingStatKey").jsonPrimitive.content) + assertEquals("kotlin_files", first.getValue("effectiveCompletedStatKey").jsonPrimitive.content) + assertFalse("remainingFilter" in first, "No filter is written when there is none") + assertEquals( + "tdi__kotlin_payments__remaining", + second.getValue("effectiveRemainingStatKey").jsonPrimitive.content, + ) + val completedMatcher = second.getValue("completedFilter").jsonObject + .getValue("extras").jsonObject.getValue("team").jsonObject + assertEquals("true", completedMatcher.getValue("negate").jsonPrimitive.content) + val remainingFilter = second.getValue("remainingFilter").jsonObject + assertEquals( + "false", + remainingFilter.getValue("extras").jsonObject.getValue("team").jsonObject + .getValue("negate").jsonPrimitive.content, + "Defaults are written, so readers that ignore Kotlin defaults see them", + ) + } + + @Test + fun `tdi_config json round trips`() { + val config = TechDebtInitiativeConfig(listOf(unfiltered, filtered)) + val decoded = InvertJson.decodeFromString( + TechDebtInitiativeConfig.serializer(), + InvertJson.encodeToString(TechDebtInitiativeConfig.serializer(), config), + ) + assertEquals(config, decoded) + assertEquals(filtered.effectiveRemainingStatKey, decoded.tdis[1].effectiveRemainingStatKey) + } + + @Test + fun `tdi_config json written before filters existed still decodes`() { + val decoded = InvertJson.decodeFromString( + TechDebtInitiativeConfig.serializer(), + """{"tdis":[{"id":"kotlin","title":"Migrate to Kotlin","descriptionMarkdown":"","unit":"Files",""" + + """"completedStatKey":"kotlin_files","remainingStatKey":"java_files"}]}""", + ) + assertEquals(unfiltered, decoded.tdis.single()) + assertEquals("java_files", decoded.tdis.single().effectiveRemainingStatKey) + } + + @Test + fun `tdi_config json can be read with Gson`() { + // Some consumers read tdi_config.json with Gson, which cannot create interfaces and ignores + // Kotlin default values. + val json = InvertJson.encodeToString( + TechDebtInitiativeConfig.serializer(), + TechDebtInitiativeConfig(listOf(unfiltered, filtered)), + ) + + val decoded = Gson().fromJson(json, TechDebtInitiativeConfig::class.java) + + assertEquals(listOf(unfiltered, filtered), decoded.tdis) + assertEquals("tdi__kotlin_payments__remaining", decoded.tdis[1].effectiveRemainingStatKey) + assertEquals("kotlin_files", decoded.tdis[0].effectiveCompletedStatKey) + } +} diff --git a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt new file mode 100644 index 00000000..43b5ab75 --- /dev/null +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt @@ -0,0 +1,82 @@ +package com.squareup.invert.models + +import kotlinx.serialization.EncodeDefault +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.Serializable + +/** + * Selects part of a [Stat], so that a [com.squareup.invert.models.js.TechDebtInitiative] can track + * a subset of an existing stat. + * + * Every condition that is set must match. + * + * These classes use only concrete types and always encode their non-null defaults, so that + * consumers which read `tdi_config.json` with Gson (which cannot create interfaces and ignores + * Kotlin default values) can parse them. + */ +@OptIn(ExperimentalSerializationApi::class) +@Serializable +data class StatFilter( + /** + * [StatDataType.CODE_REFERENCES] stats only. Each entry must match the code reference's + * [Stat.CodeReferencesStat.CodeReference.extras] value for that key. Every key must be declared + * in the stat's [StatMetadata.extras]. + */ + @EncodeDefault + val extras: Map = emptyMap(), + /** + * [StatDataType.NUMERIC] and [StatDataType.BOOLEAN] stats only. Matches the stat's `details`. + * + * These stats hold one value per module, so a module whose `details` do not match contributes + * `0` (or `false`) instead of its value. + */ + val details: ValueMatcher? = null, +) + +/** + * How a [ValueMatcher] compares a value. + */ +enum class MatchOp { + /** Matches when the value equals any of [ValueMatcher.values]. */ + ONE_OF, + + /** + * Matches when any of [ValueMatcher.values], read as a regular expression, is found anywhere in + * the value. Anchor the pattern with `^` and `$` to match the whole value. + */ + REGEX, + + /** Matches when the value is present, whatever it is. [ValueMatcher.values] is ignored. */ + PRESENT, +} + +/** + * Matches a single, possibly missing, [String] value. + * + * A missing value never matches [MatchOp.ONE_OF] or [MatchOp.REGEX]. With [negate], a missing + * value therefore matches: "not one of X" includes items that have no value at all. + */ +@OptIn(ExperimentalSerializationApi::class) +@Serializable +data class ValueMatcher( + val op: MatchOp, + @EncodeDefault + val values: List = emptyList(), + /** Inverts the result. */ + @EncodeDefault + val negate: Boolean = false, +) { + + /** A copy of this matcher with the result inverted. */ + fun negated(): ValueMatcher = copy(negate = !negate) + + companion object { + fun equalTo(value: String): ValueMatcher = ValueMatcher(MatchOp.ONE_OF, listOf(value)) + + fun oneOf(vararg values: String): ValueMatcher = ValueMatcher(MatchOp.ONE_OF, values.toList()) + + fun regex(vararg patterns: String): ValueMatcher = ValueMatcher(MatchOp.REGEX, patterns.toList()) + + fun present(): ValueMatcher = ValueMatcher(MatchOp.PRESENT) + } +} diff --git a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt index 30371907..31b3db22 100644 --- a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt @@ -1,6 +1,9 @@ package com.squareup.invert.models.js +import com.squareup.invert.models.StatFilter import com.squareup.invert.models.StatKey +import kotlinx.serialization.EncodeDefault +import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable /** @@ -11,7 +14,16 @@ import kotlinx.serialization.Serializable * * 1. Pure Burndown: in which case only [remainingStatKey] is specified. * 2. % Completion: in which case a [completedStatKey] and [remainingStatKey] are specified. + * + * Either stat can be narrowed with a [StatFilter] ([remainingFilter], [completedFilter]). The + * filtered result is published at build time as a derived stat, under [effectiveRemainingStatKey] + * and [effectiveCompletedStatKey], so that it gets totals, history and exports like any other + * stat. Read the effective keys to show or export an initiative's numbers. + * + * A derived stat's history is keyed by [id]. If you change what a filter selects, also change + * [id], so the old and new definitions do not share one history. */ +@OptIn(ExperimentalSerializationApi::class) @Serializable data class TechDebtInitiative( /** Unique identifier for this initiative, should remain constant for deep-linking **/ @@ -27,9 +39,50 @@ data class TechDebtInitiative( val completedStatKey: StatKey?, /** The remaining code references of this TDI that need to be addressed. **/ val remainingStatKey: StatKey, -) + /** (Optional) Only count the part of [remainingStatKey] that matches this filter. **/ + val remainingFilter: StatFilter? = null, + /** (Optional) Only count the part of [completedStatKey] that matches this filter. **/ + val completedFilter: StatFilter? = null, +) { + /** + * The stat to read for this initiative's remaining work: [remainingStatKey], or the derived + * stat when [remainingFilter] is set. + * + * Computed from the other properties. It is written to `tdi_config.json` for consumers that + * cannot compute it, such as shell scripts. + */ + @EncodeDefault + val effectiveRemainingStatKey: StatKey = + if (remainingFilter == null) remainingStatKey else derivedStatKey(id, StatRole.REMAINING) + + /** + * The stat to read for this initiative's completed work: [completedStatKey], or the derived + * stat when [completedFilter] is set. `null` when there is no [completedStatKey]. + * + * Computed from the other properties, and written to `tdi_config.json` like + * [effectiveRemainingStatKey]. + */ + @EncodeDefault + val effectiveCompletedStatKey: StatKey? = completedStatKey?.let { completedStatKey -> + if (completedFilter == null) completedStatKey else derivedStatKey(id, StatRole.COMPLETED) + } + + /** Which of an initiative's two stats a key refers to. */ + enum class StatRole(val keySuffix: String, val displayName: String) { + REMAINING("remaining", "Remaining"), + COMPLETED("completed", "Completed"), + } + + companion object { + private const val DERIVED_STAT_KEY_PREFIX = "tdi__" + + /** The key of the derived stat for an initiative's filtered [role] stat. */ + fun derivedStatKey(id: String, role: StatRole): StatKey = + "$DERIVED_STAT_KEY_PREFIX${id}__${role.keySuffix}" + } +} @Serializable data class TechDebtInitiativeConfig( val tdis: List, -) \ No newline at end of file +) diff --git a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt new file mode 100644 index 00000000..cafdd0ae --- /dev/null +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt @@ -0,0 +1,124 @@ +package com.squareup.invert.models.utils + +import com.squareup.invert.models.MatchOp +import com.squareup.invert.models.Stat +import com.squareup.invert.models.StatDataType +import com.squareup.invert.models.StatFilter +import com.squareup.invert.models.StatMetadata +import com.squareup.invert.models.ValueMatcher + +/** + * Validation and evaluation of [StatFilter]s, shared by the build and the web report so that + * both apply the same rules. + */ +object StatFilters { + + /** + * Returns a description of every problem with applying [filter] to the stat described by + * [statMetadata], or an empty list if there are none. + */ + fun validate(filter: StatFilter, statMetadata: StatMetadata): List { + val errors = mutableListOf() + val statKey = statMetadata.key + when (statMetadata.dataType) { + StatDataType.CODE_REFERENCES -> { + if (filter.details != null) { + errors.add("'details' cannot filter '$statKey', a CODE_REFERENCES stat. Use 'extras'.") + } + if (filter.extras.isEmpty()) { + errors.add("The filter for '$statKey' has no 'extras' conditions.") + } + val declaredExtraKeys = statMetadata.extras.map { it.key }.toSet() + filter.extras.keys.filterNot { it in declaredExtraKeys }.forEach { extraKey -> + errors.add( + "Extra '$extraKey' is not declared by '$statKey'. " + + "Declared extras: ${declaredExtraKeys.sorted().ifEmpty { listOf("(none)") }.joinToString()}" + ) + } + } + + StatDataType.NUMERIC, + StatDataType.BOOLEAN -> { + if (filter.extras.isNotEmpty()) { + errors.add( + "'extras' cannot filter '$statKey', a ${statMetadata.dataType} stat. Use 'details'." + ) + } + if (filter.details == null) { + errors.add("The filter for '$statKey' has no 'details' condition.") + } + } + + StatDataType.STRING -> { + errors.add("'$statKey' is a STRING stat, which has no totals and cannot be filtered.") + } + } + + val matchers = filter.extras.map { (key, matcher) -> "extras[$key]" to matcher } + + listOfNotNull(filter.details?.let { "details" to it }) + matchers.forEach { (name, matcher) -> + errors.addAll(validate(matcher).map { "$name of the filter for '$statKey': $it" }) + } + return errors + } + + private fun validate(matcher: ValueMatcher): List = buildList { + when (matcher.op) { + MatchOp.ONE_OF -> if (matcher.values.isEmpty()) add("ONE_OF needs at least one value.") + MatchOp.REGEX -> { + if (matcher.values.isEmpty()) add("REGEX needs at least one pattern.") + matcher.values.forEach { pattern -> + try { + Regex(pattern) + } catch (e: Exception) { + add("Invalid regular expression '$pattern': ${e.message}") + } + } + } + + MatchOp.PRESENT -> Unit + } + } + + /** Builds a predicate for [matcher]. Regular expressions are compiled once, here. */ + fun predicate(matcher: ValueMatcher): (String?) -> Boolean { + val matches: (String) -> Boolean = when (matcher.op) { + MatchOp.ONE_OF -> matcher.values.toSet()::contains + MatchOp.REGEX -> { + val regexes = matcher.values.map(::Regex) + fun(value: String): Boolean = regexes.any { it.containsMatchIn(value) } + } + + MatchOp.PRESENT -> fun(_: String): Boolean = true + } + val negate = matcher.negate + return fun(value: String?): Boolean = (value != null && matches(value)) != negate + } + + /** + * Builds a function that applies [filter] to one module's [Stat]: + * + * - [Stat.CodeReferencesStat]: keeps only the code references whose extras match. + * - [Stat.NumericStat] / [Stat.BooleanStat]: keeps the stat if its details match, otherwise + * replaces its value with `0` / `false`, so the module still reports the stat. + * + * Call [validate] first. A [Stat.StringStat] is returned unchanged. + */ + fun transform(filter: StatFilter): (Stat) -> Stat { + val extrasPredicates = filter.extras.map { (key, matcher) -> key to predicate(matcher) } + val detailsPredicate = filter.details?.let { predicate(it) } ?: { true } + return { stat -> + when (stat) { + is Stat.CodeReferencesStat -> Stat.CodeReferencesStat( + stat.value.filter { codeReference -> + extrasPredicates.all { (key, matches) -> matches(codeReference.extras[key]) } + } + ) + + is Stat.NumericStat -> if (detailsPredicate(stat.details)) stat else stat.copy(value = 0) + is Stat.BooleanStat -> if (detailsPredicate(stat.details)) stat else stat.copy(value = false) + is Stat.StringStat -> stat + } + } + } +} From 10d929881899f2fdb07c1820cdab4dbb62ec1522 Mon Sep 17 00:00:00 2001 From: Eric Amorde Date: Mon, 9 Nov 2026 13:00:59 -0800 Subject: [PATCH 2/4] Drop the Gson compatibility test No consumer reads tdi_config.json into the Invert models with Gson, so the test and its test dependency are not needed. Defaults are still encoded for readers that are not written in Kotlin. Co-Authored-By: Claude Opus 5.5 --- gradle/libs.versions.toml | 1 - invert-gradle-plugin/build.gradle.kts | 2 -- .../invert/models/TechDebtInitiativeTest.kt | 17 ----------------- .../com/squareup/invert/models/StatFilter.kt | 5 ++--- 4 files changed, 2 insertions(+), 23 deletions(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index e26bff46..5b8802c1 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -27,7 +27,6 @@ detekt-sarif4k = { module = "io.github.detekt.sarif4k:sarif4k", version.ref = "s javax-inject = { module = "javax.inject:javax.inject", version.ref = "javax-inject" } kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" } -gson = { module = "com.google.code.gson:gson", version = "2.11.0" } kotlin-compiler-embeddable = { module = "org.jetbrains.kotlin:kotlin-compiler-embeddable", version.ref = "kotlin" } kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core", version.ref = "kotlinx-serialization" } diff --git a/invert-gradle-plugin/build.gradle.kts b/invert-gradle-plugin/build.gradle.kts index cb1be5b9..2cb10995 100644 --- a/invert-gradle-plugin/build.gradle.kts +++ b/invert-gradle-plugin/build.gradle.kts @@ -60,8 +60,6 @@ dependencies { } testImplementation(libs.kotlin.test) - // Consumers parse tdi_config.json with Gson; tests check the models stay compatible. - testImplementation(libs.gson) } kotlin { diff --git a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt index 75b27de6..8be47778 100644 --- a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt @@ -1,6 +1,5 @@ package com.squareup.invert.models -import com.google.gson.Gson import com.squareup.invert.models.InvertSerialization.InvertJson import com.squareup.invert.models.js.TechDebtInitiative import com.squareup.invert.models.js.TechDebtInitiativeConfig @@ -99,20 +98,4 @@ class TechDebtInitiativeTest { assertEquals(unfiltered, decoded.tdis.single()) assertEquals("java_files", decoded.tdis.single().effectiveRemainingStatKey) } - - @Test - fun `tdi_config json can be read with Gson`() { - // Some consumers read tdi_config.json with Gson, which cannot create interfaces and ignores - // Kotlin default values. - val json = InvertJson.encodeToString( - TechDebtInitiativeConfig.serializer(), - TechDebtInitiativeConfig(listOf(unfiltered, filtered)), - ) - - val decoded = Gson().fromJson(json, TechDebtInitiativeConfig::class.java) - - assertEquals(listOf(unfiltered, filtered), decoded.tdis) - assertEquals("tdi__kotlin_payments__remaining", decoded.tdis[1].effectiveRemainingStatKey) - assertEquals("kotlin_files", decoded.tdis[0].effectiveCompletedStatKey) - } } diff --git a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt index 43b5ab75..32d0292b 100644 --- a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt @@ -10,9 +10,8 @@ import kotlinx.serialization.Serializable * * Every condition that is set must match. * - * These classes use only concrete types and always encode their non-null defaults, so that - * consumers which read `tdi_config.json` with Gson (which cannot create interfaces and ignores - * Kotlin default values) can parse them. + * These classes always encode their non-null defaults, so that consumers of `tdi_config.json` + * that are not written in Kotlin see every field. */ @OptIn(ExperimentalSerializationApi::class) @Serializable From 15c39f4ee5d0d7be64a310343d5a6fa7dbe67fe2 Mon Sep 17 00:00:00 2001 From: Eric Amorde Date: Mon, 9 Nov 2026 13:58:14 -0800 Subject: [PATCH 3/4] Add StatFilter.key and limit filters to code references A filter can now set an explicit derived stat key, so its history can be versioned independently of the initiative id. Filters only apply to code references stats; the details condition for numeric and boolean stats is removed until that case has its own design. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- .../report/TechDebtInitiativeStats.kt | 5 +- .../report/TechDebtInitiativeStatsTest.kt | 60 +++++++++++++--- .../squareup/invert/models/StatFiltersTest.kt | 47 +++++------- .../invert/models/TechDebtInitiativeTest.kt | 17 +++++ .../com/squareup/invert/models/StatFilter.kt | 22 +++--- .../invert/models/js/TechDebtInitiative.kt | 22 +++--- .../invert/models/utils/StatFilters.kt | 71 +++++++------------ 8 files changed, 139 insertions(+), 109 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30e3896f..c103c50e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,9 @@ ## Unreleased -* Tech Debt Initiatives can count part of a stat. `TechDebtInitiative.remainingFilter` and `completedFilter` take a `StatFilter`: `extras` conditions for code references, or a `details` condition for numeric and boolean stats. Each filtered stat is published at build time as a derived stat, `tdi____remaining` or `tdi____completed`, which gets totals, history, the web report and the per-stat JSON and SARIF exports like any other stat. It is left out of the aggregate `stats.sarif`. +* Tech Debt Initiatives can count part of a stat. `TechDebtInitiative.remainingFilter` and `completedFilter` take a `StatFilter` of `extras` conditions on a code references stat. Each filtered stat is published at build time as a derived stat, keyed by the filter's optional `key` or by default `tdi____remaining` or `tdi____completed`, which gets totals, history, the web report and the per-stat JSON and SARIF exports like any other stat. It is left out of the aggregate `stats.sarif`. History is kept by the derived key, so change `key` when a filter's definition changes. * `TechDebtInitiative.effectiveRemainingStatKey` and `effectiveCompletedStatKey` name the stat to read for an initiative (the derived stat when filtered), and are written to `tdi_config.json`. Consumers that show or export initiative numbers should read these instead of `remainingStatKey` and `completedStatKey`. -* Invalid filters fail the report: an extra that the stat does not declare, a condition that does not apply to the stat type, an empty or invalid matcher, a duplicate initiative id, or a derived key that a collected stat already uses. +* Invalid filters fail the report: a filter on a stat that is not a code references stat, an extra that the stat does not declare, an empty or invalid matcher, a blank `key`, a derived key produced more than once (duplicate initiative ids or filter keys), or a derived key that a collected stat already uses. * Changing `techDebtInitiatives` now reruns the `invert` task. ## Version 0.0.16 diff --git a/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt index b7fa4f3e..143a398d 100644 --- a/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt +++ b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt @@ -34,7 +34,7 @@ internal object TechDebtInitiativeStats { val sourceStatKey: StatKey, val filter: StatFilter, ) { - val key: StatKey = TechDebtInitiative.derivedStatKey(tdi.id, role) + val key: StatKey = filter.key ?: TechDebtInitiative.derivedStatKey(tdi.id, role) } /** @@ -72,7 +72,8 @@ internal object TechDebtInitiativeStats { derivedStats.groupBy { it.key }.filterValues { it.size > 1 }.forEach { (key, duplicates) -> errors.add( "Derived stat key '$key' is produced more than once " + - "(TDI ids: ${duplicates.joinToString { it.tdi.id }}). TDI ids must be unique." + "(TDI ids: ${duplicates.joinToString { it.tdi.id }}). " + + "TDI ids and StatFilter keys must be unique." ) } diff --git a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt index 8bf64e3f..db5ea418 100644 --- a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt @@ -116,16 +116,31 @@ class TechDebtInitiativeStatsTest { } @Test - fun `derived numeric stat zeroes modules whose details do not match`() { - val tdi = dialogsTdi.copy( - id = "unit_tests", - remainingStatKey = testCountMetadata.key, - remainingFilter = StatFilter(details = ValueMatcher.equalTo("unit")), - ) + fun `derived stat uses the filter key when set`() { + val versionedKey = "legacy_screens.kind_dialog.v2" + val tdi = dialogsTdi.copy(remainingFilter = dialogsTdi.remainingFilter!!.copy(key = versionedKey)) val result = TechDebtInitiativeStats.addDerivedStats(collectedData(), listOf(tdi), logger) - val byModule = result.collectedData.collectedStats.associateBy { it.path } - assertEquals(Stat.NumericStat(3, "unit"), byModule.getValue(":app").stats["tdi__unit_tests__remaining"]) - assertEquals(Stat.NumericStat(0, "ui"), byModule.getValue(":lib").stats["tdi__unit_tests__remaining"]) + + assertEquals(setOf(versionedKey), result.derivedStatKeys) + assertEquals(versionedKey, tdi.effectiveRemainingStatKey) + val app = result.collectedData.collectedStats.single { it.path == ":app" } + assertEquals( + listOf("app/A.kt"), + (app.stats.getValue(versionedKey) as Stat.CodeReferencesStat).value.map { it.filePath }, + ) + assertFalse(derivedKey in app.stats, "The default key is not used") + } + + @Test + fun `filter on a numeric stat fails`() { + val error = assertFailsWith { + TechDebtInitiativeStats.addDerivedStats( + collectedData(), + listOf(dialogsTdi.copy(remainingStatKey = testCountMetadata.key)), + logger, + ) + } + assertTrue(error.message.orEmpty().contains("'test_count' is a NUMERIC stat"), error.message) } @Test @@ -153,6 +168,33 @@ class TechDebtInitiativeStatsTest { assertTrue(error.message.orEmpty().contains("produced more than once"), error.message) } + @Test + fun `duplicate filter keys fail`() { + val filter = dialogsTdi.remainingFilter!!.copy(key = "dialogs.v1") + val error = assertFailsWith { + TechDebtInitiativeStats.addDerivedStats( + collectedData(), + listOf( + dialogsTdi.copy(remainingFilter = filter), + dialogsTdi.copy(id = "other_dialogs", remainingFilter = filter), + ), + logger, + ) + } + val message = error.message.orEmpty() + assertTrue(message.contains("'dialogs.v1' is produced more than once"), message) + assertTrue(message.contains("legacy_dialogs, other_dialogs"), message) + } + + @Test + fun `filter key used by a collected stat fails`() { + val tdi = dialogsTdi.copy(remainingFilter = dialogsTdi.remainingFilter!!.copy(key = screensMetadata.key)) + val error = assertFailsWith { + TechDebtInitiativeStats.addDerivedStats(collectedData(), listOf(tdi), logger) + } + assertTrue(error.message.orEmpty().contains("already used by a collected stat"), error.message) + } + @Test fun `derived key used by a collected stat fails`() { val data = collectedData(extraStats = mapOf(screensMetadata.copy(key = derivedKey) to Stat.CodeReferencesStat(emptyList()))) diff --git a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/StatFiltersTest.kt b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/StatFiltersTest.kt index 829402ac..d15a8b21 100644 --- a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/StatFiltersTest.kt +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/StatFiltersTest.kt @@ -79,17 +79,6 @@ class StatFiltersTest { assertEquals(listOf("a.kt"), (result as Stat.CodeReferencesStat).value.map { it.filePath }) } - @Test - fun `transform zeroes basic stats whose details do not match`() { - val transform = StatFilters.transform(StatFilter(details = ValueMatcher.regex("^unit"))) - - assertEquals(Stat.NumericStat(5, "unit tests"), transform(Stat.NumericStat(5, "unit tests"))) - assertEquals(Stat.NumericStat(0, "ui tests"), transform(Stat.NumericStat(7, "ui tests"))) - assertEquals(Stat.NumericStat(0, null), transform(Stat.NumericStat(7, null))) - assertEquals(Stat.BooleanStat(false, "ui"), transform(Stat.BooleanStat(true, "ui"))) - assertEquals(Stat.BooleanStat(true, "unit"), transform(Stat.BooleanStat(true, "unit"))) - } - @Test fun `validate accepts a filter on declared extras`() { val filter = StatFilter(extras = mapOf("kind" to ValueMatcher.equalTo("dialog"))) @@ -106,28 +95,28 @@ class StatFiltersTest { } @Test - fun `validate rejects conditions that do not apply to the stat type`() { - assertEquals( - 2, - StatFilters.validate(StatFilter(details = ValueMatcher.present()), codeReferencesMetadata).size, - "details on code references, and no extras", - ) - assertEquals( - 2, - StatFilters.validate( - StatFilter(extras = mapOf("kind" to ValueMatcher.present())), - numericMetadata, - ).size, - "extras on a numeric stat, and no details", - ) + fun `validate rejects stats that are not code references`() { + val filter = StatFilter(extras = mapOf("kind" to ValueMatcher.present())) + listOf(StatDataType.NUMERIC, StatDataType.BOOLEAN, StatDataType.STRING).forEach { dataType -> + val errors = StatFilters.validate(filter, numericMetadata.copy(dataType = dataType)) + assertEquals(1, errors.size, errors.toString()) + assertTrue(errors.single().contains("is a $dataType stat"), errors.single()) + } + } + + @Test + fun `validate rejects a filter without extras conditions`() { assertTrue( - StatFilters.validate( - StatFilter(details = ValueMatcher.present()), - numericMetadata.copy(dataType = StatDataType.STRING), - ).single().contains("STRING") + StatFilters.validate(StatFilter(), codeReferencesMetadata).single().contains("no 'extras' conditions") ) } + @Test + fun `validate rejects a blank key`() { + val filter = StatFilter(extras = mapOf("kind" to ValueMatcher.present()), key = " ") + assertTrue(StatFilters.validate(filter, codeReferencesMetadata).single().contains("blank 'key'")) + } + @Test fun `validate rejects empty and invalid matchers`() { val errors = StatFilters.validate( diff --git a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt index 8be47778..c7f20c68 100644 --- a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt @@ -45,6 +45,23 @@ class TechDebtInitiativeTest { ) } + @Test + fun `effective keys are filter keys when set`() { + val keyed = filtered.copy( + remainingFilter = filtered.remainingFilter!!.copy(key = "java_files.payments.v2"), + ) + assertEquals("java_files.payments.v2", keyed.effectiveRemainingStatKey) + assertEquals("tdi__kotlin_payments__completed", keyed.effectiveCompletedStatKey) + + val json = InvertJson.encodeToJsonElement(TechDebtInitiative.serializer(), keyed).jsonObject + assertEquals("java_files.payments.v2", json.getValue("effectiveRemainingStatKey").jsonPrimitive.content) + assertEquals( + "java_files.payments.v2", + json.getValue("remainingFilter").jsonObject.getValue("key").jsonPrimitive.content, + ) + assertFalse("key" in json.getValue("completedFilter").jsonObject, "No key is written when there is none") + } + @Test fun `effective completed key is null without a completed stat`() { assertNull(filtered.copy(completedStatKey = null).effectiveCompletedStatKey) diff --git a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt index 32d0292b..3b8c39dc 100644 --- a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt @@ -5,10 +5,8 @@ import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable /** - * Selects part of a [Stat], so that a [com.squareup.invert.models.js.TechDebtInitiative] can track - * a subset of an existing stat. - * - * Every condition that is set must match. + * Selects part of a [StatDataType.CODE_REFERENCES] stat by its code references' extras, so that a + * [com.squareup.invert.models.js.TechDebtInitiative] can track a subset of an existing stat. * * These classes always encode their non-null defaults, so that consumers of `tdi_config.json` * that are not written in Kotlin see every field. @@ -17,19 +15,21 @@ import kotlinx.serialization.Serializable @Serializable data class StatFilter( /** - * [StatDataType.CODE_REFERENCES] stats only. Each entry must match the code reference's - * [Stat.CodeReferencesStat.CodeReference.extras] value for that key. Every key must be declared - * in the stat's [StatMetadata.extras]. + * Conditions on a code reference's [Stat.CodeReferencesStat.CodeReference.extras], by extra key. + * A code reference is kept when all of them match. Every key must be declared in the stat's + * [StatMetadata.extras]. */ @EncodeDefault val extras: Map = emptyMap(), /** - * [StatDataType.NUMERIC] and [StatDataType.BOOLEAN] stats only. Matches the stat's `details`. + * (Optional) The key of the derived stat that holds the filtered result. Defaults to + * [com.squareup.invert.models.js.TechDebtInitiative.derivedStatKey]. * - * These stats hold one value per module, so a module whose `details` do not match contributes - * `0` (or `false`) instead of its value. + * History is kept by this key. Set it to version the definition independently of the + * initiative's id, and change it when you change what the filter selects, so that the old and + * new definitions do not share one history. */ - val details: ValueMatcher? = null, + val key: StatKey? = null, ) /** diff --git a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt index 31b3db22..105d7755 100644 --- a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt @@ -15,13 +15,15 @@ import kotlinx.serialization.Serializable * 1. Pure Burndown: in which case only [remainingStatKey] is specified. * 2. % Completion: in which case a [completedStatKey] and [remainingStatKey] are specified. * - * Either stat can be narrowed with a [StatFilter] ([remainingFilter], [completedFilter]). The - * filtered result is published at build time as a derived stat, under [effectiveRemainingStatKey] - * and [effectiveCompletedStatKey], so that it gets totals, history and exports like any other - * stat. Read the effective keys to show or export an initiative's numbers. + * Either stat, when it is a code references stat, can be narrowed with a [StatFilter] + * ([remainingFilter], [completedFilter]). The filtered result is published at build time as a + * derived stat, under [effectiveRemainingStatKey] and [effectiveCompletedStatKey], so that it gets + * totals, history and exports like any other stat. Read the effective keys to show or export an + * initiative's numbers. * - * A derived stat's history is keyed by [id]. If you change what a filter selects, also change - * [id], so the old and new definitions do not share one history. + * A derived stat's history is kept by its key: [StatFilter.key], or [derivedStatKey] of [id] when + * it is not set. If you change what a filter selects, also change that key, so the old and new + * definitions do not share one history. */ @OptIn(ExperimentalSerializationApi::class) @Serializable @@ -46,14 +48,14 @@ data class TechDebtInitiative( ) { /** * The stat to read for this initiative's remaining work: [remainingStatKey], or the derived - * stat when [remainingFilter] is set. + * stat when [remainingFilter] is set ([StatFilter.key], or [derivedStatKey] by default). * * Computed from the other properties. It is written to `tdi_config.json` for consumers that * cannot compute it, such as shell scripts. */ @EncodeDefault val effectiveRemainingStatKey: StatKey = - if (remainingFilter == null) remainingStatKey else derivedStatKey(id, StatRole.REMAINING) + remainingFilter?.let { it.key ?: derivedStatKey(id, StatRole.REMAINING) } ?: remainingStatKey /** * The stat to read for this initiative's completed work: [completedStatKey], or the derived @@ -64,7 +66,7 @@ data class TechDebtInitiative( */ @EncodeDefault val effectiveCompletedStatKey: StatKey? = completedStatKey?.let { completedStatKey -> - if (completedFilter == null) completedStatKey else derivedStatKey(id, StatRole.COMPLETED) + completedFilter?.let { it.key ?: derivedStatKey(id, StatRole.COMPLETED) } ?: completedStatKey } /** Which of an initiative's two stats a key refers to. */ @@ -76,7 +78,7 @@ data class TechDebtInitiative( companion object { private const val DERIVED_STAT_KEY_PREFIX = "tdi__" - /** The key of the derived stat for an initiative's filtered [role] stat. */ + /** The default key of the derived stat for an initiative's filtered [role] stat. */ fun derivedStatKey(id: String, role: StatRole): StatKey = "$DERIVED_STAT_KEY_PREFIX${id}__${role.keySuffix}" } diff --git a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt index cafdd0ae..97ae7a52 100644 --- a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt @@ -20,44 +20,28 @@ object StatFilters { fun validate(filter: StatFilter, statMetadata: StatMetadata): List { val errors = mutableListOf() val statKey = statMetadata.key - when (statMetadata.dataType) { - StatDataType.CODE_REFERENCES -> { - if (filter.details != null) { - errors.add("'details' cannot filter '$statKey', a CODE_REFERENCES stat. Use 'extras'.") - } - if (filter.extras.isEmpty()) { - errors.add("The filter for '$statKey' has no 'extras' conditions.") - } - val declaredExtraKeys = statMetadata.extras.map { it.key }.toSet() - filter.extras.keys.filterNot { it in declaredExtraKeys }.forEach { extraKey -> - errors.add( - "Extra '$extraKey' is not declared by '$statKey'. " + - "Declared extras: ${declaredExtraKeys.sorted().ifEmpty { listOf("(none)") }.joinToString()}" - ) - } - } - - StatDataType.NUMERIC, - StatDataType.BOOLEAN -> { - if (filter.extras.isNotEmpty()) { - errors.add( - "'extras' cannot filter '$statKey', a ${statMetadata.dataType} stat. Use 'details'." - ) - } - if (filter.details == null) { - errors.add("The filter for '$statKey' has no 'details' condition.") - } - } - - StatDataType.STRING -> { - errors.add("'$statKey' is a STRING stat, which has no totals and cannot be filtered.") + if (statMetadata.dataType != StatDataType.CODE_REFERENCES) { + errors.add( + "'$statKey' is a ${statMetadata.dataType} stat. Only CODE_REFERENCES stats can be filtered." + ) + } + if (filter.key?.isBlank() == true) { + errors.add("The filter for '$statKey' has a blank 'key'. Remove it to use the default key.") + } + if (filter.extras.isEmpty()) { + errors.add("The filter for '$statKey' has no 'extras' conditions.") + } + if (statMetadata.dataType == StatDataType.CODE_REFERENCES) { + val declaredExtraKeys = statMetadata.extras.map { it.key }.toSet() + filter.extras.keys.filterNot { it in declaredExtraKeys }.forEach { extraKey -> + errors.add( + "Extra '$extraKey' is not declared by '$statKey'. " + + "Declared extras: ${declaredExtraKeys.sorted().ifEmpty { listOf("(none)") }.joinToString()}" + ) } } - - val matchers = filter.extras.map { (key, matcher) -> "extras[$key]" to matcher } + - listOfNotNull(filter.details?.let { "details" to it }) - matchers.forEach { (name, matcher) -> - errors.addAll(validate(matcher).map { "$name of the filter for '$statKey': $it" }) + filter.extras.forEach { (extraKey, matcher) -> + errors.addAll(validate(matcher).map { "extras[$extraKey] of the filter for '$statKey': $it" }) } return errors } @@ -96,17 +80,14 @@ object StatFilters { } /** - * Builds a function that applies [filter] to one module's [Stat]: - * - * - [Stat.CodeReferencesStat]: keeps only the code references whose extras match. - * - [Stat.NumericStat] / [Stat.BooleanStat]: keeps the stat if its details match, otherwise - * replaces its value with `0` / `false`, so the module still reports the stat. + * Builds a function that applies [filter] to one module's [Stat.CodeReferencesStat], keeping + * only the code references whose extras all match. A module with no matches keeps an empty + * stat, so a finished initiative reads `0`. * - * Call [validate] first. A [Stat.StringStat] is returned unchanged. + * Call [validate] first. Other stat types are returned unchanged. */ fun transform(filter: StatFilter): (Stat) -> Stat { val extrasPredicates = filter.extras.map { (key, matcher) -> key to predicate(matcher) } - val detailsPredicate = filter.details?.let { predicate(it) } ?: { true } return { stat -> when (stat) { is Stat.CodeReferencesStat -> Stat.CodeReferencesStat( @@ -115,9 +96,7 @@ object StatFilters { } ) - is Stat.NumericStat -> if (detailsPredicate(stat.details)) stat else stat.copy(value = 0) - is Stat.BooleanStat -> if (detailsPredicate(stat.details)) stat else stat.copy(value = false) - is Stat.StringStat -> stat + else -> stat } } } From 50dae943de9e3be8bcc65387ad65769953f7c558 Mon Sep 17 00:00:00 2001 From: Eric Amorde Date: Mon, 9 Nov 2026 14:11:22 -0800 Subject: [PATCH 4/4] Keep the TechDebtInitiative constructor and validate filters on missing stats - Add @JvmOverloads so Java and Groovy callers keep the constructor without filters. - Report filter problems that do not depend on the source stat (blank key, empty extras, invalid matchers) even when the source stat was not collected. - Correct the StatFilters KDoc: only the build uses it, with JVM regex syntax. Co-Authored-By: Claude Opus 5.5 --- .../report/TechDebtInitiativeStats.kt | 7 ++++ .../report/TechDebtInitiativeStatsTest.kt | 19 +++++++++++ .../invert/models/TechDebtInitiativeTest.kt | 7 ++++ .../invert/models/js/TechDebtInitiative.kt | 3 +- .../invert/models/utils/StatFilters.kt | 32 +++++++++++++------ 5 files changed, 57 insertions(+), 11 deletions(-) diff --git a/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt index 143a398d..b8f94df9 100644 --- a/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt +++ b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt @@ -90,6 +90,13 @@ internal object TechDebtInitiativeStats { } val sourceMetadata = collectedStatInfos[derivedStat.sourceStatKey] if (sourceMetadata == null) { + // Still report the problems that do not depend on the source stat, so that a bad filter + // does not pass just because its source stat was not collected in this build. + val filterErrors = StatFilters.validate(derivedStat.filter, derivedStat.sourceStatKey) + if (filterErrors.isNotEmpty()) { + errors.addAll(filterErrors.map { "TDI '$tdiId' ${roleName}Filter: $it" }) + return@forEach + } logger.warn( "TDI '$tdiId': $roleName stat '${derivedStat.sourceStatKey}' was not collected, " + "so derived stat '${derivedStat.key}' was not created." diff --git a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt index db5ea418..60e7d0b3 100644 --- a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt @@ -215,6 +215,25 @@ class TechDebtInitiativeStatsTest { assertTrue(warnings.single().contains("'not_collected' was not collected"), warnings.toString()) } + @Test + fun `invalid filter on a missing source stat still fails`() { + val error = assertFailsWith { + TechDebtInitiativeStats.addDerivedStats( + collectedData(), + listOf( + dialogsTdi.copy( + remainingStatKey = "not_collected", + remainingFilter = StatFilter(extras = mapOf("kind" to ValueMatcher.regex("(unclosed")), key = ""), + ), + ), + logger, + ) + } + val message = error.message.orEmpty() + assertTrue(message.contains("blank 'key'"), message) + assertTrue(message.contains("Invalid regular expression '(unclosed'"), message) + } + @Test fun `writeProjectData publishes totals, exports and effective keys for derived stats`() { InvertReportWriter(logger, testDir).writeProjectData( diff --git a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt index c7f20c68..f7842c79 100644 --- a/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt @@ -62,6 +62,13 @@ class TechDebtInitiativeTest { assertFalse("key" in json.getValue("completedFilter").jsonObject, "No key is written when there is none") } + @Test + fun `the constructor without filters is still available to Java and Groovy`() { + val string = String::class.java + val constructor = TechDebtInitiative::class.java.getConstructor(string, string, string, string, string, string) + assertEquals(unfiltered, constructor.newInstance("kotlin", "Migrate to Kotlin", "", "Files", "kotlin_files", "java_files")) + } + @Test fun `effective completed key is null without a completed stat`() { assertNull(filtered.copy(completedStatKey = null).effectiveCompletedStatKey) diff --git a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt index 105d7755..fb557b2d 100644 --- a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/js/TechDebtInitiative.kt @@ -5,6 +5,7 @@ import com.squareup.invert.models.StatKey import kotlinx.serialization.EncodeDefault import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable +import kotlin.jvm.JvmOverloads /** * A special class of stats that represent tracking of Tech Debt in a repository, facilitating @@ -27,7 +28,7 @@ import kotlinx.serialization.Serializable */ @OptIn(ExperimentalSerializationApi::class) @Serializable -data class TechDebtInitiative( +data class TechDebtInitiative @JvmOverloads constructor( /** Unique identifier for this initiative, should remain constant for deep-linking **/ val id: String, /** Display title **/ diff --git a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt index 97ae7a52..200a2f3c 100644 --- a/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt @@ -4,12 +4,14 @@ import com.squareup.invert.models.MatchOp import com.squareup.invert.models.Stat import com.squareup.invert.models.StatDataType import com.squareup.invert.models.StatFilter +import com.squareup.invert.models.StatKey import com.squareup.invert.models.StatMetadata import com.squareup.invert.models.ValueMatcher /** - * Validation and evaluation of [StatFilter]s, shared by the build and the web report so that - * both apply the same rules. + * Validation and evaluation of [StatFilter]s. + * + * The build uses these on the JVM, so regular expressions follow JVM syntax. */ object StatFilters { @@ -24,14 +26,7 @@ object StatFilters { errors.add( "'$statKey' is a ${statMetadata.dataType} stat. Only CODE_REFERENCES stats can be filtered." ) - } - if (filter.key?.isBlank() == true) { - errors.add("The filter for '$statKey' has a blank 'key'. Remove it to use the default key.") - } - if (filter.extras.isEmpty()) { - errors.add("The filter for '$statKey' has no 'extras' conditions.") - } - if (statMetadata.dataType == StatDataType.CODE_REFERENCES) { + } else { val declaredExtraKeys = statMetadata.extras.map { it.key }.toSet() filter.extras.keys.filterNot { it in declaredExtraKeys }.forEach { extraKey -> errors.add( @@ -40,6 +35,23 @@ object StatFilters { ) } } + errors.addAll(validate(filter, statKey)) + return errors + } + + /** + * Returns a description of every problem with [filter] that does not depend on the stat it + * filters, or an empty list if there are none. Use this when that stat's metadata is not + * available. [statKey] names the stat in the messages. + */ + fun validate(filter: StatFilter, statKey: StatKey): List { + val errors = mutableListOf() + if (filter.key?.isBlank() == true) { + errors.add("The filter for '$statKey' has a blank 'key'. Remove it to use the default key.") + } + if (filter.extras.isEmpty()) { + errors.add("The filter for '$statKey' has no 'extras' conditions.") + } filter.extras.forEach { (extraKey, matcher) -> errors.addAll(validate(matcher).map { "extras[$extraKey] of the filter for '$statKey': $it" }) }