Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:49:58 +08:00
commit 5007abf04b
89 changed files with 44129 additions and 0 deletions

750
skills/uv/SKILL.md Normal file
View File

@@ -0,0 +1,750 @@
---
name: uv
description: Expert guidance for Astral's uv - an extremely fast Python package and project manager. Use when working with Python projects, managing dependencies, creating scripts with PEP 723 metadata, installing tools, managing Python versions, or configuring package indexes. Covers project initialization, dependency management, virtual environments, tool installation, workspace configuration, CI/CD integration, and migration from pip/poetry.
---
# uv: Modern Python Package and Project Manager
## Overview
uv is Astral's extremely fast Python package and project manager written in Rust, designed as a unified replacement for pip, pip-tools, pipx, poetry, pyenv, and virtualenv. It delivers 10-100x faster performance while providing modern dependency management with lockfiles and reproducible environments.
## When to Use This Skill
Use this skill when:
- Initializing new Python projects or scripts
- Managing project dependencies with pyproject.toml
- Creating portable single-file scripts with PEP 723 inline metadata
- Installing or running command-line tools (ruff, black, httpie, etc.)
- Managing Python interpreter versions
- Setting up virtual environments
- Configuring package indexes or private registries
- Migrating from pip, pip-tools, poetry, or conda
- Configuring CI/CD pipelines for Python projects
- Setting up Docker containers for Python applications
- Troubleshooting dependency resolution or build failures
## Core Capabilities
### 1. Project Initialization and Management
**Initialize new projects:**
```bash
# Standard project with recommended structure
uv init myproject
# Application project (default)
uv init myapp --app
# Library/package project (includes src/ layout)
uv init mylib --lib --build-backend hatchling
# Bare project (pyproject.toml only)
uv init --bare
```
**Project structure created:**
```text
myproject/
├── .venv/ # Virtual environment (auto-created)
├── .python-version # Pinned Python version
├── README.md
├── main.py # Sample entry point
├── pyproject.toml # Project metadata and dependencies
└── uv.lock # Lockfile (like Cargo.lock or package-lock.json)
```
### 2. Dependency Management
**Add dependencies to project:**
```bash
# Production dependencies
uv add requests 'flask>=2.0,<3.0' pydantic
# Development dependencies
uv add --dev pytest pytest-cov ruff mypy black
# Optional dependency groups
uv add --group docs sphinx sphinx-rtd-theme
uv add --group test pytest-asyncio hypothesis
# From various sources
uv add git+https://github.com/psf/requests@main
uv add --editable ./local-package
uv add ../sibling-package
```
**Remove dependencies:**
```bash
uv remove requests flask
uv remove --dev pytest
uv remove --group docs sphinx
```
**Lock and sync environments:**
```bash
# Update lockfile with latest compatible versions
uv lock
# Upgrade all packages
uv lock --upgrade
# Upgrade specific packages
uv lock --upgrade-package requests --upgrade-package flask
# Install all dependencies from lockfile
uv sync
# Install without dev dependencies (production)
uv sync --no-dev
# Install with optional groups
uv sync --extra docs --extra test
# Sync without updating lockfile (CI mode)
uv sync --frozen
# Error if lockfile out of sync (strict CI mode)
uv sync --locked
```
### 3. Running Code in Project Context
**Execute scripts and commands:**
```bash
# Run Python script in project environment
uv run python script.py
# Run module (like python -m)
uv run -m pytest
uv run -m flask run --port 8000
# Run with specific Python version
uv run --python 3.11 script.py
uv run --python pypy@3.9 test.py
# Run without syncing first (use current environment state)
uv run --frozen script.py
# Run with additional temporary dependencies
uv run --with httpx --with rich script.py
# Run without project dependencies (standalone)
uv run --no-project example.py
# Run with environment variables from file
uv run --env-file .env script.py
```
### 4. PEP 723 Inline Script Metadata
**Create portable single-file scripts with dependencies:**
```bash
# Initialize script with metadata block
uv init --script example.py --python 3.12
# Add dependencies to existing script
uv add --script example.py requests rich
```
**Example script structure:**
```python
#!/usr/bin/env -S uv --quiet run --active --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "requests>=2.31",
# "rich>=13.0",
# ]
# ///
import requests
from rich import print
response = requests.get("https://api.github.com/repos/astral-sh/uv")
print(f"Stars: {response.json()['stargazers_count']}")
```
**Run scripts:**
```bash
# Auto-creates isolated environment and runs
uv run example.py
# Run with additional dependencies
uv run --with beautifulsoup4 example.py
# Lock script for reproducibility
uv lock --script example.py # Creates example.py.lock
# Make executable and run directly
chmod +x example.py
./example.py
```
**Best practices for scripts:**
- Always include `requires-python` for compatibility
- Use version constraints for critical dependencies
- Lock scripts before sharing for reproducibility
- Add `exclude-newer` in `[tool.uv]` for time-based pinning
### 5. Tool Management
**One-off tool execution (ephemeral environments):**
```bash
# Run tool without installing (uvx is alias)
uvx ruff check
uvx pycowsay "hello from uv"
# Run specific version
uvx ruff@0.3.0 check
uvx --from 'ruff>=0.3.0,<0.4.0' ruff check
# Run tool from different package
uvx --from httpie http GET example.com
# Run with plugin/additional dependencies
uvx --with mkdocs-material mkdocs serve
```
**Persistent tool installation:**
```bash
# Install tool globally (adds to PATH)
uv tool install ruff black mypy
# Install with version constraint
uv tool install 'httpie>0.1.0'
# Install from git
uv tool install git+https://github.com/httpie/cli
# Install with additional packages
uv tool install mkdocs --with mkdocs-material
# Upgrade tools
uv tool upgrade ruff
uv tool upgrade --all
# List installed tools
uv tool list
uv tool list --show-paths
# Uninstall tool
uv tool uninstall ruff
# Update shell configuration for tools
uv tool update-shell
```
### 6. Python Version Management
**Install and manage Python versions:**
```bash
# Install specific Python version (auto-downloads if needed)
uv python install 3.12
uv python install 3.11 3.12 3.13 # Multiple at once
# List available versions
uv python list
uv python list --all-versions
# Pin Python version for project
uv python pin 3.12 # Creates .python-version
# Find Python executable
uv python find 3.11
# Upgrade Python installations
uv python upgrade 3.11
uv python upgrade --all
# Use specific Python for command
uv run --python 3.11 script.py
uv venv --python 3.12.0
```
**Python is automatically downloaded when needed:**
- Supports CPython, PyPy, GraalPy, and other implementations
- Managed installations stored in `~/.local/share/uv/python/` (Unix)
- Preference configurable: `only-managed`, `managed`, `system`, `only-system`
### 7. Virtual Environment Management
**Create virtual environments:**
```bash
# Create in .venv directory (default)
uv venv
# Create with specific Python version
uv venv --python 3.11
uv venv --python pypy3.9
# Create with custom path
uv venv myenv
# Create with system packages access
uv venv --system-site-packages
# Create with seed packages (pip, setuptools, wheel)
uv venv --seed
# Activate (standard Python activation)
source .venv/bin/activate # Unix
.venv\Scripts\activate # Windows
```
**Warning**: Running `uv venv` again **wipes existing environment** without confirmation.
### 8. pip-Compatible Interface
**Direct pip replacement commands:**
```bash
# Install packages
uv pip install flask requests
uv pip install -r requirements.txt
uv pip install -e . # Editable install
# Install from git
uv pip install git+https://github.com/psf/requests
uv pip install git+https://github.com/pallets/flask@main
# Compile requirements (like pip-compile)
uv pip compile pyproject.toml -o requirements.txt
uv pip compile requirements.in -o requirements.txt
uv pip compile --upgrade-package ruff requirements.in
# Sync environment to exact requirements (like pip-sync)
uv pip sync requirements.txt
# Uninstall packages
uv pip uninstall flask requests
uv pip uninstall -r requirements.txt
# List installed packages
uv pip list
uv pip list --format json
uv pip freeze > requirements.txt
# Show package info
uv pip show requests
# Check for conflicts
uv pip check
# Display dependency tree
uv pip tree
uv pip tree --depth 2
```
### 9. Workspace Management (Monorepos)
**Configure workspaces in root pyproject.toml:**
```toml
[tool.uv.workspace]
members = ["packages/*", "apps/*"]
exclude = ["packages/deprecated"]
```
**Workspace dependency references:**
```toml
[project]
name = "myapp"
dependencies = ["shared-lib", "core-utils"]
[tool.uv.sources]
shared-lib = { workspace = true }
core-utils = { workspace = true }
```
**Workspace commands:**
```bash
# Build specific workspace package
uv build --package my-package
# Run in workspace package context
uv run --package my-package python script.py
# Lock workspace (single lockfile for all members)
uv lock
```
### 10. Package Building and Publishing
**Build distributions:**
```bash
# Build wheel and source distribution
uv build
# Build only wheel
uv build --wheel
# Build specific workspace package
uv build --package my-package
# Output to custom directory
uv build --out-dir dist/
```
**Publish to PyPI:**
```bash
# Install twine separately for now
uv pip install twine
# Upload to PyPI
twine upload dist/*
# With authentication
twine upload dist/* --username __token__ --password $PYPI_TOKEN
```
## Configuration
### pyproject.toml Structure
**Standard project configuration:**
```toml
[project]
name = "myproject"
version = "1.0.0"
description = "My awesome project"
requires-python = ">=3.11"
dependencies = [
"fastapi>=0.115.2",
"pydantic>=2.5.3",
]
# Development dependencies using PEP 735 dependency groups
[dependency-groups]
dev = [
"pytest>=8.4.2",
"pytest-cov>=6.0.0",
"pytest-mock>=3.15.1",
"ruff>=0.13.3",
"pyright>=1.1.406",
"mypy>=1.18.2",
"pre-commit>=4.3.0",
]
docs = ["sphinx>=7.0", "sphinx-rtd-theme>=1.3.0"]
test = ["pytest-cov>=6.0.0", "pytest-asyncio>=0.21.0"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.uv]
# Core settings
managed = true
package = true
default-groups = ["dev"]
# Resolution
resolution = "highest" # or "lowest", "lowest-direct"
index-strategy = "first-index"
# Build configuration
compile-bytecode = true
no-build-isolation-package = ["flash-attn"]
# Python management
python-preference = "managed"
python-downloads = "automatic"
# Custom package sources
[tool.uv.sources]
torch = { index = "pytorch-cu121" }
internal-lib = { workspace = true }
# Custom indexes
[[tool.uv.index]]
name = "pytorch-cu121"
url = "https://download.pytorch.org/whl/cu121"
explicit = true
```
### Environment Variables
**Key environment variables:**
```bash
# Cache and directories
export UV_CACHE_DIR="/custom/cache"
export UV_PROJECT_ENVIRONMENT=".venv"
# Python management
export UV_PYTHON_PREFERENCE="managed"
export UV_PYTHON_DOWNLOADS="automatic"
# Network configuration
export UV_CONCURRENT_DOWNLOADS=20
export UV_CONCURRENT_BUILDS=8
# Index authentication
export UV_INDEX_PRIVATE_USERNAME="user"
export UV_INDEX_PRIVATE_PASSWORD="pass"
# Preview features
export UV_PREVIEW=1
# Disable cache
export UV_NO_CACHE=1
# System Python
export UV_SYSTEM_PYTHON=1
```
For complete configuration reference, see `references/configuration.md`.
## Common Workflows
### Starting a New Project
```bash
# 1. Initialize project
uv init myproject
cd myproject
# 2. Add dependencies
uv add fastapi uvicorn sqlalchemy
# 3. Add dev dependencies
uv add --dev pytest ruff mypy
# 4. Run application
uv run python main.py
# 5. Run tests
uv run pytest
```
### Creating a Portable Script
```bash
# 1. Create script with metadata
uv init --script analyze.py --python 3.11
# 2. Add dependencies
uv add --script analyze.py pandas matplotlib
# 3. Edit script content
# (add your code to analyze.py)
# 4. Lock for reproducibility
uv lock --script analyze.py
# 5. Make executable
chmod +x analyze.py
# 6. Run
./analyze.py
```
### Migrating from pip/requirements.txt
```bash
# 1. Initialize project
uv init --bare
# 2. Import dependencies
uv add -r requirements.txt
uv add --dev -r requirements-dev.txt
# 3. Remove old files
rm requirements.txt requirements-dev.txt
# 4. Use uv commands going forward
uv sync # Install dependencies
uv add new-package # Add new dependency
```
### Migrating from Poetry
```bash
# Option 1: Automated migration
uvx migrate-to-uv
uvx migrate-to-uv --dry-run # Preview first
# Option 2: Manual conversion
# - Convert [tool.poetry] to [project]
# - Convert poetry.lock to uv.lock: uv lock
# - Use uv commands instead of poetry commands
```
### CI/CD Integration (GitHub Actions)
```yaml
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
- name: Set up Python
run: uv python install 3.11
- name: Install dependencies
run: uv sync --frozen --all-extras
- name: Run tests
run: uv run pytest
- name: Run linters
run: |
uv run ruff check .
uv run mypy .
```
### Docker Integration
```dockerfile
FROM python:3.12-slim
# Install uv
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
WORKDIR /app
# Copy dependency files
COPY pyproject.toml uv.lock ./
# Install dependencies
RUN uv sync --frozen --no-dev
# Copy application
COPY . .
# Use virtual environment
ENV PATH="/app/.venv/bin:$PATH"
CMD ["python", "main.py"]
```
## Troubleshooting
### "Externally Managed" Error
**Problem**: `error: The interpreter is externally managed`
**Solution**: Use virtual environments instead of `--system`:
```bash
uv venv
source .venv/bin/activate
uv pip install package
```
### Build Failures
**Problem**: Package fails to build from source
**Common causes**:
- Missing system dependencies (compilers, headers)
- Python version incompatibility
- Outdated package version
**Solutions**:
- Install system dependencies: `apt-get install python3-dev build-essential`
- Add version constraints: `uv add "numpy>=1.20"`
- Check error message for missing modules
### Lockfile Out of Sync
**Problem**: Dependencies changed but lockfile not updated
**Solutions**:
```bash
uv lock # Regenerate lockfile
uv sync --locked # Error if out of sync (CI mode)
uv sync --frozen # Don't update lockfile
```
### Cache Issues
**Problem**: Stale cache causing problems
**Solutions**:
```bash
uv cache clean # Clean entire cache
uv cache prune # Remove unreachable entries
uv --no-cache <command> # Bypass cache temporarily
```
For more troubleshooting scenarios, see `references/troubleshooting.md`.
## Resources
This skill includes comprehensive reference documentation:
### references/
- `cli_reference.md` - Complete CLI commands and arguments reference
- `configuration.md` - All configuration options and environment variables
- `workflows.md` - Detailed workflow guides and examples
- `troubleshooting.md` - Common issues and solutions
### assets/
- `pyproject_templates/` - Example pyproject.toml configurations
- `script_examples/` - PEP 723 script templates
- `docker_examples/` - Docker configuration templates
- `github_actions/` - CI/CD workflow examples
## Key Principles
1. **Speed**: uv is 10-100x faster than traditional tools
2. **Reproducibility**: Lockfiles ensure consistent environments
3. **Simplicity**: Single tool replaces multiple Python tools
4. **Modern Standards**: PEP 723 scripts, standard pyproject.toml
5. **Developer Experience**: Automatic Python installation, smart defaults
## Version Information
Current latest version: **0.9.5** (October 2025)
Key recent features:
- Python 3.14 support with free-threaded builds
- Enhanced authentication system
- Advanced build configuration
- Workspace improvements
- Docker image optimizations
## External Resources
- Official docs: <https://docs.astral.sh/uv/>
- GitHub: <https://github.com/astral-sh/uv>
- Concepts guide: <https://docs.astral.sh/uv/concepts/>
- Migration guides: <https://docs.astral.sh/uv/guides/migration/>

