-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathemk.py
2646 lines (2213 loc) · 118 KB
/
emk.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
from __future__ import print_function
import os
import sys
import imp
if sys.version_info[0] < 3:
_string_type = basestring
import __builtin__ as builtins
else:
_string_type = str
import builtins
import logging
import collections
import errno
import traceback
import time
import cPickle as pickle
import threading
import shutil
import multiprocessing
import re
import hashlib
_module_path = os.path.realpath(__file__)
class _Target(object):
"""
Representation of a potential target (ie, a rule product).
Properties should not be modified.
Properties:
orig_path -- The original (relative) path of the target, as specified to emk.rule() or @emk.make_rule.
rule -- The emk.Rule instance that generates this target.
abs_path -- The canonical path of the target.
attached -- The set of targets (canonical paths) that have been attached to this target. Only usable when a rule is executing.
"""
def __init__(self, local_path, rule):
self.orig_path = local_path
self.rule = rule
if rule:
self.abs_path = _make_target_abspath(local_path, rule.scope)
else:
self.abs_path = local_path
self.attached = set()
self._rebuild_if_changed = False
self._required_by = set()
self._built = False
self._visited = False
self._virtual_modtime = None
class _Rule(object):
"""
Representation of a rule.
Properties should not be modified.
Properties:
func -- The function to execute to run the rule. This should take at least 2 arguments: the list of canonical product paths,
the list of canonical requirement paths, and any additional args as desired.
produces -- The list of emk.Target instances that are produced by this rule.
requires -- The list of things that this rule depends on (canonical paths). These are the primary dependencies of the rule.
All primary dependencies of a rule are built before the rule is built. If a primary dependency does not
exist, a build error is raised.
args -- The arbitrary args that will be passed (unpacked) to the rule function (specified when the rule was created).
cwd_safe -- Whether or not the rule is cwd-safe (True or False). Specified when the rule was created.
cwd-unsafe rules are executed sequentially in a single thread, and the current working directory
of the process is set the the scope dir for the rule before it is executed. cwd-safe rules
may be executed concurrently with any other rules, and the current working directory is not set.
ex_safe -- Whether or not the rule is exception safe (True or False). Specified when the rule was created. If an exception occurs while
a non-exception-safe rule is executing, emk will print a warning indicating that a rule was partially executed, and should be cleaned.
has_changed -- The function to execute to determine if a requirement or product has changed. Uses emk.default_has_changed by default.
The function should take a single argument which is the absolute path of the thing to check to see if it has changed.
When this function is executing, emk.current_rule and emk.rule_cache() are available.
stack -- The stack of where the rule was defined (a list of strings).
Build-time properties (only usable when the rule is being executed):
weak_deps -- The set of weak dependencies (canonical paths) of this rule (added using emk.weak_depend()).
If a weak dependency does not exist, the rule is still built. If there is no cached information
for a weak dependency, the dependency is treated as "not changed" (so the rule will not be rebuilt).
Primarily used for dependencies that are discovered within the primary dependenceies (eg, header files).
secondary_deps -- The set of extra dependencies (canonical paths) of this rule (added using emk.depend()).
All secondary dependencies of a rule are built before the rule is built. If a secondary dependency does not
exist, a build error is raised.
"""
def __init__(self, requires, args, func, cwd_safe, ex_safe, has_changed, scope):
self.func = func
self.produces = []
self.requires = requires
self.args = args
self.cwd_safe = cwd_safe
self.ex_safe = ex_safe
self.has_changed = has_changed
self.scope = scope
self._key = None
self._cache = None
self._untouched = set()
self._lock = threading.Lock()
self.secondary_deps = set()
self.weak_deps = set()
self._required_targets = []
self._remaining_unbuilt_reqs = 0
self._want_build = False
self._built = False
self._ran_func = False
self.stack = []
self._req_trace = {}
class _ScopeData(object):
def __init__(self, parent, scope_type, scope_dir, proj_dir):
self.parent = parent
self.scope_type = scope_type
self.dir = scope_dir
self.proj_dir = proj_dir
self.has_rules_file = False
self._cache = None
self._do_later_funcs = []
if parent:
self.default_modules = list(parent.default_modules)
self.pre_modules = list(parent.pre_modules)
self.build_dir = parent.build_dir
self.module_paths = list(parent.module_paths)
self.recurse_dirs = parent.recurse_dirs.copy()
else:
self.default_modules = []
self.pre_modules = []
self.build_dir = "__build__"
self.module_paths = []
self.recurse_dirs = set()
self.modules = {} # map module name to instance (_Module_Instance)
self.weak_modules = {}
self.targets = {} # map original target name->target for the current scope
def prepare_do_later(self):
self._do_later_funcs = []
class _RuleQueue(object):
"""
A threadsafe queue, servicing 1 "special" thread and 0 or more "normal" threads.
The special thread is the only thread that is allowed to handle "special" queue items;
it may also handle normal queue items. The normal threads only handle normal queue items.
Basically this is for handling cwd-unsafe rules. cwd-safe rules are "normal" and may be handled by any thread;
cwd-unsafe rules are "special" and are only handled by the single special thread, so
there is only ever one thread controlling the current working directory.
It works as a normal threadsafe queue, but with a separate queue for the special items.
The special thread checks to see if there are any items on the special queue; if not, it tries to
grab an item from the normal queue; if there are no items on the normal queue either then it waits
for an item to appear on the special queue.
When a new item is added, it is added to the special queue if it is a special item. Otherwise, if
the special queue is empty, and the special thread is not currently handling an item, the item is
added to the special queue as well. Otherwise the item is added to the normal queue.
This allows work to be shared equally among the threads, while still allowing the special items
to be handled by only the special thread.
"""
def __init__(self, num_threads):
self.num_threads = num_threads
self.lock = threading.Lock()
self.join_cond = threading.Condition(self.lock)
self.special_cond = threading.Condition(self.lock)
self.cond = threading.Condition(self.lock)
self.special_queue = collections.deque()
self.queue = collections.deque()
self.errors = []
self.tasks = 0
self.special_thread_busy = False
self.STOP = object()
def put(self, rule):
with self.lock:
if self.errors:
return
self.tasks += 1
if not rule.cwd_safe or (not len(self.special_queue) and not self.special_thread_busy) or self.num_threads == 1:
# not cwd_safe, or special queue is empty, so add to special queue
self.special_queue.append(rule)
self.special_cond.notify()
else:
# add to normal queue
self.queue.append(rule)
self.cond.notify()
def get(self, special):
with self.lock:
if self.errors:
return self.STOP # stop immediately
if special:
if len(self.special_queue):
item = self.special_queue.popleft()
elif len(self.queue) and not (self.queue[0] is self.STOP):
# note that the special thread will only get STOP off of the special queue
item = self.queue.popleft()
else:
while not len(self.special_queue):
self.special_cond.wait()
item = self.special_queue.popleft()
self.special_thread_busy = True
return item
else:
while not len(self.queue):
self.cond.wait()
return self.queue.popleft()
def done_task(self, special):
with self.lock:
if self.errors:
return
if special:
self.special_thread_busy = False
self.tasks -= 1
if self.tasks == 0:
self.join_cond.notifyAll()
def join(self):
with self.lock:
while self.tasks and not self.errors:
self.join_cond.wait()
def stop(self):
with self.lock:
self.special_queue.append(self.STOP)
self.special_cond.notify()
num_threads = self.num_threads - 1
while num_threads > 0:
num_threads -= 1
self.queue.append(self.STOP)
self.cond.notify()
def error(self, err):
with self.lock:
self.errors.append(err)
self.join_cond.notifyAll()
class _Container(object):
pass
_clean_log = logging.getLogger("emk.clean")
class _Clean_Module(object):
"""
Module "clean".
The clean module is automatically loaded in every rules scope. It provides the "clean" target,
which will delete the build directory for the rules scope if the build directory is a subdirectory
of the scope directory (so it won't delete the build directory if it is set to ".." for example).
Properties:
remove_build_dir -- If True, the clean rule will not delete the build directory. This is inherited
by child scopes.
"""
def __init__(self, scope, parent=None):
if parent:
self.remove_build_dir = parent.remove_build_dir
else:
self.remove_build_dir = True
def new_scope(self, scope):
return _Clean_Module(scope, self)
def remove_cache(self, build_dir):
hash = hashlib.md5(emk.scope_dir).hexdigest()
cache_path = os.path.join(build_dir, "__emk_cache__" + hash)
_clean_log.debug("Removing cache %s", cache_path)
try:
os.remove(cache_path)
except OSError:
pass
def clean_func(self, produces, requires):
build_dir = os.path.realpath(os.path.join(emk.scope_dir, emk.build_dir))
if self.remove_build_dir:
if os.path.commonprefix([build_dir, emk.scope_dir]) == emk.scope_dir:
_clean_log.info("Removing directory %s", build_dir)
shutil.rmtree(build_dir, ignore_errors=True)
else:
self.remove_cache(build_dir)
else:
self.remove_cache(build_dir)
emk.mark_virtual(*produces)
def post_rules(self):
emk.rule(self.clean_func, ["clean"], [emk.ALWAYS_BUILD], cwd_safe=True, ex_safe=True)
class _Module_Instance(object):
def __init__(self, name, instance, mod):
self.name = name # module name
self.instance = instance # module instance
self.mod = mod # python module that was imported
class _Always_Build(object):
def __repr__(self):
return "emk.ALWAYS_BUILD"
class _BuildError(Exception):
def __init__(self, msg, extra_info=None):
self.msg = msg
self.extra_info = extra_info
def __str__(self):
return self.msg
def _style_tag(tag):
return "\000\001" + tag + "\001\000"
class _NoStyler(object):
def __init__(self):
self.r = re.compile("\000\001([0-9A-Za-z_]*)\001\000")
def style(self, string, record):
return self.r.sub('', string)
class _PassthroughStyler(object):
"""
Passthrough styler. Does not modify the emk style tags in any way.
"""
def style(self, string, record):
return string
class _ConsoleStyler(object):
"""
Console styler. Converts the emk style tags into ANSI escape codes.
Properties:
styles -- A dict containing "tag": <escape code> mappings. You may modify this dict to change
the output or add additional mappings.
"""
def __init__(self):
self.r = re.compile("\000\001([0-9A-Za-z_]*)\001\000")
self.styles = {"bold":"\033[1m", "u":"\033[4m", "red":"\033[31m", "green":"\033[32m", "blue":"\033[34m",
"important":"\033[1m\033[31m", "rule_stack":"\033[34m", "stderr":"\033[31m"}
def style(self, string, record):
r = self.r
styles = self.styles.copy()
if record.levelno >= logging.WARNING:
styles["logtype"] = "\033[1m"
if record.levelno >= logging.ERROR:
styles["logtype"] = "\033[1m\033[31m"
stack = []
start = 0
bits = []
if record.levelno == logging.DEBUG:
bits.append("\033[34m")
m = r.search(string, start)
while m:
bits.append(string[start:m.start(0)])
style = styles.get(m.group(1))
if style is not None:
stack.append(style)
bits.append(style)
elif m.group(1) == '' or m.group(1) == '__end__':
prevstyle = stack.pop()
if prevstyle:
bits.append("\033[0m")
bits.append(''.join(stack))
else:
stack.append('')
start = m.end(0)
m = r.search(string, start)
bits.append(string[start:])
bits.append("\033[0m")
return ''.join(bits)
class _HtmlStyler(object):
"""
HTML styler. Converts the emk style tags into CSS classes.
Each log record (ie, an entire log message) is surrounded by <div class="emk_log emk_$levelname>...<\div>" tags,
where the $levelname is debug, info, warning etc. Each emk style tag is converted into a <span class="emk_$tag">...<\span>,
with $tag being the emk tag string.
The characters '<', '>', and '&' are escaped for HTML. Four consecutive spaces will be replaced with four non-breaking spaces
for indentation. Newlines in log messages will be repalced with <br>.
Using this styler, the emk output can be inserted into an HTML page with appropriate CSS to make it look fancy.
Example CSS:
<style type="text/css">
div.emk_log {margin: 0.2em 0; font-family: Arial, Helvetica, sans-serif;}
div.emk_debug {color:blue;}
.emk_warning .emk_logtype {font-weight:bold;}
.emk_error .emk_logtype {font-weight:bold; color:red;}
.emk_important {font-weight:bold; color:red;}
.emk_stderr {color:red;}
.emk_u {text-decoration:underline;}
.emk_bold {font-weight:bold;}
.emk_rule_stack {color:blue;}
div.emk_log:nth-child(even) { background-color:#fff; }
div.emk_log:nth-child(odd) { background-color:#eee; }
</style>
"""
def __init__(self):
self.div_regex = re.compile("\000\001__start__\001\000")
self.end_div_regex = re.compile("\000\001__end__\001\000" + r'\s*')
self.span_regex = re.compile("\000\001([0-9A-Za-z_]+)\001\000")
def style(self, string, record):
string = string.replace('&', '&').replace('<', '<').replace('>', '>')
string = self.div_regex.sub('<div class="emk_log emk_%s">' % (record.orig_levelname), string)
string = self.end_div_regex.sub('</div>', string)
string = self.span_regex.sub(r'<span class="emk_\1">', string)
string = string.replace("\000\001\001\000", '</span>').replace("\n", "<br>").replace(" ", " ")
return string
class _Formatter(logging.Formatter):
"""
Formatter for emk log messages.
This formatter converts the log levelname to lowercase. If "extra={'adorn':False}" was passed to the log call,
the message will be passed to the styler as-is. Otherwise, the format string is interpolated using the log record's __dict__.
Properties:
format_str -- The format string to use for normal ("adorned") log messages.
styler -- The log styler to use to convert emk style tags.
"""
def __init__(self, format):
self.format_str = format
self.styler = _NoStyler()
def format(self, record):
record.message = record.getMessage()
record.orig_levelname = record.levelname.lower()
record.levelname = _style_tag('logtype') + record.levelname.lower() + _style_tag('')
if record.__dict__.get("adorn") is False:
return self.styler.style(_style_tag('__start__') + record.message + _style_tag('__end__'), record)
return self.styler.style(_style_tag('__start__') + (self.format_str % (record.__dict__)) + _style_tag('__end__'), record)
class _WindowsOutputHandler(logging.StreamHandler):
def __init__(self, stream=None):
super(_WindowsOutputHandler, self).__init__(stream)
self._windows_color_map = {
0: 0x00, # black
1: 0x04, # red
2: 0x02, # green
3: 0x06, # yellow
4: 0x01, # blue
5: 0x05, # magenta
6: 0x03, # cyan
7: 0x07, # white
}
self._handle = None
import ctypes
try:
fd = stream.fileno()
if fd in (1, 2): # stdout or stderr
self._handle = ctypes.windll.kernel32.GetStdHandle(-10 - fd)
self.set_text_attr = ctypes.windll.kernel32.SetConsoleTextAttribute
except IOError:
pass
self.r = re.compile("\033\[([0-9]+)m")
self._default_style = 0x07
def _get_style(self, current_style, ansi_code):
if ansi_code == 0:
return self._default_style
elif ansi_code == 1:
return current_style | 0x08
elif 30 <= ansi_code <= 37:
return (current_style & ~0x07) | self._windows_color_map[ansi_code - 30]
elif 40 <= ansi_code <= 47:
return (current_style & ~0x70) | (self._windows_color_map[ansi_code - 40] << 4)
else:
return current_style
def _output(self, string):
_handle = self._handle
stream = self.stream
r = self.r
start = 0
current_style = self._default_style
m = r.search(string, start)
while m:
stream.write(string[start:m.start(0)])
code = int(m.group(1))
current_style = self._get_style(current_style, code)
if _handle:
self.set_text_attr(_handle, current_style)
start = m.end(0)
m = r.search(string, start)
stream.write(string[start:])
def emit(self, record):
try:
msg = self.format(record)
self._output(msg)
self.stream.write('\n')
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
def _find_project_dir(path):
dir = path
prev = None
while dir != prev:
if os.path.isfile(os.path.join(dir, "emk_project.py")):
return dir
prev = dir
dir, tail = os.path.split(dir)
return dir
def _try_call_method(mod, name):
try:
func = getattr(mod.instance, name)
except AttributeError:
return
try:
func()
except _BuildError:
raise
except Exception:
raise _BuildError("Error running %s.%s()" % (mod.name, name), _get_exception_info())
def _flatten_gen(args):
# generator to convert args into a list of strings
# args might be a string, or a list containing strings or lists
global _string_type
if isinstance(args, (_string_type, _Always_Build)):
yield args
else: # assume a list-like thing
for arg in args:
for s in _flatten_gen(arg):
yield s
def _get_exception_info():
t, value, trace = sys.exc_info()
stack = traceback.extract_tb(trace)
lines = ["%s: %s" % (t.__name__, str(value))]
lines.extend(_format_stack(_filter_stack(stack)))
return lines
emk_dev = False
def _filter_stack(stack):
"""
Filter the given stack to remove leading internal stack frames that are not useful for users.
"""
if emk_dev:
return stack
new_stack = []
entered_emk = False
left_emk = False
for item in stack:
if left_emk:
new_stack.append(item)
elif entered_emk:
if not __file__.startswith(item[0]):
left_emk = True
new_stack.append(item)
elif __file__.startswith(item[0]):
entered_emk = True
if not entered_emk:
return stack
return new_stack
def _format_stack(stack):
return ["%s line %s, in %s: '%s'" % item for item in stack]
def _format_decorator_stack(stack):
if not stack:
return stack
first_line = stack[0]
result = ["%s line %s (or later), in %s" % (first_line[0], first_line[1]+1, first_line[2])]
result.extend(_format_stack(stack[1:]))
return result
def _make_abspath(rel_path, scope):
"""
Make a path absolute, using the scope dir as a base for relative paths.
"""
if os.path.isabs(rel_path):
return rel_path
return os.path.join(scope.dir, rel_path)
def _make_target_abspath(rel_path, scope):
"""
Return a canonical target path based on the current scope. The proj and build dir placeholders will
be replaced according to the current scope.
"""
if rel_path.startswith(emk.proj_dir_placeholder):
rel_path = rel_path.replace(emk.proj_dir_placeholder, scope.proj_dir, 1)
if os.path.isabs(scope.build_dir):
start, sep, end = rel_path.partition(emk.build_dir_placeholder)
if sep:
path = os.path.realpath(scope.build_dir + end)
else:
path = rel_path
else:
path = rel_path.replace(emk.build_dir_placeholder, scope.build_dir)
return os.path.realpath(_make_abspath(path, scope))
def _make_require_abspath(rel_path, scope):
"""
Return an absolute require path based on the current scope. The proj dir placeholder will
be replaced according to the current scope; the build dir placeholder will not be replaced until
later, in case the build dir for the given path is not yet known.
"""
if rel_path is emk.ALWAYS_BUILD:
return emk.ALWAYS_BUILD
if rel_path.startswith(emk.proj_dir_placeholder):
rel_path = rel_path.replace(emk.proj_dir_placeholder, scope.proj_dir, 1)
return os.path.realpath(_make_abspath(rel_path, scope))
class EMK_Base(object):
"""
Private implementation details of emk. The public API is derived from this class.
"""
def __init__(self, args):
global emk_dev
self._flatten_gen = _flatten_gen
self.log = logging.getLogger("emk")
if sys.platform == "win32":
handler = _WindowsOutputHandler(sys.stdout)
else:
handler = logging.StreamHandler(sys.stdout)
self.formatter = _Formatter("%(name)s (%(levelname)s): %(message)s")
handler.setFormatter(self.formatter)
self.log.addHandler(handler)
self.log.propagate = False
self.build_dir_placeholder = "$:build:$"
self.proj_dir_placeholder = "$:proj:$"
global _module_path
self._emk_dir, tail = os.path.split(_module_path)
self._local = threading.local()
self._local.current_rule = None
self._prebuild_funcs = [] # list of (scope, func)
self._postbuild_funcs = [] # list of (scope, func)
self._targets = {} # map absolute target name -> target
self._rules = []
self._bad_rules = []
self._visited_dirs = {}
self._current_proj_dir = None
self._stored_subproj_scopes = {} # map subproj path to loaded subproj scope (_ScopeData)
self._known_build_dirs = {} # map path to build dir defined for that path
self._all_loaded_modules = {} # map absolute module path to module
self.ALWAYS_BUILD = _Always_Build()
self._auto_targets = set()
self._aliases = {}
self._attached_dependencies = {}
self._secondary_dependencies = {}
self._weak_dependencies = {}
self._requires_rule = set()
self._rebuild_if_changed = set()
self._fixed_aliases = {}
self._fixed_auto_targets = []
self._must_build = []
self._done_build = False
self._added_rule = False
self._cleaning = False
self._building = False
self._did_run = False
self._toplevel_examined_targets = set()
self._lock = threading.Lock()
# parse args
log_levels = {"debug":logging.DEBUG, "info":logging.INFO, "warning":logging.WARNING, "error":logging.ERROR, "critical":logging.CRITICAL}
self._options = {}
self.log.setLevel(logging.INFO)
self._options["log"] = "info"
self._options["emk_dev"] = "no"
self._build_threads = multiprocessing.cpu_count()
self._options["threads"] = "x"
stylers = {"no":_NoStyler, "console":_ConsoleStyler, "html":_HtmlStyler, "passthrough":_PassthroughStyler}
self._options["style"] = "console"
self.traces = set()
self._trace_unchanged = False
self._options["trace_unchanged"] = "no"
self._explicit_targets = set()
for arg in args:
if '=' in arg:
key, eq, val = arg.partition('=')
if key == "explicit_target":
self._explicit_targets.add(val)
else:
if key == "log":
level = val.lower()
if level in log_levels:
self.log.setLevel(log_levels[level])
else:
self.log.error("Unknown log level '%s'", level)
elif key == "emk_dev" and val == "yes":
emk_dev = True
elif key == "threads":
if val != "x":
try:
val = int(val, base=0)
if val < 1:
val = 1
except ValueError:
self.log.error("Thread count '%s' cannot be converted to an integer", val)
val = 1
self._build_threads = val
elif key == "style":
if val not in stylers:
self.log.error("Unknown log style option '%s'", val)
val = "no"
elif key == "trace":
self.traces = set(val.split(','))
elif key == "trace_unchanged" and val == "yes":
self._trace_unchanged = True
self._options[key] = val
else:
self._explicit_targets.add(arg)
self.formatter.styler = stylers[self._options["style"]]()
if "clean" in self._explicit_targets:
self._cleaning = True
self._explicit_targets = set(["clean"])
scope = property(lambda self: self._local.current_scope)
def _import_from(self, paths, name, set_scope_dir=False):
if self.building:
stack = _format_stack(_filter_stack(traceback.extract_stack()[:-1]))
raise _BuildError("Cannot call import_from() when building", stack)
fixed_paths = [_make_target_abspath(path, self.scope) for path in _flatten_gen(paths)]
oldpath = os.getcwd()
fp = None
try:
fp, pathname, description = imp.find_module(name, fixed_paths)
mpath = os.path.realpath(pathname)
d, tail = os.path.split(mpath)
os.chdir(d)
if description[2] == imp.PY_COMPILED and not os.path.isfile(name + ".py"):
raise ImportError("No matching .py")
if set_scope_dir:
self.scope.dir = d
return imp.load_module(name, fp, pathname, description)
except ImportError:
self.log.info("Could not import '%s' from %s", name, fixed_paths)
except _BuildError:
raise
except Exception as e:
raise _BuildError("Error importing '%s' from %s" % (name, fixed_paths), _get_exception_info())
finally:
os.chdir(oldpath)
if fp:
fp.close()
return None
def _get_target(self, path, create_new=False):
t = self._targets.get(path)
if t is not None:
return t
t = self._fixed_aliases.get(path)
if t is not None:
return t
if create_new:
self.log.debug("Creating artificial target for %s", path)
target = _Target(path, None)
self._targets[path] = target
return target
def _resolve_build_dirs(self, dirs):
# fix paths (convert $:build:$)
updated_paths = []
for path in dirs:
if path is self.ALWAYS_BUILD:
updated_paths.append(path)
continue
begin, build, end = path.partition(self.build_dir_placeholder)
if build:
d = os.path.dirname(begin)
if d in self._known_build_dirs:
bd = self._known_build_dirs[d]
if os.path.isabs(bd):
n = os.path.realpath(bd + end)
else:
n = begin + bd + end
updated_paths.append(n)
self.log.debug("Fixed %s in path: %s => %s" % (self.build_dir_placeholder, path, n))
else:
raise _BuildError("Could not resolve %s for path %s" % (self.build_dir_placeholder, path))
else:
updated_paths.append(path)
return updated_paths
def _fix_explicit_targets(self):
fixed_targets = set()
for target in self._explicit_targets:
fixed_targets.add(_make_target_abspath(target, self.scope))
self._explicit_targets = fixed_targets
def _fix_traces(self):
fixed_traces = set()
for trace in self.traces:
fixed_traces.add(_make_target_abspath(trace, self.scope))
self.traces = fixed_traces
def _remove_artificial_targets(self):
real_targets = {}
for path, target in self._targets.items():
if target.rule:
real_targets[path] = target
self._targets = real_targets
def _fix_aliases(self):
unfixed_aliases = self._aliases.copy()
fixed_aliases = {}
did_fix = True
while unfixed_aliases and did_fix:
unfixed = {}
did_fix = False
for alias, target in unfixed_aliases.items():
t = self._targets.get(target)
if t is not None:
did_fix = True
fixed_aliases[alias] = t
self.log.debug("Fixed alias %s => %s", alias, t.abs_path)
elif target in fixed_aliases:
did_fix = True
fixed_aliases[alias] = fixed_aliases[target]
self.log.debug("Fixed alias %s => %s", alias, fixed_aliases[target].abs_path)
else:
unfixed[alias] = target
unfixed_aliases = unfixed
# can't fix any more, so assume the rest refer to files with no rules
for alias, target in unfixed_aliases.items():
self.log.debug("could not fix alias %s => %s", alias, target)
t = _Target(target, None)
self._targets[target] = t
fixed_aliases[alias] = t
self._fixed_aliases = fixed_aliases
def _fix_depends(self):
leftovers = {}
for path, depends in self._secondary_dependencies.items():
target = self._get_target(path)
if target:
if target._built:
raise _BuildError("Cannot add secondary dependencies to '%s' since it has already been built" % (target.abs_path))
new_deps = set(self._resolve_build_dirs(depends))
target.rule.secondary_deps |= new_deps
else:
self.log.debug("Target %s had secondary dependencies, but there is no rule for it yet", path)
leftovers[path] = depends
self._secondary_dependencies = leftovers
def _fix_weak_depends(self):
leftovers = {}
for path, depends in self._weak_dependencies.items():
target = self._get_target(path)
if target:
if target._built:
self.log.info("Cannot add weak dependencies to '%s' since it has already been built" % (target.abs_path))
continue
new_deps = set(self._resolve_build_dirs(depends))
target.rule.weak_deps |= new_deps
else:
self.log.debug("Target %s had weak dependencies, but there is no rule for it yet", path)
leftovers[path] = depends
self._weak_dependencies = leftovers
def _fix_attached(self):
for path, attached in self._attached_dependencies.items():
target = self._get_target(path)
if target:
new_deps = set(self._resolve_build_dirs(attached))
target.attached = target.attached.union(new_deps)
if target._built: # need to build now, since it was attached to something that was already built
l = [self._get_target(a) for a in new_deps]
dep_targets = [t for t in l if t]
for d in dep_targets:
if not d._built:
self._must_build.append(d)
else:
self.log.debug("Target %s was attached to, but not yet defined as a product of a rule", path)
def _fix_requires(self, rule):
if rule._built:
return
rule.requires = self._resolve_build_dirs(rule.requires)
secondaries = set(self._resolve_build_dirs(rule.secondary_deps))
updated_paths = secondaries.union(set(rule.requires))
weak_secondaries = set(self._resolve_build_dirs(rule.weak_deps)) - updated_paths
# convert paths to actual targets
required_targets = []
for path in updated_paths:
target = self._get_target(path, create_new=True)
target._required_by.add(rule) # when the target is built, we need to know which rules to examine for further building
required_targets.append((target, False))
for path in weak_secondaries:
target = self._get_target(path, create_new=True)
if target.rule:
target._required_by.add(rule)
required_targets.append((target, True))
rule._required_targets = required_targets
def _fix_auto_targets(self):
self._fixed_auto_targets = []
for path in self._auto_targets:
self._fixed_auto_targets.append(self._get_target(path, create_new=True))
self._auto_targets.clear() # don't need these anymore since they will be built from the fixed list if necessary
def _fix_requires_rule(self):
self._requires_rule = set(self._resolve_build_dirs(self._requires_rule))
def _fix_rebuild_if_changed(self):
for path in self._resolve_build_dirs(self._rebuild_if_changed):
t = self._targets.get(path)
if t:
t._rebuild_if_changed = True
def _setup_rule_cache(self, rule):
paths = [t.abs_path for t in rule.produces]
paths.sort()
rule._key = key = hashlib.md5('\0'.join(paths)).hexdigest()
cache = rule.scope._cache.setdefault("rules", {}).setdefault(key, {})
rule._cache = cache
def _toplevel_examine_target(self, target):
if not target in self._toplevel_examined_targets:
self._toplevel_examined_targets.add(target)
self._examine_target(target, False)
def _examine_target(self, target, weak):
if target._built or target._visited is True or (target._visited == "weak" and weak):
return