-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
1655 lines (1418 loc) · 65.2 KB
/
main.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
# -*- coding: utf-8 -*-
import argparse
from ast import Str
import datetime
import hashlib
import importlib
import importlib.util
import io
import logging
import os
from pyclbr import Class
import re
import shlex
import shutil
import subprocess
import sys
import tarfile
import urllib.request
from pprint import pprint as pp
from colorama import init, Fore, Style
from typing import List, Tuple, Union
from urllib.parse import urlparse
import progressbar
import requests
from ansimarkup import ansistring
import packages
from packages.base_package import BasePackage
from pathlibex import Path
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
class MyLogFormatter(logging.Formatter):
def __init__(self, l, ld):
MyLogFormatter.log_format = l
MyLogFormatter.log_date_format = ld
super().__init__(
fmt="%(levelno)d: %(msg)s",
datefmt=MyLogFormatter.log_date_format,
style="%",
)
def format(self, record):
if not hasattr(record, "type"):
record.type = ""
else:
record.type = "[" + record.type.upper() + "]" # type: ignore
if record.levelno == logging.DEBUG:
record.levelname = f"<grey>{record.levelname}</grey>"
record.msg = f"<grey>{record.msg}</grey>"
elif record.levelno == logging.INFO:
record.levelname = f"<cyan>{record.levelname}</cyan>"
record.msg = f"<cyan>{record.msg}</cyan>"
elif record.levelno == logging.ERROR:
record.levelname = f"<light-red>{record.levelname}</light-red>"
record.msg = f"<light-red>{record.msg}</light-red>"
elif record.levelno == logging.WARNING:
record.levelname = f"<light-yellow>{record.levelname}</light-yellow>"
record.msg = f"<light-yellow>{record.msg}</light-yellow>"
self._style._fmt = MyLogFormatter.log_format
result = logging.Formatter.format(self, record)
result = ansistring(result)
return result
class CrossCompiler:
def __init__(self):
hdlr = logging.StreamHandler(sys.stdout)
self.logger = logging.getLogger(__name__)
self.logger.addHandler(hdlr)
self.logger.setLevel(logging.INFO)
fmt = MyLogFormatter(
"<light-cyan>[%(asctime)s][%(levelname)s]</light-cyan>%(type)s %(message)s",
"%H:%M:%S",
)
hdlr.setFormatter(fmt)
self.cmdLineArgs = None
self.packages: dict[str, BasePackage] = {}
self.packagesBuilt: dict[str, bool] = {}
self.originalEnv = dict(os.environ)
self.projectRoot = Path(os.getcwd())
self.fullPatchDir = self.projectRoot.joinpath("patches")
self.workPath = Path(os.getcwd()).joinpath("work")
self.installDir = Path(os.getcwd()).joinpath("install")
self.xArchPrefixStr = f"x86_64"
self.mingwPrefixStr = f"{self.xArchPrefixStr}-w64-mingw32"
self.mingwPrefixStrDash = f"{self.xArchPrefixStr}-w64-mingw32-"
self.toolchainRootPath = self.workPath.joinpath("toolchain")
self.toolchainPathOne = self.toolchainRootPath.joinpath(self.mingwPrefixStr)
self.toolchainBinPathOne = self.toolchainPathOne.joinpath("bin")
self.toolchainPathTwo = self.toolchainPathOne.joinpath(self.mingwPrefixStr)
self.pkgConfigPath = self.toolchainPathTwo.joinpath("lib/pkgconfig")
self.toolchainBinPathTwo = self.toolchainPathTwo.joinpath("bin")
self.crossPrefix = self.toolchainPathTwo
self.packagesRoot = self.workPath.joinpath("sources")
self.rustTargetStr = "x86_64-pc-windows-gnu"
self.runProcessDebug = False
self.originalPATH = os.environ["PATH"]
self.localPkgConfigPath = self.aquireLocalPkgConfigPath()
self.userAgent = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"
)
self.bitnessStr = "x86_64"
self.bitnessStrWin = "win64"
self.bitnessStrNum = "64"
self.cmakeToolchainFile = self.workPath.joinpath("mingw_toolchain.cmake")
self.cargoHomePath = self.workPath.joinpath("cargohome")
self.mesonEnvFile = self.workPath.joinpath("meson_environment.ini")
self.mesonNativeFile = self.workPath.joinpath("meson_native.ini")
self.makePrefixOptions = (
f"CC={self.mingwPrefixStrDash}gcc",
f"AR={self.mingwPrefixStrDash}ar",
f"PREFIX={self.crossPrefix}",
f"RANLIB={self.mingwPrefixStrDash}ranlib",
f"LD={self.mingwPrefixStrDash}ld",
f"STRIP={self.mingwPrefixStrDash}strip",
f"CXX={self.mingwPrefixStrDash}g++",
)
self.formatDict = {
"bitness": self.bitnessStr,
"bitness_win": self.bitnessStrWin,
"bitness_num": self.bitnessStrNum,
"toolchain_path_one": str(self.toolchainPathOne),
"arch_string": self.xArchPrefixStr,
"target_prefix": str(self.crossPrefix),
"target_prefix_sed_escaped": str(self.crossPrefix).replace("/", "\\/"),
"toolchain_bin_path_one": str(self.toolchainBinPathOne),
"toolchain_bin_path_two": str(self.toolchainBinPathTwo),
"mingw_prefix": str(self.mingwPrefixStr),
"mingw_prefix_dash": str(self.mingwPrefixStrDash),
"cmake_toolchain_file": str(self.cmakeToolchainFile),
"cmake_prefix_options": (
f"-DCMAKE_TOOLCHAIN_FILE={self.cmakeToolchainFile}",
"-GNinja",
"-DCMAKE_BUILD_TYPE=Release",
),
"autoconf_prefix_options": (
"--host={mingw_prefix}",
"--prefix={target_prefix}",
"--disable-shared",
"--enable-static",
),
"meson_prefix_options": (
"--prefix={target_prefix}",
"--cross-file={meson_env_file}",
"--native-file=" + str(self.mesonNativeFile),
"--buildtype=release",
),
"meson_options": (
"--cross-file={meson_env_file}",
"--native-file=" + str(self.mesonNativeFile),
"--buildtype=release",
),
"meson_env_file": str(self.mesonEnvFile),
"meson_native_file": str(self.mesonNativeFile),
"make_prefix_options": self.makePrefixOptions,
"rust_target": self.rustTargetStr,
"pkg_config_path": str(self.pkgConfigPath),
"local_pkg_config_path": self.localPkgConfigPath,
"local_path": self.originalPATH,
"install_path": str(self.installDir),
}
os.makedirs("work/sources", exist_ok=True)
self.loadPackages()
self.sanityCheckPackages()
self.createCargoHome() # we build this first so we do not have to worry about the enviroment being correct.
self.buildLLVMToolchain()
self.createCmakeToolchainFile()
self.createMesonEnvFile()
self.setDefaultEnv()
self.parseCommandLine()
self.buildPackageAndDeps(self.packages["mpv"])
def parseCommandLine(self):
parser = argparse.ArgumentParser(description="Py Cross")
parser.add_argument(
"packages",
nargs="*",
help="Single package or list of package to build",
)
parser.add_argument("-sd", '--skip-dependencies', action="store_true", help="Skip dependencies")
parser.add_argument("-d", "--debug", action="store_true", help="Enable debug mode")
parser.add_argument("-de", "--dependends", nargs='?', help="List all what packages depend on a package")
parser.add_argument("-l", "--list", action="store_true", help="List all packages")
parser.add_argument("-t", "--test", action="store_true", help="")
parser.add_argument(
"-w",
"--wait",
action="store_true",
help="Wait after each build step until confirmation",
)
self.cmdLineArgs = parser.parse_args()
if self.cmdLineArgs.packages and len(self.cmdLineArgs.packages):
non_existing = []
for p in self.cmdLineArgs.packages:
p = p.lower()
if not p in self.packages:
non_existing.append(p)
if non_existing:
self.logger.error(
f"The package(s): {'; '.join([f'<u>{s}</u>' for s in non_existing])}, do not exist."
)
exit(1)
self.buildBackageList(self.cmdLineArgs.packages)
exit()
if self.cmdLineArgs.dependends:
self.findDependends()
if self.cmdLineArgs.test:
self.test()
if self.cmdLineArgs.list:
self.printPackageList()
def findDependends(self):
pkgName = self.cmdLineArgs.dependends
for (name, pkg) in self.packages.items():
pkg: BasePackage
if pkgName in pkg.depends:
print(name)
exit()
def test(self):
maxNameLength = len(max(self.packages.keys(), key=len)) +1
for (name, pkg) in self.packages.items():
pkg: BasePackage
link = pkg.url
if pkg.source_type != BasePackage.SourceType.Git:
continue
self.get_latest_commit_time(link)
exit()
def time_since_commit(self, commit_time):
commit_datetime = datetime.fromisoformat(commit_time[:-1])
now = datetime.utcnow()
delta = relativedelta(now, commit_datetime)
total_days = delta.days + delta.months * 30 + delta.years * 365
if total_days <= 7:
return f"{Fore.RED}{self.format_timedelta(delta)} ago{Style.RESET_ALL}"
else:
raise Exception()
def format_timedelta(self, delta):
delta_str = ""
if delta.years:
delta_str += f"{delta.years} year{'s' if delta.years > 1 else ''} "
if delta.months:
delta_str += f"{delta.months} month{'s' if delta.months > 1 else ''} "
if delta.days:
delta_str += f"{delta.days} day{'s' if delta.days > 1 else ''} "
if delta.hours:
delta_str += f"{delta.hours} hour{'s' if delta.hours > 1 else ''} "
if delta.minutes:
delta_str += f"{delta.minutes} minute{'s' if delta.minutes > 1 else ''} "
if delta.seconds:
delta_str += f"{delta.seconds} second{'s' if delta.seconds > 1 else ''} "
return delta_str.strip()
def get_latest_commit_time(self, repo_url):
if "github.com" in repo_url:
repo_owner, repo_name = re.findall(r"github\.com\/([A-z0-9\-\_\.]+)\/([A-z0-9\.\-\_]+)", repo_url)[0]
repo_name = repo_name.replace(".git", "")
api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/commits"
headers = {'Authorization': f'Bearer GITHUB_TOKEN'}
response = requests.get(api_url, headers=headers)
response_json = response.json()
if response.status_code == 200:
latest_commit_time = response_json[0]['commit']['committer']['date']
try:
print(f"{latest_commit_time} - {self.time_since_commit(latest_commit_time)} - {repo_name}")
except:
pass
else:
return f"Error: {response.status_code} - {response_json['message']} - {api_url} - {repo_url}"
else:
return
def printPackageList(self):
maxNameLength = len(max(self.packages.keys(), key=len)) +1
for (name, pkg) in self.packages.items():
pkg: BasePackage
link = pkg.url
if pkg.source_type == BasePackage.SourceType.Archive:
link = pkg.mirrors[0]["url"]
print(f'Name: {name:<{maxNameLength}} Link: {link:<{80}}')
def aquireLocalPkgConfigPath(self):
possiblePathsStr = (
subprocess.check_output(
"pkg-config --variable pc_path pkg-config",
shell=True,
stderr=subprocess.STDOUT,
)
.decode("utf-8")
.strip()
)
if possiblePathsStr == "":
raise Exception(
"Unable to determine local pkg-config path(s), pkg-config output is empty"
)
possiblePaths = [Path(x.strip()) for x in possiblePathsStr.split(":")]
for p in possiblePaths:
if not p.exists():
possiblePaths.remove(p)
if not len(possiblePaths):
raise Exception(
f"Unable to determine local pkg-config path(s), pkg-config output is: {possiblePathsStr}"
)
return ":".join(str(x) for x in possiblePaths)
def buildBackageList(self, pkgLst: List[Str]):
for pkgName in pkgLst:
self.buildPackageAndDeps(self.packages[pkgName])
def buildPackageAndDeps(self, pkg: BasePackage):
self.logger.info(f"Building {pkg.name}")
if pkg.name in self.packagesBuilt:
if self.packagesBuilt[pkg.name]:
self.logger.info(f"{pkg.name} already built")
return
else:
raise Exception(f"Error building {pkg.name}: circular dependency detected.")
self.packagesBuilt[pkg.name] = False
if len(pkg.depends) > 0 and not self.cmdLineArgs.skip_dependencies:
self.logger.info(f"{pkg.name} depends on {pkg.depends}")
for pkg_name in pkg.depends:
if pkg_name not in self.packages:
raise Exception(
f"{pkg_name} is not an available package, requested by: {pkg.name}"
)
dependency_pkg = self.packages[pkg_name]
self.buildPackageAndDeps(dependency_pkg)
try:
self.buildPackage(pkg)
self.packagesBuilt[pkg.name] = True
self.logger.info(f"{pkg.name} built successfully")
except:
self.packagesBuilt[pkg.name] = False
raise
def setDefaultEnv(self):
os.environ["PATH"] = f"{self.toolchainBinPathOne}:{self.originalEnv['PATH']}"
os.environ["CARGO_HOME"] = str(self.cargoHomePath)
os.environ["PKG_CONFIG_LIBDIR"] = ""
os.environ["PKG_CONFIG_PATH"] = str(self.pkgConfigPath)
os.environ["COLOR"] = "ON" # Force coloring on (for CMake primarily)
os.environ["TERM"] = "xterm"
os.environ["CLICOLOR_FORCE"] = "ON" # Force coloring on (for CMake primarily)
# os.environ["CFLAGS"] = "-ggdb -Og"
# os.environ["CMAKE_SYSTEM_IGNORE_PATH"] = "/;/usr;/usr/local"
# os.environ["MESON_CMAKE_TOOLCHAIN_FILE"] = str(self.cmakeToolchainFile)
# os.environ["CC"] = f"{self.mingwPrefixStrDash}gcc"
# os.environ["AR"] = f"{self.mingwPrefixStrDash}ar"
# os.environ["PREFIX"] = f"{self.crossPrefix}"
# os.environ["RANLIB"] = f"{self.mingwPrefixStrDash}ranlib"
# os.environ["LD"] = f"{self.mingwPrefixStrDash}ld"
# os.environ["STRIP"] = f"{self.mingwPrefixStrDash}strip"
# os.environ["CXX"] = f"{self.mingwPrefixStrDash}g++"
# pp(os.environ)
def createSymlink(self, sourcePath: Path, targetLinkPath: Path):
if not sourcePath.exists():
raise ValueError(f"{sourcePath} does not exist")
if targetLinkPath.exists():
self.logger.warning(F"Failed Creating Symlink from {sourcePath} to {targetLinkPath}, path exists.")
return
if sourcePath.is_file():
link_type = "file"
elif sourcePath.is_dir():
link_type = "dir"
else:
raise ValueError(f"{sourcePath} is not a file or directory")
try:
os.symlink(
str(sourcePath),
str(targetLinkPath),
target_is_directory=(link_type == "dir"),
)
self.logger.info(F"Creating Symlink from {sourcePath} to {targetLinkPath}")
except OSError as e:
raise OSError(f"Failed to create symlink: {e}")
def getPackagePathByName(self, name, root=False):
pkg: BasePackage = self.packages[name]
pkgPath = pkg.path
if pkg.get_source_subfolder and not root:
pkgPath = pkgPath.joinpath(pkg.get_source_subfolder)
return pkgPath
def handleRegexReplace(self, rp, packageName):
multiline = False
cwd = Path(os.getcwd())
if "in_file" not in rp:
self.logger.error(
f"The regex_replace command in the package {packageName}:\n{rp}\nMisses the in_file parameter."
)
exit(1)
if 0 not in rp:
self.logger.error(
f'A regex_replace command in the package {packageName}\nrequires at least the "0" key to be a RegExpression, if 1 is not defined matching lines will be removed.'
)
exit(1)
in_files = rp["in_file"]
if isinstance(in_files, (list, tuple)):
in_files = (cwd.joinpath(self.format_variable_str(x)) for x in in_files)
else:
in_files = (cwd.joinpath(self.format_variable_str(in_files)),)
repls = [
self.format_variable_str(rp[0]),
]
if 1 in rp:
repls.append(self.format_variable_str(rp[1]))
if "multiline" in rp:
multiline = True
self.logger.info(
f"Running regex replace commands on package: '{packageName}' [{os.getcwd()}]"
)
for _current_infile in in_files:
if "out_file" not in rp:
out_files = (_current_infile,)
shutil.copy(
_current_infile,
_current_infile.parent.joinpath(_current_infile.name + ".backup"),
)
else:
if isinstance(rp["out_file"], (list, tuple)):
out_files = (cwd.joinpath(self.format_variable_str(x)) for x in rp["out_file"])
else:
out_files = (cwd.joinpath(self.format_variable_str(rp["out_file"])),)
for _current_outfile in out_files:
if not _current_infile.exists():
self.logger.warning(
f"[Regex-Command] In-File '{_current_infile}' does not exist in '{os.getcwd()}'"
)
if _current_outfile == _current_infile:
_backup = _current_infile.parent.joinpath(_current_infile.name + ".backup")
if not _backup.parent.exists():
self.logger.warning(
f"[Regex-Command] Out-File parent '{_backup.parent}' does not exist."
)
shutil.copy(_current_infile, _backup)
_tmp_file = _current_infile.parent.joinpath(_current_infile.name + ".tmp")
shutil.move(_current_infile, _tmp_file)
_current_infile = _tmp_file
self.logger.info(f"[{packageName}] Running regex command on '{_current_outfile}'")
if multiline:
with open(_current_infile, "r") as f:
with open(_current_outfile, "w") as nf:
replaceWith = ""
if len(repls) >= 2:
replaceWith = repls[1]
newFile = re.sub(repls[0], replaceWith, f.read(), flags=re.MULTILINE)
nf.write(newFile)
else:
with open(_current_infile, "r") as f:
with open(_current_outfile, "w") as nf:
for line in f:
if re.search(repls[0], line) and len(repls) > 1:
self.logger.info(f"RegEx replacing line")
self.logger.info(f"in {_current_outfile}\n{line}\nwith:")
line = re.sub(repls[0], repls[1], line)
self.logger.info(f"\n{line}")
nf.write(line)
elif re.search(repls[0], line):
self.logger.info(f"RegEx removing line\n{line}:")
else:
nf.write(line)
_current_infile.unlink()
_backup.unlink()
def runProcess(self, args, ignore_errors=False, exit_on_error=True, inputFile=None) -> int:
if not isinstance(args, tuple) and not isinstance(args, list):
raise ValueError("only tuple/list accepted")
args = self.format_variable_list(args)
stdin_arg = subprocess.PIPE if inputFile is not None else None
if self.runProcessDebug:
self.logger.info(f"Running process: {' '.join(args)}")
process = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=stdin_arg,
)
if inputFile is not None and process.stdin is not None:
with open(inputFile, "rb") as f:
input_data = f.read()
process.stdin.write(input_data)
process.stdin.close()
if process.stderr is None and process.stdout is None:
raise Exception("stderr and stdout are empty.")
while process.stdout is not None:
nextline = process.stdout.readline()
if nextline == b"" and process.poll() is not None:
break
line_str = nextline.decode("utf-8", "ignore")
sys.stdout.write(line_str)
if process.stdout:
process.stdout.close()
return_code = process.wait()
if return_code != 0:
if not ignore_errors:
self.logger.error(
f"Error [{return_code}] running process: '{' '.join(str(x) for x in args)}' in '{os.getcwd()}'"
)
if exit_on_error:
exit(1)
return return_code
def svnHasNewCommits(self, pkg: BasePackage):
# Get local revision using svn info command
local_info = os.popen("svn info").read().strip()
local_rev_match = re.search(r"^Revision:\s*(\d+)", local_info, re.MULTILINE)
local_rev = local_rev_match.group(1) if local_rev_match else ""
# Get remote revision using svn info command with package URL
remote_info = os.popen(f"svn info {pkg.url}").read().strip()
remote_rev_match = re.search(r"^Revision:\s*(\d+)", remote_info, re.MULTILINE)
remote_rev = remote_rev_match.group(1) if remote_rev_match else ""
return local_rev != remote_rev
def svnCheckout(self, package: BasePackage):
checkoutUrl = package.url
if package.path.exists():
_olddir = os.getcwd()
os.chdir(package.path)
if self.svnHasNewCommits(package):
self.runProcess(["svn", "update"])
os.chdir(_olddir)
return True
else:
self.logger.info(f"SVN repo for {package.name} is up to date")
os.chdir(_olddir)
return False
self.logger.info(f"Checking out {package.name} from '{checkoutUrl}'")
self.runProcess(["svn", "checkout", checkoutUrl, str(package.path)])
return True
def gitHasNewCommits(self):
localCommit = os.popen("git rev-parse HEAD").read().strip()
remoteCommit = (
os.popen("git ls-remote -q . HEAD").read().strip().split("\n")[0].split("\t")[0]
)
return not localCommit == remoteCommit
def gitClone(self, package: BasePackage):
cloneUrl = package.url
originalPath = os.getcwd()
if package.path.exists():
os.chdir(package.path)
if self.gitHasNewCommits():
self.runProcess(("git", "pull"))
os.chdir(originalPath)
return True
else:
self.logger.info(f"Git repo for {package.name} is up to date")
os.chdir(originalPath)
return False
cloneCmd = ["git", "clone", "--progress", "-v"]
if package.git_depth and not package.git_tag:
cloneCmd.append(f"--depth={package.git_depth}")
if package.git_recursive:
cloneCmd.append("--recursive")
if package.git_shallow_submodules:
cloneCmd.append("--shallow-submodules")
if package.git_branch:
if package.git_tag:
self.logger.error("You can <b>not</b> use git tag and branch at the <u>same time</u>.")
exit(1)
cloneCmd.append(f"--branch={package.git_branch}")
cloneCmd.append(cloneUrl)
cloneCmd.append(str(package.path))
self.logger.info(f"Cloning {package.name} with '{shlex.join(self.format_variable_list(cloneCmd))}'")
self.runProcess(cloneCmd)
if package.git_tag:
package.path.pushd()
self.logger.info(f"Checking out tag [{package.git_tag}] for {package.name}")
self.runProcess(["git", "checkout", package.git_tag])
package.path.popd()
return True
def hgHasNewCommits(self):
localRevision = os.popen("hg identify --debug").read().strip().split()[0]
remoteRevision = os.popen("hg identify -r default --debug").read().strip().split()[0]
return not localRevision == remoteRevision
def hgClone(self, package: BasePackage):
cloneUrl = package.url
if package.path.exists():
_olddir = os.getcwd()
os.chdir(package.path)
if self.hgHasNewCommits():
self.runProcess(("hg", "pull"))
os.chdir(_olddir)
return True
else:
self.logger.info(f"Mercurial repo for {package.name} is up to date")
os.chdir(_olddir)
return False
cmd = ["hg", "clone", "-v", cloneUrl, str(package.path)]
self.logger.info(f"Cloning {package.name} with '{shlex.join(self.format_variable_list(cmd))}'")
self.runProcess(cmd)
return True
def hashFile(self, fname, type="sha256"):
if type == "sha256":
hash_obj = hashlib.sha256()
elif type == "sha512":
hash_obj = hashlib.sha512()
elif type == "sha1":
hash_obj = hashlib.sha1()
elif type == "md5":
hash_obj = hashlib.md5()
elif type == "blake2b":
hash_obj = hashlib.blake2b()
else:
raise ValueError(f"Unsupported hash type: {type}")
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_obj.update(chunk)
return hash_obj.hexdigest()
def verifyHash(self, file, hash):
newHash = self.hashFile(file, hash["type"])
if hash["sum"] == newHash:
return (True, hash["sum"], newHash)
return (False, hash["sum"], newHash)
def extractFile(self, filename, outputPath):
def on_progress(filename, position, total_size, pb):
pass
def get_file_progress_file_object_class(on_progress, pb):
class FileProgressFileObject(tarfile.ExFileObject):
def read(self, size, *args):
on_progress(self.name, self.position, self.size, pb) # type:ignore
return tarfile.ExFileObject.read(self, size, *args)
return FileProgressFileObject
class ProgressFileObject(io.FileIO):
def __init__(self, path, pb, *args, **kwargs):
self.pb = pb
self._total_size = os.path.getsize(path)
io.FileIO.__init__(self, path, *args, **kwargs)
def read(self, size):
self.pb.update(self.tell())
return io.FileIO.read(self, size)
#:
terms = shutil.get_terminal_size((100, 100))
# filler = 0
# if terms[0] > 100:
# filler = int(terms[0]/4)
widgets = [
progressbar.FormatCustomText(
"Extracting : {:25.25}".format(os.path.basename(filename))
),
" ",
progressbar.Percentage(),
" ",
progressbar.Bar(fill=chr(9617), marker=chr(9608), left="[", right="]"),
" ",
progressbar.DataSize(),
"/",
progressbar.DataSize(variable="max_value"),
# " "*filler,
]
pbar = progressbar.ProgressBar(widgets=widgets, maxval=os.path.getsize(filename))
pbar.start()
tarfile.TarFile.fileobject = get_file_progress_file_object_class(on_progress, pbar)
tar = tarfile.open(fileobj=ProgressFileObject(filename, pbar), mode="r:*")
# outputPath = os.path.commonprefix(tar.getnames())
if os.path.isfile(outputPath):
tar.close()
pbar.finish()
return outputPath
else:
members = tar.getmembers()
if len(members) == 1 and members[0].name != Path(filename).stem.rstrip(".tar"):
base_path = members[0].name
else:
base_path = Path(filename).stem.rstrip(".tar")
for i in range(len(members)):
np = Path(members[i].name)
members[i].name = str(Path(*np.parts[1:]))
if base_path != Path(filename).stem.rstrip(".tar"):
members[i].name = str(Path(base_path) / Path(*np.parts))
tar.extractall(path=outputPath, members=members)
tar.close()
pbar.finish()
return outputPath
#:
def downloadArchive(self, package: BasePackage, path=None):
if package.path.exists():
return (True, package.path)
for mirror in package.mirrors:
url = mirror["url"]
self.logger.info(f"Downloading {package.name} from '{url}'")
f = self.downloadFile(url, outputPath=path)
hashes = mirror["hashes"]
for h in hashes: # type:ignore
self.logger.info("Comparing hashes..")
if h["sum"] == "SKIP":
return (False, f)
hashReturn = self.verifyHash(f, h)
if hashReturn[0] is True:
self.logger.info(
"Hashes matched: {0}...{1} (local) == {2}...{3} (remote)".format(
hashReturn[1][0:5],
hashReturn[1][-5:],
hashReturn[2][0:5],
hashReturn[2][-5:],
)
)
return (False, f)
else:
self.logger.error(
"File hashes didn't match: %s(local) != %s(remote)"
% (hashReturn[1], hashReturn[2])
)
raise Exception("File download error: Hash mismatch")
exit(1)
return None
def format_variable_str(self, in_str: str):
if not isinstance(in_str, str):
raise ValueError(f"The input is not a string: {in_str}")
matches = re.findall(r"\{([^{}]+)\}|\!CMD\(([^)]+)\)CMD\!", in_str)
modified_str = in_str # create a new variable to store the modified string
for var, cmd in matches:
if var:
if var in self.formatDict:
modified_var = self.formatDict[var]
if isinstance(modified_var, list) or isinstance(modified_var, tuple):
modified_var = self.format_variable_list(modified_var)
if isinstance(modified_var, list) or isinstance(modified_var, tuple):
return modified_var
elif not isinstance(modified_var, str):
raise ValueError(
f"The variable {var} contains a non str or list value: {modified_var}"
)
modified_str = re.sub(
r"\{" + re.escape(var) + r"\}",
modified_var,
modified_str,
)
elif cmd:
try:
cmd_output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT).decode().strip()
modified_str = re.sub(
r"\!CMD\(" + re.escape(cmd) + r"\)CMD\!",
cmd_output,
modified_str,
)
except subprocess.CalledProcessError as e:
print(f"Command '{cmd}' failed with error:\n{e.output.decode()}")
sys.exit()
return modified_str # return the modified string
def format_variable_list(
self, str_obj: Union[List[str], Tuple[str]]
) -> Union[List[str], Tuple[str]]:
if isinstance(str_obj, list):
formatted_lst = []
for in_str in str_obj:
if isinstance(in_str, str):
new = self.format_variable_str(in_str)
if isinstance(new, list) or isinstance(new, tuple):
formatted_lst.extend(new)
else:
formatted_lst.append(new)
else:
raise TypeError(
f"Input must be a list or a tuple of strings, not {type(in_str)} [{in_str}]"
)
return list(formatted_lst)
elif isinstance(str_obj, tuple):
formatted_tpl = []
for in_obj in str_obj:
if isinstance(in_obj, str):
new = self.format_variable_str(in_obj)
if isinstance(new, list) or isinstance(new, tuple):
formatted_tpl.extend(new)
else:
formatted_tpl.append(new)
# formatted_tpl.append(self.format_variable_str(in_obj))
else:
raise TypeError(
f"Input must be a list or a tuple of string, not {type(in_obj)} [{in_obj}]"
)
return tuple(formatted_tpl)
else:
raise TypeError(
f"Input must be a list or a tuple of strings, not {type(str_obj)} [{str_obj}]"
)
def formatVariableStr(self, strLst: Union[List[str], Tuple[str]]) -> Tuple[str]:
if not strLst:
return tuple(strLst)
formattedStrings = []
if not isinstance(strLst, tuple) and not isinstance(strLst, list):
strLst = (strLst,)
for s in strLst:
s: str
matches = re.findall(r"(\{([a-zA-Z0-9_\-]+)\})|(\!CMD\(([^\)]+)\)CMD\!)", s)
if matches:
for match in matches:
if match[0]:
replaceVar = self.formatDict[match[1]]
if isinstance(replaceVar, tuple):
group1 = self.formatVariableStr(replaceVar)
formattedStrings.extend(group1)
else:
s = re.sub(r"\{[a-zA-Z0-9_\-]+\}", replaceVar, s)
formattedStrings.append(s)
elif match[2]:
cmd_output = subprocess.check_output(match[3], shell=True).decode().strip()
s = re.sub(r"\!CMD\(([^\)]+)\)CMD\!", cmd_output, s)
formattedStrings.append(s)
else:
formattedStrings.append(s)
return tuple(formattedStrings)
def formatVariableStrO2(self, strLst: Union[List[str], Tuple[str]]) -> Tuple[str]:
if not strLst:
return tuple(strLst)
formattedStrings = []
if not isinstance(strLst, tuple) and not isinstance(strLst, list):
strLst = (strLst,)
for s in strLst:
s: str
matches = re.findall(r"(\{([a-zA-Z0-9_\-]+)\})", s)
if matches:
for match in matches:
replaceVar = self.formatDict[match[1]]
if isinstance(replaceVar, tuple):
group1 = self.formatVariableStr(replaceVar)
formattedStrings.extend(group1)
else:
s = re.sub(r"\{[a-zA-Z0-9_\-]+\}", replaceVar, s)
formattedStrings.append(s)
else:
formattedStrings.append(s)
return tuple(formattedStrings)
def formatVariableStrO(self, strLst: Union[List, Tuple]):
if not strLst:
return tuple(strLst)
formattedStrings = []
if not isinstance(strLst, tuple) and not isinstance(strLst, list):
strLst = (strLst,)
for s in strLst:
s: str
matches = re.findall(r"(\{([a-zA-Z0-9_\-]+)\})", s)
if matches:
for match in matches:
replaceVar = self.formatDict[match[1]]
if isinstance(replaceVar, tuple):
group1 = []
for x in replaceVar:
group1.append(x)
formattedStrings.extend(group1)
else:
formattedStrings.append(re.sub(r"\{[a-zA-Z0-9_\-]+\}", replaceVar, s))
else:
formattedStrings.append(s)
return tuple(formattedStrings)
def autogenConfigure(self, pkg: BasePackage):
if pkg.autogen:
if pkg.autogen_only_reconf:
self.runProcess(["autoreconf", "-vi"])
self.logger.info(f"Running only autoreconf for {pkg.name} in {os.getcwd()}")
else:
if pkg.path.joinpath("autogen.sh").exists():
self.logger.info(f"Running autogen for {pkg.name} in {os.getcwd()}")
self.runProcess(["./autogen.sh"])
else:
self.logger.info(f"Running autoreconf for {pkg.name} in {os.getcwd()}")
self.runProcess(["autoreconf", "-vi"])
# def display_message(self, message):
# return
# """Display message in console and wait for any key to be pressed"""
# sys.stdout.write(message)
# sys.stdout.flush()
# # Wait for a single key press
# try:
# if sys.platform.startswith("win"):
# # For Windows systems, use msvcrt.getch()
# msvcrt.getch()
# else:
# # For Unix-like systems, use getch.getch()
# getch.getch()
# except KeyboardInterrupt:
# # Handle the user pressing Ctrl-C by exiting the function
# pass
def aquirePackage(self, package: BasePackage):
packageDir = package.path
if package.source_type == BasePackage.SourceType.Git:
if not self.gitClone(package):
self.packagesBuilt[package.name] = True
return False
else:
return True