View File

@@ -0,0 +1,51 @@
# Multi-stage Docker build with uv
# Optimized for production deployments with minimal image size
# Stage 1: Builder
FROM python:3.12-slim AS builder
# Install uv
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
# Set working directory
WORKDIR /app
# Copy dependency files
COPY pyproject.toml uv.lock ./
# Create virtual environment and install dependencies
# Using --frozen ensures we use exact versions from lockfile
# Using --no-dev excludes development dependencies
RUN uv sync --frozen --no-dev
# Stage 2: Runtime
FROM python:3.12-slim
# Set working directory
WORKDIR /app
# Copy virtual environment from builder
COPY --from=builder /app/.venv /app/.venv
# Copy application code
COPY . .
# Set environment variables
ENV PATH="/app/.venv/bin:$PATH" \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1
# Create non-root user for security
RUN useradd -m -u 1000 appuser && \
chown -R appuser:appuser /app
USER appuser
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD python -c "import sys; sys.exit(0)"
# Expose port
EXPOSE 8000
# Run application
CMD ["python", "-m", "myapp"]

View File

@@ -0,0 +1,29 @@
# Simple Docker build with uv
# Single-stage build for development or simpler deployments
FROM python:3.12-slim
# Install uv
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
# Set working directory
WORKDIR /app
# Copy all files
COPY . .
# Create virtual environment and install dependencies
RUN uv venv /opt/venv && \
. /opt/venv/bin/activate && \
uv sync --frozen --no-dev
# Set environment to use virtual environment
ENV VIRTUAL_ENV=/opt/venv \
PATH="/opt/venv/bin:$PATH" \
PYTHONUNBUFFERED=1
# Expose port
EXPOSE 8000
# Run application
CMD ["python", "-m", "myapp"]

View File

