config/shared/home/gg.sh

50 lines
1.2 KiB
Bash
Raw Normal View History

2024-04-12 14:57:54 +03:00
# shellcheck shell=bash
_GG_MAXDEPTH=5
2024-04-12 14:02:28 +03:00
gg() {
2024-04-12 14:57:54 +03:00
local _gopath
_gopath=$(git rev-parse --show-toplevel)
local paths=($(g "$@"))
local path_index=0
2024-04-12 14:02:28 +03:00
if [ ${#paths[@]} -gt 1 ]; then
2024-04-12 14:57:54 +03:00
local c=1
2024-04-12 14:02:28 +03:00
for path in "${paths[@]}"; do
2024-04-12 14:57:54 +03:00
echo "[$c]: cd ${_gopath}/${path}"
2024-04-12 14:02:28 +03:00
c=$((c+1))
done
echo -n "Go to which path: "
2024-04-12 14:57:54 +03:00
read -r path_index
2024-04-12 14:02:28 +03:00
2024-04-12 14:57:54 +03:00
path_index=$((path_index-1))
2024-04-12 14:02:28 +03:00
fi
2024-04-12 14:57:54 +03:00
local path=${paths[$path_index]}
cd "$_gopath/$path" || {
>&2 echo "?"
exit 1
}
2024-04-12 14:02:28 +03:00
}
#
# Print the directories of the specified Go package name.
#
g() {
2024-04-12 14:57:54 +03:00
local pkg_candidates
pkg_candidates="$( (cd "$_gopath" && find . -mindepth 1 -maxdepth ${_GG_MAXDEPTH} -type d -path "*/$1" -and -not -path '*/vendor/*' -print) | sed 's/^\.\///g')"
2024-04-12 14:02:28 +03:00
echo "$pkg_candidates" | awk '{print length, $0 }' | sort -n | awk '{print $2}'
}
#
# Bash autocomplete for g and gg functions.
#
_g_complete()
{
COMPREPLY=()
local cur
cur="${COMP_WORDS[COMP_CWORD]}"
2024-04-12 14:57:54 +03:00
COMPREPLY=( $(compgen -W "$(for f in $(find "$_gopath" -mindepth 1 -maxdepth ${_GG_MAXDEPTH} -type d -name "${cur}*" ! -name '.*' ! -path '*/.git/*' ! -path '*/test/*' ! -path '*/vendor/*'); do echo "${f##*/}"; done)" -- "$cur") )
2024-04-12 14:02:28 +03:00
return 0
}
complete -F _g_complete g
complete -F _g_complete gg