Unverified Commit 97715a29 authored by Daz DeBoer's avatar Daz DeBoer Committed by GitHub
Browse files

Redesign the caching Job Summary (#985)

Redesigns the caching section of the Job Summary into a single,
consistent layout across every cache provider and state, and integrates
the provider message into the report rather than appending it
disconnected at the bottom.

## Motivation

The caching report was produced by three divergent code paths (NoOp /
basic / enhanced), each rendering its own markdown:

- **Explicitly disabled** → a one-line message, no expand, no provider
note.
- **Enhanced** (incl. skipped-due-to-existing-home) → a full `<details>`
block.
- **Basic** → a one-line message with **no** expandable details at all.

The Enhanced/Basic provider note floated at the very bottom,
disconnected from the report.

## What changed

`save()` now returns structured `CacheReport` data instead of
pre-rendered HTML, and a single renderer (`caching-report.ts`) produces
one unified layout for all variants:

- **Section heading**: `#### <icon> Gradle Caching — <Provider>
(<status>)`
- **Status line** explaining what the cache did
- **Integrated provider note** woven in under the heading — now shown
**unconditionally** (no longer gated on license acceptance)
- **Expandable cache-entry details** when there are entries — basic
caching now gets this too

The two disabled variants (explicitly disabled, and skipped due to a
pre-existing Gradle User Home) render as **compact callouts with no
expandable section**.

### Main repo
- `caching-report.ts` (new): central renderer + all framing copy + entry
table/`<pre>` helpers.
- `cache-service.ts`: `CacheReport` / `CacheEntryReport` / status types;
`save()` returns `CacheReport`.
- `cache-service-loader.ts`: `NoOp` returns a report;
`LicenseWarningCacheService` removed; new `getProviderNote()`.
- `cache-service-basic.ts`: builds a `CacheReport`.
- `job-summary.ts` / `setup-gradle.ts`: thread `CacheReport` +
`ProviderNote`.
- `configuration.ts`: remove now-unused `isCacheLicenseAccepted()`.

### Vendored library
The structured contract requires **gradle-actions-caching v0.7.0**
(gradle/actions-caching#74). This PR updates the vendored library to
that release — the official `Update gradle-actions-caching library to
v0.7.0` vendor commit is included here, so merging this PR ships the
redesign together with the library it depends on.

## Testing

- Both repos build; prettier + eslint clean.
- `gradle/actions`: 363/363 Jest tests pass, including new
`caching-report.test.ts` covering every variant.
- `gradle-actions-caching`: 74/74 pass under JDK 17.
- Rendered markdown verified for all five variants (enhanced/basic
enabled & read-only, disabled, skipped).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: default avatarBot Githubaction <[email protected]>
Co-authored-by: default avatarClaude Opus 4.8 (1M context) <[email protected]>
parent 8b6cdb5f
Loading
Loading
Loading
Loading
+74 −12
Changes for sources/src/cache-service-basic.ts: 74 added lines, 12 removed lines.
Original line number Diff line number Diff line
@@ -4,7 +4,9 @@ import * as glob from '@actions/glob'
import * as path from 'path'

import {BuildResult} from './build-results'
import {CacheOptions, CacheService} from './cache-service'
import {CacheEntryReport, CacheOptions, CacheReport, CacheService} from './cache-service'

const ENTRY_NAME = 'Gradle User Home'

const PRIMARY_KEY_STATE = 'BASIC_CACHE_PRIMARY_KEY'
const RESTORED_KEY_STATE = 'BASIC_CACHE_RESTORED_KEY'
@@ -40,21 +42,39 @@ export class BasicCacheService implements CacheService {
        }
    }

    async save(gradleUserHome: string, _buildResults: BuildResult[], cacheOptions: CacheOptions): Promise<string> {
        if (cacheOptions.readOnly) {
    async save(gradleUserHome: string, _buildResults: BuildResult[], cacheOptions: CacheOptions): Promise<CacheReport> {
        const primaryKey = core.getState(PRIMARY_KEY_STATE)
        const restoredKey = core.getState(RESTORED_KEY_STATE)
            if (restoredKey) {
                return `Basic caching was read-only. Restored from cache key \`${restoredKey}\`.`

        if (cacheOptions.readOnly) {
            return {
                status: 'read-only',
                entries: [
                    entryReport({
                        primaryKey,
                        restoredKey,
                        restoredOutcome: restoredKey
                            ? '(Entry restored: exact match found)'
                            : '(Entry not restored: no match found)',
                        savedOutcome: '(Entry not saved: cache is read-only)'
                    })
                ]
            }
            return 'Basic caching was read-only. No cache entry was found to restore.'
        }

        const primaryKey = core.getState(PRIMARY_KEY_STATE)
        const restoredKey = core.getState(RESTORED_KEY_STATE)

        if (restoredKey === primaryKey) {
            core.info(`Basic caching restored entry with key \`${primaryKey}\`. Save was skipped.`)
            return `Basic caching restored entry with key \`${primaryKey}\`. Save was skipped.`
            return {
                status: 'enabled',
                entries: [
                    entryReport({
                        primaryKey,
                        restoredKey,
                        restoredOutcome: '(Entry restored: exact match found)',
                        savedOutcome: '(Entry not saved: entry with key already exists)'
                    })
                ]
            }
        }

        const cachePaths = getCachePaths(gradleUserHome)
@@ -62,13 +82,55 @@ export class BasicCacheService implements CacheService {
        try {
            await cache.saveCache(cachePaths, primaryKey)
            core.info(`Basic caching saved entry with key: ${primaryKey}`)
            return `Basic caching saved entry with key \`${primaryKey}\`.`
            return {
                status: 'enabled',
                entries: [
                    entryReport({
                        primaryKey,
                        restoredKey,
                        savedKey: primaryKey,
                        restoredOutcome: restoredKey
                            ? '(Entry restored: exact match found)'
                            : '(Entry not restored: no match found)',
                        savedOutcome: '(Entry saved)'
                    })
                ]
            }
        } catch (error) {
            core.warning(`Basic caching failed to save entry with key \`${primaryKey}\`: ${error}`)
            return `Basic caching save failed: ${error}`
            return {
                status: 'enabled',
                entries: [
                    entryReport({
                        primaryKey,
                        restoredKey,
                        restoredOutcome: restoredKey
                            ? '(Entry restored: exact match found)'
                            : '(Entry not restored: no match found)',
                        savedOutcome: `(Entry not saved: ${error})`
                    })
                ]
            }
        }
    }
}

function entryReport(opts: {
    primaryKey: string
    restoredKey?: string
    savedKey?: string
    restoredOutcome: string
    savedOutcome: string
}): CacheEntryReport {
    return {
        entryName: ENTRY_NAME,
        requestedKey: opts.primaryKey || undefined,
        restoredKey: opts.restoredKey || undefined,
        restoredOutcome: opts.restoredOutcome,
        savedKey: opts.savedKey || undefined,
        savedOutcome: opts.savedOutcome
    }
}

function getCachePaths(gradleUserHome: string): string[] {
    return [path.join(gradleUserHome, 'caches'), path.join(gradleUserHome, 'wrapper')]
+20 −47
Changes for sources/src/cache-service-loader.ts: 20 added lines, 47 removed lines.
Original line number Diff line number Diff line
@@ -5,57 +5,24 @@ import {pathToFileURL} from 'url'
import {CacheConfig, CacheProvider} from './configuration'
import {BasicCacheService} from './cache-service-basic'
import {BuildResult} from './build-results'
import {CacheOptions, CacheService} from './cache-service'

const NOOP_CACHING_REPORT = `
[Cache was disabled](https://github.com/gradle/actions/blob/main/docs/setup-gradle.md#disabling-caching). Gradle User Home was not restored from or saved to the cache.
`
import {CacheOptions, CacheReport, CacheService} from './cache-service'
import {ProviderNote} from './caching-report'

const ENHANCED_CACHE_MESSAGE = `Enhanced Caching: This build is using the proprietary 'gradle-actions-caching' provider for optimized caching support. See https://github.com/gradle/actions/blob/main/DISTRIBUTION.md for terms of use and opt-out instructions.`

const ENHANCED_CACHE_SUMMARY = `
> [!NOTE]
> ### ⚡️ Enhanced Caching enabled
> This build provides optimized caching support via the proprietary **gradle-actions-caching** provider. 
> See [DISTRIBUTION.md](https://github.com/gradle/actions/blob/main/DISTRIBUTION.md) for terms of use and opt-out instructions.
`

const BASIC_CACHE_MESSAGE = `Basic Caching: This build uses the open-source caching provider for reliable, path-based caching of Gradle dependencies. Upgrade available: for faster builds and advanced features, consider switching to the Enhanced Caching provider. See https://github.com/gradle/actions/blob/main/DISTRIBUTION.md for details.`

const BASIC_CACHE_SUMMARY = `
> [!NOTE]
> ### 🛡️ Basic Caching enabled
> This build uses the open-source caching provider for reliable, path-based caching of Gradle dependencies. 
> 
> **Upgrade Available:** For faster builds and advanced features, consider switching to the **Enhanced Caching** provider. 
> See [DISTRIBUTION.md](https://github.com/gradle/actions/blob/main/DISTRIBUTION.md) for details.`
const BASIC_CACHE_MESSAGE = `Basic Caching: This build uses the basic open-source caching provider. For faster builds and advanced features, consider switching to the Enhanced Caching provider. See https://github.com/gradle/actions/blob/main/DISTRIBUTION.md for details.`

class NoOpCacheService implements CacheService {
    async restore(_gradleUserHome: string, _cacheOptions: CacheOptions): Promise<void> {
        return
    }

    async save(_gradleUserHome: string, _buildResults: BuildResult[], _cacheOptions: CacheOptions): Promise<string> {
        return NOOP_CACHING_REPORT
    }
}

class LicenseWarningCacheService implements CacheService {
    private delegate: CacheService
    private summary: string

    constructor(delegate: CacheService, summary: string) {
        this.delegate = delegate
        this.summary = summary
    }

    async restore(gradleUserHome: string, cacheOptions: CacheOptions): Promise<void> {
        await this.delegate.restore(gradleUserHome, cacheOptions)
    }

    async save(gradleUserHome: string, buildResults: BuildResult[], cacheOptions: CacheOptions): Promise<string> {
        const cachingReport = await this.delegate.save(gradleUserHome, buildResults, cacheOptions)
        return `${cachingReport}\n${this.summary}`
    async save(
        _gradleUserHome: string,
        _buildResults: BuildResult[],
        _cacheOptions: CacheOptions
    ): Promise<CacheReport> {
        return {status: 'disabled', entries: []}
    }
}

@@ -67,16 +34,22 @@ export async function getCacheService(cacheConfig: CacheConfig): Promise<CacheSe

    if (cacheConfig.getCacheProvider() === CacheProvider.Basic) {
        logCacheMessage(BASIC_CACHE_MESSAGE)
        return new LicenseWarningCacheService(new BasicCacheService(), BASIC_CACHE_SUMMARY)
        return new BasicCacheService()
    }

    logCacheMessage(ENHANCED_CACHE_MESSAGE)
    const cacheService = await loadVendoredCacheService()
    if (cacheConfig.isCacheLicenseAccepted()) {
        return cacheService
    return loadVendoredCacheService()
}

    return new LicenseWarningCacheService(cacheService, ENHANCED_CACHE_SUMMARY)
/**
 * Identifies the caching provider for the Job Summary. Returns `undefined` when
 * caching is disabled, since no provider is engaged in that case.
 */
export function getProviderNote(cacheConfig: CacheConfig): ProviderNote | undefined {
    if (cacheConfig.isCacheDisabled()) {
        return undefined
    }
    return cacheConfig.getCacheProvider() === CacheProvider.Basic ? {kind: 'basic'} : {kind: 'enhanced'}
}

export async function loadVendoredCacheService(): Promise<CacheService> {
+39 −1
Changes for sources/src/cache-service.ts: 39 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -12,7 +12,45 @@ export interface CacheOptions {
    excludes: string[]
}

export type CacheStatus =
    | 'enabled'
    | 'read-only'
    | 'write-only'
    | 'disabled'
    | 'disabled-existing-home'
    | 'not-available'

export type CacheCleanupStatus =
    | 'enabled'
    | 'disabled-param'
    | 'disabled-failure'
    | 'disabled-config-cache-hit'
    | 'disabled-readonly'

export interface CacheEntryReport {
    entryName: string
    requestedKey?: string
    restoredKey?: string
    restoredSize?: number
    restoredTime?: number
    restoredOutcome: string
    savedKey?: string
    savedSize?: number
    savedTime?: number
    savedOutcome: string
}

/**
 * Structured result of a cache save operation. Rendering this into a human-readable
 * Job Summary is handled centrally by `caching-report.ts`.
 */
export interface CacheReport {
    status: CacheStatus
    cleanup?: CacheCleanupStatus
    entries: CacheEntryReport[]
}

export interface CacheService {
    restore(gradleUserHome: string, cacheOptions: CacheOptions): Promise<void>
    save(gradleUserHome: string, buildResults: BuildResult[], cacheOptions: CacheOptions): Promise<string>
    save(gradleUserHome: string, buildResults: BuildResult[], cacheOptions: CacheOptions): Promise<CacheReport>
}
+168
Changes for sources/src/caching-report.ts: 168 added lines, 0 removed lines.
Original line number Diff line number Diff line
import {CacheCleanupStatus, CacheEntryReport, CacheReport, CacheStatus} from './cache-service'

const DOCS = 'https://github.com/gradle/actions/blob/main/docs/setup-gradle.md'
const DISTRIBUTION = 'https://github.com/gradle/actions/blob/main/DISTRIBUTION.md'

/**
 * Identifies the caching provider in use, so the report can attribute the cache
 * and surface the relevant terms-of-use / upgrade information.
 */
export interface ProviderNote {
    kind: 'enhanced' | 'basic'
}

const STATUS_COPY: Record<CacheStatus, string> = {
    enabled: `[Cache was enabled](${DOCS}#caching-build-state-between-jobs) — Gradle User Home was restored from the cache and saved for use by subsequent jobs.`,
    'read-only': `[Cache was read-only](${DOCS}#using-the-cache-read-only) — by default, the action only writes to the cache for jobs running on the default branch.`,
    'write-only': `[Cache was write-only](${DOCS}#using-the-cache-write-only) — Gradle User Home was not restored from the cache.`,
    disabled: `[Caching was disabled](${DOCS}#disabling-caching) — Gradle User Home was not restored from or saved to the cache.`,
    'disabled-existing-home': `⚠️ [Caching was skipped](${DOCS}#overwriting-an-existing-gradle-user-home) — a pre-existing Gradle User Home was found, so the cache was not restored or saved.`,
    'not-available': `Caching is not available — the GitHub Actions cache service could not be reached, so Gradle User Home was not restored or saved.`
}

const CLEANUP_COPY: Record<CacheCleanupStatus, string> = {
    enabled: `[Cache cleanup](${DOCS}#configuring-cache-cleanup) purged stale files from Gradle User Home before saving.`,
    'disabled-param': `[Cache cleanup](${DOCS}#configuring-cache-cleanup) was disabled via action parameter.`,
    'disabled-failure': `[Cache cleanup](${DOCS}#configuring-cache-cleanup) was skipped due to a build failure. Use \`cache-cleanup: always\` to override.`,
    'disabled-config-cache-hit': `[Cache cleanup](${DOCS}#configuring-cache-cleanup) was skipped due to configuration-cache reuse.`,
    'disabled-readonly': `[Cache cleanup](${DOCS}#configuring-cache-cleanup) is always disabled when the cache is read-only.`
}

/**
 * Renders a cache report into the unified Job Summary markdown, with a consistent
 * skeleton across every variant: a section heading, a status line, an integrated
 * provider note, and (when there are entries) an expandable details section.
 */
export function renderCachingReport(report: CacheReport, providerNote?: ProviderNote): string {
    if (!isActive(report.status)) {
        // Disabled / skipped / unavailable: a compact heading + status line, no expandable section.
        return `${renderHeading(report.status, providerNote)}\n\n${STATUS_COPY[report.status]}\n`
    }
    const sections = [
        renderHeading(report.status, providerNote),
        renderProviderNote(providerNote),
        // Status and cleanup messages live inside the details expando; if there are no entries
        // to expand, fall back to showing the status line directly.
        report.entries.length > 0 ? renderDetails(report) : STATUS_COPY[report.status]
    ]
    return `${sections.filter(section => section !== undefined && section !== '').join('\n\n')}\n`
}

function isActive(status: CacheStatus): boolean {
    return status === 'enabled' || status === 'read-only' || status === 'write-only'
}

function renderHeading(status: CacheStatus, providerNote?: ProviderNote): string {
    if (!isActive(status)) {
        const label =
            status === 'disabled-existing-home' ? 'Skipped' : status === 'not-available' ? 'Unavailable' : 'Disabled'
        return `<h4>Gradle State Caching - ${label}</h4>`
    }

    const icon = providerNote?.kind === 'basic' ? '🛡️' : '⚡'
    const provider = providerNote?.kind === 'basic' ? 'Basic' : 'Enhanced'
    const suffix = status === 'read-only' ? ' (read-only)' : status === 'write-only' ? ' (write-only)' : ''
    return `<h4>Gradle State Caching - ${icon} ${provider}${suffix}</h4>`
}

function renderCleanupLine(cleanup?: CacheCleanupStatus): string | undefined {
    return cleanup ? CLEANUP_COPY[cleanup] : undefined
}

function renderProviderNote(providerNote?: ProviderNote): string | undefined {
    if (!providerNote) {
        return undefined
    }
    if (providerNote.kind === 'enhanced') {
        return `**[Enhanced Caching](${DOCS}#enhanced-caching)** uses the proprietary \`gradle-actions-caching\` provider. See [DISTRIBUTION.md](${DISTRIBUTION}) for terms of use and opt-out instructions.`
    }
    return `**[Basic Caching](${DOCS}#basic-caching)** uses the basic open-source caching provider. For faster builds and advanced features, consider the **[Enhanced Caching](${DOCS}#enhanced-caching)** provider.`
}

function renderDetails(report: CacheReport): string {
    const entries = report.entries
    const restored = entries.filter(entry => entry.restoredKey).length
    const saved = entries.filter(entry => entry.savedKey).length
    const summary = hasMetrics(entries)
        ? `Entries: ${restored} restored (${getSize(entries, e => e.restoredSize)}Mb), ${saved} saved (${getSize(entries, e => e.savedSize)}Mb) - Expand for more details`
        : `Entries: ${restored} restored, ${saved} saved - Expand for more details`

    const cleanup = report.status === 'enabled' ? renderCleanupLine(report.cleanup) : undefined
    const table = renderEntryTable(report.entries)
    const pre = `<pre>\n${renderEntryDetails(report.entries)}</pre>`
    const body = [STATUS_COPY[report.status], cleanup, table, pre].filter(Boolean).join('\n\n')

    return `<details>
<summary>${summary}</summary>

${body}
</details>`
}

function hasMetrics(entries: CacheEntryReport[]): boolean {
    return entries.some(entry => entry.restoredSize || entry.restoredTime || entry.savedSize || entry.savedTime)
}

function renderEntryTable(entries: CacheEntryReport[]): string {
    if (!hasMetrics(entries)) {
        return ''
    }
    return `<table>
    <tr><td></td><th>Count</th><th>Total Size (Mb)</th><th>Total Time (ms)</th></tr>
    <tr><td>Entries Restored</td>
        <td>${getCount(entries, e => e.restoredSize)}</td>
        <td>${getSize(entries, e => e.restoredSize)}</td>
        <td>${getTime(entries, e => e.restoredTime)}</td>
    </tr>
    <tr><td>Entries Saved</td>
        <td>${getCount(entries, e => e.savedSize)}</td>
        <td>${getSize(entries, e => e.savedSize)}</td>
        <td>${getTime(entries, e => e.savedTime)}</td>
    </tr>
</table>`
}

function renderEntryDetails(entries: CacheEntryReport[]): string {
    return entries
        .map(
            entry => `Entry: ${entry.entryName}
    Requested Key : ${entry.requestedKey ?? ''}
    Restored  Key : ${entry.restoredKey ?? ''}
              Size: ${formatSize(entry.restoredSize)}
              Time: ${formatTime(entry.restoredTime)}
              ${entry.restoredOutcome}
    Saved     Key : ${entry.savedKey ?? ''}
              Size: ${formatSize(entry.savedSize)}
              Time: ${formatTime(entry.savedTime)}
              ${entry.savedOutcome}
`
        )
        .join('---\n')
}

function getCount(entries: CacheEntryReport[], predicate: (value: CacheEntryReport) => number | undefined): number {
    return entries.filter(e => predicate(e)).length
}

function getSize(entries: CacheEntryReport[], predicate: (value: CacheEntryReport) => number | undefined): number {
    const bytes = entries.map(e => predicate(e) ?? 0).reduce((p, v) => p + v, 0)
    return Math.round(bytes / (1024 * 1024))
}

function getTime(entries: CacheEntryReport[], predicate: (value: CacheEntryReport) => number | undefined): number {
    return entries.map(e => predicate(e) ?? 0).reduce((p, v) => p + v, 0)
}

function formatSize(bytes: number | undefined): string {
    if (bytes === undefined || bytes === 0) {
        return ''
    }
    return `${Math.round(bytes / (1024 * 1024))} MB (${bytes} B)`
}

function formatTime(ms: number | undefined): string {
    if (ms === undefined || ms === 0) {
        return ''
    }
    return `${ms} ms`
}
−5
Changes for sources/src/configuration.ts: 0 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -167,11 +167,6 @@ export class CacheConfig {
        return core.getMultilineInput('gradle-home-cache-excludes')
    }

    isCacheLicenseAccepted(): boolean {
        const dvConfig = new DevelocityConfig()
        return dvConfig.getDevelocityAccessKey() !== '' || dvConfig.hasTermsOfUseAgreement()
    }

    getCacheProvider(): CacheProvider {
        const val = core.getInput('cache-provider')
        switch (val.toLowerCase().trim()) {
Loading