vercmp/vercmp.sh

70 lines
1.8 KiB
Bash
Executable File

#!/bin/sh
set -e
# if this is running on an interactive terminal (as opposed to in a script),
# and if tput is installed and knows some color codes...
if [ -t 1 ] && [ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]; then
_clr="$(tput sgr0)"
_red="$(tput setaf 1)"
fi
err() { echo "$_red[ERR]$_clr $@" >&2; exit 1; }
VERCMPROOT="$(dirname "$(readlink -f "$0")")"
[ "$1" ] || cat <<EOF
usage:
$(basename $0) [-f <format>] <comparison string>
$(basename $0) formats
comparison string:
"<version 1> <op> <version 2>"
op:
== equal
!= not equal
>= greater than or equal
<= less than or equal
> greater than
< less than
format:
the name of the format to use for parsing and comparing the versions.
see '$(basename $0) formats' for a list of formats.
(format scripts are kept in $VERCMPROOT/format)
EOF
[ -d "$VERCMPROOT/format" ] \
|| err "no format directory! install one. see makefile or README for details."
if [ "$1" = "formats" ]; then
ls $VERCMPROOT/format/*.sh | sed -e 's/.*\/\(.*\).sh/\1/'
exit 0
fi
[ "$1" = "-f" ] && { fmt="$2"; shift; shift; } || fmt="default"
# make $fmt available to version format scripts
export fmt
v1="$(echo "$1" | awk '{ print $1 }')"
op="$(echo "$1" | awk '{ print $2 }')"
v2="$(echo "$1" | awk '{ print $3 }')"
[ "$v2" ] || err "could not determine second version to use in comparison!"
[ -e "$VERCMPROOT/format/$fmt.sh" ] || err "unrecognized version format: $fmt"
. "$VERCMPROOT/format/$fmt.sh"
# 'comparever' returns =, <, or >
relation="$(comparever $v1 $v2)"
no() { echo "no" && exit 0; }
case $op in
'!=') [ "$relation" != "=" ] || no ;;
'=='|'='|'>'|'<'|'>='|'<=') [ "${op#*$relation}" != "${op}" ] || no ;;
*) err "unrecognized operator: $op" ;;
esac
echo "yes"