Compare commits

..
Author SHA1 Message Date
eifinger-botandKevin Stillhammer edc4037b1b fix: add timeout to fetch to prevent silent hangs
Add AbortSignal.timeout(30s) to fetch requests to ensure they fail
fast instead of hanging indefinitely when network issues occur.
This fixes issues where the action would hang and eventually get
killed by GitHub Actions without a clear error message.
2026-05-31 09:25:28 +02:00
64 changed files with 19714 additions and 25753 deletions
+4 -7
View File
@@ -1,6 +1,6 @@
--- ---
name: dependabot-pr-rollup name: dependabot-pr-rollup
description: Find open Dependabot PRs for the current GitHub repo, compare each PR head to its base branch, replay only the net dependency changes in a fresh worktree and branch, run npm validation, then commit, push, and open a pull request labeled dependencies. Use when you want to batch or manually replicate active Dependabot updates. description: Find open Dependabot PRs for the current GitHub repo, compare each PR head to its base branch, replay only the net dependency changes in a fresh worktree and branch, run npm validation, and optionally commit, push, and open a PR. Use when you want to batch or manually replicate active Dependabot updates.
license: MIT license: MIT
compatibility: Requires git, git worktree, gh CLI auth, npm, and a GitHub repo with an origin remote. compatibility: Requires git, git worktree, gh CLI auth, npm, and a GitHub repo with an origin remote.
--- ---
@@ -13,7 +13,7 @@ Use this skill when the user wants to:
- find all open Dependabot PRs in the current repo - find all open Dependabot PRs in the current repo
- reproduce their net effect in one local branch - reproduce their net effect in one local branch
- validate the result with the repo's standard npm checks - validate the result with the repo's standard npm checks
- commit and push the validated changes, then open a PR labeled `dependencies` - optionally commit, push, and open a PR
## Workflow ## Workflow
@@ -26,10 +26,8 @@ Use this skill when the user wants to:
- Inspect `package.json` before editing. - Inspect `package.json` before editing.
- Run `npm ci --ignore-scripts` before applying updates. - Run `npm ci --ignore-scripts` before applying updates.
- Use `npm install ... --ignore-scripts` for direct dependency changes so `package-lock.json` stays in sync. - Use `npm install ... --ignore-scripts` for direct dependency changes so `package-lock.json` stays in sync.
- When updating `@biomejs/biome`, also update the Biome schema URL version in `biome.json` to match the installed Biome version.
7. Run `npm run all`. 7. Run `npm run all`.
8. Commit the changed source, lockfile, and generated artifacts, then push the branch. 8. If requested, commit the changed source, lockfile, and generated artifacts, then push and open a PR.
9. Always open a pull request for the rollup and add the `dependencies` label to it. Pass `--label dependencies` to `gh pr create`, or add the label immediately afterward with `gh pr edit --add-label dependencies`.
## Repo-specific notes ## Repo-specific notes
@@ -47,5 +45,4 @@ Always report:
- new worktree path - new worktree path
- files changed - files changed
- `npm run all` result - `npm run all` result
- commit SHA and PR URL - if applicable, commit SHA and PR URL
- confirmation that the PR has the `dependencies` label
-1
View File
@@ -1,3 +1,2 @@
* text=auto eol=lf * text=auto eol=lf
dist/** -diff linguist-generated=true dist/** -diff linguist-generated=true
src/download/checksum/known-checksums.json linguist-generated=true
-4
View File
@@ -8,10 +8,6 @@ self-hosted-runner:
# Empty array means no configuration variable is allowed. # Empty array means no configuration variable is allowed.
config-variables: null config-variables: null
paths: paths:
.github/workflows/**/*.{yml,yaml}:
ignore:
- 'specifying action "\$/" in invalid format because ref is missing'
- 'reusable workflow call "\$/.+" at "uses" is not following the format'
.github/workflows/test.yml: .github/workflows/test.yml:
ignore: ignore:
- 'invalid runner name.+' - 'invalid runner name.+'
+2 -2
View File
@@ -5,11 +5,11 @@ updates:
schedule: schedule:
interval: daily interval: daily
cooldown: cooldown:
default-days: 30 default-days: 7
- package-ecosystem: npm - package-ecosystem: npm
directory: / directory: /
schedule: schedule:
interval: daily interval: daily
cooldown: cooldown:
default-days: 30 default-days: 7
+4 -4
View File
@@ -41,13 +41,13 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 uses: github/codeql-action/init@68bde559dea0fdcac2102bfdf6230c5f70eb485e # v4.35.4
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
source-root: src source-root: src
@@ -59,7 +59,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below) # If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild - name: Autobuild
uses: github/codeql-action/autobuild@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 uses: github/codeql-action/autobuild@68bde559dea0fdcac2102bfdf6230c5f70eb485e # v4.35.4
# ️ Command-line programs to run using the OS shell. # ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl # 📚 https://git.io/JvXDl
@@ -73,4 +73,4 @@ jobs:
# make release # make release
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 uses: github/codeql-action/analyze@68bde559dea0fdcac2102bfdf6230c5f70eb485e # v4.35.4
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
pull-requests: read pull-requests: read
steps: steps:
- name: 🚀 Run Release Drafter - name: 🚀 Run Release Drafter
uses: release-drafter/release-drafter@34d80673e067bdc0c24568d3af899c216adcfaa9 # v7.7.0 uses: release-drafter/release-drafter@5de93583980a40bd78603b6dfdcda5b4df377b32 # v7.2.0
with: with:
commitish: ${{ github.sha }} commitish: ${{ github.sha }}
env: env:
-11
View File
@@ -111,14 +111,3 @@ jobs:
echo "Publishing draft release $TAG" echo "Publishing draft release $TAG"
gh release edit "$TAG" --draft=false gh release edit "$TAG" --draft=false
update-docs:
name: Update docs
needs:
- release
uses: $/.github/workflows/update-docs.yml
permissions:
contents: write
pull-requests: write
with:
tag: v${{ inputs.version }}
+121 -124
View File
@@ -21,14 +21,14 @@ jobs:
permissions: permissions:
security-events: write # for zizmor security-events: write # for zizmor
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Actionlint - name: Actionlint
uses: eifinger/actionlint-action@1fc89649be682d16ec5cf65ea16e269eb88d3982 # v1.10.2 uses: eifinger/actionlint-action@7802e0cc3ab3f81cbffb36fb0bf1a3621d994b89 # v1.10.1
- name: Run zizmor - name: Run zizmor
uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2 uses: zizmorcore/zizmor-action@a16621b09c6db4281f81a93cb393b05dcd7b7165 # v0.5.5
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with: with:
node-version-file: .nvmrc node-version-file: .nvmrc
cache: npm cache: npm
@@ -51,12 +51,12 @@ jobs:
matrix: matrix:
os: [ubuntu-latest, macos-latest, macos-14, windows-latest] os: [ubuntu-latest, macos-latest, macos-14, windows-latest]
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install latest version - name: Install latest version
id: setup-uv id: setup-uv
uses: $/ uses: ./
- run: uv sync - run: uv sync
working-directory: __tests__/fixtures/uv-project working-directory: __tests__/fixtures/uv-project
shell: bash shell: bash
@@ -76,12 +76,12 @@ jobs:
test-uv-no-modify-path: test-uv-no-modify-path:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install with UV_NO_MODIFY_PATH set - name: Install with UV_NO_MODIFY_PATH set
id: setup-uv id: setup-uv
uses: $/ uses: ./
env: env:
UV_NO_MODIFY_PATH: 1 UV_NO_MODIFY_PATH: 1
- run: | - run: |
@@ -125,12 +125,12 @@ jobs:
expected-version: "0.1.0" expected-version: "0.1.0"
resolution-strategy: "lowest" resolution-strategy: "lowest"
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install version ${{ matrix.input.version-input }} with strategy ${{ matrix.input.resolution-strategy || 'highest' }} - name: Install version ${{ matrix.input.version-input }} with strategy ${{ matrix.input.resolution-strategy || 'highest' }}
id: setup-uv id: setup-uv
uses: $/ uses: ./
with: with:
version: ${{ matrix.input.version-input }} version: ${{ matrix.input.version-input }}
resolution-strategy: ${{ matrix.input.resolution-strategy || 'highest' }} resolution-strategy: ${{ matrix.input.resolution-strategy || 'highest' }}
@@ -154,8 +154,11 @@ jobs:
matrix: matrix:
version-input: ["latest", ">=0.8"] version-input: ["latest", ">=0.8"]
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Install version ${{ matrix.version-input }} - name: Install version ${{ matrix.version-input }}
uses: $/ uses: ./
with: with:
version: ${{ matrix.version-input }} version: ${{ matrix.version-input }}
- name: Latest version gets installed - name: Latest version gets installed
@@ -191,11 +194,11 @@ jobs:
- working-directory: "__tests__/fixtures/uv-toml-project" - working-directory: "__tests__/fixtures/uv-toml-project"
expected-version: "0.5.15" expected-version: "0.5.15"
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install version from ${{ matrix.input.working-directory }} - name: Install version from ${{ matrix.input.working-directory }}
uses: $/ uses: ./
with: with:
working-directory: ${{ matrix.input.working-directory }} working-directory: ${{ matrix.input.working-directory }}
- name: Correct version gets installed - name: Correct version gets installed
@@ -217,11 +220,11 @@ jobs:
- version-file: "__tests__/fixtures/.tool-versions" - version-file: "__tests__/fixtures/.tool-versions"
expected-version: "0.5.15" expected-version: "0.5.15"
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install version from ${{ matrix.input.version-file }} - name: Install version from ${{ matrix.input.version-file }}
uses: $/ uses: ./
with: with:
version-file: ${{ matrix.input.version-file }} version-file: ${{ matrix.input.version-file }}
- name: Correct version gets installed - name: Correct version gets installed
@@ -231,40 +234,15 @@ jobs:
exit 1 exit 1
fi fi
test-tool-versions-python-version:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install versions from .tool-versions
id: setup-uv
uses: $/
with:
version-file: "__tests__/fixtures/.tool-versions"
- name: Verify Python version from .tool-versions
run: |
if [ "$UV_PYTHON" != "3.13.1t" ]; then
echo "Wrong UV_PYTHON: $UV_PYTHON"
exit 1
fi
if [ "$PYTHON_VERSION" != "3.13.1t" ]; then
echo "Wrong python-version output: $PYTHON_VERSION"
exit 1
fi
shell: bash
env:
PYTHON_VERSION: ${{ steps.setup-uv.outputs.python-version }}
test-malformed-pyproject-file-fallback: test-malformed-pyproject-file-fallback:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install using malformed pyproject.toml - name: Install using malformed pyproject.toml
id: setup-uv id: setup-uv
uses: $/ uses: ./
with: with:
working-directory: "__tests__/fixtures/malformed-pyproject-toml-project" working-directory: "__tests__/fixtures/malformed-pyproject-toml-project"
- run: uv --help - run: uv --help
@@ -279,11 +257,11 @@ jobs:
- os: macos-latest - os: macos-latest
checksum: "a70cbfbf3bb5c08b2f84963b4f12c94e08fbb2468ba418a3bfe1066fbe9e7218" checksum: "a70cbfbf3bb5c08b2f84963b4f12c94e08fbb2468ba418a3bfe1066fbe9e7218"
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Checksum matches expected - name: Checksum matches expected
uses: $/ uses: ./
with: with:
version: "0.3.2" version: "0.3.2"
checksum: ${{ matrix.inputs.checksum }} checksum: ${{ matrix.inputs.checksum }}
@@ -293,11 +271,11 @@ jobs:
test-with-explicit-token: test-with-explicit-token:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install default version - name: Install default version
uses: $/ uses: ./
with: with:
github-token: ${{ secrets.GITHUB_TOKEN }} github-token: ${{ secrets.GITHUB_TOKEN }}
- run: uv sync - run: uv sync
@@ -306,9 +284,12 @@ jobs:
test-uvx: test-uvx:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Install default version - name: Install default version
uses: $/ uses: ./
- run: uvx ruff@0.14.10 --version - run: uvx ruff --version
test-tool-install: test-tool-install:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
@@ -316,9 +297,12 @@ jobs:
matrix: matrix:
os: [ubuntu-latest, macos-latest, macos-14, windows-latest] os: [ubuntu-latest, macos-latest, macos-14, windows-latest]
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Install default version - name: Install default version
uses: $/ uses: ./
- run: uv tool install ruff==0.14.10 - run: uv tool install ruff
- run: ruff --version - run: ruff --version
test-python-version: test-python-version:
@@ -327,12 +311,12 @@ jobs:
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] os: [ubuntu-latest, macos-latest, windows-latest]
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install latest version - name: Install latest version
id: setup-uv id: setup-uv
uses: $/ uses: ./
with: with:
python-version: 3.13.1t python-version: 3.13.1t
- name: Verify UV_PYTHON is set to correct version - name: Verify UV_PYTHON is set to correct version
@@ -359,9 +343,12 @@ jobs:
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] os: [ubuntu-latest, macos-latest, windows-latest]
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Install latest version - name: Install latest version
id: setup-uv id: setup-uv
uses: $/ uses: ./
with: with:
python-version: 3.13.1t python-version: 3.13.1t
activate-environment: true activate-environment: true
@@ -395,9 +382,12 @@ jobs:
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] os: [ubuntu-latest, macos-latest, windows-latest]
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Install latest version - name: Install latest version
id: setup-uv id: setup-uv
uses: $/ uses: ./
with: with:
python-version: 3.13.1t python-version: 3.13.1t
activate-environment: true activate-environment: true
@@ -443,6 +433,9 @@ jobs:
test-activate-environment-no-project: test-activate-environment-no-project:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Create incompatible pyproject.toml - name: Create incompatible pyproject.toml
run: | run: |
cat > pyproject.toml <<'EOF' cat > pyproject.toml <<'EOF'
@@ -458,7 +451,7 @@ jobs:
shell: bash shell: bash
- name: Install latest version with no-project - name: Install latest version with no-project
id: setup-uv id: setup-uv
uses: $/ uses: ./
with: with:
python-version: 3.13.1t python-version: 3.13.1t
activate-environment: true activate-environment: true
@@ -484,11 +477,11 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: debian:unstable container: debian:unstable
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install latest version - name: Install latest version
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
- run: uv sync - run: uv sync
@@ -496,14 +489,14 @@ jobs:
test-musl: test-musl:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: alpine@sha256:28bd5fe8b56d1bd048e5babf5b10710ebe0bae67db86916198a6eec434943f8b # 3.24.1 container: alpine
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install latest version - name: Install latest version
id: setup-uv id: setup-uv
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
- name: Verify cache key contains alpine - name: Verify cache key contains alpine
@@ -537,9 +530,12 @@ jobs:
- os: windows-2025 - os: windows-2025
expected-os: "windows-2025" expected-os: "windows-2025"
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup uv - name: Setup uv
id: setup-uv id: setup-uv
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
- name: Verify cache key contains OS version - name: Verify cache key contains OS version
@@ -560,11 +556,11 @@ jobs:
enable-cache: ["true", "false", "auto"] enable-cache: ["true", "false", "auto"]
os: ["ubuntu-latest", "windows-latest"] os: ["ubuntu-latest", "windows-latest"]
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Setup with cache - name: Setup with cache
uses: $/ uses: ./
with: with:
enable-cache: ${{ matrix.enable-cache }} enable-cache: ${{ matrix.enable-cache }}
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-${{ matrix.os }}-${{ matrix.enable-cache }} cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-${{ matrix.os }}-${{ matrix.enable-cache }}
@@ -579,12 +575,12 @@ jobs:
os: ["ubuntu-latest", "windows-latest"] os: ["ubuntu-latest", "windows-latest"]
needs: test-setup-cache needs: test-setup-cache
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Restore with cache - name: Restore with cache
id: restore id: restore
uses: $/ uses: ./
with: with:
enable-cache: ${{ matrix.enable-cache }} enable-cache: ${{ matrix.enable-cache }}
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-${{ matrix.os }}-${{ matrix.enable-cache }} cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-${{ matrix.os }}-${{ matrix.enable-cache }}
@@ -613,11 +609,11 @@ jobs:
test-setup-cache-requirements-txt: test-setup-cache-requirements-txt:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- 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-requirements-txt cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-requirements-txt
@@ -629,12 +625,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: test-setup-cache-requirements-txt needs: test-setup-cache-requirements-txt
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Restore with cache - name: Restore with cache
id: restore id: restore
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-requirements-txt cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-requirements-txt
@@ -653,11 +649,11 @@ jobs:
test-setup-cache-dependency-glob: test-setup-cache-dependency-glob:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Setup with cache - name: Setup with cache
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-dependency-glob: | cache-dependency-glob: |
@@ -670,7 +666,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: test-setup-cache-dependency-glob needs: test-setup-cache-dependency-glob
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Change pyproject.toml - name: Change pyproject.toml
@@ -679,7 +675,7 @@ jobs:
echo 'dev-dependencies = []' >> __tests__/fixtures/uv-project/pyproject.toml echo 'dev-dependencies = []' >> __tests__/fixtures/uv-project/pyproject.toml
- name: Restore with cache - name: Restore with cache
id: restore id: restore
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-dependency-glob: | cache-dependency-glob: |
@@ -698,11 +694,11 @@ jobs:
test-setup-cache-save-cache-false: test-setup-cache-save-cache-false:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Setup with cache - name: Setup with cache
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
save-cache: false save-cache: false
@@ -714,12 +710,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: test-setup-cache-save-cache-false needs: test-setup-cache-save-cache-false
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Restore with cache - name: Restore with cache
id: restore id: restore
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-save-cache-false cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-save-cache-false
@@ -734,11 +730,11 @@ jobs:
test-setup-cache-restore-cache-false: test-setup-cache-restore-cache-false:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- 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-restore-cache-false cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-restore-cache-false
@@ -749,12 +745,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: test-setup-cache-restore-cache-false needs: test-setup-cache-restore-cache-false
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Restore with cache - name: Restore with cache
id: restore id: restore
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
restore-cache: false restore-cache: false
@@ -777,8 +773,11 @@ jobs:
expected-cache-dir: "D:\\a\\_temp\\setup-uv-cache" expected-cache-dir: "D:\\a\\_temp\\setup-uv-cache"
runs-on: ${{ matrix.inputs.os }} runs-on: ${{ matrix.inputs.os }}
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- 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-cache-local cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-cache-local
@@ -792,8 +791,11 @@ jobs:
test-cache-local-cache-disabled: test-cache-local-cache-disabled:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup without cache - name: Setup without cache
uses: $/ uses: ./
with: with:
enable-cache: false enable-cache: false
@@ -808,8 +810,11 @@ jobs:
test-cache-local-cache-disabled-but-explicit-path: test-cache-local-cache-disabled-but-explicit-path:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup without cache - name: Setup without cache
uses: $/ uses: ./
with: with:
enable-cache: false enable-cache: false
cache-local-path: /tmp/uv-cache-disabled cache-local-path: /tmp/uv-cache-disabled
@@ -825,13 +830,13 @@ jobs:
test-no-python-version: test-no-python-version:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Fake pyproject.toml at root - name: Fake pyproject.toml at root
run: cp __tests__/fixtures/old-python-constraint-project/pyproject.toml pyproject.toml run: cp __tests__/fixtures/old-python-constraint-project/pyproject.toml pyproject.toml
- name: Setup with cache - name: Setup with cache
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
- run: uv sync - run: uv sync
@@ -840,11 +845,11 @@ jobs:
test-custom-manifest-file: test-custom-manifest-file:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install from custom manifest file - name: Install from custom manifest file
uses: $/ uses: ./
with: with:
manifest-file: "https://raw.githubusercontent.com/astral-sh/setup-uv/${{ github.ref }}/__tests__/download/custom-manifest.ndjson" manifest-file: "https://raw.githubusercontent.com/astral-sh/setup-uv/${{ github.ref }}/__tests__/download/custom-manifest.ndjson"
- run: uv sync - run: uv sync
@@ -856,25 +861,17 @@ jobs:
exit 1 exit 1
fi fi
test-download-from-astral-mirror-false:
runs-on: ubuntu-latest
steps:
- name: Install with download-from-astral-mirror disabled
id: setup-uv
uses: $/
with:
download-from-astral-mirror: false
- name: Verify uv is installed
run: uv --version
test-absolute-path: test-absolute-path:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Create requirements.txt - name: Create requirements.txt
run: echo "uv==0.6.17" > /tmp/setup-uv-requirements.txt run: echo "uv==0.6.17" > /tmp/setup-uv-requirements.txt
- name: Install from requirements file - name: Install from requirements file
id: setup-uv id: setup-uv
uses: $/ uses: ./
with: with:
version-file: "/tmp/setup-uv-requirements.txt" version-file: "/tmp/setup-uv-requirements.txt"
- name: Correct version gets installed - name: Correct version gets installed
@@ -887,13 +884,16 @@ jobs:
test-relative-path: test-relative-path:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: mkdir - name: mkdir
run: mkdir -p /tmp/setup-uv-test-relative-path run: mkdir -p /tmp/setup-uv-test-relative-path
- name: Create requirements.txt - name: Create requirements.txt
run: echo "uv==0.6.17" > /tmp/setup-uv-test-relative-path/setup-uv-requirements.txt run: echo "uv==0.6.17" > /tmp/setup-uv-test-relative-path/setup-uv-requirements.txt
- name: Install from requirements file - name: Install from requirements file
id: setup-uv id: setup-uv
uses: $/ uses: ./
with: with:
version-file: "./setup-uv-requirements.txt" version-file: "./setup-uv-requirements.txt"
working-directory: "/tmp/setup-uv-test-relative-path" working-directory: "/tmp/setup-uv-test-relative-path"
@@ -908,11 +908,11 @@ jobs:
test-cache-prune-force: test-cache-prune-force:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Setup uv - name: Setup uv
uses: $/ uses: ./
with: with:
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-cache-prune-force cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-cache-prune-force
- name: Create long running python script - name: Create long running python script
@@ -925,7 +925,7 @@ jobs:
test-cache-dir-from-file: test-cache-dir-from-file:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Verify uv cache dir is not populated - name: Verify uv cache dir is not populated
@@ -935,7 +935,7 @@ jobs:
exit 1 exit 1
fi fi
- name: Setup uv - name: Setup uv
uses: $/ uses: ./
with: with:
working-directory: __tests__/fixtures/cache-dir-defined-project working-directory: __tests__/fixtures/cache-dir-defined-project
- run: uv sync - run: uv sync
@@ -952,11 +952,11 @@ jobs:
env: env:
UV_PYTHON_INSTALL_DIR: /tmp/missing-uv-python UV_PYTHON_INSTALL_DIR: /tmp/missing-uv-python
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Setup uv with cache and python cache enabled - name: Setup uv with cache and python cache enabled
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-python: true cache-python: true
@@ -973,7 +973,7 @@ jobs:
test-cache-python-installs: test-cache-python-installs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Verify Python install dir is not populated - name: Verify Python install dir is not populated
@@ -983,7 +983,7 @@ jobs:
exit 1 exit 1
fi fi
- name: Setup uv with cache - name: Setup uv with cache
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-python: true cache-python: true
@@ -1000,7 +1000,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: test-cache-python-installs needs: test-cache-python-installs
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Verify Python install dir does not exist - name: Verify Python install dir does not exist
@@ -1011,7 +1011,7 @@ jobs:
fi fi
- name: Restore with cache - name: Restore with cache
id: restore id: restore
uses: $/ uses: ./
with: with:
enable-cache: true enable-cache: true
cache-python: true cache-python: true
@@ -1042,9 +1042,12 @@ jobs:
expected-python-dir: "D:\\a\\_temp\\uv-python-dir" expected-python-dir: "D:\\a\\_temp\\uv-python-dir"
runs-on: ${{ matrix.inputs.os }} runs-on: ${{ matrix.inputs.os }}
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Install latest version - name: Install latest version
id: setup-uv id: setup-uv
uses: $/ uses: ./
- name: Check Python dir is expected dir - name: Check Python dir is expected dir
run: | run: |
if [ "$UV_PYTHON_INSTALL_DIR" != "${{ matrix.inputs.expected-python-dir }}" ]; then if [ "$UV_PYTHON_INSTALL_DIR" != "${{ matrix.inputs.expected-python-dir }}" ]; then
@@ -1055,29 +1058,25 @@ jobs:
- name: Install python works - name: Install python works
run: uv python install run: uv python install
test-workflow-run: test-act:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Install act - name: Install act
run: gh extension install https://github.com/nektos/gh-act run: gh extension install https://github.com/nektos/gh-act
env: env:
GH_TOKEN: ${{ github.token }} GH_TOKEN: ${{ github.token }}
- name: Verify workflow_run disables automatic caching with act - name: Run test-uvx with act
run: | run: gh act -j test-uvx -P ubuntu-latest=catthehacker/ubuntu:act-latest
gh act workflow_run \
-W __tests__/workflows/workflow-run.yml \
-P ubuntu-latest=catthehacker/ubuntu:act-latest \
--env RUNNER_ENVIRONMENT=github-hosted
env: env:
GH_TOKEN: ${{ github.token }} GH_TOKEN: ${{ github.token }}
validate-typings: validate-typings:
runs-on: "ubuntu-latest" runs-on: "ubuntu-latest"
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: false persist-credentials: false
- name: Validate typings - name: Validate typings
@@ -1094,7 +1093,6 @@ jobs:
- test-from-working-directory-version - test-from-working-directory-version
- test-malformed-pyproject-file-fallback - test-malformed-pyproject-file-fallback
- test-version-file-version - test-version-file-version
- test-tool-versions-python-version
- test-checksum - test-checksum
- test-with-explicit-token - test-with-explicit-token
- test-uvx - test-uvx
@@ -1121,7 +1119,6 @@ jobs:
- test-restore-cache-restore-cache-false - test-restore-cache-restore-cache-false
- test-no-python-version - test-no-python-version
- test-custom-manifest-file - test-custom-manifest-file
- test-download-from-astral-mirror-false
- test-absolute-path - test-absolute-path
- test-relative-path - test-relative-path
- test-cache-prune-force - test-cache-prune-force
@@ -1130,7 +1127,7 @@ jobs:
- test-cache-python-installs - test-cache-python-installs
- test-restore-python-installs - test-restore-python-installs
- test-python-install-dir - test-python-install-dir
- test-workflow-run - test-act
- validate-typings - validate-typings
if: always() if: always()
steps: steps:
+19 -25
View File
@@ -1,46 +1,28 @@
name: "Update docs" name: "Update docs"
on: on:
workflow_call: push:
inputs: tags:
tag: - "v*.*.*"
description: "Release tag to update docs for (e.g., v8.2.0)"
required: true
type: string
workflow_dispatch:
permissions: {} permissions: {}
jobs: jobs:
update-docs: update-docs:
continue-on-error: ${{ github.event_name == 'workflow_call' }}
runs-on: ubuntu-24.04-arm runs-on: ubuntu-24.04-arm
permissions: permissions:
contents: write contents: write
pull-requests: write pull-requests: write
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
fetch-depth: 0
persist-credentials: true persist-credentials: true
- name: Get tag info - name: Get tag info
id: tag-info id: tag-info
run: | run: |
if [ -n "$INPUT_TAG" ]; then TAG_NAME="${GITHUB_REF#refs/tags/}"
TAG_NAME="$INPUT_TAG"
else
TAG_NAME=$(git tag --list 'v[0-9]*.[0-9]*.[0-9]*' --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -1)
fi
if [[ ! "$TAG_NAME" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "::error::Tag must match vMAJOR.MINOR.PATCH (e.g., v8.2.0)"
exit 1
fi
COMMIT_SHA=$(git rev-list -n 1 "$TAG_NAME") COMMIT_SHA=$(git rev-list -n 1 "$TAG_NAME")
echo "tag=$TAG_NAME" >> "$GITHUB_OUTPUT" echo "tag=$TAG_NAME" >> "$GITHUB_OUTPUT"
echo "sha=$COMMIT_SHA" >> "$GITHUB_OUTPUT" echo "sha=$COMMIT_SHA" >> "$GITHUB_OUTPUT"
env:
INPUT_TAG: ${{ inputs.tag }}
- name: Update references in docs - name: Update references in docs
run: | run: |
OLD_REF=$(grep -oh 'astral-sh/setup-uv@[a-f0-9]\{40\} # v[0-9][^ ]*' README.md docs/*.md | head -1) OLD_REF=$(grep -oh 'astral-sh/setup-uv@[a-f0-9]\{40\} # v[0-9][^ ]*' README.md docs/*.md | head -1)
@@ -60,8 +42,20 @@ jobs:
else else
echo "changes-exist=false" >> "$GITHUB_OUTPUT" echo "changes-exist=false" >> "$GITHUB_OUTPUT"
fi fi
- name: Create Pull Request - name: Commit and push changes
if: ${{ steps.changes-exist.outputs.changes-exist == 'true' }} if: ${{ steps.changes-exist.outputs.changes-exist == 'true' }}
id: commit-and-push
continue-on-error: true
run: |
git config user.name "$GITHUB_ACTOR"
git config user.email "$GITHUB_ACTOR@users.noreply.github.com"
git add .
git commit -m "docs: update version references to $NEW_VERSION"
git push origin HEAD:refs/heads/main
env:
NEW_VERSION: ${{ steps.tag-info.outputs.tag }}
- name: Create Pull Request
if: ${{ steps.changes-exist.outputs.changes-exist == 'true' && steps.commit-and-push.outcome != 'success' }}
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
with: with:
commit-message: "docs: update version references to ${{ steps.tag-info.outputs.tag }}" commit-message: "docs: update version references to ${{ steps.tag-info.outputs.tag }}"
@@ -70,6 +64,6 @@ jobs:
Update `uses: astral-sh/setup-uv@...` references in documentation to Update `uses: astral-sh/setup-uv@...` references in documentation to
`${{ steps.tag-info.outputs.sha }} # ${{ steps.tag-info.outputs.tag }}`. `${{ steps.tag-info.outputs.sha }} # ${{ steps.tag-info.outputs.tag }}`.
base: main base: main
labels: "automated-pr,documentation" labels: "automated-pr,update-docs"
branch: update-docs-${{ steps.tag-info.outputs.tag }} branch: update-docs-${{ steps.tag-info.outputs.tag }}
delete-branch: true delete-branch: true
+17 -4
View File
@@ -15,10 +15,10 @@ jobs:
contents: write contents: write
pull-requests: write pull-requests: write
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with: with:
persist-credentials: true persist-credentials: true
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with: with:
node-version-file: .nvmrc node-version-file: .nvmrc
cache: npm cache: npm
@@ -26,7 +26,7 @@ jobs:
id: update-known-checksums id: update-known-checksums
run: run:
node dist/update-known-checksums/index.cjs node dist/update-known-checksums/index.cjs
src/download/checksum/known-checksums.json src/download/checksum/known-checksums.ts
- name: Check for changes - name: Check for changes
id: changes-exist id: changes-exist
run: | run: |
@@ -39,8 +39,21 @@ jobs:
- name: Compile changes - name: Compile changes
if: ${{ steps.changes-exist.outputs.changes-exist == 'true' }} if: ${{ steps.changes-exist.outputs.changes-exist == 'true' }}
run: npm ci --ignore-scripts && npm run all run: npm ci --ignore-scripts && npm run all
- name: Create Pull Request - name: Commit and push changes
if: ${{ steps.changes-exist.outputs.changes-exist == 'true' }} if: ${{ steps.changes-exist.outputs.changes-exist == 'true' }}
id: commit-and-push
continue-on-error: true
run: |
git config user.name "$GITHUB_ACTOR"
git config user.email "$GITHUB_ACTOR@users.noreply.github.com"
git add .
git commit -m "chore: update known checksums for $LATEST_VERSION"
git push origin HEAD:refs/heads/main
env:
LATEST_VERSION: ${{ steps.update-known-checksums.outputs.latest-version }}
- name: Create Pull Request
if: ${{ steps.changes-exist.outputs.changes-exist == 'true' && steps.commit-and-push.outcome != 'success' }}
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
with: with:
commit-message: "chore: update known checksums" commit-message: "chore: update known checksums"
-3
View File
@@ -1,3 +0,0 @@
engine-strict = true
ignore-scripts = true
min-release-age = 7
+1 -1
View File
@@ -1 +1 @@
24.19.0 24
+14 -39
View File
@@ -26,7 +26,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@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
``` ```
If you do not specify a version, this action will look for a [required-version](https://docs.astral.sh/uv/reference/settings/#required-version) If you do not specify a version, this action will look for a [required-version](https://docs.astral.sh/uv/reference/settings/#required-version)
@@ -42,18 +42,18 @@ Have a look under [Advanced Configuration](#advanced-configuration) for detailed
```yaml ```yaml
- name: Install uv with all available options - name: Install uv with all available options
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
# The version of uv to install, e.g., "0.5.0", "latest", or "latest-known" (default: searches for version in config files, then latest) # The version of uv to install (default: searches for version in config files, then latest)
version: "" version: ""
# Path to a file containing the version of uv to install, e.g., uv.toml, pyproject.toml, .tool-versions, requirements.txt or uv.lock. A selected .tool-versions file can also provide the Python version (default: searches uv.toml then pyproject.toml) # Path to a file containing the version of uv to install (default: searches uv.toml then pyproject.toml)
version-file: "" version-file: ""
# Resolution strategy when resolving version ranges: 'highest' or 'lowest' # Resolution strategy when resolving version ranges: 'highest' or 'lowest'
resolution-strategy: "highest" resolution-strategy: "highest"
# The version of Python to set UV_PYTHON to (overrides the Python version from .tool-versions) # The version of Python to set UV_PYTHON to
python-version: "" python-version: ""
# Use uv venv to activate a venv ready to be used by later steps # Use uv venv to activate a venv ready to be used by later steps
@@ -74,7 +74,7 @@ Have a look under [Advanced Configuration](#advanced-configuration) for detailed
# Used when downloading uv from GitHub releases # Used when downloading uv from GitHub releases
github-token: ${{ github.token }} github-token: ${{ github.token }}
# Enable the GitHub Actions cache for uv: true, false, or auto (enabled on GitHub-hosted runners except for release, tag push, pull_request_target, and workflow_run events; disabled on self-hosted runners) # Enable uploading of the uv cache: true, false, or auto (enabled on GitHub-hosted runners, disabled on self-hosted runners)
enable-cache: "auto" enable-cache: "auto"
# Glob pattern to match files relative to the repository root to control the cache # Glob pattern to match files relative to the repository root to control the cache
@@ -100,7 +100,7 @@ Have a look under [Advanced Configuration](#advanced-configuration) for detailed
cache-local-path: "" cache-local-path: ""
# Prune cache before saving # Prune cache before saving
prune-cache: "false" prune-cache: "true"
# Upload managed Python installations to the GitHub Actions cache # Upload managed Python installations to the GitHub Actions cache
cache-python: "false" cache-python: "false"
@@ -120,14 +120,8 @@ Have a look under [Advanced Configuration](#advanced-configuration) for detailed
# URL to a custom manifest file in the astral-sh/versions format # URL to a custom manifest file in the astral-sh/versions format
manifest-file: "" manifest-file: ""
# Download uv from the Astral mirror instead of directly from GitHub Releases
download-from-astral-mirror: "true"
# Add problem matchers # Add problem matchers
add-problem-matchers: "true" add-problem-matchers: "true"
# Suppress info-level log output. Only warnings and errors are shown
quiet: "false"
``` ```
### Outputs ### Outputs
@@ -144,30 +138,11 @@ Have a look under [Advanced Configuration](#advanced-configuration) for detailed
You can use the input `python-version` to set the environment variable `UV_PYTHON` for the rest of your workflow 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`, `.python-version`, and This will override any python version specifications in `pyproject.toml` and `.python-version`
an explicitly selected `.tool-versions` file.
When `version-file` points to `.tool-versions`, its `python` entry is used if neither
`python-version` nor `UV_PYTHON` is set:
```text
uv 0.12.3
python 3.13
```
```yaml
- uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1
with:
version-file: ".tool-versions"
```
Only a single Python version is supported. Filesystem paths are not supported for uv or Python.
Multiple Python fallback versions and the asdf `ref:`, `path:`, and `system` forms are ignored with
a warning.
```yaml ```yaml
- name: Install the latest version of uv and set the python version to 3.13t - name: Install the latest version of uv and set the python version to 3.13t
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
python-version: 3.13t python-version: 3.13t
- run: uv pip install --python=3.13t pip - run: uv pip install --python=3.13t pip
@@ -185,7 +160,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v5
- name: Install the latest version of uv and set the python version - name: Install the latest version of uv and set the python version
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}
- name: Test with python ${{ matrix.python-version }} - name: Test with python ${{ matrix.python-version }}
@@ -202,7 +177,7 @@ It also controls where [the venv gets created](#activate-environment), unless `v
```yaml ```yaml
- name: Install uv based on the config files in the working-directory - name: Install uv based on the config files in the working-directory
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
working-directory: my/subproject/dir working-directory: my/subproject/dir
``` ```
@@ -244,7 +219,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@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
- name: Test - name: Test
@@ -256,7 +231,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@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
- name: Install Python 3.12 - name: Install Python 3.12
@@ -275,7 +250,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@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
- 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 }}"
``` ```
-5
View File
@@ -1,5 +0,0 @@
# Security policy
Report suspected vulnerabilities according to [Astral's security policy](https://github.com/astral-sh/.github/blob/main/SECURITY.md).
For this repository's security boundaries and reporting criteria, see the [setup-uv threat model](docs/threat-model.md).
-74
View File
@@ -1,74 +0,0 @@
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
import { createSetupInputs } from "../helpers/setup-inputs";
const mockRestoreCache = jest.fn();
const mockSaveState = jest.fn();
const mockSetOutput = jest.fn();
jest.unstable_mockModule("@actions/cache", () => ({
restoreCache: mockRestoreCache,
}));
jest.unstable_mockModule("@actions/core", () => ({
saveState: mockSaveState,
setOutput: mockSetOutput,
}));
jest.unstable_mockModule("../../src/hash/hash-files", () => ({
hashFiles: jest.fn(async () => "dependencyhash"),
}));
jest.unstable_mockModule("../../src/utils/logging", () => ({
info: jest.fn(),
warning: jest.fn(),
}));
jest.unstable_mockModule("../../src/utils/platforms", () => ({
getArch: jest.fn(() => "x86_64"),
getOSNameVersion: jest.fn(() => "ubuntu-24.04"),
getPlatform: jest.fn(async () => "unknown-linux-gnu"),
}));
const { restoreCache } = await import("../../src/cache/restore-cache");
function cacheKeyOutput(): string {
const call = mockSetOutput.mock.calls.find(([name]) => name === "cache-key");
expect(call).toBeDefined();
return call?.[1] as string;
}
beforeEach(() => {
jest.clearAllMocks();
});
describe("restoreCache", () => {
it("encodes Python version ranges before adding them to the cache key", async () => {
await restoreCache(createSetupInputs(), ">3.10.11,<3.11");
const cacheKey = cacheKeyOutput();
expect(cacheKey).not.toContain(",");
expect(cacheKey).toContain("-%3E3.10.11%2C%3C3.11-");
});
it("encodes cache suffixes before adding them to the cache key", async () => {
const inputs = createSetupInputs({ cacheSuffix: "tests-3.10,3.11" });
await restoreCache(inputs, "3.11");
const cacheKey = cacheKeyOutput();
expect(cacheKey).not.toContain(",");
expect(cacheKey).toContain("-tests-3.10%2C3.11");
});
it("uses an unpruned cache key by default", async () => {
const inputs = createSetupInputs({ cacheSuffix: "tests-3.11" });
await restoreCache(inputs, "3.11");
expect(cacheKeyOutput()).toBe(
"setup-uv-2-x86_64-unknown-linux-gnu-ubuntu-24.04-3.11-dependencyhash-tests-3.11",
);
});
});
+6 -6
View File
@@ -40,9 +40,9 @@ it.each<KnownVersionFixture>([
known: false, known: false,
version: "0.0.15", version: "0.0.15",
}, },
])( ])("isknownVersion should return $known for version $version", ({
"isknownVersion should return $known for version $version", version,
({ version, known }) => { known,
expect(isknownVersion(version)).toBe(known); }) => {
}, expect(isknownVersion(version)).toBe(known);
); });
@@ -1,20 +0,0 @@
import { expect, it, jest } from "@jest/globals";
jest.unstable_mockModule(
"../../../src/download/checksum/known-checksums",
() => ({
KNOWN_CHECKSUMS: {
"aarch64-apple-darwin-1.9.0": "checksum",
"x86_64-unknown-linux-gnu-1.8.0": "checksum",
"x86_64-unknown-linux-gnu-1.10.0": "checksum",
},
}),
);
const { getLatestKnownVersion } = await import(
"../../../src/download/checksum/known-version"
);
it("returns the highest version with a built-in checksum", () => {
expect(getLatestKnownVersion()).toBe("1.10.0");
});
@@ -1,27 +0,0 @@
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { expect, test } from "@jest/globals";
import { updateChecksums } from "../../../src/download/checksum/update-known-checksums";
test("serializes checksum entries as JSON data", async () => {
const tempDirectory = await fs.mkdtemp(
path.join(os.tmpdir(), "setup-uv-checksums-test-"),
);
const outputPath = path.join(tempDirectory, "known-checksums.json");
const key = 'platform-1.0.0"\n};\nglobalThis.compromised = true;';
const checksum = 'checksum"\\\nvalue';
try {
await updateChecksums(outputPath, [
{ checksum, key },
{ checksum: "duplicate", key },
]);
const content = await fs.readFile(outputPath, "utf8");
expect(JSON.parse(content)).toEqual({ [key]: checksum });
expect(content.endsWith("\n")).toBe(true);
} finally {
await fs.rm(tempDirectory, { force: true, recursive: true });
}
});
+4 -81
View File
@@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it, jest } from "@jest/globals"; import { beforeEach, describe, expect, it, jest } from "@jest/globals";
import * as semver from "semver"; import * as semver from "semver";
import { VERSIONS_MANIFEST_URL } from "../../src/utils/constants";
const mockInfo = jest.fn(); const mockInfo = jest.fn();
const mockWarning = jest.fn(); const mockWarning = jest.fn();
@@ -37,14 +36,11 @@ const mockGetLatestVersion = jest.fn<any>();
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests. // biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
const mockGetAllVersions = jest.fn<any>(); const mockGetAllVersions = jest.fn<any>();
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests. // biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
const mockGetFirstMatchingVersion = jest.fn<any>();
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
const mockGetArtifact = jest.fn<any>(); const mockGetArtifact = jest.fn<any>();
jest.unstable_mockModule("../../src/download/manifest", () => ({ jest.unstable_mockModule("../../src/download/manifest", () => ({
getAllVersions: mockGetAllVersions, getAllVersions: mockGetAllVersions,
getArtifact: mockGetArtifact, getArtifact: mockGetArtifact,
getFirstMatchingVersion: mockGetFirstMatchingVersion,
getLatestVersion: mockGetLatestVersion, getLatestVersion: mockGetLatestVersion,
})); }));
@@ -55,12 +51,6 @@ jest.unstable_mockModule("../../src/download/checksum/checksum", () => ({
validateChecksum: mockValidateChecksum, validateChecksum: mockValidateChecksum,
})); }));
const mockGetLatestKnownVersion = jest.fn(() => "0.9.25");
jest.unstable_mockModule("../../src/download/checksum/known-version", () => ({
getLatestKnownVersion: mockGetLatestKnownVersion,
}));
const { downloadVersion, resolveVersion, rewriteToMirror } = await import( const { downloadVersion, resolveVersion, rewriteToMirror } = await import(
"../../src/download/download-version" "../../src/download/download-version"
); );
@@ -75,10 +65,8 @@ describe("download-version", () => {
mockCacheDir.mockReset(); mockCacheDir.mockReset();
mockGetLatestVersion.mockReset(); mockGetLatestVersion.mockReset();
mockGetAllVersions.mockReset(); mockGetAllVersions.mockReset();
mockGetFirstMatchingVersion.mockReset();
mockGetArtifact.mockReset(); mockGetArtifact.mockReset();
mockValidateChecksum.mockReset(); mockValidateChecksum.mockReset();
mockGetLatestKnownVersion.mockClear();
mockDownloadTool.mockResolvedValue("/tmp/downloaded"); mockDownloadTool.mockResolvedValue("/tmp/downloaded");
mockExtractTar.mockResolvedValue("/tmp/extracted"); mockExtractTar.mockResolvedValue("/tmp/extracted");
@@ -97,53 +85,14 @@ describe("download-version", () => {
expect(mockGetLatestVersion).toHaveBeenCalledWith(undefined); expect(mockGetLatestVersion).toHaveBeenCalledWith(undefined);
}); });
it("resolves latest-known without reading the manifest", async () => { it("uses the default manifest to resolve available versions", async () => {
const version = await resolveVersion("latest-known", undefined); mockGetAllVersions.mockResolvedValue(["0.9.26", "0.9.25"]);
expect(version).toBe("0.9.25");
expect(mockGetLatestKnownVersion).toHaveBeenCalledTimes(1);
expect(mockGetLatestVersion).not.toHaveBeenCalled();
expect(mockGetAllVersions).not.toHaveBeenCalled();
expect(mockGetFirstMatchingVersion).not.toHaveBeenCalled();
});
it("stops at the first matching version in the default manifest", async () => {
mockGetFirstMatchingVersion.mockImplementation(
(predicate: (version: string) => boolean) =>
["0.9.26", "0.9.25"].find(predicate),
);
const version = await resolveVersion("^0.9.0", undefined); const version = await resolveVersion("^0.9.0", undefined);
expect(version).toBe("0.9.26"); expect(version).toBe("0.9.26");
expect(mockGetFirstMatchingVersion).toHaveBeenCalledTimes(1); expect(mockGetAllVersions).toHaveBeenCalledTimes(1);
expect(mockGetAllVersions).not.toHaveBeenCalled(); expect(mockGetAllVersions).toHaveBeenCalledWith(undefined);
});
it("streams ranges when the default manifest URL is explicit", async () => {
mockGetFirstMatchingVersion.mockImplementation(
(predicate: (version: string) => boolean) =>
["0.9.26", "0.9.25"].find(predicate),
);
const version = await resolveVersion("^0.9.0", VERSIONS_MANIFEST_URL);
expect(version).toBe("0.9.26");
expect(mockGetFirstMatchingVersion).toHaveBeenCalledTimes(1);
expect(mockGetAllVersions).not.toHaveBeenCalled();
});
it("streams PEP 440 ranges from the default manifest", async () => {
mockGetFirstMatchingVersion.mockImplementation(
(predicate: (version: string) => boolean) =>
["0.9.26", "0.9.25"].find(predicate),
);
const version = await resolveVersion("!=0.9.26", undefined);
expect(version).toBe("0.9.25");
expect(mockGetFirstMatchingVersion).toHaveBeenCalledTimes(1);
expect(mockGetAllVersions).not.toHaveBeenCalled();
}); });
it("treats == exact pins as explicit versions", async () => { it("treats == exact pins as explicit versions", async () => {
@@ -427,32 +376,6 @@ describe("download-version", () => {
"0.9.26", "0.9.26",
); );
}); });
it("skips the Astral mirror when downloadFromAstralMirror is false", async () => {
mockGetArtifact.mockResolvedValue({
archiveFormat: "tar.gz",
checksum: "abc123",
downloadUrl:
"https://github.com/astral-sh/uv/releases/download/0.9.26/uv-x86_64-unknown-linux-gnu.tar.gz",
});
await downloadVersion(
"unknown-linux-gnu",
"x86_64",
"0.9.26",
undefined,
"token",
undefined,
false,
);
expect(mockDownloadTool).toHaveBeenCalledWith(
"https://github.com/astral-sh/uv/releases/download/0.9.26/uv-x86_64-unknown-linux-gnu.tar.gz",
undefined,
"token",
);
expect(mockDownloadTool).toHaveBeenCalledTimes(1);
});
}); });
describe("rewriteToMirror", () => { describe("rewriteToMirror", () => {
+1 -191
View File
@@ -1,11 +1,4 @@
import { import { beforeEach, describe, expect, it, jest } from "@jest/globals";
afterEach,
beforeEach,
describe,
expect,
it,
jest,
} from "@jest/globals";
// biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests. // biome-ignore lint/suspicious/noExplicitAny: Mock requires flexible typing in tests.
const mockFetch = jest.fn<any>(); const mockFetch = jest.fn<any>();
@@ -20,12 +13,10 @@ jest.unstable_mockModule("../../src/utils/fetch", () => ({
})); }));
const { const {
MANIFEST_FETCH_ATTEMPTS,
clearManifestCache, clearManifestCache,
fetchManifest, fetchManifest,
getAllVersions, getAllVersions,
getArtifact, getArtifact,
getFirstMatchingVersion,
getLatestVersion, getLatestVersion,
parseManifest, parseManifest,
} = await import("../../src/download/manifest"); } = await import("../../src/download/manifest");
@@ -42,7 +33,6 @@ function createMockResponse(
data: string, data: string,
) { ) {
return { return {
body: null,
ok, ok,
status, status,
statusText, statusText,
@@ -50,41 +40,12 @@ function createMockResponse(
}; };
} }
function createStreamingMockResponse(
chunks: string[],
cancel: () => void | Promise<void> = () => {},
close = false,
) {
const encoder = new TextEncoder();
return {
body: new ReadableStream<Uint8Array>({
cancel,
start(controller) {
for (const chunk of chunks) {
controller.enqueue(encoder.encode(chunk));
}
if (close) {
controller.close();
}
},
}),
ok: true,
status: 200,
statusText: "OK",
text: async () => chunks.join(""),
};
}
describe("manifest", () => { describe("manifest", () => {
beforeEach(() => { beforeEach(() => {
clearManifestCache(); clearManifestCache();
mockFetch.mockReset(); mockFetch.mockReset();
}); });
afterEach(() => {
jest.useRealTimers();
});
describe("fetchManifest", () => { describe("fetchManifest", () => {
it("fetches and parses manifest data", async () => { it("fetches and parses manifest data", async () => {
mockFetch.mockResolvedValue( mockFetch.mockResolvedValue(
@@ -98,34 +59,6 @@ describe("manifest", () => {
expect(versions[1]?.version).toBe("0.9.25"); expect(versions[1]?.version).toBe("0.9.25");
}); });
it("retries network failures", async () => {
jest.useFakeTimers();
mockFetch
.mockRejectedValueOnce(new Error("request timed out"))
.mockResolvedValueOnce(
createMockResponse(true, 200, "OK", sampleManifestResponse),
);
const result = fetchManifest();
await jest.runAllTimersAsync();
await expect(result).resolves.toHaveLength(2);
expect(mockFetch).toHaveBeenCalledTimes(2);
});
it("stops after the configured number of network failures", async () => {
jest.useFakeTimers();
mockFetch.mockRejectedValue(new Error("request timed out"));
const result = expect(fetchManifest()).rejects.toThrow(
"request timed out",
);
await jest.runAllTimersAsync();
await result;
expect(mockFetch).toHaveBeenCalledTimes(MANIFEST_FETCH_ATTEMPTS);
});
it("throws on a failed fetch", async () => { it("throws on a failed fetch", async () => {
mockFetch.mockResolvedValue( mockFetch.mockResolvedValue(
createMockResponse(false, 500, "Internal Server Error", ""), createMockResponse(false, 500, "Internal Server Error", ""),
@@ -172,75 +105,6 @@ describe("manifest", () => {
getLatestVersion("https://example.com/custom.ndjson"), getLatestVersion("https://example.com/custom.ndjson"),
).resolves.toBe("0.9.26"); ).resolves.toBe("0.9.26");
}); });
it("stops reading the default manifest after the first record", async () => {
const [latestVersion] = sampleManifestResponse.split("\n");
const cancel = jest.fn();
mockFetch.mockResolvedValue(
createStreamingMockResponse(
[
latestVersion.slice(0, 100),
`${latestVersion.slice(100)}\n`,
"invalid trailing data\n",
],
cancel,
),
);
await expect(getLatestVersion()).resolves.toBe("0.9.26");
await expect(
getArtifact("0.9.26", "aarch64", "apple-darwin"),
).resolves.toBeDefined();
expect(cancel).toHaveBeenCalledTimes(1);
expect(mockFetch).toHaveBeenCalledTimes(1);
});
it("does not fail when canceling the remaining response fails", async () => {
const [latestVersion] = sampleManifestResponse.split("\n");
mockFetch.mockResolvedValue(
createStreamingMockResponse([`${latestVersion}\n`], () =>
Promise.reject(new Error("cancel failed")),
),
);
await expect(getLatestVersion()).resolves.toBe("0.9.26");
});
});
describe("getFirstMatchingVersion", () => {
it("stops at the first matching record", async () => {
const cancel = jest.fn();
mockFetch.mockResolvedValue(
createStreamingMockResponse(
[`${sampleManifestResponse}\n`, "invalid trailing data\n"],
cancel,
),
);
await expect(
getFirstMatchingVersion((version) => version === "0.9.25"),
).resolves.toBe("0.9.25");
expect(cancel).toHaveBeenCalledTimes(1);
});
it("caches a fully consumed response stream", async () => {
mockFetch.mockResolvedValue(
createStreamingMockResponse(
[`${sampleManifestResponse}\n`],
undefined,
true,
),
);
await expect(
getFirstMatchingVersion((version) => version === "0.0.1"),
).resolves.toBeUndefined();
await expect(getLatestVersion()).resolves.toBe("0.9.26");
expect(mockFetch).toHaveBeenCalledTimes(1);
});
}); });
describe("getArtifact", () => { describe("getArtifact", () => {
@@ -304,60 +168,6 @@ describe("manifest", () => {
expect(artifact).toBeUndefined(); expect(artifact).toBeUndefined();
}); });
it("does not cache records from a failed stream read", async () => {
const [latestVersion] = sampleManifestResponse.split("\n");
mockFetch
.mockResolvedValueOnce(
createStreamingMockResponse([
`${latestVersion}\n`,
"invalid manifest record\n",
]),
)
.mockResolvedValueOnce(
createMockResponse(true, 200, "OK", sampleManifestResponse),
);
await expect(
getArtifact("0.0.1", "aarch64", "apple-darwin"),
).rejects.toThrow("Failed to parse manifest data");
await expect(getLatestVersion()).resolves.toBe("0.9.26");
expect(mockFetch).toHaveBeenCalledTimes(2);
});
it("does not cache records when the response stream fails", async () => {
const [latestVersion] = sampleManifestResponse.split("\n");
const encoder = new TextEncoder();
let sentVersion = false;
const body = new ReadableStream<Uint8Array>({
pull(controller) {
if (!sentVersion) {
sentVersion = true;
controller.enqueue(encoder.encode(`${latestVersion}\n`));
return;
}
controller.error(new Error("response stream failed"));
},
});
mockFetch
.mockResolvedValueOnce({
body,
ok: true,
status: 200,
statusText: "OK",
})
.mockResolvedValueOnce(
createMockResponse(true, 200, "OK", sampleManifestResponse),
);
await expect(
getArtifact("0.0.1", "aarch64", "apple-darwin"),
).rejects.toThrow("response stream failed");
await expect(getLatestVersion()).resolves.toBe("0.9.26");
expect(mockFetch).toHaveBeenCalledTimes(2);
});
}); });
describe("parseManifest", () => { describe("parseManifest", () => {
-1
View File
@@ -1,2 +1 @@
uv 0.5.15 uv 0.5.15
python 3.13.1t
-36
View File
@@ -1,36 +0,0 @@
import { CacheLocalSource, type SetupInputs } from "../../src/utils/inputs";
export function createSetupInputs(
overrides: Partial<SetupInputs> = {},
): SetupInputs {
return {
activateEnvironment: false,
addProblemMatchers: false,
cacheDependencyGlob: "uv.lock",
cacheLocalPath: {
path: "/tmp/setup-uv-cache",
source: CacheLocalSource.Input,
},
cachePython: false,
cacheSuffix: "",
checksum: "",
downloadFromAstralMirror: false,
enableCache: true,
githubToken: "",
ignoreEmptyWorkdir: false,
ignoreNothingToCache: false,
noProject: false,
pruneCache: false,
pythonDir: "/tmp/uv-python-dir",
pythonVersion: "",
quiet: false,
resolutionStrategy: "highest",
restoreCache: false,
saveCache: true,
venvPath: "/workspace/.venv",
version: "",
versionFile: "",
workingDirectory: "/workspace",
...overrides,
};
}
-112
View File
@@ -12,13 +12,10 @@ import {
let mockInputs: Record<string, string> = {}; let mockInputs: Record<string, string> = {};
const tempDirs: string[] = []; const tempDirs: string[] = [];
const ORIGINAL_GITHUB_EVENT_NAME = process.env.GITHUB_EVENT_NAME;
const ORIGINAL_GITHUB_REF = process.env.GITHUB_REF;
const ORIGINAL_HOME = process.env.HOME; const ORIGINAL_HOME = process.env.HOME;
const ORIGINAL_RUNNER_ENVIRONMENT = process.env.RUNNER_ENVIRONMENT; const ORIGINAL_RUNNER_ENVIRONMENT = process.env.RUNNER_ENVIRONMENT;
const ORIGINAL_RUNNER_TEMP = process.env.RUNNER_TEMP; const ORIGINAL_RUNNER_TEMP = process.env.RUNNER_TEMP;
const ORIGINAL_UV_CACHE_DIR = process.env.UV_CACHE_DIR; const ORIGINAL_UV_CACHE_DIR = process.env.UV_CACHE_DIR;
const ORIGINAL_UV_PYTHON = process.env.UV_PYTHON;
const ORIGINAL_UV_PYTHON_INSTALL_DIR = process.env.UV_PYTHON_INSTALL_DIR; const ORIGINAL_UV_PYTHON_INSTALL_DIR = process.env.UV_PYTHON_INSTALL_DIR;
const mockDebug = jest.fn(); const mockDebug = jest.fn();
@@ -55,13 +52,10 @@ function createTempProject(files: Record<string, string> = {}): string {
function resetEnvironment(): void { function resetEnvironment(): void {
jest.clearAllMocks(); jest.clearAllMocks();
mockInputs = {}; mockInputs = {};
delete process.env.GITHUB_EVENT_NAME;
delete process.env.GITHUB_REF;
process.env.HOME = "/home/testuser"; process.env.HOME = "/home/testuser";
delete process.env.RUNNER_ENVIRONMENT; delete process.env.RUNNER_ENVIRONMENT;
delete process.env.RUNNER_TEMP; delete process.env.RUNNER_TEMP;
delete process.env.UV_CACHE_DIR; delete process.env.UV_CACHE_DIR;
delete process.env.UV_PYTHON;
delete process.env.UV_PYTHON_INSTALL_DIR; delete process.env.UV_PYTHON_INSTALL_DIR;
} }
@@ -70,13 +64,10 @@ function restoreEnvironment(): void {
fs.rmSync(dir, { force: true, recursive: true }); fs.rmSync(dir, { force: true, recursive: true });
} }
process.env.GITHUB_EVENT_NAME = ORIGINAL_GITHUB_EVENT_NAME;
process.env.GITHUB_REF = ORIGINAL_GITHUB_REF;
process.env.HOME = ORIGINAL_HOME; process.env.HOME = ORIGINAL_HOME;
process.env.RUNNER_ENVIRONMENT = ORIGINAL_RUNNER_ENVIRONMENT; process.env.RUNNER_ENVIRONMENT = ORIGINAL_RUNNER_ENVIRONMENT;
process.env.RUNNER_TEMP = ORIGINAL_RUNNER_TEMP; process.env.RUNNER_TEMP = ORIGINAL_RUNNER_TEMP;
process.env.UV_CACHE_DIR = ORIGINAL_UV_CACHE_DIR; process.env.UV_CACHE_DIR = ORIGINAL_UV_CACHE_DIR;
process.env.UV_PYTHON = ORIGINAL_UV_PYTHON;
process.env.UV_PYTHON_INSTALL_DIR = ORIGINAL_UV_PYTHON_INSTALL_DIR; process.env.UV_PYTHON_INSTALL_DIR = ORIGINAL_UV_PYTHON_INSTALL_DIR;
} }
@@ -103,109 +94,6 @@ describe("loadInputs", () => {
expect(inputs.resolutionStrategy).toBe("highest"); expect(inputs.resolutionStrategy).toBe("highest");
}); });
it("uses the Python version from an explicitly selected .tool-versions file", () => {
mockInputs["working-directory"] = createTempProject({
".tool-versions": "uv 0.12.3\npython 3.13.1t\n",
});
mockInputs["version-file"] = ".tool-versions";
const inputs = loadInputs();
expect(inputs.pythonVersion).toBe("3.13.1t");
});
it("prefers the python-version input over .tool-versions", () => {
mockInputs["working-directory"] = createTempProject({
".tool-versions": "uv 0.12.3\npython 3.13\n",
});
mockInputs["version-file"] = ".tool-versions";
mockInputs["python-version"] = "3.12";
const inputs = loadInputs();
expect(inputs.pythonVersion).toBe("3.12");
});
it("preserves UV_PYTHON instead of overriding it from .tool-versions", () => {
mockInputs["working-directory"] = createTempProject({
".tool-versions": "uv 0.12.3\npython 3.13\n",
});
mockInputs["version-file"] = ".tool-versions";
process.env.UV_PYTHON = "3.11";
const inputs = loadInputs();
expect(inputs.pythonVersion).toBe("");
expect(process.env.UV_PYTHON).toBe("3.11");
});
it("does not discover .tool-versions from the working directory", () => {
mockInputs["working-directory"] = createTempProject({
".tool-versions": "uv 0.12.3\npython 3.13\n",
});
const inputs = loadInputs();
expect(inputs.pythonVersion).toBe("");
});
it.each(["pull_request_target", "workflow_run", "release"])(
"disables automatic caching for the %s event",
(eventName) => {
mockInputs["working-directory"] = "/workspace";
mockInputs["enable-cache"] = "auto";
process.env.RUNNER_ENVIRONMENT = "github-hosted";
process.env.RUNNER_TEMP = "/runner-temp";
process.env.GITHUB_EVENT_NAME = eventName;
const inputs = loadInputs();
expect(inputs.enableCache).toBe(false);
expect(mockInfo).toHaveBeenCalledWith(
`Caching is disabled for the ${eventName} event`,
);
},
);
it("disables automatic caching for tag pushes", () => {
mockInputs["working-directory"] = "/workspace";
mockInputs["enable-cache"] = "auto";
process.env.RUNNER_ENVIRONMENT = "github-hosted";
process.env.RUNNER_TEMP = "/runner-temp";
process.env.GITHUB_EVENT_NAME = "push";
process.env.GITHUB_REF = "refs/tags/v1.0.0";
const inputs = loadInputs();
expect(inputs.enableCache).toBe(false);
expect(mockInfo).toHaveBeenCalledWith("Caching is disabled for tag pushes");
});
it("enables automatic caching for branch pushes", () => {
mockInputs["working-directory"] = "/workspace";
mockInputs["enable-cache"] = "auto";
process.env.RUNNER_ENVIRONMENT = "github-hosted";
process.env.RUNNER_TEMP = "/runner-temp";
process.env.GITHUB_EVENT_NAME = "push";
process.env.GITHUB_REF = "refs/heads/main";
const inputs = loadInputs();
expect(inputs.enableCache).toBe(true);
});
it("honors explicitly enabled caching for sensitive events", () => {
mockInputs["working-directory"] = "/workspace";
mockInputs["enable-cache"] = "true";
process.env.RUNNER_ENVIRONMENT = "github-hosted";
process.env.RUNNER_TEMP = "/runner-temp";
process.env.GITHUB_EVENT_NAME = "release";
const inputs = loadInputs();
expect(inputs.enableCache).toBe(true);
});
it("uses cache-dir from pyproject.toml when present", () => { it("uses cache-dir from pyproject.toml when present", () => {
mockInputs["working-directory"] = createTempProject({ mockInputs["working-directory"] = createTempProject({
"pyproject.toml": `[project] "pyproject.toml": `[project]
@@ -1,9 +1,5 @@
import { expect, test } from "@jest/globals"; import { expect, test } from "@jest/globals";
import { getUvVersionFromFile } from "../../src/version/file-parser"; import { getUvVersionFromFile } from "../../src/version/file-parser";
import {
getUvVersionFromPyprojectContent,
getUvVersionFromRequirementsText,
} from "../../src/version/requirements-file";
test("ignores dependencies starting with uv", async () => { test("ignores dependencies starting with uv", async () => {
const parsedVersion = getUvVersionFromFile( const parsedVersion = getUvVersionFromFile(
@@ -11,27 +7,3 @@ test("ignores dependencies starting with uv", async () => {
); );
expect(parsedVersion).toBe("0.6.17"); expect(parsedVersion).toBe("0.6.17");
}); });
test.each([
["without space before marker", "uv==0.11.20; sys_platform != 'emscripten'"],
["with space before marker", "uv==0.11.20 ; sys_platform != 'emscripten'"],
])(
"strips PEP 508 markers from pyproject dependency groups %s",
(_, dependency) => {
const parsedVersion = getUvVersionFromPyprojectContent(`[dependency-groups]
test = [
"${dependency}",
]
`);
expect(parsedVersion).toBe("==0.11.20");
},
);
test("strips PEP 508 markers from requirements dependencies", () => {
const parsedVersion = getUvVersionFromRequirementsText(
"uv==0.11.20; sys_platform != 'emscripten'",
);
expect(parsedVersion).toBe("==0.11.20");
});
+2 -90
View File
@@ -21,11 +21,6 @@ async function getVersionFromToolVersions(filePath: string) {
return getUvVersionFromToolVersions(filePath); return getUvVersionFromToolVersions(filePath);
} }
async function getPythonVersionFromToolVersions(filePath: string) {
const module = await import("../../src/version/tool-versions-file");
return module.getPythonVersionFromToolVersions(filePath);
}
describe("getUvVersionFromToolVersions", () => { describe("getUvVersionFromToolVersions", () => {
beforeEach(() => { beforeEach(() => {
jest.resetModules(); jest.resetModules();
@@ -66,8 +61,8 @@ describe("getUvVersionFromToolVersions", () => {
expect(result).toBe("0.3.0"); expect(result).toBe("0.3.0");
}); });
it("should skip comments", async () => { it("should skip commented lines", async () => {
const fileContent = "# uv 0.1.0\npython 3.11.0\nuv 0.2.0 # inline comment"; const fileContent = "# uv 0.1.0\npython 3.11.0\nuv 0.2.0";
mockReadFileSync.mockReturnValue(fileContent); mockReadFileSync.mockReturnValue(fileContent);
const result = await getVersionFromToolVersions(".tool-versions"); const result = await getVersionFromToolVersions(".tool-versions");
@@ -113,20 +108,6 @@ describe("getUvVersionFromToolVersions", () => {
); );
}); });
it.each(["/my/python/exploit", "my/exploited/uv", "C:\\exploited\\uv"])(
"should warn and return undefined for path %s",
async (version) => {
mockReadFileSync.mockReturnValue(`uv ${version}`);
const result = await getVersionFromToolVersions(".tool-versions");
expect(result).toBeUndefined();
expect(mockWarning).toHaveBeenCalledWith(
`The uv version ${version} in .tool-versions is not supported. Paths are not allowed.`,
);
},
);
it("should handle file path with .tool-versions extension", async () => { it("should handle file path with .tool-versions extension", async () => {
const fileContent = "uv 0.1.0"; const fileContent = "uv 0.1.0";
mockReadFileSync.mockReturnValue(fileContent); mockReadFileSync.mockReturnValue(fileContent);
@@ -140,72 +121,3 @@ describe("getUvVersionFromToolVersions", () => {
); );
}); });
}); });
describe("getPythonVersionFromToolVersions", () => {
beforeEach(() => {
jest.resetModules();
jest.clearAllMocks();
});
it("should return version for a valid Python entry", async () => {
mockReadFileSync.mockReturnValue(
"nodejs 24.0.0\r\npython v3.13.1t # use free-threaded Python\r\nuv 0.12.3",
);
const result = await getPythonVersionFromToolVersions(".tool-versions");
expect(result).toBe("3.13.1t");
});
it("should return the first matching Python version", async () => {
mockReadFileSync.mockReturnValue("python 3.12\npython 3.13");
const result = await getPythonVersionFromToolVersions(".tool-versions");
expect(result).toBe("3.12");
});
it("should return undefined when no Python entry is found", async () => {
mockReadFileSync.mockReturnValue("uv 0.12.3\nnodejs 24.0.0");
const result = await getPythonVersionFromToolVersions(".tool-versions");
expect(result).toBeUndefined();
});
it("should warn and return undefined for multiple Python versions", async () => {
mockReadFileSync.mockReturnValue("python 3.13 3.12 system");
const result = await getPythonVersionFromToolVersions(".tool-versions");
expect(result).toBeUndefined();
expect(mockWarning).toHaveBeenCalledWith(
"Multiple Python versions in .tool-versions are not supported. The Python entry will be ignored.",
);
});
it.each([
"ref:main",
"path:~/src/python",
"system",
"/my/python/exploit",
"my/exploited/python",
"C:\\exploited\\python",
])("should warn and return undefined for %s", async (version) => {
mockReadFileSync.mockReturnValue(`python ${version}`);
const result = await getPythonVersionFromToolVersions(".tool-versions");
expect(result).toBeUndefined();
expect(mockWarning).toHaveBeenCalledWith(
`The Python version ${version} in .tool-versions is not supported. The Python entry will be ignored.`,
);
});
it("should return undefined for non-.tool-versions files", async () => {
const result = await getPythonVersionFromToolVersions(".python-version");
expect(result).toBeUndefined();
expect(mockReadFileSync).not.toHaveBeenCalled();
});
});
-36
View File
@@ -1,36 +0,0 @@
import { describe, expect, it } from "@jest/globals";
import { getUvVersionFromUvLockContent } from "../../src/version/uv-lock-file";
const UV_LOCK = `version = 1
requires-python = ">=3.12"
[[package]]
name = "anyio"
version = "4.6.0"
source = { registry = "https://pypi.org/simple" }
[[package]]
name = "uv"
version = "0.8.17"
source = { registry = "https://pypi.org/simple" }
`;
describe("getUvVersionFromUvLockContent", () => {
it("returns the exact uv version locked in uv.lock", () => {
expect(getUvVersionFromUvLockContent(UV_LOCK)).toBe("0.8.17");
});
it("returns undefined when uv is not a locked package", () => {
const content = `version = 1
[[package]]
name = "anyio"
version = "4.6.0"
`;
expect(getUvVersionFromUvLockContent(content)).toBeUndefined();
});
it("returns undefined when there are no packages", () => {
expect(getUvVersionFromUvLockContent("version = 1\n")).toBeUndefined();
});
});
@@ -63,24 +63,6 @@ describe("resolveVersionRequest", () => {
}); });
}); });
it("uses the exact uv version locked in uv.lock when it is passed via version-file", () => {
const workingDirectory = createTempProject({
"uv.lock": `version = 1\n\n[[package]]\nname = "uv"\nversion = "0.8.17"\nsource = { registry = "https://pypi.org/simple" }\n`,
});
const request = resolveVersionRequest({
versionFile: path.join(workingDirectory, "uv.lock"),
workingDirectory,
});
expect(request).toEqual({
format: "uv.lock",
source: "version-file",
sourcePath: path.join(workingDirectory, "uv.lock"),
specifier: "0.8.17",
});
});
it("uses requirements.txt when it is passed via version-file", () => { it("uses requirements.txt when it is passed via version-file", () => {
const workingDirectory = createTempProject({ const workingDirectory = createTempProject({
"requirements.txt": "uv==0.6.17\nuvicorn==0.35.0\n", "requirements.txt": "uv==0.6.17\nuvicorn==0.35.0\n",
-42
View File
@@ -1,42 +0,0 @@
name: "test workflow_run caching"
on: # zizmor: ignore[dangerous-triggers] this workflow is a test fixture executed by act only
workflow_run:
workflows:
- test
types:
- completed
permissions:
contents: read
jobs:
test-cache-disabled:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup uv with automatic caching
id: setup-uv
uses: ./
- name: Verify automatic caching is disabled
env:
CACHE_KEY: ${{ steps.setup-uv.outputs.cache-key }}
run: |
if [ "$GITHUB_EVENT_NAME" != "workflow_run" ]; then
echo "Expected workflow_run event, got: $GITHUB_EVENT_NAME"
exit 1
fi
if [ "$RUNNER_ENVIRONMENT" != "github-hosted" ]; then
echo "Expected a simulated GitHub-hosted runner, got: $RUNNER_ENVIRONMENT"
exit 1
fi
if [ -n "$CACHE_KEY" ]; then
echo "Cache key should not be set for a workflow_run event: $CACHE_KEY"
exit 1
fi
if [ -n "$UV_CACHE_DIR" ]; then
echo "UV_CACHE_DIR should not be set for a workflow_run event: $UV_CACHE_DIR"
exit 1
fi
-4
View File
@@ -52,12 +52,8 @@ inputs:
type: string type: string
manifest-file: manifest-file:
type: string type: string
download-from-astral-mirror:
type: boolean
add-problem-matchers: add-problem-matchers:
type: boolean type: boolean
quiet:
type: boolean
resolution-strategy: resolution-strategy:
type: enum type: enum
allowed-values: allowed-values:
+5 -11
View File
@@ -4,13 +4,13 @@ description:
author: "astral-sh" author: "astral-sh"
inputs: inputs:
version: version:
description: "The version of uv to install, e.g., `0.5.0`, `latest`, or `latest-known`. Defaults to the version in pyproject.toml or `latest`." description: "The version of uv to install e.g., `0.5.0` Defaults to the version in pyproject.toml or 'latest'."
default: "" default: ""
version-file: version-file:
description: "Path to a file containing the version of uv to install, e.g., uv.toml, pyproject.toml, .tool-versions, requirements.txt or uv.lock. A selected .tool-versions file can also provide the Python version. Defaults to searching for uv.toml and if not found pyproject.toml." description: "Path to a file containing the version of uv to install. Defaults to searching for uv.toml and if not found pyproject.toml."
default: "" default: ""
python-version: python-version:
description: "The version of Python to set UV_PYTHON to. Overrides the Python version from .tool-versions." description: "The version of Python to set UV_PYTHON to"
required: false required: false
activate-environment: activate-environment:
description: "Use uv venv to activate a venv ready to be used by later steps. " description: "Use uv venv to activate a venv ready to be used by later steps. "
@@ -33,7 +33,7 @@ inputs:
required: false required: false
default: ${{ github.token }} default: ${{ github.token }}
enable-cache: enable-cache:
description: "Enable the GitHub Actions cache for uv. 'auto' enables caching on GitHub-hosted runners except for release, tag push, pull_request_target, and workflow_run events." description: "Enable uploading of the uv cache"
default: "auto" default: "auto"
cache-dependency-glob: cache-dependency-glob:
description: description:
@@ -61,7 +61,7 @@ inputs:
default: "" default: ""
prune-cache: prune-cache:
description: "Prune cache before saving." description: "Prune cache before saving."
default: "false" default: "true"
cache-python: cache-python:
description: "Upload managed Python installations to the Github Actions cache." description: "Upload managed Python installations to the Github Actions cache."
default: "false" default: "false"
@@ -80,15 +80,9 @@ inputs:
manifest-file: manifest-file:
description: "URL to a custom manifest file in the astral-sh/versions format." description: "URL to a custom manifest file in the astral-sh/versions format."
required: false required: false
download-from-astral-mirror:
description: "Download uv from the Astral mirror instead of directly from GitHub Releases."
default: "true"
add-problem-matchers: add-problem-matchers:
description: "Add problem matchers." description: "Add problem matchers."
default: "true" default: "true"
quiet:
description: "Suppress info-level log output. Only warnings and errors are shown."
default: "false"
resolution-strategy: resolution-strategy:
description: "Resolution strategy to use when resolving version ranges. 'highest' uses the latest compatible version, 'lowest' uses the oldest compatible version." description: "Resolution strategy to use when resolving version ranges. 'highest' uses the latest compatible version, 'lowest' uses the oldest compatible version."
default: "highest" default: "highest"
+2 -2
View File
@@ -1,5 +1,5 @@
{ {
"$schema": "https://biomejs.dev/schemas/2.5.7/schema.json", "$schema": "https://biomejs.dev/schemas/2.4.7/schema.json",
"assist": { "assist": {
"actions": { "actions": {
"source": { "source": {
@@ -34,7 +34,7 @@
"linter": { "linter": {
"enabled": true, "enabled": true,
"rules": { "rules": {
"preset": "recommended" "recommended": true
} }
}, },
"vcs": { "vcs": {
Generated Vendored
+1594 -3162
View File
File diff suppressed because it is too large Load Diff
Generated Vendored
+4811 -9403
View File
File diff suppressed because one or more lines are too long
+2016 -4749
View File
File diff suppressed because one or more lines are too long
+8 -35
View File
@@ -6,29 +6,16 @@ This document covers advanced options for configuring which version of uv to ins
```yaml ```yaml
- name: Install the latest version of uv - name: Install the latest version of uv
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
version: "latest" version: "latest"
``` ```
## Install the latest version with a checksum verified by this action
Use `latest-known` to install the newest uv version whose checksums were bundled with the version of setup-uv used by your workflow. Version resolution is performed locally without fetching the latest release, so updating setup-uv also updates the version selected by `latest-known`.
When `manifest-file` is set, `latest-known` still selects a version from setup-uv's bundled checksum table, but the artifact and checksum come from the custom manifest.
```yaml
- name: Install the latest version of uv known to setup-uv
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1
with:
version: "latest-known"
```
## 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@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
version: "0.4.4" version: "0.4.4"
``` ```
@@ -41,21 +28,21 @@ 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@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
version: ">=0.4.0" version: ">=0.4.0"
``` ```
```yaml ```yaml
- name: Pinning a minor version of uv - name: Pinning a minor version of uv
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
version: "0.4.x" version: "0.4.x"
``` ```
```yaml ```yaml
- name: Install a pep440-specifier-satisfying version of uv - name: Install a pep440-specifier-satisfying version of uv
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
version: ">=0.4.25,<0.5" version: ">=0.4.25,<0.5"
``` ```
@@ -67,7 +54,7 @@ You can change this behavior using the `resolution-strategy` input:
```yaml ```yaml
- name: Install the lowest compatible version of uv - name: Install the lowest compatible version of uv
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
version: ">=0.4.0" version: ">=0.4.0"
resolution-strategy: "lowest" resolution-strategy: "lowest"
@@ -85,25 +72,11 @@ You can use the `version-file` input to specify a file that contains the version
This can either be a `pyproject.toml` or `uv.toml` file which defines a `required-version` or This can either be a `pyproject.toml` or `uv.toml` file which defines a `required-version` or
uv defined as a dependency in `pyproject.toml` or `requirements.txt`. uv defined as a dependency in `pyproject.toml` or `requirements.txt`.
[asdf](https://asdf-vm.com/) `.tool-versions` is also supported for selecting uv. If neither [asdf](https://asdf-vm.com/) `.tool-versions` is also supported, but without the `ref` syntax.
`python-version` nor `UV_PYTHON` is set, the `python` entry from the selected file is also exported
as `UV_PYTHON`. Only a single Python version is supported; multiple fallback versions and the asdf
`ref:`, `path:`, and `system` forms are ignored with a warning.
```yaml ```yaml
- name: Install uv based on the version defined in pyproject.toml - name: Install uv based on the version defined in pyproject.toml
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
version-file: "pyproject.toml" version-file: "pyproject.toml"
``` ```
If uv is locked as a dependency in your `uv.lock`, you can point `version-file` at the
lockfile to install the exact pinned version. This keeps CI runs deterministic and avoids
silently picking up a newer uv until the lockfile is updated.
```yaml
- name: Install uv based on the version locked in uv.lock
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1
with:
version-file: "uv.lock"
```
+27 -29
View File
@@ -23,7 +23,7 @@ The computed cache key is available as the `cache-key` output:
```yaml ```yaml
- name: Setup uv - name: Setup uv
id: setup-uv id: setup-uv
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
- name: Print cache key - name: Print cache key
@@ -33,15 +33,12 @@ The computed cache key is available as the `cache-key` output:
## Enable caching ## Enable caching
> [!NOTE] > [!NOTE]
> The entire uv cache is uploaded to the GitHub Actions cache by default. To reduce the cache size, > The cache is pruned before it is uploaded to the GitHub Actions cache. This can lead to
> see [Enable cache pruning](#enable-cache-pruning). > a small or empty cache. See [Disable cache pruning](#disable-cache-pruning) for more details.
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 uploaded 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.
With the default `enable-cache: auto`, caching is enabled on GitHub-hosted runners except for Caching is enabled by default on GitHub-hosted runners.
`release`, tag push, `pull_request_target`, and `workflow_run` events. Caching is disabled for these
events to prevent insecure or release-sensitive jobs from restoring potentially poisoned caches.
Set `enable-cache: true` to explicitly enable caching for any event.
> [!TIP] > [!TIP]
> >
@@ -53,7 +50,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@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
cache-suffix: "optional-suffix" cache-suffix: "optional-suffix"
@@ -92,7 +89,7 @@ changes. If you use relative paths, they are relative to the working directory.
```yaml ```yaml
- name: Define a cache dependency glob - name: Define a cache dependency glob
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
cache-dependency-glob: "**/pyproject.toml" cache-dependency-glob: "**/pyproject.toml"
@@ -100,7 +97,7 @@ changes. If you use relative paths, they are relative to the working directory.
```yaml ```yaml
- name: Define a list of cache dependency globs - name: Define a list of cache dependency globs
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
cache-dependency-glob: | cache-dependency-glob: |
@@ -110,7 +107,7 @@ changes. If you use relative paths, they are relative to the working directory.
```yaml ```yaml
- name: Define an absolute cache dependency glob - name: Define an absolute cache dependency glob
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
cache-dependency-glob: "/tmp/my-folder/requirements*.txt" cache-dependency-glob: "/tmp/my-folder/requirements*.txt"
@@ -118,7 +115,7 @@ changes. If you use relative paths, they are relative to the working directory.
```yaml ```yaml
- name: Never invalidate the cache - name: Never invalidate the cache
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
cache-dependency-glob: "" cache-dependency-glob: ""
@@ -131,7 +128,7 @@ By default, the cache will be restored.
```yaml ```yaml
- name: Don't restore an existing cache - name: Don't restore an existing cache
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
restore-cache: false restore-cache: false
@@ -145,7 +142,7 @@ By default, the cache will be saved.
```yaml ```yaml
- name: Don't save the cache after the run - name: Don't save the cache after the run
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
save-cache: false save-cache: false
@@ -171,34 +168,35 @@ It defaults to `setup-uv-cache` in the `TMP` dir, `D:\a\_temp\setup-uv-cache` on
```yaml ```yaml
- name: Define a custom uv cache path - name: Define a custom uv cache path
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
cache-local-path: "/path/to/cache" cache-local-path: "/path/to/cache"
``` ```
## Enable cache pruning ## Disable cache pruning
By default, the entire uv cache is persisted across runs. On GitHub-hosted runners, it's typically By default, the uv cache is pruned after every run, removing pre-built wheels, but retaining any
faster to prune the cache before saving it, removing pre-built wheels, but retaining any wheels that wheels that were built from source. On GitHub-hosted runners, it's typically faster to omit those
were built from source. The pre-built wheels are then re-downloaded from the registry on each run. pre-built wheels from the cache (and instead re-download them from the registry on each run).
See the [documentation](https://docs.astral.sh/uv/concepts/cache/#caching-in-continuous-integration) However, on self-hosted or local runners, preserving the cache may be more efficient. See
for more information. the [documentation](https://docs.astral.sh/uv/concepts/cache/#caching-in-continuous-integration) for
more information.
If you want to prune the cache before saving it, enable cache pruning with the `prune-cache` input. If you want to persist the entire cache across runs, disable cache pruning with the `prune-cache`
input.
```yaml ```yaml
- name: Prune the cache before saving it - name: Don't prune the cache before saving it
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
prune-cache: true prune-cache: false
``` ```
## Cache Python installs ## Cache Python installs
By default, the Python install dir (`uv python dir` / `UV_PYTHON_INSTALL_DIR`) is not cached, By default, the Python install dir (`uv python dir` / `UV_PYTHON_INSTALL_DIR`) is not cached,
for the same reason that pruning the dependency cache can improve performance on GitHub-hosted for the same reason that the dependency cache is pruned.
runners.
If you want to cache Python installs along with your dependencies, set the `cache-python` input to `true`. If you want to cache Python installs along with your dependencies, set the `cache-python` input to `true`.
Note that this only caches Python versions that uv actually installs into `UV_PYTHON_INSTALL_DIR` Note that this only caches Python versions that uv actually installs into `UV_PYTHON_INSTALL_DIR`
@@ -207,7 +205,7 @@ To force managed Python installs, set `UV_PYTHON_PREFERENCE=only-managed`.
```yaml ```yaml
- name: Cache Python installs - name: Cache Python installs
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
cache-python: true cache-python: true
@@ -225,7 +223,7 @@ If you want to ignore this, set the `ignore-nothing-to-cache` input to `true`.
```yaml ```yaml
- name: Ignore nothing to cache - name: Ignore nothing to cache
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
enable-cache: true enable-cache: true
ignore-nothing-to-cache: true ignore-nothing-to-cache: true
+3 -3
View File
@@ -10,7 +10,7 @@ are automatically verified by this action. The sha256 hashes can be found on the
```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@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
version: "0.3.1" version: "0.3.1"
checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8" checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8"
@@ -39,7 +39,7 @@ The `archive_format` field is currently ignored.
```yaml ```yaml
- name: Use a custom manifest file - name: Use a custom manifest file
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
manifest-file: "https://example.com/my-custom-manifest.ndjson" manifest-file: "https://example.com/my-custom-manifest.ndjson"
``` ```
@@ -58,7 +58,7 @@ You can disable this by setting the `add-problem-matchers` input to `false`.
```yaml ```yaml
- name: Install the latest version of uv without problem matchers - name: Install the latest version of uv without problem matchers
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
add-problem-matchers: false add-problem-matchers: false
``` ```
+9 -10
View File
@@ -9,7 +9,7 @@ This allows directly using it in later steps:
```yaml ```yaml
- name: Install the latest version of uv and activate the environment - name: Install the latest version of uv and activate the environment
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
activate-environment: true activate-environment: true
- run: uv pip install pip - run: uv pip install pip
@@ -20,7 +20,7 @@ By default, the venv is created at `.venv` inside the `working-directory`.
You can customize the venv location with `venv-path`, for example to place it in the runner temp directory: You can customize the venv location with `venv-path`, for example to place it in the runner temp directory:
```yaml ```yaml
- uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 - uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
activate-environment: true activate-environment: true
venv-path: ${{ runner.temp }}/custom-venv venv-path: ${{ runner.temp }}/custom-venv
@@ -51,7 +51,7 @@ 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@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
github-token: ${{ secrets.CUSTOM_GITHUB_TOKEN }} github-token: ${{ secrets.CUSTOM_GITHUB_TOKEN }}
``` ```
@@ -69,7 +69,7 @@ input:
```yaml ```yaml
- name: Install the latest version of uv with a custom tool dir - name: Install the latest version of uv with a custom tool dir
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
tool-dir: "/path/to/tool/dir" tool-dir: "/path/to/tool/dir"
``` ```
@@ -88,7 +88,7 @@ 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@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
tool-bin-dir: "/path/to/tool-bin/dir" tool-bin-dir: "/path/to/tool-bin/dir"
``` ```
@@ -105,7 +105,7 @@ This action supports expanding the `~` character to the user's home directory fo
```yaml ```yaml
- name: Expand the tilde character - name: Expand the tilde character
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
cache-local-path: "~/path/to/cache" cache-local-path: "~/path/to/cache"
tool-dir: "~/path/to/tool/dir" tool-dir: "~/path/to/tool/dir"
@@ -122,7 +122,7 @@ If you want to ignore this, set the `ignore-empty-workdir` input to `true`.
```yaml ```yaml
- name: Ignore empty workdir - name: Ignore empty workdir
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
ignore-empty-workdir: true ignore-empty-workdir: true
``` ```
@@ -131,7 +131,7 @@ If you want to ignore this, set the `ignore-empty-workdir` input to `true`.
This action sets several environment variables that influence uv's behavior and can be used by subsequent steps: This action sets several environment variables that influence uv's behavior and can be used by subsequent steps:
- `UV_PYTHON`: Set when `python-version` is specified or the selected `.tool-versions` file contains a supported `python` entry. Controls which Python version uv uses. - `UV_PYTHON`: Set when `python-version` input is specified. Controls which Python version uv uses.
- `UV_CACHE_DIR`: Set when caching is enabled (unless already configured in uv config files). Controls where uv stores its cache. - `UV_CACHE_DIR`: Set when caching is enabled (unless already configured in uv config files). Controls where uv stores its cache.
- `UV_TOOL_DIR`: Set when `tool-dir` input is specified. Controls where uv installs tool environments. - `UV_TOOL_DIR`: Set when `tool-dir` input is specified. Controls where uv installs tool environments.
- `UV_TOOL_BIN_DIR`: Set when `tool-bin-dir` input is specified. Controls where uv installs tool binaries. - `UV_TOOL_BIN_DIR`: Set when `tool-bin-dir` input is specified. Controls where uv installs tool binaries.
@@ -142,11 +142,10 @@ This action sets several environment variables that influence uv's behavior and
- `UV_NO_MODIFY_PATH`: If set, prevents the action from modifying PATH. Cannot be used with `activate-environment`. - `UV_NO_MODIFY_PATH`: If set, prevents the action from modifying PATH. Cannot be used with `activate-environment`.
- `UV_CACHE_DIR`: If already set, the action will respect it instead of setting its own cache directory. - `UV_CACHE_DIR`: If already set, the action will respect it instead of setting its own cache directory.
- `UV_PYTHON`: If already set and `python-version` is not specified, the action will respect it instead of using the `python` entry from `.tool-versions`.
```yaml ```yaml
- name: Example using environment variables - name: Example using environment variables
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with: with:
python-version: "3.12" python-version: "3.12"
tool-dir: "/custom/tool/dir" tool-dir: "/custom/tool/dir"
-81
View File
@@ -1,81 +0,0 @@
# setup-uv Repository Threat Model
## Overview
`setup-uv` is a GitHub Action that installs or reuses `uv`, modifies `PATH` and the environment for later steps, may execute a discovered Python interpreter, may create or clear a virtual environment, and may restore or save caches. It may use `github-token` to authenticate GitHub downloads; it requires no OIDC credential or additional workflow secret.
The consumer runtime is the selected ref's committed action metadata, bundles, and runner-interpreted companion files; source alone is not evidence of shipped behavior. Privileged automation that generates, updates, or publishes those artifacts is also in scope.
The assets are job credentials; integrity of installed executables, interpreter, environment, checkout, runner, artifacts, and caches; isolation between jobs sharing caches or persistent runners; integrity of published action refs; and workflow compute/storage availability.
Material failures are unauthorized executable selection, credential disclosure, premature execution of lower-authority content, filesystem escape or destructive path use, cross-authority cache/runner persistence, and unauthorized publication.
## Threat Model, Trust Boundaries, and Assumptions
### Authority and trust boundaries
| Actor or input | Trust decision |
|---|---|
| Maintainers, repository/configuration administrators, and GitHub infrastructure | Trusted roots for source, bundles, workflows, refs, rulesets, environments, runner protocol, hosted isolation, and cache service. A lower-authority path into these roots is in scope; their compromise alone is not a repository bug. |
| Consumer workflow authors and runner operators | Control the action ref, trigger, runner, permissions, secrets, proxy, environment, inputs, paths, globs, and custom sources. These are trusted choices unless derived from lower-authority event data. Selecting a custom manifest delegates metadata and executable authority; selecting a path authorizes normal operations on it and intended referents. |
| Selected checkout, project authors, and pull-request contributors | The consumer delegates project/version files, interpreter discovery state, virtual environments, symlinks, cache inputs, and code execution within `setup-uv`'s process environment. Checkout-controlled behavior is trusted unless it overrides an explicit workflow choice or crosses an independent cache, runner, remote, or publication boundary. |
| Remote metadata and artifacts | Default official endpoints, TLS roots, and an operator proxy are trusted mutable authorities. A custom manifest authorizes its URLs and hashes; a hash supplied by that same authority detects corruption, not malice. |
| Cache and runner-state producers/consumers | Same-principal state is trusted by default. Integrity attacks require a lower-authority producer and higher-authority consumer. Confidentiality can flow the opposite way because lower-authority refs may read eligible higher-authority caches. Shared self-hosted state creates a boundary only when principals and authority differ. |
| GitHub-managed automation | Dependency, coding-agent, and review workflows may exist outside the committed tree. Treat them as external principals and obtain their effective trigger, actor, token, environment, ref, and write/secret authority from live evidence. |
### Assumptions
- Running the selected `uv` and checkout-selected Python interpreters is intended. Project execution is out of scope unless it bypasses an explicit workflow choice or crosses an independent cache, runner, remote, or publication boundary.
- Mutable official manifests, ranges, `latest`, and unprotected refs are not attacker control. A protected ref or independent checksum matters only if the selected bundle actually enforces it.
- Same-user changes to paths, environment, proxies, or tool/cache state are not separate attacks. Demonstrate a cross-principal or lower-to-higher boundary.
- Content merged through a trust path that can also merge executable code is not a lower-authority source; require a narrower writer or post-review mutation path.
- Running `setup-uv` on an untrusted checkout with higher authority is a consumer trust decision; checkout-selected code may inherit the action environment.
- Authorized paths include expected symlink/junction referents. Absolute paths and paths outside the workspace are supported; an escape requires independent control crossing an unauthorized boundary.
- Hosted runners are assumed ephemeral and isolated. Persistence or hostile co-tenancy on self-hosted runners must be demonstrated.
- Branch/tag rules, environments, token defaults, cache visibility, fork policy, dynamic workflows, and runner allocation are external state. Re-query required approvals/checks, bypass actors, tag movement, deployment reviewers/principals, release targets, and effective permissions for each attack path.
- Web-application classes such as sessions, CSRF, XSS, SQL injection, and tenant isolation are not applicable.
### Security invariants
1. **Published runtime:** review `action.yml`, committed `dist/*.cjs`, and runner-interpreted shipped files; source-only fixes do not protect consumers.
2. **Executable identity:** precedence is workflow version, version file, project configuration, then `latest`. Manifest authority, platform, variant, URL, checksum, mirror fallback, extraction, and cache placement must bind the intended artifact. A tool-cache hit bypasses download validation and depends on cache provenance.
3. **Credential recipients:** tokens and URL credentials may reach only workflow-authorized origins, redirects, paths, and logs. Metadata authority does not imply token-recipient authority.
4. **Executable boundaries:** checkout-selected interpreters are authorized by default. Explicit workflow selections must win, and independent cache, runner, or remote state must not substitute executables or gain additional authority.
5. **Paths and action channels:** path/environment changes, virtual-environment clearing, outputs, state, and problem matchers must affect only authorized targets and keep untrusted values as data.
6. **Cache boundaries:** keys, scope, restore paths, and executable content must prevent lower-to-higher poisoning; cache contents and post-action path re-resolution must prevent higher-to-lower disclosure, destructive pruning, or persistence.
7. **Workflow and release authority:** unreviewed code or mutable tooling must not acquire write, secret, OIDC, artifact, deployment, tag, or publication authority. Only the intended reviewed bundles and commit may be released.
8. **Availability:** independently controlled manifests, archives, globs, traversal, and caches must stay within the accepted one-job resource-failure model.
### Finding gate
Before reporting, identify the attacker and victim principals; exact controlled input; scanned action and checkout refs; runtime reachability in committed bundles; effective token, secrets/OIDC, environment gates, cache scope, and runner persistence; applicable defaults and opt-ins; validation performed or skipped; declared trust roots; baseline versus incremental capability; and concrete impact. Reproduce platform-specific behavior and distinguish the scanned ref from other versions.
A report must demonstrate independent attacker control, a violated guarantee, committed-runtime reachability, incremental capability, and practical impact; otherwise it is not a security finding and should not be reported as one.
## Attack Surface, Mitigations, and Attacker Stories
| Surface | Security-relevant behavior and controls | Reportable attacker story |
|---|---|---|
| Published action and build/release supply chain | Consumers execute committed bundles and embedded dependencies. Verify source/bundle alignment, lockfile integrity, dependency-install policy, reproducible/generated-diff checks, immutable action pins, branch enforcement, and publication target checks. | A lower-authority contributor or dependency changes shipped code, or release automation publishes a different commit, by bypassing an effective review, branch, or release control. |
| Version, manifest, proxy, and network selection | Project files may select an official version by documented precedence. Custom manifests may select URLs, hashes, variants, and platforms and may reach arbitrary network locations. Parsing should reject malformed, ambiguous, unsupported, or incorrectly typed records; verify HTTPS, time/size bounds, proxy behavior, and selected-ref defaults. | Lower-authority event/project data violates a promised fixed version, escapes the selected manifest, probes runner-only services, causes material resource use, selects attacker bytes, or redirects later credentials. Operator selection of a custom authority is not itself a finding. |
| Artifact URL, token, checksum, extraction, and tool cache | Mirror fallback must preserve identity and checksum policy. Origin gating should restrict tokens; redirect handling should strip authorization across unauthorized hosts and reject downgrade. Verify checksum precedence and reject missing/empty hashes when policy requires validation. Independent hashes must precede extraction. Native helpers come from `PATH`; tool-cache hits skip network/hash validation. | An attacker receives a usable token outside delegated authority, bypasses an independent pin, exploits archive/link traversal, substitutes the cached executable, or poisons shared tool state later executed with higher authority. Same-authority manifest hashes and same-user cache changes do not establish the boundary. |
| Interpreter, PATH, virtual environment, and action channels | Checkout-selected interpreters, virtual environments, paths, symlinks, and helpers are delegated project authority. Explicit workflow choices must bind; the action also changes later-step paths/environment, emits state/outputs, invokes native helpers, and consumes cache/runner state. | Independent cache, runner, or remote content substitutes an executable; an explicit workflow choice is bypassed; or action channels cross an authority boundary. Same-checkout interpreter, path, and helper effects are not findings. |
| GitHub uv/Python caches and post action | Cache keys should partition platform, interpreter, dependency, and policy state and restore without unsafe fallback. Determine cache defaults, visibility, and the exact hit/miss path from the selected ref and GitHub policy; an exact hit may suppress post save/prune. Post processing re-reads inputs/config/environment and may save re-resolved uv or Python paths. | A lower producer supplies executable content to a higher consumer; a higher producer exposes private data to a lower cache reader; or a later successful step retargets a cache miss toward sensitive files, destructive pruning, or cross-job persistence. Existing equal-authority code with the same secrets often gains no new confidentiality. |
| CI, updater, dynamic automation, and release workflows | PR workflows intentionally execute contributor code. Verify effective permissions, fork behavior, credential persistence, mutable tooling, security-upload authority, and whether checks are required. Updaters convert remote data into source under write authority. Distinguish ruleset-required deployment from human review present only in a workflow DAG. | Unreviewed code gains write/secret/OIDC/artifact authority; remote metadata becomes executable generated source; a dynamic workflow has unexpected authority; or an actor satisfies a deployment/tag rule without the intended review and publishes a malicious ref. |
| Availability and logging | Manifests, version enumeration, archives, globs, hashing, caches, and remote strings can consume resources or influence logs. Verify size/count/expansion bounds, timeouts, retries, top-level error handling, and that parsing never executes data. | Independently controlled input causes reliable material workflow cost, disk/memory exhaustion, or meaningful log/output manipulation. A bounded one-job failure or operator-selected broad input is usually Low or correctness. |
| Lower-priority classes | Shell injection is constrained where child execution uses argv, but workflow shell blocks still require quoting review. Prototype pollution requires a dangerous merge/sink. Secret-shaped strings require proof of a genuine usable secret. Documentation drift, range surprises, malformed trusted config, and test-only code normally lack a security boundary. | Report only when a concrete lower-authority value reaches an execution, credential, persistent-state, publication, or material-availability sink. |
## Severity Calibration (Critical, High, Medium, Low)
Severity follows the complete attack graph and incremental capability, not the presence of words such as token, checksum, cache, manifest, archive, Python, PATH, release, or OIDC.
| Severity | Threshold | Representative examples |
|---|---|---|
| **Critical** | A low-prerequisite remote/lower-authority attacker compromises default distribution or installation across many consumers, publishes trusted malicious action artifacts, or gains broad credentials/runner control under safe defaults without first compromising a declared trust root. | Bypass an effective hash/origin control to distribute an automatically executed malicious binary at scale; reach publication authority to ship malicious bundles or move trusted refs without required approval; exploit default-accepted archive content for host overwrite or cross-job execution across hosted runners. |
| **High** | A demonstrated lower-authority input crosses an execution, confidentiality, integrity, or persistence boundary in a privileged job and gains substantial capability. | Independent shared-state interpreter substitution in a write/OIDC release job; shared cache poisoning later executed with secrets; high-value cache disclosure to an untrusted ref; usable write-token disclosure; independent-pin bypass; archive/cache escape into sensitive state. |
| **Medium** | A real but constrained crossing causes limited credential/filesystem impact, reliable remote denial of service, scoped persistence, or premature execution in a realistic uncommon configuration. | Limited executable substitution from independent cache/runner state in a read-only job; same-repository cache confusion or disclosure; reliable hosted-runner exhaustion; disclosure of a usable read-only private token; output manipulation without publication or high-value credentials. |
| **Low** | A genuine weak boundary causes narrow disclosure, log/annotation spoofing, defense-in-depth weakness, exotic cache aliasing without a privileged consumer, or limited waste. | Confusing logs with no execution effect; bounded job failure; limited overwrite of nonexecuted cache data; disclosure of a path/URL without private data or follow-on capability. |
Trust-root compromise may have Critical impact but is not a repository Critical without a lower-authority path into that root or an independent control that should have survived. High requires exact trigger, refs, effective authority, sink, and committed runtime; it cannot rely only on a trusted operator choosing malicious inputs, same-user state changes, or code already intentionally executed with equal authority. A separate privileged consumer, broad secret, persistent trusted state, publication path, or cross-repository boundary can raise Medium to High.
Normally non-reportable without additional evidence: expected mutability of ranges, `latest`, official/custom sources, or unprotected refs; documented project version selection; checkout-selected interpreters, paths, virtual environments, symlinks, and helpers; deliberate operator selection of manifests, proxies, checksums, or paths; same-principal cache/path changes; requested `uv` or dependency execution; trusted-runner `PATH` lookup; test/developer-only code without a shipped or privileged-workflow path; behavior fixed in the scanned ref; and correctness/compatibility/documentation issues without incremental confidentiality, integrity, persistence, or availability impact.
+1323 -1512
View File
File diff suppressed because it is too large Load Diff
+15 -25
View File
@@ -5,16 +5,6 @@
"type": "module", "type": "module",
"description": "Set up your GitHub Actions workflow with a specific version of uv", "description": "Set up your GitHub Actions workflow with a specific version of uv",
"main": "dist/setup/index.cjs", "main": "dist/setup/index.cjs",
"engines": {
"npm": ">=11.10.0"
},
"devEngines": {
"packageManager": {
"name": "npm",
"version": ">=11.10.0",
"onFail": "error"
}
},
"scripts": { "scripts": {
"build": "tsc --noEmit", "build": "tsc --noEmit",
"check": "biome check --write", "check": "biome check --write",
@@ -22,7 +12,7 @@
"test:unit": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js", "test:unit": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js",
"test": "npm run build && npm run test:unit", "test": "npm run build && npm run test:unit",
"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_versions node dist/update-known-checksums/index.cjs src/download/checksum/known-checksums.json", "update-known-checksums": "RUNNER_TEMP=known_versions node dist/update-known-checksums/index.cjs src/download/checksum/known-checksums.ts",
"all": "npm run build && npm run check && npm run package && npm run test:unit" "all": "npm run build && npm run check && npm run package && npm run test:unit"
}, },
"repository": { "repository": {
@@ -38,26 +28,26 @@
"author": "@eifinger", "author": "@eifinger",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/cache": "^6.2.0", "@actions/cache": "^6.0.0",
"@actions/core": "^3.0.0", "@actions/core": "^3.0.0",
"@actions/exec": "^3.0.0", "@actions/exec": "^3.0.0",
"@actions/glob": "^0.7.0", "@actions/glob": "^0.6.1",
"@actions/io": "^3.0.2", "@actions/io": "^3.0.2",
"@actions/tool-cache": "^4.0.0", "@actions/tool-cache": "^4.0.0",
"@renovatebot/pep440": "^5.0.0", "@renovatebot/pep440": "^4.2.2",
"smol-toml": "^1.7.1", "smol-toml": "^1.6.0",
"undici": "^8.10.0" "undici": "^7.24.2"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "^2.5.7", "@biomejs/biome": "^2.4.7",
"@types/js-yaml": "^4.0.9", "@types/js-yaml": "^4.0.9",
"@types/node": "^26.1.2", "@types/node": "^25.5.0",
"@types/semver": "^7.8.0", "@types/semver": "^7.7.1",
"@vercel/ncc": "^0.44.1", "@vercel/ncc": "^0.38.4",
"esbuild": "^0.28.1", "esbuild": "^0.27.4",
"jest": "^30.4.2", "jest": "^30.3.0",
"js-yaml": "^5.2.3", "js-yaml": "^4.1.1",
"ts-jest": "^29.4.11", "ts-jest": "^29.4.6",
"typescript": "^6.0.3" "typescript": "^5.9.3"
} }
} }
+9 -12
View File
@@ -2,7 +2,6 @@ import * as cache from "@actions/cache";
import * as core from "@actions/core"; import * as core from "@actions/core";
import { hashFiles } from "../hash/hash-files"; import { hashFiles } from "../hash/hash-files";
import type { SetupInputs } from "../utils/inputs"; import type { SetupInputs } from "../utils/inputs";
import * as log from "../utils/logging";
import { getArch, getOSNameVersion, getPlatform } from "../utils/platforms"; import { getArch, getOSNameVersion, getPlatform } from "../utils/platforms";
export const STATE_CACHE_KEY = "cache-key"; export const STATE_CACHE_KEY = "cache-key";
@@ -20,7 +19,7 @@ export async function restoreCache(
core.setOutput("cache-key", cacheKey); core.setOutput("cache-key", cacheKey);
if (!inputs.restoreCache) { if (!inputs.restoreCache) {
log.info("restore-cache is false. Skipping restore cache step."); core.info("restore-cache is false. Skipping restore cache step.");
core.setOutput("python-cache-hit", false); core.setOutput("python-cache-hit", false);
return; return;
} }
@@ -56,7 +55,7 @@ async function restoreCacheFromKey(
stateKey: string, stateKey: string,
outputKey: string, outputKey: string,
): Promise<void> { ): Promise<void> {
log.info( core.info(
`Trying to restore cache from GitHub Actions cache with key: ${cacheKey}`, `Trying to restore cache from GitHub Actions cache with key: ${cacheKey}`,
); );
let matchedKey: string | undefined; let matchedKey: string | undefined;
@@ -64,7 +63,7 @@ async function restoreCacheFromKey(
matchedKey = await cache.restoreCache([cachePath], cacheKey); matchedKey = await cache.restoreCache([cachePath], cacheKey);
} catch (err) { } catch (err) {
const message = (err as Error).message; const message = (err as Error).message;
log.warning(message); core.warning(message);
core.setOutput(outputKey, false); core.setOutput(outputKey, false);
return; return;
} }
@@ -78,7 +77,7 @@ async function computeKeys(
): Promise<string> { ): Promise<string> {
let cacheDependencyPathHash = "-"; let cacheDependencyPathHash = "-";
if (inputs.cacheDependencyGlob !== "") { if (inputs.cacheDependencyGlob !== "") {
log.info( core.info(
`Searching files using cache dependency glob: ${inputs.cacheDependencyGlob.split("\n").join(",")}`, `Searching files using cache dependency glob: ${inputs.cacheDependencyGlob.split("\n").join(",")}`,
); );
cacheDependencyPathHash += await hashFiles( cacheDependencyPathHash += await hashFiles(
@@ -86,7 +85,7 @@ async function computeKeys(
true, true,
); );
if (cacheDependencyPathHash === "-") { if (cacheDependencyPathHash === "-") {
log.warning( core.warning(
`No file matched to [${inputs.cacheDependencyGlob.split("\n").join(",")}]. The cache will never get invalidated. Make sure you have checked out the target repository and configured the cache-dependency-glob input correctly.`, `No file matched to [${inputs.cacheDependencyGlob.split("\n").join(",")}]. The cache will never get invalidated. Make sure you have checked out the target repository and configured the cache-dependency-glob input correctly.`,
); );
} }
@@ -94,10 +93,8 @@ async function computeKeys(
if (cacheDependencyPathHash === "-") { if (cacheDependencyPathHash === "-") {
cacheDependencyPathHash = "-no-dependency-glob"; cacheDependencyPathHash = "-no-dependency-glob";
} }
const suffix = inputs.cacheSuffix const suffix = inputs.cacheSuffix ? `-${inputs.cacheSuffix}` : "";
? `-${encodeURIComponent(inputs.cacheSuffix)}` const version = pythonVersion ?? "unknown";
: "";
const version = encodeURIComponent(pythonVersion ?? "unknown");
const platform = await getPlatform(); const platform = await getPlatform();
const osNameVersion = getOSNameVersion(); const osNameVersion = getOSNameVersion();
const pruned = inputs.pruneCache ? "-pruned" : ""; const pruned = inputs.pruneCache ? "-pruned" : "";
@@ -112,12 +109,12 @@ function handleMatchResult(
outputKey: string, outputKey: string,
): void { ): void {
if (!matchedKey) { if (!matchedKey) {
log.info(`No GitHub Actions cache found for key: ${primaryKey}`); core.info(`No GitHub Actions cache found for key: ${primaryKey}`);
core.setOutput(outputKey, false); core.setOutput(outputKey, false);
return; return;
} }
core.saveState(stateKey, matchedKey); core.saveState(stateKey, matchedKey);
log.info(`cache restored from GitHub Actions cache with key: ${matchedKey}`); core.info(`cache restored from GitHub Actions cache with key: ${matchedKey}`);
core.setOutput(outputKey, true); core.setOutput(outputKey, true);
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-23
View File
@@ -1,23 +0,0 @@
import * as semver from "semver";
import { KNOWN_CHECKSUMS } from "./known-checksums";
const VERSION_IN_CHECKSUM_KEY_PATTERN =
/-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/;
export function getLatestKnownVersion(): string {
const versions = new Set<string>();
for (const key of Object.keys(KNOWN_CHECKSUMS)) {
const version = key.match(VERSION_IN_CHECKSUM_KEY_PATTERN)?.[1];
if (version !== undefined) {
versions.add(version);
}
}
const latestVersion = [...versions].sort(semver.rcompare)[0];
if (!latestVersion) {
throw new Error("Could not determine latest known version from checksums.");
}
return latestVersion;
}
@@ -19,7 +19,16 @@ export async function updateChecksums(
deduplicatedEntries.set(entry.key, entry.checksum); deduplicatedEntries.set(entry.key, entry.checksum);
} }
const content = `${JSON.stringify(Object.fromEntries(deduplicatedEntries), null, 2)}\n`; const body = [...deduplicatedEntries.entries()]
.map(([key, checksum]) => ` "${key}":\n "${checksum}"`)
.join(",\n");
const content =
"// AUTOGENERATED_DO_NOT_EDIT\n" +
"export const KNOWN_CHECKSUMS: { [key: string]: string } = {\n" +
body +
(body === "" ? "" : ",\n") +
"};\n";
await fs.writeFile(filePath, content); await fs.writeFile(filePath, content);
} }
+4 -8
View File
@@ -8,7 +8,6 @@ import {
TOOL_CACHE_NAME, TOOL_CACHE_NAME,
VERSIONS_MANIFEST_URL, VERSIONS_MANIFEST_URL,
} from "../utils/constants"; } from "../utils/constants";
import * as log from "../utils/logging";
import type { Architecture, Platform } from "../utils/platforms"; import type { Architecture, Platform } from "../utils/platforms";
import { validateChecksum } from "./checksum/checksum"; import { validateChecksum } from "./checksum/checksum";
import { getArtifact } from "./manifest"; import { getArtifact } from "./manifest";
@@ -37,7 +36,6 @@ export async function downloadVersion(
checksum: string | undefined, checksum: string | undefined,
githubToken: string, githubToken: string,
manifestUrl?: string, manifestUrl?: string,
downloadFromAstralMirror = true,
): Promise<{ version: string; cachedToolDir: string }> { ): Promise<{ version: string; cachedToolDir: string }> {
const artifact = await getArtifact(version, arch, platform, manifestUrl); const artifact = await getArtifact(version, arch, platform, manifestUrl);
@@ -54,9 +52,7 @@ export async function downloadVersion(
? checksum ? checksum
: resolveChecksum(checksum, artifact.checksum); : resolveChecksum(checksum, artifact.checksum);
const mirrorUrl = downloadFromAstralMirror const mirrorUrl = rewriteToMirror(artifact.downloadUrl);
? rewriteToMirror(artifact.downloadUrl)
: undefined;
const downloadUrl = mirrorUrl ?? artifact.downloadUrl; const downloadUrl = mirrorUrl ?? artifact.downloadUrl;
try { try {
@@ -74,7 +70,7 @@ export async function downloadVersion(
throw err; throw err;
} }
log.warning( core.warning(
`Failed to download from mirror, falling back to GitHub Releases: ${(err as Error).message}`, `Failed to download from mirror, falling back to GitHub Releases: ${(err as Error).message}`,
); );
@@ -124,7 +120,7 @@ async function downloadArtifact(
checksum: string | undefined, checksum: string | undefined,
githubToken: string | undefined, githubToken: string | undefined,
): Promise<{ version: string; cachedToolDir: string }> { ): Promise<{ version: string; cachedToolDir: string }> {
log.info(`Downloading uv from "${downloadUrl}" ...`); core.info(`Downloading uv from "${downloadUrl}" ...`);
const downloadPath = await tc.downloadTool( const downloadPath = await tc.downloadTool(
downloadUrl, downloadUrl,
undefined, undefined,
@@ -140,7 +136,7 @@ async function downloadArtifact(
// so this may fail if another tar, like gnu tar, ends up being used. // so this may fail if another tar, like gnu tar, ends up being used.
uvDir = await tc.extractTar(downloadPath, undefined, "x"); uvDir = await tc.extractTar(downloadPath, undefined, "x");
} catch (err) { } catch (err) {
log.info( core.info(
`Extracting with tar failed, falling back to zip extraction: ${(err as Error).message}`, `Extracting with tar failed, falling back to zip extraction: ${(err as Error).message}`,
); );
const extension = getExtension(platform); const extension = getExtension(platform);
+40 -168
View File
@@ -1,9 +1,6 @@
import { createInterface } from "node:readline";
import { Readable } from "node:stream";
import * as core from "@actions/core"; import * as core from "@actions/core";
import { VERSIONS_MANIFEST_URL } from "../utils/constants"; import { VERSIONS_MANIFEST_URL } from "../utils/constants";
import { fetch } from "../utils/fetch"; import { fetch } from "../utils/fetch";
import * as log from "../utils/logging";
import { selectDefaultVariant } from "./variant-selection"; import { selectDefaultVariant } from "./variant-selection";
export interface ManifestArtifact { export interface ManifestArtifact {
@@ -25,27 +22,28 @@ export interface ArtifactResult {
downloadUrl: string; downloadUrl: string;
} }
interface CachedManifest { const cachedManifestData = new Map<string, ManifestVersion[]>();
complete: boolean;
versions: ManifestVersion[];
}
const cachedManifestData = new Map<string, CachedManifest>();
export const MANIFEST_FETCH_ATTEMPTS = 3;
export async function fetchManifest( export async function fetchManifest(
manifestUrl: string = VERSIONS_MANIFEST_URL, manifestUrl: string = VERSIONS_MANIFEST_URL,
): Promise<ManifestVersion[]> { ): Promise<ManifestVersion[]> {
const cachedManifest = cachedManifestData.get(manifestUrl); const cachedVersions = cachedManifestData.get(manifestUrl);
if (cachedManifest?.complete === true) { if (cachedVersions !== undefined) {
core.debug(`Using cached manifest data from ${manifestUrl}`); core.debug(`Using cached manifest data from ${manifestUrl}`);
return cachedManifest.versions; return cachedVersions;
}
core.info(`Fetching manifest data from ${manifestUrl} ...`);
const response = await fetch(manifestUrl, {});
if (!response.ok) {
throw new Error(
`Failed to fetch manifest data: ${response.status} ${response.statusText}`,
);
} }
const response = await fetchManifestResponse(manifestUrl);
const body = await response.text(); const body = await response.text();
const versions = parseManifest(body, manifestUrl); const versions = parseManifest(body, manifestUrl);
cachedManifestData.set(manifestUrl, { complete: true, versions }); cachedManifestData.set(manifestUrl, versions);
return versions; return versions;
} }
@@ -58,7 +56,11 @@ export function parseManifest(
throw new Error(`Manifest at ${sourceDescription} is empty.`); throw new Error(`Manifest at ${sourceDescription} is empty.`);
} }
rejectLegacyManifest(trimmed, sourceDescription); if (trimmed.startsWith("[")) {
throw new Error(
`Legacy JSON array manifests are no longer supported in ${sourceDescription}. Use the astral-sh/versions manifest format instead.`,
);
}
const versions: ManifestVersion[] = []; const versions: ManifestVersion[] = [];
@@ -68,7 +70,22 @@ export function parseManifest(
continue; continue;
} }
versions.push(parseManifestRecord(record, sourceDescription, index + 1)); let parsed: unknown;
try {
parsed = JSON.parse(record);
} catch (error) {
throw new Error(
`Failed to parse manifest data from ${sourceDescription} at line ${index + 1}: ${(error as Error).message}`,
);
}
if (!isManifestVersion(parsed)) {
throw new Error(
`Invalid manifest record in ${sourceDescription} at line ${index + 1}.`,
);
}
versions.push(parsed);
} }
if (versions.length === 0) { if (versions.length === 0) {
@@ -81,10 +98,7 @@ export function parseManifest(
export async function getLatestVersion( export async function getLatestVersion(
manifestUrl: string = VERSIONS_MANIFEST_URL, manifestUrl: string = VERSIONS_MANIFEST_URL,
): Promise<string> { ): Promise<string> {
const latestVersion = const latestVersion = (await fetchManifest(manifestUrl))[0]?.version;
manifestUrl === VERSIONS_MANIFEST_URL
? (await findManifestVersion(() => true))?.version
: (await fetchManifest(manifestUrl))[0]?.version;
if (latestVersion === undefined) { if (latestVersion === undefined) {
throw new Error("No versions found in manifest data"); throw new Error("No versions found in manifest data");
@@ -94,20 +108,10 @@ export async function getLatestVersion(
return latestVersion; return latestVersion;
} }
// The default manifest is guaranteed to be ordered newest-first:
// https://github.com/astral-sh/versions#format
export async function getFirstMatchingVersion(
predicate: (version: string) => boolean,
): Promise<string | undefined> {
return (
await findManifestVersion((versionData) => predicate(versionData.version))
)?.version;
}
export async function getAllVersions( export async function getAllVersions(
manifestUrl: string = VERSIONS_MANIFEST_URL, manifestUrl: string = VERSIONS_MANIFEST_URL,
): Promise<string[]> { ): Promise<string[]> {
log.info( core.info(
`Getting available versions from ${manifestSource(manifestUrl)} ...`, `Getting available versions from ${manifestSource(manifestUrl)} ...`,
); );
const versions = await fetchManifest(manifestUrl); const versions = await fetchManifest(manifestUrl);
@@ -120,12 +124,10 @@ export async function getArtifact(
platform: string, platform: string,
manifestUrl: string = VERSIONS_MANIFEST_URL, manifestUrl: string = VERSIONS_MANIFEST_URL,
): Promise<ArtifactResult | undefined> { ): Promise<ArtifactResult | undefined> {
const versionData = const versions = await fetchManifest(manifestUrl);
manifestUrl === VERSIONS_MANIFEST_URL const versionData = versions.find(
? await findManifestVersion((candidate) => candidate.version === version) (candidate) => candidate.version === version,
: (await fetchManifest(manifestUrl)).find( );
(candidate) => candidate.version === version,
);
if (!versionData) { if (!versionData) {
core.debug(`Version ${version} not found in manifest ${manifestUrl}`); core.debug(`Version ${version} not found in manifest ${manifestUrl}`);
return undefined; return undefined;
@@ -166,105 +168,6 @@ export function clearManifestCache(manifestUrl?: string): void {
cachedManifestData.delete(manifestUrl); cachedManifestData.delete(manifestUrl);
} }
async function fetchManifestResponse(manifestUrl: string) {
let response: Awaited<ReturnType<typeof fetch>> | undefined;
for (let attempt = 1; attempt <= MANIFEST_FETCH_ATTEMPTS; attempt++) {
log.info(`Fetching manifest data from ${manifestUrl} ...`);
try {
response = await fetch(manifestUrl, {});
break;
} catch (error) {
if (attempt >= MANIFEST_FETCH_ATTEMPTS) {
throw error;
}
const delayMs = 1_000 * 2 ** (attempt - 1);
log.info(`Manifest fetch failed; retrying in ${delayMs}ms ...`);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
if (response === undefined) {
throw new Error("Manifest fetch attempts exhausted.");
}
if (!response.ok) {
throw new Error(
`Failed to fetch manifest data: ${response.status} ${response.statusText}`,
);
}
return response;
}
async function findManifestVersion(
predicate: (versionData: ManifestVersion) => boolean,
): Promise<ManifestVersion | undefined> {
const cachedManifest = cachedManifestData.get(VERSIONS_MANIFEST_URL);
const cachedVersion = cachedManifest?.versions.find(predicate);
if (cachedVersion !== undefined || cachedManifest?.complete === true) {
return cachedVersion;
}
const response = await fetchManifestResponse(VERSIONS_MANIFEST_URL);
if (response.body === null) {
const versions = parseManifest(
await response.text(),
VERSIONS_MANIFEST_URL,
);
cachedManifestData.set(VERSIONS_MANIFEST_URL, {
complete: true,
versions,
});
return versions.find(predicate);
}
const input = Readable.fromWeb(response.body);
const lines = createInterface({ crlfDelay: Number.POSITIVE_INFINITY, input });
const versions: ManifestVersion[] = [];
let complete = false;
let lineNumber = 0;
let matchedVersion: ManifestVersion | undefined;
try {
for await (const line of lines) {
lineNumber += 1;
const record = line.trim();
if (record === "") {
continue;
}
if (versions.length === 0) {
rejectLegacyManifest(record, VERSIONS_MANIFEST_URL);
}
const versionData = parseManifestRecord(
record,
VERSIONS_MANIFEST_URL,
lineNumber,
);
versions.push(versionData);
if (predicate(versionData)) {
matchedVersion = versionData;
break;
}
}
complete = matchedVersion === undefined;
} finally {
lines.close();
if (!complete) {
input.destroy();
}
}
if (versions.length === 0) {
throw new Error(`Manifest at ${VERSIONS_MANIFEST_URL} is empty.`);
}
cachedManifestData.set(VERSIONS_MANIFEST_URL, { complete, versions });
return matchedVersion;
}
function manifestSource(manifestUrl: string): string { function manifestSource(manifestUrl: string): string {
if (manifestUrl === VERSIONS_MANIFEST_URL) { if (manifestUrl === VERSIONS_MANIFEST_URL) {
return VERSIONS_MANIFEST_URL; return VERSIONS_MANIFEST_URL;
@@ -273,37 +176,6 @@ function manifestSource(manifestUrl: string): string {
return `manifest-file ${manifestUrl}`; return `manifest-file ${manifestUrl}`;
} }
function parseManifestRecord(
record: string,
sourceDescription: string,
lineNumber: number,
): ManifestVersion {
let parsed: unknown;
try {
parsed = JSON.parse(record);
} catch (error) {
throw new Error(
`Failed to parse manifest data from ${sourceDescription} at line ${lineNumber}: ${(error as Error).message}`,
);
}
if (!isManifestVersion(parsed)) {
throw new Error(
`Invalid manifest record in ${sourceDescription} at line ${lineNumber}.`,
);
}
return parsed;
}
function rejectLegacyManifest(data: string, sourceDescription: string): void {
if (data.startsWith("[")) {
throw new Error(
`Legacy JSON array manifests are no longer supported in ${sourceDescription}. Use the astral-sh/versions manifest format instead.`,
);
}
}
function isManifestVersion(value: unknown): value is ManifestVersion { function isManifestVersion(value: unknown): value is ManifestVersion {
if (!isRecord(value)) { if (!isRecord(value)) {
return false; return false;
+2 -2
View File
@@ -2,8 +2,8 @@ import * as crypto from "node:crypto";
import * as fs from "node:fs"; import * as fs from "node:fs";
import * as stream from "node:stream"; import * as stream from "node:stream";
import * as util from "node:util"; import * as util from "node:util";
import * as core from "@actions/core";
import { create } from "@actions/glob"; import { create } from "@actions/glob";
import * as log from "../utils/logging";
/** /**
* Hashes files matching the given glob pattern. * Hashes files matching the given glob pattern.
@@ -19,7 +19,7 @@ export async function hashFiles(
): Promise<string> { ): Promise<string> {
const globber = await create(pattern); const globber = await create(pattern);
let hasMatch = false; let hasMatch = false;
const writeDelegate = verbose ? log.info : log.debug; const writeDelegate = verbose ? core.info : core.debug;
const result = crypto.createHash("sha256"); const result = crypto.createHash("sha256");
let count = 0; let count = 0;
for await (const file of globber.globGenerator()) { for await (const file of globber.globGenerator()) {
+12 -31
View File
@@ -10,27 +10,6 @@ import {
} from "./cache/restore-cache"; } from "./cache/restore-cache";
import { STATE_UV_PATH, STATE_UV_VERSION } from "./utils/constants"; import { STATE_UV_PATH, STATE_UV_VERSION } from "./utils/constants";
import { loadInputs, type SetupInputs } from "./utils/inputs"; import { loadInputs, type SetupInputs } from "./utils/inputs";
import * as log from "./utils/logging";
function formatUnexpectedFailure(error: unknown): string {
if (error instanceof Error) {
return error.stack ?? error.message;
}
return String(error);
}
function failUnexpectedly(event: string, error: unknown): never {
core.setFailed(`${event}: ${formatUnexpectedFailure(error)}`);
process.exit(1);
}
process.on("uncaughtException", (error) => {
failUnexpectedly("Uncaught exception", error);
});
process.on("unhandledRejection", (reason) => {
failUnexpectedly("Unhandled promise rejection", reason);
});
export async function run(): Promise<void> { export async function run(): Promise<void> {
try { try {
@@ -39,7 +18,7 @@ export async function run(): Promise<void> {
if (inputs.saveCache) { if (inputs.saveCache) {
await saveCache(inputs); await saveCache(inputs);
} else { } else {
log.info("save-cache is false. Skipping save cache step."); core.info("save-cache is false. Skipping save cache step.");
} }
// https://github.com/nodejs/node/issues/56645#issuecomment-3924958861 // https://github.com/nodejs/node/issues/56645#issuecomment-3924958861
await new Promise((resolve) => setTimeout(resolve, 100)); await new Promise((resolve) => setTimeout(resolve, 100));
@@ -62,11 +41,11 @@ async function saveCache(inputs: SetupInputs): Promise<void> {
const matchedKey = core.getState(STATE_CACHE_MATCHED_KEY); const matchedKey = core.getState(STATE_CACHE_MATCHED_KEY);
if (!cacheKey) { if (!cacheKey) {
log.warning("Error retrieving cache key from state."); core.warning("Error retrieving cache key from state.");
return; return;
} }
if (matchedKey === cacheKey) { if (matchedKey === cacheKey) {
log.info(`Cache hit occurred on key ${cacheKey}, not saving cache.`); core.info(`Cache hit occurred on key ${cacheKey}, not saving cache.`);
} else { } else {
if (inputs.pruneCache) { if (inputs.pruneCache) {
await pruneCache(); await pruneCache();
@@ -75,7 +54,7 @@ async function saveCache(inputs: SetupInputs): Promise<void> {
const actualCachePath = getUvCachePath(inputs); const actualCachePath = getUvCachePath(inputs);
if (!fs.existsSync(actualCachePath)) { if (!fs.existsSync(actualCachePath)) {
if (inputs.ignoreNothingToCache) { if (inputs.ignoreNothingToCache) {
log.info( core.info(
"No cacheable uv cache paths were found. Ignoring because ignore-nothing-to-cache is enabled.", "No cacheable uv cache paths were found. Ignoring because ignore-nothing-to-cache is enabled.",
); );
} else { } else {
@@ -95,7 +74,7 @@ async function saveCache(inputs: SetupInputs): Promise<void> {
if (inputs.cachePython) { if (inputs.cachePython) {
if (!fs.existsSync(inputs.pythonDir)) { if (!fs.existsSync(inputs.pythonDir)) {
log.warning( core.warning(
`Python cache path ${inputs.pythonDir} does not exist on disk. Skipping Python cache save because no managed Python installation was found. If you want uv to install managed Python instead of using a system interpreter, set UV_PYTHON_PREFERENCE=only-managed.`, `Python cache path ${inputs.pythonDir} does not exist on disk. Skipping Python cache save because no managed Python installation was found. If you want uv to install managed Python instead of using a system interpreter, set UV_PYTHON_PREFERENCE=only-managed.`,
); );
return; return;
@@ -122,7 +101,7 @@ async function pruneCache(): Promise<void> {
execArgs.push("--force"); execArgs.push("--force");
} }
log.info("Pruning cache..."); core.info("Pruning cache...");
const uvPath = core.getState(STATE_UV_PATH); const uvPath = core.getState(STATE_UV_PATH);
await exec.exec(uvPath, execArgs, options); await exec.exec(uvPath, execArgs, options);
} }
@@ -137,7 +116,7 @@ function getUvCachePath(inputs: SetupInputs): string {
process.env.UV_CACHE_DIR && process.env.UV_CACHE_DIR &&
process.env.UV_CACHE_DIR !== inputs.cacheLocalPath.path process.env.UV_CACHE_DIR !== inputs.cacheLocalPath.path
) { ) {
log.warning( core.warning(
`The environment variable UV_CACHE_DIR has been changed to "${process.env.UV_CACHE_DIR}", by an action or step running after astral-sh/setup-uv. This can lead to unexpected behavior. If you expected this to happen set the cache-local-path input to "${process.env.UV_CACHE_DIR}" instead of "${inputs.cacheLocalPath.path}".`, `The environment variable UV_CACHE_DIR has been changed to "${process.env.UV_CACHE_DIR}", by an action or step running after astral-sh/setup-uv. This can lead to unexpected behavior. If you expected this to happen set the cache-local-path input to "${process.env.UV_CACHE_DIR}" instead of "${inputs.cacheLocalPath.path}".`,
); );
return process.env.UV_CACHE_DIR; return process.env.UV_CACHE_DIR;
@@ -154,13 +133,15 @@ async function saveCacheToKey(
const matchedKey = core.getState(stateKey); const matchedKey = core.getState(stateKey);
if (matchedKey === cacheKey) { if (matchedKey === cacheKey) {
log.info(`${cacheName} hit occurred on key ${cacheKey}, not saving cache.`); core.info(
`${cacheName} hit occurred on key ${cacheKey}, not saving cache.`,
);
return; return;
} }
log.info(`Including ${cacheName} path: ${cachePath}`); core.info(`Including ${cacheName} path: ${cachePath}`);
await cache.saveCache([cachePath], cacheKey); await cache.saveCache([cachePath], cacheKey);
log.info(`${cacheName} saved with key: ${cacheKey}`); core.info(`${cacheName} saved with key: ${cacheKey}`);
} }
run(); run();
+21 -43
View File
@@ -9,7 +9,6 @@ import {
} from "./download/download-version"; } from "./download/download-version";
import { STATE_UV_PATH, STATE_UV_VERSION } from "./utils/constants"; import { STATE_UV_PATH, STATE_UV_VERSION } from "./utils/constants";
import { CacheLocalSource, loadInputs, type SetupInputs } from "./utils/inputs"; import { CacheLocalSource, loadInputs, type SetupInputs } from "./utils/inputs";
import * as log from "./utils/logging";
import { import {
type Architecture, type Architecture,
getArch, getArch,
@@ -20,26 +19,6 @@ import { resolveUvVersion } from "./version/resolve";
const sourceDir = __dirname; const sourceDir = __dirname;
function formatUnexpectedFailure(error: unknown): string {
if (error instanceof Error) {
return error.stack ?? error.message;
}
return String(error);
}
function failUnexpectedly(event: string, error: unknown): never {
core.setFailed(`${event}: ${formatUnexpectedFailure(error)}`);
process.exit(1);
}
process.on("uncaughtException", (error) => {
failUnexpectedly("Uncaught exception", error);
});
process.on("unhandledRejection", (reason) => {
failUnexpectedly("Unhandled promise rejection", reason);
});
async function getPythonVersion(inputs: SetupInputs): Promise<string> { async function getPythonVersion(inputs: SetupInputs): Promise<string> {
if (inputs.pythonVersion !== "") { if (inputs.pythonVersion !== "") {
return inputs.pythonVersion; return inputs.pythonVersion;
@@ -97,7 +76,7 @@ async function run(): Promise<void> {
core.setOutput("uv-version", setupResult.version); core.setOutput("uv-version", setupResult.version);
core.saveState(STATE_UV_VERSION, setupResult.version); core.saveState(STATE_UV_VERSION, setupResult.version);
log.info(`Successfully installed uv version ${setupResult.version}`); core.info(`Successfully installed uv version ${setupResult.version}`);
const detectedPythonVersion = await getPythonVersion(inputs); const detectedPythonVersion = await getPythonVersion(inputs);
core.setOutput("python-version", detectedPythonVersion); core.setOutput("python-version", detectedPythonVersion);
@@ -116,11 +95,11 @@ async function run(): Promise<void> {
function detectEmptyWorkdir(inputs: SetupInputs): void { function detectEmptyWorkdir(inputs: SetupInputs): void {
if (fs.readdirSync(inputs.workingDirectory).length === 0) { if (fs.readdirSync(inputs.workingDirectory).length === 0) {
if (inputs.ignoreEmptyWorkdir) { if (inputs.ignoreEmptyWorkdir) {
log.info( core.info(
"Empty workdir detected. Ignoring because ignore-empty-workdir is enabled", "Empty workdir detected. Ignoring because ignore-empty-workdir is enabled",
); );
} else { } else {
log.warning( core.warning(
"Empty workdir detected. This may cause unexpected behavior. You can enable ignore-empty-workdir to mute this warning.", "Empty workdir detected. This may cause unexpected behavior. You can enable ignore-empty-workdir to mute this warning.",
); );
} }
@@ -141,7 +120,7 @@ async function setupUv(
}); });
const toolCacheResult = tryGetFromToolCache(arch, resolvedVersion); const toolCacheResult = tryGetFromToolCache(arch, resolvedVersion);
if (toolCacheResult.installedPath) { if (toolCacheResult.installedPath) {
log.info(`Found uv in tool-cache for ${toolCacheResult.version}`); core.info(`Found uv in tool-cache for ${toolCacheResult.version}`);
return { return {
uvDir: toolCacheResult.installedPath, uvDir: toolCacheResult.installedPath,
version: toolCacheResult.version, version: toolCacheResult.version,
@@ -155,7 +134,6 @@ async function setupUv(
inputs.checksum, inputs.checksum,
inputs.githubToken, inputs.githubToken,
inputs.manifestFile, inputs.manifestFile,
inputs.downloadFromAstralMirror,
); );
return { return {
@@ -169,39 +147,39 @@ function addUvToPathAndOutput(cachedPath: string): void {
core.saveState(STATE_UV_PATH, `${cachedPath}${path.sep}uv`); core.saveState(STATE_UV_PATH, `${cachedPath}${path.sep}uv`);
core.setOutput("uvx-path", `${cachedPath}${path.sep}uvx`); core.setOutput("uvx-path", `${cachedPath}${path.sep}uvx`);
if (process.env.UV_NO_MODIFY_PATH !== undefined) { if (process.env.UV_NO_MODIFY_PATH !== undefined) {
log.info("UV_NO_MODIFY_PATH is set, not modifying PATH"); core.info("UV_NO_MODIFY_PATH is set, not modifying PATH");
} else { } else {
core.addPath(cachedPath); core.addPath(cachedPath);
log.info(`Added ${cachedPath} to the path`); core.info(`Added ${cachedPath} to the path`);
} }
} }
function addToolBinToPath(inputs: SetupInputs): void { function addToolBinToPath(inputs: SetupInputs): void {
if (inputs.toolBinDir !== undefined) { if (inputs.toolBinDir !== undefined) {
core.exportVariable("UV_TOOL_BIN_DIR", inputs.toolBinDir); core.exportVariable("UV_TOOL_BIN_DIR", inputs.toolBinDir);
log.info(`Set UV_TOOL_BIN_DIR to ${inputs.toolBinDir}`); core.info(`Set UV_TOOL_BIN_DIR to ${inputs.toolBinDir}`);
if (process.env.UV_NO_MODIFY_PATH !== undefined) { if (process.env.UV_NO_MODIFY_PATH !== undefined) {
log.info( core.info(
`UV_NO_MODIFY_PATH is set, not adding ${inputs.toolBinDir} to path`, `UV_NO_MODIFY_PATH is set, not adding ${inputs.toolBinDir} to path`,
); );
} else { } else {
core.addPath(inputs.toolBinDir); core.addPath(inputs.toolBinDir);
log.info(`Added ${inputs.toolBinDir} to the path`); core.info(`Added ${inputs.toolBinDir} to the path`);
} }
} else { } else {
if (process.env.UV_NO_MODIFY_PATH !== undefined) { if (process.env.UV_NO_MODIFY_PATH !== undefined) {
log.info("UV_NO_MODIFY_PATH is set, not adding user local bin to path"); core.info("UV_NO_MODIFY_PATH is set, not adding user local bin to path");
return; return;
} }
if (process.env.XDG_BIN_HOME !== undefined) { if (process.env.XDG_BIN_HOME !== undefined) {
core.addPath(process.env.XDG_BIN_HOME); core.addPath(process.env.XDG_BIN_HOME);
log.info(`Added ${process.env.XDG_BIN_HOME} to the path`); core.info(`Added ${process.env.XDG_BIN_HOME} to the path`);
} else if (process.env.XDG_DATA_HOME !== undefined) { } else if (process.env.XDG_DATA_HOME !== undefined) {
core.addPath(`${process.env.XDG_DATA_HOME}/../bin`); core.addPath(`${process.env.XDG_DATA_HOME}/../bin`);
log.info(`Added ${process.env.XDG_DATA_HOME}/../bin to the path`); core.info(`Added ${process.env.XDG_DATA_HOME}/../bin to the path`);
} else { } else {
core.addPath(`${process.env.HOME}/.local/bin`); core.addPath(`${process.env.HOME}/.local/bin`);
log.info(`Added ${process.env.HOME}/.local/bin to the path`); core.info(`Added ${process.env.HOME}/.local/bin to the path`);
} }
} }
} }
@@ -209,25 +187,25 @@ function addToolBinToPath(inputs: SetupInputs): void {
function setToolDir(inputs: SetupInputs): void { function setToolDir(inputs: SetupInputs): void {
if (inputs.toolDir !== undefined) { if (inputs.toolDir !== undefined) {
core.exportVariable("UV_TOOL_DIR", inputs.toolDir); core.exportVariable("UV_TOOL_DIR", inputs.toolDir);
log.info(`Set UV_TOOL_DIR to ${inputs.toolDir}`); core.info(`Set UV_TOOL_DIR to ${inputs.toolDir}`);
} }
} }
function addPythonDirToPath(inputs: SetupInputs): void { function addPythonDirToPath(inputs: SetupInputs): void {
core.exportVariable("UV_PYTHON_INSTALL_DIR", inputs.pythonDir); core.exportVariable("UV_PYTHON_INSTALL_DIR", inputs.pythonDir);
log.info(`Set UV_PYTHON_INSTALL_DIR to ${inputs.pythonDir}`); core.info(`Set UV_PYTHON_INSTALL_DIR to ${inputs.pythonDir}`);
if (process.env.UV_NO_MODIFY_PATH !== undefined) { if (process.env.UV_NO_MODIFY_PATH !== undefined) {
log.info("UV_NO_MODIFY_PATH is set, not adding python dir to path"); core.info("UV_NO_MODIFY_PATH is set, not adding python dir to path");
} else { } else {
core.addPath(inputs.pythonDir); core.addPath(inputs.pythonDir);
log.info(`Added ${inputs.pythonDir} to the path`); core.info(`Added ${inputs.pythonDir} to the path`);
} }
} }
function setupPython(inputs: SetupInputs): void { function setupPython(inputs: SetupInputs): void {
if (inputs.pythonVersion !== "") { if (inputs.pythonVersion !== "") {
core.exportVariable("UV_PYTHON", inputs.pythonVersion); core.exportVariable("UV_PYTHON", inputs.pythonVersion);
log.info(`Set UV_PYTHON to ${inputs.pythonVersion}`); core.info(`Set UV_PYTHON to ${inputs.pythonVersion}`);
} }
} }
@@ -239,7 +217,7 @@ async function activateEnvironment(inputs: SetupInputs): Promise<void> {
); );
} }
log.info(`Creating and activating python venv at ${inputs.venvPath}...`); core.info(`Creating and activating python venv at ${inputs.venvPath}...`);
const venvArgs = [ const venvArgs = [
"venv", "venv",
inputs.venvPath, inputs.venvPath,
@@ -265,13 +243,13 @@ async function activateEnvironment(inputs: SetupInputs): Promise<void> {
function setCacheDir(inputs: SetupInputs): void { function setCacheDir(inputs: SetupInputs): void {
if (inputs.cacheLocalPath !== undefined) { if (inputs.cacheLocalPath !== undefined) {
if (inputs.cacheLocalPath.source === CacheLocalSource.Config) { if (inputs.cacheLocalPath.source === CacheLocalSource.Config) {
log.info( core.info(
"Using cache-dir from uv config file, not modifying UV_CACHE_DIR", "Using cache-dir from uv config file, not modifying UV_CACHE_DIR",
); );
return; return;
} }
core.exportVariable("UV_CACHE_DIR", inputs.cacheLocalPath.path); core.exportVariable("UV_CACHE_DIR", inputs.cacheLocalPath.path);
log.info(`Set UV_CACHE_DIR to ${inputs.cacheLocalPath.path}`); core.info(`Set UV_CACHE_DIR to ${inputs.cacheLocalPath.path}`);
} }
} }
+28 -4
View File
@@ -1,6 +1,6 @@
import * as core from "@actions/core"; import * as core from "@actions/core";
import * as semver from "semver"; import * as semver from "semver";
import { getLatestKnownVersion } from "./download/checksum/known-version"; import { KNOWN_CHECKSUMS } from "./download/checksum/known-checksums";
import { import {
type ChecksumEntry, type ChecksumEntry,
updateChecksums, updateChecksums,
@@ -10,7 +10,9 @@ import {
getLatestVersion, getLatestVersion,
type ManifestVersion, type ManifestVersion,
} from "./download/manifest"; } from "./download/manifest";
import * as log from "./utils/logging";
const VERSION_IN_CHECKSUM_KEY_PATTERN =
/-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/;
async function run(): Promise<void> { async function run(): Promise<void> {
const checksumFilePath = process.argv.slice(2)[0]; const checksumFilePath = process.argv.slice(2)[0];
@@ -21,10 +23,10 @@ async function run(): Promise<void> {
} }
const latestVersion = await getLatestVersion(); const latestVersion = await getLatestVersion();
const latestKnownVersion = getLatestKnownVersion(); const latestKnownVersion = getLatestKnownVersionFromChecksums();
if (semver.lte(latestVersion, latestKnownVersion)) { if (semver.lte(latestVersion, latestKnownVersion)) {
log.info( core.info(
`Latest release (${latestVersion}) is not newer than the latest known version (${latestKnownVersion}). Skipping update.`, `Latest release (${latestVersion}) is not newer than the latest known version (${latestKnownVersion}). Skipping update.`,
); );
return; return;
@@ -37,6 +39,28 @@ async function run(): Promise<void> {
core.setOutput("latest-version", latestVersion); core.setOutput("latest-version", latestVersion);
} }
function getLatestKnownVersionFromChecksums(): string {
const versions = new Set<string>();
for (const key of Object.keys(KNOWN_CHECKSUMS)) {
const version = extractVersionFromChecksumKey(key);
if (version !== undefined) {
versions.add(version);
}
}
const latestVersion = [...versions].sort(semver.rcompare)[0];
if (!latestVersion) {
throw new Error("Could not determine latest known version from checksums.");
}
return latestVersion;
}
function extractVersionFromChecksumKey(key: string): string | undefined {
return key.match(VERSION_IN_CHECKSUM_KEY_PATTERN)?.[1];
}
function extractChecksumsFromManifest( function extractChecksumsFromManifest(
versions: ManifestVersion[], versions: ManifestVersion[],
): ChecksumEntry[] { ): ChecksumEntry[] {
+1 -1
View File
@@ -16,7 +16,7 @@ export function getProxyAgent() {
export const fetch = async (url: string, opts: RequestInit) => { export const fetch = async (url: string, opts: RequestInit) => {
// Merge timeout signal with any existing signal from opts // Merge timeout signal with any existing signal from opts
const timeoutSignal = AbortSignal.timeout(5_000); const timeoutSignal = AbortSignal.timeout(30_000);
const existingSignal = opts.signal; const existingSignal = opts.signal;
const mergedSignal = existingSignal const mergedSignal = existingSignal
? AbortSignal.any([timeoutSignal, existingSignal]) ? AbortSignal.any([timeoutSignal, existingSignal])
+7 -59
View File
@@ -1,9 +1,6 @@
import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import * as core from "@actions/core"; import * as core from "@actions/core";
import { getPythonVersionFromToolVersions } from "../version/tool-versions-file";
import { getConfigValueFromTomlFile } from "./config-file"; import { getConfigValueFromTomlFile } from "./config-file";
import * as log from "./logging";
export enum CacheLocalSource { export enum CacheLocalSource {
Input, Input,
@@ -43,9 +40,7 @@ export interface SetupInputs {
pythonDir: string; pythonDir: string;
githubToken: string; githubToken: string;
manifestFile?: string; manifestFile?: string;
downloadFromAstralMirror: boolean;
addProblemMatchers: boolean; addProblemMatchers: boolean;
quiet: boolean;
resolutionStrategy: ResolutionStrategy; resolutionStrategy: ResolutionStrategy;
} }
@@ -53,7 +48,7 @@ export function loadInputs(): SetupInputs {
const workingDirectory = core.getInput("working-directory"); const workingDirectory = core.getInput("working-directory");
const version = core.getInput("version"); const version = core.getInput("version");
const versionFile = getVersionFile(workingDirectory); const versionFile = getVersionFile(workingDirectory);
const pythonVersion = getPythonVersion(versionFile); const pythonVersion = core.getInput("python-version");
const activateEnvironment = core.getBooleanInput("activate-environment"); const activateEnvironment = core.getBooleanInput("activate-environment");
const noProject = core.getBooleanInput("no-project"); const noProject = core.getBooleanInput("no-project");
const venvPath = getVenvPath(workingDirectory, activateEnvironment); const venvPath = getVenvPath(workingDirectory, activateEnvironment);
@@ -78,10 +73,7 @@ export function loadInputs(): SetupInputs {
const pythonDir = getUvPythonDir(); const pythonDir = getUvPythonDir();
const githubToken = core.getInput("github-token"); const githubToken = core.getInput("github-token");
const manifestFile = getManifestFile(); const manifestFile = getManifestFile();
const downloadFromAstralMirror =
core.getInput("download-from-astral-mirror") === "true";
const addProblemMatchers = core.getInput("add-problem-matchers") === "true"; const addProblemMatchers = core.getInput("add-problem-matchers") === "true";
const quiet = core.getInput("quiet") === "true";
const resolutionStrategy = getResolutionStrategy(); const resolutionStrategy = getResolutionStrategy();
return { return {
@@ -92,7 +84,6 @@ export function loadInputs(): SetupInputs {
cachePython, cachePython,
cacheSuffix, cacheSuffix,
checksum, checksum,
downloadFromAstralMirror,
enableCache, enableCache,
githubToken, githubToken,
ignoreEmptyWorkdir, ignoreEmptyWorkdir,
@@ -102,7 +93,6 @@ export function loadInputs(): SetupInputs {
pruneCache, pruneCache,
pythonDir, pythonDir,
pythonVersion, pythonVersion,
quiet,
resolutionStrategy, resolutionStrategy,
restoreCache, restoreCache,
saveCache, saveCache,
@@ -124,28 +114,6 @@ function getVersionFile(workingDirectory: string): string {
return versionFileInput; return versionFileInput;
} }
function getPythonVersion(versionFile: string): string {
const pythonVersionInput = core.getInput("python-version");
if (pythonVersionInput !== "") {
return pythonVersionInput;
}
if (process.env.UV_PYTHON !== undefined && process.env.UV_PYTHON !== "") {
return "";
}
if (versionFile === "" || !fs.existsSync(versionFile)) {
return "";
}
try {
return getPythonVersionFromToolVersions(versionFile) ?? "";
} catch (err) {
log.warning(
`Error while parsing Python version from ${versionFile}: ${(err as Error).message}`,
);
return "";
}
}
function getVenvPath( function getVenvPath(
workingDirectory: string, workingDirectory: string,
activateEnvironment: boolean, activateEnvironment: boolean,
@@ -153,7 +121,7 @@ function getVenvPath(
const venvPathInput = core.getInput("venv-path"); const venvPathInput = core.getInput("venv-path");
if (venvPathInput !== "") { if (venvPathInput !== "") {
if (!activateEnvironment) { if (!activateEnvironment) {
log.warning("venv-path is only used when activate-environment is true"); core.warning("venv-path is only used when activate-environment is true");
} }
const tildeExpanded = expandTilde(venvPathInput); const tildeExpanded = expandTilde(venvPathInput);
return normalizePath(resolveRelativePath(workingDirectory, tildeExpanded)); return normalizePath(resolveRelativePath(workingDirectory, tildeExpanded));
@@ -164,27 +132,7 @@ function getVenvPath(
function getEnableCache(): boolean { function getEnableCache(): boolean {
const enableCacheInput = core.getInput("enable-cache"); const enableCacheInput = core.getInput("enable-cache");
if (enableCacheInput === "auto") { if (enableCacheInput === "auto") {
if (process.env.RUNNER_ENVIRONMENT !== "github-hosted") { return process.env.RUNNER_ENVIRONMENT === "github-hosted";
return false;
}
const eventName = process.env.GITHUB_EVENT_NAME;
const isTagPush =
eventName === "push" && process.env.GITHUB_REF?.startsWith("refs/tags/");
if (isTagPush) {
log.info("Caching is disabled for tag pushes");
return false;
}
if (
eventName === "pull_request_target" ||
eventName === "workflow_run" ||
eventName === "release"
) {
log.info(`Caching is disabled for the ${eventName} event`);
return false;
}
return true;
} }
return enableCacheInput === "true"; return enableCacheInput === "true";
} }
@@ -244,7 +192,7 @@ function getCacheLocalPath(
return { path: cacheDirFromConfig, source: CacheLocalSource.Config }; return { path: cacheDirFromConfig, source: CacheLocalSource.Config };
} }
if (process.env.UV_CACHE_DIR !== undefined) { if (process.env.UV_CACHE_DIR !== undefined) {
log.info(`UV_CACHE_DIR is already set to ${process.env.UV_CACHE_DIR}`); core.info(`UV_CACHE_DIR is already set to ${process.env.UV_CACHE_DIR}`);
return { path: process.env.UV_CACHE_DIR, source: CacheLocalSource.Env }; return { path: process.env.UV_CACHE_DIR, source: CacheLocalSource.Env };
} }
if (enableCache) { if (enableCache) {
@@ -281,12 +229,12 @@ function getCacheDirFromConfig(
try { try {
const cacheDir = getConfigValueFromTomlFile(resolvedPath, "cache-dir"); const cacheDir = getConfigValueFromTomlFile(resolvedPath, "cache-dir");
if (cacheDir !== undefined) { if (cacheDir !== undefined) {
log.info(`Found cache-dir in ${resolvedPath}: ${cacheDir}`); core.info(`Found cache-dir in ${resolvedPath}: ${cacheDir}`);
return cacheDir; return cacheDir;
} }
} catch (err) { } catch (err) {
const message = (err as Error).message; const message = (err as Error).message;
log.warning(`Error while parsing ${filePath}: ${message}`); core.warning(`Error while parsing ${filePath}: ${message}`);
return undefined; return undefined;
} }
} }
@@ -295,7 +243,7 @@ function getCacheDirFromConfig(
export function getUvPythonDir(): string { export function getUvPythonDir(): string {
if (process.env.UV_PYTHON_INSTALL_DIR !== undefined) { if (process.env.UV_PYTHON_INSTALL_DIR !== undefined) {
log.info( core.info(
`UV_PYTHON_INSTALL_DIR is already set to ${process.env.UV_PYTHON_INSTALL_DIR}`, `UV_PYTHON_INSTALL_DIR is already set to ${process.env.UV_PYTHON_INSTALL_DIR}`,
); );
return process.env.UV_PYTHON_INSTALL_DIR; return process.env.UV_PYTHON_INSTALL_DIR;
-21
View File
@@ -1,21 +0,0 @@
import * as core from "@actions/core";
let quiet: boolean | undefined;
function isQuiet(): boolean {
if (quiet === undefined) {
quiet =
typeof core.getInput === "function" && core.getInput("quiet") === "true";
}
return quiet;
}
export function info(msg: string): void {
if (!isQuiet()) {
core.info(msg);
}
}
export const warning = core.warning;
export const error = core.error;
export const debug = core.debug;
+1 -17
View File
@@ -102,7 +102,6 @@ export function getOSNameVersion(): string {
function getLinuxOSNameVersion(): string { function getLinuxOSNameVersion(): string {
const files = ["/etc/os-release", "/usr/lib/os-release"]; const files = ["/etc/os-release", "/usr/lib/os-release"];
let idWithoutVersion: string | undefined;
for (const file of files) { for (const file of files) {
try { try {
@@ -110,9 +109,8 @@ function getLinuxOSNameVersion(): string {
const id = parseOsReleaseValue(content, "ID"); const id = parseOsReleaseValue(content, "ID");
const versionId = parseOsReleaseValue(content, "VERSION_ID"); const versionId = parseOsReleaseValue(content, "VERSION_ID");
// Fallback for rolling releases (debian:unstable/testing, arch, etc.) // Fallback for rolling releases (debian:unstable/testing, arch, etc.)
// that don't have VERSION_ID but have VERSION_CODENAME or BUILD_ID // that don't have VERSION_ID but have VERSION_CODENAME
const versionCodename = parseOsReleaseValue(content, "VERSION_CODENAME"); const versionCodename = parseOsReleaseValue(content, "VERSION_CODENAME");
const buildId = parseOsReleaseValue(content, "BUILD_ID");
if (id && versionId) { if (id && versionId) {
return `${id}-${versionId}`; return `${id}-${versionId}`;
@@ -120,25 +118,11 @@ function getLinuxOSNameVersion(): string {
if (id && versionCodename) { if (id && versionCodename) {
return `${id}-${versionCodename}`; return `${id}-${versionCodename}`;
} }
if (id && buildId) {
return `${id}-${buildId}`;
}
// Remember the ID but keep looking: the next file might still
// provide a version field
if (id && idWithoutVersion === undefined) {
idWithoutVersion = id;
}
} catch { } catch {
// Try next file // Try next file
} }
} }
// Fallback for rolling releases (e.g. void) that have no version
// field at all
if (idWithoutVersion) {
return idWithoutVersion;
}
throw new Error( throw new Error(
"Failed to determine Linux distribution. " + "Failed to determine Linux distribution. " +
"Could not read /etc/os-release or /usr/lib/os-release", "Could not read /etc/os-release or /usr/lib/os-release",
+7 -11
View File
@@ -1,6 +1,6 @@
import fs from "node:fs"; import fs from "node:fs";
import * as core from "@actions/core";
import { getConfigValueFromTomlContent } from "../utils/config-file"; import { getConfigValueFromTomlContent } from "../utils/config-file";
import * as log from "../utils/logging";
import { import {
getUvVersionFromParsedPyproject, getUvVersionFromParsedPyproject,
getUvVersionFromRequirementsText, getUvVersionFromRequirementsText,
@@ -9,7 +9,6 @@ import {
import { normalizeVersionSpecifier } from "./specifier"; import { normalizeVersionSpecifier } from "./specifier";
import { getUvVersionFromToolVersions } from "./tool-versions-file"; import { getUvVersionFromToolVersions } from "./tool-versions-file";
import type { ParsedVersionFile, VersionFileFormat } from "./types"; import type { ParsedVersionFile, VersionFileFormat } from "./types";
import { getUvVersionFromUvLock } from "./uv-lock-file";
interface VersionFileParser { interface VersionFileParser {
format: VersionFileFormat; format: VersionFileFormat;
@@ -50,11 +49,6 @@ const VERSION_FILE_PARSERS: VersionFileParser[] = [
}, },
supports: (filePath) => filePath.endsWith("pyproject.toml"), supports: (filePath) => filePath.endsWith("pyproject.toml"),
}, },
{
format: "uv.lock",
parse: (filePath) => getUvVersionFromUvLock(filePath),
supports: (filePath) => filePath.endsWith("uv.lock"),
},
{ {
format: "requirements", format: "requirements",
parse: (filePath) => { parse: (filePath) => {
@@ -68,10 +62,10 @@ const VERSION_FILE_PARSERS: VersionFileParser[] = [
export function getParsedVersionFile( export function getParsedVersionFile(
filePath: string, filePath: string,
): ParsedVersionFile | undefined { ): ParsedVersionFile | undefined {
log.info(`Trying to find version for uv in: ${filePath}`); core.info(`Trying to find version for uv in: ${filePath}`);
if (!fs.existsSync(filePath)) { if (!fs.existsSync(filePath)) {
log.info(`Could not find file: ${filePath}`); core.info(`Could not find file: ${filePath}`);
return undefined; return undefined;
} }
@@ -87,13 +81,15 @@ export function getParsedVersionFile(
} }
const normalizedSpecifier = normalizeVersionSpecifier(specifier); const normalizedSpecifier = normalizeVersionSpecifier(specifier);
log.info(`Found version for uv in ${filePath}: ${normalizedSpecifier}`); core.info(`Found version for uv in ${filePath}: ${normalizedSpecifier}`);
return { return {
format: parser.format, format: parser.format,
specifier: normalizedSpecifier, specifier: normalizedSpecifier,
}; };
} catch (error) { } catch (error) {
log.warning(`Error while parsing ${filePath}: ${(error as Error).message}`); core.warning(
`Error while parsing ${filePath}: ${(error as Error).message}`,
);
return undefined; return undefined;
} }
} }
+3 -7
View File
@@ -63,11 +63,7 @@ function getUvVersionFromAllDependencies(
allDependencies: string[], allDependencies: string[],
): string | undefined { ): string | undefined {
return allDependencies return allDependencies
.map(getUvVersionFromDependency) .find((dep: string) => dep.match(/^uv[=<>~!]/))
.find((version): version is string => version !== undefined); ?.match(/^uv([=<>~!]+\S*)/)?.[1]
} .trim();
function getUvVersionFromDependency(dependency: string): string | undefined {
const dependencyWithoutMarker = dependency.split(";", 1)[0]?.trim();
return dependencyWithoutMarker?.match(/^uv([=<>~!]+\S*)/)?.[1].trim();
} }
+9 -62
View File
@@ -2,15 +2,8 @@ import * as core from "@actions/core";
import * as tc from "@actions/tool-cache"; import * as tc from "@actions/tool-cache";
import * as pep440 from "@renovatebot/pep440"; import * as pep440 from "@renovatebot/pep440";
import * as semver from "semver"; import * as semver from "semver";
import { getLatestKnownVersion } from "../download/checksum/known-version"; import { getAllVersions, getLatestVersion } from "../download/manifest";
import {
getAllVersions,
getFirstMatchingVersion,
getLatestVersion,
} from "../download/manifest";
import { VERSIONS_MANIFEST_URL } from "../utils/constants";
import type { ResolutionStrategy } from "../utils/inputs"; import type { ResolutionStrategy } from "../utils/inputs";
import * as log from "../utils/logging";
import { import {
type ParsedVersionSpecifier, type ParsedVersionSpecifier,
parseVersionSpecifier, parseVersionSpecifier,
@@ -63,7 +56,7 @@ class LatestVersionResolver implements ConcreteVersionResolver {
context.parsedSpecifier.kind === "range" && context.parsedSpecifier.kind === "range" &&
context.parsedSpecifier.isSimpleMinimumVersionSpecifier context.parsedSpecifier.isSimpleMinimumVersionSpecifier
) { ) {
log.info("Found minimum version specifier, using latest version"); core.info("Found minimum version specifier, using latest version");
} }
const latestVersion = await getLatestVersion(context.manifestUrl); const latestVersion = await getLatestVersion(context.manifestUrl);
@@ -88,26 +81,13 @@ class RangeVersionResolver implements ConcreteVersionResolver {
return undefined; return undefined;
} }
let resolvedVersion: string | undefined; const availableVersions = await getAllVersions(context.manifestUrl);
if ( core.debug(`Available versions: ${availableVersions}`);
context.resolutionStrategy === "highest" &&
(context.manifestUrl === undefined || const resolvedVersion =
context.manifestUrl === VERSIONS_MANIFEST_URL) context.resolutionStrategy === "lowest"
) { ? minSatisfying(availableVersions, context.parsedSpecifier.normalized)
resolvedVersion = await findHighestSatisfyingVersion( : maxSatisfying(availableVersions, context.parsedSpecifier.normalized);
context.parsedSpecifier.normalized,
);
} else {
const availableVersions = await getAllVersions(context.manifestUrl);
core.debug(`Available versions: ${availableVersions}`);
resolvedVersion =
context.resolutionStrategy === "lowest"
? minSatisfying(availableVersions, context.parsedSpecifier.normalized)
: maxSatisfying(
availableVersions,
context.parsedSpecifier.normalized,
);
}
if (resolvedVersion === undefined) { if (resolvedVersion === undefined) {
throw new Error(`No version found for ${context.parsedSpecifier.raw}`); throw new Error(`No version found for ${context.parsedSpecifier.raw}`);
@@ -144,10 +124,6 @@ export async function resolveVersion(
): Promise<string> { ): Promise<string> {
core.debug(`Resolving version: ${versionInput}`); core.debug(`Resolving version: ${versionInput}`);
if (versionInput.trim() === "latest-known") {
return getLatestKnownVersion();
}
const context: ConcreteVersionResolutionContext = { const context: ConcreteVersionResolutionContext = {
manifestUrl, manifestUrl,
parsedSpecifier: parseVersionSpecifier(versionInput), parsedSpecifier: parseVersionSpecifier(versionInput),
@@ -164,35 +140,6 @@ export async function resolveVersion(
throw new Error(`No version found for ${versionInput}`); throw new Error(`No version found for ${versionInput}`);
} }
async function findHighestSatisfyingVersion(
versionSpecifier: string,
): Promise<string | undefined> {
// This fast path assumes uv releases are semver-monotonic: newer manifest
// entries always have higher versions, with no lower-version backports.
const semverRange = semver.validRange(versionSpecifier);
if (semverRange !== null) {
const semverMatch = await getFirstMatchingVersion((version) =>
semver.satisfies(version, semverRange),
);
if (semverMatch !== undefined) {
core.debug(
`Found a version that satisfies the semver range: ${semverMatch}`,
);
return semverMatch;
}
}
const pep440Match = await getFirstMatchingVersion((version) =>
pep440.satisfies(version, versionSpecifier),
);
if (pep440Match !== undefined) {
core.debug(
`Found a version that satisfies the pep440 specifier: ${pep440Match}`,
);
}
return pep440Match;
}
function maxSatisfying( function maxSatisfying(
versions: string[], versions: string[],
version: string, version: string,
+14 -69
View File
@@ -4,83 +4,28 @@ import * as core from "@actions/core";
export function getUvVersionFromToolVersions( export function getUvVersionFromToolVersions(
filePath: string, filePath: string,
): string | undefined { ): string | undefined {
const versions = getToolVersions(filePath, "uv");
if (versions === undefined || versions.length !== 1) {
return undefined;
}
const version = stripVersionPrefix(versions[0]);
if (isPath(version)) {
core.warning(
`The uv version ${versions[0]} in .tool-versions is not supported. Paths are not allowed.`,
);
return undefined;
}
if (version.startsWith("ref")) {
core.warning(
"The ref syntax of .tool-versions is not supported. Please use a released version instead.",
);
return undefined;
}
return version;
}
export function getPythonVersionFromToolVersions(
filePath: string,
): string | undefined {
const versions = getToolVersions(filePath, "python");
if (versions === undefined || versions.length === 0) {
return undefined;
}
if (versions.length > 1) {
core.warning(
"Multiple Python versions in .tool-versions are not supported. The Python entry will be ignored.",
);
return undefined;
}
const version = stripVersionPrefix(versions[0]);
if (
version === "system" ||
version.startsWith("ref:") ||
version.startsWith("path:") ||
isPath(version)
) {
core.warning(
`The Python version ${versions[0]} in .tool-versions is not supported. The Python entry will be ignored.`,
);
return undefined;
}
return version;
}
function getToolVersions(
filePath: string,
toolName: string,
): string[] | undefined {
if (!filePath.endsWith(".tool-versions")) { if (!filePath.endsWith(".tool-versions")) {
return undefined; return undefined;
} }
const fileContents = fs.readFileSync(filePath, "utf8"); const fileContents = fs.readFileSync(filePath, "utf8");
const lines = fileContents.split("\n");
for (const line of fileContents.split("\n")) { for (const line of lines) {
const content = line.split("#", 1)[0].trim(); // Skip commented lines
if (content === "") { if (line.trim().startsWith("#")) {
continue; continue;
} }
const match = line.match(/^\s*uv\s*v?\s*(?<version>[^\s]+)\s*$/);
const [tool, ...versions] = content.split(/\s+/); if (match) {
if (tool === toolName) { const matchedVersion = match.groups?.version.trim();
return versions; if (matchedVersion?.startsWith("ref")) {
core.warning(
"The ref syntax of .tool-versions is not supported. Please use a released version instead.",
);
return undefined;
}
return matchedVersion;
} }
} }
return undefined; return undefined;
} }
function stripVersionPrefix(version: string): string {
return version.startsWith("v") ? version.slice(1) : version;
}
function isPath(version: string): boolean {
return version.includes("/") || version.includes("\\");
}
-1
View File
@@ -11,7 +11,6 @@ export type VersionFileFormat =
| ".tool-versions" | ".tool-versions"
| "pyproject.toml" | "pyproject.toml"
| "requirements" | "requirements"
| "uv.lock"
| "uv.toml"; | "uv.toml";
export interface ParsedVersionFile { export interface ParsedVersionFile {
-24
View File
@@ -1,24 +0,0 @@
import fs from "node:fs";
import * as toml from "smol-toml";
interface UvLockPackage {
name?: string;
version?: string;
}
interface UvLock {
package?: UvLockPackage[];
}
export function getUvVersionFromUvLock(filePath: string): string | undefined {
const fileContent = fs.readFileSync(filePath, "utf-8");
return getUvVersionFromUvLockContent(fileContent);
}
export function getUvVersionFromUvLockContent(
fileContent: string,
): string | undefined {
const parsed = toml.parse(fileContent) as UvLock;
const uvPackage = parsed.package?.find((pkg) => pkg.name === "uv");
return uvPackage?.version;
}
+2 -2
View File
@@ -1,5 +1,5 @@
import * as path from "node:path"; import * as path from "node:path";
import * as log from "../utils/logging"; import * as core from "@actions/core";
import { getParsedVersionFile } from "./file-parser"; import { getParsedVersionFile } from "./file-parser";
import { normalizeVersionSpecifier } from "./specifier"; import { normalizeVersionSpecifier } from "./specifier";
import type { import type {
@@ -111,7 +111,7 @@ export class WorkspaceVersionResolver implements VersionRequestResolver {
}; };
} }
log.info( core.info(
"Could not determine uv version from uv.toml or pyproject.toml. Falling back to latest.", "Could not determine uv version from uv.toml or pyproject.toml. Falling back to latest.",
); );
return undefined; return undefined;
-1
View File
@@ -5,7 +5,6 @@
"module": "esnext", "module": "esnext",
"moduleResolution": "bundler", "moduleResolution": "bundler",
"noImplicitAny": true, "noImplicitAny": true,
"resolveJsonModule": true,
"strict": true, "strict": true,
"target": "ES2022" "target": "ES2022"
}, },