@@ -0,0 +1,120 @@
# Comprehensive CI workflow with uv
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
env:
UV_SYSTEM_PYTHON: 1 # Optional: use system Python
jobs:
# Linting and formatting
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v6
with:
version: "0.9.5"
enable-cache: true
- name: Set up Python
run: uv python install 3.11
- name: Install dependencies
run: uv sync --frozen --all-extras
- name: Run ruff (linter)
run: uv run ruff check .
- name: Run ruff (formatter)
run: uv run ruff format --check .
- name: Run mypy (type checker)
run: uv run mypy src/
# Test matrix across multiple Python versions
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: ["3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Set up Python ${{ matrix.python-version }}
run: uv python install ${{ matrix.python-version }}
- name: Install dependencies
run: uv sync --frozen --all-extras
- name: Run tests
run: uv run pytest --cov --cov-report=xml
- name: Upload coverage
if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.11'
uses: codecov/codecov-action@v3
with:
file: ./coverage.xml
# Build and verify package
build:
runs-on: ubuntu-latest
needs: [lint, test]
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v6
- name: Set up Python
run: uv python install 3.11
- name: Build package
run: uv build
- name: Check package metadata
run: uv run twine check dist/*
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
# Optional: Publish to PyPI (on release tags)
publish:
if: startsWith(github.ref, 'refs/tags/v')
needs: [build]
runs-on: ubuntu-latest
permissions:
id-token: write # Required for trusted publishing
steps:
- uses: actions/checkout@v4
- name: Download artifacts
uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
packages-dir: dist/

View File

@@ -0,0 +1,286 @@
# Advanced Python Project Configuration
# Full-featured configuration with custom indexes, workspace, and advanced settings
[project]
name = "advanced-project"
version = "1.0.0"
description = "Advanced Python project with custom configuration"
readme = "README.md"
requires-python = ">=3.11"
authors = [{name = "Your Name", email = "your.email@example.com"}]
license = {text = "MIT"}
dependencies = [
"fastapi>=0.115.0",
"torch", # Will be sourced from custom index
"pydantic>=2.5.0",
]
# Development dependencies using PEP 735 dependency groups
[dependency-groups]
dev = [
"pytest>=8.4.2",
"pytest-cov>=6.0.0",
"pytest-mock>=3.15.1",
"ruff>=0.13.3",
"pyright>=1.1.406",
"mypy>=1.18.2",
"pre-commit>=4.3.0",
]
test = [
"pytest-cov>=6.0.0",
"pytest-asyncio>=0.21.0",
"hypothesis>=6.0.0",
]
docs = [
"sphinx>=7.0",
"sphinx-rtd-theme>=1.3.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.uv]
# Core settings
managed = true
package = true
default-groups = ["dev"]
# Resolution strategy
resolution = "highest" # highest/lowest/lowest-direct
fork-strategy = "requires-python"
index-strategy = "first-index"
# Environment restrictions (only resolve for these platforms)
environments = [
"sys_platform == 'darwin'",
"sys_platform == 'linux'",
]
# Require support for specific platforms
required-environments = [
"sys_platform == 'linux' and platform_machine == 'x86_64'",
]
# Dependency version management
constraint-dependencies = [
"grpcio<1.65", # Constraint: don't allow grpcio >= 1.65
]
override-dependencies = [
"werkzeug==2.3.0", # Override: always use this exact version
]
build-constraint-dependencies = [
"setuptools==60.0.0", # Constraint for build dependencies
]
# Build configuration
compile-bytecode = true
no-build-isolation-package = ["flash-attn", "deepspeed"]
# Cache configuration
cache-dir = "./.uv_cache"
cache-keys = [
{ file = "pyproject.toml" },
{ file = "requirements.txt" },
{ git = { commit = true } },
]
# Network configuration
concurrent-downloads = 20
concurrent-builds = 8
# Python management
python-preference = "managed"
python-downloads = "automatic"
# Security
keyring-provider = "subprocess"
allow-insecure-host = []
# Preview features
preview = false
# Extra build dependencies (for packages without proper metadata)
[tool.uv.extra-build-dependencies]
flash-attn = ["torch", "setuptools", "ninja"]
deepspeed = [{ requirement = "torch", match-runtime = true }]
# Build environment variables
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
opencv-python = { CMAKE_ARGS = "-DWITH_CUDA=ON" }
# Custom package sources
[tool.uv.sources]
# PyTorch from custom index
torch = { index = "pytorch-cu121" }
# Internal workspace dependency
# internal-lib = { workspace = true }
# Git source
# httpx = { git = "https://github.com/encode/httpx", tag = "0.27.0" }
# Local path (development)
# local-pkg = { path = "../local-pkg", editable = true }
# Conditional sources (platform-specific)
# torch = [
# { index = "pytorch-cu118", marker = "sys_platform == 'darwin'" },
# { index = "pytorch-cu121", marker = "sys_platform == 'linux'" },
# ]
# Custom package indexes
[[tool.uv.index]]
name = "pytorch-cu121"
url = "https://download.pytorch.org/whl/cu121"
explicit = true # Only use for explicitly pinned packages
default = false # Don't replace PyPI as default
[[tool.uv.index]]
name = "private-registry"
url = "https://packages.example.com/simple"
explicit = true
authenticate = "always" # Always send authentication
# Workspace configuration (for monorepos)
[tool.uv.workspace]
members = ["packages/*", "apps/*"]
exclude = ["packages/deprecated"]
# Conflict resolution (mutually exclusive extras)
[[tool.uv.conflicts]]
extra = ["cuda", "rocm"]
[[tool.uv.conflicts]]
group = ["prod", "dev"]
# pip-specific settings (only for uv pip commands)
[tool.uv.pip]
compile-bytecode = true
strict = true
generate-hashes = false
annotation-style = "line"
extra = ["dev"]
universal = false
no-strip-markers = false
# Ruff configuration
[tool.ruff]
target-version = "py311"
line-length = 120
fix = true
preview = true
[tool.ruff.format]
docstring-code-format = true
quote-style = "double"
line-ending = "lf"
skip-magic-trailing-comma = true
preview = true
[tool.ruff.lint]
extend-select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"UP", # pyupgrade
"YTT", # flake8-2020
"S", # flake8-bandit
"B", # flake8-bugbear
"A", # flake8-builtins
"C4", # flake8-comprehensions
"T10", # flake8-debugger
"SIM", # flake8-simplify
"C90", # mccabe
"PGH", # pygrep-hooks
"RUF", # ruff-specific
"TRY", # tryceratops
"DOC", # pydocstyle
"D", # pydocstyle
]
ignore = [
"COM812", # Missing trailing comma
"COM819", # Missing trailing comma
"D107", # Missing docstring in __init__
"D415", # First line should end with a period
"E111", # Indentation is not a multiple of four
"E117", # Over-indented for visual indent
"E203", # whitespace before ':'
"E402", # Module level import not at top
"E501", # Line length exceeds maximum limit
"ISC001", # isort configuration is missing
"ISC002", # isort configuration is missing
"Q000", # Remove bad quotes
"Q001", # Remove bad quotes
"Q002", # Remove bad quotes
"Q003", # Remove bad quotes
"TRY003", # Exception message should not be too long
"S404", # module is possibly insecure
"S603", # subprocess-without-shell-equals-true
"S606", # start-process-with-no-shell
"DOC501", # Missing raises section
]
unfixable = ["F401", "S404", "S603", "S606", "DOC501"]
[tool.ruff.lint.pycodestyle]
max-line-length = 120
[tool.ruff.lint.isort]
combine-as-imports = true
split-on-trailing-comma = false
force-single-line = false
force-wrap-aliases = false
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
[tool.ruff.lint.pydocstyle]
convention = "google"
[tool.ruff.lint.mccabe]
max-complexity = 10
[tool.ruff.lint.per-file-ignores]
"**/tests/*" = ["S101", "S603", "S607", "D102", "D200", "D100"]
"**/test_*.py" = ["S101", "S603", "S607", "D102", "D200", "D100"]
# Mypy configuration
[tool.mypy]
python_version = "3.11"
strict = true
extra_checks = true
warn_unused_configs = true
warn_redundant_casts = true
warn_unused_ignores = true
ignore_missing_imports = true
show_error_codes = true
pretty = true
disable_error_code = "call-arg,arg-type"
# Pytest configuration
[tool.pytest.ini_options]
addopts = [
"--cov=advanced_project",
"--cov-report=term-missing",
"-v",
]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
markers = [
"slow: tests that take significant time to run",
"integration: integration tests",
]
[tool.coverage.run]
omit = ["*/tests/*"]
[tool.coverage.report]
show_missing = true
fail_under = 70

View File

@@ -0,0 +1,184 @@
# Basic Python Project Configuration
# Use this template for simple Python projects
[project]
name = "my-project"
version = "0.1.0"
description = "A simple Python project"
readme = "README.md"
requires-python = ">=3.11"
authors = [
{name = "Your Name", email = "your.email@example.com"}
]
license = {text = "MIT"}
keywords = ["example", "project"]
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
]
# Core dependencies
dependencies = [
"requests>=2.31.0",
]
# Development dependencies using PEP 735 dependency groups
[dependency-groups]
dev = [
"pytest>=8.4.2",
"pytest-cov>=6.0.0",
"pytest-mock>=3.15.1",
"ruff>=0.13.3",
"pyright>=1.1.406",
"mypy>=1.18.2",
"pre-commit>=4.3.0",
]
# Entry points for CLI tools
[project.scripts]
my-tool = "my_project.cli:main"
# Project URLs
[project.urls]
Homepage = "https://github.com/yourusername/my-project"
Documentation = "https://my-project.readthedocs.io"
Repository = "https://github.com/yourusername/my-project.git"
Issues = "https://github.com/yourusername/my-project/issues"
# Build system
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
# uv configuration
[tool.uv]
managed = true
package = true
default-groups = ["dev"]
# Development server sources (optional)
[tool.uv.sources]
# Example: Install from git during development
# requests = { git = "https://github.com/psf/requests", branch = "main" }
# Ruff configuration
[tool.ruff]
target-version = "py311"
line-length = 120
fix = true
preview = true
[tool.ruff.format]
docstring-code-format = true
quote-style = "double"
line-ending = "lf"
skip-magic-trailing-comma = true
preview = true
[tool.ruff.lint]
extend-select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"UP", # pyupgrade
"YTT", # flake8-2020
"S", # flake8-bandit
"B", # flake8-bugbear
"A", # flake8-builtins
"C4", # flake8-comprehensions
"T10", # flake8-debugger
"SIM", # flake8-simplify
"C90", # mccabe
"PGH", # pygrep-hooks
"RUF", # ruff-specific
"TRY", # tryceratops
"DOC", # pydocstyle
"D", # pydocstyle
]
ignore = [
"COM812", # Missing trailing comma
"COM819", # Missing trailing comma
"D107", # Missing docstring in __init__
"D415", # First line should end with a period
"E111", # Indentation is not a multiple of four
"E117", # Over-indented for visual indent
"E203", # whitespace before ':'
"E402", # Module level import not at top
"E501", # Line length exceeds maximum limit
"ISC001", # isort configuration is missing
"ISC002", # isort configuration is missing
"Q000", # Remove bad quotes
"Q001", # Remove bad quotes
"Q002", # Remove bad quotes
"Q003", # Remove bad quotes
"TRY003", # Exception message should not be too long
"S404", # module is possibly insecure
"S603", # subprocess-without-shell-equals-true
"S606", # start-process-with-no-shell
"DOC501", # Missing raises section
]
unfixable = ["F401", "S404", "S603", "S606", "DOC501"]
[tool.ruff.lint.pycodestyle]
max-line-length = 120
[tool.ruff.lint.isort]
combine-as-imports = true
split-on-trailing-comma = false
force-single-line = false
force-wrap-aliases = false
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
[tool.ruff.lint.pydocstyle]
convention = "google"
[tool.ruff.lint.mccabe]
max-complexity = 10
[tool.ruff.lint.per-file-ignores]
"**/tests/*" = ["S101", "S603", "S607", "D102", "D200", "D100"]
"**/test_*.py" = ["S101", "S603", "S607", "D102", "D200", "D100"]
# Mypy configuration
[tool.mypy]
python_version = "3.11"
strict = true
extra_checks = true
warn_unused_configs = true
warn_redundant_casts = true
warn_unused_ignores = true
ignore_missing_imports = true
show_error_codes = true
pretty = true
disable_error_code = "call-arg,arg-type"
# Pytest configuration
[tool.pytest.ini_options]
addopts = [
"--cov=my_project",
"--cov-report=term-missing",
"-v",
]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
markers = [
"slow: tests that take significant time to run",
"integration: integration tests",
]
[tool.coverage.run]
omit = ["*/tests/*"]
[tool.coverage.report]
show_missing = true
fail_under = 70

