git-auto-fetch.plugin.zsh 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. GIT_TERMINAL_PROMPT=0 \
  27. command git fetch --all 2>/dev/null &>> "$gitdir/FETCH_LOG"
  28. ) &|
  29. }
  30. function git-auto-fetch {
  31. # Do nothing if not in a git repository
  32. command git rev-parse --is-inside-work-tree &>/dev/null || return 0
  33. # Remove or create guard file depending on its existence
  34. local guard="$(command git rev-parse --git-dir)/NO_AUTO_FETCH"
  35. if [[ -f "$guard" ]]; then
  36. command rm "$guard" && echo "${fg_bold[green]}enabled${reset_color}"
  37. else
  38. command touch "$guard" && echo "${fg_bold[red]}disabled${reset_color}"
  39. fi
  40. }
  41. # zle-line-init widget (don't redefine if already defined)
  42. (( ! ${+functions[_git-auto-fetch_zle-line-init]} )) || return 0
  43. case "$widgets[zle-line-init]" in
  44. # Simply define the function if zle-line-init doesn't yet exist
  45. builtin|"") function _git-auto-fetch_zle-line-init() {
  46. git-fetch-all
  47. } ;;
  48. # Override the current zle-line-init widget, calling the old one
  49. user:*) zle -N _git-auto-fetch_orig_zle-line-init "${widgets[zle-line-init]#user:}"
  50. function _git-auto-fetch_zle-line-init() {
  51. git-fetch-all
  52. zle _git-auto-fetch_orig_zle-line-init -- "$@"
  53. } ;;
  54. esac
  55. zle -N zle-line-init _git-auto-fetch_zle-line-init