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 # Name of file to look for when entering directories.
8 : ${DOTENV_FILE_ENTER:=.env}
10 # Name of file to look for when leaving directories.
11 # Requires DOTENV_HANDLE_LEAVE=1.
12 : ${DOTENV_FILE_LEAVE:=.env.leave}
14 # Look for .env in parent dirs?
15 : ${DOTENV_LOOK_UPWARDS:=0}
17 # Handle leave events when changing away from a subtree, where an "enter"
19 : ${DOTENV_HANDLE_LEAVE:=1}
22 # Internal: stack of entered (and handled) directories.
23 _dotenv_stack_entered=()
28 env_shasum=$(shasum $env_file | cut -d' ' -f1)
29 echo "$env_file:$env_shasum"
32 _dotenv_authorized_env_file() {
34 local pair=$(_dotenv_hash_pair $env_file)
35 test -f $ENV_AUTHORIZATION_FILE \
36 && \grep -qF $pair $ENV_AUTHORIZATION_FILE
41 _dotenv_deauthorize $env_file
42 _dotenv_hash_pair $env_file >> $ENV_AUTHORIZATION_FILE
45 _dotenv_deauthorize() {
47 if [[ -f $ENV_AUTHORIZATION_FILE ]]; then
48 echo $(\grep -vF $env_file $ENV_AUTHORIZATION_FILE) > $ENV_AUTHORIZATION_FILE
52 # This function can be mocked in tests
53 _dotenv_read_answer() {
59 _dotenv_check_authorized_env_file() {
60 if ! [[ -f $1 ]]; then
63 if ! _dotenv_authorized_env_file $1; then
64 echo "Attempting to load unauthorized env file: $1"
66 echo "**********************************************"
70 echo "**********************************************"
72 echo -n "Would you like to authorize it? [y/N] "
74 local answer=$(_dotenv_read_answer)
76 if [[ $answer != 'y' ]]; then
94 unset _dotenv_event _dotenv_cwd
97 _dotenv_chpwd_handler() {
98 local env_file="$PWD/$DOTENV_FILE_ENTER"
100 # Handle leave event for previously sourced env files.
101 if [[ $DOTENV_HANDLE_LEAVE == 1 ]] && (( $#_dotenv_stack_entered )); then
102 for prev_dir in ${_dotenv_stack_entered}; do
103 if ! [[ ${PWD}/ == ${prev_dir}/* ]]; then
104 local env_file_leave=$prev_dir/$DOTENV_FILE_LEAVE
105 if _dotenv_check_authorized_env_file $env_file_leave; then
106 _dotenv_source $env_file_leave leave
108 # Remove this entry from the stack.
109 _dotenv_stack_entered=(${_dotenv_stack_entered#$prev_dir})
114 if ! [[ -f $env_file ]] && [[ $DOTENV_LOOK_UPWARDS == 1 ]]; then
115 setopt localoptions extendedglob
117 m=((../)#${DOTENV_FILE_ENTER}(N))
119 env_file=${${m[1]}:A}
125 if ! _dotenv_check_authorized_env_file $env_file; then
129 # Load the env file only once.
130 if (( ${+_dotenv_stack_entered[(r)${env_file:A:h}]} )); then
134 _dotenv_stack_entered+=(${env_file:A:h})
136 _dotenv_source $env_file enter
139 autoload -U add-zsh-hook
140 add-zsh-hook chpwd _dotenv_chpwd_handler
142 # Look in current directory already.
143 _dotenv_chpwd_handler