View File

@@ -0,0 +1,199 @@
# GitLab Package Registry Configuration
# Template matching user's GitLab-based workflow
[project]
name = "my-project"
version = "0.1.0"
description = "Project using GitLab package registry"
readme = "README.md"
requires-python = ">=3.11"
authors = [{ name = "Your Name", email = "your.email@example.com" }]
license = { text = "MIT" }
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
]
dependencies = [
"typer>=0.19.2",
"pydantic>=2.12.2",
"python-dotenv>=1.1.1",
]
[project.scripts]
my-tool = "my_project.cli:app"
[project.urls]
Homepage = "https://sourcery.assaabloy.net/group/project"
Documentation = "https://sourcery.assaabloy.net/group/project/-/blob/main/README.md"
Repository = "https://sourcery.assaabloy.net/group/project"
"Bug Tracker" = "https://sourcery.assaabloy.net/group/project/-/issues"
# Build system with hatchling and vcs versioning
[build-system]
requires = ["hatchling", "hatch-vcs"]
build-backend = "hatchling.build"
# Use dependency-groups instead of optional-dependencies
[dependency-groups]
dev = [
"pytest>=8.4.2",
"pytest-cov>=6.0.0",
"pytest-mock>=3.15.1",
"ruff>=0.13.3",
"pyright>=1.1.406",
"mypy>=1.18.2",
"pre-commit>=4.3.0",
]
# Ruff configuration following user's pattern
[tool.ruff]
target-version = "py311"
line-length = 120
fix = true
preview = true
[tool.ruff.format]
docstring-code-format = true
quote-style = "double"
line-ending = "lf"
skip-magic-trailing-comma = true
preview = true
[tool.ruff.lint]
extend-select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"UP", # pyupgrade
"YTT", # flake8-2020
"S", # flake8-bandit
"B", # flake8-bugbear
"A", # flake8-builtins
"C4", # flake8-comprehensions
"T10", # flake8-debugger
"SIM", # flake8-simplify
"C90", # mccabe
"PGH", # pygrep-hooks
"RUF", # ruff-specific
"TRY", # tryceratops
"DOC", # pydocstyle
"D", # pydocstyle
]
ignore = [
"COM812", # Missing trailing comma
"COM819", # Missing trailing comma
"D107", # Missing docstring in __init__
"D415", # First line should end with a period
"E111", # Indentation is not a multiple of four
"E117", # Over-indented for visual indent
"E203", # whitespace before ':'
"E402", # Module level import not at top
"E501", # Line length exceeds maximum limit
"ISC001", # isort configuration is missing
"ISC002", # isort configuration is missing
"Q000", # Remove bad quotes
"Q001", # Remove bad quotes
"Q002", # Remove bad quotes
"Q003", # Remove bad quotes
"TRY003", # Exception message should not be too long
"S404", # module is possibly insecure
"S603", # subprocess-without-shell-equals-true
"S606", # start-process-with-no-shell
"DOC501", # Missing raises section
]
unfixable = ["F401", "S404", "S603", "S606", "DOC501"]
[tool.ruff.lint.pycodestyle]
max-line-length = 120
[tool.ruff.lint.isort]
combine-as-imports = true
split-on-trailing-comma = false
force-single-line = false
force-wrap-aliases = false
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
[tool.ruff.lint.pydocstyle]
convention = "google"
[tool.ruff.lint.mccabe]
max-complexity = 10
[tool.ruff.lint.per-file-ignores]
"**/tests/*" = ["S101", "S603", "S607", "D102", "D200", "D100"]
"**/test_*.py" = ["S101", "S603", "S607", "D102", "D200", "D100"]
# Mypy configuration
[tool.mypy]
python_version = "3.11"
strict = true
extra_checks = true
warn_unused_configs = true
warn_redundant_casts = true
warn_unused_ignores = true
ignore_missing_imports = true
show_error_codes = true
pretty = true
disable_error_code = "call-arg,arg-type"
# Pytest configuration
[tool.pytest.ini_options]
addopts = [
"--cov=my_project",
"--cov-report=term-missing",
"-v",
]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
markers = [
"slow: tests that take significant time to run",
"integration: integration tests",
]
[tool.coverage.run]
omit = ["*/tests/*"]
[tool.coverage.report]
show_missing = true
fail_under = 70
# Hatchling configuration with vcs versioning
[tool.hatch.version]
source = "vcs"
[tool.hatch.build.targets.sdist]
include = [
"my_project",
"README.md",
"pyproject.toml",
]
[tool.hatch.build.targets.wheel]
include = ["my_project"]
# uv configuration for GitLab package registry
[tool.uv]
# Publish to GitLab package registry
publish-url = "https://sourcery.assaabloy.net/api/v4/projects/PROJECT_ID/packages/pypi"
# Use GitLab as default index
[[tool.uv.index]]
name = "gitlab"
url = "https://sourcery.assaabloy.net/api/v4/projects/PROJECT_ID/packages/pypi/simple"
default = true
authenticate = "always"
# Authentication via environment variables:
# export UV_INDEX_GITLAB_USERNAME="__token__"
# export UV_INDEX_GITLAB_PASSWORD="your-gitlab-token"

View File

