Skip to content

Instantly share code, notes, and snippets.

@carmanchris31
Last active September 22, 2023 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carmanchris31/133a9ba4699bf068e6170c59b8d6f281 to your computer and use it in GitHub Desktop.
Save carmanchris31/133a9ba4699bf068e6170c59b8d6f281 to your computer and use it in GitHub Desktop.
Update go version on cd (OSX, bash@3, zsh, gimme)
gimme_after_cd() {
debug_log() {
test "$DEBUG" = "1" && echo "[debug] $1"
}
find_go_mod() {
dir=$PWD
while [ "$dir" != "/" ]; do
if [ -f "$dir/go.mod" ]; then
echo "$dir/go.mod"
return
else
dir=$(dirname "$dir")
fi
done
echo
}
resolve_version() {
version="$1"
if [[ "$version" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
major=$(echo "$version" | cut -d '.' -f 1)
minor=$(echo "$version" | cut -d '.' -f 2);minor=${minor:=x}
patch=$(echo "$version" | cut -d '.' -f 3);patch=${patch:=x}
version="$major.$minor.$patch"
fi
gimme --resolve "$version" | head -1
}
debug_log "checking for gimme"
if command -v gimme >/dev/null; then
debug_log "gimme found!"
else
echo "[error] Please install gimme to install go versions (see https://github.com/travis-ci/gimme#installation--usage)"
return
fi
debug_log "searching for go.mod"
GO_MOD_FILE=$(find_go_mod)
if [ -n "$GO_MOD_FILE" ]; then
debug_log "go.mod found: $GO_MOD_FILE"
FOUND=$(sed -En 's/^go[[:space:]]+([[:digit:].]+)$/\1/p' $GO_MOD_FILE)
WANT=$(resolve_version "$FOUND")
debug_log "extracted go version: $FOUND ($WANT)"
else
debug_log "go.mod not found"
WANT=$(resolve_version stable)
debug_log "defaulting to stable ($WANT)"
fi
debug_log "checking current go version"
if command -v go >/dev/null; then
GOT=$(resolve_version $(go version | cut -d " " -f 3 | cut -c 3-))
debug_log "go version is $GOT"
else
debug_log "go not found"
GOT="none"
fi
if [ "$WANT" = "$GOT" ]; then
debug_log "versions match; nothing to do"
else
debug_log "updating to go $WANT from $GOT"
echo -n "Using " && eval "$(gimme $WANT)"
fi
}
gimme_after_cd
add-zsh-hook chpwd gimme_after_cd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment