-
Notifications
You must be signed in to change notification settings - Fork 10
/
hancho.py
executable file
·1621 lines (1253 loc) · 54.6 KB
/
hancho.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/python3
# pylint: disable=too-many-lines
# pylint: disable=protected-access
# pylint: disable=unused-argument
"""Hancho v0.4.0 @ 2024-11-01 - A simple, pleasant build system."""
from os import path
import argparse
import asyncio
import builtins
import copy
import glob
import inspect
import io
import json
import os
import random
import re
import shutil
import subprocess
import sys
import time
import traceback
import types
from collections import abc
# If we were launched directly, a reference to this module is already in sys.modules[__name__].
# Stash another reference in sys.modules["hancho"] so that build.hancho and descendants don't try
# to load a second copy of Hancho.
sys.modules["hancho"] = sys.modules[__name__]
# ---------------------------------------------------------------------------------------------------
# Logging stuff
first_line_block = True
def log_line(message):
app.log += message
if not app.flags.quiet:
sys.stdout.write(message)
sys.stdout.flush()
def log(message, *, sameline=False, **kwargs):
"""Simple logger that can do same-line log messages like Ninja."""
if not sys.stdout.isatty():
sameline = False
if sameline:
kwargs.setdefault("end", "")
output = io.StringIO()
print(message, file=output, **kwargs)
output = output.getvalue()
if not output:
return
if sameline:
output = output[: os.get_terminal_size().columns - 1]
output = "\r" + output + "\x1B[K"
log_line(output)
else:
if app.line_dirty:
log_line("\n")
log_line(output)
app.line_dirty = sameline
def line_block(lines):
count = len(lines)
global first_line_block # pylint: disable=global-statement
if not first_line_block:
print(f"\x1b[{count}A")
else:
first_line_block = False
for y in range(count):
if y > 0:
print()
line = lines[y]
if line is not None:
line = line[: os.get_terminal_size().columns - 20]
print(line, end="")
print("\x1b[K", end="")
sys.stdout.flush()
def log_exception():
log(color(255, 128, 128), end="")
log(traceback.format_exc())
log(color(), end="")
# ---------------------------------------------------------------------------------------------------
# Path manipulation
def abs_path(raw_path, strict=False) -> str | list[str]:
if listlike(raw_path):
return [abs_path(p, strict) for p in raw_path]
result = path.abspath(raw_path)
if strict and not path.exists(result):
raise FileNotFoundError(raw_path)
return result
def rel_path(path1, path2):
if listlike(path1):
return [rel_path(p, path2) for p in path1]
# Generating relative paths in the presence of symlinks doesn't work with either
# Path.relative_to or os.path.relpath - the former balks at generating ".." in paths, the
# latter does generate them but "path/with/symlink/../foo" doesn't behave like you think it
# should. What we really want is to just remove redundant cwd stuff off the beginning of the
# path, which we can do with simple string manipulation.
return path1.removeprefix(path2 + "/") if path1 != path2 else "."
def join_path(path1, path2, *args):
result = join_path2(path1, path2, *args)
return flatten(result) if listlike(result) else result
def join_path2(path1, path2, *args):
if len(args) > 0:
return [join_path(path1, p) for p in join_path(path2, *args)] # pylint: disable=E1120
if listlike(path1):
return [join_path(p, path2) for p in flatten(path1)]
if listlike(path2):
return [join_path(path1, p) for p in flatten(path2)]
if not path2:
raise ValueError(f"Cannot join '{path1}' with '{type(path2)}' == '{path2}'")
return path.join(path1, path2)
def normalize_path(file_path):
assert isinstance(file_path, str)
assert not macro_regex.search(file_path)
file_path = path.abspath(path.join(os.getcwd(), file_path))
file_path = path.normpath(file_path)
assert path.isabs(file_path)
# if not path.isfile(file_path):
# print(f"Could not find file {file_path}")
# assert path.isfile(file_path)
return file_path
# ---------------------------------------------------------------------------------------------------
# Helper methods
def listlike(variant):
return isinstance(variant, abc.Sequence) and not isinstance(
variant, (str, bytes, bytearray)
)
def dictlike(variant):
return isinstance(variant, abc.Mapping)
def flatten(variant):
if listlike(variant):
return [x for element in variant for x in flatten(element)]
elif variant is None:
return []
return [variant]
def join_prefix(prefix, strings):
return [prefix + str(s) for s in flatten(strings)]
def join_suffix(strings, suffix):
return [str(s) + suffix for s in flatten(strings)]
def stem(filename):
filename = flatten(filename)[0]
filename = path.basename(filename)
return path.splitext(filename)[0]
def color(red=None, green=None, blue=None):
"""Converts RGB color to ANSI format string."""
# Color strings don't work in Windows console, so don't emit them.
# if not Config.use_color or os.name == "nt":
# return ""
if red is None:
return "\x1B[0m"
return f"\x1B[38;2;{red};{green};{blue}m"
def run_cmd(cmd):
"""Runs a console command synchronously and returns its stdout with whitespace stripped."""
return subprocess.check_output(cmd, shell=True, text=True).strip()
def swap_ext(name, new_ext):
"""Replaces file extensions on either a single filename or a list of filenames."""
if isinstance(name, Task):
name = name.out_files
if listlike(name):
return [swap_ext(n, new_ext) for n in name]
return path.splitext(name)[0] + new_ext
def mtime(filename):
"""Gets the file's mtime and tracks how many times we've called mtime()"""
app.mtime_calls += 1
return os.stat(filename).st_mtime_ns
def maybe_as_number(text):
"""Tries to convert a string to an int, then a float, then gives up. Used for ingesting
unrecognized flag values."""
try:
return int(text)
except ValueError:
try:
return float(text)
except ValueError:
return text
####################################################################################################
# Heplers for managing variants (could be Config, list, dict, etc.)
def merge_variant(lhs, rhs):
if isinstance(lhs, Config) and dictlike(rhs):
for key, rval in rhs.items():
lval = lhs.get(key, None)
if lval is None or rval is not None:
lhs[key] = merge_variant(lval, rval)
return lhs
return copy.deepcopy(rhs)
def apply_variant(key, val, apply):
apply(key, val)
if dictlike(val):
for key2, val2 in val.items():
apply_variant(key2, val2, apply)
elif listlike(val):
for key2, val2 in enumerate(val):
apply_variant(key2, val2, apply)
return val
def map_variant(key, val, apply):
val = apply(key, val)
if dictlike(val):
for key2, val2 in val.items():
val[key2] = map_variant(key2, val2, apply)
elif listlike(val):
for key2, val2 in enumerate(val):
val[key2] = map_variant(key2, val2, apply)
return val
async def await_variant(variant):
"""Recursively replaces every awaitable in the variant with its awaited value."""
if isinstance(variant, Promise):
variant = await variant.get()
variant = await await_variant(variant)
elif isinstance(variant, Task):
await variant.await_done()
variant = await await_variant(variant.out_files)
elif dictlike(variant):
for key, val in variant.items():
variant[key] = await await_variant(val)
elif listlike(variant):
for key, val in enumerate(variant):
variant[key] = await await_variant(val)
else:
while inspect.isawaitable(variant):
variant = await variant
return variant
####################################################################################################
class Dumper:
def __init__(self, max_depth=2):
self.depth = 0
self.max_depth = max_depth
def indent(self):
return " " * self.depth
def dump(self, variant):
result = f"{type(variant).__name__} @ {hex(id(variant))} "
if isinstance(variant, Task):
result += self.dump_dict(variant.__dict__)
elif isinstance(variant, HanchoAPI):
result += self.dump_dict(variant.__dict__)
elif isinstance(variant, Config):
result += self.dump_dict(variant)
elif listlike(variant):
result += self.dump_list(variant)
elif dictlike(variant):
result = ""
result += self.dump_dict(variant)
elif isinstance(variant, str):
result = ""
result += '"' + str(variant) + '"'
else:
result = ""
result += str(variant)
return result
def dump_list(self, l):
if len(l) == 0:
return "[]"
if len(l) == 1:
return f"[{self.dump(l[0])}]"
if self.depth >= self.max_depth:
return "[...]"
result = "[\n"
self.depth += 1
for val in l:
result += self.indent() + self.dump(val) + ",\n"
self.depth -= 1
result += self.indent() + "]"
return result
def dump_dict(self, d):
if self.depth >= self.max_depth:
return "{...}"
result = "{\n"
self.depth += 1
for key, val in d.items():
result += self.indent() + f"{key} = " + self.dump(val) + ",\n"
self.depth -= 1
result += self.indent() + "}"
return result
####################################################################################################
class Utils:
# fmt: off
abs_path = staticmethod(abs_path)
color = staticmethod(color)
flatten = staticmethod(flatten)
glob = staticmethod(glob.glob)
hancho_dir = path.dirname(path.realpath(__file__))
join_path = staticmethod(join_path)
join_prefix = staticmethod(join_prefix)
join_suffix = staticmethod(join_suffix)
len = staticmethod(len)
log = staticmethod(log)
path = path
print = staticmethod(print)
re = re
rel_path = staticmethod(rel_path)
run_cmd = staticmethod(run_cmd)
stem = staticmethod(stem)
swap_ext = staticmethod(swap_ext)
# fmt: on
####################################################################################################
class Config(dict, Utils):
"""
A Config object is a specialized dict that also supports 'config.attribute' syntax as well as
arbitrary "merging" of dicts/keys and text template expansion.
"""
def __init__(self, *args, **kwargs):
self.merge(*args)
self.merge(kwargs)
def __repr__(self):
return Dumper(2).dump(self)
def __getattr__(self, key):
if not dict.__contains__(self, key):
raise AttributeError(name=key, obj=self)
result = dict.__getitem__(self, key)
return result
def __setattr__(self, key, val):
return dict.__setitem__(self, key, val)
def __delattr__(self, key):
if not dict.__contains__(self, key):
raise AttributeError(name=key, obj=self)
return dict.__delitem__(self, key)
# ----------------------------------------
def merge(self, *args, **kwargs):
for arg in flatten(args):
if arg is not None:
assert dictlike(arg)
merge_variant(self, arg)
merge_variant(self, kwargs)
return self
def expand(self, variant):
return expand_variant(Expander(self), variant)
def rel(self, sub_path):
return rel_path(sub_path, expand_variant(self, self.task_dir))
####################################################################################################
# Hancho's text expansion system. Works similarly to Python's F-strings, but with quite a bit more
# power.
#
# The code here requires some explanation.
#
# We do not necessarily know in advance how the users will nest strings, macros, callbacks,
# etcetera. Text expansion therefore requires dynamic-dispatch-type stuff to ensure that we always
# end up with flat strings.
#
# The result of this is that the functions here are mutually recursive in a way that can lead to
# confusing callstacks, but that should handle every possible case of stuff inside other stuff.
#
# The depth checks are to prevent recursive runaway - the MAX_EXPAND_DEPTH limit is arbitrary but
# should suffice.
#
# Also - TEFINAE - Text Expansion Failure Is Not An Error. Config objects can contain macros that
# are not expandable inside the config. This allows config objects nested inside other configs to
# contain templates that can only be expanded in the context of the outer config, and things will
# still Just Work.
# The maximum number of recursion levels we will do to expand a macro.
# Tests currently require MAX_EXPAND_DEPTH >= 6
MAX_EXPAND_DEPTH = 20
# Matches macros inside a string.
macro_regex = re.compile("{[^{}]*}")
# ----------------------------------------
# Helper methods
def trace_prefix(expander):
"""Prints the left-side trellis of the expansion traces."""
assert isinstance(expander, Expander)
return hex(id(expander.config)) + ": " + ("┃ " * app.expand_depth)
def trace_variant(variant):
"""Prints the right-side values of the expansion traces."""
if callable(variant):
return f"Callable @ {hex(id(variant))}"
elif isinstance(variant, Config):
return f"Config @ {hex(id(variant))}'"
elif isinstance(variant, Expander):
return f"Expander @ {hex(id(variant.config))}'"
else:
return f"'{variant}'"
def expand_inc():
"""Increments the current expansion recursion depth."""
app.expand_depth += 1
if app.expand_depth > MAX_EXPAND_DEPTH:
raise RecursionError("TemplateRecursion: Text expansion failed to terminate")
def expand_dec():
"""Decrements the current expansion recursion depth."""
app.expand_depth -= 1
if app.expand_depth < 0:
raise RecursionError("Text expand_inc/dec unbalanced")
def stringify_variant(variant):
"""Converts any type into an expansion-compatible string."""
if variant is None:
return ""
elif isinstance(variant, Expander):
return stringify_variant(variant.config)
elif isinstance(variant, Task):
return stringify_variant(variant.out_files)
elif listlike(variant):
variant = [stringify_variant(val) for val in variant]
return " ".join(variant)
else:
return str(variant)
class Expander:
"""Wraps a Config object and expands all fields read from it."""
def __init__(self, config):
self.config = config
# We save a copy of 'trace', otherwise we end up printing traces of reading trace.... :P
self.trace = config.get("trace", app.flags.trace)
def __getitem__(self, key):
return self.get(key)
def __getattr__(self, key):
return self.get(key)
def get(self, key):
try:
# This has to be getattr() so that we also check other Config base classes like Utils.
val = getattr(self.config, key)
except KeyError:
if self.trace:
log(trace_prefix(self) + f"Read '{key}' failed")
raise
if self.trace:
if key != "__iter__":
log(trace_prefix(self) + f"Read '{key}' = {trace_variant(val)}")
val = expand_variant(self, val)
return val
def expand_text(expander, text):
"""Replaces all macros in 'text' with their expanded, stringified values."""
if not macro_regex.search(text):
return text
if expander.trace:
log(trace_prefix(expander) + f"┏ expand_text '{text}'")
expand_inc()
# ==========
temp = text
result = ""
while span := macro_regex.search(temp):
result += temp[0 : span.start()]
macro = temp[span.start() : span.end()]
variant = expand_macro(expander, macro)
result += stringify_variant(variant)
temp = temp[span.end() :]
result += temp
# ==========
expand_dec()
if expander.trace:
log(trace_prefix(expander) + f"┗ expand_text '{text}' = '{result}'")
# If expansion changed the text, try to expand it again.
if result != text:
result = expand_text(expander, result)
return result
def expand_macro(expander, macro):
"""Evaluates the contents of a "{macro}" string. If eval throws an exception, the macro is
returned unchanged."""
assert isinstance(expander, Expander)
if expander.trace:
log(trace_prefix(expander) + f"┏ expand_macro '{macro}'")
expand_inc()
# ==========
result = macro
failed = False
try:
result = eval(macro[1:-1], {}, expander) # pylint: disable=eval-used
except BaseException: # pylint: disable=broad-exception-caught
failed = True
# ==========
expand_dec()
if expander.trace:
if failed:
log(trace_prefix(expander) + f"┗ expand_macro '{macro}' failed")
else:
log(trace_prefix(expander) + f"┗ expand_macro '{macro}' = {result}")
return result
def expand_variant(expander, variant):
"""Expands all macros anywhere inside 'variant', making deep copies where needed so we don't
expand someone else's data."""
# This level of tracing is too spammy to be useful.
# if expander.trace:
# log(trace_config(expander) + f"┏ expand_variant {trace_variant(variant)}")
# expand_inc()
if isinstance(variant, Config):
result = Expander(variant)
elif listlike(variant):
result = [expand_variant(expander, val) for val in variant]
elif dictlike(variant):
result = {
expand_variant(expander, key): expand_variant(expander, val)
for key, val in variant.items()
}
elif isinstance(variant, str):
result = expand_text(expander, variant)
else:
result = variant
# expand_dec()
# if expander.trace:
# log(trace_config(expander) + f"┗ expand_variant {trace_variant(variant)} = {trace_variant(result)}")
return result
####################################################################################################
class Promise:
def __init__(self, task, *args):
self.task = task
self.args = args
async def get(self):
await self.task.await_done()
if len(self.args) == 0:
return self.task.out_files
elif len(self.args) == 1:
return self.task.config[self.args[0]]
else:
return [self.task.config[field] for field in self.args]
####################################################################################################
class TaskState:
DECLARED = "DECLARED"
QUEUED = "QUEUED"
STARTED = "STARTED"
AWAITING_INPUTS = "AWAITING_INPUTS"
TASK_INIT = "TASK_INIT"
AWAITING_JOBS = "AWAITING_JOBS"
RUNNING_COMMANDS = "RUNNING_COMMANDS"
FINISHED = "FINISHED"
CANCELLED = "CANCELLED"
FAILED = "FAILED"
SKIPPED = "SKIPPED"
BROKEN = "BROKEN"
####################################################################################################
class Task:
default_desc = "{command}"
default_command = None
default_task_dir = "{mod_dir}"
default_build_dir = "{build_root}/{build_tag}/{rel_path(task_dir, repo_dir)}"
default_build_root = "{repo_dir}/build"
default_build_tag = ""
def __init__(self, *args, **kwargs):
self.config = Config(
desc=Task.default_desc,
command=Task.default_command,
)
self.config.merge(*args, **kwargs)
self._task_index = 0
self.in_files = []
self.out_files = []
self._state = TaskState.DECLARED
self._reason = None
self.asyncio_task = None
self._loaded_files = list(app.loaded_files)
self._stdout = ""
self._stderr = ""
self._returncode = -1
app.all_tasks.append(self)
#if self.config.get("queue", False):
# self.queue()
# ----------------------------------------
# WARNING: Tasks must _not_ be copied or we'll hit the "Multiple tasks generate file X" checks.
def __copy__(self):
return self
def __deepcopy__(self, memo):
return self
def __repr__(self):
return Dumper(2).dump(self)
# ----------------------------------------
def queue(self):
if self._state is TaskState.DECLARED:
app.queued_tasks.append(self)
self._state = TaskState.QUEUED
def apply(_, val):
if isinstance(val, Task):
val.queue()
return val
map_variant(None, self.config, apply)
def start(self):
self.queue()
if self._state is TaskState.QUEUED:
self.asyncio_task = asyncio.create_task(self.task_main())
self._state = TaskState.STARTED
app.tasks_started += 1
async def await_done(self):
self.start()
await self.asyncio_task
def promise(self, *args):
return Promise(self, *args)
# -----------------------------------------------------------------------------------------------
def print_status(self):
"""Print the "[1/N] Compiling foo.cpp -> foo.o" status line and debug information"""
verbosity = self.config.get("verbosity", app.flags.verbosity)
log(
f"{color(128,255,196)}[{self._task_index}/{app.tasks_started}]{color()} {self.config.desc}",
sameline=verbosity == 0,
)
# -----------------------------------------------------------------------------------------------
async def task_main(self):
"""Entry point for async task stuff, handles exceptions generated during task execution."""
verbosity = self.config.get("verbosity", app.flags.verbosity)
debug = self.config.get("debug", app.flags.debug)
force = self.config.get("force", app.flags.force)
# Await everything awaitable in this task's config.
# If any of this tasks's dependencies were cancelled, we propagate the cancellation to
# downstream tasks.
try:
assert self._state is TaskState.STARTED
self._state = TaskState.AWAITING_INPUTS
for key, val in self.config.items():
self.config[key] = await await_variant(val)
except BaseException as ex: # pylint: disable=broad-exception-caught
# Exceptions during awaiting inputs means that this task cannot proceed, cancel it.
self._state = TaskState.CANCELLED
app.tasks_cancelled += 1
raise asyncio.CancelledError() from ex
# Everything awaited, task_init runs synchronously.
try:
self._state = TaskState.TASK_INIT
self.task_init()
except asyncio.CancelledError as ex:
# We discovered during init that we don't need to run this task.
self._state = TaskState.CANCELLED
app.tasks_cancelled += 1
raise asyncio.CancelledError() from ex
except BaseException as ex: # pylint: disable=broad-exception-caught
self._state = TaskState.BROKEN
app.tasks_broken += 1
raise ex
# Early-out if this is a no-op task
if self.config.command is None:
app.tasks_finished += 1
self._state = TaskState.FINISHED
return
# Check if we need a rebuild
self._reason = self.needs_rerun(force)
if not self._reason:
app.tasks_skipped += 1
self._state = TaskState.SKIPPED
return
try:
# Wait for enough jobs to free up to run this task.
job_count = self.config.get("job_count", 1)
self._state = TaskState.AWAITING_JOBS
await app.job_pool.acquire_jobs(job_count, self)
# Run the commands.
self._state = TaskState.RUNNING_COMMANDS
app.tasks_running += 1
self._task_index = app.tasks_running
self.print_status()
if verbosity or debug:
log(f"{color(128,128,128)}Reason: {self._reason}{color()}")
for command in flatten(self.config.command):
await self.run_command(command)
if self._returncode != 0:
break
except BaseException as ex: # pylint: disable=broad-exception-caught
# If any command failed, we print the error and propagate it to downstream tasks.
self._state = TaskState.FAILED
app.tasks_failed += 1
raise ex
finally:
await app.job_pool.release_jobs(job_count, self)
# Task finished successfully
self._state = TaskState.FINISHED
app.tasks_finished += 1
# -----------------------------------------------------------------------------------------------
def task_init(self):
"""All the setup steps needed before we run a task."""
debug = self.config.get("debug", app.flags.debug)
if debug:
log(f"\nTask before expand: {self}")
# ----------------------------------------
# Expand task_dir and build_dir
# pylint: disable=attribute-defined-outside-init
self.config.task_dir = abs_path(self.config.expand(self.config.task_dir))
self.config.build_dir = abs_path(self.config.expand(self.config.build_dir))
# Raw tasks may not have a repo_dir.
repo_dir = self.config.get("repo_dir", None)
if repo_dir is not None:
if not self.config.build_dir.startswith(repo_dir):
raise ValueError(
f"Path error, build_dir {self.config.build_dir} is not under repo dir {repo_dir}"
)
# ----------------------------------------
# Expand all in_ and out_ filenames
# We _must_ expand these first before joining paths or the paths will be incorrect:
# prefix + swap(abs_path) != abs(prefix + swap(path))
for key, val in self.config.items():
if key.startswith("in_") or key.startswith("out_"):
def expand_path(_, val):
if not isinstance(val, str):
return val
val = self.config.expand(val)
val = path.normpath(val)
return val
self.config[key] = map_variant(key, val, expand_path)
# Make all in_ and out_ file paths absolute
# FIXME feeling like in_depfile should really be io_depfile...
for key, val in self.config.items():
if key.startswith("out_") or key == "in_depfile":
def move_to_builddir(_, val):
if not isinstance(val, str):
return val
# Note this conditional needs to be first, as build_dir can itself be under
# task_dir
if val.startswith(self.config.build_dir):
# Absolute path under build_dir, do nothing.
pass
elif val.startswith(self.config.task_dir):
# Absolute path under task_dir, move to build_dir
val = rel_path(val, self.config.task_dir)
val = join_path(self.config.build_dir, val)
elif path.isabs(val):
raise ValueError(f"Output file has absolute path that is not under task_dir or build_dir : {val}")
else:
# Relative path, add build_dir
val = join_path(self.config.build_dir, val)
return val
self.config[key] = map_variant(key, val, move_to_builddir)
elif key.startswith("in_"):
def move_to_taskdir(key, val):
if not isinstance(val, str):
return val
if not path.isabs(val):
val = join_path(self.config.task_dir, val)
return val
self.config[key] = map_variant(key, val, move_to_taskdir)
# Gather all inputs to task.in_files and outputs to task.out_files
for key, val in self.config.items():
# Note - we only add the depfile to in_files _if_it_exists_, otherwise we will fail a check
# that all our inputs are present.
if key == "in_depfile":
if path.isfile(val):
self.in_files.append(val)
elif key.startswith("out_"):
self.out_files.extend(flatten(val))
elif key.startswith("in_"):
self.in_files.extend(flatten(val))
# ----------------------------------------
# And now we can expand the command.
self.config.desc = self.config.expand(self.config.desc)
self.config.command = self.config.expand(self.config.command)
if debug:
log(f"\nTask after expand: {self}")
# ----------------------------------------
# Check for task collisions
# FIXME need a test for this that uses symlinks
if self.out_files and self.config.command is not None:
for file in self.out_files:
file = path.realpath(file)
if file in app.filename_to_fingerprint:
raise ValueError(f"TaskCollision: Multiple tasks build {file}")
app.filename_to_fingerprint[file] = self.config.command
# ----------------------------------------
# Sanity checks
# Check for missing input files/paths
if not path.exists(self.config.task_dir):
raise FileNotFoundError(self.config.task_dir)
for file in self.in_files:
if file is None:
raise ValueError("in_files contained a None")
if not path.exists(file):
raise FileNotFoundError(file)
# Check that all build files would end up under build_dir
for file in self.out_files:
if file is None:
raise ValueError("out_files contained a None")
if not file.startswith(self.config.build_dir):
raise ValueError(
f"Path error, output file {file} is not under build_dir {self.config.build_dir}"
)
# Check for duplicate task outputs
if self.config.command:
for file in self.out_files:
#if file in app.all_out_files:
# raise NameError(f"Multiple rules build {file}!")
app.all_out_files.add(file)
# Make sure our output directories exist
if not app.flags.dry_run:
for file in self.out_files:
os.makedirs(path.dirname(file), exist_ok=True)
# -----------------------------------------------------------------------------------------------
def needs_rerun(self, force=False):
"""Checks if a task needs to be re-run, and returns a non-empty reason if so."""
debug = self.config.get("debug", app.flags.debug)
if force:
return f"Files {self.out_files} forced to rebuild"
if not self.in_files:
return "Always rebuild a target with no inputs"
if not self.out_files:
return "Always rebuild a target with no outputs"
# Check if any of our output files are missing.
for file in self.out_files:
if not path.exists(file):
return f"Rebuilding because {file} is missing"
# Check if any of our input files are newer than the output files.