@@ -0,0 +1,112 @@
#!/usr/bin/env -S uv --quiet run --active --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "pandas>=2.0.0",
# "matplotlib>=3.7.0",
# "rich>=13.0.0",
# ]
# [tool.uv]
# exclude-newer = "2025-10-24T00:00:00Z" # Time-based reproducibility
# ///
"""Data Analysis Script Example
This script demonstrates PEP 723 inline script metadata with uv.
It analyzes CSV data and creates visualizations.
Usage:
# Make executable and run
chmod +x data_analysis.py
./data_analysis.py data.csv
# Or run directly with uv
uv run data_analysis.py data.csv
# With additional dependencies
uv run --with seaborn data_analysis.py data.csv
"""
import sys
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
from rich.console import Console
from rich.table import Table
console = Console()
def analyze_data(csv_path: str) -> None:
"""Analyze CSV data and display summary statistics."""
# Load data
df = pd.read_csv(csv_path)
console.print(f"[bold green]Analyzing {csv_path}[/bold green]")
console.print(f"Shape: {df.shape[0]} rows x {df.shape[1]} columns\n")
# Display summary statistics in rich table
table = Table(title="Summary Statistics")
table.add_column("Column", style="cyan")
table.add_column("Mean", style="magenta")
table.add_column("Std", style="green")
table.add_column("Min", style="yellow")
table.add_column("Max", style="red")
for col in df.select_dtypes(include=["number"]).columns:
table.add_row(
col, f"{df[col].mean():.2f}", f"{df[col].std():.2f}", f"{df[col].min():.2f}", f"{df[col].max():.2f}"
)
console.print(table)
# Create visualization
_fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# Plot 1: Distribution of first numeric column
numeric_cols = df.select_dtypes(include=["number"]).columns
if len(numeric_cols) > 0:
df[numeric_cols[0]].hist(ax=axes[0], bins=30)
axes[0].set_title(f"Distribution of {numeric_cols[0]}")
axes[0].set_xlabel(numeric_cols[0])
axes[0].set_ylabel("Frequency")
# Plot 2: Correlation heatmap
if len(numeric_cols) > 1:
corr = df.loc[:, numeric_cols].corr()
im = axes[1].imshow(corr, cmap="coolwarm", aspect="auto")
axes[1].set_xticks(range(len(numeric_cols)))
axes[1].set_yticks(range(len(numeric_cols)))
axes[1].set_xticklabels(numeric_cols, rotation=45)
axes[1].set_yticklabels(numeric_cols)
axes[1].set_title("Correlation Matrix")
plt.colorbar(im, ax=axes[1])
plt.tight_layout()
output_path = Path(csv_path).stem + "_analysis.png"
plt.savefig(output_path, dpi=150)
console.print(f"\n[bold green]✓[/bold green] Saved visualization to {output_path}")
def main() -> None:
"""Main entry point."""
if len(sys.argv) < 2:
console.print("[bold red]Error:[/bold red] Please provide CSV file path")
console.print("\nUsage: uv run data_analysis.py <csv_file>")
sys.exit(1)
csv_path = sys.argv[1]
if not Path(csv_path).exists():
console.print(f"[bold red]Error:[/bold red] File '{csv_path}' not found")
sys.exit(1)
try:
analyze_data(csv_path)
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {e}")
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,632 @@
# uv CLI Reference
Complete command-line interface reference for uv (v0.9.5).
## Global Flags
Available across all commands:
```bash
--help, -h Display help
--verbose, -v Verbose logging (repeat for more: -vv, -vvv)
--quiet, -q Suppress output
--color <WHEN> Color output (auto/always/never)
--no-progress Hide progress indicators
--cache-dir <DIR> Cache directory
--no-cache Disable caching
--offline Disable network access
--python <VERSION> Python interpreter/version
--directory <PATH> Working directory
--config-file <PATH> Custom config file
--no-config Ignore config files
--preview Enable preview features
```
## Project Commands
### uv init
Create new project or script.
```bash
uv init [OPTIONS] [PATH]
--lib, --library Create library (implies --package)
--app, --application Create application (default)
--script Create PEP 723 script
--package Distributable package with src/
--no-package Non-package (virtual) project
--bare Minimal configuration only
--build-backend <BACKEND> Build system (hatchling/setuptools/uv_build)
--python <VERSION> Python version requirement
--vcs <VCS> Version control (git/none)
--python-pin Create .python-version
```
### uv add
Add dependencies to project.
```bash
uv add [OPTIONS] <PACKAGES>...
--dev Add to dev dependencies
--group <GROUP> Add to dependency group
--optional <EXTRA> Add to optional dependencies
--editable, -e Editable/development mode
--frozen Skip lockfile updates
--locked Assert lockfile unchanged
--no-sync Skip environment sync
--bounds <TYPE> Version constraint (lowest/compatible/exact)
--branch <BRANCH> Git branch
--tag <TAG> Git tag
--rev <REV> Git revision
--raw-sources Raw source specifiers
```
### uv remove
Remove dependencies.
```bash
uv remove [OPTIONS] <PACKAGES>...
--dev Remove from dev dependencies
--group <GROUP> Remove from dependency group
--optional <EXTRA> Remove from optional dependencies
--frozen Skip lockfile updates
--locked Assert lockfile unchanged
```
### uv sync
Synchronize project environment with lockfile.
```bash
uv sync [OPTIONS]
--extra <EXTRA>, -E Include optional dependencies
--all-extras Include all optional dependencies
--no-dev Exclude dev dependencies
--only-dev Only dev dependencies
--group <GROUP> Include dependency group
--only-group <GROUP> Only specified group
--no-install-project Skip installing project itself
--frozen Use existing lockfile
--locked Assert lockfile unchanged
--inexact Allow non-exact versions
--python <VERSION> Target Python version
```
### uv lock
Update project lockfile.
```bash
uv lock [OPTIONS]
--frozen Don't update lockfile
--locked Assert lockfile unchanged
--upgrade, -U Allow package upgrades
--upgrade-package <PKG>, -P Upgrade specific packages
--dry-run Show changes without writing
```
### uv run
Execute commands in project environment.
```bash
uv run [OPTIONS] <COMMAND> [ARGS]...
--python <VERSION> Python version
--module, -m Run as module
--script, -s Treat as PEP 723 script
--with <PKG>, -w Include temporary packages
--isolated Fresh isolated environment
--frozen Skip lockfile updates
--locked Assert lockfile unchanged
--no-sync Skip environment sync
--no-project Don't load project environment
--no-dev Exclude dev dependencies
--extra <EXTRA> Include optional dependencies
--all-extras Include all optional dependencies
--package <PKG> Run for specific workspace package
--env-file <FILE> Load environment variables
```
### uv tree
Display dependency tree.
```bash
uv tree [OPTIONS]
--depth <DEPTH> Maximum display depth
--prune <PKG> Prune packages from tree
--package <PKG> Show tree for specific package
--invert Show reverse dependencies
--no-dedupe Show all occurrences
```
### uv export
Export dependencies to various formats.
```bash
uv export [OPTIONS]
--format <FORMAT> Output format (requirements-txt/pylock)
-o, --output-file <FILE> Output file path
--extra <EXTRA> Include optional dependencies
--all-extras Include all optional dependencies
--no-dev Exclude dev dependencies
--frozen Use existing lockfile
```
## Tool Management
### uv tool run (alias: uvx)
Execute tool without persistent installation.
```bash
uvx [OPTIONS] <COMMAND> [ARGS]...
uv tool run [OPTIONS] <COMMAND> [ARGS]...
--from <PACKAGE> Source package
--with <PACKAGE> Include additional packages
--python <VERSION> Python version
--isolated Fresh environment
```
### uv tool install
Install tool persistently.
```bash
uv tool install [OPTIONS] <PACKAGE>
--from <PACKAGE> Install from specific package
--with <PACKAGE> Include additional packages
--python <VERSION> Python version
--force Overwrite existing
--editable, -e Editable mode
```
### uv tool upgrade
Update installed tool.
```bash
uv tool upgrade [OPTIONS] [PACKAGE]
--all Upgrade all tools
```
### uv tool list
List installed tools.
```bash
uv tool list [OPTIONS]
--show-paths Display installation paths
```
### uv tool uninstall
Remove installed tool.
```bash
uv tool uninstall <PACKAGE>
```
## Python Management
### uv python install
Install Python versions.
```bash
uv python install [OPTIONS] <VERSIONS>...
--force Reinstall if present
--preview Allow preview versions
```
### uv python list
List Python versions.
```bash
uv python list [OPTIONS]
--all-versions Show all available versions
--only-installed Show only installed versions
```
### uv python pin
Pin Python version for project.
```bash
uv python pin [OPTIONS] <VERSION>
--global Pin globally for user
--rm Remove pin
--python-preference <PREF> Preference (only-managed/managed/system/only-system)
```
### uv python find
Locate Python interpreter.
```bash
uv python find <VERSION>
```
### uv python upgrade
Update Python installations.
```bash
uv python upgrade [OPTIONS] [VERSION]
--all Upgrade all installations
```
## pip Interface
### uv pip install
Install packages.
```bash
uv pip install [OPTIONS] <PACKAGES>...
--requirement <FILE>, -r Install from requirements
--editable <PATH>, -e Editable mode
--constraint <FILE>, -c Apply constraints
--override <FILE> Apply overrides
--extra <EXTRA> Install optional dependencies
--all-extras Install all optional dependencies
--no-deps Don't install dependencies
--python <PYTHON> Target Python environment
--system Install into system Python
--break-system-packages Allow system modifications
--target <DIR> Install to directory
--upgrade, -U Upgrade packages
--upgrade-package <PKG>, -P Upgrade specific packages
--force-reinstall Reinstall even if satisfied
--no-build Don't build from source
--no-binary <PKG> Don't use wheels
--only-binary <PKG> Only use wheels
--dry-run Show changes without installing
```
### uv pip compile
Generate requirements file.
```bash
uv pip compile [OPTIONS] <INPUT_FILES>...
-o, --output-file <FILE> Output file
--extra <EXTRA> Include optional dependencies
--all-extras Include all optional dependencies
--constraint <FILE>, -c Apply constraints
--override <FILE> Apply overrides
--python <VERSION> Target Python version
--python-platform <PLATFORM> Target platform
--python-version <VERSION> Python version constraint
--universal Cross-platform requirements
--no-strip-markers Preserve environment markers
--resolution <STRATEGY> Resolution strategy (highest/lowest/lowest-direct)
--prerelease <MODE> Pre-release handling (allow/disallow/if-necessary/if-necessary-or-explicit)
--upgrade, -U Allow upgrades
--upgrade-package <PKG>, -P Upgrade specific packages
--generate-hashes Include package hashes
--annotation-style <STYLE> Annotation format (line/split)
```
### uv pip sync
Install from requirements file.
```bash
uv pip sync [OPTIONS] <FILE>
--python <PYTHON> Target Python environment
--system Install into system Python
--break-system-packages Allow system modifications
--target <DIR> Install to directory
--no-build Don't build from source
--dry-run Show changes without installing
--reinstall Reinstall all packages
--link-mode <MODE> Installation link mode (clone/copy/hardlink/symlink)
--compile-bytecode Compile to bytecode
--require-hashes Require package hashes
```
### uv pip uninstall
Remove packages.
```bash
uv pip uninstall [OPTIONS] <PACKAGES>...
--requirement <FILE>, -r Uninstall from requirements
--python <PYTHON> Target Python environment
--system Uninstall from system Python
```
### uv pip freeze
List installed packages.
```bash
uv pip freeze [OPTIONS]
--exclude-editable Exclude editable packages
--strict Fail on missing dependencies
--python <PYTHON> Target Python environment
```
### uv pip list
List installed packages with formatting.
```bash
uv pip list [OPTIONS]
--editable, -e Show only editable packages
--exclude-editable Exclude editable packages
--format <FORMAT> Output format (columns/freeze/json)
--python <PYTHON> Target Python environment
--system Target system Python
```
### uv pip show
Display package information.
```bash
uv pip show <PACKAGE>
--python <PYTHON> Target Python environment
--system Target system Python
```
### uv pip tree
Display dependency tree.
```bash
uv pip tree [OPTIONS]
--depth <DEPTH> Maximum display depth
--prune <PKG> Prune packages
--package <PKG> Show tree for specific package
--invert Show reverse dependencies
--python <PYTHON> Target Python environment
--no-dedupe Show all occurrences
```
### uv pip check
Verify dependencies.
```bash
uv pip check [OPTIONS]
--python <PYTHON> Target Python environment
--system Target system Python
```
## Virtual Environments
### uv venv
Create virtual environment.
```bash
uv venv [OPTIONS] [PATH]
--python <VERSION> Python version
--seed Install seed packages (pip, setuptools, wheel)
--prompt <PROMPT> Custom environment prompt
--system-site-packages Access to system packages
--relocatable Relocatable environment
--allow-existing Allow existing directory
--no-project Don't detect project
```
## Build and Publish
### uv build
Build Python packages.
```bash
uv build [OPTIONS] [SRC]
--sdist Build source distribution only
--wheel Build wheel only
--out-dir <DIR> Output directory (default: dist/)
--package <PACKAGE> Build specific workspace package
--no-build-isolation Disable build isolation
--build-constraint <FILE> Apply build constraints
--config-setting <KEY=VALUE> Pass settings to build backend
```
### uv publish
Upload distributions to package indexes.
```bash
uv publish [OPTIONS] [FILES]...
--username <USER>, -u Registry username
--password <PASS>, -p Registry password
--token <TOKEN>, -t Authentication token
--publish-url <URL> Registry URL (default: PyPI)
--index <NAME> Named index from config
--keyring-provider <PROVIDER> Keyring authentication
--trusted-publishing <MODE> OIDC trusted publishing (always/if-available/never)
--check-url <URL> Verify package existence URL
--build Build packages before publishing
--no-build Publish existing distributions
```
## Cache Management
### uv cache clean
Clear cache.
```bash
uv cache clean [OPTIONS] [PACKAGE]
--package <PACKAGE> Clean specific package only
```
### uv cache prune
Remove unreachable entries.
```bash
uv cache prune [OPTIONS]
--ci Optimize for CI (keep wheels, remove downloads)
```
### uv cache dir
Show cache directory path.
```bash
uv cache dir
```
## Self Management
### uv self update
Update uv itself.
```bash
uv self update [OPTIONS]
--version <VERSION> Update to specific version
```
### uv self version
Show uv version.
```bash
uv self version
uv --version # Equivalent
uv -V # Short form
```
## Utility Commands
### uv generate-shell-completion
Generate shell completions.
```bash
uv generate-shell-completion <SHELL>
# Shells: bash, zsh, fish, elvish, powershell
```
## Index and Resolution Flags
Control package index behavior:
```bash
--index <NAME>=<URL> Named package index
--default-index <URL> Primary index
--extra-index-url <URL> Supplementary index
--find-links <PATH_OR_URL> Find-links location
--no-index Ignore all indexes
--index-strategy <STRATEGY> Resolution strategy (first-index/unsafe-first-match/unsafe-best-match)
--resolution <STRATEGY> Version selection (highest/lowest/lowest-direct)
--prerelease <MODE> Pre-release handling
--exclude-newer <TIMESTAMP> Exclude packages newer than timestamp
--no-sources Ignore [tool.uv.sources]
```
## Build Flags
Control build and installation:
```bash
--no-build Don't build from source
--no-binary <PKG> Don't use wheels (use :all: for all)
--only-binary <PKG> Only use wheels (use :all: for all)
--no-build-isolation Disable build isolation
--no-build-isolation-package <PKG> Disable for specific packages
--build-constraint <FILE> Build dependency constraints
--config-setting <KEY=VALUE> PEP 517 build backend settings
--link-mode <MODE> Installation method (clone/copy/hardlink/symlink)
--compile-bytecode Compile to bytecode
--reinstall Reinstall all packages
--reinstall-package <PKG> Reinstall specific packages
--require-hashes Require package hashes
```
## Examples
**Initialize and manage project:**
```bash
uv init myproject --lib
cd myproject
uv add requests pytest --dev
uv lock
uv sync
uv run pytest
```
**Create and run script:**
```bash
uv init --script analyze.py
uv add --script analyze.py pandas matplotlib
uv run analyze.py
```
**Install and use tools:**
```bash
uvx ruff check
uv tool install black
black myfile.py
```
**Python version management:**
```bash
uv python install 3.12
uv python pin 3.12
uv run --python 3.11 script.py
```
**pip interface:**
```bash
uv pip install flask
uv pip compile requirements.in -o requirements.txt
uv pip sync requirements.txt
```
**Build and publish:**
```bash
uv build
uv publish --token $PYPI_TOKEN
```

