aboutsummaryrefslogtreecommitdiffstats
path: root/build/scripts/jni_swig.py
blob: 71a5174da53a92cb2f97d9bd0b7cf2319b867a14 (plain) (blame)
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
import argparse
import subprocess
import re
import os
import tarfile


def parse_args():
    parser = argparse.ArgumentParser(description='Wrapper script to invoke swig.')
    parser.add_argument('--swig', help='path to the swig executable')
    parser.add_argument(
        '--default-module', type=str, help='swig -module argument value for inputs without %module statement'
    )
    parser.add_argument('--package-by-file', help='path to file which dir must be converted to swig -package argument')
    parser.add_argument('--jsrc', help='jsrc output archive filename')
    parser.add_argument('--src', help='input .swg file path')
    parser.add_argument('--out-header', help='header file which must exist even if it was not generated by swig')
    parser.add_argument('args', nargs="*", help='regular swig arguments')

    return parser.parse_args()


def path2pkg(path):
    return path.replace('/', '.').replace('-', '_')


def main(args):
    package = path2pkg(os.path.dirname(args.package_by_file))
    outdir = None
    if args.jsrc:
        outdir = package.replace('.', '/')
        outdir_abs = os.path.join(os.path.dirname(args.jsrc), outdir)
        if not os.path.exists(outdir_abs):
            os.makedirs(outdir_abs)
    cmd = (
        [args.swig, '-c++', '-java', '-package', package]
        + (['-outdir', outdir_abs] if outdir is not None else [])
        + args.args
    )
    if '-module' not in args.args and args.default_module:
        with open(args.src, 'r') as f:
            if not re.search(r'(?m)^%module\b', f.read()):
                cmd += ['-module', args.default_module]
    subprocess.check_call(cmd + [args.src])
    if args.out_header and not os.path.exists(args.out_header):
        open(args.out_header, 'w').close()
    if args.jsrc:
        with tarfile.open(args.jsrc, 'a') as tf:
            tf.add(outdir_abs, arcname=outdir)


if __name__ == '__main__':
    main(parse_args())