5
0
mirror of https://github.com/astral-sh/setup-uv.git synced 2025-12-17 11:05:59 +00:00

Compare commits

..

3 Commits

Author SHA1 Message Date
Kevin Stillhammer
2233977af9 leave uv.exe in D: 2024-09-18 20:49:20 +02:00
Kevin Stillhammer
363497d0ae mv uv.exe onto D: 2024-09-18 18:17:51 +02:00
Kevin Stillhammer
561bff6f70 Add tool bin dir to PATH on windows 2024-09-18 18:00:23 +02:00
26 changed files with 12430 additions and 9287 deletions

4
.eslintignore Normal file
View File

@@ -0,0 +1,4 @@
dist/
lib/
node_modules/
jest.config.js

61
.eslintrc.json Normal file
View File

@@ -0,0 +1,61 @@
{
"plugins": ["jest", "@typescript-eslint"],
"extends": ["plugin:github/recommended"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "module",
"project": "./tsconfig.json"
},
"rules": {
"no-shadow": "off",
"@typescript-eslint/no-shadow": ["error"],
"i18n-text/no-en": "off",
"eslint-comments/no-use": "off",
"import/no-namespace": "off",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/explicit-member-accessibility": [
"error",
{ "accessibility": "no-public" }
],
"@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/array-type": "error",
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/ban-ts-comment": "error",
"camelcase": "off",
"@typescript-eslint/consistent-type-assertions": "error",
"@typescript-eslint/explicit-function-return-type": [
"error",
{ "allowExpressions": true }
],
"@typescript-eslint/func-call-spacing": ["error", "never"],
"@typescript-eslint/no-array-constructor": "error",
"@typescript-eslint/no-empty-interface": "error",
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-extraneous-class": "error",
"@typescript-eslint/no-for-in-array": "error",
"@typescript-eslint/no-inferrable-types": "error",
"@typescript-eslint/no-misused-new": "error",
"@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/no-unnecessary-qualifier": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/no-useless-constructor": "error",
"@typescript-eslint/no-var-requires": "error",
"@typescript-eslint/prefer-for-of": "warn",
"@typescript-eslint/prefer-function-type": "warn",
"@typescript-eslint/prefer-includes": "error",
"@typescript-eslint/prefer-string-starts-ends-with": "error",
"@typescript-eslint/promise-function-async": "error",
"@typescript-eslint/require-array-sort-compare": "error",
"@typescript-eslint/restrict-plus-operands": "error",
"@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unbound-method": "error"
},
"env": {
"node": true,
"es6": true,
"jest/globals": true
}
}

View File

@@ -11,7 +11,10 @@ concurrency:
jobs: jobs:
test-setup-cache: test-setup-cache:
runs-on: windows-latest runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [windows-latest]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Setup with cache - name: Setup with cache
@@ -22,7 +25,10 @@ jobs:
- run: uv sync - run: uv sync
working-directory: __tests__\fixtures\uv-project working-directory: __tests__\fixtures\uv-project
test-restore-cache: test-restore-cache:
runs-on: windows-latest runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [windows-latest]
needs: test-setup-cache needs: test-setup-cache
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4

View File

@@ -11,18 +11,24 @@ concurrency:
jobs: jobs:
test-setup-cache: test-setup-cache:
runs-on: ubuntu-latest runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, macos-14]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Setup with cache - name: Setup with cache
uses: ./ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}
- run: uv sync - run: uv sync
working-directory: __tests__/fixtures/uv-project working-directory: __tests__/fixtures/uv-project
test-restore-cache: test-restore-cache:
runs-on: ubuntu-latest runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, macos-14]
needs: test-setup-cache needs: test-setup-cache
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -31,7 +37,7 @@ jobs:
uses: ./ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}
- name: Cache was hit - name: Cache was hit
run: | run: |
if [ "$CACHE_HIT" != "true" ]; then if [ "$CACHE_HIT" != "true" ]; then
@@ -53,7 +59,7 @@ jobs:
cache-dependency-glob: | cache-dependency-glob: |
__tests__/fixtures/uv-project/uv.lock __tests__/fixtures/uv-project/uv.lock
**/pyproject.toml **/pyproject.toml
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-dependency-glob cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}
- run: uv sync - run: uv sync
working-directory: __tests__/fixtures/uv-project working-directory: __tests__/fixtures/uv-project
test-restore-cache-dependency-glob: test-restore-cache-dependency-glob:
@@ -73,8 +79,7 @@ jobs:
cache-dependency-glob: | cache-dependency-glob: |
__tests__/fixtures/uv-project/uv.lock __tests__/fixtures/uv-project/uv.lock
**/pyproject.toml **/pyproject.toml
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-dependency-glob cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}
ignore-nothing-to-cache: true
- name: Cache was not hit - name: Cache was not hit
run: | run: |
if [ "$CACHE_HIT" == "true" ]; then if [ "$CACHE_HIT" == "true" ]; then
@@ -84,19 +89,19 @@ jobs:
CACHE_HIT: ${{ steps.restore.outputs.cache-hit }} CACHE_HIT: ${{ steps.restore.outputs.cache-hit }}
test-setup-cache-local: test-setup-cache-local:
runs-on: selfhosted-ubuntu-arm64 runs-on: oracle-aarch64
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Setup with cache - name: Setup with cache
uses: ./ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-local cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}
cache-local-path: /tmp/uv-cache cache-local-path: /tmp/uv-cache
- run: uv sync - run: uv sync
working-directory: __tests__/fixtures/uv-project working-directory: __tests__/fixtures/uv-project
test-restore-cache-local: test-restore-cache-local:
runs-on: selfhosted-ubuntu-arm64 runs-on: oracle-aarch64
needs: test-setup-cache-local needs: test-setup-cache-local
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -105,7 +110,7 @@ jobs:
uses: ./ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-local cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}
cache-local-path: /tmp/uv-cache cache-local-path: /tmp/uv-cache
- name: Cache was hit - name: Cache was hit
run: | run: |
@@ -116,49 +121,3 @@ jobs:
CACHE_HIT: ${{ steps.restore.outputs.cache-hit }} CACHE_HIT: ${{ steps.restore.outputs.cache-hit }}
- run: uv sync - run: uv sync
working-directory: __tests__/fixtures/uv-project working-directory: __tests__/fixtures/uv-project
test-tilde-expansion-cache-local-path:
runs-on: selfhosted-ubuntu-arm64
steps:
- uses: actions/checkout@v4
- name: Create cache directory
run: mkdir -p ~/uv-cache
shell: bash
- name: Setup with cache
uses: ./
with:
cache-local-path: ~/uv-cache/cache-local-path
- run: uv sync
working-directory: __tests__/fixtures/uv-project
test-tilde-expansion-cache-dependency-glob:
runs-on: selfhosted-ubuntu-arm64
steps:
- uses: actions/checkout@v4
- name: Create cache directory
run: mkdir -p ~/uv-cache
shell: bash
- name: Create cache dependency glob file
run: touch ~/uv-cache.glob
shell: bash
- name: Setup with cache
uses: ./
with:
enable-cache: true
cache-local-path: ~/uv-cache/cache-dependency-glob
cache-dependency-glob: "~/uv-cache.glob"
- run: uv sync
working-directory: __tests__/fixtures/uv-project
cleanup-tilde-expansion-tests:
needs:
- test-tilde-expansion-cache-local-path
- test-tilde-expansion-cache-dependency-glob
runs-on: selfhosted-ubuntu-arm64
steps:
- name: Remove cache directory
run: rm -rf ~/uv-cache
shell: bash
- name: Remove cache dependency glob file
run: rm -f ~/uv-cache.glob
shell: bash

View File

@@ -28,18 +28,19 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest, macos-latest, macos-14] os: [ubuntu-latest, macos-latest, macos-14, oracle-aarch64]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Install latest version - name: Install default version
uses: ./ uses: ./
- run: uv sync - run: uv sync
working-directory: __tests__/fixtures/uv-project working-directory: __tests__/fixtures/uv-project
test-specific-version: test-specific-version:
runs-on: ubuntu-latest runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
uv-version: ["0.3.0", "0.3.2", "0.3", "0.3.x", ">=0.3.0"] os: [ubuntu-latest, macos-latest, macos-14, oracle-aarch64]
uv-version: ["latest", "0.3.0", "0.3.2", "0.3", "0.3.x", ">=0.3.0"]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Install version ${{ matrix.uv-version }} - name: Install version ${{ matrix.uv-version }}
@@ -49,7 +50,10 @@ jobs:
- run: uv sync - run: uv sync
working-directory: __tests__/fixtures/uv-project working-directory: __tests__/fixtures/uv-project
test-semver-range: test-semver-range:
runs-on: ubuntu-latest runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, oracle-aarch64]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Install version 0.3 - name: Install version 0.3
@@ -68,15 +72,15 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest, macos-latest] os: [ubuntu-latest, oracle-aarch64]
checksum: checksum:
["4d9279ad5ca596b1e2d703901d508430eb07564dc4d8837de9e2fca9c90f8ecd"] ["4d9279ad5ca596b1e2d703901d508430eb07564dc4d8837de9e2fca9c90f8ecd"]
exclude: exclude:
- os: macos-latest - os: oracle-aarch64
checksum: "4d9279ad5ca596b1e2d703901d508430eb07564dc4d8837de9e2fca9c90f8ecd" checksum: "4d9279ad5ca596b1e2d703901d508430eb07564dc4d8837de9e2fca9c90f8ecd"
include: include:
- os: macos-latest - os: oracle-aarch64
checksum: "a70cbfbf3bb5c08b2f84963b4f12c94e08fbb2468ba418a3bfe1066fbe9e7218" checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8"
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Checksum matches expected - name: Checksum matches expected
@@ -105,53 +109,10 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: os: [windows-latest]
[
ubuntu-latest,
macos-latest,
macos-14,
windows-latest,
]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Install default version - name: Install default version
uses: ./ uses: ./
- run: uv tool install ruff - run: uv tool install ruff
- run: ruff --version - run: ruff --version
test-tilde-expansion-tool-dirs:
runs-on: selfhosted-ubuntu-arm64
steps:
- uses: actions/checkout@v4
- name: Setup with cache
uses: ./
with:
tool-bin-dir: "~/tool-bin-dir"
tool-dir: "~/tool-dir"
- name: "Check if tool dirs are expanded"
run: |
if ! echo "$PATH" | grep -q "/home/ubuntu/tool-bin-dir"; then
echo "PATH does not contain /home/ubuntu/tool-bin-dir: $PATH"
exit 1
fi
if [ "$UV_TOOL_DIR" != "/home/ubuntu/tool-dir" ]; then
echo "UV_TOOL_DIR does not contain /home/ubuntu/tool-dir: $UV_TOOL_DIR"
exit 1
fi
test-python-version:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.12", "3.13t"]
steps:
- uses: actions/checkout@v4
- name: Install latest version
uses: ./
with:
python-version: ${{ matrix.python-version }}
- name: Verify UV_PYTHON is set to correct version
run: |
if [ "$UV_PYTHON" != "${{ matrix.python-version }}" ]; then
exit 1
fi
- run: uv sync
working-directory: __tests__/fixtures/uv-project

View File

@@ -17,7 +17,7 @@ jobs:
src/download/checksum/known-checksums.ts ${{ secrets.GITHUB_TOKEN }} src/download/checksum/known-checksums.ts ${{ secrets.GITHUB_TOKEN }}
- run: npm install && npm run all - run: npm install && npm run all
- name: Create Pull Request - name: Create Pull Request
uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f # v7.0.5 uses: peter-evans/create-pull-request@6cd32fd93684475c31847837f87bb135d40a2b79 # v7.0.3
with: with:
commit-message: "chore: update known checksums" commit-message: "chore: update known checksums"
title: title:

3
.prettierignore Normal file
View File

@@ -0,0 +1,3 @@
dist/
lib/
node_modules/

4
.prettierrc.json Normal file
View File

@@ -0,0 +1,4 @@
{
"trailingComma": "all",
"proseWrap": "always"
}

184
README.md
View File

