Skip to content

Commit

Permalink
Improve loadenv prototype
Browse files Browse the repository at this point in the history
  • Loading branch information
iainelder committed Jun 23, 2023
1 parent 27983ef commit fa13da0
Showing 1 changed file with 30 additions and 5 deletions.
35 changes: 30 additions & 5 deletions scripts/profile/loadenv.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,51 @@ mkdir --parents "$ENVDIR"
function .env {
declare name="${1}"

bash --init-file <(cat \
~/.bashrc \
<(direnv stdlib) \
"$ENVDIR/$name" \
<(cat <<< "export PS1='($name) $PS1'") \
envdir="$(dirname "$(realpath "$ENVDIR/$name")")"

# Start a subshell as the simplest way to unload variables at the end.
# `init-file` runs commands before going interactive.
#
# 1. Load bashrc because `init-file` overrides the normal load sequence.
# 2. Add env name to shell prompt as Python's virtualenv does.
# 3. Move into the envdir so that commands like `pwd` work in the .envrc
# 4. Load direnv stdlib because .envrc files may use it.
# 5. Load the .envrc without using direnv to use it in any directory.
# 6. Move back so that when Bash goes interactive I'm in the same place.
#
#
bash --init-file <(
cat \
~/.bashrc \
<(cat <<< "export PS1='($name) $PS1'") \
<(cat <<< "pushd '$envdir' > /dev/null") \
<(direnv stdlib) \
"$ENVDIR/$name" \
<(cat <<< "popd > /dev/null") \
)
}

# Register a new .envrc or update an existing one. Prompts to confirm update.
function lnenv {
declare name="${1}"

ln -s -i -T "$(pwd)/.envrc" "$ENVDIR/$name"
}

# Unregister an .envrc.
function rmenv {
declare name="${1}"

rm "$ENVDIR/$name"
}

# Lists registered .envrc files.
function lsenv {
find "$ENVDIR" -mindepth 1 -maxdepth 1 -printf "%f -> %l\n"
}

# I discovered similar tools after writing this. The magic words to search on
# Google for were `bash environment switcher`.

# https://github.com/smarie/env-switcher-gui
# https://github.com/robdmc/switchenv

0 comments on commit fa13da0

Please sign in to comment.