Enhance caching in setup-node with package manager filed detection

This commit is contained in:
priya-kinthali 2025-08-22 16:36:33 +05:30
parent 1c26a09e00
commit 674c3e93f9
6 changed files with 186 additions and 4 deletions

View file

@ -1,6 +1,7 @@
import * as core from '@actions/core';
import os from 'os';
import fs from 'fs';
import * as auth from './authutil';
import * as path from 'path';
@ -20,6 +21,9 @@ export async function run() {
let arch = core.getInput('architecture');
const cache = core.getInput('cache');
const packagemanagercache =
(core.getInput('package-manager-cache') || 'true').toUpperCase() ===
'TRUE';
// if architecture supplied but node-version is not
// if we don't throw a warning, the already installed x64 node will be used which is not probably what user meant.
@ -63,10 +67,14 @@ export async function run() {
auth.configAuthentication(registryUrl, alwaysAuth);
}
const resolvedPackageManager = getNameFromPackageManagerField();
const cacheDependencyPath = core.getInput('cache-dependency-path');
if (cache && isCacheFeatureAvailable()) {
core.saveState(State.CachePackageManager, cache);
const cacheDependencyPath = core.getInput('cache-dependency-path');
await restoreCache(cache, cacheDependencyPath);
} else if (resolvedPackageManager && packagemanagercache) {
core.saveState(State.CachePackageManager, resolvedPackageManager);
await restoreCache(resolvedPackageManager, cacheDependencyPath);
}
const matchersPath = path.join(__dirname, '../..', '.github');
@ -117,3 +125,23 @@ function resolveVersionInput(): string {
return version;
}
export function getNameFromPackageManagerField(): string | undefined {
// Check devEngines.packageManager and packageManager field in package.json
try {
const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf-8'));
return (
packageJson.devEngines?.packageManager?.name ||
(() => {
const pm = packageJson.packageManager;
if (typeof pm === 'string') {
const match = pm.match(/^(?:\^)?(npm|yarn|pnpm)@/);
return match ? match[1] : undefined;
}
return undefined;
})()
);
} catch (err) {
return undefined;
}
}