View File

@@ -0,0 +1,541 @@
# uv Configuration Reference
Complete configuration guide for uv (v0.9.5).
## Configuration Files
### File Discovery Hierarchy
1. **Project-level** (current or parent directories):
- `pyproject.toml` (under `[tool.uv]`)
- `uv.toml` (no prefix required)
2. **User-level**:
- Linux/macOS: `~/.config/uv/uv.toml`
- Windows: `%APPDATA%\uv\uv.toml`
3. **System-level**:
- Linux/macOS: `/etc/uv/uv.toml`
- Windows: `%PROGRAMDATA%\uv\uv.toml`
### Precedence Order
1. Command-line arguments (highest)
2. Environment variables
3. Project-level configuration
4. User-level configuration
5. System-level configuration (lowest)
**Note**: `uv.toml` takes precedence over `pyproject.toml` in same directory.
## pyproject.toml Configuration
### Project Metadata
```toml
[project]
name = "myproject"
version = "1.0.0"
description = "Project description"
requires-python = ">=3.11"
dependencies = [
"requests>=2.31",
"fastapi>=0.115",
]
# Preferred: Use PEP 735 dependency groups
[dependency-groups]
dev = [
"pytest>=8.4.2",
"ruff>=0.13.3",
"mypy>=1.18.2",
]
docs = ["sphinx", "mkdocs"]
test = ["pytest-cov", "hypothesis"]
# Alternative: project.optional-dependencies (older pattern)
# [project.optional-dependencies]
# dev = ["pytest>=8.3", "ruff>=0.5"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
```
### Core uv Settings
```toml
[tool.uv]
# Project management
managed = true # uv manages project
package = true # Project is Python package
default-groups = ["dev"] # Default dependency groups
# Resolution
resolution = "highest" # highest/lowest/lowest-direct
fork-strategy = "requires-python" # requires-python/fewest
index-strategy = "first-index" # first-index/unsafe-first-match/unsafe-best-match
# Environment restrictions
environments = [
"sys_platform == 'darwin'",
"sys_platform == 'linux'",
]
# Dependency constraints
constraint-dependencies = ["grpcio<1.65"]
override-dependencies = ["werkzeug==2.3.0"]
# Build configuration
compile-bytecode = true
no-build-isolation-package = ["flash-attn"]
config-settings = { editable_mode = "compat" }
# Cache configuration
cache-dir = "./.uv_cache"
cache-keys = [
{ file = "pyproject.toml" },
{ git = { commit = true } },
]
# Network configuration
concurrent-downloads = 20
concurrent-builds = 8
offline = false
# Python management
python-preference = "managed" # only-managed/managed/system/only-system
python-downloads = "automatic" # automatic/manual/never
# Security
keyring-provider = "subprocess" # subprocess/disabled
allow-insecure-host = ["packages.example.com"]
# Preview features
preview = true
```
### Package Indexes
```toml
[[tool.uv.index]]
name = "pytorch-cu121"
url = "https://download.pytorch.org/whl/cu121"
explicit = true # Require explicit pinning
default = false # Replace PyPI as default
authenticate = "always" # always/never
cache-control = "max-age=3600"
[[tool.uv.index]]
name = "private-registry"
url = "https://packages.example.com/simple"
explicit = true
```
### Dependency Sources
```toml
[tool.uv.sources]
# Workspace dependencies
internal-lib = { workspace = true }
# Git repositories
httpx = { git = "https://github.com/encode/httpx" }
fastapi = { git = "https://github.com/tiangolo/fastapi", branch = "main" }
requests = { git = "https://github.com/psf/requests", tag = "v2.31.0" }
# Local paths
local-pkg = { path = "../local-pkg" }
editable-pkg = { path = "./pkg", editable = true }
# URLs
package-url = { url = "https://example.com/package.tar.gz" }
# Index pinning
torch = { index = "pytorch-cu121" }
# Conditional sources
package = [
{ index = "linux-index", marker = "sys_platform == 'linux'" },
{ index = "macos-index", marker = "sys_platform == 'darwin'" },
]
```
### Workspace Configuration
```toml
[tool.uv.workspace]
members = ["packages/*", "apps/*"]
exclude = ["packages/deprecated"]
```
### Build Configuration
```toml
[tool.uv]
# Build isolation control
no-build-isolation-package = ["flash-attn", "deepspeed"]
# Extra build dependencies
[tool.uv.extra-build-dependencies]
flash-attn = ["torch", "setuptools"]
deepspeed = [{ requirement = "torch", match-runtime = true }]
# Build environment variables
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
opencv-python = { CMAKE_ARGS = "-DWITH_CUDA=ON" }
# Dependency metadata (for packages without proper metadata)
[[tool.uv.dependency-metadata]]
name = "package-name"
version = "1.0.0"
requires-dist = ["dependency1>=1.0"]
requires-python = ">=3.8"
# Per-package build settings
[tool.uv.config-settings-package]
numpy = { editable_mode = "compat" }
scipy = { use_system_blas = "true" }
# Build constraints
build-constraint-dependencies = ["setuptools==60.0.0"]
```
### Conflict Resolution
```toml
[tool.uv]
# Declare mutually exclusive extras/groups
conflicts = [
[
{ extra = "cuda" },
{ extra = "rocm" },
],
[
{ group = "prod" },
{ group = "dev" },
],
]
```
### pip-Specific Settings
```toml
[tool.uv.pip]
compile-bytecode = true
strict = true
generate-hashes = true
annotation-style = "line" # line/split
extra = ["dev", "test"]
output-file = "requirements.txt"
break-system-packages = false
no-strip-markers = false
universal = false
```
## Environment Variables
### Core Configuration
```bash
# Directories
UV_CACHE_DIR=/custom/cache
UV_PROJECT_ENVIRONMENT=.venv
UV_WORKING_DIRECTORY=/path/to/project
# Configuration
UV_CONFIG_FILE=/path/to/uv.toml
UV_NO_CONFIG=1
# Python management
UV_PYTHON=3.11
UV_PYTHON_PREFERENCE=managed # only-managed/managed/system/only-system
UV_PYTHON_DOWNLOADS=automatic # automatic/manual/never
UV_PYTHON_INSTALL_DIR=~/.python
UV_MANAGED_PYTHON=1
UV_SYSTEM_PYTHON=1
```
### Network and Performance
```bash
# Downloads and builds
UV_CONCURRENT_DOWNLOADS=20
UV_CONCURRENT_BUILDS=8
UV_CONCURRENT_INSTALLS=4
UV_HTTP_TIMEOUT=30
UV_HTTP_RETRIES=3
# Network control
UV_OFFLINE=1
UV_NO_CACHE=1
```
### Index Configuration
```bash
# Primary index
UV_DEFAULT_INDEX=https://pypi.org/simple
UV_INDEX_URL=https://pypi.org/simple # Deprecated
# Additional indexes
UV_INDEX="name1=https://index1.com name2=https://index2.com"
UV_EXTRA_INDEX_URL=https://custom.index.com # Deprecated
# Index authentication
UV_INDEX_PRIVATE_REGISTRY_USERNAME=user
UV_INDEX_PRIVATE_REGISTRY_PASSWORD=pass
```
### Build Configuration
```bash
# Build control
UV_COMPILE_BYTECODE=1
UV_NO_BUILD_ISOLATION=1
UV_NO_BUILD=1
UV_NO_BUILD_PACKAGE="numpy scipy"
UV_NO_BINARY=1
UV_NO_BINARY_PACKAGE="numpy scipy"
UV_CONFIG_SETTINGS='{"editable_mode": "compat"}'
# Build constraints
UV_BUILD_CONSTRAINT=/path/to/constraints.txt
```
### Resolution Control
```bash
# Resolution strategy
UV_RESOLUTION=highest # highest/lowest/lowest-direct
UV_PRERELEASE=if-necessary # allow/disallow/if-necessary/if-necessary-or-explicit
UV_EXCLUDE_NEWER=2025-01-01T00:00:00Z
# Lock and sync
UV_FROZEN=1
UV_LOCKED=1
UV_NO_SYNC=1
# Dependencies
UV_DEV=1
UV_NO_DEV=1
UV_NO_EDITABLE=1
```
### Security
```bash
# Authentication
UV_KEYRING_PROVIDER=subprocess # subprocess/disabled
UV_NATIVE_TLS=1
# Insecure hosts
UV_INSECURE_HOST="host1.com host2.com"
# Publishing
UV_PUBLISH_USERNAME=__token__
UV_PUBLISH_PASSWORD=$PYPI_TOKEN
UV_PUBLISH_TOKEN=$PYPI_TOKEN
UV_TRUSTED_PUBLISHING=automatic
```
### Output Control
```bash
# Output format
UV_NO_PROGRESS=1
UV_NO_WRAP=1
UV_QUIET=1
UV_VERBOSE=1
UV_COLOR=always # always/never/auto
UV_LOG_CONTEXT=1
```
### Tool Management
```bash
UV_TOOL_DIR=~/.local/share/uv/tools
UV_TOOL_BIN_DIR=~/.local/bin
```
### Preview Features
```bash
UV_PREVIEW=1
UV_PREVIEW_FEATURES=feature1,feature2
```
### Advanced Settings
```bash
# Installation
UV_LINK_MODE=copy # clone/copy/hardlink/symlink
UV_REINSTALL=1
UV_UPGRADE=1
UV_NO_INDEX=1
UV_ISOLATED=1
# Environment files
UV_ENV_FILE=.env.production
UV_NO_ENV_FILE=1
# S3 support (preview)
UV_S3_ENDPOINT_URL=https://s3.amazonaws.com
# Mirrors
UV_PYTHON_INSTALL_MIRROR=https://mirror.example.com
UV_PYPY_INSTALL_MIRROR=https://pypy-mirror.example.com
# Debug
RUST_LOG=uv=debug
RUST_BACKTRACE=1
```
## Complete Example Configuration
```toml
[project]
name = "myproject"
version = "1.0.0"
requires-python = ">=3.11"
dependencies = ["fastapi>=0.115", "torch"]
# Preferred: Use PEP 735 dependency groups
[dependency-groups]
dev = [
"pytest>=8.4.2",
"ruff>=0.13.3",
"mypy>=1.18.2",
]
test = ["pytest-cov", "pytest-asyncio"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.uv]
# Project configuration
managed = true
package = true
default-groups = ["dev"]
# Resolution
resolution = "highest"
fork-strategy = "requires-python"
index-strategy = "first-index"
# Environment restrictions
environments = ["sys_platform == 'linux'"]
required-environments = ["sys_platform == 'linux' and platform_machine == 'x86_64'"]
# Constraints
constraint-dependencies = ["grpcio<1.65"]
override-dependencies = ["werkzeug==2.3.0"]
build-constraint-dependencies = ["setuptools==60.0.0"]
# Build configuration
compile-bytecode = true
no-build-isolation-package = ["flash-attn"]
config-settings = { editable_mode = "compat" }
# Cache configuration
cache-dir = "./.uv_cache"
cache-keys = [
{ file = "pyproject.toml" },
{ git = { commit = true } },
]
# Network
concurrent-downloads = 20
concurrent-builds = 8
# Python management
python-preference = "managed"
python-downloads = "automatic"
# Security
keyring-provider = "subprocess"
# Preview features
preview = true
# Extra build configuration
[tool.uv.extra-build-dependencies]
flash-attn = [{ requirement = "torch", match-runtime = true }]
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
# Package sources
[tool.uv.sources]
torch = { index = "pytorch-cu121" }
internal-lib = { workspace = true }
# Custom indexes
[[tool.uv.index]]
name = "pytorch-cu121"
url = "https://download.pytorch.org/whl/cu121"
explicit = true
[[tool.uv.index]]
name = "private"
url = "https://packages.example.com/simple"
authenticate = "always"
# Workspace configuration
[tool.uv.workspace]
members = ["packages/*"]
exclude = ["packages/deprecated"]
# pip-specific settings
[tool.uv.pip]
compile-bytecode = true
strict = true
generate-hashes = false
# Conflict resolution
[[tool.uv.conflicts]]
extra = ["cuda", "rocm"]
```
## Configuration Best Practices
1. **Project vs User Config**: Keep project-specific settings in `pyproject.toml`, user preferences in `~/.config/uv/uv.toml`
2. **Security**: Never commit credentials to version control, use environment variables
3. **Index Pinning**: Use `explicit = true` for custom indexes to prevent accidents
4. **Build Isolation**: Only disable for problematic packages, document why
5. **Cache**: Use project-local cache (`.uv_cache`) for CI reproducibility
6. **Python Preference**: Use `managed` for consistent team environments
7. **Lockfiles**: Always commit `uv.lock` for reproducible installs
8. **Environment Restrictions**: Use `environments` to prevent platform-specific resolution issues
9. **Preview Features**: Test in development before enabling in production
## uv.toml Format
`uv.toml` uses same structure as `pyproject.toml` but **without** `[tool.uv]` prefix:
```toml
# uv.toml (no [tool.uv] prefix)
managed = true
resolution = "highest"
compile-bytecode = true
[[index]]
name = "pytorch"
url = "https://download.pytorch.org/whl/cpu"
```
Equivalent to:
```toml
# pyproject.toml (with [tool.uv] prefix)
[tool.uv]
managed = true
resolution = "highest"
compile-bytecode = true
[[tool.uv.index]]
name = "pytorch"
url = "https://download.pytorch.org/whl/cpu"
```

