rev: 5af3ab66d60a5c98a08b91a43a5bf3f60c771dbf tukan/externals/build_common.py -rw-r--r-- 21.9 KiB View raw Log this file
5af3ab66d60a — Leonard Ritter merge a month ago
                                                                                
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
from __future__ import (print_function, division, absolute_import)

import re
import argparse
import tempfile
import fnmatch
import os
import sys
import urllib
import shutil
import tarfile
import math
import zipfile
import traceback
import time

from subprocess import Popen, PIPE

################################################################################

THISDIR = os.path.abspath(os.path.dirname(__file__))
ROOTDIR = os.path.abspath(os.path.join(THISDIR, '..'))
BUILDDIR = os.path.abspath(os.path.join(ROOTDIR, 'build'))
TMPDIR = os.path.abspath(os.path.join(BUILDDIR, 'tmp'))
BINDIR = os.path.abspath(os.path.join(ROOTDIR, 'bin'))
LUADIR = os.path.abspath(os.path.join(ROOTDIR, 'modules'))
LIBDIR = os.path.abspath(os.path.join(BUILDDIR, 'lib'))
INCLUDEDIR = os.path.abspath(os.path.join(BUILDDIR, 'include'))
CDEFDIR = os.path.abspath(os.path.join(ROOTDIR, 'cdefs'))
COREDIR = os.path.abspath(os.path.join(ROOTDIR, 'core'))
SRCDIR = os.path.abspath(os.path.join(BUILDDIR, 'src'))
ASSETDIR = os.path.abspath(os.path.join(ROOTDIR, 'assets'))
ARCHIVEDIR = os.path.join(THISDIR, 'archives')
DOWNLOADDIR = os.path.join(THISDIR, 'downloads')

IS_X64 = sys.maxsize > 2**32

def ensure_build_folders():
    for path in [
        INCLUDEDIR,
        BINDIR,
        LIBDIR,
        CDEFDIR,
        LUADIR,
        ARCHIVEDIR,
        DOWNLOADDIR
    ]:
        if not os.path.isdir(path):
                os.makedirs(path)

################################################################################

def preprocess_c_header(text, cpp_options=[], cpp_path='mcpp'):
    cmdline = ' '.join([
        cpp_path,
    ] + cpp_options + [
        '-P',
    ])
    pipe = Popen(cmdline, shell=True,
            stdin=PIPE, stdout=PIPE, universal_newlines=True)
    result = pipe.communicate(input=text)[0]
    assert pipe.returncode == 0
    return result

def shell(cmd, retry=1):
    for i in range(retry):
        print('#{}: {}'.format(i+1,cmd))
        result = os.system(cmd)
        if result == 0:
            return True
        if retry > 1:
            print("Failed, retrying...")
            time.sleep(1)
    raise OSError("command failed. :(")
    return False

def gen_rotator():
    import time
    T = time.time()
    while True:
        t = time.time() - T
        n = ''
        for c in range(30):
            p = c / 30.0
            phase2 = math.sin(p * 2.0 * math.pi)
            phase = p * phase2 * 2.0 * math.pi
            f = math.sin(phase + t*10.0)
            n += ' .oO'[int((f+1.0)*0.5*3+0.5)]
        yield n

################################################################################

def download_tempfile(url, filename, remove_stale = True, filepath = None):
    if filepath:
        tempfilepath = filepath
    else:
        tempdir = tempfile.gettempdir()
        tempfilepath = os.path.join(tempdir, filename)
    print("Downloading {0} to {1}...".format(url,tempfilepath))
    if os.path.isfile(tempfilepath):
        if remove_stale:
            print("Removing stale {0}".format(tempfilepath))
            os.remove(tempfilepath)
        else:
            return tempfilepath
    rotator = gen_rotator()
    def reporthook(count,blocksize,totalsize):
        perc = min(count * blocksize, totalsize) * 100.0 / totalsize
        print_r("%5.1f%% downloaded... %s" % (perc,rotator.next()))
        sys.stdout.flush()
    import ssl
    # lifehack
    if hasattr(ssl, '_create_unverified_context'):
        ssl._create_default_https_context = ssl._create_unverified_context
    urllib.urlretrieve(url, tempfilepath, reporthook)
    print_r("Done.")
    return tempfilepath

