I wanted to put the current git hash in my prompt; but my initial approach was kind of laggy:
psvar="$(git log -n1 --pretty='format: %h' 2>/dev/null)"
(with $PROMPT
including %1v
to make that visible)
I tried the vcs_info
plugin, but that was also laggy. So I've ended up writing my own function:
function githead() {
local commondir ref hash _
local gitdir="${1:a}"
until [[ -e "$gitdir/.git" ]]; do
local updir="${gitdir%/*}"
[[ "$updir" == "$gitdir" ]] && return 1
gitdir="$updir"
done
gitdir="$gitdir/.git"
[[ -f "$gitdir" ]] && read _ gitdir < "$gitdir"
read _ ref < "$gitdir/HEAD"
local commondir="$gitdir/commondir"
[[ -e "$commondir" ]] && gitdir="$gitdir/$(<$commondir)"
ref="$gitdir/$ref"
read hash <"$ref"
print -r "${hash::12}"
return 0
}
It's certainly faster, but that's _bound_ to be brittle. In particular, a couple of the files I have to read look like they _could_ contain more than one line of content, and not necessarily put the line I want at the top.
Is there a fast way of getting the current hash from git, which is more robust than what I've written by hand?
Asked by sh1
(113 rep)
Mar 7, 2025, 06:19 AM
Last activity: Mar 12, 2025, 04:51 AM
Last activity: Mar 12, 2025, 04:51 AM