Skip to content

Instantly share code, notes, and snippets.

@donaldguy
Created May 28, 2024 00:26
Show Gist options
  • Save donaldguy/1a18aa3a639ced600f592ad327dcd2c2 to your computer and use it in GitHub Desktop.
Save donaldguy/1a18aa3a639ced600f592ad327dcd2c2 to your computer and use it in GitHub Desktop.
some pretty stupid roundabout bash
# cross-platform bash-3.2 compatible (thanks macos)
#
# examples:
#
# $ version_endpoints_compare "3.7.1" "<=4.3.1" "=4.3.4" ">=4.3.5" ">=4.4"
# <=4.3.1
# $ version_endpoints_compare "4.3.1" "<=4.3.1" "=4.3.4" ">=4.3.5" ">=4.4"
# <=4.3.1
# $ version_endpoints_compare "4.3.2" "<=4.3.1" "=4.3.4" ">=4.3.5" ">=4.4"
# other
# $ version_endpoints_compare "4.3.3" "<=4.3.1" "=4.3.4" ">=4.3.5" ">=4.4"
# other
# $ version_endpoints_compare "4.3.4" "<=4.3.1" "=4.3.4" ">=4.3.5" ">=4.4"
# =4.3.4
# $ version_endpoints_compare "4.3.5" "<=4.3.1" "=4.3.4" ">=4.3.5" ">=4.4"
# >=4.3.5
# $ version_endpoints_compare "4.3.7" "<=4.3.1" "=4.3.4" ">=4.3.5" ">=4.4"
# >=4.3.5
# $ version_endpoints_compare "4.4.0" "<=4.3.1" "=4.3.4" ">=4.3.5" ">=4.4"
# >=4.4
# $ version_endpoints_compare "5.2.1" "<=4.3.1" "=4.3.4" ">=4.3.5" ">=4.4"
# >=4.4
# >=4.4
# or without an equals condition:
# $ version_endpoints_compare "4.3.1" "<=4.3.1" ">=4.3.5" ">=4.4"
# "<=4.3.1"
# $ version_endpoints_compare "4.3.4" "<=4.3.1" ">=4.3.5" ">=4.4"
# other
# $ version_endpoints_compare "4.3.5" "<=4.3.1" ">=4.3.5" ">=4.4"
# >=4.3.5
#
#
# as currently written only supports one equals condtion
#
#
# Intended usage pattern is like
#
# case version_endpoints_compare "$version" "<=4.3.1" ">=4.3.5" ">=4.4" in
# <=4.3.1)
# .... ;;
# other) ... ;;
fail() {
echo -e "\e[31mFail:\e[m $*"
exit 1
}
version_endpoints_compare() {
local input_verson;
input_version="$1";
shift;
local input_line_included=""
local constraint_sort_lines=()
local constraints=()
for c in "$@"; do
if [[ "$c" =~ ^"<=" ]]; then
constraint_sort_lines+=("${c#<=*}C")
constraints+=("$c")
elif [[ "$c" =~ ^"=" ]]; then
constraint_sort_lines+=("${c#=*}A")
if [[ -z "$input_line_included" ]]; then
constraint_sort_lines+=("${input_version}B input_version")
constraints+=("other")
input_line_included="yes"
fi
constraints+=("$c")
elif [[ "$c" =~ ^">=" ]]; then
if [[ -z "$input_line_included" ]]; then
constraint_sort_lines+=("${input_version}B input_version")
constraints+=("other")
input_line_included="yes"
fi
constraint_sort_lines+=("${c#>=*}")
constraints+=("$c")
else
fail "Unrecognized constraint: '$c'. Should start with <=, =, or >=";
fi
done
line_after_sort=$(printf "%s\n" "${constraint_sort_lines[@]}" | sort --version-sort | \
grep --line-number "input_version" | cut -f1 -d: )
echo "${constraints[line_after_sort - 1]}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment