Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ jobs:
| `cache` | Enable caching of project dependencies | No | `false` |
| `cache-toolchain` | Cache Vite+, managed Node.js, and the selected package manager in GitHub Actions. Requires exact versions | No | `false` |
| `cache-save` | Save enabled dependency and toolchain caches in the post action | No | `true` |
| `cache-prune` | Prune the pnpm store before saving a dependency cache restored from an older lock file | No | `false` |
| `cache-dependency-path` | Path to lock file for cache key generation | No | Auto-detected |
| `registry-url` | Optional registry to set up for auth. Sets the registry in `.npmrc` and reads auth from `NODE_AUTH_TOKEN` | No | |
| `scope` | Optional scope for scoped registries. Falls back to repo owner for GitHub Packages | No | |
Expand Down Expand Up @@ -512,10 +513,25 @@ When `cache: true` is set, the action additionally caches project dependencies b

The dependency cache key format is: `vite-plus-{OS}-{arch}-{pm}-{lockfile-hash}`

On a lockfile hash miss, the action restores the newest cache for the same OS and architecture, and saves it with the packages the new lock file added. Packages the lock file no longer uses stay in the store, so with long cache retention the cache keeps growing.

When `working-directory` is set, lockfile auto-detection runs in that directory.

When `cache-dependency-path` points to a lock file in a subdirectory, the action resolves the package-manager cache directory from that lock file's directory.

### Prune the pnpm store

Set `cache-prune: true` to run `pnpm store prune` on a store restored from an older lock file before saving it. The new cache then keeps only the packages that installs on the runner use. The action prunes only with pnpm 12.16.0 or later, because earlier versions can prune packages that were copied or cloned into `node_modules`.

Enable it only in jobs that install every package in the lock file. After `run-install: false`, a `--prod` install, or a filtered install, pruning removes packages that the lock file still needs. Later jobs restore that store by its exact key and do not save it again, so they download the missing packages on every run.

```yaml
- uses: voidzero-dev/setup-vp@v1.22.0
with:
cache: true
cache-prune: true
```

### Control cache saving

