git-auto-fetch.plugin.zsh 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Default auto-fetch interval: 60 seconds
  2. : ${GIT_AUTO_FETCH_INTERVAL:=60}
  3. # Necessary for the git-fetch-all function
  4. zmodload zsh/datetime zsh/stat
  5. function git-fetch-all {
  6. (
  7. # Get git root directory
  8. if ! gitdir="$(command git rev-parse --git-dir 2>/dev/null)"; then
  9. return 0
  10. fi
  11. # Do nothing if auto-fetch is disabled or don't have permissions
  12. if [[ ! -w "$gitdir" || -f "$gitdir/NO_AUTO_FETCH" ]] ||
  13. [[ -f "$gitdir/FETCH_LOG" && ! -w "$gitdir/FETCH_LOG" ]]; then
  14. return 0
  15. fi
  16. # Get time (seconds) when auto-fetch was last run
  17. lastrun="$(zstat +mtime "$gitdir/FETCH_LOG" 2>/dev/null || echo 0)"
  18. # Do nothing if not enough time has passed since last auto-fetch
  19. if (( EPOCHSECONDS - lastrun < $GIT_AUTO_FETCH_INTERVAL )); then
  20. return 0
  21. fi
  22. # Fetch all remotes (avoid ssh passphrase prompt)
  23. date -R &>! "$gitdir/FETCH_LOG"
  24. GIT_SSH_COMMAND="command ssh -o BatchMode=yes" \
  25. command git fetch --all 2>/dev/null &>> "$gitdir/FETCH_LOG"
  26. ) &|
  27. }
  28. function git-auto-fetch {
  29. # Do nothing if not in a git repository
  30. command git rev-parse --is-inside-work-tree &>/dev/null || return 0
  31. # Remove or create guard file depending on its existence
  32. local guard="$(command git rev-parse --git-dir)/NO_AUTO_FETCH"
  33. if [[ -f "$guard" ]]; then
  34. command rm "$guard" && echo "${fg_bold[green]}enabled${reset_color}"
  35. else
  36. command touch "$guard" && echo "${fg_bold[red]}disabled${reset_color}"
  37. fi
  38. }
  39. # zle-line-init widget (don't redefine if already defined)
  40. (( ! ${+functions[_git-auto-fetch_zle-line-init]} )) || return 0
  41. case "$widgets[zle-line-init]" in
  42. # Simply define the function if zle-line-init doesn't yet exist
  43. builtin|"") function _git-auto-fetch_zle-line-init() {
  44. git-fetch-all
  45. } ;;
  46. # Override the current zle-line-init widget, calling the old one
  47. user:*) zle -N _git-auto-fetch_orig_zle-line-init "${widgets[zle-line-init]#user:}"
  48. function _git-auto-fetch_zle-line-init() {
  49. git-fetch-all
  50. zle _git-auto-fetch_orig_zle-line-init -- "$@"
  51. } ;;
  52. esac
  53. zle -N zle-line-init _git-auto-fetch_zle-line-init