-
Notifications
You must be signed in to change notification settings - Fork 3
/
check-deps
executable file
·319 lines (256 loc) · 8.56 KB
/
check-deps
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
#!/usr/bin/env python
from __future__ import annotations
import sys
import configparser
from dataclasses import dataclass, field
from typing import Optional, List, Mapping, Tuple, Callable, TypeVar
from enum import Enum
import asyncio
import re
from contextlib import contextmanager, redirect_stdout
import textwrap
import io
assert sys.version_info[0] == 3, "This script only works with Python 3."
class ConfigError(Exception):
pass
T = TypeVar("T")
def async_cache(f):
async def g(self, *args, **kwargs):
async with self._lock:
if self._done:
return self._result
self._result = await f(self, *args, **kwargs)
self._done = True
return self._result
return g
class Relation(Enum):
GE = 1
LE = 2
LT = 3
GT = 4
EQ = 5
NE = 6
def __str__(self):
return {
Relation.GE: ">=",
Relation.LE: "<=",
Relation.LT: "<",
Relation.GT: ">",
Relation.EQ: "==",
Relation.NE: "!="}[self]
@dataclass
class Version:
number: Tuple[int, ...]
extra: Optional[str]
def __lt__(self, other):
for n, m in zip(self.number, other.number):
if n < m:
return True
elif n > m:
return False
return False
def __gt__(self, other):
return other < self
def __le__(self, other):
for n, m in zip(self.number, other.number):
if n < m:
return True
elif n > m:
return False
return True
def __ge__(self, other):
return other <= self
def __eq__(self, other):
for n, m in zip(self.number, other.number):
if n != m:
return False
return True
def __ne__(self, other):
return not self == other
def __str__(self):
return ".".join(map(str, self.number)) + (self.extra or "")
@dataclass
class VersionConstraint:
version: Version
relation: Relation
def __call__(self, other: Version) -> bool:
method = f"__{self.relation.name}__".lower()
return getattr(other, method)(self.version)
def __str__(self):
return f"{self.relation}{self.version}"
def split_at(split_chars: str, x: str) -> Tuple[str, str]:
a = x.split(split_chars, maxsplit=1)
if len(a) == 2:
return a[0], a[1]
else:
return a[0], ""
def parse_split_f(split_chars: str, f: Callable[[str], T], x: str) \
-> Tuple[T, str]:
item, x = split_at(split_chars, x)
val = f(item)
return val, x
def parse_version(x: str) -> Tuple[Version, str]:
_x = x
number = []
extra = None
while True:
try:
n, _x = parse_split_f(".", int, _x)
number.append(n)
except ValueError:
if len(x) > 0:
m = re.match("([0-9]*)(.*)", _x)
if lastn := m and m.group(1):
number.append(int(lastn))
if suff := m and m.group(2):
extra = suff or None
else:
extra = _x
break
if not number:
raise ConfigError(f"A version needs a numeric component, got: {x}")
return Version(tuple(number), extra), _x
def parse_relation(x: str) -> Tuple[Relation, str]:
op_map = {
"<=": Relation.LE,
">=": Relation.GE,
"<": Relation.LT,
">": Relation.GT,
"==": Relation.EQ,
"!=": Relation.NE}
for sym, op in op_map.items():
if x.startswith(sym):
return (op, x[len(sym):])
raise ConfigError(f"Not a comparison operator: {x}")
def parse_version_constraint(x: str) -> Tuple[VersionConstraint, str]:
relation, x = parse_relation(x)
version, x = parse_version(x)
return VersionConstraint(version, relation), x
@dataclass
class Result:
test: VersionTest
success: bool
failure_text: Optional[str] = None
found_version: Optional[Version] = None
def __bool__(self):
return self.success
@dataclass
class VersionTest:
name: str
require: VersionConstraint
get_version: str
platform: Optional[str] = None
pattern: Optional[str] = None
suggestion_text: Optional[str] = None
suggestion: Optional[str] = None
depends: List[str] = field(default_factory=list)
template: Optional[str] = None
_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
_done: bool = False
def print_formatted(self, message):
output_prefix = f"{self.name} {self.require}"
print(f"{output_prefix:25}: {message}")
def print_not_found(self):
self.print_formatted("not found")
@async_cache
async def run(self, recurse):
for dep in self.depends:
if not await recurse(dep):
return Result(self, False,
failure_text=f"Failed dependency: {dep}")
proc = await asyncio.create_subprocess_shell(
self.get_version,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
(stdout, stderr) = await proc.communicate()
if proc.returncode != 0:
self.print_not_found()
return Result(
self,
success=False,
failure_text=f"{stderr.decode().strip()}")
try:
if self.pattern is not None:
m = re.match(self.pattern, stdout.decode())
if m is not None:
out, _ = parse_version(m.group(1).strip())
else:
self.print_not_found()
return Result(self, False, failure_text=f"No regex match on pattern '{self.pattern}'")
else:
out, _ = parse_version(stdout.decode().strip())
except ConfigError as e:
return Result(self, False, failure_text=str(e))
if self.require(out):
self.print_formatted(f"{str(out):10} Ok")
return Result(self, True)
else:
self.print_formatted(f"{str(out):10} Fail")
return Result(self, False, failure_text="Too old.",
found_version=out)
def parse_config(name: str, config: Mapping[str, str], templates):
if "template" in config:
_config = {}
for k, v in templates[config["template"]].items():
if isinstance(v, str):
_config[k] = v.format(name=name)
else:
_config[k] = v
_config.update(config)
else:
_config = dict(config)
_deps = map(str.strip, _config.get("depends", "").split(","))
deps = list(filter(lambda x: x != "", _deps))
assert "require" in _config, "Every item needs a `require` field"
assert "get_version" in _config, "Every item needs a `get_version` field"
require, _ = parse_version_constraint(_config["require"])
return VersionTest(
name=name,
require=require,
get_version=_config["get_version"],
platform=_config.get("platform", None),
pattern=_config.get("pattern", None),
suggestion_text=_config.get("suggestion_text", None),
suggestion=_config.get("suggestion", None),
depends=deps,
template=_config.get("template", None))
@contextmanager
def indent(prefix: str):
f = io.StringIO()
with redirect_stdout(f):
yield
output = f.getvalue()
print(textwrap.indent(output, prefix), end="")
async def main():
config = configparser.ConfigParser()
config.read("dependencies.ini")
templates = {
name[9:]: config[name]
for name in config if name.startswith("template:")
}
try:
tests = {
name: parse_config(name, config[name], templates)
for name in config if ":" not in name and name != "DEFAULT"
}
except (AssertionError, ConfigError) as e:
print("Configuration error:", e)
sys.exit(1)
async def test_version(name: str):
assert name in tests, f"unknown dependency {name}"
x = await tests[name].run(test_version)
return x
result = await asyncio.gather(*(test_version(k) for k in tests))
if all(r.success for r in result):
print("Success")
sys.exit(0)
else:
print("Failure")
with indent(" | "):
for r in (r for r in result if not r.success):
if r.failure_text:
print(f"{r.test.name}: {r.failure_text}")
if r.found_version:
print(f" found version {r.found_version}")
sys.exit(1)
asyncio.run(main())