Skip to content

Instantly share code, notes, and snippets.

@sghael
Last active June 19, 2025 17:46
Show Gist options
  • Save sghael/efa0dae3ec007c32c79827b413d73acb to your computer and use it in GitHub Desktop.
Save sghael/efa0dae3ec007c32c79827b413d73acb to your computer and use it in GitHub Desktop.
.envrc to automatically activate conda environment when entering directory
# Setup conda environment from env.yml or environment.yml
setup_conda_env() {
# Find environment file
local env_file
if [ -f "environment.yml" ]; then
env_file="environment.yml"
elif [ -f "env.yml" ]; then
env_file="env.yml"
else
echo "Error: No environment.yml or env.yml file found"
return 1
fi
# Extract environment name
local env_name=$(grep '^name:' "$env_file" | sed 's/name:[[:space:]]*//')
if [ -z "$env_name" ]; then
echo "Error: Could not extract environment name from $env_file"
return 1
fi
# Prepare timestamp tracking & ensure .direnv exists
local timestamp_file=".direnv/last_env_update"
mkdir -p .direnv
# Check if environment already exists (robust detection)
if ! mamba env list | awk '{print $1}' | grep -qx "$env_name"; then
# Create environment only if it doesn't exist
echo "Creating new environment '$env_name'..."
mamba env create -f "$env_file" -y
# Mark env as up-to-date so we don't immediately run `env update`
touch "$timestamp_file"
fi
# Update only if environment file has changed
if [ ! -f "$timestamp_file" ] || [ "$env_file" -nt "$timestamp_file" ]; then
echo "Updating environment from $env_file..."
mamba env update -n "$env_name" -f "$env_file" --prune
touch "$timestamp_file"
fi
# Activate the environment
eval "$(mamba shell hook --shell bash)"
mamba activate "$env_name"
echo "Environment '$env_name' activated"
}
# Run the setup
setup_conda_env
# Set project-specific environment variables
export PROJECT_ROOT=$(pwd)
export PYTHONPATH="$PROJECT_ROOT:$PROJECT_ROOT/src:$PYTHONPATH"
# Load .env file if it exists
if [ -f .env ]; then
set -a
source .env
set +a
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment