-
Notifications
You must be signed in to change notification settings - Fork 282
/
wscript
406 lines (336 loc) · 10.7 KB
/
wscript
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
#! /usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2015
"""
to make a custom waf file use the option --tools
To add a tool that does not exist in the folder compat15, pass an absolute path:
./waf-light --tools=compat15,/comp/waf/aba.py --prelude=$'\tfrom waflib.extras import aba\n\taba.foo()'
"""
VERSION="1.8.8"
APPNAME='waf'
REVISION=''
top = '.'
out = 'build'
zip_types = ['bz2', 'gz', 'xz']
PRELUDE = ''
#from tokenize import *
import tokenize
import os, sys, re, io, optparse
from waflib import Utils, Options, Logs
from hashlib import md5
from waflib import Configure
Configure.autoconfig = 1
def sub_file(fname, lst):
f = open(fname, 'rU')
try:
txt = f.read()
finally:
f.close()
for (key, val) in lst:
re_pat = re.compile(key, re.M)
txt = re_pat.sub(val, txt)
f = open(fname, 'w')
try:
f.write(txt)
finally:
f.close()
def to_bytes(x):
if sys.hexversion>0x300000f:
return x.encode()
return x
print("------> Executing code from the top-level wscript <-----")
def init(ctx):
if Options.options.setver: # maintainer only (ita)
ver = Options.options.setver
hexver = Utils.num2ver(ver)
hexver = '0x%x'%hexver
sub_file('wscript', (('^VERSION=(.*)', 'VERSION="%s"' % ver), ))
sub_file('waf-light', (('^VERSION=(.*)', 'VERSION="%s"' % ver), ))
pats = []
pats.append(('^WAFVERSION=(.*)', 'WAFVERSION="%s"' % ver))
pats.append(('^HEXVERSION(.*)', 'HEXVERSION=%s' % hexver))
try:
rev = ctx.cmd_and_log("git rev-parse HEAD").strip()
pats.append(('^WAFREVISION(.*)', 'WAFREVISION="%s"' % rev))
except Exception:
rev = ''
sub_file('waflib/Context.py', pats)
sys.exit(0)
def check(ctx):
Logs.warn('Nothing to do')
# this function is called before any other for parsing the command-line
def options(opt):
# generate waf
opt.add_option('--make-waf', action='store_true', default=True,
help='creates the waf script', dest='waf')
opt.add_option('--sign', action='store_true', default=False, help='make a signed file', dest='signed')
opt.add_option('--zip-type', action='store', default='bz2',
help='specify the zip type [Allowed values: %s]' % ' '.join(zip_types), dest='zip')
opt.add_option('--make-batch', action='store_true', default=False,
help='creates a convenience waf.bat file (done automatically on win32 systems)',
dest='make_batch')
opt.add_option('--yes', action='store_true', default=False,
help=optparse.SUPPRESS_HELP,
dest='yes')
# those ones are not too interesting
opt.add_option('--set-version', default='',
help='sets the version number for waf releases (for the maintainer)', dest='setver')
opt.add_option('--strip', action='store_true', default=True,
help='shrinks waf (strip docstrings, saves 33kb)',
dest='strip_comments')
opt.add_option('--nostrip', action='store_false', help='no shrinking',
dest='strip_comments')
opt.add_option('--tools', action='store', help='Comma-separated 3rd party tools to add, eg: "compat,ocaml" [Default: "compat15"]',
dest='add3rdparty', default='compat15')
opt.add_option('--coretools', action='store', help='Comma-separated core tools to add, eg: "vala,tex" [Default: all of them]',
dest='coretools', default='default')
opt.add_option('--prelude', action='store', help='Code to execute before calling waf', dest='prelude', default=PRELUDE)
opt.load('python')
def process_tokens(tokens):
accu = []
prev = tokenize.NEWLINE
indent = 0
line_buf = []
for (type, token, start, end, line) in tokens:
token = token.replace('\r\n', '\n')
if type == tokenize.NEWLINE:
if line_buf:
accu.append(indent * '\t')
ln = "".join(line_buf)
if ln == 'if __name__=="__main__":': break
#ln = ln.replace('\n', '')
accu.append(ln)
accu.append('\n')
line_buf = []
prev = tokenize.NEWLINE
elif type == tokenize.INDENT:
indent += 1
elif type == tokenize.DEDENT:
indent -= 1
elif type == tokenize.NAME:
if prev == tokenize.NAME or prev == tokenize.NUMBER: line_buf.append(' ')
line_buf.append(token)
elif type == tokenize.NUMBER:
if prev == tokenize.NAME or prev == tokenize.NUMBER: line_buf.append(' ')
line_buf.append(token)
elif type == tokenize.STRING:
if not line_buf and token.startswith('"'): pass
else: line_buf.append(token)
elif type == tokenize.COMMENT:
pass
elif type == tokenize.OP:
line_buf.append(token)
else:
if token != "\n": line_buf.append(token)
if token != '\n':
prev = type
body = "".join(accu)
return body
deco_re = re.compile('(def|class)\\s+(\w+)\\(.*')
def process_decorators(body):
lst = body.splitlines()
accu = []
all_deco = []
buf = [] # put the decorator lines
for line in lst:
if line.startswith('@'):
buf.append(line[1:])
elif buf:
name = deco_re.sub('\\2', line)
if not name:
raise IOError("decorator not followed by a function!" + line)
for x in buf:
all_deco.append("%s(%s)" % (x, name))
accu.append(line)
buf = []
else:
accu.append(line)
return "\n".join(accu+all_deco)
def sfilter(path):
if path.endswith('.py') :
if Options.options.strip_comments:
if sys.version_info[0] >= 3:
f = open(path, "rb")
try:
tk = tokenize.tokenize(f.readline)
next(tk) # the first one is always tokenize.ENCODING for Python 3, ignore it
cnt = process_tokens(tk)
finally:
f.close()
else:
f = open(path, "r")
try:
cnt = process_tokens(tokenize.generate_tokens(f.readline))
finally:
f.close()
else:
f = open(path, "r")
try:
cnt = f.read()
finally:
f.close()
# WARNING: since we now require python 2.4, we do not process the decorators anymore
# if you need such a thing, uncomment the code below:
#cnt = process_decorators(cnt)
#if cnt.find('set(') > -1:
# cnt = 'import sys\nif sys.hexversion < 0x020400f0: from sets import Set as set\n' + cnt
cnt = '#! /usr/bin/env python\n# encoding: utf-8\n# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file\n\n' + cnt
else:
f = open(path, "r")
try:
cnt = f.read()
finally:
f.close()
if sys.hexversion > 0x030000f0:
return (io.BytesIO(cnt.encode('utf-8')), len(cnt.encode('utf-8')), cnt)
return (io.BytesIO(cnt), len(cnt), cnt)
def create_waf(self, *k, **kw):
mw = 'tmp-waf-'+VERSION
print("-> preparing %r" % mw)
import tarfile, re, zipfile
zipType = Options.options.zip.strip().lower()
if zipType not in zip_types:
zipType = zip_types[0]
files = []
add3rdparty = []
for x in Options.options.add3rdparty.split(','):
if os.path.isabs(x):
files.append(x)
else:
add3rdparty.append(x + '.py')
coretools = []
for x in Options.options.coretools.split(','):
coretools.append(x + '.py')
for d in '. Tools extras'.split():
dd = os.path.join('waflib', d)
for k in os.listdir(dd):
if k == '__init__.py':
files.append(os.path.join(dd, k))
continue
if d == 'Tools' and Options.options.coretools != 'default':
if not k in coretools:
continue
if d == 'extras':
if not k in add3rdparty:
continue
if k.endswith('.py'):
files.append(os.path.join(dd, k))
#open a file as tar.[extension] for writing
tar = tarfile.open('%s.tar.%s' % (mw, zipType), "w:%s" % zipType)
z = zipfile.ZipFile("zip/waflib.zip", "w", compression=zipfile.ZIP_DEFLATED)
for x in files:
tarinfo = tar.gettarinfo(x, x)
tarinfo.uid = tarinfo.gid = 0
tarinfo.uname = tarinfo.gname = 'root'
(code, size, cnt) = sfilter(x)
tarinfo.size = size
if os.path.isabs(x):
tarinfo.name = 'waflib/extras/' + os.path.split(x)[1]
print(" adding %s as %s" % (x, tarinfo.name))
def dest(x):
if os.path.isabs(x):
return os.path.join("extras", os.path.basename(x))
else:
return os.path.normpath(os.path.relpath(x, "."))
z.write(x, dest(x))
tar.addfile(tarinfo, code)
tar.close()
z.close()
f = open('waf-light', 'rU')
try:
code1 = f.read()
finally:
f.close()
# now store the revision unique number in waf
code1 = code1.replace("if sys.hexversion<0x206000f:\n\traise ImportError('Python >= 2.6 is required to create the waf file')\n", '')
code1 = code1.replace('\t#import waflib.extras.compat15#PRELUDE', Options.options.prelude)
# when possible, set the git revision in the waf file
bld = self.generator.bld
try:
rev = bld.cmd_and_log("git rev-parse HEAD", quiet=0).strip()
except Exception:
rev = ''
else:
reg = re.compile('^GIT(.*)', re.M)
code1 = reg.sub('GIT="%s"' % rev, code1)
# if the waf file is installed somewhere... but do not do that
prefix = ''
reg = re.compile('^INSTALL=(.*)', re.M)
code1 = reg.sub(r'INSTALL=%r' % prefix, code1)
#change the tarfile extension in the waf script
reg = re.compile('bz2', re.M)
code1 = reg.sub(zipType, code1)
if zipType == 'gz':
code1 = code1.replace('bunzip2', 'gzip -d')
elif zipType == 'xz':
code1 = code1.replace('bunzip2', 'xz -d')
f = open('%s.tar.%s' % (mw, zipType), 'rb')
try:
cnt = f.read()
finally:
f.close()
# the REVISION value is the md5 sum of the binary blob (facilitate audits)
m = md5()
m.update(cnt)
REVISION = m.hexdigest()
reg = re.compile('^REVISION=(.*)', re.M)
code1 = reg.sub(r'REVISION="%s"' % REVISION, code1)
def find_unused(kd, ch):
for i in range(35, 125):
for j in range(35, 125):
if i==j: continue
if i == 39 or j == 39: continue
if i == 92 or j == 92: continue
s = chr(i) + chr(j)
if -1 == kd.find(s.encode()):
return (kd.replace(ch.encode(), s.encode()), s)
raise
# The reverse order prevents collisions
(cnt, C3) = find_unused(cnt, '\x00')
(cnt, C2) = find_unused(cnt, '\r')
(cnt, C1) = find_unused(cnt, '\n')
ccc = code1.replace("C1='x'", "C1='%s'" % C1).replace("C2='x'", "C2='%s'" % C2).replace("C3='x'", "C3='%s'" % C3)
f = open('waf', 'wb')
try:
f.write(ccc.encode())
f.write(to_bytes('#==>\n#'))
f.write(cnt)
f.write(to_bytes('\n#<==\n'))
if Options.options.signed:
f.flush()
try:
os.remove('waf.asc')
except OSError:
pass
ret = Utils.subprocess.Popen('gpg -bass waf', shell=True).wait()
if ret:
raise ValueError('Could not sign the waf file!')
sig = Utils.readf('waf.asc')
sig = sig.replace('\r', '').replace('\n', '\\n')
f.write('#')
f.write(sig)
f.write('\n')
finally:
f.close()
if sys.platform == 'win32' or Options.options.make_batch:
f = open('waf.bat', 'w')
try:
f.write('@python -x "%~dp0waf" %*\n@exit /b %ERRORLEVEL%\n')
finally:
f.close()
if sys.platform != 'win32':
os.chmod('waf', Utils.O755)
os.remove('%s.tar.%s' % (mw, zipType))
def make_copy(inf, outf):
(a, b, cnt) = sfilter(inf)
f = open(outf, "wb")
try:
f.write(cnt)
finally:
f.close()
def configure(conf):
conf.load('python')
conf.check_python_version((2,4))
def build(bld):
waf = bld.path.make_node('waf') # create the node right here
bld(name='create_waf', rule=create_waf, target=waf, always=True, color='PINK', update_outputs=True)