Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 09:05:19 +08:00
commit 09fec2555b
96 changed files with 24269 additions and 0 deletions

500
skills/uv-debug/SKILL.md Normal file
View File

@@ -0,0 +1,500 @@
---
name: uv-debug
description: Troubleshooting and debugging problems with uv (Python package manager). Use when encountering uv installation issues, stale build cache, package not updating, or discrepancies between uv run and global installs.
---
# UV Debugging Skill
## Purpose
This skill provides systematic troubleshooting workflows for common `uv` (Python package manager) issues, with particular focus on build cache problems, installation discrepancies, and package update issues.
## When to Use This Skill
Use this skill when encountering:
- Code changes not appearing after `uv tool install`
- Discrepancy between `uv run <command>` and globally installed command
- New files/modules missing from installed package
- "Command not found" after installation
- Stale build cache issues
- Installation mode confusion (editable vs production)
## Core Concepts
### UV Installation Modes
**Production Install:**
```bash
uv tool install .
```
- Builds wheel package (cached snapshot)
- Fast to install, slow to update
- Requires reinstall after code changes
- Isolated from source directory
**Editable Install:**
```bash
uv tool install --editable .
```
- Creates symlinks to source directory
- Changes reflect immediately
- Best for active development
- Less isolated
**Local Environment:**
```bash
uv sync # Setup environment
uv run <command> # Execute from source
```
- No global install needed
- Always uses current source code
- Fastest iteration cycle
- Recommended for development
### Build Cache Location
**Global tool installs:**
```
~/.local/share/uv/tools/<package-name>/
```
**Build artifacts:**
```
build/ - Temporary build files
dist/ - Built wheels (.whl) and source distributions
*.egg-info/ - Package metadata and file manifest
```
## Troubleshooting Workflows
### Workflow 1: Code Changes Not Appearing
**Symptoms:**
- Ran `uv tool install .` or `make install`
- Code changes don't appear in installed command
- New files/modules missing
**Diagnostic Steps:**
1. **Verify the discrepancy:**
```bash
# Check which version is running
which <command>
# Test local version
uv run <command> --help
# Test global version
<command> --help
```
2. **Check for stale build artifacts:**
```bash
ls -la build/ dist/ *.egg-info 2>/dev/null
```
3. **Identify installation mode:**
```bash
# Check if editable install
ls ~/.local/share/uv/tools/<package>/ | grep -i editable
```
**Solutions (in order of preference):**
**Solution A: Clean and Reinstall (Recommended)**
```bash
# Remove stale artifacts
rm -rf build/ dist/ *.egg-info
# Force fresh build
uv tool install --force .
# Verify
<command> --help
```
**Solution B: Use Makefile Pattern**
```makefile
install: clean
uv tool install --force .
clean:
rm -rf build/ dist/ *.egg-info
find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
```
**Solution C: Switch to Local Environment**
```bash
# Setup once
uv sync
# Use for development
uv run <command>
```
**Solution D: Use Editable Mode**
```bash
uv tool install --editable .
```
### Workflow 2: New Module Not Found
**Symptoms:**
- Added new Python file (e.g., `mypackage/commands/new_cmd.py`)
- `ModuleNotFoundError` or command not recognized
- `uv run` works but global install doesn't
**Root Cause:**
Wheel package built before new file existed. Package metadata (`*.egg-info/RECORD`) doesn't list the new file.
**Solution:**
```bash
# 1. Clean build artifacts
rm -rf build/ dist/ *.egg-info
# 2. Reinstall with force
uv tool install --force .
# 3. Verify new module appears
<command> <new-subcommand> --help
```
**Prevention:**
Add to Makefile:
```makefile
install: clean
uv tool install --force .
```
### Workflow 3: Debugging Installation Location
**Symptoms:**
- Unsure which version is running
- Multiple installations conflict
- Changes not appearing despite reinstall
**Diagnostic Commands:**
```bash
# 1. Check which executable
which <command>
# 2. Check Python import location
python3 -c "import <package>; print(<package>.__file__)"
# 3. List all installations
find ~/.local/share/uv/tools -name "<package>*"
# 4. Check if editable install
cat ~/.local/share/uv/tools/<package>/*/site-packages/*.pth 2>/dev/null
```
**Interpretation:**
If `which <command>` shows:
- `~/.local/share/uv/tools/` → Global uv install
- `/usr/local/bin/` → System-wide install (pip)
- `<project>/.venv/bin/` → Virtual environment
If `.pth` file exists → Editable install (points to source)
### Workflow 4: Entry Point Not Updating
**Symptoms:**
- Changed command name or added new subcommand
- Entry point not updating in installed version
**Root Cause:**
Entry points defined in `pyproject.toml` are baked into wheel at build time.
**Solution:**
1. **Verify entry point definition:**
```bash
# Read pyproject.toml
grep -A 10 "\[project.scripts\]" pyproject.toml
```
2. **Clean and rebuild:**
```bash
rm -rf build/ dist/ *.egg-info
uv tool install --force .
```
3. **Verify entry points installed:**
```bash
ls ~/.local/share/uv/tools/<package>/*/bin/
```
### Workflow 5: Dependency Issues
**Symptoms:**
- Import errors for dependencies
- Version conflicts
- `ModuleNotFoundError` for installed packages
**Diagnostic:**
```bash
# Check installed dependencies
uv pip list
# Check project dependencies
grep -A 20 "dependencies" pyproject.toml
# Check dependency resolution
uv pip tree
```
**Solution:**
```bash
# Sync dependencies
uv sync --all-extras
# Or for global install
uv tool install --force --reinstall-package <package> .
```
## Decision Tree
```
Code changes not appearing?
├─ Does `uv run <cmd>` work?
│ ├─ Yes → Stale build cache
│ │ └─ Solution: rm -rf build/ dist/ *.egg-info && uv tool install --force .
│ └─ No → Code issue, not cache
│ └─ Debug the code itself
├─ New file/module missing?
│ └─ Solution: Clean build artifacts and reinstall
├─ Entry point not found?
│ └─ Check pyproject.toml [project.scripts], then clean and reinstall
└─ Dependency missing?
└─ Run uv sync or uv tool install --reinstall-package
```
## Best Practices
### Development Workflow
**Option 1: Local Environment (Recommended)**
```bash
# Setup once
uv sync
# Develop with instant updates
uv run <command>
uv run pytest
```
**Option 2: Editable Install**
```bash
# Install once
uv tool install --editable .
# Changes reflect immediately
<command> # Always uses latest source
```
**Option 3: Production Build with Makefile**
```bash
# Makefile ensures clean builds
make install
# Reinstall after each change
make install
```
### Testing Installation
Before distributing or deploying:
```bash
# 1. Clean environment
rm -rf build/ dist/ *.egg-info
# 2. Production build
uv tool install --force .
# 3. Test from clean shell
<command> --help
<command> <subcommand>
# 4. Verify all entry points
ls ~/.local/share/uv/tools/<package>/*/bin/
```
## Common Mistakes
### Mistake 1: Assuming `--force` Cleans Cache
**Wrong:**
```bash
uv tool install --force . # Doesn't clean build artifacts!
```
**Right:**
```bash
rm -rf build/ dist/ *.egg-info
uv tool install --force .
```
**Why:** `--force` reinstalls but may reuse cached wheel from `dist/`.
### Mistake 2: Editing Global Install Directly
**Wrong:**
```bash
# Editing files in ~/.local/share/uv/tools/<package>/
vim ~/.local/share/uv/tools/<package>/.../myfile.py
```
**Right:**
```bash
# Edit source, then reinstall
vim mypackage/myfile.py
make install
```
### Mistake 3: Mixing Installation Methods
**Problem:**
```bash
uv tool install . # Production install
# Later...
uv tool install --editable . # Now editable
# Changes behavior unpredictably
```
**Solution:**
Pick one method and stick with it, or uninstall first:
```bash
uv tool uninstall <package>
uv tool install --editable .
```
## Advanced Debugging
### Inspecting Wheel Contents
```bash
# Build wheel
uv build
# List contents
unzip -l dist/*.whl
# Extract and examine
unzip dist/*.whl -d /tmp/wheel-inspect
ls -la /tmp/wheel-inspect/<package>/
```
### Checking Package Metadata
```bash
# View installed package info
uv pip show <package>
# View RECORD file (manifest of installed files)
cat ~/.local/share/uv/tools/<package>/*/*.dist-info/RECORD
```
### Debugging Import Paths
```python
import sys
print("Python path:")
for p in sys.path:
print(f" {p}")
import <package>
print(f"\nPackage location: {<package>.__file__}")
```
## Reference: Build Process
Understanding what happens during `uv tool install .`:
1. **Read metadata** - Parse `pyproject.toml` for package info
2. **Collect files** - Find all Python files in package
3. **Build wheel** - Create `.whl` in `dist/`
4. **Write manifest** - Record all files in `*.egg-info/RECORD`
5. **Install wheel** - Copy to `~/.local/share/uv/tools/<package>/`
6. **Create entry points** - Generate executables in `bin/`
**Key insight:** Steps 3-4 create a snapshot. New files added after this won't be included until rebuild.
## Quick Reference
**Check what's running:**
```bash
which <command>
uv run <command> --version
<command> --version
```
**Clean build cache:**
```bash
rm -rf build/ dist/ *.egg-info
```
**Fresh install:**
```bash
uv tool install --force .
```
**Development mode:**
```bash
uv sync && uv run <command>
```
**Inspect installation:**
```bash
ls ~/.local/share/uv/tools/<package>/
uv pip show <package>
```
## Official UV Documentation
**Cache Management:**
- https://docs.astral.sh/uv/concepts/cache/ - How UV caches packages, cache types, cache location, cache commands
**Build Troubleshooting:**
- https://docs.astral.sh/uv/reference/troubleshooting/build-failures/ - Common build errors, missing dependencies, build isolation issues
**CLI Commands:**
- https://docs.astral.sh/uv/reference/cli/ - Complete command reference with all flags and options
**Settings Reference:**
- https://docs.astral.sh/uv/reference/settings/ - Configuration options for build constraints, cache control, dependency resolution
## Internal References
For deep technical details, see:
- `references/python-build-cache.md` - Why Python build cache doesn't auto-update
- `references/uv-cli-reference.md` - UV command workflows and examples
## Troubleshooting Checklist
When encountering issues:
- [ ] Does `uv run <command>` work? (Rules out code issues)
- [ ] Are there stale artifacts in `build/`, `dist/`, `*.egg-info`?
- [ ] Which installation mode am I using? (production/editable/local)
- [ ] Did I recently add new files?
- [ ] Did I update `pyproject.toml` dependencies or entry points?
- [ ] Am I using the right `which <command>` version?
- [ ] Have I tried cleaning and reinstalling?
## Exit Codes
Common uv exit codes:
- `0` - Success
- `1` - General error
- `2` - Command line usage error
- `101` - Package not found
- `102` - Version conflict

View File

@@ -0,0 +1,540 @@
# Python Build Cache Deep Dive
## Overview
This document explains in detail how Python's packaging system caches builds, why this causes "code not updating" issues, and the technical mechanisms behind different installation modes.
## The Build Process
### Standard Build (Non-Editable)
When running `uv tool install .` or `pip install .`:
```
Source Code → setup.py/pyproject.toml → Build Backend → Wheel → Installation
```
**Step-by-step breakdown:**
1. **Parse metadata:**
- Read `pyproject.toml` or `setup.py`
- Extract: name, version, dependencies, entry points
- Determine which files to include
2. **Collect source files:**
- Find all `.py` files in package
- Apply MANIFEST.in rules (if exists)
- Apply `pyproject.toml` includes/excludes
3. **Build wheel (.whl):**
- Compile C extensions (if any)
- Copy Python files
- Generate metadata files
- Create ZIP archive named `<package>-<version>-py3-none-any.whl`
- Store in `dist/` directory
4. **Generate metadata:**
- Create `<package>.egg-info/` directory
- Write `SOURCES.txt` (list of source files used)
- Write `RECORD` (list of files to install)
- Write `entry_points.txt` (console scripts)
- Write `requires.txt` (dependencies)
5. **Install wheel:**
- Extract wheel to installation directory
- Create entry point executables in `bin/`
- Update Python's package registry
**Key files created:**
```
build/
├── lib/
│ └── mypackage/
│ └── (compiled files)
└── bdist.*/
└── (platform-specific builds)
dist/
└── mypackage-1.0.0-py3-none-any.whl ← The cached snapshot
mypackage.egg-info/
├── SOURCES.txt ← Source files at build time
├── RECORD ← Files to install
├── entry_points.txt ← Console scripts
└── requires.txt ← Dependencies
```
### Why It's a Snapshot
**The wheel is a frozen moment in time:**
```python
# At build time (t=0):
mypackage/
__init__.py Included in wheel
cli.py Included in wheel
commands/
send.py Included in wheel
read.py Included in wheel
# After adding new file (t=1):
mypackage/
__init__.py
cli.py
commands/
send.py
read.py
workflows.py NOT in wheel! Built at t=0
```
**The wheel still contains only files from t=0:**
```bash
$ unzip -l dist/mypackage-1.0.0-py3-none-any.whl
mypackage/__init__.py
mypackage/cli.py
mypackage/commands/send.py
mypackage/commands/read.py
# workflows.py is MISSING
```
**Even `--force` reinstall uses this stale wheel:**
```bash
uv tool install --force .
# Still installs the old wheel from dist/!
```
## Installation Locations
### UV Tool Install
```
~/.local/share/uv/tools/<package>/
├── bin/
│ └── <command> ← Executable entry point
├── lib/
│ └── python3.x/
│ └── site-packages/
│ ├── <package>/ ← Package code
│ └── <package>-<version>.dist-info/
│ ├── RECORD
│ ├── entry_points.txt
│ └── METADATA
```
### Editable Install
**Instead of copying files, creates pointer:**
```
~/.local/share/uv/tools/<package>/
├── bin/
│ └── <command>
└── lib/
└── python3.x/
└── site-packages/
├── __editables__/
│ └── <package>.pth ← Points to source directory
└── <package>-<version>.dist-info/
```
**The `.pth` file contains:**
```
/absolute/path/to/source/directory
```
**Python's import system:**
1. Reads `.pth` file
2. Adds path to `sys.path`
3. Imports directly from source directory
4. New files appear immediately (no reinstall)
### Local Environment (uv run)
**No global installation at all:**
```
project/
├── .venv/
│ ├── bin/
│ │ └── python ← Local Python interpreter
│ └── lib/
│ └── python3.x/
│ └── site-packages/ ← Dependencies only
├── mypackage/ ← Source code (NOT installed)
└── pyproject.toml
```
**How `uv run` works:**
```bash
uv run mycommand
```
Internally executes:
```bash
PYTHONPATH=/path/to/project:$PYTHONPATH \
.venv/bin/python -m mypackage.cli
```
**Import resolution:**
1. Check `PYTHONPATH` first (finds `mypackage/` in project root)
2. Import directly from source
3. No build, no cache, always latest
## Why --force Doesn't Help
**Common misconception:**
```bash
uv tool install --force . # "Force should rebuild, right?"
```
**What `--force` actually does:**
- Uninstalls existing package
- Reinstalls from available sources
- **Does NOT** delete `build/` or `dist/`
**The problem:**
```bash
# 1. First install (builds wheel)
uv tool install .
# Creates: dist/mypackage-1.0.0-py3-none-any.whl
# 2. Add new file
touch mypackage/commands/workflows.py
# 3. Force reinstall
uv tool install --force .
# Finds existing wheel in dist/
# Reinstalls OLD wheel (still no workflows.py!)
```
**Why it finds the old wheel:**
UV's build process:
1. Check if wheel exists in `dist/` matching current version
2. If yes, use that wheel (fast!)
3. If no, build new wheel
**The version in `pyproject.toml` hasn't changed**, so UV reuses the cached wheel.
## How to Force Fresh Build
**Option 1: Clean first**
```bash
rm -rf build/ dist/ *.egg-info
uv tool install --force .
```
**Option 2: Bump version**
```toml
[project]
version = "1.0.1" # Changed from 1.0.0
```
```bash
uv tool install --force .
# No matching wheel in dist/, builds fresh
```
**Option 3: Build explicitly**
```bash
uv build --force
uv tool install --force .
```
## Metadata Files Deep Dive
### RECORD File
Lists every file installed, with checksums:
```
mypackage/__init__.py,sha256=abc123...,1234
mypackage/cli.py,sha256=def456...,5678
mypackage/commands/send.py,sha256=ghi789...,9012
mypackage/commands/read.py,sha256=jkl012...,3456
```
**New files aren't in RECORD = won't be installed**
### entry_points.txt
Defines console scripts:
```
[console_scripts]
gmail = mypackage.cli:main
```
**This is read at install time to create executables in `bin/`**
Changes to entry points require rebuild.
### SOURCES.txt
Lists source files used during build:
```
mypackage/__init__.py
mypackage/cli.py
mypackage/commands/send.py
mypackage/commands/read.py
setup.py
pyproject.toml
```
**Diagnostic use:** If a file is missing here, it wasn't included in the build.
## Debugging Cache Issues
### Check if wheel is stale
```bash
# 1. List files in wheel
unzip -l dist/*.whl | grep -i workflows
# If empty, file not in wheel
# 2. Check SOURCES.txt
cat *.egg-info/SOURCES.txt | grep workflows
# If empty, file wasn't included in build
# 3. Check build timestamp
ls -la dist/*.whl
# If older than source files, rebuild needed
```
### Compare local vs installed
```bash
# Source files
find mypackage -name "*.py" | sort
# Installed files
find ~/.local/share/uv/tools/mypackage -name "*.py" | sort
# Diff them
diff <(find mypackage -name "*.py" | sort) \
<(find ~/.local/share/uv/tools/mypackage -name "*.py" | sed 's|.*mypackage|mypackage|' | sort)
```
### Verify import source
```python
import mypackage
print(mypackage.__file__)
# Should point to installed location, not source
```
## Performance Trade-offs
### Why Caching Exists
**Without caching (rebuild every time):**
- Slow: Parsing, file collection, wheel building (seconds to minutes)
- Wasteful: Rebuilding unchanged code
- Inconsistent: Different builds might produce different results
**With caching (reuse wheel):**
- Fast: Just extract and copy (milliseconds)
- Efficient: Build once, install many
- Reproducible: Same wheel = same result
**The trade-off:**
- Development: Need to rebuild after changes (overhead)
- Production: Install is fast and predictable (benefit)
## Best Practices by Use Case
### Active Development
```bash
# Option 1: No install (recommended)
uv sync
uv run mycommand
# Option 2: Editable install
uv tool install --editable .
# Option 3: Makefile automation
make install # (with clean dependency)
```
### Testing Production Build
```bash
# Clean environment
rm -rf build/ dist/ *.egg-info
# Fresh build
uv tool install --force .
# Test
mycommand --help
```
### Distribution
```bash
# Build wheel
uv build
# Upload to PyPI
uv publish
# Users install
uv tool install mypackage
# (Downloads from PyPI, no source needed)
```
## Common Scenarios
### Scenario 1: Added New Subcommand
**Problem:**
```bash
# Added mypackage/commands/workflows.py
uv tool install --force .
mycommand workflows # Command not found
```
**Why:**
- Entry point might need updating in `pyproject.toml`
- Or file just not in cached wheel
**Solution:**
```bash
# 1. Check entry points
grep -A 5 "\[project.scripts\]" pyproject.toml
# 2. Clean and rebuild
rm -rf build/ dist/ *.egg-info
uv tool install --force .
```
### Scenario 2: Updated Dependency
**Problem:**
```bash
# Updated pyproject.toml dependencies
uv tool install --force .
# Still using old dependency version
```
**Why:**
- Wheel metadata includes dependency list
- Cached wheel has old requirements
**Solution:**
```bash
rm -rf build/ dist/ *.egg-info
uv tool install --force --reinstall-package <dependency> .
```
### Scenario 3: Moved Files
**Problem:**
```bash
# Moved mypackage/utils.py → mypackage/helpers/utils.py
uv tool install --force .
# Import still finds old location
```
**Why:**
- Old wheel still has `mypackage/utils.py`
- New file at `mypackage/helpers/utils.py` not in wheel
**Solution:**
```bash
rm -rf build/ dist/ *.egg-info
uv tool install --force .
```
## Wheel Internals
### Wheel Format
A wheel is a ZIP archive with structure:
```
mypackage-1.0.0-py3-none-any.whl
├── mypackage/ ← Package code
│ ├── __init__.py
│ └── cli.py
└── mypackage-1.0.0.dist-info/ ← Metadata
├── WHEEL ← Wheel version, tags
├── METADATA ← Package info (name, version, deps)
├── RECORD ← File checksums
└── entry_points.txt ← Console scripts
```
### Wheel Naming Convention
```
{distribution}-{version}-{python}-{abi}-{platform}.whl
```
Example: `mypackage-1.0.0-py3-none-any.whl`
- `mypackage` - Distribution name
- `1.0.0` - Version
- `py3` - Python 3 compatible
- `none` - No ABI requirement
- `any` - Any platform
**Pure Python wheels use `py3-none-any`**
**Compiled extensions use specific tags (e.g., `cp311-cp311-macosx_11_0_arm64`)**
## Comparison: Other Package Managers
### npm (Node.js)
```bash
npm install # Installs to node_modules/
npm link # Similar to editable install
```
**npm doesn't cache builds** - packages are just copied
**No build cache issues** - source and installed are always in sync
### cargo (Rust)
```bash
cargo build # Builds to target/
cargo install # Installs from crates.io
```
**cargo caches compiled artifacts** but rebuilds on source changes
**Incremental compilation** - only rebuilds changed files
### pip/uv (Python)
```bash
pip install . # Builds wheel, installs
pip install -e . # Editable install
```
**Caches wheels** - can cause stale installs
**Requires explicit rebuild** for changes to appear
## Summary
**Key Takeaways:**
1. **Wheels are snapshots** - Frozen at build time, don't auto-update
2. **Build artifacts cache** - `build/`, `dist/`, `*.egg-info` persist
3. **`--force` doesn't clean** - Reinstalls but may reuse cached wheel
4. **Editable mode works differently** - Uses symlinks, not copies
5. **`uv run` bypasses install** - Runs directly from source
6. **Clean before rebuild** - Only way to guarantee fresh build
**Mental Model:**
```
Source Code ──build──> Wheel (snapshot) ──install──> Installation
↓ ↑ ↓
Change Cached! Stale!
↓ ↑ ↓
Must clean cache to force rebuild
```
**When in doubt:**
```bash
rm -rf build/ dist/ *.egg-info && uv tool install --force .
```

