mirror of
https://github.com/Swatinem/rust-cache.git
synced 2025-12-27 01:53:59 -05:00
Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a226033982 | ||
|
|
d30f1144e8 | ||
|
|
b1db5f9d5f | ||
|
|
3cf7f8cc28 | ||
|
|
e03705e031 | ||
|
|
b86d1c6caa | ||
|
|
f27990c89a | ||
|
|
a95ba19544 | ||
|
|
82c8487d00 | ||
|
|
67c46e7159 | ||
|
|
44b6087283 | ||
|
|
e207df5d26 | ||
|
|
decb69d790 | ||
|
|
ab6b2769d1 | ||
|
|
578b235f6e | ||
|
|
5113490c3f | ||
|
|
c0e052c18c | ||
|
|
4e0f4b19dd | ||
|
|
b919e1427f | ||
|
|
b8a6852b4f | ||
|
|
80c47cc945 | ||
|
|
5ec9842c14 | ||
|
|
3312b3ab47 | ||
|
|
f6987ea139 | ||
|
|
e97a782690 | ||
|
|
b00faf5858 | ||
|
|
9de8f90afb | ||
|
|
fd201ad913 | ||
|
|
cf3f88254c | ||
|
|
4fedae9bcf | ||
|
|
1e604afb09 | ||
|
|
dd05243424 | ||
|
|
65dbc54a5d | ||
|
|
be7377e68e | ||
|
|
2656b87321 | ||
|
|
715970feed | ||
|
|
3d4000164d | ||
|
|
988c164c3d | ||
|
|
bb80d0f127 | ||
|
|
ad97570a01 | ||
|
|
060bda31e0 | ||
|
|
865fd1f6db | ||
|
|
7c7e41ab01 | ||
|
|
68aeeba167 | ||
|
|
def0926359 | ||
|
|
827c240e23 | ||
|
|
5e9fae966f | ||
|
|
127a0e9568 | ||
|
|
99229f978c | ||
|
|
6fd3edff69 | ||
|
|
a1c019f71a | ||
|
|
664ce0090f |
32
.github/workflows/buildjet.yml
vendored
Normal file
32
.github/workflows/buildjet.yml
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
name: buildjet
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
buildjet:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
|
||||
name: Test buildjet provider on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- run: rustup toolchain install stable --profile minimal --no-self-update
|
||||
|
||||
- uses: ./
|
||||
with:
|
||||
workspaces: tests
|
||||
cache-provider: buildjet
|
||||
|
||||
- run: |
|
||||
cargo check
|
||||
cargo test
|
||||
cargo build --release
|
||||
working-directory: tests
|
||||
45
.github/workflows/check-dist.yml
vendored
Normal file
45
.github/workflows/check-dist.yml
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
name: check dist/
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
pull_request:
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
check-dist:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Node.js 20.x
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 20.x
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Rebuild the dist/ directory
|
||||
run: npm run prepare
|
||||
|
||||
- name: Compare the expected and actual dist/ directories
|
||||
run: |
|
||||
if [ "$(git diff dist/ | wc -l)" -gt "0" ]; then
|
||||
echo "Detected uncommitted changes after build. See status below:"
|
||||
git diff
|
||||
exit 1
|
||||
fi
|
||||
id: diff
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: ${{ failure() && steps.diff.conclusion == 'failure' }}
|
||||
with:
|
||||
name: dist
|
||||
path: dist/
|
||||
6
.github/workflows/coverage.yml
vendored
6
.github/workflows/coverage.yml
vendored
@@ -18,11 +18,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked.
|
||||
# This can result in the CI failure, see: https://github.com/rust-lang/rustup/issues/3029
|
||||
- run: |
|
||||
rustup set auto-self-update disable
|
||||
rustup toolchain install stable --profile minimal --component llvm-tools-preview
|
||||
- run: rustup toolchain install stable --profile minimal --component llvm-tools-preview --no-self-update
|
||||
|
||||
- uses: taiki-e/install-action@cargo-llvm-cov
|
||||
|
||||
|
||||
31
.github/workflows/git-registry.yml
vendored
Normal file
31
.github/workflows/git-registry.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
name: git-registry
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
git-registry:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
|
||||
name: Test cargo "git" registry on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: git
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- run: rustup toolchain install stable --profile minimal --no-self-update
|
||||
|
||||
- uses: ./
|
||||
with:
|
||||
workspaces: tests
|
||||
|
||||
- run: |
|
||||
cargo check
|
||||
cargo test
|
||||
working-directory: tests
|
||||
6
.github/workflows/install.yml
vendored
6
.github/workflows/install.yml
vendored
@@ -18,11 +18,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked.
|
||||
# This can result in the CI failure, see: https://github.com/rust-lang/rustup/issues/3029
|
||||
- run: |
|
||||
rustup set auto-self-update disable
|
||||
rustup toolchain install stable --profile minimal
|
||||
- run: rustup toolchain install stable --profile minimal --no-self-update
|
||||
|
||||
- uses: ./
|
||||
|
||||
|
||||
9
.github/workflows/simple.yml
vendored
9
.github/workflows/simple.yml
vendored
@@ -9,7 +9,7 @@ jobs:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
|
||||
name: Test `cargo check/test` on ${{ matrix.os }}
|
||||
name: Test `cargo check/test/build` on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
env:
|
||||
@@ -18,11 +18,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked.
|
||||
# This can result in the CI failure, see: https://github.com/rust-lang/rustup/issues/3029
|
||||
- run: |
|
||||
rustup set auto-self-update disable
|
||||
rustup toolchain install stable --profile minimal
|
||||
- run: rustup toolchain install stable --profile minimal --no-self-update
|
||||
|
||||
- uses: ./
|
||||
with:
|
||||
@@ -31,4 +27,5 @@ jobs:
|
||||
- run: |
|
||||
cargo check
|
||||
cargo test
|
||||
cargo build --release
|
||||
working-directory: tests
|
||||
|
||||
36
.github/workflows/sparse-registry.yml
vendored
36
.github/workflows/sparse-registry.yml
vendored
@@ -1,36 +0,0 @@
|
||||
name: sparse-registry
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
sparse-registry:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
|
||||
name: Test `cargo check/test` with sparse registry on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_UNSTABLE_SPARSE_REGISTRY: true
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked.
|
||||
# This can result in the CI failure, see: https://github.com/rust-lang/rustup/issues/3029
|
||||
- run: |
|
||||
rustup set auto-self-update disable
|
||||
rustup toolchain install nightly --profile minimal
|
||||
rustup default nightly
|
||||
|
||||
- uses: ./
|
||||
with:
|
||||
workspaces: tests
|
||||
|
||||
- run: |
|
||||
cargo check
|
||||
cargo test
|
||||
working-directory: tests
|
||||
6
.github/workflows/target-dir.yml
vendored
6
.github/workflows/target-dir.yml
vendored
@@ -18,11 +18,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked.
|
||||
# This can result in the CI failure, see: https://github.com/rust-lang/rustup/issues/3029
|
||||
- run: |
|
||||
rustup set auto-self-update disable
|
||||
rustup toolchain install stable --profile minimal
|
||||
- run: rustup toolchain install stable --profile minimal --no-self-update
|
||||
|
||||
# the `workspaces` option has the format `$workspace -> $target-dir`
|
||||
# and the `$target-dir` is relative to the `$workspace`.
|
||||
|
||||
6
.github/workflows/workspaces.yml
vendored
6
.github/workflows/workspaces.yml
vendored
@@ -18,11 +18,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked.
|
||||
# This can result in the CI failure, see: https://github.com/rust-lang/rustup/issues/3029
|
||||
- run: |
|
||||
rustup set auto-self-update disable
|
||||
rustup toolchain install stable --profile minimal --target wasm32-unknown-unknown
|
||||
- run: rustup toolchain install stable --profile minimal --target wasm32-unknown-unknown --no-self-update
|
||||
|
||||
- uses: ./
|
||||
with:
|
||||
|
||||
54
CHANGELOG.md
54
CHANGELOG.md
@@ -1,5 +1,59 @@
|
||||
# Changelog
|
||||
|
||||
## 2.7.2
|
||||
|
||||
- Only key by `Cargo.toml` and `Cargo.lock` files of workspace members.
|
||||
|
||||
## 2.7.1
|
||||
|
||||
- Update toml parser to fix parsing errors.
|
||||
|
||||
## 2.7.0
|
||||
|
||||
- Properly cache `trybuild` tests.
|
||||
|
||||
## 2.6.2
|
||||
|
||||
- Fix `toml` parsing.
|
||||
|
||||
## 2.6.1
|
||||
|
||||
- Fix hash contributions of `Cargo.lock`/`Cargo.toml` files.
|
||||
|
||||
## 2.6.0
|
||||
|
||||
- Add "buildjet" as a second `cache-provider` backend.
|
||||
- Clean up sparse registry index.
|
||||
- Do not clean up src of `-sys` crates.
|
||||
- Remove `.cargo/credentials.toml` before saving.
|
||||
|
||||
## 2.5.1
|
||||
|
||||
- Fix hash contribution of `Cargo.lock`.
|
||||
|
||||
## 2.5.0
|
||||
|
||||
- feat: Rm workspace crates version before caching.
|
||||
- feat: Add hash of `.cargo/config.toml` to key.
|
||||
|
||||
## 2.4.0
|
||||
|
||||
- Fix cache key stability.
|
||||
- Use 8 character hash components to reduce the key length, making it more readable.
|
||||
|
||||
## 2.3.0
|
||||
|
||||
- Add `cache-all-crates` option, which enables caching of crates installed by workflows.
|
||||
- Add installed packages to cache key, so changes to workflows that install rust tools are detected and cached properly.
|
||||
- Fix cache restore failures due to upstream bug.
|
||||
- Fix `EISDIR` error due to globed directories.
|
||||
- Update runtime `@actions/cache`, `@actions/io` and dev `typescript` dependencies.
|
||||
- Update `npm run prepare` so it creates distribution files with the right line endings.
|
||||
|
||||
## 2.2.1
|
||||
|
||||
- Update `@actions/cache` dependency to fix usage of `zstd` compression.
|
||||
|
||||
## 2.2.0
|
||||
|
||||
- Add new `save-if` option to always restore, but only conditionally save the cache.
|
||||
|
||||
22
README.md
22
README.md
@@ -54,11 +54,25 @@ sensible defaults.
|
||||
# default: "false"
|
||||
cache-on-failure: ""
|
||||
|
||||
# Determines which crates are cached.
|
||||
# If `true` all crates will be cached, otherwise only dependent crates will be cached.
|
||||
# Useful if additional crates are used for CI tooling.
|
||||
# default: "false"
|
||||
cache-all-crates: ""
|
||||
|
||||
# Determiners whether the cache should be saved.
|
||||
# If `false`, the cache is only restored.
|
||||
# Useful for jobs where the matrix is additive e.g. additional Cargo features.
|
||||
# Useful for jobs where the matrix is additive e.g. additional Cargo features,
|
||||
# or when only runs from `master` should be saved to the cache.
|
||||
# default: "true"
|
||||
save-if: ""
|
||||
# To only cache runs from `master`:
|
||||
save-if: ${{ github.ref == 'refs/heads/master' }}
|
||||
|
||||
# Specifies what to use as the backend providing cache
|
||||
# Can be set to either "github" or "buildjet"
|
||||
# default: "github"
|
||||
cache-provider: ""
|
||||
```
|
||||
|
||||
Further examples are available in the [.github/workflows](./.github/workflows/) directory.
|
||||
@@ -79,7 +93,8 @@ repositories with only a `Cargo.toml` file have limited benefits, as cargo will
|
||||
_always_ use the most up-to-date dependency versions, which may not be cached.
|
||||
|
||||
Usage with Stable Rust is most effective, as a cache is tied to the Rust version.
|
||||
Using it with Nightly Rust is less effective as it will throw away the cache every day.
|
||||
Using it with Nightly Rust is less effective as it will throw away the cache every day,
|
||||
unless a specific nightly build is being pinned.
|
||||
|
||||
## Cache Details
|
||||
|
||||
@@ -95,6 +110,7 @@ This cache is automatically keyed by:
|
||||
- the value of some compiler-specific environment variables (eg. RUSTFLAGS, etc), and
|
||||
- a hash of all `Cargo.lock` / `Cargo.toml` files found anywhere in the repository (if present).
|
||||
- a hash of all `rust-toolchain` / `rust-toolchain.toml` files in the root of the repository (if present).
|
||||
- a hash of all `.cargo/config.toml` files in the root of the repository (if present).
|
||||
|
||||
An additional input `key` can be provided if the builtin keys are not sufficient.
|
||||
|
||||
@@ -130,7 +146,7 @@ otherwise corrupt the cache on macOS builds.
|
||||
This specialized cache action is built on top of the upstream cache action
|
||||
maintained by GitHub. The same restrictions and limits apply, which are
|
||||
documented here:
|
||||
https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows
|
||||
[Caching dependencies to speed up workflows](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows)
|
||||
|
||||
In particular, caches are currently limited to 10 GB in total and exceeding that
|
||||
limit will cause eviction of older caches.
|
||||
|
||||
1
TODO.md
1
TODO.md
@@ -1,4 +1,3 @@
|
||||
- better .cargo/bin handling:
|
||||
- get a list of all the files on "pre"/"restore"
|
||||
- move the files out of the way on "post"/"save" and move them back afterwards
|
||||
- properly clean sparse registry
|
||||
|
||||
10
action.yml
10
action.yml
@@ -28,15 +28,23 @@ inputs:
|
||||
cache-on-failure:
|
||||
description: "Cache even if the build fails. Defaults to false."
|
||||
required: false
|
||||
cache-all-crates:
|
||||
description: "Determines which crates are cached. If `true` all crates will be cached, otherwise only dependent crates will be cached."
|
||||
required: false
|
||||
default: "false"
|
||||
save-if:
|
||||
description: "Determiners whether the cache should be saved. If `false`, the cache is only restored."
|
||||
required: false
|
||||
default: "true"
|
||||
cache-provider:
|
||||
description: "Determines which provider to use for caching. Options are github or buildjet, defaults to github."
|
||||
required: false
|
||||
default: "github"
|
||||
outputs:
|
||||
cache-hit:
|
||||
description: "A boolean value that indicates an exact match was found."
|
||||
runs:
|
||||
using: "node16"
|
||||
using: "node20"
|
||||
main: "dist/restore/index.js"
|
||||
post: "dist/save/index.js"
|
||||
post-if: "success() || env.CACHE_ON_FAILURE == 'true'"
|
||||
|
||||
36428
dist/restore/index.js
vendored
36428
dist/restore/index.js
vendored
File diff suppressed because one or more lines are too long
36436
dist/save/index.js
vendored
36436
dist/save/index.js
vendored
File diff suppressed because one or more lines are too long
924
package-lock.json
generated
924
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
19
package.json
19
package.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "rust-cache",
|
||||
"version": "2.2.0",
|
||||
"version": "2.7.2",
|
||||
"description": "A GitHub Action that implements smart caching for rust/cargo projects with sensible defaults.",
|
||||
"keywords": [
|
||||
"actions",
|
||||
@@ -22,17 +22,20 @@
|
||||
},
|
||||
"homepage": "https://github.com/Swatinem/rust-cache#readme",
|
||||
"dependencies": {
|
||||
"@actions/cache": "^3.0.6",
|
||||
"@actions/core": "^1.10.0",
|
||||
"@actions/buildjet-cache": "npm:github-actions.cache-buildjet@0.2.0",
|
||||
"@actions/cache": "^3.2.2",
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/exec": "^1.1.1",
|
||||
"@actions/glob": "^0.3.0",
|
||||
"@actions/io": "^1.1.2"
|
||||
"@actions/glob": "^0.4.0",
|
||||
"@actions/io": "^1.1.3",
|
||||
"smol-toml": "1.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vercel/ncc": "^0.34.0",
|
||||
"typescript": "4.8.4"
|
||||
"@vercel/ncc": "^0.38.1",
|
||||
"linefix": "^0.1.1",
|
||||
"typescript": "5.2.2"
|
||||
},
|
||||
"scripts": {
|
||||
"prepare": "ncc build --target es2020 -o dist/restore src/restore.ts && ncc build --target es2020 -o dist/save src/save.ts"
|
||||
"prepare": "ncc build --target es2020 -o dist/restore src/restore.ts && ncc build --target es2020 -o dist/save src/save.ts && linefix dist"
|
||||
}
|
||||
}
|
||||
|
||||
107
src/cleanup.ts
107
src/cleanup.ts
@@ -3,7 +3,8 @@ import * as io from "@actions/io";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
import { CARGO_HOME, STATE_BINS } from "./config";
|
||||
import { CARGO_HOME } from "./config";
|
||||
import { exists } from "./utils";
|
||||
import { Packages } from "./workspace";
|
||||
|
||||
export async function cleanTargetDir(targetDir: string, packages: Packages, checkTimestamp = false) {
|
||||
@@ -34,6 +35,26 @@ export async function cleanTargetDir(targetDir: string, packages: Packages, chec
|
||||
async function cleanProfileTarget(profileDir: string, packages: Packages, checkTimestamp = false) {
|
||||
core.debug(`cleaning profile directory "${profileDir}"`);
|
||||
|
||||
// Quite a few testing utility crates store compilation artifacts as nested
|
||||
// workspaces under `target/tests`. Notably, `target/tests/target` and
|
||||
// `target/tests/trybuild`.
|
||||
if (path.basename(profileDir) === "tests") {
|
||||
try {
|
||||
// https://github.com/vertexclique/kaos/blob/9876f6c890339741cc5be4b7cb9df72baa5a6d79/src/cargo.rs#L25
|
||||
// https://github.com/eupn/macrotest/blob/c4151a5f9f545942f4971980b5d264ebcd0b1d11/src/cargo.rs#L27
|
||||
cleanTargetDir(path.join(profileDir, "target"), packages, checkTimestamp);
|
||||
} catch { }
|
||||
try {
|
||||
// https://github.com/dtolnay/trybuild/blob/eec8ca6cb9b8f53d0caf1aa499d99df52cae8b40/src/cargo.rs#L50
|
||||
cleanTargetDir(path.join(profileDir, "trybuild"), packages, checkTimestamp);
|
||||
} catch { }
|
||||
|
||||
// Delete everything else.
|
||||
await rmExcept(profileDir, new Set(["target", "trybuild"]), checkTimestamp);
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
let keepProfile = new Set(["build", ".fingerprint", "deps"]);
|
||||
await rmExcept(profileDir, keepProfile);
|
||||
|
||||
@@ -69,9 +90,14 @@ export async function getCargoBins(): Promise<Set<string>> {
|
||||
return bins;
|
||||
}
|
||||
|
||||
export async function cleanBin() {
|
||||
/**
|
||||
* Clean the cargo bin directory, removing the binaries that existed
|
||||
* when the action started, as they were not created by the build.
|
||||
*
|
||||
* @param oldBins The binaries that existed when the action started.
|
||||
*/
|
||||
export async function cleanBin(oldBins: Array<string>) {
|
||||
const bins = await getCargoBins();
|
||||
const oldBins = JSON.parse(core.getState(STATE_BINS));
|
||||
|
||||
for (const bin of oldBins) {
|
||||
bins.delete(bin);
|
||||
@@ -85,12 +111,16 @@ export async function cleanBin() {
|
||||
}
|
||||
}
|
||||
|
||||
export async function cleanRegistry(packages: Packages) {
|
||||
// `.cargo/registry/src`
|
||||
// we can remove this completely, as cargo will recreate this from `cache`
|
||||
await rmRF(path.join(CARGO_HOME, "registry", "src"));
|
||||
export async function cleanRegistry(packages: Packages, crates = true) {
|
||||
// remove `.cargo/credentials.toml`
|
||||
try {
|
||||
const credentials = path.join(CARGO_HOME, ".cargo", "credentials.toml");
|
||||
core.debug(`deleting "${credentials}"`);
|
||||
await fs.promises.unlink(credentials);
|
||||
} catch {}
|
||||
|
||||
// `.cargo/registry/index`
|
||||
let pkgSet = new Set(packages.map((p) => p.name));
|
||||
const indexDir = await fs.promises.opendir(path.join(CARGO_HOME, "registry", "index"));
|
||||
for await (const dirent of indexDir) {
|
||||
if (dirent.isDirectory()) {
|
||||
@@ -101,14 +131,38 @@ export async function cleanRegistry(packages: Packages) {
|
||||
// for a git registry, we can remove `.cache`, as cargo will recreate it from git
|
||||
if (await exists(path.join(dirPath, ".git"))) {
|
||||
await rmRF(path.join(dirPath, ".cache"));
|
||||
} else {
|
||||
await cleanRegistryIndexCache(dirPath, pkgSet);
|
||||
}
|
||||
// TODO: else, clean `.cache` based on the `packages`
|
||||
}
|
||||
}
|
||||
|
||||
const pkgSet = new Set(packages.map((p) => `${p.name}-${p.version}.crate`));
|
||||
if (!crates) {
|
||||
core.debug("skipping registry cache and src cleanup");
|
||||
return;
|
||||
}
|
||||
|
||||
// `.cargo/registry/src`
|
||||
// Cargo usually re-creates these from the `.crate` cache below,
|
||||
// but for some reason that does not work for `-sys` crates that check timestamps
|
||||
// to decide if rebuilds are necessary.
|
||||
pkgSet = new Set(packages.filter((p) => p.name.endsWith("-sys")).map((p) => `${p.name}-${p.version}`));
|
||||
const srcDir = await fs.promises.opendir(path.join(CARGO_HOME, "registry", "src"));
|
||||
for await (const dirent of srcDir) {
|
||||
if (dirent.isDirectory()) {
|
||||
// eg `.cargo/registry/src/github.com-1ecc6299db9ec823`
|
||||
// or `.cargo/registry/src/index.crates.io-e139d0d48fed7772`
|
||||
const dir = await fs.promises.opendir(path.join(srcDir.path, dirent.name));
|
||||
for await (const dirent of dir) {
|
||||
if (dirent.isDirectory() && !pkgSet.has(dirent.name)) {
|
||||
await rmRF(path.join(dir.path, dirent.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `.cargo/registry/cache`
|
||||
pkgSet = new Set(packages.map((p) => `${p.name}-${p.version}.crate`));
|
||||
const cacheDir = await fs.promises.opendir(path.join(CARGO_HOME, "registry", "cache"));
|
||||
for await (const dirent of cacheDir) {
|
||||
if (dirent.isDirectory()) {
|
||||
@@ -125,6 +179,28 @@ export async function cleanRegistry(packages: Packages) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively walks and cleans the index `.cache`
|
||||
async function cleanRegistryIndexCache(dirName: string, keepPkg: Set<string>) {
|
||||
let dirIsEmpty = true;
|
||||
const cacheDir = await fs.promises.opendir(dirName);
|
||||
for await (const dirent of cacheDir) {
|
||||
if (dirent.isDirectory()) {
|
||||
if (await cleanRegistryIndexCache(path.join(dirName, dirent.name), keepPkg)) {
|
||||
await rm(dirName, dirent);
|
||||
} else {
|
||||
dirIsEmpty &&= false;
|
||||
}
|
||||
} else {
|
||||
if (keepPkg.has(dirent.name)) {
|
||||
dirIsEmpty &&= false;
|
||||
} else {
|
||||
await rm(dirName, dirent);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dirIsEmpty;
|
||||
}
|
||||
|
||||
export async function cleanGit(packages: Packages) {
|
||||
const coPath = path.join(CARGO_HOME, "git", "checkouts");
|
||||
const dbPath = path.join(CARGO_HOME, "git", "db");
|
||||
@@ -181,10 +257,10 @@ const ONE_WEEK = 7 * 24 * 3600 * 1000;
|
||||
|
||||
/**
|
||||
* Removes all files or directories in `dirName` matching some criteria.
|
||||
*
|
||||
*
|
||||
* When the `checkTimestamp` flag is set, this will also remove anything older
|
||||
* than one week.
|
||||
*
|
||||
*
|
||||
* Otherwise, it will remove everything that does not match any string in the
|
||||
* `keepPrefix` set.
|
||||
* The matching strips and trailing `-$hash` suffix.
|
||||
@@ -233,12 +309,3 @@ async function rmRF(dirName: string) {
|
||||
core.debug(`deleting "${dirName}"`);
|
||||
await io.rmRF(dirName);
|
||||
}
|
||||
|
||||
async function exists(path: string) {
|
||||
try {
|
||||
await fs.promises.access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
218
src/config.ts
218
src/config.ts
@@ -2,19 +2,20 @@ import * as core from "@actions/core";
|
||||
import * as glob from "@actions/glob";
|
||||
import crypto from "crypto";
|
||||
import fs from "fs";
|
||||
import fs_promises from "fs/promises";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import * as toml from "smol-toml";
|
||||
|
||||
import { getCmdOutput } from "./utils";
|
||||
import { getCargoBins } from "./cleanup";
|
||||
import { CacheProvider, exists, getCmdOutput } from "./utils";
|
||||
import { Workspace } from "./workspace";
|
||||
|
||||
const HOME = os.homedir();
|
||||
export const CARGO_HOME = process.env.CARGO_HOME || path.join(HOME, ".cargo");
|
||||
|
||||
const STATE_LOCKFILE_HASH = "RUST_CACHE_LOCKFILE_HASH";
|
||||
const STATE_LOCKFILES = "RUST_CACHE_LOCKFILES";
|
||||
export const STATE_BINS = "RUST_CACHE_BINS";
|
||||
export const STATE_KEY = "RUST_CACHE_KEY";
|
||||
const STATE_CONFIG = "RUST_CACHE_CONFIG";
|
||||
const HASH_LENGTH = 8;
|
||||
|
||||
export class CacheConfig {
|
||||
/** All the paths we want to cache */
|
||||
@@ -27,6 +28,9 @@ export class CacheConfig {
|
||||
/** The workspace configurations */
|
||||
public workspaces: Array<Workspace> = [];
|
||||
|
||||
/** The cargo binaries present during main step */
|
||||
public cargoBins: Array<string> = [];
|
||||
|
||||
/** The prefix portion of the cache key */
|
||||
private keyPrefix = "";
|
||||
/** The rust version considered for the cache key */
|
||||
@@ -103,20 +107,14 @@ export class CacheConfig {
|
||||
}
|
||||
|
||||
self.keyEnvs = keyEnvs;
|
||||
key += `-${hasher.digest("hex")}`;
|
||||
|
||||
key += `-${digest(hasher)}`;
|
||||
|
||||
self.restoreKey = key;
|
||||
|
||||
// Construct the lockfiles portion of the key:
|
||||
// This considers all the files found via globbing for various manifests
|
||||
// and lockfiles.
|
||||
// This part is computed in the "pre"/"restore" part of the job and persisted
|
||||
// into the `state`. That state is loaded in the "post"/"save" part of the
|
||||
// job so we have consistent values even though the "main" actions run
|
||||
// might create/overwrite lockfiles.
|
||||
|
||||
let lockHash = core.getState(STATE_LOCKFILE_HASH);
|
||||
let keyFiles: Array<string> = JSON.parse(core.getState(STATE_LOCKFILES) || "[]");
|
||||
|
||||
// Constructs the workspace config and paths to restore:
|
||||
// The workspaces are given using a `$workspace -> $target` syntax.
|
||||
@@ -131,31 +129,107 @@ export class CacheConfig {
|
||||
}
|
||||
self.workspaces = workspaces;
|
||||
|
||||
if (!lockHash) {
|
||||
keyFiles = keyFiles.concat(await globFiles("rust-toolchain\nrust-toolchain.toml"));
|
||||
for (const workspace of workspaces) {
|
||||
const root = workspace.root;
|
||||
keyFiles.push(
|
||||
...(await globFiles(
|
||||
`${root}/**/Cargo.toml\n${root}/**/Cargo.lock\n${root}/**/rust-toolchain\n${root}/**/rust-toolchain.toml`,
|
||||
)),
|
||||
);
|
||||
}
|
||||
keyFiles.sort((a, b) => a.localeCompare(b));
|
||||
let keyFiles = await globFiles(".cargo/config.toml\nrust-toolchain\nrust-toolchain.toml");
|
||||
const parsedKeyFiles = []; // keyFiles that are parsed, pre-processed and hashed
|
||||
|
||||
hasher = crypto.createHash("sha1");
|
||||
for (const file of keyFiles) {
|
||||
for await (const chunk of fs.createReadStream(file)) {
|
||||
hasher.update(chunk);
|
||||
hasher = crypto.createHash("sha1");
|
||||
|
||||
for (const workspace of workspaces) {
|
||||
const root = workspace.root;
|
||||
keyFiles.push(
|
||||
...(await globFiles(
|
||||
`${root}/**/.cargo/config.toml\n${root}/**/rust-toolchain\n${root}/**/rust-toolchain.toml`,
|
||||
)),
|
||||
);
|
||||
|
||||
const workspaceMembers = await workspace.getWorkspaceMembers();
|
||||
|
||||
const cargo_manifests = sort_and_uniq(workspaceMembers.map(member => path.join(member.path, "Cargo.toml")));
|
||||
|
||||
for (const cargo_manifest of cargo_manifests) {
|
||||
try {
|
||||
const content = await fs_promises.readFile(cargo_manifest, { encoding: "utf8" });
|
||||
// Use any since TomlPrimitive is not exposed
|
||||
const parsed = toml.parse(content) as { [key: string]: any };
|
||||
|
||||
if ("package" in parsed) {
|
||||
const pack = parsed.package;
|
||||
if ("version" in pack) {
|
||||
pack["version"] = "0.0.0";
|
||||
}
|
||||
}
|
||||
|
||||
for (const prefix of ["", "build-", "dev-"]) {
|
||||
const section_name = `${prefix}dependencies`;
|
||||
if (!(section_name in parsed)) {
|
||||
continue;
|
||||
}
|
||||
const deps = parsed[section_name];
|
||||
|
||||
for (const key of Object.keys(deps)) {
|
||||
const dep = deps[key];
|
||||
|
||||
try {
|
||||
if ("path" in dep) {
|
||||
dep.version = "0.0.0";
|
||||
dep.path = "";
|
||||
}
|
||||
} catch (_e) {
|
||||
// Not an object, probably a string (version),
|
||||
// continue.
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hasher.update(JSON.stringify(parsed));
|
||||
|
||||
parsedKeyFiles.push(cargo_manifest);
|
||||
} catch (e) { // Fallback to caching them as regular file
|
||||
core.warning(`Error parsing Cargo.toml manifest, fallback to caching entire file: ${e}`);
|
||||
keyFiles.push(cargo_manifest);
|
||||
}
|
||||
}
|
||||
lockHash = hasher.digest("hex");
|
||||
|
||||
core.saveState(STATE_LOCKFILE_HASH, lockHash);
|
||||
core.saveState(STATE_LOCKFILES, JSON.stringify(keyFiles));
|
||||
const cargo_lock = path.join(workspace.root, "Cargo.lock");
|
||||
if (await exists(cargo_lock)) {
|
||||
try {
|
||||
const content = await fs_promises.readFile(cargo_lock, { encoding: "utf8" });
|
||||
const parsed = toml.parse(content);
|
||||
|
||||
if (parsed.version !== 3 || !("package" in parsed)) {
|
||||
// Fallback to caching them as regular file since this action
|
||||
// can only handle Cargo.lock format version 3
|
||||
core.warning('Unsupported Cargo.lock format, fallback to caching entire file');
|
||||
keyFiles.push(cargo_lock);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Package without `[[package]].source` and `[[package]].checksum`
|
||||
// are the one with `path = "..."` to crates within the workspace.
|
||||
const packages = (parsed.package as any[]).filter((p: any) => "source" in p || "checksum" in p);
|
||||
|
||||
hasher.update(JSON.stringify(packages));
|
||||
|
||||
parsedKeyFiles.push(cargo_lock);
|
||||
} catch (e) { // Fallback to caching them as regular file
|
||||
core.warning(`Error parsing Cargo.lock manifest, fallback to caching entire file: ${e}`);
|
||||
keyFiles.push(cargo_lock);
|
||||
}
|
||||
}
|
||||
}
|
||||
keyFiles = sort_and_uniq(keyFiles);
|
||||
|
||||
for (const file of keyFiles) {
|
||||
for await (const chunk of fs.createReadStream(file)) {
|
||||
hasher.update(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
self.keyFiles = keyFiles;
|
||||
let lockHash = digest(hasher);
|
||||
|
||||
keyFiles.push(...parsedKeyFiles);
|
||||
self.keyFiles = sort_and_uniq(keyFiles);
|
||||
|
||||
key += `-${lockHash}`;
|
||||
self.cacheKey = key;
|
||||
@@ -171,11 +245,40 @@ export class CacheConfig {
|
||||
self.cachePaths.push(dir);
|
||||
}
|
||||
|
||||
const bins = await getCargoBins();
|
||||
self.cargoBins = Array.from(bins.values());
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
printInfo() {
|
||||
/**
|
||||
* Reads and returns the cache config from the action `state`.
|
||||
*
|
||||
* @throws {Error} if the state is not present.
|
||||
* @returns {CacheConfig} the configuration.
|
||||
* @see {@link CacheConfig#saveState}
|
||||
* @see {@link CacheConfig#new}
|
||||
*/
|
||||
static fromState(): CacheConfig {
|
||||
const source = core.getState(STATE_CONFIG);
|
||||
if (!source) {
|
||||
throw new Error("Cache configuration not found in state");
|
||||
}
|
||||
|
||||
const self = new CacheConfig();
|
||||
Object.assign(self, JSON.parse(source));
|
||||
self.workspaces = self.workspaces.map((w: any) => new Workspace(w.root, w.target));
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the configuration to the action log.
|
||||
*/
|
||||
printInfo(cacheProvider: CacheProvider) {
|
||||
core.startGroup("Cache Configuration");
|
||||
core.info(`Cache Provider:`);
|
||||
core.info(` ${cacheProvider.name}`);
|
||||
core.info(`Workspaces:`);
|
||||
for (const workspace of this.workspaces) {
|
||||
core.info(` ${workspace.root}`);
|
||||
@@ -201,6 +304,33 @@ export class CacheConfig {
|
||||
}
|
||||
core.endGroup();
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the configuration to the state store.
|
||||
* This is used to restore the configuration in the post action.
|
||||
*/
|
||||
saveState() {
|
||||
core.saveState(STATE_CONFIG, this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the cache is up to date.
|
||||
*
|
||||
* @returns `true` if the cache is up to date, `false` otherwise.
|
||||
*/
|
||||
export function isCacheUpToDate(): boolean {
|
||||
return core.getState(STATE_CONFIG) === "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a hex digest of the given hasher truncated to `HASH_LENGTH`.
|
||||
*
|
||||
* @param hasher The hasher to digest.
|
||||
* @returns The hex digest.
|
||||
*/
|
||||
function digest(hasher: crypto.Hash): string {
|
||||
return hasher.digest("hex").substring(0, HASH_LENGTH);
|
||||
}
|
||||
|
||||
interface RustVersion {
|
||||
@@ -223,5 +353,25 @@ async function globFiles(pattern: string): Promise<string[]> {
|
||||
const globber = await glob.create(pattern, {
|
||||
followSymbolicLinks: false,
|
||||
});
|
||||
return await globber.glob();
|
||||
// fs.statSync resolve the symbolic link and returns stat for the
|
||||
// file it pointed to, so isFile would make sure the resolved
|
||||
// file is actually a regular file.
|
||||
return (await globber.glob()).filter((file) => fs.statSync(file).isFile());
|
||||
}
|
||||
|
||||
function sort_and_uniq(a: string[]) {
|
||||
return a
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.reduce((accumulator: string[], currentValue: string) => {
|
||||
const len = accumulator.length;
|
||||
// If accumulator is empty or its last element != currentValue
|
||||
// Since array is already sorted, elements with the same value
|
||||
// are grouped together to be continugous in space.
|
||||
//
|
||||
// If currentValue != last element, then it must be unique.
|
||||
if (len == 0 || accumulator[len - 1].localeCompare(currentValue) != 0) {
|
||||
accumulator.push(currentValue);
|
||||
}
|
||||
return accumulator;
|
||||
}, []);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import * as cache from "@actions/cache";
|
||||
import * as core from "@actions/core";
|
||||
|
||||
import { cleanTargetDir, getCargoBins } from "./cleanup";
|
||||
import { CacheConfig, STATE_BINS, STATE_KEY } from "./config";
|
||||
import { cleanTargetDir } from "./cleanup";
|
||||
import { CacheConfig } from "./config";
|
||||
import { getCacheProvider, reportError } from "./utils";
|
||||
|
||||
process.on("uncaughtException", (e) => {
|
||||
core.info(`[warning] ${e.message}`);
|
||||
core.error(e.message);
|
||||
if (e.stack) {
|
||||
core.info(e.stack);
|
||||
core.error(e.stack);
|
||||
}
|
||||
});
|
||||
|
||||
async function run() {
|
||||
if (!cache.isFeatureAvailable()) {
|
||||
const cacheProvider = getCacheProvider();
|
||||
|
||||
if (!cacheProvider.cache.isFeatureAvailable()) {
|
||||
setCacheHitOutput(false);
|
||||
return;
|
||||
}
|
||||
@@ -26,38 +28,41 @@ async function run() {
|
||||
core.exportVariable("CARGO_INCREMENTAL", 0);
|
||||
|
||||
const config = await CacheConfig.new();
|
||||
config.printInfo();
|
||||
config.printInfo(cacheProvider);
|
||||
core.info("");
|
||||
|
||||
const bins = await getCargoBins();
|
||||
core.saveState(STATE_BINS, JSON.stringify([...bins]));
|
||||
|
||||
core.info(`... Restoring cache ...`);
|
||||
const key = config.cacheKey;
|
||||
const restoreKey = await cache.restoreCache(config.cachePaths, key, [config.restoreKey]);
|
||||
// Pass a copy of cachePaths to avoid mutating the original array as reported by:
|
||||
// https://github.com/actions/toolkit/pull/1378
|
||||
// TODO: remove this once the underlying bug is fixed.
|
||||
const restoreKey = await cacheProvider.cache.restoreCache(config.cachePaths.slice(), key, [config.restoreKey]);
|
||||
if (restoreKey) {
|
||||
core.info(`Restored from cache key "${restoreKey}".`);
|
||||
core.saveState(STATE_KEY, restoreKey);
|
||||
|
||||
if (restoreKey !== key) {
|
||||
const match = restoreKey === key;
|
||||
core.info(`Restored from cache key "${restoreKey}" full match: ${match}.`);
|
||||
if (!match) {
|
||||
// pre-clean the target directory on cache mismatch
|
||||
for (const workspace of config.workspaces) {
|
||||
try {
|
||||
await cleanTargetDir(workspace.target, [], true);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// We restored the cache but it is not a full match.
|
||||
config.saveState();
|
||||
}
|
||||
|
||||
setCacheHitOutput(restoreKey === key);
|
||||
setCacheHitOutput(match);
|
||||
} else {
|
||||
core.info("No cache found.");
|
||||
config.saveState();
|
||||
|
||||
setCacheHitOutput(false);
|
||||
}
|
||||
} catch (e) {
|
||||
setCacheHitOutput(false);
|
||||
|
||||
core.info(`[warning] ${(e as any).stack}`);
|
||||
reportError(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
46
src/save.ts
46
src/save.ts
@@ -1,74 +1,80 @@
|
||||
import * as cache from "@actions/cache";
|
||||
import * as core from "@actions/core";
|
||||
import * as exec from "@actions/exec";
|
||||
|
||||
import { cleanBin, cleanGit, cleanRegistry, cleanTargetDir } from "./cleanup";
|
||||
import { CacheConfig, STATE_KEY } from "./config";
|
||||
import { CacheConfig, isCacheUpToDate } from "./config";
|
||||
import { getCacheProvider, reportError } from "./utils";
|
||||
|
||||
process.on("uncaughtException", (e) => {
|
||||
core.info(`[warning] ${e.message}`);
|
||||
core.error(e.message);
|
||||
if (e.stack) {
|
||||
core.info(e.stack);
|
||||
core.error(e.stack);
|
||||
}
|
||||
});
|
||||
|
||||
async function run() {
|
||||
const cacheProvider = getCacheProvider();
|
||||
|
||||
const save = core.getInput("save-if").toLowerCase() || "true";
|
||||
|
||||
if (!(cache.isFeatureAvailable() && save === "true")) {
|
||||
if (!(cacheProvider.cache.isFeatureAvailable() && save === "true")) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await CacheConfig.new();
|
||||
config.printInfo();
|
||||
core.info("");
|
||||
|
||||
if (core.getState(STATE_KEY) === config.cacheKey) {
|
||||
if (isCacheUpToDate()) {
|
||||
core.info(`Cache up-to-date.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const config = CacheConfig.fromState();
|
||||
config.printInfo(cacheProvider);
|
||||
core.info("");
|
||||
|
||||
// TODO: remove this once https://github.com/actions/toolkit/pull/553 lands
|
||||
await macOsWorkaround();
|
||||
|
||||
const allPackages = [];
|
||||
for (const workspace of config.workspaces) {
|
||||
const packages = await workspace.getPackages();
|
||||
const packages = await workspace.getPackagesOutsideWorkspaceRoot();
|
||||
allPackages.push(...packages);
|
||||
try {
|
||||
core.info(`... Cleaning ${workspace.target} ...`);
|
||||
await cleanTargetDir(workspace.target, packages);
|
||||
} catch (e) {
|
||||
core.info(`[warning] ${(e as any).stack}`);
|
||||
core.debug(`${(e as any).stack}`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
core.info(`... Cleaning cargo registry ...`);
|
||||
await cleanRegistry(allPackages);
|
||||
const crates = core.getInput("cache-all-crates").toLowerCase() || "false";
|
||||
core.info(`... Cleaning cargo registry (cache-all-crates: ${crates}) ...`);
|
||||
await cleanRegistry(allPackages, crates !== "true");
|
||||
} catch (e) {
|
||||
core.info(`[warning] ${(e as any).stack}`);
|
||||
core.debug(`${(e as any).stack}`);
|
||||
}
|
||||
|
||||
try {
|
||||
core.info(`... Cleaning cargo/bin ...`);
|
||||
await cleanBin();
|
||||
await cleanBin(config.cargoBins);
|
||||
} catch (e) {
|
||||
core.info(`[warning] ${(e as any).stack}`);
|
||||
core.debug(`${(e as any).stack}`);
|
||||
}
|
||||
|
||||
try {
|
||||
core.info(`... Cleaning cargo git cache ...`);
|
||||
await cleanGit(allPackages);
|
||||
} catch (e) {
|
||||
core.info(`[warning] ${(e as any).stack}`);
|
||||
core.debug(`${(e as any).stack}`);
|
||||
}
|
||||
|
||||
core.info(`... Saving cache ...`);
|
||||
await cache.saveCache(config.cachePaths, config.cacheKey);
|
||||
// Pass a copy of cachePaths to avoid mutating the original array as reported by:
|
||||
// https://github.com/actions/toolkit/pull/1378
|
||||
// TODO: remove this once the underlying bug is fixed.
|
||||
await cacheProvider.cache.saveCache(config.cachePaths.slice(), config.cacheKey);
|
||||
} catch (e) {
|
||||
core.info(`[warning] ${(e as any).stack}`);
|
||||
reportError(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
47
src/utils.ts
47
src/utils.ts
@@ -1,5 +1,18 @@
|
||||
import * as core from "@actions/core";
|
||||
import * as exec from "@actions/exec";
|
||||
import * as buildjetCache from "@actions/buildjet-cache";
|
||||
import * as ghCache from "@actions/cache";
|
||||
import fs from "fs";
|
||||
|
||||
export function reportError(e: any) {
|
||||
const { commandFailed } = e;
|
||||
if (commandFailed) {
|
||||
core.error(`Command failed: ${commandFailed.command}`);
|
||||
core.error(commandFailed.stderr);
|
||||
} else {
|
||||
core.error(`${e.stack}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCmdOutput(
|
||||
cmd: string,
|
||||
@@ -22,9 +35,39 @@ export async function getCmdOutput(
|
||||
...options,
|
||||
});
|
||||
} catch (e) {
|
||||
core.info(`[warning] Command failed: ${cmd} ${args.join(" ")}`);
|
||||
core.info(`[warning] ${stderr}`);
|
||||
(e as any).commandFailed = {
|
||||
command: `${cmd} ${args.join(" ")}`,
|
||||
stderr,
|
||||
};
|
||||
throw e;
|
||||
}
|
||||
return stdout;
|
||||
}
|
||||
|
||||
export interface CacheProvider {
|
||||
name: string;
|
||||
cache: typeof ghCache;
|
||||
}
|
||||
|
||||
export function getCacheProvider(): CacheProvider {
|
||||
const cacheProvider = core.getInput("cache-provider");
|
||||
const cache = cacheProvider === "github" ? ghCache : cacheProvider === "buildjet" ? buildjetCache : undefined;
|
||||
|
||||
if (!cache) {
|
||||
throw new Error(`The \`cache-provider\` \`{cacheProvider}\` is not valid.`);
|
||||
}
|
||||
|
||||
return {
|
||||
name: cacheProvider,
|
||||
cache: cache,
|
||||
};
|
||||
}
|
||||
|
||||
export async function exists(path: string) {
|
||||
try {
|
||||
await fs.promises.access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,26 +8,33 @@ const SAVE_TARGETS = new Set(["lib", "proc-macro"]);
|
||||
export class Workspace {
|
||||
constructor(public root: string, public target: string) {}
|
||||
|
||||
public async getPackages(): Promise<Packages> {
|
||||
async getPackages(filter: ((p: Meta['packages'][0]) => boolean), ...extraArgs: string[]): Promise<Packages> {
|
||||
let packages: Packages = [];
|
||||
try {
|
||||
core.debug(`collecting metadata for "${this.root}"`);
|
||||
const meta: Meta = JSON.parse(
|
||||
await getCmdOutput("cargo", ["metadata", "--all-features", "--format-version", "1"], {
|
||||
await getCmdOutput("cargo", ["metadata", "--all-features", "--format-version", "1", ...extraArgs], {
|
||||
cwd: this.root,
|
||||
}),
|
||||
);
|
||||
core.debug(`workspace "${this.root}" has ${meta.packages.length} packages`);
|
||||
for (const pkg of meta.packages) {
|
||||
if (pkg.manifest_path.startsWith(this.root)) {
|
||||
continue;
|
||||
}
|
||||
for (const pkg of meta.packages.filter(filter)) {
|
||||
const targets = pkg.targets.filter((t) => t.kind.some((kind) => SAVE_TARGETS.has(kind))).map((t) => t.name);
|
||||
packages.push({ name: pkg.name, version: pkg.version, targets, path: path.dirname(pkg.manifest_path) });
|
||||
}
|
||||
} catch {}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
return packages;
|
||||
}
|
||||
|
||||
public async getPackagesOutsideWorkspaceRoot(): Promise<Packages> {
|
||||
return await this.getPackages(pkg => !pkg.manifest_path.startsWith(this.root));
|
||||
}
|
||||
|
||||
public async getWorkspaceMembers(): Promise<Packages> {
|
||||
return await this.getPackages(_ => true, "--no-deps");
|
||||
}
|
||||
}
|
||||
|
||||
export interface PackageDefinition {
|
||||
|
||||
95
tests/Cargo.lock
generated
95
tests/Cargo.lock
generated
@@ -10,9 +10,18 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.13.0"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd"
|
||||
checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
|
||||
|
||||
[[package]]
|
||||
name = "basic-toml"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7bfc506e7a2370ec239e1d072507b2a80c833083699d3c6fa176fbb4de8448c6"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
@@ -148,6 +157,12 @@ dependencies = [
|
||||
"pin-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.3.14"
|
||||
@@ -483,9 +498,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.11.11"
|
||||
version = "0.11.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b75aa69a3f06bbcc66ede33af2af253c6f7a86b1ca0033f60c580a27074fbf92"
|
||||
checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
@@ -499,10 +514,10 @@ dependencies = [
|
||||
"hyper-tls",
|
||||
"ipnet",
|
||||
"js-sys",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"mime",
|
||||
"native-tls",
|
||||
"once_cell",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"serde",
|
||||
@@ -523,6 +538,8 @@ name = "rust-cache"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"reqwest",
|
||||
"tikv-jemallocator",
|
||||
"trybuild",
|
||||
"watto",
|
||||
]
|
||||
|
||||
@@ -567,9 +584,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.144"
|
||||
version = "1.0.185"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f747710de3dcd43b88c9168773254e809d8ddbdf9653b84e2554ab219f17860"
|
||||
checksum = "be9b6f69f1dfd54c3b568ffa45c310d6973a5e5148fd40cf515acaf38cf5bc31"
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.147"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f1d362ca8fc9c3e3a7484440752472d68a6caa98f1ab81d99b5dfe517cec852"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
@@ -638,6 +666,15 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "termcolor"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6"
|
||||
dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.33"
|
||||
@@ -658,6 +695,26 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tikv-jemalloc-sys"
|
||||
version = "0.5.4+5.3.0-patched"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9402443cb8fd499b6f327e40565234ff34dbda27460c5b47db0db77443dd85d1"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tikv-jemallocator"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "965fe0c26be5c56c94e38ba547249074803efd52adfb66de62107d95aab3eaca"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tikv-jemalloc-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.6.0"
|
||||
@@ -746,6 +803,21 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
|
||||
|
||||
[[package]]
|
||||
name = "trybuild"
|
||||
version = "1.0.80"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "501dbdbb99861e4ab6b60eb6a7493956a9defb644fd034bc4a5ef27c693c8a3a"
|
||||
dependencies = [
|
||||
"basic-toml",
|
||||
"glob",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"termcolor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi"
|
||||
version = "0.3.8"
|
||||
@@ -902,6 +974,15 @@ version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
|
||||
dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-x86_64-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
|
||||
@@ -6,5 +6,11 @@ authors = ["Arpad Borsos <arpad.borsos@googlemail.com>"]
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
reqwest = "0.11.11"
|
||||
reqwest = "0.11.18"
|
||||
watto = { git = "https://github.com/getsentry/watto", rev = "d71c8218506bddba102a124a460d64da25e303dc", features = ["strings"] }
|
||||
|
||||
[dev-dependencies]
|
||||
trybuild = "1"
|
||||
|
||||
[target.'cfg(not(target_env = "msvc"))'.dependencies]
|
||||
tikv-jemallocator = "0.5.4"
|
||||
|
||||
2
tests/rust-toolchain/.keep
Normal file
2
tests/rust-toolchain/.keep
Normal file
@@ -0,0 +1,2 @@
|
||||
the `rust-toolchain` directory will be globbed,
|
||||
and should not lead to any errors down the road
|
||||
@@ -1,3 +1,10 @@
|
||||
#[cfg(not(target_env = "msvc"))]
|
||||
use tikv_jemallocator::Jemalloc;
|
||||
|
||||
#[cfg(not(target_env = "msvc"))]
|
||||
#[global_allocator]
|
||||
static GLOBAL: Jemalloc = Jemalloc;
|
||||
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
|
||||
6
tests/tests/trybuild.rs
Normal file
6
tests/tests/trybuild.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
#[test]
|
||||
fn test_trybuild() {
|
||||
let t = trybuild::TestCases::new();
|
||||
t.pass("tests/trybuild/empty_main.rs");
|
||||
t.compile_fail("tests/trybuild/fail_to_compile.rs");
|
||||
}
|
||||
1
tests/tests/trybuild/empty_main.rs
Normal file
1
tests/tests/trybuild/empty_main.rs
Normal file
@@ -0,0 +1 @@
|
||||
fn main() {}
|
||||
3
tests/tests/trybuild/fail_to_compile.rs
Normal file
3
tests/tests/trybuild/fail_to_compile.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
"foobar".foobar();
|
||||
}
|
||||
5
tests/tests/trybuild/fail_to_compile.stderr
Normal file
5
tests/tests/trybuild/fail_to_compile.stderr
Normal file
@@ -0,0 +1,5 @@
|
||||
error[E0599]: no method named `foobar` found for reference `&'static str` in the current scope
|
||||
--> tests/trybuild/fail_to_compile.rs:2:14
|
||||
|
|
||||
2 | "foobar".foobar();
|
||||
| ^^^^^^ method not found in `&str`
|
||||
Reference in New Issue
Block a user