def print_r(text):
    text = text.rstrip('\n \t')
    spaces = 80 - len(text)
    sys.stdout.write('\r' + text + ' '*spaces)
    sys.stdout.flush()

def copyovertree(src, dst, symlinks=False, ignore=None):
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    if not os.path.isdir(dst):
        os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                if os.path.isfile(dstname):
                    os.remove(dstname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copyovertree(srcname, dstname, symlinks, ignore)
            else:
                # Will raise a SpecialFileError for unsupported file types
                shutil.copy2(srcname, dstname)
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except shutil.Error, err:
            errors.extend(err.args[0])
        except EnvironmentError, why:
            errors.append((srcname, dstname, str(why)))
    try:
        shutil.copystat(src, dst)
    except OSError, why:
        if shutil.WindowsError is not None and isinstance(why,
            shutil.WindowsError):
            # Copying file access times may fail on Windows
            pass
        else:
            errors.extend((src, dst, str(why)))
    if errors:
        raise shutil.Error, errors

def copytree(srcpath, dstpath, ignore_files=[], ignore_func=None):
    if ignore_func is None:
        ignore_func = shutil.ignore_patterns(*ignore_files)

    def ignore_func_ex(dirpath, fnames):
        print(dirpath)
        return ignore_func(dirpath, fnames)

    print("Copying",srcpath,"=>",dstpath)
    copyovertree(srcpath, dstpath, symlinks=True, ignore=ignore_func_ex)

def unpack_contents(arcfilepath, targetdir, printfunc = None):
    base = None
    if printfunc is None:
        printfunc = print
    if (arcfilepath.endswith('.deb')):
        tempdir = tempfile.gettempdir()
        os.chdir(tempdir)
        dataarc = os.path.join(tempdir, 'data.tar.gz')
        if os.path.isfile(dataarc):
            os.remove(dataarc)
        if os.system("ar vx {}".format(arcfilepath)): return base
        arcfilepath = dataarc
    if arcfilepath.endswith('.xz'):
        newfile = os.path.splitext(arcfilepath)[0]
        if os.path.isfile(newfile):
            os.remove(newfile)
        shell('xz -d -k {}'.format(arcfilepath))
        arcfilepath = newfile

    if (arcfilepath.endswith('.tar.bz2') or arcfilepath.endswith('.tar.gz')
        or arcfilepath.endswith('.tgz') or arcfilepath.endswith('.tar')):
        tf = tarfile.open(arcfilepath,'r')
        folders = []
        files = []
        symlinks = []
        for member in tf.getmembers():
            assert not ('..' in member.name)
            if not ('/' in member.name):
                continue
            if not base:
                base = member.name[:member.name.index('/')]
            name = member.name[member.name.index('/')+1:]
            fullpath = os.path.join(targetdir, name)
            if member.type == tarfile.DIRTYPE:
                folders.append((fullpath, member))
            elif member.type in (tarfile.REGTYPE, tarfile.AREGTYPE):
                files.append((fullpath, member))
            elif member.type == tarfile.SYMTYPE:
                symlinks.append((fullpath, member))
            else:
                #raise ValueError, "unrecognized member type: {}".format(member.type)
                pass

        for fullpath,member in folders:
            if os.path.isdir(fullpath):
                printfunc("skipping {0}...".format(fullpath))
            else:
                printfunc("creating {0}...".format(fullpath))
                os.makedirs(fullpath)

        for fullpath,member in files:
                printfunc("extracting {0}...".format(fullpath))
                ifile = tf.extractfile(member)
                basedir = os.path.dirname(fullpath)
                if not os.path.isdir(basedir):
                    os.makedirs(basedir)
                with file(fullpath, 'wb') as ofile:
                    ofile.write(ifile.read())
                ifile.close()
                # apply access flags but make sure files are always overwritable
                os.chmod(fullpath, member.mode | 0222)

        if (sys.platform == 'win32'):
            for fullpath,member in symlinks:
                    printfunc("unable to symlink {} -> {}...".format(fullpath, member.linkname))
                    #os.symlink(member.linkname, fullpath)
        else:
            for fullpath,member in symlinks:
                    printfunc("symlinking {} -> {}...".format(fullpath, member.linkname))
                    os.symlink(member.linkname, fullpath)

        tf.close()
    elif arcfilepath.endswith('.zip'):
        with zipfile.ZipFile(arcfilepath,'r') as tf:
            for member in tf.infolist():
                if not ('/' in member.filename):
                    continue
                if member.filename.endswith('/'): # folder path
                    continue
                if not base:
                    base = member.filename[:member.filename.index('/')]
                name = member.filename[member.filename.index('/')+1:]
                fullpath = os.path.join(targetdir, name)
                printfunc("extracting {0}...".format(fullpath))
                basedir = os.path.dirname(fullpath)
                if not os.path.isdir(basedir):
                    os.makedirs(basedir)
                try:
                    data = tf.read(member)
                except IOError:
                    printfunc("Unable to extract {}, skipping".format(fullpath))
                    traceback.print_exc()
                with file(fullpath, 'wb') as ofile:
                    ofile.write(data)
    else:
        printfunc("Don't know how to deal with this archive type. I'm going to cry a bit now.")
        return
    printfunc("Done.")
    return base

def pack_archive(archivepath, base_dir, dirname):
    print("{} <= {}{}{}".format(archivepath, base_dir, os.sep, dirname))
    if archivepath.endswith('.tar.gz'):
        shell('tar -C {} -zcf {} {}'.format(
            base_dir, archivepath,
            dirname))
    elif archivepath.endswith('.zip'):
        cwd = os.getcwd()
        os.chdir(base_dir)
        shell('7z a -ssc -r {} {}'.format(
            archivepath, dirname))
        os.chdir(cwd)
    else:
        raise ValueError, 'unknown file extension'

################################################################################

class BuilderBase(object):
    NAME = ''
    BUILDDIR = BUILDDIR
    ROOTDIR = ROOTDIR
    TMPDIR = TMPDIR
    BINDIR = BINDIR
    LIBDIR = LIBDIR
    INCLUDEDIR = INCLUDEDIR
    SRCDIR = SRCDIR
    LUADIR = LUADIR
    CDEFDIR = CDEFDIR
    COREDIR = COREDIR
    IS_X64 = IS_X64
    ASSETDIR = ASSETDIR
    EXTERNALDIR = THISDIR
    ARCHIVEDIR = ARCHIVEDIR
    DOWNLOADDIR = DOWNLOADDIR
    PLATFORM = sys.platform
    if PLATFORM == 'msys':
        PLATFORM = 'win32'
    IS_LINUX2 = PLATFORM == 'linux2'
    IS_DARWIN = PLATFORM == 'darwin'
    IS_WIN32 = PLATFORM == 'win32'

    HG_URL = None
    HG_REVISION = None
    # 'get' on bitbucket, 'archive' everywhere else, None to disable
    HG_ARCHIVE = 'get'

    GIT_URL = None
    GIT_REVISION = None
    GIT_ARCHIVE = 'archive'

    SVN_URL = None
    SVN_REVISION = None

    URL = None
    ARCHIVE = None

    def __init__(self):
        assert self.NAME, 'NAME missing'
        self.TARGETDIR = os.path.join(self.SRCDIR, self.NAME.lower())
        parser = argparse.ArgumentParser(description='check out and build {}'.format(
            self.NAME))
        parser.add_argument('--nocdef', action='store_true',
            help="skip generating cdef file")
        parser.add_argument('--nobuild', action='store_true',
            help="skip building")
        parser.add_argument('--forcedownload', action='store_true',
            help="re-download archive")
        parser.add_argument('--skip', metavar='module', type=str, nargs='+',
                   help='modules to skip')
        self.parser = parser
        self.skip = False

    def parse_args(self):
        self.args = self.parser.parse_args()
        self.skip = self.NAME.lower() in (self.args.skip or [])

    def download_hg(self, targetdir):
        if not os.path.isdir(targetdir):
            if self.HG_REVISION:
                cmd = 'hg clone -r {0} {1} {2}'.format(
                    self.HG_REVISION, self.HG_URL, targetdir)
            else:
                cmd = 'hg clone {} {}'.format(
                    self.HG_URL, targetdir)
            shell(cmd)
        else:
            os.chdir(targetdir)
            shell('hg pull')
            if self.HG_REVISION:
                cmd = 'hg up -r {}'.format(self.HG_REVISION)
            else:
                cmd = 'hg up'
            shell(cmd)
        return True

    def download_local_hg(self, targetdir):
        self.rmtree(targetdir)
        self.makedirs(targetdir)
        os.chdir(self.HG_DIR)
        if self.HG_REVISION:
            cmd = 'hg archive -r {0} {1}'.format(
                self.HG_REVISION, targetdir)
        else:
            cmd = 'hg archive {}'.format(targetdir)
        shell(cmd)
        return True

    def download_git(self, targetdir):
        if not os.path.isdir(targetdir):
            cmd = 'git clone --recursive {0} {1}'.format(self.GIT_URL, targetdir)
            shell(cmd)
        else:
            os.chdir(targetdir)
            cmd = 'git fetch'
            shell(cmd)
        if self.GIT_REVISION:
            os.chdir(targetdir)
            cmd = 'git checkout -q {}'.format(self.GIT_REVISION)
            shell(cmd)
        return True

    def download_svn(self, targetdir):
        self.rmtree(targetdir)
        cmd = 'svn export -r {0} {1} {2}'.format(
            self.SVN_REVISION, self.SVN_URL, targetdir)
        shell(cmd)
        return True

    def download_archive(self, targetdir):
        url = self.URL
        if not url.endswith('/'):
            url += '/'
        url += self.ARCHIVE
        self.rmtree(targetdir)
        self.makedirs(targetdir)
        tempfilepath = download_tempfile(url, self.ARCHIVE)
        base = unpack_contents(tempfilepath, targetdir)
        if not base:
            return
        return True

    def download_sources(self, targetdir):
        if self.HG_URL:
            return self.download_hg(targetdir)
        elif self.GIT_URL:
            return self.download_git(targetdir)
        elif self.SVN_URL:
            return self.download_svn(targetdir)
        elif self.URL:
            return self.download_archive(targetdir)
        elif self.HG_DIR:
            return self.download_local_hg(targetdir)
        elif self.ARCHIVE:
            base = unpack_contents(
                os.path.join(self.ARCHIVEDIR, self.ARCHIVE), targetdir)
            if not base: return
        else:
            # just create the empty targetdir
            self.makedirs(targetdir)
        return True

    @staticmethod
    def rmtree(path):
        if os.path.isdir(path):
            print("Wiping {}".format(path))
            shutil.rmtree(path)

    @staticmethod
    def makedirs(path):
        if not os.path.exists(path):
            os.makedirs(path)

    def apply_patch(self, filepath):
        cmd = 'patch -d {} -p 1 -i {}'.format(self.TARGETDIR, filepath)
        shell(cmd)

    def run_linux2_build(self):
        raise Exception('todo')

    def run_darwin_build(self):
        raise Exception('todo')

    def run_win32_build(self):
        raise Exception('todo')

    def cpp(self, code, cpp_options=[]):
        cpp_options.extend([
            '-N',
            '-I' + self.INCLUDEDIR,
            '-I' + os.path.join(self.EXTERNALDIR, 'include')
        ])
        if self.IS_WIN32:
            cpp_path = os.path.join(self.BINDIR, 'mcpp.exe')
        else:
            cpp_path = os.path.join(self.BINDIR, 'mcpp')
        assert os.path.isfile(cpp_path), 'mcpp not installed yet.'
        return preprocess_c_header(code, cpp_options=cpp_options,
            cpp_path=cpp_path)

    def write(self, filepath, content):
        with open(filepath, 'w') as f:
            f.write(content)

    def write_cdef(self, text, filepath = None):
        if filepath is None:
            filepath = os.path.join(self.CDEFDIR, self.NAME + '.cdef')
        print("writing '{}'...".format(filepath))
        with open(filepath, 'w') as f:
            f.write(text)

    def parse_cdef_defines(self, source):
        re_define_num = re.compile(r'^\#define\s+(\w+)\s+(\S+)\s+')
        for line in source.splitlines():
            line = line.strip()
            if line.startswith('#define'):
                m = re_define_num.search(line)
                if m:
                    key = m.group(1)
                    value = m.group(2)
                    if value.startswith('/*'):
                        value = None
                    yield key,value

    def filter_cdef_defines(self, source, whitelist=[], blacklist=[]):
        def key_ok(key):
            if blacklist:
                for entry in blacklist:
                    if fnmatch.fnmatchcase(key, entry):
                        return False
            if whitelist:
                for entry in whitelist:
                    if fnmatch.fnmatchcase(key, entry):
                        return True
                return False
            return True

        re_define_num = re.compile(r'^\#define\s+(\w+)\s+(\S+)\s+')
        lines = []
        assigns = []
        for line in source.splitlines():
            line = line.strip()
            if line.startswith('#define'):
                m = re_define_num.search(line)
                if m:
                    key = m.group(1)
                    value = m.group(2)
                    if key.startswith('__'):
                        continue
                    if value.startswith('/*'):
                        continue
                    assigns.append((key,value))
            else:
                lines.append(line)

        # try executing these assignments as long as one
        # assignment goes through, effectively bruteforcing
        # dependencies
        namespace = {}
        while True:
            k = len(assigns)
            for entry in assigns:
                key,value = entry
                try:
                    exec '{} = ({})'.format(key,value) in namespace
                    assigns.remove(entry)
                    continue
                except:
                    pass
                value = value.replace('f','')
                try:
                    exec '{} = ({})'.format(key,value) in namespace
                    assigns.remove(entry)
                    continue
                except:
                    pass
            if len(assigns) == k: break

        for key,value in assigns:
            print("ignoring",key,value)

        enums = []
        for key in sorted(namespace):
            if key.startswith('_'): continue
            if not key_ok(key): continue
            value = namespace[key]
            if isinstance(value, int):
                enums.append('{} = {},'.format(key, hex(value)))
            elif isinstance(value, long):
                print("WARNING: can't include",key,repr(value))
            else:
                print("skipping",key,repr(value))
                continue
        if enums:
            lines.append('enum {')
            lines.extend(enums)
            lines.append('};')

        source = '\n'.join(lines)

        return source

    def gen_cdef(self):
        pass

    def store_dep(self):
        cwd = os.getcwd()
        basepath = self.DOWNLOADDIR
        targetdir = os.path.join(basepath, self.NAME)
        archive = os.path.join(basepath, self.NAME + '.tar.gz')
        self.rmtree(targetdir)
        archive_exists = os.path.isfile(archive)
        if not archive_exists or self.args.forcedownload:
            if archive_exists:
                os.remove(archive)
            if self.HG_URL:
                if self.HG_ARCHIVE is None:
                    self.download_sources(targetdir)
                    os.chdir(targetdir)
                    self.shell('hg archive {}'.format(archive))
                    self.rmtree(targetdir)
                else:
                    rev = self.HG_REVISION or 'tip'
                    url = self.HG_URL + '/' + self.HG_ARCHIVE + '/' + rev + '.tar.gz'
                    download_tempfile(url, archive)
            elif self.GIT_URL:
                rev = self.GIT_REVISION or 'master'
                url = self.GIT_URL + '/' + self.GIT_ARCHIVE + '/' + rev + '.tar.gz'
                download_tempfile(url, archive)
            elif self.SVN_URL or self.URL:
                self.download_sources(targetdir)
                os.chdir(basepath)
                if self.IS_WIN32:
                    self.shell('tar -zcvf {} {}'.format(
                        archive, self.NAME))
                else:
                    self.shell('tar --force-local -zcvf {} {}'.format(
                        archive, self.NAME))
                self.rmtree(targetdir)
        os.chdir(cwd)

    def run_build(self):
        cwd = os.getcwd()
        archivepath = os.path.join(self.DOWNLOADDIR, self.NAME + '.tar.gz')
        if os.path.isfile(archivepath):
            self.rmtree(self.TARGETDIR)
            self.makedirs(self.TARGETDIR)
            unpack_contents(archivepath, self.TARGETDIR)
        else:
            print("archive missing, attempting direct download...")
            assert self.download_sources(self.TARGETDIR)
        os.chdir(self.TARGETDIR)
        getattr(self, 'run_' + self.PLATFORM + '_build')()
        print("{} is ready.".format(self.NAME))
        os.chdir(cwd)

    def run(self):
        self.parse_args()
        if not self.args.nobuild:
            ensure_build_folders()
            self.store_dep()
            self.run_build()
        #if not self.args.nocdef:
        #    self.gen_cdef()

    shell = staticmethod(shell)
    copy2 = staticmethod(shutil.copy2)
    copytree = staticmethod(copytree)
    chdir = staticmethod(os.chdir)
    makedirs = staticmethod(os.makedirs)
    joinpath = staticmethod(os.path.join)
    pathsep = os.pathsep
    sep = os.sep

################################################################################