Skip to content

Instantly share code, notes, and snippets.

@dberstein
Last active October 24, 2018 07:26
Show Gist options
  • Save dberstein/3e1f0fea899e9d7c4b7c99f5e0267fc1 to your computer and use it in GitHub Desktop.
Save dberstein/3e1f0fea899e9d7c4b7c99f5e0267fc1 to your computer and use it in GitHub Desktop.
Shell semver component bump (1 line function)
# SemVer bump small shell/python function: bumps component $1 ("major", "minor" or "patch") from version in $2 (or STDIN).
# Version components to the right of the bump rollback to 0, ie. 1.2.3:1.2.4 or 1.2.3:1.3.0 or 1.2.3:2.0.0.
function bump() {
echo ${2:-$(</dev/stdin)} | python -c 'from sys import argv,stdin,stdout;n={"major":0,"minor":1,"patch":2}.get(argv[-1]);v=list(map(int,stdin.read().strip().split(".")));v[n]=v[n]+1;v[n+1:]=[0]*len(v[n+1:]);stdout.write(".".join(map(str,v))+"\n")' $1
}
## Examples
# # Version as parameter
# $ bump minor 1.0.1
# 1.1.0
# # Version from STDIN
# $ echo 1.0.1 | bump minor
# 1.1.0
# # Parameter has priority over STDIN
# $ echo 4.4.4 | bump patch 1.1.1
# 1.1.2
# # Bump in sequence
# $ echo 1.1.1 | bump patch | bump patch
# 1.1.3
# Loop example
# $ VERSION="$(($RANDOM%4)).$(($RANDOM%5)).$(($RANDOM%6))" && MAJOR_EVERY=7 && MINOR_EVERY=5 && \
# echo "Start version: $VERSION, dump minor every ${MINOR_EVERY}, major every ${MAJOR_EVERY}" && \
# for i in $(seq 1 20); do
# BUMP=patch
# [ $((${i}%${MINOR_EVERY})) -eq 0 ] && BUMP=minor
# [ $((${i}%${MAJOR_EVERY})) -eq 0 ] && BUMP=major
# echo -n "${VERSION} ${BUMP} bump = "
# VERSION=$(echo ${VERSION} | bump ${BUMP})
# echo ${VERSION}
# done | cat -b
# Start version: 1.0.1, dump minor every 5, major every 7
# 1 1.0.1 patch bump = 1.0.2
# 2 1.0.2 patch bump = 1.0.3
# 3 1.0.3 patch bump = 1.0.4
# 4 1.0.4 patch bump = 1.0.5
# 5 1.0.5 minor bump = 1.1.0
# 6 1.1.0 patch bump = 1.1.1
# 7 1.1.1 major bump = 2.0.0
# 8 2.0.0 patch bump = 2.0.1
# 9 2.0.1 patch bump = 2.0.2
# 10 2.0.2 minor bump = 2.1.0
# 11 2.1.0 patch bump = 2.1.1
# 12 2.1.1 patch bump = 2.1.2
# 13 2.1.2 patch bump = 2.1.3
# 14 2.1.3 major bump = 3.0.0
# 15 3.0.0 minor bump = 3.1.0
# 16 3.1.0 patch bump = 3.1.1
# 17 3.1.1 patch bump = 3.1.2
# 18 3.1.2 patch bump = 3.1.3
# 19 3.1.3 patch bump = 3.1.4
# 20 3.1.4 minor bump = 3.2.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment