Skip to content

Instantly share code, notes, and snippets.

@RhetTbull
Last active July 16, 2025 14:15
Show Gist options
  • Save RhetTbull/28e96ebe9453188588ef039e8768c164 to your computer and use it in GitHub Desktop.
Save RhetTbull/28e96ebe9453188588ef039e8768c164 to your computer and use it in GitHub Desktop.
Automatically create Python venv with uv and configure direnv
#!/usr/bin/env bash
# venv.sh - Initialize a uv-based venv for a Python repo with direnv integration
set -e
# Remove .python-version if it exists
if [ -f ".python-version" ]; then
echo "🧹 Removing existing .python-version"
rm .python-version
fi
# Create venv using uv if it doesn't exist
if [ -d ".venv" ]; then
echo "βœ… .venv already exists. Skipping venv creation."
else
echo "🐍 Creating virtual environment using uv..."
uv venv
fi
# Create .envrc for direnv if it doesn't exist or if content is incorrect
if [ -f ".envrc" ]; then
if grep -Fxq "source .venv/bin/activate" .envrc; then
echo "βœ… .envrc already configured for direnv."
else
echo "πŸ”§ Updating .envrc for direnv autoload"
echo "source .venv/bin/activate" > .envrc
fi
else
echo "πŸ”§ Creating .envrc for direnv autoload"
echo "source .venv/bin/activate" > .envrc
fi
# Allow direnv
echo "βœ… Allowing direnv to load .envrc"
direnv allow
# Download Python .gitignore from GitHub if it doesn't exist
gitignore_created=false
if [ -f ".gitignore" ]; then
echo "βœ… .gitignore already exists. Skipping download."
else
echo "πŸ“₯ Downloading Python .gitignore from GitHub..."
curl -s https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore -o .gitignore
if [ $? -eq 0 ]; then
echo "βœ… Python .gitignore downloaded successfully"
gitignore_created=true
else
echo "⚠️ Failed to download .gitignore, continuing without it"
fi
fi
# Add .envrc to .gitignore if it's not already there
gitignore_changed=false
if [ -f ".gitignore" ]; then
if ! grep -Fxq ".envrc" .gitignore; then
echo "πŸ”§ Adding .envrc to .gitignore"
echo ".envrc" >> .gitignore
gitignore_changed=true
else
echo "βœ… .envrc already in .gitignore"
fi
fi
# Initialize git if not already initialized
if [ ! -d ".git" ]; then
echo "πŸ”§ Initializing git repository"
git init
fi
# Commit .gitignore changes if it was modified or created
if [ "$gitignore_created" = true ] || [ "$gitignore_changed" = true ]; then
if [ -f ".gitignore" ]; then
echo "πŸ“ Committing .gitignore changes"
git add .gitignore
if [ "$gitignore_created" = true ] && [ "$gitignore_changed" = true ]; then
git commit -m "Add Python .gitignore from GitHub and include .envrc"
elif [ "$gitignore_created" = true ]; then
git commit -m "Add Python .gitignore from GitHub"
else
git commit -m "Add .envrc to .gitignore"
fi
fi
fi
echo "πŸŽ‰ Virtual environment and direnv configuration complete!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment