Created
September 10, 2019 08:44
-
-
Save squio/e51a10360ce72b0b5cc7d8895df14ce8 to your computer and use it in GitHub Desktop.
Parse a semantic version string to a 32 bit integer and reverse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# NOTE this works only with bash, not dash | |
# Based on: | |
# https://gist.github.com/dislick/914e67444f8f71df3900bd77ccec6091 | |
# NOTE: first digit is MSB contrary to the Javascript version linked above. | |
# This does not work for non-numerical strings but this should be easy to remedy | |
# https://semver.org/#semantic-versioning-specification-semver | |
# Semantic Version string to numerical version | |
semver2num() { | |
IN="$1" | |
C=2 | |
NUMVER=0 | |
while IFS='.' read -ra ADDR; do | |
for i in "${ADDR[@]}"; do | |
N=$(($i<<10*$C)) | |
let NUMVER=$NUMVER+$N | |
let C=$C-1 | |
if [ $C -eq -1 ]; then | |
break; | |
fi | |
done | |
done <<< "$IN" | |
echo $NUMVER | |
} | |
# Numerical version to Semabtic Version string | |
num2semver() { | |
NUMVER=$1 | |
S2=$(($NUMVER & 1023)) | |
S1=$(($NUMVER >>10 & 1023)) | |
S0=$(($NUMVER >>20 & 1023)) | |
echo "$S0.$S1.$S2" | |
} | |
VSTRING="3.2.4" | |
echo Original version string: $VSTRING | |
NUMERICAL=$(semver2num "$VSTRING") | |
echo Numerical version: $NUMERICAL | |
SEMVER=$(num2semver $NUMERICAL) | |
echo Semver: $SEMVER |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment