diff --git a/CHANGELOG.md b/CHANGELOG.md index 5281b748..c103c50e 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` 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: 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 * 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/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..b8f94df9 --- /dev/null +++ b/invert-gradle-plugin/src/main/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStats.kt @@ -0,0 +1,163 @@ +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 = filter.key ?: 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 and StatFilter keys 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) { + // 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." + ) + 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..60e7d0b3 --- /dev/null +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/internal/report/TechDebtInitiativeStatsTest.kt @@ -0,0 +1,352 @@ +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 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) + + 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 + 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 `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()))) + 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 `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( + 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..d15a8b21 --- /dev/null +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/StatFiltersTest.kt @@ -0,0 +1,142 @@ +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 `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 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(), 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( + 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..f7842c79 --- /dev/null +++ b/invert-gradle-plugin/src/test/kotlin/com/squareup/invert/models/TechDebtInitiativeTest.kt @@ -0,0 +1,125 @@ +package com.squareup.invert.models + +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 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 `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) + } + + @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) + } +} 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..3b8c39dc --- /dev/null +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/StatFilter.kt @@ -0,0 +1,81 @@ +package com.squareup.invert.models + +import kotlinx.serialization.EncodeDefault +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.Serializable + +/** + * 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. + */ +@OptIn(ExperimentalSerializationApi::class) +@Serializable +data class StatFilter( + /** + * 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(), + /** + * (Optional) The key of the derived stat that holds the filtered result. Defaults to + * [com.squareup.invert.models.js.TechDebtInitiative.derivedStatKey]. + * + * 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 key: StatKey? = 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..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 @@ -1,7 +1,11 @@ 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 +import kotlin.jvm.JvmOverloads /** * A special class of stats that represent tracking of Tech Debt in a repository, facilitating @@ -11,9 +15,20 @@ 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, 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 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 -data class TechDebtInitiative( +data class TechDebtInitiative @JvmOverloads constructor( /** Unique identifier for this initiative, should remain constant for deep-linking **/ val id: String, /** Display title **/ @@ -27,9 +42,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 ([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 = + remainingFilter?.let { it.key ?: derivedStatKey(id, StatRole.REMAINING) } ?: remainingStatKey + + /** + * 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 -> + completedFilter?.let { it.key ?: derivedStatKey(id, StatRole.COMPLETED) } ?: completedStatKey + } + + /** 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 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}" + } +} @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..200a2f3c --- /dev/null +++ b/invert-models/src/commonMain/kotlin/com/squareup/invert/models/utils/StatFilters.kt @@ -0,0 +1,115 @@ +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.StatKey +import com.squareup.invert.models.StatMetadata +import com.squareup.invert.models.ValueMatcher + +/** + * Validation and evaluation of [StatFilter]s. + * + * The build uses these on the JVM, so regular expressions follow JVM syntax. + */ +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 + if (statMetadata.dataType != StatDataType.CODE_REFERENCES) { + errors.add( + "'$statKey' is a ${statMetadata.dataType} stat. Only CODE_REFERENCES stats can be filtered." + ) + } else { + 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()}" + ) + } + } + 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" }) + } + 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.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. Other stat types are returned unchanged. + */ + fun transform(filter: StatFilter): (Stat) -> Stat { + val extrasPredicates = filter.extras.map { (key, matcher) -> key to predicate(matcher) } + return { stat -> + when (stat) { + is Stat.CodeReferencesStat -> Stat.CodeReferencesStat( + stat.value.filter { codeReference -> + extrasPredicates.all { (key, matches) -> matches(codeReference.extras[key]) } + } + ) + + else -> stat + } + } + } +}