dotenv.plugin.zsh 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. ## Functions
  7. source_env() {
  8. if [[ -f $ZSH_DOTENV_FILE ]]; then
  9. if [[ "$ZSH_DOTENV_PROMPT" != false ]]; then
  10. local confirmation dirpath="${PWD:A}"
  11. # make sure there is an allowed file
  12. touch "$ZSH_DOTENV_ALLOWED_LIST"
  13. # check if current directory's .env file is allowed or ask for confirmation
  14. if ! grep -q "$dirpath" "$ZSH_DOTENV_ALLOWED_LIST" &>/dev/null; then
  15. # print same-line prompt and output newline character if necessary
  16. echo -n "dotenv: found '$ZSH_DOTENV_FILE' file. Source it? ([Y]es/[n]o/[a]lways) "
  17. read -k 1 confirmation; [[ "$confirmation" != $'\n' ]] && echo
  18. # check input
  19. case "$confirmation" in
  20. [nN]) return ;;
  21. [aA]) echo "$dirpath" >> "$ZSH_DOTENV_ALLOWED_LIST" ;;
  22. *) ;; # interpret anything else as a yes
  23. esac
  24. fi
  25. fi
  26. # test .env syntax
  27. zsh -fn $ZSH_DOTENV_FILE || echo "dotenv: error when sourcing '$ZSH_DOTENV_FILE' file" >&2
  28. setopt localoptions allexport
  29. source $ZSH_DOTENV_FILE
  30. fi
  31. }
  32. autoload -U add-zsh-hook
  33. add-zsh-hook chpwd source_env
  34. source_env