-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathconvertors.py
More file actions
99 lines (71 loc) · 2.46 KB
/
convertors.py
File metadata and controls
99 lines (71 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
from __future__ import annotations
import math
import uuid
from typing import (
Any,
ClassVar,
Generic,
TypeVar,
)
T = TypeVar("T")
class Convertor(Generic[T]):
regex: ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError()
def to_string(self, value: T) -> str:
raise NotImplementedError()
class StringConvertor(Convertor[str]):
regex = r"[^/]+"
def convert(self, value: str) -> str:
return value
def to_string(self, value: str) -> str:
value = str(value)
assert "/" not in value, "May not contain path separators"
assert value, "Must not be empty"
return value
class PathConvertor(Convertor[str]):
regex = r".*"
def convert(self, value: str) -> str:
return str(value)
def to_string(self, value: str) -> str:
return str(value)
class IntegerConvertor(Convertor[int]):
regex = r"[0-9]+"
def convert(self, value: str) -> int:
try:
return int(value)
except ValueError:
raise ValueError(f"Value '{value}' is not a valid integer")
def to_string(self, value: int) -> str:
value = int(value)
assert value >= 0, "Negative integers are not supported"
return str(value)
class FloatConvertor(Convertor[float]):
regex = r"[0-9]+(?:\.[0-9]+)?"
def convert(self, value: str) -> float:
try:
return float(value)
except ValueError:
raise ValueError(f"Value '{value}' is not a valid float")
def to_string(self, value: float) -> str:
value = float(value)
assert value >= 0.0, "Negative floats are not supported"
assert not math.isnan(value), "NaN values are not supported"
assert not math.isinf(value), "Infinite values are not supported"
return f"{value:.20f}".rstrip("0").rstrip(".")
class UUIDConvertor(Convertor[uuid.UUID]):
regex = r"[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}"
def convert(self, value: str) -> uuid.UUID:
try:
return uuid.UUID(value)
except ValueError:
raise ValueError(f"Value '{value}' is not a valid UUID")
def to_string(self, value: uuid.UUID) -> str:
return str(value)
CONVERTOR_TYPES: dict[str, Convertor[Any]] = {
"str": StringConvertor(),
"path": PathConvertor(),
"int": IntegerConvertor(),
"float": FloatConvertor(),
"uuid": UUIDConvertor(),
}