forked from swiftlang/swift-source-compat-suite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
project.py
1634 lines (1437 loc) · 66.2 KB
/
project.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 python3
# ===--- project.py -------------------------------------------------------===
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ===----------------------------------------------------------------------===
"""A library containing common project building functionality."""
import multiprocessing
import os
import platform
import re
import shutil
import filecmp
import sys
import json
import time
import argparse
import shlex
from concurrent import futures
from enum import Enum
import common
swift_branch = None
def set_swift_branch(branch):
"""Configure the library for a specific branch.
>>> set_swift_branch('main')
"""
global swift_branch
swift_branch = branch
common.set_swift_branch(branch)
class TimeReporter(object):
def __init__(self, file_path):
self._file_path = file_path
self._time_data = {}
def update(self, project, elapsed):
self._time_data[project + '.compile_time'] = elapsed
def __del__(self):
if self._file_path and self._time_data:
with open(self._file_path, 'w+') as f:
json.dump(self._time_data, f)
class ProjectTarget(object):
"""An abstract project target."""
def get_build_command(self, incremental=False):
"""Return a command that builds the project target."""
raise NotImplementedError
def get_test_command(self, incremental=False):
"""Return a command that tests the project target."""
raise NotImplementedError
def build(self, sandbox_profile, stdout=sys.stdout, stderr=sys.stderr,
incremental=False):
"""Build the project target."""
return common.check_execute(self.get_build_command(incremental=incremental),
sandbox_profile=sandbox_profile,
stdout=stdout, stderr=stdout)
def test(self, sandbox_profile, stdout=sys.stdout, stderr=sys.stderr,
incremental=False):
"""Test the project target."""
return common.check_execute(self.get_test_command(incremental=incremental),
sandbox_profile=sandbox_profile,
stdout=stdout, stderr=stdout)
class XcodeTarget(ProjectTarget):
"""An Xcode workspace scheme."""
def __init__(self, swiftc, project, target, destination, pretargets, env,
added_xcodebuild_flags, is_workspace, has_scheme,
clean_build,
stdout,
stderr):
self._swiftc = swiftc
self._project = project
self._target = target
self._destination = destination
self._pretargets = pretargets
self._env = env
self._added_xcodebuild_flags = added_xcodebuild_flags
self._is_workspace = is_workspace
self._has_scheme = has_scheme
self._clean_build = clean_build
self.stdout = stdout,
self.stderr = stderr
@property
def project_param(self):
if self._is_workspace:
return '-workspace'
return '-project'
@property
def target_param(self):
if self._has_scheme:
return '-scheme'
return '-target'
def get_build_command(self, incremental=False):
project_param = self.project_param
target_param = self.target_param
try:
build_parent_dir = common.check_execute_output([
'git', '-C', os.path.dirname(self._project),
'rev-parse', '--show-toplevel'],
stdout=self.stdout,
stderr=self.stderr,
).rstrip()
except common.ExecuteCommandFailure as error:
build_parent_dir = os.path.dirname(self._project)
build_dir = os.path.join(build_parent_dir, 'build')
build = []
if self._clean_build and not incremental and not self._pretargets:
build += ['clean']
build += ['build']
dir_override = []
if self._has_scheme:
dir_override += ['-derivedDataPath', build_dir]
elif 'SYMROOT' not in self._env:
dir_override += ['SYMROOT=' + build_dir]
dir_override += [f"{k}={v}" for k, v in self._env.items()]
command = (['xcodebuild']
+ build
+ [project_param, self._project,
target_param, self._target,
'-destination', self._destination]
+ dir_override
+ ['CODE_SIGN_IDENTITY=',
'CODE_SIGNING_REQUIRED=NO',
'ENTITLEMENTS_REQUIRED=NO',
'ENABLE_BITCODE=NO',
'INDEX_ENABLE_DATA_STORE=NO',
'GCC_TREAT_WARNINGS_AS_ERRORS=NO',
'SWIFT_TREAT_WARNINGS_AS_ERRORS=NO'])
command += self._added_xcodebuild_flags
if self._destination == 'generic/platform=watchOS':
command += ['ARCHS=armv7k']
if self._destination == 'generic/platform=iOS':
command += ['EXCLUDED_ARCHS=armv7 armv7s']
return command
def get_prebuild_command(self, incremental=False):
project_param = self.project_param
target_param = self.target_param
try:
build_parent_dir = common.check_execute_output([
'git', '-C', os.path.dirname(self._project),
'rev-parse', '--show-toplevel'],
stdout=self.stdout,
stderr=self.stderr,
).rstrip()
except common.ExecuteCommandFailure as error:
build_parent_dir = os.path.dirname(self._project)
build_dir = os.path.join(build_parent_dir, 'build')
build = []
if self._clean_build and not incremental:
build += ['clean']
if self._pretargets:
build += ['build']
dir_override = []
if self._has_scheme:
dir_override += ['-derivedDataPath', build_dir]
elif not 'SYMROOT' in self._env:
dir_override += ['SYMROOT=' + build_dir]
dir_override += [f"{k}={v}" for k, v in self._env.items()]
project_target_params = [project_param, self._project,
'-destination', self._destination]
for pretarget in self._pretargets:
project_target_params += [target_param, pretarget]
command = (['xcodebuild']
+ build
+ project_target_params
+ dir_override
+ ['CODE_SIGN_IDENTITY=',
'CODE_SIGNING_REQUIRED=NO',
'ENTITLEMENTS_REQUIRED=NO',
'ENABLE_BITCODE=NO',
'INDEX_ENABLE_DATA_STORE=NO',
'GCC_TREAT_WARNINGS_AS_ERRORS=NO',
'SWIFT_TREAT_WARNINGS_AS_ERRORS=NO'])
command += self._added_xcodebuild_flags
if self._destination == 'generic/platform=watchOS':
command += ['ARCHS=armv7k']
return command
def get_test_command(self, incremental=False):
project_param = self.project_param
target_param = self.target_param
test = ['clean', 'test']
if incremental:
test = ['test']
command = (['xcodebuild']
+ test
+ [project_param, self._project,
target_param, self._target,
'-destination', self._destination,
# TODO: stdlib search code
'SWIFT_LIBRARY_PATH=%s' %
get_stdlib_platform_path(
self._swiftc,
self._destination)]
+ ['INDEX_ENABLE_DATA_STORE=NO',
'GCC_TREAT_WARNINGS_AS_ERRORS=NO'])
command += self._added_xcodebuild_flags
return command
def build(self, sandbox_profile, stdout=sys.stdout, stderr=sys.stderr,
incremental=False, time_reporter=None):
"""Build the project target."""
if self._pretargets:
common.check_execute(self.get_prebuild_command(incremental=incremental),
sandbox_profile=sandbox_profile,
stdout=stdout, stderr=stdout)
start_time = None
if time_reporter:
start_time = time.time()
returncode = common.check_execute(self.get_build_command(incremental=incremental),
sandbox_profile=sandbox_profile,
stdout=stdout, stderr=stdout)
if returncode == 0 and time_reporter:
elapsed = time.time() - start_time
time_reporter.update(self._target, elapsed)
return returncode
def get_stdlib_platform_path(swiftc, destination):
"""Return the corresponding stdlib name for a destination."""
platform_stdlib_path = {
'macOS': 'macosx',
'iOS': 'iphonesimulator',
'tvOS': 'appletvsimulator',
'watchOS': 'watchsimulator',
}
stdlib_dir = None
for platform_key in platform_stdlib_path:
if platform_key in destination:
stdlib_dir = platform_stdlib_path[platform_key]
break
assert stdlib_dir is not None
stdlib_path = os.path.join(os.path.dirname(os.path.dirname(swiftc)),
'lib/swift/' + stdlib_dir)
return stdlib_path
def clean_swift_package(path, swiftc, sandbox_profile,
stdout=sys.stdout, stderr=sys.stderr):
"""Clean a Swift package manager project."""
swift = os.path.join(os.path.dirname(swiftc), 'swift')
if swift_branch == 'swift-3.0-branch':
command = [swift, 'build', '-C', path, '--clean']
else:
command = [swift, 'package', '--package-path', path, 'clean']
if (swift_branch not in ['swift-3.0-branch',
'swift-3.1-branch']):
command.insert(2, '--disable-sandbox')
return common.check_execute(command, sandbox_profile=sandbox_profile,
stdout=stdout, stderr=stderr)
def build_swift_package(path, swiftc, swift_version, configuration,
sandbox_profile, stdout=sys.stdout, stderr=sys.stderr,
added_swift_flags=None,
incremental=False,
override_swift_exec=None,
build_tests=False):
"""Build a Swift package manager project."""
swift = os.path.join(os.path.dirname(swiftc), 'swift')
if not incremental:
clean_swift_package(path, swiftc, sandbox_profile,
stdout=stdout, stderr=stderr)
env = os.environ
env['DYLD_LIBRARY_PATH'] = get_stdlib_platform_path(swiftc, 'macOS')
env['SWIFT_EXEC'] = override_swift_exec or swiftc
command = [swift, 'build', '--package-path', path, '--verbose',
'--configuration', configuration]
if (swift_branch not in ['swift-3.0-branch',
'swift-3.1-branch']):
command.insert(2, '--disable-sandbox')
if build_tests:
command += ['--build-tests']
if sys.platform == "linux":
command += ['--enable-test-discovery']
added_swift_flags += ' -enable-testing'
if swift_version:
if '.' not in swift_version:
swift_version += '.0'
major, minor = swift_version.split('.', 1)
# Need to use float for minor version parsing
# because it's possible that it would be specified
# as e.g. `4.0.3`
if int(major) == 4 and float(minor) == 2.0:
command += ['-Xswiftc', '-swift-version', '-Xswiftc', swift_version]
else:
command += ['-Xswiftc', '-swift-version', '-Xswiftc', major]
if added_swift_flags is not None:
for flag in added_swift_flags.split():
command += ["-Xswiftc", flag]
return common.check_execute(command, timeout=3600,
sandbox_profile=sandbox_profile,
stdout=stdout, stderr=stderr,
env=env)
def test_swift_package(path, swiftc, sandbox_profile,
stdout=sys.stdout, stderr=sys.stderr,
added_swift_flags=None,
incremental=False,
override_swift_exec=None):
"""Test a Swift package manager project."""
swift = os.path.join(os.path.dirname(swiftc), 'swift')
if not incremental:
clean_swift_package(path, swiftc, sandbox_profile)
env = os.environ
env['SWIFT_EXEC'] = override_swift_exec or swiftc
command = [swift, 'test', '-C', path, '--verbose']
if added_swift_flags is not None:
for flag in added_swift_flags.split():
command += ["-Xswiftc", flag]
if (swift_branch not in ['swift-3.0-branch',
'swift-3.1-branch']):
command.insert(2, '--disable-sandbox')
return common.check_execute(command, timeout=3600,
sandbox_profile=sandbox_profile,
stdout=stdout, stderr=stderr,
env=env)
def checkout(root_path, repo, commit):
"""Checkout an indexed repository."""
path = os.path.join(root_path, repo['path'])
if repo['repository'] == 'Git':
if os.path.exists(path):
return common.git_update(repo['url'], commit, path)
else:
return common.git_clone(repo['url'], path, tree=commit)
raise common.Unreachable('Unsupported repository: %s' %
repo['repository'])
def strip_resource_phases(repo_path, stdout=sys.stdout, stderr=sys.stderr):
"""Strip resource build phases from a given project."""
command = ['perl', '-i', '-00ne',
'print unless /Begin PBXResourcesBuildPhase/']
for root, dirs, files in os.walk(repo_path):
for filename in files:
if filename == 'project.pbxproj':
pbxfile = os.path.join(root, filename)
common.check_execute(command + [pbxfile],
stdout=stdout, stderr=stderr)
def dispatch(root_path, repo, action, swiftc, swift_version,
sandbox_profile_xcodebuild, sandbox_profile_package,
added_swift_flags, added_xcodebuild_flags,
build_config, should_strip_resource_phases=False,
stdout=sys.stdout, stderr=sys.stderr,
incremental=False, time_reporter = None, override_swift_exec=None):
"""Call functions corresponding to actions."""
substitutions = action.copy()
substitutions.update(repo)
if added_swift_flags:
# Support added swift flags specific to the current repository and
# action by passing their fields as keyword arguments to format, e.g.
# so that {path} in '-index-store-path /tmp/index/{path}' is replaced
# with the value of repo's path field.
added_swift_flags = added_swift_flags.format(**substitutions)
if added_xcodebuild_flags:
added_xcodebuild_flags = \
shlex.split(added_xcodebuild_flags.format(**substitutions))
else:
added_xcodebuild_flags = []
if action['action'] == 'BuildSwiftPackage':
if not build_config:
build_config = action['configuration']
build_tests = (action.get('build_tests') == 'true' and build_config == 'debug') \
or (action.get('build_tests_release') and build_config == 'release')
return build_swift_package(os.path.join(root_path, repo['path']),
swiftc, swift_version,
build_config,
sandbox_profile_package,
stdout=stdout, stderr=stderr,
added_swift_flags=added_swift_flags,
incremental=incremental,
override_swift_exec=override_swift_exec,
build_tests=build_tests)
elif action['action'] == 'TestSwiftPackage':
return test_swift_package(os.path.join(root_path, repo['path']),
swiftc,
sandbox_profile_package,
stdout=stdout, stderr=stderr,
added_swift_flags=added_swift_flags,
incremental=incremental,
override_swift_exec=override_swift_exec)
elif re.match(r'^(Build|Test)Xcode(Workspace|Project)(Scheme|Target)$',
action['action']):
match = re.match(
r'^(Build|Test)Xcode(Workspace|Project)(Scheme|Target)$',
action['action']
)
initial_xcodebuild_flags = ['SWIFT_EXEC=%s' % (override_swift_exec or swiftc),
'-IDEPackageSupportDisableManifestSandbox=YES']
if build_config == 'debug':
initial_xcodebuild_flags += ['-configuration', 'Debug']
elif build_config == 'release':
initial_xcodebuild_flags += ['-configuration', 'Release']
elif 'configuration' in action:
initial_xcodebuild_flags += ['-configuration',
action['configuration']]
build_env = {}
if 'environment' in action:
build_env = action['environment']
pretargets = []
if 'pretargets' in action:
pretargets = action['pretargets']
other_swift_flags = []
if swift_version:
if '.' not in swift_version:
swift_version += '.0'
major, minor = swift_version.split('.', 1)
# Need to use float for minor version parsing
# because it's possible that it would be specified
# as e.g. `4.0.3`
if int(major) == 4 and float(minor) == 2.0:
other_swift_flags += ['-swift-version', swift_version]
initial_xcodebuild_flags += ['SWIFT_VERSION=%s' % swift_version]
else:
other_swift_flags += ['-swift-version', major]
initial_xcodebuild_flags += ['SWIFT_VERSION=%s' % major]
if added_swift_flags:
other_swift_flags.append(added_swift_flags)
if other_swift_flags:
other_swift_flags = ['$(OTHER_SWIFT_FLAGS)'] + other_swift_flags
initial_xcodebuild_flags += ['OTHER_SWIFT_FLAGS=%s' % ' '.join(other_swift_flags)]
is_workspace = match.group(2).lower() == 'workspace'
project_path = os.path.join(root_path, repo['path'],
action[match.group(2).lower()])
has_scheme = match.group(3).lower() == 'scheme'
clean_build = True
if 'clean_build' in action:
clean_build = action['clean_build']
xcode_target = \
XcodeTarget(swiftc,
project_path,
action[match.group(3).lower()],
action['destination'],
pretargets,
build_env,
initial_xcodebuild_flags + added_xcodebuild_flags,
is_workspace,
has_scheme,
clean_build,
stdout,
stderr)
if should_strip_resource_phases:
strip_resource_phases(os.path.join(root_path, repo['path']),
stdout=stdout, stderr=stderr)
if match.group(1) == 'Build':
return xcode_target.build(sandbox_profile_xcodebuild,
stdout=stdout, stderr=stderr,
incremental=incremental,
time_reporter=time_reporter)
else:
return xcode_target.test(sandbox_profile_xcodebuild,
stdout=stdout, stderr=stderr,
incremental=incremental)
else:
raise common.Unimplemented("Unknown action: %s" % action['action'])
def is_xfailed(xfail_args, compatible_version, platform, swift_branch, build_config, job_type):
"""Return whether the specified swift version/platform/branch/configuration/job is xfailed."""
if isinstance(xfail_args, dict):
xfail_args = [xfail_args]
def is_or_contains(spec, arg):
return arg in spec if isinstance(spec, list) else spec == arg
def matches(spec):
issue = spec['issue'].split()[0]
current = {
'compatibility': compatible_version,
'branch': swift_branch,
'platform': platform,
'job': job_type,
}
if 'configuration' in spec:
if build_config is None:
raise common.Unreachable("'xfail' entry contains 'configuration' "
"but none supplied via '--build-config' or the containing "
"action's 'configuration' field.")
current['configuration'] = build_config.lower()
for key, value in current.items():
if key in spec and not is_or_contains(spec[key], value):
return None
return issue
for spec in xfail_args:
issue = matches(spec)
if issue is not None:
return issue
return None
def str2bool(s):
"""Convert an argument string into a boolean."""
if s.lower() == 'true':
return True
elif s.lower() == 'false':
return False
else:
raise argparse.ArgumentTypeError('true/false boolean value expected.')
def add_arguments(parser):
"""Add common arguments to parser."""
parser.register('type', 'bool', str2bool)
parser.add_argument('--verbose',
action='store_true')
# TODO: remove Linux sandbox hack
if platform.system() == 'Darwin':
parser.add_argument('--swiftc',
metavar='PATH',
help='swiftc executable',
required=True,
type=os.path.abspath)
parser.add_argument('--override-swift-exec',
metavar='PATH',
help='override the SWIFT_EXEC that is used to build the projects',
type=os.path.abspath)
else:
parser.add_argument('--swiftc',
metavar='PATH',
help='swiftc executable',
required=True)
parser.add_argument('--override-swift-exec',
metavar='PATH',
help='override the SWIFT_EXEC that is used to build the projects')
parser.add_argument('--projects',
metavar='PATH',
required=True,
help='JSON project file',
type=os.path.abspath)
parser.add_argument('--swift-version',
metavar='VERS',
help='Swift version mode (default: None)')
parser.add_argument('--include-repos',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to include a repo '
'(example: \'path == "Alamofire"\')')
parser.add_argument('--exclude-repos',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to exclude a repo '
'(example: \'path == "Alamofire"\')')
parser.add_argument('--include-versions',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to include a Swift version '
'(example: '
'\'version == "3.0"\')')
parser.add_argument('--exclude-versions',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to exclude a Swift version '
'(example: '
'\'version == "3.0"\')')
parser.add_argument('--include-actions',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to include an action '
'(example: '
'\'action == "BuildXcodeWorkspaceScheme"\')')
parser.add_argument('--exclude-actions',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to exclude an action '
'(example: '
'\'action == "BuildXcodeWorkspaceScheme"\')')
parser.add_argument('--swift-branch',
metavar='BRANCH',
help='Swift branch configuration to use',
default='main')
parser.add_argument('--sandbox-profile-xcodebuild',
metavar='FILE',
help='sandbox xcodebuild build and test operations '
'with profile',
type=os.path.abspath)
parser.add_argument('--sandbox-profile-package',
metavar='FILE',
help='sandbox package build and test operations with '
'profile',
type=os.path.abspath)
parser.add_argument("--test-incremental",
help='test incremental-mode over multiple commits',
action='store_true')
parser.add_argument("--add-swift-flags",
metavar="FLAGS",
help='add flags to each Swift invocation (note: field '
'names from projects.json enclosed in {} will be '
'replaced with their value)',
default='')
parser.add_argument("--add-xcodebuild-flags",
metavar="FLAGS",
help='add flags to each xcodebuild invocation (note: field '
'names from projects.json enclosed in {} will be '
'replaced with their value)',
default='')
parser.add_argument("--skip-clean",
help='skip all git and build clean steps before '
'building projects',
action='store_true'),
parser.add_argument("--build-config",
metavar="NAME",
choices=['debug', 'release'],
dest='build_config',
help='specify "debug" or "release" to override '
'the build configuration in the projects.json file')
parser.add_argument("--strip-resource-phases",
help='strip all resource phases from project file '
'before building (default: true)',
metavar='BOOL',
type='bool',
nargs='?',
const=True,
default=True)
parser.add_argument("--project-cache-path",
help='Path of the dir where all the project binaries will be placed',
metavar='PATH',
type=os.path.abspath,
default='project_cache')
parser.add_argument("--report-time-path",
help='export time for building each xcode build target to the specified json file',
type=os.path.abspath)
parser.add_argument("--clang",
help='clang executable to build Xcode projects',
type=os.path.abspath)
parser.add_argument("--job-type",
help="The type of job to run. This influences which projects are XFailed, for example the stress tester tracks its XFails under a different job type. Defaults to 'source-compat'.",
default='source-compat')
parser.add_argument('--process-count',
type=int,
help='Number of parallel process to spawn when building projects',
default=multiprocessing.cpu_count())
parser.add_argument('--junit',
action='store_true',
help='Write a junit.xml file containing the project build results')
def add_minimal_arguments(parser):
"""Add common arguments to parser."""
parser.add_argument('--verbose',
action='store_true')
parser.add_argument('--projects',
metavar='PATH',
required=True,
help='JSON project file',
type=os.path.abspath)
parser.add_argument('--include-repos',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to include a repo '
'(example: \'path == "Alamofire"\')')
parser.add_argument('--exclude-repos',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to exclude a repo '
'(example: \'path == "Alamofire"\')')
parser.add_argument('--include-versions',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to include a Swift version '
'(example: '
'\'version == "3.0"\')')
parser.add_argument('--exclude-versions',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to exclude a Swift version '
'(example: '
'\'version == "3.0"\')')
parser.add_argument('--include-actions',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to include an action '
'(example: '
'\'action == "BuildXcodeWorkspaceScheme"\')')
parser.add_argument('--exclude-actions',
metavar='PREDICATE',
default=[],
action='append',
help='a Python predicate to determine '
'whether to exclude an action '
'(example: '
'\'action == "BuildXcodeWorkspaceScheme"\')')
parser.add_argument('--swift-branch',
metavar='BRANCH',
help='Swift branch configuration to use',
default='main')
def evaluate_predicate(element, predicate):
"""Evaluate predicate in context of index element fields."""
# pylint: disable=I0011,W0122,W0123
for key in element:
if isinstance(element[key], str):
exec(key + ' = """' + element[key] + '"""')
return eval(predicate)
def included_element(include_predicates, exclude_predicates, element):
"""Return whether an index element should be included."""
return (not any(evaluate_predicate(element, ep)
for ep in exclude_predicates) and
(include_predicates == [] or
any(evaluate_predicate(element, ip)
for ip in include_predicates)))
class FactoryBuilder:
"""Class used by a Factory to encapsulate the class needed to build + the arguments.
This allows the Factory to be pickle-able"""
def __init__(self, builder_class, factoryargs):
self.builder = builder_class
self.factory_args = factoryargs
def initialize(self, *initargs):
return self.builder(*(self.factory_args + initargs))
class Factory:
@classmethod
def factory(cls, *factoryargs):
return FactoryBuilder(cls, factoryargs)
def dict_get(dictionary, *args, **kwargs):
"""Return first value in dictionary by iterating through keys"""
for key in args:
try:
return dictionary[key]
except KeyError:
pass
if 'default' in kwargs:
return kwargs['default']
else:
raise KeyError
class ResultEnum(Enum):
FAIL = 0
XFAIL = 1
PASS = 2
UPASS = 3
class Result:
def __init__(self, result, text, logfile=None):
self.result = result
self.text = text
self.logfile = logfile
def __str__(self):
return self.result.name
class ActionResult(Result):
pass
class ListResult(Result):
def __init__(self):
self.subresults = {result_enum: [] for result_enum in ResultEnum}
def add(self, result):
if result:
self.subresults[result.result].append(result)
def xfails(self):
return self.subresults[ResultEnum.XFAIL]
def fails(self):
return self.subresults[ResultEnum.FAIL]
def upasses(self):
return self.subresults[ResultEnum.UPASS]
def passes(self):
return self.subresults[ResultEnum.PASS]
def all(self):
return [i for l in self.subresults.values() for i in l]
def recursive_all(self):
stack = self.all()
actions = []
while stack:
result = stack.pop(0)
if isinstance(result, ActionResult):
actions.append(result)
else:
for r in result.all():
stack.insert(0, r)
return actions
@property
def result(self):
if self.subresults[ResultEnum.FAIL]:
return ResultEnum.FAIL
elif self.subresults[ResultEnum.UPASS]:
return ResultEnum.UPASS
elif self.subresults[ResultEnum.XFAIL]:
return ResultEnum.XFAIL
elif self.subresults[ResultEnum.PASS]:
return ResultEnum.PASS
else:
return ResultEnum.PASS
def __add__(self, other):
n = self.__class__()
n.subresults = {
ResultEnum.__dict__[x]:
(self.subresults[ResultEnum.__dict__[x]] +
other.subresults[ResultEnum.__dict__[x]])
for x in ResultEnum.__dict__ if not x.startswith('_')}
return n
class ProjectListResult(ListResult):
def __str__(self):
output = ""
xfails = [ar for ar in self.recursive_all()
if ar.result == ResultEnum.XFAIL]
fails = [ar for ar in self.recursive_all()
if ar.result == ResultEnum.FAIL]
upasses = [ar for ar in self.recursive_all()
if ar.result == ResultEnum.UPASS]
passes = [ar for ar in self.recursive_all()
if ar.result == ResultEnum.PASS]
if xfails:
output += ('='*40) + '\n'
output += 'XFailures:' '\n'
for xfail in xfails:
output += ' ' + xfail.text + '\n'
if upasses:
output += ('='*40) + '\n'
output += 'UPasses:' + '\n'
for upass in upasses:
output += ' ' + upass.text + '\n'
if fails:
output += ('='*40) + '\n'
output += 'Failures:' + '\n'
for fail in fails:
output += ' ' + fail.text + '\n'
output += ('='*40) + '\n'
output += 'Action Summary:' + '\n'
output += (' Passed: %s' % len(passes)) + '\n'
output += (' Failed: %s' % len(fails)) + '\n'
output += (' XFailed: %s' % len(xfails)) + '\n'
output += (' UPassed: %s' % len(upasses)) + '\n'
output += (' Total: %s' % (len(fails) +
len(passes) +
len(xfails) +
len(upasses))) + '\n'
output += '='*40 + '\n'
output += 'Repository Summary:' + '\n'
output += ' Total: %s' % len(self.all()) + '\n'
output += '='*40 + '\n'
output += 'Result: ' + self.result.name + '\n'
output += '='*40
return output
def xml_string(self):
status_message = {
ResultEnum.PASS: 'This project built successfully',
ResultEnum.FAIL: 'This project failed to build',
ResultEnum.UPASS: 'This project built successfully, but it was expected to fail',
ResultEnum.XFAIL: 'This project failed to build as expected'
}
action_results = self.recursive_all()
build_url = os.environ.get('BUILD_URL')
# Build out Junit Report
xml_report = f"<testsuite tests='{len(action_results)}'>\n"
for action_result in action_results:
# Create a link to the build log if running in a CI environment (Jenkins)
if build_url:
build_log = build_url + f'artifact/swift-source-compat-suite/{action_result}_{action_result.logfile}'
else:
build_log = f'{action_result}_{action_result.logfile}'
if action_result.result == ResultEnum.XFAIL or action_result.result == ResultEnum.UPASS:
match = re.compile(r"(XFAIL|UPASS):(.*?),(.*?)$").search(action_result.text)
xfail_link = match.group(2)
junit_testcase_name = match.group(3)
else:
match = re.compile(r"(PASS|FAIL):(.*?)$").search(action_result.text)
junit_testcase_name = match.group(2)
xfail_link = ''
# Create testcase. Add status message and a link to the build log
xml_report += f"<testcase classname='build' name='{junit_testcase_name}'>\n"
if action_result.result == ResultEnum.PASS or action_result.result == ResultEnum.XFAIL:
xml_report += f"<system-out>{status_message[action_result.result]}. {xfail_link}\n" \
f"Build log: {build_log}</system-out>"
else:
xml_report += f"<failure type='failure' message='{status_message[action_result.result]}. " \
f"{xfail_link}'>Build log: {build_log}</failure>"
xml_report += "</testcase>\n"
xml_report += "</testsuite>\n"
return xml_report
class ProjectResult(ListResult):
pass
class VersionResult(ListResult):
pass
class ListBuilder(Factory):
def __init__(self, include, exclude, verbose, subbuilder, target):
self.include = include