perf(git): cache the git version used for alias selection (#14068)

Co-authored-by: Carlo Sala <carlosalag@protonmail.com>
This commit is contained in:
Robby RussellandCarlo Sala authored and GitHub committed 2026-12-03 14:24:03 +01:00
1 parent 3d55d66d8b
commit ab9cf2989f
2 files changed
+120 -1

No files matched your search

+29 -1
View File
@@ -1,6 +1,34 @@
# Git version checking
autoload -Uz is-at-least
git_version="${${(As: :)$(git version 2>/dev/null)}[3]}"
# Running `git version` forks on every startup, so cache the result for a day
# in $ZSH_CACHE_DIR, keyed on the resolved git binary's path and mtime.
# Run the fallback outside this function so its locals cannot shadow wrapper variables.
() {
# Shell overrides and relative PATH entries can make the command hash
# differ from the Git that Zsh actually runs.
(( $+functions[git] || $+aliases[git] || $+galiases[git] || ${path[(I)(|[^/]*)]} )) && return 1
local cache="$ZSH_CACHE_DIR/git-version" git_path="${commands[git]:+${commands[git]:A}}" key magic
local -a stat lines
# Shims and the macOS developer-tool dispatcher can select a different Git.
[[ "${git_path:t:r}" = 'git' ]] || return 1
[[ "$OSTYPE" == darwin* && "$git_path" = /usr/bin/git ]] && return 1
read -r -k 2 -u 0 magic 2>/dev/null < "$git_path" || return 1
[[ "$magic" = '#!' ]] && return 1
zmodload -F zsh/stat b:zstat && zstat -A stat +mtime -- "$git_path" 2>/dev/null || return 1
key="$git_path $stat[1]"
lines=("$cache"(Nm-1))
(( $#lines )) && lines=("${(@f)$(<"$cache")}")
if [[ "$lines[1]" = "$key" && "$lines[2]" == <->.<->* ]]; then
git_version="$lines[2]"
return 0
fi
git_version="${${(As: :)$(git version 2>/dev/null)}[3]}"
[[ ! -w "$ZSH_CACHE_DIR" ]] || print -rl -- "$key" "$git_version" >| "$cache"
return 0
} || git_version="${${(As: :)$(git version 2>/dev/null)}[3]}"
#
# Functions Current