Skip to content

Instantly share code, notes, and snippets.

@leophys
Last active August 28, 2023 05:16
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leophys/05ea3bbaf3b7a69c21de8678e4bb7fe9 to your computer and use it in GitHub Desktop.
Save leophys/05ea3bbaf3b7a69c21de8678e4bb7fe9 to your computer and use it in GitHub Desktop.
Optionally colored and fuzzy findable godoc
### colored and fuzzy go doc
if which bat > /dev/null; then
function _godoc() {
if echo $1|grep -q -E "^([a-zA-Z0-9/]+)$"; then
go doc ${@} | bat -p -l md
elif echo $1|grep -q -E "^[a-zA-Z0-9/]+\.[a-zA-Z0-9.]+$"; then
go doc ${@} | bat -p -l go
elif echo $1|grep -q -E "^([a-zA-Z0-9/._-]+)/.*\.[a-zA-Z0-9.]+$"; then
go doc ${@} | bat -p -l go
else
go doc ${@} | bat -p -l md
fi
}
else
function _godoc() {
go doc ${@}
}
fi
function gomodroot() {
. <(go env|grep -E "^GOMOD")
echo ${GOMOD%%go.mod}
unset GOMOD
}
function _godocbuildcache() {
local VERSION="$(go version|awk '{print $3}')"
local DOCCACHE="${GODOC_CACHE:-${HOME}/.cache/godoc}/${VERSION}"
if [ -d ${DOCCACHE} ]; then
return 0
fi
echo "generating stdlib godoc cache, wait some time" 1>&2
mkdir -p ${DOCCACHE}
for DEP in $(go list std|grep -v -E "internal/"); do
go doc -short ${DEP}|sed -e 's/^\ *\(func\|type\|const\|var\)\ \([a-zA-Z0-9]\+\).*/\2/'|xargs -I {} echo ${DEP}.{} 2>/dev/null >> ${DOCCACHE}/stdlib.symbols
done
echo "done generating stdlib godoc cache" 1>&2
}
function _godocenum() {
_godocbuildcache
local VERSION="$(go version|awk '{print $3}')"
local DOCCACHE="${GODOC_CACHE:-${HOME}/.cache/godoc}/${VERSION}"
cat ${DOCCACHE}/stdlib.symbols
for DEP in $(go list -f '{{ join .Deps "\n" }}' $(gomodroot)/...); do
for SYM in $(go doc -short ${DEP}|sed -e 's/^\ *\(func\|type\|const\|var\)\ \([a-zA-Z0-9]\+\).*/\2/'); do
echo ${DEP}.${SYM}
done
done
}
function godoc() {
if [ $# -eq 0 ]; then
if which bat > /dev/null; then
OBJ=$(_godocenum|fzf --height=80% --info=inline --reverse --border --margin=1 --padding=1 --preview="go doc {1}|bat --color always -p -l go")
else
OBJ=$(_godocenum|fzf --height=80% --info=inline --reverse --border --margin=1 --padding=1 --preview="go doc {1}")
fi
_godoc ${OBJ}
else
_godoc ${@}
fi
}
# vim: set ft=zsh et sw=0 ts=2 sts=0:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment