Compare commits

..

No commits in common. "main" and "v7.0" have entirely different histories.
main ... v7.0

36 changed files with 108905 additions and 49895 deletions

View file

@ -1,263 +0,0 @@
# Copilot Instructions for setup-uv
This document provides essential information for GitHub Copilot coding agents working on the `astral-sh/setup-uv` repository.
## Repository Overview
**setup-uv** is a GitHub Action that sets up the [uv](https://docs.astral.sh/uv/)
Python package installer in GitHub Actions workflows.
It's a TypeScript-based action that downloads uv binaries, manages caching, handles version resolution,
and configures the environment for subsequent workflow steps.
### Key Features
- Downloads and installs specific uv versions from GitHub releases
- Supports version resolution from config files (pyproject.toml, uv.toml, .tool-versions)
- Implements intelligent caching for both uv cache and Python installations
- Provides cross-platform support (Linux, macOS, Windows, including ARM architectures)
- Includes problem matchers for Python error reporting
- Supports environment activation and custom tool directories
## Repository Structure
**Size**: Small-medium repository (~50 source files, ~400 total files including dependencies)
**Languages**: TypeScript (primary), JavaScript (compiled output), JSON (configuration)
**Runtime**: Node.js 24 (GitHub Actions runtime)
**Key Dependencies**: @actions/core, @actions/cache, @actions/tool-cache, @octokit/core
### Core Architecture
```
src/
├── setup-uv.ts # Main entry point and orchestration
├── save-cache.ts # Post-action cache saving logic
├── update-known-versions.ts # Maintenance script for version updates
├── cache/ # Cache management functionality
├── download/ # Version resolution and binary downloading
├── utils/ # Input parsing, platform detection, configuration
└── version/ # Version resolution from various file formats
```
### Key Files and Locations
- **Action Definition**: `action.yml` - Defines all inputs/outputs and entry points
- **Main Source**: `src/setup-uv.ts` - Primary action logic
- **Configuration**: `biome.json` (linting), `tsconfig.json` (TypeScript), `jest.config.js` (testing)
- **Compiled Output**: `dist/` - Contains compiled Node.js bundles (auto-generated, committed)
- **Test Fixtures**: `__tests__/fixtures/` - Sample projects for different configuration scenarios
- **Workflows**: `.github/workflows/test.yml` - Comprehensive CI/CD pipeline
## Build and Development Process
### Prerequisites
- Node.js 24+ (matches GitHub Actions runtime)
- npm (included with Node.js)
### Essential Commands (ALWAYS run in this order)
#### 1. Install Dependencies
```bash
npm ci --ignore-scripts
```
**Timing**: ~20-30 seconds
**Note**: Always run this first after cloning or when package.json changes
#### 2. Build TypeScript
```bash
npm run build
```
**Timing**: ~5-10 seconds
**Purpose**: Compiles TypeScript source to JavaScript in `lib/` directory
#### 3. Lint and Format Code
```bash
npm run check
```
**Timing**: ~2-5 seconds
**Tool**: Biome (replaces ESLint/Prettier)
**Auto-fixes**: Formatting, import organization, basic linting issues
#### 4. Package for Distribution
```bash
npm run package
```
**Timing**: ~20-30 seconds
**Purpose**: Creates bundled distributions in `dist/` using @vercel/ncc
**Critical**: This step MUST be run before committing - the `dist/` files are used by GitHub Actions
#### 5. Run Tests
```bash
npm test
```
**Timing**: ~10-15 seconds
**Framework**: Jest with TypeScript support
**Coverage**: Unit tests for version resolution, input parsing, checksum validation
#### 6. Complete Validation (Recommended)
```bash
npm run all
```
**Timing**: ~60-90 seconds
**Purpose**: Runs build → check → package → test in sequence
**Use**: Before making pull requests or when unsure about build state
### Important Build Notes
**CRITICAL**: Always run `npm run package` after making code changes. The `dist/` directory contains the compiled bundles that GitHub Actions actually executes. Forgetting this step will cause your changes to have no effect.
**TypeScript Warnings**: You may see ts-jest warnings about "isolatedModules" - these are harmless and don't affect functionality.
**Biome**: This project uses Biome instead of ESLint/Prettier. Run `npm run check` to fix formatting and linting issues automatically.
## Testing Strategy
### Unit Tests
- **Location**: `__tests__/` directory
- **Framework**: Jest with ts-jest transformer
- **Coverage**: Version resolution, input parsing, checksum validation, utility functions
### Integration Tests
- **Location**: `.github/workflows/test.yml`
- **Scope**: Full end-to-end testing across multiple platforms and scenarios
- **Key Test Categories**:
- Version installation (specific, latest, semver ranges)
- Cache behavior (setup, restore, invalidation)
- Cross-platform compatibility (Ubuntu, macOS, Windows, ARM)
- Configuration file parsing (pyproject.toml, uv.toml, requirements.txt)
- Error handling and edge cases
### Test Fixtures
Located in `__tests__/fixtures/`, these provide sample projects with different configurations:
- `pyproject-toml-project/` - Standard Python project with uv version specification
- `uv-toml-project/` - Project using uv.toml configuration
- `requirements-txt-project/` - Legacy requirements.txt format
- `cache-dir-defined-project/` - Custom cache directory configuration
## Continuous Integration
### GitHub Workflows
#### Primary Test Suite (`.github/workflows/test.yml`)
- **Triggers**: PRs, pushes to main, manual dispatch
- **Matrix**: Multiple OS (Ubuntu, macOS, Windows), architecture (x64, ARM), and configuration combinations
- **Duration**: ~5 minutes for full matrix
- **Key Validations**:
- Cross-platform installation and functionality
- Cache behavior and performance
- Version resolution from various sources
- Tool directory configurations
- Problem matcher functionality
#### Maintenance Workflows
- **CodeQL Analysis**: Security scanning on pushes/PRs
- **Update Known Versions**: Daily job to sync with latest uv releases
- **Dependabot**: Automated dependency updates
### Pre-commit Validation
The CI runs these checks that you should run locally:
1. `npm run all` - Complete build and test suite
2. ActionLint - GitHub Actions workflow validation
3. Change detection - Ensures no uncommitted build artifacts
## Key Configuration Files
### Action Configuration (`action.yml`)
Defines 20+ inputs including version specifications,
cache settings, tool directories, and environment options.
This file is the authoritative source for understanding available action parameters.
### TypeScript Configuration (`tsconfig.json`)
- Target: ES2024
- Module: nodenext (Node.js modules)
- Strict mode enabled
- Output directory: `lib/`
### Linting Configuration (`biome.json`)
- Formatter and linter combined
- Enforces consistent code style
- Automatically organizes imports and sorts object keys
## Common Development Patterns
### Making Code Changes
1. Edit TypeScript source files in `src/`
2. Run `npm run build` to compile
3. Run `npm run check` to format and lint
4. Run `npm run package` to update distribution bundles
5. Run `npm test` to verify functionality
6. Commit all changes including `dist/` files
### Adding New Features
- Follow existing patterns in `src/utils/inputs.ts` for new action inputs
- Update `action.yml` to declare new inputs/outputs
- Add corresponding tests in `__tests__/`
- Add a test in `.github/workflows/test.yml` if it affects integration
- Update README.md with usage examples
### Cache-Related Changes
- Cache logic is complex and affects performance significantly
- Test with multiple cache scenarios (hit, miss, invalidation)
- Consider impact on both GitHub-hosted and self-hosted runners
- Validate cache key generation and dependency detection
### Version Resolution Changes
- Version resolution supports multiple file formats and precedence rules
- Test with fixtures in `__tests__/fixtures/`
- Consider backward compatibility with existing projects
- Validate semver and PEP 440 specification handling
## Troubleshooting
### Build Failures
- **"Module not found"**: Run `npm ci --ignore-scripts` to ensure dependencies are installed
- **TypeScript errors**: Check `tsconfig.json` and ensure all imports are valid
- **Test failures**: Check if test fixtures have been modified or if logic changes broke assumptions
### Action Failures in Workflows
- **Changes not taking effect**: Ensure `npm run package` was run and `dist/` files committed
- **Version resolution issues**: Check version specification format and file existence
- **Cache problems**: Verify cache key generation and dependency glob patterns
### Common Gotchas
- **Forgetting to package**: Code changes won't work without running `npm run package`
- **Platform differences**: Windows paths use backslashes, test cross-platform behavior
- **Cache invalidation**: Cache keys are sensitive to dependency file changes
- **Tool directory permissions**: Some platforms require specific directory setups
## Trust These Instructions
These instructions are comprehensive and current. Only search for additional information if:
- You encounter specific error messages not covered here
- You need to understand implementation details of specific functions
- The instructions appear outdated (check repository commit history)
For most development tasks, following the build process and development patterns outlined above will be sufficient.

View file

@ -4,12 +4,8 @@ updates:
directory: /
schedule:
interval: daily
cooldown:
default-days: 7
- package-ecosystem: npm
directory: /
schedule:
interval: daily
cooldown:
default-days: 7

View file

@ -41,13 +41,13 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
uses: github/codeql-action/init@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6
with:
languages: ${{ matrix.language }}
source-root: src
@ -59,7 +59,7 @@ jobs:
# 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)
- name: Autobuild
uses: github/codeql-action/autobuild@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
uses: github/codeql-action/autobuild@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@ -73,4 +73,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
uses: github/codeql-action/analyze@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6

View file

@ -19,6 +19,6 @@ jobs:
pull-requests: read
steps:
- name: 🚀 Run Release Drafter
uses: release-drafter/release-drafter@6db134d15f3909ccc9eefd369f02bd1e9cffdf97 # v6.2.0
uses: release-drafter/release-drafter@b1476f6e6eb133afa41ed8589daba6dc69b4d3f5 # v6.1.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View file

@ -21,19 +21,18 @@ jobs:
permissions:
security-events: write # for zizmor
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Actionlint
uses: eifinger/actionlint-action@447fbfe7533062b7a9ea55f790f2396fba6d052a # v1.10.0
uses: eifinger/actionlint-action@23c85443d840cd73bbecb9cddfc933cc21649a38 # v1.9.1
- name: Run zizmor
uses: zizmorcore/zizmor-action@135698455da5c3b3e55f73f4419e481ab68cdd95 # v0.4.1
- uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
uses: zizmorcore/zizmor-action@e673c3917a1aef3c65c972347ed84ccd013ecda4 # v0.2.0
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version-file: .nvmrc
cache: npm
node-version: "24"
- run: |
npm ci --ignore-scripts
npm install
- run: |
npm run all
- name: Check all jobs are in all-tests-passed.needs
@ -51,7 +50,7 @@ jobs:
matrix:
os: [ubuntu-latest, macos-latest, macos-14, windows-latest]
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install latest version
@ -76,7 +75,7 @@ jobs:
test-uv-no-modify-path:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install with UV_NO_MODIFY_PATH set
@ -112,28 +111,15 @@ jobs:
expected-version: "0.3.5"
- version-input: ">=0.4.25,<0.5"
expected-version: "0.4.30"
- version-input: ">=0.4.25,<0.5"
expected-version: "0.4.25"
resolution-strategy: "lowest"
- version-input: ">=0.4.25"
expected-version: "0.4.25"
resolution-strategy: "lowest"
- version-input: ">=0.1,<0.2"
expected-version: "0.1.45"
resolution-strategy: "highest"
- version-input: ">=0.1.0,<0.2"
expected-version: "0.1.0"
resolution-strategy: "lowest"
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install version ${{ matrix.input.version-input }} with strategy ${{ matrix.input.resolution-strategy || 'highest' }}
- name: Install version ${{ matrix.input.version-input }}
id: setup-uv
uses: ./
with:
version: ${{ matrix.input.version-input }}
resolution-strategy: ${{ matrix.input.resolution-strategy || 'highest' }}
- name: Correct version gets installed
run: |
if [ "$(uv --version)" != "uv ${{ matrix.input.expected-version }}" ]; then
@ -154,7 +140,7 @@ jobs:
matrix:
version-input: ["latest", ">=0.8"]
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install version ${{ matrix.version-input }}
@ -182,7 +168,7 @@ jobs:
- working-directory: "__tests__/fixtures/uv-toml-project"
expected-version: "0.5.15"
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install version from ${{ matrix.input.working-directory }}
@ -208,7 +194,7 @@ jobs:
- version-file: "__tests__/fixtures/.tool-versions"
expected-version: "0.5.15"
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install version from ${{ matrix.input.version-file }}
@ -225,7 +211,7 @@ jobs:
test-malformed-pyproject-file-fallback:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install using malformed pyproject.toml
@ -245,7 +231,7 @@ jobs:
- os: macos-latest
checksum: "a70cbfbf3bb5c08b2f84963b4f12c94e08fbb2468ba418a3bfe1066fbe9e7218"
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Checksum matches expected
@ -259,7 +245,7 @@ jobs:
test-with-explicit-token:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install default version
@ -272,7 +258,7 @@ jobs:
test-uvx:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install default version
@ -283,9 +269,15 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, macos-14, windows-latest]
os:
[
ubuntu-latest,
macos-latest,
macos-14,
windows-latest,
]
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install default version
@ -293,17 +285,38 @@ jobs:
- run: uv tool install ruff
- run: ruff --version
test-tilde-expansion-tool-dirs:
runs-on: selfhosted-ubuntu-arm64
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Setup with cache
uses: ./
with:
tool-bin-dir: "~/tool-bin-dir"
tool-dir: "~/tool-dir"
- name: "Check if tool dirs are expanded"
run: |
if ! echo "$PATH" | grep -q "/home/ubuntu/tool-bin-dir"; then
echo "PATH does not contain /home/ubuntu/tool-bin-dir: $PATH"
exit 1
fi
if [ "$UV_TOOL_DIR" != "/home/ubuntu/tool-dir" ]; then
echo "UV_TOOL_DIR does not contain /home/ubuntu/tool-dir: $UV_TOOL_DIR"
exit 1
fi
test-python-version:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install latest version
id: setup-uv
uses: ./
with:
python-version: 3.13.1t
@ -314,14 +327,6 @@ jobs:
exit 1
fi
shell: bash
- name: Verify output python-version is correct
run: |
if [ "$PYTHON_VERSION" != "3.13.1t" ]; then
exit 1
fi
shell: bash
env:
PYTHON_VERSION: ${{ steps.setup-uv.outputs.python-version }}
- run: uv sync
working-directory: __tests__/fixtures/uv-project
@ -329,13 +334,12 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
os: [ ubuntu-latest, macos-latest, windows-latest ]
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install latest version
id: setup-uv
uses: ./
with:
python-version: 3.13.1t
@ -350,144 +354,27 @@ jobs:
exit 1
fi
shell: bash
- name: Verify output venv is set
run: |
if [ -z "$UV_VENV" ]; then
echo "output venv is not set"
exit 1
fi
if [ ! -d "$UV_VENV" ]; then
echo "output venv not point to a directory: $UV_VENV"
exit 1
fi
shell: bash
env:
UV_VENV: ${{ steps.setup-uv.outputs.venv }}
test-activate-environment-custom-path:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Install latest version
id: setup-uv
uses: ./
with:
python-version: 3.13.1t
activate-environment: true
venv-path: ${{ runner.temp }}/custom-venv
- name: Verify VIRTUAL_ENV matches output
run: |
if [ "$VIRTUAL_ENV" != "$UV_VENV" ]; then
echo "VIRTUAL_ENV does not match venv output: $VIRTUAL_ENV vs $UV_VENV"
exit 1
fi
shell: bash
env:
UV_VENV: ${{ steps.setup-uv.outputs.venv }}
- name: Verify venv location is runner.temp/custom-venv
run: |
python - <<'PY'
import os
from pathlib import Path
venv = Path(os.environ["VIRTUAL_ENV"]).resolve()
temp = Path(os.environ["RUNNER_TEMP"]).resolve()
if venv.name != "custom-venv":
raise SystemExit(f"Expected venv name 'custom-venv', got: {venv}")
if venv.parent != temp:
raise SystemExit(f"Expected venv under {temp}, got: {venv}")
if not venv.is_dir():
raise SystemExit(f"Venv directory does not exist: {venv}")
PY
shell: bash
- name: Verify packages can be installed
run: uv pip install pip
shell: bash
- name: Verify python runs from custom venv
run: |
python - <<'PY'
import sys
if "custom-venv" not in sys.executable:
raise SystemExit(f"Python is not running from custom venv: {sys.executable}")
PY
shell: bash
test-musl:
runs-on: ubuntu-latest
container: alpine
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install latest version
id: setup-uv
uses: ./
with:
enable-cache: true
- name: Verify cache key contains alpine
run: |
echo "Cache key: $CACHE_KEY"
if echo "$CACHE_KEY" | grep -qv "alpine"; then
echo "Cache key does not contain 'alpine'"
exit 1
fi
shell: sh
env:
CACHE_KEY: ${{ steps.setup-uv.outputs.cache-key }}
- run: uv sync
working-directory: __tests__/fixtures/uv-project
test-cache-key-os-version:
runs-on: ${{ matrix.os }}
strategy:
matrix:
include:
- os: ubuntu-22.04
expected-os: "ubuntu-22.04"
- os: ubuntu-24.04
expected-os: "ubuntu-24.04"
- os: macos-14
expected-os: "macos-14"
- os: macos-15
expected-os: "macos-15"
- os: windows-2022
expected-os: "windows-2022"
- os: windows-2025
expected-os: "windows-2025"
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup uv
id: setup-uv
uses: ./
with:
enable-cache: true
- name: Verify cache key contains OS version
run: |
echo "Cache key: $CACHE_KEY"
if [[ "$CACHE_KEY" != *"${{ matrix.expected-os }}"* ]]; then
echo "Cache key does not contain expected OS version: ${{ matrix.expected-os }}"
exit 1
fi
shell: bash
env:
CACHE_KEY: ${{ steps.setup-uv.outputs.cache-key }}
test-setup-cache:
runs-on: ${{ matrix.os }}
strategy:
matrix:
enable-cache: ["true", "false", "auto"]
os: ["ubuntu-latest", "windows-latest"]
enable-cache: [ "true", "false", "auto" ]
os: [ "ubuntu-latest", "selfhosted-ubuntu-arm64", "windows-latest" ]
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Setup with cache
@ -502,11 +389,11 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
enable-cache: ["true", "false", "auto"]
os: ["ubuntu-latest", "windows-latest"]
enable-cache: [ "true", "false", "auto" ]
os: [ "ubuntu-latest", "selfhosted-ubuntu-arm64", "windows-latest" ]
needs: test-setup-cache
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Restore with cache
@ -525,7 +412,7 @@ jobs:
CACHE_HIT: ${{ steps.restore.outputs.cache-hit }}
shell: bash
- name: Cache was not hit
if: ${{ matrix.enable-cache == 'false' }}
if: ${{ matrix.enable-cache == 'false' || (matrix.enable-cache == 'auto' && matrix.os == 'selfhosted-ubuntu-arm64') }}
run: |
if [ "$CACHE_HIT" == "true" ]; then
exit 1
@ -540,7 +427,7 @@ jobs:
test-setup-cache-requirements-txt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Setup with cache
@ -556,7 +443,7 @@ jobs:
runs-on: ubuntu-latest
needs: test-setup-cache-requirements-txt
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Restore with cache
@ -580,7 +467,7 @@ jobs:
test-setup-cache-dependency-glob:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Setup with cache
@ -597,7 +484,7 @@ jobs:
runs-on: ubuntu-latest
needs: test-setup-cache-dependency-glob
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Change pyproject.toml
@ -625,7 +512,7 @@ jobs:
test-setup-cache-save-cache-false:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Setup with cache
@ -641,7 +528,7 @@ jobs:
runs-on: ubuntu-latest
needs: test-setup-cache-save-cache-false
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Restore with cache
@ -661,7 +548,7 @@ jobs:
test-setup-cache-restore-cache-false:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Setup with cache
@ -676,7 +563,7 @@ jobs:
runs-on: ubuntu-latest
needs: test-setup-cache-restore-cache-false
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Restore with cache
@ -702,9 +589,11 @@ jobs:
expected-cache-dir: "/home/runner/work/_temp/setup-uv-cache"
- os: windows-latest
expected-cache-dir: "D:\\a\\_temp\\setup-uv-cache"
- os: selfhosted-ubuntu-arm64
expected-cache-dir: "/home/ubuntu/.cache/uv"
runs-on: ${{ matrix.inputs.os }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Setup with cache
@ -722,7 +611,7 @@ jobs:
test-cache-local-cache-disabled:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Setup without cache
@ -738,30 +627,99 @@ jobs:
fi
shell: bash
test-cache-local-cache-disabled-but-explicit-path:
runs-on: ubuntu-latest
test-setup-cache-local:
runs-on: selfhosted-ubuntu-arm64
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Setup without cache
- name: Setup with cache
uses: ./
with:
enable-cache: false
cache-local-path: /tmp/uv-cache-disabled
- name: Check UV_CACHE_DIR is set
enable-cache: true
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-local
cache-local-path: /tmp/uv-cache
- run: uv sync
working-directory: __tests__/fixtures/uv-project
test-restore-cache-local:
runs-on: selfhosted-ubuntu-arm64
needs: test-setup-cache-local
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Restore with cache
id: restore
uses: ./
with:
enable-cache: true
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-setup-cache-local
cache-local-path: /tmp/uv-cache
- name: Cache was hit
run: |
if [ "$UV_CACHE_DIR" != "/tmp/uv-cache-disabled" ]; then
echo "UV_CACHE_DIR should be set when cache is disabled but explicit path is provided"
if [ "$CACHE_HIT" != "true" ]; then
exit 1
fi
env:
CACHE_HIT: ${{ steps.restore.outputs.cache-hit }}
- run: uv sync
working-directory: __tests__/fixtures/uv-project
test-tilde-expansion-cache-local-path:
runs-on: selfhosted-ubuntu-arm64
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Create cache directory
run: mkdir -p ~/uv-cache
shell: bash
- name: Setup with cache
uses: ./
with:
cache-local-path: ~/uv-cache/cache-local-path
- run: uv sync
working-directory: __tests__/fixtures/uv-project
test-tilde-expansion-cache-dependency-glob:
runs-on: selfhosted-ubuntu-arm64
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Create cache directory
run: mkdir -p ~/uv-cache
shell: bash
- name: Create cache dependency glob file
run: touch ~/uv-cache.glob
shell: bash
- name: Setup with cache
uses: ./
with:
enable-cache: true
cache-local-path: ~/uv-cache/cache-dependency-glob
cache-dependency-glob: "~/uv-cache.glob"
- run: uv sync
working-directory: __tests__/fixtures/uv-project
cleanup-tilde-expansion-tests:
needs:
- test-tilde-expansion-cache-local-path
- test-tilde-expansion-cache-dependency-glob
if: always()
runs-on: selfhosted-ubuntu-arm64
steps:
- name: Remove cache directory
run: rm -rf ~/uv-cache
shell: bash
- name: Remove cache dependency glob file
run: rm -f ~/uv-cache.glob
shell: bash
test-no-python-version:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Fake pyproject.toml at root
@ -776,7 +734,7 @@ jobs:
test-custom-manifest-file:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Install from custom manifest file
@ -795,7 +753,7 @@ jobs:
test-absolute-path:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Create requirements.txt
@ -815,7 +773,7 @@ jobs:
test-relative-path:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: mkdir
@ -839,7 +797,7 @@ jobs:
test-cache-prune-force:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Setup uv
@ -856,7 +814,7 @@ jobs:
test-cache-dir-from-file:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: false
- name: Verify uv cache dir is not populated
@ -878,141 +836,6 @@ jobs:
exit 1
fi
test-cache-python-missing-managed-install-dir:
runs-on: ubuntu-latest
env:
UV_PYTHON_INSTALL_DIR: /tmp/missing-uv-python
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup uv with cache and python cache enabled
uses: ./
with:
enable-cache: true
cache-python: true
python-version: "3.12"
cache-local-path: /tmp/setup-uv-cache
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-cache-python-missing-managed-install-dir
- name: Ensure uv cache dir exists so only python-cache behavior is tested
run: uv sync
working-directory: __tests__/fixtures/uv-project
shell: bash
- name: Ensure managed Python install dir does not exist and this does not break caching
run: rm -rf "$UV_PYTHON_INSTALL_DIR"
test-cache-python-installs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Verify Python install dir is not populated
run: |
if [ -d /home/runner/work/_temp/uv-python-dir ]; then
echo "Python install dir should not exist"
exit 1
fi
- name: Setup uv with cache
uses: ./
with:
enable-cache: true
cache-python: true
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-cache-python-installs
- run: uv sync --managed-python
working-directory: __tests__/fixtures/uv-project
- name: Verify Python install dir exists
run: |
if [ ! -d /home/runner/work/_temp/uv-python-dir ]; then
echo "Python install dir should exist"
exit 1
fi
test-restore-python-installs:
runs-on: ubuntu-latest
needs: test-cache-python-installs
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Verify Python install dir does not exist
run: |
if [ -d /home/runner/work/_temp/uv-python-dir ]; then
echo "Python install dir should not exist"
exit 1
fi
- name: Restore with cache
id: restore
uses: ./
with:
enable-cache: true
cache-python: true
cache-suffix: ${{ github.run_id }}-${{ github.run_attempt }}-test-cache-python-installs
- name: Verify Python install dir exists
run: |
if [ ! -d /home/runner/work/_temp/uv-python-dir ]; then
echo "Python install dir should exist"
exit 1
fi
- name: Cache was hit
run: |
if [ "$CACHE_HIT" != "true" ]; then
exit 1
fi
env:
CACHE_HIT: ${{ steps.restore.outputs.python-cache-hit }}
- run: uv sync --managed-python
working-directory: __tests__/fixtures/uv-project
test-python-install-dir:
strategy:
matrix:
inputs:
- os: ubuntu-latest
expected-python-dir: "/home/runner/work/_temp/uv-python-dir"
- os: windows-latest
expected-python-dir: "D:\\a\\_temp\\uv-python-dir"
runs-on: ${{ matrix.inputs.os }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Install latest version
id: setup-uv
uses: ./
- name: Check Python dir is expected dir
run: |
if [ "$UV_PYTHON_INSTALL_DIR" != "${{ matrix.inputs.expected-python-dir }}" ]; then
echo "Wrong UV_PYTHON_INSTALL_DIR: UV_PYTHON_INSTALL_DIR"
exit 1
fi
shell: bash
- name: Install python works
run: uv python install
test-act:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Install act
run: gh extension install https://github.com/nektos/gh-act
env:
GH_TOKEN: ${{ github.token }}
- name: Run test-uvx with act
run: gh act -j test-uvx -P ubuntu-latest=catthehacker/ubuntu:act-latest
env:
GH_TOKEN: ${{ github.token }}
validate-typings:
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Validate typings
uses: typesafegithub/github-actions-typing@9ddf35b71a482be7d8922b28e8d00df16b77e315 # v2.2.2
all-tests-passed:
runs-on: ubuntu-latest
needs:
@ -1028,14 +851,12 @@ jobs:
- test-with-explicit-token
- test-uvx
- test-tool-install
- test-tilde-expansion-tool-dirs
- test-python-version
- test-activate-environment
- test-activate-environment-custom-path
- test-musl
- test-cache-key-os-version
- test-cache-local
- test-cache-local-cache-disabled
- test-cache-local-cache-disabled-but-explicit-path
- test-setup-cache
- test-restore-cache
- test-setup-cache-requirements-txt
@ -1046,18 +867,17 @@ jobs:
- test-restore-cache-save-cache-false
- test-setup-cache-restore-cache-false
- test-restore-cache-restore-cache-false
- test-setup-cache-local
- test-restore-cache-local
- test-tilde-expansion-cache-local-path
- test-tilde-expansion-cache-dependency-glob
- cleanup-tilde-expansion-tests
- test-no-python-version
- test-custom-manifest-file
- test-absolute-path
- test-relative-path
- test-cache-prune-force
- test-cache-dir-from-file
- test-cache-python-missing-managed-install-dir
- test-cache-python-installs
- test-restore-python-installs
- test-python-install-dir
- test-act
- validate-typings
if: always()
steps:
- name: All tests passed

View file

@ -13,12 +13,11 @@ jobs:
runs-on: ubuntu-24.04-arm
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: true
- uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: "20"
- name: Update known versions
@ -29,21 +28,19 @@ jobs:
version-manifest.json
${{ secrets.GITHUB_TOKEN }}
- name: Check for changes
id: changes-exist
id: changes_exist
run: |
git status --porcelain
if [ -n "$(git status --porcelain)" ]; then
echo "changes-exist=true" >> "$GITHUB_OUTPUT"
echo "changes_exist=true" >> "$GITHUB_OUTPUT"
else
echo "changes-exist=false" >> "$GITHUB_OUTPUT"
echo "changes_exist=false" >> "$GITHUB_OUTPUT"
fi
- name: Compile changes
if: ${{ steps.changes-exist.outputs.changes-exist == 'true' }}
run: npm ci --ignore-scripts && npm run all
if: ${{ steps.changes_exist.outputs.changes_exist == 'true' }}
run: npm ci && npm run all
- name: Commit and push changes
if: ${{ steps.changes-exist.outputs.changes-exist == 'true' }}
id: commit-and-push
continue-on-error: true
if: ${{ steps.changes_exist.outputs.changes_exist == 'true' }}
run: |
git config user.name "$GITHUB_ACTOR"
git config user.email "$GITHUB_ACTOR@users.noreply.github.com"
@ -52,19 +49,3 @@ jobs:
git push origin HEAD:refs/heads/main
env:
LATEST_VERSION: ${{ steps.update-known-versions.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@c0f553fe549906ede9cf27b5156039d195d2ece0 # v8.1.0
with:
commit-message: "chore: update known checksums"
title:
"chore: update known checksums for ${{
steps.update-known-versions.outputs.latest-version }}"
body:
"chore: update known checksums for ${{
steps.update-known-versions.outputs.latest-version }}"
base: main
labels: "automated-pr,update-known-versions"
branch: update-known-versions-pr
delete-branch: true

