Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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__<id>__remaining` or `tdi__<id>__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.
Expand Down
107 changes: 107 additions & 0 deletions examples/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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<com.squareup.invert.CollectedStat>? {
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(
Expand All @@ -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=<effectiveRemainingStatKey>&completed=<effectiveCompletedStatKey>`.
// 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(),
),
),
)
)
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -39,6 +41,30 @@ class InvertReportWriter(
historicalData: Set<HistoricalData>,
techDebtInitiatives: List<TechDebtInitiative>,
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<StatKey>,
historicalData: Set<HistoricalData>,
techDebtInitiatives: List<TechDebtInitiative>,
aggregateStatsSarifReportEnabled: Boolean,
) {
val collectedOwners: Set<CollectedOwnershipForProject> = collectedData.collectedOwners
val collectedStats: Set<CollectedStatsForProject> = collectedData.collectedStats
Expand Down Expand Up @@ -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.")
Expand All @@ -106,6 +138,7 @@ class InvertReportWriter(
writeIndividualCodeReferenceStatFiles(
reportDirectory = rootBuildReportsDir,
aggregatedCollectedData = collectedData,
writeEvenIfEmptyStatKeys = derivedStatKeys,
)

// Write TDI config if we have specified any via extension.
Expand Down Expand Up @@ -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<StatKey>,
) {
val allStatMetadatas =
aggregatedCollectedData.collectedStats.flatMap { it.statInfos.values }.distinct()
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
@@ -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<StatKey>,
)

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<TechDebtInitiative>,
logger: InvertLogger,
): Result {
val errors = mutableListOf<String>()
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<StatKey, StatMetadata> = 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<StatKey, StatMetadata>()
val transformsBySourceKey = mutableMapOf<StatKey, MutableList<Pair<StatMetadata, (Stat) -> 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<String>) {
require(errors.isEmpty()) {
"Invalid Tech Debt Initiative filters:\n" + errors.joinToString("\n") { " - $it" }
}
}
}
Loading
Loading