-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvariant.py
More file actions
272 lines (226 loc) · 9.49 KB
/
variant.py
File metadata and controls
272 lines (226 loc) · 9.49 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
from __future__ import annotations
import contextlib
import hashlib
import sys
from collections import defaultdict
from dataclasses import asdict
from dataclasses import dataclass
from dataclasses import field
from functools import cached_property
from variantlib.constants import VALIDATION_FEATURE_NAME_REGEX
from variantlib.constants import VALIDATION_FEATURE_REGEX
from variantlib.constants import VALIDATION_NAMESPACE_REGEX
from variantlib.constants import VALIDATION_PROPERTY_REGEX
from variantlib.constants import VALIDATION_VALUE_REGEX
from variantlib.constants import VariantInfoJsonDict
from variantlib.errors import ValidationError
from variantlib.models.base import BaseModel
from variantlib.protocols import VariantFeatureName
from variantlib.protocols import VariantFeatureValue
from variantlib.protocols import VariantNamespace
from variantlib.validators.base import validate_list_all_unique
from variantlib.validators.base import validate_matches_re
from variantlib.validators.base import validate_type
from variantlib.validators.combining import validate_and
if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self
VARIANT_HASH_LENGTH = 8
@dataclass(frozen=True, order=True)
class VariantFeature(BaseModel):
namespace: VariantNamespace = field(
metadata={
"validator": lambda val: validate_and(
[
lambda v: validate_type(v, VariantNamespace),
lambda v: validate_matches_re(v, VALIDATION_NAMESPACE_REGEX), # pyright: ignore[reportArgumentType]
],
value=val,
)
}
)
feature: VariantFeatureName = field(
metadata={
"validator": lambda val: validate_and(
[
lambda v: validate_type(v, VariantFeatureName),
lambda v: validate_matches_re(v, VALIDATION_FEATURE_NAME_REGEX), # pyright: ignore[reportArgumentType]
],
value=val,
)
}
)
@property
def feature_hash(self) -> int:
# __class__ is being added to guarantee the hash to be specific to this class
# note: can't use `self.__class__` because of inheritance
return hash((VariantFeature, self.namespace, self.feature))
def to_str(self) -> str:
# Variant-Property: <namespace> :: <feature> :: <val>
return f"{self.namespace} :: {self.feature}"
def serialize(self) -> dict[str, str]:
return asdict(self)
@classmethod
def deserialize(cls, data: dict[str, str]) -> Self:
for field_name in cls.__dataclass_fields__:
if field_name not in data:
raise ValidationError(f"Extra field not known: `{field_name}`")
return cls(**data)
@classmethod
def from_str(cls, input_str: str) -> Self:
# Try matching the input string with the regex pattern
match = VALIDATION_FEATURE_REGEX.fullmatch(input_str.strip())
if match is None:
raise ValidationError(
f"Invalid format: `{input_str}`, expected format: "
"'<namespace> :: <feature>'"
)
# Extract the namespace, feature, and value from the match groups
namespace = match.group("namespace")
feature = match.group("feature")
# Return an instance of VariantFeature using the parsed values
return cls(namespace=namespace, feature=feature)
@dataclass(frozen=True, order=True)
class VariantProperty(VariantFeature):
value: VariantFeatureValue = field(
metadata={
"validator": lambda val: validate_and(
[
lambda v: validate_type(v, VariantFeatureValue),
lambda v: validate_matches_re(v, VALIDATION_VALUE_REGEX), # pyright: ignore[reportArgumentType]
],
value=val,
)
}
)
@property
def property_hash(self) -> int:
# __class__ is being added to guarantee the hash to be specific to this class
return hash((self.__class__, self.namespace, self.feature, self.value))
@property
def feature_object(self) -> VariantFeature:
return VariantFeature(namespace=self.namespace, feature=self.feature)
def to_str(self) -> str:
# Variant-Property: <namespace> :: <feature> :: <val>
return f"{self.namespace} :: {self.feature} :: {self.value}"
@classmethod
def from_str(cls, input_str: str) -> Self:
# Try matching the input string with the regex pattern
match = VALIDATION_PROPERTY_REGEX.fullmatch(input_str.strip())
if match is None:
raise ValidationError(
f"Invalid format: `{input_str}`, "
"expected format: `<namespace> :: <feature> :: <value>`"
)
# Extract the namespace, feature, and value from the match groups
namespace = match.group("namespace")
feature = match.group("feature")
value = match.group("value")
# Return an instance of VariantProperty using the parsed values
return cls(namespace=namespace, feature=feature, value=value)
@dataclass(frozen=True)
class VariantDescription(BaseModel):
"""
A `Variant` is being described by a N >= 1 `VariantProperty`.
Each informing the packaging toolkit about a unique `namespace-feature-value`
combination.
All together they identify the package producing a "variant hash", unique
to the exact combination of `VariantProperty` provided for a given package.
"""
properties: list[VariantProperty] = field(
metadata={
"validator": lambda val: validate_and(
[
lambda v: validate_type(v, list[VariantProperty]),
lambda v: validate_list_all_unique(
v, keys=["namespace", "feature", "value"]
),
],
value=val,
),
},
default_factory=list,
)
def __post_init__(self) -> None:
# We sort the data so that they always get displayed/hashed
# in a consistent manner.
# Note: We have to execute this before validation to guarantee hash consistency.
with contextlib.suppress(AttributeError):
# Only "legal way" to modify a frozen dataclass attribute post init.
object.__setattr__(self, "properties", sorted(self.properties))
# Execute the validator
super().__post_init__()
def is_null_variant(self) -> bool:
"""
Check if the variant is a null variant.
A null variant is a variant with no properties.
"""
return not self.properties
@cached_property
def hexdigest(self) -> str:
"""
Compute the hash of the object.
"""
hash_object = hashlib.sha256()
# Append a newline to every serialized property to ensure that they
# are separated from one another. Otherwise, two "adjacent" variants
# such as:
# a :: b :: cx
# d :: e :: f
# and:
# a :: b :: c
# xd :: e :: f
# would serialize to the same hash.
for vprop in self.properties:
hash_object.update(f"{vprop.to_str()}\n".encode())
# Like digest() except the digest is returned as a string object of double
# length, containing only hexadecimal digits. This may be used to exchange the
# value safely in email or other non-binary environments.
# Source: https://docs.python.org/3/library/hashlib.html#hashlib.hash.hexdigest
return hash_object.hexdigest()[:VARIANT_HASH_LENGTH]
@classmethod
def deserialize(cls, properties: list[dict[str, str]]) -> Self:
return cls(
properties=[VariantProperty.deserialize(vdata) for vdata in properties]
)
def serialize(self) -> list[dict[str, str]]:
return [vprop.serialize() for vprop in self.properties]
def to_dict(self) -> VariantInfoJsonDict:
data = asdict(self)
result: defaultdict[str, dict[str, list[str]]] = defaultdict(
lambda: defaultdict(list)
)
for vprop in data["properties"]:
namespace = vprop["namespace"]
feature = vprop["feature"]
value = vprop["value"]
result[namespace][feature].append(value)
return dict(result)
@classmethod
def from_dict(cls, data: VariantInfoJsonDict) -> Self:
vprops = [
VariantProperty(namespace=namespace, feature=key, value=vprop_val)
for namespace, vdata in data.items()
for key, vprop_values in vdata.items()
for vprop_val in vprop_values
]
return cls(vprops)
@dataclass(frozen=True)
class VariantValidationResult:
results: dict[VariantProperty, bool | None]
multi_value_violations: frozenset[VariantFeature]
def is_valid(self, allow_unknown_plugins: bool = True) -> bool:
return (
not self.multi_value_violations
and False not in self.results.values()
and (allow_unknown_plugins or None not in self.results.values())
)
@property
def invalid_properties(self) -> list[VariantProperty]:
"""List of properties declared invalid by plugins"""
return [x for x, y in self.results.items() if y is False]
@property
def unknown_properties(self) -> list[VariantProperty]:
"""List of properties not in any recognized namespace"""
return [x for x, y in self.results.items() if y is None]