Compare commits

...

39 Commits

Author SHA1 Message Date
Bishal Prasad 657c52f11e fix merge 2022-12-06 18:45:12 +00:00
Bishal Prasad 34e917cb7d Merge branch '700-actionscache-granular-cache-control' into bishal/outputter 2022-12-06 18:42:19 +00:00
Bishal Prasad ac8fc97c06 update save as well 2022-12-06 18:26:58 +00:00
Sankalp Kotewar 86712a0733
dist 2022-12-06 10:10:52 +00:00
Sankalp Kotewar d6e98d9302
Calling methods from same file 2022-12-06 10:08:26 +00:00
Sankalp Kotewar a76826ef46
Removed commented lines 2022-12-06 10:07:30 +00:00
Sankalp Kotewar e02e5113ed
Removed return type in promise 2022-12-06 10:03:48 +00:00
Sankalp Kotewar 85ae5bbcea
Fixed breaking test case 2022-12-06 09:36:37 +00:00
Sankalp Kotewar cce93fb2c7
Generated dist 2022-12-06 08:23:10 +00:00
Sankalp Kotewar e3d8fb0b34
Merge pull request #1016 from actions/bishal/outputter
Refactor setting output and state into a generic outputter
2022-12-05 18:10:52 +05:30
Bishal Prasad d95c048983 refactor into a generic outputter 2022-12-05 11:36:14 +00:00
Sankalp Kotewar 706c369cf1
Merge branch 'main' into 700-actionscache-granular-cache-control 2022-12-05 12:24:53 +05:30
Sankalp Kotewar 11ab7ccfa2
Reverted custom asks implemented and added wrapper 2022-12-02 10:14:43 +00:00
Sankalp Kotewar 4b5f33df54
Updated new actions' input descriptions 2022-12-01 08:27:08 +00:00
Sankalp Kotewar 56a0133650
Merge branch 'main' into 700-actionscache-granular-cache-control 2022-11-30 16:20:50 +05:30
Sankalp Kotewar 19446b165a
Slight modification for test cases check 2022-11-30 10:47:09 +00:00
Sankalp Kotewar 8a88690a20
Fixed test cases issues 2022-11-30 08:38:59 +00:00
Sankalp Kotewar 6e2c6a5916
Formatted document 2022-11-30 08:30:16 +00:00
Sankalp Kotewar 2c9fb32186
Merge branch 'main' into 700-actionscache-granular-cache-control 2022-11-30 13:57:39 +05:30
Sankalp Kotewar 01d96636a0
Some cleanup 2022-11-30 08:26:50 +00:00
Sankalp Kotewar 9c5a42a7c9
Added test cases 2022-11-30 08:11:55 +00:00
Sankalp Kotewar a172494938
Reverted wrapper changes 2022-11-29 10:56:53 +00:00
Sankalp Kotewar f8717682fb
Impl separated 2022-11-29 09:55:41 +00:00
Sankalp Kotewar af1210e2a3
test 2022-11-29 09:51:53 +00:00
Sankalp Kotewar ab0e7714ce
new try 2022-11-29 09:39:21 +00:00
Sankalp Kotewar fb4a5dce60
test 2022-11-29 09:33:03 +00:00
Sankalp Kotewar 71334c58b2
Test 2022-11-29 09:06:10 +00:00
Sankalp Kotewar 888d454557
experimenting 2022-11-29 09:03:19 +00:00
Sankalp Kotewar dddd7ce07c
added debug logs 2022-11-29 08:26:52 +00:00
Sankalp Kotewar abddc4dd44
Merge remote-tracking branch 'origin/master' into 700-actionscache-granular-cache-control 2022-11-29 08:08:32 +00:00
Sankalp Kotewar 921c58ee44
Changed logs to warnings 2022-11-29 08:06:41 +00:00
Sankalp Kotewar 7f45813c72
Adding wrapper class 2022-11-29 08:02:27 +00:00
Vipul 0769f2e443
Merge branch 'main' into master 2022-11-28 23:50:15 -08:00
Sankalp Kotewar 5fe0b944ef
Updated variable name 2022-11-29 07:48:11 +00:00
Sankalp Kotewar 69b8227b27
Basic implementation 2022-11-25 09:16:56 +00:00
Vipul 515d10b4fd
Merge pull request #746 from actions/revert-173-add-stack-example
Revert "Add example for Haskell Stack"
2022-02-22 12:44:25 +05:30
Vipul 669e7536d9
Revert "Add example for Haskell Stack" 2022-02-22 12:17:37 +05:30
Vipul 29dbbce762
Merge pull request #173 from malob/add-stack-example
Add example for Haskell Stack
2022-02-22 12:11:06 +05:30
Malo Bourgon ea5981db97 Add example for Haskell Stack 2022-02-21 14:59:28 -08:00
15 changed files with 3174 additions and 2887 deletions

