git-auto-fetch.plugin.zsh 2.0 KB

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