Skip to content

Instantly share code, notes, and snippets.

@Nimamoh
Last active January 7, 2021 17:52
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 Nimamoh/26cdc99b71a5a160460863370a2bbd20 to your computer and use it in GitHub Desktop.
Save Nimamoh/26cdc99b71a5a160460863370a2bbd20 to your computer and use it in GitHub Desktop.
Take a semantic version string and outputs potential docker tags
#!/bin/sh
# GPL-3.0-or-later
#
# Usage: semver-to-docker-labels.sh SEMANTIC_VERSION_STRING
#
# Print possible docker labels for a semantic version string.
# For semantic version with no pre-release or build number. It will output:
#
# major
# major.minor
# major.minor.patch
#
# For other format, it will output the semantic version string as is.
#
main() {
#
# The regex is the official one from Semantic Versioning 2.0.0
# https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
#
semver=$(trim_string "$1")
regex="^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$"
if ! echo "$semver" | grep -P "$regex" > /dev/null;
then
>&2 echo "$semver is not a valid semantic versionning string"
exit 1
fi
case $semver in
*+*)
>&2 echo "$semver is a valid semantic versionning but docker labels doesn't support buildmetadata."
exit 1
;;
*-*)
echo "$semver"
exit 0
;;
esac
i=0
semver=$(split "$semver" "." | tr '\n' ' ')
for part in $semver; do
case $i in
0) major=$part ;;
1) minor=$part ;;
2) patch=$part ;;
esac
i=$((i+1))
done
echo "$major"
echo "$major.$minor"
echo "$major.$minor.$patch"
}
split() {
set -f
old_ifs=$IFS
IFS=$2
# shellcheck disable=2086
set -- $1
printf '%s\n' "$@"
IFS=$old_ifs
set +f
}
trim_string() {
trim=${1#${1%%[![:space:]]*}}
trim=${trim%${trim##*[![:space:]]}}
printf '%s\n' "$trim"
}
main "$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment