-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatatypes.py
More file actions
348 lines (272 loc) · 8.84 KB
/
datatypes.py
File metadata and controls
348 lines (272 loc) · 8.84 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from __future__ import annotations
import copy
from dataclasses import Field, dataclass, field, fields
import dataclasses
from functools import reduce
import json
import pathlib
import sys
from typing import (
Any,
Callable,
Dict,
Generator,
List,
MutableSequence,
Optional,
Type,
TypeVar,
Union,
cast,
)
import zipfile
PathLike = Union[str, pathlib.Path]
T = TypeVar("T")
JsonClassTag = "_IsJsonClass"
_TYPE_MAP: Dict[str, Optional[Type[Any]]] = {}
def get_class(name: str) -> Optional[Type[Any]]:
try:
return _TYPE_MAP[name]
except KeyError:
pass
parts = name.partition(".")
try:
m = sys.modules[__name__]
cls = _TYPE_MAP[name] = cast(Type[Any], getattr(m, name))
return cls
except AttributeError:
pass
try:
if parts[1] and "[" not in parts[0]:
cls = _TYPE_MAP[name] = cast(
Type[Any],
reduce(getattr, name.split(".")[1:], __import__(parts[0])),
)
except AttributeError:
pass
_TYPE_MAP[name] = None
return None
def parse_list(
items: Union[List[T], List[Union[T, Dict[Any, Any]]]], type: Type[T]
) -> List[T]:
return [type(**v) if isinstance(v, dict) else v for v in items] # type: ignore
def parse_dict(
items: Union[Dict[str, T], Dict[str, Union[T, Dict[Any, Any]]]], type: Type[T]
) -> Dict[str, T]:
return {k: type(**v) if isinstance(v, dict) else v for k, v in items.items()}
def process_json_dict(items: dict[str, Any]) -> dict[str, Any]:
safe_items = {k: v for k, v in items.items() if not k.startswith("+")}
append_items = {k: v for k, v in items.items() if k.startswith("+")}
for k, v in append_items.items():
attr = k[1:]
if attr not in safe_items:
raise TypeError(f"Invalid key: +{attr}")
current = safe_items[attr]
if not isinstance(current, MutableSequence):
raise TypeError(f"Invalid key +{attr} for appending new items")
current.extend(v) # type: ignore
return safe_items
def post_init(self: Any) -> None:
for f in fields(self):
value = getattr(self, f.name)
if isinstance(value, dict):
value = process_json_dict(cast(dict[str, Any], value))
setattr(self, f.name, value)
init = f.metadata.get("__post_init__", None)
if init is not None:
setattr(self, f.name, init(getattr(self, f.name)))
continue
type = get_class(str(f.type))
if type is None:
continue
if getattr(type, JsonClassTag, False):
if isinstance(value, dict):
setattr(self, f.name, type(**value))
continue
if type is pathlib.Path:
setattr(self, f.name, pathlib.Path(value))
continue
def jsonclass(cls: Type[T]) -> Type[T]:
old_init: Optional[Callable[[T], None]] = getattr(cls, "__post_init__", None)
new_init: Callable[[T], None]
if old_init is None:
new_init = post_init
else:
def init(self: T) -> None:
post_init(self)
old_init(self) # type: ignore
new_init = init
setattr(cls, "__post_init__", new_init)
setattr(cls, JsonClassTag, True)
return cls
def listfield(type: Type[T], optional: bool = False) -> List[T]:
def parse(items: Optional[List[T]]) -> Optional[List[T]]:
if items is None:
return None
return parse_list(items, type)
kwargs: Dict[str, Any] = {}
if optional:
kwargs["default"] = None
else:
kwargs["default_factory"] = list
return field(
**kwargs,
metadata=dict(__post_init__=parse),
)
@dataclass
class Substitution:
search: str
replace: str
@dataclass
@jsonclass
class Pattern:
pattern: str
substitutions: List[Substitution] = listfield(Substitution)
@dataclass
class FileCopy:
source: str
destination: str
@dataclass
@jsonclass
class ReplaceAction:
regex: List[Pattern] = listfield(Pattern)
template_files: List[FileCopy] = listfield(FileCopy)
@dataclass
@jsonclass
class PostBuildActionList:
clean: List[str] = field(default_factory=list)
install: List[FileCopy] = listfield(FileCopy)
@dataclass
class PostBuildAction(PostBuildActionList):
pdb2mdb: Optional[pathlib.Path] = None
def __init__(
self,
clean: List[str] = dataclasses.MISSING, # type: ignore
install: List[FileCopy] = dataclasses.MISSING, # type: ignore
pdb2mdb: Optional[PathLike] = None,
**kwargs: PostBuildActionList,
) -> None:
super().__init__(clean, install)
self.pdb2mdb = None
if pdb2mdb is not None:
self.pdb2mdb = pathlib.Path(pdb2mdb)
self.per_target = parse_dict(kwargs, PostBuildActionList)
# emulate dynamic fields
fs: Dict[str, Field[Any]] = getattr(self, "__dataclass_fields__")
default_field = fs["pdb2mdb"]
for name in self.per_target:
f = copy.copy(default_field)
f.name = name
f.type = "PostBuildActionList" # type: ignore
fs[name] = f
try:
self.__post_init__() # type: ignore
except AttributeError:
pass
def __getitem__(self, key: str) -> PostBuildActionList:
return self.per_target[key]
def __getattr__(self, name: str) -> PostBuildActionList:
try:
return self[name]
except KeyError as e:
raise AttributeError(name) from e
def __contains__(self, key: str) -> bool:
return key in self.per_target
def update(self, other: PostBuildActionList) -> None:
self.clean = other.clean
self.install = other.install
@dataclass
@jsonclass
class Dependency:
path: pathlib.Path
destination: str
include: List[str] = field(default_factory=list)
exclude: List[str] = field(default_factory=list)
map: List[FileCopy] = listfield(FileCopy)
@dataclass
@jsonclass
class PackageAction:
filename: str
output_dir: pathlib.Path = field(default_factory=lambda: pathlib.Path(""))
include: List[str] = field(default_factory=list)
exclude: List[str] = field(default_factory=list)
map: List[FileCopy] = listfield(FileCopy)
dependencies: List[Dependency] = listfield(Dependency)
compression: Optional[str] = "DEFLATED"
@property
def compression_value(self) -> Optional[int]:
if self.compression is None:
return None
return getattr(zipfile, f"ZIP_{self.compression.upper()}")
@dataclass
@jsonclass
class BurstTarget:
platform: str
output: pathlib.Path
include: Optional[str] = None
safety_checks: Optional[bool] = None
fastmath: Optional[bool] = None
targets: Optional[List[str]] = None
enable_guard: Optional[bool] = None
float_precision: Optional[str] = None
float_mode: Optional[str] = None
debug: Optional[str] = None
debugMode: Optional[bool] = None
verbose: Optional[bool] = None
log_timings: Optional[bool] = None
root_assemblies: Optional[List[pathlib.Path]] = listfield(
pathlib.Path, optional=True
)
assembly_folders: Optional[List[pathlib.Path]] = listfield(
pathlib.Path, optional=True
)
include_root_assembly_references: Optional[bool] = None
def update(self, other: BurstTarget) -> None:
for f in fields(other):
value = getattr(other, f.name)
if value is None:
continue
setattr(self, f.name, value)
@dataclass
@jsonclass
class BurstCompileAction:
bcl: pathlib.Path
debug: bool = False
targets: List[BurstTarget] = listfield(BurstTarget)
@dataclass
@jsonclass
class Config:
root: pathlib.Path
build_props: pathlib.Path
post_build: PostBuildAction
replace: ReplaceAction
package: PackageAction
burst_compile: BurstCompileAction
variables: Dict[str, Union[str, int]] = field(default_factory=dict)
def __post_init__(self):
if not self.build_props.is_absolute():
self.build_props = self.root / self.build_props
def glob(
self, pattern: PathLike, root: Optional[PathLike] = None
) -> Generator[pathlib.Path, None, None]:
if root is None:
root = self.root
else:
root = pathlib.Path(root)
pattern = pathlib.Path(pattern).expanduser()
if pattern.is_absolute():
parts = pattern.parts
root = pathlib.Path(parts[0])
p = str(pathlib.Path(*parts[1:]))
else:
p = str(pattern)
return root.glob(p)
class JSONEncoder(json.JSONEncoder):
def default(self, o: Any):
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
if isinstance(o, pathlib.Path):
return str(o)
return super().default(o)