dotenv.plugin.zsh 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. ## Settings
  2. # Filename of the dotenv file to look for
  3. : ${ZSH_DOTENV_FILE:=.env}
  4. # Path to the file containing allowed paths
  5. : ${ZSH_DOTENV_ALLOWED_LIST:="${ZSH_CACHE_DIR:-$ZSH/cache}/dotenv-allowed.list"}
  6. : ${ZSH_DOTENV_DISALLOWED_LIST:="${ZSH_CACHE_DIR:-$ZSH/cache}/dotenv-disallowed.list"}
  7. ## Functions
  8. source_env() {
  9. if [[ -f $ZSH_DOTENV_FILE ]]; then
  10. if [[ "$ZSH_DOTENV_PROMPT" != false ]]; then
  11. local confirmation dirpath="${PWD:A}"
  12. # make sure there is an (dis-)allowed file
  13. touch "$ZSH_DOTENV_ALLOWED_LIST"
  14. touch "$ZSH_DOTENV_DISALLOWED_LIST"
  15. # early return if disallowed
  16. if grep -q "$dirpath" "$ZSH_DOTENV_DISALLOWED_LIST" &>/dev/null; then
  17. return;
  18. fi
  19. # check if current directory's .env file is allowed or ask for confirmation
  20. if ! grep -q "$dirpath" "$ZSH_DOTENV_ALLOWED_LIST" &>/dev/null; then
  21. # print same-line prompt and output newline character if necessary
  22. echo -n "dotenv: found '$ZSH_DOTENV_FILE' file. Source it? ([Y]es/[n]o/[a]lways/n[e]ver) "
  23. read -k 1 confirmation; [[ "$confirmation" != $'\n' ]] && echo
  24. # check input
  25. case "$confirmation" in
  26. [nN]) return ;;
  27. [aA]) echo "$dirpath" >> "$ZSH_DOTENV_ALLOWED_LIST" ;;
  28. [eE]) echo "$dirpath" >> "$ZSH_DOTENV_DISALLOWED_LIST"; return ;;
  29. *) ;; # interpret anything else as a yes
  30. esac
  31. fi
  32. fi
  33. # test .env syntax
  34. zsh -fn $ZSH_DOTENV_FILE || echo "dotenv: error when sourcing '$ZSH_DOTENV_FILE' file" >&2
  35. setopt localoptions allexport
  36. source $ZSH_DOTENV_FILE
  37. fi
  38. }
  39. autoload -U add-zsh-hook
  40. add-zsh-hook chpwd source_env
  41. source_env