]> Sergey Matveev's repositories - zsh-autoenv.git/blob - autoenv.zsh
51ccca0eec3d1fae2a5393d0f9de9e97cb38d166
[zsh-autoenv.git] / autoenv.zsh
1 # Stolen from
2 # https://github.com/joshuaclayton/dotfiles/blob/master/zsh_profile.d/autoenv.zsh
3
4 export ENV_AUTHORIZATION_FILE=$HOME/.env_auth
5
6 _dotenv_hash_pair() {
7   local env_file=$1
8   env_shasum=$(shasum $env_file | cut -d' ' -f1)
9   echo "$env_file:$env_shasum"
10 }
11
12 _dotenv_authorized_env_file() {
13   local env_file=$1
14   local pair=$(_dotenv_hash_pair $env_file)
15   touch $ENV_AUTHORIZATION_FILE
16   \grep -Gq $pair $ENV_AUTHORIZATION_FILE
17 }
18
19 _dotenv_authorize() {
20   local env_file=$1
21   _dotenv_deauthorize $env_file
22   _dotenv_hash_pair $env_file >> $ENV_AUTHORIZATION_FILE
23 }
24
25 _dotenv_deauthorize() {
26   local env_file=$1
27   echo $(\grep -Gv $env_file $ENV_AUTHORIZATION_FILE) > $ENV_AUTHORIZATION_FILE
28 }
29
30 _dotenv_print_unauthorized_message() {
31   echo "Attempting to load unauthorized env: $1"
32   echo ""
33   echo "**********************************************"
34   echo ""
35   cat $1
36   echo ""
37   echo "**********************************************"
38   echo ""
39   echo "Would you like to authorize it? (y/n)"
40 }
41
42 # This function can be mocked in tests
43 _dotenv_read_answer() {
44   read answer
45 }
46
47 _dotenv_source_env() {
48   local env_file="$PWD/.env"
49
50   if [[ -f $env_file ]]
51   then
52     if _dotenv_authorized_env_file $env_file
53     then
54       source $env_file
55       return 0
56     fi
57
58     _dotenv_print_unauthorized_message $env_file
59
60     _dotenv_read_answer
61
62     if [[ $answer == 'y' ]]
63     then
64       _dotenv_authorize $env_file
65       source $env_file
66     fi
67   fi
68 }
69
70 chpwd_functions=($chpwd_functions _dotenv_source_env)