mirror of
https://github.com/actions/setup-go.git
synced 2026-10-06 16:44:34 +03:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad9941188f |
No files matched your search
@@ -127,6 +127,8 @@ The `cache` input is optional, and caching is enabled by default. To disable cac
|
||||
|
||||
By default, the action looks for `go.mod` in the repository root and uses its hash as part of the cache key. Use the `cache-dependency-path` input when you have multiple dependency files, or when they’re located in different subdirectories. This input supports glob patterns.
|
||||
|
||||
Module sources (`GOMODCACHE`) and build outputs (`GOCACHE`) are cached separately. On the same runner OS, module sources can be reused across Go versions and runner architectures, while build outputs remain partitioned by Go version, runner architecture, and Linux runner image. The `cache-hit` output is `true` only when both cache entries are restored on their primary keys.
|
||||
|
||||
If caching cannot be performed for any reason, the action logs a warning and continues workflow execution.
|
||||
|
||||
For examples of using `cache-dependency-path`, see the [Caching](docs/advanced-usage.md#caching) section of the [Advanced usage](docs/advanced-usage.md) guide.
|
||||
|
||||
+321
-60
@@ -1,5 +1,8 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
import {jest, describe, it, expect, beforeEach, afterEach} from '@jest/globals';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
jest.unstable_mockModule('@actions/cache', () => ({
|
||||
saveCache: jest.fn(),
|
||||
@@ -50,91 +53,349 @@ const core = await import('@actions/core');
|
||||
const glob = await import('@actions/glob');
|
||||
const cacheRestore = await import('../src/cache-restore.js');
|
||||
const cacheUtils = await import('../src/cache-utils.js');
|
||||
import type {PackageManagerInfo} from '../src/package-managers.js';
|
||||
const {run: saveCaches} = await import('../src/cache-save.js');
|
||||
import type {CacheDirectory} from '../src/cache-utils.js';
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>(done => {
|
||||
resolve = done;
|
||||
});
|
||||
return {promise, resolve};
|
||||
}
|
||||
|
||||
describe('restoreCache', () => {
|
||||
let hashFilesSpy: jest.Mock<typeof glob.hashFiles>;
|
||||
let getCacheDirectoryPathSpy: jest.Mock<
|
||||
typeof cacheUtils.getCacheDirectoryPath
|
||||
const hashFilesSpy = glob.hashFiles as jest.Mock<typeof glob.hashFiles>;
|
||||
const getCacheDirectoryPathSpy =
|
||||
cacheUtils.getCacheDirectoryPath as jest.Mock<
|
||||
typeof cacheUtils.getCacheDirectoryPath
|
||||
>;
|
||||
const restoreCacheSpy = cache.restoreCache as jest.Mock<
|
||||
typeof cache.restoreCache
|
||||
>;
|
||||
let restoreCacheSpy: jest.Mock<typeof cache.restoreCache>;
|
||||
let infoSpy: jest.Mock<typeof core.info>;
|
||||
let setOutputSpy: jest.Mock<typeof core.setOutput>;
|
||||
const saveCacheSpy = cache.saveCache as jest.Mock<typeof cache.saveCache>;
|
||||
const infoSpy = core.info as jest.Mock<typeof core.info>;
|
||||
const setOutputSpy = core.setOutput as jest.Mock<typeof core.setOutput>;
|
||||
|
||||
const versionSpec = '1.13.1';
|
||||
const packageManager = 'default';
|
||||
const cacheDependencyPath = 'path';
|
||||
|
||||
let originalWorkspace: string | undefined;
|
||||
const modulePath = 'module_cache_directory';
|
||||
const buildPath = 'build_cache_directory';
|
||||
const directories: CacheDirectory[] = [
|
||||
{kind: 'modules', path: modulePath},
|
||||
{kind: 'build', path: buildPath}
|
||||
];
|
||||
const originalEnv = {...process.env};
|
||||
const originalArch = Object.getOwnPropertyDescriptor(process, 'arch')!;
|
||||
const originalPlatform = Object.getOwnPropertyDescriptor(
|
||||
process,
|
||||
'platform'
|
||||
)!;
|
||||
|
||||
beforeEach(() => {
|
||||
originalWorkspace = process.env.GITHUB_WORKSPACE;
|
||||
process.env.GITHUB_WORKSPACE = '/test/workspace';
|
||||
//Arrange
|
||||
hashFilesSpy = glob.hashFiles as jest.Mock<typeof glob.hashFiles>;
|
||||
getCacheDirectoryPathSpy = cacheUtils.getCacheDirectoryPath as jest.Mock<
|
||||
typeof cacheUtils.getCacheDirectoryPath
|
||||
>;
|
||||
restoreCacheSpy = cache.restoreCache as jest.Mock<
|
||||
typeof cache.restoreCache
|
||||
>;
|
||||
infoSpy = core.info as jest.Mock<typeof core.info>;
|
||||
setOutputSpy = core.setOutput as jest.Mock<typeof core.setOutput>;
|
||||
|
||||
getCacheDirectoryPathSpy.mockImplementation(
|
||||
(PackageManager: PackageManagerInfo) => {
|
||||
return Promise.resolve([
|
||||
'cache_directory_path',
|
||||
'cache_directory_path'
|
||||
]);
|
||||
}
|
||||
);
|
||||
jest.resetAllMocks();
|
||||
process.env = {
|
||||
...originalEnv,
|
||||
GITHUB_WORKSPACE: '/test/workspace',
|
||||
RUNNER_OS: 'Linux',
|
||||
ImageOS: 'ubuntu24'
|
||||
};
|
||||
Object.defineProperty(process, 'arch', {value: 'x64'});
|
||||
Object.defineProperty(process, 'platform', {value: 'linux'});
|
||||
hashFilesSpy.mockResolvedValue('file_hash');
|
||||
getCacheDirectoryPathSpy.mockResolvedValue(directories);
|
||||
restoreCacheSpy.mockResolvedValue(undefined);
|
||||
saveCacheSpy.mockResolvedValue(1);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env.GITHUB_WORKSPACE = originalWorkspace;
|
||||
process.env = {...originalEnv};
|
||||
Object.defineProperty(process, 'arch', originalArch);
|
||||
Object.defineProperty(process, 'platform', originalPlatform);
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
const restore = (version = versionSpec) =>
|
||||
cacheRestore.restoreCache(version, packageManager, cacheDependencyPath);
|
||||
|
||||
const requestedKeys = () => {
|
||||
const moduleCall = restoreCacheSpy.mock.calls.find(
|
||||
([paths]) => paths[0] === modulePath
|
||||
);
|
||||
const buildCall = restoreCacheSpy.mock.calls.find(
|
||||
([paths]) => paths[0] === buildPath
|
||||
);
|
||||
expect(moduleCall).toBeDefined();
|
||||
expect(buildCall).toBeDefined();
|
||||
return {modules: moduleCall![1], build: buildCall![1]};
|
||||
};
|
||||
|
||||
it('should throw if dependency file path is not valid', async () => {
|
||||
// Arrange
|
||||
hashFilesSpy.mockImplementation(() => Promise.resolve(''));
|
||||
// Act + Assert
|
||||
await expect(
|
||||
cacheRestore.restoreCache(
|
||||
versionSpec,
|
||||
packageManager,
|
||||
cacheDependencyPath
|
||||
)
|
||||
).rejects.toThrow(
|
||||
hashFilesSpy.mockResolvedValue('');
|
||||
|
||||
await expect(restore()).rejects.toThrow(
|
||||
'Some specified paths were not resolved, unable to cache dependencies.'
|
||||
);
|
||||
expect(restoreCacheSpy).not.toHaveBeenCalled();
|
||||
expect(setOutputSpy).toHaveBeenLastCalledWith('cache-hit', false);
|
||||
});
|
||||
|
||||
it('should inform if cache hit is not occurred', async () => {
|
||||
// Arrange
|
||||
hashFilesSpy.mockImplementation(() => Promise.resolve('file_hash'));
|
||||
restoreCacheSpy.mockImplementation(() => Promise.resolve(''));
|
||||
// Act + Assert
|
||||
it('restores modules and build outputs as separate cache entries', async () => {
|
||||
await restore();
|
||||
|
||||
const keys = requestedKeys();
|
||||
expect(keys.modules).not.toBe(keys.build);
|
||||
expect(restoreCacheSpy).toHaveBeenCalledTimes(2);
|
||||
expect(restoreCacheSpy).toHaveBeenCalledWith([modulePath], keys.modules);
|
||||
expect(restoreCacheSpy).toHaveBeenCalledWith([buildPath], keys.build);
|
||||
expect(infoSpy).toHaveBeenCalledWith('modules cache is not found');
|
||||
expect(infoSpy).toHaveBeenCalledWith('build cache is not found');
|
||||
});
|
||||
|
||||
it.each([
|
||||
{platform: 'linux', firstFails: false},
|
||||
{platform: 'linux', firstFails: true},
|
||||
{platform: 'win32', firstFails: false},
|
||||
{platform: 'win32', firstFails: true}
|
||||
])(
|
||||
'starts both restores concurrently on $platform and waits for both (first fails=$firstFails)',
|
||||
async ({platform, firstFails}) => {
|
||||
Object.defineProperty(process, 'platform', {value: platform});
|
||||
const started = [deferred(), deferred()];
|
||||
const release = [deferred(), deferred()];
|
||||
let completed = false;
|
||||
restoreCacheSpy.mockImplementation(async (paths, key) => {
|
||||
const index = paths[0] === modulePath ? 0 : 1;
|
||||
started[index].resolve();
|
||||
await release[index].promise;
|
||||
if (index === 0 && firstFails) {
|
||||
throw new Error('Module cache unavailable');
|
||||
}
|
||||
return key;
|
||||
});
|
||||
|
||||
const pending = restore().then(() => {
|
||||
completed = true;
|
||||
});
|
||||
try {
|
||||
await Promise.all(started.map(signal => signal.promise));
|
||||
release[0].resolve();
|
||||
// Let the first completion propagate while the second stays blocked.
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
expect(completed).toBe(false);
|
||||
expect(core.saveState).not.toHaveBeenCalled();
|
||||
expect(setOutputSpy).not.toHaveBeenCalledWith('cache-hit', true);
|
||||
} finally {
|
||||
release.forEach(signal => signal.resolve());
|
||||
await pending;
|
||||
}
|
||||
|
||||
expect(setOutputSpy).toHaveBeenLastCalledWith('cache-hit', !firstFails);
|
||||
expect(core.saveState).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['linux', 'win32'])(
|
||||
'restores overlapping directories sequentially on %s',
|
||||
async platform => {
|
||||
Object.defineProperty(process, 'platform', {value: platform});
|
||||
getCacheDirectoryPathSpy.mockResolvedValue([
|
||||
directories[0],
|
||||
{kind: 'build', path: path.join(modulePath, 'build')}
|
||||
]);
|
||||
const firstStarted = deferred();
|
||||
const releaseFirst = deferred();
|
||||
restoreCacheSpy.mockImplementation(async (paths, key) => {
|
||||
if (paths[0] === modulePath) {
|
||||
firstStarted.resolve();
|
||||
await releaseFirst.promise;
|
||||
}
|
||||
return key;
|
||||
});
|
||||
|
||||
const pending = restore();
|
||||
try {
|
||||
await firstStarted.promise;
|
||||
expect(restoreCacheSpy).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
releaseFirst.resolve();
|
||||
await pending;
|
||||
}
|
||||
|
||||
expect(restoreCacheSpy).toHaveBeenCalledTimes(2);
|
||||
expect(setOutputSpy).toHaveBeenLastCalledWith('cache-hit', true);
|
||||
}
|
||||
);
|
||||
|
||||
it.each([
|
||||
{modules: false, build: false},
|
||||
{modules: true, build: false},
|
||||
{modules: false, build: true},
|
||||
{modules: true, build: true}
|
||||
])(
|
||||
'reports hits and saves misses independently (modules=$modules, build=$build)',
|
||||
async hits => {
|
||||
const state = new Map<string, string>();
|
||||
(core.saveState as jest.Mock<typeof core.saveState>).mockImplementation(
|
||||
(name, value) => {
|
||||
state.set(name, JSON.stringify(value));
|
||||
}
|
||||
);
|
||||
(core.getState as jest.Mock<typeof core.getState>).mockImplementation(
|
||||
name => state.get(name) || ''
|
||||
);
|
||||
(
|
||||
core.getBooleanInput as jest.Mock<typeof core.getBooleanInput>
|
||||
).mockReturnValue(true);
|
||||
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
|
||||
restoreCacheSpy.mockImplementation(async (paths, key) =>
|
||||
hits[paths[0] === modulePath ? 'modules' : 'build'] ? key : undefined
|
||||
);
|
||||
|
||||
await restore();
|
||||
const keys = requestedKeys();
|
||||
expect(setOutputSpy).toHaveBeenLastCalledWith(
|
||||
'cache-hit',
|
||||
hits.modules && hits.build
|
||||
);
|
||||
|
||||
// Changing the Go environment later must not change the saved paths.
|
||||
process.env.GOMODCACHE = 'different_module_cache';
|
||||
process.env.GOCACHE = 'different_build_cache';
|
||||
await saveCaches();
|
||||
|
||||
for (const {kind, path} of directories) {
|
||||
if (hits[kind]) {
|
||||
expect(saveCacheSpy).not.toHaveBeenCalledWith([path], keys[kind]);
|
||||
} else {
|
||||
expect(saveCacheSpy).toHaveBeenCalledWith([path], keys[kind]);
|
||||
}
|
||||
}
|
||||
expect(saveCacheSpy).toHaveBeenCalledTimes(
|
||||
Number(!hits.modules) + Number(!hits.build)
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it('does not report a full hit for a non-primary cache match', async () => {
|
||||
restoreCacheSpy.mockImplementation(async (_paths, key) => `${key}-other`);
|
||||
|
||||
await restore();
|
||||
|
||||
expect(setOutputSpy).toHaveBeenLastCalledWith('cache-hit', false);
|
||||
});
|
||||
|
||||
it.each(directories)(
|
||||
'continues restoring when the $kind cache fails',
|
||||
async ({kind, path}) => {
|
||||
restoreCacheSpy.mockImplementation(async (paths, key) => {
|
||||
if (paths[0] === path) {
|
||||
throw new Error('Unable to reach the service');
|
||||
}
|
||||
return key;
|
||||
});
|
||||
|
||||
await restore();
|
||||
|
||||
expect(restoreCacheSpy).toHaveBeenCalledTimes(2);
|
||||
expect(core.warning).toHaveBeenCalledWith(
|
||||
`Restore ${kind} cache failed: Unable to reach the service`
|
||||
);
|
||||
expect(setOutputSpy).toHaveBeenLastCalledWith('cache-hit', false);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(directories)(
|
||||
'restores only $kind when the other directory cannot be resolved',
|
||||
async directory => {
|
||||
getCacheDirectoryPathSpy.mockResolvedValue([directory]);
|
||||
restoreCacheSpy.mockImplementation(async (_paths, key) => key);
|
||||
|
||||
await restore();
|
||||
|
||||
expect(restoreCacheSpy).toHaveBeenCalledTimes(1);
|
||||
expect(restoreCacheSpy).toHaveBeenCalledWith(
|
||||
[directory.path],
|
||||
expect.any(String)
|
||||
);
|
||||
expect(setOutputSpy).toHaveBeenLastCalledWith('cache-hit', false);
|
||||
}
|
||||
);
|
||||
|
||||
it('reuses modules across Go versions without reusing build outputs', async () => {
|
||||
await restore();
|
||||
const before = requestedKeys();
|
||||
restoreCacheSpy.mockClear();
|
||||
|
||||
await restore('1.26.1');
|
||||
const after = requestedKeys();
|
||||
|
||||
expect(after.modules).toBe(before.modules);
|
||||
expect(after.build).not.toBe(before.build);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'runner architecture',
|
||||
change: () => Object.defineProperty(process, 'arch', {value: 'arm64'})
|
||||
},
|
||||
{
|
||||
name: 'runner image',
|
||||
change: () => {
|
||||
process.env.ImageOS = 'ubuntu26';
|
||||
}
|
||||
}
|
||||
])('reuses only modules when the $name changes', async ({change}) => {
|
||||
await restore();
|
||||
const before = requestedKeys();
|
||||
restoreCacheSpy.mockClear();
|
||||
|
||||
change();
|
||||
await restore();
|
||||
const after = requestedKeys();
|
||||
|
||||
expect(after.modules).toBe(before.modules);
|
||||
expect(after.build).not.toBe(before.build);
|
||||
});
|
||||
|
||||
it('keeps both cache entries isolated by runner OS', async () => {
|
||||
await restore();
|
||||
const before = requestedKeys();
|
||||
restoreCacheSpy.mockClear();
|
||||
|
||||
process.env.RUNNER_OS = 'Windows';
|
||||
await restore();
|
||||
const after = requestedKeys();
|
||||
|
||||
expect(after.modules).not.toBe(before.modules);
|
||||
expect(after.build).not.toBe(before.build);
|
||||
});
|
||||
|
||||
it('invalidates both cache entries when the dependency hash changes', async () => {
|
||||
await restore();
|
||||
const before = requestedKeys();
|
||||
restoreCacheSpy.mockClear();
|
||||
|
||||
hashFilesSpy.mockResolvedValue('different_file_hash');
|
||||
await restore();
|
||||
const after = requestedKeys();
|
||||
|
||||
expect(after.modules).not.toBe(before.modules);
|
||||
expect(after.build).not.toBe(before.build);
|
||||
});
|
||||
|
||||
it('hashes the configured dependency paths for both cache entries', async () => {
|
||||
const dependencyPaths = 'go.sum\ntools/go.sum';
|
||||
|
||||
await cacheRestore.restoreCache(
|
||||
versionSpec,
|
||||
packageManager,
|
||||
cacheDependencyPath
|
||||
dependencyPaths
|
||||
);
|
||||
expect(infoSpy).toHaveBeenCalledWith('Cache is not found');
|
||||
});
|
||||
|
||||
it('should set output if cache hit is occurred', async () => {
|
||||
// Arrange
|
||||
hashFilesSpy.mockImplementation(() => Promise.resolve('file_hash'));
|
||||
restoreCacheSpy.mockImplementation(() => Promise.resolve('cache_key'));
|
||||
// Act + Assert
|
||||
await cacheRestore.restoreCache(
|
||||
versionSpec,
|
||||
packageManager,
|
||||
cacheDependencyPath
|
||||
);
|
||||
expect(setOutputSpy).toHaveBeenCalledWith('cache-hit', true);
|
||||
expect(hashFilesSpy).toHaveBeenCalledWith(dependencyPaths);
|
||||
expect(restoreCacheSpy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should throw if dependency file is not found in workspace', async () => {
|
||||
|
||||
+186
-72
@@ -1,3 +1,5 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
import {jest, describe, it, expect, beforeEach, afterEach} from '@jest/globals';
|
||||
|
||||
jest.unstable_mockModule('@actions/cache', () => ({
|
||||
@@ -22,26 +24,22 @@ const realFs = (await import('fs')).default;
|
||||
const fsExports = {...realFs, existsSync: jest.fn()};
|
||||
jest.unstable_mockModule('fs', () => ({...fsExports, default: fsExports}));
|
||||
|
||||
// Import real cache-utils (with mocked @actions) before mocking it
|
||||
const realCacheUtils = await import('../src/cache-utils.js');
|
||||
|
||||
jest.unstable_mockModule('../src/cache-utils.js', () => ({
|
||||
...realCacheUtils,
|
||||
getCacheDirectoryPath: jest.fn()
|
||||
}));
|
||||
|
||||
const cache = await import('@actions/cache');
|
||||
const core = await import('@actions/core');
|
||||
const fs = (await import('fs')).default;
|
||||
const cacheUtils = await import('../src/cache-utils.js');
|
||||
const {run} = await import('../src/cache-save.js');
|
||||
const {State} = await import('../src/constants.js');
|
||||
import type {CacheEntry} from '../src/cache-utils.js';
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>(done => {
|
||||
resolve = done;
|
||||
});
|
||||
return {promise, resolve};
|
||||
}
|
||||
|
||||
describe('cache-save', () => {
|
||||
const primaryKey = 'primary-key';
|
||||
|
||||
let primaryKeyValue: string;
|
||||
let matchedKeyValue: string;
|
||||
let entries: CacheEntry[];
|
||||
|
||||
let getBooleanInputSpy: jest.Mock<typeof core.getBooleanInput>;
|
||||
let getStateSpy: jest.Mock<typeof core.getState>;
|
||||
@@ -50,14 +48,21 @@ describe('cache-save', () => {
|
||||
let debugSpy: jest.Mock<typeof core.debug>;
|
||||
let setFailedSpy: jest.Mock<typeof core.setFailed>;
|
||||
let saveCacheSpy: jest.Mock<typeof cache.saveCache>;
|
||||
let getCacheDirectoryPathSpy: jest.Mock<
|
||||
typeof cacheUtils.getCacheDirectoryPath
|
||||
>;
|
||||
let existsSpy: jest.Mock<typeof fs.existsSync>;
|
||||
|
||||
beforeEach(() => {
|
||||
primaryKeyValue = primaryKey;
|
||||
matchedKeyValue = 'matched-key';
|
||||
entries = [
|
||||
{
|
||||
kind: 'modules',
|
||||
path: 'module_cache_directory',
|
||||
primaryKey: 'modules-primary-key'
|
||||
},
|
||||
{
|
||||
kind: 'build',
|
||||
path: 'build_cache_directory',
|
||||
primaryKey: 'build-primary-key'
|
||||
}
|
||||
];
|
||||
|
||||
getBooleanInputSpy = core.getBooleanInput as jest.Mock<
|
||||
typeof core.getBooleanInput
|
||||
@@ -65,15 +70,7 @@ describe('cache-save', () => {
|
||||
getBooleanInputSpy.mockReturnValue(true);
|
||||
|
||||
getStateSpy = core.getState as jest.Mock<typeof core.getState>;
|
||||
getStateSpy.mockImplementation((key: string) => {
|
||||
if (key === State.CachePrimaryKey) {
|
||||
return primaryKeyValue;
|
||||
}
|
||||
if (key === State.CacheMatchedKey) {
|
||||
return matchedKeyValue;
|
||||
}
|
||||
return '';
|
||||
});
|
||||
getStateSpy.mockImplementation(() => JSON.stringify(entries));
|
||||
|
||||
infoSpy = core.info as jest.Mock<typeof core.info>;
|
||||
infoSpy.mockImplementation(() => undefined);
|
||||
@@ -90,18 +87,12 @@ describe('cache-save', () => {
|
||||
saveCacheSpy = cache.saveCache as jest.Mock<typeof cache.saveCache>;
|
||||
saveCacheSpy.mockImplementation(() => Promise.resolve(0));
|
||||
|
||||
getCacheDirectoryPathSpy = cacheUtils.getCacheDirectoryPath as jest.Mock<
|
||||
typeof cacheUtils.getCacheDirectoryPath
|
||||
>;
|
||||
getCacheDirectoryPathSpy.mockImplementation(() =>
|
||||
Promise.resolve(['cache_directory_path', 'cache_directory_path'])
|
||||
);
|
||||
|
||||
existsSpy = fs.existsSync as jest.Mock<typeof fs.existsSync>;
|
||||
existsSpy.mockImplementation(() => true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
@@ -115,78 +106,201 @@ describe('cache-save', () => {
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'starts both saves concurrently and waits before exiting (first fails=%s)',
|
||||
async firstFails => {
|
||||
const started = [deferred(), deferred()];
|
||||
const release = [deferred(), deferred()];
|
||||
const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {
|
||||
return undefined as never;
|
||||
});
|
||||
saveCacheSpy.mockImplementation(async paths => {
|
||||
const index = paths[0] === entries[0].path ? 0 : 1;
|
||||
started[index].resolve();
|
||||
await release[index].promise;
|
||||
if (index === 0 && firstFails) {
|
||||
throw new Error('Module cache unavailable');
|
||||
}
|
||||
return 1;
|
||||
});
|
||||
|
||||
const pending = run(true);
|
||||
try {
|
||||
await Promise.all(started.map(signal => signal.promise));
|
||||
release[0].resolve();
|
||||
// Let the first completion propagate while the second stays blocked.
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
expect(exitSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
release.forEach(signal => signal.resolve());
|
||||
await pending;
|
||||
}
|
||||
|
||||
expect(exitSpy).toHaveBeenCalledTimes(1);
|
||||
expect(exitSpy).toHaveBeenCalledWith(0);
|
||||
expect(infoSpy).toHaveBeenCalledWith(
|
||||
`Cache saved with the key: ${entries[1].primaryKey}`
|
||||
);
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('does not save cache when there are no cache folders on the disk', async () => {
|
||||
existsSpy.mockImplementation(() => false);
|
||||
|
||||
await run();
|
||||
|
||||
expect(warningSpy).toHaveBeenCalledWith(
|
||||
'There are no cache folders on the disk'
|
||||
for (const {kind, path} of entries) {
|
||||
expect(infoSpy).toHaveBeenCalledWith(
|
||||
`[warning]${kind} cache folder doesn't exist on disk: ${path}`
|
||||
);
|
||||
}
|
||||
expect(saveCacheSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['modules', 'build'])(
|
||||
'saves the other cache when the %s directory is missing',
|
||||
async kind => {
|
||||
const missing = entries.find(entry => entry.kind === kind)!;
|
||||
const existing = entries.find(entry => entry.kind !== kind)!;
|
||||
existsSpy.mockImplementation(path => path !== missing.path);
|
||||
|
||||
await run();
|
||||
|
||||
expect(saveCacheSpy).toHaveBeenCalledTimes(1);
|
||||
expect(saveCacheSpy).toHaveBeenCalledWith(
|
||||
[existing.path],
|
||||
existing.primaryKey
|
||||
);
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('does not save cache when no cache entries were prepared', async () => {
|
||||
getStateSpy.mockReturnValue('');
|
||||
|
||||
await run();
|
||||
|
||||
expect(infoSpy).toHaveBeenCalledWith(
|
||||
'Cache keys were not generated. Please check the log messages above for more errors or information'
|
||||
);
|
||||
expect(saveCacheSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not save cache when the primary key was not generated', async () => {
|
||||
primaryKeyValue = '';
|
||||
it('does not fail the workflow if the saved state is invalid', async () => {
|
||||
getStateSpy.mockReturnValue('{');
|
||||
|
||||
await run();
|
||||
|
||||
expect(infoSpy).toHaveBeenCalledWith(
|
||||
'Primary key was not generated. Please check the log messages above for more errors or information'
|
||||
);
|
||||
expect(warningSpy).toHaveBeenCalledWith(expect.any(String));
|
||||
expect(saveCacheSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not save cache when a cache hit occurred on the primary key', async () => {
|
||||
matchedKeyValue = primaryKey;
|
||||
it('does not save either cache when both primary keys were hit', async () => {
|
||||
for (const entry of entries) {
|
||||
entry.matchedKey = entry.primaryKey;
|
||||
}
|
||||
|
||||
await run();
|
||||
|
||||
expect(infoSpy).toHaveBeenCalledWith(
|
||||
`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`
|
||||
);
|
||||
expect(saveCacheSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('saves cache when the primary key differs from the matched key', async () => {
|
||||
await run();
|
||||
|
||||
expect(saveCacheSpy).toHaveBeenCalled();
|
||||
expect(infoSpy).toHaveBeenCalledWith(
|
||||
`Cache saved with the key: ${primaryKey}`
|
||||
);
|
||||
expect(warningSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('save with -1 cacheId , should not fail workflow', async () => {
|
||||
saveCacheSpy.mockImplementation(() => Promise.resolve(-1));
|
||||
it.each(['modules', 'build'])(
|
||||
'skips only the %s cache when its primary key was hit',
|
||||
async kind => {
|
||||
const hit = entries.find(entry => entry.kind === kind)!;
|
||||
const miss = entries.find(entry => entry.kind !== kind)!;
|
||||
hit.matchedKey = hit.primaryKey;
|
||||
|
||||
await run();
|
||||
|
||||
expect(saveCacheSpy).toHaveBeenCalledTimes(1);
|
||||
expect(saveCacheSpy).toHaveBeenCalledWith([miss.path], miss.primaryKey);
|
||||
expect(warningSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('saves both cache directories under separate keys on a cold run', async () => {
|
||||
await run();
|
||||
|
||||
expect(saveCacheSpy).toHaveBeenCalled();
|
||||
expect(debugSpy).toHaveBeenCalledWith(
|
||||
`Cache was not saved for the key: ${primaryKey}`
|
||||
);
|
||||
expect(infoSpy).not.toHaveBeenCalledWith(
|
||||
`Cache saved with the key: ${primaryKey}`
|
||||
);
|
||||
expect(saveCacheSpy).toHaveBeenCalledTimes(2);
|
||||
for (const {path, primaryKey} of entries) {
|
||||
expect(saveCacheSpy).toHaveBeenCalledWith([path], primaryKey);
|
||||
expect(infoSpy).toHaveBeenCalledWith(
|
||||
`Cache saved with the key: ${primaryKey}`
|
||||
);
|
||||
}
|
||||
expect(warningSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('saves with error from toolkit, should not fail workflow', async () => {
|
||||
saveCacheSpy.mockImplementation(() =>
|
||||
Promise.reject(new Error('Unable to reach the service'))
|
||||
);
|
||||
it('saves caches restored from non-primary matches', async () => {
|
||||
for (const entry of entries) {
|
||||
entry.matchedKey = `${entry.primaryKey}-other`;
|
||||
}
|
||||
|
||||
await run();
|
||||
|
||||
expect(saveCacheSpy).toHaveBeenCalled();
|
||||
expect(warningSpy).toHaveBeenCalledWith('Unable to reach the service');
|
||||
expect(saveCacheSpy).toHaveBeenCalledTimes(2);
|
||||
expect(warningSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['modules', 'build'])(
|
||||
'continues saving when the %s cache reservation fails',
|
||||
async kind => {
|
||||
const failed = entries.find(entry => entry.kind === kind)!;
|
||||
const saved = entries.find(entry => entry.kind !== kind)!;
|
||||
saveCacheSpy.mockImplementation(async paths =>
|
||||
paths[0] === failed.path ? -1 : 1
|
||||
);
|
||||
|
||||
await run();
|
||||
|
||||
expect(saveCacheSpy).toHaveBeenCalledTimes(2);
|
||||
expect(debugSpy).toHaveBeenCalledWith(
|
||||
`Cache was not saved for the key: ${failed.primaryKey}`
|
||||
);
|
||||
expect(infoSpy).not.toHaveBeenCalledWith(
|
||||
`Cache saved with the key: ${failed.primaryKey}`
|
||||
);
|
||||
expect(infoSpy).toHaveBeenCalledWith(
|
||||
`Cache saved with the key: ${saved.primaryKey}`
|
||||
);
|
||||
expect(warningSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['modules', 'build'])(
|
||||
'continues saving when the %s cache upload throws',
|
||||
async kind => {
|
||||
const failed = entries.find(entry => entry.kind === kind)!;
|
||||
const saved = entries.find(entry => entry.kind !== kind)!;
|
||||
saveCacheSpy.mockImplementation(async paths => {
|
||||
if (paths[0] === failed.path) {
|
||||
throw new Error('Unable to reach the service');
|
||||
}
|
||||
return 1;
|
||||
});
|
||||
|
||||
await run();
|
||||
|
||||
expect(saveCacheSpy).toHaveBeenCalledTimes(2);
|
||||
expect(warningSpy).toHaveBeenCalledWith(
|
||||
`Save ${kind} cache failed: Unable to reach the service`
|
||||
);
|
||||
expect(infoSpy).toHaveBeenCalledWith(
|
||||
`Cache saved with the key: ${saved.primaryKey}`
|
||||
);
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
});
|
||||
+196
-21
@@ -1,4 +1,14 @@
|
||||
import {jest, describe, it, expect, beforeEach, afterAll} from '@jest/globals';
|
||||
import {
|
||||
jest,
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
afterAll
|
||||
} from '@jest/globals';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
jest.unstable_mockModule('@actions/exec', () => ({
|
||||
exec: jest.fn(),
|
||||
@@ -84,7 +94,10 @@ describe('getPackageManagerInfo', () => {
|
||||
const packageManagerName = 'default';
|
||||
const expectedResult = {
|
||||
dependencyFilePattern: 'go.mod',
|
||||
cacheFolderCommandList: ['go env GOMODCACHE', 'go env GOCACHE']
|
||||
cacheFolderCommandList: [
|
||||
{kind: 'modules', command: 'go env GOMODCACHE'},
|
||||
{kind: 'build', command: 'go env GOCACHE'}
|
||||
]
|
||||
};
|
||||
|
||||
//Act + Assert
|
||||
@@ -112,16 +125,29 @@ describe('getCacheDirectoryPath', () => {
|
||||
|
||||
const validPackageManager: PackageManagerInfo = {
|
||||
dependencyFilePattern: 'go.mod',
|
||||
cacheFolderCommandList: ['go env GOMODCACHE', 'go env GOCACHE']
|
||||
cacheFolderCommandList: [
|
||||
{kind: 'modules', command: 'go env GOMODCACHE'},
|
||||
{kind: 'build', command: 'go env GOCACHE'}
|
||||
]
|
||||
};
|
||||
|
||||
it('should return path to the cache folders which specified package manager uses', async () => {
|
||||
//Arrange
|
||||
getExecOutputSpy.mockImplementation(async (commandLine: string) => {
|
||||
return {exitCode: 0, stdout: 'path/to/cache/folder', stderr: ''};
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout:
|
||||
commandLine === 'go env GOMODCACHE'
|
||||
? 'path/to/modules'
|
||||
: 'path/to/build',
|
||||
stderr: ''
|
||||
};
|
||||
});
|
||||
|
||||
const expectedResult = ['path/to/cache/folder', 'path/to/cache/folder'];
|
||||
const expectedResult = [
|
||||
{kind: 'modules', path: 'path/to/modules'},
|
||||
{kind: 'build', path: 'path/to/build'}
|
||||
];
|
||||
|
||||
//Act + Assert
|
||||
return cacheUtils
|
||||
@@ -129,27 +155,43 @@ describe('getCacheDirectoryPath', () => {
|
||||
.then(data => expect(data).toEqual(expectedResult));
|
||||
});
|
||||
|
||||
it('should return path to the cache folder if one command return empty str', async () => {
|
||||
//Arrange
|
||||
getExecOutputSpy.mockImplementationOnce(async (commandLine: string) => {
|
||||
return {exitCode: 0, stdout: 'path/to/cache/folder', stderr: ''};
|
||||
});
|
||||
it.each(validPackageManager.cacheFolderCommandList)(
|
||||
'preserves the $kind identity when the other command returns an empty path',
|
||||
async ({kind, command}) => {
|
||||
getExecOutputSpy.mockImplementation(async commandLine => ({
|
||||
exitCode: 0,
|
||||
stdout: commandLine === command ? 'path/to/cache/folder' : '',
|
||||
stderr: ''
|
||||
}));
|
||||
|
||||
getExecOutputSpy.mockImplementationOnce(async (commandLine: string) => {
|
||||
return {exitCode: 0, stdout: '', stderr: ''};
|
||||
});
|
||||
await expect(
|
||||
cacheUtils.getCacheDirectoryPath(validPackageManager)
|
||||
).resolves.toEqual([{kind, path: 'path/to/cache/folder'}]);
|
||||
}
|
||||
);
|
||||
|
||||
const expectedResult = ['path/to/cache/folder'];
|
||||
it.each(validPackageManager.cacheFolderCommandList)(
|
||||
'preserves the $kind identity when the other command fails',
|
||||
async ({kind, command}) => {
|
||||
getExecOutputSpy.mockImplementation(async commandLine => {
|
||||
if (commandLine !== command) {
|
||||
throw new Error('Could not run go env');
|
||||
}
|
||||
return {exitCode: 0, stdout: 'path/to/cache/folder', stderr: ''};
|
||||
});
|
||||
|
||||
//Act + Assert
|
||||
return cacheUtils
|
||||
.getCacheDirectoryPath(validPackageManager)
|
||||
.then(data => expect(data).toEqual(expectedResult));
|
||||
});
|
||||
await expect(
|
||||
cacheUtils.getCacheDirectoryPath(validPackageManager)
|
||||
).resolves.toEqual([{kind, path: 'path/to/cache/folder'}]);
|
||||
expect(core.info).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Could not run go env')
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it('should throw if the both commands return empty str', async () => {
|
||||
getExecOutputSpy.mockImplementation(async (commandLine: string) => {
|
||||
return {exitCode: 10, stdout: '', stderr: ''};
|
||||
return {exitCode: 0, stdout: '', stderr: ''};
|
||||
});
|
||||
|
||||
//Act + Assert
|
||||
@@ -158,7 +200,7 @@ describe('getCacheDirectoryPath', () => {
|
||||
}).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('should throw if the specified package name is invalid', async () => {
|
||||
it('should throw if both commands fail', async () => {
|
||||
getExecOutputSpy.mockImplementation(async (commandLine: string) => {
|
||||
return {exitCode: 10, stdout: '', stderr: 'Error message'};
|
||||
});
|
||||
@@ -170,6 +212,139 @@ describe('getCacheDirectoryPath', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('canRestoreCachesInParallel', () => {
|
||||
const originalPlatform = Object.getOwnPropertyDescriptor(
|
||||
process,
|
||||
'platform'
|
||||
)!;
|
||||
const directoryStat = fs.lstatSync(process.cwd());
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(process, 'platform', {value: 'linux'});
|
||||
jest.spyOn(fs, 'lstatSync').mockReturnValue(directoryStat);
|
||||
jest
|
||||
.spyOn(fs, 'realpathSync')
|
||||
.mockImplementation(directory => path.resolve(directory.toString()));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process, 'platform', originalPlatform);
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{modules: 'cache/modules', build: 'cache/build', parallel: true},
|
||||
{modules: 'cache', build: 'cache-build', parallel: true},
|
||||
{modules: 'cache', build: 'cache', parallel: false},
|
||||
{modules: 'cache', build: 'cache/build', parallel: false},
|
||||
{modules: 'cache/modules', build: 'cache', parallel: false},
|
||||
{modules: 'cache', build: 'cache/../cache', parallel: false}
|
||||
])(
|
||||
'checks overlapping paths: $modules and $build',
|
||||
({modules, build, parallel}) => {
|
||||
expect(
|
||||
cacheUtils.canRestoreCachesInParallel([
|
||||
{kind: 'modules', path: modules},
|
||||
{kind: 'build', path: build}
|
||||
])
|
||||
).toBe(parallel);
|
||||
}
|
||||
);
|
||||
|
||||
it('allows concurrent Windows restores with disjoint paths', () => {
|
||||
Object.defineProperty(process, 'platform', {value: 'win32'});
|
||||
|
||||
expect(
|
||||
cacheUtils.canRestoreCachesInParallel([
|
||||
{kind: 'modules', path: 'cache/modules'},
|
||||
{kind: 'build', path: 'cache/build'}
|
||||
])
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it.each(['darwin', 'win32'])(
|
||||
'handles case-insensitive paths conservatively on %s',
|
||||
platform => {
|
||||
Object.defineProperty(process, 'platform', {value: platform});
|
||||
|
||||
expect(
|
||||
cacheUtils.canRestoreCachesInParallel([
|
||||
{kind: 'modules', path: 'cache'},
|
||||
{kind: 'build', path: 'CACHE/build'}
|
||||
])
|
||||
).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
it.each([true, false])(
|
||||
'serializes symlink aliases with missing cache directories (overlap=%s)',
|
||||
overlap => {
|
||||
const alias = path.resolve('alias');
|
||||
const target = path.resolve('target');
|
||||
jest.spyOn(fs, 'lstatSync').mockImplementation(directory => {
|
||||
if (directory !== alias && directory !== target) {
|
||||
throw Object.assign(new Error('Missing path'), {code: 'ENOENT'});
|
||||
}
|
||||
return directoryStat;
|
||||
});
|
||||
jest.spyOn(fs, 'realpathSync').mockReturnValue(target);
|
||||
|
||||
expect(
|
||||
cacheUtils.canRestoreCachesInParallel([
|
||||
{kind: 'modules', path: path.join(alias, 'modules')},
|
||||
{
|
||||
kind: 'build',
|
||||
path: path.join(target, overlap ? 'modules/build' : 'build')
|
||||
}
|
||||
])
|
||||
).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['nested alias', 'alias through module cache'])(
|
||||
'serializes restores when the %s resolves outside the module cache',
|
||||
scenario => {
|
||||
const modules = path.resolve('modules');
|
||||
const target = path.resolve('external-build');
|
||||
const alias = path.join(modules, 'build-link');
|
||||
const build =
|
||||
scenario === 'nested alias'
|
||||
? path.join(alias, 'cache')
|
||||
: path.resolve('build-alias', 'cache');
|
||||
jest.spyOn(fs, 'realpathSync').mockImplementation(directory => {
|
||||
const absolute = path.resolve(directory.toString());
|
||||
if (absolute === build) {
|
||||
return path.join(target, 'cache');
|
||||
}
|
||||
if (absolute === path.dirname(build)) {
|
||||
return scenario === 'nested alias' ? target : alias;
|
||||
}
|
||||
return absolute;
|
||||
});
|
||||
|
||||
expect(
|
||||
cacheUtils.canRestoreCachesInParallel([
|
||||
{kind: 'modules', path: modules},
|
||||
{kind: 'build', path: build}
|
||||
])
|
||||
).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
it('falls back to sequential restores when path resolution fails', () => {
|
||||
jest.spyOn(fs, 'realpathSync').mockImplementation(() => {
|
||||
throw new Error('Cannot resolve path');
|
||||
});
|
||||
|
||||
expect(
|
||||
cacheUtils.canRestoreCachesInParallel([
|
||||
{kind: 'modules', path: 'cache/modules'},
|
||||
{kind: 'build', path: 'cache/build'}
|
||||
])
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isCacheFeatureAvailable', () => {
|
||||
//Arrange
|
||||
const isFeatureAvailableSpy = cache.isFeatureAvailable as jest.Mock<
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ outputs:
|
||||
go-version:
|
||||
description: 'The installed Go version. Useful when given a version range as input.'
|
||||
cache-hit:
|
||||
description: 'A boolean value to indicate if a cache was hit'
|
||||
description: 'A boolean value indicating whether both module and build cache entries were restored on their primary keys'
|
||||
GOPATH:
|
||||
description: 'The value of `go env GOPATH`.'
|
||||
GOBIN:
|
||||
|
||||
Vendored
+24
-89
@@ -40669,8 +40669,8 @@ function getExecOutput(commandLine, args, options) {
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
//Using string decoder covers the case where a mult-byte character is split
|
||||
const stdoutDecoder = new external_string_decoder_.StringDecoder('utf8');
|
||||
const stderrDecoder = new external_string_decoder_.StringDecoder('utf8');
|
||||
const stdoutDecoder = new StringDecoder('utf8');
|
||||
const stderrDecoder = new StringDecoder('utf8');
|
||||
const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout;
|
||||
const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr;
|
||||
const stdErrListener = (data) => {
|
||||
@@ -96210,8 +96210,7 @@ function saveCacheV2(paths_1, key_1, options_1) {
|
||||
;// CONCATENATED MODULE: ./src/constants.ts
|
||||
var State;
|
||||
(function (State) {
|
||||
State["CachePrimaryKey"] = "CACHE_KEY";
|
||||
State["CacheMatchedKey"] = "CACHE_RESULT";
|
||||
State["CacheEntries"] = "CACHE_ENTRIES";
|
||||
})(State || (State = {}));
|
||||
var Outputs;
|
||||
(function (Outputs) {
|
||||
@@ -96229,79 +96228,11 @@ const GO_ENV_OUTPUTS = (/* unused pure expression or super */ null && ([
|
||||
'GOTOOLDIR'
|
||||
]));
|
||||
|
||||
;// CONCATENATED MODULE: ./src/package-managers.ts
|
||||
const supportedPackageManagers = {
|
||||
default: {
|
||||
dependencyFilePattern: 'go.mod',
|
||||
cacheFolderCommandList: ['go env GOMODCACHE', 'go env GOCACHE']
|
||||
}
|
||||
};
|
||||
|
||||
;// CONCATENATED MODULE: ./src/cache-utils.ts
|
||||
|
||||
|
||||
|
||||
|
||||
const getCommandOutput = async (toolCommand) => {
|
||||
let { stdout, stderr, exitCode } = await getExecOutput(toolCommand, undefined, { ignoreReturnCode: true });
|
||||
if (exitCode) {
|
||||
stderr = !stderr.trim()
|
||||
? `The '${toolCommand}' command failed with exit code: ${exitCode}`
|
||||
: stderr;
|
||||
throw new Error(stderr);
|
||||
}
|
||||
return stdout.trim();
|
||||
};
|
||||
const getPackageManagerInfo = async (packageManager) => {
|
||||
if (!supportedPackageManagers[packageManager]) {
|
||||
throw new Error(`It's not possible to use ${packageManager}, please, check correctness of the package manager name spelling.`);
|
||||
}
|
||||
const obtainedPackageManager = supportedPackageManagers[packageManager];
|
||||
return obtainedPackageManager;
|
||||
};
|
||||
const getCacheDirectoryPath = async (packageManagerInfo) => {
|
||||
const pathOutputs = await Promise.allSettled(packageManagerInfo.cacheFolderCommandList.map(async (command) => getCommandOutput(command)));
|
||||
const results = pathOutputs.map(item => {
|
||||
if (item.status === 'fulfilled') {
|
||||
return item.value;
|
||||
}
|
||||
else {
|
||||
info(`[warning]getting cache directory path failed: ${item.reason}`);
|
||||
}
|
||||
return '';
|
||||
});
|
||||
const cachePaths = results.filter(item => item);
|
||||
if (!cachePaths.length) {
|
||||
throw new Error(`Could not get cache folder paths.`);
|
||||
}
|
||||
return cachePaths;
|
||||
};
|
||||
function cache_utils_isGhes() {
|
||||
const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com');
|
||||
const hostname = ghUrl.hostname.trimEnd().toUpperCase();
|
||||
const isGitHubHost = hostname === 'GITHUB.COM';
|
||||
const isGitHubEnterpriseCloudHost = hostname.endsWith('.GHE.COM');
|
||||
const isLocalHost = hostname.endsWith('.LOCALHOST');
|
||||
return !isGitHubHost && !isGitHubEnterpriseCloudHost && !isLocalHost;
|
||||
}
|
||||
function isCacheFeatureAvailable() {
|
||||
if (cache.isFeatureAvailable()) {
|
||||
return true;
|
||||
}
|
||||
if (cache_utils_isGhes()) {
|
||||
core.warning('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.');
|
||||
return false;
|
||||
}
|
||||
core.warning('The runner was not able to contact the cache service. Caching will be skipped');
|
||||
return false;
|
||||
}
|
||||
|
||||
;// CONCATENATED MODULE: ./src/cache-save.ts
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in
|
||||
// @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to
|
||||
// throw an uncaught exception. Instead of failing this action, just warn.
|
||||
@@ -96334,28 +96265,32 @@ async function run(earlyExit) {
|
||||
}
|
||||
}
|
||||
const cachePackages = async () => {
|
||||
const packageManager = 'default';
|
||||
const state = getState(State.CacheMatchedKey);
|
||||
const primaryKey = getState(State.CachePrimaryKey);
|
||||
const packageManagerInfo = await getPackageManagerInfo(packageManager);
|
||||
const cachePaths = await getCacheDirectoryPath(packageManagerInfo);
|
||||
const nonExistingPaths = cachePaths.filter(cachePath => !external_fs_default().existsSync(cachePath));
|
||||
if (nonExistingPaths.length === cachePaths.length) {
|
||||
warning('There are no cache folders on the disk');
|
||||
const entries = JSON.parse(getState(State.CacheEntries) || '[]');
|
||||
if (!entries.length) {
|
||||
info('Cache keys were not generated. Please check the log messages above for more errors or information');
|
||||
return;
|
||||
}
|
||||
if (nonExistingPaths.length) {
|
||||
logWarning(`Cache folder path is retrieved but doesn't exist on disk: ${nonExistingPaths.join(', ')}`);
|
||||
}
|
||||
if (!primaryKey) {
|
||||
info('Primary key was not generated. Please check the log messages above for more errors or information');
|
||||
return;
|
||||
}
|
||||
if (primaryKey === state) {
|
||||
await Promise.all(entries.map(async (entry) => {
|
||||
try {
|
||||
await saveCacheEntry(entry);
|
||||
}
|
||||
catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
warning(`Save ${entry.kind} cache failed: ${message}`);
|
||||
}
|
||||
}));
|
||||
};
|
||||
const saveCacheEntry = async (entry) => {
|
||||
const { kind, path, primaryKey, matchedKey } = entry;
|
||||
if (primaryKey === matchedKey) {
|
||||
info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`);
|
||||
return;
|
||||
}
|
||||
const cacheId = await cache_saveCache(cachePaths, primaryKey);
|
||||
if (!external_fs_default().existsSync(path)) {
|
||||
logWarning(`${kind} cache folder doesn't exist on disk: ${path}`);
|
||||
return;
|
||||
}
|
||||
const cacheId = await cache_saveCache([path], primaryKey);
|
||||
if (cacheId === -1) {
|
||||
// saveCache returns -1 without throwing when the cache was not saved, e.g.
|
||||
// a reserve collision or a read-only token (fork PR). @actions/cache has
|
||||
|
||||
Vendored
+108
-20
@@ -97543,8 +97543,7 @@ function saveCacheV2(paths_1, key_1, options_1) {
|
||||
;// CONCATENATED MODULE: ./src/constants.ts
|
||||
var State;
|
||||
(function (State) {
|
||||
State["CachePrimaryKey"] = "CACHE_KEY";
|
||||
State["CacheMatchedKey"] = "CACHE_RESULT";
|
||||
State["CacheEntries"] = "CACHE_ENTRIES";
|
||||
})(State || (State = {}));
|
||||
var Outputs;
|
||||
(function (Outputs) {
|
||||
@@ -97566,7 +97565,10 @@ const GO_ENV_OUTPUTS = [
|
||||
const supportedPackageManagers = {
|
||||
default: {
|
||||
dependencyFilePattern: 'go.mod',
|
||||
cacheFolderCommandList: ['go env GOMODCACHE', 'go env GOCACHE']
|
||||
cacheFolderCommandList: [
|
||||
{ kind: 'modules', command: 'go env GOMODCACHE' },
|
||||
{ kind: 'build', command: 'go env GOCACHE' }
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
@@ -97575,6 +97577,8 @@ const supportedPackageManagers = {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const getCommandOutput = async (toolCommand) => {
|
||||
let { stdout, stderr, exitCode } = await getExecOutput(toolCommand, undefined, { ignoreReturnCode: true });
|
||||
if (exitCode) {
|
||||
@@ -97593,22 +97597,78 @@ const getPackageManagerInfo = async (packageManager) => {
|
||||
return obtainedPackageManager;
|
||||
};
|
||||
const getCacheDirectoryPath = async (packageManagerInfo) => {
|
||||
const pathOutputs = await Promise.allSettled(packageManagerInfo.cacheFolderCommandList.map(async (command) => getCommandOutput(command)));
|
||||
const results = pathOutputs.map(item => {
|
||||
const pathOutputs = await Promise.allSettled(packageManagerInfo.cacheFolderCommandList.map(async ({ kind, command }) => ({
|
||||
kind,
|
||||
path: await getCommandOutput(command)
|
||||
})));
|
||||
const cachePaths = [];
|
||||
for (const item of pathOutputs) {
|
||||
if (item.status === 'fulfilled') {
|
||||
return item.value;
|
||||
if (item.value.path) {
|
||||
cachePaths.push(item.value);
|
||||
}
|
||||
}
|
||||
else {
|
||||
core_info(`[warning]getting cache directory path failed: ${item.reason}`);
|
||||
}
|
||||
return '';
|
||||
});
|
||||
const cachePaths = results.filter(item => item);
|
||||
}
|
||||
if (!cachePaths.length) {
|
||||
throw new Error(`Could not get cache folder paths.`);
|
||||
}
|
||||
return cachePaths;
|
||||
};
|
||||
function canRestoreCachesInParallel(directories) {
|
||||
try {
|
||||
const paths = directories.map(directory => {
|
||||
const resolvedPath = resolveCachePath(directory.path);
|
||||
// Conservatively handle case-insensitive Windows/macOS filesystems.
|
||||
return process.platform === 'darwin' || process.platform === 'win32'
|
||||
? resolvedPath.toLowerCase()
|
||||
: resolvedPath;
|
||||
});
|
||||
// A cache archive can replace symlinks traversed by the other restore.
|
||||
// Canonical destinations alone do not capture that extraction footprint.
|
||||
if (paths.some((resolvedPath, index) => {
|
||||
const absolutePath = external_path_default().resolve(directories[index].path);
|
||||
const normalizedPath = process.platform === 'darwin' || process.platform === 'win32'
|
||||
? absolutePath.toLowerCase()
|
||||
: absolutePath;
|
||||
return resolvedPath !== normalizedPath;
|
||||
})) {
|
||||
return false;
|
||||
}
|
||||
return paths.every((parent, index) => paths.every((child, otherIndex) => {
|
||||
if (index === otherIndex) {
|
||||
return true;
|
||||
}
|
||||
const relative = external_path_default().relative(parent, child);
|
||||
return (relative === '..' ||
|
||||
relative.startsWith(`..${(external_path_default()).sep}`) ||
|
||||
external_path_default().isAbsolute(relative));
|
||||
}));
|
||||
}
|
||||
catch {
|
||||
// If the paths cannot be resolved safely, avoid concurrent extraction.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function resolveCachePath(directory) {
|
||||
const absolutePath = external_path_default().resolve(directory);
|
||||
try {
|
||||
external_fs_default().lstatSync(absolutePath);
|
||||
}
|
||||
catch (error) {
|
||||
const parent = external_path_default().dirname(absolutePath);
|
||||
if (error.code !== 'ENOENT' ||
|
||||
parent === absolutePath) {
|
||||
throw error;
|
||||
}
|
||||
// Cold cache directories may not exist yet. Resolve their existing
|
||||
// ancestors so symlink aliases still participate in the overlap check.
|
||||
return external_path_default().join(resolveCachePath(parent), external_path_default().basename(absolutePath));
|
||||
}
|
||||
return external_fs_default().realpathSync(absolutePath);
|
||||
}
|
||||
function cache_utils_isGhes() {
|
||||
const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com');
|
||||
const hostname = ghUrl.hostname.trimEnd().toUpperCase();
|
||||
@@ -97638,6 +97698,7 @@ function isCacheFeatureAvailable() {
|
||||
|
||||
|
||||
const cache_restore_restoreCache = async (versionSpec, packageManager, cacheDependencyPath) => {
|
||||
setOutput(Outputs.CacheHit, false);
|
||||
const packageManagerInfo = await getPackageManagerInfo(packageManager);
|
||||
const platform = process.env.RUNNER_OS;
|
||||
const arch = process.arch;
|
||||
@@ -97650,18 +97711,45 @@ const cache_restore_restoreCache = async (versionSpec, packageManager, cacheDepe
|
||||
throw new Error('Some specified paths were not resolved, unable to cache dependencies.');
|
||||
}
|
||||
const linuxVersion = process.env.RUNNER_OS === 'Linux' ? `${process.env.ImageOS}-` : '';
|
||||
const primaryKey = `setup-go-${platform}-${arch}-${linuxVersion}go-${versionSpec}-${fileHash}`;
|
||||
core_debug(`primary key is ${primaryKey}`);
|
||||
saveState(State.CachePrimaryKey, primaryKey);
|
||||
const cacheKey = await restoreCache(cachePaths, primaryKey);
|
||||
setOutput(Outputs.CacheHit, Boolean(cacheKey));
|
||||
if (!cacheKey) {
|
||||
core_info(`Cache is not found`);
|
||||
setOutput(Outputs.CacheHit, false);
|
||||
return;
|
||||
const primaryKeys = {
|
||||
// Downloaded module sources can be reused across Go versions and runner
|
||||
// architectures. Keep OS isolation for filesystem compatibility.
|
||||
modules: `setup-go-modules-${platform}-${fileHash}`,
|
||||
build: `setup-go-build-${platform}-${arch}-${linuxVersion}go-${versionSpec}-${fileHash}`
|
||||
};
|
||||
const entries = cachePaths.map(directory => ({
|
||||
...directory,
|
||||
primaryKey: primaryKeys[directory.kind]
|
||||
}));
|
||||
const restoreEntry = async (entry) => {
|
||||
core_debug(`${entry.kind} primary key is ${entry.primaryKey}`);
|
||||
try {
|
||||
entry.matchedKey = await restoreCache([entry.path], entry.primaryKey);
|
||||
if (entry.matchedKey) {
|
||||
core_info(`${entry.kind} cache restored from key: ${entry.matchedKey}`);
|
||||
}
|
||||
else {
|
||||
core_info(`${entry.kind} cache is not found`);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
warning(`Restore ${entry.kind} cache failed: ${message}`);
|
||||
}
|
||||
};
|
||||
if (canRestoreCachesInParallel(entries)) {
|
||||
await Promise.all(entries.map(restoreEntry));
|
||||
}
|
||||
saveState(State.CacheMatchedKey, cacheKey);
|
||||
core_info(`Cache restored from key: ${cacheKey}`);
|
||||
else {
|
||||
for (const entry of entries) {
|
||||
await restoreEntry(entry);
|
||||
}
|
||||
}
|
||||
// Preserve the resolved paths so the post step uses the same cache versions,
|
||||
// even if a later step changes the Go environment.
|
||||
saveState(State.CacheEntries, entries);
|
||||
setOutput(Outputs.CacheHit, entries.length === packageManagerInfo.cacheFolderCommandList.length &&
|
||||
entries.every(entry => entry.matchedKey === entry.primaryKey));
|
||||
};
|
||||
const findDependencyFile = (packageManager) => {
|
||||
const dependencyFile = packageManager.dependencyFilePattern;
|
||||
|
||||
+27
-13
@@ -240,7 +240,16 @@ steps:
|
||||
```
|
||||
|
||||
## Caching
|
||||
|
||||
|
||||
The action restores and saves two independent cache entries:
|
||||
|
||||
- **Module sources (`GOMODCACHE`)**: keyed by the runner OS and dependency-file hash. These sources can be reused across Go versions, runner architectures, and runner images on the same OS.
|
||||
- **Build outputs (`GOCACHE`)**: keyed by the runner OS, runner architecture, Linux runner image (when applicable), Go version, and dependency-file hash.
|
||||
|
||||
Both entries use the hash of `cache-dependency-path`, or the root `go.mod` by default. Adding source files or build settings to that input invalidates both entries when those files change. Custom cache locations and the cache service's normal access restrictions still apply.
|
||||
|
||||
Each entry is restored and saved independently, with concurrent transfers where safe. An exact hit is not uploaded again, even when the other entry misses. A failure for one entry does not prevent caching the other. The `cache-hit` output is `true` only when both entries are restored on their primary keys.
|
||||
|
||||
### Caching in monorepos
|
||||
|
||||
```yaml
|
||||
@@ -281,7 +290,7 @@ steps:
|
||||
|
||||
### Multi-target builds
|
||||
|
||||
`cache-dependency-path` isn’t limited to dependency files (like `go.sum`). It can also include files that capture build settings (for example, `GOOS`/`GOARCH`). This allows separate caches per target platform (OS/architecture) and helps avoid reusing caches across incompatible builds.
|
||||
`GOOS` and `GOARCH` are not automatically included in the cache keys. `cache-dependency-path` isn’t limited to dependency files (like `go.sum`); it can also include files that capture these build settings. This prevents jobs for different targets from competing to populate the same immutable cache entry. Because both entries use the same dependency-file hash, this workaround separates the module cache as well as the build cache.
|
||||
|
||||
```yaml
|
||||
env:
|
||||
@@ -289,16 +298,15 @@ env:
|
||||
GOARCH: ...
|
||||
|
||||
steps:
|
||||
- run: echo "$GOOS $GOARCH" > env.txt
|
||||
|
||||
- uses: actions/checkout@v7
|
||||
- run: echo "$GOOS $GOARCH" > env.txt
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.25'
|
||||
cache-dependency-path: |
|
||||
go.sum
|
||||
env.txt
|
||||
- run: go run hello.go
|
||||
- run: go build ./...
|
||||
```
|
||||
|
||||
### Cache invalidation on source changes
|
||||
@@ -365,20 +373,26 @@ jobs:
|
||||
if: runner.os == 'Linux'
|
||||
shell: bash
|
||||
run: echo "CACHE_OS_SUFFIX=$ImageOS-" >> $GITHUB_ENV
|
||||
- name: Restore Go cache
|
||||
id: go-cache
|
||||
- name: Restore Go module cache
|
||||
id: go-module-cache
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: |
|
||||
${{ env.GO_MOD_CACHE }}
|
||||
${{ env.GO_BUILD_CACHE }}
|
||||
key: setup-go-${{ runner.os }}-${{ env.ARCH }}-${{ env.CACHE_OS_SUFFIX }}go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('**/go.mod') }}
|
||||
path: ${{ env.GO_MOD_CACHE }}
|
||||
key: setup-go-modules-${{ runner.os }}-${{ hashFiles('go.mod') }}
|
||||
- name: Restore Go build cache
|
||||
id: go-build-cache
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: ${{ env.GO_BUILD_CACHE }}
|
||||
key: setup-go-build-${{ runner.os }}-${{ env.ARCH }}-${{ env.CACHE_OS_SUFFIX }}go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod') }}
|
||||
- name: Download modules
|
||||
run: go mod download
|
||||
- name: Build
|
||||
run: go build ./...
|
||||
```
|
||||
|
||||
Use the same file patterns in `hashFiles` as the `cache-dependency-path` of the workflow that saves the caches. The example above matches the default root `go.mod` input.
|
||||
|
||||
> If there are several builds on the same repo, it may make sense to create a cache in one build and use it in others. The action [actions/cache/restore](https://github.com/actions/cache/tree/main/restore#only-restore-cache)
|
||||
should be used in this case.
|
||||
|
||||
@@ -407,7 +421,7 @@ jobs:
|
||||
|
||||
### `cache-hit`
|
||||
|
||||
**cache-hit** output is available with a boolean value that indicates whether a cache hit occurred on the primary key:
|
||||
**cache-hit** is `true` only when both the module cache and the build cache are restored on their primary keys. If only one entry hits its primary key, the output is `false`, but that entry is still used and is not saved again. An entry restored from a non-primary key can still be saved under its primary key:
|
||||
|
||||
```yaml
|
||||
jobs:
|
||||
@@ -420,7 +434,7 @@ jobs:
|
||||
with:
|
||||
go-version: '1.24'
|
||||
cache: true
|
||||
- run: echo "Was the Go cache restored? ${{ steps.go124.outputs.cache-hit }}" # true if cache-hit occurred
|
||||
- run: echo "Were both Go caches restored? ${{ steps.go124.outputs.cache-hit }}"
|
||||
```
|
||||
|
||||
### Go environment outputs
|
||||
|
||||
+48
-13
@@ -6,13 +6,19 @@ import fs from 'fs';
|
||||
|
||||
import {State, Outputs} from './constants.js';
|
||||
import {PackageManagerInfo} from './package-managers.js';
|
||||
import {getCacheDirectoryPath, getPackageManagerInfo} from './cache-utils.js';
|
||||
import {
|
||||
CacheEntry,
|
||||
canRestoreCachesInParallel,
|
||||
getCacheDirectoryPath,
|
||||
getPackageManagerInfo
|
||||
} from './cache-utils.js';
|
||||
|
||||
export const restoreCache = async (
|
||||
versionSpec: string,
|
||||
packageManager: string,
|
||||
cacheDependencyPath?: string
|
||||
) => {
|
||||
core.setOutput(Outputs.CacheHit, false);
|
||||
const packageManagerInfo = await getPackageManagerInfo(packageManager);
|
||||
const platform = process.env.RUNNER_OS;
|
||||
const arch = process.arch;
|
||||
@@ -32,22 +38,51 @@ export const restoreCache = async (
|
||||
|
||||
const linuxVersion =
|
||||
process.env.RUNNER_OS === 'Linux' ? `${process.env.ImageOS}-` : '';
|
||||
const primaryKey = `setup-go-${platform}-${arch}-${linuxVersion}go-${versionSpec}-${fileHash}`;
|
||||
core.debug(`primary key is ${primaryKey}`);
|
||||
const primaryKeys = {
|
||||
// Downloaded module sources can be reused across Go versions and runner
|
||||
// architectures. Keep OS isolation for filesystem compatibility.
|
||||
modules: `setup-go-modules-${platform}-${fileHash}`,
|
||||
build: `setup-go-build-${platform}-${arch}-${linuxVersion}go-${versionSpec}-${fileHash}`
|
||||
};
|
||||
const entries: CacheEntry[] = cachePaths.map(directory => ({
|
||||
...directory,
|
||||
primaryKey: primaryKeys[directory.kind]
|
||||
}));
|
||||
|
||||
core.saveState(State.CachePrimaryKey, primaryKey);
|
||||
const restoreEntry = async (entry: CacheEntry) => {
|
||||
core.debug(`${entry.kind} primary key is ${entry.primaryKey}`);
|
||||
try {
|
||||
entry.matchedKey = await cache.restoreCache(
|
||||
[entry.path],
|
||||
entry.primaryKey
|
||||
);
|
||||
if (entry.matchedKey) {
|
||||
core.info(`${entry.kind} cache restored from key: ${entry.matchedKey}`);
|
||||
} else {
|
||||
core.info(`${entry.kind} cache is not found`);
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
core.warning(`Restore ${entry.kind} cache failed: ${message}`);
|
||||
}
|
||||
};
|
||||
|
||||
const cacheKey = await cache.restoreCache(cachePaths, primaryKey);
|
||||
core.setOutput(Outputs.CacheHit, Boolean(cacheKey));
|
||||
|
||||
if (!cacheKey) {
|
||||
core.info(`Cache is not found`);
|
||||
core.setOutput(Outputs.CacheHit, false);
|
||||
return;
|
||||
if (canRestoreCachesInParallel(entries)) {
|
||||
await Promise.all(entries.map(restoreEntry));
|
||||
} else {
|
||||
for (const entry of entries) {
|
||||
await restoreEntry(entry);
|
||||
}
|
||||
}
|
||||
|
||||
core.saveState(State.CacheMatchedKey, cacheKey);
|
||||
core.info(`Cache restored from key: ${cacheKey}`);
|
||||
// Preserve the resolved paths so the post step uses the same cache versions,
|
||||
// even if a later step changes the Go environment.
|
||||
core.saveState(State.CacheEntries, entries);
|
||||
core.setOutput(
|
||||
Outputs.CacheHit,
|
||||
entries.length === packageManagerInfo.cacheFolderCommandList.length &&
|
||||
entries.every(entry => entry.matchedKey === entry.primaryKey)
|
||||
);
|
||||
};
|
||||
|
||||
const findDependencyFile = (packageManager: PackageManagerInfo) => {
|
||||
|
||||
+26
-30
@@ -2,7 +2,7 @@ import * as core from '@actions/core';
|
||||
import * as cache from '@actions/cache';
|
||||
import fs from 'fs';
|
||||
import {State} from './constants.js';
|
||||
import {getCacheDirectoryPath, getPackageManagerInfo} from './cache-utils.js';
|
||||
import type {CacheEntry} from './cache-utils.js';
|
||||
|
||||
// Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in
|
||||
// @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to
|
||||
@@ -39,47 +39,43 @@ export async function run(earlyExit?: boolean) {
|
||||
}
|
||||
|
||||
const cachePackages = async () => {
|
||||
const packageManager = 'default';
|
||||
|
||||
const state = core.getState(State.CacheMatchedKey);
|
||||
const primaryKey = core.getState(State.CachePrimaryKey);
|
||||
|
||||
const packageManagerInfo = await getPackageManagerInfo(packageManager);
|
||||
|
||||
const cachePaths = await getCacheDirectoryPath(packageManagerInfo);
|
||||
|
||||
const nonExistingPaths = cachePaths.filter(
|
||||
cachePath => !fs.existsSync(cachePath)
|
||||
const entries: CacheEntry[] = JSON.parse(
|
||||
core.getState(State.CacheEntries) || '[]'
|
||||
);
|
||||
|
||||
if (nonExistingPaths.length === cachePaths.length) {
|
||||
core.warning('There are no cache folders on the disk');
|
||||
return;
|
||||
}
|
||||
|
||||
if (nonExistingPaths.length) {
|
||||
logWarning(
|
||||
`Cache folder path is retrieved but doesn't exist on disk: ${nonExistingPaths.join(
|
||||
', '
|
||||
)}`
|
||||
);
|
||||
}
|
||||
|
||||
if (!primaryKey) {
|
||||
if (!entries.length) {
|
||||
core.info(
|
||||
'Primary key was not generated. Please check the log messages above for more errors or information'
|
||||
'Cache keys were not generated. Please check the log messages above for more errors or information'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (primaryKey === state) {
|
||||
await Promise.all(
|
||||
entries.map(async entry => {
|
||||
try {
|
||||
await saveCacheEntry(entry);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
core.warning(`Save ${entry.kind} cache failed: ${message}`);
|
||||
}
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
const saveCacheEntry = async (entry: CacheEntry) => {
|
||||
const {kind, path, primaryKey, matchedKey} = entry;
|
||||
if (primaryKey === matchedKey) {
|
||||
core.info(
|
||||
`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const cacheId = await cache.saveCache(cachePaths, primaryKey);
|
||||
if (!fs.existsSync(path)) {
|
||||
logWarning(`${kind} cache folder doesn't exist on disk: ${path}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const cacheId = await cache.saveCache([path], primaryKey);
|
||||
if (cacheId === -1) {
|
||||
// saveCache returns -1 without throwing when the cache was not saved, e.g.
|
||||
// a reserve collision or a read-only token (fork PR). @actions/cache has
|
||||
|
||||
+88
-12
@@ -1,11 +1,24 @@
|
||||
import * as cache from '@actions/cache';
|
||||
import * as core from '@actions/core';
|
||||
import * as exec from '@actions/exec';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import {
|
||||
supportedPackageManagers,
|
||||
PackageManagerInfo
|
||||
PackageManagerInfo,
|
||||
CacheKind
|
||||
} from './package-managers.js';
|
||||
|
||||
export interface CacheDirectory {
|
||||
kind: CacheKind;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface CacheEntry extends CacheDirectory {
|
||||
primaryKey: string;
|
||||
matchedKey?: string;
|
||||
}
|
||||
|
||||
export const getCommandOutput = async (toolCommand: string) => {
|
||||
let {stdout, stderr, exitCode} = await exec.getExecOutput(
|
||||
toolCommand,
|
||||
@@ -36,24 +49,24 @@ export const getPackageManagerInfo = async (packageManager: string) => {
|
||||
|
||||
export const getCacheDirectoryPath = async (
|
||||
packageManagerInfo: PackageManagerInfo
|
||||
) => {
|
||||
): Promise<CacheDirectory[]> => {
|
||||
const pathOutputs = await Promise.allSettled(
|
||||
packageManagerInfo.cacheFolderCommandList.map(async command =>
|
||||
getCommandOutput(command)
|
||||
)
|
||||
packageManagerInfo.cacheFolderCommandList.map(async ({kind, command}) => ({
|
||||
kind,
|
||||
path: await getCommandOutput(command)
|
||||
}))
|
||||
);
|
||||
|
||||
const results = pathOutputs.map(item => {
|
||||
const cachePaths: CacheDirectory[] = [];
|
||||
for (const item of pathOutputs) {
|
||||
if (item.status === 'fulfilled') {
|
||||
return item.value;
|
||||
if (item.value.path) {
|
||||
cachePaths.push(item.value);
|
||||
}
|
||||
} else {
|
||||
core.info(`[warning]getting cache directory path failed: ${item.reason}`);
|
||||
}
|
||||
|
||||
return '';
|
||||
});
|
||||
|
||||
const cachePaths = results.filter(item => item);
|
||||
}
|
||||
|
||||
if (!cachePaths.length) {
|
||||
throw new Error(`Could not get cache folder paths.`);
|
||||
@@ -62,6 +75,69 @@ export const getCacheDirectoryPath = async (
|
||||
return cachePaths;
|
||||
};
|
||||
|
||||
export function canRestoreCachesInParallel(
|
||||
directories: CacheDirectory[]
|
||||
): boolean {
|
||||
try {
|
||||
const paths = directories.map(directory => {
|
||||
const resolvedPath = resolveCachePath(directory.path);
|
||||
// Conservatively handle case-insensitive Windows/macOS filesystems.
|
||||
return process.platform === 'darwin' || process.platform === 'win32'
|
||||
? resolvedPath.toLowerCase()
|
||||
: resolvedPath;
|
||||
});
|
||||
// A cache archive can replace symlinks traversed by the other restore.
|
||||
// Canonical destinations alone do not capture that extraction footprint.
|
||||
if (
|
||||
paths.some((resolvedPath, index) => {
|
||||
const absolutePath = path.resolve(directories[index].path);
|
||||
const normalizedPath =
|
||||
process.platform === 'darwin' || process.platform === 'win32'
|
||||
? absolutePath.toLowerCase()
|
||||
: absolutePath;
|
||||
return resolvedPath !== normalizedPath;
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return paths.every((parent, index) =>
|
||||
paths.every((child, otherIndex) => {
|
||||
if (index === otherIndex) {
|
||||
return true;
|
||||
}
|
||||
const relative = path.relative(parent, child);
|
||||
return (
|
||||
relative === '..' ||
|
||||
relative.startsWith(`..${path.sep}`) ||
|
||||
path.isAbsolute(relative)
|
||||
);
|
||||
})
|
||||
);
|
||||
} catch {
|
||||
// If the paths cannot be resolved safely, avoid concurrent extraction.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveCachePath(directory: string): string {
|
||||
const absolutePath = path.resolve(directory);
|
||||
try {
|
||||
fs.lstatSync(absolutePath);
|
||||
} catch (error) {
|
||||
const parent = path.dirname(absolutePath);
|
||||
if (
|
||||
(error as NodeJS.ErrnoException).code !== 'ENOENT' ||
|
||||
parent === absolutePath
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
// Cold cache directories may not exist yet. Resolve their existing
|
||||
// ancestors so symlink aliases still participate in the overlap check.
|
||||
return path.join(resolveCachePath(parent), path.basename(absolutePath));
|
||||
}
|
||||
return fs.realpathSync(absolutePath);
|
||||
}
|
||||
|
||||
export function isGhes(): boolean {
|
||||
const ghUrl = new URL(
|
||||
process.env['GITHUB_SERVER_URL'] || 'https://github.com'
|
||||
|
||||
+1
-2
@@ -1,6 +1,5 @@
|
||||
export enum State {
|
||||
CachePrimaryKey = 'CACHE_KEY',
|
||||
CacheMatchedKey = 'CACHE_RESULT'
|
||||
CacheEntries = 'CACHE_ENTRIES'
|
||||
}
|
||||
|
||||
export enum Outputs {
|
||||
|
||||
@@ -2,14 +2,19 @@ type SupportedPackageManagers = {
|
||||
[prop: string]: PackageManagerInfo;
|
||||
};
|
||||
|
||||
export type CacheKind = 'modules' | 'build';
|
||||
|
||||
export interface PackageManagerInfo {
|
||||
dependencyFilePattern: string;
|
||||
cacheFolderCommandList: string[];
|
||||
cacheFolderCommandList: {kind: CacheKind; command: string}[];
|
||||
}
|
||||
|
||||
export const supportedPackageManagers: SupportedPackageManagers = {
|
||||
default: {
|
||||
dependencyFilePattern: 'go.mod',
|
||||
cacheFolderCommandList: ['go env GOMODCACHE', 'go env GOCACHE']
|
||||
cacheFolderCommandList: [
|
||||
{kind: 'modules', command: 'go env GOMODCACHE'},
|
||||
{kind: 'build', command: 'go env GOCACHE'}
|
||||
]
|
||||
}
|
||||
};
|
||||
Reference in new issue
Block a user