-
Notifications
You must be signed in to change notification settings - Fork 4
/
nova_builder.py
2110 lines (1609 loc) · 67.2 KB
/
nova_builder.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
"""
This file is a part of the Nova Physics Engine
project and distributed under the MIT license.
Copyright © Kadir Aksoy
https://github.com/kadir014/nova-physics
Nova Physics Engine Build System
--------------------------------
Build & package Nova Physics
Build & run examples
Build & run benchmarks
Build & run unit tests
This script requires Python 3.9+ and is one-file
with no dependencies for convenience and portability.
"""
from typing import Union, Optional
import sys
import os
import stat
import subprocess
import platform
import shutil
import json
import tarfile
import zipfile
import io
import urllib.error
import urllib.request
import multiprocessing
from abc import ABC, abstractmethod
from pathlib import Path
from enum import Enum
from time import perf_counter, time, gmtime
IS_WIN = platform.system() == "Windows"
# Fix windows terminal
if IS_WIN:
subprocess.run("", shell=True)
# This import won't be used anywhere else
from ctypes import windll
k = windll.kernel32
k.SetConsoleMode(k.GetStdHandle(-11), 7) # -11 = stdout
SEGFAULT_CODES = (
3221225477, # This can also mean a network error, but irrevelant in our case
11,
-11,
134,
139
)
class FG:
"""
ANSI escape codes for terminal foreground colors.
"""
black = "\033[30m"
darkgray = "\033[90m"
lightgray = "\033[37m"
white = "\033[97m"
red = "\033[31m"
orange = "\033[33m"
yellow = "\033[93m"
green = "\033[32m"
blue = "\033[34m"
cyan = "\033[36m"
purple = "\033[35m"
magenta = "\033[95m"
lightred = "\033[91m"
lightgreen = "\033[92m"
lightblue = "\033[94m"
lightcyan = "\033[96m"
@staticmethod
def rgb(r: int, g: int, b: int) -> str:
return f"\033[38;2;{r};{g};{b}m"
class BG:
"""
ANSI escape codes for terminal background colors.
"""
black = "\033[40m"
darkgray = "\033[100m"
lightgray = "\033[47m"
white = "\033[107m"
red = "\033[41m"
orange = "\033[43m"
yellow = "\033[103m"
green = "\033[42m"
blue = "\033[44m"
cyan = "\033[46m"
purple = "\033[45m"
magenta = "\033[105m"
lightred = "\033[101m"
lightgreen = "\033[102m"
lightblue = "\033[104m"
lightcyan = "\033[106m"
@staticmethod
def rgb(r: int, g: int, b: int) -> str:
return f"\033[48;2;{r};{g};{b}m"
# Other ANSI escape codes for graphic modes
# (some doesn't work on some terminals)
class Style:
"""
Other ANSI escape codes for graphic modes.
Some doesn't work on some terminals.
"""
bold = "\033[01m"
underline = "\033[04m"
reverse = "\033[07m"
strike = "\033[09m"
RESET = "\033[0m"
def format_colors(string: str, no_ansi: bool = False) -> str:
""" Format string with color codes. """
# This could be shortened with loops but meh..
pairs = {
"{RESET}": RESET,
"{FG.black}": FG.black,
"{FG.darkgray}": FG.darkgray,
"{FG.lightgray}": FG.lightgray,
"{FG.white}": FG.white,
"{FG.red}": FG.red,
"{FG.orange}": FG.orange,
"{FG.yellow}": FG.yellow,
"{FG.green}": FG.green,
"{FG.blue}": FG.blue,
"{FG.cyan}": FG.cyan,
"{FG.purple}": FG.purple,
"{FG.magenta}": FG.magenta,
"{FG.lightred}": FG.lightred,
"{FG.lightgreen}": FG.lightgreen,
"{FG.lightblue}": FG.lightblue,
"{FG.lightcyan}": FG.lightcyan,
"{BG.black}": BG.black,
"{BG.darkgray}": BG.darkgray,
"{BG.lightgray}": BG.lightgray,
"{BG.white}": BG.white,
"{BG.red}": BG.red,
"{BG.orange}": BG.orange,
"{BG.yellow}": BG.yellow,
"{BG.green}": BG.green,
"{BG.blue}": BG.blue,
"{BG.cyan}": BG.cyan,
"{BG.purple}": BG.purple,
"{BG.magenta}": BG.magenta,
"{BG.lightred}": BG.lightred,
"{BG.lightgreen}": BG.lightgreen,
"{BG.lightblue}": BG.lightblue,
"{BG.lightcyan}": BG.lightcyan,
"{Style.reverse}": Style.reverse
}
for key in pairs:
if no_ansi:
string = string.replace(key, pairs[key])
else:
string = string.replace(key, "")
return string
class ProgressBar:
"""
Simplistic progress bar.
"""
def __init__(self,
template: str,
minvalue: Optional[float] = 0.0,
maxvalue: Optional[float] = 1.0,
value: Optional[float] = None
) -> None:
self.template = template
self.minvalue = minvalue
self.maxvalue = maxvalue
self.value = self.minvalue if value is None else value
self.start_time = time()
self.bar_length = 30
self.mbps = 0.0
def _render(self) -> str:
""" Render the progress bar string. """
render = self.template
normval = self.minvalue + self.value * (self.maxvalue - self.minvalue)
fpercent = normval * 100
percent = round(fpercent)
elapsed = gmtime(time() - self.start_time)
remaining = gmtime(((time() - self.start_time) / self.value) * self.maxvalue)
render = render.replace("{fpercent}", f"{fpercent}")
render = render.replace("{percent}", f"{percent}")
render = render.replace("{mbps}", f"{round(self.mbps, 2)}")
render = render.replace("{ela.hours}", f"{elapsed.tm_hour}")
render = render.replace("{ela.mins}", f"{elapsed.tm_min}")
render = render.replace("{ela.secs}", f"{elapsed.tm_sec}")
render = render.replace("{rem.hours}", f"{remaining.tm_hour}")
render = render.replace("{rem.mins}", f"{remaining.tm_min}")
render = render.replace("{rem.secs}", f"{remaining.tm_sec}")
render = render.replace("{progress}", f"[{'='*int(normval * self.bar_length): <{self.bar_length}}]")
return render
def progress(self, increment: float) -> None:
""" Advance the progress bar. """
self.value += increment
print(f"{self._render()}\033[1G\033[1A")
def clear(self) -> None:
""" Clear the last output of progress bar. """
print(f"{' ' * 100}\033[1G\033[1A")
def error(messages: Union[list, str], no_color: bool = False) -> None:
""" Log error message and abort. """
if isinstance(messages, str):
msg = f"{{FG.red}}{{Style.reverse}} FAIL {{RESET}} {messages}\n"
print(format_colors(msg, no_color))
raise SystemExit(1)
else:
msg = f"{{FG.red}}{{Style.reverse}} FAIL {{RESET}} {messages[0]}\n"
for line in messages[1:]:
msg += f" {line}\n"
print(format_colors(msg, no_color))
raise SystemExit(1)
def success(messages: Union[list, str], no_color: bool = False) -> None:
""" Log success message. """
if isinstance(messages, str):
msg = f"{{FG.lightgreen}}{{Style.reverse}} DONE {{RESET}} {messages}\n"
print(format_colors(msg, no_color))
else:
msg = f"{{FG.lightgreen}}{{Style.reverse}} DONE {{RESET}} {messages[0]}\n"
for line in messages[1:]:
msg += f" {line}\n"
print(format_colors(msg, no_color))
def info(messages: Union[list, str], no_color: bool = False) -> None:
""" Log information message. """
if isinstance(messages, str):
msg = f"{{FG.cyan}}{{Style.reverse}} INFO {{RESET}} {messages}"
print(format_colors(msg, no_color))
else:
msg = f"{{FG.cyan}}{{Style.reverse}} INFO {{RESET}} {messages[0]}"
for line in messages[1:]:
msg += f" {line}\n"
print(format_colors(msg, no_color))
def get_output(cmd: str) -> str:
""" Run check_output, return empty string on error. """
try:
return subprocess.check_output(
cmd, shell=True, stderr=subprocess.DEVNULL
).decode("utf-8").strip()
except:
return ""
class Platform:
"""
Platform specific information gatherer.
Attributes
----------
is_64 Whether the system architechure is 64-bit or not.
system Most basic name that represents the system.
name Name of the system.
min_name Shortened name (without release versions, etc..)
Possible configurations on different platforms:
Attribute | Windows | Manjaro | Ubuntu | MacOS | Other Linux
----------+-----------------+------------+--------------+--------+------------------
system | Windows | Linux | Linux | Darwin | Linux
name | Windows 10 Home | Manjaro 23 | Ubuntu 20.04 | ? | release + version
min_name | Windows | Manjaro | Ubuntu | ? | Linux
"""
def __init__(self) -> None:
self.is_64 = "64" in platform.architecture()[0]
self.system = platform.system()
if IS_WIN:
# Some possible edition outputs:
# Core, CoreSingleLanguage, Ultimate
edition = platform.win32_edition()
if "Core" in edition:
edition = "Home"
self.name = f"Windows {platform.release()} {edition}"
self.min_name = "Windows"
else:
# These will be overwritten with gathered info
self.name = platform.release() + platform.version()
self.min_name = f"Unknown Linux"
lsb_fields = self.parse_lsb_release()
# Manjaro Linux
if "manjaro" in platform.platform().lower():
self.name = "Manjaro"
if "Release" in lsb_fields: self.name += f" {lsb_fields['Release']}"
self.min_name = "Manjaro"
# Ubuntu
elif "ubuntu" in platform.version().lower():
self.name = "Ubuntu"
if "Description" in lsb_fields: self.name += lsb_fields["Description"].replace("Ubuntu", "")
self.min_name = "Ubuntu"
else:
os_release = self.parse_os_release()
if "ID" in os_release:
# Fedora
if os_release["ID"].lower() == "fedora":
self.min_name = "Fedora"
if "PRETTY_NAME" in os_release: self.name = os_release["PRETTY_NAME"]
else: self.name = self.min_name
@staticmethod
def parse_lsb_release() -> dict:
"""
Parse "lsb_release -a" command that is found in most Linux distros
by default to get more detailed system information.
"""
out = get_output("lsb_release -a")
if len(out) == 0: return {}
fields = {}
for line in out.split("\n"):
split = line.split(":")
if len(split) <= 1: continue
fields[split[0].strip()] = split[1].strip()
return fields
@staticmethod
def parse_os_release() -> dict:
"""
Parse "cat /etc/os_release" command that is found in most Linux distros
to get more detailed system information, in case lsb_release doesn't exist.
"""
out = get_output("cat /etc/os-release")
if len(out) == 0: return {}
fields = {}
for line in out.split("\n"):
split = line.split("=")
if len(split) <= 1: continue
fields[split[0].strip()] = split[1].strip()
return fields
PLATFORM = Platform()
BASE_PATH = Path(os.getcwd())
SRC_PATH = BASE_PATH / "src"
INCLUDE_PATH = BASE_PATH / "include"
BUILD_PATH = BASE_PATH / "build"
DEPS_PATH = BASE_PATH / "deps"
CACHE_PATH = BASE_PATH / "cache"
EXAMPLES_PATH = BASE_PATH / "examples"
BENCHS_PATH = BASE_PATH / "benchmarks"
TESTS_PATH = BASE_PATH / "tests"
def get_nova_version() -> str:
""" Get Nova Phyiscs Engine version number. """
with open(INCLUDE_PATH / "novaphysics" / "novaphysics.h", "r") as header_file:
content = header_file.readlines()
major, minor, patch = 0, 0, 0
for line in content:
if line.startswith("#define NV_VERSION_MAJOR"):
major = int(line[24:].strip())
elif line.startswith("#define NV_VERSION_MINOR"):
minor = int(line[24:].strip())
elif line.startswith("#define NV_VERSION_PATCH"):
patch = int(line[24:].strip())
return f"{major}.{minor}.{patch}"
def remove_readonly(action, name, exc) -> None:
""" Overwrites READ-ONLY files as WRITE-ONLY and removes them. """
os.chmod(name, stat.S_IWRITE)
os.remove(name)
def remove_dir(path: Path) -> None:
""" Remove directory with its contents recursively. """
shutil.rmtree(path, onerror=remove_readonly)
def copy_dir(
src_path: Path,
dst_path: Path,
symlinks: bool = False,
ignore: bool = None
) -> None:
""" Copy one directory's content into another one recursively. """
for item in os.listdir(src_path):
try:
s = os.path.join(src_path, item)
d = os.path.join(dst_path, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
except:
pass
def copy_dlls(src_dir: Path, dst_dir: Path) -> None:
""" Copy DLL files from one directory to another. """
for item in os.listdir(src_dir):
s = os.path.join(src_dir, item)
if os.path.isfile(s):
if item.endswith(".dll"):
shutil.copyfile(s, dst_dir / item)
class CLI:
"""
Class that parses and handles command line arguments and commands.
"""
def __init__(self) -> None:
self.commands = {}
self.arguments = {}
self.extra_arguments = []
@property
def command_count(self) -> int:
return sum(int(self.check_command(command)) for command in self.commands)
@property
def argument_count(self) -> int:
return sum(int(self.check_argument(argument)) for argument in self.arguments)
def add_command(self, command: str, doc: str) -> bool:
""" Add a command. """
self.commands[command] = {
"doc": doc,
"passed": False
}
def add_argument(self,
argument: Union[str, tuple[str, str]],
doc: str,
accepts_value: bool = False,
accepts_suffix: bool = False,
value: Union[None, str, int] = None
) -> None:
""" Add an argument. """
self.arguments[argument] = {
"doc": doc,
"passed": False,
"accepts_value": accepts_value,
"accepts_suffix": accepts_suffix,
"value": value
}
def check_command(self, command: str) -> bool:
""" Check if the command is passed. """
return self.commands[command]["passed"]
def check_argument(self, argument: Union[str, tuple[str, str]]) -> bool:
""" Check if the argument is passed. """
for arg in self.arguments:
if isinstance(arg, str):
if arg == argument:
return self.arguments[arg]["passed"]
elif isinstance(arg, tuple):
if argument in arg or argument == arg:
return self.arguments[arg]["passed"]
def get_argument(self,
argument: Union[str, tuple[str, str]]
) -> Union[None, str, int]:
""" Get the value of argument. """
for arg in self.arguments:
if isinstance(arg, str):
if arg == argument:
return self.arguments[arg]["value"]
elif isinstance(arg, tuple):
if argument in arg or argument == arg:
return self.arguments[arg]["value"]
def parse(self) -> None:
""" Parse command line. """
for arg in sys.argv[1:]:
if self._set_argument(arg):
continue
if self._set_command(arg):
continue
self.extra_arguments.append(arg)
def usage(self) -> str:
""" Generate usage manual. """
script_name = sys.argv[0].replace(".py", "")
man = \
f"{{FG.orange}}Usage:{{RESET}} {script_name} [arguments] <command> [extra arguments...]\n" + \
"\n" + \
"{FG.orange}Commands:{RESET}\n"
GAP = 20
for command in self.commands:
command_l = command.ljust(GAP)
man += f" {{FG.lightcyan}}{command_l}{{RESET}} {self.commands[command]['doc']}\n"
man += "\n{FG.orange}Arguments:{RESET}\n"
for argument in self.arguments:
if isinstance(argument, tuple):
option_l = f"{{FG.lightcyan}}{argument[0]} {{FG.darkgray}}| {{FG.lightcyan}}{argument[1]}{{RESET}}"
option_l = option_l.ljust(GAP + 48)
else:
option_l = f"{{FG.lightcyan}}{argument.ljust(GAP)}{{RESET}}"
man += f" {option_l} {self.arguments[argument]['doc']}\n"
return man
def _set_command(self, raw: str) -> bool:
""" Check if the command exists and set it. """
for cmd in self.commands:
if raw == cmd:
self.commands[cmd]["passed"] = True
return True
return False
def _set_argument(self, raw: str) -> bool:
""" Check if the argument exists and set it. """
for arg in self.arguments:
if isinstance(arg, str):
if raw.startswith(arg):
parsed = self._parse_argument(raw, arg, self.arguments[arg])
if not parsed["valid"]: continue
self.arguments[arg]["passed"] = True
self.arguments[arg]["value"] = parsed["value"]
return True
elif isinstance(arg, tuple):
if raw.startswith(arg[0]) or raw.startswith(arg[1]):
parsed = self._parse_argument(raw, arg, self.arguments[arg])
if not parsed["valid"]: continue
self.arguments[arg]["passed"] = True
self.arguments[arg]["value"] = parsed["value"]
return True
return False
def _parse_argument(self,
raw: str,
argument: Union[str, tuple[str, str]],
context: dict
) -> dict:
dash = 0
if raw.startswith("-"): dash = 1
elif raw.startswith("--"): dash = 2
if context["accepts_value"]:
if "=" in raw:
s = raw.split("=")
arg = s[0]
val = s[1]
return {"valid": self._is_valid(arg, argument), "value": val}
else:
return {"valid": self._is_valid(raw, argument), "value": None}
elif context["accepts_suffix"]:
raw_ = raw[dash:]
# Do you have a better solution to parse suffix values? Cuz I don't
if any(char.isdigit() for char in raw_):
letters = []
digits = []
for char in raw_:
if char.isalpha(): letters.append(char)
elif char.isdigit(): digits.append(char)
letters = "".join(letters)
digits = int("".join(digits))
return {
"valid": self._is_valid(f"{'-'*dash}{letters}", argument),
"value": digits
}
else:
return {"valid": self._is_valid(raw, argument), "value": None}
else:
return {"valid": self._is_valid(raw, argument), "value": None}
def _is_valid(self,
argument: str,
original: Union[str, tuple[str, str]]
) -> bool:
if isinstance(original, str):
return argument == original
elif isinstance(original, tuple):
if argument == original[0]: return True
elif argument == original[1]: return True
class DependencyManager:
"""
Class to download & manage build dependencies.
"""
def __init__(self, cli: CLI) -> None:
self.cli = cli
self.no_color = not self.cli.check_argument("-n")
self.chunk_size = 4 * 1024
# Don't forget to update versions
SDL2_VER = "2.28.5"
TTF_VER = "2.20.2"
# Library and DLL files are Windows only
self.dependencies = {
"SDL2": {
"url": f"https://github.com/libsdl-org/SDL/releases/download/release-{SDL2_VER}/SDL2-devel-{SDL2_VER}-mingw.tar.gz",
"include": {
"satisfied": False,
"path": DEPS_PATH / "include" / "SDL2",
"archive-path": f"SDL2-{SDL2_VER}/x86_64-w64-mingw32/include/SDL2"
},
"lib-x64": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "lib-x64" / "SDL2",
"archive-path": f"SDL2-{SDL2_VER}/x86_64-w64-mingw32/lib"
},
"lib-x86": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "lib-x86" / "SDL2",
"archive-path": f"SDL2-{SDL2_VER}/i686-w64-mingw32/lib"
},
"bin-x64": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "bin-x64" / "SDL2",
"archive-path": f"SDL2-{SDL2_VER}/x86_64-w64-mingw32/bin"
},
"bin-x86": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "bin-x86" / "SDL2",
"archive-path": f"SDL2-{SDL2_VER}/i686-w64-mingw32/bin"
}
},
"SDL2-MSVC": {
"url": f"https://github.com/libsdl-org/SDL/releases/download/release-{SDL2_VER}/SDL2-devel-{SDL2_VER}-VC.zip",
"include": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "include" / "SDL2-MSVC",
"archive-path": f"SDL2-{SDL2_VER}/include"
},
"lib-x64": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "lib-x64" / "SDL2-MSVC",
"archive-path": f"SDL2-{SDL2_VER}/lib/x64"
},
"lib-x86": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "lib-x86" / "SDL2-MSVC",
"archive-path": f"SDL2-{SDL2_VER}/lib/x86"
},
"bin-x64": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "bin-x64" / "SDL2-MSVC",
"archive-path": f"SDL2-{SDL2_VER}/lib/x64"
},
"bin-x86": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "bin-x86" / "SDL2-MSVC",
"archive-path": f"SDL2-{SDL2_VER}/lib/x86"
}
},
"SDL2_ttf": {
"url": f"https://github.com/libsdl-org/SDL_ttf/releases/download/release-{TTF_VER}/SDL2_ttf-devel-{TTF_VER}-mingw.tar.gz",
"include": {
"satisfied": False,
"path": DEPS_PATH / "include" / "SDL2",
"archive-path": f"SDL2_ttf-{TTF_VER}/x86_64-w64-mingw32/include/SDL2"
},
"lib-x64": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "lib-x64" / "SDL2_ttf",
"archive-path": f"SDL2_ttf-{TTF_VER}/x86_64-w64-mingw32/lib"
},
"lib-x86": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "lib-x86" / "SDL2_ttf",
"archive-path": f"SDL2_ttf-{TTF_VER}/i686-w64-mingw32/lib"
},
"bin-x64": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "bin-x64" / "SDL2_ttf",
"archive-path": f"SDL2_ttf-{TTF_VER}/x86_64-w64-mingw32/bin"
},
"bin-x86": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "bin-x86" / "SDL2_ttf",
"archive-path": f"SDL2_ttf-{TTF_VER}/i686-w64-mingw32/bin"
}
},
"SDL2_ttf-MSVC": {
"url": f"https://github.com/libsdl-org/SDL_ttf/releases/download/release-{TTF_VER}/SDL2_ttf-devel-{TTF_VER}-VC.zip",
"include": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "include" / "SDL2-MSVC",
"archive-path": f"SDL2_ttf-{TTF_VER}/include"
},
"lib-x64": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "lib-x64" / "SDL2_ttf-MSVC",
"archive-path": f"SDL2_ttf-{TTF_VER}/lib/x64"
},
"lib-x86": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "lib-x86" / "SDL2_ttf-MSVC",
"archive-path": f"SDL2_ttf-{TTF_VER}/lib/x86"
},
"bin-x64": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "bin-x64" / "SDL2_ttf-MSVC",
"archive-path": f"SDL2_ttf-{TTF_VER}/lib/x64"
},
"bin-x86": {
"satisfied": not IS_WIN,
"path": DEPS_PATH / "bin-x86" / "SDL2_ttf-MSVC",
"archive-path": f"SDL2_ttf-{TTF_VER}/lib/x86"
}
}
}
def download(self, url: str) -> bytes:
""" Download & return the data. """
try:
response = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
error(
f"{{FG.lightcyan}}{url}{{RESET}} responsed with code {{FG.lightred}}{e.code}{{RESET}}.",
self.no_color
)
size = int(response.info()["Content-Length"])
template = f"{{progress}} {{FG.yellow}}{{percent}}%{{RESET}} {{FG.magenta}}{{mbps}}Mbps{{RESET}} ETA {{FG.lightblue}}{{ela.hours}}:{{ela.mins}}:{{ela.secs}}{{RESET}} RTA {{FG.lightblue}}{{rem.hours}}:{{rem.mins}}:{{rem.secs}}{{RESET}}"
template = format_colors(template, self.no_color)
bar = ProgressBar(template)
fp = io.BytesIO()
dl = 0
start = perf_counter()
while True:
chunk = response.read(self.chunk_size)
dl += len(chunk)
if not chunk: break
fp.write(chunk)
mbps = dl / (perf_counter() - start) / (2 ** 17)
bar.mbps = mbps
bar.progress(self.chunk_size / size)
bar.clear()
fp.seek(0)
return fp.read()
def extract(self, data: bytes, path: Path) -> None:
""" Extract archive data to path. """
try:
with tarfile.open(mode="r:gz", fileobj=io.BytesIO(data)) as tar:
tar.extractall(path)
except tarfile.ReadError:
with zipfile.ZipFile(io.BytesIO(data)) as zip:
zip.extractall(path)
except Exception as e:
raise e
def check(self) -> None:
""" Check if dependencies satisfy. """
for dep in self.dependencies:
for pack in self.dependencies[dep]:
if pack == "url": continue
if os.path.exists(self.dependencies[dep][pack]["path"]):
self.dependencies[dep][pack]["satisfied"] = True
def missing(self, dep_: Optional[str] = None) -> int:
""" Return number of missing dependencies. """
deps = 0
for dep in self.dependencies:
if dep_ is not None and dep != dep_: continue
for pack in self.dependencies[dep]:
if pack == "url": continue
if not self.dependencies[dep][pack]["satisfied"]:
deps += 1
return deps
def clean(self) -> None:
""" Clean temporary repositories. """
for dep_name in self.dependencies:
temp_dir = DEPS_PATH / f"_{dep_name}"
if os.path.exists(temp_dir):
remove_dir(temp_dir)
def satisfy(self) -> None:
""" Download, extract and organize all dependencies. """
# Don't need to continue if all deps are satisfied
if self.missing() == 0:
return
if not os.path.exists(DEPS_PATH):
os.mkdir(DEPS_PATH)
if not os.path.exists(DEPS_PATH / "include"):
os.mkdir(DEPS_PATH / "include")
if not os.path.exists(DEPS_PATH / "lib-x64"):
os.mkdir(DEPS_PATH / "lib-x64")
if not os.path.exists(DEPS_PATH / "lib-x86"):
os.mkdir(DEPS_PATH / "lib-x86")
if not os.path.exists(DEPS_PATH / "bin-x64"):
os.mkdir(DEPS_PATH / "bin-x64")
if not os.path.exists(DEPS_PATH / "bin-x86"):
os.mkdir(DEPS_PATH / "bin-x86")
start = time()
self.clean()
for dep_name in self.dependencies:
temp_dir = DEPS_PATH / f"_{dep_name}"
dep = self.dependencies[dep_name]
if self.missing(dep_name):
info(f"Downloading {{FG.lightcyan}}{dep['url']}{{RESET}}", self.no_color)
self.extract(
self.download(dep["url"]),
temp_dir
)
if not dep["include"]["satisfied"]:
info(
f"Extracting {{FG.yellow}}{temp_dir / dep['include']['archive-path']}{{RESET}}",
self.no_color
)
if not os.path.exists(dep["include"]["path"]):
os.mkdir(dep["include"]["path"])
copy_dir(
temp_dir / dep["include"]["archive-path"],
dep["include"]["path"]
)
if IS_WIN:
if not dep["lib-x64"]["satisfied"]:
info(
f"Extracting {{FG.yellow}}{temp_dir / dep['lib-x64']['archive-path']}{{RESET}}",
self.no_color
)
if not os.path.exists(dep["lib-x64"]["path"]):
os.mkdir(dep["lib-x64"]["path"])
copy_dir(
temp_dir / dep["lib-x64"]["archive-path"],
dep["lib-x64"]["path"]
)
if not dep["lib-x86"]["satisfied"]:
info(
f"Extracting {{FG.yellow}}{temp_dir / dep['lib-x86']['archive-path']}{{RESET}}",
self.no_color
)