2 # https://github.com/joshuaclayton/dotfiles/blob/master/zsh_profile.d/autoenv.zsh
4 # TODO: move this to DOTENV_*?!
5 export ENV_AUTHORIZATION_FILE=$HOME/.env_auth
7 : ${DOTENV_FILE_ENTER:=.env}
8 : ${DOTENV_FILE_LEAVE:=.env.leave}
10 # Look for .env in parent dirs?
11 : ${DOTENV_LOOK_UPWARDS:=0}
13 # Handle leave events, when leaving ?
14 : ${DOTENV_HANDLE_LEAVE:=1}
19 env_shasum=$(shasum $env_file | cut -d' ' -f1)
20 echo "$env_file:$env_shasum"
23 _dotenv_authorized_env_file() {
25 local pair=$(_dotenv_hash_pair $env_file)
26 touch $ENV_AUTHORIZATION_FILE
27 \grep -Gq $pair $ENV_AUTHORIZATION_FILE
32 _dotenv_deauthorize $env_file
33 _dotenv_hash_pair $env_file >> $ENV_AUTHORIZATION_FILE
36 _dotenv_deauthorize() {
38 echo $(\grep -Gv $env_file $ENV_AUTHORIZATION_FILE) > $ENV_AUTHORIZATION_FILE
41 _dotenv_print_unauthorized_message() {
42 echo "Attempting to load unauthorized env file: $1"
44 echo "**********************************************"
48 echo "**********************************************"
50 echo -n "Would you like to authorize it? [y/N] "
53 # This function can be mocked in tests
54 _dotenv_read_answer() {
60 _dotenv_check_authorized_env_file() {
61 if ! _dotenv_authorized_env_file $1; then
62 _dotenv_print_unauthorized_message $1
64 local answer=$(_dotenv_read_answer)
66 if [[ $answer != 'y' ]]; then
75 _dotenv_stack_entered=()
77 _dotenv_chpwd_handler() {
78 local env_file="$PWD/$DOTENV_FILE_ENTER"
80 # Handle leave event for previously sourced env files.
81 if [[ $DOTENV_HANDLE_LEAVE == 1 ]] && (( $#_dotenv_stack_entered )); then
82 for prev_dir in ${_dotenv_stack_entered}; do
83 if ! [[ ${PWD}/ == ${prev_dir}/* ]]; then
84 local env_file_leave=$prev_dir/$DOTENV_FILE_LEAVE
85 if _dotenv_check_authorized_env_file $env_file_leave; then
87 source $env_file_leave
90 # Remove this entry from the stack.
91 _dotenv_stack_entered=(${_dotenv_stack_entered#$prev_dir})
96 if ! [[ -f $env_file ]] && [[ $DOTENV_LOOK_UPWARDS == 1 ]]; then
97 setopt localoptions extendedglob
99 m=((../)#${DOTENV_FILE_ENTER}(N))
105 if ! [[ -f $env_file ]]; then
109 if ! _dotenv_check_authorized_env_file $env_file; then
113 # Load the env file only once.
114 if (( ${+_dotenv_stack_entered[(r)${env_file:A:h}]} )); then
118 _dotenv_stack_entered+=(${env_file:A:h})
125 autoload -U add-zsh-hook
126 add-zsh-hook chpwd _dotenv_chpwd_handler
128 # Look in current directory already.
129 _dotenv_chpwd_handler