forked from DeadSix27/python_cross_compile_script
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcross_compiler.py
3470 lines (3207 loc) · 155 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) 2017 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.
# ###################################################
# ###################################################
# ################ REQUIRED PACKAGES ################
# ###################################################
# Package dependencies (some may be missing):
#
# Ubuntu 17.04 (Zesty Zapus)
# Ubuntu 16.10 (Yakkety)
# Fedora 25 (Twenty Five)
#
# sudo apt install build-essential autoget 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
# ###################################################
# ################# TODO ###################
# ###################################################
# ## Feel free to help out with whatever is in this list (or any other thing) ##
# List:
# - Fix libbluray in shared.
# - Basic optional config file.
# - Remote hosting of product/dependency hosting as json files.
# - Implement hash support for archives, mostly for the self hosted ones.
# ###################################################
# ################# CONFIGURATION ###################
# ###################################################
import os.path,logging,re,subprocess,sys,shutil,urllib.request,urllib.parse,stat
import hashlib,glob,traceback,time,zlib,codecs,argparse
import http.cookiejar
from multiprocessing import cpu_count
from pathlib import Path
from urllib.parse import urlparse
from collections import OrderedDict
_CPU_COUNT = cpu_count() # the default automaticlaly sets it to your core-count but you can set it manually too # default: cpu_count()
_QUIET = False # This is only for the 'just build it all mode', in CLI you should use "-q" # default: false
_LOG_DATEFORMAT = '%H:%M:%S' # default: %H:%M:%S
_LOGFORMAT = '[%(asctime)s][%(levelname)s] %(message)s' # default: [%(asctime)s][%(levelname)s] %(message)s
_WORKDIR = 'workdir' # default: workdir
_MINGW_DIR = 'xcompilers' # default: xcompilers
_BITNESS = ( 64, ) # as of now only 64 is tested, 32 could work, for multi-bit write it like (64, 32), this is completely untested .
_ORIG_CFLAGS = '-march=sandybridge -O3' # I've had issues recently with the binaries not working on older systems despite using a old march, so stick to sandybridge for now, for others see: https://gcc.gnu.org/onlinedocs/gcc-6.3.0/gcc/x86-Options.html#x86-Options
_ENABLE_STATUSFILE = True # NOT IMPLEMENTED YET !
_STATUS_FILE = os.getcwd() + "/status_file" # NOT IMPLEMENTED YET !
# Remove a product, re-order them or add your own, do as you like.
PRODUCT_ORDER = ( 'cuetools', 'aria2', 'x265_multibit', 'x264_10bit', 'x264_8bit', 'flac', 'vorbis-tools', 'lame3', 'sox', 'mpv', 'ffmpeg_static', 'ffmpeg_shared', 'curl', 'wget' )
#
# ###################################################
# ###################################################
# ###################################################
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 MyFormatter(logging.Formatter):
inf_fmt = Colors.LIGHTCYAN_EX + _LOGFORMAT + Colors.RESET
err_fmt = Colors.LIGHTRED_EX + _LOGFORMAT + Colors.RESET
dbg_fmt = Colors.LIGHTYELLOW_EX + _LOGFORMAT + Colors.RESET
war_fmt = Colors.YELLOW + _LOGFORMAT + Colors.RESET
def __init__(self):
super().__init__(fmt="%(levelno)d: %(msg)s", datefmt=_LOG_DATEFORMAT, style='%')
def format(self, record):
format_orig = self._style._fmt
if record.levelno == logging.DEBUG:
self._style._fmt = MyFormatter.dbg_fmt
elif record.levelno == logging.INFO:
self._style._fmt = MyFormatter.inf_fmt
elif record.levelno == logging.ERROR:
self._style._fmt = MyFormatter.err_fmt
elif record.levelno == logging.WARNING:
self._style._fmt = MyFormatter.war_fmt
result = logging.Formatter.format(self, record)
self._style._fmt = format_orig
return result
_BASE_URL = 'https://raw.githubusercontent.com/DeadSix27/python_cross_compile_script/master'
_MINGW_SCRIPT_URL = '/mingw_build_scripts/mingw-build-script-posix_threads.sh' # with win32 posix threading support
_GCC_VER = "7.2.0" # old was 7.1.0, 6.3.0, but is not supported by me anymore.
_MINGW_GIT_COMMIT_BRANCH = "d3a74e38ba2a1ea3eb971b501d05cef364bb25ff"
_DEBUG = False # for.. debugging.. purposes this is the same as --debug in CLI, only use this if you do not use CLI.
_OUR_VER = ".".join(str(x) for x in sys.version_info[0:3])
_TESTED_VERS = ['3.5.3','3.5.2','3.6.0']
class CrossCompileScript:
def __init__(self,product_order,products,depends,variables):
self.PRODUCT_ORDER = product_order
self.PRODUCTS = products
self.DEPENDS = depends
self.VARIABLES = variables
self.init()
def init(self):
fmt = MyFormatter()
hdlr = logging.StreamHandler(sys.stdout)
hdlr.setFormatter(fmt)
self.logger = logging.getLogger(__name__)
self.logger.addHandler(hdlr)
self.fullCurrentPath = os.getcwd()
self.fullWorkDir = os.path.join(self.fullCurrentPath,_WORKDIR)
self.fullProductDir = None
self.targetBitness = _BITNESS
self.originalPATH = os.environ["PATH"]
self.mingwScriptURL = _BASE_URL + _MINGW_SCRIPT_URL
self.compileTarget = None
self.compilePrefix = None
self.mingwBinpath = None
self.fullCrossPrefix = None
self.makePrefixOptions = None
self.bitnessDir = None
self.bitnessDir2 = None
self.winBitnessDir = None
self.pkgConfigPath = None
self.bareCrossPrefix = None
self.cpuCount = None
self.originalCflags = None
self.buildLogFile = None
self.quietMode = _QUIET
self.debugMode = _DEBUG
self.logger.setLevel(logging.INFO)
if self.debugMode:
self.init_debugMode()
if self.quietMode:
self.init_quietMode()
def init_quietMode(self):
self.logger.warning('Quiet mode is enabled')
self.buildLogFile = codecs.open("raw_build.log","w","utf-8")
def init_debugMode(self):
self.logger.setLevel(logging.DEBUG)
self.logger.debug('Debugging is on')
def listify_pdeps(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 'version' in val['_info']:
if len(val['_info']['version']) > longestVer:
longestVer = len(val['_info']['version'])
name = key
if len(name) > longestName:
longestName = len(name)
# 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.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 'version' in val['_info']:
ver = Colors.GREEN + val['_info']['version'] + Colors.RESET
name = key
# if '_info' in val:
# if 'fancy_name' in val['_info']:
# name = val['_info']['fancy_name']
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 '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 '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 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.build_mingw(64)
main.initBuildFolders()
for k,v in pdlist.items():
if '_disabled' not in v:
if '_info' in v:
beforePath = os.getcwd()
path = main.get_thing_path(k,v,type)
print(path)
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) 2017 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 '
if _OUR_VER not in _TESTED_VERS:
_epilog = Colors.RED + "Warning: This script is not tested on your Python Version: " + _OUR_VER + Colors.RESET + "\n\n" +_epilog
parser = argparse.ArgumentParser(formatter_class=epiFormatter, epilog=_epilog)
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.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.listify_pdeps(self.PRODUCTS,"P"))
list_p_group1.add_argument('-d', '--dependencies', nargs=0, help='List all dependencies', action=self.listify_pdeps(self.DEPENDS, "D"))
chelps_p = subparsers.add_parser('chelps', help= 'Type: \'' + parser.prog + ' chelps --help\' for more help')
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.PRODUCTS,"P",self))
chelps_p_group1.add_argument('-d', '--dependencies', nargs=0, help='Write all dependency config helps to confighelps.txt', action=self.assembleConfigHelps(self.DEPENDS, "D",self))
group2 = parser.add_mutually_exclusive_group( required = True )
group2.add_argument( '-p', '--build_product_list', dest='PRODUCT', help='Build this product list' )
group2.add_argument( '-pl', '--build_product', dest='PRODUCT_LIST', help='Build this product (and dependencies)' )
group2.add_argument( '-d', '--build_dependency', dest='DEPENDENCY', help='Build this dependency' )
group2.add_argument( '-dl', '--build_dependency_list', dest='DEPENDENCY_LIST', help='Build this dependency list' )
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' )
if len(sys.argv)==1:
self.defaultEntrace()
else:
def errorOut(p,t,m=None):
if m == 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()
forceRebuild = False
if args.debug:
self.debugMode = True
self.init_debugMode()
if args.quiet:
self.quietMode = True
self.init_quietMode()
if args.force:
forceRebuild = True
thingToBuild = None
buildType = None
finalThingList = []
if args.PRODUCT:
buildType = "PRODUCT"
thingToBuild = args.PRODUCT
if thingToBuild in self.PRODUCTS:
finalThingList.append(thingToBuild)
else:
errorOut(thingToBuild,buildType)
elif args.DEPENDENCY:
buildType = "DEPENDENCY"
thingToBuild = args.DEPENDENCY
if thingToBuild in self.DEPENDS:
finalThingList.append(thingToBuild)
else:
errorOut(thingToBuild,buildType)
elif args.DEPENDENCY_LIST:
buildType = "DEPENDENCY"
thingToBuild = args.DEPENDENCY_LIST
if "," not in thingToBuild:
errorOut(None,None,"Error: are you sure the list format is correct? It must be dependency1;dependency2;dependency3;...")
for d in thingToBuild.split(","):
if d in self.DEPENDS:
finalThingList.append(d)
else:
errorOut(thingToBuild,buildType)
elif args.PRODUCT_LIST:
buildType = "PRODUCT"
thingToBuild = args.PRODUCT_LIST
if "," not in thingToBuild:
errorOut(None,None,"Error: are you sure the list format is correct? It must be product1;product2;product3,...")
for d in thingToBuild.split(","):
if d in self.PRODUCTS:
finalThingList.append(d)
else:
errorOut(thingToBuild,buildType)
elif args.build_all:
self.defaultEntrace()
return
self.logger.warning('Starting custom build process for: {0}'.format(thingToBuild))
for thing in finalThingList:
for b in self.targetBitness:
main.prepareBuilding(b)
main.build_mingw(b)
main.initBuildFolders()
if buildType == "PRODUCT":
self.build_thing(thing,self.PRODUCTS[thing],buildType,forceRebuild)
else:
self.build_thing(thing,self.DEPENDS[thing],buildType,forceRebuild)
main.finishBuilding()
def defaultEntrace(self):
for b in self.targetBitness:
self.prepareBuilding(b)
self.build_mingw(b)
self.initBuildFolders()
for p in self.PRODUCT_ORDER:
self.build_thing(p,self.PRODUCTS[p],"PRODUCT")
self.finishBuilding()
def finishBuilding(self):
self.cchdir("..")
def prepareBuilding(self,b):
if not os.path.isdir(_WORKDIR):
self.logger.info("Creating workdir: %s" % (_WORKDIR))
os.makedirs(_WORKDIR, exist_ok=True)
self.cchdir(_WORKDIR)
self.bitnessDir = "x86_64" if b is 64 else "i686" # e.g x86_64
self.bitnessDir2 = "x86_64" if b is 64 else "x86" # just for vpx...
self.bitnessDir3 = "mingw64" if b is 64 else "mingw" # just for openssl...
self.winBitnessDir = "win64" if b is 64 else "win32" # e.g win64
self.compileTarget = "{0}-w64-mingw32".format ( self.bitnessDir ) # e.g x86_64-w64-mingw32
self.compilePrefix = "{0}/{1}/mingw-w64-{2}/{3}".format( self.fullWorkDir, _MINGW_DIR, self.bitnessDir, self.compileTarget ) # workdir/xcompilers/mingw-w64-x86_64/x86_64-w64-mingw32
self.offtreePrefix = "{0}".format( os.path.join(self.fullWorkDir,self.bitnessDir + "_offtree") ) # workdir/x86_64_offtree
self.hostTarget = "{0}/{1}/mingw-w64-{2}".format( self.fullWorkDir, _MINGW_DIR, self.bitnessDir )
self.mingwBinpath = "{0}/{1}/mingw-w64-{2}/bin".format( self.fullWorkDir, _MINGW_DIR, self.bitnessDir ) # e.g workdir/xcompilers/mingw-w64-x86_64/bin
self.fullCrossPrefix = "{0}/{1}-w64-mingw32-".format( self.mingwBinpath, self.bitnessDir ) # e.g workdir/xcompilers/mingw-w64-x86_64/bin/x86_64-w64-mingw32-
self.bareCrossPrefix = "{0}-w64-mingw32-".format( self.bitnessDir ) # e.g x86_64-w64-mingw32-
self.makePrefixOptions = "CC={cross_prefix_bare}gcc AR={cross_prefix_bare}ar PREFIX={compile_prefix} RANLIB={cross_prefix_bare}ranlib LD={cross_prefix_bare}ld STRIP={cross_prefix_bare}strip CXX={cross_prefix_bare}g++".format( cross_prefix_bare=self.bareCrossPrefix, compile_prefix=self.compilePrefix )
self.cmakePrefixOptions = "-G\"Unix Makefiles\" -DENABLE_STATIC_RUNTIME=1 -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={compile_prefix}".format(cross_prefix_full=self.fullCrossPrefix, compile_prefix=self.compilePrefix )
self.pkgConfigPath = "{0}/lib/pkgconfig".format( self.compilePrefix ) #e.g workdir/xcompilers/mingw-w64-x86_64/x86_64-w64-mingw32/lib/pkgconfig
self.fullProductDir = os.path.join(self.fullWorkDir,self.bitnessDir + "_products")
self.currentBitness = b
self.cpuCount = _CPU_COUNT
self.originalCflags = _ORIG_CFLAGS
if self.debugMode:
print('self.bitnessDir = \n' + self.bitnessDir + '\n\n')
print('self.bitnessDir2 = \n' + self.bitnessDir2 + '\n\n')
print('self.winBitnessDir = \n' + self.winBitnessDir + '\n\n')
print('self.compileTarget = \n' + self.compileTarget + '\n\n')
print('self.compilePrefix = \n' + self.compilePrefix + '\n\n')
print('self.mingwBinpath = \n' + self.mingwBinpath + '\n\n')
print('self.fullCrossPrefix = \n' + self.fullCrossPrefix + '\n\n')
print('self.bareCrossPrefix = \n' + self.bareCrossPrefix + '\n\n')
print('self.makePrefixOptions = \n' + self.makePrefixOptions + '\n\n')
print('self.cmakePrefixOptions = \n' + self.cmakePrefixOptions + '\n\n')
print('self.pkgConfigPath = \n' + self.pkgConfigPath + '\n\n')
print('self.fullProductDir = \n' + self.fullProductDir + '\n\n')
print('self.currentBitness = \n' + str(self.currentBitness) + '\n\n')
print('PATH = \n' + os.environ["PATH"] + '\n\n')
os.environ["PATH"] = "{0}:{1}".format ( self.mingwBinpath, self.originalPATH )
#os.environ["PATH"] = "{0}:{1}:{2}".format ( self.mingwBinpath, os.path.join(self.compilePrefix,'bin'), self.originalPATH ) #todo properly test this..
os.environ["PKG_CONFIG_PATH"] = self.pkgConfigPath
os.environ["PKG_CONFIG_LIBDIR"] = ""
#:
def initBuildFolders(self):
if not os.path.isdir(self.bitnessDir):
self.logger.info("Creating bitdir: {0}".format( self.bitnessDir ))
os.makedirs(self.bitnessDir, exist_ok=True)
if not os.path.isdir(self.bitnessDir + "_products"):
self.logger.info("Creating bitdir: {0}".format( self.bitnessDir + "_products" ))
os.makedirs(self.bitnessDir + "_products", exist_ok=True)
if not os.path.isdir(self.bitnessDir + "_offtree"):
self.logger.info("Creating bitdir: {0}".format( self.bitnessDir + "_offtree" ))
os.makedirs(self.bitnessDir + "_offtree", exist_ok=True)
def build_mingw(self,bitness):
gcc_bin = os.path.join(self.mingwBinpath, self.bitnessDir + "-w64-mingw32-gcc")
if os.path.isfile(gcc_bin):
self.logger.info("MinGW-w64 is already installed")
return
if not os.path.isdir(_MINGW_DIR):
self.logger.info("Building MinGW-w64 in folder '{0}'".format( _MINGW_DIR ))
os.makedirs(_MINGW_DIR, exist_ok=True)
os.unsetenv("CFLAGS")
self.cchdir(_MINGW_DIR)
mingw_script_file = self.download_file(self.mingwScriptURL)
#mingw_script_options = "--clean-build --disable-shared --default-configure --threads=pthreads-w32 --pthreads-w32-ver=2-9-1 --cpu-count={0} --mingw-w64-ver=git --gcc-ver=6.3.0 --enable-gendef".format ( _CPU_COUNT )
mingw_script_options = "--clean-build --disable-shared --default-configure --threads=winpthreads --cpu-count={0} --mingw-w64-ver=git --gcc-ver={1} --mingw-branch={2} --enable-gendef".format ( _CPU_COUNT, _GCC_VER, _MINGW_GIT_COMMIT_BRANCH )
self.chmodpux(mingw_script_file)
try:
self.run_process( [ "bash " + mingw_script_file, mingw_script_options, "--build-type={0}".format( self.winBitnessDir ) ], False, False )
except Exception as e:
self.logger.error("Previous MinGW build may have failed, delete the compiler folder named '{0}' and try again".format( _MINGW_DIR ))
exit(1)
self.cchdir("..")
#:
def downloadHeader(self,url):
destination = os.path.join(self.compilePrefix,"include")
fileName = os.path.basename(urlparse(url).path)
if not os.path.isfile(os.path.join(destination,fileName)):
fname = self.download_file(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 download_file(self,link, targetName = None):
_MAX_REDIRECTS = 5
cj = http.cookiejar.CookieJar()
class RHandler(urllib.request.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
result = urllib.request.HTTPRedirectHandler.http_error_301(
self, req, fp, code, msg, headers)
result.status = code
return result
def http_error_302(self, req, fp, code, msg, headers):
result = urllib.request.HTTPRedirectHandler.http_error_302(
self, req, fp, code, msg, headers)
result.status = code
return result
def sizeof_fmt(num, suffix='B'): # sizeof_fmt is courtesy of https://stackoverflow.com/a/1094933
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)
link = urllib.parse.unquote(link)
_CHUNKSIZE = 10240
if not link.lower().startswith("https") and not link.lower().startswith("file"):
print("WARNING: Using non-SSL http is not advised..") # gotta get peoples attention somehow eh?
fname = None
if targetName == None:
fname = os.path.basename(urlparse(link).path)
else:
fname = targetName
#print("Downloading {0} to {1} ".format( link, fname) )
ua = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
if 'sourceforge.net' in link.lower():
ua = 'wget/1.18' # sourceforge gives direct dls to wget agents.
f = open(fname,'ab')
hdrs = [ # act like chrome
('Connection' , 'keep-alive'),
('Pragma' , 'no-cache'),
('Cache-Control' , 'no-cache'),
('Upgrade-Insecure-Requests' , '1'),
('User-Agent' , ua),
('Accept' , 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'),
# ('Accept-Encoding' , 'gzip'),
('Accept-Language' , 'en-US,en;q=0.8'),
]
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) #),RHandler()
opener.addheaders = hdrs
response = None
request = urllib.request.Request(link)
try:
response = opener.open(request)
olink = link
for i in range(0, _MAX_REDIRECTS): # i have no idea of this is something I should be doing.
if olink == response.geturl():
break
else:
print("Following redirect to: {0}".format(response.geturl()))
response = opener.open(urllib.request.Request(response.geturl()))
olink = response.geturl()
except Exception as e:
traceback.print_exc()
f.close()
exit()
headers = str(response.info())
length = re.search(r'Content-Length: ([0-9]+)', headers, re.IGNORECASE)
fileSize = None
if length == None:
pass #tbd
else:
fileSize = int(length.groups()[0])
#fileSizeDigits = int(math.log10(fileSize))+1
downloadedBytes = 0
start = time.clock()
fancyFileSize = None
if fileSize != None:
fancyFileSize = sizeof_fmt(fileSize)
fancyFileSize = fancyFileSize.ljust(len(fancyFileSize))
isGzipped = False
if "content-encoding" in response.headers:
if response.headers["content-encoding"] == "gzip":
isGzipped = True
while True:
chunk = response.read(_CHUNKSIZE)
downloadedBytes += len(chunk)
if isGzipped:
if len(chunk):
try:
chunk = zlib.decompress(chunk, 15+32)
except Exception as e:
print(e)
exit()
f.write(chunk)
if fileSize != None:
done = int(50 * downloadedBytes / fileSize)
fancySpeed = sizeof_fmt((downloadedBytes//(time.clock() - start))/8,"B/s").rjust(5, ' ')
fancyDownloadedBytes = sizeof_fmt(downloadedBytes).rjust(len(fancyFileSize), ' ')
print("[{0}] - {1}/{2} ({3})".format( '|' * done + '-' * (50-done), fancyDownloadedBytes,fancyFileSize,fancySpeed), end= "\r")
else:
print("{0}".format( sizeof_fmt(downloadedBytes) ), end="\r")
if not len(chunk):
break
print("")
response.close()
f.close()
#print("File fully downloaded to:",fname)
return os.path.basename(link)
#:
def run_process(self,command,ignoreErrors = False, exitOnError = True):
isSvn = False
if not isinstance(command, str):
command = " ".join(command) # could fail I guess
if command.lower().startswith("svn"):
isSvn = True
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
while True:
nextline = process.stdout.readline()
if nextline == b'' and process.poll() is not None:
break
if isSvn:
if not nextline.decode('utf-8').startswith('A '):
if self.quietMode == True:
self.buildLogFile.write(nextline.decode('utf-8','replace'))
else:
sys.stdout.write(nextline.decode('utf-8','replace'))
sys.stdout.flush()
else:
if self.quietMode == True:
self.buildLogFile.write(nextline.decode('utf-8','replace'))
else:
sys.stdout.write(nextline.decode('utf-8','replace'))
sys.stdout.flush()
return_code = process.returncode
output = process.communicate()[0]
process.wait()
if (return_code == 0):
return output
else:
if ignoreErrors:
return output
self.logger.error("Error [{0}] running process: '{1}' in '{2}'".format(return_code,command,os.getcwd()))
self.logger.error("You can try deleting the product/dependency folder: '{0}' and re-run the script".format(os.getcwd()))
if self.quietMode:
self.logger.error("Please check the raw_build.log file")
if exitOnError:
exit(1)
#p = subprocess.Popen(command, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, universal_newlines = True, shell = True)
#for line in iter(p.stdout.readline, b''):
# sys.stdout.write(line)
# sys.stdout.flush()
#p.close()
def get_process_result(self,command):
if not isinstance(command, str):
command = " ".join(command) # could fail I guess
process = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True, shell=True)
out = process.stdout.readline().rstrip("\n").rstrip("\r")
process.stdout.close()
return_code = process.wait()
if (return_code == 0):
return out
else:
self.logger.error("Error [%d] creating process '%s'" % (return_code,command))
exit()
def sanitize_filename(self,f):
return re.sub(r'[/\\:*?"<>|]', '', f)
def md5(self,*args):
msg = ''.join(args).encode("utf-8")
m = hashlib.md5()
m.update(msg)
return m.hexdigest()
def touch(self,f):
Path(f).touch()
def chmodpux(self,file):
st = os.stat(file)
os.chmod(file, st.st_mode | stat.S_IXUSR) #S_IEXEC would be just +x
#:
def mercurial_clone(self,url,virtFolderName=None,renameTo=None,desiredBranch=None):
if virtFolderName == None:
virtFolderName = self.sanitize_filename(os.path.basename(url))
if not virtFolderName.endswith(".hg"): virtFolderName += ".hg"
virtFolderName = virtFolderName.replace(".hg","_hg")
else:
virtFolderName = self.sanitize_filename(virtFolderName)
realFolderName = virtFolderName
if renameTo != None:
realFolderName = renameTo
branchString = ""
if desiredBranch != None:
branchString = " {0}".format( desiredBranch )
if os.path.isdir(realFolderName):
self.cchdir(realFolderName)
hgVersion = subprocess.check_output('hg --debug id -i', shell=True)
self.run_process('hg pull -u')
self.run_process('hg update -C{0}'.format(" default" if desiredBranch == None else branchString))
hgVersionNew = subprocess.check_output('hg --debug id -i', shell=True)
if hgVersion != hgVersionNew:
self.logger.debug("HG clone has code changes, updating")
self.removeAlreadyFiles()
else:
self.logger.debug("HG clone already up to date")
self.cchdir("..")
else:
self.logger.info("HG cloning '%s' to '%s'" % (url,realFolderName))
self.run_process('hg clone {0} {1}'.format(url,realFolderName + ".tmp" ))
if desiredBranch != None:
self.cchdir(realFolderName + ".tmp")
self.logger.debug("HG updating to:{0}".format(" master" if desiredBranch == None else branchString))
self.run_process('hg up{0} -v'.format("" if desiredBranch == None else branchString))
self.cchdir("..")
self.run_process('mv "{0}" "{1}"'.format(realFolderName + ".tmp", realFolderName))
self.logger.info("Finished HG cloning '%s' to '%s'" % (url,realFolderName))
return realFolderName
#:
def git_clone(self,url,virtFolderName=None,renameTo=None,desiredBranch=None,recursive=False):
if virtFolderName == None:
virtFolderName = self.sanitize_filename(os.path.basename(url))
if not virtFolderName.endswith(".git"): virtFolderName += ".git"
virtFolderName = virtFolderName.replace(".git","_git")
else:
virtFolderName = self.sanitize_filename(virtFolderName)
realFolderName = virtFolderName
if renameTo != None:
realFolderName = renameTo
branchString = ""
if desiredBranch != None:
branchString = " {0}".format( desiredBranch )
properBranchString = "master"
if desiredBranch != None:
properBranchString = desiredBranch
if os.path.isdir(realFolderName):
self.cchdir(realFolderName)
self.run_process('git remote update')
UPSTREAM = '@{u}' # or branchName i guess
if desiredBranch != None:
UPSTREAM = properBranchString
LOCAL = subprocess.check_output('git rev-parse @',shell=True).decode("utf-8")
REMOTE = subprocess.check_output('git rev-parse "{0}"'.format(UPSTREAM),shell=True).decode("utf-8")
BASE = subprocess.check_output('git merge-base @ "{0}"'.format(UPSTREAM),shell=True).decode("utf-8")
self.run_process('git checkout -f')
self.run_process('git checkout {0}'.format(properBranchString))
if LOCAL == REMOTE:
self.logger.debug("####################")
self.logger.debug("Up to date")
self.logger.debug("LOCAL: " + LOCAL)
self.logger.debug("REMOTE: " + REMOTE)
self.logger.debug("BASE: " + BASE)
self.logger.debug("####################")
elif LOCAL == BASE:
self.logger.debug("####################")
self.logger.debug("Need to pull")
self.logger.debug("LOCAL: " + LOCAL)
self.logger.debug("REMOTE: " + REMOTE)
self.logger.debug("BASE: " + BASE)
self.logger.debug("####################")
if desiredBranch != None:
#bsSplit = properBranchString.split("/")
#if len(bsSplit) == 2:
# self.run_process('git pull origin {1}'.format(bsSplit[0],bsSplit[1]))
#else:
self.run_process('git pull origin {0}'.format(properBranchString))
else:
self.run_process('git pull'.format(properBranchString))
self.run_process('git clean -xfdf') #https://gist.github.com/nicktoumpelis/11214362
self.run_process('git submodule foreach --recursive git clean -xfdf')
self.run_process('git reset --hard')
self.run_process('git submodule foreach --recursive git reset --hard')
self.run_process('git submodule update --init --recursive')
elif REMOTE == BASE:
self.logger.debug("####################")
self.logger.debug("need to push")
self.logger.debug("LOCAL: " + LOCAL)
self.logger.debug("REMOTE: " + REMOTE)
self.logger.debug("BASE: " + BASE)
self.logger.debug("####################")
else:
self.logger.debug("####################")
self.logger.debug("diverged?")
self.logger.debug("LOCAL: " + LOCAL)
self.logger.debug("REMOTE: " + REMOTE)
self.logger.debug("BASE " + BASE)
self.logger.debug("####################")
self.cchdir("..")
else:
recur = ""
if recursive:
recur = " --recursive"
self.logger.info("GIT cloning '%s' to '%s'" % (url,os.getcwd() +"/"+ realFolderName))
self.run_process('git clone{0} --progress "{1}" "{2}"'.format(recur,url,realFolderName + ".tmp" ))
if desiredBranch != None:
self.cchdir(realFolderName + ".tmp")
self.logger.debug("GIT Checking out:{0}".format(" master" if desiredBranch == None else branchString))
self.run_process('git checkout{0}'.format(" master" if desiredBranch == None else branchString))
self.cchdir("..")
self.run_process('mv "{0}" "{1}"'.format(realFolderName + ".tmp", realFolderName))
self.logger.info("Finished GIT cloning '%s' to '%s'" % (url,realFolderName))
return realFolderName
#:
def svn_clone(self, url, dir, desiredBranch = None): # "branch".. "clone"..
dir = self.sanitize_filename(dir)
if not dir.endswith("_svn"): dir += "_svn"
if not os.path.isdir(dir):
self.logger.info("SVN checking out to %s" % (dir))
if desiredBranch == None:
self.run_process('svn co "%s" "%s.tmp" --non-interactive --trust-server-cert' % (url,dir))
else:
self.run_process('svn co -r "%s" "%s" "%s.tmp" --non-interactive --trust-server-cert' % (desiredBranch,url,dir))
shutil.move('%s.tmp' % dir, dir)
else:
pass
#svn up?
return dir
#:
def download_unpack_file(self,url,folderName = None,workDir = None):
fileName = os.path.basename(urlparse(url).path)
if folderName == None:
folderName = os.path.basename(os.path.splitext(urlparse(url).path)[0]).rstrip(".tar")
folderToCheck = folderName
if workDir != None:
folderToCheck = workDir
if not os.path.isfile(os.path.join(folderToCheck,"unpacked.successfully")):
self.logger.info("Downloading {0} ({1})".format( fileName, url ))
self.download_file(url,fileName)
self.logger.info("Unpacking {0}".format( fileName ))
tars = (".gz",".bz2",".xz",".bz",".tgz") # i really need a better system for this.. but in reality, those are probably the only formats we will ever encounter.
if fileName.endswith(tars):
self.run_process('tar -xf "{0}"'.format( fileName ))
else:
self.run_process('unzip "{0}"'.format( fileName ))
self.touch(os.path.join(folderName,"unpacked.successfully"))
os.remove(fileName)
return folderName
else:
self.logger.debug("{0} already downloaded".format( fileName ))
return folderName
#:
def get_thing_path(self,name,data,type): # type = PRODUCT or DEPENDENCY
outPath = os.getcwd()
workDir = None
renameFolder = None
if 'rename_folder' in data:
if data['rename_folder'] != None:
renameFolder = data['rename_folder']
if type == "P":
outPath = os.path.join(outPath,self.bitnessDir + "_products")
self.cchdir(self.bitnessDir + "_products")
else:
outPath = os.path.join(outPath,self.bitnessDir)
self.cchdir(self.bitnessDir)
if data["repo_type"] == "git":
branch = self.getValueOrNone(data,'branch')
recursive = self.getValueOrNone(data,'recursive_git')
folderName = self.getValueOrNone(data,'folder_name')
workDir = self.git_clone(data["url"],folderName,renameFolder,branch,recursive)
if data["repo_type"] == "svn":
workDir = self.svn_clone(data["url"],data["folder_name"],renameFolder)
if data['repo_type'] == 'mercurial':
branch = self.getValueOrNone(data,'branch')
workDir = self.mercurial_clone(data["url"],self.getValueOrNone(data,'folder_name'),renameFolder,branch)
if data["repo_type"] == "archive":
if "folder_name" in data:
workDir = self.download_unpack_file(data["url"],data["folder_name"],workDir)
else:
workDir = self.download_unpack_file(data["url"],None,workDir)
if workDir == None:
print("Unexpected error when building {0}, please report this:".format(name), sys.exc_info()[0])
raise
if 'rename_folder' in data: # this should be moved inside the download functions, TODO.. but lazy
if data['rename_folder'] != None:
if not os.path.isdir(data['rename_folder']):
shutil.move(workDir, data['rename_folder'])
workDir = data['rename_folder']
self.cchdir("..")
return os.path.join(outPath,workDir)
def build_thing(self,name,data,type,force_rebuild = False, skipDepends = False): # type = PRODUCT or DEPENDENCY # I couldn't come up with a better name :S
#we are in workdir
if '_already_built' in data:
if data['_already_built'] == True:
return
if self.debugMode:
for tk in os.environ:
print("############ " + tk + " : " + os.environ[tk])
if 'skip_deps' in data:
if data['skip_deps'] == True:
skipDepends = True
if "depends_on" in data and skipDepends == False: #dependception
if len(data["depends_on"])>0:
self.logger.info("Building dependencies of '%s'" % (name))
for libraryName in data["depends_on"]:
if libraryName not in self.DEPENDS:
raise MissingDependency("The dependency '{0}' of '{1}' does not exist in dependency config.".format( libraryName, name)) #sys.exc_info()[0]
else:
self.build_thing(libraryName,self.DEPENDS[libraryName],"DEPENDENCY")