scripts: Compare apt/dpkg version numbers correctly

The termux_pkg_is_update_needed() function (exposed in the command-line
tool ./scripts/bin/apt-compare-versions) currently calls into python to
use the pkg_resources.parse_version() function.

This does not handle version numbers as apt/dpkg does - see
https://www.debian.org/doc/debian-policy/ch-controlfields.html#version,
so use dpkg --compare-versions for the version number comparison.

For instance, correct apt/dpkg behaviour is:
- '1-0' and '1' are the same version (the 'debian_revision' field)
- '1~rc1' is considered an earlier version than '1' (useful for being
   able to use release candidates)
- '1:1' is considered a later version than '2' (the epoch field, useful
   when upstream version numbering scheme changes).

This also exits with an error if a version cannot be parsed, and fixes
deprecation warnings when runing on later python versions (as
pkg_resources.parse_version() is going to be removed).
This commit is contained in:
Fredrik Fornwall 2023-10-03 13:58:48 +02:00
parent b69765c5a2
commit a93aeedba0
1 changed files with 10 additions and 14 deletions

View File

@ -1,4 +1,5 @@
#!/bin/bash
termux_pkg_is_update_needed() {
# USAGE: termux_pkg_is_update_needed <current-version> <latest-version>
if [[ -z "$1" ]] || [[ -z "$2" ]]; then
@ -10,21 +11,14 @@ termux_pkg_is_update_needed() {
# Compare versions.
# shellcheck disable=SC2091
if $(
cat <<-EOF | python3 -
import sys
from pkg_resources import parse_version
if parse_version("${CURRENT_VERSION}") < parse_version("${LATEST_VERSION}"):
sys.exit(0)
else:
sys.exit(1)
EOF
); then
dpkg --compare-versions "${CURRENT_VERSION}" lt "${LATEST_VERSION}"
DPKG_EXIT_CODE=$?
if [ "$DPKG_EXIT_CODE" = 0 ]; then
return 0 # true. Update needed.
elif [ "$DPKG_EXIT_CODE" = 1 ]; then
return 1 # false. Update not needed.
fi
return 1 # false. Update not needed.
termux_error_exit "Bad 'dpkg --compare-versions' exit code: $DPKG_EXIT_CODE - bad version numbers?"
}
# Make it also usable as command line tool. `scripts/bin/apt-compare-versions` is symlinked to this file.
@ -58,8 +52,10 @@ if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
else
if termux_pkg_is_update_needed "${first_version}" "${second_version}"; then
echo "${first_version} < ${second_version}"
else
elif termux_pkg_is_update_needed "${second_version}" "${first_version}"; then
echo "${first_version} > ${second_version}"
else
echo "${first_version} = ${second_version}"
fi
fi
fi