跳到主要内容

Using Dependency Cache

Applicable Scenarios

When you need to cache dependency packages (npm, Maven, pip, Gradle, etc.) to speed up subsequent builds.

Prerequisites

  • The cache directory path is confirmed.
  • The version of the cache plugin used is confirmed (recommended v4).
  • Understand the design principles of cache keys and restore-keys.

Quick Example

name: ci-with-cache

on:
push:
branches:
- main

jobs:
build:
runs-on: [ubuntu-latest, x64, small]
steps:
- uses: checkout

- name: Cache npm dependencies
uses: cache
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
npm-${{ runner.os }}-

- name: Install and test
run: |
npm ci
npm test

Configuration Description

Cache Plugin Parameters

steps:
- name: Cache dependencies
uses: cache
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
npm-${{ runner.os }}-
ParameterRequiredDescription
pathYesThe cache directory path, supports single or multiple paths
keyYesThe cache key, which directly restores the cache when there is an exact match
restore-keysNoA list of fallback restore keys for prefix matching, tried in order

Cache Matching Mechanism

  1. First, try an exact match with key.
  2. If the exact match fails, try prefix matching in the order of restore-keys list.
  3. Prefix matching restores the most recent cache with the same prefix.
  4. If all matches fail, the contents of path will be saved as a new cache after the step is executed.

Multi-path Caching

steps:
- name: Cache multiple paths
uses: cache
with:
path: |
~/.npm
~/.cache/pip
node_modules
key: deps-${{ runner.os }}-${{ hashFiles('package-lock.json', 'requirements.txt') }}

Common Language Cache Examples

Node.js / npm

steps:
- name: Cache npm
uses: cache
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
npm-${{ runner.os }}-
- run: npm ci

Java / Maven

steps:
- name: Cache Maven
uses: cache
with:
path: ~/.m2/repository
key: maven-${{ runner.os }}-${{ hashFiles('**/pom.xml') }}
restore-keys: |
maven-${{ runner.os }}-
- run: mvn -B test

Java / Gradle

steps:
- name: Cache Gradle
uses: cache
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', 'gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- run: ./gradlew build

Python / pip

steps:
- name: Cache pip
uses: cache
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-${{ hashFiles('requirements.txt') }}
restore-keys: |
pip-${{ runner.os }}-
- run: pip install -r requirements.txt

Go

steps:
- name: Cache Go modules
uses: cache
with:
path: ~/go/pkg/mod
key: go-${{ runner.os }}-${{ hashFiles('go.sum') }}
restore-keys: |
go-${{ runner.os }}-
- run: go build ./...