Compare commits

..

99 Commits

Author SHA1 Message Date
Sankalp Kotewar
ed5e94a5f5
Merge pull request #1006 from actions/700-actionscache-granular-cache-control
Actions Cache Granular Control Implementation
2022-12-15 16:22:14 +05:30
Sankalp Kotewar
6277f55919
Updated beta version to 3.2.0-beta.1 2022-12-15 10:11:38 +00:00
Sankalp Kotewar
c30e6dcb11
Merge pull request #1017 from actions/kotewar/readme-updates-for-granular-control
Readme updates for granular control
2022-12-15 14:38:13 +05:30
Sankalp Kotewar
05c9b49ea4
nit: added language to code blocks 2022-12-15 09:05:17 +00:00
Sankalp Kotewar
da311f75a6
nit 2022-12-15 09:01:49 +00:00
Sankalp Kotewar
7a139a9cec
Addressed review comments 2022-12-15 08:59:40 +00:00
Sankalp Kotewar
930f080bad
Added test case for restore state 2022-12-15 04:12:52 +00:00
Sankalp Kotewar
56e956426f
Repositioned new actions introduction 2022-12-14 18:49:43 +00:00
Sankalp Kotewar
766d8255cd
Removed verbose statements 2022-12-14 18:46:21 +00:00
Sankalp Kotewar
686bf424a8
Update save/README.md
Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com>
2022-12-15 00:07:16 +05:30
Sankalp Kotewar
fb5b333162
Update save/README.md
Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com>
2022-12-15 00:07:06 +05:30
Sankalp Kotewar
c11ac6c2fe
Update restore/README.md
Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com>
2022-12-15 00:06:56 +05:30
Sankalp Kotewar
d5c949690c
Update restore/README.md
Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com>
2022-12-15 00:06:41 +05:30
Sankalp Kotewar
44df5ab77e
Update restore/README.md
Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com>
2022-12-15 00:06:10 +05:30
Sankalp Kotewar
65057ce6fe
Added cache hit info in readme 2022-12-14 10:23:32 +00:00
Sankalp Kotewar
8031e403b4
Merge remote-tracking branch 'origin/700-actionscache-granular-cache-control' into kotewar/readme-updates-for-granular-control 2022-12-14 10:19:50 +00:00
Sankalp Kotewar
c8d01facfc
Renamed output 2022-12-14 09:17:49 +00:00
Sankalp Kotewar
81aaae062b
Updates to save readme 2022-12-14 04:40:58 +00:00
Sankalp Kotewar
9d445b2565
Added save readme 2022-12-14 04:35:02 +00:00
Sankalp Kotewar
adecab4b4a
Merge remote-tracking branch 'origin/700-actionscache-granular-cache-control' into kotewar/readme-updates-for-granular-control 2022-12-12 14:22:14 +00:00
Sankalp Kotewar
075ad790b0
Merged beta branch and resolved conflicts 2022-12-12 14:18:42 +00:00
Sankalp Kotewar
b275c83bd6
Merge remote-tracking branch 'origin/releases/v3-beta' into 700-actionscache-granular-cache-control 2022-12-12 14:18:23 +00:00
Sankalp Kotewar
1ddc49105d
Removed unused code 2022-12-12 14:03:16 +00:00
Sankalp Kotewar
407044787b
Added more assertions as values can't be checked 2022-12-12 13:50:54 +00:00
Sankalp Kotewar
87a7d01109
Update restore/action.yml
Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com>
2022-12-12 18:50:18 +05:30
Sankalp Kotewar
29d6c7aa7f
Update restore/action.yml
Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com>
2022-12-12 18:50:09 +05:30
Sankalp Kotewar
df53d3c04b
Update restore/action.yml
Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com>
2022-12-12 18:49:59 +05:30
Sankalp Kotewar
dd740c87de
Update restore/action.yml
Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com>
2022-12-12 18:49:53 +05:30
Sankalp Kotewar
0a6e5b052a
Update save/action.yml
Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com>
2022-12-12 18:49:45 +05:30
Sampark Sharma
a2137c625c
update for new beta release 2022-12-12 13:01:08 +00:00
Sampark Sharma
5a2b5e5714
Add support for gzip fallback for restore of old cache on windows 2022-12-12 12:57:44 +00:00
Sampark Sharma
9e9a19bf5f
Update dist folder 2022-12-12 12:57:44 +00:00
Sampark Sharma
84ea3e177d
Changes for beta release 2022-12-12 12:57:43 +00:00
Sankalp Kotewar
00b72c7e02
Updated outputs of restore action 2022-12-12 11:36:12 +00:00
Sankalp Kotewar
0cc9c1d4e8
Merge remote-tracking branch 'origin/700-actionscache-granular-cache-control' into kotewar/readme-updates-for-granular-control 2022-12-12 11:33:04 +00:00
Sankalp Kotewar
ccf90c02ed
Fixed breaking test case 2022-12-12 10:01:21 +00:00
Sankalp Kotewar
4f42dc56c1
Added stateprovider test cases 2022-12-12 09:53:50 +00:00
Sankalp Kotewar
b6604364ae
Deleted stateprovider tests until added 2022-12-12 07:28:47 +00:00
Sankalp Kotewar
c0cc8dd60a
added stateprovider changes 2022-12-12 07:28:12 +00:00
Sankalp Kotewar
91d7bd61be
Fixed review comments and tests 2022-12-12 07:26:18 +00:00
Sankalp Kotewar
5e7f2c1182
Fixed breaking test case 2022-12-11 16:47:35 +00:00
Sankalp Kotewar
3d4af52c52
Renamed variables and added tests 2022-12-11 13:33:36 +00:00
Sankalp Kotewar
d91f5bd2fd
Fixed inputs 2022-12-09 13:56:33 +00:00
Sankalp Kotewar
61aa90bfc3
Removed comments 2022-12-09 12:59:43 +00:00
Sankalp Kotewar
0c2d18e609
Merge pull request #1024 from actions/kotewar/save-changes
Granular cache control save related changes and new inputs
2022-12-09 18:22:02 +05:30
Sankalp Kotewar
804322aab0
Updated new actions dist files 2022-12-09 09:42:25 +00:00
Sankalp Kotewar
f426a0deb2
Merge remote-tracking branch 'origin/700-actionscache-granular-cache-control' into kotewar/save-changes 2022-12-09 09:40:50 +00:00
Sankalp Kotewar
be72d0432d
Merge remote-tracking branch 'origin/releases/v3-beta' into 700-actionscache-granular-cache-control 2022-12-09 09:38:08 +00:00
Sankalp Kotewar
8ecd00a4be
Added restore only and save only test cases 2022-12-08 17:56:21 +00:00
Sankalp Kotewar
12a1a354bd
Fixed test cases 2022-12-08 17:39:12 +00:00
Sankalp Kotewar
782b0bd3df
Fixed test cases 2022-12-08 17:30:24 +00:00
Sampark Sharma
f33ca902b8
Merge pull request #1022 from actions/phantsure/v3-beta
Release cache `3.1.0-beta.2` with gzip fallback for old cache
2022-12-08 15:39:59 +05:30
Sampark Sharma
d48d03435b
Add support for gzip fallback for restore of old cache on windows 2022-12-08 09:54:44 +00:00
Sankalp Kotewar
6f77edac15
dist 2022-12-08 08:33:23 +00:00
Sankalp Kotewar
6e12d27152
Fixed formatting 2022-12-08 08:24:43 +00:00
Sankalp Kotewar
c346bf01e0
Merge remote-tracking branch 'origin/releases/v3-beta' into 700-actionscache-granular-cache-control 2022-12-08 07:48:07 +00:00
Sampark Sharma
593e91a38b
Update dist folder 2022-12-08 07:28:04 +00:00
Sampark Sharma
e4c2242eff
Changes for beta release 2022-12-08 07:28:03 +00:00
Tanuj Kumar Mishra
66ef8a0951
Merge pull request #1018 from actions/bishal/outputter
Update save with a wrapper layer
2022-12-07 17:03:07 +05:30
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
Sankalp Kotewar
020a412c27
Readme draft for new actions 2022-12-05 12:34:45 +00:00
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
97 changed files with 121187 additions and 139505 deletions

View File

@ -6,7 +6,7 @@
// 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"
"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.

View File

@ -1,22 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
groups:
minor-actions-dependencies:
update-types: [minor, patch]
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "daily"
allow:
- dependency-type: direct
- dependency-type: production

View File

@ -1,3 +1,9 @@
# `dist/index.js` is a special file in Actions.
# When you reference an action with `uses:` in a workflow,
# `index.js` is the code that will run.
# For our project, we generate this file through a build process
# from other source files.
# We need to make sure the checked-in `index.js` actually matches what we expect it to be.
name: Check dist/
on:
@ -12,8 +18,33 @@ on:
workflow_dispatch:
jobs:
call-check-dist:
name: Check dist/
uses: actions/reusable-workflows/.github/workflows/check-dist.yml@main
check-dist:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js 16.x
uses: actions/setup-node@v3
with:
node-version: "20.x"
node-version: 16.x
cache: npm
- name: Install dependencies
run: npm ci
- name: Rebuild the dist/ directory
run: npm run build
- name: Compare the expected and actual dist/ directories
run: |
if [ "$(git diff --ignore-space-at-eol dist/ | wc -l)" -gt "0" ]; then
echo "Detected uncommitted changes after build. See status below:"
git diff
exit 1
fi
id: diff
# If index.js was different than expected, upload the expected version as an artifact
- uses: actions/upload-artifact@v3
if: ${{ failure() && steps.diff.conclusion == 'failure' }}
with:
name: dist
path: dist/

View File

@ -10,7 +10,7 @@ jobs:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v9
- uses: actions/stale@v3
with:
days-before-issue-stale: 200
days-before-issue-close: 5

View File

@ -8,39 +8,45 @@ on:
jobs:
CodeQL-Build:
# CodeQL runs on ubuntu-latest, windows-latest, and macos-latest
runs-on: ubuntu-latest
permissions:
# required for all workflows
security-events: write
# CodeQL runs on ubuntu-latest and windows-latest
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v3
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
uses: github/codeql-action/init@v1
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java, ruby
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
# If this step fails, then you should remove it and run the build manually (see below).
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v3
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following
# three lines and modify them (or add more) to build your code if your
# project uses a compiled language
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
uses: github/codeql-action/analyze@v1

View File

@ -7,9 +7,18 @@ on:
pull_request:
branches:
- main
workflow_dispatch:
jobs:
call-licensed:
name: Licensed
uses: actions/reusable-workflows/.github/workflows/licensed.yml@main
test:
runs-on: ubuntu-latest
name: Check licenses
steps:
- uses: actions/checkout@v3
- run: npm ci
- name: Install licensed
run: |
cd $RUNNER_TEMP
curl -Lfs -o licensed.tar.gz https://github.com/github/licensed/releases/download/2.12.2/licensed-2.12.2-linux-x64.tar.gz
sudo tar -xzf licensed.tar.gz
sudo mv licensed /usr/local/bin/licensed
- run: licensed status

View File

@ -1,20 +0,0 @@
name: 'Publish Immutable Action Version'
on:
release:
types: [released]
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
packages: write
steps:
- name: Checking out
uses: actions/checkout@v4
- name: Publish
id: publish
uses: actions/publish-immutable-action@0.0.3

View File

@ -1,28 +0,0 @@
name: Release new action version
on:
release:
types: [released]
workflow_dispatch:
inputs:
TAG_NAME:
description: 'Tag name that the major tag will point to'
required: true
env:
TAG_NAME: ${{ github.event.inputs.TAG_NAME || github.event.release.tag_name }}
permissions:
contents: write
jobs:
update_tag:
name: Update the major tag to include the ${{ github.event.inputs.TAG_NAME || github.event.release.tag_name }} changes
environment:
name: releaseNewActionVersion
runs-on: ubuntu-latest
steps:
- name: Update the ${{ env.TAG_NAME }} tag
id: update-major-tag
uses: actions/publish-action@v0.3.0
with:
source-tag: ${{ env.TAG_NAME }}
slack-webhook: ${{ secrets.SLACK_WEBHOOK }}

View File

@ -20,11 +20,11 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js 20.x
uses: actions/setup-node@v4
uses: actions/checkout@v3
- name: Setup Node.js 16.x
uses: actions/setup-node@v3
with:
node-version: 20.x
node-version: 16.x
cache: npm
- run: npm ci
- name: Prettier Format Check
@ -43,7 +43,7 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Generate files in working directory
shell: bash
run: __tests__/create-cache-files.sh ${{ runner.os }} test-cache
@ -66,7 +66,7 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Restore cache
uses: ./
with:
@ -96,7 +96,7 @@ jobs:
https_proxy: http://squid-proxy:3128
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Generate files
run: __tests__/create-cache-files.sh proxy test-cache
- name: Save cache
@ -119,7 +119,7 @@ jobs:
https_proxy: http://squid-proxy:3128
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Restore cache
uses: ./
with:

View File

@ -14,9 +14,3 @@ allowed:
reviewed:
npm:
- sax
- "@protobuf-ts/plugin-framework" # Apache-2.0
- "@protobuf-ts/runtime" # Apache-2.0
- fs.realpath # ISC
- glob # ISC
- prettier # MIT
- lodash # MIT

BIN
.licenses/NOTICE generated

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
.licenses/npm/psl.dep.yml generated Normal file

Binary file not shown.

Binary file not shown.

BIN
.licenses/npm/tough-cookie-3.0.1.dep.yml generated Normal file

Binary file not shown.

BIN
.licenses/npm/tough-cookie-4.0.0.dep.yml generated Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
.licenses/npm/universalify.dep.yml generated Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

230
README.md
View File

