Skip to content

Instantly share code, notes, and snippets.

@RobertAudi
Last active August 29, 2015 14:05
Show Gist options
  • Save RobertAudi/9bea0709bf349d39c8ca to your computer and use it in GitHub Desktop.
Save RobertAudi/9bea0709bf349d39c8ca to your computer and use it in GitHub Desktop.
My take on directory-specific environments on the command-line
#!/usr/bin/env zsh
#
# USAGE: autoenv [action]
#
# Actions:
# up (aliased to u)
# down (aliased to d)
#
error() { echo "$@" 1>&2 }
init() {
unset -f autoenv-up autoenv-down > /dev/null 2>&1
local red_color="\e[31m"
local green_color="\e[32m"
local yellow_color="\e[33m"
local no_color="\e[0m"
if (( $# > 1 )); then
error "${red_color}ERROR: Too many arguments!${no_color}"
return 1
fi
local autoenv_action="up"
[[ -n "$1" ]] && autoenv_action="$1"
if [[ ! -f ".env" ]]; then
error "${red_color}ERROR: Could not find .env file!${no_color}"
return 1
fi
source .env > /dev/null 2>&1
if ! type autoenv-up > /dev/null 2>&1; then
error "${red_color}ERROR: Invalid syntax in the .env file!${no_color}"
error "${yellow_color}The .env file must define \`autoenv-up\` and \`autoenv-down\` functions!${no_color}"
return 1
fi
case "$autoenv_action" in
u|up)
autoenv-up
echo "${green_color}SUCCESS: autoenv up!${no_color}"
;;
d|down)
autoenv-down
echo "${green_color}SUCCESS: autoenv down!${no_color}"
;;
*)
error "${red_color}ERROR: Invalid autoenv action: ${1}${no_color}"
return 1
esac
unset -f autoenv-up autoenv-down > /dev/null 2>&1
}
init $@
# Example `cd` wrapper
cd() {
local directory
if (( $# -eq 0 )); then
directory="$HOME"
elif [[ "$1" == "-" ]]; then
directory="$OLDPWD"
else
directory="$1"
fi
if [[ -f $directory ]]; then
echo "$fg[red]$directory is a file!$reset_color"
return 1
fi
directory="$(realpath $directory)"
if [[ "$(pwd)" != "$directory" && ! "$(pwd)" =~ "$directory" ]]; then
autoenv down > /dev/null 2>&1
fi
builtin cd $directory > /dev/null
autoenv up 2> /dev/null || true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment