forked from adtools/amigaos-cross-toolchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
542 lines (431 loc) · 13.2 KB
/
common.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
#!/usr/bin/env python2.7 -B
from __future__ import print_function
from fnmatch import fnmatch
from glob import glob
from logging import debug, info, error
from os import path
import contextlib
from distutils import spawn, sysconfig
import fileinput
import os
from multiprocessing import cpu_count
import shutil
import site
import subprocess
import sys
import tarfile
import tempfile
import urllib2
import zipfile
VARS = {}
def setvar(**kwargs):
for key, item in kwargs.items():
VARS[key] = item.format(**VARS)
def fill_in(value):
if type(value) == str:
return value.format(**VARS)
return value
def fill_in_args(fn):
def wrapper(*args, **kwargs):
args = list(fill_in(arg) for arg in args)
kwargs = dict((key, fill_in(value)) for key, value in kwargs.items())
return fn(*args, **kwargs)
return wrapper
def flatten(*args):
queue = list(args)
while queue:
item = queue.pop(0)
if type(item) == list:
queue = item + queue
elif type(item) == tuple:
queue = list(item) + queue
else:
yield item
chdir = fill_in_args(os.chdir)
path.exists = fill_in_args(path.exists)
path.join = fill_in_args(path.join)
path.relpath = fill_in_args(path.relpath)
@fill_in_args
def panic(*args):
error(*args)
sys.exit(1)
@fill_in_args
def cmpver(op, v1, v2):
assert op in ['eq', 'lt', 'gt']
v1 = [int(x) for x in v1.split('.')]
v2 = [int(x) for x in v2.split('.')]
def _cmp(l1, l2):
if not len(l1) and not len(l2):
return 0
if not len(l1):
return -1
if not len(l2):
return 1
if l1[0] < l2[0]:
return -1
if l1[0] > l2[0]:
return 1
if l1[0] == l2[0]:
return _cmp(l1[1:], l2[1:])
res = _cmp(v1, v2)
return ((op == 'eq' and res == 0) or
(op == 'lt' and res < 0) or
(op == 'gt' and res > 0))
@fill_in_args
def topdir(name):
if not path.isabs(name):
name = path.abspath(name)
return path.relpath(name, '{top}')
@fill_in_args
def find_executable(name):
return (spawn.find_executable(name) or
panic('Executable "%s" not found!', name))
@fill_in_args
def find(root, **kwargs):
only_files = kwargs.get('only_files', False)
include = kwargs.get('include', ['*'])
exclude = kwargs.get('exclude', [''])
lst = []
for name in sorted(os.listdir(root)):
fullname = path.join(root, name)
is_dir = path.isdir(fullname)
excluded = any(fnmatch(name, pat) for pat in exclude)
included = any(fnmatch(name, pat) for pat in include)
if included and not excluded:
if not (is_dir and only_files):
lst.append(fullname)
if is_dir and not excluded:
lst.extend(find(fullname, **kwargs))
return lst
@fill_in_args
def touch(name):
try:
os.utime(name, None)
except:
open(name, 'a').close()
@fill_in_args
def mkdtemp(**kwargs):
if 'dir' in kwargs and not path.isdir(kwargs['dir']):
mkdir(kwargs['dir'])
return tempfile.mkdtemp(**kwargs)
@fill_in_args
def mkstemp(**kwargs):
if 'dir' in kwargs and not path.isdir(kwargs['dir']):
mkdir(kwargs['dir'])
return tempfile.mkstemp(**kwargs)
@fill_in_args
def rmtree(*names):
for name in flatten(names):
if path.isdir(name):
debug('rmtree "%s"', topdir(name))
shutil.rmtree(name)
@fill_in_args
def remove(*names):
for name in flatten(names):
if path.isfile(name):
debug('remove "%s"', topdir(name))
os.remove(name)
@fill_in_args
def mkdir(*names):
for name in flatten(names):
if name and not path.isdir(name):
debug('makedir "%s"', topdir(name))
os.makedirs(name)
@fill_in_args
def copy(src, dst):
debug('copy "%s" to "%s"', topdir(src), topdir(dst))
shutil.copy2(src, dst)
@fill_in_args
def copytree(src, dst, **kwargs):
debug('copytree "%s" to "%s"', topdir(src), topdir(dst))
mkdir(dst)
for name in find(src, **kwargs):
target = path.join(dst, path.relpath(name, src))
if path.isdir(name):
mkdir(target)
else:
copy(name, target)
@fill_in_args
def move(src, dst):
debug('move "%s" to "%s"', topdir(src), topdir(dst))
shutil.move(src, dst)
@fill_in_args
def symlink(src, name):
if not path.islink(name):
debug('symlink "%s" points at "%s"', topdir(name), src)
os.symlink(src, name)
@fill_in_args
def chmod(name, mode):
debug('change permissions on "%s" to "%o"', topdir(name), mode)
os.chmod(name, mode)
@fill_in_args
def execute(*cmd):
debug('execute "%s"', " ".join(cmd))
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError as ex:
panic('command "%s" failed with %d', " ".join(list(ex.cmd)), ex.returncode)
@fill_in_args
def textfile(*lines):
f, name = mkstemp(dir='{tmpdir}')
debug('creating text file script "%s"', topdir(name))
os.write(f, '\n'.join(lines) + '\n')
os.close(f)
return name
@fill_in_args
def download(url, name):
info('download "%s" to "%s"', url, topdir(name))
u = urllib2.urlopen(url)
meta = u.info()
try:
size = int(meta.getheaders('Content-Length')[0])
except IndexError:
size = None
if size:
info('download: %s (size: %d)', name, size)
else:
info('download: %s', name)
with open(name, 'wb') as f:
done = 0
block = 8192
while True:
buf = u.read(block)
if not buf:
break
done += len(buf)
f.write(buf)
if size:
status = r"%d [%3.2f%%]" % (done, done * 100. / size)
else:
status = r"%d" % done
status = status + chr(8) * (len(status) + 1)
sys.stdout.write(status)
sys.stdout.flush()
print("")
@fill_in_args
def unarc(name):
info('extract files from "%s"', topdir(name))
if name.endswith('.lha'):
import lhafile
arc = lhafile.LhaFile(name)
for item in arc.infolist():
filename = os.sep.join(item.filename.split('\\'))
mkdir(path.dirname(filename))
debug('extract "%s"', filename)
if path.isdir(filename):
continue
with open(filename, 'w') as f:
f.write(arc.read(item.filename))
elif name.endswith('.tar.gz') or name.endswith('.tar.bz2'):
with tarfile.open(name) as arc:
for item in arc.getmembers():
debug('extract "%s"' % item.name)
arc.extract(item)
elif name.endswith('.zip'):
with zipfile.ZipFile(name) as arc:
for item in arc.infolist():
debug('extract "%s"' % item.filename)
arc.extract(item)
else:
raise RuntimeError('Unrecognized archive: "%s"', name)
@fill_in_args
def fix_python_shebang(filename, prefix):
PYTHON = fill_in('{python}')
SITEDIR = path.join(prefix, '{sitedir}')
for line in fileinput.input(files=[filename], inplace=True):
line = line.rstrip()
if line.startswith('#!'):
print('#!/usr/bin/env PYTHONPATH=%s %s' % (SITEDIR, PYTHON))
else:
print(line.rstrip())
@fill_in_args
def find_site_dir(dirname):
prefix = sysconfig.EXEC_PREFIX
destlib = sysconfig.get_config_var('DESTLIB')
return path.join(dirname, destlib[len(prefix) + 1:], 'site-packages')
@fill_in_args
def add_site_dir(dirname):
dirname = find_site_dir(dirname)
info('adding "%s" to python site dirs', topdir(dirname))
site.addsitedir(dirname)
@contextlib.contextmanager
def cwd(name):
old = os.getcwd()
if not path.exists(name):
mkdir(name)
try:
debug('enter directory "%s"', topdir(name))
chdir(name)
yield
finally:
chdir(old)
@contextlib.contextmanager
def env(**kwargs):
backup = {}
try:
for key, value in kwargs.items():
debug('changing environment variable "%s" to "%s"', key, value)
old = os.environ.get(key, None)
os.environ[key] = fill_in(value)
backup[key] = old
yield
finally:
for key, value in backup.items():
debug('restoring old value of environment variable "%s"', key)
if value is None:
del os.environ[key]
else:
os.environ[key] = value
def recipe(name, nargs=0):
def real_decorator(fn):
@fill_in_args
def wrapper(*args, **kwargs):
target = [str(arg) for arg in args[:min(nargs, len(args))]]
if len(target) > 0:
target = [target[0], fill_in(name)] + target[1:]
target = '-'.join(target)
else:
target = fill_in(name)
target = target.replace('_', '-')
target = target.replace('/', '-')
stamp = path.join('{stamps}', target)
if not path.exists('{stamps}'):
mkdir('{stamps}')
if not path.exists(stamp):
fn(*args, **kwargs)
touch(stamp)
else:
info('already done "%s"', target)
return wrapper
return real_decorator
def extend_pythonpath(prefix):
SITEDIR = path.join(prefix, '{sitedir}')
try:
return ':'.join([os.environ['PYTHONPATH'], SITEDIR])
except KeyError:
return SITEDIR
@recipe('pyinstall', 1)
def pyinstall(name, **kwargs):
prefix = kwargs.get('prefix', '{prefix}')
mkdir(path.join(prefix, '{sitedir}'))
with env(PYTHONPATH=extend_pythonpath(prefix)):
execute('{python}', '-m', 'easy_install', '--prefix=' + prefix, name)
@recipe('pyfixbin', 1)
def pyfixbin(name, names, **kwargs):
prefix = kwargs.get('prefix', '{prefix}')
for name in names:
fix_python_shebang(path.join(prefix, 'bin', name), prefix)
@recipe('pysetup', 1)
def pysetup(name, **kwargs):
prefix = kwargs.get('prefix', '{prefix}')
mkdir(path.join(prefix, '{sitedir}'))
with env(PYTHONPATH=extend_pythonpath(prefix)):
with cwd(path.join('{build}', name)):
execute('{python}', 'setup.py', 'build')
execute('{python}', 'setup.py', 'install', '--prefix=' + prefix)
@recipe('fetch', 1)
def fetch(name, url):
if url.startswith('http') or url.startswith('ftp'):
if not path.exists(name):
download(url, name)
else:
info('File "%s" already downloaded.', name)
elif url.startswith('svn'):
execute('svn', 'export', url, name)
elif url.startswith('git'):
if not path.exists(name):
execute('git', 'clone', url, name)
else:
with cwd(name):
execute('git', 'pull')
elif url.startswith('file'):
if not path.exists(name):
_, src = url.split('://')
copy(src, name)
else:
panic('URL "%s" not recognized!', url)
@recipe('unpack', 1)
def unpack(name, work_dir='{sources}', top_dir=None, dst_dir=None):
try:
src = (glob(path.join('{archives}', name) + '*') +
glob(path.join('{submodules}', name) + '*'))[0]
except IndexError:
panic('Missing files for "%s".', name)
dst = path.join(work_dir, dst_dir or name)
info('preparing files for "%s"', name)
if path.isdir(src):
if top_dir is not None:
src = path.join(src, top_dir)
copytree(src, dst, exclude=['.svn', '.git'])
else:
tmpdir = mkdtemp(dir='{tmpdir}')
with cwd(tmpdir):
unarc(src)
copytree(path.join(tmpdir, top_dir or name), dst)
rmtree(tmpdir)
@recipe('patch', 1)
def patch(name, work_dir='{sources}'):
with cwd(work_dir):
for name in find(path.join('{patches}', name),
only_files=True, exclude=['*~']):
if fnmatch(name, '*.diff'):
execute('patch', '-t', '-p0', '-i', name)
else:
dst = path.relpath(name, '{patches}')
mkdir(path.dirname(dst))
copy(name, dst)
@recipe('configure', 1)
def configure(name, *confopts, **kwargs):
info('configuring "%s"', name)
if 'from_dir' in kwargs:
from_dir = kwargs['from_dir']
else:
from_dir = path.join('{sources}', name)
if kwargs.get('copy_source', False):
rmtree(path.join('{build}', name))
copytree(path.join('{sources}', name), path.join('{build}', name))
from_dir = '.'
with cwd(path.join('{build}', name)):
remove(find('.', include=['config.cache']))
execute(path.join(from_dir, 'configure'), *confopts)
@recipe('make', 2)
def make(name, target=None, makefile=None, parallel=False, **makevars):
info('running make "%s"', target)
with cwd(path.join('{build}', name)):
args = ['%s=%s' % item for item in makevars.items()]
if target is not None:
args = [target] + args
if makefile is not None:
args = ['-f', makefile] + args
if parallel:
args = ['-j%d' % cpu_count()] + args
execute('make', *args)
def require_header(headers, lang='c', errmsg='', symbol=None, value=None):
debug('require_header "%s"', headers[0])
for header in headers:
cmd = {'c': os.environ['CC'], 'c++': os.environ['CXX']}[lang]
cmd = fill_in(cmd).split()
opts = ['-fsyntax-only', '-x', lang, '-']
proc = subprocess.Popen(cmd + opts,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
proc_stdin = ['#include <%s>' % header]
if symbol:
if value:
proc_stdin.append("#if %s != %s" % (symbol, value))
else:
proc_stdin.append("#ifndef %s" % symbol)
proc_stdin.append("#error")
proc_stdin.append("#endif")
proc_stdout, proc_stderr = proc.communicate('\n'.join(proc_stdin))
proc.wait()
if proc.returncode == 0:
return
panic(errmsg)
__all__ = ['setvar', 'panic', 'cmpver', 'find_executable', 'chmod', 'execute',
'rmtree', 'mkdir', 'copy', 'copytree', 'unarc', 'fetch', 'cwd',
'symlink', 'remove', 'move', 'find', 'textfile', 'env', 'path',
'add_site_dir', 'find_site_dir', 'pysetup', 'pyinstall', 'recipe',
'unpack', 'patch', 'configure', 'make', 'require_header', 'touch',
'pyfixbin']