quicktex/tools/stubgen.py

59 lines
1.8 KiB
Python
Raw Normal View History

2021-04-04 04:03:24 +00:00
import inspect
import os.path
import tempfile
2021-04-04 06:52:42 +00:00
import pybind11_stubgen as sg
2021-04-04 04:03:24 +00:00
package = 'quicktex'
prefix = '_'
modules = set()
2021-04-04 04:17:06 +00:00
def find_submodules(pkg):
modules.add(pkg.__name__.split('.')[-1])
2021-04-04 04:03:24 +00:00
2021-04-04 04:17:06 +00:00
for element_name in dir(pkg):
element = getattr(pkg, element_name)
2021-04-04 04:03:24 +00:00
if inspect.ismodule(element):
find_submodules(element)
if __name__ == "__main__":
find_submodules(__import__(prefix + package))
2021-04-04 06:52:42 +00:00
pkgdir = os.path.abspath(os.curdir)
2021-04-04 04:03:24 +00:00
with tempfile.TemporaryDirectory() as out:
2021-04-04 04:17:06 +00:00
# generate stubs using mypy Stubgen
2021-04-04 06:52:42 +00:00
sg.main(['-o', out, '--root-module-suffix', "", prefix + package])
os.curdir = pkgdir
2021-04-04 04:17:06 +00:00
# walk resulting stubs and move them to their new location
2021-04-04 04:03:24 +00:00
for root, dirs, files in os.walk(out):
for stub_name in files:
2021-04-04 04:17:06 +00:00
# location of the extension module's stub file
ext_module = os.path.relpath(root, out)
2021-04-04 04:03:24 +00:00
2021-04-04 06:52:42 +00:00
if stub_name.split('.')[-1] != 'pyi':
continue
2021-04-04 04:03:24 +00:00
if stub_name != '__init__.pyi':
2021-04-04 04:17:06 +00:00
ext_module = os.path.join(ext_module, os.path.splitext(stub_name)[0])
2021-04-04 04:03:24 +00:00
2021-04-04 04:17:06 +00:00
# open and read the stub file and replace all extension module names with their python counterparts
2021-04-04 04:03:24 +00:00
with open(os.path.join(root, stub_name), 'r') as fp:
contents = fp.read()
for mod in modules:
new_mod = mod.replace(prefix, '')
contents = contents.replace(mod, new_mod)
2021-04-04 04:03:24 +00:00
2021-04-04 04:17:06 +00:00
# write out to the new location
py_module = ext_module.replace(prefix, '')
with open(os.path.join(os.curdir, *py_module.split('.'), '__init__.pyi'), 'w') as fp:
2021-04-04 04:03:24 +00:00
fp.write(contents)
2021-04-04 04:17:06 +00:00
print(ext_module + ' -> ' + fp.name)