-
Notifications
You must be signed in to change notification settings - Fork 0
/
make.py
executable file
·1962 lines (1520 loc) · 66.1 KB
/
make.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# MAKE.py
# by Lut99
#
# Created:
# 02 Aug 2023, 08:38:41
# Last edited:
# 05 Mar 2024, 11:41:48
# Auto updated?
# Yes
#
# Description:
# Make script for the Brane IDE project.
#
import abc
import argparse
import os
import pathlib
import platform
import shlex
import subprocess
import sys
import time
import typing
##### GLOBALS #####
# Determines if `pdebug()` does anything
DEBUG: bool = True
# Determines any arguments relevant only for targets
TARGET_ARGS: typing.Dict[str, typing.Any] = {}
##### HELPER FUNCTIONS #####
def supports_color():
"""
Returns True if the running system's terminal supports color, and False
otherwise.
From: https://stackoverflow.com/a/22254892
"""
plat = sys.platform
supported_platform = plat != 'Pocket PC' and (plat != 'win32' or
'ANSICON' in os.environ)
# isatty is not always implemented, #6223.
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
return supported_platform and is_a_tty
def perror(message: str):
"""
Prints an error message to stderr with appropriate colouring.
"""
# Deduce the colours to use
start = "\033[91;1m" if supports_color() else ""
mid = "\033[1m" if supports_color() else ""
end = "\033[0m" if supports_color() else ""
# Prints the warning message with those colours
print(f"{mid}[{end}{start}ERROR{end}{mid}] {message}{end}", file=sys.stderr)
def pwarn(message: str):
"""
Prints a warning message to stderr with appropriate colouring.
"""
# Deduce the colours to use
start = "\033[3;1m" if supports_color() else ""
mid = "\033[1m" if supports_color() else ""
end = "\033[0m" if supports_color() else ""
# Prints the warning message with those colours
print(f"{mid}[{end}{start}WARN{end}{mid}] {message}{end}", file=sys.stderr)
def pdebug(message: str):
"""
Prints a debug message to stderr with appropriate colouring.
Note: only prints if the global `DEBUG` is set.
"""
if DEBUG:
# Deduce the colours to use
start = "\033[90;1m" if supports_color() else ""
mid = "\033[90m" if supports_color() else ""
end = "\033[0m" if supports_color() else ""
# Prints the warning message with those colours
print(f"{mid}[{end}{start}DEBUG{end}{mid}] {message}{end}", file=sys.stderr)
def get_active_instance() -> typing.Optional[str]:
"""
Returns the path to the active instance as indicated by Brane.
Note that this function tightly integrates with brane-cli to find the active instance.
Configuration directory location taken as brane_cli does, using https://docs.rs/dirs-2/latest/dirs_2/fn.config_dir.html.
# Returns
The path, or else `None` if we failed. The error is already printed as a warning, then.
"""
# Expand the user path
home = pathlib.Path.home()
if Os.default() == Os.windows():
config = f"{home}\\Appdata\\Roaming"
elif Os.default() == Os.darwin():
config = f"{home}/Library/Preferences"
elif Os.default() == Os.linux():
config = f"{home}/.config"
else:
raise ValueError(f"Unknown OS default '{Os.default()}'")
brane = f"{config}/brane"
# Check if it exists
if not os.path.exists(brane):
# Return the local directory instead
pdebug(f"Brane configuration directory '{brane}' not found; assuming `brane` executable not used")
return None
# Attempt to find the active instance
active = f"{brane}/active_instance"
try:
with open(active, "r") as h:
active_instance = h.read()
except FileNotFoundError:
pwarn(f"Brane configuration directory exists, but no active instance found (run 'brane instance use ...' to make one active)")
pdebug(f"Brane configuration directory: '{brane}'")
pdebug(f"Expected location of active instance file: '{active}'")
return None
except IOError as e:
pwarn(f"Failed to read active instance file '{active}': {e}")
return None
# Attempt to find that instance
instances = f"{brane}/instances"
instance = f"{instances}/{active_instance}"
if not os.path.exists(instance):
pwarn(f"Instance '{active_instance}' is currently marked as active instance, but no such instance found")
return None
# Otherwise yay
return instance
def get_default_api_addr() -> str:
"""
Attempts to get the currently active instance's API endpoint.
If this fails, falls back to 'http://localhost:50051'.
# Returns
The path to the currently active certificate directory.
"""
# Get the active instance's directory
instance = get_active_instance()
if instance is None:
pdebug("Falling back to 'http://localhost:50051'")
return "http://localhost:50051"
# Attempt to read the YAML file with the info
info = f"{instance}/info.yml"
try:
with open(info, "r") as h:
info = h.read()
except IOError as e:
pwarn(f"Failed to read instance info file '{info}': {e}")
pdebug("Falling back to 'http://localhost:50051'")
return "http://localhost:50051"
# Attempt to find the api address
for line in info.splitlines():
if len(line) >= 5 and line[:5] == "api: ":
# We found it, mark whatever follows
return line[5:]
# Otherwise, not found
pwarn(f"Instance info file '{info}' does not mention API address")
pdebug("Falling back to 'http://localhost:50051'")
return "http://localhost:50051"
def get_default_drv_addr() -> str:
"""
Attempts to get the currently active instance's driver endpoint.
If this fails, falls back to 'grpc://localhost:50053'.
# Returns
The path to the currently active certificate directory.
"""
# Get the active instance's directory
instance = get_active_instance()
if instance is None:
pdebug("Falling back to 'http://localhost:50053'")
return "http://localhost:50053"
# Attempt to read the YAML file with the info
info = f"{instance}/info.yml"
try:
with open(info, "r") as h:
info = h.read()
except IOError as e:
pwarn(f"Failed to read instance info file '{info}': {e}")
pdebug("Falling back to 'http://localhost:50053'")
return "http://localhost:50053"
# Attempt to find the api address
for line in info.splitlines():
if len(line) >= 5 and line[:5] == "drv: ":
# We found it, mark whatever follows
return line[5:]
# Otherwise, not found
pwarn(f"Instance info file '{info}' does not mention driver address")
pdebug("Falling back to 'http://localhost:50053'")
return "http://localhost:50053"
def get_default_certs_dir() -> str:
"""
Attempts to get the currently active certificate directory.
If this fails, falls back to './certs'.
# Returns
The path to the currently active certificate directory.
"""
# Get the active instance's directory
instance = get_active_instance()
if instance is None:
pdebug("Falling back to './certs'")
return "./certs"
# If we found it, mark its directory!
return f"{instance}/certs"
##### HELPER STRUCTS #####
T = typing.TypeVar("T")
class ResolveArgs(typing.Generic[T]):
"""
"Generics function" that resolves a given string value in the `TARGET_ARGS` dictionary if it starts with a dollar sign (`$`).
# Arguments
- `key`: The key to resolve.
# Returns
Either the key if it did not start with a dollar sign, or else the resolved value casted to type `T`.
"""
def __call__(self, key: str) -> typing.Union[str, T]:
"""
"Generics function" that resolves a given string value in the `TARGET_ARGS` dictionary if it starts with a dollar sign (`$`).
# Arguments
- `key`: The key to resolve.
# Returns
Either the key if it did not start with a dollar sign, or else the resolved value casted to type `T`.
"""
# See if it starts with the all-important dollar
if len(key) == 0 or key[0] != '$': return key
key = key[1:]
# Else, resolve to the value
if key not in TARGET_ARGS: raise KeyError(f"Unknown key '{key}' in TARGET_ARGS")
value = TARGET_ARGS[key]
# Return it as the target type
return value
class Arch:
"""
Defines a class for keeping track of the target architecture.
"""
_arch: str
# Represents the AMD64 architecture.
AMD64: str = "amd64"
# Represents the ARM64 architecture.
ARM64: str = "arm64"
def __init__(self, arch: str):
"""
Constructor for the Arch.
# Arguments
- `arch`: The string representation of the target architecture. Can be:
- `x86_64` or `amd64` for Arch.Amd64; or
- `aarch64` or `arm64` for Arch.Arm64.
# Returns
A new instance of Self.
# Errors
This function may eror if the input string was an invalid architecture.
"""
# Attempt to parse it
try:
self._arch = self.allowed()[arch]
except KeyError:
raise ValueError(f"Invalid architecture string '{arch}'")
@staticmethod
def default():
"""
Creates a default Arch matching the host's architecture.
"""
if platform.machine().lower() == "x86_64" or platform.machine().lower() == "amd64":
return Arch(Arch.AMD64)
elif platform.machine().lower() == "arm64" or platform.machine().lower() == "aarch64":
return Arch(Arch.ARM64)
else:
pwarn("Could not determine processor architecture; assuming x86-64 (specify it manually using '--arch' if incorrect)")
return Arch(Arch.AMD64)
@staticmethod
def amd64():
"""
Constructor for an x86-64 architecture.
Shorthand for: `Arch(Arch.AMD64)`.
# Returns
A new instance of Self that refers to an x86-64 / AMD64 architecture.
"""
return Arch(Arch.AMD64)
@staticmethod
def arm64():
"""
Constructor for an ARM 64-bit architecture.
Shorthand for: `Arch(Arch.ARM64)`.
# Returns
A new instance of Self that refers to a 64-bit ARM architecture.
"""
return Arch(Arch.ARM64)
def __eq__(self, other: typing.Any) -> bool:
if type(self) == type(other):
return self._arch == other._arch
else:
return False
def __str__(self) -> str:
"""
Serializes the Arch for readability purposes.
"""
if self._arch == Arch.AMD64:
return "AMD64"
elif self._arch == Arch.ARM64:
return "ARM64"
else:
raise ValueError(f"Invalid internal architecture string '{self._arch}'")
def brane(self) -> str:
"""
Serializes the Arch for use in Brane executable names / other Brane executables.
"""
if self._arch == Arch.AMD64:
return "x86_64"
elif self._arch == Arch.ARM64:
return "aarch64"
else:
raise ValueError(f"Invalid internal architecture string '{self._arch}'")
def docker(self) -> str:
"""
Serializes the Arch for use in Docker commands.
"""
if self._arch == Arch.AMD64:
return "amd64"
elif self._arch == Arch.ARM64:
return "arm64"
else:
raise ValueError(f"Invalid internal architecture string '{self._arch}'")
@staticmethod
def allowed() -> typing.Dict[str, str]:
"""
Returns a mapping of all inputs to output architectures.
# Returns
A map of valid string representations mapping to output `Arch`s.
"""
return {
"x86_64" : Arch.AMD64,
"amd64" : Arch.AMD64,
"aarch64" : Arch.ARM64,
"arm64" : Arch.ARM64,
}
class Os:
"""
Defines a class for keeping track of the target operating system.
"""
_os: str
# Represents Windows.
WINDOWS: str = "windows"
# Represents macOS.
DARWIN: str = "darwin"
# Represents Linux.
LINUX: str = "linux"
def __init__(self, os: str):
"""
Constructor for the OS.
# Arguments
- `os`: The string representation of the target operating system. Can be:
- `win` or `windows` for Os.WINDOWS;
- `macos` or `darwin` for Os.DARWIN; or
- `linux` for Os.LINUX.
# Returns
A new instance of Self.
# Errors
This function may eror if the input string was an invalid operating system.
"""
# Attempt to parse it
try:
self._os = self.allowed()[os]
except KeyError:
raise ValueError(f"Invalid operating system string '{os}'")
@staticmethod
def default():
"""
Creates a default OS matching the host's architecture.
"""
if platform.system().lower() == "windows":
return Os(Os.WINDOWS)
elif platform.system().lower() == "darwin":
return Os(Os.DARWIN)
elif platform.system().lower() == "linux":
return Os(Os.LINUX)
else:
pwarn("Could not determine operating system; assuming Linux (specify it manually using '--os' if incorrect)")
return Os(Os.LINUX)
@staticmethod
def windows():
"""
Constructor for a Windows operating system.
Shorthand for: `Os(Os.WINDOWS)`.
# Returns
A new instance of Self that refers to Windows.
"""
return Os(Os.WINDOWS)
@staticmethod
def darwin():
"""
Constructor for a macOS (Darwin) operating system.
Shorthand for: `Os(Os.DARWIN)`.
# Returns
A new instance of Self that refers to macOS.
"""
return Os(Os.DARWIN)
@staticmethod
def linux():
"""
Constructor for a Linux operating system.
Shorthand for: `Os(Os.LINUX)`.
# Returns
A new instance of Self that refers to Linux.
"""
return Os(Os.LINUX)
def __eq__(self, other: typing.Any) -> bool:
if type(self) == type(other):
return self._os == other._os
else:
return False
def __str__(self) -> str:
"""
Serializes the OS for readability purposes.
"""
if self._os == Os.WINDOWS:
return "Windows"
elif self._os == Os.DARWIN:
return "macOS"
elif self._os == Os.LINUX:
return "Linux"
else:
raise ValueError(f"Invalid internal operating system string '{self._os}'")
def brane(self) -> str:
"""
Serializes the OS for use in Brane executable names / other Brane executables.
"""
if self._os == Os.WINDOWS:
return "win"
elif self._os == Os.DARWIN:
return "darwin"
elif self._os == Os.LINUX:
return "linux"
else:
raise ValueError(f"Invalid internal operating system string '{self._os}'")
def docker(self) -> str:
"""
Serializes the OS for use in Docker commands.
"""
if self._os == Os.WINDOWS:
return "windows"
elif self._os == Os.DARWIN:
return "darwin"
elif self._os == Os.LINUX:
return "linux"
else:
raise ValueError(f"Invalid internal operating system string '{self._os}'")
@staticmethod
def allowed() -> typing.Dict[str, str]:
"""
Returns a mapping of all inputs to output operating systems.
# Returns
A map of valid string representations mapping to output `Os`s.
"""
return {
"win" : Os.WINDOWS,
"windows" : Os.WINDOWS,
"macos" : Os.DARWIN,
"darwin" : Os.DARWIN,
"linux" : Os.LINUX,
}
class Process:
"""
Builds an abstraction over a subprocess that is useful to us.
"""
exe : str
args : typing.List[str]
env : typing.Dict[str, str]
_stdout : bool
_stderr : bool
def __init__(self, exe: typing.Union[str, typing.List[str]], *args: str, env: typing.Dict[str, str] = dict(os.environ), capture_stdout: bool = False, capture_stderr: bool = False):
"""
Constructor for the Process.
# Arguments
- `exe`: The executable to run (i.e., first argument).
- `args`: Any other arguments.
- `env`: The environment to set for this Process. Copies the script's environment by default.
- `capture_stdout`: Whether to capture stdout (True) or simply write to this process' stdout.
- `capture_stderr`: Whether to capture stderr (True) or simply write to this process' stderr.
# Returns
A new instance of a Process.
"""
# Build the process
if type(exe) == str:
self.exe = exe
self.args = list(args)
elif type(exe) == list:
self.exe = exe[0]
self.args = exe[1:]
else:
raise TypeError(f"Illegal type '{type(exe)}' for exe")
self.env = env
self._stdout = capture_stdout
self._stderr = capture_stderr
def add_arg(self, *args: str):
"""
Adds additional arguments.
"""
self.args += list(args)
def execute(self, dry_run: bool, show_cmd: bool = True) -> typing.Tuple[int, typing.Optional[str], typing.Optional[str]]:
"""
Executes the process.
# Arguments
- `dry_run`: If True, does not actually run the command but returns a bogus (0, "", "") (or None if applicable)
- `show_cmd`: Whether to print the command we're executing to the stdout/stderr or not.
# Returns
A tuple with:
- The exit code of the process.
- The captured stdout (if capture_stdout was True; otherwise, `None` is returned)
- The captured stderr (if capture_stderr was True; otherwise, `None` is returned)
# Errors
This function will raise an exception if we failed to run the process in the first place.
"""
# Print the thing if desired
args = [ self.exe ] + self.args
if show_cmd:
bold = "\033[1m" if supports_color() else ""
end = "\033[0m" if supports_color() else ""
print(f"{bold} > {Process.shellify(args)}{end}")
# Run the argument if not dry_run
if not dry_run:
handle = subprocess.Popen(args, env=self.env, stdout=(subprocess.PIPE if self._stdout else sys.stdout), stderr=(subprocess.PIPE if self._stderr else sys.stderr))
(stdout, stderr) = handle.communicate()
return (handle.returncode, stdout.decode() if self._stdout else None, stderr.decode() if self._stderr else None)
else:
# Return dummy values
return (0, "" if self._stdout else None, "" if self._stderr else None)
@staticmethod
def shellify(args: typing.List[str]) -> str:
"""
Converts a list of arguments to a shell-like string.
"""
return ' '.join([ (f"\"{a}\"" if ' ' in a else f"{a}") for a in args ])
class ExtractMethod(abc.ABC):
"""
Virtual class for all possible log extraction methods.
"""
def __init__(self):
# Nothing to be done
pass
@abc.abstractmethod
def extract(self, haystack: str) -> typing.Optional[str]:
"""
Extracts the interested area from the given text and returns it.
# Arguments
- `haystack`: The text to extract from.
# Returns
The extract part of the `haystack`.
"""
pass
class ConsecutiveExtract(ExtractMethod):
"""
Applies multiple Extracts, each to the result of the previous.
"""
_extracts : typing.List[ExtractMethod]
def __init__(self, extracts: typing.List[ExtractMethod]):
"""
Constructor for the ConsecutiveExtract.
# Arguments
- `extracts`: The list of extracts to consecutively apply.
# Returns
A new instance of a ConsecutiveExtract.
"""
# initialize super
super().__init__()
# Set the extracts
self._extracts = extracts
def extract(self, haystack: str) -> typing.Optional[str]:
"""
Extracts the interested area from the given text and returns it.
# Arguments
- `haystack`: The text to extract from.
# Returns
The extract part of the `haystack`.
"""
# Apply them as long as we can
for ext in self._extracts:
narrowed_haystack = ext.extract(haystack)
if narrowed_haystack is None: return None
haystack = narrowed_haystack
return haystack
class MatchedLineExtract(ExtractMethod):
"""
Matches the first line that contains the given substring.
"""
_substr : str
_nth: int
def __init__(self, substring: str, nth: int = 0):
"""
Constructor for the MatchedLineExtract.
# Arguments
- `substring`: The first line containing this as a substring is returned.
- `nth`: How manieth match to take. By default, means the first one. Can use -1 to mean the last, -2 to mean the second-to-last, etc.
# Returns
A new instance of a MatchedLineExtract.
"""
# initialize super
super().__init__()
# Set out own parameters
self._substr = substring
self._nth = nth
def extract(self, haystack: str) -> typing.Optional[str]:
"""
Extracts the interested area from the given text and returns it.
# Arguments
- `haystack`: The text to extract from.
# Returns
The extract part of the `haystack`.
"""
# Return the line that has the substring
n_matches = 0
for line in haystack.splitlines():
if self._substr in line:
if n_matches == self._nth: return line
n_matches += 1
# Else, return None
return None
class MatchNthWordExtract(ExtractMethod):
"""
Matches only the nth word in the given input.
"""
_n : int
def __init__(self, n: int):
"""
Constructor for the MatchNthWordExtract.
# Arguments
- `n`: Gives the meaning to "n" in "The n'th word to match" (zero-indexed).
# Returns
A new instance of a MatchNthWordExtract.
"""
# initialize super
super().__init__()
# Set out own parameters
self._n = n
def extract(self, haystack: str) -> typing.Optional[str]:
"""
Extracts the interested area from the given text and returns it.
# Arguments
- `haystack`: The text to extract from.
# Returns
The extract part of the `haystack`.
"""
# Return the nth word
for (i, word) in enumerate(haystack.split()):
if i == self._n: return word
# Else, return None
return None
##### TARGET DEFINITIONS #####
class Target(abc.ABC):
"""
Defines the common ancestor for all targets in this make script.
"""
id : str
deps : typing.List[str]
desc : str
def __init__(self, id: str, dependencies: typing.List[str] = [], description: str = ""):
"""
Initializes the common ancestor of all targets.
# Arguments
- `id`: The string identifier for this target.
- `deps`: A list of target identifier to mark as dependencies of this target.
- `description`: Some human-readable description of what this target does.
"""
self.id = id
self.deps = dependencies
self.desc = description
@abc.abstractmethod
def build(self, arch: Arch, os: Os, dry_run: bool) -> bool:
"""
Builds this target.
# Arguments
- `arch`: The `Arch` that describes the architecture to build for.
- `os`: The `Os` that describes the operating system to build for.
- `dry_run`: If True, does not run any commands but just says it would.
# Returns
Whether any changes to relevant output were triggered.
"""
pass
@abc.abstractmethod
def is_outdated(self) -> bool:
"""
Compute whether this target needs to be updated.
Note that dependencies marking themselves as outdated are already taken care of.
# Returns
True if it should be updated, False if it shouldn't.
"""
pass
class ArrayTarget(Target):
"""
Target that runs multiple various other targets in succession.
This can be modelled with dependencies too, but this target is here to reduce the target count.
"""
_targets : typing.List[Target]
def __init__(self, id: str, targets: typing.List[Target], deps: typing.List[str] = [], description: str = ""):
"""
Constructor for the ArrayTarget.
# Arguments
- `id`: The string identifier for this target.
- `targets`: A list of targets to run.
- `deps`: A list of target identifier to mark as dependencies of this target.
- `description`: Some human-readable description of what this target does.
# Returns
A new ArrayTarget instance.
"""
# Construct the super
super().__init__(id, deps, description)
# Set the commands
self._targets = targets
def build(self, arch: Arch, os: Os, dry_run: bool) -> bool:
"""
Builds this target.
# Arguments
- `arch`: The `Arch` that describes the architecture to build for.
- `os`: The `Os` that describes the operating system to build for.
- `dry_run`: If True, does not run any commands but just says it would.
# Returns
Whether any changes to relevant output were triggered.
"""
# Simply build them all in-order
changed = False
for target in self._targets:
pdebug(f"Building child target '{target.id}' of target '{self.id}'")
changed = changed or target.build(arch, os, dry_run)
return changed
def is_outdated(self) -> bool:
"""
Compute whether this target needs to be updated.
Note that dependencies marking themselves as outdated are already taken care of.
# Returns
True if it should be updated, False if it shouldn't.
"""
# Simply check for outdatedness in-order
for target in self._targets:
if target.is_outdated():
pdebug(f"Marking target '{self.id}' as outdated because child target '{target.id}' is outdated")
return True
pdebug("Marking target '{}' as up-to-date because all child targets ({}) are up-to-date".format(self.id, ", ".join([ f"'{t.id}'" for t in self._targets ])))
return False
class MakeDirTarget(Target):
"""
Target that creates a directory using Python's API.
"""
_path : str
_all : bool
def __init__(self, id: str, path: str, make_all: bool = True, deps: typing.List[str] = [], description: str = ""):
"""
Constructor for the MakeDirTarget.
# Arguments
- `id`: The string identifier for this target.
- `path`: The path of the directory to construct.
- `make_all`: If true, also creates missing parent directories.
- `deps`: A list of target identifier to mark as dependencies of this target.
- `description`: Some human-readable description of what this target does.
# Returns
A new MakeDirTarget instance.
"""
# Construct the super
super().__init__(id, deps, description)
# Set the commands
self._path = path
self._all = make_all
def build(self, _arch: Arch, _os: Os, dry_run: bool) -> bool:
"""
Builds this target.
# Arguments
- `arch`: The `Arch` that describes the architecture to build for.
- `os`: The `Os` that describes the operating system to build for.
- `dry_run`: If True, does not run any commands but just says it would.
# Returns
Whether any changes to relevant output were triggered.
"""
# Determine colours to use
bold = "\033[1m" if supports_color() else ""
end = "\033[0m" if supports_color() else ""