git-auto-fetch.plugin.zsh 2.1 KB

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