Unverified Commit cfd20ecc authored by daz's avatar daz
Browse files

Replace static config methods with config types

This will allow different entry points to have different inputs.
parent ed4d086d
Loading
Loading
Loading
Loading
+5 −17
Changes for sources/src/build-scan.ts: 5 added lines, 17 removed lines.
Original line number Diff line number Diff line
import * as core from '@actions/core'
import {getBuildScanPublishEnabled, getBuildScanTermsOfUseUrl, getBuildScanTermsOfUseAgree} from './input-params'
import {BuildScanConfig} from './input-params'

export function setup(): void {
export function setup(config: BuildScanConfig): void {
    maybeExportVariable('DEVELOCITY_INJECTION_INIT_SCRIPT_NAME', 'gradle-actions.inject-develocity.init.gradle')
    maybeExportVariable('DEVELOCITY_AUTO_INJECTION_CUSTOM_VALUE', 'gradle-actions')
    if (getBuildScanPublishEnabled() && verifyTermsOfUseAgreement()) {
    if (config.getBuildScanPublishEnabled()) {
        maybeExportVariable('DEVELOCITY_INJECTION_ENABLED', 'true')
        maybeExportVariable('DEVELOCITY_PLUGIN_VERSION', '3.17')
        maybeExportVariable('DEVELOCITY_CCUD_PLUGIN_VERSION', '1.13')
        maybeExportVariable('DEVELOCITY_TERMS_OF_USE_URL', getBuildScanTermsOfUseUrl())
        maybeExportVariable('DEVELOCITY_TERMS_OF_USE_AGREE', getBuildScanTermsOfUseAgree())
        maybeExportVariable('DEVELOCITY_TERMS_OF_USE_URL', config.getBuildScanTermsOfUseUrl())
        maybeExportVariable('DEVELOCITY_TERMS_OF_USE_AGREE', config.getBuildScanTermsOfUseAgree())
    }
}

function verifyTermsOfUseAgreement(): boolean {
    if (
        (getBuildScanTermsOfUseUrl() !== 'https://gradle.com/terms-of-service' &&
            getBuildScanTermsOfUseUrl() !== 'https://gradle.com/help/legal-terms-of-use') ||
        getBuildScanTermsOfUseAgree() !== 'yes'
    ) {
        core.warning(`Terms of use must be agreed in order to publish build scans.`)
        return false
    }
    return true
}

function maybeExportVariable(variableName: string, value: unknown): void {
    if (!process.env[variableName]) {
        core.exportVariable(variableName, value)
+13 −11
Changes for sources/src/cache-base.ts: 13 added lines, 11 removed lines.
Original line number Diff line number Diff line
@@ -4,7 +4,7 @@ import * as glob from '@actions/glob'

import path from 'path'
import fs from 'fs'
import * as params from './input-params'
import {CacheConfig} from './input-params'
import {CacheListener} from './cache-reporting'
import {saveCache, restoreCache, cacheDebug, isCacheDebuggingEnabled, tryDelete, generateCacheKey} from './cache-utils'
import {GradleHomeEntryExtractor, ConfigurationCacheEntryExtractor} from './cache-extract-entries'
@@ -14,15 +14,17 @@ const RESTORED_CACHE_KEY_KEY = 'restored-cache-key'
export const META_FILE_DIR = '.setup-gradle'

export class GradleStateCache {
    private cacheConfig: CacheConfig
    private cacheName: string
    private cacheDescription: string

    protected readonly userHome: string
    protected readonly gradleUserHome: string

    constructor(userHome: string, gradleUserHome: string) {
    constructor(userHome: string, gradleUserHome: string, cacheConfig: CacheConfig) {
        this.userHome = userHome
        this.gradleUserHome = gradleUserHome
        this.cacheConfig = cacheConfig
        this.cacheName = 'gradle'
        this.cacheDescription = 'Gradle User Home'
    }
@@ -31,7 +33,7 @@ export class GradleStateCache {
        this.initializeGradleUserHome()

        // Export the GRADLE_ENCRYPTION_KEY variable if provided
        const encryptionKey = params.getCacheEncryptionKey()
        const encryptionKey = this.cacheConfig.getCacheEncryptionKey()
        if (encryptionKey) {
            core.exportVariable('GRADLE_ENCRYPTION_KEY', encryptionKey)
        }
@@ -52,7 +54,7 @@ export class GradleStateCache {
    async restore(listener: CacheListener): Promise<void> {
        const entryListener = listener.entry(this.cacheDescription)

        const cacheKey = generateCacheKey(this.cacheName)
        const cacheKey = generateCacheKey(this.cacheName, this.cacheConfig)

        cacheDebug(
            `Requesting ${this.cacheDescription} with
@@ -82,8 +84,8 @@ export class GradleStateCache {
     */
    async afterRestore(listener: CacheListener): Promise<void> {
        await this.debugReportGradleUserHomeSize('as restored from cache')
        await new GradleHomeEntryExtractor(this.gradleUserHome).restore(listener)
        await new ConfigurationCacheEntryExtractor(this.gradleUserHome).restore(listener)
        await new GradleHomeEntryExtractor(this.gradleUserHome, this.cacheConfig).restore(listener)
        await new ConfigurationCacheEntryExtractor(this.gradleUserHome, this.cacheConfig).restore(listener)
        await this.debugReportGradleUserHomeSize('after restoring common artifacts')
    }

@@ -95,7 +97,7 @@ export class GradleStateCache {
     * it is saved with the exact key.
     */
    async save(listener: CacheListener): Promise<void> {
        const cacheKey = generateCacheKey(this.cacheName).key
        const cacheKey = generateCacheKey(this.cacheName, this.cacheConfig).key
        const restoredCacheKey = core.getState(RESTORED_CACHE_KEY_KEY)
        const gradleHomeEntryListener = listener.entry(this.cacheDescription)

@@ -133,8 +135,8 @@ export class GradleStateCache {
        await this.debugReportGradleUserHomeSize('before saving common artifacts')
        await this.deleteExcludedPaths()
        await Promise.all([
            new GradleHomeEntryExtractor(this.gradleUserHome).extract(listener),
            new ConfigurationCacheEntryExtractor(this.gradleUserHome).extract(listener)
            new GradleHomeEntryExtractor(this.gradleUserHome, this.cacheConfig).extract(listener),
            new ConfigurationCacheEntryExtractor(this.gradleUserHome, this.cacheConfig).extract(listener)
        ])
        await this.debugReportGradleUserHomeSize(
            "after extracting common artifacts (only 'caches' and 'notifications' will be stored)"
@@ -145,7 +147,7 @@ export class GradleStateCache {
     * Delete any file paths that are excluded by the `gradle-home-cache-excludes` parameter.
     */
    private async deleteExcludedPaths(): Promise<void> {
        const rawPaths: string[] = params.getCacheExcludes()
        const rawPaths: string[] = this.cacheConfig.getCacheExcludes()
        rawPaths.push('caches/*/cc-keystore')
        const resolvedPaths = rawPaths.map(x => path.resolve(this.gradleUserHome, x))

@@ -168,7 +170,7 @@ export class GradleStateCache {
     * but this can be overridden by the `gradle-home-cache-includes` parameter.
     */
    protected getCachePath(): string[] {
        const rawPaths: string[] = params.getCacheIncludes()
        const rawPaths: string[] = this.cacheConfig.getCacheIncludes()
        rawPaths.push(META_FILE_DIR)
        const resolvedPaths = rawPaths.map(x => this.resolveCachePath(x))
        cacheDebug(`Using cache paths: ${resolvedPaths}`)
+20 −11
Changes for sources/src/cache-extract-entries.ts: 20 added lines, 11 removed lines.
Original line number Diff line number Diff line
@@ -4,12 +4,19 @@ import * as core from '@actions/core'
import * as glob from '@actions/glob'
import * as semver from 'semver'

import * as params from './input-params'

import {META_FILE_DIR} from './cache-base'
import {CacheEntryListener, CacheListener} from './cache-reporting'
import {cacheDebug, getCacheKeyPrefix, hashFileNames, restoreCache, saveCache, tryDelete} from './cache-utils'
import {
    cacheDebug,
    getCacheKeyPrefix,
    hashFileNames,
    isCacheDebuggingEnabled,
    restoreCache,
    saveCache,
    tryDelete
} from './cache-utils'
import {BuildResult, loadBuildResults} from './build-results'
import {CacheConfig} from './input-params'

const SKIP_RESTORE_VAR = 'GRADLE_BUILD_ACTION_SKIP_RESTORE'

@@ -80,12 +87,14 @@ class ExtractedCacheEntryDefinition {
 * for more efficient storage.
 */
abstract class AbstractEntryExtractor {
    protected readonly cacheConfig: CacheConfig
    protected readonly gradleUserHome: string
    private extractorName: string

    constructor(gradleUserHome: string, extractorName: string) {
    constructor(gradleUserHome: string, extractorName: string, cacheConfig: CacheConfig) {
        this.gradleUserHome = gradleUserHome
        this.extractorName = extractorName
        this.cacheConfig = cacheConfig
    }

    /**
@@ -261,7 +270,7 @@ abstract class AbstractEntryExtractor {

    // Run actions sequentially if debugging is enabled
    private async awaitForDebugging(p: Promise<ExtractedCacheEntry>): Promise<ExtractedCacheEntry> {
        if (params.isCacheDebuggingEnabled()) {
        if (isCacheDebuggingEnabled()) {
            await p
        }
        return p
@@ -306,8 +315,8 @@ abstract class AbstractEntryExtractor {
}

export class GradleHomeEntryExtractor extends AbstractEntryExtractor {
    constructor(gradleUserHome: string) {
        super(gradleUserHome, 'gradle-home')
    constructor(gradleUserHome: string, cacheConfig: CacheConfig) {
        super(gradleUserHome, 'gradle-home', cacheConfig)
    }

    async extract(listener: CacheListener): Promise<void> {
@@ -363,8 +372,8 @@ export class GradleHomeEntryExtractor extends AbstractEntryExtractor {
}

export class ConfigurationCacheEntryExtractor extends AbstractEntryExtractor {
    constructor(gradleUserHome: string) {
        super(gradleUserHome, 'configuration-cache')
    constructor(gradleUserHome: string, cacheConfig: CacheConfig) {
        super(gradleUserHome, 'configuration-cache', cacheConfig)
    }

    /**
@@ -377,7 +386,7 @@ export class ConfigurationCacheEntryExtractor extends AbstractEntryExtractor {
            return
        }

        if (!params.getCacheEncryptionKey()) {
        if (!this.cacheConfig.getCacheEncryptionKey()) {
            this.markNotRestored(listener, 'Encryption Key was not provided')
            return
        }
@@ -399,7 +408,7 @@ export class ConfigurationCacheEntryExtractor extends AbstractEntryExtractor {
    }

    async extract(listener: CacheListener): Promise<void> {
        if (!params.getCacheEncryptionKey()) {
        if (!this.cacheConfig.getCacheEncryptionKey()) {
            const cacheEntryDefinitions = this.getExtractedCacheEntryDefinitions()
            if (cacheEntryDefinitions.length > 0) {
                core.info('Not saving configuration-cache state, as no encryption key was provided')
+7 −28
Changes for sources/src/cache-utils.ts: 7 added lines, 28 removed lines.
Original line number Diff line number Diff line
@@ -7,9 +7,8 @@ import * as crypto from 'crypto'
import * as path from 'path'
import * as fs from 'fs'

import * as params from './input-params'

import {CacheEntryListener} from './cache-reporting'
import {CacheConfig, getJobMatrix} from './input-params'

const CACHE_PROTOCOL_VERSION = 'v9-'

@@ -22,31 +21,11 @@ const CACHE_KEY_JOB_EXECUTION_VAR = 'GRADLE_BUILD_ACTION_CACHE_KEY_JOB_EXECUTION
const SEGMENT_DOWNLOAD_TIMEOUT_VAR = 'SEGMENT_DOWNLOAD_TIMEOUT_MINS'
const SEGMENT_DOWNLOAD_TIMEOUT_DEFAULT = 10 * 60 * 1000 // 10 minutes

export function isCacheDisabled(): boolean {
    if (!cache.isFeatureAvailable()) {
        return true
    }
    return params.isCacheDisabled()
}

export function isCacheReadOnly(): boolean {
    return !isCacheWriteOnly() && params.isCacheReadOnly()
}

export function isCacheWriteOnly(): boolean {
    return params.isCacheWriteOnly()
}

export function isCacheOverwriteExisting(): boolean {
    return params.isCacheOverwriteExisting()
}

export function isCacheDebuggingEnabled(): boolean {
    return params.isCacheDebuggingEnabled()
    if (core.isDebug()) {
        return true
    }

export function isCacheCleanupEnabled(): boolean {
    return params.isCacheCleanupEnabled()
    return process.env['GRADLE_BUILD_ACTION_CACHE_DEBUG_ENABLED'] ? true : false
}

/**
@@ -80,7 +59,7 @@ export class CacheKey {
 * - Any previous key for this Job (any matrix)
 * - Any previous key for this cache on the current OS
 */
export function generateCacheKey(cacheName: string): CacheKey {
export function generateCacheKey(cacheName: string, config: CacheConfig): CacheKey {
    const cacheKeyBase = `${getCacheKeyPrefix()}${CACHE_PROTOCOL_VERSION}${cacheName}`

    // At the most general level, share caches for all executions on the same OS
@@ -95,7 +74,7 @@ export function generateCacheKey(cacheName: string): CacheKey {
    // Exact match on Git SHA
    const cacheKey = `${cacheKeyForJobContext}-${getCacheKeyJobExecution()}`

    if (params.isCacheStrictMatch()) {
    if (config.isCacheStrictMatch()) {
        return new CacheKey(cacheKey, [cacheKeyForJobContext])
    }

@@ -125,7 +104,7 @@ function getCacheKeyJobInstance(): string {
    // By default, we hash the workflow name and the full `matrix` data for the run, to uniquely identify this job invocation
    // The only way we can obtain the `matrix` data is via the `workflow-job-context` parameter in action.yml.
    const workflowName = github.context.workflow
    const workflowJobContext = params.getJobMatrix()
    const workflowJobContext = getJobMatrix()
    return hashStrings([workflowName, workflowJobContext])
}

+18 −18
Changes for sources/src/caches.ts: 18 added lines, 18 removed lines.
Original line number Diff line number Diff line
import * as core from '@actions/core'
import {
    isCacheCleanupEnabled,
    isCacheDisabled,
    isCacheReadOnly,
    isCacheWriteOnly,
    isCacheOverwriteExisting
} from './cache-utils'
import {CacheListener} from './cache-reporting'
import {DaemonController} from './daemon-controller'
import {GradleStateCache} from './cache-base'
import {CacheCleaner} from './cache-cleaner'
import {CacheConfig} from './input-params'

const CACHE_RESTORED_VAR = 'GRADLE_BUILD_ACTION_CACHE_RESTORED'

export async function restore(userHome: string, gradleUserHome: string, cacheListener: CacheListener): Promise<void> {
export async function restore(
    userHome: string,
    gradleUserHome: string,
    cacheListener: CacheListener,
    cacheConfig: CacheConfig
): Promise<void> {
    // Bypass restore cache on all but first action step in workflow.
    if (process.env[CACHE_RESTORED_VAR]) {
        core.info('Cache only restored on first action step.')
@@ -21,9 +20,9 @@ export async function restore(userHome: string, gradleUserHome: string, cacheLis
    }
    core.exportVariable(CACHE_RESTORED_VAR, true)

    const gradleStateCache = new GradleStateCache(userHome, gradleUserHome)
    const gradleStateCache = new GradleStateCache(userHome, gradleUserHome, cacheConfig)

    if (isCacheDisabled()) {
    if (cacheConfig.isCacheDisabled()) {
        core.info('Cache is disabled: will not restore state from previous builds.')
        // Initialize the Gradle User Home even when caching is disabled.
        gradleStateCache.init()
@@ -32,7 +31,7 @@ export async function restore(userHome: string, gradleUserHome: string, cacheLis
    }

    if (gradleStateCache.cacheOutputExists()) {
        if (!isCacheOverwriteExisting()) {
        if (!cacheConfig.isCacheOverwriteExisting()) {
            core.info('Gradle User Home already exists: will not restore from cache.')
            // Initialize pre-existing Gradle User Home.
            gradleStateCache.init()
@@ -47,7 +46,7 @@ export async function restore(userHome: string, gradleUserHome: string, cacheLis
    // Mark the state as restored so that post-action will perform save.
    core.saveState(CACHE_RESTORED_VAR, true)

    if (isCacheWriteOnly()) {
    if (cacheConfig.isCacheWriteOnly()) {
        core.info('Cache is write-only: will not restore from cache.')
        cacheListener.cacheWriteOnly = true
        return
@@ -57,7 +56,7 @@ export async function restore(userHome: string, gradleUserHome: string, cacheLis
        await gradleStateCache.restore(cacheListener)
    })

    if (isCacheCleanupEnabled() && !isCacheReadOnly()) {
    if (cacheConfig.isCacheCleanupEnabled()) {
        core.info('Preparing cache for cleanup.')
        const cacheCleaner = new CacheCleaner(gradleUserHome, process.env['RUNNER_TEMP']!)
        await cacheCleaner.prepare()
@@ -68,9 +67,10 @@ export async function save(
    userHome: string,
    gradleUserHome: string,
    cacheListener: CacheListener,
    daemonController: DaemonController
    daemonController: DaemonController,
    cacheConfig: CacheConfig
): Promise<void> {
    if (isCacheDisabled()) {
    if (cacheConfig.isCacheDisabled()) {
        core.info('Cache is disabled: will not save state for later builds.')
        return
    }
@@ -80,7 +80,7 @@ export async function save(
        return
    }

    if (isCacheReadOnly()) {
    if (cacheConfig.isCacheReadOnly()) {
        core.info('Cache is read-only: will not save state for use in subsequent builds.')
        cacheListener.cacheReadOnly = true
        return
@@ -88,7 +88,7 @@ export async function save(

    await daemonController.stopAllDaemons()

    if (isCacheCleanupEnabled()) {
    if (cacheConfig.isCacheCleanupEnabled()) {
        core.info('Forcing cache cleanup.')
        const cacheCleaner = new CacheCleaner(gradleUserHome, process.env['RUNNER_TEMP']!)
        try {
@@ -99,6 +99,6 @@ export async function save(
    }

    await core.group('Caching Gradle state', async () => {
        return new GradleStateCache(userHome, gradleUserHome).save(cacheListener)
        return new GradleStateCache(userHome, gradleUserHome, cacheConfig).save(cacheListener)
    })
}
Loading