Skip to content

Instantly share code, notes, and snippets.

@allex
Last active May 18, 2022 11:51
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 allex/91ea3983be9ef1aa64bf00b246df0b0b to your computer and use it in GitHub Desktop.
Save allex/91ea3983be9ef1aa64bf00b246df0b0b to your computer and use it in GitHub Desktop.
git-rev
#!/bin/bash
set -euE
# Similar as `npm version`, bump version by git tags or custom version file
#
# by @allex_wang <https://iallex.com> | MIT
#
# Usage:
#
# git-rev
# -r, --release <patch | minor | major | from-git>
# --bump-file <*.json, .version> bump file for retrieve reference version
#
# GistID: 91ea3983be9ef1aa64bf00b246df0b0b
# GistURL: https://gist.github.com/allex/91ea3983be9ef1aa64bf00b246df0b0b
PROG=$(basename "$0")
SH_DIR="$(cd -P -- "$(dirname -- "$(readlink "$0")")" && pwd -P)"
bump_file=""
bump_git=false
with_sha1=false
newversion="patch"
args=( )
while [ $# -gt 0 ]; do
case "$1" in
-r | --release)
# patch, minor, major
newversion=${2:-patch}
shift
;;
--bump-git)
bump_git=true
;;
--bump-file)
bump_file=$2
shift
;;
--with-sha1)
with_sha1=true
;;
-h | --help)
cat <<-EOF
Usage:
$PROG -r [<newversion> | major | minor | patch | from-git]
EOF
;;
-*)
;;
*)
args+=("$1")
;;
esac
shift
done
[ ${#args[@]} -gt 0 ] && eval set -- "${args[@]}"
# check $1 greater than $2
is_gt_ver () {
printf '%s\n%s\n' "$2" "$1" | sort -V -C
}
get_newversion () {
newversion="$1"
if [[ "$newversion" =~ ^[0-9]+(.[0-9]+)*.[0-9x]+ ]]; then
echo "$newversion"
return
fi
if ! ([ "$newversion" = "from-git" ] || $bump_git) && [ -f "${bump_file}" ]; then
if [ "${bump_file##*.}" = "json" ]; then
version=$(awk -F'"' '/"version": ".+"/{print $4;exit;}' "$bump_file") || exit $?
else
version=$(head -n 1 "$bump_file" | cut -d " " -f 1) || exit $?
fi
else
version=$(git describe --tags HEAD 2>/dev/null | awk '{sub(/-[0-9]+-g.{7,}/,"");print}') || exit $?
fi
echo "${version:-0.0.0}" | awk -vflg="$newversion" '{
if (match($0,/\.[0-9]+$/)) {
l = split($0, arr, /\./);
if (l>=3) {
n=l;
dic["patch"]=0;
dic["minor"]=1;
dic["major"]=2;
n=l-dic[flg];
n=n<0?l:n;
for (i=1;i<=l;i++) {
if (i==n) arr[i]+=1; else if (i>n) arr[i]=0;
result=i==1?arr[i]:result"."arr[i];
}
print result;
exit;
}
}
print $0;
}'
}
tag=$(get_newversion "$newversion")
if $with_sha1; then
ref=$(git rev-parse "${1:-HEAD}")
sha1=$(git log -1 --pretty="%h" "$ref") # short sha1
tag=$tag-$sha1
fi
echo "$tag"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment