Skip to content

Commit

Permalink
dep: add Version.with_op() support
Browse files Browse the repository at this point in the history
  • Loading branch information
radhermit committed Dec 17, 2023
1 parent ebcef47 commit 675462a
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/pkgcraft/C.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -2064,3 +2064,11 @@ cdef extern from "pkgcraft.h":
# # Safety
# The version argument should be a non-null Version pointer.
char *pkgcraft_version_str(Version *v)

# Potentially create a new Version by applying an operator.
#
# Returns NULL on error.
#
# # Safety
# The argument must be a non-null Version pointer.
Version *pkgcraft_version_with_op(Version *v, Operator op)
53 changes: 52 additions & 1 deletion src/pkgcraft/dep/version.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ from enum import IntEnum
from .. cimport C
from .._misc cimport SENTINEL, cstring_to_str

from ..error import InvalidVersion
from ..error import InvalidVersion, PkgcraftError


class Operator(IntEnum):
Expand Down Expand Up @@ -174,6 +174,57 @@ cdef class Version:
inst.ptr = ptr
return inst

def with_op(self, op not None):
"""Potentially create a new Version by applying an operator.
Args:
op (str | Operator): the operator to apply
Returns:
Version: the newly created Version (or the original object if no changes were made)
Raises:
PkgcraftError: for invalid operator arguments
>>> from pkgcraft.dep import Version, Operator
>>> ver = Version('1-r2')
String-based operator
>>> str(ver.with_op('>='))
'>=1-r2'
Enum-based operator
>>> str(ver.with_op(Operator.Less))
'<1-r2'
Invalid operator
>>> ver.with_op(Operator.Approximate)
Traceback (most recent call last):
...
pkgcraft.error.PkgcraftError: ~ version operator can't be used with a revision
Applying the existing operator returns the original Version
>>> v1 = Version('>1-r2')
>>> v2 = v1.with_op(">")
>>> v1 is v2
True
"""
if isinstance(op, str):
op = Operator.from_str(op)
else:
op = Operator(op)

ptr = C.pkgcraft_version_with_op(self.ptr, op)
if ptr is NULL:
raise PkgcraftError
elif ptr != self.ptr:
return Version.from_ptr(ptr)
return self

@property
def op(self):
"""Get a version's operator.
Expand Down

0 comments on commit 675462a

Please sign in to comment.