#!/usr/bin/sh # goupgrade # You need go installed and GOBIN needs to be in PATH. set -eu goup_local () { local go_cmd bin_dir sdk_dir installed latest current go_cmd="${1-go}" bin_dir="$($go_cmd env GOBIN)" bin_dir="${bin_dir:-"$($go_cmd env GOPATH)/bin"}" sdk_dir=~/sdk installed="$(echo "$bin_dir"/go1.* | xargs basename -a | sort -Vr)" latest="$(echo "$installed" | head -n1)" current="$(readlink "$(command -v go)")" env -i GOUP_LINK_NAME="$go_cmd" \ GOUP_INSTALLED="'$installed'" \ GOUP_LATEST="$latest" \ GOUP_CURRENT="$current" \ GOUP_BIN_DIR="$bin_dir" \ GOUP_SDK_DIR="$sdk_dir" } goup_latest_avail () { local cmd if command -v curl >/dev/null then cmd='curl -s' elif command -v wget >/dev/null then cmd='wget -q -O -' else echo 'curl or wget is not installed!' >&2 exit 1 fi $cmd 'https://go.dev/VERSION?m=text' | head -n1 } goup_install () { local version="$1" go install golang.org/dl/"$version"@latest "$GOUP_BIN_DIR/$version" download } goup_uninstall () { local version="$1" if [ "$GOUP_CURRENT" = "$version" ] then echo "can't unistall current version" && exit 1 fi rm -rf "${GOUP_SDK_DIR:?}/$version" rm "$GOUP_BIN_DIR/$version" } goup_set () { local version="$1" if ! echo "$GOUP_INSTALLED" | grep -Fq "$version" then echo "$version not installed"; exit 1 fi if [ "$GOUP_CURRENT" = "$version" ] then exit fi read -p "set $GOUP_LINK_NAME to version $version? [y/N] " -r bool if [ "$bool" != y ] then exit 1 fi ln -fs "$version" "$GOUP_BIN_DIR/$GOUP_LINK_NAME" "$GOUP_LINK_NAME" download ln -fs "$("$GOUP_LINK_NAME" env GOROOT)/bin/gofmt" "$GOUP_BIN_DIR/gofmt" } linkname=go while getopts l: arg do case $arg in (l) linkname="$OPTARG";; (?) exit 2;; esac done shift $((OPTIND - 1)) case ${1-} in (g|get) eval "$(goup_local "$linkname")"; echo "$GOUP_CURRENT";; (c|check) eval "$(goup_local "$linkname")"; [ "$(goup_latest_avail)" = "$GOUP_LATEST" ]; exit $?;; (l|list) eval "$(goup_local "$linkname")"; echo "$GOUP_INSTALLED";; (s|set) eval "$(goup_local "$linkname")"; : "${2:?You need to set a version!}"; if [ "$2" = latest ]; then goup_set "$GOUP_LATEST"; else goup_set "$2"; fi;; (i|install) eval "$(goup_local "$linkname")"; goup_install "${2:?You need to set a version!}";; (d|delete) eval "$(goup_local "$linkname")"; goup_uninstall "${2:?You need to set a version!}";; (u|upgrade) latest="$(goup_latest_avail)"; $0 -l "$linkname" i "$latest" && $0 s "$latest";; (h|help) cat <