Skip to content

Instantly share code, notes, and snippets.

@robbwagoner
Last active July 21, 2017 23:53
Show Gist options
  • Save robbwagoner/a22c2a81afef34719959 to your computer and use it in GitHub Desktop.
Save robbwagoner/a22c2a81afef34719959 to your computer and use it in GitHub Desktop.
Git date and SHA from local repo
#!/usr/bin/env bash
#
# Display Git metadata useful for other scripts
#
# ------------------------------------
# Convert UNIX timestamp (seconds since epoch UTC) to YYYY-MM-DDTHH:MM:SSZ
# ------------------------------------
function unix_to_iso() {
declare ts=${1}
declare formatOutput="+%FT%TZ"
case $(uname -s) in
( Darwin )
TZ=UTC date -j -f "%s" $ts $formatOutput
;;
( Linux )
TZ=UTC date -d @$ts $formatOutput
;;
esac
}
# ------------------------------------
# Get the most recently updated branch
# ------------------------------------
latest_branch() {
ref=$(git for-each-ref \
--count=1 \
--sort='-committerdate' \
--format='%(refname:short)' \
'**')
echo ${ref#*/} # strip origin/ off
}
# ------------------------------------
# Get the most recently created tag
# ------------------------------------
latest_tag() {
{
# annotated tags
git for-each-ref \
--count=1 \
--sort='-taggerdate' \
--format='%(taggerdate:raw) %(refname:short)' \
'refs/tags' ;
# lightweight tags
git for-each-ref \
--count=1 \
--sort='-committerdate' \
--format='%(committerdate:raw) %(refname:short)' \
'refs/tags' ;
} | sort -n |tail -1 |awk '{ print $3 }'
}
# ------------------------------------
# Get the git metadata for the current project
# ------------------------------------
declare -a versionSplit=( $(TZ=UTC git log -n 1 --pretty="%ct %h %H") )
versionDate=$(unix_to_iso ${versionSplit[0]})
versionSHA=${versionSplit[1]}
versionSHALong=${versionSplit[2]}
cat <<EOF
BRANCH=$(git rev-parse --abbrev-ref HEAD)
COMMIT_DATE=$versionDate
SHA_SHORT=$versionSHA
SHA=$versionSHALong
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment