42 Commits

Author SHA1 Message Date
Arpad Borsos
b8a6852b4f 2.6.0
Some checks failed
buildjet / Test buildjet provider on ubuntu-latest (push) Failing after 0s
coverage / Test `cargo-llvm-cov` on ubuntu-latest (push) Failing after 0s
git-registry / Test cargo "git" registry on ubuntu-latest (push) Failing after 0s
install / Test `cargo install` on ubuntu-latest (push) Failing after 0s
simple / Test `cargo check/test/build` on ubuntu-latest (push) Failing after 0s
target-dir / Test custom target-dir on ubuntu-latest (push) Failing after 0s
workspaces / Test multiple workspaces on ubuntu-latest (push) Failing after 0s
buildjet / Test buildjet provider on macos-latest (push) Has been cancelled
buildjet / Test buildjet provider on windows-latest (push) Has been cancelled
coverage / Test `cargo-llvm-cov` on macos-latest (push) Has been cancelled
coverage / Test `cargo-llvm-cov` on windows-latest (push) Has been cancelled
git-registry / Test cargo "git" registry on macos-latest (push) Has been cancelled
git-registry / Test cargo "git" registry on windows-latest (push) Has been cancelled
install / Test `cargo install` on macos-latest (push) Has been cancelled
install / Test `cargo install` on windows-latest (push) Has been cancelled
simple / Test `cargo check/test/build` on macos-latest (push) Has been cancelled
simple / Test `cargo check/test/build` on windows-latest (push) Has been cancelled
target-dir / Test custom target-dir on macos-latest (push) Has been cancelled
target-dir / Test custom target-dir on windows-latest (push) Has been cancelled
workspaces / Test multiple workspaces on macos-latest (push) Has been cancelled
workspaces / Test multiple workspaces on windows-latest (push) Has been cancelled
2023-08-02 13:06:28 +02:00
Arpad Borsos
80c47cc945 Clean up credentials.toml 2023-08-02 12:54:48 +02:00
Arpad Borsos
5ec9842c14 bump test dependencies 2023-08-02 12:47:24 +02:00
Arpad Borsos
3312b3ab47 Slightly improve docs 2023-08-02 12:46:45 +02:00
Arpad Borsos
f6987ea139 Improve errors and cleanup
- Silence errors and do not create error annotations, fixes #144
- Implement cleanup for new sparse registry
- Do not clean `-sys` dependencies from `registry/src`, hopefully fixes  #150
2023-08-02 12:15:14 +02:00
Arpad Borsos
e97a782690 move buildjet test into its own workflow 2023-08-02 10:38:22 +02:00
Jordan Oroshiba
b00faf5858 Add BuildJet Option (#154) 2023-08-01 09:01:11 +02:00
Arpad Borsos
9de8f90afb Add jemalloc to test -sys style dependencies 2023-07-31 16:34:21 +02:00
Arpad Borsos
fd201ad913 test globbing of rust-toolchain differently 2023-07-31 16:26:42 +02:00
Arpad Borsos
cf3f88254c "properly rename git-registry workflow" 2023-07-31 16:02:24 +02:00
Arpad Borsos
4fedae9bcf "update dependencies and rebuild" 2023-07-31 16:01:23 +02:00
Arpad Borsos
1e604afb09 Update workflow definitions
- Use rust `--no-self-update` flag instead of separate command.
- Add an explicit test for the `git` registry, as the sparse registry is now the default.
2023-07-31 15:31:10 +02:00
Arpad Borsos
dd05243424 2.5.1
Some checks failed
coverage / Test `cargo-llvm-cov` on ubuntu-latest (push) Failing after 0s
globbed-directories / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
install / Test `cargo install` on ubuntu-latest (push) Failing after 0s
simple / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
sparse-registry / Test `cargo check/test` with sparse registry on ubuntu-latest (push) Failing after 0s
target-dir / Test custom target-dir on ubuntu-latest (push) Failing after 0s
workspaces / Test multiple workspaces on ubuntu-latest (push) Failing after 0s
coverage / Test `cargo-llvm-cov` on macos-latest (push) Has been cancelled
coverage / Test `cargo-llvm-cov` on windows-latest (push) Has been cancelled
install / Test `cargo install` on macos-latest (push) Has been cancelled
install / Test `cargo install` on windows-latest (push) Has been cancelled
simple / Test `cargo check/test` on macos-latest (push) Has been cancelled
simple / Test `cargo check/test` on windows-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on macos-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on windows-latest (push) Has been cancelled
target-dir / Test custom target-dir on macos-latest (push) Has been cancelled
target-dir / Test custom target-dir on windows-latest (push) Has been cancelled
workspaces / Test multiple workspaces on macos-latest (push) Has been cancelled
workspaces / Test multiple workspaces on windows-latest (push) Has been cancelled
2023-07-03 19:38:11 +02:00
Arpad Borsos
65dbc54a5d update changelog 2023-07-03 19:38:01 +02:00
Jiahao XU
be7377e68e fix src/config.ts: Remove sort_object (#152)
Fixed #151

I've tried running manually load and parse `Cargo.lock` and it runs fine
until `sort_object` is called.

Since `Cargo.lock` is auto-generated and usually sorted, I think there
is no need for sorting.

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2023-06-27 08:55:56 +02:00
Arpad Borsos
2656b87321 2.5.0
Some checks failed
coverage / Test `cargo-llvm-cov` on ubuntu-latest (push) Failing after 0s
globbed-directories / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
install / Test `cargo install` on ubuntu-latest (push) Failing after 0s
simple / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
sparse-registry / Test `cargo check/test` with sparse registry on ubuntu-latest (push) Failing after 0s
target-dir / Test custom target-dir on ubuntu-latest (push) Failing after 0s
workspaces / Test multiple workspaces on ubuntu-latest (push) Failing after 0s
coverage / Test `cargo-llvm-cov` on macos-latest (push) Has been cancelled
coverage / Test `cargo-llvm-cov` on windows-latest (push) Has been cancelled
install / Test `cargo install` on macos-latest (push) Has been cancelled
install / Test `cargo install` on windows-latest (push) Has been cancelled
simple / Test `cargo check/test` on macos-latest (push) Has been cancelled
simple / Test `cargo check/test` on windows-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on macos-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on windows-latest (push) Has been cancelled
target-dir / Test custom target-dir on macos-latest (push) Has been cancelled
target-dir / Test custom target-dir on windows-latest (push) Has been cancelled
workspaces / Test multiple workspaces on macos-latest (push) Has been cancelled
workspaces / Test multiple workspaces on windows-latest (push) Has been cancelled
2023-06-18 15:32:29 +02:00
Jiahao XU
715970feed feat: Add hash of .cargo/config.toml to key (#149)
Also:
 - Add and use `sort_and_uniq` to make sure `globFile` resulting
   and `keyFiles` does not contain duplicates.
 - Only returns regular file in function `globFile`

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2023-06-18 10:12:25 +02:00
Jiahao XU
3d4000164d feat: Rm workspace crates version before caching (#147)
Fixed #146

 - Set all `package.version` in `Cargo.toml` to `0.0.0`
 - Set `{build-, dev-, }dependencies` of workspace crates to `0.0.0`
 - Remove workspace crates from `Cargo.lock` before caching
 - Sort all toml objects before hashing them as json

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2023-06-18 09:29:44 +02:00
Arpad Borsos
988c164c3d 2.4.0
Some checks failed
coverage / Test `cargo-llvm-cov` on ubuntu-latest (push) Failing after 0s
globbed-directories / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
install / Test `cargo install` on ubuntu-latest (push) Failing after 0s
simple / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
sparse-registry / Test `cargo check/test` with sparse registry on ubuntu-latest (push) Failing after 0s
target-dir / Test custom target-dir on ubuntu-latest (push) Failing after 0s
workspaces / Test multiple workspaces on ubuntu-latest (push) Failing after 0s
coverage / Test `cargo-llvm-cov` on macos-latest (push) Has been cancelled
coverage / Test `cargo-llvm-cov` on windows-latest (push) Has been cancelled
install / Test `cargo install` on macos-latest (push) Has been cancelled
install / Test `cargo install` on windows-latest (push) Has been cancelled
simple / Test `cargo check/test` on macos-latest (push) Has been cancelled
simple / Test `cargo check/test` on windows-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on macos-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on windows-latest (push) Has been cancelled
target-dir / Test custom target-dir on macos-latest (push) Has been cancelled
target-dir / Test custom target-dir on windows-latest (push) Has been cancelled
workspaces / Test multiple workspaces on macos-latest (push) Has been cancelled
workspaces / Test multiple workspaces on windows-latest (push) Has been cancelled
2023-05-21 19:36:24 +02:00
Steven Hartland
bb80d0f127 chore: use 8 character hash components (#143)
Use 8 character hash components to reduce the key length, making it
more readable.

Fixes #97
2023-05-19 20:30:37 +02:00
Steven Hartland
ad97570a01 fix: cache key stability (#142)
Ensure consistency of main and post configuration by storing and
restoring it from state, which in turn ensures cache key stability.

Also:
* Fixed some typos.
* Use core.error for logging errors.
* Fix inverted condition on cache-all-crates.

Reverts: #138
Fixes #140
2023-05-18 22:48:40 +02:00
Arpad Borsos
060bda31e0 2.3.0
Some checks failed
coverage / Test `cargo-llvm-cov` on ubuntu-latest (push) Failing after 0s
globbed-directories / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
install / Test `cargo install` on ubuntu-latest (push) Failing after 0s
simple / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
sparse-registry / Test `cargo check/test` with sparse registry on ubuntu-latest (push) Failing after 0s
target-dir / Test custom target-dir on ubuntu-latest (push) Failing after 0s
workspaces / Test multiple workspaces on ubuntu-latest (push) Failing after 0s
coverage / Test `cargo-llvm-cov` on macos-latest (push) Has been cancelled
coverage / Test `cargo-llvm-cov` on windows-latest (push) Has been cancelled
install / Test `cargo install` on macos-latest (push) Has been cancelled
install / Test `cargo install` on windows-latest (push) Has been cancelled
simple / Test `cargo check/test` on macos-latest (push) Has been cancelled
simple / Test `cargo check/test` on windows-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on macos-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on windows-latest (push) Has been cancelled
target-dir / Test custom target-dir on macos-latest (push) Has been cancelled
target-dir / Test custom target-dir on windows-latest (push) Has been cancelled
workspaces / Test multiple workspaces on macos-latest (push) Has been cancelled
workspaces / Test multiple workspaces on windows-latest (push) Has been cancelled
2023-05-13 12:16:43 +02:00
Arpad Borsos
865fd1f6db "update dependencies and changelog" 2023-05-13 12:16:26 +02:00
Steven Hartland
7c7e41ab01 chore: changelog v2.3.0 (#139)
Update CHANGELOG for v2.3.0 release.
2023-05-13 12:13:40 +02:00
Steven Hartland
68aeeba167 chore: use linefix to ensure platform line endings (#135)
Use linefix so that when developing changes the results of npm run prepare always have unix line endings so git diff commands don't show line ending changes for the ncc generated files.
2023-05-11 23:19:46 +02:00
Steven Hartland
def0926359 feat: add option to cache all crates (#137)
Add cache-all-crates option which allows all crates to be cached instead
of just the dependency crates. This is useful when additional crates are
required for CI tooling.
2023-05-11 23:15:09 +02:00
Steven Hartland
827c240e23 fix: cache key dependency on installed packages (#138)
Add the installed packages to the environment element of the cache key
so that CI tooling is considered. This ensures that rust CI tooling is
cached correctly when changes occur. Prior to this a manual key change
or cache expiry would need to occur before CI tools were correctly
cached.
2023-05-11 23:12:12 +02:00
Steven Hartland
5e9fae966f fix: cache restore failures (#136)
Fix cache restore failures to to upstream bug.

Fixes #119
2023-05-11 09:01:27 +02:00
Arpad Borsos
127a0e9568 "update dependencies and rebuild" 2023-05-02 22:03:29 +02:00
Felix Riegger
99229f978c Fix EISDIR error due to globbed directories (#1) (#132) 2023-05-02 21:49:27 +02:00
Arpad Borsos
6fd3edff69 2.2.1
Some checks failed
coverage / Test `cargo-llvm-cov` on ubuntu-latest (push) Failing after 0s
install / Test `cargo install` on ubuntu-latest (push) Failing after 0s
simple / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
sparse-registry / Test `cargo check/test` with sparse registry on ubuntu-latest (push) Failing after 0s
target-dir / Test custom target-dir on ubuntu-latest (push) Failing after 0s
workspaces / Test multiple workspaces on ubuntu-latest (push) Failing after 0s
coverage / Test `cargo-llvm-cov` on macos-latest (push) Has been cancelled
coverage / Test `cargo-llvm-cov` on windows-latest (push) Has been cancelled
install / Test `cargo install` on macos-latest (push) Has been cancelled
install / Test `cargo install` on windows-latest (push) Has been cancelled
simple / Test `cargo check/test` on macos-latest (push) Has been cancelled
simple / Test `cargo check/test` on windows-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on macos-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on windows-latest (push) Has been cancelled
target-dir / Test custom target-dir on macos-latest (push) Has been cancelled
target-dir / Test custom target-dir on windows-latest (push) Has been cancelled
workspaces / Test multiple workspaces on macos-latest (push) Has been cancelled
workspaces / Test multiple workspaces on windows-latest (push) Has been cancelled
2023-02-24 10:59:55 +01:00
Arpad Borsos
a1c019f71a update dependencies and rebuild 2023-02-24 10:58:39 +01:00
Jongwoo Han
664ce0090f chore: Create check-dist.yml (#96) 2022-12-17 10:01:41 +01:00
Arpad Borsos
359a70e43a 2.2.0
Some checks failed
coverage / Test `cargo-llvm-cov` on ubuntu-latest (push) Failing after 0s
install / Test `cargo install` on ubuntu-latest (push) Failing after 0s
simple / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
sparse-registry / Test `cargo check/test` with sparse registry on ubuntu-latest (push) Failing after 0s
target-dir / Test custom target-dir on ubuntu-latest (push) Failing after 0s
workspaces / Test multiple workspaces on ubuntu-latest (push) Failing after 0s
coverage / Test `cargo-llvm-cov` on macos-latest (push) Has been cancelled
coverage / Test `cargo-llvm-cov` on windows-latest (push) Has been cancelled
install / Test `cargo install` on macos-latest (push) Has been cancelled
install / Test `cargo install` on windows-latest (push) Has been cancelled
simple / Test `cargo check/test` on macos-latest (push) Has been cancelled
simple / Test `cargo check/test` on windows-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on macos-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on windows-latest (push) Has been cancelled
target-dir / Test custom target-dir on macos-latest (push) Has been cancelled
target-dir / Test custom target-dir on windows-latest (push) Has been cancelled
workspaces / Test multiple workspaces on macos-latest (push) Has been cancelled
workspaces / Test multiple workspaces on windows-latest (push) Has been cancelled
2022-11-09 20:14:41 +01:00
Lucas Fernandes Nogueira
ecee04e7b3 feat: add save-if option, closes #66 (#91) 2022-11-06 19:15:00 +01:00
Arpad Borsos
b894d59a8d 2.1.0
Some checks failed
coverage / Test `cargo-llvm-cov` on ubuntu-latest (push) Failing after 0s
install / Test `cargo install` on ubuntu-latest (push) Failing after 0s
simple / Test `cargo check/test` on ubuntu-latest (push) Failing after -1s
sparse-registry / Test `cargo check/test` with sparse registry on ubuntu-latest (push) Failing after 0s
target-dir / Test custom target-dir on ubuntu-latest (push) Failing after 0s
workspaces / Test multiple workspaces on ubuntu-latest (push) Failing after 0s
coverage / Test `cargo-llvm-cov` on macos-latest (push) Has been cancelled
coverage / Test `cargo-llvm-cov` on windows-latest (push) Has been cancelled
install / Test `cargo install` on macos-latest (push) Has been cancelled
install / Test `cargo install` on windows-latest (push) Has been cancelled
simple / Test `cargo check/test` on macos-latest (push) Has been cancelled
simple / Test `cargo check/test` on windows-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on macos-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on windows-latest (push) Has been cancelled
target-dir / Test custom target-dir on macos-latest (push) Has been cancelled
target-dir / Test custom target-dir on windows-latest (push) Has been cancelled
workspaces / Test multiple workspaces on macos-latest (push) Has been cancelled
workspaces / Test multiple workspaces on windows-latest (push) Has been cancelled
2022-11-06 10:06:04 +01:00
Arpad Borsos
e78327dd9e small code style improvements, README and CHANGELOG updates 2022-11-06 09:50:33 +01:00
Lucas Fernandes Nogueira
ccdddcc049 only hash Cargo.toml/Cargo.lock that belong to a configured workspace (#90) 2022-11-05 21:18:04 +01:00
Arpad Borsos
b5ec9edd91 2.0.2
Some checks failed
coverage / Test `cargo-llvm-cov` on ubuntu-latest (push) Failing after 0s
install / Test `cargo install` on ubuntu-latest (push) Failing after 0s
simple / Test `cargo check/test` on ubuntu-latest (push) Failing after 0s
sparse-registry / Test `cargo check/test` with sparse registry on ubuntu-latest (push) Failing after 0s
target-dir / Test custom target-dir on ubuntu-latest (push) Failing after 0s
workspaces / Test multiple workspaces on ubuntu-latest (push) Failing after 0s
coverage / Test `cargo-llvm-cov` on macos-latest (push) Has been cancelled
coverage / Test `cargo-llvm-cov` on windows-latest (push) Has been cancelled
install / Test `cargo install` on macos-latest (push) Has been cancelled
install / Test `cargo install` on windows-latest (push) Has been cancelled
simple / Test `cargo check/test` on macos-latest (push) Has been cancelled
simple / Test `cargo check/test` on windows-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on macos-latest (push) Has been cancelled
sparse-registry / Test `cargo check/test` with sparse registry on windows-latest (push) Has been cancelled
target-dir / Test custom target-dir on macos-latest (push) Has been cancelled
target-dir / Test custom target-dir on windows-latest (push) Has been cancelled
workspaces / Test multiple workspaces on macos-latest (push) Has been cancelled
workspaces / Test multiple workspaces on windows-latest (push) Has been cancelled
2022-11-03 11:26:28 +01:00
Arpad Borsos
3f2513fdf4 avoid calling cargo metadata on pre-cleanup 2022-11-03 11:26:22 +01:00
Arpad Borsos
19c46583c5 update dependencies 2022-11-03 11:09:40 +01:00
Mikhail Katychev
b8e72aae83 Added prefix-key cache-directories and cache-targets options (#85) 2022-10-18 23:05:42 +02:00
27 changed files with 22262 additions and 17237 deletions

32
.github/workflows/buildjet.yml vendored Normal file
View 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
View 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 16.x
uses: actions/setup-node@v3
with:
node-version: 16.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/

View File

@@ -18,11 +18,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked. - run: rustup toolchain install stable --profile minimal --component llvm-tools-preview --no-self-update
# 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
- uses: taiki-e/install-action@cargo-llvm-cov - uses: taiki-e/install-action@cargo-llvm-cov

31
.github/workflows/git-registry.yml vendored Normal file
View 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

View File

@@ -18,11 +18,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked. - run: rustup toolchain install stable --profile minimal --no-self-update
# 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
- uses: ./ - uses: ./

View File

@@ -9,7 +9,7 @@ jobs:
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] 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 }} runs-on: ${{ matrix.os }}
env: env:
@@ -18,11 +18,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked. - run: rustup toolchain install stable --profile minimal --no-self-update
# 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
- uses: ./ - uses: ./
with: with:
@@ -31,4 +27,5 @@ jobs:
- run: | - run: |
cargo check cargo check
cargo test cargo test
cargo build --release
working-directory: tests working-directory: tests

View File

@@ -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

View File

@@ -18,11 +18,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked. - run: rustup toolchain install stable --profile minimal --no-self-update
# 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
# the `workspaces` option has the format `$workspace -> $target-dir` # the `workspaces` option has the format `$workspace -> $target-dir`
# and the `$target-dir` is relative to the `$workspace`. # and the `$target-dir` is relative to the `$workspace`.

View File

@@ -18,11 +18,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
# When rustup is updated, it tries to replace its binary, which on Windows is somehow locked. - run: rustup toolchain install stable --profile minimal --target wasm32-unknown-unknown --no-self-update
# 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
- uses: ./ - uses: ./
with: with:

View File

@@ -1,5 +1,52 @@
# Changelog # Changelog
## 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.
## 2.1.0
- Only hash `Cargo.{lock,toml}` files in the configured workspace directories.
## 2.0.2
- Avoid calling `cargo metadata` on pre-cleanup.
- Added `prefix-key`, `cache-directories` and `cache-targets` options.
## 2.0.1 ## 2.0.1
- Primarily just updating dependencies to fix GitHub deprecation notices. - Primarily just updating dependencies to fix GitHub deprecation notices.

View File

@@ -14,33 +14,65 @@ sensible defaults.
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
with: with:
# An explicit cache key that is used instead of the automatic `job`-based # The prefix cache key, this can be changed to start a new cache manually.
# cache key and is thus stable across jobs. # default: "v0-rust"
# Default: empty prefix-key: ""
# A cache key that is used instead of the automatic `job`-based key,
# and is stable over multiple jobs.
# default: empty
shared-key: "" shared-key: ""
# An additional cache key that is added alongside the automatic `job`-based # An additional cache key that is added alongside the automatic `job`-based
# cache key and can be used to further differentiate jobs. # cache key and can be used to further differentiate jobs.
# Default: empty # default: empty
key: "" key: ""
# A whitespace separated list of env-var *prefixes* who's value contributes # A whitespace separated list of env-var *prefixes* who's value contributes
# to the environment cache key. # to the environment cache key.
# The env-vars are matched by *prefix*, so the default `RUST` var will # The env-vars are matched by *prefix*, so the default `RUST` var will
# match all of `RUSTC`, `RUSTUP_*`, `RUSTFLAGS`, `RUSTDOC_*`, etc. # match all of `RUSTC`, `RUSTUP_*`, `RUSTFLAGS`, `RUSTDOC_*`, etc.
# Default: "CARGO CC CFLAGS CXX CMAKE RUST" # default: "CARGO CC CFLAGS CXX CMAKE RUST"
env-vars: "" env-vars: ""
# The cargo workspaces and target directory configuration. # The cargo workspaces and target directory configuration.
# These entries are separated by newlines and have the form # These entries are separated by newlines and have the form
# `$workspace -> $target`. The `$target` part is treated as a directory # `$workspace -> $target`. The `$target` part is treated as a directory
# relative to the `$workspace` and defaults to "target" if not explicitly given. # relative to the `$workspace` and defaults to "target" if not explicitly given.
# Default: ". -> target" # default: ". -> target"
workspaces: "" workspaces: ""
# Additional non workspace directories to be cached, separated by newlines.
cache-directories: ""
# Determines whether workspace `target` directories are cached.
# If `false`, only the cargo registry will be cached.
# default: "true"
cache-targets: ""
# Determines if the cache should be saved even when the workflow has failed. # Determines if the cache should be saved even when the workflow has failed.
# Default: "false" # default: "false"
cache-on-failure: "" 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,
# 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/head/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. Further examples are available in the [.github/workflows](./.github/workflows/) directory.
@@ -61,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. _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. 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 ## Cache Details
@@ -77,6 +110,7 @@ This cache is automatically keyed by:
- the value of some compiler-specific environment variables (eg. RUSTFLAGS, etc), and - 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 `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 `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. An additional input `key` can be provided if the builtin keys are not sufficient.
@@ -112,7 +146,7 @@ otherwise corrupt the cache on macOS builds.
This specialized cache action is built on top of the upstream cache action This specialized cache action is built on top of the upstream cache action
maintained by GitHub. The same restrictions and limits apply, which are maintained by GitHub. The same restrictions and limits apply, which are
documented here: 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 In particular, caches are currently limited to 10 GB in total and exceeding that
limit will cause eviction of older caches. limit will cause eviction of older caches.

View File

@@ -1,4 +1,3 @@
- better .cargo/bin handling: - better .cargo/bin handling:
- get a list of all the files on "pre"/"restore" - 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 - move the files out of the way on "post"/"save" and move them back afterwards
- properly clean sparse registry

View File

@@ -2,24 +2,47 @@ name: "Rust Cache"
description: "A GitHub Action that implements smart caching for rust/cargo projects with sensible defaults." description: "A GitHub Action that implements smart caching for rust/cargo projects with sensible defaults."
author: "Arpad Borsos <swatinem@swatinem.de>" author: "Arpad Borsos <swatinem@swatinem.de>"
inputs: inputs:
prefix-key:
description: "The prefix cache key, this can be changed to start a new cache manually."
required: false
default: "v0-rust"
shared-key: shared-key:
description: "An additional cache key that is stable over multiple jobs" description: "A cache key that is used instead of the automatic `job`-based key, and is stable over multiple jobs."
required: false required: false
key: key:
description: "An additional key for the cache" description: "An additional cache key that is added alongside the automatic `job`-based cache key and can be used to further differentiate jobs."
required: false required: false
env-vars: env-vars:
description: "Additional environment variables to include in the cache key, separated by spaces" description: "Additional environment variables to include in the cache key, separated by spaces."
required: false required: false
workspaces: workspaces:
description: "Paths to multiple Cargo workspaces and their target directories, separated by newlines" description: "Paths to multiple Cargo workspaces and their target directories, separated by newlines."
required: false required: false
cache-directories:
description: "Additional non workspace directories to be cached, separated by newlines."
required: false
cache-targets:
description: "Determines whether workspace targets are cached. If `false`, only the cargo registry will be cached."
required: false
default: "true"
cache-on-failure: cache-on-failure:
description: "Cache even if the build fails. Defaults to false" description: "Cache even if the build fails. Defaults to false."
required: 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: outputs:
cache-hit: cache-hit:
description: "A boolean value that indicates an exact match was found" description: "A boolean value that indicates an exact match was found."
runs: runs:
using: "node16" using: "node16"
main: "dist/restore/index.js" main: "dist/restore/index.js"

18888
dist/restore/index.js vendored

File diff suppressed because one or more lines are too long

18894
dist/save/index.js vendored

File diff suppressed because one or more lines are too long

870
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
{ {
"private": true, "private": true,
"name": "rust-cache", "name": "rust-cache",
"version": "2.0.1", "version": "2.6.0",
"description": "A GitHub Action that implements smart caching for rust/cargo projects with sensible defaults.", "description": "A GitHub Action that implements smart caching for rust/cargo projects with sensible defaults.",
"keywords": [ "keywords": [
"actions", "actions",
@@ -22,17 +22,20 @@
}, },
"homepage": "https://github.com/Swatinem/rust-cache#readme", "homepage": "https://github.com/Swatinem/rust-cache#readme",
"dependencies": { "dependencies": {
"@actions/cache": "^3.0.5", "@actions/buildjet-cache": "npm:github-actions.cache-buildjet@0.1.2",
"@actions/cache": "^3.2.1",
"@actions/core": "^1.10.0", "@actions/core": "^1.10.0",
"@actions/exec": "^1.1.1", "@actions/exec": "^1.1.1",
"@actions/glob": "^0.3.0", "@actions/glob": "^0.4.0",
"@actions/io": "^1.1.2" "@actions/io": "^1.1.3",
"toml": "^3.0.0"
}, },
"devDependencies": { "devDependencies": {
"@vercel/ncc": "^0.34.0", "@vercel/ncc": "^0.36.1",
"typescript": "4.8.4" "linefix": "^0.1.1",
"typescript": "5.1.6"
}, },
"scripts": { "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"
} }
} }

View File

@@ -3,7 +3,7 @@ import * as io from "@actions/io";
import fs from "fs"; import fs from "fs";
import path from "path"; import path from "path";
import { CARGO_HOME, STATE_BINS } from "./config"; import { CARGO_HOME } from "./config";
import { Packages } from "./workspace"; import { Packages } from "./workspace";
export async function cleanTargetDir(targetDir: string, packages: Packages, checkTimestamp = false) { export async function cleanTargetDir(targetDir: string, packages: Packages, checkTimestamp = false) {
@@ -69,9 +69,14 @@ export async function getCargoBins(): Promise<Set<string>> {
return bins; 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 bins = await getCargoBins();
const oldBins = JSON.parse(core.getState(STATE_BINS));
for (const bin of oldBins) { for (const bin of oldBins) {
bins.delete(bin); bins.delete(bin);
@@ -85,12 +90,16 @@ export async function cleanBin() {
} }
} }
export async function cleanRegistry(packages: Packages) { export async function cleanRegistry(packages: Packages, crates = true) {
// `.cargo/registry/src` // remove `.cargo/credentials.toml`
// we can remove this completely, as cargo will recreate this from `cache` try {
await rmRF(path.join(CARGO_HOME, "registry", "src")); const credentials = path.join(CARGO_HOME, ".cargo", "credentials.toml");
core.debug(`deleting "${credentials}"`);
await fs.promises.unlink(credentials);
} catch {}
// `.cargo/registry/index` // `.cargo/registry/index`
let pkgSet = new Set(packages.map((p) => p.name));
const indexDir = await fs.promises.opendir(path.join(CARGO_HOME, "registry", "index")); const indexDir = await fs.promises.opendir(path.join(CARGO_HOME, "registry", "index"));
for await (const dirent of indexDir) { for await (const dirent of indexDir) {
if (dirent.isDirectory()) { if (dirent.isDirectory()) {
@@ -101,14 +110,38 @@ export async function cleanRegistry(packages: Packages) {
// for a git registry, we can remove `.cache`, as cargo will recreate it from git // for a git registry, we can remove `.cache`, as cargo will recreate it from git
if (await exists(path.join(dirPath, ".git"))) { if (await exists(path.join(dirPath, ".git"))) {
await rmRF(path.join(dirPath, ".cache")); 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` // `.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")); const cacheDir = await fs.promises.opendir(path.join(CARGO_HOME, "registry", "cache"));
for await (const dirent of cacheDir) { for await (const dirent of cacheDir) {
if (dirent.isDirectory()) { if (dirent.isDirectory()) {
@@ -125,6 +158,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) { export async function cleanGit(packages: Packages) {
const coPath = path.join(CARGO_HOME, "git", "checkouts"); const coPath = path.join(CARGO_HOME, "git", "checkouts");
const dbPath = path.join(CARGO_HOME, "git", "db"); const dbPath = path.join(CARGO_HOME, "git", "db");
@@ -180,17 +235,29 @@ export async function cleanGit(packages: Packages) {
const ONE_WEEK = 7 * 24 * 3600 * 1000; const ONE_WEEK = 7 * 24 * 3600 * 1000;
/** /**
* Removes all files or directories in `dirName`, except the ones matching * Removes all files or directories in `dirName` matching some criteria.
* any string in the `keepPrefix` set.
*
* The matching strips and trailing `-$hash` suffix.
* *
* When the `checkTimestamp` flag is set, this will also remove anything older * When the `checkTimestamp` flag is set, this will also remove anything older
* than one week. * 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.
*/ */
async function rmExcept(dirName: string, keepPrefix: Set<string>, checkTimestamp = false) { async function rmExcept(dirName: string, keepPrefix: Set<string>, checkTimestamp = false) {
const dir = await fs.promises.opendir(dirName); const dir = await fs.promises.opendir(dirName);
for await (const dirent of dir) { for await (const dirent of dir) {
if (checkTimestamp) {
const fileName = path.join(dir.path, dirent.name);
const { mtime } = await fs.promises.stat(fileName);
const isOutdated = Date.now() - mtime.getTime() > ONE_WEEK;
if (isOutdated) {
await rm(dir.path, dirent);
}
return;
}
let name = dirent.name; let name = dirent.name;
// strip the trailing hash // strip the trailing hash
@@ -199,14 +266,7 @@ async function rmExcept(dirName: string, keepPrefix: Set<string>, checkTimestamp
name = name.slice(0, idx); name = name.slice(0, idx);
} }
let isOutdated = false; if (!keepPrefix.has(name)) {
if (checkTimestamp) {
const fileName = path.join(dir.path, dirent.name);
const { mtime } = await fs.promises.stat(fileName);
isOutdated = Date.now() - mtime.getTime() > ONE_WEEK;
}
if (!keepPrefix.has(name) || isOutdated) {
await rm(dir.path, dirent); await rm(dir.path, dirent);
} }
} }

View File

@@ -2,19 +2,20 @@ import * as core from "@actions/core";
import * as glob from "@actions/glob"; import * as glob from "@actions/glob";
import crypto from "crypto"; import crypto from "crypto";
import fs from "fs"; import fs from "fs";
import fs_promises from "fs/promises";
import os from "os"; import os from "os";
import path from "path"; import path from "path";
import * as toml from "toml";
import { getCmdOutput } from "./utils"; import { getCargoBins } from "./cleanup";
import { CacheProvider, getCmdOutput } from "./utils";
import { Workspace } from "./workspace"; import { Workspace } from "./workspace";
const HOME = os.homedir(); const HOME = os.homedir();
export const CARGO_HOME = process.env.CARGO_HOME || path.join(HOME, ".cargo"); export const CARGO_HOME = process.env.CARGO_HOME || path.join(HOME, ".cargo");
const STATE_LOCKFILE_HASH = "RUST_CACHE_LOCKFILE_HASH"; const STATE_CONFIG = "RUST_CACHE_CONFIG";
const STATE_LOCKFILES = "RUST_CACHE_LOCKFILES"; const HASH_LENGTH = 8;
export const STATE_BINS = "RUST_CACHE_BINS";
export const STATE_KEY = "RUST_CACHE_KEY";
export class CacheConfig { export class CacheConfig {
/** All the paths we want to cache */ /** All the paths we want to cache */
@@ -27,6 +28,9 @@ export class CacheConfig {
/** The workspace configurations */ /** The workspace configurations */
public workspaces: Array<Workspace> = []; public workspaces: Array<Workspace> = [];
/** The cargo binaries present during main step */
public cargoBins: Array<string> = [];
/** The prefix portion of the cache key */ /** The prefix portion of the cache key */
private keyPrefix = ""; private keyPrefix = "";
/** The rust version considered for the cache key */ /** The rust version considered for the cache key */
@@ -50,7 +54,7 @@ export class CacheConfig {
// This uses either the `shared-key` input, // This uses either the `shared-key` input,
// or the `key` input combined with the `job` key. // or the `key` input combined with the `job` key.
let key = `v0-rust`; let key = core.getInput("prefix-key") || "v0-rust";
const sharedKey = core.getInput("shared-key"); const sharedKey = core.getInput("shared-key");
if (sharedKey) { if (sharedKey) {
@@ -103,43 +107,14 @@ export class CacheConfig {
} }
self.keyEnvs = keyEnvs; self.keyEnvs = keyEnvs;
key += `-${hasher.digest("hex")}`;
key += `-${digest(hasher)}`;
self.restoreKey = key; self.restoreKey = key;
// Construct the lockfiles portion of the key: // Construct the lockfiles portion of the key:
// This considers all the files found via globbing for various manifests // This considers all the files found via globbing for various manifests
// and lockfiles. // 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) || "[]");
if (!lockHash) {
const globber = await glob.create("**/Cargo.toml\n**/Cargo.lock\nrust-toolchain\nrust-toolchain.toml", {
followSymbolicLinks: false,
});
keyFiles = await globber.glob();
keyFiles.sort((a, b) => a.localeCompare(b));
hasher = crypto.createHash("sha1");
for (const file of keyFiles) {
for await (const chunk of fs.createReadStream(file)) {
hasher.update(chunk);
}
}
lockHash = hasher.digest("hex");
core.saveState(STATE_LOCKFILE_HASH, lockHash);
core.saveState(STATE_LOCKFILES, JSON.stringify(keyFiles));
}
self.keyFiles = keyFiles;
key += `-${lockHash}`;
self.cacheKey = key;
// Constructs the workspace config and paths to restore: // Constructs the workspace config and paths to restore:
// The workspaces are given using a `$workspace -> $target` syntax. // The workspaces are given using a `$workspace -> $target` syntax.
@@ -154,13 +129,148 @@ export class CacheConfig {
} }
self.workspaces = workspaces; self.workspaces = workspaces;
self.cachePaths = [CARGO_HOME, ...workspaces.map((ws) => ws.target)]; 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 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 cargo_manifests = sort_and_uniq(await globFiles(`${root}/**/Cargo.toml`));
for (const cargo_manifest of cargo_manifests) {
try {
const content = await fs_promises.readFile(cargo_manifest, { encoding: "utf8" });
const parsed = toml.parse(content);
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];
if ("path" in dep) {
dep.version = "0.0.0";
}
}
}
hasher.update(JSON.stringify(parsed));
parsedKeyFiles.push(cargo_manifest);
} catch (_e) {
// Fallback to caching them as regular file
keyFiles.push(cargo_manifest);
}
}
const cargo_locks = sort_and_uniq(await globFiles(`${root}/**/Cargo.lock`));
for (const cargo_lock of cargo_locks) {
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
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.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
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);
}
}
let lockHash = digest(hasher);
keyFiles.push(...parsedKeyFiles);
self.keyFiles = sort_and_uniq(keyFiles);
key += `-${lockHash}`;
self.cacheKey = key;
self.cachePaths = [CARGO_HOME];
const cacheTargets = core.getInput("cache-targets").toLowerCase() || "true";
if (cacheTargets === "true") {
self.cachePaths.push(...workspaces.map((ws) => ws.target));
}
const cacheDirectories = core.getInput("cache-directories");
for (const dir of cacheDirectories.trim().split(/\s+/).filter(Boolean)) {
self.cachePaths.push(dir);
}
const bins = await getCargoBins();
self.cargoBins = Array.from(bins.values());
return self; 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.startGroup("Cache Configuration");
core.info(`Cache Provider:`);
core.info(` ${cacheProvider.name}`);
core.info(`Workspaces:`); core.info(`Workspaces:`);
for (const workspace of this.workspaces) { for (const workspace of this.workspaces) {
core.info(` ${workspace.root}`); core.info(` ${workspace.root}`);
@@ -186,6 +296,33 @@ export class CacheConfig {
} }
core.endGroup(); 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 { interface RustVersion {
@@ -203,3 +340,30 @@ async function getRustVersion(): Promise<RustVersion> {
.filter((s) => s.length === 2); .filter((s) => s.length === 2);
return Object.fromEntries(splits); return Object.fromEntries(splits);
} }
async function globFiles(pattern: string): Promise<string[]> {
const globber = await glob.create(pattern, {
followSymbolicLinks: false,
});
// 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;
}, []);
}

View File

@@ -1,18 +1,20 @@
import * as cache from "@actions/cache";
import * as core from "@actions/core"; import * as core from "@actions/core";
import { cleanTargetDir, getCargoBins } from "./cleanup"; import { cleanTargetDir } from "./cleanup";
import { CacheConfig, STATE_BINS, STATE_KEY } from "./config"; import { CacheConfig } from "./config";
import { getCacheProvider, reportError } from "./utils";
process.on("uncaughtException", (e) => { process.on("uncaughtException", (e) => {
core.info(`[warning] ${e.message}`); core.error(e.message);
if (e.stack) { if (e.stack) {
core.info(e.stack); core.error(e.stack);
} }
}); });
async function run() { async function run() {
if (!cache.isFeatureAvailable()) { const cacheProvider = getCacheProvider();
if (!cacheProvider.cache.isFeatureAvailable()) {
setCacheHitOutput(false); setCacheHitOutput(false);
return; return;
} }
@@ -26,40 +28,41 @@ async function run() {
core.exportVariable("CARGO_INCREMENTAL", 0); core.exportVariable("CARGO_INCREMENTAL", 0);
const config = await CacheConfig.new(); const config = await CacheConfig.new();
config.printInfo(); config.printInfo(cacheProvider);
core.info(""); core.info("");
const bins = await getCargoBins();
core.saveState(STATE_BINS, JSON.stringify([...bins]));
core.info(`... Restoring cache ...`); core.info(`... Restoring cache ...`);
const key = config.cacheKey; 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) { if (restoreKey) {
core.info(`Restored from cache key "${restoreKey}".`); const match = restoreKey === key;
core.saveState(STATE_KEY, restoreKey); core.info(`Restored from cache key "${restoreKey}" full match: ${match}.`);
if (!match) {
if (restoreKey !== key) {
// pre-clean the target directory on cache mismatch // pre-clean the target directory on cache mismatch
for (const workspace of config.workspaces) { for (const workspace of config.workspaces) {
try { try {
const packages = await workspace.getPackages(); await cleanTargetDir(workspace.target, [], true);
await cleanTargetDir(workspace.target, packages, true);
} catch {} } catch {}
} }
// We restored the cache but it is not a full match.
config.saveState();
} }
setCacheHitOutput(restoreKey === key); setCacheHitOutput(match);
} else { } else {
core.info("No cache found."); core.info("No cache found.");
config.saveState();
setCacheHitOutput(false); setCacheHitOutput(false);
} }
} catch (e) { } catch (e) {
setCacheHitOutput(false); setCacheHitOutput(false);
core.info(`[warning] ${(e as any).stack}`); reportError(e);
} }
} }

View File

@@ -1,32 +1,36 @@
import * as cache from "@actions/cache";
import * as core from "@actions/core"; import * as core from "@actions/core";
import * as exec from "@actions/exec"; import * as exec from "@actions/exec";
import { cleanBin, cleanGit, cleanRegistry, cleanTargetDir } from "./cleanup"; 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) => { process.on("uncaughtException", (e) => {
core.info(`[warning] ${e.message}`); core.error(e.message);
if (e.stack) { if (e.stack) {
core.info(e.stack); core.error(e.stack);
} }
}); });
async function run() { async function run() {
if (!cache.isFeatureAvailable()) { const cacheProvider = getCacheProvider();
const save = core.getInput("save-if").toLowerCase() || "true";
if (!(cacheProvider.cache.isFeatureAvailable() && save === "true")) {
return; return;
} }
try { try {
const config = await CacheConfig.new(); if (isCacheUpToDate()) {
config.printInfo();
core.info("");
if (core.getState(STATE_KEY) === config.cacheKey) {
core.info(`Cache up-to-date.`); core.info(`Cache up-to-date.`);
return; return;
} }
const config = CacheConfig.fromState();
config.printInfo(cacheProvider);
core.info("");
// TODO: remove this once https://github.com/actions/toolkit/pull/553 lands // TODO: remove this once https://github.com/actions/toolkit/pull/553 lands
await macOsWorkaround(); await macOsWorkaround();
@@ -38,35 +42,39 @@ async function run() {
core.info(`... Cleaning ${workspace.target} ...`); core.info(`... Cleaning ${workspace.target} ...`);
await cleanTargetDir(workspace.target, packages); await cleanTargetDir(workspace.target, packages);
} catch (e) { } catch (e) {
core.info(`[warning] ${(e as any).stack}`); core.debug(`${(e as any).stack}`);
} }
} }
try { try {
core.info(`... Cleaning cargo registry ...`); const crates = core.getInput("cache-all-crates").toLowerCase() || "false";
await cleanRegistry(allPackages); core.info(`... Cleaning cargo registry (cache-all-crates: ${crates}) ...`);
await cleanRegistry(allPackages, crates !== "true");
} catch (e) { } catch (e) {
core.info(`[warning] ${(e as any).stack}`); core.debug(`${(e as any).stack}`);
} }
try { try {
core.info(`... Cleaning cargo/bin ...`); core.info(`... Cleaning cargo/bin ...`);
await cleanBin(); await cleanBin(config.cargoBins);
} catch (e) { } catch (e) {
core.info(`[warning] ${(e as any).stack}`); core.debug(`${(e as any).stack}`);
} }
try { try {
core.info(`... Cleaning cargo git cache ...`); core.info(`... Cleaning cargo git cache ...`);
await cleanGit(allPackages); await cleanGit(allPackages);
} catch (e) { } catch (e) {
core.info(`[warning] ${(e as any).stack}`); core.debug(`${(e as any).stack}`);
} }
core.info(`... Saving cache ...`); 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) { } catch (e) {
core.info(`[warning] ${(e as any).stack}`); reportError(e);
} }
} }

View File

@@ -1,5 +1,17 @@
import * as core from "@actions/core"; import * as core from "@actions/core";
import * as exec from "@actions/exec"; import * as exec from "@actions/exec";
import * as buildjetCache from "@actions/buildjet-cache";
import * as ghCache from "@actions/cache";
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( export async function getCmdOutput(
cmd: string, cmd: string,
@@ -22,9 +34,30 @@ export async function getCmdOutput(
...options, ...options,
}); });
} catch (e) { } catch (e) {
core.info(`[warning] Command failed: ${cmd} ${args.join(" ")}`); (e as any).commandFailed = {
core.info(`[warning] ${stderr}`); command: `${cmd} ${args.join(" ")}`,
stderr,
};
throw e; throw e;
} }
return stdout; 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,
};
}

View File

@@ -1,3 +1,4 @@
import * as core from "@actions/core";
import path from "path"; import path from "path";
import { getCmdOutput } from "./utils"; import { getCmdOutput } from "./utils";
@@ -10,11 +11,13 @@ export class Workspace {
public async getPackages(): Promise<Packages> { public async getPackages(): Promise<Packages> {
let packages: Packages = []; let packages: Packages = [];
try { try {
core.debug(`collecting metadata for "${this.root}"`);
const meta: Meta = JSON.parse( const meta: Meta = JSON.parse(
await getCmdOutput("cargo", ["metadata", "--all-features", "--format-version", "1"], { await getCmdOutput("cargo", ["metadata", "--all-features", "--format-version", "1"], {
cwd: this.root, cwd: this.root,
}), }),
); );
core.debug(`workspace "${this.root}" has ${meta.packages.length} packages`);
for (const pkg of meta.packages) { for (const pkg of meta.packages) {
if (pkg.manifest_path.startsWith(this.root)) { if (pkg.manifest_path.startsWith(this.root)) {
continue; continue;

31
tests/Cargo.lock generated
View File

@@ -10,9 +10,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]] [[package]]
name = "base64" name = "base64"
version = "0.13.0" version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
@@ -483,9 +483,9 @@ dependencies = [
[[package]] [[package]]
name = "reqwest" name = "reqwest"
version = "0.11.11" version = "0.11.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b75aa69a3f06bbcc66ede33af2af253c6f7a86b1ca0033f60c580a27074fbf92" checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55"
dependencies = [ dependencies = [
"base64", "base64",
"bytes", "bytes",
@@ -499,10 +499,10 @@ dependencies = [
"hyper-tls", "hyper-tls",
"ipnet", "ipnet",
"js-sys", "js-sys",
"lazy_static",
"log", "log",
"mime", "mime",
"native-tls", "native-tls",
"once_cell",
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
"serde", "serde",
@@ -523,6 +523,7 @@ name = "rust-cache"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"reqwest", "reqwest",
"tikv-jemallocator",
"watto", "watto",
] ]
@@ -658,6 +659,26 @@ dependencies = [
"syn", "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]] [[package]]
name = "tinyvec" name = "tinyvec"
version = "1.6.0" version = "1.6.0"

View File

@@ -6,5 +6,8 @@ authors = ["Arpad Borsos <arpad.borsos@googlemail.com>"]
edition = "2021" edition = "2021"
[dependencies] [dependencies]
reqwest = "0.11.11" reqwest = "0.11.18"
watto = { git = "https://github.com/getsentry/watto", rev = "d71c8218506bddba102a124a460d64da25e303dc", features = ["strings"] } watto = { git = "https://github.com/getsentry/watto", rev = "d71c8218506bddba102a124a460d64da25e303dc", features = ["strings"] }
[target.'cfg(not(target_env = "msvc"))'.dependencies]
tikv-jemallocator = "0.5.4"

View File

@@ -0,0 +1,2 @@
the `rust-toolchain` directory will be globbed,
and should not lead to any errors down the road

View File

@@ -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() { fn main() {
println!("Hello, world!"); println!("Hello, world!");
} }