This repository has been archived by the owner on Apr 13, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
cross_compiler.py
executable file
·2707 lines (2284 loc) · 99.1 KB
/
cross_compiler.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 -*-
# ####################################################
# Copyright (C) 2018-2020 DeadSix27 (https://github.com/DeadSix27/python_cross_compile_script)
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ###################################################
# ###################################################
# ### Settings are located in cross_compiler.yaml ###
# ###### That file will be generated on start. ######
# ###################################################
# ###################################################
# ################ REQUIRED PACKAGES ################
# ###################################################
# Package dependencies (some may be missing):
# sudo apt install build-essential autogen libtool libtool-bin pkg-config texinfo yasm git make automake gcc pax cvs subversion flex bison patch mercurial cmake gettext autopoint libxslt1.1 docbook-utils rake docbook-xsl gperf gyp p7zip-full p7zip docbook-to-man pandoc rst2pdf
import argparse
import ast
import codecs
import glob
import hashlib
import importlib
import logging
import os.path
import os
import re
import shutil
import stat
import subprocess
import sys
import traceback
import urllib.parse
import urllib.request
from collections import defaultdict
from multiprocessing import cpu_count
from pathlib import Path
from urllib.parse import urlparse
import progressbar # Run pip3 install progressbar2
import requests # Run pip3 install requests
import yaml
class Colors: # ansi colors
RESET = '\033[0m'
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
LIGHTBLACK_EX = '\033[90m' # those seem to work on the major OS so meh.
LIGHTRED_EX = '\033[91m'
LIGHTGREEN_EX = '\033[92m'
LIGHTYELLOW_EX = '\033[93m'
LIGHTBLUE_EX = '\033[94m'
LIGHTMAGENTA_EX = '\033[95m'
LIGHTCYAN_EX = '\033[96m'
LIGHTWHITE_EX = '\033[9m'
class MissingDependency(Exception):
__module__ = 'exceptions'
def __init__(self, message):
self.message = message
class MyLogFormatter(logging.Formatter):
def __init__(self, l, ld):
MyLogFormatter.log_format = l
MyLogFormatter.log_date_format = ld
MyLogFormatter.inf_fmt = Colors.LIGHTCYAN_EX + MyLogFormatter.log_format + Colors.RESET
MyLogFormatter.err_fmt = Colors.LIGHTRED_EX + MyLogFormatter.log_format + Colors.RESET
MyLogFormatter.dbg_fmt = Colors.LIGHTYELLOW_EX + MyLogFormatter.log_format + Colors.RESET
MyLogFormatter.war_fmt = Colors.YELLOW + MyLogFormatter.log_format + Colors.RESET
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() + "]"
format_orig = self._style._fmt
if record.levelno == logging.DEBUG:
self._style._fmt = MyLogFormatter.dbg_fmt
elif record.levelno == logging.INFO:
self._style._fmt = MyLogFormatter.inf_fmt
elif record.levelno == logging.ERROR:
self._style._fmt = MyLogFormatter.err_fmt
elif record.levelno == logging.WARNING:
self._style._fmt = MyLogFormatter.war_fmt
result = logging.Formatter.format(self, record)
self._style._fmt = format_orig
return result
class CrossCompileScript:
def __init__(self):
sys.dont_write_bytecode = True # Avoid __pycache__ folder, never liked that solution
hdlr = logging.StreamHandler(sys.stdout)
fmt = MyLogFormatter("[%(asctime)s][%(levelname)s]%(type)s %(message)s", "%H:%M:%S")
hdlr.setFormatter(fmt)
self.logger = logging.getLogger(__name__)
self.logger.addHandler(hdlr)
self.logger.setLevel(logging.INFO)
self.config = self.loadConfig()
fmt = MyLogFormatter(self.config["script"]["log_format"], self.config["script"]["log_date_format"])
hdlr.setFormatter(fmt)
self.packages = self.loadPackages(self.config["script"]["packages_folder"])
self.lastError = None
self.init()
def errorExit(self, msg):
self.logger.error(msg)
sys.exit(1)
def loadPackages(self, packages_folder):
def isPathDisabled(path):
for part in path.parts:
if part.lower().startswith("_disabled"):
return True
return False
depsFolder = Path(os.path.join(packages_folder, "dependencies"))
prodFolder = Path(os.path.join(packages_folder, "products"))
varsPath = Path(os.path.join(packages_folder, "variables.py"))
if not os.path.isdir(packages_folder):
self.errorExit("Packages folder '%s' does not exist." % (packages_folder))
if not os.path.isdir(depsFolder): # TODO simplify code
self.errorExit("Packages folder '%s' does not exist." % (depsFolder))
if not os.path.isfile(varsPath):
self.errorExit("Variables file '%s' does not exist." % (varsPath))
tmpPkglist = {'deps': [], 'prods': [], 'vars': []}
packages = {'deps': {}, 'prods': {}, 'vars': {}}
for path, subdirs, files in os.walk(depsFolder):
for name in files:
p = Path(os.path.join(path, name))
if p.suffix == ".py":
if not isPathDisabled(p):
tmpPkglist["deps"].append(p)
for path, subdirs, files in os.walk(prodFolder):
for name in files:
p = Path(os.path.join(path, name))
if p.suffix == ".py":
if not isPathDisabled(p):
tmpPkglist["prods"].append(p)
if len(tmpPkglist["deps"]) < 1: # TODO simplify code
self.errorExit("There's no packages in the folder '%s'." % (depsFolder))
if len(tmpPkglist["prods"]) < 1:
self.errorExit("There's no packages in the folder '%s'." % (prodFolder))
with open(varsPath, "r", encoding="utf-8") as f:
try:
o = ast.literal_eval(f.read()) # was gonna use .json instead of eval on py files, but I like having multiline strings and comments.. so.
if not isinstance(o, dict):
self.errorExit("Variables file is misformatted")
packages["vars"] = o
except SyntaxError:
self.errorExit("Loading variables.py failed:\n\n" + traceback.format_exc())
for d in tmpPkglist["deps"]:
with open(d, "r", encoding="utf-8") as f:
p = Path(d)
packageName = p.stem.lower()
try:
o = ast.literal_eval(f.read())
if not isinstance(o, dict):
self.errorExit("Package file '%s' is misformatted" % (p.name))
if "_info" not in o and not self.boolKey(o, "is_dep_inheriter"):
self.logger.warning("Package '%s.py' is missing '_info' tag." % (packageName))
if self.boolKey(o, "_disabled"):
self.logger.debug("Package '%s.py' has option '_disabled' set, not loading." % (packageName))
else:
packages["deps"][packageName] = o
except SyntaxError:
self.errorExit("Loading '%s.py' failed:\n\n%s" % (packageName, traceback.format_exc()))
for d in tmpPkglist["prods"]:
with open(d, "r", encoding="utf-8") as f:
p = Path(d)
packageName = p.stem.lower()
try:
o = ast.literal_eval(f.read())
if not isinstance(o, dict):
self.errorExit("Package file '%s' is misformatted" % (p.name))
if "_info" not in o and not self.boolKey(o, "is_dep_inheriter"):
self.logger.warning("Package '%s.py' is missing '_info' tag." % (packageName))
if self.boolKey(o, "_disabled"):
self.logger.debug("Package '%s.py' has option '_disabled' set, not loading." % (packageName))
else:
packages["prods"][packageName] = o
except SyntaxError:
self.errorExit("Loading '%s.py' failed:\n\n%s" % (packageName, traceback.format_exc()))
self.logger.info("Loaded %d packages", len(packages["prods"]) + len(packages["deps"]))
return packages
def confDiff(self, default, users): # very basic config comparison
for category in default:
if category not in users:
return (False, F"User config is missing '{category}' category, please delete your config to regenerate a new one OR add it manually.")
elif category != "version":
for option in default[category]:
if option not in users[category]:
return (False, F"User config is missing '{option}' option in '{category}' category, please delete your config to regenerate a new one OR add it manually.")
return (True, 'Config Ok')
def loadConfig(self):
self.config = { # Default config
'version': 1.0,
'script': {
'debug': False,
'quiet': False,
'log_date_format': '%H:%M:%S',
'log_format': '[%(asctime)s][%(levelname)s]%(type)s %(message)s',
'product_order': ['mpv', 'ffmpeg'],
'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0',
'mingw_toolchain_path': 'mingw_toolchain_script/mingw_toolchain_script.py',
'packages_folder': 'packages',
},
'toolchain': {
'output_path': '{work_dir}/{bit_name_win}_output',
'bitness': [64, ],
'cpu_count': cpu_count(),
'mingw_commit': None,
'mingw_debug_build': False,
'mingw_dir': 'toolchain',
'mingw_custom_cflags': None,
'work_dir': 'workdir',
'original_cflags': '-O3',
}
}
config_file = Path(__file__).stem + ".yaml"
if not os.path.isfile(config_file):
self.writeDefaultConfig(config_file)
conf = None
with open(config_file, 'r') as cs:
try:
conf = yaml.safe_load(cs)
except yaml.YAMLError as e:
self.logger.error("Failed to load config file " + str(e))
traceback.print_exc()
sys.exit(1)
confCheck = self.confDiff(self.config, conf)
if confCheck[0]:
return conf
else:
self.logger.error("%s" % (confCheck[1]))
sys.exit(1)
return None
def writeDefaultConfig(self, config_file):
with open(config_file, "w", encoding="utf-8") as f:
f.write(yaml.dump(self.config))
self.logger.info("Wrote default configuration file to: '%s'" % (config_file))
def init(self):
self.product_order = self.config["script"]["product_order"]
self.projectRoot = Path(os.getcwd())
self.fullPatchDir = self.projectRoot.joinpath("patches")
self.fullWorkDir = self.projectRoot.joinpath(self.config["toolchain"]["work_dir"])
self.mingwDir = self.config["toolchain"]["mingw_dir"]
self.targetBitness = self.config["toolchain"]["bitness"]
self.originalPATH = os.environ["PATH"]
self.quietMode = self.config["script"]["quiet"]
self.debugMode = self.config["script"]["debug"]
self.userAgent = self.config["script"]["user_agent"]
if self.debugMode:
self.initDebugMode()
if self.quietMode:
self.initQuietMode()
def initQuietMode(self):
self.logger.warning('Quiet mode is enabled')
self.buildLogFile = codecs.open("raw_build.log", "w", "utf-8")
def initDebugMode(self):
self.logger.setLevel(logging.DEBUG)
self.logger.debug('Debugging is on')
def listifyPackages(self, pdlist, type):
class customArgsAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
format = "CLI"
if args.markdown:
format = "MD"
if args.csv:
format = "CSV"
if format == "CLI":
longestName = 0
longestVer = 1
for key, val in pdlist.items():
if '_info' in val:
if val['repo_type'] == 'git' or val['repo_type'] == 'mercurial':
if 'branch' in val:
if val['branch'] is not None:
rTypeStr = 'git' if val['repo_type'] == 'git' else 'hg '
cVer = rTypeStr + ' (' + val['branch'][0:6] + ')'
else:
cVer = 'git (master)' if val['repo_type'] == 'git' else 'hg (default)'
val['_info']['version'] = cVer
if 'version' in val['_info']:
if len(val['_info']['version']) > longestVer:
longestVer = len(val['_info']['version'])
name = key
if len(name) > longestName:
longestName = len(name)
else:
if len(key) > longestName:
longestName = len(key)
HEADER = "Product"
if type == "D":
HEADER = "Dependency"
if longestName < len('Dependency'):
longestName = len('Dependency')
HEADER_V = "Version"
if longestVer < len(HEADER_V):
longestVer = len(HEADER_V)
print(' {0} - {1}'.format(HEADER.rjust(longestName, ' '), HEADER_V.ljust(longestVer, ' ')))
print('')
for key, val in sorted(pdlist.items()):
ver = Colors.RED + "(no version)" + Colors.RESET
if '_info' in val:
if val['repo_type'] == 'git' or val['repo_type'] == 'mercurial':
if 'branch' in val:
if val['branch'] is not None:
rTypeStr = 'git' if val['repo_type'] == 'git' else 'hg '
cVer = rTypeStr + ' (' + val['branch'][0:6] + ')'
else:
cVer = 'git (master)' if val['repo_type'] == 'git' else 'hg (default)'
val['_info']['version'] = cVer
if 'version' in val['_info']:
ver = Colors.GREEN + val['_info']['version'] + Colors.RESET
name = key
print(' {0} - {1}'.format(name.rjust(longestName, ' '), ver.ljust(longestVer, ' ')))
elif format == "MD":
longestName = 0
longestVer = 1
for key, val in pdlist.items():
if '_info' in val:
if val['repo_type'] == 'git' or val['repo_type'] == 'mercurial':
if 'branch' in val:
if val['branch'] is not None:
rTypeStr = 'git' if val['repo_type'] == 'git' else 'hg '
cVer = rTypeStr + ' (' + val['branch'][0:6] + ')'
else:
cVer = 'git (master)' if val['repo_type'] == 'git' else 'hg (default)'
val['_info']['version'] = cVer
if 'version' in val['_info']:
if len(val['_info']['version']) > longestVer:
longestVer = len(val['_info']['version'])
if 'fancy_name' in val['_info']:
if len(val['_info']['fancy_name']) > longestName:
longestName = len(val['_info']['fancy_name'])
else:
if len(key) > longestName:
longestName = len(key)
HEADER = "Product"
if type == "D":
HEADER = "Dependency"
if longestName < len('Dependency'):
longestName = len('Dependency')
HEADER_V = "Version"
if longestVer < len(HEADER_V):
longestVer = len(HEADER_V)
print('| {0} | {1} |'.format(HEADER.ljust(longestName, ' '), HEADER_V.ljust(longestVer, ' ')))
print('| {0}:|:{1} |'.format(longestName * '-', longestVer * '-'))
for key, val in sorted(pdlist.items()):
if '_info' in val:
ver = "?"
name = key
if val['repo_type'] == 'git' or val['repo_type'] == 'mercurial':
if 'branch' in val:
if val['branch'] is not None:
rTypeStr = 'git' if val['repo_type'] == 'git' else 'hg '
cVer = rTypeStr + ' (' + val['branch'][0:6] + ')'
else:
cVer = 'git (master)' if val['repo_type'] == 'git' else 'hg (default)'
val['_info']['version'] = cVer
if 'version' in val['_info']:
ver = val['_info']['version']
if 'fancy_name' in val['_info']:
name = val['_info']['fancy_name']
print('| {0} | {1} |'.format(name.ljust(longestName, ' '), ver.ljust(longestVer, ' ')))
else:
print(";".join(sorted(pdlist.keys())))
setattr(args, self.dest, values)
parser.exit()
return customArgsAction
def resetDefaultEnvVars(self):
# os.environ["PATH"] = "{0}:{1}:{2}".format (self.mingwBinpath, os.path.join(self.targetPrefix, 'bin'), self.originalPATH) # TODO: properly test this..
os.environ["CFLAGS"] = self.originalCflags
os.environ["CXXFLAGS"] = self.originalCflags
os.environ["PKG_CONFIG_LIBDIR"] = ""
os.environ["PATH"] = "{0}:{1}".format(self.mingwBinpath, self.originalPATH)
os.environ["PKG_CONFIG_PATH"] = self.pkgConfigPath
os.environ["COLOR"] = "ON" # Force coloring on (for CMake primarily)
os.environ["CLICOLOR_FORCE"] = "ON" # Force coloring on (for CMake primarily)
os.environ["CARGO_HOME"] = str(self.cargoHomePath)
def assembleConfigHelps(self, pdlist, type, main):
class customArgsAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
main.quietMode = True
main.init_quietMode()
main.prepareBuilding(64)
main.initBuildFolders()
main.resetDefaultEnvVars()
main.build_mingw(64)
for k, v in pdlist.items():
if '_disabled' not in v:
if '_info' in v:
beforePath = os.getcwd()
path = main.getPackagePath(k, v, type)
main.cchdir(path)
if os.path.isfile(os.path.join(path, "configure")):
os.system("./configure --help")
if os.path.isfile(os.path.join(path, "waf")):
os.system("./waf --help")
main.cchdir(beforePath)
print("-------------------")
setattr(args, self.dest, values)
parser.exit()
return customArgsAction
def commandLineEntrace(self):
class epiFormatter(argparse.RawDescriptionHelpFormatter):
w = shutil.get_terminal_size((120, 10))[0]
def __init__(self, max_help_position=w, width=w, *args, **kwargs):
kwargs['max_help_position'] = max_help_position
kwargs['width'] = width
super(epiFormatter, self).__init__(*args, **kwargs)
def _split_lines(self, text, width):
return text.splitlines()
_epilog = 'Copyright (C) 2018-2019 DeadSix27 (https://github.com/DeadSix27/python_cross_compile_script)\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at https://mozilla.org/MPL/2.0/.\n '
parser = argparse.ArgumentParser(formatter_class=epiFormatter, epilog=_epilog)
parser.set_defaults(which='main')
parser.description = Colors.CYAN + 'Pythonic Cross Compile Helper (MPL2.0)' + Colors.RESET + '\n\nExample usages:' \
'\n "{0} list -p" - lists all the products' \
'\n "{0} -a" - builds everything' \
'\n "{0} -f -d libx264" - forces the rebuilding of libx264' \
'\n "{0} -pl x265_10bit,mpv" - builds this list of products in that order' \
'\n "{0} -q -p ffmpeg_static" - will quietly build ffmpeg-static'.format(parser.prog)
subparsers = parser.add_subparsers(help='Sub commands')
list_p = subparsers.add_parser('list', help='Type: \'' + parser.prog + ' list --help\' for more help')
list_p.set_defaults(which='list_p')
list_p.add_argument('-md', '--markdown', help='Print list in markdown format', action='store_true')
list_p.add_argument('-cv', '--csv', help='Print list as CSV-like string', action='store_true')
list_p_group1 = list_p.add_mutually_exclusive_group(required=True)
list_p_group1.add_argument('-p', '--products', nargs=0, help='List all products', action=self.listifyPackages(self.packages["prods"], "P"))
list_p_group1.add_argument('-d', '--dependencies', nargs=0, help='List all dependencies', action=self.listifyPackages(self.packages["deps"], "D"))
chelps_p = subparsers.add_parser('chelps', help='Type: \'' + parser.prog + ' chelps --help\' for more help')
list_p.set_defaults(which='chelps_p')
chelps_p_group1 = chelps_p.add_mutually_exclusive_group(required=True)
chelps_p_group1.add_argument('-p', '--products', nargs=0, help='Write all product config helps to confighelps.txt', action=self.assembleConfigHelps(self.packages["prods"], "P", self))
chelps_p_group1.add_argument('-d', '--dependencies', nargs=0, help='Write all dependency config helps to confighelps.txt', action=self.assembleConfigHelps(self.packages["deps"], "D", self))
info_p = subparsers.add_parser('info', help='Type: \'' + parser.prog + ' info --help\' for more help')
info_p.set_defaults(which='info_p')
info_p_group1 = info_p.add_mutually_exclusive_group(required=True)
info_p_group1.add_argument('-r', '--required-by', help='List all packages this dependency is required by', default=None)
info_p_group1.add_argument('-d', '--depends-on', help='List all packages this package depends on (recursively)', default=None)
group2 = parser.add_mutually_exclusive_group(required=False)
group2.add_argument('-p', '--build-product', dest='PRODUCT', help='Build the specificed product package(s)')
group2.add_argument('-d', '--build-dependency', dest='DEPENDENCY', help='Build the specificed dependency package(s)')
group2.add_argument('-a', '--build-all', help='Build all products (according to order)', action='store_true')
parser.add_argument('-q', '--quiet', help='Only show info lines', action='store_true')
parser.add_argument('-f', '--force', help='Force rebuild, deletes already files', action='store_true')
parser.add_argument('-g', '--debug', help='Show debug information', action='store_true')
parser.add_argument('-s', '--skip-depends', help='Skip dependencies when building', action='store_true')
if len(sys.argv) == 1:
self.defaultEntrace()
else:
def errorOut(p, t, m=None):
if m is None:
fullStr = Colors.LIGHTRED_EX + 'Error:\n ' + Colors.CYAN + '\'{0}\'' + Colors.LIGHTRED_EX + ' is not a valid {2}\n Type: ' + Colors.CYAN + '\'{1} list --products/--dependencies\'' + Colors.LIGHTRED_EX + ' for a full list'
print(fullStr.format(p, os.path.basename(__file__), "Product" if t == "PRODUCT" else "Dependency") + Colors.RESET)
else:
print(m)
exit(1)
args = parser.parse_args()
if args.which == "info_p":
if args.required_by:
self.listRequiredBy(args.required_by)
if args.depends_on:
self.listDependsOn(args.depends_on)
return
forceRebuild = False
if args.debug:
self.debugMode = True
self.initDebugMode()
if args.quiet:
self.quietMode = True
self.initQuietMode()
if args.force:
forceRebuild = True
buildType = None
finalPkgList = []
if args.PRODUCT or args.DEPENDENCY:
strPkgs = args.DEPENDENCY
buildType = "DEPENDENCY"
if args.PRODUCT is not None:
strPkgs = args.PRODUCT
buildType = "PRODUCT"
pkgList = re.split(r'(?<!\\),', strPkgs)
for p in pkgList:
if buildType == "PRODUCT":
if p not in self.packages["prods"]:
self.errorExit("Product package '%s' does not exist." % (p))
if buildType == "DEPENDENCY":
if p not in self.packages["deps"]:
self.errorExit("Dependency package '%s' does not exist." % (p))
finalPkgList.append(p.replace("\\,", ","))
elif args.build_all:
self.defaultEntrace()
return
self.logger.info('Starting custom build process for: {0}'.format(",".join(finalPkgList)))
skipDeps = False
if args.skip_depends:
skipDeps = True
for thing in finalPkgList:
for b in self.targetBitness:
main.prepareBuilding(b)
main.buildMingw(b)
main.initBuildFolders()
if buildType == "PRODUCT":
self.buildThing(thing, self.packages["prods"][thing], buildType, forceRebuild, skipDeps)
else:
self.buildThing(thing, self.packages["deps"][thing], buildType, forceRebuild, skipDeps)
main.finishBuilding()
def listDependsOn(self, pkgName):
if pkgName not in self.packages["prods"] and pkgName not in self.packages["deps"]:
self.logger.error("'%s' is not an existing package." % (pkgName))
sys.exit(1)
deps = {}
def getDeps(x):
oobj = {}
if "depends_on" in self.packages["deps"][x]:
for x in self.packages["deps"][x]["depends_on"]:
oobj[x] = None
if "depends_on" in self.packages["deps"][x]:
oobj[x] = {}
for _newPkgName in self.packages["deps"][x]["depends_on"]:
oobj[x][_newPkgName] = getDeps(_newPkgName)
return oobj
import pprint
pprint.pprint(getDeps(pkgName))
def listRequiredBy(self, o):
# ptype = None
# if o in self.packages["prods"]:
# ptype = "prods"
# elif o in self.packages["deps"]:
# ptype = "deps"
# else:
if o not in self.packages["prods"] and o not in self.packages["deps"]:
self.logger.error("'%s' is not an existing package." % (o))
sys.exit(1)
prodsRequiringIt = []
depsRequiringIt = []
for p in self.packages["deps"]:
pkg = self.packages["deps"][p]
if "depends_on" in pkg:
if o in pkg["depends_on"]:
depsRequiringIt.append(p)
for p in self.packages["prods"]:
pkg = self.packages["prods"][p]
if "depends_on" in pkg:
if o in pkg["depends_on"]:
prodsRequiringIt.append(p)
if len(prodsRequiringIt) > 0 or len(depsRequiringIt) > 0:
self.logger.info("Packages requiring '%s':" % (o))
if len(depsRequiringIt) > 0:
self.logger.info("\tDependencies: %s" % (",".join(depsRequiringIt)))
if len(prodsRequiringIt) > 0:
self.logger.info("\tProducts : %s" % (",".join(prodsRequiringIt)))
else:
self.logger.warning("There are no packages that require '%s'." % (o))
sys.exit(0)
def defaultEntrace(self):
for b in self.targetBitness:
self.prepareBuilding(b)
self.buildMingw(b)
self.initBuildFolders()
for p in self.product_order:
self.buildThing(p, self.packages["prods"][p], "PRODUCT")
self.finishBuilding()
def finishBuilding(self):
self.cchdir("..")
def formatConfig(self, c: dict):
def fmt(d):
if isinstance(d, dict):
return {self.replaceToolChainVars(k): fmt(v) for k, v in d.items()}
elif isinstance(d, list):
return [fmt(o) for o in d]
else:
if isinstance(d, str):
return self.replaceToolChainVars(d)
else:
return d
try:
return fmt(c)
except KeyError as e:
self.errorExit(F"Failed to parse config file, the variable {e} does not exist.")
def prepareBuilding(self, bitness):
self.logger.info('Starting build script')
if not self.fullWorkDir.exists():
self.logger.info("Creating workdir: %s" % (self.fullWorkDir))
self.fullWorkDir.mkdir()
self.cchdir(self.fullWorkDir)
self.currentBitness = bitness
self.bitnessStr = "x86_64" if bitness == 64 else "i686" # e.g x86_64
self.bitnessPath = self.fullWorkDir.joinpath("x86_64" if bitness == 64 else "i686") # e.g x86_64
self.bitnessStr2 = "x86_64" if bitness == 64 else "x86" # just for vpx...
self.bitnessStr3 = "mingw64" if bitness == 64 else "mingw" # just for openssl...
self.bitnessStrWin = "win64" if bitness == 64 else "win32" # e.g win64
self.targetHostStr = F"{self.bitnessStr}-w64-mingw32" # e.g x86_64-w64-mingw32
self.rustTargetStr = "x86_64-pc-windows-gnu" # hardcoded, only 64bit supported.
self.targetPrefix = self.fullWorkDir.joinpath(self.mingwDir, self.bitnessStr + "-w64-mingw32", self.targetHostStr) # workdir/xcompilers/mingw-w64-x86_64/x86_64-w64-mingw32
self.inTreePrefix = self.fullWorkDir.joinpath(self.bitnessStr) # workdir/x86_64
self.offtreePrefix = self.fullWorkDir.joinpath(self.bitnessStr + "_offtree") # workdir/x86_64_offtree
self.targetSubPrefix = self.fullWorkDir.joinpath(self.mingwDir, self.bitnessStr + "-w64-mingw32") # e.g workdir/xcompilers/mingw-w64-x86_64
self.mingwBinpath = self.fullWorkDir.joinpath(self.mingwDir, self.bitnessStr + "-w64-mingw32", "bin") # e.g workdir/xcompilers/mingw-w64-x86_64/bin
self.mingwBinpath2 = self.fullWorkDir.joinpath(self.mingwDir, self.bitnessStr + "-w64-mingw32", self.bitnessStr + "-w64-mingw32", "bin") # e.g workdir/xcompilers/x86_64-w64-mingw32/x86_64-w64-mingw32/bin
self.fullCrossPrefixStr = F"{self.mingwBinpath}/{self.bitnessStr}-w64-mingw32-" # e.g workdir/xcompilers/mingw-w64-x86_64/bin/x86_64-w64-mingw32-
self.shortCrossPrefixStr = F"{self.bitnessStr}-w64-mingw32-" # e.g x86_64-w64-mingw32-
self.autoConfPrefixOptions = F'--host={self.targetHostStr} --prefix={self.targetPrefix} --disable-shared --enable-static'
#--with-sysroot="{self.targetSubPrefix}"
self.makePrefixOptions = F'CC={self.shortCrossPrefixStr}gcc ' \
F"AR={self.shortCrossPrefixStr}ar " \
F"PREFIX={self.targetPrefix} " \
F"RANLIB={self.shortCrossPrefixStr}ranlib " \
F"LD={self.shortCrossPrefixStr}ld " \
F"STRIP={self.shortCrossPrefixStr}strip " \
F'CXX={self.shortCrossPrefixStr}g++' # --sysroot="{self.targetSubPrefix}"'
self.pkgConfigPath = "{0}/lib/pkgconfig".format(self.targetPrefix) # e.g workdir/xcompilers/mingw-w64-x86_64/x86_64-w64-mingw32/lib/pkgconfig
self.localPkgConfigPath = self.aquireLocalPkgConfigPath()
self.mesonEnvFile = self.fullWorkDir.joinpath("meson_environment.txt")
self.cmakeToolchainFile = self.fullWorkDir.joinpath("mingw_toolchain.cmake")
self.cargoHomePath = self.fullWorkDir.joinpath("cargohome")
self.cmakePrefixOptions = F'-DCMAKE_TOOLCHAIN_FILE="{self.cmakeToolchainFile}" -G\"Ninja\"'
self.cmakePrefixOptionsOld = "-G\"Unix Makefiles\" -DCMAKE_SYSTEM_PROCESSOR=\"{bitness}\" -DCMAKE_SYSTEM_NAME=Windows -DCMAKE_RANLIB={cross_prefix_full}ranlib -DCMAKE_C_COMPILER={cross_prefix_full}gcc -DCMAKE_CXX_COMPILER={cross_prefix_full}g++ -DCMAKE_RC_COMPILER={cross_prefix_full}windres -DCMAKE_FIND_ROOT_PATH={target_prefix}".format(cross_prefix_full=self.fullCrossPrefixStr, target_prefix=self.targetPrefix, bitness=self.bitnessStr)
self.cpuCount = self.config["toolchain"]["cpu_count"]
self.originalCflags = self.config["toolchain"]["original_cflags"]
self.originbalLdLibPath = os.environ["LD_LIBRARY_PATH"] if "LD_LIBRARY_PATH" in os.environ else ""
self.fullProductDir = self.fullWorkDir.joinpath(self.bitnessStr + "_products")
self.formatDict = defaultdict(lambda: "")
self.formatDict.update(
{
'cmake_prefix_options': self.cmakePrefixOptions,
'cmake_prefix_options_old': self.cmakePrefixOptionsOld,
'make_prefix_options': self.makePrefixOptions,
'autoconf_prefix_options': self.autoConfPrefixOptions,
'pkg_config_path': self.pkgConfigPath,
'local_pkg_config_path': self.localPkgConfigPath,
'local_path': self.originalPATH,
'mingw_binpath': self.mingwBinpath,
'mingw_binpath2': self.mingwBinpath2,
'cross_prefix_bare': self.shortCrossPrefixStr,
'cross_prefix_full': self.fullCrossPrefixStr,
'target_prefix': self.targetPrefix,
'project_root': self.projectRoot,
'work_dir': self.fullWorkDir,
'inTreePrefix': self.inTreePrefix,
'offtree_prefix': self.offtreePrefix,
'target_host': self.targetHostStr,
'target_sub_prefix': self.targetSubPrefix,
'bit_name': self.bitnessStr,
'bit_name2': self.bitnessStr2,
'bit_name3': self.bitnessStr3,
'bit_name_win': self.bitnessStrWin,
'bit_num': self.currentBitness,
'rust_target': self.rustTargetStr,
'product_prefix': self.fullProductDir,
'target_prefix_sed_escaped': str(self.targetPrefix).replace("/", "\\/"),
'make_cpu_count': "-j {0}".format(self.cpuCount),
'original_cflags': self.originalCflags,
'cflag_string': self.generateCflagString('--extra-cflags='),
'current_path': os.getcwd(),
'current_envpath': self.getKeyOrBlankString(os.environ, "PATH"),
'meson_env_file': self.mesonEnvFile
} # type: ignore
)
self.config = self.formatConfig(self.config)
self.fullOutputDir = self.projectRoot.joinpath(self.replaceToolChainVars(self.config["toolchain"]["output_path"]))
self.formatDict['output_prefix'] = str(self.fullOutputDir)
#:
def initBuildFolders(self):
if not self.bitnessPath.exists():
self.logger.info(F"Creating bitdir: {self.bitnessPath}")
self.bitnessPath.mkdir(exist_ok=True)
if not self.fullProductDir.exists():
self.logger.info(F"Creating product path: {self.fullProductDir}")
self.fullProductDir.mkdir(exist_ok=True)
if not self.fullOutputDir.exists():
self.logger.info(F"Creating output path: {self.fullOutputDir}")
self.fullOutputDir.mkdir(exist_ok=True)
if not self.offtreePrefix.exists():
self.logger.info(F"Creating bitdir: {self.offtreePrefix}")
self.offtreePrefix.mkdir(exist_ok=True)
# create toolchain files for meson and cmake
self.createMesonEnvFile()
self.createCmakeToolchainFile()
self.createCargoHome()
def boolKey(self, d, k):
if k in d:
if d[k]:
return True
return False
def reStrip(self, pat, txt):
x = re.sub(pat, '', txt)
return re.sub(r'[ ]+', ' ', x).strip()
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 buildMingw(self, bitness):
gcc_bin = os.path.join(self.mingwBinpath, self.bitnessStr + "-w64-mingw32-gcc")
if os.path.isfile(gcc_bin):
gccOutput = subprocess.check_output(gcc_bin + " -v", shell=True, stderr=subprocess.STDOUT).decode("utf-8")
workingGcc = re.compile("^Target: .*-w64-mingw32$", re.MULTILINE).findall(gccOutput)
if len(workingGcc) > 0:
self.logger.info("MinGW-w64 install is working!")
return
else:
raise Exception("GCC is not working properly, target is not mingw32.")
exit(1)
elif not os.path.isdir(self.mingwDir):
self.logger.info("Building MinGW-w64 in folder '{0}'".format(self.mingwDir))
# os.makedirs(self.mingwDir, exist_ok=True)
os.unsetenv("CFLAGS")
# self.cchdir(self.mingwDir)
module_path = self.config["script"]["mingw_toolchain_path"].replace("/", ".").rstrip(".py")
if not os.path.isfile(os.path.join("..", self.config["script"]["mingw_toolchain_path"])):
self.errorExit("Specified MinGW build script path does not exist: '%s'" % (module_path))
def toolchainBuildStatus(logMessage):
self.logger.info(logMessage)
mod = importlib.import_module(module_path)
# from mingw_toolchain_script.mingw_toolchain_script import MinGW64ToolChainBuilder
toolchainBuilder = mod.MinGW64ToolChainBuilder()
toolchainBuilder.workDir = self.mingwDir
if self.config["toolchain"]["mingw_commit"] is not None:
toolchainBuilder.setMinGWcheckout(self.config["toolchain"]["mingw_commit"])
if self.config["toolchain"]["mingw_custom_cflags"] is not None:
toolchainBuilder.setCustomCflags(self.config["toolchain"]["mingw_custom_cflags"])
toolchainBuilder.setDebugBuild(self.config["toolchain"]["mingw_debug_build"])
toolchainBuilder.onStatusUpdate += toolchainBuildStatus
toolchainBuilder.build()
# self.cchdir("..")
else:
self.logger.error("It looks like the previous MinGW build failed, please delete the folder '%s' and re-run this script" % self.mingwDir)
sys.exit(1)
#:
def downloadHeader(self, url):
destination = self.targetPrefix.joinpath("include")
fileName = os.path.basename(urlparse(url).path)
if not os.path.isfile(os.path.join(destination, fileName)):
fname = self.downloadFile(url)
self.logger.debug("Moving Header File: '{0}' to '{1}'".format(fname, destination))
shutil.move(fname, destination)
else:
self.logger.debug("Header File: '{0}' already downloaded".format(fileName))
def downloadFile(self, url=None, outputFileName=None, outputPath=None, bytesMode=False):
def fmt_size(num, suffix="B"):
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, "Yi", suffix)
#:
if not url:
raise Exception("No URL specified.")
if outputPath is None: # Default to current dir.
outputPath = os.getcwd()
else:
if not os.path.isdir(outputPath):
raise Exception('Specified path "{0}" does not exist'.format(outputPath))
fileName = os.path.basename(url) # Get URL filename
userAgent = self.userAgent
if 'sourceforge.net' in url.lower():
userAgent = 'wget/1.18' # sourceforce <3 wget
if url.lower().startswith("ftp://"):
self.logger.info("Requesting : {0}".format(url))
if outputFileName is not None:
fileName = outputFileName
fullOutputPath = os.path.join(outputPath, fileName)
urllib.request.urlretrieve(url, fullOutputPath)
return fullOutputPath
if url.lower().startswith("file://"):
url = url.replace("file://", "")
self.logger.info("Copying : {0}".format(url))
if outputFileName is not None:
fileName = outputFileName
fullOutputPath = os.path.join(outputPath, fileName)
try:
shutil.copyfile(url, fullOutputPath)
except Exception as e:
print(e)
exit(1)
return fullOutputPath
req = requests.get(url, stream=True, headers={"User-Agent": userAgent})
if req.status_code != 200:
req.raise_for_status()
if "content-disposition" in req.headers:
reSponse = re.findall("filename=(.+)", req.headers["content-disposition"])
if reSponse is None:
fileName = os.path.basename(url)
else:
fileName = reSponse[0]
size = None
compressed = False
if "Content-Length" in req.headers:
size = int(req.headers["Content-Length"])
if "Content-Encoding" in req.headers:
if req.headers["Content-Encoding"] == "gzip":
compressed = True
self.logger.info("Requesting : {0} - {1}".format(url, fmt_size(size) if size is not None else "?"))
# terms = shutil.get_terminal_size((100,100))
# filler = 0
# if terms[0] > 100:
# filler = int(terms[0]/4)
widgetsNoSize = [
progressbar.FormatCustomText("Downloading: {:25.25}".format(os.path.basename(fileName))), " ",
progressbar.AnimatedMarker(markers='|/-\\'), " ",
progressbar.DataSize()
# " "*filler
]
widgets = [
progressbar.FormatCustomText("Downloading: {: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"), " |",
progressbar.AdaptiveTransferSpeed(), " | ",
progressbar.ETA(),
# " "*filler
]
pbar = None
if size is None:
pbar = progressbar.ProgressBar(widgets=widgetsNoSize, maxval=progressbar.UnknownLength)
else:
pbar = progressbar.ProgressBar(widgets=widgets, maxval=size)
if outputFileName is not None:
fileName = outputFileName
fullOutputPath = os.path.join(outputPath, fileName)
updateSize = 0
if isinstance(pbar.max_value, int):
updateSize = pbar.max_value if pbar.max_value < 1024 else 1024