View file

@ -17,7 +17,7 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
persist-credentials: true # needed for git push below
- name: Update Major Minor Tags

3
.gitignore vendored
View file

@ -100,6 +100,3 @@ lib/**/*
# Idea IDEs (PyCharm, WebStorm, IntelliJ, etc)
.idea/
# Compiled scripts
.github/scripts/*.js

1
.nvmrc
View file

@ -1 +0,0 @@
24

View file

@ -1 +0,0 @@
.github/copilot-instructions.md

559
README.md
View file

@ -12,11 +12,27 @@ Set up your GitHub Actions workflow with a specific version of [uv](https://docs
- [Usage](#usage)
- [Install a required-version or latest (default)](#install-a-required-version-or-latest-default)
- [Inputs](#inputs)
- [Outputs](#outputs)
- [Install the latest version](#install-the-latest-version)
- [Install a specific version](#install-a-specific-version)
- [Install a version by supplying a semver range or pep440 specifier](#install-a-version-by-supplying-a-semver-range-or-pep440-specifier)
- [Install a version defined in a requirements or config file](#install-a-version-defined-in-a-requirements-or-config-file)
- [Python version](#python-version)
- [Activate environment](#activate-environment)
- [Working directory](#working-directory)
- [Advanced Configuration](#advanced-configuration)
- [Validate checksum](#validate-checksum)
- [Enable Caching](#enable-caching)
- [Cache dependency glob](#cache-dependency-glob)
- [Restore cache](#restore-cache)
- [Save cache](#save-cache)
- [Local cache path](#local-cache-path)
- [Disable cache pruning](#disable-cache-pruning)
- [Ignore nothing to cache](#ignore-nothing-to-cache)
- [GitHub authentication token](#github-authentication-token)
- [UV_TOOL_DIR](#uv_tool_dir)
- [UV_TOOL_BIN_DIR](#uv_tool_bin_dir)
- [Tilde Expansion](#tilde-expansion)
- [Manifest file](#manifest-file)
- [Add problem matchers](#add-problem-matchers)
- [How it works](#how-it-works)
- [FAQ](#faq)
@ -26,7 +42,7 @@ Set up your GitHub Actions workflow with a specific version of [uv](https://docs
```yaml
- name: Install the latest version of uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v6
```
If you do not specify a version, this action will look for a [required-version](https://docs.astral.sh/uv/reference/settings/#required-version)
@ -35,101 +51,65 @@ in a `uv.toml` or `pyproject.toml` file in the repository root. If none is found
For an example workflow, see
[here](https://github.com/charliermarsh/autobot/blob/e42c66659bf97b90ca9ff305a19cc99952d0d43f/.github/workflows/ci.yaml).
### Inputs
All inputs and their defaults.
Have a look under [Advanced Configuration](#advanced-configuration) for detailed documentation on most of them.
### Install the latest version
```yaml
- name: Install uv with all available options
uses: astral-sh/setup-uv@v7
- name: Install the latest version of uv
uses: astral-sh/setup-uv@v6
with:
# The version of uv to install (default: searches for version in config files, then latest)
version: ""
# Path to a file containing the version of uv to install (default: searches uv.toml then pyproject.toml)
version-file: ""
# Resolution strategy when resolving version ranges: 'highest' or 'lowest'
resolution-strategy: "highest"
# The version of Python to set UV_PYTHON to
python-version: ""
# Use uv venv to activate a venv ready to be used by later steps
activate-environment: "false"
# Custom path for the virtual environment when using activate-environment (default: .venv in the working directory)
venv-path: ""
# The directory to execute all commands in and look for files such as pyproject.toml
working-directory: ""
# The checksum of the uv version to install
checksum: ""
# Used to increase the rate limit when retrieving versions and downloading uv
github-token: ${{ github.token }}
# Enable uploading of the uv cache: true, false, or auto (enabled on GitHub-hosted runners, disabled on self-hosted runners)
enable-cache: "auto"
# Glob pattern to match files relative to the repository root to control the cache
cache-dependency-glob: |
**/*requirements*.txt
**/*requirements*.in
**/*constraints*.txt
**/*constraints*.in
**/pyproject.toml
**/uv.lock
**/*.py.lock
# Whether to restore the cache if found
restore-cache: "true"
# Whether to save the cache after the run
save-cache: "true"
# Suffix for the cache key
cache-suffix: ""
# Local path to store the cache (default: "" - uses system temp directory)
cache-local-path: ""
# Prune cache before saving
prune-cache: "true"
# Upload managed Python installations to the GitHub Actions cache
cache-python: "false"
# Ignore when nothing is found to cache
ignore-nothing-to-cache: "false"
# Ignore when the working directory is empty
ignore-empty-workdir: "false"
# Custom path to set UV_TOOL_DIR to
tool-dir: ""
# Custom path to set UV_TOOL_BIN_DIR to
tool-bin-dir: ""
# URL to the manifest file containing available versions and download URLs
manifest-file: ""
# Add problem matchers
add-problem-matchers: "true"
version: "latest"
```
### Outputs
### Install a specific version
- `uv-version`: The installed uv version. Useful when using latest.
- `uv-path`: The path to the installed uv binary.
- `uvx-path`: The path to the installed uvx binary.
- `cache-hit`: A boolean value to indicate a cache entry was found.
- `venv`: Path to the activated venv if activate-environment is true.
- `python-version`: The Python version that was set.
- `python-cache-hit`: A boolean value to indicate the Python cache entry was found.
```yaml
- name: Install a specific version of uv
uses: astral-sh/setup-uv@v6
with:
version: "0.4.4"
```
### Install a version by supplying a semver range or pep440 specifier
You can specify a [semver range](https://github.com/npm/node-semver?tab=readme-ov-file#ranges)
or [pep440 specifier](https://peps.python.org/pep-0440/#version-specifiers)
to install the latest version that satisfies the range.
```yaml
- name: Install a semver range of uv
uses: astral-sh/setup-uv@v6
with:
version: ">=0.4.0"
```
```yaml
- name: Pinning a minor version of uv
uses: astral-sh/setup-uv@v6
with:
version: "0.4.x"
```
```yaml
- name: Install a pep440-specifier-satisfying version of uv
uses: astral-sh/setup-uv@v6
with:
version: ">=0.4.25,<0.5"
```
### Install a version defined in a requirements or config file
You can use the `version-file` input to specify a file that contains the version of uv to install.
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`.
[asdf](https://asdf-vm.com/) `.tool-versions` is also supported, but without the `ref` syntax.
```yaml
- name: Install uv based on the version defined in pyproject.toml
uses: astral-sh/setup-uv@v6
with:
version-file: "pyproject.toml"
```
### Python version
@ -139,7 +119,7 @@ This will override any python version specifications in `pyproject.toml` and `.p
```yaml
- name: Install the latest version of uv and set the python version to 3.13t
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v6
with:
python-version: 3.13t
- run: uv pip install --python=3.13t pip
@ -157,36 +137,377 @@ jobs:
steps:
- uses: actions/checkout@v5
- name: Install the latest version of uv and set the python version
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v6
with:
python-version: ${{ matrix.python-version }}
- name: Test with python ${{ matrix.python-version }}
run: uv run --frozen pytest
```
### Activate environment
You can set `activate-environment` to `true` to automatically activate a venv.
This allows directly using it in later steps:
```yaml
- name: Install the latest version of uv and activate the environment
uses: astral-sh/setup-uv@v6
with:
activate-environment: true
- run: uv pip install pip
```
> [!WARNING]
>
> Activating the environment adds your dependencies to the `PATH`, which could break some workflows.
> For example, if you have a dependency which requires uv, e.g., `hatch`, activating the
> environment will shadow the `uv` binary installed by this action and may result in a different uv
> version being used.
>
> We do not recommend using this setting for most use-cases. Instead, use `uv run` to execute
> commands in the environment.
### Working directory
You can set the working directory with the `working-directory` input.
This controls where we look for `pyproject.toml`, `uv.toml` and `.python-version` files
which are used to determine the version of uv and python to install.
It also controls where [the venv gets created](#activate-environment), unless `venv-path` is set.
It also controls where [the venv gets created](#activate-environment).
```yaml
- name: Install uv based on the config files in the working-directory
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v6
with:
working-directory: my/subproject/dir
```
## Advanced Configuration
### Validate checksum
For more advanced configuration options, see our detailed documentation:
You can specify a checksum to validate the downloaded executable. Checksums up to the default version
are automatically verified by this action. The sha256 hashes can be found on the
[releases page](https://github.com/astral-sh/uv/releases) of the uv repo.
- **[Advanced Version Configuration](docs/advanced-version-configuration.md)** - Resolution strategies and version files
- **[Caching](docs/caching.md)** - Complete guide to caching configuration
- **[Environment and Tools](docs/environment-and-tools.md)** - Environment activation, tool directories, authentication, and environment variables
- **[Customization](docs/customization.md)** - Checksum validation, custom manifests, and problem matchers
```yaml
- name: Install a specific version and validate the checksum
uses: astral-sh/setup-uv@v6
with:
version: "0.3.1"
checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8"
```
### Enable caching
> [!NOTE]
> The cache is pruned before it is uploaded to the GitHub Actions cache. This can lead to
> 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
the GitHub Actions cache. This can speed up runs that reuse the cache by several minutes.
Caching is enabled by default on GitHub-hosted runners.
> [!TIP]
>
> On self-hosted runners this is usually not needed since the cache generated by uv on the runner's
> filesystem is not removed after a run. For more details see [Local cache path](#local-cache-path).
You can optionally define a custom cache key suffix.
```yaml
- name: Enable caching and define a custom cache key suffix
id: setup-uv
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
cache-suffix: "optional-suffix"
```
When the cache was successfully restored, the output `cache-hit` will be set to `true` and you can
use it in subsequent steps. For example, to use the cache in the above case:
```yaml
- name: Do something if the cache was restored
if: steps.setup-uv.outputs.cache-hit == 'true'
run: echo "Cache was restored"
```
#### Cache dependency glob
If you want to control when the GitHub Actions cache is invalidated, specify a glob pattern with the
`cache-dependency-glob` input. The GitHub Actions cache will be invalidated if any file matching the glob pattern
changes. If you use relative paths, they are relative to the repository root.
> [!NOTE]
>
> You can look up supported patterns [here](https://github.com/actions/toolkit/tree/main/packages/glob#patterns)
>
> The default is
> ```yaml
> cache-dependency-glob: |
> **/*requirements*.txt
> **/*requirements*.in
> **/*constraints*.txt
> **/*constraints*.in
> **/pyproject.toml
> **/uv.lock
> **/*.py.lock
> ```
```yaml
- name: Define a cache dependency glob
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
cache-dependency-glob: "**/pyproject.toml"
```
```yaml
- name: Define a list of cache dependency globs
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
cache-dependency-glob: |
**/requirements*.txt
**/pyproject.toml
```
```yaml
- name: Define an absolute cache dependency glob
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
cache-dependency-glob: "/tmp/my-folder/requirements*.txt"
```
```yaml
- name: Never invalidate the cache
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
cache-dependency-glob: ""
```
#### Restore cache
Restoring an existing cache can be enabled or disabled with the `restore-cache` input.
By default, the cache will be restored.
```yaml
- name: Don't restore an existing cache
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
restore-cache: false
```
#### Save cache
You can also disable saving the cache after the run with the `save-cache` input.
This can be useful to save cache storage when you know you will not use the cache of the run again.
By default, the cache will be saved.
```yaml
- name: Don't save the cache after the run
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
save-cache: false
```
### Local cache path
If caching is enabled, this action controls where uv stores its cache on the runner's filesystem
by setting `UV_CACHE_DIR`.
It defaults to `setup-uv-cache` in the `TMP` dir, `D:\a\_temp\uv-tool-dir` on Windows and
`/tmp/setup-uv-cache` on Linux/macOS. You can change the default by specifying the path with the
`cache-local-path` input.
> [!NOTE]
> If the environment variable `UV_CACHE_DIR` is already set this action will not override it.
> If you configured [cache-dir](https://docs.astral.sh/uv/reference/settings/#cache-dir) in your
> config file then it is also respected and this action will not set `UV_CACHE_DIR`.
```yaml
- name: Define a custom uv cache path
uses: astral-sh/setup-uv@v6
with:
cache-local-path: "/path/to/cache"
```
### Disable cache pruning
By default, the uv cache is pruned after every run, removing pre-built wheels, but retaining any
wheels that were built from source. On GitHub-hosted runners, it's typically faster to omit those
pre-built wheels from the cache (and instead re-download them from the registry on each run).
However, on self-hosted or local runners, preserving the cache may be more efficient. See
the [documentation](https://docs.astral.sh/uv/concepts/cache/#caching-in-continuous-integration) for
more information.
If you want to persist the entire cache across runs, disable cache pruning with the `prune-cache`
input.
```yaml
- name: Don't prune the cache before saving it
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
prune-cache: false
```
### Ignore nothing to cache
By default, the action will fail if caching is enabled but there is nothing to upload (the uv cache directory does not exist).
If you want to ignore this, set the `ignore-nothing-to-cache` input to `true`.
```yaml
- name: Ignore nothing to cache
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
ignore-nothing-to-cache: true
```
### Ignore empty workdir
By default, the action will warn if the workdir is empty, because this is usually the case when
`actions/checkout` is configured to run after `setup-uv`, which is not supported.
If you want to ignore this, set the `ignore-empty-workdir` input to `true`.
```yaml
- name: Ignore empty workdir
uses: astral-sh/setup-uv@v6
with:
ignore-empty-workdir: true
```
### GitHub authentication token
This action uses the GitHub API to fetch the uv release artifacts. To avoid hitting the GitHub API
rate limit too quickly, an authentication token can be provided via the `github-token` input. By
default, the `GITHUB_TOKEN` secret is used, which is automatically provided by GitHub Actions.
If the default
[permissions for the GitHub token](https://docs.github.com/en/actions/security-for-github-actions/security-guides/automatic-token-authentication#permissions-for-the-github_token)
are not sufficient, you can provide a custom GitHub token with the necessary permissions.
```yaml
- name: Install the latest version of uv with a custom GitHub token
uses: astral-sh/setup-uv@v6
with:
github-token: ${{ secrets.CUSTOM_GITHUB_TOKEN }}
```
### UV_TOOL_DIR
On Windows `UV_TOOL_DIR` is set to `uv-tool-dir` in the `TMP` dir (e.g. `D:\a\_temp\uv-tool-dir`).
On GitHub hosted runners this is on the much faster `D:` drive.
On all other platforms the tool environments are placed in the
[default location](https://docs.astral.sh/uv/concepts/tools/#tools-directory).
If you want to change this behaviour (especially on self-hosted runners) you can use the `tool-dir`
input:
```yaml
- name: Install the latest version of uv with a custom tool dir
uses: astral-sh/setup-uv@v6
with:
tool-dir: "/path/to/tool/dir"
```
### UV_TOOL_BIN_DIR
On Windows `UV_TOOL_BIN_DIR` is set to `uv-tool-bin-dir` in the `TMP` dir (e.g.
`D:\a\_temp\uv-tool-bin-dir`). On GitHub hosted runners this is on the much faster `D:` drive. This
path is also automatically added to the PATH.
On all other platforms the tool binaries get installed to the
[default location](https://docs.astral.sh/uv/concepts/tools/#the-bin-directory).
If you want to change this behaviour (especially on self-hosted runners) you can use the
`tool-bin-dir` input:
```yaml
- name: Install the latest version of uv with a custom tool bin dir
uses: astral-sh/setup-uv@v6
with:
tool-bin-dir: "/path/to/tool-bin/dir"
```
### Tilde Expansion
This action supports expanding the `~` character to the user's home directory for the following inputs:
- `version-file`
- `cache-local-path`
- `tool-dir`
- `tool-bin-dir`
- `cache-dependency-glob`
```yaml
- name: Expand the tilde character
uses: astral-sh/setup-uv@v6
with:
cache-local-path: "~/path/to/cache"
tool-dir: "~/path/to/tool/dir"
tool-bin-dir: "~/path/to/tool-bin/dir"
cache-dependency-glob: "~/my-cache-buster"
```
### Manifest file
The `manifest-file` input allows you to specify a JSON manifest that lists available uv versions,
architectures, and their download URLs. By default, this action uses the manifest file contained
in this repository, which is automatically updated with each release of uv.
The manifest file contains an array of objects, each describing a version,
architecture, platform, and the corresponding download URL. For example:
```json
[
{
"version": "0.7.13",
"artifactName": "uv-aarch64-apple-darwin.tar.gz",
"arch": "aarch64",
"platform": "apple-darwin",
"downloadUrl": "https://github.com/astral-sh/uv/releases/download/0.7.13/uv-aarch64-apple-darwin.tar.gz"
},
...
]
```
You can supply a custom manifest file URL to define additional versions,
architectures, or different download URLs.
This is useful if you maintain your own uv builds or want to override the default sources.
```yaml
- name: Use a custom manifest file
uses: astral-sh/setup-uv@v6
with:
manifest-file: "https://example.com/my-custom-manifest.json"
```
> [!NOTE]
> When you use a custom manifest file and do not set the `version` input, its default value is `latest`.
> This means the action will install the latest version available in the custom manifest file.
> This is different from the default behavior of installing the latest version from the official uv releases.
### Add problem matchers
This action automatically adds
[problem matchers](https://github.com/actions/toolkit/blob/main/docs/problem-matchers.md)
for python errors.
You can disable this by setting the `add-problem-matchers` input to `false`.
```yaml
- name: Install the latest version of uv without problem matchers
uses: astral-sh/setup-uv@v6
with:
add-problem-matchers: false
```
## How it works
@ -205,8 +526,7 @@ by name (`uv`).
With `setup-uv`, you can install a specific version of Python using `uv python install` rather than
relying on `actions/setup-python`.
Using `actions/setup-python` can be faster (~1s), because GitHub includes several Python versions in the runner image
which are available to get activated by `actions/setup-python` without having to download them.
Using `actions/setup-python` can be faster, because GitHub caches the Python versions alongside the runner.
For example:
@ -214,7 +534,7 @@ For example:
- name: Checkout the repository
uses: actions/checkout@main
- name: Install the latest version of uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
- name: Test
@ -226,7 +546,7 @@ To install a specific version of Python, use
```yaml
- name: Install the latest version of uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
- name: Install Python 3.12
@ -245,7 +565,7 @@ output:
uses: actions/checkout@main
- name: Install the default version of uv
id: setup-uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v6
- name: Print the installed version
run: echo "Installed uv version is ${{ steps.setup-uv.outputs.uv-version }}"
```
@ -254,13 +574,14 @@ output:
**Yes!**
The cache key gets computed by using the cache-dependency-glob (see [Caching documentation](docs/caching.md)).
The cache key gets computed by using the [cache-dependency-glob](#cache-dependency-glob).
If you have jobs which use the same dependency definitions from `requirements.txt` or
If you
have jobs which use the same dependency definitions from `requirements.txt` or
`pyproject.toml` but different
[resolution strategies](https://docs.astral.sh/uv/concepts/resolution/#resolution-strategy),
each job will have different dependencies or dependency versions.
But if you do not add the resolution strategy as a cache-suffix (see [Caching documentation](docs/caching.md)),
But if you do not add the resolution strategy as a [cache-suffix](#enable-caching),
they will have the same cache key.
This means the first job which starts uploading its cache will win and all other job will fail
@ -273,15 +594,15 @@ You might see errors like
### Why do I see warnings like `No GitHub Actions cache found for key`
When a workflow runs for the first time on a branch and has a new cache key, because the
cache-dependency-glob (see [Caching documentation](docs/caching.md)) found changed files (changed dependencies),
[cache-dependency-glob](#cache-dependency-glob) found changed files (changed dependencies),
the cache will not be found and the warning `No GitHub Actions cache found for key` will be printed.
While this might be irritating at first, it is expected behaviour and the cache will be created
and reused in later workflows.
The reason for the warning is that we have to way to know if this is the first run of a new
cache key or the user accidentally misconfigured the cache-dependency-glob
or cache-suffix (see [Caching documentation](docs/caching.md)) and the cache never gets used.
The reason for the warning is, that we have to way to know if this is the first run of a new
cache key or the user accidentally misconfigured the [cache-dependency-glob](#cache-dependency-glob)
or [cache-suffix](#enable-caching) and the cache never gets used.
### Do I have to run `actions/checkout` before or after `setup-uv`?
@ -292,7 +613,7 @@ Running `actions/checkout` after `setup-uv` **is not supported**.
### Does `setup-uv` also install my project or its dependencies automatically?
No, `setup-uv` alone won't install any libraries from your `pyproject.toml` or `requirements.txt`, it only sets up `uv`.
No, `setup-uv` alone wont install any libraries from your `pyproject.toml` or `requirements.txt`, it only sets up `uv`.
You should run `uv sync` or `uv pip install .` separately, or use `uv run ...` to ensure necessary dependencies are installed.
### Why is a changed cache not detected and not the full cache uploaded?
@ -306,11 +627,11 @@ if an uploaded cache exists for this key.
If yes (e.g. contents of `uv.lock` did not change since last run) the dependencies in the cache
are up to date and the cache will be downloaded and used.
Details on determining which files will lead to different caches can be read in the
[Caching documentation](docs/caching.md).
Details on determining which files will lead to different caches can be read under
[cache-dependency-glob](#cache-dependency-glob)
Some dependencies will never be uploaded to the cache and will be downloaded again on each run
as described in the [Caching documentation](docs/caching.md).
as described in [disable-cache-pruning](#disable-cache-pruning)
## Acknowledgements

View file

@ -29,9 +29,9 @@ it.each<KnownVersionFixture>([
known: false,
version: "0.0.15",
},
])("isknownVersion should return $known for version $version", ({
version,
known,
}) => {
expect(isknownVersion(version)).toBe(known);
});
])(
"isknownVersion should return $known for version $version",
({ version, known }) => {
expect(isknownVersion(version)).toBe(known);
},
);

View file

@ -9,5 +9,5 @@ dependencies = [
]
[build-system]
requires = ["uv_build>=0.9.22,<0.10.0"]
build-backend = "uv_build"
requires = ["hatchling"]
build-backend = "hatchling.build"

View file

@ -1,9 +1,33 @@
version = 1
revision = 3
requires-python = ">=3.8, <=3.9"
requires-python = ">=3.12"
[[package]]
name = "old-python-constraint-project"
name = "ruff"
version = "0.6.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/23/f4/279d044f66b79261fd37df76bf72b64471afab5d3b7906a01499c4451910/ruff-0.6.2.tar.gz", hash = "sha256:239ee6beb9e91feb8e0ec384204a763f36cb53fb895a1a364618c6abb076b3be", size = 2460281 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/72/4b/47dd7a69287afb4069fa42c198e899463605460a58120196711bfcf0446b/ruff-0.6.2-py3-none-linux_armv6l.whl", hash = "sha256:5c8cbc6252deb3ea840ad6a20b0f8583caab0c5ef4f9cca21adc5a92b8f79f3c", size = 9695871 },
{ url = "https://files.pythonhosted.org/packages/ae/c3/8aac62ac4638c14a740ee76a755a925f2d0d04580ab790a9887accb729f6/ruff-0.6.2-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:17002fe241e76544448a8e1e6118abecbe8cd10cf68fde635dad480dba594570", size = 9459354 },
{ url = "https://files.pythonhosted.org/packages/2f/cf/77fbd8d4617b9b9c503f9bffb8552c4e3ea1a58dc36975e7a9104ffb0f85/ruff-0.6.2-py3-none-macosx_11_0_arm64.whl", hash = "sha256:3dbeac76ed13456f8158b8f4fe087bf87882e645c8e8b606dd17b0b66c2c1158", size = 9163871 },
{ url = "https://files.pythonhosted.org/packages/05/1c/765192bab32b79efbb498b06f0b9dcb3629112b53b8777ae1d19b8209e09/ruff-0.6.2-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:094600ee88cda325988d3f54e3588c46de5c18dae09d683ace278b11f9d4d534", size = 10096250 },
{ url = "https://files.pythonhosted.org/packages/08/d0/86f3cb0f6934c99f759c232984a5204d67a26745cad2d9edff6248adf7d2/ruff-0.6.2-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:316d418fe258c036ba05fbf7dfc1f7d3d4096db63431546163b472285668132b", size = 9475376 },
{ url = "https://files.pythonhosted.org/packages/cd/cc/4c8d0e225b559a3fae6092ec310d7150d3b02b4669e9223f783ef64d82c0/ruff-0.6.2-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d72b8b3abf8a2d51b7b9944a41307d2f442558ccb3859bbd87e6ae9be1694a5d", size = 10295634 },
{ url = "https://files.pythonhosted.org/packages/db/96/d2699cfb1bb5a01c68122af43454c76c31331e1c8a9bd97d653d7c82524b/ruff-0.6.2-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:2aed7e243be68487aa8982e91c6e260982d00da3f38955873aecd5a9204b1d66", size = 11024941 },
{ url = "https://files.pythonhosted.org/packages/8b/a9/6ecd66af8929e0f2a1ed308a4137f3521789f28f0eb97d32c2ca3aa7000c/ruff-0.6.2-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d371f7fc9cec83497fe7cf5eaf5b76e22a8efce463de5f775a1826197feb9df8", size = 10606894 },
{ url = "https://files.pythonhosted.org/packages/e4/73/2ee4cd19f44992fedac1cc6db9e3d825966072f6dcbd4032f21cbd063170/ruff-0.6.2-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a8f310d63af08f583363dfb844ba8f9417b558199c58a5999215082036d795a1", size = 11552886 },
{ url = "https://files.pythonhosted.org/packages/60/4c/c0f1cd35ce4a93c54a6bb1ee6934a3a205fa02198dd076678193853ceea1/ruff-0.6.2-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7db6880c53c56addb8638fe444818183385ec85eeada1d48fc5abe045301b2f1", size = 10264945 },
{ url = "https://files.pythonhosted.org/packages/c4/89/e45c9359b9cdd4245512ea2b9f2bb128a997feaa5f726fc9e8c7a66afadf/ruff-0.6.2-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:1175d39faadd9a50718f478d23bfc1d4da5743f1ab56af81a2b6caf0a2394f23", size = 10100007 },
{ url = "https://files.pythonhosted.org/packages/06/74/0bd4e0a7ed5f6908df87892f9bf60a2356c0fd74102d8097298bd9b4f346/ruff-0.6.2-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:5b939f9c86d51635fe486585389f54582f0d65b8238e08c327c1534844b3bb9a", size = 9559267 },
{ url = "https://files.pythonhosted.org/packages/54/03/3dc6dc9419f276f05805bf888c279e3e0b631284abd548d9e87cebb93aec/ruff-0.6.2-py3-none-musllinux_1_2_i686.whl", hash = "sha256:d0d62ca91219f906caf9b187dea50d17353f15ec9bb15aae4a606cd697b49b4c", size = 9905304 },
{ url = "https://files.pythonhosted.org/packages/5c/5b/d6a72a6a6bbf097c09de468326ef5fa1c9e7aa5e6e45979bc0d984b0dbe7/ruff-0.6.2-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:7438a7288f9d67ed3c8ce4d059e67f7ed65e9fe3aa2ab6f5b4b3610e57e3cb56", size = 10341480 },
{ url = "https://files.pythonhosted.org/packages/79/a9/0f2f21fe15ba537c46598f96aa9ae4a3d4b9ec64926664617ca6a8c772f4/ruff-0.6.2-py3-none-win32.whl", hash = "sha256:279d5f7d86696df5f9549b56b9b6a7f6c72961b619022b5b7999b15db392a4da", size = 7961901 },
{ url = "https://files.pythonhosted.org/packages/b0/80/fff12ffe11853d9f4ea3e5221e6dd2e93640a161c05c9579833e09ad40a7/ruff-0.6.2-py3-none-win_amd64.whl", hash = "sha256:d9f3469c7dd43cd22eb1c3fc16926fb8258d50cb1b216658a07be95dd117b0f2", size = 8783320 },
{ url = "https://files.pythonhosted.org/packages/56/91/577cdd64cce5e74d3f8b5ecb93f29566def569c741eb008aed4f331ef821/ruff-0.6.2-py3-none-win_arm64.whl", hash = "sha256:f28fcd2cd0e02bdf739297516d5643a945cc7caf09bd9bcb4d932540a5ea4fa9", size = 8225886 },
]
[[package]]
name = "uv-project"
version = "0.1.0"
source = { editable = "." }
dependencies = [
@ -11,30 +35,4 @@ dependencies = [
]
[package.metadata]
requires-dist = [{ name = "ruff", specifier = ">=0.6.2" }]
[[package]]
name = "ruff"
version = "0.14.10"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/57/08/52232a877978dd8f9cf2aeddce3e611b40a63287dfca29b6b8da791f5e8d/ruff-0.14.10.tar.gz", hash = "sha256:9a2e830f075d1a42cd28420d7809ace390832a490ed0966fe373ba288e77aaf4", size = 5859763, upload-time = "2025-12-18T19:28:57.98Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/60/01/933704d69f3f05ee16ef11406b78881733c186fe14b6a46b05cfcaf6d3b2/ruff-0.14.10-py3-none-linux_armv6l.whl", hash = "sha256:7a3ce585f2ade3e1f29ec1b92df13e3da262178df8c8bdf876f48fa0e8316c49", size = 13527080, upload-time = "2025-12-18T19:29:25.642Z" },
{ url = "https://files.pythonhosted.org/packages/df/58/a0349197a7dfa603ffb7f5b0470391efa79ddc327c1e29c4851e85b09cc5/ruff-0.14.10-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:674f9be9372907f7257c51f1d4fc902cb7cf014b9980152b802794317941f08f", size = 13797320, upload-time = "2025-12-18T19:29:02.571Z" },
{ url = "https://files.pythonhosted.org/packages/7b/82/36be59f00a6082e38c23536df4e71cdbc6af8d7c707eade97fcad5c98235/ruff-0.14.10-py3-none-macosx_11_0_arm64.whl", hash = "sha256:d85713d522348837ef9df8efca33ccb8bd6fcfc86a2cde3ccb4bc9d28a18003d", size = 12918434, upload-time = "2025-12-18T19:28:51.202Z" },
{ url = "https://files.pythonhosted.org/packages/a6/00/45c62a7f7e34da92a25804f813ebe05c88aa9e0c25e5cb5a7d23dd7450e3/ruff-0.14.10-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6987ebe0501ae4f4308d7d24e2d0fe3d7a98430f5adfd0f1fead050a740a3a77", size = 13371961, upload-time = "2025-12-18T19:29:04.991Z" },
{ url = "https://files.pythonhosted.org/packages/40/31/a5906d60f0405f7e57045a70f2d57084a93ca7425f22e1d66904769d1628/ruff-0.14.10-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:16a01dfb7b9e4eee556fbfd5392806b1b8550c9b4a9f6acd3dbe6812b193c70a", size = 13275629, upload-time = "2025-12-18T19:29:21.381Z" },
{ url = "https://files.pythonhosted.org/packages/3e/60/61c0087df21894cf9d928dc04bcd4fb10e8b2e8dca7b1a276ba2155b2002/ruff-0.14.10-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7165d31a925b7a294465fa81be8c12a0e9b60fb02bf177e79067c867e71f8b1f", size = 14029234, upload-time = "2025-12-18T19:29:00.132Z" },
{ url = "https://files.pythonhosted.org/packages/44/84/77d911bee3b92348b6e5dab5a0c898d87084ea03ac5dc708f46d88407def/ruff-0.14.10-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:c561695675b972effb0c0a45db233f2c816ff3da8dcfbe7dfc7eed625f218935", size = 15449890, upload-time = "2025-12-18T19:28:53.573Z" },
{ url = "https://files.pythonhosted.org/packages/e9/36/480206eaefa24a7ec321582dda580443a8f0671fdbf6b1c80e9c3e93a16a/ruff-0.14.10-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4bb98fcbbc61725968893682fd4df8966a34611239c9fd07a1f6a07e7103d08e", size = 15123172, upload-time = "2025-12-18T19:29:23.453Z" },
{ url = "https://files.pythonhosted.org/packages/5c/38/68e414156015ba80cef5473d57919d27dfb62ec804b96180bafdeaf0e090/ruff-0.14.10-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f24b47993a9d8cb858429e97bdf8544c78029f09b520af615c1d261bf827001d", size = 14460260, upload-time = "2025-12-18T19:29:27.808Z" },
{ url = "https://files.pythonhosted.org/packages/b3/19/9e050c0dca8aba824d67cc0db69fb459c28d8cd3f6855b1405b3f29cc91d/ruff-0.14.10-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59aabd2e2c4fd614d2862e7939c34a532c04f1084476d6833dddef4afab87e9f", size = 14229978, upload-time = "2025-12-18T19:29:11.32Z" },
{ url = "https://files.pythonhosted.org/packages/51/eb/e8dd1dd6e05b9e695aa9dd420f4577debdd0f87a5ff2fedda33c09e9be8c/ruff-0.14.10-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:213db2b2e44be8625002dbea33bb9c60c66ea2c07c084a00d55732689d697a7f", size = 14338036, upload-time = "2025-12-18T19:29:09.184Z" },
{ url = "https://files.pythonhosted.org/packages/6a/12/f3e3a505db7c19303b70af370d137795fcfec136d670d5de5391e295c134/ruff-0.14.10-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:b914c40ab64865a17a9a5b67911d14df72346a634527240039eb3bd650e5979d", size = 13264051, upload-time = "2025-12-18T19:29:13.431Z" },
{ url = "https://files.pythonhosted.org/packages/08/64/8c3a47eaccfef8ac20e0484e68e0772013eb85802f8a9f7603ca751eb166/ruff-0.14.10-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1484983559f026788e3a5c07c81ef7d1e97c1c78ed03041a18f75df104c45405", size = 13283998, upload-time = "2025-12-18T19:29:06.994Z" },
{ url = "https://files.pythonhosted.org/packages/12/84/534a5506f4074e5cc0529e5cd96cfc01bb480e460c7edf5af70d2bcae55e/ruff-0.14.10-py3-none-musllinux_1_2_i686.whl", hash = "sha256:c70427132db492d25f982fffc8d6c7535cc2fd2c83fc8888f05caaa248521e60", size = 13601891, upload-time = "2025-12-18T19:28:55.811Z" },
{ url = "https://files.pythonhosted.org/packages/0d/1e/14c916087d8598917dbad9b2921d340f7884824ad6e9c55de948a93b106d/ruff-0.14.10-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:5bcf45b681e9f1ee6445d317ce1fa9d6cba9a6049542d1c3d5b5958986be8830", size = 14336660, upload-time = "2025-12-18T19:29:16.531Z" },
{ url = "https://files.pythonhosted.org/packages/f2/1c/d7b67ab43f30013b47c12b42d1acd354c195351a3f7a1d67f59e54227ede/ruff-0.14.10-py3-none-win32.whl", hash = "sha256:104c49fc7ab73f3f3a758039adea978869a918f31b73280db175b43a2d9b51d6", size = 13196187, upload-time = "2025-12-18T19:29:19.006Z" },
{ url = "https://files.pythonhosted.org/packages/fb/9c/896c862e13886fae2af961bef3e6312db9ebc6adc2b156fe95e615dee8c1/ruff-0.14.10-py3-none-win_amd64.whl", hash = "sha256:466297bd73638c6bdf06485683e812db1c00c7ac96d4ddd0294a338c62fdc154", size = 14661283, upload-time = "2025-12-18T19:29:30.16Z" },
{ url = "https://files.pythonhosted.org/packages/74/31/b0e29d572670dca3674eeee78e418f20bdf97fa8aa9ea71380885e175ca0/ruff-0.14.10-py3-none-win_arm64.whl", hash = "sha256:e51d046cf6dda98a4633b8a8a771451107413b0f07183b2bef03f075599e44e6", size = 13729839, upload-time = "2025-12-18T19:28:48.636Z" },
]
requires-dist = [{ name = "ruff" }]

View file

@ -5,7 +5,6 @@ jest.mock("@actions/core", () => {
(name: string) => (mockInputs[name] ?? "") === "true",
),
getInput: jest.fn((name: string) => mockInputs[name] ?? ""),
warning: jest.fn(),
};
});
@ -25,7 +24,6 @@ const ORIGINAL_HOME = process.env.HOME;
describe("cacheDependencyGlob", () => {
beforeEach(() => {
jest.resetModules();
jest.clearAllMocks();
mockInputs = {};
process.env.HOME = "/home/testuser";
});
@ -86,125 +84,3 @@ describe("cacheDependencyGlob", () => {
);
});
});
describe("tool directories", () => {
beforeEach(() => {
jest.resetModules();
jest.clearAllMocks();
mockInputs = {};
process.env.HOME = "/home/testuser";
});
afterEach(() => {
process.env.HOME = ORIGINAL_HOME;
});
it("expands tilde for tool-bin-dir and tool-dir", async () => {
mockInputs["working-directory"] = "/workspace";
mockInputs["tool-bin-dir"] = "~/tool-bin-dir";
mockInputs["tool-dir"] = "~/tool-dir";
const { toolBinDir, toolDir } = await import("../../src/utils/inputs");
expect(toolBinDir).toBe("/home/testuser/tool-bin-dir");
expect(toolDir).toBe("/home/testuser/tool-dir");
});
});
describe("cacheLocalPath", () => {
beforeEach(() => {
jest.resetModules();
jest.clearAllMocks();
mockInputs = {};
process.env.HOME = "/home/testuser";
});
afterEach(() => {
process.env.HOME = ORIGINAL_HOME;
});
it("expands tilde in cache-local-path", async () => {
mockInputs["working-directory"] = "/workspace";
mockInputs["cache-local-path"] = "~/uv-cache/cache-local-path";
const { CacheLocalSource, cacheLocalPath } = await import(
"../../src/utils/inputs"
);
expect(cacheLocalPath).toEqual({
path: "/home/testuser/uv-cache/cache-local-path",
source: CacheLocalSource.Input,
});
});
});
describe("venvPath", () => {
beforeEach(() => {
jest.resetModules();
jest.clearAllMocks();
mockInputs = {};
process.env.HOME = "/home/testuser";
});
afterEach(() => {
process.env.HOME = ORIGINAL_HOME;
});
it("defaults to .venv in the working directory", async () => {
mockInputs["working-directory"] = "/workspace";
const { venvPath } = await import("../../src/utils/inputs");
expect(venvPath).toBe("/workspace/.venv");
});
it("resolves a relative venv-path", async () => {
mockInputs["working-directory"] = "/workspace";
mockInputs["activate-environment"] = "true";
mockInputs["venv-path"] = "custom-venv";
const { venvPath } = await import("../../src/utils/inputs");
expect(venvPath).toBe("/workspace/custom-venv");
});
it("normalizes venv-path with trailing slash", async () => {
mockInputs["working-directory"] = "/workspace";
mockInputs["activate-environment"] = "true";
mockInputs["venv-path"] = "custom-venv/";
const { venvPath } = await import("../../src/utils/inputs");
expect(venvPath).toBe("/workspace/custom-venv");
});
it("keeps an absolute venv-path unchanged", async () => {
mockInputs["working-directory"] = "/workspace";
mockInputs["activate-environment"] = "true";
mockInputs["venv-path"] = "/tmp/custom-venv";
const { venvPath } = await import("../../src/utils/inputs");
expect(venvPath).toBe("/tmp/custom-venv");
});
it("expands tilde in venv-path", async () => {
mockInputs["working-directory"] = "/workspace";
mockInputs["activate-environment"] = "true";
mockInputs["venv-path"] = "~/.venv";
const { venvPath } = await import("../../src/utils/inputs");
expect(venvPath).toBe("/home/testuser/.venv");
});
it("warns when venv-path is set but activate-environment is false", async () => {
mockInputs["working-directory"] = "/workspace";
mockInputs["venv-path"] = "custom-venv";
const { activateEnvironment, venvPath } = await import(
"../../src/utils/inputs"
);
expect(activateEnvironment).toBe(false);
expect(venvPath).toBe("/workspace/custom-venv");
const mockedCore = jest.requireMock("@actions/core") as {
warning: jest.Mock;
};
expect(mockedCore.warning).toHaveBeenCalledWith(
"venv-path is only used when activate-environment is true",
);
});
});

View file

@ -1,77 +0,0 @@
# See https://github.com/typesafegithub/github-actions-typing
inputs:
version:
type: string
version-file:
type: string
python-version:
type: string
activate-environment:
type: boolean
venv-path:
type: string
working-directory:
type: string
checksum:
type: string
github-token:
type: string
enable-cache:
type: enum
allowed-values:
- "true"
- "false"
- auto
cache-dependency-glob:
type: list
separator: "\n"
list-item:
type: string
restore-cache:
type: boolean
save-cache:
type: boolean
cache-suffix:
type: string
cache-local-path:
type: string
prune-cache:
type: boolean
cache-python:
type: boolean
ignore-nothing-to-cache:
type: boolean
ignore-empty-workdir:
type: boolean
tool-dir:
type: string
tool-bin-dir:
type: string
manifest-file:
type: string
add-problem-matchers:
type: boolean
resolution-strategy:
type: enum
allowed-values:
- highest
- lowest
outputs:
uv-version:
type: string
uv-path:
type: string
uvx-path:
type: string
cache-hit:
type: boolean
cache-key:
type: string
venv:
type: string
python-version:
type: string
python-cache-hit:
type: boolean

View file

@ -15,9 +15,6 @@ inputs:
activate-environment:
description: "Use uv venv to activate a venv ready to be used by later steps. "
default: "false"
venv-path:
description: "Custom path for the virtual environment when using activate-environment. Defaults to '.venv' in the working directory."
default: ""
working-directory:
description: "The directory to execute all commands in and look for files such as pyproject.toml"
default: ${{ github.workspace }}
@ -34,7 +31,7 @@ inputs:
default: "auto"
cache-dependency-glob:
description:
"Glob pattern to match files relative to the working directory to control
"Glob pattern to match files relative to the repository root to control
the cache."
default: |
**/*requirements*.txt
@ -59,9 +56,6 @@ inputs:
prune-cache:
description: "Prune cache before saving."
default: "true"
cache-python:
description: "Upload managed Python installations to the Github Actions cache."
default: "false"
ignore-nothing-to-cache:
description: "Ignore when nothing is found to cache."
default: "false"
@ -80,9 +74,6 @@ inputs:
add-problem-matchers:
description: "Add problem matchers."
default: "true"
resolution-strategy:
description: "Resolution strategy to use when resolving version ranges. 'highest' uses the latest compatible version, 'lowest' uses the oldest compatible version."
default: "highest"
outputs:
uv-version:
description: "The installed uv version. Useful when using latest."
@ -92,14 +83,6 @@ outputs:
description: "The path to the installed uvx binary."
cache-hit:
description: "A boolean value to indicate a cache entry was found"
cache-key:
description: "The cache key used for storing/restoring the cache"
venv:
description: "Path to the activated venv if activate-environment is true"
python-version:
description: "The Python version that was set."
python-cache-hit:
description: "A boolean value to indicate the Python cache entry was found"
runs:
using: "node24"
main: "dist/setup/index.js"

View file

@ -1,5 +1,5 @@
{
"$schema": "https://biomejs.dev/schemas/2.3.7/schema.json",
"$schema": "https://biomejs.dev/schemas/2.2.4/schema.json",
"assist": {
"actions": {
"source": {
@ -18,8 +18,7 @@
"!**/node_modules",
"!**/package*.json",
"!**/known-checksums.*"
],
"maxSize": 2097152
]
},
"formatter": {
"enabled": true,

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

File diff suppressed because one or more lines are too long

61562
dist/setup/index.js generated vendored

File diff suppressed because one or more lines are too long

42123
dist/update-known-versions/index.js generated vendored

File diff suppressed because one or more lines are too long

View file

@ -1,82 +0,0 @@
# Advanced Version Configuration
This document covers advanced options for configuring which version of uv to install.
## Install the latest version
```yaml
- name: Install the latest version of uv
uses: astral-sh/setup-uv@v7
with:
version: "latest"
```
## Install a specific version
```yaml
- name: Install a specific version of uv
uses: astral-sh/setup-uv@v7
with:
version: "0.4.4"
```
## Install a version by supplying a semver range or pep440 specifier
You can specify a [semver range](https://github.com/npm/node-semver?tab=readme-ov-file#ranges)
or [pep440 specifier](https://peps.python.org/pep-0440/#version-specifiers)
to install the latest version that satisfies the range.
```yaml
- name: Install a semver range of uv
uses: astral-sh/setup-uv@v7
with:
version: ">=0.4.0"
```
```yaml
- name: Pinning a minor version of uv
uses: astral-sh/setup-uv@v7
with:
version: "0.4.x"
```
```yaml
- name: Install a pep440-specifier-satisfying version of uv
uses: astral-sh/setup-uv@v7
with:
version: ">=0.4.25,<0.5"
```
## Resolution strategy
By default, when resolving version ranges, setup-uv will install the highest compatible version.
You can change this behavior using the `resolution-strategy` input:
```yaml
- name: Install the lowest compatible version of uv
uses: astral-sh/setup-uv@v7
with:
version: ">=0.4.0"
resolution-strategy: "lowest"
```
The supported resolution strategies are:
- `highest` (default): Install the latest version that satisfies the constraints
- `lowest`: Install the oldest version that satisfies the constraints
This can be useful for testing compatibility with older versions of uv, similar to uv's own `--resolution-strategy` option.
## Install a version defined in a requirements or config file
You can use the `version-file` input to specify a file that contains the version of uv to install.
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`.
[asdf](https://asdf-vm.com/) `.tool-versions` is also supported, but without the `ref` syntax.
```yaml
- name: Install uv based on the version defined in pyproject.toml
uses: astral-sh/setup-uv@v7
with:
version-file: "pyproject.toml"
```

View file

@ -1,225 +0,0 @@
# Caching
This document covers all caching-related configuration options for setup-uv.
## Cache key
The cache key is automatically generated based on:
- **Architecture**: CPU architecture (e.g., `x86_64`, `aarch64`)
- **Platform**: OS platform type (e.g., `unknown-linux-gnu`, `unknown-linux-musl`, `apple-darwin`,
`pc-windows-msvc`)
- **OS version**: OS name and version (e.g., `ubuntu-22.04`, `macos-14`, `windows-2022`)
- **Python version**: The Python version in use
- **Cache options**: Whether pruning and Python caching are enabled
- **Dependency hash**: Hash of files matching `cache-dependency-glob`
- **Suffix**: Optional `cache-suffix` if provided
Including the OS version ensures that caches are not shared between different OS versions,
preventing binary incompatibility issues when runner images change.
The computed cache key is available as the `cache-key` output:
```yaml
- name: Setup uv
id: setup-uv
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
- name: Print cache key
run: echo "Cache key: ${{ steps.setup-uv.outputs.cache-key }}"
```
## Enable caching
> [!NOTE]
> The cache is pruned before it is uploaded to the GitHub Actions cache. This can lead to
> 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
the GitHub Actions cache. This can speed up runs that reuse the cache by several minutes.
Caching is enabled by default on GitHub-hosted runners.
> [!TIP]
>
> On self-hosted runners this is usually not needed since the cache generated by uv on the runner's
> filesystem is not removed after a run. For more details see [Local cache path](#local-cache-path).
You can optionally define a custom cache key suffix.
```yaml
- name: Enable caching and define a custom cache key suffix
id: setup-uv
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
cache-suffix: "optional-suffix"
```
When the cache was successfully restored, the output `cache-hit` will be set to `true` and you can
use it in subsequent steps. For example, to use the cache in the above case:
```yaml
- name: Do something if the cache was restored
if: steps.setup-uv.outputs.cache-hit == 'true'
run: echo "Cache was restored"
```
## Cache dependency glob
If you want to control when the GitHub Actions cache is invalidated, specify a glob pattern with the
`cache-dependency-glob` input. The GitHub Actions cache will be invalidated if any file matching the glob pattern
changes. If you use relative paths, they are relative to the working directory.
> [!NOTE]
>
> You can look up supported patterns [here](https://github.com/actions/toolkit/tree/main/packages/glob#patterns)
>
> The default is
> ```yaml
> cache-dependency-glob: |
> **/*requirements*.txt
> **/*requirements*.in
> **/*constraints*.txt
> **/*constraints*.in
> **/pyproject.toml
> **/uv.lock
> **/*.py.lock
> ```
```yaml
- name: Define a cache dependency glob
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
cache-dependency-glob: "**/pyproject.toml"
```
```yaml
- name: Define a list of cache dependency globs
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
cache-dependency-glob: |
**/requirements*.txt
**/pyproject.toml
```
```yaml
- name: Define an absolute cache dependency glob
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
cache-dependency-glob: "/tmp/my-folder/requirements*.txt"
```
```yaml
- name: Never invalidate the cache
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
cache-dependency-glob: ""
```
## Restore cache
Restoring an existing cache can be enabled or disabled with the `restore-cache` input.
By default, the cache will be restored.
```yaml
- name: Don't restore an existing cache
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
restore-cache: false
```
## Save cache
You can also disable saving the cache after the run with the `save-cache` input.
This can be useful to save cache storage when you know you will not use the cache of the run again.
By default, the cache will be saved.
```yaml
- name: Don't save the cache after the run
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
save-cache: false
```
## Local cache path
If caching is enabled, this action controls where uv stores its cache on the runner's filesystem
by setting `UV_CACHE_DIR`.
It defaults to `setup-uv-cache` in the `TMP` dir, `D:\a\_temp\setup-uv-cache` on Windows and
`/tmp/setup-uv-cache` on Linux/macOS. You can change the default by specifying the path with the
`cache-local-path` input.
> [!NOTE]
> If the environment variable `UV_CACHE_DIR` is already set this action will not override it.
> If you configured [cache-dir](https://docs.astral.sh/uv/reference/settings/#cache-dir) in your
> config file then it is also respected and this action will not set `UV_CACHE_DIR`.
> [!NOTE]
> If caching is disabled, you can still use `cache-local-path` so this action sets `UV_CACHE_DIR`
> to your desired path.
```yaml
- name: Define a custom uv cache path
uses: astral-sh/setup-uv@v7
with:
cache-local-path: "/path/to/cache"
```
## Disable cache pruning
By default, the uv cache is pruned after every run, removing pre-built wheels, but retaining any
wheels that were built from source. On GitHub-hosted runners, it's typically faster to omit those
pre-built wheels from the cache (and instead re-download them from the registry on each run).
However, on self-hosted or local runners, preserving the cache may be more efficient. See
the [documentation](https://docs.astral.sh/uv/concepts/cache/#caching-in-continuous-integration) for
more information.
If you want to persist the entire cache across runs, disable cache pruning with the `prune-cache`
input.
```yaml
- name: Don't prune the cache before saving it
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
prune-cache: false
```
## Cache Python installs
By default, the Python install dir (`uv python dir` / `UV_PYTHON_INSTALL_DIR`) is not cached,
for the same reason that the dependency cache is pruned.
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`
(i.e. managed Python installs). If uv uses a system Python, there may be nothing to cache.
To force managed Python installs, set `UV_PYTHON_PREFERENCE=only-managed`.
```yaml
- name: Cache Python installs
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
cache-python: true
```
## Ignore nothing to cache
By default, the action will fail if caching is enabled but there is nothing to upload (the uv cache directory does not exist).
If you want to ignore this, set the `ignore-nothing-to-cache` input to `true`.
```yaml
- name: Ignore nothing to cache
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
ignore-nothing-to-cache: true
```

View file

@ -1,70 +0,0 @@
# Customization
This document covers advanced customization options including checksum validation, custom manifests, and problem matchers.
## Validate checksum
You can specify a checksum to validate the downloaded executable. Checksums up to the default version
are automatically verified by this action. The sha256 hashes can be found on the
[releases page](https://github.com/astral-sh/uv/releases) of the uv repo.
```yaml
- name: Install a specific version and validate the checksum
uses: astral-sh/setup-uv@v7
with:
version: "0.3.1"
checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8"
```
## Manifest file
The `manifest-file` input allows you to specify a JSON manifest that lists available uv versions,
architectures, and their download URLs. By default, this action uses the manifest file contained
in this repository, which is automatically updated with each release of uv.
The manifest file contains an array of objects, each describing a version,
architecture, platform, and the corresponding download URL. For example:
```json
[
{
"version": "0.7.13",
"artifactName": "uv-aarch64-apple-darwin.tar.gz",
"arch": "aarch64",
"platform": "apple-darwin",
"downloadUrl": "https://github.com/astral-sh/uv/releases/download/0.7.13/uv-aarch64-apple-darwin.tar.gz"
},
...
]
```
You can supply a custom manifest file URL to define additional versions,
architectures, or different download URLs.
This is useful if you maintain your own uv builds or want to override the default sources.
```yaml
- name: Use a custom manifest file
uses: astral-sh/setup-uv@v7
with:
manifest-file: "https://example.com/my-custom-manifest.json"
```
> [!NOTE]
> When you use a custom manifest file and do not set the `version` input, its default value is `latest`.
> This means the action will install the latest version available in the custom manifest file.
> This is different from the default behavior of installing the latest version from the official uv releases.
## Add problem matchers
This action automatically adds
[problem matchers](https://github.com/actions/toolkit/blob/main/docs/problem-matchers.md)
for python errors.
You can disable this by setting the `add-problem-matchers` input to `false`.
```yaml
- name: Install the latest version of uv without problem matchers
uses: astral-sh/setup-uv@v7
with:
add-problem-matchers: false
```

View file

@ -1,157 +0,0 @@
# Environment and Tools
This document covers environment activation, tool directory configuration, and authentication options.
## Activate environment
You can set `activate-environment` to `true` to automatically activate a venv.
This allows directly using it in later steps:
```yaml
- name: Install the latest version of uv and activate the environment
uses: astral-sh/setup-uv@v7
with:
activate-environment: true
- run: uv pip install pip
```
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:
```yaml
- uses: astral-sh/setup-uv@v7
with:
activate-environment: true
venv-path: ${{ runner.temp }}/custom-venv
```
> [!WARNING]
>
> Activating the environment adds your dependencies to the `PATH`, which could break some workflows.
> For example, if you have a dependency which requires uv, e.g., `hatch`, activating the
> environment will shadow the `uv` binary installed by this action and may result in a different uv
> version being used.
>
> We do not recommend using this setting for most use-cases. Instead, use `uv run` to execute
> commands in the environment.
## GitHub authentication token
This action uses the GitHub API to fetch the uv release artifacts. To avoid hitting the GitHub API
rate limit too quickly, an authentication token can be provided via the `github-token` input. By
default, the `GITHUB_TOKEN` secret is used, which is automatically provided by GitHub Actions.
If the default
[permissions for the GitHub token](https://docs.github.com/en/actions/security-for-github-actions/security-guides/automatic-token-authentication#permissions-for-the-github_token)
are not sufficient, you can provide a custom GitHub token with the necessary permissions.
```yaml
- name: Install the latest version of uv with a custom GitHub token
uses: astral-sh/setup-uv@v7
with:
github-token: ${{ secrets.CUSTOM_GITHUB_TOKEN }}
```
## UV_TOOL_DIR
On Windows `UV_TOOL_DIR` is set to `uv-tool-dir` in the `TMP` dir (e.g. `D:\a\_temp\uv-tool-dir`).
On GitHub hosted runners this is on the much faster `D:` drive.
On all other platforms the tool environments are placed in the
[default location](https://docs.astral.sh/uv/concepts/tools/#tools-directory).
If you want to change this behaviour (especially on self-hosted runners) you can use the `tool-dir`
input:
```yaml
- name: Install the latest version of uv with a custom tool dir
uses: astral-sh/setup-uv@v7
with:
tool-dir: "/path/to/tool/dir"
```
## UV_TOOL_BIN_DIR
On Windows `UV_TOOL_BIN_DIR` is set to `uv-tool-bin-dir` in the `TMP` dir (e.g.
`D:\a\_temp\uv-tool-bin-dir`). On GitHub hosted runners this is on the much faster `D:` drive. This
path is also automatically added to the PATH.
On all other platforms the tool binaries get installed to the
[default location](https://docs.astral.sh/uv/concepts/tools/#the-bin-directory).
If you want to change this behaviour (especially on self-hosted runners) you can use the
`tool-bin-dir` input:
```yaml
- name: Install the latest version of uv with a custom tool bin dir
uses: astral-sh/setup-uv@v7
with:
tool-bin-dir: "/path/to/tool-bin/dir"
```
## Tilde Expansion
This action supports expanding the `~` character to the user's home directory for the following inputs:
- `version-file`
- `cache-local-path`
- `tool-dir`
- `tool-bin-dir`
- `cache-dependency-glob`
```yaml
- name: Expand the tilde character
uses: astral-sh/setup-uv@v7
with:
cache-local-path: "~/path/to/cache"
tool-dir: "~/path/to/tool/dir"
tool-bin-dir: "~/path/to/tool-bin/dir"
cache-dependency-glob: "~/my-cache-buster"
```
## Ignore empty workdir
By default, the action will warn if the workdir is empty, because this is usually the case when
`actions/checkout` is configured to run after `setup-uv`, which is not supported.
If you want to ignore this, set the `ignore-empty-workdir` input to `true`.
```yaml
- name: Ignore empty workdir
uses: astral-sh/setup-uv@v7
with:
ignore-empty-workdir: true
```
## Environment Variables
This action sets several environment variables that influence uv's behavior and can be used by subsequent steps:
- `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_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_PYTHON_INSTALL_DIR`: Always set. Controls where uv installs Python versions.
- `VIRTUAL_ENV`: Set when `activate-environment` is true. Points to the activated virtual environment.
**Environment variables that affect the action behavior:**
- `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.
```yaml
- name: Example using environment variables
uses: astral-sh/setup-uv@v7
with:
python-version: "3.12"
tool-dir: "/custom/tool/dir"
enable-cache: true
- name: Check environment variables
run: |
echo "UV_PYTHON: $UV_PYTHON"
echo "UV_CACHE_DIR: $UV_CACHE_DIR"
echo "UV_TOOL_DIR: $UV_TOOL_DIR"
echo "UV_PYTHON_INSTALL_DIR: $UV_PYTHON_INSTALL_DIR"
```

1890
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -17,37 +17,32 @@
"type": "git",
"url": "git+https://github.com/astral-sh/setup-uv.git"
},
"keywords": [
"actions",
"python",
"setup",
"uv"
],
"keywords": ["actions", "python", "setup", "uv"],
"author": "@eifinger",
"license": "MIT",
"dependencies": {
"@actions/cache": "^4.1.0",
"@actions/cache": "^4.0.5",
"@actions/core": "^1.11.1",
"@actions/exec": "^1.1.1",
"@actions/glob": "^0.5.0",
"@actions/io": "^1.1.3",
"@actions/tool-cache": "^2.0.2",
"@octokit/core": "^7.0.6",
"@octokit/plugin-paginate-rest": "^14.0.0",
"@octokit/plugin-rest-endpoint-methods": "^17.0.0",
"@octokit/core": "^7.0.5",
"@octokit/plugin-paginate-rest": "^13.1.1",
"@octokit/plugin-rest-endpoint-methods": "^16.1.0",
"@renovatebot/pep440": "^4.2.1",
"smol-toml": "^1.4.2",
"undici": "5.28.5"
"undici": "^7.16.0"
},
"devDependencies": {
"@biomejs/biome": "2.3.7",
"@biomejs/biome": "2.2.4",
"@types/js-yaml": "^4.0.9",
"@types/node": "^24.10.1",
"@types/node": "^24.7.0",
"@types/semver": "^7.7.1",
"@vercel/ncc": "^0.38.4",
"jest": "^30.2.0",
"jest": "^30.1.3",
"js-yaml": "^4.1.0",
"ts-jest": "^29.4.5",
"typescript": "^5.9.3"
"ts-jest": "^29.4.4",
"typescript": "^5.9.2"
}
}

View file

@ -1,82 +1,48 @@
import * as cache from "@actions/cache";
import * as core from "@actions/core";
import * as exec from "@actions/exec";
import { hashFiles } from "../hash/hash-files";
import {
cacheDependencyGlob,
cacheLocalPath,
cachePython,
cacheSuffix,
pruneCache,
pythonDir,
pythonVersion as pythonVersionInput,
restoreCache as shouldRestoreCache,
workingDirectory,
} from "../utils/inputs";
import { getArch, getOSNameVersion, getPlatform } from "../utils/platforms";
import { getArch, getPlatform } from "../utils/platforms";
export const STATE_CACHE_KEY = "cache-key";
export const STATE_CACHE_MATCHED_KEY = "cache-matched-key";
export const STATE_PYTHON_CACHE_MATCHED_KEY = "python-cache-matched-key";
const CACHE_VERSION = "1";
const CACHE_VERSION = "2";
export async function restoreCache(pythonVersion?: string): Promise<void> {
const cacheKey = await computeKeys(pythonVersion);
export async function restoreCache(): Promise<void> {
const cacheKey = await computeKeys();
core.saveState(STATE_CACHE_KEY, cacheKey);
core.setOutput("cache-key", cacheKey);
if (!shouldRestoreCache) {
core.info("restore-cache is false. Skipping restore cache step.");
core.setOutput("python-cache-hit", false);
return;
}
if (cacheLocalPath === undefined) {
throw new Error(
"cache-local-path is not set. Cannot restore cache without a valid cache path.",
);
}
await restoreCacheFromKey(
cacheKey,
cacheLocalPath.path,
STATE_CACHE_MATCHED_KEY,
"cache-hit",
);
if (cachePython) {
await restoreCacheFromKey(
`${cacheKey}-python`,
pythonDir,
STATE_PYTHON_CACHE_MATCHED_KEY,
"python-cache-hit",
);
} else {
core.setOutput("python-cache-hit", false);
}
}
async function restoreCacheFromKey(
cacheKey: string,
cachePath: string,
stateKey: string,
outputKey: string,
): Promise<void> {
core.info(
`Trying to restore cache from GitHub Actions cache with key: ${cacheKey}`,
);
let matchedKey: string | undefined;
core.info(
`Trying to restore uv cache from GitHub Actions cache with key: ${cacheKey}`,
);
try {
matchedKey = await cache.restoreCache([cachePath], cacheKey);
matchedKey = await cache.restoreCache([cacheLocalPath], cacheKey);
} catch (err) {
const message = (err as Error).message;
core.warning(message);
core.setOutput(outputKey, false);
core.setOutput("cache-hit", false);
return;
}
handleMatchResult(matchedKey, cacheKey, stateKey, outputKey);
handleMatchResult(matchedKey, cacheKey);
}
async function computeKeys(pythonVersion?: string): Promise<string> {
async function computeKeys(): Promise<string> {
let cacheDependencyPathHash = "-";
if (cacheDependencyGlob !== "") {
core.info(
@ -93,27 +59,56 @@ async function computeKeys(pythonVersion?: string): Promise<string> {
cacheDependencyPathHash = "-no-dependency-glob";
}
const suffix = cacheSuffix ? `-${cacheSuffix}` : "";
const version = pythonVersion ?? "unknown";
const pythonVersion = await getPythonVersion();
const platform = await getPlatform();
const osNameVersion = getOSNameVersion();
const pruned = pruneCache ? "-pruned" : "";
const python = cachePython ? "-py" : "";
return `setup-uv-${CACHE_VERSION}-${getArch()}-${platform}-${osNameVersion}-${version}${pruned}${python}${cacheDependencyPathHash}${suffix}`;
return `setup-uv-${CACHE_VERSION}-${getArch()}-${platform}-${pythonVersion}${pruned}${cacheDependencyPathHash}${suffix}`;
}
async function getPythonVersion(): Promise<string> {
if (pythonVersionInput !== "") {
return pythonVersionInput;
}
let output = "";
const options: exec.ExecOptions = {
listeners: {
stdout: (data: Buffer) => {
output += data.toString();
},
},
silent: !core.isDebug(),
};
try {
const execArgs = ["python", "find", "--directory", workingDirectory];
await exec.exec("uv", execArgs, options);
const pythonPath = output.trim();
output = "";
await exec.exec(pythonPath, ["--version"], options);
// output is like "Python 3.8.10"
return output.split(" ")[1].trim();
} catch (error) {
const err = error as Error;
core.debug(`Failed to get python version from uv. Error: ${err.message}`);
return "unknown";
}
}
function handleMatchResult(
matchedKey: string | undefined,
primaryKey: string,
stateKey: string,
outputKey: string,
): void {
if (!matchedKey) {
core.info(`No GitHub Actions cache found for key: ${primaryKey}`);
core.setOutput(outputKey, false);
core.setOutput("cache-hit", false);
return;
}
core.saveState(stateKey, matchedKey);
core.info(`cache restored from GitHub Actions cache with key: ${matchedKey}`);
core.setOutput(outputKey, true);
core.saveState(STATE_CACHE_MATCHED_KEY, matchedKey);
core.info(
`uv cache restored from GitHub Actions cache with key: ${matchedKey}`,
);
core.setOutput("cache-hit", true);
}

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,6 @@ import * as core from "@actions/core";
import * as tc from "@actions/tool-cache";
import type { Endpoints } from "@octokit/types";
import * as pep440 from "@renovatebot/pep440";
import * as semver from "semver";
import { OWNER, REPO, TOOL_CACHE_NAME } from "../utils/constants";
import { Octokit } from "../utils/octokit";
import type { Architecture, Platform } from "../utils/platforms";
@ -108,21 +107,12 @@ async function downloadVersion(
await validateChecksum(checkSum, downloadPath, arch, platform, version);
let uvDir: string;
const extension = getExtension(platform);
if (platform === "pc-windows-msvc") {
const fullPathWithExtension = `${downloadPath}${extension}`;
await fs.copyFile(downloadPath, fullPathWithExtension);
uvDir = await tc.extractZip(fullPathWithExtension);
// On windows extracting the zip does not create an intermediate directory
try {
// Try tar first as it's much faster, but only bsdtar supports zip files,
// so this my fail if another tar, like gnu tar, ends up being used.
uvDir = await tc.extractTar(downloadPath, undefined, "x");
} catch (err) {
core.info(
`Extracting with tar failed, falling back to zip extraction: ${(err as Error).message}`,
);
const extension = getExtension(platform);
const fullPathWithExtension = `${downloadPath}${extension}`;
await fs.copyFile(downloadPath, fullPathWithExtension);
uvDir = await tc.extractZip(fullPathWithExtension);
}
} else {
const extractedDir = await tc.extractTar(downloadPath);
uvDir = path.join(extractedDir, artifactName);
@ -144,31 +134,28 @@ export async function resolveVersion(
versionInput: string,
manifestFile: string | undefined,
githubToken: string,
resolutionStrategy: "highest" | "lowest" = "highest",
): Promise<string> {
core.debug(`Resolving version: ${versionInput}`);
let version: string;
const isSimpleMinimumVersionSpecifier =
versionInput.includes(">") && !versionInput.includes(",");
const resolveVersionSpecifierToLatest =
isSimpleMinimumVersionSpecifier && resolutionStrategy === "highest";
if (resolveVersionSpecifierToLatest) {
if (isSimpleMinimumVersionSpecifier) {
core.info("Found minimum version specifier, using latest version");
}
if (manifestFile) {
version =
versionInput === "latest" || resolveVersionSpecifierToLatest
versionInput === "latest" || isSimpleMinimumVersionSpecifier
? await getLatestVersionInManifest(manifestFile)
: versionInput;
} else {
version =
versionInput === "latest" || resolveVersionSpecifierToLatest
versionInput === "latest" || isSimpleMinimumVersionSpecifier
? await getLatestVersion(githubToken)
: versionInput;
}
if (tc.isExplicitVersion(version)) {
core.debug(`Version ${version} is an explicit version.`);
if (resolveVersionSpecifierToLatest) {
if (isSimpleMinimumVersionSpecifier) {
if (!pep440.satisfies(version, versionInput)) {
throw new Error(`No version found for ${versionInput}`);
}
@ -177,10 +164,7 @@ export async function resolveVersion(
}
const availableVersions = await getAvailableVersions(githubToken);
core.debug(`Available versions: ${availableVersions}`);
const resolvedVersion =
resolutionStrategy === "lowest"
? minSatisfying(availableVersions, version)
: maxSatisfying(availableVersions, version);
const resolvedVersion = maxSatisfying(availableVersions, version);
if (resolvedVersion === undefined) {
throw new Error(`No version found for ${version}`);
}
@ -280,24 +264,3 @@ function maxSatisfying(
}
return undefined;
}
function minSatisfying(
versions: string[],
version: string,
): string | undefined {
// For semver, we need to use a different approach since tc.evaluateVersions only returns max
// Let's use semver directly for min satisfying
const minSemver = semver.minSatisfying(versions, version);
if (minSemver !== null) {
core.debug(`Found a version that satisfies the semver range: ${minSemver}`);
return minSemver;
}
const minPep440 = pep440.minSatisfying(versions, version);
if (minPep440 !== null) {
core.debug(
`Found a version that satisfies the pep440 specifier: ${minPep440}`,
);
return minPep440;
}
return undefined;
}

View file

@ -6,15 +6,12 @@ import * as pep440 from "@renovatebot/pep440";
import {
STATE_CACHE_KEY,
STATE_CACHE_MATCHED_KEY,
STATE_PYTHON_CACHE_MATCHED_KEY,
} from "./cache/restore-cache";
import { STATE_UV_PATH, STATE_UV_VERSION } from "./utils/constants";
import {
cacheLocalPath,
cachePython,
enableCache,
ignoreNothingToCache,
pythonDir,
pruneCache as shouldPruneCache,
saveCache as shouldSaveCache,
} from "./utils/inputs";
@ -27,9 +24,6 @@ export async function run(): Promise<void> {
} else {
core.info("save-cache is false. Skipping save cache step.");
}
// https://github.com/nodejs/node/issues/56645#issuecomment-3077594952
await new Promise((resolve) => setTimeout(resolve, 50));
// node will stay alive if any promises are not resolved,
// which is a possibility if HTTP requests are dangling
// due to retries or timeouts. We know that if we got here
@ -53,47 +47,42 @@ async function saveCache(): Promise<void> {
}
if (matchedKey === cacheKey) {
core.info(`Cache hit occurred on key ${cacheKey}, not saving cache.`);
} else {
if (shouldPruneCache) {
await pruneCache();
}
const actualCachePath = getUvCachePath();
if (!fs.existsSync(actualCachePath)) {
if (ignoreNothingToCache) {
core.info(
"No cacheable uv cache paths were found. Ignoring because ignore-nothing-to-cache is enabled.",
);
} else {
throw new Error(
`Cache path ${actualCachePath} does not exist on disk. This likely indicates that there are no dependencies to cache. Consider disabling the cache input if it is not needed.`,
);
}
} else {
await saveCacheToKey(
cacheKey,
actualCachePath,
STATE_CACHE_MATCHED_KEY,
"uv cache",
);
}
return;
}
if (cachePython) {
if (!fs.existsSync(pythonDir)) {
core.warning(
`Python cache path ${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;
}
if (shouldPruneCache) {
await pruneCache();
}
const pythonCacheKey = `${cacheKey}-python`;
await saveCacheToKey(
pythonCacheKey,
pythonDir,
STATE_PYTHON_CACHE_MATCHED_KEY,
"Python cache",
let actualCachePath = cacheLocalPath;
if (process.env.UV_CACHE_DIR && process.env.UV_CACHE_DIR !== cacheLocalPath) {
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 "${cacheLocalPath}".`,
);
actualCachePath = process.env.UV_CACHE_DIR;
}
core.info(`Saving cache path: ${actualCachePath}`);
if (!fs.existsSync(actualCachePath) && !ignoreNothingToCache) {
throw new Error(
`Cache path ${actualCachePath} does not exist on disk. This likely indicates that there are no dependencies to cache. Consider disabling the cache input if it is not needed.`,
);
}
try {
await cache.saveCache([actualCachePath], cacheKey);
core.info(`cache saved with the key: ${cacheKey}`);
} catch (e) {
if (
e instanceof Error &&
e.message ===
"Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved."
) {
core.info(
"No cacheable paths were found. Ignoring because ignore-nothing-to-save is enabled.",
);
} else {
throw e;
}
}
}
@ -113,42 +102,4 @@ async function pruneCache(): Promise<void> {
await exec.exec(uvPath, execArgs, options);
}
function getUvCachePath(): string {
if (cacheLocalPath === undefined) {
throw new Error(
"cache-local-path is not set. Cannot save cache without a valid cache path.",
);
}
if (
process.env.UV_CACHE_DIR &&
process.env.UV_CACHE_DIR !== cacheLocalPath.path
) {
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 "${cacheLocalPath.path}".`,
);
return process.env.UV_CACHE_DIR;
}
return cacheLocalPath.path;
}
async function saveCacheToKey(
cacheKey: string,
cachePath: string,
stateKey: string,
cacheName: string,
): Promise<void> {
const matchedKey = core.getState(stateKey);
if (matchedKey === cacheKey) {
core.info(
`${cacheName} hit occurred on key ${cacheKey}, not saving cache.`,
);
return;
}
core.info(`Including ${cacheName} path: ${cachePath}`);
await cache.saveCache([cachePath], cacheKey);
core.info(`${cacheName} saved with key: ${cacheKey}`);
}
run();

View file

@ -8,23 +8,20 @@ import {
resolveVersion,
tryGetFromToolCache,
} from "./download/download-version";
import { getConfigValueFromTomlFile } from "./utils/config-file";
import { STATE_UV_PATH, STATE_UV_VERSION } from "./utils/constants";
import {
activateEnvironment as activateEnvironmentInput,
addProblemMatchers,
CacheLocalSource,
cacheLocalPath,
checkSum,
enableCache,
githubToken,
ignoreEmptyWorkdir,
manifestFile,
pythonDir,
pythonVersion,
resolutionStrategy,
toolBinDir,
toolDir,
venvPath,
versionFile as versionFileInput,
version as versionInput,
workingDirectory,
@ -37,37 +34,6 @@ import {
} from "./utils/platforms";
import { getUvVersionFromFile } from "./version/resolve";
async function getPythonVersion(): Promise<string> {
if (pythonVersion !== "") {
return pythonVersion;
}
let output = "";
const options: exec.ExecOptions = {
listeners: {
stdout: (data: Buffer) => {
output += data.toString();
},
},
silent: !core.isDebug(),
};
try {
const execArgs = ["python", "find", "--directory", workingDirectory];
await exec.exec("uv", execArgs, options);
const pythonPath = output.trim();
output = "";
await exec.exec(pythonPath, ["--version"], options);
// output is like "Python 3.8.10"
return output.split(" ")[1].trim();
} catch (error) {
const err = error as Error;
core.debug(`Failed to get python version from uv. Error: ${err.message}`);
return "unknown";
}
}
async function run(): Promise<void> {
detectEmptyWorkdir();
const platform = await getPlatform();
@ -85,7 +51,6 @@ async function run(): Promise<void> {
addToolBinToPath();
addUvToPathAndOutput(setupResult.uvDir);
setToolDir();
addPythonDirToPath();
setupPython();
await activateEnvironment();
addMatchers();
@ -95,14 +60,9 @@ async function run(): Promise<void> {
core.saveState(STATE_UV_VERSION, setupResult.version);
core.info(`Successfully installed uv version ${setupResult.version}`);
const pythonVersion = await getPythonVersion();
core.setOutput("python-version", pythonVersion);
if (enableCache) {
await restoreCache(pythonVersion);
await restoreCache();
}
// https://github.com/nodejs/node/issues/56645#issuecomment-3077594952
await new Promise((resolve) => setTimeout(resolve, 50));
process.exit(0);
} catch (err) {
core.setFailed((err as Error).message);
@ -110,7 +70,7 @@ async function run(): Promise<void> {
}
function detectEmptyWorkdir(): void {
if (fs.readdirSync(workingDirectory).length === 0) {
if (fs.readdirSync(".").length === 0) {
if (ignoreEmptyWorkdir) {
core.info(
"Empty workdir detected. Ignoring because ignore-empty-workdir is enabled",
@ -158,12 +118,7 @@ async function determineVersion(
manifestFile: string | undefined,
): Promise<string> {
if (versionInput !== "") {
return await resolveVersion(
versionInput,
manifestFile,
githubToken,
resolutionStrategy,
);
return await resolveVersion(versionInput, manifestFile, githubToken);
}
if (versionFileInput !== "") {
const versionFromFile = getUvVersionFromFile(versionFileInput);
@ -172,12 +127,7 @@ async function determineVersion(
`Could not determine uv version from file: ${versionFileInput}`,
);
}
return await resolveVersion(
versionFromFile,
manifestFile,
githubToken,
resolutionStrategy,
);
return await resolveVersion(versionFromFile, manifestFile, githubToken);
}
const versionFromUvToml = getUvVersionFromFile(
`${workingDirectory}${path.sep}uv.toml`,
@ -194,7 +144,6 @@ async function determineVersion(
versionFromUvToml || versionFromPyproject || "latest",
manifestFile,
githubToken,
resolutionStrategy,
);
}
@ -245,17 +194,6 @@ function setToolDir(): void {
}
}
function addPythonDirToPath(): void {
core.exportVariable("UV_PYTHON_INSTALL_DIR", pythonDir);
core.info(`Set UV_PYTHON_INSTALL_DIR to ${pythonDir}`);
if (process.env.UV_NO_MODIFY_PATH !== undefined) {
core.info("UV_NO_MODIFY_PATH is set, not adding python dir to path");
} else {
core.addPath(pythonDir);
core.info(`Added ${pythonDir} to the path`);
}
}
function setupPython(): void {
if (pythonVersion !== "") {
core.exportVariable("UV_PYTHON", pythonVersion);
@ -270,36 +208,34 @@ async function activateEnvironment(): Promise<void> {
"UV_NO_MODIFY_PATH and activate-environment cannot be used together.",
);
}
const execArgs = ["venv", ".venv", "--directory", workingDirectory];
core.info(`Creating and activating python venv at ${venvPath}...`);
await exec.exec("uv", [
"venv",
venvPath,
"--directory",
workingDirectory,
"--clear",
]);
core.info("Activating python venv...");
await exec.exec("uv", execArgs);
let venvBinPath = `${venvPath}${path.sep}bin`;
let venvBinPath = `${workingDirectory}${path.sep}.venv${path.sep}bin`;
if (process.platform === "win32") {
venvBinPath = `${venvPath}${path.sep}Scripts`;
venvBinPath = `${workingDirectory}${path.sep}.venv${path.sep}Scripts`;
}
core.addPath(path.resolve(venvBinPath));
core.exportVariable("VIRTUAL_ENV", venvPath);
core.setOutput("venv", venvPath);
core.exportVariable(
"VIRTUAL_ENV",
path.resolve(`${workingDirectory}${path.sep}.venv`),
);
}
}
function setCacheDir(): void {
if (cacheLocalPath !== undefined) {
if (cacheLocalPath.source === CacheLocalSource.Config) {
if (enableCache) {
const cacheDirFromConfig = getConfigValueFromTomlFile("", "cache-dir");
if (cacheDirFromConfig !== undefined) {
core.info(
"Using cache-dir from uv config file, not modifying UV_CACHE_DIR",
);
return;
}
core.exportVariable("UV_CACHE_DIR", cacheLocalPath.path);
core.info(`Set UV_CACHE_DIR to ${cacheLocalPath.path}`);
core.exportVariable("UV_CACHE_DIR", cacheLocalPath);
core.info(`Set UV_CACHE_DIR to ${cacheLocalPath}`);
}
}

View file

@ -2,19 +2,11 @@ import path from "node:path";
import * as core from "@actions/core";
import { getConfigValueFromTomlFile } from "./config-file";
export enum CacheLocalSource {
Input,
Config,
Env,
Default,
}
export const workingDirectory = core.getInput("working-directory");
export const version = core.getInput("version");
export const versionFile = getVersionFile();
export const pythonVersion = core.getInput("python-version");
export const activateEnvironment = core.getBooleanInput("activate-environment");
export const venvPath = getVenvPath();
export const checkSum = core.getInput("checksum");
export const enableCache = getEnableCache();
export const restoreCache = core.getInput("restore-cache") === "true";
@ -23,19 +15,16 @@ export const cacheSuffix = core.getInput("cache-suffix") || "";
export const cacheLocalPath = getCacheLocalPath();
export const cacheDependencyGlob = getCacheDependencyGlob();
export const pruneCache = core.getInput("prune-cache") === "true";
export const cachePython = core.getInput("cache-python") === "true";
export const ignoreNothingToCache =
core.getInput("ignore-nothing-to-cache") === "true";
export const ignoreEmptyWorkdir =
core.getInput("ignore-empty-workdir") === "true";
export const toolBinDir = getToolBinDir();
export const toolDir = getToolDir();
export const pythonDir = getUvPythonDir();
export const githubToken = core.getInput("github-token");
export const manifestFile = getManifestFile();
export const addProblemMatchers =
core.getInput("add-problem-matchers") === "true";
export const resolutionStrategy = getResolutionStrategy();
function getVersionFile(): string {
const versionFileInput = core.getInput("version-file");
@ -46,18 +35,6 @@ function getVersionFile(): string {
return versionFileInput;
}
function getVenvPath(): string {
const venvPathInput = core.getInput("venv-path");
if (venvPathInput !== "") {
if (!activateEnvironment) {
core.warning("venv-path is only used when activate-environment is true");
}
const tildeExpanded = expandTilde(venvPathInput);
return normalizePath(resolveRelativePath(tildeExpanded));
}
return normalizePath(resolveRelativePath(".venv"));
}
function getEnableCache(): boolean {
const enableCacheInput = core.getInput("enable-cache");
if (enableCacheInput === "auto") {
@ -100,51 +77,32 @@ function getToolDir(): string | undefined {
return undefined;
}
function getCacheLocalPath():
| {
path: string;
source: CacheLocalSource;
}
| undefined {
function getCacheLocalPath(): string {
const cacheLocalPathInput = core.getInput("cache-local-path");
if (cacheLocalPathInput !== "") {
const tildeExpanded = expandTilde(cacheLocalPathInput);
return {
path: resolveRelativePath(tildeExpanded),
source: CacheLocalSource.Input,
};
return resolveRelativePath(tildeExpanded);
}
const cacheDirFromConfig = getCacheDirFromConfig();
if (cacheDirFromConfig !== undefined) {
return { path: cacheDirFromConfig, source: CacheLocalSource.Config };
return cacheDirFromConfig;
}
if (process.env.UV_CACHE_DIR !== undefined) {
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 process.env.UV_CACHE_DIR;
}
if (getEnableCache()) {
if (process.env.RUNNER_ENVIRONMENT === "github-hosted") {
if (process.env.RUNNER_TEMP !== undefined) {
return {
path: `${process.env.RUNNER_TEMP}${path.sep}setup-uv-cache`,
source: CacheLocalSource.Default,
};
}
throw Error(
"Could not determine UV_CACHE_DIR. Please make sure RUNNER_TEMP is set or provide the cache-local-path input",
);
if (process.env.RUNNER_ENVIRONMENT === "github-hosted") {
if (process.env.RUNNER_TEMP !== undefined) {
return `${process.env.RUNNER_TEMP}${path.sep}setup-uv-cache`;
}
if (process.platform === "win32") {
return {
path: `${process.env.APPDATA}${path.sep}uv${path.sep}cache`,
source: CacheLocalSource.Default,
};
}
return {
path: `${process.env.HOME}${path.sep}.cache${path.sep}uv`,
source: CacheLocalSource.Default,
};
throw Error(
"Could not determine UV_CACHE_DIR. Please make sure RUNNER_TEMP is set or provide the cache-local-path input",
);
}
if (process.platform === "win32") {
return `${process.env.APPDATA}${path.sep}uv${path.sep}cache`;
}
return `${process.env.HOME}${path.sep}.cache${path.sep}uv`;
}
function getCacheDirFromConfig(): string | undefined {
@ -165,28 +123,6 @@ function getCacheDirFromConfig(): string | undefined {
return undefined;
}
export function getUvPythonDir(): string {
if (process.env.UV_PYTHON_INSTALL_DIR !== undefined) {
core.info(
`UV_PYTHON_INSTALL_DIR is already set to ${process.env.UV_PYTHON_INSTALL_DIR}`,
);
return process.env.UV_PYTHON_INSTALL_DIR;
}
if (process.env.RUNNER_ENVIRONMENT !== "github-hosted") {
if (process.platform === "win32") {
return `${process.env.APPDATA}${path.sep}uv${path.sep}python`;
} else {
return `${process.env.HOME}${path.sep}.local${path.sep}share${path.sep}uv${path.sep}python`;
}
}
if (process.env.RUNNER_TEMP !== undefined) {
return `${process.env.RUNNER_TEMP}${path.sep}uv-python-dir`;
}
throw Error(
"Could not determine UV_PYTHON_INSTALL_DIR. Please make sure RUNNER_TEMP is set or provide the UV_PYTHON_INSTALL_DIR environment variable",
);
}
function getCacheDependencyGlob(): string {
const cacheDependencyGlobInput = core.getInput("cache-dependency-glob");
if (cacheDependencyGlobInput !== "") {
@ -207,19 +143,6 @@ function expandTilde(input: string): string {
return input;
}
function normalizePath(inputPath: string): string {
const normalized = path.normalize(inputPath);
const root = path.parse(normalized).root;
// Remove any trailing path separators, except when the whole path is the root.
let trimmed = normalized;
while (trimmed.length > root.length && trimmed.endsWith(path.sep)) {
trimmed = trimmed.slice(0, -1);
}
return trimmed;
}
function resolveRelativePath(inputPath: string): string {
const hasNegation = inputPath.startsWith("!");
const pathWithoutNegation = hasNegation ? inputPath.substring(1) : inputPath;
@ -239,16 +162,3 @@ function getManifestFile(): string | undefined {
}
return undefined;
}
function getResolutionStrategy(): "highest" | "lowest" {
const resolutionStrategyInput = core.getInput("resolution-strategy");
if (resolutionStrategyInput === "lowest") {
return "lowest";
}
if (resolutionStrategyInput === "highest" || resolutionStrategyInput === "") {
return "highest";
}
throw new Error(
`Invalid resolution-strategy: ${resolutionStrategyInput}. Must be 'highest' or 'lowest'.`,
);
}

View file

@ -1,5 +1,3 @@
import fs from "node:fs";
import os from "node:os";
import * as core from "@actions/core";
import * as exec from "@actions/exec";
export type Platform =
@ -76,71 +74,3 @@ async function isMuslOs(): Promise<boolean> {
return false;
}
}
/**
* Returns OS name and version for cache key differentiation.
* Examples: "ubuntu-22.04", "macos-14", "windows-2022"
* Throws if OS detection fails.
*/
export function getOSNameVersion(): string {
const platform = process.platform;
if (platform === "linux") {
return getLinuxOSNameVersion();
}
if (platform === "darwin") {
return getMacOSNameVersion();
}
if (platform === "win32") {
return getWindowsNameVersion();
}
throw new Error(`Unsupported platform: ${platform}`);
}
function getLinuxOSNameVersion(): string {
const files = ["/etc/os-release", "/usr/lib/os-release"];
for (const file of files) {
try {
const content = fs.readFileSync(file, "utf8");
const id = parseOsReleaseValue(content, "ID");
const versionId = parseOsReleaseValue(content, "VERSION_ID");
if (id && versionId) {
return `${id}-${versionId}`;
}
} catch {
// Try next file
}
}
throw new Error(
"Failed to determine Linux distribution. " +
"Could not read /etc/os-release or /usr/lib/os-release",
);
}
function parseOsReleaseValue(content: string, key: string): string | undefined {
const regex = new RegExp(`^${key}=["']?([^"'\\n]*)["']?$`, "m");
const match = content.match(regex);
return match?.[1];
}
function getMacOSNameVersion(): string {
const darwinVersion = Number.parseInt(os.release().split(".")[0], 10);
if (Number.isNaN(darwinVersion)) {
throw new Error(`Failed to parse macOS version from: ${os.release()}`);
}
const macosVersion = darwinVersion - 9;
return `macos-${macosVersion}`;
}
function getWindowsNameVersion(): string {
const version = os.version();
const match = version.match(/Windows(?: Server)? (\d+)/);
if (!match) {
throw new Error(`Failed to parse Windows version from: ${version}`);
}
return `windows-${match[1]}`;
}

View file

@ -6,7 +6,7 @@
"outDir": "./lib" /* Redirect output structure to the directory. */,
"rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
"strict": true /* Enable all strict type-checking options. */,
"target": "ES2022" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"target": "ES2024" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
},
"exclude": ["node_modules", "**/*.test.ts"]
}

File diff suppressed because it is too large Load diff