Skip to content

Commit 2da2c33

Browse files
bigdazclaude
andcommitted
Align BasicCacheService with actions/setup-java caching algorithm
- Remove restoreKeys to avoid cache bloat when Gradle wrapper version changes (see actions/setup-java#269) - Use glob.hashFiles() instead of manual file hashing to match setup-java - Save primary key to state during restore, retrieve in save instead of recomputing (matches setup-java behavior) - Use setup-java cache key prefix for compatibility Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1 parent 702a629 commit 2da2c33

2 files changed

Lines changed: 112 additions & 61 deletions

File tree

‎sources/src/cache-service-basic.ts‎

Lines changed: 25 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
import * as cache from '@actions/cache'
22
import * as core from '@actions/core'
33
import * as glob from '@actions/glob'
4-
import * as crypto from 'crypto'
5-
import * as fs from 'fs'
64
import * as path from 'path'
75

86
import {BuildResult} from './build-results'
97
import {CacheOptions, CacheService} from './cache-service'
108

9+
const PRIMARY_KEY_STATE = 'BASIC_CACHE_PRIMARY_KEY'
1110
const RESTORED_KEY_STATE = 'BASIC_CACHE_RESTORED_KEY'
12-
const CACHE_KEY_PREFIX = 'gradle-actions-basic'
11+
const CACHE_KEY_PREFIX = 'setup-java'
1312

1413
const GRADLE_BUILD_FILE_PATTERNS = [
1514
'**/*.gradle*',
@@ -28,13 +27,15 @@ export class BasicCacheService implements CacheService {
2827

2928
const cachePaths = getCachePaths(gradleUserHome)
3029
const primaryKey = await computeCacheKey()
31-
const restoreKeys = [getRestoreKeyPrefix()]
30+
core.saveState(PRIMARY_KEY_STATE, primaryKey)
3231

32+
// No "restoreKeys" is set, to start with a clear cache after dependency update
33+
// See https://github.com/actions/setup-java/issues/269
3334
try {
34-
const restoredKey = await cache.restoreCache(cachePaths, primaryKey, restoreKeys)
35-
if (restoredKey) {
36-
core.saveState(RESTORED_KEY_STATE, restoredKey)
37-
core.info(`Gradle User Home restored from cache key: ${restoredKey}`)
35+
const matchedKey = await cache.restoreCache(cachePaths, primaryKey)
36+
if (matchedKey) {
37+
core.saveState(RESTORED_KEY_STATE, matchedKey)
38+
core.info(`Gradle User Home restored from cache key: ${matchedKey}`)
3839
} else {
3940
core.info('Gradle User Home cache not found. Will start with empty state.')
4041
}
@@ -52,11 +53,17 @@ export class BasicCacheService implements CacheService {
5253
return 'Gradle User Home cache entry was not restored and was not saved (caching is read-only or disabled).'
5354
}
5455

55-
const primaryKey = await computeCacheKey()
56-
const restoredKey = core.getState(RESTORED_KEY_STATE)
56+
const matchedKey = core.getState(RESTORED_KEY_STATE)
57+
58+
// Inputs are re-evaluated before the post action, so we want the original key used for restore
59+
let primaryKey = core.getState(PRIMARY_KEY_STATE)
60+
if (!primaryKey) {
61+
// Fallback: compute key if restore was not called (e.g. writeOnly mode)
62+
primaryKey = await computeCacheKey()
63+
}
5764

58-
if (restoredKey === primaryKey) {
59-
core.info(`Gradle User Home cache hit with exact key ${primaryKey}. Save skipped.`)
65+
if (matchedKey === primaryKey) {
66+
core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`)
6067
return `Gradle User Home cache hit with exact key \`${primaryKey}\`. Save was skipped.`
6168
}
6269

@@ -77,27 +84,12 @@ function getCachePaths(gradleUserHome: string): string[] {
7784
return [path.join(gradleUserHome, 'caches'), path.join(gradleUserHome, 'wrapper')]
7885
}
7986

80-
function getRestoreKeyPrefix(): string {
81-
return `${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS'] || 'unknown'}-${process.arch}-gradle-`
82-
}
83-
8487
async function computeCacheKey(): Promise<string> {
85-
const fileHash = await hashGradleBuildFiles()
86-
return `${getRestoreKeyPrefix()}${fileHash}`
87-
}
88-
89-
async function hashGradleBuildFiles(): Promise<string> {
90-
const hash = crypto.createHash('sha256')
91-
const globber = await glob.create(GRADLE_BUILD_FILE_PATTERNS.join('\n'))
92-
const files = (await globber.glob()).sort()
93-
94-
for (const file of files) {
95-
const stat = fs.statSync(file)
96-
if (stat.isFile()) {
97-
const content = fs.readFileSync(file)
98-
hash.update(content)
99-
}
88+
const fileHash = await glob.hashFiles(GRADLE_BUILD_FILE_PATTERNS.join('\n'))
89+
if (!fileHash) {
90+
throw new Error(
91+
`No file in ${process.cwd()} matched to [${GRADLE_BUILD_FILE_PATTERNS}], make sure you have checked out the target repository`
92+
)
10093
}
101-
102-
return hash.digest('hex').substring(0, 32)
94+
return `${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-${process.arch}-gradle-${fileHash}`
10395
}

‎sources/test/jest/cache-service-basic.test.ts‎

Lines changed: 87 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -21,25 +21,15 @@ jest.unstable_mockModule('@actions/core', () => ({
2121
}))
2222

2323
// Mock @actions/glob
24-
const mockGlob = jest.fn<() => Promise<string[]>>()
24+
const mockHashFiles = jest.fn<(pattern: string) => Promise<string>>()
2525
jest.unstable_mockModule('@actions/glob', () => ({
26-
create: jest.fn<() => Promise<{glob: typeof mockGlob}>>().mockImplementation(async () => ({
27-
glob: mockGlob
28-
}))
29-
}))
30-
31-
// Mock fs
32-
const mockReadFileSync = jest.fn()
33-
const mockStatSync = jest.fn()
34-
jest.unstable_mockModule('fs', () => ({
35-
readFileSync: mockReadFileSync,
36-
statSync: mockStatSync,
37-
default: {readFileSync: mockReadFileSync, statSync: mockStatSync}
26+
hashFiles: mockHashFiles
3827
}))
3928

4029
const {BasicCacheService} = await import('../../src/cache-service-basic')
4130

42-
const KEY_PREFIX = `gradle-actions-basic-Linux-${process.arch}-gradle-`
31+
const HASH = 'abc123def456'
32+
const PRIMARY_KEY = `setup-java-Linux-${process.arch}-gradle-${HASH}`
4333

4434
describe('BasicCacheService', () => {
4535
let service: InstanceType<typeof BasicCacheService>
@@ -48,7 +38,7 @@ describe('BasicCacheService', () => {
4838
jest.clearAllMocks()
4939
service = new BasicCacheService()
5040
process.env['RUNNER_OS'] = 'Linux'
51-
mockGlob.mockResolvedValue([])
41+
mockHashFiles.mockResolvedValue(HASH)
5242
})
5343

5444
describe('restore', () => {
@@ -82,8 +72,8 @@ describe('BasicCacheService', () => {
8272
expect(mockRestoreCache).not.toHaveBeenCalled()
8373
})
8474

85-
it('restores cache and saves state on hit', async () => {
86-
mockRestoreCache.mockResolvedValue(`${KEY_PREFIX}abc123`)
75+
it('restores cache without restoreKeys and saves both keys to state', async () => {
76+
mockRestoreCache.mockResolvedValue(PRIMARY_KEY)
8777

8878
await service.restore('/home/.gradle', {
8979
disabled: false,
@@ -96,15 +86,13 @@ describe('BasicCacheService', () => {
9686
excludes: []
9787
})
9888

89+
// No restoreKeys parameter — exact match only (setup-java#269)
9990
expect(mockRestoreCache).toHaveBeenCalledWith(
10091
['/home/.gradle/caches', '/home/.gradle/wrapper'],
101-
expect.stringContaining(KEY_PREFIX),
102-
[KEY_PREFIX]
103-
)
104-
expect(mockSaveState).toHaveBeenCalledWith(
105-
'BASIC_CACHE_RESTORED_KEY',
106-
`${KEY_PREFIX}abc123`
92+
PRIMARY_KEY
10793
)
94+
expect(mockSaveState).toHaveBeenCalledWith('BASIC_CACHE_PRIMARY_KEY', PRIMARY_KEY)
95+
expect(mockSaveState).toHaveBeenCalledWith('BASIC_CACHE_RESTORED_KEY', PRIMARY_KEY)
10896
})
10997

11098
it('handles cache miss gracefully', async () => {
@@ -121,7 +109,10 @@ describe('BasicCacheService', () => {
121109
excludes: []
122110
})
123111

124-
expect(mockSaveState).not.toHaveBeenCalled()
112+
// Primary key should still be saved to state even on miss
113+
expect(mockSaveState).toHaveBeenCalledWith('BASIC_CACHE_PRIMARY_KEY', PRIMARY_KEY)
114+
// Restored key should NOT be saved
115+
expect(mockSaveState).not.toHaveBeenCalledWith('BASIC_CACHE_RESTORED_KEY', expect.anything())
125116
expect(mockInfo).toHaveBeenCalledWith(
126117
expect.stringContaining('not found')
127118
)
@@ -145,6 +136,23 @@ describe('BasicCacheService', () => {
145136
expect.stringContaining('Failed to restore')
146137
)
147138
})
139+
140+
it('throws when no build files are found', async () => {
141+
mockHashFiles.mockResolvedValue('')
142+
143+
await expect(
144+
service.restore('/home/.gradle', {
145+
disabled: false,
146+
readOnly: false,
147+
writeOnly: false,
148+
overwriteExisting: false,
149+
strictMatch: false,
150+
cleanup: 'never',
151+
includes: [],
152+
excludes: []
153+
})
154+
).rejects.toThrow('No file in')
155+
})
148156
})
149157

150158
describe('save', () => {
@@ -166,7 +174,10 @@ describe('BasicCacheService', () => {
166174
})
167175

168176
it('skips save when readOnly and reports restored key', async () => {
169-
mockGetState.mockReturnValue(`${KEY_PREFIX}abc123`)
177+
mockGetState.mockImplementation((name: string) => {
178+
if (name === 'BASIC_CACHE_RESTORED_KEY') return PRIMARY_KEY
179+
return ''
180+
})
170181
const report = await service.save('/home/.gradle', [], {
171182
disabled: false,
172183
readOnly: true,
@@ -180,7 +191,7 @@ describe('BasicCacheService', () => {
180191

181192
expect(mockSaveCache).not.toHaveBeenCalled()
182193
expect(report).toContain('restored from cache key')
183-
expect(report).toContain(`${KEY_PREFIX}abc123`)
194+
expect(report).toContain(PRIMARY_KEY)
184195
expect(report).toContain('read-only')
185196
})
186197

@@ -201,7 +212,55 @@ describe('BasicCacheService', () => {
201212
expect(report).toContain('not restored')
202213
})
203214

204-
it('saves cache and returns report on success', async () => {
215+
it('skips save when matched key equals primary key', async () => {
216+
mockGetState.mockImplementation((name: string) => {
217+
if (name === 'BASIC_CACHE_RESTORED_KEY') return PRIMARY_KEY
218+
if (name === 'BASIC_CACHE_PRIMARY_KEY') return PRIMARY_KEY
219+
return ''
220+
})
221+
222+
const report = await service.save('/home/.gradle', [], {
223+
disabled: false,
224+
readOnly: false,
225+
writeOnly: false,
226+
overwriteExisting: false,
227+
strictMatch: false,
228+
cleanup: 'never',
229+
includes: [],
230+
excludes: []
231+
})
232+
233+
expect(mockSaveCache).not.toHaveBeenCalled()
234+
expect(report).toContain('Save was skipped')
235+
})
236+
237+
it('uses primary key from state, not recomputed', async () => {
238+
const stateKey = `setup-java-Linux-${process.arch}-gradle-statedhash`
239+
mockGetState.mockImplementation((name: string) => {
240+
if (name === 'BASIC_CACHE_PRIMARY_KEY') return stateKey
241+
return ''
242+
})
243+
mockSaveCache.mockResolvedValue(0)
244+
245+
const report = await service.save('/home/.gradle', [], {
246+
disabled: false,
247+
readOnly: false,
248+
writeOnly: false,
249+
overwriteExisting: false,
250+
strictMatch: false,
251+
cleanup: 'never',
252+
includes: [],
253+
excludes: []
254+
})
255+
256+
expect(mockSaveCache).toHaveBeenCalledWith(
257+
['/home/.gradle/caches', '/home/.gradle/wrapper'],
258+
stateKey
259+
)
260+
expect(report).toContain(stateKey)
261+
})
262+
263+
it('computes key as fallback when primary key not in state', async () => {
205264
mockGetState.mockReturnValue('')
206265
mockSaveCache.mockResolvedValue(0)
207266

@@ -218,7 +277,7 @@ describe('BasicCacheService', () => {
218277

219278
expect(mockSaveCache).toHaveBeenCalledWith(
220279
['/home/.gradle/caches', '/home/.gradle/wrapper'],
221-
expect.stringContaining(KEY_PREFIX)
280+
PRIMARY_KEY
222281
)
223282
expect(report).toContain('saved to cache')
224283
})

0 commit comments

Comments
 (0)