Core cache functionality for saving and restoring files using GitHub's caching service with support for both legacy (v1) and new (v2) cache services.
Check if the Actions cache service is available in the current environment.
/**
* Check the presence of Actions cache service
* @returns true if Actions cache service feature is available, otherwise false
*/
function isFeatureAvailable(): boolean;This function checks for the presence of required environment variables:
ACTIONS_RESULTS_URLACTIONS_CACHE_URLUsage Example:
import { isFeatureAvailable } from '@actions/cache';
if (isFeatureAvailable()) {
console.log('Cache service is available');
// Proceed with cache operations
} else {
console.log('Cache service is not available, skipping cache operations');
}Restore cached files from the cache service using primary key and optional restore keys for fallback matching.
/**
* Restores cache from keys
* @param paths - List of file paths to restore from the cache
* @param primaryKey - Explicit key for restoring the cache. Lookup is done with prefix matching
* @param restoreKeys - Optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey
* @param options - Cache download options
* @param enableCrossOsArchive - Optional boolean enabled to restore on windows any cache created on any platform
* @returns Cache key for cache hit, otherwise undefined
*/
function restoreCache(
paths: string[],
primaryKey: string,
restoreKeys?: string[],
options?: DownloadOptions,
enableCrossOsArchive?: boolean = false
): Promise<string | undefined>;Key Features:
options.lookupOnlyUsage Examples:
import { restoreCache } from '@actions/cache';
// Basic cache restore
const paths = ['node_modules'];
const primaryKey = 'npm-deps-abc123';
const cacheKey = await restoreCache(paths, primaryKey);
if (cacheKey) {
console.log(`Cache restored: ${cacheKey}`);
} else {
console.log('Cache miss');
}
// With restore keys for fallback
const restoreKeys = [
'npm-deps-abc', // Less specific fallback
'npm-deps-', // Even less specific
'npm-' // Most general fallback
];
const cacheKey = await restoreCache(paths, primaryKey, restoreKeys);
// Lookup only (check existence without downloading)
const lookupOptions = { lookupOnly: true };
const existingKey = await restoreCache(paths, primaryKey, restoreKeys, lookupOptions);
if (existingKey) {
console.log(`Cache exists with key: ${existingKey}`);
// Decide whether to download it later
}
// Cross-OS restore (restore Windows cache on Linux)
const cacheKey = await restoreCache(paths, primaryKey, restoreKeys, undefined, true);Save files to the cache service with a specified key for future restoration.
/**
* Saves a list of files with the specified key
* @param paths - List of file paths to be cached
* @param key - Explicit key for restoring the cache
* @param options - Cache upload options
* @param enableCrossOsArchive - Optional boolean enabled to save cache on windows which could be restored on any platform
* @returns Cache ID if the cache was saved successfully, throws error if save fails
*/
function saveCache(
paths: string[],
key: string,
options?: UploadOptions,
enableCrossOsArchive?: boolean = false
): Promise<number>;Key Features:
Usage Examples:
import { saveCache } from '@actions/cache';
// Basic cache save
const paths = [
'node_modules',
'packages/*/node_modules'
];
const key = 'npm-deps-abc123';
try {
const cacheId = await saveCache(paths, key);
console.log(`Cache saved successfully with ID: ${cacheId}`);
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message);
} else if (error instanceof ReserveCacheError) {
console.warn('Cache reservation failed:', error.message);
} else {
console.error('Cache save failed:', error.message);
}
}
// With upload options
const uploadOptions = {
uploadConcurrency: 8,
uploadChunkSize: 64 * 1024 * 1024, // 64MB chunks
useAzureSdk: true
};
const cacheId = await saveCache(paths, key, uploadOptions);
// Cross-OS save (save on Windows, restore on Linux)
const cacheId = await saveCache(paths, key, undefined, true);Cache keys must follow these validation rules:
Hierarchical Keys: Use hierarchical key structure for better cache hit rates:
// Most specific to least specific
const primaryKey = `npm-${platform}-${arch}-${hashFiles('package-lock.json')}`;
const restoreKeys = [
`npm-${platform}-${arch}-`,
`npm-${platform}-`,
`npm-`
];Content-Based Keys: Include file hashes in keys for cache invalidation:
import { createHash } from 'crypto';
import { readFileSync } from 'fs';
function hashFiles(pattern: string): string {
// Implementation to hash files matching pattern
const content = readFileSync('package-lock.json', 'utf8');
return createHash('sha256').update(content).digest('hex');
}
const key = `deps-${hashFiles('**/package-lock.json')}`;Cache operations can throw several types of errors:
Thrown for validation failures like invalid key format or missing paths:
try {
await restoreCache([], 'key'); // Empty paths
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
// Handle validation error
}
}Thrown when unable to reserve cache, typically when another job is creating the same cache:
try {
await saveCache(paths, key);
} catch (error) {
if (error instanceof ReserveCacheError) {
console.warn('Cache reservation failed:', error.message);
// Another job may be creating this cache, continue without caching
}
}Other errors are logged as warnings and don't break the workflow:
try {
const cacheKey = await restoreCache(paths, primaryKey, restoreKeys);
} catch (error) {
// Cache failures are non-blocking - workflow continues
console.warn('Cache operation failed:', error.message);
}