-
Notifications
You must be signed in to change notification settings - Fork 304
/
Blackfile.py
2750 lines (2464 loc) · 111 KB
/
Blackfile.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
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is Komodo code.
#
# The Initial Developer of the Original Code is ActiveState Software Inc.
# Portions created by ActiveState Software Inc are Copyright (C) 2000-2007
# ActiveState Software Inc. All Rights Reserved.
#
# Contributor(s):
# ActiveState Software Inc
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
"""Blackfile for Komodo.
Usage:
bk configure ... # configure a Komodo build
bk build # build it
bk package # create a package (default is the native installer)
Typical commands for a Komodo development build:
bk configure --release --moz-src=../path/to/moz/build
bk build
bk run # run it, test it
Typical commands for building all Komodo bits:
bk configure --release --moz-src=../path/to/moz/build --full
bk build # build all the bits
bk image # put the install image together
bk package [PKGNAME] # package up everything, don't specify a
# PKGNAME to build all packages that this
# platform can build
PKGNAME's are installer (aka msi, dbg, aspackage).
"""
import os, sys, os, shutil
import cPickle as pickle
import time
from os.path import join, dirname, exists, isfile, basename, abspath, \
isdir, splitext
from fnmatch import fnmatch
import glob
import shutil
try:
from hashlib import md5
except ImportError:
from md5 import md5
import subprocess
import operator
import logging
import black, black.configure, black.configure.std
import tmShUtil
sys.path.insert(0, "")
from bklocal import * # local Black configuration items
sys.path.insert(0, "util")
try:
import patchtree
import platinfo
import buildutils
import kopkglib
import applib
import changelog
finally:
del sys.path[0]
#---- exceptions
class Error(Exception):
pass
#---- globals
log = logging.getLogger("build")
if 1:
# Remove logging setup if/when "bk" grows real logging control.
logging.basicConfig()
log.setLevel(logging.INFO)
out = sys.stdout
_table = {} # for "build quick"
if sys.platform == "win32":
EXE = ".exe"
else:
EXE = ""
#---- internal support routines
# Recipe: paths_from_path_patterns (0.3.6)
def _should_include_path(path, includes, excludes):
"""Return True iff the given path should be included."""
from os.path import basename
from fnmatch import fnmatch
base = basename(path)
if includes:
for include in includes:
if fnmatch(base, include):
try:
log.debug("include `%s' (matches `%s')", path, include)
except (NameError, AttributeError):
pass
break
else:
log.debug("exclude `%s' (matches no includes)", path)
return False
for exclude in excludes:
if fnmatch(base, exclude):
try:
log.debug("exclude `%s' (matches `%s')", path, exclude)
except (NameError, AttributeError):
pass
return False
return True
_NOT_SPECIFIED = ("NOT", "SPECIFIED")
def _paths_from_path_patterns(path_patterns, files=True, dirs="never",
recursive=True, includes=[], excludes=[],
on_error=_NOT_SPECIFIED):
"""_paths_from_path_patterns([<path-patterns>, ...]) -> file paths
Generate a list of paths (files and/or dirs) represented by the given path
patterns.
"path_patterns" is a list of paths optionally using the '*', '?' and
'[seq]' glob patterns.
"files" is boolean (default True) indicating if file paths
should be yielded
"dirs" is string indicating under what conditions dirs are
yielded. It must be one of:
never (default) never yield dirs
always yield all dirs matching given patterns
if-not-recursive only yield dirs for invocations when
recursive=False
See use cases below for more details.
"recursive" is boolean (default True) indicating if paths should
be recursively yielded under given dirs.
"includes" is a list of file patterns to include in recursive
searches.
"excludes" is a list of file and dir patterns to exclude.
(Note: This is slightly different than GNU grep's --exclude
option which only excludes *files*. I.e. you cannot exclude
a ".svn" dir.)
"on_error" is an error callback called when a given path pattern
matches nothing:
on_error(PATH_PATTERN)
If not specified, the default is look for a "log" global and
call:
log.error("`%s': No such file or directory")
Specify None to do nothing.
Typically this is useful for a command-line tool that takes a list
of paths as arguments. (For Unix-heads: the shell on Windows does
NOT expand glob chars, that is left to the app.)
Use case #1: like `grep -r`
{files=True, dirs='never', recursive=(if '-r' in opts)}
script FILE # yield FILE, else call on_error(FILE)
script DIR # yield nothing
script PATH* # yield all files matching PATH*; if none,
# call on_error(PATH*) callback
script -r DIR # yield files (not dirs) recursively under DIR
script -r PATH* # yield files matching PATH* and files recursively
# under dirs matching PATH*; if none, call
# on_error(PATH*) callback
Use case #2: like `file -r` (if it had a recursive option)
{files=True, dirs='if-not-recursive', recursive=(if '-r' in opts)}
script FILE # yield FILE, else call on_error(FILE)
script DIR # yield DIR, else call on_error(DIR)
script PATH* # yield all files and dirs matching PATH*; if none,
# call on_error(PATH*) callback
script -r DIR # yield files (not dirs) recursively under DIR
script -r PATH* # yield files matching PATH* and files recursively
# under dirs matching PATH*; if none, call
# on_error(PATH*) callback
Use case #3: kind of like `find .`
{files=True, dirs='always', recursive=(if '-r' in opts)}
script FILE # yield FILE, else call on_error(FILE)
script DIR # yield DIR, else call on_error(DIR)
script PATH* # yield all files and dirs matching PATH*; if none,
# call on_error(PATH*) callback
script -r DIR # yield files and dirs recursively under DIR
# (including DIR)
script -r PATH* # yield files and dirs matching PATH* and recursively
# under dirs; if none, call on_error(PATH*)
# callback
"""
from os.path import basename, exists, isdir, join
from glob import glob
assert not isinstance(path_patterns, basestring), \
"'path_patterns' must be a sequence, not a string: %r" % path_patterns
GLOB_CHARS = '*?['
for path_pattern in path_patterns:
# Determine the set of paths matching this path_pattern.
for glob_char in GLOB_CHARS:
if glob_char in path_pattern:
paths = glob(path_pattern)
break
else:
paths = exists(path_pattern) and [path_pattern] or []
if not paths:
if on_error is None:
pass
elif on_error is _NOT_SPECIFIED:
try:
log.error("`%s': No such file or directory", path_pattern)
except (NameError, AttributeError):
pass
else:
on_error(path_pattern)
for path in paths:
if isdir(path):
# 'includes' SHOULD affect whether a dir is yielded.
if (dirs == "always"
or (dirs == "if-not-recursive" and not recursive)
) and _should_include_path(path, includes, excludes):
yield path
# However, if recursive, 'includes' should NOT affect
# whether a dir is recursed into. Otherwise you could
# not:
# script -r --include="*.py" DIR
if recursive and _should_include_path(path, [], excludes):
for dirpath, dirnames, filenames in os.walk(path):
dir_indeces_to_remove = []
for i, dirname in enumerate(dirnames):
d = join(dirpath, dirname)
if dirs == "always" \
and _should_include_path(d, includes, excludes):
yield d
if not _should_include_path(d, [], excludes):
dir_indeces_to_remove.append(i)
for i in reversed(dir_indeces_to_remove):
del dirnames[i]
if files:
for filename in sorted(filenames):
f = join(dirpath, filename)
if _should_include_path(f, includes, excludes):
yield f
elif files and _should_include_path(path, includes, excludes):
yield path
# Recipe: splitall (0.2) in C:\trentm\tm\recipes\cookbook
def _splitall(path):
r"""Split the given path into all constituent parts.
Often, it's useful to process parts of paths more generically than
os.path.split(), for example if you want to walk up a directory.
This recipe splits a path into each piece which corresponds to a
mount point, directory name, or file. A few test cases make it
clear:
>>> splitall('')
[]
>>> splitall('a/b/c')
['a', 'b', 'c']
>>> splitall('/a/b/c/')
['/', 'a', 'b', 'c']
>>> splitall('/')
['/']
>>> splitall('C:\\a\\b')
['C:\\', 'a', 'b']
>>> splitall('C:\\a\\')
['C:\\', 'a']
(From the Python Cookbook, Files section, Recipe 99.)
"""
allparts = []
while 1:
parts = os.path.split(path)
if parts[0] == path: # sentinel for absolute paths
allparts.insert(0, parts[0])
break
elif parts[1] == path: # sentinel for relative paths
allparts.insert(0, parts[1])
break
else:
path = parts[0]
allparts.insert(0, parts[1])
allparts = [p for p in allparts if p] # drop empty strings
return allparts
# Recipe: relpath (0.2) in C:\trentm\tm\recipes\cookbook
def _relpath(path, relto=None):
"""Relativize the given path to another (relto).
"relto" indicates a directory to which to make "path" relative.
It default to the cwd if not specified.
"""
if not os.path.isabs(path):
path = os.path.abspath(path)
if relto is None:
relto = os.getcwd()
else:
relto = os.path.abspath(relto)
if sys.platform.startswith("win"):
def _equal(a, b): return a.lower() == b.lower()
else:
def _equal(a, b): return a == b
pathDrive, pathRemainder = os.path.splitdrive(path)
if not pathDrive:
pathDrive = os.path.splitdrive(os.getcwd())[0]
relToDrive, relToRemainder = os.path.splitdrive(relto)
if not _equal(pathDrive, relToDrive):
# Which is better: raise an exception or return ""?
return ""
#raise OSError("Cannot make '%s' relative to '%s'. They are on "\
# "different drives." % (path, relto))
pathParts = _splitall(pathRemainder)[1:] # drop the leading root dir
relToParts = _splitall(relToRemainder)[1:] # drop the leading root dir
#print "_relpath: pathPaths=%s" % pathParts
#print "_relpath: relToPaths=%s" % relToParts
for pathPart, relToPart in zip(pathParts, relToParts):
if _equal(pathPart, relToPart):
# drop the leading common dirs
del pathParts[0]
del relToParts[0]
#print "_relpath: pathParts=%s" % pathParts
#print "_relpath: relToParts=%s" % relToParts
# Relative path: walk up from "relto" dir and walk down "path".
relParts = [os.curdir] + [os.pardir]*len(relToParts) + pathParts
#print "_relpath: relParts=%s" % relParts
relPath = os.path.normpath( os.path.join(*relParts) )
return relPath
def _short_ver_str_from_ver_info(ver_info):
def isint(s):
try:
int(s)
except ValueError:
return False
else:
return True
dotted = []
for bit in ver_info:
if bit is None:
continue
if dotted and isint(dotted[-1]) and isint(bit):
dotted.append('.')
dotted.append(str(bit))
return ''.join(dotted)
def _ver_info_from_long_ver_str(long_ver_str):
"""Return a version info tuple for the given long version string.
Examples of a "long" version string are:
4.0.0-alpha3-12345, 1.2.3-beta-54321, 4.2.5-2598, 5.0.0-43251
"Short" would be more like:
4.0.0a3, 1.2.3b, 4.2.5
The returned tuple will be:
(<major>, <minor>, <patch>, <quality>, <quality-num>, <build-num>)
where <quality> is a letter ('a' for alpha, 'b' for beta, 'c' if not
given). <quality-num> and <build-num> default to None. The defaults are
chosen to make sorting result in a natural order.
"""
def _isalpha(ch):
return 'a' <= ch <= 'z' or 'A' <= ch <= 'Z'
def _isdigit(ch):
return '0' <= ch <= '9'
def _split_quality(s):
for i in reversed(range(1, len(s)+1)):
if not _isdigit(s[i-1]):
break
if i == len(s):
quality_name, quality_num = s, None
else:
quality_name, quality_num = s[:i], int(s[i:])
quality = {'alpha': 'a', 'beta': 'b', 'rc': 'c', 'devel': 'd'}[quality_name]
return quality, quality_num
bits = []
for i, undashed in enumerate(long_ver_str.split('-')):
for undotted in undashed.split('.'):
if len(bits) == 3:
# This is the "quality" section: 2 bits
if _isalpha(undotted[0]):
bits += list(_split_quality(undotted))
continue
else:
bits += ['c', None]
try:
bits.append(int(undotted))
except ValueError:
bits.append(undotted)
# After first undashed segment should have: (major, minor, patch)
if i == 0:
while len(bits) < 3:
bits.append(0)
return tuple(bits)
def _cp(src, dst):
if sys.platform == "win32":
if isdir(src):
if not exists(dst):
os.makedirs(dst)
_run('xcopy /q/s "%s" "%s"' % (src, dst))
elif '*' in src or '?' in src:
if not exists(dst):
os.makedirs(dst)
for path in glob.glob(src):
_run('copy "%s" "%s"' % (path, dst))
else:
if not exists(dirname(dst)):
os.makedirs(dirname(dst))
_run('copy "%s" "%s"' % (src, dst))
else:
if '*' in src or '?' in src:
_run('mkdir -p "%s"' % dst)
for path in glob.glob(src):
_run('cp -R "%s" "%s"' % (path, dst))
else:
_run('mkdir -p "%s"' % dirname(dst))
_run('cp -R "%s" "%s"' % (src, dst))
def _isdir(dirname):
r"""os.path.isdir() doesn't work for UNC mount points. Fake it."""
if sys.platform[:3] == 'win' and dirname[:2] == r'\\':
if os.path.exists(dirname):
return os.path.isdir(dirname)
try:
os.listdir(dirname)
except WindowsError:
return 0
else:
return os.path.ismount(dirname)
else:
return os.path.isdir(dirname)
def _rmtreeOnError(rmFunction, filePath, excInfo):
if excInfo[0] == OSError:
# presuming because file is read-only
os.chmod(filePath, 0777)
rmFunction(filePath)
def _rmtree(dirname):
import shutil
shutil.rmtree(dirname, 0, _rmtreeOnError)
def _mkdir(newdir):
"""works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exception
- parent directory(ies) does not exist, make them as well
"""
if _isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
head, tail = os.path.split(newdir)
if head and not _isdir(head):
_mkdir(head)
#print "_mkdir %s" % repr(newdir)
if tail:
os.mkdir(newdir)
def _copy(src, dst):
"""works the way a good copy should :)
- no source, raise an exception
- destination directory, make a file in that dir named after src
- source directory, recursively copy the directory to the destination
- filename wildcarding allowed
NOTE:
- This copy CHANGES THE FILE ATTRIBUTES.
"""
import string, glob, shutil
assert src != dst, "You are try to copy a file to itself. Bad you! "\
"src='%s' dst='%s'" % (src, dst)
# determine if filename wildcarding is being used
# (only raise error if non-wildcarded source file does not exist)
if string.find(src, '*') != -1 or \
string.find(src, '?') != -1 or \
string.find(src, '[') != -1:
usingWildcards = 1
srcFiles = glob.glob(src)
else:
usingWildcards = 0
srcFiles = [src]
for srcFile in srcFiles:
if os.path.isfile(srcFile):
if usingWildcards:
srcFileHead, srcFileTail = os.path.split(srcFile)
srcHead, srcTail = os.path.split(src)
dstHead, dstTail = os.path.split(dst)
if dstTail == srcTail:
dstFile = os.path.join(dstHead, srcFileTail)
else:
dstFile = os.path.join(dst, srcFileTail)
else:
dstFile = dst
dstFileHead, dstFileTail = os.path.split(dstFile)
if dstFileHead and not _isdir(dstFileHead):
_mkdir(dstFileHead)
if _isdir(dstFile):
dstFile = os.path.join(dstFile, os.path.basename(srcFile))
#print "copy %s %s" % (srcFile, dstFile)
if os.path.isfile(dstFile):
# make sure 'dstFile' is writeable
os.chmod(dstFile, 0755)
shutil.copy(srcFile, dstFile)
# make the new 'dstFile' writeable
os.chmod(dstFile, 0755)
elif _isdir(srcFile):
srcFiles = os.listdir(srcFile)
if not os.path.exists(dst):
_mkdir(dst)
for f in srcFiles:
s = os.path.join(srcFile, f)
d = os.path.join(dst, f)
try:
_copy(s, d)
except (IOError, os.error), why:
raise OSError("Can't copy %s to %s: %s"\
% (repr(s), repr(d), str(why)))
elif not usingWildcards:
raise OSError("Source file %s does not exist" % repr(srcFile))
def _escapeArg(arg):
"""Escape the given command line argument for the shell."""
#XXX There is a probably more that we should escape here.
return arg.replace('"', r'\"')
def _joinArgv(argv):
r"""Join an arglist to a string appropriate for running.
>>> import os
>>> _joinArgv(['foo', 'bar "baz'])
'foo "bar \\"baz"'
"""
cmdstr = ""
for arg in argv:
if ' ' in arg or ';' in arg:
cmdstr += '"%s"' % _escapeArg(arg)
else:
cmdstr += _escapeArg(arg)
cmdstr += ' '
if cmdstr.endswith(' '): cmdstr = cmdstr[:-1] # strip trailing space
return cmdstr
# Recipe: run (0.5.3) in C:\trentm\tm\recipes\cookbook
_RUN_DEFAULT_LOGSTREAM = ("RUN", "DEFAULT", "LOGSTREAM")
def __run_log(logstream, msg, *args, **kwargs):
if not logstream:
pass
elif logstream is _RUN_DEFAULT_LOGSTREAM:
try:
log
except NameError:
pass
else:
if hasattr(log, "debug"):
log.debug(msg, *args, **kwargs)
else:
logstream(msg, *args, **kwargs)
def _run(cmd, logstream=_RUN_DEFAULT_LOGSTREAM, cwd=None, env=None):
"""Run the given command.
"cmd" is the command to run
"cwd" is the directory in which the commmand is run.
"env" is the optional environment dict to use
"logstream" is an optional logging stream on which to log the
command. If None, no logging is done. If unspecifed, this
looks for a Logger instance named 'log' and logs the command
on log.debug().
Raises OSError if the command returns a non-zero exit status.
"""
if isinstance(cmd, (list, tuple)):
cmd = list(cmd)
cmdline = " ".join(cmd)
shell = False
else:
cmdline = str(cmd)
shell = True
if cwd is not None:
__run_log(logstream, "running '%s' in '%s'", cmdline, cwd)
else:
__run_log(logstream, "running '%s'", cmdline)
p = subprocess.Popen(cmd, cwd=cwd, shell=shell, env=env)
status = p.wait()
if status:
#TODO: add std OSError attributes or pick more approp. exception
raise OSError("error running '%s': %r" % (cmdline, status))
def _run_in_dir(cmd, cwd, logstream=_RUN_DEFAULT_LOGSTREAM):
"""Run the given command in the given working directory.
"cmd" is the command to run
"cwd" is the directory in which the commmand is run.
"logstream" is an optional logging stream on which to log the
command. If None, no logging is done. If unspecifed, this
looks for a Logger instance named 'log' and logs the command
on log.debug().
Raises OSError is the command returns a non-zero exit status.
"""
_run(cmd, logstream=None, cwd=cwd)
#---- define the Komodo configuration items
configuration = {
"PATH": SetPath(),
"systemDirs": black.configure.std.SystemDirs(),
"path": black.configure.std.Path(),
"prebuiltPaths": PrebuiltPaths(),
"siloedPythonExeName": SiloedPythonExeName(), # "python", "python.exe", "python_d.exe"
"siloedPythonInstallDir": SiloedPythonInstallDir(),
"siloedPythonBinDir": SiloedPythonBinDir(),
"siloedPythonVersion": SiloedPythonVersion(), # e.g. "2.4.1"
"siloedPyVer": SiloedPyVer(), # e.g. "2.4"
"siloedPython": SiloedPython(), # e.g. /full/path/to/siloed/bin/python
"havePy2to3": HavePy2to3(), # siloed Python has sufficient lib2to3 support
"siloedDistutilsLibDirName": SiloedDistutilsLibDirName(), # e.g "lib.win32-2.4"
"perlVersion": black.configure.std.PerlVersion(perlBinDirItemName="unsiloedPerlBinDir"),
"activePerlBuild": black.configure.std.ActivePerlBuild(perlBinDirItemName="unsiloedPerlBinDir"),
"unsiloedPerlBinDir": UnsiloedPerlBinDir(),
"unsiloedPerlExe": UnsiloedPerlExe(),
"unsiloedPythonBinDir": UnsiloedPythonBinDir(),
"unsiloedPythonExe": UnsiloedPythonExe(),
"consInstallDir": ConsInstallDir(),
"consVersion": ConsVersion(),
#---- mozilla environment settings
"MOZ_DEBUG": black.configure.mozilla.SetMozDebug(),
"XPCOM_DEBUG_BREAK": black.configure.mozilla.SetXpcomDebugBreakDebug(),
"MOZ_SRC": SetMozSrc(),
"MOZBUILD_STATE_PATH": SetMozStatePath(),
"LD_LIBRARY_PATH": SetLdLibraryPath(),
# TODO: setup mozLdLibraryPath and have a custom LD_LIBRARY_PATH *or*
# setup a generic SetPathEnvVar("LD_LIBRARY_PATH", [list of
# configuration items to add to it]),
# TODO: the same kind of generic this for PATH
#---- Microsoft Visual Studio setup ----
"compiler": SetupCompiler(),
"mozMake": MozMake(),
"mozGcc": MozGcc(),
"mozGxx": MozGxx(),
"mozCFlags": MozCFlags(),
"mozCxxFlags": MozCxxFlags(),
"mozLdFlags": MozLdFlags(),
"mozGreMilestone": MozGreMilestone(),
"setupMozEnv": SetupMozEnv(),
#---- komodo stuff
# TODO: complain if Komodo debug/release conflicts with the debug/release
# state of the MOZ_SRC
"platform": Platform(),
"architecture": Architecture(),
# Komodo build/version configuration vars.
"sourceId": SourceId(), # e.g., 1234M
"sccRepoName": "oksvn", # openkomodo.com SVN repo
"sccType": SCCType(),
"sccBranch": SCCBranch(), # e.g.: "trunk"
"sccRepo": SCCRepo(), # upstream repo location
"normSCCBranch": NormSCCBranch(), # Normalized version.
# - base variables: # Example:
"komodoVersion": KomodoVersion(), # 3.10.0-alpha1
"productType": ProductType(), # ide
"prettyProductType": PrettyProductType(), # IDE
"productTagLine": ProductTagLine(), # The professional IDE for dynamic languages
"buildNum": BuildNum(), # 123456
# - derived from base variables:
"komodoShortVersion": KomodoShortVersion(), # 3.10
"komodoMarketingVersion": KomodoMarketingVersion(), # 3.X-alpha1 (dropping '0' here for effect)
"komodoMarketingShortVersion": KomodoMarketingShortVersion(), # 3.X
"komodoPrettyVersion": KomodoPrettyVersion(), # 3.X Alpha 1
"komodoFullPrettyVersion": KomodoFullPrettyVersion(), # Komodo IDE 3.X Alpha 1 (Build 123456)
"komodoTitleBarName": KomodoTitleBarName(), # ActiveState Komodo IDE 3.X
"komodoAppDataDirName": KomodoAppDataDirName(), # KomodoIDE or komodoide (plat-dep)
"version": Version(), # alias for 'komodoVersion' (kept for compat)
# - MSI variables:
"msiProductName": MSIProductName(), # ActiveState Komodo IDE 3.X Alpha 1
"msiInstallName": MSIInstallName(), # ActiveState Komodo 3.X
"msiKomodoVersion": MSIKomodoVersion(), # 3.10.0 (XXX need to have more differentiation here!)
"msiKomodoId": MSIKomodoId(), # Komod310 (XXX has to be max 8 chars!)
"msiRegistryId": MSIRegistryId(), # 3.10-ide
"macKomodoAppBuildName": MacKomodoAppBuildName(), # e.g. "Komodo.app"
"macKomodoAppInstallName": MacKomodoAppInstallName(), # e.g. "Komodo IDE.app"
"msiKomodoPrettyId": MSIKomodoPrettyId(),
"msiVccrtMsmPath": MSIVccrtMsmPath(),
"msiVccrtRedistPath": MSIVccrtRedistPath(),
"msiVccrtPolicyMsmPath": MSIVccrtPolicyMsmPath(),
# OSX packaging:
"osxCodeSignExecutable": OSXCodeSignExecutable(),
"osxCodeSigningCert": OSXCodeSigningCert(),
# Windows msi signing:
"winCodeSigningCert": WinCodeSigningCert(),
"komodoPackageBase": KomodoPackageBase(),
"komodoUpdateManualURL": KomodoUpdateManualURL(),
"gnomeDesktopName": GnomeDesktopName(),
"gnomeDesktopGenericName": GnomeDesktopGenericName(),
"gnomeDesktopCategories": GnomeDesktopCategories(),
"gnomeDesktopShortcutName": GnomeDesktopShortcutName(),
"buildType": BuildType(), # "release" or "debug"
"buildFlavour": BuildFlavour(), # "dev" or "full"
"updateChannel": UpdateChannel(), # "nightly", "beta" or "release"
"versionInfoFile": VersionInfoFile(),
"KOMODO_HOSTNAME": SetKomodoHostname(),
"withSymbols": WithSymbols(),
"withCrashReportSymbols": WithCrashReportSymbols(),
"PYTHONPATH": SetPythonPath(),
"PYTHONHOME": SetPythonHome(),
"MOZILLA_FIVE_HOME": SetMozillaFiveHome(),
"komodoDevDir": KomodoDevDir(),
"mozillaDevDir": MozillaDevDir(),
"komodoDefaultUserInstallDir": KomodoDefaultUserInstallDir(),
"mozSrc": MozSrc(),
"mozObjDir": MozObjDir(),
"mozDist": MozDist(),
"mozDevelDist": MozDevelDist(),
"mozBin": MozBin(),
"mozDevelBin": MozDevelBin(),
"mozApp": MozApp(),
"mozExe": MozExe(),
"mozVersion": MozVersion(),
"mozVersionNumber": MozVersionNumber(),
"mozResourcesDir": MozResourcesDir(),
"mozComponentsDir": MozComponentsDir(), #XXX necessary?
"mozChromeDir": MozChromeDir(), #XXX necessary?
"mozPluginsDir": MozPluginsDir(), #XXX necessary?
"mozExtensionDir": MozExtensionDir(),
"KOMODO_MOZBINDIR": SetMozBinDir(),
"komodoPythonUtilsDir": KomodoPythonUtilsDir(), #XXX change to LibDir
"installRelDir": InstallRelDir(),
"userDataDir": UserDataDir(),
"supportDir": SupportDir(),
"sdkDir": SDKDir(),
"stubDir": StubDir(), # the build dir for the Komodo starter stub
"readmeDir": ReadmeDir(), # prominent dir for a few standalone doc bits
"sysdllsDir": SysdllsDir(), # dir for system DLLs to install (if necessary)
"installSupportDir": InstallSupportDir(), # dir for installer support files
"buildRelDir": BuildRelDir(),
"buildAbsDir": BuildAbsDir(),
"packagesRelDir": PackagesRelDir(),
"packagesAbsDir": PackagesAbsDir(),
"exportRelDir": ExportRelDir(),
"idlExportRelDir": IdlExportRelDir(),
"installRelDir_ForCons": InstallRelDir_ForCons(),
"buildRelDir_ForCons": BuildRelDir_ForCons(),
"contribBuildRelDir_ForCons": ContribBuildRelDir_ForCons(),
"testBuildRelDir_ForCons": TestBuildRelDir_ForCons(),
"exportRelDir_ForCons": ExportRelDir_ForCons(),
"idlExportRelDir_ForCons": IdlExportRelDir_ForCons(),
"installAbsDir": InstallAbsDir(),
"scintillaBuildDir": ScintillaBuildDir(),
"linuxDistro": LinuxDistro(),
"komodoInstallerPackage": KomodoInstallerPackage(),
"configTokens": ConfigTokens(),
"mozPatchesPackageName": MozPatchesPackageName(),
"withTests": WithTests(),
"withCasper": WithCasper(),
"withJSLib": WithJSLib(),
"withKomodoCix": WithKomodoCix(),
"withWatchdogFSNotifications": WithWatchdogFSNotifications(),
# PGO builds
"withPGOGeneration": WithPGOGeneration(),
"withPGOCollection": WithPGOCollection(),
"universal": UniversalApp(), # ppc+i386 builds
"ludditeVersion": LudditeVersion(),
"isGTK2Siloed": IsGTK2Siloed(),
"buildTime": BuildTime(),
"buildASCTime": BuildASCTime(),
"buildPlatform": BuildPlatform(),
#---- items necessary for building a Komodo installer
# (i.e. not required for plain development builds),
"jarring": Jarring(),
}
if sys.platform == "win32":
configuration["nonMsysPerl"] = NonMsysPerlExe()
#---- command overrides specific to this Komodo branch
def _Tar(argline):
"""just call 'tar' with the given argument line and fail gracefully"""
# XXX replace this or get rid of it
out.write("run: 'tar %s'\n" % argline)
if not tmShUtil.Which("tar"):
raise black.BlackError("no 'tar' on path")
else:
return os.system("tar " + argline)
def _rmemptydirs(dirname):
for subdir in os.listdir(dirname):
subdir = os.path.join(dirname, subdir)
if not os.path.islink(subdir) and os.path.isdir(subdir):
_rmemptydirs(subdir)
if not os.listdir(dirname):
out.write("rmdir %s\n" % dirname)
os.rmdir(dirname)
def _banner(text, ch='=', length=78):
"""Return a banner line centering the given text.
"text" is the text to show in the banner. None can be given to have
no text.
"ch" (optional, default '=') is the banner line character (can
also be a short string to repeat).
"length" (optional, default 78) is the length of banner to make.
Examples:
>>> banner("Peggy Sue")
'================================= Peggy Sue =================================='
>>> banner("Peggy Sue", ch='-', length=50)
'------------------- Peggy Sue --------------------'
>>> banner("Pretty pretty pretty pretty Peggy Sue", length=40)
'Pretty pretty pretty pretty Peggy Sue'
"""
if text is None:
return ch * length
elif len(text) + 2 + len(ch)*2 > length:
# Not enough space for even one line char (plus space) around text.
return text
else:
remain = length - (len(text) + 2)
prefix_len = remain / 2
suffix_len = remain - prefix_len
if len(ch) == 1:
prefix = ch * prefix_len
suffix = ch * suffix_len
else:
prefix = ch * (prefix_len/len(ch)) + ch[:prefix_len%len(ch)]
suffix = ch * (suffix_len/len(ch)) + ch[:suffix_len%len(ch)]
return prefix + ' ' + text + ' ' + suffix
def FetchDependentSources(cfg, argv, update=True):
"""get dependent sources we need (svn externals / git submodules)
bk fetch
This command takes no arguments. It will attempt to download the
required external sources (such as the documentation).
"""
try:
if argv[0] in ("--update", "-u"):
update = True
argv.pop(0)
elif argv[0] in ("--no-update", "-n"):
update = False
argv.pop(0)
except IndexError:
pass # no argv
if not cfg.sccType:
# Not under scc... not sure what we are dealing with then.
# (This might be the case for, e.g., source tarballs)
return
children = []
"""< This is a sequence of dicts; each has a name (for display only),
a dir (where the result will go), and some data about how to get
the result. For git repos, the subkey "git" contains the
mapping from the toplevel git repo to the url for the sub-repo;
both are relative to the root of the server.
"""
for child in children:
if child["sccType"] != cfg.sccType:
continue
if cfg.sccType == "git":
repo_url = child["url"]
if exists(child["dir"]):
if update:
print("Updating git %s in %r" % (child["name"], child["dir"]))
_run(["git", "pull", "--rebase"], cwd=child["dir"])
else:
if not isdir(dirname(child["dir"])):
os.makedirs(dirname(child["dir"]))
print("Cloning git %s into %r" % (child["name"], child["dir"]))
_run(["git", "clone", repo_url, child["dir"]])
else:
# svn doesn't reach here, svn:externals can do the job
raise RuntimeError("Don't know how to get %s via %s"
% (child["name"], cfg.sccType))
def StripBinaries(topdir):
"""Remove any unnecssary information from the Komodo binaries"""
import subprocess
print "Stripping binaries in: %r" % (topdir, )
if sys.platform.startswith("linux"):
# First, ensure the binary files we want to update are write-able.
chmod_cmd = ["find", '"%s"' % (topdir, ), "|",
"xargs", "file", "|",
"grep", "ELF", "|",
"cut", "-f", "1", "-d", ":", "|",
"xargs", "chmod", "u+w"]
_run(" ".join(chmod_cmd))
# Strip the binaries using the linux strip command.
strip_cmd = ["find", '"%s"' % (topdir, ), "|",
"xargs", "file", "|",
"grep", "ELF", "|",
"cut", "-f", "1", "-d", ":", "|",
"xargs", "strip"]
try:
_run(" ".join(strip_cmd))
except OSError:
pass # Ignore errors from trying to strip binaries.
def GenerateCaches(cfg):
"""Generate various cache files for faster loading"""
# Generate a pickled version of the prefs file - bug 96273.
import tmShUtil
oldDir = os.getcwdu()
cmd = '"%s/mozpython" src/prefs/pref_pickler.py' % (cfg.mozBin,)
print("running '%s' in '%s'" % (cmd, cfg.komodoDevDir))
try:
os.chdir(cfg.komodoDevDir)
tmShUtil.RunInContext(cfg.envScriptName,
[cmd])
if not exists(join(cfg.supportDir, "prefs.xmlc")):
raise Error("Failed to generate pickled default prefs")
finally:
os.chdir(oldDir)
def ImageKomodo(cfg, argv):