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