Auto activate Conda with direnv

2024-03-25 (Updated 2024-03-25)

Conda sucks

Yeah, but I have to use it, and this articles explains how to auto activate Conda with direnv.

I know what you're thinking, but conda activate <environment> in .envrc doesn't work

Setup direnv

Paste the following into your .config/direnv/direnvrc

this is from direnv GitHub wiki

layout_anaconda() {
 local ACTIVATE="${HOME}/anaconda3/bin/activate"

 if [ -n "$1" ]; then
  # Explicit environment name from layout command.
  local env_name="$1"
  source $ACTIVATE ${env_name}
 elif (grep -q name: environment.yml); then
  # Detect environment name from `environment.yml` file in `.envrc` directory
  source $ACTIVATE $(grep name: environment.yml | sed -e 's/name: //' | cut -d "'" -f 2 | cut -d '"' -f 2)
 else
  (>&2 echo No environment specified)
  exit 1
 fi
}

Conda zsh init script

Copy this into ~/.zconda (or whatever you want to name it)

# >>> conda initialize >>>
__conda_setup="$('/<home>/anaconda3/bin/conda' 'shell.zsh' 'hook' 2>/dev/null)"
if [ $? -eq 0 ]; then
 eval "$__conda_setup"
else
 if [ -f "/<home>/anaconda3/etc/profile.d/conda.sh" ]; then
  . "/<home>/anaconda3/etc/profile.d/conda.sh"
 else
  export PATH="/<home>/anaconda3/bin:$PATH"
 fi
fi
unset __conda_setup
# <<< conda initialize <<<

This is from Conda install script

then source it in your .zshrc or .zlogin

I have this as my .zlogin:

export LANG=en_US.UTF-8
unset LANGUAGE

export EDITOR=nvim

source ~/.zconda

zinit light conda-incubator/conda-zsh-completion

export WORDCHARS=''

Set up in your project's .direnv

Run direnv edit ., and paste these into your editor

source ~/.zconda
layout anaconda <env>

The first line is not necessary, only needed if you run in tmux.