Skip to content

Instantly share code, notes, and snippets.

@rexagod
Last active June 19, 2024 20:02
Show Gist options
  • Save rexagod/e6425d6795bc99a55ffcfece224664e6 to your computer and use it in GitHub Desktop.
Save rexagod/e6425d6795bc99a55ffcfece224664e6 to your computer and use it in GitHub Desktop.
Go-compliant version generator for any module (local or otherwise).
#!/bin/bash
# This script returns the resolved `go.mod`-compliant version of a module, as found in `go get <module>@<ref>`.
# Usage: [HOST_URI|REPOSITORY_OWNER] $0 -p [REPOSITORY] -f [REF]
# * different platform: [HOST_URI] $0
# * different owner: [REPOSITORY_OWNER] $0
# * different repository: $0 -p [REPOSITORY]
# * different ref: $0 -f [REF]
# All arguments are optional.
# Optional: Bind this to `git mod-version` after dropping this script in your $PATH, i.e., in your `~/.gitconfig`:
# [alias]
# mod-version = !which mod-version.sh && mod-version.sh
set -exo pipefail
if [[ "$1" != "-p" ]] && [[ "$1" != "-f" ]] && [[ "$#" != 0 ]]; then
echo "Usage: [HOST_URI|REPOSITORY_OWNER] $0 [-p repository] [-f ref]" >&2
exit 1
fi
REPOSITORY_OWNER="${REPOSITORY_OWNER:-$(whoami)}"
DEFAULT_HOST_URI="github.com/$REPOSITORY_OWNER"
HOST_URI=${HOST_URI:-$DEFAULT_HOST_URI}
DEFAULT_REPOSITORY=$(pwd | sed 's/.*\///')
REPOSITORY=$DEFAULT_REPOSITORY
DEFAULT_REF="HEAD"
REF=$DEFAULT_REF
repository="$DEFAULT_REPOSITORY"
ref="$DEFAULT_REF"
while getopts "p:f:" opt; do
case $opt in
p)
repository=$OPTARG
;;
f)
ref=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
echo "Usage: [HOST_URI|REPOSITORY_OWNER] $0 [-p repository] [-f ref]" >&2
exit 1
;;
esac
done
did_cd=false
if [[ "$HOST_URI" != "$DEFAULT_HOST_URI" ]] || [[ "$repository" != "$DEFAULT_REPOSITORY" ]]; then
REPOSITORY="$repository"
rm -rf "/tmp/$REPOSITORY"
git clone "https://$HOST_URI/$REPOSITORY" "/tmp/$REPOSITORY"
cd "/tmp/$REPOSITORY"
did_cd=true
fi
REF=$(git rev-parse "$ref")
if [[ "$did_cd" == "true" ]]; then
cd - || exit
fi
MODULE="$HOST_URI/$REPOSITORY@${REF:0:12}"
go list -m -json "$MODULE" | jq ".Version" | tr -d \"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment