From a989e7fbdc05b8753c256cfa688a69cb5d38555d Mon Sep 17 00:00:00 2001 From: Alexandre <44178713+alexbelgium@users.noreply.github.com> Date: Sat, 1 Aug 2026 18:51:14 +0200 Subject: [PATCH] feat(addons_updater): write Home Assistant compliant addon versions (#2925) * feat(addons_updater): write Home Assistant compliant addon versions The updater copied the raw upstream tag into config.yaml. Home Assistant orders addon versions with awesomeversion and hides the update when it can compare both versions and the new one is not strictly newer, so tags such as 1.2.3-2, 1.2.3+4 or 1.2.3-2026-08-01 silently stopped the update from being offered, and tags such as version-bf9e0b4f or ubuntu-2026-06-01 cannot be ordered at all. The addon version is now derived from the upstream tag by ha_version.py, using the same library Home Assistant uses: a sortable and newer tag is kept as it is, 1.2.3-4 and 1.2.3+4 become 1.2.3.4, otherwise the release number inside the tag, an incremented addon number or the date is used. updater.json keeps the raw upstream tag, so the same upstream release is never published twice. Co-Authored-By: Claude Opus 5 * fix(addons_updater): address review comments - calendar versions carrying a counter now advance to the current date instead of only incrementing the counter - --selftest runs against a fixed date, so it keeps passing after today - config.json is written from a validated jq result, as updater.json is - README states the raw tag is added to the changelog only when it differs from the addon version - docstring, comment and changelog formatting Co-Authored-By: Claude Opus 5 * feat(addons_updater): turn pre-release markers into a version section "5.0.0b5" is published as "5.0.0.5" so the beta number keeps ordering the addon instead of relying on how awesomeversion reads the marker. Co-Authored-By: Claude Opus 5 * feat(addons_updater): keep every number of an unorderable tag "v26.2-ls256" is published as "v26.2.256", "nightly-2.6.1.5509-ls8" as "2.6.1.5509.8" and "4.16-r0-ls94" as "4.16.0.94", so the build number keeps ordering the addon instead of being dropped. Words holding no number, architectures and commit hashes are left out, and a section ending on a year is counted up rather than incremented. Co-Authored-By: Claude Opus 5 * style(addons_updater): keep the helper docstrings on one line Codacy runs pydocstyle with D213, which the multi-line summary added with the numbers rule trips. Co-Authored-By: Claude Opus 5 * fix(addons_updater): leave out more arch words and unreal dates "i686" and friends were read as the number 686, and "2026.02.31" was taken for a calendar version. Both now fall back to the plain number rules. Co-Authored-By: Claude Opus 5 --------- Co-authored-by: Claude Opus 5 --- addons_updater/CHANGELOG.md | 7 + addons_updater/Dockerfile | 5 + addons_updater/README.md | 16 + addons_updater/config.yaml | 2 +- .../rootfs/etc/cont-init.d/99-run.sh | 115 ++++-- addons_updater/rootfs/usr/bin/ha_version.py | 334 ++++++++++++++++++ 6 files changed, 454 insertions(+), 25 deletions(-) create mode 100644 addons_updater/rootfs/usr/bin/ha_version.py diff --git a/addons_updater/CHANGELOG.md b/addons_updater/CHANGELOG.md index 6a56fec8aa..fef2b11e53 100644 --- a/addons_updater/CHANGELOG.md +++ b/addons_updater/CHANGELOG.md @@ -1,3 +1,10 @@ +## 2026.08 (2026-08-01) + +- Addon versions written in config.yaml now always comply with Home Assistant versioning: an upstream tag Home Assistant cannot order (`version-bf9e0b4f`, `ubuntu-2026-06-01`, ...) or would sort as older (`1.2.3-2`, `1.2.3+4`) no longer lands in config.yaml. The addon number is incremented instead, while the raw upstream tag stays in updater.json so the same release is never published twice +- Pre-release markers become a version section, `5.0.0b5` is published as `5.0.0.5` +- A tag Home Assistant cannot order keeps every number it carries, `v26.2-ls256` is published as `v26.2.256` +- Upstream tags are escaped before being replaced in Dockerfile/build files + ## 2026.06 (05-06-2026) - Minor bugs fixed ## 2026.05 (30-05-2026) diff --git a/addons_updater/Dockerfile b/addons_updater/Dockerfile index 2ad6221eea..b802304398 100644 --- a/addons_updater/Dockerfile +++ b/addons_updater/Dockerfile @@ -56,6 +56,11 @@ ENV PACKAGES="" COPY ha_autoapps.sh /ha_autoapps.sh RUN chmod 744 /ha_autoapps.sh && /ha_autoapps.sh "$PACKAGES" && rm /ha_autoapps.sh +# Library used by Home Assistant to order addon versions, so that the version +# published by the updater is one Home Assistant offers as an update. Keep the +# pin aligned with the Supervisor requirements.txt +RUN pip install --no-cache-dir awesomeversion==25.8.0 + ################ # 4 Entrypoint # ################ diff --git a/addons_updater/README.md b/addons_updater/README.md index 9a116ab5d2..33c004b330 100644 --- a/addons_updater/README.md +++ b/addons_updater/README.md @@ -73,6 +73,22 @@ You can add the following tags in the file : - dockerhub_by_date: in dockerhub, uses the last_update date instead of the version - dockerhub_list_size: in dockerhub, how many containers to consider for latest version +### Addon version numbering + +The `version` written in the addon `config.yaml` is the one Home Assistant compares to decide whether an update is available. Home Assistant hides the update when it can order both versions and the new one is not strictly newer (`1.2.3` -> `1.2.3-2` is a semver pre-release, so it is *older*), and it cannot order tags such as `version-bf9e0b4f` or `ubuntu-2026-06-01` at all. + +The addon version is therefore derived from the upstream tag: + +- a tag Home Assistant can order and that is newer is used as it is +- `1.2.3-4` and `1.2.3+4` become `1.2.3.4` +- a pre-release marker becomes a section of its own, so the number it carries keeps ordering the addon: `5.0.0b5` -> `5.0.0.5` +- a tag it cannot order keeps every number it carries, in order: `v26.2-ls256` -> `v26.2.256`, `nightly-2.6.1.5509-ls8` -> `2.6.1.5509.8`, `4.16-r0-ls94` -> `4.16.0.94`, `ubuntu-2026-07-28` -> `2026.07.28`. Words holding no number, an architecture, and anything else such as a commit hash are left out +- a tag holding no number at all (`version-bf9e0b4f`, `sts`) increments the current addon version (`1.37` -> `1.38`), or uses the date when there is nothing to increment (`2026.08.01`, then `2026.08.01.1` for a second update the same day) + +`updater.json` always keeps the raw upstream tag, so the next run still compares upstream with upstream and a single upstream release never triggers two addon updates. The raw tag is also kept in the Dockerfile and the build files, and is added to the changelog entry when it differs from the addon version. + +These rules are checked by `python3 /usr/bin/ha_version.py --selftest`, which can be run from a terminal in the addon container. + ### Addon configuration Here you define the values that will allow the addon to connect to your repository. diff --git a/addons_updater/config.yaml b/addons_updater/config.yaml index dd0bffcde1..de2e87d662 100644 --- a/addons_updater/config.yaml +++ b/addons_updater/config.yaml @@ -30,4 +30,4 @@ schema: slug: updater udev: true url: https://github.com/alexbelgium/hassio-addons/tree/master/addons_updater -version: "2026.06" +version: "2026.08" diff --git a/addons_updater/rootfs/etc/cont-init.d/99-run.sh b/addons_updater/rootfs/etc/cont-init.d/99-run.sh index be5607e3d2..4f9bc65942 100755 --- a/addons_updater/rootfs/etc/cont-init.d/99-run.sh +++ b/addons_updater/rootfs/etc/cont-init.d/99-run.sh @@ -20,6 +20,29 @@ else DATE_FORMAT="+%d-%m-%Y" fi +# Version published in the addon configuration, which is the one Home +# Assistant compares; the upstream tag lives in updater.json instead +function config_version() { + local folder="$1" + if [ -f "$folder/config.json" ]; then + jq -r '.version // empty' "$folder/config.json" + elif [ -f "$folder/config.yaml" ]; then + sed -n 's/^version:[[:space:]]*//p' "$folder/config.yaml" \ + | head -n 1 \ + | sed -e 's/[[:space:]]*#.*$//' -e 's/^"//' -e 's/"$//' \ + | sed -e "s/^'//" -e "s/'$//" + fi +} + +# Escape a version so that sed treats it as plain text on both sides +function sed_pattern() { + printf '%s' "$1" | sed -e 's/[]\/$*.^[]/\\&/g' +} + +function sed_replacement() { + printf '%s' "$1" | sed -e 's/[\/&]/\\&/g' +} + #Defining github value LOGINFO="... github authentification" && if [ "$VERBOSE" = true ]; then bashio::log.info "$LOGINFO"; fi @@ -315,10 +338,6 @@ for f in */; do # Add brackets LASTVERSION='"'${LASTVERSION}'"' - # Avoid characters incompatible with HomeAssistant version name - LASTVERSION2=${LASTVERSION//+/-} - CURRENT2=${CURRENT//+/-} - # Skip if current or last version is empty (would corrupt files by replacing all "" occurrences) if [ "${CURRENT}" = '""' ] || [ "${LASTVERSION}" = '""' ]; then bashio::log.warning "... $SLUG : skipping update due to empty version string (current=${CURRENT}, latest=${LASTVERSION})" @@ -326,43 +345,91 @@ for f in */; do fi # Update if needed - if [ "${CURRENT2}" != "${LASTVERSION2}" ]; then + if [ "${CURRENT}" != "${LASTVERSION}" ]; then LOGINFO="... $SLUG : update from ${CURRENT} to ${LASTVERSION}" && if [ "$VERBOSE" = true ]; then bashio::log.info "$LOGINFO"; fi - #Change all instances of version + ADDONFOLDER="/data/${BASENAME}/${SLUG}" + + # Version currently published, before any file is touched + CONFIGVERSION="$(config_version "$ADDONFOLDER" || true)" + if [ -z "$CONFIGVERSION" ]; then + bashio::log.error "... $SLUG : no version found in the addon config, skipping" + continue + fi + + # Home Assistant hides an update when it can compare both + # versions and the new one is not strictly newer, and cannot + # order tags such as "version-bf9e0b4f" at all. The addon + # version is therefore derived from the upstream tag, which + # stays untouched in updater.json so that the same upstream + # release is never published twice + if ! ADDONVERSION="$(python3 /usr/bin/ha_version.py --current "$CONFIGVERSION" --upstream "${LASTVERSION//\"/}")"; then + bashio::log.error "... $SLUG : no Home Assistant compliant version derived from ${LASTVERSION}, skipping" + continue + fi + + if [ "$ADDONVERSION" != "${LASTVERSION//\"/}" ]; then + bashio::log.blue "... $SLUG : Home Assistant would not offer ${LASTVERSION//\"/} as an update of $CONFIGVERSION, addon version set to $ADDONVERSION" + fi + + #Change all instances of version, the addon config excluded as + #its version can now differ from the upstream tag LOGINFO="... $SLUG : updating files" && if [ "$VERBOSE" = true ]; then bashio::log.info "$LOGINFO"; fi - for files in "config.json" "config.yaml" "Dockerfile" "build.json" "build.yaml"; do - if [ -f /data/"${BASENAME}"/"${SLUG}"/$files ]; then - sed -i "s/${CURRENT}/${LASTVERSION}/g" /data/"${BASENAME}"/"${SLUG}"/"$files" + CURRENTPATTERN="$(sed_pattern "$CURRENT")" + LASTVERSIONTEXT="$(sed_replacement "$LASTVERSION")" + for files in "Dockerfile" "build.json" "build.yaml"; do + if [ -f "$ADDONFOLDER/$files" ]; then + sed -i "s/${CURRENTPATTERN}/${LASTVERSIONTEXT}/g" "$ADDONFOLDER/$files" fi done # Remove " and modify version LASTVERSION=${LASTVERSION//\"/} CURRENT=${CURRENT//\"/} - if [ -f /data/"${BASENAME}"/"${SLUG}"/config.json ]; then - jq --arg variable "$LASTVERSION" '.version = $variable' /data/"${BASENAME}"/"${SLUG}"/config.json | sponge /data/"${BASENAME}"/"${SLUG}"/config.json # Replace version tag - elif [ -f /data/"${BASENAME}"/"${SLUG}"/config.yaml ]; then - sed -i "/version:/c\version: \"$LASTVERSION\"" /data/"${BASENAME}"/"${SLUG}"/config.yaml + if [ -f "$ADDONFOLDER/config.json" ]; then + # Piping jq into sponge would empty the file if jq fails + if CONFIGJSON="$(jq --arg variable "$ADDONVERSION" '.version = $variable' "$ADDONFOLDER/config.json")"; then + printf '%s\n' "$CONFIGJSON" > "$ADDONFOLDER/config.json" # Replace version tag + fi + elif [ -f "$ADDONFOLDER/config.yaml" ]; then + sed -i "/^version:/c\version: \"$ADDONVERSION\"" "$ADDONFOLDER/config.yaml" fi - jq --arg variable "$LASTVERSION" '.upstream_version = $variable' /data/"${BASENAME}"/"${SLUG}"/updater.json | sponge /data/"${BASENAME}"/"${SLUG}"/updater.json # Replace upstream tag - jq --arg variable "$DATE" '.last_update = $variable' /data/"${BASENAME}"/"${SLUG}"/updater.json | sponge /data/"${BASENAME}"/"${SLUG}"/updater.json # Replace date tag + + # Leave the addon untouched rather than committing a version + # Home Assistant would not offer + if [ "$(config_version "$ADDONFOLDER")" != "$ADDONVERSION" ]; then + bashio::log.error "... $SLUG : version $ADDONVERSION could not be written in the addon config, reverting" + git checkout -- "$ADDONFOLDER" + continue + fi + + # Replace upstream tag and date, keeping the file intact if jq + # fails as a truncated updater.json would lose the addon source + if ! UPDATERJSON="$(jq --arg version "$LASTVERSION" --arg date "$DATE" '.upstream_version = $version | .last_update = $date' "$ADDONFOLDER/updater.json")"; then + bashio::log.error "... $SLUG : updater.json could not be updated, reverting" + git checkout -- "$ADDONFOLDER" + continue + fi + printf '%s\n' "$UPDATERJSON" > "$ADDONFOLDER/updater.json" #Update changelog - touch "/data/${BASENAME}/${SLUG}/CHANGELOG.md" - if [[ "$SOURCE" == *"github"* ]]; then - sed -i "1i - Update to latest version from $UPSTREAM (changelog : https://github.com/${UPSTREAM%/}/releases)" "/data/${BASENAME}/${SLUG}/CHANGELOG.md" - else - sed -i "1i - Update to latest version from $UPSTREAM" "/data/${BASENAME}/${SLUG}/CHANGELOG.md" + touch "$ADDONFOLDER/CHANGELOG.md" + if [ "$ADDONVERSION" != "$LASTVERSION" ]; then + sed -i "1i - Upstream tag : $LASTVERSION" "$ADDONFOLDER/CHANGELOG.md" fi - sed -i "1i ## ${LASTVERSION} (${DATE})" "/data/${BASENAME}/${SLUG}/CHANGELOG.md" - sed -i "1i\ " "/data/${BASENAME}/${SLUG}/CHANGELOG.md" + if [[ "$SOURCE" == *"github"* ]]; then + sed -i "1i - Update to latest version from $UPSTREAM (changelog : https://github.com/${UPSTREAM%/}/releases)" "$ADDONFOLDER/CHANGELOG.md" + else + sed -i "1i - Update to latest version from $UPSTREAM" "$ADDONFOLDER/CHANGELOG.md" + fi + sed -i "1i ## ${ADDONVERSION} (${DATE})" "$ADDONFOLDER/CHANGELOG.md" + sed -i "1i\ " "$ADDONFOLDER/CHANGELOG.md" LOGINFO="... $SLUG : files updated" && if [ "$VERBOSE" = true ]; then bashio::log.info "$LOGINFO"; fi #Git commit and push git add -A # add all modified files - git commit -m "Updater bot : $SLUG updated to ${LASTVERSION}" > /dev/null + git commit -m "Updater bot : $SLUG updated to ${ADDONVERSION} (upstream ${LASTVERSION})" > /dev/null LOGINFO="... $SLUG : push to github" && if [ "$VERBOSE" = true ]; then bashio::log.info "$LOGINFO"; fi @@ -374,7 +441,7 @@ for f in */; do fi #Log - bashio::log.yellow "... $SLUG updated from ${CURRENT} to ${LASTVERSION}" + bashio::log.yellow "... $SLUG updated to ${ADDONVERSION} (upstream ${CURRENT} to ${LASTVERSION})" else bashio::log.green "... $SLUG is up-to-date ${CURRENT}" diff --git a/addons_updater/rootfs/usr/bin/ha_version.py b/addons_updater/rootfs/usr/bin/ha_version.py new file mode 100644 index 0000000000..1c9f289bb8 --- /dev/null +++ b/addons_updater/rootfs/usr/bin/ha_version.py @@ -0,0 +1,334 @@ +#!/usr/bin/env python3 +"""Compute a Home Assistant compliant addon version.""" + +# Home Assistant orders addon versions with awesomeversion. Its update +# entity hides the update whenever the two versions *can* be compared and +# the new one is not strictly newer, and it cannot order a version at all +# when the string follows no known scheme. Whatever lands in the addon +# config.yaml must therefore be recognisable and strictly greater than the +# version users already have installed. +# +# Upstream tags do not always cooperate: +# +# * "1.2.3-4" is a semver pre-release, i.e. older than "1.2.3" +# * "1.2.3+4" only differs by build metadata, which semver ignores +# * "version-bf9e0b4f" or "ubuntu-2026-06-01" follow no scheme at all +# +# This helper therefore decides what to write in config.yaml, while the raw +# upstream tag stays in updater.json: the next run keeps comparing upstream +# with upstream, so a single upstream release never triggers two addon +# updates. + +from __future__ import annotations + +import argparse +import re +import sys +from collections.abc import Iterator +from datetime import date + +from awesomeversion import ( + AwesomeVersion, + AwesomeVersionCompareException, + AwesomeVersionStrategy, +) + +# "5.0.0b5" -> "5.0.0.5": a pre-release marker is not a version section, +# so it is turned into one rather than left for Home Assistant to guess. +MARKER = re.compile(r"^(v?\d+(?:\.\d+)*)(?:alpha|beta|rc|a|b)(\d+)(?=$|-)") +# "1.2.3-4" -> "1.2.3.4": a numeric suffix behind a dash is a semver +# pre-release and sorts before the version it is meant to supersede. +PRERELEASE = re.compile(r"^(v?\d+(?:\.\d+)*)-(\d+(?:\.\d+)*)$") +# A version made of numbers only, e.g. "1.37" or "v2026.07.10.2". +DOTTED_NUMBER = re.compile(r"^(?Pv?)(?P\d+(?:\.\d+)*)$") +# A number carrying a name, e.g. "ls256", "r0" or the bare "2026". +NAMED_NUMBER = re.compile(r"^[A-Za-z]*(\d+(?:\.\d+)*)$") +# Words holding a number that says nothing about the release. +NOT_A_NUMBER = frozenset( + ( + "aarch64", + "amd64", + "arm64", + "armhf", + "armv6", + "armv7", + "i386", + "i486", + "i586", + "i686", + "mips64", + "ppc64", + "riscv64", + "win32", + "win64", + "x64", + "x86", + ) +) + +# Upper bound for the ".1", ".2", ... local rebuild counters. +MAX_COUNTER = 100 + + +def normalise(version: str) -> str: + """Rewrite the parts of a tag Home Assistant would sort wrongly.""" + version = version.strip() + # Build metadata is ignored by semver precedence, a section is not. + version = version.replace("+", ".") + # In both, group 1 is the release and group 2 the number to keep. + version = MARKER.sub(r"\1.\2", version) + return PRERELEASE.sub(r"\1.\2", version) + + +def is_sortable(version: str) -> bool: + """Return True when awesomeversion recognises the version scheme.""" + if not version: + return False + return AwesomeVersion(version).strategy != AwesomeVersionStrategy.UNKNOWN + + +def is_newer(candidate: str, current: str) -> bool: + """Return True when Home Assistant would offer the candidate.""" + if not candidate or candidate == current: + return False + if not current: + return True + try: + return AwesomeVersion(candidate) > AwesomeVersion(current) + except AwesomeVersionCompareException: + # Home Assistant shows the update when it cannot compare, and it + # is the only way out of a version following no known scheme. + return True + + +def is_acceptable(candidate: str, current: str) -> bool: + """Return True for a version safe to write in the addon config.""" + return is_sortable(candidate) and is_newer(candidate, current) + + +def is_year(section: str) -> bool: + """Return True for a section that can only be a year.""" + return len(section) == 4 and 2000 <= int(section) <= 2999 + + +def is_date_like(number: str) -> bool: + """Return True for a real "YYYY.MM.DD", with or without a counter.""" + parts = number.split(".") + if len(parts) < 3 or not is_year(parts[0]): + return False + try: + date(*(int(part) for part in parts[:3])) + except ValueError: + return False + return True + + +def increment(number: str) -> str: + """Increment the last section, keeping any zero padding.""" + parts = number.split(".") + parts[-1] = str(int(parts[-1]) + 1).zfill(len(parts[-1])) + return ".".join(parts) + + +def counters(base: str) -> Iterator[str]: + """Yield ".1", ".2", ... local rebuild counters.""" + for counter in range(1, MAX_COUNTER): + yield f"{base}.{counter}" + + +def skeleton(version: str) -> str: + """Return every number of a tag, in order, as dotted sections.""" + # "v26.2-ls256" -> "v26.2.256", "nightly-2.6.1.5509-ls8" -> + # "2.6.1.5509.8", "4.16-r0-ls94" -> "4.16.0.94". Words carrying no + # number and anything else, a commit hash in particular, are dropped. + numbers = [] + for word in re.split(r"[-/]", normalise(version)): + if word.lower() in NOT_A_NUMBER: + continue + named = NAMED_NUMBER.match(word) + if named: + numbers.append(named.group(1)) + if not numbers: + return "" + prefix = "v" if version.startswith("v") else "" + return prefix + ".".join(numbers) + + +def upstream_candidates(upstream: str) -> Iterator[str]: + """Yield the upstream tag, then the numbers hidden in it.""" + yield normalise(upstream) + # "v26.3-ls256" -> "v26.3.256": the numbers of a tag Home Assistant + # cannot sort still order the addon better than one of our making. + yield skeleton(upstream) + + +def local_candidates(current: str, today: date, release: str) -> Iterator[str]: + """Yield sortable versions derived from the current addon version.""" + calver = today.strftime("%Y.%m.%d") + normalised = normalise(current) + dotted = DOTTED_NUMBER.match(normalised) + + # An upstream that rebuilds the release the current version was built + # from, such as "v26.3-ls257" after "v26.3-ls256", gets a local + # counter ("26.3.1") instead of a release it never published. + if release and normalised.startswith(release): + yield from counters(release) + + if dotted and is_date_like(dotted.group("number")): + # Calendar versioned addon: move to today, then count up when + # several upstream releases land on the same day. + yield calver + if dotted.group("number").count(".") > 2: + yield dotted.group("prefix") + increment(dotted.group("number")) + yield from counters(normalised) + elif dotted: + # "1.37" -> "1.38": the number already in use simply moves on, + # unless it ends on a year, which belongs to a date the addon + # does not choose. + if not is_year(dotted.group("number").split(".")[-1]): + yield dotted.group("prefix") + increment(dotted.group("number")) + yield from counters(normalised) + else: + # Nothing sortable to build on, e.g. "version-bf9e0b4f": keep the + # numbers when the version has some, else switch to calendar + # versioning, which is ordered and never runs out of numbers. + numbers = skeleton(normalised) + if numbers: + yield numbers + yield from counters(numbers) + yield calver + yield from counters(calver) + + +def resolve(current: str, upstream: str, today: date) -> str: + """Return the version to write in the addon configuration.""" + for candidate in upstream_candidates(upstream): + if is_acceptable(candidate, current): + return candidate + for candidate in local_candidates(current, today, skeleton(upstream)): + if is_acceptable(candidate, current): + return candidate + return "" + + +# Date the expectations below are written against. +SELFTEST_DATE = date(2026, 8, 1) + +SELFTESTS = ( + # (current, upstream, expected) + # Sortable upstream releases are used as they are. + ("3.0.3", "3.0.4", "3.0.4"), + ("v3.21.0", "v3.22.0", "v3.22.0"), + ("2026.02.28", "2026.03.01", "2026.03.01"), + ("1.43.1.10611", "1.43.2.10650", "1.43.2.10650"), + # Tags Home Assistant compares as older than what is installed. + ("1.2.3", "1.2.3-2", "1.2.3.2"), + ("1.2.3.2", "1.2.3-3", "1.2.3.3"), + ("1.2.3", "1.2.3+4", "1.2.3.4"), + ("1.2.3.4", "1.2.3+5", "1.2.3.5"), + ("1.2.4", "1.2.3", "1.2.5"), + # Pre-release markers become a section of their own, so that the + # number they carry keeps ordering the addon versions. + ("5.0.0b5-3", "5.0.0b5", "5.0.0.5"), + ("5.0.0.5", "5.0.0b6", "5.0.0.6"), + ("5.0.0.6", "5.0.0", "5.0.0.7"), + ("1.2.3", "1.2.4rc2", "1.2.4.2"), + ("1.2.3", "2.0.0beta1", "2.0.0.1"), + ("1.2.3", "1.2.4a1-2", "1.2.4.1.2"), + # Tags Home Assistant cannot order keep every number they carry. + ("v26.2-ls255", "v26.3-ls256", "v26.3.256"), + ("v26.3.256", "v26.3-ls257", "v26.3.257"), + ("v1.67.0.8", "nightly-2.6.1.5509-ls8", "2.6.1.5509.8"), + ("4.16.0.93", "4.16-r0-ls94", "4.16.0.94"), + ("1.43.3.10828.315", "1.43.3.10828-00f62d37d-ls316", "1.43.3.10828.316"), + ("2026.06.01", "ubuntu-2026-07-01", "2026.07.01"), + ("20260729.1", "nightly-20260801", "20260801"), + ("20260801", "nightly-20260801-2", "20260801.2"), + # A word holding a number that is not part of the release is left out. + ("5.3.2025.11.08", "5.3-amd64-2025-11-09", "5.3.2025.11.09"), + ("1.2.3", "nightly-1.2.4-i686", "1.2.4"), + ("1.2.3", "nightly-1.2.4-armv6", "1.2.4"), + # A date that does not exist is a number like any other. + ("2026.02.31", "version-1a2b3c4d", "2026.02.32"), + ("2026.02.29", "version-1a2b3c4d", "2026.02.30"), + ("2028.02.29", "version-1a2b3c4d", "2028.02.29.1"), + # Dockerhub tags dated by the updater itself. + ("1.2.3.2026.07.25", "1.2.3-2026-08-01", "1.2.3.2026.08.01"), + # The same, dated the other way round: the date cannot order the + # addon, so a local counter does. + ("1.2.3.25.07.2026", "1.2.3-01-08-2026", "1.2.3.25.07.2026.1"), + # Tags holding no number at all: the addon number moves on... + ("1.37", "ubunturesolute-version-8208e985", "1.38"), + ("1.4", "sha-2b71a1c", "1.5"), + ("2025.12-6", "alpine-sts", "2026.08.01"), + ("version-bf9e0b4f", "version-1a2b3c4d", "2026.08.01"), + # ... and calendar versions count up on the same day. + ("2026.08.01", "version-1a2b3c4d", "2026.08.01.1"), + ("2026.08.01.1", "version-2b3c4d5e", "2026.08.01.2"), + ("2026.07.30.2", "version-3c4d5e6f", "2026.08.01"), + # A version dated in the future is never downgraded. + ("2026.09.15", "version-4d5e6f70", "2026.09.15.1"), + # Switching between schemes, in both directions. + ("version-bf9e0b4f", "3.0.4", "3.0.4"), + ("3.0.4", "version-bf9e0b4f", "3.0.5"), + # Tags holding characters that are special to sed. + ("1.2.3", "1.2.4+build[1]", "1.2.4"), + ("1.2.3", "release/2.0", "2.0"), + ("2.0", "release/2.0.1", "2.0.1"), + ("26.3", "v26.2-ls260", "26.4"), + # No current version to build on. + ("", "3.0.4", "3.0.4"), + ("", "1.2.3-2", "1.2.3.2"), + ("", "version-bf9e0b4f", "2026.08.01"), +) + + +def selftest(today: date) -> int: + """Check the rules above against known addon version histories.""" + failures = 0 + for current, upstream, expected in SELFTESTS: + result = resolve(current, upstream, today) + if result != expected: + failures += 1 + print( + f"FAIL {current!r} + {upstream!r} -> " + f"{result!r}, expected {expected!r}", + file=sys.stderr, + ) + print(f"{len(SELFTESTS) - failures}/{len(SELFTESTS)} checks passed") + return 1 if failures else 0 + + +def main() -> int: + """Parse the arguments and print the resulting version.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--current", default="", help="version in use") + parser.add_argument("--upstream", default="", help="upstream tag") + parser.add_argument("--today", default="", help="YYYY-MM-DD override") + parser.add_argument( + "--selftest", action="store_true", help="run the built-in checks" + ) + args = parser.parse_args() + + if args.selftest: + # The expectations above are written against a fixed date, so the + # checks keep passing whenever they are run. + if args.today: + return selftest(date.fromisoformat(args.today)) + return selftest(SELFTEST_DATE) + + today = date.fromisoformat(args.today) if args.today else date.today() + + if not args.upstream: + parser.error("--upstream is required") + + version = resolve(args.current.strip(), args.upstream.strip(), today) + if not version: + print("no Home Assistant compliant version found", file=sys.stderr) + return 1 + print(version) + return 0 + + +if __name__ == "__main__": + sys.exit(main())