Parent directory

git-auto-fetch.plugin.zsh

2250 bytes
 1# Default auto-fetch interval: 60 seconds
 2: ${GIT_AUTO_FETCH_INTERVAL:=60}
 3
 4# Necessary for the git-fetch-all function
 5zmodload zsh/datetime
 6zmodload -F zsh/stat b:zstat  # only zstat command, not stat command
 7
 8function git-fetch-all {
 9  (
10    # Get git root directory
11    if ! gitdir="$(command git rev-parse --git-dir 2>/dev/null)"; then
12      return 0
13    fi
14
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
18      return 0
19    fi
20
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
25      return 0
26    fi
27
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 --recurse-submodules=yes 2>/dev/null &>> "$gitdir/FETCH_LOG"
33  ) &|
34}
35
36function 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
39
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}"
44  else
45    command touch "$guard" && echo "${fg_bold[red]}disabled${reset_color}"
46  fi
47}
48
49# zle-line-init widget (don't redefine if already defined)
50(( ! ${+functions[_git-auto-fetch_zle-line-init]} )) || return 0
51
52case "$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() {
55      git-fetch-all
56    } ;;
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() {
60      git-fetch-all
61      zle _git-auto-fetch_orig_zle-line-init -- "$@"
62    } ;;
63esac
64
65zle -N zle-line-init _git-auto-fetch_zle-line-init