Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.gradle.plugins.report

data class ReportCommit(val sha: String, val pr: Int)
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.gradle.plugins.report

data class TestReport(
val name: String,
val type: Type,
val status: Status,
val commit: String,
val url: String,
) {
enum class Type {
UNIT_TEST,
INSTRUMENTATION_TEST,
}

enum class Status {
SUCCESS,
FAILURE,
OTHER,
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.gradle.plugins.report

import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import java.io.FileWriter
import java.io.IOException
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import java.util.regex.Matcher
import java.util.regex.Pattern
import org.gradle.internal.Pair
import java.util.stream.Stream
import kotlin.streams.toList

@SuppressWarnings("NewApi")
class UnitTestReport(private val apiToken: String) {
private val client: HttpClient =
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build()

fun createReport(commitCount: Int) {
val response = request("commits?per_page=$commitCount", JsonArray::class.java)
val commits =
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned in the previous review, all the manipulation below would be unnecessary if the "search" method is used, rather than the "commit" method. Filter the data at request time, rather than after fetching it, and also the response object includes in separate fields the PR number, rather than using regex to try to extract it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I may understand this wrong, but GitHub's search endpoint exists primarily for text searching, and cannot output what we want, specifically, only merged PRs (not something that can be filtered) sorted by date of merge (many search options, none support this). I'll update the page size to only request what we need, but there is no filtering of commits here, every commit on the main branch is used.

Copy link
Collaborator

@rlazo rlazo Oct 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can filter by pr status in the search api with the query

repo:firebase/firebase-android-sdk is:pr is:merged

the actual issue, as you pointed out, is that sorting by merge date isn't supported (there's a feature request open since 2023 about it https://github.com/orgs/community/discussions/60876)

The next best thing we can do in this case is rely on graphql to fetch the data we need without us doing the parsing.

For example

    1 query {
    2   repository(owner: "firebase", name: "firebase-android-sdk") {
    3     ref(qualifiedName: "refs/heads/main") {
    4       target {
    5         ... on Commit {
    6           history(first: 20) {
    7             nodes {
    8               messageHeadline
    9               oid
   10               associatedPullRequests(first: 1) {
   11                 nodes {
   12                   number
   13                   title
   14                 }
   15               }
   16             }
   17           }
   18         }
   19       }
   20     }
   21   }
   22 }

will get us the commit and PR data in a single request without parsing. There's likely a way of crafting the query to get more of the data. The easiest way is using gemini to help you expand and explore the API if you are not familiar with graphql

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I need to push back here, even this graphql solution is going back to primarily indexing commits on main, which still presents the proposed problem of non-squashed commits causing issues, and, additionally, the associated pull requests solution is perhaps even less rigorous than our predictable string parsing, because it returns an arbitrary list of PRs that contain the commit SHA, which can be merged PRs with the change, draft PRs that got branched from, features on top of branches (like the existing branch based on this one to add the workflow). I'm just not convinced that this is a more durable and reasonable solution than the commit text parsing, which we already use for more critical infrastructure in our release generation. I think if we went with this we'd be creating real problems by solving niche or hypothetical ones.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have 2 concerns with the approach proposed in this PR:

a) It relies on commits as a proxy for pull requests, which are the actual data we need for test reporting
b) It relies on parsing free text to obtain critical information, the PR number

While I originally thought there was a way around (a), after investigating it further, as mentioned in my previous comment, it's simple not possible. Github does not provide a way of fetching PRs in the right order, and there's no guarantee that we could do the sorting client side unless we fetch a huge number of PRs. We need to use the commits.

As for (b), the concern about getting an "arbitrary list of PRs" appears to contradict the official documentation. Based on the API documentation, the solution proposed above is guaranteed to return:

"The merged Pull Request that introduced the commit to the repository. If the commit is not present in the default branch, additionally returns open Pull Requests associated with the commit."

This behaviour guarantees we only retrieve the merged PR, plus any currently open (draft/feature) PRs only if the commit is not yet present on the default branch. Since we only reference commits already present in the default branch, the documentation implies we should only get the merged PR.

I don't see how this leads to the arbitrary list of draft/branched PRs you described. Can you point to documentation or an example where this behaviour occurs for a commit already on main?

GraphQL has the added benefit of enabling complex queries that would otherwise require several REST request. This could reduce the amount of code we need to process the data, which is a net positive. That being said, I don't know how much further it can simplify our particular workflow.

Ultimately, parsing free text is inherently risky and IMO should be avoided if a structured API provides an alternative.

response
.stream()
.limit(commitCount.toLong())
.map { el: JsonElement ->
val obj = el as JsonObject
var pr = -1
val matcher: Matcher =
PR_NUMBER_MATCHER.matcher((obj["commit"] as JsonObject)["message"].toString())
if (matcher.find()) {
pr = matcher.group(1).toInt()
}
ReportCommit(obj["sha"].toString(), pr)
}
.toList()
outputReport(commits)
}

private fun outputReport(commits: List<ReportCommit>) {
val reports: MutableList<TestReport> = ArrayList()
for (commit in commits) {
reports.addAll(parseTestReports(commit.sha))
}
val output = StringBuilder()
output.append("### Unit Tests\n\n")
output.append(
generateTable(
commits,
reports.filter { r: TestReport -> r.type == TestReport.Type.UNIT_TEST },
)
)
output.append("\n")
output.append("### Instrumentation Tests\n\n")
output.append(
generateTable(
commits,
reports.filter { r: TestReport -> r.type == TestReport.Type.INSTRUMENTATION_TEST },
)
)
output.append("\n")

try {
val writer = FileWriter("test-report.md")
writer.append(output.toString())
writer.close()
} catch (e: Exception) {
throw RuntimeException("Error writing report file", e)
}
}

private fun generateTable(reportCommits: List<ReportCommit>, reports: List<TestReport>): String {
val commitLookup = reportCommits.associateBy(ReportCommit::sha)
val commits = reports.map(TestReport::commit).distinct()
var sdks = reports.map(TestReport::name).distinct().sorted()
val lookup = reports.associateBy({ report -> Pair.of(report.name, report.commit) })
val successPercentage: MutableMap<String, Int> = HashMap()
var passingSdks = 0
// Get success percentage
for (sdk in sdks) {
var sdkTestCount = 0
var sdkTestSuccess = 0
for (commit in commits) {
if (lookup.containsKey(Pair.of(sdk, commit))) {
val report: TestReport = lookup.get(Pair.of(sdk, commit))!!
if (report.status != TestReport.Status.OTHER) {
sdkTestCount++
if (report.status == TestReport.Status.SUCCESS) {
sdkTestSuccess++
}
}
}
}
if (sdkTestSuccess == sdkTestCount) {
passingSdks++
}
successPercentage.put(sdk, sdkTestSuccess * 100 / sdkTestCount)
}
sdks =
sdks
.filter { s: String? -> successPercentage[s] != 100 }
.sortedBy { o: String -> successPercentage[o]!! }
if (sdks.isEmpty()) {
return "*All tests passing*\n"
}
val output = StringBuilder("| |")
for (commit in commits) {
val rc = commitLookup.get(commit)
output.append(" ")
if (rc != null && rc.pr != -1) {
output.append("[#${rc.pr}](https://github.com/firebase/firebase-android-sdk/pull/${rc.pr})")
} else {
output.append(commit)
}
output.append(" |")
}
output.append(" Success Rate |\n|")
output.append(" :--- |")
output.append(" :---: |".repeat(commits.size))
output.append(" :--- |")
for (sdk in sdks) {
output.append("\n| ").append(sdk).append(" |")
for (commit in commits) {
if (lookup.containsKey(Pair.of(sdk, commit))) {
val report: TestReport = lookup[Pair.of(sdk, commit)]!!
val icon =
when (report.status) {
TestReport.Status.SUCCESS -> "✅"
TestReport.Status.FAILURE -> "⛔"
TestReport.Status.OTHER -> "➖"
}
val link: String = " [%s](%s)".format(icon, report.url)
output.append(link)
}
output.append(" |")
}
output.append(" ")
val successChance: Int = successPercentage.get(sdk)!!
if (successChance == 100) {
output.append("✅ 100%")
} else {
output.append("⛔ ").append(successChance).append("%")
}
output.append(" |")
}
output.append("\n")
if (passingSdks > 0) {
output.append("\n*+").append(passingSdks).append(" passing SDKs*\n")
}
return output.toString()
}

private fun parseTestReports(commit: String): List<TestReport> {
val runs = request("actions/runs?head_sha=" + commit)
for (el in runs["workflow_runs"] as JsonArray) {
val run = el as JsonObject
val name = run["name"].toString()
if (name == "CI Tests") {
return parseCITests(run["id"].toString(), commit)
}
}
return listOf()
}

private fun parseCITests(id: String, commit: String): List<TestReport> {
val reports: MutableList<TestReport> = ArrayList()
val jobs = request("actions/runs/" + id + "/jobs")
for (el in jobs["jobs"] as JsonArray) {
val job = el as JsonObject
val jid = job["name"].toString()
if (jid.startsWith("Unit Tests (:")) {
reports.add(parseJob(TestReport.Type.UNIT_TEST, job, commit))
} else if (jid.startsWith("Instrumentation Tests (:")) {
reports.add(parseJob(TestReport.Type.INSTRUMENTATION_TEST, job, commit))
}
}
return reports
}

private fun parseJob(type: TestReport.Type, job: JsonObject, commit: String): TestReport {
var name =
job["name"]
.toString()
.split("\\(:".toRegex())
.dropLastWhile { it.isEmpty() }
.toTypedArray()[1]
name = name.substring(0, name.length - 1) // Remove trailing ")"
var status = TestReport.Status.OTHER
if (job["status"].toString() == "completed") {
if (job["conclusion"].toString() == "success") {
status = TestReport.Status.SUCCESS
} else {
status = TestReport.Status.FAILURE
}
}
val url = job["html_url"].toString()
return TestReport(name, type, status, commit, url)
}

private fun request(path: String): JsonObject {
return request(path, JsonObject::class.java)
}

private fun <T> request(path: String, clazz: Class<T>): T {
return request(URI.create(URL_PREFIX + path), clazz)
}

/**
* Abstracts away paginated calling. Naively joins pages together by merging root level arrays.
*/
private fun <T> request(uri: URI, clazz: Class<T>): T {
val request =
HttpRequest.newBuilder()
.GET()
.uri(uri)
.header("Authorization", "Bearer $apiToken")
.header("X-GitHub-Api-Version", "2022-11-28")
.build()
try {
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
val body = response.body()
if (response.statusCode() >= 300) {
System.err.println(response)
System.err.println(body)
}
val json = when (clazz) {
JsonObject::class.java -> Json.decodeFromString<JsonObject>(body)
JsonArray::class.java -> Json.decodeFromString<JsonArray>(body)
else -> throw IllegalArgumentException()
}
if (json is JsonObject) {
// Retrieve and merge objects from other pages, if present
return response.headers().firstValue("Link").map { link: String ->
val parts = link.split(",".toRegex()).dropLastWhile { it.isEmpty() }
for (part in parts) {
if (part.endsWith("rel=\"next\"")) {
// <foo>; rel="next" -> foo
val url =
part
.split(">;".toRegex())
.dropLastWhile { it.isEmpty() }
.toTypedArray()[0]
.split("<".toRegex())
.dropLastWhile { it.isEmpty() }
.toTypedArray()[1]
val p = request<JsonObject>(URI.create(url), JsonObject::class.java)
return@map JsonObject(json.keys.associateWith {
key: String ->

if (json[key] is JsonArray && p.containsKey(key) && p[key] is JsonArray) {
JsonArray(Stream.concat((json[key] as JsonArray).stream(), (p[key] as JsonArray).stream()).toList())
}
json[key]!!
})
}
}
return@map json
}.orElse(json) as T
}
return json as T
} catch (e: IOException) {
throw RuntimeException(e)
} catch (e: InterruptedException) {
throw RuntimeException(e)
}
}

companion object {
/*
* Matches commit names for their PR number generated by GitHub, eg, `foo bar (#1234)`.
*/
private val PR_NUMBER_MATCHER: Pattern = Pattern.compile(".*\\(#([0-9]+)\\)")
private const val URL_PREFIX = "https://api.github.com/repos/firebase/firebase-android-sdk/"
}
}
Loading