@ -1,11 +1,12 @@
# Cache action
# cache
This action allows caching dependencies and build outputs to improve workflow execution time.
>Two other actions are available in addition to the primary `cache` action:
>
>* [Restore action](./restore/README.md)
>* [Save action](./save/README.md)
In addition to this `cache` action, other two actions are also available
[Restore action](./restore/README.md)
[Save action](./save/README.md)
[![Tests](https://github.com/actions/cache/actions/workflows/workflow.yml/badge.svg)](https://github.com/actions/cache/actions/workflows/workflow.yml)
@ -13,33 +14,10 @@ This action allows caching dependencies and build outputs to improve workflow ex
See ["Caching dependencies to speed up workflows"](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows).
## What's New
### ⚠️ Important changes
The cache backend service has been rewritten from the ground up for improved performance and reliability. [actions/cache](https://github.com/actions/cache) now integrates with the new cache service (v2) APIs.
The new service will gradually roll out as of **February 1st, 2025**. The legacy service will also be sunset on the same date. Changes in these release are **fully backward compatible**.
**We are deprecating some versions of this action**. We recommend upgrading to version `v4` or `v3` as soon as possible before **February 1st, 2025.** (Upgrade instructions below).
If you are using pinned SHAs, please use the SHAs of versions `v4.2.0` or `v3.4.0`
If you do not upgrade, all workflow runs using any of the deprecated [actions/cache](https://github.com/actions/cache) will fail.
Upgrading to the recommended versions will not break your workflows.
Read more about the change & access the migration guide: [reference to the announcement](https://github.com/actions/cache/discussions/1510).
### v4
* Integrated with the new cache service (v2) APIs.
* Updated to node 20
### v3
* Integrated with the new cache service (v2) APIs.
* Added support for caching in GHES 3.5+.
* Added support for caching from GHES 3.5.
* Fixed download issue for files > 2GB during restore.
* Updated the minimum runner version support from node 12 -> node 16.
* Fixed avoiding empty cache save when no files are available for caching.
@ -48,56 +26,40 @@ Read more about the change & access the migration guide: [reference to the annou
* Fixed cache not working with github workspace directory or current directory.
* Fixed the download stuck problem by introducing a timeout of 1 hour for cache downloads.
* Fix zstd not working for windows on gnu tar in issues.
* Allowing users to provide a custom timeout as input for aborting download of a cache segment using an environment variable `SEGMENT_DOWNLOAD_TIMEOUT_MINS`. Default is 10 minutes.
* New actions are available for granular control over caches - [restore](restore/action.yml) and [save](save/action.yml).
* Support cross-os caching as an opt-in feature. See [Cross OS caching](./tips-and-workarounds.md#cross-os-cache) for more info.
* Added option to fail job on cache miss. See [Exit workflow on cache miss](./restore/README.md#exit-workflow-on-cache-miss) for more info.
* Fix zstd not being used after zstd version upgrade to 1.5.4 on hosted runners
* Added option to lookup cache without downloading it.
* Reduced segment size to 128MB and segment timeout to 10 minutes to fail fast in case the cache download is stuck.
* Allowing users to provide a custom timeout as input for aborting download of a cache segment using an environment variable `SEGMENT_DOWNLOAD_TIMEOUT_MINS`. Default is 60 minutes.
See the [v2 README.md](https://github.com/actions/cache/blob/v2/README.md) for older updates.
Refer [here](https://github.com/actions/cache/blob/v2/README.md) for previous versions
## Usage
### Pre-requisites
Create a workflow `.yml` file in your repositories `.github/workflows` directory. An [example workflow](#example-workflow) is available below. For more information, reference the GitHub Help Documentation for [Creating a workflow file](https://help.github.com/en/articles/configuring-a-workflow#creating-a-workflow-file).
Create a workflow `.yml` file in your repository's `.github/workflows` directory. An [example workflow](#example-cache-workflow) is available below. For more information, see the GitHub Help Documentation for [Creating a workflow file](https://help.github.com/en/articles/configuring-a-workflow#creating-a-workflow-file).
If you are using this inside a container, a POSIX-compliant `tar` needs to be included and accessible from the execution path.
If you are using a `self-hosted` Windows runner, `GNU tar` and `zstd` are required for [Cross-OS caching](https://github.com/actions/cache/blob/main/tips-and-workarounds.md#cross-os-cache) to work. They are also recommended to be installed in general so the performance is on par with `hosted` Windows runners.
If you are using this inside a container, a POSIX-compliant `tar` needs to be included and accessible in the execution path.
### Inputs
* `key` - An explicit key for a cache entry. See [creating a cache key](#creating-a-cache-key).
* `path` - A list of files, directories, and wildcard patterns to cache and restore. See [`@actions/glob`](https://github.com/actions/toolkit/tree/main/packages/glob) for supported patterns.
* `restore-keys` - An ordered multiline string listing the prefix-matched keys, that are used for restoring stale cache if no cache hit occurred for key.
* `enableCrossOsArchive` - An optional boolean when enabled, allows Windows runners to save or restore caches that can be restored or saved respectively on other platforms. Default: `false`
* `fail-on-cache-miss` - Fail the workflow if cache entry is not found. Default: `false`
* `lookup-only` - If true, only checks if cache entry exists and skips download. Does not change save cache behavior. Default: `false`
* `key` - An explicit key for restoring and saving the cache
* `restore-keys` - An ordered list of prefix-matched keys to use for restoring stale cache if no cache hit occurred for key.
#### Environment Variables
* `SEGMENT_DOWNLOAD_TIMEOUT_MINS` - Segment download timeout (in minutes, default `10`) to abort download of the segment if not completed in the defined number of minutes. [Read more](https://github.com/actions/cache/blob/main/tips-and-workarounds.md#cache-segment-restore-timeout)
* `SEGMENT_DOWNLOAD_TIMEOUT_MINS` - Segment download timeout (in minutes, default `60`) to abort download of the segment if not completed in the defined number of minutes. [Read more](https://github.com/actions/cache/blob/main/workarounds.md#cache-segment-restore-timeout)
### Outputs
* `cache-hit` - A string value to indicate an exact match was found for the key.
* If there's a cache hit, this will be 'true' or 'false' to indicate if there's an exact match for `key`.
* If there's a cache miss, this will be an empty string.
* `cache-hit` - A boolean value to indicate an exact match was found for the key.
> Note: `cache-hit` will be set to `true` only when cache hit occurs for the exact `key` match. For a partial key match via `restore-keys` or a cache miss, it will be set to `false`.
See [Skipping steps based on cache-hit](#skipping-steps-based-on-cache-hit) for info on using this output
### Cache scopes
The cache is scoped to the key, [version](#cache-version), and branch. The default branch cache is available to other branches.
The cache is scoped to the key, [version](#cache-version) and branch. The default branch cache is available to other branches.
See [Matching a cache key](https://help.github.com/en/actions/configuring-and-managing-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key) for more info.
### Example cache workflow
#### Restoring and saving cache using a single action
### Example workflow
```yaml
name: Caching Primes
@ -109,11 +71,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: Cache Primes
id: cache-primes
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: prime-numbers
key: ${{ runner.os }}-primes
@ -126,49 +88,7 @@ jobs:
run: /primes.sh -d prime-numbers
```
The `cache` action provides a `cache-hit` output which is set to `true` when the cache is restored using the primary `key` and `false` when the cache is restored using `restore-keys` or no cache is restored.
#### Using a combination of restore and save actions
```yaml
name: Caching Primes
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Restore cached Primes
id: cache-primes-restore
uses: actions/cache/restore@v4
with:
path: |
path/to/dependencies
some/other/dependencies
key: ${{ runner.os }}-primes
.
. //intermediate workflow steps
.
- name: Save Primes
id: cache-primes-save
uses: actions/cache/save@v4
with:
path: |
path/to/dependencies
some/other/dependencies
key: ${{ steps.cache-primes-restore.outputs.cache-primary-key }}
```
> **Note**
> You must use the `cache` or `restore` action in your workflow before you need to use the files that might be restored from the cache. If the provided `key` matches an existing cache, a new cache is not created and if the provided `key` doesn't match an existing cache, a new cache is automatically created provided the job completes successfully.
## Caching Strategies
With the introduction of the `restore` and `save` actions, a lot of caching use cases can now be achieved. Please see the [caching strategies](./caching-strategies.md) document for understanding how you can use the actions strategically to achieve the desired goal.
> Note: You must use the `cache` action in your workflow before you need to use the files that might be restored from the cache. If the provided `key` matches an existing cache, a new cache is not created and if the provided `key` doesn't match an existing cache, a new cache is automatically created provided the job completes successfully.
## Implementation Examples
@ -176,32 +96,30 @@ Every programming language and framework has its own way of caching.
See [Examples](examples.md) for a list of `actions/cache` implementations for use with:
* [Bun](./examples.md#bun)
* [C# - NuGet](./examples.md#c---nuget)
* [Clojure - Lein Deps](./examples.md#clojure---lein-deps)
* [D - DUB](./examples.md#d---dub)
* [Deno](./examples.md#deno)
* [Elixir - Mix](./examples.md#elixir---mix)
* [Go - Modules](./examples.md#go---modules)
* [Haskell - Cabal](./examples.md#haskell---cabal)
* [Haskell - Stack](./examples.md#haskell---stack)
* [Java - Gradle](./examples.md#java---gradle)
* [Java - Maven](./examples.md#java---maven)
* [Node - npm](./examples.md#node---npm)
* [Node - Lerna](./examples.md#node---lerna)
* [Node - Yarn](./examples.md#node---yarn)
* [OCaml/Reason - esy](./examples.md#ocamlreason---esy)
* [PHP - Composer](./examples.md#php---composer)
* [Python - pip](./examples.md#python---pip)
* [Python - pipenv](./examples.md#python---pipenv)
* [R - renv](./examples.md#r---renv)
* [Ruby - Bundler](./examples.md#ruby---bundler)
* [Rust - Cargo](./examples.md#rust---cargo)
* [Scala - SBT](./examples.md#scala---sbt)
* [Swift, Objective-C - Carthage](./examples.md#swift-objective-c---carthage)
* [Swift, Objective-C - CocoaPods](./examples.md#swift-objective-c---cocoapods)
* [Swift - Swift Package Manager](./examples.md#swift---swift-package-manager)
* [Swift - Mint](./examples.md#swift---mint)
- [C# - NuGet](./examples.md#c---nuget)
- [Clojure - Lein Deps](./examples.md#clojure---lein-deps)
- [D - DUB](./examples.md#d---dub)
- [Deno](./examples.md#deno)
- [Elixir - Mix](./examples.md#elixir---mix)
- [Go - Modules](./examples.md#go---modules)
- [Haskell - Cabal](./examples.md#haskell---cabal)
- [Haskell - Stack](./examples.md#haskell---stack)
- [Java - Gradle](./examples.md#java---gradle)
- [Java - Maven](./examples.md#java---maven)
- [Node - npm](./examples.md#node---npm)
- [Node - Lerna](./examples.md#node---lerna)
- [Node - Yarn](./examples.md#node---yarn)
- [OCaml/Reason - esy](./examples.md#ocamlreason---esy)
- [PHP - Composer](./examples.md#php---composer)
- [Python - pip](./examples.md#python---pip)
- [Python - pipenv](./examples.md#python---pipenv)
- [R - renv](./examples.md#r---renv)
- [Ruby - Bundler](./examples.md#ruby---bundler)
- [Rust - Cargo](./examples.md#rust---cargo)
- [Scala - SBT](./examples.md#scala---sbt)
- [Swift, Objective-C - Carthage](./examples.md#swift-objective-c---carthage)
- [Swift, Objective-C - CocoaPods](./examples.md#swift-objective-c---cocoapods)
- [Swift - Swift Package Manager](./examples.md#swift---swift-package-manager)
## Creating a cache key
@ -210,7 +128,7 @@ A cache key can include any of the contexts, functions, literals, and operators
For example, using the [`hashFiles`](https://docs.github.com/en/actions/learn-github-actions/expressions#hashfiles) function allows you to create a new cache when dependencies change.
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
path/to/dependencies
@ -225,10 +143,10 @@ Additionally, you can use arbitrary command output in a cache key, such as a dat
- name: Get Date
id: get-date
run: |
echo "date=$(/bin/date -u "+%Y%m%d")" >> $GITHUB_OUTPUT
echo "::set-output name=date::$(/bin/date -u "+%Y%m%d")"
shell: bash
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: path/to/dependencies
key: ${{ runner.os }}-${{ steps.get-date.outputs.date }}-${{ hashFiles('**/lockfiles') }}
@ -242,15 +160,14 @@ A repository can have up to 10GB of caches. Once the 10GB limit is reached, olde
## Skipping steps based on cache-hit
Using the `cache-hit` output, subsequent steps (such as install or build) can be skipped when a cache hit occurs on the key. It is recommended to install missing/updated dependencies in case of a partial key match when the key is dependent on the `hash` of the package file.
Using the `cache-hit` output, subsequent steps (such as install or build) can be skipped when a cache hit occurs on the key. It is recommended to install the missing/updated dependencies in case of a partial key match when the key is dependent on the `hash` of the package file.
Example:
```yaml
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- uses: actions/cache@v4
- uses: actions/cache@v3
id: cache
with:
path: path/to/dependencies
@ -261,13 +178,13 @@ steps:
run: /install.sh
```
> **Note** The `id` defined in `actions/cache` must match the `id` in the `if` statement (i.e. `steps.[ID].outputs.cache-hit`)
> Note: The `id` defined in `actions/cache` must match the `id` in the `if` statement (i.e. `steps.[ID].outputs.cache-hit`)
## Cache Version
Cache version is a hash [generated](https://github.com/actions/toolkit/blob/500d0b42fee2552ae9eeb5933091fe2fbf14e72d/packages/cache/src/internal/cacheHttpClient.ts#L73-L90) for a combination of compression tool used (Gzip, Zstd, etc. based on the runner OS) and the `path` of directories being cached. If two caches have different versions, they are identified as unique caches while matching. This for example, means that a cache created on `windows-latest` runner can't be restored on `ubuntu-latest` as cache `Version`s are different.
Cache version is a hash [generated](https://github.com/actions/toolkit/blob/500d0b42fee2552ae9eeb5933091fe2fbf14e72d/packages/cache/src/internal/cacheHttpClient.ts#L73-L90) for a combination of compression tool used (Gzip, Zstd, etc. based on the runner OS) and the `path` of directories being cached. If two caches have different versions, they are identified as unique caches while matching. This, for example, means that a cache created on a `windows-latest` runner can't be restored on `ubuntu-latest` as cache `Version`s are different.
> Pro tip: The [list caches](https://docs.github.com/en/rest/actions/cache#list-github-actions-caches-for-a-repository) API can be used to get the version of a cache. This can be helpful to troubleshoot cache miss due to version.
> Pro tip: [List caches](https://docs.github.com/en/rest/actions/cache#list-github-actions-caches-for-a-repository) API can be used to get the version of a cache. This can be helpful to troubleshoot cache miss due to version.
<details>
<summary>Example</summary>
@ -278,11 +195,11 @@ jobs:
build-linux:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: Cache Primes
id: cache-primes
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: prime-numbers
key: primes
@ -293,7 +210,7 @@ jobs:
- name: Cache Numbers
id: cache-numbers
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: numbers
key: primes
@ -305,11 +222,11 @@ jobs:
build-windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: Cache Primes
id: cache-primes
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: prime-numbers
key: primes
@ -318,27 +235,22 @@ jobs:
if: steps.cache-primes.outputs.cache-hit != 'true'
run: ./generate-primes -d prime-numbers
```
</details>
## Known practices and workarounds
Following are some of the known practices/workarounds which community has used to fulfill specific requirements. You may choose to use them if suits your use case. Note these are not necessarily the only or the recommended solution.
There are a number of community practices/workarounds to fulfill specific requirements. You may choose to use them if they suit your use case. Note these are not necessarily the only solution or even a recommended solution.
- [Cache segment restore timeout](./tips-and-workarounds.md#cache-segment-restore-timeout)
- [Update a cache](./tips-and-workarounds.md#update-a-cache)
- [Use cache across feature branches](./tips-and-workarounds.md#use-cache-across-feature-branches)
- [Improving cache restore performance on Windows/Using cross-os caching](./tips-and-workarounds.md#improving-cache-restore-performance-on-windows-using-cross-os-caching)
- [Force deletion of caches overriding default cache eviction policy](./tips-and-workarounds.md#force-deletion-of-caches-overriding-default-cache-eviction-policy)
* [Cache segment restore timeout](./tips-and-workarounds.md#cache-segment-restore-timeout)
* [Update a cache](./tips-and-workarounds.md#update-a-cache)
* [Use cache across feature branches](./tips-and-workarounds.md#use-cache-across-feature-branches)
* [Cross OS cache](./tips-and-workarounds.md#cross-os-cache)
* [Force deletion of caches overriding default cache eviction policy](./tips-and-workarounds.md#force-deletion-of-caches-overriding-default-cache-eviction-policy)
### Windows environment variables
Please note that Windows environment variables (like `%LocalAppData%`) will NOT be expanded by this action. Instead, prefer using `~` in your paths which will expand to the HOME directory. For example, instead of `%LocalAppData%`, use `~\AppData\Local`. For a list of supported default environment variables, see the [Learn GitHub Actions: Variables](https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables) page.
#### Windows environment variables
Please note that Windows environment variables (like `%LocalAppData%`) will NOT be expanded by this action. Instead, prefer using `~` in your paths which will expand to HOME directory. For example, instead of `%LocalAppData%`, use `~\AppData\Local`. For a list of supported default environment variables, see [this](https://docs.github.com/en/actions/learn-github-actions/environment-variables) page.
## Contributing
We would love for you to contribute to `actions/cache`. Pull requests are welcome! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) for more information.
We would love for you to contribute to `actions/cache`, pull requests are welcome! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) for more information.
## License
The scripts and documentation in this project are released under the [MIT License](LICENSE)

View File

@ -1,174 +1,54 @@
# Releases
### 4.2.3
- Bump `@actions/cache` to v4.0.3 (obfuscates SAS token in debug logs for cache entries)
### 4.2.2
- Bump `@actions/cache` to v4.0.2
### 4.2.1
- Bump `@actions/cache` to v4.0.1
### 4.2.0
TLDR; The cache backend service has been rewritten from the ground up for improved performance and reliability. [actions/cache](https://github.com/actions/cache) now integrates with the new cache service (v2) APIs.
The new service will gradually roll out as of **February 1st, 2025**. The legacy service will also be sunset on the same date. Changes in these release are **fully backward compatible**.
**We are deprecating some versions of this action**. We recommend upgrading to version `v4` or `v3` as soon as possible before **February 1st, 2025.** (Upgrade instructions below).
If you are using pinned SHAs, please use the SHAs of versions `v4.2.0` or `v3.4.0`
If you do not upgrade, all workflow runs using any of the deprecated [actions/cache](https://github.com/actions/cache) will fail.
Upgrading to the recommended versions will not break your workflows.
### 4.1.2
- Add GitHub Enterprise Cloud instances hostname filters to inform API endpoint choices - [#1474](https://github.com/actions/cache/pull/1474)
- Security fix: Bump braces from 3.0.2 to 3.0.3 - [#1475](https://github.com/actions/cache/pull/1475)
### 4.1.1
- Restore original behavior of `cache-hit` output - [#1467](https://github.com/actions/cache/pull/1467)
### 4.1.0
- Ensure `cache-hit` output is set when a cache is missed - [#1404](https://github.com/actions/cache/pull/1404)
- Deprecate `save-always` input - [#1452](https://github.com/actions/cache/pull/1452)
### 4.0.2
- Fixed restore `fail-on-cache-miss` not working.
### 4.0.1
- Updated `isGhes` check
### 4.0.0
- Updated minimum runner version support from node 12 -> node 20
### 3.4.0
- Integrated with the new cache service (v2) APIs
### 3.3.3
- Updates @actions/cache to v3.2.3 to fix accidental mutated path arguments to `getCacheVersion` [actions/toolkit#1378](https://github.com/actions/toolkit/pull/1378)
- Additional audit fixes of npm package(s)
### 3.3.2
- Fixes bug with Azure SDK causing blob downloads to get stuck.
### 3.3.1
- Reduced segment size to 128MB and segment timeout to 10 minutes to fail fast in case the cache download is stuck.
### 3.3.0
- Added option to lookup cache without downloading it.
### 3.2.6
- Fix zstd not being used after zstd version upgrade to 1.5.4 on hosted runners.
### 3.2.5
- Added fix to prevent from setting MYSYS environment variable globally.
### 3.2.4
- Added option to fail job on cache miss.
### 3.2.3
- Support cross os caching on Windows as an opt-in feature.
- Fix issue with symlink restoration on Windows for cross-os caches.
### 3.2.2
- Reverted the changes made in 3.2.1 to use gnu tar and zstd by default on windows.
### 3.2.1
- Update `@actions/cache` on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. ([issue](https://github.com/actions/cache/issues/984))
- Added support for fallback to gzip to restore old caches on windows.
- Added logs for cache version in case of a cache miss.
### 3.2.0
- Released the two new actions - [restore](restore/action.yml) and [save](save/action.yml) for granular control on cache
### 3.2.0-beta.1
- Added two new actions - [restore](restore/action.yml) and [save](save/action.yml) for granular control on cache.
### 3.1.0-beta.3
- Bug fixes for bsdtar fallback if gnutar not available and gzip fallback if cache saved using old cache action on windows.
### 3.1.0-beta.2
- Added support for fallback to gzip to restore old caches on windows.
### 3.1.0-beta.1
- Update `@actions/cache` on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. ([issue](https://github.com/actions/cache/issues/984))
### 3.0.11
- Update toolkit version to 3.0.5 to include `@actions/core@^1.10.0`
- Update `@actions/cache` to use updated `saveState` and `setOutput` functions from `@actions/core@^1.10.0`
### 3.0.10
- Fix a bug with sorting inputs.
- Update definition for restore-keys in README.md
### 3.0.9
- Enhanced the warning message for cache unavailablity in case of GHES.
### 3.0.8
- Fix zstd not working for windows on gnu tar in issues [#888](https://github.com/actions/cache/issues/888) and [#891](https://github.com/actions/cache/issues/891).
- Allowing users to provide a custom timeout as input for aborting download of a cache segment using an environment variable `SEGMENT_DOWNLOAD_TIMEOUT_MINS`. Default is 60 minutes.
### 3.0.7
- Fixed [#810](https://github.com/actions/cache/issues/810) - download stuck issue. A new timeout is introduced in the download process to abort the download if it gets stuck and doesn't finish within an hour.
### 3.0.6
- Fixed [#809](https://github.com/actions/cache/issues/809) - zstd -d: no such file or directory error
- Fixed [#833](https://github.com/actions/cache/issues/833) - cache doesn't work with github workspace directory
### 3.0.5
- Removed error handling by consuming actions/cache 3.0 toolkit, Now cache server error handling will be done by toolkit. ([PR](https://github.com/actions/cache/pull/834))
### 3.0.4
- Fixed tar creation error while trying to create tar with path as `~/` home folder on `ubuntu-latest`. ([issue](https://github.com/actions/cache/issues/689))
### 3.0.3
- Fixed avoiding empty cache save when no files are available for caching. ([issue](https://github.com/actions/cache/issues/624))
### 3.0.2
- Added support for dynamic cache size cap on GHES.
### 3.0.0
- Updated minimum runner version support from node 12 -> node 16
### 3.0.1
- Added support for caching from GHES 3.5.
- Fixed download issue for files > 2GB during restore.
### 3.0.0
### 3.0.2
- Added support for dynamic cache size cap on GHES.
- Updated minimum runner version support from node 12 -> node 16
### 3.0.3
- Fixed avoiding empty cache save when no files are available for caching. ([issue](https://github.com/actions/cache/issues/624))
### 3.0.4
- Fixed tar creation error while trying to create tar with path as `~/` home folder on `ubuntu-latest`. ([issue](https://github.com/actions/cache/issues/689))
### 3.0.5
- Removed error handling by consuming actions/cache 3.0 toolkit, Now cache server error handling will be done by toolkit. ([PR](https://github.com/actions/cache/pull/834))
### 3.0.6
- Fixed [#809](https://github.com/actions/cache/issues/809) - zstd -d: no such file or directory error
- Fixed [#833](https://github.com/actions/cache/issues/833) - cache doesn't work with github workspace directory
### 3.0.7
- Fixed [#810](https://github.com/actions/cache/issues/810) - download stuck issue. A new timeout is introduced in the download process to abort the download if it gets stuck and doesn't finish within an hour.
### 3.0.8
- Fix zstd not working for windows on gnu tar in issues [#888](https://github.com/actions/cache/issues/888) and [#891](https://github.com/actions/cache/issues/891).
- Allowing users to provide a custom timeout as input for aborting download of a cache segment using an environment variable `SEGMENT_DOWNLOAD_TIMEOUT_MINS`. Default is 60 minutes.
### 3.0.9
- Enhanced the warning message for cache unavailablity in case of GHES.
### 3.0.10
- Fix a bug with sorting inputs.
- Update definition for restore-keys in README.md
### 3.0.11
- Update toolkit version to 3.0.5 to include `@actions/core@^1.10.0`
- Update `@actions/cache` to use updated `saveState` and `setOutput` functions from `@actions/core@^1.10.0`
### 3.1.0-beta.1
- Update `@actions/cache` on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. ([issue](https://github.com/actions/cache/issues/984))
### 3.1.0-beta.2
- Added support for fallback to gzip to restore old caches on windows.
### 3.1.0-beta.3
- Bug fixes for bsdtar fallback if gnutar not available and gzip fallback if cache saved using old cache action on windows.
### 3.2.0-beta.1
- Added two new actions - [restore](restore/action.yml) and [save](save/action.yml) for granular control on cache.

View File

@ -8,26 +8,17 @@ import * as testUtils from "../src/utils/testUtils";
jest.mock("@actions/core");
jest.mock("@actions/cache");
let pristineEnv: NodeJS.ProcessEnv;
beforeAll(() => {
pristineEnv = process.env;
jest.spyOn(core, "getInput").mockImplementation((name, options) => {
return jest.requireActual("@actions/core").getInput(name, options);
});
});
beforeEach(() => {
jest.resetModules();
process.env = pristineEnv;
afterEach(() => {
delete process.env[Events.Key];
delete process.env[RefKey];
});
afterAll(() => {
process.env = pristineEnv;
});
test("isGhes returns true if server url is not github.com", () => {
try {
process.env["GITHUB_SERVER_URL"] = "http://example.com";
@ -183,26 +174,6 @@ test("getInputAsInt throws if required and value missing", () => {
).toThrowError();
});
test("getInputAsBool returns false if input not set", () => {
expect(actionUtils.getInputAsBool("undefined")).toBe(false);
});
test("getInputAsBool returns value if input is valid", () => {
testUtils.setInput("foo", "true");
expect(actionUtils.getInputAsBool("foo")).toBe(true);
});
test("getInputAsBool returns false if input is invalid or NaN", () => {
testUtils.setInput("foo", "bar");
expect(actionUtils.getInputAsBool("foo")).toBe(false);
});
test("getInputAsBool throws if required and value missing", () => {
expect(() =>
actionUtils.getInputAsBool("undefined2", { required: true })
).toThrowError();
});
test("isCacheFeatureAvailable for ac enabled", () => {
jest.spyOn(cache, "isFeatureAvailable").mockImplementation(() => true);
@ -240,28 +211,3 @@ test("isCacheFeatureAvailable for ac disabled on dotcom", () => {
delete process.env["GITHUB_SERVER_URL"];
}
});
test("isGhes returns false when the GITHUB_SERVER_URL environment variable is not defined", async () => {
delete process.env["GITHUB_SERVER_URL"];
expect(actionUtils.isGhes()).toBeFalsy();
});
test("isGhes returns false when the GITHUB_SERVER_URL environment variable is set to github.com", async () => {
process.env["GITHUB_SERVER_URL"] = "https://github.com";
expect(actionUtils.isGhes()).toBeFalsy();
});
test("isGhes returns false when the GITHUB_SERVER_URL environment variable is set to a GitHub Enterprise Cloud-style URL", async () => {
process.env["GITHUB_SERVER_URL"] = "https://contoso.ghe.com";
expect(actionUtils.isGhes()).toBeFalsy();
});
test("isGhes returns false when the GITHUB_SERVER_URL environment variable has a .localhost suffix", async () => {
process.env["GITHUB_SERVER_URL"] = "https://mock-github.localhost";
expect(actionUtils.isGhes()).toBeFalsy();
});
test("isGhes returns true when the GITHUB_SERVER_URL environment variable is set to some other URL", async () => {
process.env["GITHUB_SERVER_URL"] = "https://src.onpremise.fabrikam.com";
expect(actionUtils.isGhes()).toBeTruthy();
});

View File

@ -2,7 +2,7 @@ import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, RefKey } from "../src/constants";
import { restoreRun } from "../src/restoreImpl";
import run from "../src/restore";
import * as actionUtils from "../src/utils/actionUtils";
import * as testUtils from "../src/utils/testUtils";
@ -27,17 +27,9 @@ beforeAll(() => {
return actualUtils.getInputAsArray(name, options);
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.getInputAsBool(name, options);
}
);
});
beforeEach(() => {
jest.restoreAllMocks();
process.env[Events.Key] = Events.Push;
process.env[RefKey] = "refs/heads/feature-branch";
@ -58,8 +50,7 @@ test("restore with no cache found", async () => {
const key = "node-test";
testUtils.setInputs({
path: path,
key,
enableCrossOsArchive: false
key
});
const infoMock = jest.spyOn(core, "info");
@ -71,18 +62,10 @@ test("restore with no cache found", async () => {
return Promise.resolve(undefined);
});
await restoreRun();
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(stateMock).toHaveBeenCalledTimes(1);
@ -101,8 +84,7 @@ test("restore with restore keys and no cache found", async () => {
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey],
enableCrossOsArchive: false
restoreKeys: [restoreKey]
});
const infoMock = jest.spyOn(core, "info");
@ -114,18 +96,10 @@ test("restore with restore keys and no cache found", async () => {
return Promise.resolve(undefined);
});
await restoreRun();
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, [restoreKey]);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(stateMock).toHaveBeenCalledTimes(1);
@ -142,8 +116,7 @@ test("restore with cache found for key", async () => {
const key = "node-test";
testUtils.setInputs({
path: path,
key,
enableCrossOsArchive: false
key
});
const infoMock = jest.spyOn(core, "info");
@ -156,18 +129,10 @@ test("restore with cache found for key", async () => {
return Promise.resolve(key);
});
await restoreRun();
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(stateMock).toHaveBeenCalledWith("CACHE_RESULT", key);
@ -187,8 +152,7 @@ test("restore with cache found for restore key", async () => {
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey],
enableCrossOsArchive: false
restoreKeys: [restoreKey]
});
const infoMock = jest.spyOn(core, "info");
@ -201,18 +165,10 @@ test("restore with cache found for restore key", async () => {
return Promise.resolve(restoreKey);
});
await restoreRun();
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, [restoreKey]);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(stateMock).toHaveBeenCalledWith("CACHE_RESULT", restoreKey);
@ -225,134 +181,3 @@ test("restore with cache found for restore key", async () => {
);
expect(failedMock).toHaveBeenCalledTimes(0);
});
test("Fail restore when fail on cache miss is enabled and primary + restore keys not found", async () => {
const path = "node_modules";
const key = "node-test";
const restoreKey = "node-";
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey],
failOnCacheMiss: true
});
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await restoreRun();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(0);
expect(failedMock).toHaveBeenCalledWith(
`Failed to restore cache entry. Exiting as fail-on-cache-miss is set. Input key: ${key}`
);
expect(failedMock).toHaveBeenCalledTimes(1);
});
test("restore when fail on cache miss is enabled and primary key doesn't match restored key", async () => {
const path = "node_modules";
const key = "node-test";
const restoreKey = "node-";
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey],
failOnCacheMiss: true
});
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(restoreKey);
});
await restoreRun();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(stateMock).toHaveBeenCalledWith("CACHE_RESULT", restoreKey);
expect(stateMock).toHaveBeenCalledTimes(2);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "false");
expect(infoMock).toHaveBeenCalledWith(
`Cache restored from key: ${restoreKey}`
);
expect(failedMock).toHaveBeenCalledTimes(0);
});
test("restore with fail on cache miss disabled and no cache found", async () => {
const path = "node_modules";
const key = "node-test";
const restoreKey = "node-";
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey],
failOnCacheMiss: false
});
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await restoreRun();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(stateMock).toHaveBeenCalledTimes(1);
expect(infoMock).toHaveBeenCalledWith(
`Cache not found for input keys: ${key}, ${restoreKey}`
);
expect(failedMock).toHaveBeenCalledTimes(0);
});

View File

@ -2,7 +2,7 @@ import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, RefKey } from "../src/constants";
import { restoreImpl } from "../src/restoreImpl";
import run from "../src/restoreImpl";
import { StateProvider } from "../src/stateProvider";
import * as actionUtils from "../src/utils/actionUtils";
import * as testUtils from "../src/utils/testUtils";
@ -28,17 +28,9 @@ beforeAll(() => {
return actualUtils.getInputAsArray(name, options);
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.getInputAsBool(name, options);
}
);
});
beforeEach(() => {
jest.restoreAllMocks();
process.env[Events.Key] = Events.Push;
process.env[RefKey] = "refs/heads/feature-branch";
@ -60,7 +52,7 @@ test("restore with invalid event outputs warning", async () => {
const invalidEvent = "commit_comment";
process.env[Events.Key] = invalidEvent;
delete process.env[RefKey];
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(logWarningMock).toHaveBeenCalledWith(
`Event Validation Error: The event type ${invalidEvent} is not supported because it's not tied to a branch or tag ref.`
);
@ -76,7 +68,7 @@ test("restore without AC available should no-op", async () => {
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(0);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
@ -92,7 +84,7 @@ test("restore on GHES without AC available should no-op", async () => {
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(0);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
@ -105,8 +97,7 @@ test("restore on GHES with AC available ", async () => {
const key = "node-test";
testUtils.setInputs({
path: path,
key,
enableCrossOsArchive: false
key
});
const infoMock = jest.spyOn(core, "info");
@ -119,18 +110,10 @@ test("restore on GHES with AC available ", async () => {
return Promise.resolve(key);
});
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
@ -143,7 +126,7 @@ test("restore on GHES with AC available ", async () => {
test("restore with no path should fail", async () => {
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(0);
// this input isn't necessary for restore b/c tarball contains entries relative to workspace
expect(failedMock).not.toHaveBeenCalledWith(
@ -155,7 +138,7 @@ test("restore with no key", async () => {
testUtils.setInput(Inputs.Path, "node_modules");
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(0);
expect(failedMock).toHaveBeenCalledWith(
"Input required and not supplied: key"
@ -169,22 +152,13 @@ test("restore with too many keys should fail", async () => {
testUtils.setInputs({
path: path,
key,
restoreKeys,
enableCrossOsArchive: false
restoreKeys
});
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
restoreKeys,
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, restoreKeys);
expect(failedMock).toHaveBeenCalledWith(
`Key Validation Error: Keys are limited to a maximum of 10.`
);
@ -195,22 +169,13 @@ test("restore with large key should fail", async () => {
const key = "foo".repeat(512); // Over the 512 character limit
testUtils.setInputs({
path: path,
key,
enableCrossOsArchive: false
key
});
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(failedMock).toHaveBeenCalledWith(
`Key Validation Error: ${key} cannot be larger than 512 characters.`
);
@ -221,22 +186,13 @@ test("restore with invalid key should fail", async () => {
const key = "comma,comma";
testUtils.setInputs({
path: path,
key,
enableCrossOsArchive: false
key
});
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(failedMock).toHaveBeenCalledWith(
`Key Validation Error: ${key} cannot contain commas.`
);
@ -247,8 +203,7 @@ test("restore with no cache found", async () => {
const key = "node-test";
testUtils.setInputs({
path: path,
key,
enableCrossOsArchive: false
key
});
const infoMock = jest.spyOn(core, "info");
@ -260,18 +215,10 @@ test("restore with no cache found", async () => {
return Promise.resolve(undefined);
});
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(failedMock).toHaveBeenCalledTimes(0);
@ -288,8 +235,7 @@ test("restore with restore keys and no cache found", async () => {
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey],
enableCrossOsArchive: false
restoreKeys: [restoreKey]
});
const infoMock = jest.spyOn(core, "info");
@ -301,18 +247,10 @@ test("restore with restore keys and no cache found", async () => {
return Promise.resolve(undefined);
});
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, [restoreKey]);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(failedMock).toHaveBeenCalledTimes(0);
@ -327,8 +265,7 @@ test("restore with cache found for key", async () => {
const key = "node-test";
testUtils.setInputs({
path: path,
key,
enableCrossOsArchive: false
key
});
const infoMock = jest.spyOn(core, "info");
@ -341,18 +278,10 @@ test("restore with cache found for key", async () => {
return Promise.resolve(key);
});
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
@ -369,8 +298,7 @@ test("restore with cache found for restore key", async () => {
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey],
enableCrossOsArchive: false
restoreKeys: [restoreKey]
});
const infoMock = jest.spyOn(core, "info");
@ -383,18 +311,10 @@ test("restore with cache found for restore key", async () => {
return Promise.resolve(restoreKey);
});
await restoreImpl(new StateProvider());
await run(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, [restoreKey]);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
@ -404,64 +324,3 @@ test("restore with cache found for restore key", async () => {
);
expect(failedMock).toHaveBeenCalledTimes(0);
});
test("restore with lookup-only set", async () => {
const path = "node_modules";
const key = "node-test";
testUtils.setInputs({
path: path,
key,
lookupOnly: true
});
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(key);
});
await restoreImpl(new StateProvider());
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: true
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(stateMock).toHaveBeenCalledWith("CACHE_RESULT", key);
expect(stateMock).toHaveBeenCalledTimes(2);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "true");
expect(infoMock).toHaveBeenCalledWith(
`Cache found and can be restored from key: ${key}`
);
expect(failedMock).toHaveBeenCalledTimes(0);
});
test("restore failure with earlyExit should call process exit", async () => {
testUtils.setInput(Inputs.Path, "node_modules");
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
const processExitMock = jest.spyOn(process, "exit").mockImplementation();
// call restoreImpl with `earlyExit` set to true
await restoreImpl(new StateProvider(), true);
expect(restoreCacheMock).toHaveBeenCalledTimes(0);
expect(failedMock).toHaveBeenCalledWith(
"Input required and not supplied: key"
);
expect(processExitMock).toHaveBeenCalledWith(1);
});

View File

@ -2,7 +2,7 @@ import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, RefKey } from "../src/constants";
import { restoreOnlyRun } from "../src/restoreImpl";
import run from "../src/restoreOnly";
import * as actionUtils from "../src/utils/actionUtils";
import * as testUtils from "../src/utils/testUtils";
@ -27,18 +27,9 @@ beforeAll(() => {
return actualUtils.getInputAsArray(name, options);
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
return jest
.requireActual("../src/utils/actionUtils")
.getInputAsBool(name, options);
}
);
});
beforeEach(() => {
jest.restoreAllMocks();
process.env[Events.Key] = Events.Push;
process.env[RefKey] = "refs/heads/feature-branch";
@ -59,8 +50,7 @@ test("restore with no cache found", async () => {
const key = "node-test";
testUtils.setInputs({
path: path,
key,
enableCrossOsArchive: false
key
});
const infoMock = jest.spyOn(core, "info");
@ -72,18 +62,10 @@ test("restore with no cache found", async () => {
return Promise.resolve(undefined);
});
await restoreOnlyRun();
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(outputMock).toHaveBeenCalledWith("cache-primary-key", key);
expect(outputMock).toHaveBeenCalledTimes(1);
@ -101,8 +83,7 @@ test("restore with restore keys and no cache found", async () => {
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey],
enableCrossOsArchive: false
restoreKeys: [restoreKey]
});
const infoMock = jest.spyOn(core, "info");
@ -114,18 +95,10 @@ test("restore with restore keys and no cache found", async () => {
return Promise.resolve(undefined);
});
await restoreOnlyRun();
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, [restoreKey]);
expect(outputMock).toHaveBeenCalledWith("cache-primary-key", key);
expect(failedMock).toHaveBeenCalledTimes(0);
@ -140,8 +113,7 @@ test("restore with cache found for key", async () => {
const key = "node-test";
testUtils.setInputs({
path: path,
key,
enableCrossOsArchive: false
key
});
const infoMock = jest.spyOn(core, "info");
@ -153,18 +125,10 @@ test("restore with cache found for key", async () => {
return Promise.resolve(key);
});
await restoreOnlyRun();
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(outputMock).toHaveBeenCalledWith("cache-primary-key", key);
expect(outputMock).toHaveBeenCalledWith("cache-hit", "true");
@ -183,8 +147,7 @@ test("restore with cache found for restore key", async () => {
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey],
enableCrossOsArchive: false
restoreKeys: [restoreKey]
});
const infoMock = jest.spyOn(core, "info");
@ -196,18 +159,10 @@ test("restore with cache found for restore key", async () => {
return Promise.resolve(restoreKey);
});
await restoreOnlyRun();
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, [restoreKey]);
expect(outputMock).toHaveBeenCalledWith("cache-primary-key", key);
expect(outputMock).toHaveBeenCalledWith("cache-hit", "false");

View File

@ -2,7 +2,7 @@ import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, RefKey } from "../src/constants";
import { saveRun } from "../src/saveImpl";
import run from "../src/save";
import * as actionUtils from "../src/utils/actionUtils";
import * as testUtils from "../src/utils/testUtils";
@ -35,14 +35,6 @@ beforeAll(() => {
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
return jest
.requireActual("../src/utils/actionUtils")
.getInputAsBool(name, options);
}
);
jest.spyOn(actionUtils, "isExactKeyMatch").mockImplementation(
(key, cacheResult) => {
return jest
@ -100,17 +92,12 @@ test("save with valid inputs uploads a cache", async () => {
return Promise.resolve(cacheId);
});
await saveRun();
await run();
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
{
expect(saveCacheMock).toHaveBeenCalledWith([inputPath], primaryKey, {
uploadChunkSize: 4000000
},
false
);
});
expect(failedMock).toHaveBeenCalledTimes(0);
});

View File

@ -2,7 +2,7 @@ import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, RefKey } from "../src/constants";
import { saveImpl } from "../src/saveImpl";
import run from "../src/saveImpl";
import { StateProvider } from "../src/stateProvider";
import * as actionUtils from "../src/utils/actionUtils";
import * as testUtils from "../src/utils/testUtils";
@ -32,14 +32,6 @@ beforeAll(() => {
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
return jest
.requireActual("../src/utils/actionUtils")
.getInputAsBool(name, options);
}
);
jest.spyOn(actionUtils, "isExactKeyMatch").mockImplementation(
(key, cacheResult) => {
return jest
@ -55,7 +47,6 @@ beforeAll(() => {
});
beforeEach(() => {
jest.restoreAllMocks();
process.env[Events.Key] = Events.Push;
process.env[RefKey] = "refs/heads/feature-branch";
@ -77,7 +68,7 @@ test("save with invalid event outputs warning", async () => {
const invalidEvent = "commit_comment";
process.env[Events.Key] = invalidEvent;
delete process.env[RefKey];
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(logWarningMock).toHaveBeenCalledWith(
`Event Validation Error: The event type ${invalidEvent} is not supported because it's not tied to a branch or tag ref.`
);
@ -100,7 +91,7 @@ test("save with no primary key in state outputs warning", async () => {
});
const saveCacheMock = jest.spyOn(cache, "saveCache");
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(0);
expect(logWarningMock).toHaveBeenCalledWith(`Key is not specified.`);
@ -115,7 +106,7 @@ test("save without AC available should no-op", async () => {
const saveCacheMock = jest.spyOn(cache, "saveCache");
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(0);
});
@ -128,7 +119,7 @@ test("save on ghes without AC available should no-op", async () => {
const saveCacheMock = jest.spyOn(cache, "saveCache");
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(0);
});
@ -161,17 +152,12 @@ test("save on GHES with AC available", async () => {
return Promise.resolve(cacheId);
});
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
{
expect(saveCacheMock).toHaveBeenCalledWith([inputPath], primaryKey, {
uploadChunkSize: 4000000
},
false
);
});
expect(failedMock).toHaveBeenCalledTimes(0);
});
@ -194,7 +180,7 @@ test("save with exact match returns early", async () => {
});
const saveCacheMock = jest.spyOn(cache, "saveCache");
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(0);
expect(infoMock).toHaveBeenCalledWith(
@ -221,7 +207,7 @@ test("save with missing input outputs warning", async () => {
});
const saveCacheMock = jest.spyOn(cache, "saveCache");
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(0);
expect(logWarningMock).toHaveBeenCalledWith(
@ -259,14 +245,13 @@ test("save with large cache outputs warning", async () => {
);
});
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
expect.anything(),
false
expect.anything()
);
expect(logWarningMock).toHaveBeenCalledTimes(1);
@ -306,14 +291,13 @@ test("save with reserve cache failure outputs warning", async () => {
throw error;
});
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
expect.anything(),
false
expect.anything()
);
expect(logWarningMock).toHaveBeenCalledWith(
@ -349,14 +333,13 @@ test("save with server error outputs warning", async () => {
throw new Error("HTTP Error Occurred");
});
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
expect.anything(),
false
expect.anything()
);
expect(logWarningMock).toHaveBeenCalledTimes(1);
@ -392,17 +375,12 @@ test("save with valid inputs uploads a cache", async () => {
return Promise.resolve(cacheId);
});
await saveImpl(new StateProvider());
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
{
expect(saveCacheMock).toHaveBeenCalledWith([inputPath], primaryKey, {
uploadChunkSize: 4000000
},
false
);
});
expect(failedMock).toHaveBeenCalledTimes(0);
});

View File

@ -2,7 +2,7 @@ import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, RefKey } from "../src/constants";
import { saveOnlyRun } from "../src/saveImpl";
import run from "../src/saveOnly";
import * as actionUtils from "../src/utils/actionUtils";
import * as testUtils from "../src/utils/testUtils";
@ -35,14 +35,6 @@ beforeAll(() => {
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
return jest
.requireActual("../src/utils/actionUtils")
.getInputAsBool(name, options);
}
);
jest.spyOn(actionUtils, "isExactKeyMatch").mockImplementation(
(key, cacheResult) => {
return jest
@ -90,50 +82,12 @@ test("save with valid inputs uploads a cache", async () => {
return Promise.resolve(cacheId);
});
await saveOnlyRun();
await run();
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
{
expect(saveCacheMock).toHaveBeenCalledWith([inputPath], primaryKey, {
uploadChunkSize: 4000000
},
false
);
});
expect(failedMock).toHaveBeenCalledTimes(0);
});
test("save failing logs the warning message", async () => {
const warningMock = jest.spyOn(core, "warning");
const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
const inputPath = "node_modules";
testUtils.setInput(Inputs.Key, primaryKey);
testUtils.setInput(Inputs.Path, inputPath);
testUtils.setInput(Inputs.UploadChunkSize, "4000000");
const cacheId = -1;
const saveCacheMock = jest
.spyOn(cache, "saveCache")
.mockImplementationOnce(() => {
return Promise.resolve(cacheId);
});
await saveOnlyRun();
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
{
uploadChunkSize: 4000000
},
false
);
expect(warningMock).toHaveBeenCalledTimes(1);
expect(warningMock).toHaveBeenCalledWith("Cache save failed.");
});

View File

@ -25,15 +25,16 @@ afterEach(() => {
});
test("StateProvider saves states", async () => {
const states = new Map<string, string>();
const getStateMock = jest
.spyOn(core, "getState")
.mockImplementation(key => states.get(key) || "");
.mockImplementation(name =>
jest.requireActual("@actions/core").getState(name)
);
const saveStateMock = jest
.spyOn(core, "saveState")
.mockImplementation((key, value) => {
states.set(key, value);
return jest.requireActual("@actions/core").saveState(key, value);
});
const setOutputMock = jest
@ -47,11 +48,9 @@ test("StateProvider saves states", async () => {
const stateProvider: IStateProvider = new StateProvider();
stateProvider.setState("stateKey", "stateValue");
stateProvider.setState(State.CacheMatchedKey, cacheMatchedKey);
const stateValue = stateProvider.getState("stateKey");
const cacheStateValue = stateProvider.getCacheState();
stateProvider.getState("stateKey");
stateProvider.getCacheState();
expect(stateValue).toBe("stateValue");
expect(cacheStateValue).toBe(cacheMatchedKey);
expect(getStateMock).toHaveBeenCalledTimes(2);
expect(saveStateMock).toHaveBeenCalledTimes(2);
expect(setOutputMock).toHaveBeenCalledTimes(0);

View File

@ -9,39 +9,19 @@ inputs:
description: 'An explicit key for restoring and saving the cache'
required: true
restore-keys:
description: 'An ordered multiline string listing the prefix-matched keys, that are used for restoring stale cache if no cache hit occurred for key. Note `cache-hit` returns false in this case.'
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
upload-chunk-size:
description: 'The chunk size used to split up large files during upload, in bytes'
required: false
enableCrossOsArchive:
description: 'An optional boolean when enabled, allows windows runners to save or restore caches that can be restored or saved respectively on other platforms'
default: 'false'
required: false
fail-on-cache-miss:
description: 'Fail the workflow if cache entry is not found'
default: 'false'
required: false
lookup-only:
description: 'Check if a cache entry exists for the given input(s) (key, restore-keys) without downloading the cache'
default: 'false'
required: false
save-always:
description: 'Run the post step to save the cache even if another step before fails'
default: 'false'
required: false
deprecationMessage: |
save-always does not work as intended and will be removed in a future release.
A separate `actions/cache/restore` step should be used instead.
See https://github.com/actions/cache/tree/main/save#always-save-cache for more details.
outputs:
cache-hit:
description: 'A boolean value to indicate an exact match was found for the primary key'
runs:
using: 'node20'
using: 'node16'
main: 'dist/restore/index.js'
post: 'dist/save/index.js'
post-if: "success()"
post-if: success()
branding:
icon: 'archive'
color: 'gray-dark'

View File

@ -1,289 +0,0 @@
# Caching Strategies
This document lists some of the strategies (and example workflows if possible) which can be used to ...
- use an effective cache key and/or path
- solve some common use cases around saving and restoring caches
- leverage the step inputs and outputs more effectively
## Choosing the right key
```yaml
jobs:
build:
runs-on: ubuntu-latest
- uses: actions/cache@v4
with:
key: ${{ some-metadata }}-cache
```
In your workflows, you can use different strategies to name your key depending on your use case so that the cache is scoped appropriately for your need. For example, you can have cache specific to OS, or based on the lockfile or commit SHA or even workflow run.
### Updating cache for any change in the dependencies
One of the most common use case is to use hash for lockfile as key. This way, same cache will be restored for a lockfile until there's a change in dependencies listed in lockfile.
```yaml
- uses: actions/cache@v4
with:
path: |
path/to/dependencies
some/other/dependencies
key: cache-${{ hashFiles('**/lockfiles') }}
```
### Using restore keys to download the closest matching cache
If cache is not found matching the primary key, restore keys can be used to download the closest matching cache that was recently created. This ensures that the build/install step will need to additionally fetch just a handful of newer dependencies, and hence saving build time.
```yaml
- uses: actions/cache@v4
with:
path: |
path/to/dependencies
some/other/dependencies
key: cache-npm-${{ hashFiles('**/lockfiles') }}
restore-keys: |
cache-npm-
```
The restore keys can be provided as a complete name, or a prefix, read more [here](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key) on how a cache key is matched using restore keys.
### Separate caches by Operating System
In case of workflows with matrix running for multiple Operating Systems, the caches can be stored separately for each of them. This can be used in combination with hashfiles in case multiple caches are being generated per OS.
```yaml
- uses: actions/cache@v4
with:
path: |
path/to/dependencies
some/other/dependencies
key: ${{ runner.os }}-cache
```
### Creating a short lived cache
Caches scoped to the particular workflow run id or run attempt can be stored and referred by using the run id/attempt. This is an effective way to have a short lived cache.
```yaml
key: cache-${{ github.run_id }}-${{ github.run_attempt }}
```
On similar lines, commit sha can be used to create a very specialized and short lived cache.
```yaml
- uses: actions/cache@v4
with:
path: |
path/to/dependencies
some/other/dependencies
key: cache-${{ github.sha }}
```
### Using multiple factors while forming a key depending on the need
Cache key can be formed by combination of more than one metadata, evaluated info.
```yaml
- uses: actions/cache@v4
with:
path: |
path/to/dependencies
some/other/dependencies
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
```
The [GitHub Context](https://docs.github.com/en/actions/learn-github-actions/contexts#github-context) can be used to create keys using the workflows metadata.
## Restoring Cache
### Understanding how to choose path
While setting paths for caching dependencies it is important to give correct path depending on the hosted runner you are using or whether the action is running in a container job. Assigning different `path` for save and restore will result in cache miss.
Below are GitHub hosted runner specific paths one should take care of when writing a workflow which saves/restores caches across OS.
#### Ubuntu Paths
Home directory (`~/`) = `/home/runner`
`${{ github.workspace }}` = `/home/runner/work/repo/repo`
`process.env['RUNNER_TEMP']`=`/home/runner/work/_temp`
`process.cwd()` = `/home/runner/work/repo/repo`
#### Windows Paths
Home directory (`~/`) = `C:\Users\runneradmin`
`${{ github.workspace }}` = `D:\a\repo\repo`
`process.env['RUNNER_TEMP']` = `D:\a\_temp`
`process.cwd()` = `D:\a\repo\repo`
#### macOS Paths
Home directory (`~/`) = `/Users/runner`
`${{ github.workspace }}` = `/Users/runner/work/repo/repo`
`process.env['RUNNER_TEMP']` = `/Users/runner/work/_temp`
`process.cwd()` = `/Users/runner/work/repo/repo`
Where:
`cwd()` = Current working directory where the repository code resides.
`RUNNER_TEMP` = Environment variable defined for temporary storage location.
### Make cache read only / Reuse cache from centralized job
In case you are using a centralized job to create and save your cache that can be reused by other jobs in your repository, this action will take care of your restore only needs and make the cache read-only.
```yaml
steps:
- uses: actions/checkout@v4
- uses: actions/cache/restore@v4
id: cache
with:
path: path/to/dependencies
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: /install.sh
- name: Build
run: /build.sh
- name: Publish package to public
run: /publish.sh
```
### Failing/Exiting the workflow if cache with exact key is not found
You can use the output of this action to exit the workflow on cache miss. This way you can restrict your workflow to only initiate the build when `cache-hit` occurs, in other words, cache with exact key is found.
```yaml
steps:
- uses: actions/checkout@v4
- uses: actions/cache/restore@v4
id: cache
with:
path: path/to/dependencies
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
- name: Check cache hit
if: steps.cache.outputs.cache-hit != 'true'
run: exit 1
- name: Build
run: /build.sh
```
## Saving cache
### Reusing primary key from restore cache as input to save action
If you want to avoid re-computing the cache key again in `save` action, the outputs from `restore` action can be used as input to the `save` action.
```yaml
- uses: actions/cache/restore@v4
id: restore-cache
with:
path: |
path/to/dependencies
some/other/dependencies
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
.
.
.
- uses: actions/cache/save@v4
with:
path: |
path/to/dependencies
some/other/dependencies
key: ${{ steps.restore-cache.outputs.cache-primary-key }}
```
### Re-evaluate cache key while saving cache
On the other hand, the key can also be explicitly re-computed while executing the save action. This helps in cases where the lockfiles are generated during the build.
Let's say we have a restore step that computes key at runtime
```yaml
uses: actions/cache/restore@v4
id: restore-cache
with:
key: cache-${{ hashFiles('**/lockfiles') }}
```
Case 1: Where an user would want to reuse the key as it is
```yaml
uses: actions/cache/save@v4
with:
key: ${{ steps.restore-cache.outputs.cache-primary-key }}
```
Case 2: Where the user would want to re-evaluate the key
```yaml
uses: actions/cache/save@v4
with:
key: npm-cache-${{hashfiles(package-lock.json)}}
```
### Saving cache even if the build fails
See [Always save cache](./save/README.md#always-save-cache).
### Saving cache once and reusing in multiple workflows
In case of multi-module projects, where the built artifact of one project needs to be reused in subsequent child modules, the need of rebuilding the parent module again and again with every build can be eliminated. The `actions/cache` or `actions/cache/save` action can be used to build and save the parent module artifact once, and restored multiple times while building the child modules.
#### Step 1 - Build the parent module and save it
```yaml
steps:
- uses: actions/checkout@v4
- name: Build
run: ./build-parent-module.sh
- uses: actions/cache/save@v4
id: cache
with:
path: path/to/dependencies
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
```
#### Step 2 - Restore the built artifact from cache using the same key and path
```yaml
steps:
- uses: actions/checkout@v4
- uses: actions/cache/restore@v4
id: cache
with:
path: path/to/dependencies
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: ./install.sh
- name: Build
run: ./build-child-module.sh
- name: Publish package to public
run: ./publish.sh
```

File diff suppressed because one or more lines are too long

63860
dist/restore/index.js vendored

File diff suppressed because one or more lines are too long

63787
dist/save-only/index.js vendored

File diff suppressed because one or more lines are too long

63821
dist/save/index.js vendored

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,5 @@
# Examples
- [Bun](#bun)
- [C# - NuGet](#c---nuget)
- [Clojure - Lein Deps](#clojure---lein-deps)
- [D - DUB](#d---dub)
@ -39,35 +38,13 @@
- [Swift, Objective-C - Carthage](#swift-objective-c---carthage)
- [Swift, Objective-C - CocoaPods](#swift-objective-c---cocoapods)
- [Swift - Swift Package Manager](#swift---swift-package-manager)
- [Swift - Mint](#swift---mint)
- [* - Bazel](#---bazel)
## Bun
```yaml
- uses: actions/cache@v4
with:
path: |
~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lockb') }}
```
### Windows
```yaml
- uses: actions/cache@v4
with:
path: |
~\.bun
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lockb') }}
```
## C# - NuGet
Using [NuGet lock files](https://docs.microsoft.com/nuget/consume-packages/package-references-in-project-files#locking-dependencies):
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
@ -76,10 +53,10 @@ Using [NuGet lock files](https://docs.microsoft.com/nuget/consume-packages/packa
```
Depending on the environment, huge packages might be pre-installed in the global cache folder.
With `actions/cache@v4` you can now exclude unwanted packages with [exclude pattern](https://github.com/actions/toolkit/tree/main/packages/glob#exclude-patterns)
With `actions/cache@v3` you can now exclude unwanted packages with [exclude pattern](https://github.com/actions/toolkit/tree/main/packages/glob#exclude-patterns)
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
~/.nuget/packages
@ -90,13 +67,13 @@ With `actions/cache@v4` you can now exclude unwanted packages with [exclude patt
```
Or you could move the cache folder like below.
> **Note** This workflow does not work for projects that require files to be placed in user profile package folder
>Note: This workflow does not work for projects that require files to be placed in user profile package folder
```yaml
env:
NUGET_PACKAGES: ${{ github.workspace }}/.nuget/packages
steps:
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: ${{ github.workspace }}/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
@ -108,7 +85,7 @@ steps:
```yaml
- name: Cache lein project dependencies
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-clojure-${{ hashFiles('**/project.clj') }}
@ -122,7 +99,7 @@ steps:
### POSIX
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: ~/.dub
key: ${{ runner.os }}-dub-${{ hashFiles('**/dub.selections.json') }}
@ -133,7 +110,7 @@ steps:
### Windows
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: ~\AppData\Local\dub
key: ${{ runner.os }}-dub-${{ hashFiles('**/dub.selections.json') }}
@ -146,7 +123,7 @@ steps:
### Linux
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
~/.deno
@ -157,7 +134,7 @@ steps:
### macOS
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
~/.deno
@ -168,7 +145,7 @@ steps:
### Windows
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
~\.deno
@ -179,7 +156,7 @@ steps:
## Elixir - Mix
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
deps
@ -206,7 +183,7 @@ steps:
### Linux
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
~/.cache/go-build
@ -219,7 +196,7 @@ steps:
### macOS
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
~/Library/Caches/go-build
@ -232,7 +209,7 @@ steps:
### Windows
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
~\AppData\Local\go-build
@ -248,7 +225,7 @@ We cache the elements of the Cabal store separately, as the entirety of `~/.caba
```yaml
- name: Cache ~/.cabal/packages, ~/.cabal/store and dist-newstyle
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: |
~/.cabal/packages
@ -263,14 +240,14 @@ We cache the elements of the Cabal store separately, as the entirety of `~/.caba
### Linux or macOS
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
name: Cache ~/.stack
with:
path: ~/.stack
key: ${{ runner.os }}-stack-global-${{ hashFiles('stack.yaml') }}-${{ hashFiles('package.yaml') }}
restore-keys: |
${{ runner.os }}-stack-global-
- uses: actions/cache@v4
- uses: actions/cache@v3
name: Cache .stack-work
with:
path: .stack-work
@ -282,7 +259,7 @@ We cache the elements of the Cabal store separately, as the entirety of `~/.caba
### Windows
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
name: Cache %APPDATA%\stack %LOCALAPPDATA%\Programs\stack
with:
path: |
@ -291,7 +268,7 @@ We cache the elements of the Cabal store separately, as the entirety of `~/.caba
key: ${{ runner.os }}-stack-global-${{ hashFiles('stack.yaml') }}-${{ hashFiles('package.yaml') }}
restore-keys: |
${{ runner.os }}-stack-global-
- uses: actions/cache@v4
- uses: actions/cache@v3
name: Cache .stack-work
with:
path: .stack-work
@ -302,10 +279,10 @@ We cache the elements of the Cabal store separately, as the entirety of `~/.caba
## Java - Gradle
> **Note** Ensure no Gradle daemons are running anymore when your workflow completes. Creating the cache package might fail due to locks being held by Gradle. Refer to the [Gradle Daemon documentation](https://docs.gradle.org/current/userguide/gradle_daemon.html) on how to disable or stop the Gradle Daemons.
>Note: Ensure no Gradle daemons are running anymore when your workflow completes. Creating the cache package might fail due to locks being held by Gradle. Refer to the [Gradle Daemon documentation](https://docs.gradle.org/current/userguide/gradle_daemon.html) on how to disable or stop the Gradle Daemons.
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
~/.gradle/caches
@ -319,7 +296,7 @@ We cache the elements of the Cabal store separately, as the entirety of `~/.caba
```yaml
- name: Cache local Maven repository
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
@ -334,7 +311,7 @@ For npm, cache files are stored in `~/.npm` on Posix, or `~\AppData\npm-cache` o
If using `npm config` to retrieve the cache directory, ensure you run [actions/setup-node](https://github.com/actions/setup-node) first to ensure your `npm` version is correct.
After [deprecation](https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/) of save-state and set-output commands, the correct way to set output is using `${GITHUB_OUTPUT}`. For linux, we can use `${GITHUB_OUTPUT}` whereas for windows we need to use `${env:GITHUB_OUTPUT}` due to two different default shells in these two different OS ie `bash` and `pwsh` respectively.
> **Note** It is not recommended to cache `node_modules`, as it can break across Node versions and won't work with `npm ci`
>Note: It is not recommended to cache `node_modules`, as it can break across Node versions and won't work with `npm ci`
### **Get npm cache directory using same shell**
### Bash shell
@ -355,7 +332,7 @@ After [deprecation](https://github.blog/changelog/2022-10-11-github-actions-depr
`Get npm cache directory` step can then be used with `actions/cache` as shown below
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
id: npm-cache # use this to check for `cache-hit` ==> if: steps.npm-cache.outputs.cache-hit != 'true'
with:
path: ${{ steps.npm-cache-dir.outputs.dir }}
@ -368,7 +345,7 @@ After [deprecation](https://github.blog/changelog/2022-10-11-github-actions-depr
```yaml
- name: restore lerna
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: '**/node_modules'
key: ${{ runner.os }}-${{ hashFiles('**/yarn.lock') }}
@ -380,9 +357,9 @@ The yarn cache directory will depend on your operating system and version of `ya
```yaml
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v4
- uses: actions/cache@v3
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
@ -398,9 +375,9 @@ The yarn 2 cache directory will depend on your config. See https://yarnpkg.com/c
```yaml
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT
run: echo "::set-output name=dir::$(yarn config get cacheFolder)"
- uses: actions/cache@v4
- uses: actions/cache@v3
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
@ -415,7 +392,7 @@ Esy allows you to export built dependencies and import pre-built dependencies.
```yaml
- name: Restore Cache
id: restore-cache
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: _export
key: ${{ runner.os }}-esy-${{ hashFiles('esy.lock/index.json') }}
@ -443,8 +420,8 @@ Esy allows you to export built dependencies and import pre-built dependencies.
- name: Get Composer Cache Directory
id: composer-cache
run: |
echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
- uses: actions/cache@v4
echo "::set-output name=dir::$(composer config cache-files-dir)"
- uses: actions/cache@v3
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
@ -465,7 +442,7 @@ Locations:
### Simple example
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
@ -478,7 +455,7 @@ Replace `~/.cache/pip` with the correct `path` if not using Ubuntu.
### Multiple OS's in a workflow
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
if: startsWith(runner.os, 'Linux')
with:
path: ~/.cache/pip
@ -486,7 +463,7 @@ Replace `~/.cache/pip` with the correct `path` if not using Ubuntu.
restore-keys: |
${{ runner.os }}-pip-
- uses: actions/cache@v4
- uses: actions/cache@v3
if: startsWith(runner.os, 'macOS')
with:
path: ~/Library/Caches/pip
@ -494,7 +471,7 @@ Replace `~/.cache/pip` with the correct `path` if not using Ubuntu.
restore-keys: |
${{ runner.os }}-pip-
- uses: actions/cache@v4
- uses: actions/cache@v3
if: startsWith(runner.os, 'Windows')
with:
path: ~\AppData\Local\pip\Cache
@ -520,7 +497,7 @@ jobs:
- os: windows-latest
path: ~\AppData\Local\pip\Cache
steps:
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: ${{ matrix.path }}
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
@ -530,16 +507,15 @@ jobs:
### Using pip to get cache location
> **Note** This requires pip 20.1+
> Note: This requires pip 20.1+
```yaml
- name: Get pip cache dir
id: pip-cache
shell: bash
run: |
echo "dir=$(pip cache dir)" >> $GITHUB_OUTPUT
echo "::set-output name=dir::$(pip cache dir)"
- name: pip cache
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: ${{ steps.pip-cache.outputs.dir }}
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
@ -557,7 +533,7 @@ jobs:
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: ~/.local/share/virtualenvs
key: ${{ runner.os }}-python-${{ steps.setup-python.outputs.python-version }}-pipenv-${{ hashFiles('Pipfile.lock') }}
@ -584,7 +560,7 @@ For renv, the cache directory will vary by OS. The `RENV_PATHS_ROOT` environment
cat("##[set-output name=r-version;]", R.Version()$version.string, sep = "")
shell: Rscript {0}
- name: Restore Renv package cache
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: ${{ env.RENV_PATHS_ROOT }}
key: ${{ steps.get-version.outputs.os-version }}-${{ steps.get-version.outputs.r-version }}-${{ inputs.cache-version }}-${{ hashFiles('renv.lock') }}
@ -610,7 +586,7 @@ whenever possible:
## Rust - Cargo
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
@ -625,7 +601,7 @@ whenever possible:
```yaml
- name: Cache SBT
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: |
~/.ivy2/cache
@ -636,7 +612,7 @@ whenever possible:
## Swift, Objective-C - Carthage
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: Carthage
key: ${{ runner.os }}-carthage-${{ hashFiles('**/Cartfile.resolved') }}
@ -647,7 +623,7 @@ whenever possible:
## Swift, Objective-C - CocoaPods
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: Pods
key: ${{ runner.os }}-pods-${{ hashFiles('**/Podfile.lock') }}
@ -658,57 +634,10 @@ whenever possible:
## Swift - Swift Package Manager
```yaml
- uses: actions/cache@v4
- uses: actions/cache@v3
with:
path: .build
key: ${{ runner.os }}-spm-${{ hashFiles('**/Package.resolved') }}
restore-keys: |
${{ runner.os }}-spm-
```
## Swift - Mint
```yaml
env:
MINT_PATH: .mint/lib
MINT_LINK_PATH: .mint/bin
steps:
- uses: actions/cache@v4
with:
path: .mint
key: ${{ runner.os }}-mint-${{ hashFiles('**/Mintfile') }}
restore-keys: |
${{ runner.os }}-mint-
```
## * - Bazel
[`bazelisk`](https://github.com/bazelbuild/bazelisk) does not have be to separately downloaded and installed because it's already included in GitHub's `ubuntu-latest` and `macos-latest` base images.
### Linux
```yaml
- name: Cache Bazel
uses: actions/cache@v4
with:
path: |
~/.cache/bazel
key: ${{ runner.os }}-bazel-${{ hashFiles('.bazelversion', '.bazelrc', 'WORKSPACE', 'WORKSPACE.bazel', 'MODULE.bazel') }}
restore-keys: |
${{ runner.os }}-bazel-
- run: bazelisk test //...
```
### macOS
```yaml
- name: Cache Bazel
uses: actions/cache@v4
with:
path: |
/private/var/tmp/_bazel_runner/
key: ${{ runner.os }}-bazel-${{ hashFiles('.bazelversion', '.bazelrc', 'WORKSPACE', 'WORKSPACE.bazel', 'MODULE.bazel') }}
restore-keys: |
${{ runner.os }}-bazel-
- run: bazelisk test //...
```

1757
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "cache",
"version": "4.2.3",
"version": "3.2.0-beta.1",
"private": true,
"description": "Cache dependencies and build outputs",
"main": "dist/restore/index.js",
@ -23,10 +23,10 @@
"author": "GitHub",
"license": "MIT",
"dependencies": {
"@actions/cache": "^4.0.3",
"@actions/core": "^1.11.1",
"@actions/cache": "3.1.0-beta.3",
"@actions/core": "^1.10.0",
"@actions/exec": "^1.1.1",
"@actions/io": "^1.1.3"
"@actions/io": "^1.1.2"
},
"devDependencies": {
"@types/jest": "^27.5.2",
@ -34,7 +34,7 @@
"@types/node": "^16.18.3",
"@typescript-eslint/eslint-plugin": "^5.45.0",
"@typescript-eslint/parser": "^5.45.0",
"@vercel/ncc": "^0.38.3",
"@zeit/ncc": "^0.20.5",
"eslint": "^8.28.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",

View File

@ -1,18 +1,14 @@
# Restore action
The restore action restores a cache. It works similarly to the `cache` action except that it doesn't have a post step to save the cache. This action provides granular ability to restore a cache without having to save it. It accepts the same set of inputs as the `cache` action.
The restore action, as the name suggest, restores a cache. It acts similar to the`cache` action except that it doesn't have a post step to save the cache. This action can provide you a granular control to only restore a cache without having to necessarily save it. It accepts the same set of inputs as the `cache` action.
## Documentation
## Inputs
### Inputs
* `key` - An explicit key for a cache entry. See [creating a cache key](../README.md#creating-a-cache-key).
* `path` - A list of files, directories, and wildcard patterns to restore. See [`@actions/glob`](https://github.com/actions/toolkit/tree/main/packages/glob) for supported patterns.
* `path` - A list of files, directories, and wildcard patterns to cache and restore. See [`@actions/glob`](https://github.com/actions/toolkit/tree/main/packages/glob) for supported patterns.
* `key` - String used while saving cache for restoring the cache
* `restore-keys` - An ordered list of prefix-matched keys to use for restoring stale cache if no cache hit occurred for key.
* `fail-on-cache-miss` - Fail the workflow if cache entry is not found. Default: `false`
* `lookup-only` - If true, only checks if cache entry exists and skips download. Default: `false`
### Outputs
## Outputs
* `cache-hit` - A boolean value to indicate an exact match was found for the key.
* `cache-primary-key` - Cache primary key passed in the input to use in subsequent steps of the workflow.
@ -22,8 +18,7 @@ The restore action restores a cache. It works similarly to the `cache` action ex
`cache-hit` will be set to `true` only when cache hit occurs for the exact `key` match. For a partial key match via `restore-keys` or a cache miss, it will be set to `false`.
### Environment Variables
* `SEGMENT_DOWNLOAD_TIMEOUT_MINS` - Segment download timeout (in minutes, default `10`) to abort download of the segment if not completed in the defined number of minutes. [Read more](https://github.com/actions/cache/blob/main/tips-and-workarounds.md#cache-segment-restore-timeout)
* `SEGMENT_DOWNLOAD_TIMEOUT_MINS` - Segment download timeout (in minutes, default `60`) to abort download of the segment if not completed in the defined number of minutes. [Read more](https://github.com/actions/cache/blob/main/workarounds.md#cache-segment-restore-timeout)
## Use cases
@ -31,13 +26,13 @@ As this is a newly introduced action to give users more control in their workflo
### Only restore cache
If you are using separate jobs to create and save your cache(s) to be reused by other jobs in a repository, this action will take care of your cache restoring needs.
In case you are using another workflow to create and save your cache that can be reused by other jobs in your repository, this action will take care of your restore only needs.
```yaml
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- uses: actions/cache/restore@v4
- uses: actions/cache/restore@v3
id: cache
with:
path: path/to/dependencies
@ -54,22 +49,22 @@ steps:
run: /publish.sh
```
Once the cache is restored, unlike `actions/cache`, this action won't run a post step to do post-processing, and the rest of the workflow will run as usual.
Once the cache is restored, this action won't run any post step to do post-processing like `actions/cache` and the rest of the workflow will run as usual.
### Save intermediate private build artifacts
In case of multi-module projects, where the built artifact of one project needs to be reused in subsequent child modules, the need to rebuild the parent module again and again with every build can be eliminated. The `actions/cache` or `actions/cache/save` action can be used to build and save the parent module artifact once, and it can be restored multiple times while building the child modules.
In case of multi-module projects, where the built artifact of one project needs to be reused in subsequent child modules, the need of rebuilding the parent module again and again with every build can be eliminated. The `actions/cache` or `actions/cache/save` action can be used to build and save the parent module artifact once, and restored multiple times while building the child modules.
#### Step 1 - Build the parent module and save it
```yaml
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: Build
run: /build-parent-module.sh
- uses: actions/cache/save@v4
- uses: actions/cache/save@v3
id: cache
with:
path: path/to/dependencies
@ -77,12 +72,11 @@ steps:
```
#### Step 2 - Restore the built artifact from cache using the same key and path
```yaml
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- uses: actions/cache/restore@v4
- uses: actions/cache/restore@v3
id: cache
with:
path: path/to/dependencies
@ -101,20 +95,21 @@ steps:
### Exit workflow on cache miss
You can use `fail-on-cache-miss: true` to exit a workflow on a cache miss. This way you can restrict your workflow to only build when there is a `cache-hit`.
To fail if there is no cache hit for the primary key, leave `restore-keys` empty!
You can use the output of this action to exit the workflow on cache miss. This way you can restrict your workflow to only initiate the build when `cache-hit` occurs, in other words, cache with exact key is found.
```yaml
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- uses: actions/cache/restore@v4
- uses: actions/cache/restore@v3
id: cache
with:
path: path/to/dependencies
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
fail-on-cache-miss: true
- name: Check cache hit
if: steps.cache.outputs.cache-hit != 'true'
run: exit 1
- name: Build
run: /build.sh
@ -122,14 +117,15 @@ steps:
## Tips
### Reusing primary key and restored key in the save action
Usually you may want to use the same `key` with both `actions/cache/restore` and `actions/cache/save` actions. To achieve this, use `outputs` from the `restore` action to reuse the same primary key (or the key of the cache that was restored).
#### Reusing primary key and restored key in the save action
### Using restore action outputs to make save action behave just like the cache action
Usually you may want to use same `key` in both actions/cache/restore` and `actions/cache/save` action. To achieve this, use `outputs` from the restore action to reuse the same primary key (or the key of the cache that was restored).
#### Using restore action outputs to make save action behave just like the cache action
The outputs `cache-primary-key` and `cache-matched-key` can be used to check if the restored cache is same as the given primary key. Alternatively, the `cache-hit` output can also be used to check if the restored was a complete match or a partially restored cache.
### Ensuring proper restores and save happen across the actions
#### Ensuring proper restores and save happen across the actions
It is very important to use the same `key` and `path` that were used by either `actions/cache` or `actions/cache/save` while saving the cache. Learn more about cache key [naming](https://github.com/actions/cache#creating-a-cache-key) and [versioning](https://github.com/actions/cache#cache-version) here.

View File

@ -9,19 +9,7 @@ inputs:
description: 'An explicit key for restoring the cache'
required: true
restore-keys:
description: 'An ordered multiline string listing the prefix-matched keys, that are used for restoring stale cache if no cache hit occurred for key. Note `cache-hit` returns false in this case.'
required: false
enableCrossOsArchive:
description: 'An optional boolean when enabled, allows windows runners to restore caches that were saved on other platforms'
default: 'false'
required: false
fail-on-cache-miss:
description: 'Fail the workflow if cache entry is not found'
default: 'false'
required: false
lookup-only:
description: 'Check if a cache entry exists for the given input(s) (key, restore-keys) without downloading the cache'
default: 'false'
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:
@ -31,7 +19,7 @@ outputs:
cache-matched-key:
description: 'Key of the cache that was restored, it could either be the primary key on cache-hit or a partial/complete match of one of the restore keys'
runs:
using: 'node20'
using: 'node16'
main: '../dist/restore-only/index.js'
branding:
icon: 'archive'

View File

@ -1,16 +1,14 @@
# Save action
The save action saves a cache. It works similarly to the `cache` action except that it doesn't first do a restore. This action provides granular ability to save a cache without having to restore it, or to do a save at any stage of the workflow job -- not only in post phase.
The save action, as the name suggest, saves a cache. It acts similar to the `cache` action except that it doesn't necessarily first do a restore. This action can provide you a granular control to only save a cache without having to necessarily restore it, or to do a restore anywhere in the workflow job and not only in post phase.
## Documentation
## Inputs
### Inputs
* `key` - 'An explicit key for saving the cache'
* `path` - 'A list of files, directories, and wildcard patterns to cache'
* `upload-chunk-size` - 'The chunk size used to split up large files during upload, in bytes'
* `key` - An explicit key for a cache entry. See [creating a cache key](../README.md#creating-a-cache-key).
* `path` - A list of files, directories, and wildcard patterns to cache. See [`@actions/glob`](https://github.com/actions/toolkit/tree/main/packages/glob) for supported patterns.
* `upload-chunk-size` - The chunk size used to split up large files during upload, in bytes
### Outputs
## Outputs
This action has no outputs.
@ -19,19 +17,20 @@ This action has no outputs.
### Only save cache
If you are using separate jobs for generating common artifacts and sharing them across jobs, this action will take care of your cache saving needs.
In case you are using separate jobs for generating common artifacts and sharing them across different jobs, this action will help you with your save only needs.
```yaml
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: /install.sh
- name: Build artifacts
- name: Build common artifacts
run: /build.sh
- uses: actions/cache/save@v4
- uses: actions/cache/save@v3
id: cache
with:
path: path/to/dependencies
@ -40,77 +39,46 @@ steps:
### Re-evaluate cache key while saving
With this save action, the key can now be re-evaluated while executing the action. This helps in cases where lockfiles are generated during the build.
With save action, the key can now be re-evaluated while executing the action. This helps in cases where the lockfiles are generated during the build.
Let's say we have a restore step that computes a key at runtime.
#### Restore a cache
Let's say we have a restore step that computes key at runtime
```yaml
uses: actions/cache/restore@v4
uses: actions/cache/restore@v3
id: restore-cache
with:
key: cache-${{ hashFiles('**/lockfiles') }}
```
#### Case 1 - Where a user would want to reuse the key as it is
Case 1: Where an user would want to reuse the key as it is
```yaml
uses: actions/cache/save@v4
uses: actions/cache/save@v3
with:
key: ${{ steps.restore-cache.outputs.cache-primary-key }}
key: steps.restore-cache.output.key
```
#### Case 2 - Where the user would want to re-evaluate the key
Case 2: Where the user would want to re-evaluate the key
```yaml
uses: actions/cache/save@v4
uses: actions/cache/save@v3
with:
key: npm-cache-${{hashfiles(package-lock.json)}}
```
### Always save cache
There are instances where some flaky test cases would fail the entire workflow and users would get frustrated because the builds would run for hours and the cache couldn't be saved as the workflow failed in between.
For such use-cases, users now have the ability to use the `actions/cache/save` action to save the cache by using an [`always()`](https://docs.github.com/actions/writing-workflows/choosing-what-your-workflow-does/expressions#always) condition.
This way the cache will always be saved if generated, or a warning will be generated that nothing is found on the cache path. Users can also use the `if` condition to only execute the `actions/cache/save` action depending on the output of previous steps. This way they get more control of when to save the cache.
To avoid saving a cache that already exists, the `cache-hit` output from a restore step should be checked.
The `cache-primary-key` output from the restore step should also be used to ensure
the cache key does not change during the build if it's calculated based on file contents.
Here's an example where we imagine we're calculating a lot of prime numbers and want to cache them:
There are instances where some flaky test cases would fail the entire workflow and users would get frustrated because the builds would run for hours and the cache couldn't get saved as the workflow failed in between. For such use-cases, users would now have the ability to use `actions/cache/save` action to save the cache by using `if: always()` condition. This way the cache will always be saved if generated, or a warning will be thrown that nothing is found on the cache path. Users can also use the `if` condition to only execute the `actions/cache/save` action depending on the output of the previous steps. This way they get more control on when to save the cache.
```yaml
name: Always Caching Prime Numbers
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Restore cached Prime Numbers
id: cache-prime-numbers-restore
uses: actions/cache/restore@v4
steps:
- uses: actions/checkout@v3
.
. // restore if need be
.
- name: Build
run: /build.sh
- uses: actions/cache/save@v3
if: always() // or any other condition to invoke the save action
with:
key: ${{ runner.os }}-prime-numbers
path: |
path/to/dependencies
some/other/dependencies
# Intermediate workflow steps
- name: Always Save Prime Numbers
id: cache-prime-numbers-save
if: always() && steps.cache-prime-numbers-restore.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
key: ${{ steps.cache-prime-numbers-restore.outputs.cache-primary-key }}
path: |
path/to/dependencies
some/other/dependencies
path: path/to/dependencies
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
```

View File

@ -11,12 +11,8 @@ inputs:
upload-chunk-size:
description: 'The chunk size used to split up large files during upload, in bytes'
required: false
enableCrossOsArchive:
description: 'An optional boolean when enabled, allows windows runners to save caches that can be restored on other platforms'
default: 'false'
required: false
runs:
using: 'node20'
using: 'node16'
main: '../dist/save-only/index.js'
branding:
icon: 'archive'

View File

@ -2,10 +2,7 @@ export enum Inputs {
Key = "key", // Input for cache, restore, save action
Path = "path", // Input for cache, restore, save action
RestoreKeys = "restore-keys", // Input for cache, restore action
UploadChunkSize = "upload-chunk-size", // Input for cache, save action
EnableCrossOsArchive = "enableCrossOsArchive", // Input for cache, restore, save action
FailOnCacheMiss = "fail-on-cache-miss", // Input for cache, restore action
LookupOnly = "lookup-only" // Input for cache, restore action
UploadChunkSize = "upload-chunk-size" // Input for cache, save action
}
export enum Outputs {

View File

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

View File

@ -2,16 +2,11 @@ import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, Outputs, State } from "./constants";
import {
IStateProvider,
NullStateProvider,
StateProvider
} from "./stateProvider";
import { IStateProvider } from "./stateProvider";
import * as utils from "./utils/actionUtils";
export async function restoreImpl(
stateProvider: IStateProvider,
earlyExit?: boolean | undefined
async function restoreImpl(
stateProvider: IStateProvider
): Promise<string | undefined> {
try {
if (!utils.isCacheFeatureAvailable()) {
@ -36,35 +31,21 @@ export async function restoreImpl(
const cachePaths = utils.getInputAsArray(Inputs.Path, {
required: true
});
const enableCrossOsArchive = utils.getInputAsBool(
Inputs.EnableCrossOsArchive
);
const failOnCacheMiss = utils.getInputAsBool(Inputs.FailOnCacheMiss);
const lookupOnly = utils.getInputAsBool(Inputs.LookupOnly);
const cacheKey = await cache.restoreCache(
cachePaths,
primaryKey,
restoreKeys,
{ lookupOnly: lookupOnly },
enableCrossOsArchive
restoreKeys
);
if (!cacheKey) {
// `cache-hit` is intentionally not set to `false` here to preserve existing behavior
// See https://github.com/actions/cache/issues/1466
if (failOnCacheMiss) {
throw new Error(
`Failed to restore cache entry. Exiting as fail-on-cache-miss is set. Input key: ${primaryKey}`
);
}
core.info(
`Cache not found for input keys: ${[
primaryKey,
...restoreKeys
].join(", ")}`
);
return;
}
@ -77,45 +58,12 @@ export async function restoreImpl(
);
core.setOutput(Outputs.CacheHit, isExactKeyMatch.toString());
if (lookupOnly) {
core.info(`Cache found and can be restored from key: ${cacheKey}`);
} else {
core.info(`Cache restored from key: ${cacheKey}`);
}
return cacheKey;
} catch (error: unknown) {
core.setFailed((error as Error).message);
if (earlyExit) {
process.exit(1);
}
}
}
async function run(
stateProvider: IStateProvider,
earlyExit: boolean | undefined
): Promise<void> {
await restoreImpl(stateProvider, earlyExit);
// node will stay alive if any promises are not resolved,
// which is a possibility if HTTP requests are dangling
// due to retries or timeouts. We know that if we got here
// that all promises that we care about have successfully
// resolved, so simply exit with success.
if (earlyExit) {
process.exit(0);
}
}
export async function restoreOnlyRun(
earlyExit?: boolean | undefined
): Promise<void> {
await run(new NullStateProvider(), earlyExit);
}
export async function restoreRun(
earlyExit?: boolean | undefined
): Promise<void> {
await run(new StateProvider(), earlyExit);
}
export default restoreImpl;

View File

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

View File

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

View File

@ -2,11 +2,7 @@ import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, State } from "./constants";
import {
IStateProvider,
NullStateProvider,
StateProvider
} from "./stateProvider";
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
@ -14,10 +10,7 @@ import * as utils from "./utils/actionUtils";
// throw an uncaught exception. Instead of failing this action, just warn.
process.on("uncaughtException", e => utils.logWarning(e.message));
export async function saveImpl(
stateProvider: IStateProvider
): Promise<number | void> {
let cacheId = -1;
async function saveImpl(stateProvider: IStateProvider): Promise<void> {
try {
if (!utils.isCacheFeatureAvailable()) {
return;
@ -58,16 +51,9 @@ export async function saveImpl(
required: true
});
const enableCrossOsArchive = utils.getInputAsBool(
Inputs.EnableCrossOsArchive
);
cacheId = await cache.saveCache(
cachePaths,
primaryKey,
{ uploadChunkSize: utils.getInputAsInt(Inputs.UploadChunkSize) },
enableCrossOsArchive
);
const cacheId = await cache.saveCache(cachePaths, primaryKey, {
uploadChunkSize: utils.getInputAsInt(Inputs.UploadChunkSize)
});
if (cacheId != -1) {
core.info(`Cache saved with key: ${primaryKey}`);
@ -75,50 +61,6 @@ export async function saveImpl(
} catch (error: unknown) {
utils.logWarning((error as Error).message);
}
return cacheId;
}
export async function saveOnlyRun(
earlyExit?: boolean | undefined
): Promise<void> {
try {
const cacheId = await saveImpl(new NullStateProvider());
if (cacheId === -1) {
core.warning(`Cache save failed.`);
}
} catch (err) {
console.error(err);
if (earlyExit) {
process.exit(1);
}
}
// node will stay alive if any promises are not resolved,
// which is a possibility if HTTP requests are dangling
// due to retries or timeouts. We know that if we got here
// that all promises that we care about have successfully
// resolved, so simply exit with success.
if (earlyExit) {
process.exit(0);
}
}
export async function saveRun(earlyExit?: boolean | undefined): Promise<void> {
try {
await saveImpl(new StateProvider());
} catch (err) {
console.error(err);
if (earlyExit) {
process.exit(1);
}
}
// node will stay alive if any promises are not resolved,
// which is a possibility if HTTP requests are dangling
// due to retries or timeouts. We know that if we got here
// that all promises that we care about have successfully
// resolved, so simply exit with success.
if (earlyExit) {
process.exit(0);
}
}
export default saveImpl;

View File

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

View File

@ -7,13 +7,7 @@ export function isGhes(): boolean {
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;
return ghUrl.hostname.toUpperCase() !== "GITHUB.COM";
}
export function isExactKeyMatch(key: string, cacheKey?: string): boolean {
@ -58,14 +52,6 @@ export function getInputAsInt(
return value;
}
export function getInputAsBool(
name: string,
options?: core.InputOptions
): boolean {
const result = core.getInput(name, options);
return result.toLowerCase() === "true";
}
export function isCacheFeatureAvailable(): boolean {
if (cache.isFeatureAvailable()) {
return true;

View File

@ -13,9 +13,6 @@ interface CacheInput {
path: string;
key: string;
restoreKeys?: string[];
enableCrossOsArchive?: boolean;
failOnCacheMiss?: boolean;
lookupOnly?: boolean;
}
export function setInputs(input: CacheInput): void {
@ -23,15 +20,6 @@ export function setInputs(input: CacheInput): void {
setInput(Inputs.Key, input.key);
input.restoreKeys &&
setInput(Inputs.RestoreKeys, input.restoreKeys.join("\n"));
input.enableCrossOsArchive !== undefined &&
setInput(
Inputs.EnableCrossOsArchive,
input.enableCrossOsArchive.toString()
);
input.failOnCacheMiss !== undefined &&
setInput(Inputs.FailOnCacheMiss, input.failOnCacheMiss.toString());
input.lookupOnly !== undefined &&
setInput(Inputs.LookupOnly, input.lookupOnly.toString());
}
export function clearInputs(): void {
@ -39,7 +27,4 @@ export function clearInputs(): void {
delete process.env[getInputName(Inputs.Key)];
delete process.env[getInputName(Inputs.RestoreKeys)];
delete process.env[getInputName(Inputs.UploadChunkSize)];
delete process.env[getInputName(Inputs.EnableCrossOsArchive)];
delete process.env[getInputName(Inputs.FailOnCacheMiss)];
delete process.env[getInputName(Inputs.LookupOnly)];
}

View File

@ -1,44 +1,46 @@
# Tips and workarounds
## Cache segment restore timeout
A cache gets downloaded in multiple segments of fixed sizes (`1GB` for a `32-bit` runner and `2GB` for a `64-bit` runner). Sometimes, a segment download gets stuck which causes the workflow job to be stuck forever and fail. Version `v3.0.8` of `actions/cache` introduces a segment download timeout. The segment download timeout will allow the segment download to get aborted and hence allow the job to proceed with a cache miss.
Default value of this timeout is 10 minutes and can be customized by specifying an [environment variable](https://docs.github.com/en/actions/learn-github-actions/environment-variables) named `SEGMENT_DOWNLOAD_TIMEOUT_MINS` with timeout value in minutes.
Default value of this timeout is 60 minutes and can be customized by specifying an [environment variable](https://docs.github.com/en/actions/learn-github-actions/environment-variables) named `SEGMENT_DOWNLOAD_TIMEOUT_MINS` with timeout value in minutes.
## Update a cache
A cache today is immutable and cannot be updated. But some use cases require the cache to be saved even though there was a "hit" during restore. To do so, use a `key` which is unique for every run and use `restore-keys` to restore the nearest cache. For example:
```yaml
- name: update cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3
with:
path: prime-numbers
key: primes-${{ runner.os }}-${{ github.run_id }} # Can use time based key as well
restore-keys: |
primes-${{ runner.os }}
```
Please note that this will create a new cache on every run and hence will consume the cache [quota](./README.md#cache-limits).
## Use cache across feature branches
Reusing cache across feature branches is not allowed today to provide cache [isolation](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#restrictions-for-accessing-a-cache). However if both feature branches are from the default branch, a good way to achieve this is to ensure that the default branch has a cache. This cache will then be consumable by both feature branches.
## Cross OS cache
## Improving cache restore performance on Windows/Using cross-os caching
Currently, cache restore is slow on Windows due to tar being inherently slow and the compression algorithm `gzip` in use. `zstd` is the default algorithm in use on linux and macos. It was disabled on Windows due to issues with bsd tar(libarchive), the tar implementation in use on Windows.
From `v3.2.3` cache is cross-os compatible when `enableCrossOsArchive` input is passed as true. This means that a cache created on `ubuntu-latest` or `mac-latest` can be used by `windows-latest` and vice versa, provided the workflow which runs on `windows-latest` have input `enableCrossOsArchive` as true. This is useful to cache dependencies which are independent of the runner platform. This will help reduce the consumption of the cache quota and help build for multiple platforms from the same cache. Things to keep in mind while using this feature:
To improve cache restore performance, we can re-enable `zstd` as the compression algorithm using the following workaround. Add the following step to your workflow before the cache step:
- Only cache files that are compatible across OSs.
- Caching symlinks might cause issues while restoring them as they behave differently on different OSs.
- Be mindful when caching files from outside your github workspace directory as the directory is located at different places across OS.
- Avoid using directory pointers such as `${{ github.workspace }}` or `~` (home) which eventually evaluate to an absolute path that does not match across OSs.
```yaml
- if: ${{ runner.os == 'Windows' }}
name: Use GNU tar
shell: cmd
run: |
echo "Adding GNU tar to PATH"
echo C:\Program Files\Git\usr\bin>>"%GITHUB_PATH%"
```
The `cache` action will use GNU tar instead of bsd tar on Windows. This should work on all Github Hosted runners as it is. For self-hosted runners, please ensure you have GNU tar and `zstd` installed.
The above workaround is also needed if you wish to use cross-os caching since difference of compression algorithms will result in different cache versions for the same cache key. So the above workaround will ensure `zstd` is used for caching on all platforms thus resulting in the same cache version for the same cache key.
## Force deletion of caches overriding default cache eviction policy
Caches have [branch scope restriction](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#restrictions-for-accessing-a-cache) in place. This means that if caches for a specific branch are using a lot of storage quota, it may result into more frequently used caches from `default` branch getting thrashed. For example, if there are many pull requests happening on a repo and are creating caches, these cannot be used in default branch scope but will still occupy a lot of space till they get cleaned up by [eviction policy](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#usage-limits-and-eviction-policy). But sometime we want to clean them up on a faster cadence so as to ensure default branch is not thrashing. In order to achieve this, [gh-actions-cache cli](https://github.com/actions/gh-actions-cache/) can be used to delete caches for specific branches.
Caches have [branch scope restriction](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#restrictions-for-accessing-a-cache) in place. This means that if caches for a specific branch are using a lot of storage quota, it may result into more frequently used caches from `default` branch getting thrashed. For example, if there are many pull requests happening on a repo and are creating caches, these cannot be used in default branch scope but will still occupy a lot of space till they get cleaned up by [eviction policy](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#usage-limits-and-eviction-policy). But sometime we want to clean them up on a faster cadence so as to ensure default branch is not thrashing.
This workflow uses `gh-actions-cache` to delete all the caches created by a branch.
<details>
<summary>Example</summary>
@ -53,29 +55,29 @@ on:
jobs:
cleanup:
runs-on: ubuntu-latest
permissions:
# `actions:write` permission is required to delete caches
# See also: https://docs.github.com/en/rest/actions/cache?apiVersion=2022-11-28#delete-a-github-actions-cache-for-a-repository-using-a-cache-id
actions: write
contents: read
steps:
- name: Check out code
uses: actions/checkout@v3
- name: Cleanup
run: |
gh extension install actions/gh-actions-cache
REPO=${{ github.repository }}
BRANCH=${{ github.ref }}
echo "Fetching list of cache key"
cacheKeysForPR=$(gh cache list --ref $BRANCH --limit 100 --json id --jq '.[].id')
cacheKeysForPR=$(gh actions-cache list -R $REPO -B $BRANCH | cut -f 1 )
## Setting this to not fail the workflow while deleting cache keys.
set +e
echo "Deleting caches..."
for cacheKey in $cacheKeysForPR
do
gh cache delete $cacheKey
gh actions-cache delete $cacheKey -R $REPO -B $BRANCH --confirm
done
echo "Done"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
BRANCH: refs/pull/${{ github.event.pull_request.number }}/merge
```
</details>