-
Notifications
You must be signed in to change notification settings - Fork 2
/
setup.py
2226 lines (1878 loc) · 73.9 KB
/
setup.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
'''
setup
=====
This is a relatively complicated setup script, since
it does a few things to simplify version control
and configuration files.
There's a simple script that overrides the `build_py`
command to ensure there's proper version control set
for the library.
There's also a more complex `configure` command
that configures all images from template files,
and also configures the `cmake` wrapper and the
shell version information.
'''
# IMPORTS
# -------
import ast
import enum
import glob
import itertools
import json
import re
import os
import setuptools
import shutil
import stat
import subprocess
import sys
import textwrap
try:
from setuptools import setup, Command
from setuptools.command.build_py import build_py
from setuptools.command.install import install
has_setuptools = True
except ImportError:
from distutils.core import setup, Command
from distutils.command.build_py import build_py
from distutils.command.install import install
has_setuptools = False
try:
import py2exe
except ImportError:
if len(sys.argv) >= 2 and sys.argv[1] == 'py2exe':
print('Cannot import py2exe', file=sys.stderr)
exit(1)
# CONFIG
# ------
def load_json(path):
'''Load JSON files with C++-style comments.'''
# Note: we need comments for maintainability, so we
# can annotate what works and the rationale, but
# we don't want to prevent code from working without
# a complex parser, so we do something very simple:
# only remove lines starting with '//'.
with open(path) as file:
lines = file.read().splitlines()
lines = [i for i in lines if not i.strip().startswith('//')]
return json.loads('\n'.join(lines))
HOME = os.path.dirname(os.path.realpath(__file__))
config = load_json(f'{HOME}/config/config.json')
# A lot of logic depends on being on the proper directory:
# this allows us to do out-of-source builds.
os.chdir(HOME)
def get_version(key):
'''Get the version data from the JSON config.'''
data = config[key]['version']
major = data['major']
minor = data['minor']
patch = data.get('patch', '')
release = data.get('release', '')
number = data.get('number', '')
build = data.get('build', '')
return (major, minor, patch, release, number, build)
# Read the xcross version information.
major, minor, patch, release, number, build = get_version('xcross')
version = f'{major}.{minor}'
if patch != '0':
version = f'{version}.{patch}'
release_type = {'alpha': 'a', 'beta': 'b', 'candidate': 'rc', 'post': '.post'}
if release and not number:
raise ValueError('Must provide a release number with a non-final build.')
elif release:
version = f'{version}{release_type[release]}{number}'
# py2exe version is valid one of the following:
# [0-255].[0-255].[0-65535]
# [0-255].[0-255].[0-255].[0-255]
# Therefore, we can never provide release candidate
# values or omit the patch field.
py2exe_version = f'{major}.{minor}.{patch}'
docker_major, docker_minor, docker_patch, docker_build, *_ = get_version('docker')
docker_version = f'{docker_major}.{docker_minor}'
if docker_patch != '0':
docker_version = f'{docker_version}.{docker_patch}'
# Read the dependency version information.
# This is the GCC and other utilities version from crosstool-NG.
ubuntu_major, ubuntu_minor, *_ = get_version('ubuntu')
ubuntu_version = f'{ubuntu_major}.{ubuntu_minor}'
emsdk_major, emsdk_minor, emsdk_patch, *_ = get_version('emsdk')
emsdk_version = f'{emsdk_major}.{emsdk_minor}.{emsdk_patch}'
gcc_major, gcc_minor, gcc_patch, *_ = get_version('gcc')
gcc_version = f'{gcc_major}.{gcc_minor}.{gcc_patch}'
binutils_major, binutils_minor, *_ = get_version('binutils')
binutils_version = f'{binutils_major}.{binutils_minor}'
mingw_major, mingw_minor, mingw_patch, *_ = get_version('mingw')
mingw_version = f'{mingw_major}.{mingw_minor}.{mingw_patch}'
glibc_major, glibc_minor, *_ = get_version('glibc')
glibc_version = f'{glibc_major}.{glibc_minor}'
musl_major, musl_minor, musl_patch, *_ = get_version('musl')
musl_version = f'{musl_major}.{musl_minor}.{musl_patch}'
musl_cross_major, musl_cross_minor, musl_cross_patch, *_ = get_version('musl-cross')
musl_cross_version = f'{musl_cross_major}.{musl_cross_minor}.{musl_cross_patch}'
avr_major, avr_minor, avr_patch, *_ = get_version('avr')
avr_version = f'{avr_major}.{avr_minor}.{avr_patch}'
uclibc_major, uclibc_minor, uclibc_patch, *_ = get_version('uclibc')
uclibc_version = f'{uclibc_major}.{uclibc_minor}.{uclibc_patch}'
expat_major, expat_minor, expat_patch, *_ = get_version('expat')
expat_version = f'{expat_major}.{expat_minor}.{expat_patch}'
isl_major, isl_minor, *_ = get_version('isl')
isl_version = f'{isl_major}.{isl_minor}'
linux_major, linux_minor, linux_patch, *_ = get_version('linux')
linux_version = f'{linux_major}.{linux_minor}.{linux_patch}'
linux_headers_major, linux_headers_minor, linux_headers_patch, *_ = get_version('linux-headers')
linux_headers_version = f'{linux_headers_major}.{linux_headers_minor}.{linux_headers_patch}'
gmp_major, gmp_minor, gmp_patch, *_ = get_version('gmp')
gmp_version = f'{gmp_major}.{gmp_minor}.{gmp_patch}'
mpc_major, mpc_minor, mpc_patch, *_ = get_version('mpc')
mpc_version = f'{mpc_major}.{mpc_minor}.{mpc_patch}'
mpfr_major, mpfr_minor, mpfr_patch, *_ = get_version('mpfr')
mpfr_version = f'{mpfr_major}.{mpfr_minor}.{mpfr_patch}'
buildroot_major, buildroot_minor, buildroot_patch, *_ = get_version('buildroot')
buildroot_version = f'{buildroot_major}.{buildroot_minor}.{buildroot_patch}'
ct_major, ct_minor, ct_patch, *_ = get_version('crosstool-ng')
ct_version = f'{ct_major}.{ct_minor}.{ct_patch}'
qemu_major, qemu_minor, qemu_patch, *_ = get_version('qemu')
qemu_version = f'{qemu_major}.{qemu_minor}.{qemu_patch}'
riscv_toolchain_version = config['riscv-gnu-toolchain']['riscv-version']
riscv_binutils_version = config['riscv-gnu-toolchain']['binutils-version']
riscv_gdb_version = config['riscv-gnu-toolchain']['gdb-version']
riscv_glibc_version = config['riscv-gnu-toolchain']['glibc-version']
riscv_newlib_version = config['riscv-gnu-toolchain']['newlib-version']
# Other config options.
bin_directory = f'{config["options"]["sysroot"]}/bin/'
# Read the long description.
description = 'Zero-setup cross compilation.'
with open(f'{HOME}/README.md') as file:
long_description = file.read()
# COMMANDS
# --------
# Literal boolean type for command arguments.
bool_type = (type(None), bool, int)
def parse_literal(inst, key, default, valid_types=None):
'''Parse literal user options.'''
value = getattr(inst, key)
if value != default:
value = ast.literal_eval(value)
if valid_types is not None:
assert isinstance(value, valid_types)
setattr(inst, key, value)
def check_call(code):
'''Wrap `subprocess.call` to exit on failure.'''
if code != 0:
sys.exit(code)
def has_module(module):
'''Check if the given module is installed.'''
devnull = subprocess.DEVNULL
code = subprocess.call(
[sys.executable, '-m', module, '--version'],
stdout=devnull,
stderr=devnull,
)
return code == 0
def semver():
'''Create a list of semantic versions for images.'''
versions = [
f'{docker_major}.{docker_minor}',
f'{docker_major}.{docker_minor}.{docker_patch}'
]
if docker_major != '0':
versions.append(docker_major)
return versions
def image_from_target(target, with_pkg=False):
'''Get the full image name from the target.'''
username = config['metadata']['username']
repository = config['metadata']['repository']
if with_pkg:
repository = f'pkg{repository}'
return f'{username}/{repository}:{target}'
def sorted_image_targets():
'''Get a sorted list of image targets.'''
# Need to write the total image list.
os_images = []
metal_images = []
other_images = []
for image in images:
if image.os.is_os():
os_images.append(image.target)
elif image.os.is_baremetal():
metal_images.append(image.target)
else:
other_images.append(image.target)
os_images.sort()
metal_images.sort()
other_images.sort()
return os_images + metal_images + other_images
def subslice_targets(start=None, stop=None):
'''Extract a subslice of all targets.'''
targets = sorted_image_targets()
if start is not None:
targets = targets[targets.index(start):]
if stop is not None:
targets = targets[:targets.index(stop) + 1]
return targets
def build_image(docker, target, with_pkg=False):
'''Call Docker to build a single target.'''
image = image_from_target(target, with_pkg)
image_dir = 'images'
if with_pkg:
image_dir = f'pkg{image_dir}'
path = f'{HOME}/docker/{image_dir}/Dockerfile.{target}'
return subprocess.call([docker, 'build', '-t', image, HOME, '--file', path])
class CleanDistCommand(Command):
'''A custom command to clean Python dist artifacts.'''
description = 'clean artifacts from previous python builds'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
'''Clean build data.'''
shutil.rmtree(f'{HOME}/build', ignore_errors=True)
shutil.rmtree(f'{HOME}/dist', ignore_errors=True)
shutil.rmtree(f'{HOME}/xcross.egg-info', ignore_errors=True)
# Clean py2exe files
dlls = glob.glob(f'{HOME}/*.dll')
exes = glob.glob(f'{HOME}/*.exe')
sos = glob.glob(f'{HOME}/*.so')
for file in dlls + exes + sos:
os.remove(file)
class CleanCommand(Command):
'''A custom command to clean any previous builds.'''
description = 'clean all previous builds'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
'''Clean build data.'''
self.run_command('clean_dist')
shutil.rmtree(f'{HOME}/cmake/toolchain', ignore_errors=True)
shutil.rmtree(f'{HOME}/docker/images', ignore_errors=True)
shutil.rmtree(f'{HOME}/docker/pkgimages', ignore_errors=True)
shutil.rmtree(f'{HOME}/musl/config', ignore_errors=True)
shutil.rmtree(f'{HOME}/symlink/toolchain', ignore_errors=True)
class VersionCommand(Command):
'''A custom command to configure the library version.'''
description = 'set library version'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def replace(self, string, replacements):
'''Replace template variable with value.'''
for variable, value in replacements:
string = string.replace(f'^{variable}^', value)
return string
def chmod(self, file):
'''Make a file executable.'''
flags = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
st = os.stat(file)
os.chmod(file, st.st_mode | flags)
def write_file(self, path, contents, chmod):
'''Check if we need to write a file.'''
try:
with open(path, 'r') as file:
old_contents = file.read()
should_update = old_contents != contents
except FileNotFoundError:
should_update = True
if should_update:
with open(path, 'w') as file:
file.write(contents)
if chmod:
self.chmod(path)
def configure(self, template, outfile, chmod, replacements):
'''Configure a template file.'''
with open(template, 'r') as file:
contents = file.read()
contents = self.replace(contents, replacements)
self.write_file(outfile, contents, chmod)
def run(self):
'''Modify the library version.'''
version_info = f"""
version_info(
major='{major}',
minor='{minor}',
patch='{patch}',
release='{release}',
number='{number}',
build='{build}'
)"""
xcross = f'{HOME}/xcross/__init__.py'
self.configure(f'{xcross}.in', xcross, True, [
('BIN', f'"{bin_directory}"'),
('REPOSITORY', config['metadata']['repository']),
('USERNAME', config['metadata']['username']),
('VERSION_MAJOR', f"'{major}'"),
('VERSION_MINOR', f"'{minor}'"),
('VERSION_PATCH', f"'{patch}'"),
('VERSION_RELEASE', f"'{release}'"),
('VERSION_NUMBER', f"'{number}'"),
('VERSION_BUILD', f"'{build}'"),
('VERSION_INFO', textwrap.dedent(version_info)[1:]),
('VERSION', f"'{version}'"),
])
class TagCommand(Command):
'''Scripts to automatically tag new versions.'''
description = 'tag version for release'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
'''Tag version for git release.'''
# Get our config.
git = shutil.which('git')
if not git:
raise FileNotFoundError('Unable to find program git.')
tag = f'v{version}'
# Delete any existing, conflicting tags.
devnull = subprocess.DEVNULL
env = os.environ.copy()
env['GIT_DIR'] = f'{HOME}/.git'
code = subprocess.call(
['git', 'rev-parse', tag],
stdout=devnull,
stderr=devnull,
env=env,
)
if code == 0:
check_call(subprocess.call(
['git', 'tag', '-d', tag],
stdout=devnull,
stderr=devnull,
))
# Tag the release.
check_call(subprocess.call(
['git', 'tag', tag],
stdout=devnull,
stderr=devnull,
))
class BuildImageCommand(Command):
'''Build a single Docker image.'''
description = 'build a single docker image'
user_options = [
('target=', None, 'Target name'),
('with-package-managers=', None, 'Build an image with package managers.'),
]
def initialize_options(self):
self.target = None
self.with_package_managers = None
def finalize_options(self):
assert self.target is not None
parse_literal(self, 'with_package_managers', None, bool_type)
def build_image(self, docker):
'''Build a Docker image.'''
if build_image(docker, self.target, self.with_package_managers) != 0:
print(f'Error: failed to build target {self.target}', file=sys.stderr)
sys.exit(1)
def run(self):
'''Build single Docker image.'''
docker = shutil.which('docker')
if not docker:
raise FileNotFoundError('Unable to find command docker.')
self.build_image(docker)
class BuildImagesCommand(Command):
'''Build all Docker images.'''
description = 'build all docker images'
user_options = [
('start=', None, 'Start point for images to build.'),
('stop=', None, 'Stop point for images to build.'),
('with-package-managers=', None, 'Build package manager images.'),
]
def initialize_options(self):
self.start = None
self.stop = None
self.with_package_managers = None
def finalize_options(self):
parse_literal(self, 'with_package_managers', None, bool_type)
def build_image(self, docker, target, with_package_managers=False):
'''Build a Docker image.'''
if build_image(docker, target, with_package_managers) != 0:
self.failures.append(target)
return False
return True
def tag_image(self, docker, target, tag_name, with_package_managers=False):
'''Tag an image.'''
image = image_from_target(target, with_package_managers)
tag = image_from_target(tag_name, with_package_managers)
check_call(subprocess.call([docker, 'tag', image, tag]))
def build_versions(self, docker, target, with_pkg=False):
'''Build all versions of a given target.'''
if not self.build_image(docker, target, with_pkg):
return
for version in semver():
self.tag_image(docker, target, f'{target}-{version}', with_pkg)
if target.endswith('-unknown-linux-gnu'):
self.tag_versions(docker, target, target[:-len('-unknown-linux-gnu')], with_pkg)
def tag_versions(self, docker, target, tag_name, with_pkg=False):
'''Build all versions of a given target.'''
self.tag_image(docker, target, tag_name, with_pkg)
for version in semver():
self.tag_image(docker, target, f'{tag_name}-{version}', with_pkg)
def run(self):
'''Build all Docker images.'''
docker = shutil.which('docker')
if not docker:
raise FileNotFoundError('Unable to find command docker.')
# Need to build our base vcpkg for package files.
if self.with_package_managers:
if build_image(docker, 'vcpkg', True) != 0:
print('Error: failed to build target vcpkg', file=sys.stderr)
sys.exit(1)
# Build all our Docker images.
self.failures = []
for target in subslice_targets(self.start, self.stop):
self.build_versions(docker, target)
# Only build if the previous image succeeded, and if
# the image with a package manager exists.
if self.failures and self.failures[-1] == target:
continue
elif not self.with_package_managers:
continue
if os.path.exists(f'{HOME}/docker/pkgimages/Dockerfile.{target}'):
self.build_versions(docker, target, with_pkg=True)
# Print any failures.
if self.failures:
print('Error: Failures occurred.', file=sys.stderr)
print('-------------------------', file=sys.stderr)
for failure in self.failures:
print(failure, file=sys.stderr)
sys.exit(1)
class BuildAllCommand(BuildImagesCommand):
'''Build Docker images and the Python library for dist.'''
description = 'build all docker images and wheels for release'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
'''Build all images and package for release.'''
BuildImagesCommand.run(self)
self.run_command('clean_dist')
self.run_command('configure')
self.run_command('build')
self.run_command('sdist')
self.run_command('bdist_wheel')
class BuildCommand(build_py):
'''Override build command to configure builds.'''
def run(self):
self.run_command('version')
build_py.run(self)
class InstallCommand(install):
'''Override install command to configure builds.'''
def run(self):
# Note: this should already be run, and this is redundant.
# However, if `skip_build` is provided, this needs to be run.
self.run_command('version')
install.run(self)
class PushCommand(Command):
'''Push all Docker images to Docker hub.'''
description = 'push all docker images to docker hub'
user_options = [
('start=', None, 'Start point for images to push.'),
('stop=', None, 'Stop point for images to push.'),
('with-package-managers=', None, 'Build package manager images.'),
]
def initialize_options(self):
self.start = None
self.stop = None
self.with_package_managers = None
def finalize_options(self):
parse_literal(self, 'with_package_managers', None, bool_type)
def push_image(self, docker, target, with_package_managers=False):
'''Push an image to Docker Hub.'''
image = image_from_target(target, with_package_managers)
check_call(subprocess.call([docker, 'push', image]))
def push_versions(self, docker, target, with_package_managers=False):
'''Push all versions of a given target.'''
self.push_image(docker, target, with_package_managers)
for version in semver():
self.push_image(docker, f'{target}-{version}', with_package_managers)
def push_target(self, docker, target, with_package_managers=False):
'''Push all images for a given target.'''
self.push_versions(docker, target, with_package_managers)
if target.endswith('-unknown-linux-gnu'):
base = target[:-len('-unknown-linux-gnu')]
self.push_versions(docker, base, with_package_managers)
def run(self):
'''Push all Docker images to Docker hub.'''
docker = shutil.which('docker')
if not docker:
raise FileNotFoundError('Unable to find command docker.')
# Push all our Docker images.
for target in subslice_targets(self.start, self.stop):
self.push_target(docker, target)
if not self.with_package_managers:
continue
if os.path.exists(f'{HOME}/docker/pkgimages/Dockerfile.{target}'):
self.push_target(docker, target, with_package_managers=True)
class PublishCommand(Command):
'''Publish a Python version.'''
description = 'publish python version to PyPi'
user_options = [
('test=', None, 'Upload to the test repository.'),
]
def initialize_options(self):
self.test = None
def finalize_options(self):
parse_literal(self, 'test', None, bool_type)
def run(self):
'''Run the unittest suite.'''
if not has_module('twine'):
raise FileNotFoundError('Unable to find module twine.')
self.run_command('clean_dist')
self.run_command('configure')
self.run_command('build')
self.run_command('sdist')
self.run_command('bdist_wheel')
files = glob.glob(f'{HOME}/dist/*')
command = [sys.executable, '-m', 'twine', 'upload']
if self.test:
command += ['--repository', 'testpypi']
command += files
check_call(subprocess.call(command))
class TestCommand(Command):
'''Run the unittest suite.'''
description = 'run unittest suite'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
'''Run the unittest suite.'''
if not has_module('tox'):
raise FileNotFoundError('Unable to find module tox.')
check_call(subprocess.call(['tox', HOME]))
class LintCommand(Command):
'''Lint python code.'''
description = 'lint python code'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
'''Run the unittest suite.'''
if not has_module('flake8'):
raise FileNotFoundError('Unable to find module flake8.')
self.run_command('configure')
check_call(subprocess.call(['flake8', HOME]))
class TestImagesCommand(Command):
'''Run the Docker test suite.'''
description = 'run docker test suite'
user_options = [
('start=', None, 'Start point for test suite.'),
('stop=', None, 'Stop point for test suite.'),
('os=', None, 'Do operating system tests tests.'),
('metal=', None, 'Do bare-metal tests.'),
]
metal_tests = [
'arm',
'arm64',
'avr',
'ppc',
'mips',
'mipsel',
'riscv32',
'riscv64',
('i686', 'x86'),
]
def initialize_options(self):
self.start = None
self.stop = None
self.os = True
self.metal = None
def finalize_options(self):
parse_literal(self, 'os', None, bool_type)
parse_literal(self, 'metal', None, bool_type)
def git_clone(self, git, repository):
'''Clone a given repository.'''
check_call(subprocess.call([git, 'clone', repository, f'{HOME}/buildtests']))
def run_test(
self,
docker,
target,
os_type,
script=None,
cpu=None,
**envvars
):
'''Run test for a single target.'''
# Get our command.
if script is None:
script = 'image-test'
command = f'/test/{script}.sh'
if cpu is not None:
command = f'export CPU={cpu}; {command}'
# Check for additional flags.
if self.nostartfiles(target):
flags = envvars.get('FLAGS')
if flags:
flags = f'{flags} -nostartfiles'
else:
flags = '-nostartfiles'
envvars['FLAGS'] = flags
# Build and call our docker command.
docker_command = [
docker,
'run',
'--name', f'xcross-test-{target}',
'-v', f'{HOME}/test:/test',
'--env', f'IMAGE={target}',
'--env', f'TYPE={os_type}',
]
for key, value in envvars.items():
docker_command += ['--env', f'{key}={value}']
docker_command.append(image_from_target(target))
docker_command += ['/bin/bash', '-c', command]
subprocess.check_call(docker_command)
# Clean up our stoppd container.
subprocess.check_call([docker, 'rm', f'xcross-test-{target}'])
def nostartfiles(self, target):
'''Check if an image does not have startfiles.'''
# i[3-6]86 does not provide start files, a known bug with newlib.
# moxie cannot find `__bss_start__` and `__bss_end__`.
# sparc cannot find `__stack`.
# there is no crt0 for x86_64
regex = re.compile(r'''^(?:
(?:i[3-7]86-unknown-elf)|
(?:moxie.*-none-elf)|
(?:sparc-unknown-elf)|
(?:x86_64-unknown-elf)
)$''', re.X)
return regex.match(target)
def skip(self, target):
'''Check if we should skip a given target.'''
# Check if we should skip a test.
# PPCLE is linked to the proper library, which contains the
# proper symbols, but still fails with an error:
# undefined reference to `_savegpr_29`.
return target == 'ppcle-unknown-elf'
def run_wasm(self, docker, **envvars):
'''Run a web-assembly target.'''
self.run_test(
docker,
'wasm',
'script',
**envvars,
NO_PERIPHERALS='1',
TOOLCHAIN1='jsonly',
TOOLCHAIN2='wasm',
TOOLCHAIN1_FLAGS='-s WASM=0',
TOOLCHAIN2_FLAGS='-s WASM=1',
)
def run_os(self, docker):
'''Run the tests with an operating system.'''
# Configure our test runner.
has_started = True
has_stopped = False
if self.start is not None:
has_started = False
metal_images = sorted([i.target for i in images if i.os.is_baremetal()])
os_images = sorted([i.target for i in images if i.os.is_os()])
# Run OS images.
testdir = f'{HOME}/test/buildtests'
shutil.copytree(f'{HOME}/test/cpp-helloworld', testdir, dirs_exist_ok=True)
try:
for target in os_images:
if has_started or self.start == target:
has_started = True
if not self.skip(target):
self.run_test(docker, target, 'os')
if self.stop == target:
has_stopped = True
break
# Run the special images.
if has_started and not has_stopped:
self.run_wasm(docker)
self.run_wasm(docker, CMAKE_FLAGS='-DJS_ONLY=1')
self.run_test(docker, os_images[0], 'os', CMAKE_FLAGS='-GNinja')
self.run_wasm(docker, CMAKE_FLAGS='-GNinja')
self.run_test(docker, 'ppc-unknown-linux-gnu', 'os', cpu='e500mc', NORUN2='1')
self.run_test(docker, 'ppc64-unknown-linux-gnu', 'os', cpu='power9')
self.run_test(docker, 'mips-unknown-linux-gnu', 'os', cpu='24Kf')
finally:
shutil.rmtree(testdir, ignore_errors=True)
if has_stopped:
return
# Run metal images.
shutil.copytree(f'{HOME}/test/cpp-atoi', testdir, dirs_exist_ok=True)
try:
for target in metal_images:
if has_started or self.start == target:
has_started = True
if not self.skip(target):
self.run_test(docker, target, 'metal')
if self.stop == target:
has_stopped = True
break
finally:
shutil.rmtree(testdir, ignore_errors=True)
if has_stopped:
return
def run_metal(self, docker):
'''Run the bare-metal tests.'''
for arch in self.metal_tests:
if isinstance(arch, tuple):
image = f'{arch[0]}-unknown-elf'
script = f'{arch[1]}-hw'
else:
image = f'{arch}-unknown-elf',
script = f'{arch}-hw'
self.run_test(docker, image, 'metal', script=script)
def run(self):
'''Run the docker test suite.'''
# Find our necessary commands.
docker = shutil.which('docker')
if not docker:
raise FileNotFoundError('Unable to find command docker.')
if self.os:
self.run_os(docker)
if self.metal:
self.run_metal(docker)
class TestAllCommand(TestImagesCommand):
'''Run the Python and Docker test suites.'''
def run(self):
'''Run the docker test suite.'''
self.run_command('test')
TestImagesCommand.run(self)
# IMAGES
# ------
# There are two types of images:
# 1). Images with an OS layer.
# 2). Bare-metal machines.
# Bare-metal machines don't use newlibs nanomalloc, so these do not
# support system allocators.
class OperatingSystem(enum.Enum):
'''Enumerations for known operating systems.'''
Android = enum.auto()
BareMetal = enum.auto()
Linux = enum.auto()
Emscripten = enum.auto()
Windows = enum.auto()
Unknown = enum.auto()
def is_baremetal(self):
return self == OperatingSystem.BareMetal
def is_emscripten(self):
return self == OperatingSystem.Emscripten
def is_os(self):
return (
self == OperatingSystem.Android
or self == OperatingSystem.Linux
or self == OperatingSystem.Windows
)
def to_cmake(self):
'''Get the identifier for the CMake system name.'''
return cmake_string[self]
def to_conan(self):
'''Get the identifier for the Conan system name.'''
return conan_string[self]
def to_meson(self):
'''Get the identifier for the Meson system name.'''
return meson_string[self]
def to_triple(self):
'''Get the identifier as a triple string.'''
return triple_string[self]
def to_vcpkg(self):
'''Get the identifier for the vcpkg system name.'''
return vcpkg_string[self]
@staticmethod
def from_triple(string):
'''Get the operating system from a triple string.'''
return triple_os[string]
cmake_string = {
OperatingSystem.Android: 'Android',
OperatingSystem.BareMetal: 'Generic',
# This gets ignored anyway.
OperatingSystem.Emscripten: 'Emscripten',
OperatingSystem.Linux: 'Linux',
OperatingSystem.Windows: 'Windows',
OperatingSystem.Unknown: 'Generic',
}
conan_string = {
# Conan uses CMake's feature detection for Android,
# which is famously broken. We have our custom toolchains
# to pass the proper build arguments. Just say Linux,
# and run with it.
OperatingSystem.Android: 'Linux',
OperatingSystem.Linux: 'Linux',
OperatingSystem.Windows: 'Windows',
}
meson_string = {
# The default use is just to use 'linux' for Android.
OperatingSystem.Android: 'linux',
OperatingSystem.BareMetal: 'bare metal',
OperatingSystem.Linux: 'linux',
OperatingSystem.Windows: 'windows',
}
triple_string = {
OperatingSystem.Android: 'linux',