jni_swig.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import argparse
  2. import subprocess
  3. import re
  4. import os
  5. import tarfile
  6. def parse_args():
  7. parser = argparse.ArgumentParser(description='Wrapper script to invoke swig.')
  8. parser.add_argument('--swig', help='path to the swig executable')
  9. parser.add_argument(
  10. '--default-module', type=str, help='swig -module argument value for inputs without %module statement'
  11. )
  12. parser.add_argument('--package-by-file', help='path to file which dir must be converted to swig -package argument')
  13. parser.add_argument('--jsrc', help='jsrc output archive filename')
  14. parser.add_argument('--src', help='input .swg file path')
  15. parser.add_argument('--out-header', help='header file which must exist even if it was not generated by swig')
  16. parser.add_argument('args', nargs="*", help='regular swig arguments')
  17. return parser.parse_args()
  18. def path2pkg(path):
  19. return path.replace('/', '.').replace('-', '_')
  20. def main(args):
  21. package = path2pkg(os.path.dirname(args.package_by_file))
  22. outdir = None
  23. if args.jsrc:
  24. outdir = package.replace('.', '/')
  25. outdir_abs = os.path.join(os.path.dirname(args.jsrc), outdir)
  26. if not os.path.exists(outdir_abs):
  27. os.makedirs(outdir_abs)
  28. cmd = (
  29. [args.swig, '-c++', '-java', '-package', package]
  30. + (['-outdir', outdir_abs] if outdir is not None else [])
  31. + args.args
  32. )
  33. if '-module' not in args.args and args.default_module:
  34. with open(args.src, 'r') as f:
  35. if not re.search(r'(?m)^%module\b', f.read()):
  36. cmd += ['-module', args.default_module]
  37. subprocess.check_call(cmd + [args.src])
  38. if args.out_header and not os.path.exists(args.out_header):
  39. open(args.out_header, 'w').close()
  40. if args.jsrc:
  41. with tarfile.open(args.jsrc, 'a') as tf:
  42. tf.add(outdir_abs, arcname=outdir)
  43. if __name__ == '__main__':
  44. main(parse_args())