@@ -14,17 +14,12 @@ Set up your GitHub Actions workflow with a specific version of [uv](https://docs
- [Install the latest version (default)](#install-the-latest-version-default) - [Install the latest version (default)](#install-the-latest-version-default)
- [Install a specific version](#install-a-specific-version) - [Install a specific version](#install-a-specific-version)
- [Install a version by supplying a semver range](#install-a-version-by-supplying-a-semver-range) - [Install a version by supplying a semver range](#install-a-version-by-supplying-a-semver-range)
- [Python version](#python-version)
- [Validate checksum](#validate-checksum) - [Validate checksum](#validate-checksum)
- [Enable Caching](#enable-caching) - [Enable Caching](#enable-caching)
- [Cache dependency glob](#cache-dependency-glob) - [Cache dependency glob](#cache-dependency-glob)
- [Local cache path](#local-cache-path) - [Local cache path](#local-cache-path)
- [Disable cache pruning](#disable-cache-pruning)
- [Ignore nothing to cache](#ignore-nothing-to-cache)
- [GitHub authentication token](#github-authentication-token) - [GitHub authentication token](#github-authentication-token)
- [UV_TOOL_DIR](#uv_tool_dir)
- [UV_TOOL_BIN_DIR](#uv_tool_bin_dir) - [UV_TOOL_BIN_DIR](#uv_tool_bin_dir)
- [Tilde Expansion](#tilde-expansion)
- [How it works](#how-it-works) - [How it works](#how-it-works)
- [FAQ](#faq) - [FAQ](#faq)
@@ -34,7 +29,7 @@ Set up your GitHub Actions workflow with a specific version of [uv](https://docs
```yaml ```yaml
- name: Install the latest version of uv - name: Install the latest version of uv
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
version: "latest" version: "latest"
``` ```
@@ -42,75 +37,49 @@ Set up your GitHub Actions workflow with a specific version of [uv](https://docs
For an example workflow, see For an example workflow, see
[here](https://github.com/charliermarsh/autobot/blob/e42c66659bf97b90ca9ff305a19cc99952d0d43f/.github/workflows/ci.yaml). [here](https://github.com/charliermarsh/autobot/blob/e42c66659bf97b90ca9ff305a19cc99952d0d43f/.github/workflows/ci.yaml).
> [!TIP]
>
> Using `latest` requires that uv download the executable on every run, which incurs a cost
> (especially on self-hosted runners). As a best practice, consider pinning the version to a
> specific release.
### Install a specific version ### Install a specific version
```yaml ```yaml
- name: Install a specific version of uv - name: Install a specific version of uv
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
version: "0.4.4" version: "0.4.4"
``` ```
### Install a version by supplying a semver range ### Install a version by supplying a semver range
You can specify a [semver range](https://github.com/npm/node-semver?tab=readme-ov-file#ranges) You can also specify a [semver range](https://github.com/npm/node-semver?tab=readme-ov-file#ranges)
to install the latest version that satisfies the range. to install the latest version that satisfies the range.
```yaml ```yaml
- name: Install a semver range of uv - name: Install a semver range of uv
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
version: ">=0.4.0" version: ">=0.3.0"
``` ```
```yaml ```yaml
- name: Pinning a minor version of uv - name: Pinning a minor version of uv
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
version: "0.4.x" version: "0.3.x"
```
### Python version
You can use the input `python-version` to set the environment variable `UV_PYTHON` for the rest
of your workflow.
This will override any python version specifications in `pyproject.toml` and `.python-version`
```yaml
- name: Install the latest version of uv and set the python version to 3.12
uses: astral-sh/setup-uv@v4
with:
python-version: "3.12"
```
You can combine this with a matrix to test multiple python versions:
```yaml
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9", "3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- name: Install the latest version of uv and set the python version
uses: astral-sh/setup-uv@v4
with:
python-version: ${{ matrix.python-version }}
- name: Test with python ${{ matrix.python-version }}
run: uv run --frozen pytest
``` ```
### Validate checksum ### Validate checksum
You can specify a checksum to validate the downloaded executable. Checksums up to the default version You can also specify a checksum to validate the downloaded file. Checksums up to the default version
are automatically verified by this action. The sha256 hashes can be found on the are automatically verified by this action. The sha265 hashes can be found on the
[releases page](https://github.com/astral-sh/uv/releases) of the uv repo. [releases page](https://github.com/astral-sh/uv/releases) of the uv repo.
```yaml ```yaml
- name: Install a specific version and validate the checksum - name: Install a specific version and validate the checksum
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
version: "0.3.1" version: "0.3.1"
checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8" checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8"
@@ -118,8 +87,8 @@ are automatically verified by this action. The sha256 hashes can be found on the
### Enable caching ### Enable caching
If you enable caching, the [uv cache](https://docs.astral.sh/uv/concepts/cache/) will be uploaded to If you enable caching, the [uv cache](https://docs.astral.sh/uv/concepts/cache/) will be cached to
the GitHub Actions cache. This can speed up runs that reuse the cache by several minutes. the GitHub Actions Cache. This can speed up runs that reuse the cache by several minutes.
> [!TIP] > [!TIP]
> >
@@ -131,7 +100,7 @@ You can optionally define a custom cache key suffix.
```yaml ```yaml
- name: Enable caching and define a custom cache key suffix - name: Enable caching and define a custom cache key suffix
id: setup-uv id: setup-uv
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
enable-cache: true enable-cache: true
cache-suffix: "optional-suffix" cache-suffix: "optional-suffix"
@@ -148,9 +117,9 @@ use it in subsequent steps. For example, to use the cache in the above case:
#### Cache dependency glob #### Cache dependency glob
If you want to control when the GitHub Actions cache is invalidated, specify a glob pattern with the If you want to control when the cache is invalidated, specify a glob pattern with the
`cache-dependency-glob` input. The GitHub Actions cache will be invalidated if any file matching the glob pattern `cache-dependency-glob` input. The cache will be invalidated if any file matching the glob pattern
changes. If you use relative paths, they are relative to the repository root. changes. The glob matches files relative to the repository root.
> [!NOTE] > [!NOTE]
> >
@@ -158,7 +127,7 @@ changes. If you use relative paths, they are relative to the repository root.
```yaml ```yaml
- name: Define a cache dependency glob - name: Define a cache dependency glob
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
enable-cache: true enable-cache: true
cache-dependency-glob: "**/requirements*.txt" cache-dependency-glob: "**/requirements*.txt"
@@ -166,7 +135,7 @@ changes. If you use relative paths, they are relative to the repository root.
```yaml ```yaml
- name: Define a list of cache dependency globs - name: Define a list of cache dependency globs
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
enable-cache: true enable-cache: true
cache-dependency-glob: | cache-dependency-glob: |
@@ -174,17 +143,9 @@ changes. If you use relative paths, they are relative to the repository root.
**/pyproject.toml **/pyproject.toml
``` ```
```yaml
- name: Define an absolute cache dependency glob
uses: astral-sh/setup-uv@v4
with:
enable-cache: true
cache-dependency-glob: "/tmp/my-folder/requirements*.txt"
```
```yaml ```yaml
- name: Never invalidate the cache - name: Never invalidate the cache
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
enable-cache: true enable-cache: true
cache-dependency-glob: "" cache-dependency-glob: ""
@@ -192,51 +153,16 @@ changes. If you use relative paths, they are relative to the repository root.
### Local cache path ### Local cache path
This action controls where uv stores its cache on the runner's filesystem by setting `UV_CACHE_DIR`. This action controls where uv stores its cache on the runner's filesystem. You can change the
It defaults to `setup-uv-cache` in the `TMP` dir, `D:\a\_temp\uv-tool-dir` on Windows and default (`/tmp/setup-uv-cache`) by specifying the path with the `cache-local-path` input.
`/tmp/setup-uv-cache` on Linux/macOS. You can change the default by specifying the path with the
`cache-local-path` input.
```yaml ```yaml
- name: Define a custom uv cache path - name: Define a custom uv cache path
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
cache-local-path: "/path/to/cache" cache-local-path: "/path/to/cache"
``` ```
### Disable cache pruning
By default, the uv cache is pruned after every run, removing pre-built wheels, but retaining any
wheels that were built from source. On GitHub-hosted runners, it's typically faster to omit those
pre-built wheels from the cache (and instead re-download them from the registry on each run).
However, on self-hosted or local runners, preserving the cache may be more efficient. See
the [documentation](https://docs.astral.sh/uv/concepts/cache/#caching-in-continuous-integration) for
more information.
If you want to persist the entire cache across runs, disable cache pruning with the `prune-cache`
input.
```yaml
- name: Don't prune the cache before saving it
uses: astral-sh/setup-uv@v4
with:
enable-cache: true
prune-cache: false
```
### Ignore nothing to cache
By default, the action will fail if caching is enabled but there is nothing to upload (the uv cache directory does not exist).
If you want to ignore this, set the `ignore-nothing-to-cache` input to `true`.
```yaml
- name: Ignore nothing to cache
uses: astral-sh/setup-uv@v4
with:
enable-cache: true
ignore-nothing-to-cache: true
```
### GitHub authentication token ### GitHub authentication token
This action uses the GitHub API to fetch the uv release artifacts. To avoid hitting the GitHub API This action uses the GitHub API to fetch the uv release artifacts. To avoid hitting the GitHub API
@@ -249,34 +175,15 @@ are not sufficient, you can provide a custom GitHub token with the necessary per
```yaml ```yaml
- name: Install the latest version of uv with a custom GitHub token - name: Install the latest version of uv with a custom GitHub token
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
github-token: ${{ secrets.CUSTOM_GITHUB_TOKEN }} github-token: ${{ secrets.CUSTOM_GITHUB_TOKEN }}
``` ```
### UV_TOOL_DIR
On Windows `UV_TOOL_DIR` is set to `uv-tool-dir` in the `TMP` dir (e.g. `D:\a\_temp\uv-tool-dir`).
On GitHub hosted runners this is on the much faster `D:` drive.
On all other platforms the tool environments are placed in the
[default location](https://docs.astral.sh/uv/concepts/tools/#tools-directory).
If you want to change this behaviour (especially on self-hosted runners) you can use the `tool-dir`
input:
```yaml
- name: Install the latest version of uv with a custom tool dir
uses: astral-sh/setup-uv@v4
with:
tool-dir: "/path/to/tool/dir"
```
### UV_TOOL_BIN_DIR ### UV_TOOL_BIN_DIR
On Windows `UV_TOOL_BIN_DIR` is set to `uv-tool-bin-dir` in the `TMP` dir (e.g. On Windows `UV_TOOL_BIN_DIR` is set to the `TMP` dir. On GitHub hosted runners this is on the much
`D:\a\_temp\uv-tool-bin-dir`). On GitHub hosted runners this is on the much faster `D:` drive. This faster `D:` drive. This path is also automatically added to the PATH.
path is also automatically added to the PATH.
On all other platforms the tool binaries get installed to the On all other platforms the tool binaries get installed to the
[default location](https://docs.astral.sh/uv/concepts/tools/#the-bin-directory). [default location](https://docs.astral.sh/uv/concepts/tools/#the-bin-directory).
@@ -286,28 +193,9 @@ If you want to change this behaviour (especially on self-hosted runners) you can
```yaml ```yaml
- name: Install the latest version of uv with a custom tool bin dir - name: Install the latest version of uv with a custom tool bin dir
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
tool-bin-dir: "/path/to/tool-bin/dir" tool-bin-dir: "/path/to/tool/bin"
```
### Tilde Expansion
This action supports expanding the `~` character to the user's home directory for the following inputs:
- `cache-local-path`
- `tool-dir`
- `tool-bin-dir`
- `cache-dependency-glob`
```yaml
- name: Expand the tilde character
uses: astral-sh/setup-uv@v4
with:
cache-local-path: "~/path/to/cache"
tool-dir: "~/path/to/tool/dir"
tool-bin-dir: "~/path/to/tool-bin/dir"
cache-dependency-glob: "~/my-cache-buster"
``` ```
## How it works ## How it works
@@ -334,7 +222,7 @@ For example:
- name: Checkout the repository - name: Checkout the repository
uses: actions/checkout@main uses: actions/checkout@main
- name: Install the latest version of uv - name: Install the latest version of uv
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
enable-cache: true enable-cache: true
- name: Test - name: Test
@@ -346,7 +234,7 @@ To install a specific version of Python, use
```yaml ```yaml
- name: Install the latest version of uv - name: Install the latest version of uv
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
with: with:
enable-cache: true enable-cache: true
- name: Install Python 3.12 - name: Install Python 3.12
@@ -365,7 +253,7 @@ output:
uses: actions/checkout@main uses: actions/checkout@main
- name: Install the default version of uv - name: Install the default version of uv
id: setup-uv id: setup-uv
uses: astral-sh/setup-uv@v4 uses: astral-sh/setup-uv@v3
- name: Print the installed version - name: Print the installed version
run: echo "Installed uv version is ${{ steps.setup-uv.outputs.uv-version }}" run: echo "Installed uv version is ${{ steps.setup-uv.outputs.uv-version }}"
``` ```

View File

@@ -6,9 +6,6 @@ inputs:
version: version:
description: "The version of uv to install" description: "The version of uv to install"
default: "latest" default: "latest"
python-version:
description: "The version of Python to set UV_PYTHON to"
required: false
checksum: checksum:
description: "The checksum of the uv version to install" description: "The checksum of the uv version to install"
required: false required: false
@@ -32,15 +29,6 @@ inputs:
cache-local-path: cache-local-path:
description: "Local path to store the cache." description: "Local path to store the cache."
default: "" default: ""
prune-cache:
description: "Prune cache before saving."
default: "true"
ignore-nothing-to-cache:
description: "Ignore when nothing is found to cache."
default: "false"
tool-dir:
description: "Custom path to set UV_TOOL_DIR to."
required: false
tool-bin-dir: tool-bin-dir:
description: "Custom path to set UV_TOOL_BIN_DIR to." description: "Custom path to set UV_TOOL_BIN_DIR to."
required: false required: false

View File

@@ -1,31 +0,0 @@
{
"$schema": "https://biomejs.dev/schemas/1.9.2/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": false
},
"files": {
"ignoreUnknown": false,
"ignore": ["dist", "lib", "node_modules"]
},
"formatter": {
"enabled": true,
"indentStyle": "space"
},
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"javascript": {
"formatter": {
"quoteStyle": "double",
"trailingCommas": "all"
}
}
}

3981
dist/save-cache/index.js generated vendored

File diff suppressed because one or more lines are too long

4790
dist/setup/index.js generated vendored

File diff suppressed because one or more lines are too long

4651
dist/update-known-checksums/index.js generated vendored

File diff suppressed because one or more lines are too long

6333
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,25 +6,30 @@
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"build": "tsc", "build": "tsc",
"format": "biome format --fix", "format": "prettier --write .",
"format-check": "biome format", "format-check": "prettier --check .",
"lint": "biome lint --fix", "lint": "eslint src/**/*.ts --fix",
"package": "ncc build -o dist/setup src/setup-uv.ts && ncc build -o dist/save-cache src/save-cache.ts && ncc build -o dist/update-known-checksums src/update-known-checksums.ts", "package": "ncc build -o dist/setup src/setup-uv.ts && ncc build -o dist/save-cache src/save-cache.ts && ncc build -o dist/update-known-checksums src/update-known-checksums.ts",
"test": "jest", "test": "jest",
"act": "act pull_request -W .github/workflows/test.yml --container-architecture linux/amd64 -s GITHUB_TOKEN=\"$(gh auth token)\"", "act": "act pull_request -W .github/workflows/test.yml --container-architecture linux/amd64 -s GITHUB_TOKEN=\"$(gh auth token)\"",
"update-known-checksums": "RUNNER_TEMP=known_checksums node dist/update-known-checksums/index.js src/download/checksum/known-checksums.ts \"$(gh auth token)\"", "update-known-checksums": "node dist/update-known-checksums/index.js src/download/checksum/known-checksums.ts \"$(gh auth token)\"",
"all": "npm run build && npm run format && npm run lint && npm run package && npm test" "all": "npm run build && npm run format && npm run lint && npm run package && npm test"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/astral-sh/setup-uv.git" "url": "git+https://github.com/astral-sh/setup-uv.git"
}, },
"keywords": ["actions", "python", "setup", "uv"], "keywords": [
"actions",
"python",
"setup",
"uv"
],
"author": "@eifinger", "author": "@eifinger",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/cache": "^3.3.0", "@actions/cache": "^3.2.4",
"@actions/core": "^1.11.1", "@actions/core": "^1.10.1",
"@actions/exec": "^1.1.1", "@actions/exec": "^1.1.1",
"@actions/github": "^6.0.0", "@actions/github": "^6.0.0",
"@actions/glob": "^0.5.0", "@actions/glob": "^0.5.0",
@@ -33,13 +38,20 @@
"@octokit/rest": "^21.0.2" "@octokit/rest": "^21.0.2"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "1.9.4", "@types/node": "^22.5.5",
"@types/node": "^22.9.1",
"@types/semver": "^7.5.8", "@types/semver": "^7.5.8",
"@vercel/ncc": "^0.38.3", "@typescript-eslint/eslint-plugin": "^7.15.0",
"@typescript-eslint/parser": "^7.18.0",
"@vercel/ncc": "^0.38.1",
"eslint": "^8.57.1",
"eslint-plugin-github": "^5.0.2",
"eslint-plugin-import": "^2.30.0",
"eslint-plugin-jest": "^28.8.3",
"eslint-plugin-prettier": "^5.2.1",
"jest": "^29.7.0", "jest": "^29.7.0",
"js-yaml": "^4.1.0", "js-yaml": "^4.1.0",
"prettier": "^3.3.3",
"ts-jest": "^29.2.5", "ts-jest": "^29.2.5",
"typescript": "^5.6.3" "typescript": "^5.6.2"
} }
} }

View File

@@ -1,4 +1,5 @@
import * as cache from "@actions/cache"; import * as cache from "@actions/cache";
import * as glob from "@actions/glob";
import * as core from "@actions/core"; import * as core from "@actions/core";
import { import {
cacheDependencyGlob, cacheDependencyGlob,
@@ -6,7 +7,6 @@ import {
cacheSuffix, cacheSuffix,
} from "../utils/inputs"; } from "../utils/inputs";
import { getArch, getPlatform } from "../utils/platforms"; import { getArch, getPlatform } from "../utils/platforms";
import { hashFiles } from "../hash/hash-files";
export const STATE_CACHE_KEY = "cache-key"; export const STATE_CACHE_KEY = "cache-key";
export const STATE_CACHE_MATCHED_KEY = "cache-matched-key"; export const STATE_CACHE_MATCHED_KEY = "cache-matched-key";
@@ -39,10 +39,15 @@ async function computeKeys(version: string): Promise<string> {
core.info( core.info(
`Searching files using cache dependency glob: ${cacheDependencyGlob.split("\n").join(",")}`, `Searching files using cache dependency glob: ${cacheDependencyGlob.split("\n").join(",")}`,
); );
cacheDependencyPathHash += await hashFiles(cacheDependencyGlob, true); cacheDependencyPathHash += await glob.hashFiles(
cacheDependencyGlob,
undefined,
undefined,
true,
);
if (cacheDependencyPathHash === "-") { if (cacheDependencyPathHash === "-") {
throw new Error( throw new Error(
`No file matched to [${cacheDependencyGlob.split("\n").join(",")}], make sure you have checked out the target repository`, `No file in ${process.cwd()} matched to [${cacheDependencyGlob.split("\n").join(",")}], make sure you have checked out the target repository`,
); );
} }
} else { } else {

View File

@@ -1,9 +1,9 @@
import * as fs from "node:fs"; import * as fs from "fs";
import * as crypto from "node:crypto"; import * as crypto from "crypto";
import * as core from "@actions/core"; import * as core from "@actions/core";
import { KNOWN_CHECKSUMS } from "./known-checksums"; import { KNOWN_CHECKSUMS } from "./known-checksums";
import type { Architecture, Platform } from "../../utils/platforms"; import { Architecture, Platform } from "../../utils/platforms";
export async function validateChecksum( export async function validateChecksum(
checkSum: string | undefined, checkSum: string | undefined,
@@ -12,11 +12,11 @@ export async function validateChecksum(
platform: Platform, platform: Platform,
version: string, version: string,
): Promise<void> { ): Promise<void> {
let isValid: boolean | undefined = undefined; let isValid = true;
if (checkSum !== undefined && checkSum !== "") { if (checkSum !== undefined && checkSum !== "") {
isValid = await validateFileCheckSum(downloadPath, checkSum); isValid = await validateFileCheckSum(downloadPath, checkSum);
} else { } else {
core.debug("Checksum not provided. Checking known checksums."); core.debug(`Checksum not provided. Checking known checksums.`);
const key = `${arch}-${platform}-${version}`; const key = `${arch}-${platform}-${version}`;
if (key in KNOWN_CHECKSUMS) { if (key in KNOWN_CHECKSUMS) {
const knownChecksum = KNOWN_CHECKSUMS[`${arch}-${platform}-${version}`]; const knownChecksum = KNOWN_CHECKSUMS[`${arch}-${platform}-${version}`];
@@ -27,12 +27,10 @@ export async function validateChecksum(
} }
} }
if (isValid === false) { if (!isValid) {
throw new Error(`Checksum for ${downloadPath} did not match ${checkSum}.`); throw new Error(`Checksum for ${downloadPath} did not match ${checkSum}.`);
} }
if (isValid === true) {
core.debug(`Checksum for ${downloadPath} is valid.`); core.debug(`Checksum for ${downloadPath} is valid.`);
}
} }
async function validateFileCheckSum( async function validateFileCheckSum(

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,5 @@
import { promises as fs } from "node:fs"; import { promises as fs } from "fs";
import * as tc from "@actions/tool-cache"; import * as tc from "@actions/tool-cache";
import { KNOWN_CHECKSUMS } from "./known-checksums";
export async function updateChecksums( export async function updateChecksums(
filePath: string, filePath: string,
downloadUrls: string[], downloadUrls: string[],
@@ -8,50 +7,31 @@ export async function updateChecksums(
await fs.rm(filePath); await fs.rm(filePath);
await fs.appendFile( await fs.appendFile(
filePath, filePath,
"// AUTOGENERATED_DO_NOT_EDIT\nexport const KNOWN_CHECKSUMS: { [key: string]: string } = {\n", "// AUTOGENERATED_DO_NOT_EDIT\nexport const KNOWN_CHECKSUMS: {[key: string]: string} = {\n",
); );
let firstLine = true; let firstLine = true;
for (const downloadUrl of downloadUrls) { for (const downloadUrl of downloadUrls) {
const content = await downloadAssetContent(downloadUrl);
const checksum = content.split(" ")[0].trim();
const key = getKey(downloadUrl); const key = getKey(downloadUrl);
if (key === undefined) {
continue;
}
const checksum = await getOrDownloadChecksum(key, downloadUrl);
if (!firstLine) { if (!firstLine) {
await fs.appendFile(filePath, ",\n"); await fs.appendFile(filePath, ",\n");
} }
await fs.appendFile(filePath, ` "${key}":\n "${checksum}"`); await fs.appendFile(filePath, ` '${key}':\n '${checksum}'`);
firstLine = false; firstLine = false;
} }
await fs.appendFile(filePath, ",\n};\n"); await fs.appendFile(filePath, "}\n");
} }
function getKey(downloadUrl: string): string | undefined { function getKey(downloadUrl: string): string {
// https://github.com/astral-sh/uv/releases/download/0.3.2/uv-aarch64-apple-darwin.tar.gz.sha256 // https://github.com/astral-sh/uv/releases/download/0.3.2/uv-aarch64-apple-darwin.tar.gz.sha256
const parts = downloadUrl.split("/"); const parts = downloadUrl.split("/");
const fileName = parts[parts.length - 1]; const fileName = parts[parts.length - 1];
if (fileName.startsWith("source")) {
return undefined;
}
const name = fileName.split(".")[0].split("uv-")[1]; const name = fileName.split(".")[0].split("uv-")[1];
const version = parts[parts.length - 2]; const version = parts[parts.length - 2];
return `${name}-${version}`; return `${name}-${version}`;
} }
async function getOrDownloadChecksum(
key: string,
downloadUrl: string,
): Promise<string> {
let checksum = "";
if (key in KNOWN_CHECKSUMS) {
checksum = KNOWN_CHECKSUMS[key];
} else {
const content = await downloadAssetContent(downloadUrl);
checksum = content.split(" ")[0].trim();
}
return checksum;
}
async function downloadAssetContent(downloadUrl: string): Promise<string> { async function downloadAssetContent(downloadUrl: string): Promise<string> {
const downloadPath = await tc.downloadTool(downloadUrl); const downloadPath = await tc.downloadTool(downloadUrl);
const content = await fs.readFile(downloadPath, "utf8"); const content = await fs.readFile(downloadPath, "utf8");

View File

@@ -0,0 +1,65 @@
import * as core from "@actions/core";
import * as tc from "@actions/tool-cache";
import * as exec from "@actions/exec";
import * as path from "path";
import { Architecture, Platform } from "../utils/platforms";
import { validateChecksum } from "./checksum/checksum";
import { OWNER, REPO } from "../utils/constants";
export async function downloadLatest(
platform: Platform,
arch: Architecture,
checkSum: string | undefined,
githubToken: string | undefined,
): Promise<{ cachedToolDir: string; version: string }> {
const artifact = `uv-${arch}-${platform}`;
let downloadUrl = `https://github.com/${OWNER}/${REPO}/releases/latest/download/${artifact}`;
if (platform === "pc-windows-msvc") {
downloadUrl += ".zip";
} else {
downloadUrl += ".tar.gz";
}
core.info(`Downloading uv from "${downloadUrl}" ...`);
const downloadPath = await tc.downloadTool(
downloadUrl,
undefined,
githubToken,
);
let uvExecutablePath: string;
let uvDir: string;
if (platform === "pc-windows-msvc") {
uvDir = await tc.extractZip(downloadPath);
// On windows extracting the zip does not create an intermediate directory
uvExecutablePath = path.join(uvDir, "uv.exe");
} else {
const extractedDir = await tc.extractTar(downloadPath);
uvDir = path.join(extractedDir, artifact);
uvExecutablePath = path.join(uvDir, "uv");
}
const version = await getVersion(uvExecutablePath);
await validateChecksum(checkSum, downloadPath, arch, platform, version);
return { cachedToolDir: uvDir, version };
}
async function getVersion(uvExecutablePath: string): Promise<string> {
// Parse the output of `uv --version` to get the version
// The output looks like
// uv 0.3.1 (be17d132a 2024-08-21)
const options: exec.ExecOptions = {
silent: !core.isDebug(),
};
const execArgs = ["--version"];
let output = "";
options.listeners = {
stdout: (data: Buffer) => {
output += data.toString();
},
};
await exec.exec(uvExecutablePath, execArgs, options);
const parts = output.split(" ");
return parts[1];
}

View File

@@ -1,9 +1,8 @@
import * as core from "@actions/core"; import * as core from "@actions/core";
import * as tc from "@actions/tool-cache"; import * as tc from "@actions/tool-cache";
import * as path from "node:path"; import * as path from "path";
import { promises as fs } from "node:fs";
import { OWNER, REPO, TOOL_CACHE_NAME } from "../utils/constants"; import { OWNER, REPO, TOOL_CACHE_NAME } from "../utils/constants";
import type { Architecture, Platform } from "../utils/platforms"; import { Architecture, Platform } from "../utils/platforms";
import { validateChecksum } from "./checksum/checksum"; import { validateChecksum } from "./checksum/checksum";
import * as github from "@actions/github"; import * as github from "@actions/github";
@@ -31,11 +30,12 @@ export async function downloadVersion(
): Promise<{ version: string; cachedToolDir: string }> { ): Promise<{ version: string; cachedToolDir: string }> {
const resolvedVersion = await resolveVersion(version, githubToken); const resolvedVersion = await resolveVersion(version, githubToken);
const artifact = `uv-${arch}-${platform}`; const artifact = `uv-${arch}-${platform}`;
let extension = ".tar.gz"; let downloadUrl = `https://github.com/${OWNER}/${REPO}/releases/download/${resolvedVersion}/${artifact}`;
if (platform === "pc-windows-msvc") { if (platform === "pc-windows-msvc") {
extension = ".zip"; downloadUrl += ".zip";
} else {
downloadUrl += ".tar.gz";
} }
const downloadUrl = `https://github.com/${OWNER}/${REPO}/releases/download/${resolvedVersion}/${artifact}${extension}`;
core.info(`Downloading uv from "${downloadUrl}" ...`); core.info(`Downloading uv from "${downloadUrl}" ...`);
const downloadPath = await tc.downloadTool( const downloadPath = await tc.downloadTool(
@@ -53,9 +53,7 @@ export async function downloadVersion(
let uvDir: string; let uvDir: string;
if (platform === "pc-windows-msvc") { if (platform === "pc-windows-msvc") {
const fullPathWithExtension = `${downloadPath}${extension}`; uvDir = await tc.extractZip(downloadPath);
await fs.copyFile(downloadPath, fullPathWithExtension);
uvDir = await tc.extractZip(fullPathWithExtension);
// On windows extracting the zip does not create an intermediate directory // On windows extracting the zip does not create an intermediate directory
} else { } else {
const extractedDir = await tc.extractTar(downloadPath); const extractedDir = await tc.extractTar(downloadPath);
@@ -70,14 +68,10 @@ export async function downloadVersion(
return { version: resolvedVersion, cachedToolDir }; return { version: resolvedVersion, cachedToolDir };
} }
export async function resolveVersion( async function resolveVersion(
versionInput: string, version: string,
githubToken: string, githubToken: string,
): Promise<string> { ): Promise<string> {
const version =
versionInput === "latest"
? await getLatestVersion(githubToken)
: versionInput;
if (tc.isExplicitVersion(version)) { if (tc.isExplicitVersion(version)) {
core.debug(`Version ${version} is an explicit version.`); core.debug(`Version ${version} is an explicit version.`);
return version; return version;
@@ -99,17 +93,3 @@ async function getAvailableVersions(githubToken: string): Promise<string[]> {
}); });
return response.map((release) => release.tag_name); return response.map((release) => release.tag_name);
} }
async function getLatestVersion(githubToken: string) {
const octokit = github.getOctokit(githubToken);
const { data: latestRelease } = await octokit.rest.repos.getLatestRelease({
owner: OWNER,
repo: REPO,
});
if (!latestRelease) {
throw new Error("Could not determine latest release.");
}
return latestRelease.tag_name;
}

View File

@@ -1,48 +0,0 @@
import * as crypto from "node:crypto";
import * as core from "@actions/core";
import * as fs from "node:fs";
import * as stream from "node:stream";
import * as util from "node:util";
import { create } from "@actions/glob";
/**
* Hashes files matching the given glob pattern.
*
* Copied from https://github.com/actions/toolkit/blob/20ed2908f19538e9dfb66d8083f1171c0a50a87c/packages/glob/src/internal-hash-files.ts#L9-L49
* But supports hashing files outside the GITHUB_WORKSPACE.
* @param pattern The glob pattern to match files.
* @param verbose Whether to log the files being hashed.
*/
export async function hashFiles(
pattern: string,
verbose = false,
): Promise<string> {
const globber = await create(pattern);
let hasMatch = false;
const writeDelegate = verbose ? core.info : core.debug;
const result = crypto.createHash("sha256");
let count = 0;
for await (const file of globber.globGenerator()) {
writeDelegate(file);
if (fs.statSync(file).isDirectory()) {
writeDelegate(`Skip directory '${file}'.`);
continue;
}
const hash = crypto.createHash("sha256");
const pipeline = util.promisify(stream.pipeline);
await pipeline(fs.createReadStream(file), hash);
result.write(hash.digest());
count++;
if (!hasMatch) {
hasMatch = true;
}
}
result.end();
if (hasMatch) {
writeDelegate(`Found ${count} files to hash.`);
return result.digest("hex");
}
writeDelegate("No matches found for glob");
return "";
}

View File

@@ -1,33 +1,22 @@
import * as cache from "@actions/cache"; 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 * as fs from "node:fs";
import { import {
STATE_CACHE_MATCHED_KEY, STATE_CACHE_MATCHED_KEY,
STATE_CACHE_KEY, STATE_CACHE_KEY,
} from "./cache/restore-cache"; } from "./cache/restore-cache";
import { import { cacheLocalPath, enableCache } from "./utils/inputs";
cacheLocalPath,
enableCache,
ignoreNothingToCache,
pruneCache as shouldPruneCache,
} from "./utils/inputs";
export async function run(): Promise<void> { export async function run(): Promise<void> {
try { try {
if (enableCache) { if (enableCache) {
await saveCache(); await saveCache();
// node will stay alive if any promises are not resolved,
// which is a possibility if HTTP requests are dangling
// due to retries or timeouts. We know that if we got here
// that all promises that we care about have successfully
// resolved, so simply exit with success.
process.exit(0);
} }
} catch (error) { } catch (error) {
const err = error as Error; const err = error as Error;
core.setFailed(err.message); core.setFailed(err.message);
} }
process.exit(0);
} }
async function saveCache(): Promise<void> { async function saveCache(): Promise<void> {
@@ -37,38 +26,17 @@ async function saveCache(): Promise<void> {
if (!cacheKey) { if (!cacheKey) {
core.warning("Error retrieving cache key from state."); core.warning("Error retrieving cache key from state.");
return; return;
} } else if (matchedKey === cacheKey) {
if (matchedKey === cacheKey) {
core.info(`Cache hit occurred on key ${cacheKey}, not saving cache.`); core.info(`Cache hit occurred on key ${cacheKey}, not saving cache.`);
return; return;
} }
if (shouldPruneCache) {
await pruneCache(); await pruneCache();
}
core.info(`Saving cache path: ${cacheLocalPath}`); core.info(`Saving cache path: ${cacheLocalPath}`);
if (!fs.existsSync(cacheLocalPath) && !ignoreNothingToCache) {
throw new Error(
`Cache path ${cacheLocalPath} does not exist on disk. This likely indicates that there are no dependencies to cache. Consider disabling the cache input if it is not needed.`,
);
}
try {
await cache.saveCache([cacheLocalPath], cacheKey); await cache.saveCache([cacheLocalPath], cacheKey);
core.info(`cache saved with the key: ${cacheKey}`); core.info(`cache saved with the key: ${cacheKey}`);
} catch (e) {
if (
e instanceof Error &&
e.message ===
"Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved."
) {
core.info(
"No cacheable paths were found. Ignoring because ignore-nothing-to-save is enabled.",
);
} else {
throw e;
}
}
} }
async function pruneCache(): Promise<void> { async function pruneCache(): Promise<void> {

View File

@@ -1,26 +1,24 @@
import * as core from "@actions/core"; import * as core from "@actions/core";
import * as path from "node:path"; import * as path from "path";
import { import {
downloadVersion, downloadVersion,
tryGetFromToolCache, tryGetFromToolCache,
resolveVersion,
} from "./download/download-version"; } from "./download/download-version";
import { restoreCache } from "./cache/restore-cache"; import { restoreCache } from "./cache/restore-cache";
import { downloadLatest } from "./download/download-latest";
import { import {
type Architecture, Architecture,
getArch, getArch,
getPlatform, getPlatform,
type Platform, Platform,
} from "./utils/platforms"; } from "./utils/platforms";
import { import {
cacheLocalPath, cacheLocalPath,
checkSum, checkSum,
enableCache, enableCache,
githubToken, githubToken,
pythonVersion,
toolBinDir, toolBinDir,
toolDir,
version, version,
} from "./utils/inputs"; } from "./utils/inputs";
@@ -45,14 +43,12 @@ async function run(): Promise<void> {
addUvToPath(setupResult.uvDir); addUvToPath(setupResult.uvDir);
addToolBinToPath(); addToolBinToPath();
setToolDir();
setupPython();
addMatchers();
setCacheDir(cacheLocalPath);
core.setOutput("uv-version", setupResult.version); core.setOutput("uv-version", setupResult.version);
core.info(`Successfully installed uv version ${setupResult.version}`); core.info(`Successfully installed uv version ${setupResult.version}`);
addMatchers();
setCacheDir(cacheLocalPath);
if (enableCache) { if (enableCache) {
await restoreCache(setupResult.version); await restoreCache(setupResult.version);
} }
@@ -69,28 +65,38 @@ async function setupUv(
checkSum: string | undefined, checkSum: string | undefined,
githubToken: string, githubToken: string,
): Promise<{ uvDir: string; version: string }> { ): Promise<{ uvDir: string; version: string }> {
const resolvedVersion = await resolveVersion(versionInput, githubToken); let installedPath: string | undefined;
const toolCacheResult = tryGetFromToolCache(arch, resolvedVersion); let cachedToolDir: string;
if (toolCacheResult.installedPath) { let version: string;
core.info(`Found uv in tool-cache for ${toolCacheResult.version}`); if (versionInput === "latest") {
return { const latestResult = await downloadLatest(
uvDir: toolCacheResult.installedPath,
version: toolCacheResult.version,
};
}
const downloadVersionResult = await downloadVersion(
platform, platform,
arch, arch,
resolvedVersion,
checkSum, checkSum,
githubToken, githubToken,
); );
version = latestResult.version;
cachedToolDir = latestResult.cachedToolDir;
} else {
const toolCacheResult = tryGetFromToolCache(arch, versionInput);
version = toolCacheResult.version;
installedPath = toolCacheResult.installedPath;
if (installedPath) {
core.info(`Found uv in tool-cache for ${versionInput}`);
return { uvDir: installedPath, version };
}
const versionResult = await downloadVersion(
platform,
arch,
versionInput,
checkSum,
githubToken,
);
cachedToolDir = versionResult.cachedToolDir;
version = versionResult.version;
}
return { return { uvDir: cachedToolDir, version };
uvDir: downloadVersionResult.cachedToolDir,
version: downloadVersionResult.version,
};
} }
function addUvToPath(cachedPath: string): void { function addUvToPath(cachedPath: string): void {
@@ -104,31 +110,6 @@ function addToolBinToPath(): void {
core.info(`Set UV_TOOL_BIN_DIR to ${toolBinDir}`); core.info(`Set UV_TOOL_BIN_DIR to ${toolBinDir}`);
core.addPath(toolBinDir); core.addPath(toolBinDir);
core.info(`Added ${toolBinDir} to the path`); core.info(`Added ${toolBinDir} to the path`);
} else {
if (process.env.XDG_BIN_HOME !== undefined) {
core.addPath(process.env.XDG_BIN_HOME);
core.info(`Added ${process.env.XDG_BIN_HOME} to the path`);
} else if (process.env.XDG_DATA_HOME !== undefined) {
core.addPath(`${process.env.XDG_DATA_HOME}/../bin`);
core.info(`Added ${process.env.XDG_DATA_HOME}/../bin to the path`);
} else {
core.addPath(`${process.env.HOME}/.local/bin`);
core.info(`Added ${process.env.HOME}/.local/bin to the path`);
}
}
}
function setToolDir(): void {
if (toolDir !== undefined) {
core.exportVariable("UV_TOOL_DIR", toolDir);
core.info(`Set UV_TOOL_DIR to ${toolDir}`);
}
}
function setupPython(): void {
if (pythonVersion !== "") {
core.exportVariable("UV_PYTHON", pythonVersion);
core.info(`Set UV_PYTHON to ${pythonVersion}`);
} }
} }

View File

@@ -1,48 +1,22 @@
import * as core from "@actions/core"; import * as core from "@actions/core";
import path from "node:path"; import path from "path";
export const version = core.getInput("version"); export const version = core.getInput("version");
export const pythonVersion = core.getInput("python-version");
export const checkSum = core.getInput("checksum"); export const checkSum = core.getInput("checksum");
export const enableCache = core.getInput("enable-cache") === "true"; export const enableCache = core.getInput("enable-cache") === "true";
export const cacheSuffix = core.getInput("cache-suffix") || ""; export const cacheSuffix = core.getInput("cache-suffix") || "";
export const cacheLocalPath = getCacheLocalPath(); export const cacheLocalPath = getCacheLocalPath();
export const cacheDependencyGlob = core.getInput("cache-dependency-glob"); export const cacheDependencyGlob = core.getInput("cache-dependency-glob");
export const pruneCache = core.getInput("prune-cache") === "true";
export const ignoreNothingToCache =
core.getInput("ignore-nothing-to-cache") === "true";
export const toolBinDir = getToolBinDir(); export const toolBinDir = getToolBinDir();
export const toolDir = getToolDir();
export const githubToken = core.getInput("github-token"); export const githubToken = core.getInput("github-token");
function getToolBinDir(): string | undefined { function getToolBinDir(): string | undefined {
const toolBinDirInput = core.getInput("tool-bin-dir"); const toolBinDirInput = core.getInput("tool-bin-dir");
if (toolBinDirInput !== "") { if (toolBinDirInput !== "") {
return expandTilde(toolBinDirInput); return toolBinDirInput;
} }
if (process.platform === "win32") { if (process.platform === "win32") {
if (process.env.RUNNER_TEMP !== undefined) { return "D:\\a\\_temp\\uv-tool-bin-dir";
return `${process.env.RUNNER_TEMP}${path.sep}uv-tool-bin-dir`;
}
throw Error(
"Could not determine UV_TOOL_BIN_DIR. Please make sure RUNNER_TEMP is set or provide the tool-bin-dir input",
);
}
return undefined;
}
function getToolDir(): string | undefined {
const toolDirInput = core.getInput("tool-dir");
if (toolDirInput !== "") {
return expandTilde(toolDirInput);
}
if (process.platform === "win32") {
if (process.env.RUNNER_TEMP !== undefined) {
return `${process.env.RUNNER_TEMP}${path.sep}uv-tool-dir`;
}
throw Error(
"Could not determine UV_TOOL_DIR. Please make sure RUNNER_TEMP is set or provide the tool-dir input",
);
} }
return undefined; return undefined;
} }
@@ -50,19 +24,13 @@ function getToolDir(): string | undefined {
function getCacheLocalPath(): string { function getCacheLocalPath(): string {
const cacheLocalPathInput = core.getInput("cache-local-path"); const cacheLocalPathInput = core.getInput("cache-local-path");
if (cacheLocalPathInput !== "") { if (cacheLocalPathInput !== "") {
return expandTilde(cacheLocalPathInput); return cacheLocalPathInput;
} }
if (process.env.RUNNER_TEMP !== undefined) { if (process.env.RUNNER_TEMP !== undefined) {
return `${process.env.RUNNER_TEMP}${path.sep}setup-uv-cache`; return `${process.env.RUNNER_TEMP}${path.sep}setup-uv-cache`;
} }
throw Error( if (process.platform === "win32") {
"Could not determine UV_CACHE_DIR. Please make sure RUNNER_TEMP is set or provide the cache-local-path input", return "D:\\a\\_temp\\setup-uv-cache";
);
}
function expandTilde(input: string): string {
if (input.startsWith("~")) {
return `${process.env.HOME}${input.substring(1)}`;
} }
return input; return "/tmp/setup-uv-cache";
} }