-
Notifications
You must be signed in to change notification settings - Fork 16
/
tool.py
513 lines (421 loc) · 15.9 KB
/
tool.py
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
import argparse
import glob
import inspect
from itertools import chain
from os.path import basename, dirname, exists, join, relpath
from pathlib import Path, PurePosixPath
import posixpath
import pprint
import subprocess
import sys
import types
import re
from urllib.request import Request, urlopen
from urllib.error import HTTPError
from collections import defaultdict
import tomli
import tomli_w
from contextlib import suppress
from .setup import Setup
from .autowrap.generator_data import MissingReporter
from .command.util import get_build_temp_path
from . import overrides
from . import platforms
def get_setup() -> Setup:
s = Setup()
s.prepare()
temp_path = join(get_build_temp_path(), "dlstatic")
for static_lib in s.static_libs:
static_lib.set_root(temp_path)
return s
class BuildDep:
@classmethod
def add_subparser(cls, parent_parser, subparsers):
parser = subparsers.add_parser(
"build-dep", help="Install build dependencies", parents=[parent_parser]
)
parser.add_argument("--install", help="Actually do it", action="store_true")
parser.add_argument(
"--pre",
action="store_true",
default=False,
help="Include pre-release and development versions.",
)
parser.add_argument("--find-links", help="Find links arg", default=None)
return parser
def run(self, args):
s = get_setup()
requirements = s.pyproject.get("build-system", {}).get("requires", [])
requirements.extend(s.setup_kwargs.get("install_requires", ""))
requirements.append("wheel")
pipargs = [
sys.executable,
"-m",
"pip",
"--disable-pip-version-check",
"install",
]
if args.pre:
pipargs.append("--pre")
if args.find_links:
pipargs.extend(
[
"--find-links",
args.find_links,
]
)
pipargs.extend(requirements)
print(" ".join(pipargs))
if args.install:
p = subprocess.run(pipargs)
return p.returncode
class GenCreator:
@classmethod
def add_subparser(cls, parent_parser, subparsers):
parser = subparsers.add_parser(
"create-gen",
help="Create YAML files from parsed header files",
parents=[parent_parser],
)
parser.add_argument(
"--write", help="Write to files if they don't exist", action="store_true"
)
parser.add_argument("--strip-prefixes", action="append")
return parser
def run(self, args):
pfx = ""
if args.strip_prefixes:
pfx = "strip_prefixes:\n- " + "\n- ".join(args.strip_prefixes) + "\n\n"
s = get_setup()
for wrapper in s.wrappers:
reporter = MissingReporter()
wrapper.on_build_gen("", reporter)
nada = True
for name, report in reporter.as_yaml():
report = f"---\n\n{pfx}{report}"
nada = False
if args.write:
if not exists(name):
print("Writing", name)
with open(name, "w") as fp:
fp.write(report)
else:
print(name, "already exists!")
print("===", name, "===")
print(report)
if nada:
print("Nothing to do!")
class HeaderScanner:
@classmethod
def add_subparser(cls, parent_parser, subparsers):
parser = subparsers.add_parser(
"scan-headers",
help="Generate a list of headers in TOML form",
parents=[parent_parser],
)
parser.add_argument("--only-missing", default=False, action="store_true")
return parser
def run(self, args):
s = get_setup()
already_present = {}
if args.only_missing:
for i, wrapper in enumerate(s.project.wrappers.values()):
files = set()
if wrapper.autogen_headers:
files |= {Path(f) for f in wrapper.autogen_headers.values()}
if wrapper.type_casters:
files |= {Path(tc.header) for tc in wrapper.type_casters}
if not files:
continue
for incdir in s.wrappers[i]._generation_search_path():
ifiles = already_present.setdefault(incdir, set())
incdir = Path(incdir)
for f in files:
if (incdir / f).exists():
ifiles.add(f)
for wrapper in s.wrappers:
print(
f'[tool.robotpy-build.wrappers."{wrapper.package_name}".autogen_headers]'
)
# This uses the direct include directories instead of the generation
# search path as we only want to output a file once
for incdir in wrapper.get_include_dirs():
wpresent = already_present.get(incdir, set())
files = list(
sorted(
Path(relpath(f, incdir))
for f in chain(
glob.glob(join(incdir, "**", "*.h"), recursive=True),
glob.glob(join(incdir, "**", "*.hpp"), recursive=True),
)
if "rpygen" not in f
)
)
lastdir = None
for f in files:
if f in wpresent:
continue
thisdir = f.parent
if lastdir is None:
if thisdir:
print("#", thisdir)
elif lastdir != thisdir:
print()
if thisdir:
print("#", thisdir)
lastdir = thisdir
base = f.stem
print(f'{base} = "{f.as_posix()}"')
print()
class ImportCreator:
@classmethod
def add_subparser(cls, parent_parser, subparsers):
parser = subparsers.add_parser(
"create-imports",
help="Generate suitable imports for a module",
parents=[parent_parser],
)
parser.add_argument("base", help="Ex: wpiutil")
parser.add_argument("compiled", nargs="?", help="Ex: wpiutil._impl.wpiutil")
return parser
def _rel(self, base: str, compiled: str) -> str:
base = posixpath.join(*base.split("."))
compiled = posixpath.join(*compiled.split("."))
elems = posixpath.relpath(compiled, base).split("/")
elems = ["" if e == ".." else e for e in elems]
return f".{'.'.join(elems)}"
def run(self, args):
# Runtime Dependency Check
try:
import black
except:
print("Error, The following module is required to run this tool: black")
exit(1)
compiled = args.compiled
if not compiled:
compiled = f"{args.base}._{args.base.split('.')[-1]}"
# TODO: could probably generate this from parsed code, but seems hard
ctx = {}
exec(f"from {compiled} import *", {}, ctx)
for k in list(ctx.keys()):
if isinstance(ctx[k], types.ModuleType):
del ctx[k]
relimport = self._rel(args.base, compiled)
stmt_compiled = "" if not args.compiled else f" {args.compiled}"
stmt = inspect.cleandoc(
f"""
# autogenerated by 'robotpy-build create-imports {args.base}{stmt_compiled}'
from {relimport} import {','.join(sorted(ctx.keys()))}
__all__ = ["{'", "'.join(sorted(ctx.keys()))}"]
"""
)
print(
subprocess.check_output(
["black", "-", "-q"], input=stmt.encode("utf-8")
).decode("utf-8")
)
class PlatformInfo:
@classmethod
def add_subparser(cls, parent_parser, subparsers):
parser = subparsers.add_parser(
"platform-info",
help="Displays platform-specific information",
parents=[parent_parser],
)
parser.add_argument("--list", action="store_true", default=False)
parser.add_argument("platform", nargs="?", default=None)
return parser
def run(self, args):
if args.list:
for name in platforms.get_platform_names():
print(name)
else:
p = platforms.get_platform(args.platform)
print("platform:")
pprint.pprint(p)
print()
print("override keys:")
pprint.pprint(platforms.get_platform_override_keys(p))
class ShowOverrides:
@classmethod
def add_subparser(cls, parent_parser, subparsers):
parser = subparsers.add_parser(
"show-override",
help="Displays pyproject.toml after override processing",
parents=[parent_parser],
)
parser.add_argument("toml", nargs="?", default="pyproject.toml")
parser.add_argument(
"-p",
"--platform",
default=None,
help="Use robotpy-build platform-info --list for available platforms",
)
return parser
def run(self, args):
p = platforms.get_platform(args.platform)
override_keys = platforms.get_platform_override_keys(p)
with open(args.toml, "rb") as fp:
d = tomli.load(fp)
overrides.apply_overrides(d, override_keys)
print(tomli_w.dumps(d))
class MavenParser:
after_archs = [
"static",
"debug",
"staticdebug",
]
@classmethod
def add_subparser(cls, parent_parser, subparsers):
parser = subparsers.add_parser(
"parse-maven",
help="Find supported platforms from a pyproject.toml",
parents=[parent_parser],
)
parser.add_argument(
"toml_link",
help="Ex: pyproject.toml",
)
parser.add_argument(
"-b",
"--brute_force",
action="store_true",
help="Try known os and arch combinations instead of parsing html (needed for rev)",
)
return parser
def check_url_exists(self, file_url):
with suppress(Exception):
if urlopen(Request(file_url)).code == 200:
return True
return False
def run(self, args):
self.os_names = set()
self.arch_names = set()
for plat in platforms._platforms.values():
self.os_names.add(plat.os)
self.arch_names.add(plat.arch)
with open(args.toml_link, "rb") as fp:
config = tomli.load(fp)["tool"]["robotpy-build"]
wrappers = {}
if "wrappers" in config:
wrappers = {
k: v
for (k, v) in config["wrappers"].items()
if "maven_lib_download" in v
}
static_libs = {}
if "static_libs" in config:
static_libs = {
k: v
for (k, v) in config["static_libs"].items()
if "maven_lib_download" in v
}
if wrappers == {} and static_libs == {}:
print("No maven_lib_downloads in pyproject.toml")
exit()
for w_name, wrapper in {**wrappers, **static_libs}.items():
if "maven_lib_download" not in wrapper:
continue
mvl = wrapper["maven_lib_download"]
repo_url = mvl["repo_url"]
grp = mvl["group_id"].replace(".", "/")
art = mvl["artifact_id"]
ver = mvl["version"]
dir_url = f"{repo_url}/{grp}/{art}/{ver}/"
plats = defaultdict(set)
found_source = False
source_name = None
if args.brute_force:
for os in self.os_names:
for arch in self.arch_names:
for after_arch in self.after_archs + [""]:
classifier = os + arch + after_arch
file_url = f"{dir_url}{art}-{ver}-{classifier}.zip"
if self.check_url_exists(file_url):
plats[os].add(arch)
if self.check_url_exists(f"{dir_url}{art}-{ver}-source.zip"):
found_source = True
source_name = "source"
if self.check_url_exists(f"{dir_url}{art}-{ver}-sources.zip"):
found_source = True
source_name = "sources"
else:
try:
html = str(urlopen(Request(dir_url)).read())
except HTTPError as e:
if e.code != 404:
raise e
else:
print(
"The repo url returned a 404 error. Try using the brute_force flag."
)
exit()
found_source = False
source_name = None
if "source.zip" in html:
found_source = True
source_name = "source"
if "sources.zip" in html:
found_source = True
source_name = "sources"
# matches = re.findall('\.zip">(.*?)\.zip</a>', html, re.I) # match on text
matches = re.findall('href="(.*?)">', html, re.I) # match on links
matches = [
m[:-4] for m in matches if m[-4:] == ".zip"
] # match on zip files and remove extension
for m in matches:
for os in self.os_names:
idx = m.find(os)
if idx != -1:
arch = m[idx + len(os) :]
for after_arch in self.after_archs:
arch = arch.replace(after_arch, "")
plats[os].add(arch)
break
# Formatting
print()
print(f"Wrapper / static_lib :: {w_name}")
print(f"Artifact ID :: {art}")
print(f"URL :: {dir_url}")
print()
if found_source:
print("This repo appears to provide sources.")
print("The name of the source file is:", source_name)
print()
plat_str = "supported_platforms = [\n"
for os in plats:
for arch in plats[os]:
plat_str += ' {{ os = "{}", arch = "{}" }},\n'.format(
os, arch
)
plat_str += "]"
print(plat_str)
def main():
parser = argparse.ArgumentParser(prog="robotpy-build")
parent_parser = argparse.ArgumentParser(add_help=False)
subparsers = parser.add_subparsers(dest="cmd")
subparsers.required = True
for cls in (
BuildDep,
GenCreator,
HeaderScanner,
ImportCreator,
PlatformInfo,
ShowOverrides,
MavenParser,
):
cls.add_subparser(parent_parser, subparsers).set_defaults(cls=cls)
args = parser.parse_args()
cmd = args.cls()
retval = cmd.run(args)
if retval is False:
retval = 1
elif retval is True:
retval = 0
elif isinstance(retval, int):
pass
else:
retval = 0
exit(retval)
if __name__ == "__main__":
main()