diff --git a/autoenv.zsh b/autoenv.zsh index 313378b..265482b 100644 --- a/autoenv.zsh +++ b/autoenv.zsh @@ -1,19 +1,28 @@ -# Stolen from +# Initially based on # https://github.com/joshuaclayton/dotfiles/blob/master/zsh_profile.d/autoenv.zsh # TODO: move this to DOTENV_*?! export ENV_AUTHORIZATION_FILE=$HOME/.env_auth +# Name of file to look for when entering directories. : ${DOTENV_FILE_ENTER:=.env} + +# Name of file to look for when leaving directories. +# Requires DOTENV_HANDLE_LEAVE=1. : ${DOTENV_FILE_LEAVE:=.env.leave} # Look for .env in parent dirs? : ${DOTENV_LOOK_UPWARDS:=0} -# Handle leave events, when leaving ? +# Handle leave events when changing away from a subtree, where an "enter" +# event was handled? : ${DOTENV_HANDLE_LEAVE:=1} +# Internal: stack of entered (and handled) directories. +_dotenv_stack_entered=() + + _dotenv_hash_pair() { local env_file=$1 env_shasum=$(shasum $env_file | cut -d' ' -f1) @@ -23,8 +32,8 @@ _dotenv_hash_pair() { _dotenv_authorized_env_file() { local env_file=$1 local pair=$(_dotenv_hash_pair $env_file) - touch $ENV_AUTHORIZATION_FILE - \grep -Gq $pair $ENV_AUTHORIZATION_FILE + test -f $ENV_AUTHORIZATION_FILE \ + && \grep -qF $pair $ENV_AUTHORIZATION_FILE } _dotenv_authorize() { @@ -35,19 +44,9 @@ _dotenv_authorize() { _dotenv_deauthorize() { local env_file=$1 - echo $(\grep -Gv $env_file $ENV_AUTHORIZATION_FILE) > $ENV_AUTHORIZATION_FILE -} - -_dotenv_print_unauthorized_message() { - echo "Attempting to load unauthorized env file: $1" - echo "" - echo "**********************************************" - echo "" - cat $1 - echo "" - echo "**********************************************" - echo "" - echo -n "Would you like to authorize it? [y/N] " + if [[ -f $ENV_AUTHORIZATION_FILE ]]; then + echo $(\grep -vF $env_file $ENV_AUTHORIZATION_FILE) > $ENV_AUTHORIZATION_FILE + fi } # This function can be mocked in tests @@ -59,7 +58,15 @@ _dotenv_read_answer() { _dotenv_check_authorized_env_file() { if ! _dotenv_authorized_env_file $1; then - _dotenv_print_unauthorized_message $1 + echo "Attempting to load unauthorized env file: $1" + echo "" + echo "**********************************************" + echo "" + cat $1 + echo "" + echo "**********************************************" + echo "" + echo -n "Would you like to authorize it? [y/N] " local answer=$(_dotenv_read_answer) echo @@ -72,8 +79,6 @@ _dotenv_check_authorized_env_file() { return 0 } -_dotenv_stack_entered=() - _dotenv_chpwd_handler() { local env_file="$PWD/$DOTENV_FILE_ENTER" @@ -98,15 +103,13 @@ _dotenv_chpwd_handler() { local m m=((../)#${DOTENV_FILE_ENTER}(N)) if (( $#m )); then - env_file=$m[1] + env_file=${${m[1]}:A} + else + return fi fi - if ! [[ -f $env_file ]]; then - return - fi - - if ! _dotenv_check_authorized_env_file $env_file; then + if ! [[ -f $env_file ]] || ! _dotenv_check_authorized_env_file $env_file; then return fi