jw-pkg/src/python/jw/pkg/lib/version/Version.py
Jan Lindemann 83b5151f22
lib.version.Version.next(): Step the last part
Range expansion needs a bound that steps the last existing part of a
version, add that.

next() increments the last part, whatever it is: next of '1' is '2', of
'1.0' is '1.1', of '1.2.3' is '1.2.4', of '1.2.3-45' is '1.2.3-46'.

Tests written by AI.

Signed-off-by: Jan Lindemann <jan@janware.com>
Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v0.85.1
2026-09-15 21:43:47 +02:00

247 lines
8.5 KiB
Python

from __future__ import annotations
import re
from functools import cached_property
from typing import TYPE_CHECKING, ClassVar, override
from .base import Component, Lookup
if TYPE_CHECKING:
from enum import Flag
class Version: # export
"""A version spec: a literal such as '1.2.3-4', or one of the macros
VERSION, VERSION-REVISION and REVISION, which resolve against the
version of the project the name refers to, through the lookup
callback.
Versions step through compatibility tiers: a different revision is
a binary-compatible change, a different micro is source-compatible,
a different minor carries no major incompatibilities but downstream
packages should expect trivial fixes, and a different major gives
no compatibility guarantees at all.
"""
class Error(ValueError):
pass
__FULL_ID_RE: ClassVar[
re.Pattern[str],
] = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+-[0-9]+')
__SUFFIX_RE: ClassVar[re.Pattern[str]] = re.compile('-dev$|-devel$|-run$')
@cached_property
def __resolved_id(self) -> str:
if self.__lookup_version is None:
raise Version.Error(
f'Tried to look up version of {self.base_name} without lookup function'
)
resolved = self.__lookup_version(self.base_name)
if self.__spec == 'VERSION-REVISION':
return resolved
parts = resolved.split('-')
match self.__spec:
case 'VERSION':
return parts[0]
case 'REVISION':
return parts[1] if len(parts) == 2 else ''
case _:
raise Version.Error(f'Invalid version specifier "{self.__spec}"')
def __id(self, untemplate: bool, throw: bool = True) -> str:
if not untemplate:
return self.__spec
if self.__spec not in ['VERSION', 'REVISION', 'VERSION-REVISION']:
return self.__spec
try:
return self.__resolved_id
except Exception:
if throw:
raise
return self.__spec
def __split_spec(self, untemplate: bool) -> tuple[str, str]:
parts = self.__id(untemplate).split('-')
if len(parts) == 1:
return parts[0], ''
return parts[0], parts[1]
def __split_core(self, untemplate: bool) -> tuple[str, ...]:
return tuple(self.__split_spec(untemplate)[0].split('.'))
def __parts_str(self, parts: Component, untemplate: bool) -> str:
# Without the widening, mypy will decry unreachable code below match block
match_subject: Flag = parts
match match_subject:
case Component.ID:
return self.__id(untemplate)
case Component.CORE:
return self.__split_spec(untemplate)[0]
case Component.MAJOR:
return self.__split_core(untemplate)[0]
case Component.MINOR:
return self.__split_core(untemplate)[1]
case Component.MICRO:
return self.__split_core(untemplate)[2]
case Component.REVISION:
return self.__split_spec(untemplate)[1]
case _:
pass
ret: list[str] = []
for part in [
Component.MAJOR,
Component.MINOR,
Component.MICRO,
Component.REVISION,
]:
if part not in parts:
break
ret.append(self.__parts_str(part, untemplate))
parts &= ~part
if parts:
raise Version.Error(f'Invalid version part combination {parts}')
if len(ret) < 4:
return '.'.join(ret)
return f'{".".join(ret[:3])}-{ret[3]}'
def __init__(
self, name: str, spec: str, lookup_version: Lookup | None = None
) -> None:
self.__name = name
self.__spec = spec
self.__lookup_version = lookup_version
@override
def __repr__(self) -> str:
return self.__spec
@override
def __str__(self) -> str:
return self.__id(untemplate = True, throw = False)
@classmethod
def strip_package_suffix(cls, name: str) -> str:
"""Remove the -dev, -devel or -run subpackage suffix"""
return cls.__SUFFIX_RE.sub('', name)
@property
def name(self) -> str:
return self.__name
@property
def base_name(self) -> str:
return self.strip_package_suffix(self.__name)
def parts_str(self, parts: Component, untemplate: bool) -> str:
return self.__parts_str(parts, untemplate)
@property
def is_full(self) -> bool:
"""True if the spec pins a complete version: the
VERSION-REVISION macro, or a literal of the form
MAJOR.MINOR.MICRO-REVISION. Range expansion leaves full
versions exact and expands the non-full specs.
"""
if self.__spec == 'VERSION-REVISION':
return True
return bool(self.__FULL_ID_RE.fullmatch(self.__spec))
def id(self, untemplate: bool, include_revision: bool = True) -> str:
"""Return the version id: the raw spec if untemplate is False,
else the resolved version. A VERSION spec yields the core
version.
"""
if not include_revision and self.__spec == 'VERSION':
return self.core(untemplate)
return self.__id(untemplate)
def core(self, untemplate: bool) -> str:
return self.__split_spec(untemplate)[0]
def revision(self, untemplate: bool = True) -> str:
return self.__split_spec(untemplate)[1]
@property
def major(self) -> int:
return int(self.__parts_str(Component.MAJOR, True))
@property
def minor(self) -> int:
return int(self.__parts_str(Component.MINOR, True))
@property
def micro(self) -> int:
return int(self.__parts_str(Component.MICRO, True))
@property
def next_binary_compatible(self) -> Version:
"""The next version within the binary tier: the same core with
the revision incremented. A different revision is a
binary-compatible change, so binaries built against the current
version keep working. Only the revision's leading digits count:
a suffixed revision such as '4blah' steps to '5', which sits
strictly above every variant of the current revision. A
revision without leading digits raises Version.Error.
"""
rev = self.revision(True)
m = re.match('[0-9]+', rev)
if not m:
raise Version.Error(f'Cannot increment non-numeric revision "{rev}"')
return Version(
self.__name,
f'{self.major}.{self.minor}.{self.micro}-{int(m.group()) + 1}',
self.__lookup_version,
)
@property
def next_binary_incompatible(self) -> Version:
"""The next version out of the binary tier: the micro
incremented, the revision dropped. A different micro is
source-compatible, so this is the first version binaries of the
current version are not guaranteed to run against.
"""
return Version(
self.__name,
f'{self.major}.{self.minor}.{self.micro + 1}',
self.__lookup_version,
)
@property
def next_source_incompatible(self) -> Version:
"""The next version out of the source tier: the minor
incremented, micro and revision reset. A different minor carries
no major incompatibilities, but downstream packages should
expect to need trivial fixes.
"""
return Version(
self.__name,
f'{self.major}.{self.minor + 1}.0',
self.__lookup_version,
)
@property
def next(self) -> Version:
"""The next version in the series: the last part
incremented. next of '1' is '2', of '1.0' is '1.1', of
'1.2.3' is '1.2.4', of '1.2.3-45' is '1.2.3-46'. The
separators of the spec are kept. Like in
next_binary_compatible(), only the last part's leading
digits count: a suffixed part such as '4blah' steps to
'5'. A part without leading digits raises Version.Error.
"""
untemplated = self.__id(untemplate = True, throw = True)
parts = re.split('([.-])', untemplated)
m = re.match('[0-9]+', parts[-1])
if not m:
raise Version.Error(
f'Cannot step version "{self.__spec}": the last '
f'part "{parts[-1]}" has no leading digits'
)
parts[-1] = str(int(m.group()) + 1)
return Version(
self.__name,
''.join(parts),
self.__lookup_version,
)