forked from HandBrake/HandBrake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
configure.py
2174 lines (1862 loc) · 79.7 KB
/
configure.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###############################################################################
##
## This script is coded for Python 2.7 through Python 3.x
##
## Authors: konablend
##
###############################################################################
import fnmatch
import glob
import json
import os
import platform
import random
import re
import string
import subprocess
import sys
import time
from datetime import datetime, timedelta
import argparse
from sys import stderr
from sys import stdout
class AbortError( Exception ):
def __init__( self, format, *args ):
self.value = format % args
def __str__( self ):
return self.value
###############################################################################
##
## Main configure object.
##
## dir = containing this configure script
## cwd = current working dir at time of script launch
##
class Configure( object ):
OUT_QUIET = 0
OUT_INFO = 1
OUT_VERBOSE = 2
def __init__( self, verbose ):
self._log_info = []
self._log_verbose = []
self._record = False
self.verbose = verbose
self.dir = os.path.dirname( sys.argv[0] )
self.cwd = os.getcwd()
self.build_dir = '.'
## compute src dir which is 2 dirs up from this script
self.src_dir = os.path.normpath( sys.argv[0] )
for i in range( 2 ):
self.src_dir = os.path.dirname( self.src_dir )
if len( self.src_dir ) == 0:
self.src_dir = os.curdir
def _final_dir( self, chdir, dir ):
dir = os.path.normpath( dir )
if not os.path.isabs( dir ):
if os.path.isabs( chdir ):
dir = os.path.normpath( os.path.abspath(dir ))
else:
dir = os.path.normpath( self.relpath( dir, chdir ))
return dir
## output functions
def errln( self, format, *args ):
s = (format % args)
if re.match( '^.*[!?:;.]$', s ):
stderr.write( 'ERROR: %s configure stop.\n' % (s) )
else:
stderr.write( 'ERROR: %s; configure stop.\n' % (s) )
self.record_log()
sys.exit( 1 )
def infof( self, format, *args ):
line = format % args
self._log_verbose.append( line )
if self.verbose >= Configure.OUT_INFO:
self._log_info.append( line )
stdout.write( line )
def verbosef( self, format, *args ):
line = format % args
self._log_verbose.append( line )
if self.verbose >= Configure.OUT_VERBOSE:
stdout.write( line )
## doc is ready to be populated
def doc_ready( self ):
## compute final paths as they are after chdir into build
self.build_final = os.curdir
self.src_final = self._final_dir( self.build_dir, self.src_dir )
self.prefix_final = self._final_dir( self.build_dir, self.prefix_dir )
if build_tuple.match( '*-*-darwin*' ):
self.xcode_prefix_final = self._final_dir( self.build_dir, self.xcode_prefix_dir )
self.infof( 'compute: makevar SRC/ = %s\n', self.src_final )
self.infof( 'compute: makevar BUILD/ = %s\n', self.build_final )
self.infof( 'compute: makevar PREFIX/ = %s\n', self.prefix_final )
if build_tuple.match( '*-*-darwin*' ):
self.infof( 'compute: makevar XCODE.prefix/ = %s\n', self.xcode_prefix_final )
## perform chdir and enable log recording
def chdir( self ):
if os.path.abspath( self.build_dir ) == os.path.abspath( self.src_dir ):
self.errln( 'build (scratch) directory must not be the same as top-level source root!' )
if self.build_dir != os.curdir:
if os.path.exists( self.build_dir ):
if not options.force:
self.errln( 'build directory already exists: %s (use --force to overwrite)', self.build_dir )
else:
self.mkdirs( self.build_dir )
self.infof( 'chdir: %s\n', self.build_dir )
os.chdir( self.build_dir )
## enable logging
self._record = True
def mkdirs( self, dir ):
if len(dir) and not os.path.exists( dir ):
self.infof( 'mkdir: %s\n', dir )
os.makedirs( dir )
def open( self, *args ):
dir = os.path.dirname( args[0] )
if len(args) > 1 and args[1].find('w') != -1:
self.mkdirs( dir )
m = re.match( '^(.*)\.tmp\..{8}$', args[0] )
if m:
self.infof( 'write: %s\n', m.group(1) )
else:
self.infof( 'write: %s\n', args[0] )
try:
return open( *args )
except Exception as x:
self.errln( 'open failure: %s', x )
def record_log( self ):
if not self._record:
return
self._record = False
self.verbose = Configure.OUT_QUIET
log_info_file = self.open( 'log/config.info.txt', 'w' )
for line in self._log_info:
log_info_file.write( line )
log_info_file.close()
log_verbose_file = self.open( 'log/config.verbose.txt', 'w' )
for line in self._log_verbose:
log_verbose_file.write( line )
log_verbose_file.close()
## Find executable by searching path.
## On success, returns full pathname of executable.
## On fail, returns None.
def findExecutable( self, name ):
if len( os.path.split(name)[0] ):
if os.access( name, os.X_OK ):
return name
return None
path = os.getenv( 'PATH' ) or os.defpath
for dir in path.split( os.pathsep ):
f = os.path.join( dir, name )
if os.access( f, os.X_OK ):
return f
return None
## taken from python2.6 -- we need it
def relpath( self, path, start=os.curdir ):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = os.path.abspath(start).split(os.sep)
path_list = os.path.abspath(path).split(os.sep)
# Work out how much of the filepath is shared by start and path.
i = len(os.path.commonprefix([start_list, path_list]))
rel_list = [os.pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return os.curdir
return os.path.join(*rel_list)
## update with parsed cli options
def update_cli( self, options ):
self.src_dir = os.path.normpath( options.src )
self.build_dir = os.path.normpath( options.build )
self.prefix_dir = os.path.normpath( options.prefix )
if build_tuple.match( '*-*-darwin*' ) and options.cross is None:
self.xcode_prefix_dir = os.path.normpath( options.xcode_prefix )
if options.sysroot != None:
self.sysroot_dir = os.path.normpath( options.sysroot )
else:
self.sysroot_dir = ""
try:
self.minver = options.minver
except:
self.minver = ""
## special case if src == build: add build subdir
if os.path.abspath( self.src_dir ) == os.path.abspath( self.build_dir ):
self.build_dir = os.path.join( self.build_dir, 'build' )
## generate a temporary filename - not worried about race conditions
def mktmpname( self, filename ):
return filename + '.tmp.' + ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
###############################################################################
##
## abstract action
##
## pretext = text which immediately follows 'probe:' output prefix
## abort = if true configure will exit on probe fail
## head = if true probe session is stripped of all but first line
## session = output from command, including stderr
## fail = true if probe failed
##
class Action( object ):
actions = []
def __init__( self, category, pretext='unknown', abort=False, head=False ):
if self not in Action.actions:
Action.actions.append( self )
self.category = category
self.pretext = pretext
self.abort = abort
self.head = head
self.session = None
self.run_done = False
self.fail = True
self.msg_fail = 'fail'
self.msg_pass = 'pass'
self.msg_end = 'end'
def _actionBegin( self ):
cfg.infof( '%s: %s...', self.category, self.pretext )
def _actionEnd( self ):
if self.fail:
cfg.infof( '(%s) %s\n', self.msg_fail, self.msg_end )
if self.abort:
self._dumpSession( cfg.infof )
cfg.errln( 'unable to continue' )
self._dumpSession( cfg.verbosef )
self._failSession()
else:
cfg.infof( '(%s) %s\n', self.msg_pass, self.msg_end )
self._dumpSession( cfg.verbosef )
def _dumpSession( self, printf ):
if self.session and len(self.session):
for line in self.session:
printf( ' : %s\n', line )
else:
printf( ' : <NO-OUTPUT>\n' )
def _parseSession( self ):
pass
def _failSession( self ):
pass
def run( self ):
if self.run_done:
return
self.run_done = True
self._actionBegin()
self._action()
if not self.fail:
self._parseSession()
self._actionEnd()
###############################################################################
##
## base probe: anything which runs in shell.
##
## pretext = text which immediately follows 'probe:' output prefix
## command = full command and arguments to pipe
## abort = if true configure will exit on probe fail
## head = if true probe session is stripped of all but first line
## session = output from command, including stderr
## fail = true if probe failed
##
class ShellProbe( Action ):
def __init__( self, pretext, command, abort=False, head=False ):
super( ShellProbe, self ).__init__( 'probe', pretext, abort, head )
self.command = command
def _action( self ):
## pipe and redirect stderr to stdout; effects communicate result
pipe = subprocess.Popen( self.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
## read data into memory buffers, only first element (stdout) data is used
data = pipe.communicate()
self.fail = pipe.returncode != 0
if data[0]:
self.session = data[0].splitlines()
else:
self.session = []
if pipe.returncode:
self.msg_end = 'code %d' % (pipe.returncode)
def _dumpSession( self, printf ):
printf( ' + %s\n', self.command )
super( ShellProbe, self )._dumpSession( printf )
###############################################################################
##
## Compile test probe: determine if compile time feature is supported
##
## returns true if feature successfully compiles
##
##
class CCProbe( Action ):
def __init__( self, pretext, command, test_file ):
super( CCProbe, self ).__init__( 'probe', pretext )
self.command = command
self.test_file = test_file
def _action( self ):
## write program file
with open( 'conftest.c', 'w' ) as out_file:
out_file.write( self.test_file )
## pipe and redirect stderr to stdout; effects communicate result
pipe = subprocess.Popen( '%s -c -o conftest.o conftest.c' % self.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
## read data into memory buffers, only first element (stdout) data is used
data = pipe.communicate()
self.fail = pipe.returncode != 0
if data[0]:
self.session = data[0].splitlines()
else:
self.session = []
if pipe.returncode:
self.msg_end = 'code %d' % (pipe.returncode)
os.remove( 'conftest.c' )
if not self.fail:
os.remove( 'conftest.o' )
def _dumpSession( self, printf ):
printf( ' + %s\n', self.command )
super( CCProbe, self )._dumpSession( printf )
###############################################################################
##
## Compile test probe: determine if compile time feature is supported
##
## returns true if feature successfully compiles
##
##
def PkgConfigTest(args, lib):
msg_end = ''
if Tools.pkgconfig.fail:
fail = True
session = []
msg_end = 'No pkg-config'
return fail, msg_end, session
## pipe and redirect stderr to stdout; effects communicate result
pipe = subprocess.Popen( '%s %s %s' %
(Tools.pkgconfig.pathname, args, lib),
shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
## read data into memory buffers, only first element (stdout)
## data is used
data = pipe.communicate()
fail = pipe.returncode != 0
if data[0]:
session = data[0].splitlines()
else:
session = []
if pipe.returncode:
msg_end = 'code %d' % (pipe.returncode)
return fail, msg_end, session
class PkgConfigProbe( Action ):
def __init__( self, pretext, args, lib ):
super( PkgConfigProbe, self ).__init__( 'probe', pretext )
self.args = args
self.lib = lib
def _action( self ):
self.fail, self.msg_end, self.session = PkgConfigTest(self.args,
self.lib)
def _dumpSession( self, printf ):
printf( ' + %s %s\n', Tools.pkgconfig.pathname, self.args )
super( PkgConfigProbe, self )._dumpSession( printf )
###############################################################################
##
## Compile test probe: determine if compile time feature is supported
##
## returns true if feature successfully compiles
##
##
def LDTest(command, lib, test_file):
## write program file
with open( 'conftest.c', 'w' ) as out_file:
out_file.write( test_file )
## pipe and redirect stderr to stdout; effects communicate result
pipe = subprocess.Popen( '%s -o conftest conftest.c %s' % (command, lib), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
## read data into memory buffers, only first element (stdout) data is used
data = pipe.communicate()
fail = pipe.returncode != 0
if data[0]:
session = data[0].splitlines()
else:
session = []
msg_end = ''
if pipe.returncode:
msg_end = 'code %d' % (pipe.returncode)
os.remove( 'conftest.c' )
if not fail:
try:
os.remove( 'conftest.exe' )
except:
pass
try:
os.remove( 'conftest' )
except:
pass
return (fail, msg_end, session)
class LDProbe( Action ):
def __init__( self, pretext, command, lib, test_file ):
super( LDProbe, self ).__init__( 'probe', pretext )
self.command = command
self.test_file = test_file
self.lib = lib
def _action( self ):
self.fail, self.msg_end, self.session = LDTest(
self.command, self.lib, self.test_file)
def _dumpSession( self, printf ):
printf( ' + %s\n', self.command )
super( LDProbe, self )._dumpSession( printf )
###############################################################################
##
## Basic library existence check
##
## returns true if feature successfully compiles
##
##
class ChkLib( Action ):
def __init__( self, pretext, command, lib, test_file, abort=False ):
super( ChkLib, self ).__init__( 'probe', pretext, abort=abort )
self.command = command
self.test_file = test_file
self.lib = lib
def _action( self ):
## First try pkg-config
if not Tools.pkgconfig.fail:
self.fail, self.msg_end, self.session = PkgConfigTest(
'--libs', self.lib)
if not self.fail:
return
## If pkg-config fails, try compiling and linking test file
self.fail, self.msg_end, session = LDTest(
self.command, '-l%s' % self.lib, self.test_file)
self.session.append(session)
###############################################################################
##
## GNU build tuple probe: determine canonical platform type
##
## example results from various platforms:
##
## x86_64-apple-darwin15.6.0 (Mac OS X 10.11.6 Intel)
## x86_64-apple-darwin16.6.0 (macOS 10.12.6 Intel)
## i686-pc-cygwin (Cygwin, Microsoft Vista)
## x86_64-unknown-linux-gnu (Linux, Fedora 10 x86_64)
##
class BuildTupleProbe( ShellProbe, list ):
GNU_TUPLE_RE = '([^-]+)-?([^-]*)-([^0-9-]+)([^-]*)-?([^-]*)'
def __init__( self ):
super( BuildTupleProbe, self ).__init__( 'build tuple', '%s/config.guess' % (cfg.dir), abort=True, head=True )
def _parseSession( self ):
self.spec = self.session[0].decode('utf-8') if self.session else ''
## grok GNU build tuples
m = re.match( BuildTupleProbe.GNU_TUPLE_RE, self.spec )
if not m:
self.fail = True
self.msg_end = 'invalid build tuple: %s' % (self.spec)
return
self.msg_end = self.spec
## assign tuple from regex
self[:] = m.groups()
## for clarity
self.machine = self[0]
self.vendor = self[1]
self.system = self[2]
self.release = self[3]
self.extra = self[4]
## nice formal name for 'system'
self.systemf = platform.system()
if self.match( '*-*-cygwin*' ):
self.systemf = self[2][0].upper() + self[2][1:]
## glob-match against spec
def match( self, *specs ):
for spec in specs:
if fnmatch.fnmatch( self.spec, spec ):
return True
return False
###############################################################################
class HostTupleAction( Action, list ):
def __init__( self, cross=None ):
super( HostTupleAction, self ).__init__( 'compute', 'host tuple', abort=True )
# Initialize, but allow to be reset by options
self.setHost(cross)
def setHost( self, cross ):
## check if --cross spec was used; must maintain 5-tuple compatibility with regex
if cross is not None:
self.spec = os.path.basename( cross ).rstrip( '-' )
else:
self.spec = build_tuple.spec
## grok GNU build tuples
m = re.match( BuildTupleProbe.GNU_TUPLE_RE, self.spec )
if not m:
self.msg_end = 'invalid build tuple: %s' % (self.spec)
return
self.msg_end = self.spec
## assign tuple from regex
self[:] = m.groups()
## for clarity
self.machine = self[0]
self.vendor = self[1]
self.system = self[2]
self.release = self[3]
self.extra = self[4]
self.systemf = build_tuple.systemf
try:
self.machine = arch.mode.mode
except NameError:
pass
## when cross we need switch for platforms
if cross is not None:
if self.match( '*mingw*' ):
self.systemf = 'MinGW'
elif self.systemf:
self.systemf = self.systemf.capitalize()
self.title = '%s %s' % (self.systemf,self.machine)
self.fail = False
self.spec = ('%s-%s-%s%s-%s' % (self.machine, self.vendor, self.system,
self.release, self.extra)).rstrip('-')
def _action( self ):
try:
self.setHost(options.cross)
except NameError:
self.setHost(None)
## glob-match against spec
def match( self, *specs ):
for spec in specs:
if fnmatch.fnmatch( self.spec, spec ):
return True
return False
###############################################################################
##
## value wrapper; value is accepted only if one of host specs matches
## otherwise it is None (or a keyword-supplied val)
##
## result is attribute 'value'
##
class IfHost( object ):
def __init__( self, value, *specs, **kwargs ):
self.value = kwargs.get('none',None)
for spec in specs:
if host_tuple.match( spec ):
self.value = value
break
def __nonzero__( self ):
return self.value != None
def __str__( self ):
return self.value
class IfBuild( object ):
def __init__( self, value, *specs, **kwargs ):
self.value = kwargs.get('none',None)
for spec in specs:
if build_tuple.match( spec ):
self.value = value
break
def __nonzero__( self ):
return self.value != None
def __str__( self ):
return self.value
###############################################################################
##
## platform conditional value; loops through list of tuples comparing
## to first host match and sets value accordingly; the first value is
## always default.
##
class ForHost( object ):
def __init__( self, default, *tuples ):
self.value = default
for tuple in tuples:
if host_tuple.match( tuple[1] ):
self.value = tuple[0]
break
def __str__( self ):
return self.value
###############################################################################
class ArchAction( Action ):
def __init__( self ):
super( ArchAction, self ).__init__( 'compute', 'available architectures', abort=True )
self.mode = SelectMode( 'architecture', (host_tuple.machine,host_tuple.spec) )
def _action( self ):
self.fail = False
## some match on system should be made here; otherwise we signal a warning.
if host_tuple.match( '*-*-cygwin*' ):
pass
elif host_tuple.match( '*-*-mingw*' ):
pass
elif host_tuple.match( '*-*-darwin*' ):
self.mode['x86_64'] = 'x86_64-apple-darwin%s' % (host_tuple.release)
elif host_tuple.match( '*-*-linux*' ):
pass
elif host_tuple.match( '*-*-solaris*' ):
pass
elif host_tuple.match( '*-*-freebsd*' ):
self.mode['i386'] = 'i386-portsbuild-freebsd%s' % (host_tuple.release)
self.mode['amd64'] = 'amd64-portsbuild-freebsd%s' % (host_tuple.release)
else:
self.msg_pass = 'WARNING'
self.msg_end = self.mode.toString()
## glob-match against spec
def match( self, spec ):
return fnmatch.fnmatch( self.spec, spec )
###############################################################################
class CoreProbe( Action ):
def __init__( self ):
super( CoreProbe, self ).__init__( 'probe', 'number of CPU cores' )
self.count = 1
def _action( self ):
if self.fail:
## good for darwin9.6.0 and linux
try:
self.count = os.sysconf( 'SC_NPROCESSORS_ONLN' )
if self.count < 1:
self.count = 1
self.fail = False
except:
pass
if self.fail:
## windows
try:
self.count = int( os.environ['NUMBER_OF_PROCESSORS'] )
if self.count < 1:
self.count = 1
self.fail = False
except:
pass
## clamp
if self.count < 1:
self.count = 1
elif self.count > 64:
self.count = 64
if options.launch:
if options.launch_jobs == 0:
self.jobs = core.count
else:
self.jobs = options.launch_jobs
else:
self.jobs = core.count
self.msg_end = str(self.count)
###############################################################################
class StoreCallbackAction(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
self.callback = kwargs.pop('callback', None)
super(StoreCallbackAction, self).__init__(
option_strings, dest, nargs, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
if self.callback != None:
self.callback(self, values)
class SelectMode( dict ):
def __init__( self, descr, *modes, **kwargs ):
super( SelectMode, self ).__init__( modes )
self.descr = descr
self.modes = modes
self.what = kwargs.get('what',' mode')
if modes:
self.default = kwargs.get('default',modes[0][0])
else:
self.default = None
self.mode = self.default
def cli_add_argument( self, parser, option ):
parser.add_argument(option, nargs='?', metavar='MODE',
default=self.mode, const=self.mode,
help='select %s%s: %s' % (self.descr,self.what,self.toString()),
action=StoreCallbackAction, callback=self.cli_callback)
def cli_callback( self, action, value ):
if value not in self:
raise argparse.ArgumentError(action,
'invalid %s%s: %s (choose from: %s)'
% (self.descr, self.what, value, self.toString(True)))
self.mode = value
def toString( self, nodefault=False ):
keys = list(self.copy().keys())
keys.sort()
if len(self) == 1:
value = self.mode
elif nodefault:
value = ' '.join( keys )
else:
value = '%s [%s]' % (' '.join( keys ), self.mode )
return value
###############################################################################
##
## Repository object.
## Holds information gleaned from subversion working dir.
##
## Builds are classed into one of the following types:
##
## release
## must be built from official git at version tag
## developer
## must be built from official git but is not a release
##
class RepoProbe( ShellProbe ):
def __init__( self ):
# Find script that creates repo info
try:
repo_info = os.path.join( cfg.src_dir, 'scripts', 'repo-info.sh' )
if not os.path.isfile( repo_info ):
cfg.errln( 'Missing required script %s\n', repo_info )
sys.exit( 1 )
except:
sys.exit( 1 )
super( RepoProbe, self ).__init__( 'repo info', '%s %s' %
(repo_info, cfg.src_dir) )
self.url = 'git://nowhere.com/project/unknown'
self.tag = ''
self.tag_hash = 'deadbeaf'
self.branch = 'unknown'
self.remote = 'unknown'
self.rev = 0
self.hash = 'deadbeaf'
self.shorthash = 'deadbea'
self.date = None
self.official = 0
self.type = 'developer'
def _parseSession( self ):
for line in self.session:
if isinstance(line, bytes):
line = line.decode('utf-8')
## grok fields
m = re.match( '([^\=]+)\=(.*)', line )
if not m:
continue
(name,value) = m.groups()
if name == 'URL' and value != '':
self.url = value
elif name == 'TAG':
self.tag = value
elif name == 'TAG_HASH':
self.tag_hash = value
elif name == 'BRANCH':
self.branch = value
elif name == 'REMOTE':
self.remote = value
elif name == 'REV':
self.rev = int( value )
elif name == 'DATE':
self.date = datetime.strptime(value[0:19], "%Y-%m-%d %H:%M:%S")
# strptime can't handle UTC offset
m = re.match( '^([-+]?[0-9]{2})([0-9]{2})$', value[20:])
(hh, mn) = m.groups()
utc_off_hour = int(hh)
utc_off_minute = int(mn)
if utc_off_hour >= 0:
utc_off = utc_off_hour * 60 + utc_off_minute
else:
utc_off = utc_off_hour * 60 - utc_off_minute
delta = timedelta(minutes=utc_off)
self.date = self.date - delta
elif name == 'HASH':
self.hash = value
elif name == 'SHORTHASH':
if value != '':
self.shorthash = value
else:
self.shorthash = self.hash
# type-classification via repository URL
if self.url == project.url_repo_ssh:
self.url = project.url_repo # official repo, SSH to HTTPS
if self.url == project.url_repo:
self.official = 1
if not options.snapshot and self.hash == self.tag_hash:
self.type = 'release'
else:
self.type = 'developer'
self.msg_end = self.url
def _failSession( self ):
# Look for repo info in version file.
#
# Version file would be created manually by source packager.
# e.g.
# $ HandBrake/scripts/repo-info.sh HandBrake > HandBrake/version.txt
# $ tar -czf handbrake-source.tgz --exclude .git HandBrake
cfg.infof( 'probe: version.txt...' )
try:
hvp = os.path.join( cfg.src_dir, 'version.txt' )
if os.path.isfile( hvp ) and os.path.getsize( hvp ) > 0:
with open( hvp, 'r' ) as in_file:
self.session = in_file.readlines()
if self.session:
self._parseSession()
if self.hash and self.hash != 'deadbeaf':
cfg.infof( '(pass)\n' )
else:
cfg.infof( '(fail)\n' )
except:
cfg.infof( '(fail)\n' )
###############################################################################
##
## project object.
##
## Contains manually updated version numbers consistent with HB releases
## and other project metadata.
##
class Project( Action ):
def __init__( self ):
super( Project, self ).__init__( 'compute', 'project data' )
self.name = 'HandBrake'
self.acro_lower = 'hb'
self.acro_upper = 'HB'
self.url_website = 'https://handbrake.fr'
self.url_repo = 'https://github.com/HandBrake/HandBrake.git'
self.url_repo_ssh = '[email protected]:HandBrake/HandBrake.git'
self.url_community = 'https://forum.handbrake.fr'
self.url_irc = 'irc://irc.freenode.net/handbrake'
self.name_lower = self.name.lower()
self.name_upper = self.name.upper()
self.vmajor = 0
self.vminor = 0
self.vpoint = 0
self.spoint = 0
self.suffix = ''
self.special = ''
def _action( self ):
## add architecture to URL only for Mac
if fnmatch.fnmatch( host_tuple.spec, '*-*-darwin*' ):
url_arch = '.%s' % (arch.mode.mode)
else:
url_arch = ''
if repo.date is None:
cfg.errln( '%s is missing version information it needs to build properly.\nClone the official git repository at %s\nor download an official source archive from %s\n', self.name, self.url_repo, self.url_website )
sys.exit( 1 )
if repo.tag != '':
m = re.match( '^([0-9]+)\.([0-9]+)\.([0-9]+)-?(.+)?$', repo.tag )
if not m:
cfg.errln( 'Invalid repo tag format %s\n', repo.tag )
sys.exit( 1 )
(vmajor, vminor, vpoint, suffix) = m.groups()
self.vmajor = int(vmajor)
self.vminor = int(vminor)
self.vpoint = int(vpoint)
if suffix:
self.suffix = suffix
if repo.type != 'release' or options.snapshot:
self.version = repo.date.strftime("%Y%m%d%H%M%S")
self.version += '-%s' % (repo.shorthash)
if repo.branch != '':
self.version += '-%s' % (repo.branch)
self.debversion = repo.date.strftime("%Y%m%d%H%M%S")
self.debversion += '-%s' % (repo.shorthash)
if repo.branch != '':
self.debversion += '-%s' % (repo.branch)
url_ctype = '_unstable'
url_ntype = 'unstable'
self.build = time.strftime('%Y%m%d', now) + '01'
self.title = '%s %s (%s)' % (self.name,self.version,self.build)
else:
m = re.match('^([a-zA-Z]+)\.([0-9]+)$', self.suffix)
if not m:
# Regular release
self.version = '%d.%d.%d' % (self.vmajor,self.vminor,self.vpoint)
self.debversion = '%d.%d.%d' % (self.vmajor, self.vminor, self.vpoint)
url_ctype = ''
url_ntype = 'stable'
else:
(special, spoint,) = m.groups()
self.special = special
self.spoint = int(spoint)
self.version = '%d.%d.%d-%s.%d' % (self.vmajor,self.vminor,self.vpoint, self.special, self.spoint)
self.debversion = '%d.%d.%d~%s.%d' % (self.vmajor, self.vminor, self.vpoint, self.special, self.spoint)
url_ctype = '_unstable'
url_ntype = 'unstable'
self.build = time.strftime('%Y%m%d', now) + '00'
self.title = '%s %s (%s)' % (self.name,self.version,self.build)
self.url_appcast = 'https://handbrake.fr/appcast%s%s.xml' % (url_ctype,url_arch)
self.url_appnote = 'https://handbrake.fr/appcast/%s.html' % (url_ntype)
self.msg_end = '%s (%s)' % (self.name,repo.type)
self.fail = False