fix: Adapt versioning scheme to Home Assistant and switch to uv (#896)
Some checks failed
Bump Version / Bump Version Workflow (push) Has been cancelled
docker-build / platform-excludes (push) Has been cancelled
docker-build / build (push) Has been cancelled
docker-build / merge (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
Run Pytest on Pull Request / test (push) Has been cancelled

Home Assistant expects versioning always increases numbers. Add
a date component to the development version to comply with this
expectation. The scheme is now 0.0.0.dev<date><hash>.

Use uv for creating and managing the virtual environment for developement.
This enourmously speeds up dependency updates. For this change
dependency requirements are now solely handled in pyproject.toml.
requirements.tx and requirements-dev.txt are deleted.

Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>
This commit is contained in:
Bobby Noelte
2026-02-23 20:59:03 +01:00
committed by GitHub
parent c578a56af2
commit d446274129
30 changed files with 3974 additions and 319 deletions

View File

@@ -1,8 +1,21 @@
"""Version information for akkudoktoreos."""
# -----------------------------------------------------------------
# version.py may be used __BEFORE__ the dependencies are installed.
# Use only standard python libraries
#
# Several warnings/ erros are silenced because they are
# non-critical in this context - see noqa.
# -----------------------------------------------------------------
import hashlib
import re
import subprocess
from dataclasses import dataclass
from datetime import ( # Don't use akkudoktoreos.utils.datetimeutil (-> pendulum)
datetime,
timezone,
)
from fnmatch import fnmatch
from pathlib import Path
from typing import Optional
@@ -14,14 +27,18 @@ VERSION_BASE = "0.2.0.dev"
# Project hash of relevant files
HASH_EOS = ""
# Number of digits to append to .dev to identify a development version
VERSION_DEV_PRECISION = 8
# Number of hash digits to append to .dev to identify a development version
VERSION_DEV_HASH_PRECISION = 8
# File to hold the date of the latest commit.
VERSION_DATE_FILE = Path(__file__).parent / "_version_date.py"
# Hashing configuration
DIR_PACKAGE_ROOT = Path(__file__).resolve().parent.parent
ALLOWED_SUFFIXES: set[str] = {".py", ".md", ".json"}
EXCLUDED_DIR_PATTERNS: set[str] = {"*_autosum", "*__pycache__", "*_generated"}
EXCLUDED_FILES: set[Path] = set()
# Excluded from hash/date calculation to avoid self-referencing loop
EXCLUDED_FILES: set[Path] = {VERSION_DATE_FILE}
# ------------------------------
@@ -169,18 +186,78 @@ def hash_tree(
return digest, files
def newest_commit_or_dirty_datetime(files: list[Path]) -> datetime:
"""Return the newest relevant datetime for the given files in UTC.
Checks for uncommitted changes among the given files first. If any file
has staged or unstaged modifications, the current UTC datetime is returned
to reflect that the working tree is ahead of the last commit. Otherwise,
the datetime of the most recent git commit touching any of the given files
is returned. If git is unavailable (e.g. after pip install), falls back to
reading the date from VERSION_DATE_FILE.
Args:
files: List of file paths to check for changes and commit history.
Returns:
The current UTC datetime if any file has uncommitted changes, otherwise
the UTC datetime of the most recent commit touching any of the given
files, or the datetime stored in VERSION_DATE_FILE as a last resort.
Raises:
RuntimeError: If no version date can be determined from any source.
"""
# Check for uncommitted changes among watched files
try:
status_result = subprocess.run( # noqa: S603
["git", "status", "--porcelain", "--"] + [str(f) for f in files],
capture_output=True,
text=True,
check=True,
cwd=DIR_PACKAGE_ROOT,
)
if status_result.stdout.strip():
return datetime.now(tz=timezone.utc)
result = subprocess.run( # noqa: S603
["git", "log", "-1", "--format=%ct", "--"] + [str(f) for f in files],
capture_output=True,
text=True,
check=True,
cwd=DIR_PACKAGE_ROOT,
)
ts = result.stdout.strip()
if ts:
return datetime.fromtimestamp(int(ts), tz=timezone.utc)
except (subprocess.CalledProcessError, FileNotFoundError, ValueError): # noqa: S110
pass
# Fallback to VERSION_DATE_FILE
if VERSION_DATE_FILE.exists():
try:
ns: dict[str, str] = {}
exec(VERSION_DATE_FILE.read_text(), {}, ns) # noqa: S102
date_str = ns.get("VERSION_DATE")
if date_str:
return datetime.fromisoformat(date_str).astimezone(timezone.utc)
except Exception: # noqa: S110
pass
raise RuntimeError("This should not happen - No version date info available")
# ---------------------
# Version hash function
# ---------------------
def _version_hash() -> str:
"""Calculate project hash.
def _version_date_hash() -> tuple[datetime, str]:
"""Calculate project date and hash.
Only package files in src/akkudoktoreos can be hashed to make it work also for packages.
Returns:
SHA256 hash of the project files
lattest commit date and SHA256 hash of the project files
"""
if not str(DIR_PACKAGE_ROOT).endswith("src/akkudoktoreos"):
error_msg = f"DIR_PACKAGE_ROOT does not end with src/akkudoktoreos: {DIR_PACKAGE_ROOT}"
@@ -197,23 +274,29 @@ def _version_hash() -> str:
excluded_files=EXCLUDED_FILES,
)
return hash_digest
date = newest_commit_or_dirty_datetime(hashed_files)
return date, hash_digest
def _version_calculate() -> str:
"""Calculate the full version string.
For release versions: "x.y.z"
For dev versions: "x.y.z.dev<hash>"
For dev versions: "x.y.z.dev<date><hash>"
Returns:
Full version string
"""
if VERSION_BASE.endswith(".dev"):
# After dev only digits are allowed - convert hexdigest to digits
hash_value = int(_version_hash(), 16)
hash_digits = str(hash_value % (10**VERSION_DEV_PRECISION)).zfill(VERSION_DEV_PRECISION)
return f"{VERSION_BASE}{hash_digits}"
version_date, version_hash = _version_date_hash()
hash_value = int(version_hash, 16)
hash_digits = str(hash_value % (10**VERSION_DEV_HASH_PRECISION)).zfill(
VERSION_DEV_HASH_PRECISION
)
date_digits = version_date.strftime("%y%m%d%H") if version_date else "00000000"
return f"{VERSION_BASE}{date_digits}{hash_digits}"
else:
# Release version - use base as-is
return VERSION_BASE
@@ -234,10 +317,10 @@ __version__ = _version_calculate()
# Regular expression to split the version string into pieces
VERSION_RE = re.compile(
r"""
^(?P<base>\d+\.\d+\.\d+) # x.y.z
(?:\. # .dev<hash> starts here
(?P<dev>dev) # literal 'dev'
(?P<hash>[a-f0-9]+)? # optional <hash> (hex digits)
^(?P<base>\d+\.\d+\.\d+) # x.y.z
(?:\.dev # literal '.dev' for development versions
(?P<date>\d{8}) # 8-digit date: YYMMDDHH
(?P<hash>[a-f0-9]+)? # hex hash
)?
$
""",
@@ -251,7 +334,7 @@ def version() -> dict[str, Optional[str]]:
The version string shall be of the form:
x.y.z
x.y.z.dev
x.y.z.dev<HASH>
x.y.z.dev<date><hash>
Returns:
.. code-block:: python