View File

@ -0,0 +1,14 @@
{
"name": "Node.js & TypeScript",
"image": "mcr.microsoft.com/devcontainers/typescript-node:16-bullseye",
// Features to add to the dev container. More info: https://containers.dev/implementors/features.
// "features": {},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
"postCreateCommand": "npm install && npm run build"
// Configure tool-specific properties.
// "customizations": {},
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}

View File

@ -102,7 +102,7 @@ test("restore on GHES with AC available ", async () => {
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(actionUtils, "setCacheHitOutput");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
@ -116,7 +116,7 @@ test("restore on GHES with AC available ", async () => {
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith(true);
expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "true");
expect(infoMock).toHaveBeenCalledWith(`Cache restored from key: ${key}`);
expect(failedMock).toHaveBeenCalledTimes(0);
@ -270,7 +270,7 @@ test("restore with cache found for key", async () => {
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(actionUtils, "setCacheHitOutput");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
@ -284,7 +284,7 @@ test("restore with cache found for key", async () => {
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith(true);
expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "true");
expect(infoMock).toHaveBeenCalledWith(`Cache restored from key: ${key}`);
expect(failedMock).toHaveBeenCalledTimes(0);
@ -303,7 +303,7 @@ test("restore with cache found for restore key", async () => {
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(actionUtils, "setCacheHitOutput");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
@ -317,8 +317,7 @@ test("restore with cache found for restore key", async () => {
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith(false);
expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "false");
expect(infoMock).toHaveBeenCalledWith(
`Cache restored from key: ${restoreKey}`
);

View File

@ -21,7 +21,7 @@ runs:
using: 'node16'
main: 'dist/restore/index.js'
post: 'dist/save/index.js'
post-if: 'success()'
post-if: success()
branding:
icon: 'archive'
color: 'gray-dark'

955
dist/restore/index.js vendored

File diff suppressed because it is too large Load Diff

252
dist/save/index.js vendored
View File

@ -9344,7 +9344,76 @@ function expand(str, isTop) {
/***/ }),
/* 307 */,
/* 308 */,
/* 309 */,
/* 309 */
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NullStateProvider = exports.StateProvider = void 0;
const core = __importStar(__webpack_require__(470));
const constants_1 = __webpack_require__(196);
class StateProviderBase {
constructor() {
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
this.setState = (key, value) => { };
// eslint-disable-next-line @typescript-eslint/no-unused-vars
this.getState = (key) => "";
}
getCacheState() {
const cacheKey = this.getState(constants_1.State.CacheMatchedKey);
if (cacheKey) {
core.debug(`Cache state/key: ${cacheKey}`);
return cacheKey;
}
return undefined;
}
}
class StateProvider extends StateProviderBase {
constructor() {
super(...arguments);
//setOutput = core.setOutput;
this.setState = core.saveState;
this.getState = core.getState;
}
}
exports.StateProvider = StateProvider;
class NullStateProvider extends StateProviderBase {
constructor() {
super(...arguments);
//setOutput = core.setOutput;
this.setState = core.setOutput;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
this.getState = (key) => "";
}
}
exports.NullStateProvider = NullStateProvider;
/***/ }),
/* 310 */,
/* 311 */,
/* 312 */
@ -38422,7 +38491,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCacheFeatureAvailable = exports.getInputAsInt = exports.getInputAsArray = exports.isValidEvent = exports.logWarning = exports.getCacheState = exports.setOutputAndState = exports.setCacheHitOutput = exports.setCacheState = exports.isExactKeyMatch = exports.isGhes = void 0;
exports.isCacheFeatureAvailable = exports.getInputAsInt = exports.getInputAsArray = exports.isValidEvent = exports.logWarning = exports.setCacheHitOutput = exports.isExactKeyMatch = exports.isGhes = void 0;
const cache = __importStar(__webpack_require__(692));
const core = __importStar(__webpack_require__(470));
const constants_1 = __webpack_require__(196);
@ -38438,29 +38507,10 @@ function isExactKeyMatch(key, cacheKey) {
}) === 0);
}
exports.isExactKeyMatch = isExactKeyMatch;
function setCacheState(state) {
core.saveState(constants_1.State.CacheMatchedKey, state);
}
exports.setCacheState = setCacheState;
function setCacheHitOutput(isCacheHit) {
core.setOutput(constants_1.Outputs.CacheHit, isCacheHit.toString());
}
exports.setCacheHitOutput = setCacheHitOutput;
function setOutputAndState(key, cacheKey) {
setCacheHitOutput(isExactKeyMatch(key, cacheKey));
// Store the matched cache key if it exists
cacheKey && setCacheState(cacheKey);
}
exports.setOutputAndState = setOutputAndState;
function getCacheState() {
const cacheKey = core.getState(constants_1.State.CacheMatchedKey);
if (cacheKey) {
core.debug(`Cache state/key: ${cacheKey}`);
return cacheKey;
}
return undefined;
}
exports.getCacheState = getCacheState;
function logWarning(message) {
const warningPrefix = "[warning]";
core.info(`${warningPrefix}${message}`);
@ -40892,7 +40942,96 @@ Object.defineProperty(exports, "toPlatformPath", { enumerable: true, get: functi
//# sourceMappingURL=core.js.map
/***/ }),
/* 471 */,
/* 471 */
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const cache = __importStar(__webpack_require__(692));
const core = __importStar(__webpack_require__(470));
const constants_1 = __webpack_require__(196);
const utils = __importStar(__webpack_require__(443));
// 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.
process.on("uncaughtException", e => utils.logWarning(e.message));
function saveImpl(stateProvider) {
return __awaiter(this, void 0, void 0, function* () {
try {
if (!utils.isCacheFeatureAvailable()) {
return;
}
if (!utils.isValidEvent()) {
utils.logWarning(`Event Validation Error: The event type ${process.env[constants_1.Events.Key]} is not supported because it's not tied to a branch or tag ref.`);
return;
}
// If restore has stored a primary key in state, reuse that
// Else re-evaluate from inputs
const primaryKey = stateProvider.getState(constants_1.State.CachePrimaryKey) ||
core.getInput(constants_1.Inputs.Key);
if (!primaryKey) {
utils.logWarning(`Error retrieving key from state.`);
return;
}
// If matched restore key is same as primary key, then do not save cache
// NO-OP in case of SaveOnly action
const state = stateProvider.getCacheState();
if (utils.isExactKeyMatch(primaryKey, state)) {
core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`);
return;
}
const cachePaths = utils.getInputAsArray(constants_1.Inputs.Path, {
required: true
});
const cacheId = yield cache.saveCache(cachePaths, primaryKey, {
uploadChunkSize: utils.getInputAsInt(constants_1.Inputs.UploadChunkSize)
});
if (cacheId != -1) {
core.info(`Cache saved with key: ${primaryKey}`);
}
}
catch (error) {
utils.logWarning(error.message);
}
});
}
exports.default = saveImpl;
/***/ }),
/* 472 */,
/* 473 */,
/* 474 */,
@ -47268,29 +47407,6 @@ exports.default = _default;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
@ -47300,49 +47416,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const cache = __importStar(__webpack_require__(692));
const core = __importStar(__webpack_require__(470));
const constants_1 = __webpack_require__(196);
const utils = __importStar(__webpack_require__(443));
// 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.
process.on("uncaughtException", e => utils.logWarning(e.message));
const saveImpl_1 = __importDefault(__webpack_require__(471));
const stateProvider_1 = __webpack_require__(309);
function run() {
return __awaiter(this, void 0, void 0, function* () {
try {
if (!utils.isCacheFeatureAvailable()) {
return;
}
if (!utils.isValidEvent()) {
utils.logWarning(`Event Validation Error: The event type ${process.env[constants_1.Events.Key]} is not supported because it's not tied to a branch or tag ref.`);
return;
}
const state = utils.getCacheState();
// Inputs are re-evaluted before the post action, so we want the original key used for restore
const primaryKey = core.getState(constants_1.State.CachePrimaryKey);
if (!primaryKey) {
utils.logWarning(`Error retrieving key from state.`);
return;
}
if (utils.isExactKeyMatch(primaryKey, state)) {
core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`);
return;
}
const cachePaths = utils.getInputAsArray(constants_1.Inputs.Path, {
required: true
});
const cacheId = yield cache.saveCache(cachePaths, primaryKey, {
uploadChunkSize: utils.getInputAsInt(constants_1.Inputs.UploadChunkSize)
});
if (cacheId != -1) {
core.info(`Cache saved with key: ${primaryKey}`);
}
}
catch (error) {
utils.logWarning(error.message);
}
yield (0, saveImpl_1.default)(new stateProvider_1.StateProvider());
});
}
run();

23
restore/action.yml Normal file
View File

@ -0,0 +1,23 @@
name: 'Restore Cache'
description: 'Restore Cache artifacts like dependencies and build outputs to improve workflow execution time'
author: 'GitHub'
inputs:
path:
description: 'The same list of files, directories, and wildcard patterns to restore cache that were used while saving it'
required: true
key:
description: 'An explicit key for restoring the cache'
required: true
restore-keys:
description: 'An ordered list of keys to use for restoring stale cache if no cache hit occurred for key. Note `cache-hit` returns false in this case.'
required: false
outputs:
cache-hit:
description: 'A boolean value to indicate an exact match was found for the primary key'
runs:
using: 'node16'
main: '../dist/restore/index.js'
branding:
icon: 'archive'
color: 'gray-dark'

19
save/action.yml Normal file
View File

@ -0,0 +1,19 @@
name: 'Save Cache'
description: 'Save Cache artifacts like dependencies and build outputs to improve workflow execution time'
author: 'GitHub'
inputs:
path:
description: 'A list of files, directories, and wildcard patterns to cache'
required: true
key:
description: 'An explicit key for saving the cache'
required: true
upload-chunk-size:
description: 'The chunk size used to split up large files during upload, in bytes'
required: false
runs:
using: 'node16'
main: '../dist/save/index.js'
branding:
icon: 'archive'
color: 'gray-dark'

View File

@ -1,60 +1,8 @@
import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, State } from "./constants";
import * as utils from "./utils/actionUtils";
import { StateProvider } from "./stateProvider";
import restoreImpl from "./restoreImpl";
async function run(): Promise<void> {
try {
if (!utils.isCacheFeatureAvailable()) {
utils.setCacheHitOutput(false);
return;
}
// Validate inputs, this can cause task failure
if (!utils.isValidEvent()) {
utils.logWarning(
`Event Validation Error: The event type ${
process.env[Events.Key]
} is not supported because it's not tied to a branch or tag ref.`
);
return;
}
const primaryKey = core.getInput(Inputs.Key, { required: true });
core.saveState(State.CachePrimaryKey, primaryKey);
const restoreKeys = utils.getInputAsArray(Inputs.RestoreKeys);
const cachePaths = utils.getInputAsArray(Inputs.Path, {
required: true
});
const cacheKey = await cache.restoreCache(
cachePaths,
primaryKey,
restoreKeys
);
if (!cacheKey) {
core.info(
`Cache not found for input keys: ${[
primaryKey,
...restoreKeys
].join(", ")}`
);
return;
}
// Store the matched cache key
utils.setCacheState(cacheKey);
const isExactKeyMatch = utils.isExactKeyMatch(primaryKey, cacheKey);
utils.setCacheHitOutput(isExactKeyMatch);
core.info(`Cache restored from key: ${cacheKey}`);
} catch (error: unknown) {
core.setFailed((error as Error).message);
}
await restoreImpl(new StateProvider());
}
run();

67
src/restoreImpl.ts Normal file
View File

@ -0,0 +1,67 @@
import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, Outputs, State } from "./constants";
import { IStateProvider } from "./stateProvider";
import * as utils from "./utils/actionUtils";
async function restoreImpl(stateProvider: IStateProvider): Promise<string | undefined> {
try {
if (!utils.isCacheFeatureAvailable()) {
utils.setCacheHitOutput(false);
return;
}
// Validate inputs, this can cause task failure
if (!utils.isValidEvent()) {
utils.logWarning(
`Event Validation Error: The event type ${
process.env[Events.Key]
} is not supported because it's not tied to a branch or tag ref.`
);
return;
}
const primaryKey = core.getInput(Inputs.Key, { required: true });
stateProvider.setState(State.CachePrimaryKey, primaryKey);
const restoreKeys = utils.getInputAsArray(Inputs.RestoreKeys);
const cachePaths = utils.getInputAsArray(Inputs.Path, {
required: true
});
const cacheKey = await cache.restoreCache(
cachePaths,
primaryKey,
restoreKeys
);
if (!cacheKey) {
core.info(
`Cache not found for input keys: ${[
primaryKey,
...restoreKeys
].join(", ")}`
);
return;
}
// Store the matched cache key in states
stateProvider.setState(State.CacheMatchedKey, cacheKey);
const isExactKeyMatch = utils.isExactKeyMatch(
core.getInput(Inputs.Key, { required: true }),
cacheKey
);
core.setOutput(Outputs.CacheHit, isExactKeyMatch.toString());
core.info(`Cache restored from key: ${cacheKey}`);
return cacheKey;
} catch (error: unknown) {
core.setFailed((error as Error).message);
}
}
export default restoreImpl;

10
src/restoreOnly.ts Normal file
View File

@ -0,0 +1,10 @@
import restoreImpl from "./restoreImpl";
import { NullStateProvider } from "./stateProvider";
async function run(): Promise<void> {
await restoreImpl(new NullStateProvider());
}
run();
export default run;

View File

@ -1,59 +1,8 @@
import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, State } from "./constants";
import * as utils from "./utils/actionUtils";
// 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.
process.on("uncaughtException", e => utils.logWarning(e.message));
import saveImpl from "./saveImpl";
import { StateProvider } from "./stateProvider";
async function run(): Promise<void> {
try {
if (!utils.isCacheFeatureAvailable()) {
return;
}
if (!utils.isValidEvent()) {
utils.logWarning(
`Event Validation Error: The event type ${
process.env[Events.Key]
} is not supported because it's not tied to a branch or tag ref.`
);
return;
}
const state = utils.getCacheState();
// Inputs are re-evaluted before the post action, so we want the original key used for restore
const primaryKey = core.getState(State.CachePrimaryKey);
if (!primaryKey) {
utils.logWarning(`Error retrieving key from state.`);
return;
}
if (utils.isExactKeyMatch(primaryKey, state)) {
core.info(
`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`
);
return;
}
const cachePaths = utils.getInputAsArray(Inputs.Path, {
required: true
});
const cacheId = await cache.saveCache(cachePaths, primaryKey, {
uploadChunkSize: utils.getInputAsInt(Inputs.UploadChunkSize)
});
if (cacheId != -1) {
core.info(`Cache saved with key: ${primaryKey}`);
}
} catch (error: unknown) {
utils.logWarning((error as Error).message);
}
await saveImpl(new StateProvider());
}
run();

65
src/saveImpl.ts Normal file
View File

@ -0,0 +1,65 @@
import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, State } from "./constants";
import { IStateProvider } from "./stateProvider";
import * as utils from "./utils/actionUtils";
// 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.
process.on("uncaughtException", e => utils.logWarning(e.message));
async function saveImpl(stateProvider: IStateProvider): Promise<void> {
try {
if (!utils.isCacheFeatureAvailable()) {
return;
}
if (!utils.isValidEvent()) {
utils.logWarning(
`Event Validation Error: The event type ${
process.env[Events.Key]
} is not supported because it's not tied to a branch or tag ref.`
);
return;
}
// If restore has stored a primary key in state, reuse that
// Else re-evaluate from inputs
const primaryKey =
stateProvider.getState(State.CachePrimaryKey) ||
core.getInput(Inputs.Key);
if (!primaryKey) {
utils.logWarning(`Error retrieving key from state.`);
return;
}
// If matched restore key is same as primary key, then do not save cache
// NO-OP in case of SaveOnly action
const state = stateProvider.getCacheState();
if (utils.isExactKeyMatch(primaryKey, state)) {
core.info(
`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`
);
return;
}
const cachePaths = utils.getInputAsArray(Inputs.Path, {
required: true
});
const cacheId = await cache.saveCache(cachePaths, primaryKey, {
uploadChunkSize: utils.getInputAsInt(Inputs.UploadChunkSize)
});
if (cacheId != -1) {
core.info(`Cache saved with key: ${primaryKey}`);
}
} catch (error: unknown) {
utils.logWarning((error as Error).message);
}
}
export default saveImpl;

10
src/saveOnly.ts Normal file
View File

@ -0,0 +1,10 @@
import saveImpl from "./saveImpl";
import { NullStateProvider } from "./stateProvider";
async function run(): Promise<void> {
await saveImpl(new NullStateProvider());
}
run();
export default run;

42
src/stateProvider.ts Normal file
View File

@ -0,0 +1,42 @@
import * as core from "@actions/core";
import { State } from "./constants";
export interface IStateProvider {
//setOutput(key: string, value: string): void;
setState(key: string, value: string): void;
getState(key: string): string;
getCacheState(): string | undefined;
}
class StateProviderBase implements IStateProvider {
getCacheState(): string | undefined {
const cacheKey = this.getState(State.CacheMatchedKey);
if (cacheKey) {
core.debug(`Cache state/key: ${cacheKey}`);
return cacheKey;
}
return undefined;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
setState = (key: string, value: string) => {};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getState = (key: string) => "";
}
export class StateProvider extends StateProviderBase {
//setOutput = core.setOutput;
setState = core.saveState;
getState = core.getState;
}
export class NullStateProvider extends StateProviderBase {
//setOutput = core.setOutput;
setState = core.setOutput;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getState = (key: string) => "";
}

View File

@ -1,7 +1,7 @@
import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Outputs, RefKey, State } from "../constants";
import { Outputs, RefKey } from "../constants";
export function isGhes(): boolean {
const ghUrl = new URL(
@ -19,30 +19,10 @@ export function isExactKeyMatch(key: string, cacheKey?: string): boolean {
);
}
export function setCacheState(state: string): void {
core.saveState(State.CacheMatchedKey, state);
}
export function setCacheHitOutput(isCacheHit: boolean): void {
core.setOutput(Outputs.CacheHit, isCacheHit.toString());
}
export function setOutputAndState(key: string, cacheKey?: string): void {
setCacheHitOutput(isExactKeyMatch(key, cacheKey));
// Store the matched cache key if it exists
cacheKey && setCacheState(cacheKey);
}
export function getCacheState(): string | undefined {
const cacheKey = core.getState(State.CacheMatchedKey);
if (cacheKey) {
core.debug(`Cache state/key: ${cacheKey}`);
return cacheKey;
}
return undefined;
}
export function logWarning(message: string): void {
const warningPrefix = "[warning]";
core.info(`${warningPrefix}${message}`);