#!/usr/bin/env python
""" A simple tool for importing the cffi version into pypy, should sync
whatever version you provide. Usage:

python3.9 pypy/tool/import_cffi.py <path-to-cffi>
"""
from __future__ import print_function

import sys, pathlib

def mangle(lines, ext):
    if ext == '.py':
        yield "# Generated by pypy/tool/import_cffi.py\n"
        for line in lines:
            line = line.replace('from testing', 'from extra_tests.cffi_tests')
            yield line
    elif ext in ('.c', '.h'):
        yield "/* Generated by pypy/tool/import_cffi.py */\n"
        for line in lines:
            yield line
    else:
        raise AssertionError(ext)

def fixeol(s):
    s = s.replace('\r\n', '\n')
    return s

def main(cffi_dir):
    cffi_dir = pathlib.Path(cffi_dir)
    rootdir = pathlib.Path(__file__).parent.parent.parent
    cffi_dest = rootdir / 'lib_pypy' / 'cffi'
    cffi_dest.mkdir(exist_ok=True)
    test_dest = rootdir / 'extra_tests' / 'cffi_tests'
    test_dest.ensure(dir=1)
    for p in (list(cffi_dir.join('src', 'cffi').visit(fil='*.py')) +
              list(cffi_dir.join('src', 'cffi').visit(fil='*.h'))):
        cffi_dest.join(p.relto(cffi_dir.join('src', 'cffi'))).write_binary(fixeol(p.read()))
    for p in (list(cffi_dir.join('testing').visit(fil='*.py')) +
              list(cffi_dir.join('testing').visit(fil='*.h')) +
              list(cffi_dir.join('testing').visit(fil='*.c'))):
        path = test_dest.join(p.relto(cffi_dir.join('testing')))
        path.join('..').ensure(dir=1)
        path.write_binary(fixeol(''.join(mangle(p.readlines(), p.ext))))
    path = test_dest.join('test_c.py')
    path.write_binary(fixeol(cffi_dir.join('src', 'c', 'test_c.py').read()))
    #
    # hack around a little bit...
    os.system("cd '%s' && patch -p0 < pypy/tool/import_cffi.patch" % str(rootdir))

if __name__ == '__main__':
    if sys.version_info < (3, 0):
        print(__doc__)
        print("must not use python2") 
        sys.exit(2)
    if len(sys.argv) != 2:
        print(__doc__)
        sys.exit(2)
    if not os.path.exists(sys.argv[1]):
        print(__doc__)
        print("'%s' is not a valid path" % sys.argv[1])
        sys.exit(2)
    main(sys.argv[1])
