dotenv.plugin.zsh 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. return
  11. fi
  12. if [[ "$ZSH_DOTENV_PROMPT" != false ]]; then
  13. local confirmation dirpath="${PWD:A}"
  14. # make sure there is an (dis-)allowed file
  15. touch "$ZSH_DOTENV_ALLOWED_LIST"
  16. touch "$ZSH_DOTENV_DISALLOWED_LIST"
  17. # early return if disallowed
  18. if command grep -q "$dirpath" "$ZSH_DOTENV_DISALLOWED_LIST" &>/dev/null; then
  19. return
  20. fi
  21. # check if current directory's .env file is allowed or ask for confirmation
  22. if ! command grep -q "$dirpath" "$ZSH_DOTENV_ALLOWED_LIST" &>/dev/null; then
  23. # get cursor column and print new line before prompt if not at line beginning
  24. local column
  25. echo -ne "\e[6n" > /dev/tty
  26. read -t 1 -s -d R column < /dev/tty
  27. column="${column##*\[*;}"
  28. [[ $column -eq 1 ]] || echo
  29. # print same-line prompt and output newline character if necessary
  30. echo -n "dotenv: found '$ZSH_DOTENV_FILE' file. Source it? ([Y]es/[n]o/[a]lways/n[e]ver) "
  31. read -k 1 confirmation
  32. [[ "$confirmation" = $'\n' ]] || echo
  33. # check input
  34. case "$confirmation" in
  35. [nN]) return ;;
  36. [aA]) echo "$dirpath" >> "$ZSH_DOTENV_ALLOWED_LIST" ;;
  37. [eE]) echo "$dirpath" >> "$ZSH_DOTENV_DISALLOWED_LIST"; return ;;
  38. *) ;; # interpret anything else as a yes
  39. esac
  40. fi
  41. fi
  42. # test .env syntax
  43. zsh -fn $ZSH_DOTENV_FILE || echo "dotenv: error when sourcing '$ZSH_DOTENV_FILE' file" >&2
  44. setopt localoptions allexport
  45. source $ZSH_DOTENV_FILE
  46. }
  47. autoload -U add-zsh-hook
  48. add-zsh-hook chpwd source_env
  49. source_env