Skip to content

Commit 9dbbcc8

Browse files
committed
util: version: version parsing helper
Add a helper class for parsing version strings and test. Signed-off-by: Jordan Yates <jordan@embeint.com>
1 parent 45fc6a8 commit 9dbbcc8

2 files changed

Lines changed: 65 additions & 0 deletions

File tree

src/infuse_iot/util/version.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#!/usr/bin/env
2+
3+
from typing import Self
4+
5+
6+
class Version:
7+
def __init__(self, major: int, minor: int, revision: int, build_num: int):
8+
self.major = major
9+
self.minor = minor
10+
self.revision = revision
11+
self.build_num = build_num
12+
13+
@classmethod
14+
def from_string(cls, version_string: str) -> Self:
15+
"Convert 'x.y.z+rev' string to version instance"
16+
17+
rev_split = version_string.split("+")
18+
if len(rev_split) != 2:
19+
raise ValueError(f"'{version_string}' is not a valid version string")
20+
ver_split = rev_split[0].split(".")
21+
if len(ver_split) != 3:
22+
raise ValueError(f"'{version_string}' is not a valid version string")
23+
return cls(int(ver_split[0]), int(ver_split[1]), int(ver_split[2]), int(rev_split[1], 16))
24+
25+
def __str__(self):
26+
return f"{self.major}.{self.minor}.{self.revision}+{self.build_num:08x}"
27+
28+
def __eq__(self, other):
29+
if not isinstance(other, Version):
30+
raise NotImplementedError
31+
return (
32+
self.major == other.major
33+
and self.minor == other.minor
34+
and self.revision == other.revision
35+
and self.build_num == other.build_num
36+
)

tests/util/test_version.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#!/usr/bin/env python3
2+
3+
import os
4+
5+
import pytest
6+
7+
from infuse_iot.util.version import Version
8+
9+
assert "TOXTEMPDIR" in os.environ, "you must run these tests using tox"
10+
11+
12+
def test_version_parsing():
13+
with pytest.raises(ValueError):
14+
Version.from_string("random string")
15+
with pytest.raises(ValueError):
16+
Version.from_string("1.2.3")
17+
with pytest.raises(ValueError):
18+
Version.from_string("1.2+aaaaaaaa")
19+
20+
assert Version.from_string("1.2.3+aaaaaaaa") == Version(1, 2, 3, 0xAAAAAAAA)
21+
assert Version.from_string("10.2.3+12345678") == Version(10, 2, 3, 0x12345678)
22+
assert Version.from_string("1.20.354+50") == Version(1, 20, 354, 0x50)
23+
24+
def round_trip(string: str):
25+
assert str(Version.from_string(string)) == string
26+
27+
round_trip("1.2.3+aaaaaaaa")
28+
round_trip("10.2.3+12345678")
29+
round_trip("2.20.1+00000aaa")

0 commit comments

Comments
 (0)