erg/crates/erg_compiler/lib/std/semver.er
2024-03-24 00:55:01 +09:00

72 lines
3 KiB
Python

# e.g. `nightly.0`
.Identifier = Class { .name = Str; .num = Nat }
.Identifier|<: Show|.
__str__ ref self = "\{self.name}.\{self.num}"
.Identifier|.Identifier <: Eq|.
__eq__ self, other: .Identifier =
hasattr(other, "name") and hasattr(other, "num") and \
self.name == other.name and self.num == other.num
.Identifier.
from_str s: Str =
match s.split("."):
[name, num] ->
num_ = nat(num)
assert num_ in Nat
.Identifier { .name; .num = num_ }
_ -> panic "invalid identifier string: \{s}"
@Override
__repr__ ref self = "Identifier(\{self.__str__()})"
.SemVer = Class { .major = Nat; .minor = Nat; .patch = Nat; .pre = .Identifier or NoneType }
.SemVer|<: Show|.
__str__ ref self =
if self.pre != None:
do: "\{self.major}.\{self.minor}.\{self.patch}-\{self.pre}"
do: "\{self.major}.\{self.minor}.\{self.patch}"
.SemVer.
new major, minor, patch, pre := None =
.SemVer { .major; .minor; .patch; .pre }
from_str s: Str =
match s.split("."):
[major, minor, patch] ->
.SemVer.new(nat(major), nat(minor), nat(patch))
[major, minor, patch_and_name, pre_num] ->
assert "-" in patch_and_name, "invalid semver string: \{s}"
[patch, name] = patch_and_name.split("-")
pre = .Identifier.new { .name; .num = nat pre_num }
.SemVer.new(nat(major), nat(minor), nat(patch), pre)
_ -> panic "invalid semver string: \{s}"
@Override
__repr__ ref self = "SemVer(\{self.__str__()})"
compatible_with self, other =
if self.major == 0, do:
self.compatible_with::return self == other
self.major == other.major
is_valid s: Str =
match s.split("."):
[major, minor, patch] -> major.isnumeric() and minor.isnumeric() and patch.isnumeric()
[major, minor, patch, pre] -> major.isnumeric() and minor.isnumeric() and patch.isnumeric() and pre.isalnum()
_ -> False
#[
greater self, other: .Version =
match [self.major > other.major, self.major >= other.major, self.minor > other.minor, self.minor >= other.minor, self.patch > other.patch]:
[True, _, _, _, _] -> True
[_, True, True, _, _] -> True
[_, True, _, True, True] -> True
_ -> False
]#
.SemVer|<: Eq|.
__eq__ self, other: .SemVer =
hasattr(other, "major") and hasattr(other, "minor") and hasattr(other, "patch") and hasattr(other, "pre") and \
self.major == other.major and self.minor == other.minor and self.patch == other.patch and self.pre == other.pre
.SemVerPrefix = Class { "~", "==", "<", ">", "<=", "<=", }
.SemVerSpec = Class { .prefix = .SemVerPrefix; .version = .SemVer }
if! __name__ == "__main__", do!:
v = .SemVer.new(0, 0, 1)
assert v.minor == 0
assert v.pre == None
assert v != .SemVer.new(0, 0, 2)
v2 = .SemVer.from_str("0.0.1")
assert v == v2