View File

@@ -0,0 +1,607 @@
# UV CLI Reference for Troubleshooting
## Overview
This reference covers UV commands and flags commonly used for troubleshooting package installation and build issues.
## Cache Management
### uv cache clean
Remove all or specific cache entries:
```bash
# Remove ALL cache entries
uv cache clean
# Remove cache for specific package
uv cache clean <package-name>
# Example: Clean numpy cache
uv cache clean numpy
```
**When to use:**
- Suspected stale cache causing installation issues
- After manually editing cache (not recommended)
- When builds succeed locally but fail in CI
### uv cache prune
Remove unused cache entries:
```bash
# Remove all unused cache entries
uv cache prune
# CI-optimized: Remove pre-built wheels, keep source-built wheels
uv cache prune --ci
```
**When to use:**
- Disk space optimization
- CI pipelines (use `--ci` flag)
- After resolving dependency conflicts
**Difference from `clean`:**
- `clean`: Removes everything (or specific package)
- `prune`: Removes only unused entries
- `prune --ci`: Keeps wheels built from source
## Cache Refresh Options
### --refresh
Force revalidation of all cached data:
```bash
# Refresh all dependencies
uv sync --refresh
# Refresh during install
uv pip install --refresh <package>
# Refresh tool installation
uv tool install --refresh <package>
```
**When to use:**
- After package update on PyPI
- Suspected outdated cached metadata
- Testing with latest available versions
### --refresh-package
Target specific package for revalidation:
```bash
# Refresh only numpy
uv sync --refresh-package numpy
# Refresh multiple packages
uv sync --refresh-package numpy --refresh-package pandas
```
**When to use:**
- Know specific package is outdated
- Avoid full cache revalidation overhead
- Testing specific package update
### --reinstall
Ignore existing installed versions:
```bash
# Reinstall everything
uv sync --reinstall
# Reinstall specific package
uv pip install --reinstall <package>
```
**When to use:**
- Installation corrupted
- Different version needed
- Testing clean installation
**Difference from `--refresh`:**
- `--refresh`: Revalidates cache, may reuse if valid
- `--reinstall`: Forces fresh installation regardless
## Build Isolation Control
### --no-build-isolation-package
Disable build isolation for specific packages:
```bash
# Disable isolation for one package
uv pip install --no-build-isolation-package chumpy chumpy
# Disable for multiple packages
uv pip install --no-build-isolation-package pkg1 --no-build-isolation-package pkg2 pkg1 pkg2
```
**When to use:**
- Package build script needs system dependencies
- Import errors during build
- Build backend requires pre-installed modules
**Prerequisite:** Install build dependencies first:
```bash
uv pip install pip setuptools wheel
uv pip install --no-build-isolation-package <package> <package>
```
### --no-build-isolation
Disable build isolation globally:
```bash
uv pip install --no-build-isolation <package>
```
**When to use:**
- Multiple packages need system access
- Testing build with system packages
- Legacy packages with non-standard builds
## Installation Options
### --force
Force reinstallation (for `uv tool`):
```bash
# Force tool reinstall
uv tool install --force <package>
# Force tool reinstall with editable mode
uv tool install --force --editable .
```
**When to use:**
- Tool already installed, need to update
- Switching between editable/production modes
- After source code changes (non-editable mode)
### --editable
Install in editable mode:
```bash
# Install current directory as editable
uv tool install --editable .
# Install specific package as editable
uv pip install --editable /path/to/package
```
**When to use:**
- Active development
- Changes need to reflect immediately
- No reinstall after code modifications
### --reinstall-package
Reinstall specific package:
```bash
# Reinstall numpy only
uv sync --reinstall-package numpy
# Reinstall multiple packages
uv sync --reinstall-package numpy --reinstall-package pandas
```
**When to use:**
- Specific package corrupted
- Version conflict resolution
- After dependency update
## Build Configuration
### --build-constraint
Constrain build dependencies:
```bash
# Set build constraints via config
# In pyproject.toml:
[tool.uv]
build-constraint-dependencies = ["setuptools<70"]
# Or via environment
UV_BUILD_CONSTRAINT_DEPENDENCIES="setuptools<70" uv pip install <package>
```
**When to use:**
- Outdated build dependencies causing failures
- Known incompatible build dependency versions
- Reproducible build environments
### --constraint
Apply version constraints during resolution:
```bash
# Via file
uv pip install -c constraints.txt <package>
# Via config
# In pyproject.toml:
[tool.uv]
constraint-dependencies = ["numpy<2.0"]
```
**When to use:**
- Enforcing maximum versions
- Preventing incompatible upgrades
- Corporate policy requirements
## Diagnostic Commands
### uv pip show
Display package information:
```bash
# Show installed package details
uv pip show <package>
# Output includes: version, location, dependencies
```
**When to use:**
- Verify installation location
- Check installed version
- Inspect dependencies
### uv pip list
List installed packages:
```bash
# List all packages
uv pip list
# JSON output
uv pip list --format json
```
**When to use:**
- Audit installed packages
- Check for duplicates
- Compare environments
### uv pip tree
Show dependency tree:
```bash
# Full dependency tree
uv pip tree
# Reverse tree (who depends on this package)
uv pip tree --reverse <package>
```
**When to use:**
- Understand dependency relationships
- Find dependency conflicts
- Trace transitive dependencies
## Environment Management
### uv venv
Create virtual environment:
```bash
# Create with system Python
uv venv
# Create with specific Python version
uv venv -p 3.13
# Create with seed packages (pip, setuptools, wheel)
uv venv --seed
```
**When to use:**
- Isolate project dependencies
- Test different Python versions
- Reproduce CI environment
### uv sync
Synchronize environment with lock file:
```bash
# Basic sync
uv sync
# Include all extras
uv sync --all-extras
# Development dependencies only
uv sync --dev-only
```
**When to use:**
- After updating pyproject.toml
- Setting up development environment
- Syncing team dependencies
## Tool Management
### uv tool install
Install command-line tools:
```bash
# Basic install
uv tool install <package>
# With extras
uv tool install "package[extra1,extra2]"
# Specific version
uv tool install package==1.0.0
```
### uv tool uninstall
Remove installed tools:
```bash
# Uninstall tool
uv tool uninstall <package>
```
**When to use:**
- Before switching installation modes
- Cleaning up old versions
- Resolving tool conflicts
### uv tool list
List installed tools:
```bash
# Show all tools
uv tool list
# Include package versions
uv tool list --verbose
```
## Run Commands
### uv run
Execute command in project environment:
```bash
# Run Python script
uv run python script.py
# Run package entry point
uv run <command>
# Run with specific Python
uv run -p 3.13 <command>
```
**When to use:**
- Development without global install
- Testing before installation
- Avoiding installation cache issues
## Debug Flags
### --verbose
Enable verbose logging:
```bash
# Show detailed operations
uv pip install --verbose <package>
# Abbreviated form
uv pip install -v <package>
```
**When to use:**
- Diagnosing installation issues
- Understanding resolution decisions
- Reporting bugs
### --debug
Enable debug logging:
```bash
# Maximum verbosity
uv pip install --debug <package>
```
**When to use:**
- Deep troubleshooting
- Network issues
- Cache problems
### --no-cache
Disable cache for operation:
```bash
# Install without using cache
uv pip install --no-cache <package>
```
**When to use:**
- Verifying cache isn't the problem
- Testing clean installation
- CI reproducibility checks
## Cache Location Control
### --cache-dir
Specify cache directory:
```bash
# Use custom cache location
uv pip install --cache-dir /tmp/uv-cache <package>
# Via environment variable
UV_CACHE_DIR=/tmp/uv-cache uv pip install <package>
```
**When to use:**
- CI with custom cache storage
- Testing cache behavior
- Shared team cache
## Common Troubleshooting Workflows
### Workflow 1: Resolve Build Failure
```bash
# 1. Identify if UV-specific
uv venv -p 3.13 --seed
source .venv/bin/activate
pip install --use-pep517 --no-cache --force-reinstall 'package==version'
# 2. If pip fails too, install build dependencies
apt install build-essential # Ubuntu/Debian
# or
brew install gcc # macOS
# 3. Try again with UV
uv pip install <package>
# 4. If still fails, disable build isolation
uv pip install pip setuptools
uv pip install --no-build-isolation-package <package> <package>
```
### Workflow 2: Fix Stale Cache
```bash
# 1. Clean cache for specific package
uv cache clean <package>
# 2. Force refresh
uv pip install --refresh <package>
# 3. If still issues, clean all cache
uv cache clean
# 4. Reinstall
uv pip install --reinstall <package>
```
### Workflow 3: Debug Tool Installation
```bash
# 1. Uninstall old version
uv tool uninstall <package>
# 2. Clean build artifacts in source
cd /path/to/source
rm -rf build/ dist/ *.egg-info
# 3. Fresh install
uv tool install --force .
# 4. Verify installation
which <command>
<command> --version
```
### Workflow 4: Test Production Build
```bash
# 1. Create clean environment
uv venv test-env
source test-env/bin/activate # or `test-env\Scripts\activate` on Windows
# 2. Install with no cache
uv pip install --no-cache --reinstall <package>
# 3. Test functionality
python -c "import <package>; print(<package>.__version__)"
# 4. Deactivate and cleanup
deactivate
rm -rf test-env
```
## Official Documentation Links
- **Cache Concepts:** https://docs.astral.sh/uv/concepts/cache/
- **Build Failures:** https://docs.astral.sh/uv/reference/troubleshooting/build-failures/
- **CLI Reference:** https://docs.astral.sh/uv/reference/cli/
- **Settings:** https://docs.astral.sh/uv/reference/settings/
## Exit Codes
```
0 - Success
1 - General error
2 - Command usage error
101 - Package not found
102 - Version conflict
```
## Environment Variables
```bash
UV_CACHE_DIR=/path/to/cache # Cache location
UV_NO_CACHE=1 # Disable cache
UV_PYTHON=3.13 # Default Python version
UV_INDEX_URL=https://pypi.org/simple # Package index
UV_EXTRA_INDEX_URL=https://... # Additional index
UV_NO_BUILD_ISOLATION=1 # Global build isolation disable
UV_BUILD_CONSTRAINT_DEPENDENCIES # Build dependency constraints
```
## Configuration File Priority
1. Command-line flags (highest priority)
2. Environment variables
3. `pyproject.toml` (`[tool.uv]` section)
4. `uv.toml` in project directory
5. Global config (`~/.config/uv/uv.toml`)
6. System defaults (lowest priority)
## Common Flag Combinations
**Fresh install, no cache:**
```bash
uv pip install --no-cache --reinstall <package>
```
**Debug with verbose output:**
```bash
uv pip install --verbose --debug <package>
```
**Force rebuild from source:**
```bash
uv pip install --no-binary :all: --reinstall <package>
```
**Install with custom constraints:**
```bash
uv pip install -c constraints.txt --refresh <package>
```
**Tool install with clean build:**
```bash
cd /path/to/source
rm -rf build/ dist/ *.egg-info
uv tool install --force .
```