View File

@@ -0,0 +1,732 @@
# uv Troubleshooting Guide
Common issues and solutions for uv (v0.9.5).
## Installation and Setup Issues
### uv Command Not Found
**Problem**: `uv: command not found` after installation
**Solutions**:
```bash
# Check if uv is installed
which uv
# Check PATH
echo $PATH
# Add to PATH (Unix)
export PATH="$HOME/.local/bin:$PATH"
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
# Windows: Add to PATH
# %USERPROFILE%\.local\bin
# Verify installation
uv --version
# Reinstall if necessary
curl -LsSf https://astral.sh/uv/install.sh | sh
```
### Permission Denied
**Problem**: Permission errors during installation or execution
**Solutions**:
```bash
# Unix: Fix permissions
chmod +x ~/.local/bin/uv
# Don't use sudo with uv (creates permission issues)
# Instead use virtual environments
# If accidentally used sudo
sudo chown -R $USER:$USER ~/.local/share/uv
sudo chown -R $USER:$USER ~/.cache/uv
```
## Environment Management Issues
### "Externally Managed" Error
**Problem**: `error: The Python interpreter at ... is externally managed`
**Cause**: Trying to install to uv-managed or system Python with `--system` flag
**Solutions**:
```bash
# Solution 1: Use virtual environment (recommended)
uv venv
source .venv/bin/activate
uv pip install package
# Solution 2: Use project context
uv add package # For projects
uv run python script.py # Automatically manages environment
# Solution 3: For scripts with PEP 723 metadata
uv run --script script.py # Creates isolated environment
# Don't use --system with uv-managed Python
```
### Virtual Environment Accidentally Deleted
**Problem**: Running `uv venv` again wipes existing environment
**Cause**: uv doesn't prompt before overwriting `.venv`
**Prevention**:
```bash
# Check before recreating
if [ -d ".venv" ]; then
echo "Warning: .venv exists"
# Use --force if intentional
uv venv --force
else
uv venv
fi
# Or use different path
uv venv myenv
```
**Recovery**:
```bash
# Recreate and reinstall
uv venv
uv sync # If using project with lockfile
# or
uv pip install -r requirements.txt
```
### Can't Activate Virtual Environment
**Problem**: Virtual environment activation fails
**Solutions**:
```bash
# Unix/macOS - bash/zsh
source .venv/bin/activate
# Unix/macOS - fish
source .venv/bin/activate.fish
# Windows - cmd
.venv\Scripts\activate.bat
# Windows - PowerShell
.venv\Scripts\Activate.ps1
# If PowerShell execution policy blocks
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# Alternative: Use uv run (no activation needed)
uv run python script.py
```
## Dependency Resolution Issues
### Conflicting Dependencies
**Problem**: `error: No solution found when resolving dependencies`
**Diagnosis**:
```bash
# See detailed resolution output
uv add package -vvv
# Check dependency tree for conflicts
uv tree
# Check specific package requirements
uv pip show package
```
**Solutions**:
```bash
# 1. Update packages to resolve conflict
uv lock --upgrade
uv sync
# 2. Upgrade specific conflicting package
uv lock --upgrade-package problematic-package
# 3. Use constraint to force specific version
# In pyproject.toml:
[tool.uv]
constraint-dependencies = ["conflicting-package<2.0"]
# 4. Try different resolution strategy
[tool.uv]
resolution = "lowest-direct" # Instead of "highest"
# 5. Use override for absolute control
[tool.uv]
override-dependencies = ["problematic-package==1.5.0"]
```
### Lockfile Out of Sync
**Problem**: `error: The lockfile is out of sync with the project dependencies`
**Solutions**:
```bash
# Regenerate lockfile
uv lock
# If intentional (CI), use --frozen
uv sync --frozen
# If must match exactly (strict CI), use --locked
uv sync --locked # Fails if out of sync
# Update dependencies and lockfile
uv lock --upgrade
```
### Pre-release Dependencies
**Problem**: uv won't install pre-release version you need
**Solutions**:
```bash
# Allow pre-releases in pyproject.toml
[tool.uv]
prerelease = "allow" # or "if-necessary" or "if-necessary-or-explicit"
# Or specify explicitly in dependencies
dependencies = ["package>=1.0.0a1"] # Explicit pre-release version
# Command-line override
uv add --prerelease allow package
```
## Build Failures
### Build Dependencies Missing
**Problem**: `error: Failed to build` with missing module errors
**Common Errors**:
```text
ModuleNotFoundError: No module named 'setuptools'
ModuleNotFoundError: No module named 'distutils'
ModuleNotFoundError: No module named 'Cython'
```
**Solutions**:
```bash
# 1. For modern packages, uv should handle this
# Check if package is compatible with your Python version
# 2. Install build dependencies manually (rarely needed)
uv pip install setuptools wheel
# 3. For packages requiring Cython
[tool.uv.extra-build-dependencies]
problematic-package = ["Cython"]
# 4. Python 3.12+ removed distutils
# Update to newer package version
uv add "package>=newer-version"
# 5. Use pre-built wheels instead
uv add package --only-binary package
```
### System Dependencies Missing
**Problem**: Build fails with C compiler or library errors
**Common Errors**:
```text
error: command 'gcc' failed
fatal error: Python.h: No such file or directory
error: openssl/ssl.h: No such file or directory
```
**Solutions**:
```bash
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install \
python3-dev \
build-essential \
libssl-dev \
libffi-dev \
libpq-dev \
libxml2-dev \
libxslt1-dev \
libjpeg-dev \
zlib1g-dev
# macOS
xcode-select --install
brew install openssl postgresql
# RHEL/CentOS/Fedora
sudo yum groupinstall "Development Tools"
sudo yum install python3-devel openssl-devel
# Arch Linux
sudo pacman -S base-devel python
# Verify compiler
gcc --version
python3-config --includes
```
### Build Isolation Issues
**Problem**: Package build fails due to missing dependencies in isolated environment
**Solutions**:
```bash
# Disable isolation for specific package
[tool.uv]
no-build-isolation-package = ["flash-attn", "deepspeed"]
# Provide extra build dependencies
[tool.uv.extra-build-dependencies]
flash-attn = ["torch", "setuptools", "ninja"]
# Match runtime version
[tool.uv.extra-build-dependencies]
deepspeed = [{ requirement = "torch", match-runtime = true }]
# Set build environment variables
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
```
## Package Index Issues
### Authentication Failures
**Problem**: `error: Failed to download` from private registry
**Solutions**:
```bash
# Set credentials via environment variables
export UV_INDEX_PRIVATE_USERNAME="user"
export UV_INDEX_PRIVATE_PASSWORD="password"
# Or use keyring
export UV_KEYRING_PROVIDER=subprocess
# For PyPI token
export UV_PUBLISH_TOKEN="pypi-..."
# In pyproject.toml for named index
[[tool.uv.index]]
name = "private"
url = "https://packages.example.com/simple"
authenticate = "always"
# URL-embedded credentials (less secure)
[[tool.uv.index]]
url = "https://user:pass@packages.example.com/simple"
```
### SSL Certificate Errors
**Problem**: SSL verification fails
**Solutions**:
```bash
# Use system certificates (recommended)
export UV_NATIVE_TLS=1
[tool.uv]
native-tls = true
# Allow specific insecure host (not recommended)
export UV_INSECURE_HOST="packages.example.com"
[tool.uv]
allow-insecure-host = ["packages.example.com"]
# Update certificates
# Ubuntu/Debian
sudo apt-get install ca-certificates
sudo update-ca-certificates
# macOS
# Certificates usually managed by system
```
### Package Not Found
**Problem**: `error: Package 'X' not found`
**Diagnosis**:
```bash
# Check index configuration
uv pip install package -vvv
# Verify index URL
curl https://pypi.org/simple/package-name/
# Check index strategy
[tool.uv]
index-strategy = "first-index" # Try "unsafe-best-match" if needed
```
**Solutions**:
```bash
# 1. Check package name spelling
uv add correct-package-name
# 2. Add appropriate index
[[tool.uv.index]]
name = "pytorch"
url = "https://download.pytorch.org/whl/cu121"
[tool.uv.sources]
torch = { index = "pytorch" }
# 3. Install from URL directly
uv add https://files.pythonhosted.org/.../package.whl
# 4. Check Python version compatibility
requires-python = ">=3.11" # Package may require newer Python
```
## Performance Issues
### Slow Downloads
**Problem**: Package downloads are slow
**Solutions**:
```bash
# Increase concurrent downloads
export UV_CONCURRENT_DOWNLOADS=50
[tool.uv]
concurrent-downloads = 50
# Use mirror
export UV_PYTHON_INSTALL_MIRROR="https://mirror.example.com"
# Check network
curl -o /dev/null https://pypi.org/simple/
# Disable progress bars (slight speedup)
export UV_NO_PROGRESS=1
```
### Cache Issues
**Problem**: Cache grows too large or contains stale data
**Solutions**:
```bash
# Check cache size
du -sh $(uv cache dir)
# Clean entire cache
uv cache clean
# Prune unreachable entries
uv cache prune
# CI optimization (keep wheels, remove downloads)
uv cache prune --ci
# Bypass cache temporarily
uv sync --no-cache
# Custom cache location
export UV_CACHE_DIR=/path/to/cache
[tool.uv]
cache-dir = "/path/to/cache"
```
## Script and Tool Issues
### PEP 723 Script Errors
**Problem**: Script with inline metadata won't run
**Solutions**:
```bash
# Verify metadata block format
# /// script
# requires-python = ">=3.11"
# dependencies = ["requests"]
# ///
# Must use exact format (no spaces before ///)
# Block must be at top of file (after shebang)
# Run with explicit --script flag
uv run --script script.py
# Check for syntax errors
python3 -m py_compile script.py
# Lock script dependencies
uv lock --script script.py
# Verify with verbose output
uv run --script script.py -v
```
### Tool Installation Fails
**Problem**: `uv tool install` fails or tool not in PATH
**Solutions**:
```bash
# Verify installation
uv tool list
uv tool dir
# Check PATH
echo $PATH | grep -o '\.local/bin'
# Add tools to PATH
export PATH="$(uv tool dir)/bin:$PATH"
echo 'export PATH="$(uv tool dir)/bin:$PATH"' >> ~/.bashrc
# Update shell integration
uv tool update-shell
# Reinstall tool
uv tool install --force package
# Try with specific Python
uv tool install --python 3.11 package
```
## Python Version Issues
### Wrong Python Version Used
**Problem**: uv uses unexpected Python version
**Diagnosis**:
```bash
# Check detected Python
uv python find
# Check project pin
cat .python-version
# Check preference
echo $UV_PYTHON_PREFERENCE
```
**Solutions**:
```bash
# Pin project Python version
uv python pin 3.11
# Set preference
export UV_PYTHON_PREFERENCE=managed
[tool.uv]
python-preference = "managed"
# Install required Python
uv python install 3.11
# Specify explicitly
uv run --python 3.11 script.py
uv venv --python 3.12
```
### Python Download Fails
**Problem**: `error: Failed to download Python`
**Solutions**:
```bash
# Check network connectivity
curl -I https://github.com/indygreg/python-build-standalone/releases
# Use manual download
export UV_PYTHON_DOWNLOADS=manual
# Use mirror
export UV_PYTHON_INSTALL_MIRROR="https://mirror.example.com"
# Disable downloads, use system Python
export UV_PYTHON_PREFERENCE=system
```
## Workspace Issues
### Workspace Member Not Found
**Problem**: Workspace member not detected
**Solutions**:
```bash
# Verify workspace configuration
[tool.uv.workspace]
members = ["packages/*"] # Check glob pattern
# Verify member has pyproject.toml
ls packages/*/pyproject.toml
# Check exclusions
[tool.uv.workspace]
exclude = ["packages/deprecated"]
# Run from workspace root
cd workspace-root
uv sync
# Build specific member
uv build --package member-name
```
## CI/CD Issues
### CI Cache Not Working
**Problem**: CI doesn't use cache effectively
**Solutions**:
```yaml
# GitHub Actions
- uses: actions/cache@v4
with:
path: ~/.cache/uv
key: uv-${{ runner.os }}-${{ hashFiles('uv.lock') }}
restore-keys: |
uv-${{ runner.os }}-
# Use frozen mode in CI
- run: uv sync --frozen
# Prune cache for CI efficiency
- run: uv cache prune --ci
```
### Different Results Locally vs CI
**Problem**: CI builds differently than local
**Solutions**:
```bash
# Use same Python version
uv python install $(cat .python-version)
# Use frozen lockfile
uv sync --frozen
# Use locked for strict matching
uv sync --locked
# Match Python preference
export UV_PYTHON_PREFERENCE=managed
# Check environment differences
uv run python -c "import sys; print(sys.version)"
uv pip list
```
## Debugging
### Enable Verbose Logging
```bash
# Increasing verbosity
uv sync -v # Basic verbose
uv sync -vv # More verbose
uv sync -vvv # Maximum verbosity
# Rust-level debugging
export RUST_LOG=uv=debug
export RUST_BACKTRACE=1
uv sync
# Log to file
uv sync -vvv 2>&1 | tee uv-debug.log
```
### Check System Information
```bash
# uv version and build info
uv self version
uv --version
# Python information
uv python list
uv python find
# Cache information
uv cache dir
du -sh $(uv cache dir)
# Tool information
uv tool dir
uv tool list --show-paths
# Project information
cat pyproject.toml
cat uv.lock | head -20
# System information
python3 --version
which python3
echo $PATH
env | grep UV_
```
## Getting Help
### Report Issues
```bash
# Gather diagnostic information
uv --version
python3 --version
uname -a # or systeminfo on Windows
uv sync -vvv 2>&1 | tee debug.log
# Check existing issues
# https://github.com/astral-sh/uv/issues
# Create minimal reproduction
# Include pyproject.toml, uv.lock, commands run, full error output
```
### Resources
- Documentation: <https://docs.astral.sh/uv/>
- GitHub Issues: <https://github.com/astral-sh/uv/issues>
- Discussions: <https://github.com/astral-sh/uv/discussions>
- Discord: Astral community server