Set `cache-save: false` to restore existing caches without writing new caches.
Expand Down
4 changes: 4 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ inputs:
description: "Whether to save enabled dependency and toolchain caches in the post action."
required: false
default: "true"
cache-prune:
description: "Prune the pnpm store before saving a dependency cache restored from an older lock file. Enable it only in jobs that install every package in the lock file."
required: false
default: "false"
cache-toolchain:
description: "Cache Vite+, the managed Node.js runtime, and the selected managed package manager. Requires exact Vite+ and Node.js versions. Independent of the project dependency cache."
required: false
Expand Down
84 changes: 42 additions & 42 deletions dist/index.mjs

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/cache-restore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ export async function restoreCache(inputs: Inputs): Promise<void> {

debug(`Cache paths: ${cachePaths.join(", ")}`);
saveState(State.CachePaths, JSON.stringify(cachePaths));
saveState(State.CacheLockFileType, lockFile.type);
saveState(State.CacheCwd, cacheCwd);

// Generate cache key: vite-plus-{platform}-{arch}-{lockfile-type}-{hash}
const runnerOS = process.env.RUNNER_OS || platform();
Expand Down
121 changes: 119 additions & 2 deletions src/cache-save.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { describe, it, expect, beforeEach, vi } from "vite-plus/test";
vi.mock("@actions/cache", () => ({
saveCache: vi.fn(),
}));
vi.mock("@actions/exec", () => ({
exec: vi.fn(),
getExecOutput: vi.fn(),
}));
vi.mock("@actions/core", () => ({
getState: vi.fn(),
info: vi.fn(),
Expand All @@ -13,24 +17,31 @@ vi.mock("@actions/core", () => ({

import { saveCache as saveCacheAction } from "@actions/cache";
import { getState, info, warning } from "@actions/core";
import { exec, getExecOutput } from "@actions/exec";
import { saveCache } from "./cache-save.js";
import { State } from "./types.js";

const mockedSaveCacheAction = vi.mocked(saveCacheAction);
const mockedGetState = vi.mocked(getState);
const mockedInfo = vi.mocked(info);
const mockedWarning = vi.mocked(warning);
const mockedExec = vi.mocked(exec);
const mockedGetExecOutput = vi.mocked(getExecOutput);

// Drive getState to return values for the save path:
// a primary key, distinct matched key (so we don't short-circuit on a hit),
// and non-empty cache paths.
function stubSaveState(): void {
function stubSaveState({ matchedKey = "", lockFileType = "pnpm" } = {}): void {
mockedGetState.mockImplementation((name: string) => {
switch (name) {
case State.CachePrimaryKey:
return "vite-plus-Linux-x64-pnpm-abc123";
case State.CacheMatchedKey:
return "";
return matchedKey;
case State.CacheLockFileType:
return lockFileType;
case State.CacheCwd:
return "/home/runner/work/app";
case State.CachePaths:
return JSON.stringify(["/home/runner/.cache/pnpm"]);
default:
Expand Down Expand Up @@ -77,4 +88,110 @@ describe("saveCache", () => {

expect(mockedWarning).toHaveBeenCalledWith(expect.stringContaining("boom"));
});

describe("after a restore-key match", () => {
const previousKey = "vite-plus-Linux-x64-pnpm-old999";
const cwd = "/home/runner/work/app";

// Stub `vp env current --json`, which reports the pnpm version before pruning.
function stubPackageManager(packageManager: unknown = { name: "pnpm", version: "12.18.0" }) {
mockedGetExecOutput.mockResolvedValue({
exitCode: 0,
stdout: JSON.stringify({ package_manager: packageManager }),
stderr: "",
});
}

beforeEach(() => {
stubSaveState({ matchedKey: previousKey });
mockedSaveCacheAction.mockResolvedValue(42);
});

it("prunes the restored pnpm store before saving", async () => {
stubPackageManager();
mockedExec.mockResolvedValue(0);

await saveCache({ prune: true });

expect(mockedExec).toHaveBeenCalledWith("vp", ["pm", "cache", "clean"], {
cwd,
ignoreReturnCode: true,
});
expect(mockedExec.mock.invocationCallOrder[0]).toBeLessThan(
mockedSaveCacheAction.mock.invocationCallOrder[0]!,
);
expect(mockedWarning).not.toHaveBeenCalled();
});

it("prunes with a pnpm prerelease after 12.16.0", async () => {
stubPackageManager({ name: "pnpm", version: "13.0.0-beta.1" });
mockedExec.mockResolvedValue(0);

await saveCache({ prune: true });

expect(mockedExec).toHaveBeenCalled();
});

it("does not prune unless cache-prune is enabled", async () => {
stubPackageManager();

await saveCache();

expect(mockedGetExecOutput).not.toHaveBeenCalled();
expect(mockedExec).not.toHaveBeenCalled();
expect(mockedSaveCacheAction).toHaveBeenCalled();
});

it.each(["10.34.7", "12.15.2", "unknown"])(
"does not prune with pnpm %s, which can remove packages still in use",
async (version) => {
stubPackageManager({ name: "pnpm", version });

await saveCache({ prune: true });

expect(mockedExec).not.toHaveBeenCalled();
expect(mockedSaveCacheAction).toHaveBeenCalled();
},
);

it("still saves when pruning fails", async () => {
stubPackageManager();
mockedExec.mockResolvedValue(1);

await saveCache({ prune: true });

expect(mockedWarning).toHaveBeenCalledWith(expect.stringContaining("exit code 1"));
expect(mockedSaveCacheAction).toHaveBeenCalled();
});

it("still saves when reading the pnpm version fails", async () => {
mockedGetExecOutput.mockRejectedValue(new Error("vp not found"));

await saveCache({ prune: true });

expect(mockedExec).not.toHaveBeenCalled();
expect(mockedWarning).toHaveBeenCalledWith(expect.stringContaining("vp not found"));
expect(mockedSaveCacheAction).toHaveBeenCalled();
});

it("does not prune caches of other lock file types", async () => {
stubSaveState({ matchedKey: previousKey, lockFileType: "npm" });

await saveCache({ prune: true });

expect(mockedGetExecOutput).not.toHaveBeenCalled();
expect(mockedExec).not.toHaveBeenCalled();
expect(mockedSaveCacheAction).toHaveBeenCalled();
});
});

it("does not prune when no cache was restored", async () => {
stubSaveState();
mockedSaveCacheAction.mockResolvedValue(42);

await saveCache({ prune: true });

expect(mockedGetExecOutput).not.toHaveBeenCalled();
expect(mockedExec).not.toHaveBeenCalled();
});
});
59 changes: 57 additions & 2 deletions src/cache-save.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,57 @@
import { saveCache as saveCacheAction } from "@actions/cache";
import { getState, info, warning } from "@actions/core";
import { State } from "./types.js";
import { exec, getExecOutput } from "@actions/exec";
import { satisfiesComparator } from "verkit";
import { LockFileType, State } from "./types.js";

export async function saveCache(): Promise<void> {
async function getPnpmVersion(cwd: string | undefined): Promise<string | undefined> {
const result = await getExecOutput("vp", ["env", "current", "--json"], {
cwd,
silent: true,
ignoreReturnCode: true,
});
if (result.exitCode !== 0) return undefined;
const current = JSON.parse(result.stdout) as {
package_manager?: { name?: unknown; version?: unknown };
} | null;
const packageManager = current?.package_manager;
return packageManager?.name === "pnpm" && typeof packageManager.version === "string"
? packageManager.version
: undefined;
}

// `vp pm cache clean` runs `pnpm store prune`, which removes packages that no project
// on this machine references.
async function prunePnpmStore(cwd: string | undefined): Promise<void> {
try {
const version = await getPnpmVersion(cwd);
// Before 12.16.0, `pnpm store prune` also removed packages that pnpm copied or cloned
// into node_modules. https://pnpm.io/blog/releases/12.16.0#store
if (!version || !satisfiesComparator(version, ">=12.16.0")) {
info(
`Skipping pnpm store prune: pnpm ${version ?? "(unknown)"} can remove copied or cloned packages that are still in use (fixed in pnpm 12.16.0).`,
);
return;
}

info("Cache was restored from a previous lock file. Pruning the pnpm store before saving.");
const exitCode = await exec("vp", ["pm", "cache", "clean"], { cwd, ignoreReturnCode: true });
if (exitCode !== 0) {
warning(`Failed to prune the pnpm store (exit code ${exitCode}). Saving it unpruned.`);
}
} catch (error) {
warning(`Failed to prune the pnpm store: ${String(error)}. Saving it unpruned.`);
}
}

export interface SaveCacheOptions {
// Opt-in: after a partial install (no install, `--prod`, `--filter`), pruning drops
// packages the lock file still needs, and later jobs restore that store under the
// exact lock file key without saving again.
prune?: boolean;
}

export async function saveCache({ prune = false }: SaveCacheOptions = {}): Promise<void> {
const primaryKey = getState(State.CachePrimaryKey);
const matchedKey = getState(State.CacheMatchedKey);
const cachePathsJson = getState(State.CachePaths);
Expand Down Expand Up @@ -30,6 +79,12 @@ export async function saveCache(): Promise<void> {
return;
}

// A restore-key match brings back the store of an older lock file. Without pruning,
// each lock file change saves that store plus the new packages, so it grows forever.
if (prune && matchedKey && getState(State.CacheLockFileType) === LockFileType.Pnpm) {
await prunePnpmStore(getState(State.CacheCwd) || undefined);
}

try {
const cacheId = await saveCacheAction(cachePaths, primaryKey);
if (cacheId === -1) {
Expand Down
8 changes: 7 additions & 1 deletion src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,12 @@ describe("runPost", () => {
},
);

it("passes cache-prune to the dependency cache save", async () => {
await runPost({ ...inputs(true, true), cachePrune: true });

expect(mockedSaveCache).toHaveBeenCalledExactlyOnceWith({ prune: true });
});

it("saves toolchains with dependency caching disabled", async () => {
await runPost({ ...inputs(false, true), cacheToolchain: true });

Expand All @@ -294,7 +300,7 @@ describe("runPost", () => {
it("saves the cache when caching and cache saving are enabled", async () => {
await runPost(inputs(true, true));

expect(mockedSaveCache).toHaveBeenCalledOnce();
expect(mockedSaveCache).toHaveBeenCalledExactlyOnceWith({ prune: false });
expect(saveToolchainCache).not.toHaveBeenCalled();
expect(savePackageManagerCache).not.toHaveBeenCalled();
expect(mockedInfo).not.toHaveBeenCalled();
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export async function runPost(inputs: Inputs): Promise<void> {
await Promise.all([
inputs.cacheToolchain ? saveToolchainCache() : undefined,
inputs.cacheToolchain ? savePackageManagerCache() : undefined,
inputs.cache ? saveCache() : undefined,
inputs.cache ? saveCache({ prune: inputs.cachePrune === true }) : undefined,
]);
}

Expand Down
8 changes: 8 additions & 0 deletions src/inputs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ describe("getInputs", () => {
cache: false,
cacheToolchain: false,
cacheSave: false,
cachePrune: false,
cacheDependencyPath: undefined,
});
});
Expand Down Expand Up @@ -167,6 +168,13 @@ describe("getInputs", () => {
expect(inputs.cacheSave).toBe(true);
});

it("parses cache-prune", () => {
vi.mocked(getInput).mockReturnValue("");
vi.mocked(getBooleanInput).mockImplementation((name) => name === "cache-prune");

expect(getInputs()).toMatchObject({ cachePrune: true, cacheSave: false });
});

it("should parse sfw input", () => {
vi.mocked(getInput).mockReturnValue("");
vi.mocked(getBooleanInput).mockImplementation((name) => {
Expand Down
1 change: 1 addition & 0 deletions src/inputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function getInputs(): Inputs {
cache: getBooleanInput("cache"),
cacheToolchain: getBooleanInput("cache-toolchain"),
cacheSave: getBooleanInput("cache-save"),
cachePrune: getBooleanInput("cache-prune"),
cacheDependencyPath: getInput("cache-dependency-path") || undefined,
registryUrl: getInput("registry-url") || undefined,
scope: getInput("scope") || undefined,
Expand Down
3 changes: 3 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export interface Inputs {
readonly cache: boolean;
readonly cacheToolchain?: boolean;
readonly cacheSave: boolean;
readonly cachePrune?: boolean;
readonly cacheDependencyPath?: string;
readonly registryUrl?: string;
readonly scope?: string;
Expand All @@ -45,6 +46,8 @@ export enum State {
CachePrimaryKey = "CACHE_PRIMARY_KEY",
CacheMatchedKey = "CACHE_MATCHED_KEY",
CachePaths = "CACHE_PATHS",
CacheLockFileType = "CACHE_LOCK_FILE_TYPE",
CacheCwd = "CACHE_CWD",
InstalledVersion = "INSTALLED_VERSION",
ToolchainCachePlan = "TOOLCHAIN_CACHE_PLAN",
ToolchainCacheHit = "TOOLCHAIN_CACHE_HIT",
Expand Down
1 change: 1 addition & 0 deletions test/reuse-installation-integrity.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ switch (process.argv[2]) {
INPUT_CACHE: "false",
"INPUT_CACHE-TOOLCHAIN": "false",
"INPUT_CACHE-SAVE": "false",
"INPUT_CACHE-PRUNE": "false",
INPUT_SFW: "false",
};
for (const key of overrides) delete env[key];
Expand Down
Loading