forked from graalvm/mx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mx.py
executable file
·12376 lines (10780 loc) · 508 KB
/
mx.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 python2.7
#
# ----------------------------------------------------------------------------------------------------
#
# Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# ----------------------------------------------------------------------------------------------------
#
r"""
mx is a command line tool for managing the development of Java code organized as suites of projects.
Full documentation can be found in the Wiki at https://bitbucket.org/allr/mxtool2/wiki/Home
"""
import sys
from abc import ABCMeta
if __name__ == '__main__':
# Rename this module as 'mx' so it is not re-executed when imported by other modules.
sys.modules['mx'] = sys.modules.pop('__main__')
try:
import defusedxml #pylint: disable=unused-import
from defusedxml.ElementTree import parse as etreeParse
except ImportError:
from xml.etree.ElementTree import parse as etreeParse
import os, errno, time, subprocess, shlex, types, StringIO, zipfile, signal, tempfile, platform
import textwrap
import socket
import tarfile, gzip
import hashlib
import itertools
# TODO use defusedexpat?
import xml.parsers.expat, xml.sax.saxutils, xml.dom.minidom
import shutil, re
import pipes
import difflib
import glob
import urllib2, urlparse
from collections import Callable
from collections import OrderedDict, namedtuple
from threading import Thread
from argparse import ArgumentParser, REMAINDER, Namespace
from os.path import join, basename, dirname, exists, getmtime, isabs, expandvars, isdir
import mx_unittest
import mx_findbugs
import mx_sigtest
import mx_gate
import mx_compat
_mx_home = os.path.realpath(dirname(__file__))
try:
# needed to work around https://bugs.python.org/issue1927
import readline #pylint: disable=unused-import
except ImportError:
pass
# Support for Python 2.6
def check_output(*popenargs, **kwargs):
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, _ = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
error = subprocess.CalledProcessError(retcode, cmd)
error.output = output
raise error
return output
# Support for jython
def is_jython():
return sys.platform.startswith('java')
if not is_jython():
import multiprocessing
def cpu_count():
if is_jython():
from java.lang import Runtime
runtime = Runtime.getRuntime()
cpus = runtime.availableProcessors()
else:
cpus = multiprocessing.cpu_count()
if _opts.cpu_count:
return cpus if cpus <= _opts.cpu_count else _opts.cpu_count
else:
return cpus
try: subprocess.check_output
except: subprocess.check_output = check_output
try: zipfile.ZipFile.__enter__
except:
zipfile.ZipFile.__enter__ = lambda self: self
zipfile.ZipFile.__exit__ = lambda self, t, value, traceback: self.close()
_projects = dict()
_libs = dict()
_jreLibs = dict()
_jdkLibs = dict()
_dists = dict()
_distTemplates = dict()
_licenses = dict()
_repositories = dict()
"""
Map from the name of a removed dependency to the reason it was removed.
A reason may be the name of another removed dependency, forming a causality chain.
"""
_removedDeps = {}
_suites = dict()
_loadedSuites = []
_jdkFactories = {}
_annotationProcessors = None
_mx_suite = None
_mx_tests_suite = None
_primary_suite_path = None
_primary_suite = None
_src_suitemodel = None
_dst_suitemodel = None
_opts = Namespace()
_extra_java_homes = []
_default_java_home = None
_check_global_structures = True # can be set False to allow suites with duplicate definitions to load without aborting
_vc_systems = []
_mvn = None
_binary_suites = None # source suites only if None, [] means all binary, otherwise specific list
_suites_ignore_versions = None # as per _binary_suites, ignore versions on clone
# List of functions to run when the primary suite is initialized
_primary_suite_deferrables = []
def nyi(name, obj):
abort('{} is not implemented for {}'.format(name, obj.__class__.__name__))
"""
Names of commands that do not need suites loaded.
"""
_suite_context_free = ['scloneimports']
"""
Decorator for commands that do not need suites loaded.
"""
def suite_context_free(func):
_suite_context_free.append(func.__name__)
return func
"""
Names of commands that do not need a primary suite to be available.
"""
_primary_suite_exempt = []
"""
Decorator for commands that do not need a primary suite to be available.
"""
def primary_suite_exempt(func):
_primary_suite_exempt.append(func.__name__)
return func
DEP_STANDARD = "standard dependency"
DEP_ANNOTATION_PROCESSOR = "annotation processor dependency"
DEP_EXCLUDED = "excluded library"
def _is_edge_ignored(edge, ignoredEdges):
return ignoredEdges and edge in ignoredEdges
DEBUG_WALK_DEPS = False
DEBUG_WALK_DEPS_LINE = 1
def _debug_walk_deps_helper(dep, edge, ignoredEdges):
assert edge not in ignoredEdges
global DEBUG_WALK_DEPS_LINE
if DEBUG_WALK_DEPS:
if edge:
print '{}:walk_deps:{}{} # {}'.format(DEBUG_WALK_DEPS_LINE, ' ' * edge.path_len(), dep, edge.kind)
else:
print '{}:walk_deps:{}'.format(DEBUG_WALK_DEPS_LINE, dep)
DEBUG_WALK_DEPS_LINE += 1
'''
Represents an edge traversed while visiting a spanning tree of the dependency graph.
'''
class DepEdge:
def __init__(self, src, kind, prev):
'''
src - the source of this dependency edge
kind - one of the constants DEP_STANDARD, DEP_ANNOTATION_PROCESSOR, DEP_EXCLUDED describing the type
of graph edge from 'src' to the dependency targeted by this edge
prev - the dependency edge traversed to reach 'src' or None if 'src' is a root of a dependency
graph traversal
'''
self.src = src
self.kind = kind
self.prev = prev
def __str__(self):
return '{}@{}'.format(self.src, self.kind)
def path(self):
if self.prev:
return self.prev.path() + [self.src]
return [self.src]
def path_len(self):
return 1 + self.prev.path_len() if self.prev else 0
class SuiteConstituent(object):
def __init__(self, suite, name):
self.name = name
self.suite = suite
# Should this constituent be visible outside its suite
self.internal = False
def origin(self):
"""
Gets a 2-tuple (file, line) describing the source file where this constituent
is defined or None if the location cannot be determined.
"""
suitepy = self.suite.suite_py()
if exists(suitepy):
import tokenize
with open(suitepy) as fp:
candidate = None
for t in tokenize.generate_tokens(fp.readline):
_, tval, (srow, _), _, _ = t
if candidate is None:
if tval == '"' + self.name + '"' or tval == "'" + self.name + "'":
candidate = srow
else:
if tval == ':':
return (suitepy, srow)
else:
candidate = None
def __abort_context__(self):
'''
Gets a description of where this constituent was defined in terms of source file
and line number. If no such description can be generated, None is returned.
'''
loc = self.origin()
if loc:
path, lineNo = loc
return ' File "{}", line {} in definition of {}'.format(path, lineNo, self.name)
return None
class License(SuiteConstituent):
def __init__(self, suite, name, fullname, url):
SuiteConstituent.__init__(self, suite, name)
self.fullname = fullname
self.url = url
def __eq__(self, other):
if not isinstance(other, License):
return False
return self.name == other.name and self.url == other.url and self.fullname == other.fullname
def __ne__(self, other):
return not self.__eq__(other)
"""
A dependency is a library, distribution or project specified in a suite.
The name must be unique across all Dependency instances.
"""
class Dependency(SuiteConstituent):
def __init__(self, suite, name, theLicense):
SuiteConstituent.__init__(self, suite, name)
self.theLicense = theLicense
def __cmp__(self, other):
return cmp(self.name, other.name)
def __str__(self):
return self.name
def __eq__(self, other):
return self.name == other.name
def __ne__(self, other):
return self.name != other.name
def __hash__(self):
return hash(self.name)
def isBaseLibrary(self):
return isinstance(self, BaseLibrary)
def isLibrary(self):
return isinstance(self, Library)
def isJreLibrary(self):
return isinstance(self, JreLibrary)
def isJdkLibrary(self):
return isinstance(self, JdkLibrary)
def isProject(self):
return isinstance(self, Project)
def isJavaProject(self):
return isinstance(self, JavaProject)
def isNativeProject(self):
return isinstance(self, NativeProject)
def isDistribution(self):
return isinstance(self, Distribution)
def isJARDistribution(self):
return isinstance(self, JARDistribution)
def isTARDistribution(self):
return isinstance(self, NativeTARDistribution)
def isProjectOrLibrary(self):
return self.isProject() or self.isLibrary()
def getGlobalRegistry(self):
if self.isProject():
return _projects
if self.isLibrary():
return _libs
if self.isDistribution():
return _dists
if self.isJreLibrary():
return _jreLibs
assert self.isJdkLibrary()
return _jdkLibs
def getSuiteRegistry(self):
if self.isProject():
return self.suite.projects
if self.isLibrary():
return self.suite.libs
if self.isDistribution():
return self.suite.dists
if self.isJreLibrary():
return self.suite.jreLibs
assert self.isJdkLibrary()
return self.suite.jdkLibs
"""
Return a BuildTask that can be used to build this dependency.
"""
def getBuildTask(self, args):
nyi('getBuildTask', self)
def abort(self, msg):
'''
Aborts with given message prefixed by the origin of this dependency.
'''
abort(msg, context=self)
def warn(self, msg):
'''
Warns with given message prefixed by the origin of this dependency.
'''
warn(msg, context=self)
def qualifiedName(self):
return '{}:{}'.format(self.suite.name, self.name)
def walk_deps(self, preVisit=None, visit=None, visited=None, ignoredEdges=None, visitEdge=None):
'''
Walk the dependency graph rooted at this object.
See documentation for mx.walk_deps for more info.
'''
if visited is not None:
if self in visited:
return
else:
visited = set()
if not ignoredEdges:
# Default ignored edges
ignoredEdges = [DEP_ANNOTATION_PROCESSOR, DEP_EXCLUDED]
self._walk_deps_helper(visited, None, preVisit, visit, ignoredEdges, visitEdge)
def _walk_deps_helper(self, visited, edge, preVisit=None, visit=None, ignoredEdges=None, visitEdge=None):
_debug_walk_deps_helper(self, edge, ignoredEdges)
assert self not in visited, self
visited.add(self)
if not preVisit or preVisit(self, edge):
self._walk_deps_visit_edges(visited, edge, preVisit, visit, ignoredEdges, visitEdge)
if visit:
visit(self, edge)
def _walk_deps_visit_edges(self, visited, edge, preVisit=None, visit=None, ignoredEdges=None, visitEdge=None):
nyi('_walk_deps_visit_edges', self)
def contains_dep(self, dep, includeAnnotationProcessors=False):
'''
Determines if the dependency graph rooted at this object contains 'dep'.
Returns the path from this object to 'dep' if so, otherwise returns None.
'''
if dep == self:
return [self]
class FoundPath(StopIteration):
def __init__(self, path):
StopIteration.__init__(self)
self.path = path
def visit(path, d, edge):
if dep is d:
raise FoundPath(path)
try:
ignoredEdges = [DEP_EXCLUDED] if includeAnnotationProcessors else None
self.walk_deps(visit=visit, ignoredEdges=ignoredEdges)
except FoundPath as e:
return e.path
return None
'''Only JavaProjects define Java packages'''
def defined_java_packages(self):
return []
def _resolveDepsHelper(self, deps, fatalIfMissing=True):
'''
Resolves any string entries in 'deps' to the Dependency objects named
by the strings. The 'deps' list is updated in place.
'''
if deps:
if isinstance(deps[0], str):
resolvedDeps = []
for name in deps:
s, _ = splitqualname(name)
dep = dependency(name, context=self, fatalIfMissing=fatalIfMissing)
if not dep:
continue
if dep.isProject() and self.suite is not dep.suite:
abort('cannot have an inter-suite reference to a project: ' + dep.name, context=self)
if s is None and self.suite is not dep.suite:
abort('inter-suite reference must use qualified form ' + dep.suite.name + ':' + dep.name, context=self)
if self.suite is not dep.suite and dep.internal:
abort('cannot reference internal ' + dep.name + ' from ' + self.suite.name + ' suite', context=self)
resolvedDeps.append(dep)
deps[:] = resolvedDeps
else:
# If the first element has been resolved, then all elements should have been resolved
assert len([d for d in deps if not isinstance(d, str)])
class ClasspathDependency(Dependency):
def __init__(self): # pylint: disable=super-init-not-called
pass
def classpath_repr(self, resolve=True):
'''
Gets this dependency as an element on a class path.
If 'resolve' is True, then this method aborts if the file or directory
denoted by the class path element does not exist.
'''
nyi('classpath_repr', self)
def isJar(self):
cp_repr = self.classpath_repr()
if cp_repr:
return cp_repr.endswith('.jar') or cp_repr.endswith('.JAR') or '.jar_' in cp_repr
return True
"""
A build task is used to build a dependency.
Attributes:
parallelism: how many CPUs are used when running this task
deps: array of tasks this task depends on
built: True if a build was performed
"""
class BuildTask(object):
def __init__(self, subject, args, parallelism):
self.parallelism = parallelism
self.subject = subject
self.deps = []
self.built = False
self.args = args
self.proc = None
def __str__(self):
nyi('__str__', self)
def __repr__(self):
return str(self)
def initSharedMemoryState(self):
self._builtBox = multiprocessing.Value('b', 1 if self.built else 0)
def pushSharedMemoryState(self):
self._builtBox.value = 1 if self.built else 0
def pullSharedMemoryState(self):
self.built = bool(self._builtBox.value)
def cleanSharedMemoryState(self):
self._builtBox = None
def _persistDeps(self):
'''
Saves the dependencies for this task's subject to a file. This can be used to
determine whether the ordered set of dependencies for this task have changed
since the last time it was built.
Returns True if file already existed and did not reflect the current dependencies.
'''
savedDepsFile = join(self.subject.suite.get_mx_output_dir(), 'savedDeps', self.subject.name)
currentDeps = [d.subject.name for d in self.deps]
outOfDate = False
if exists(savedDepsFile):
with open(savedDepsFile) as fp:
savedDeps = [l.strip() for l in fp.readlines()]
if savedDeps != [d.subject.name for d in self.deps]:
outOfDate = True
if len(currentDeps) == 0:
if exists(savedDepsFile):
os.remove(savedDepsFile)
else:
ensure_dir_exists(dirname(savedDepsFile))
with open(savedDepsFile, 'w') as fp:
for dname in currentDeps:
print >> fp, dname
return outOfDate
"""
Execute the build task.
"""
def execute(self):
if self.buildForbidden():
self.logSkip(None)
return
buildNeeded = False
if self.args.clean and not self.cleanForbidden():
self.logClean()
self.clean()
buildNeeded = True
reason = 'clean'
if not buildNeeded:
updated = [dep for dep in self.deps if dep.built]
if any(updated):
buildNeeded = True
if not _opts.verbose:
reason = 'dependency {} updated'.format(updated[0].subject)
else:
reason = 'dependencies updated: ' + ', '.join([u.subject.name for u in updated])
changed = self._persistDeps()
if not buildNeeded and changed:
buildNeeded = True
reason = 'dependencies were added, removed or re-ordered'
if not buildNeeded:
newestInput = None
newestInputDep = None
for dep in self.deps:
depNewestOutput = dep.newestOutput()
if depNewestOutput and (not newestInput or depNewestOutput.isNewerThan(newestInput)):
newestInput = depNewestOutput
newestInputDep = dep
if newestInputDep:
logvv('Newest dependency for {}: {} ({})'.format(self.subject.name, newestInputDep.subject.name, newestInput))
if get_env('MX_BUILD_SHALLOW_DEPENDENCY_CHECKS') is None:
shallow_dependency_checks = self.args.shallow_dependency_checks is True
else:
shallow_dependency_checks = get_env('MX_BUILD_SHALLOW_DEPENDENCY_CHECKS') == 'true'
if self.args.shallow_dependency_checks is not None and shallow_dependency_checks is True:
warn('Explicit -s argument to build command is overridden by MX_BUILD_SHALLOW_DEPENDENCY_CHECKS')
if newestInput and shallow_dependency_checks and not self.subject.isNativeProject():
newestInput = None
if __name__ != self.__module__ and self.subject.suite.getMxCompatibility().newestInputIsTimeStampFile():
newestInput = newestInput.timestamp if newestInput else float(0)
buildNeeded, reason = self.needsBuild(newestInput)
if buildNeeded:
if not self.args.clean and not self.cleanForbidden():
self.clean(forBuild=True)
self.logBuild(reason)
self.build()
self.built = True
logv('Finished {}'.format(self))
else:
self.logSkip(reason)
def logBuild(self, reason):
if reason:
log('{}... [{}]'.format(self, reason))
else:
log('{}...'.format(self))
def logClean(self):
log('Cleaning {}...'.format(self.subject.name))
def logSkip(self, reason):
if reason:
logv('[{} - skipping {}]'.format(reason, self.subject.name))
else:
logv('[skipping {}]'.format(self.subject.name))
def needsBuild(self, newestInput):
"""
Returns True if the current artifacts of this task are out dated.
The 'newestInput' argument is either None or a TimeStampFile
denoting the artifact of a dependency with the most recent modification time.
Apart from 'newestInput', this method does not inspect this task's dependencies.
"""
if self.args.force:
return (True, 'forced build')
return (False, 'unimplemented')
def newestOutput(self):
"""
Gets a TimeStampFile representing the build output file for this task
with the newest modification time or None if no build output file exists.
"""
nyi('newestOutput', self)
def buildForbidden(self):
if not self.args.only:
return False
projectNames = self.args.only.split(',')
return self.subject.name not in projectNames
def cleanForbidden(self):
return False
"""
Build the artifacts.
"""
def build(self):
nyi('build', self)
"""
Clean the build artifacts.
"""
def clean(self, forBuild=False):
nyi('clean', self)
def _needsUpdate(newestInput, path):
"""
Determines if the file denoted by 'path' does not exist or 'newestInput' is not None
and 'path's latest modification time is older than the 'newestInput' TimeStampFile.
Returns a string describing why 'path' needs updating or None if it does not need updating.
"""
if not exists(path):
return path + ' does not exist'
if newestInput:
ts = TimeStampFile(path, followSymlinks=False)
if ts.isOlderThan(newestInput):
return '{} is older than {}'.format(ts, newestInput)
return None
class DistributionTemplate(SuiteConstituent):
def __init__(self, suite, name, attrs, parameters):
SuiteConstituent.__init__(self, suite, name)
self.attrs = attrs
self.parameters = parameters
"""
A distribution is a file containing the output from one or more projects.
In some sense it is the ultimate "result" of a build (there can be more than one).
It is a Dependency because a Project or another Distribution may express a dependency on it.
Attributes:
name: unique name
deps: "dependencies" that define the components that will comprise the distribution.
See Distribution.archived_deps for a precise description.
This is a slightly misleading name, it is more akin to the "srcdirs" attribute of a Project,
as it defines the eventual content of the distribution
excludedLibs: Libraries whose jar contents should be excluded from this distribution's jar
"""
class Distribution(Dependency):
def __init__(self, suite, name, deps, excludedLibs, platformDependent, theLicense):
Dependency.__init__(self, suite, name, theLicense)
self.deps = deps
self.update_listeners = set()
self.excludedLibs = excludedLibs
self.platformDependent = platformDependent
def add_update_listener(self, listener):
self.update_listeners.add(listener)
def notify_updated(self):
for l in self.update_listeners:
l(self)
def resolveDeps(self):
self._resolveDepsHelper(self.deps, fatalIfMissing=not isinstance(self.suite, BinarySuite))
self._resolveDepsHelper(self.excludedLibs)
for l in self.excludedLibs:
if not l.isBaseLibrary():
abort('"exclude" attribute can only contain libraries: ' + l.name, context=self)
licenseId = self.theLicense if self.theLicense else self.suite.defaultLicense
if licenseId:
self.theLicense = get_license(licenseId, context=self)
def _walk_deps_visit_edges(self, visited, edge, preVisit=None, visit=None, ignoredEdges=None, visitEdge=None):
if not _is_edge_ignored(DEP_STANDARD, ignoredEdges):
for d in self.deps:
if visitEdge:
visitEdge(self, DEP_STANDARD, d)
if d not in visited:
d._walk_deps_helper(visited, DepEdge(self, DEP_STANDARD, edge), preVisit, visit, ignoredEdges, visitEdge)
if not _is_edge_ignored(DEP_EXCLUDED, ignoredEdges):
for d in self.excludedLibs:
if visitEdge:
visitEdge(self, DEP_EXCLUDED, d)
if d not in visited:
d._walk_deps_helper(visited, DepEdge(self, DEP_EXCLUDED, edge), preVisit, visit, ignoredEdges, visitEdge)
def make_archive(self):
nyi('make_archive', self)
def archived_deps(self):
'''
Gets the projects and libraries whose artifacts are the contents of the archive
created by self.make_archive().
Direct distribution dependencies are considered as "distDependencies".
Anything contained in the distDependencies will not be included in the archived_deps.
libraries listed in "excludedLibs" will also not be included.
Otherwise, archived_deps will contain everything this distribution depends on (including
indirect distribution dependencies and libraries).
'''
if not hasattr(self, '_archived_deps'):
excluded = set(self.excludedLibs)
def _visitDists(dep, edges):
if dep is not self:
excluded.add(dep)
excluded.update(dep.archived_deps())
self.walk_deps(visit=_visitDists, preVisit=lambda dst, edge: dst.isDistribution())
deps = []
def _visit(dep, edges):
if dep is not self:
deps.append(dep)
def _preVisit(dst, edge):
return dst not in excluded and not dst.isJreLibrary()
self.walk_deps(visit=_visit, preVisit=_preVisit)
self._archived_deps = deps
return self._archived_deps
def exists(self):
nyi('exists', self)
def remoteExtension(self):
nyi('remoteExtension', self)
def localExtension(self):
nyi('localExtension', self)
def remoteName(self):
if self.platformDependent:
return '{name}_{os}_{arch}'.format(name=self.name, os=get_os(), arch=get_arch())
return self.name
def postPull(self, f):
pass
def prePush(self, f):
return f
def needsUpdate(self, newestInput):
'''
Determines if this distribution needs updating taking into account the
'newestInput' TimeStampFile if 'newestInput' is not None. Returns the
reason this distribution needs updating or None if it doesn't need updating.
'''
nyi('needsUpdate', self)
def maven_artifact_id(self):
return _map_to_maven_dist_name(self.remoteName())
def maven_group_id(self):
return _mavenGroupId(self.suite)
"""
A JARDistribution is a distribution for JavaProjects and Java libraries.
A Distribution always generates a jar/zip file for the built components
and may optionally specify a zip for the sources from which the built components were generated.
Attributes:
path: suite-local path to where the jar file will be placed
sourcesPath: as path but for source files (optional)
"""
class JARDistribution(Distribution, ClasspathDependency):
def __init__(self, suite, name, subDir, path, sourcesPath, deps, mainClass, excludedLibs, distDependencies, javaCompliance, platformDependent, theLicense, javadocType="implementation", allowsJavadocWarnings=False, maven=True):
Distribution.__init__(self, suite, name, deps + distDependencies, excludedLibs, platformDependent, theLicense)
ClasspathDependency.__init__(self)
self.subDir = subDir
self.path = _make_absolute(path.replace('/', os.sep), suite.dir)
self.sourcesPath = _make_absolute(sourcesPath.replace('/', os.sep), suite.dir) if sourcesPath else None
self.archiveparticipant = None
self.mainClass = mainClass
self.javaCompliance = JavaCompliance(javaCompliance) if javaCompliance else None
self.definedAnnotationProcessors = []
self.javadocType = javadocType
self.allowsJavadocWarnings = allowsJavadocWarnings
self.maven = maven
assert path.endswith(self.localExtension())
def maven_artifact_id(self):
if isinstance(self.maven, types.DictType):
artifact_id = self.maven.get('artifactId', None)
if artifact_id:
return artifact_id
return super(JARDistribution, self).maven_artifact_id()
def maven_group_id(self):
if isinstance(self.maven, types.DictType):
group_id = self.maven.get('groupId', None)
if group_id:
return group_id
return super(JARDistribution, self).maven_group_id()
def set_archiveparticipant(self, archiveparticipant):
"""
Adds an object that participates in the make_archive method of this distribution by defining the following methods:
__opened__(arc, srcArc, services)
Called when archiving starts. The 'arc' and 'srcArc' Archiver objects are for writing to the
binary and source jars for the distribution. The 'services' dict is for collating the files
that will be written to META-INF/services in the binary jar. It's a map from service names
to a list of providers for the named service.
__add__(arcname, contents)
Submits an entry for addition to the binary archive (via the 'zf' ZipFile field of the 'arc' object).
Returns True if this object writes to the archive or wants to exclude the entry from the archive,
False if the caller should add the entry.
__addsrc__(arcname, contents)
Same as __add__ except if targets the source archive.
__closing__()
Called just before the 'services' are written to the binary archive and both archives are
written to their underlying files.
"""
self.archiveparticipant = archiveparticipant
def origin(self):
return Dependency.origin(self)
def classpath_repr(self, resolve=True):
if resolve and not exists(self.path):
abort('unbuilt distribution {} can not be on a class path'.format(self))
return self.path
"""
Gets the directory in which the IDE project configuration for this distribution is generated.
"""
def get_ide_project_dir(self):
if self.subDir:
return join(self.suite.dir, self.subDir, self.name + '.dist')
else:
return join(self.suite.dir, self.name + '.dist')
def make_archive(self):
# are sources combined into main archive?
unified = self.path == self.sourcesPath
with Archiver(self.path) as arc:
with Archiver(None if unified else self.sourcesPath) as srcArcRaw:
srcArc = arc if unified else srcArcRaw
services = {}
if self.archiveparticipant:
self.archiveparticipant.__opened__(arc, srcArc, services)
def overwriteCheck(zf, arcname, source):
if os.path.basename(arcname).startswith('.'):
logv('Excluding dotfile: ' + source)
return True
if not hasattr(zf, '_provenance'):
zf._provenance = {}
existingSource = zf._provenance.get(arcname, None)
isOverwrite = False
if existingSource and existingSource != source:
if arcname[-1] != os.path.sep:
warn(self.path + ': avoid overwrite of ' + arcname + '\n new: ' + source + '\n old: ' + existingSource)
isOverwrite = True
zf._provenance[arcname] = source
return isOverwrite
if self.mainClass:
manifest = "Manifest-Version: 1.0\nMain-Class: %s\n\n" % (self.mainClass)
if not overwriteCheck(arc.zf, "META-INF/MANIFEST.MF", "project files"):
arc.zf.writestr("META-INF/MANIFEST.MF", manifest)
for dep in self.archived_deps():
if self.theLicense is not None and dep.theLicense != self.theLicense:
if dep.suite.getMxCompatibility().supportsLicenses() and self.suite.getMxCompatibility().supportsLicenses():
report = abort
else:
report = warn
depLicense = dep.theLicense.name if dep.theLicense else '??'
selfLicense = self.theLicense.name if self.theLicense else '??'
report('Incompatible licenses: distribution {} ({}) can not contain {} ({})'.format(self.name, selfLicense, dep.name, depLicense))
if dep.isLibrary() or dep.isJARDistribution():
if dep.isLibrary():
l = dep
# merge library jar into distribution jar
logv('[' + self.path + ': adding library ' + l.name + ']')
jarPath = l.get_path(resolve=True)
jarSourcePath = l.get_source_path(resolve=True)
elif dep.isJARDistribution():
logv('[' + self.path + ': adding distribution ' + dep.name + ']')
jarPath = dep.path
jarSourcePath = dep.sourcesPath
else:
abort('Dependency not supported: {} ({})'.format(dep.name, dep.__class__.__name__))
if jarPath:
if dep.isJARDistribution() or not dep.optional or exists(jarPath):
with zipfile.ZipFile(jarPath, 'r') as lp:
entries = lp.namelist()
for arcname in entries:
if arcname.startswith('META-INF/services/') and not arcname == 'META-INF/services/':
service = arcname[len('META-INF/services/'):]
assert '/' not in service
services.setdefault(service, []).extend(lp.read(arcname).splitlines())
else:
if not overwriteCheck(arc.zf, arcname, jarPath + '!' + arcname):
contents = lp.read(arcname)
if not self.archiveparticipant or not self.archiveparticipant.__add__(arcname, contents):
arc.zf.writestr(arcname, contents)
if srcArc.zf and jarSourcePath:
with zipfile.ZipFile(jarSourcePath, 'r') as lp:
for arcname in lp.namelist():
if not overwriteCheck(srcArc.zf, arcname, jarPath + '!' + arcname):
contents = lp.read(arcname)
if not self.archiveparticipant or not self.archiveparticipant.__addsrc__(arcname, contents):
srcArc.zf.writestr(arcname, contents)
elif dep.isProject():
p = dep
if self.javaCompliance:
if p.javaCompliance > self.javaCompliance:
abort("Compliance level doesn't match: Distribution {0} requires {1}, but {2} is {3}.".format(self.name, self.javaCompliance, p.name, p.javaCompliance), context=self)
logv('[' + self.path + ': adding project ' + p.name + ']')
outputDir = p.output_dir()
for root, _, files in os.walk(outputDir):
relpath = root[len(outputDir) + 1:]
if relpath == join('META-INF', 'services'):
for service in files:
with open(join(root, service), 'r') as fp:
services.setdefault(service, []).extend([provider.strip() for provider in fp.readlines()])
else:
for f in files:
arcname = join(relpath, f).replace(os.sep, '/')
with open(join(root, f), 'rb') as fp:
contents = fp.read()
if not self.archiveparticipant or not self.archiveparticipant.__add__(arcname, contents):
arc.zf.writestr(arcname, contents)
if srcArc.zf:
sourceDirs = p.source_dirs()
if p.source_gen_dir():
sourceDirs.append(p.source_gen_dir())
for srcDir in sourceDirs:
for root, _, files in os.walk(srcDir):
relpath = root[len(srcDir) + 1:]
for f in files:
if f.endswith('.java'):
arcname = join(relpath, f).replace(os.sep, '/')
if not overwriteCheck(srcArc.zf, arcname, join(root, f)):
with open(join(root, f), 'r') as fp:
contents = fp.read()
if not self.archiveparticipant or not self.archiveparticipant.__addsrc__(arcname, contents):
srcArc.zf.writestr(arcname, contents)
else:
abort('Dependency not supported: {} ({})'.format(dep.name, dep.__class__.__name__))
if self.archiveparticipant:
self.archiveparticipant.__closing__()
for service, providers in services.iteritems():
arcname = 'META-INF/services/' + service
# Convert providers to a set before printing to remove duplicates
arc.zf.writestr(arcname, '\n'.join(frozenset(providers)) + '\n')
self.notify_updated()
def getBuildTask(self, args):