dotenv.plugin.zsh 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 -Fx -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 -Fx -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 || {
  44. echo "dotenv: error when sourcing '$ZSH_DOTENV_FILE' file" >&2
  45. return 1
  46. }
  47. setopt localoptions allexport
  48. source $ZSH_DOTENV_FILE
  49. }
  50. autoload -U add-zsh-hook
  51. add-zsh-hook chpwd source_env
  52. source_env