|
| 1 | +"""Logic for adding static typing related stubs of vendored dependencies. |
| 2 | +
|
| 3 | +We autogenerate `.pyi` stub files for the vendored modules, when vendoring. |
| 4 | +These .pyi files are not distributed (thanks to MANIFEST.in). The stub files |
| 5 | +are merely `from ... import *` but they do what they're supposed to and mypy |
| 6 | +is able to find the correct declarations using these files. |
| 7 | +""" |
| 8 | + |
| 9 | +import os |
| 10 | +from pathlib import Path |
| 11 | +from typing import Dict, Iterable, List, Tuple |
| 12 | + |
| 13 | +EXTRA_STUBS_NEEDED = { |
| 14 | + # Some projects need stubs other than a simple <name>.pyi |
| 15 | + "six": [ |
| 16 | + "six.__init__", |
| 17 | + "six.moves.__init__", |
| 18 | + "six.moves.configparser", |
| 19 | + ], |
| 20 | + # Some projects should not have stubs because they're a single module |
| 21 | + "appdirs": [], |
| 22 | + "contextlib2": [], |
| 23 | +} # type: Dict[str, List[str]] |
| 24 | + |
| 25 | + |
| 26 | +def determine_stub_files(lib): |
| 27 | + # type: (str) -> Iterable[Tuple[str, str]] |
| 28 | + # There's no special handling needed -- a <libname>.pyi file is good enough |
| 29 | + if lib not in EXTRA_STUBS_NEEDED: |
| 30 | + yield lib + ".pyi", lib |
| 31 | + return |
| 32 | + |
| 33 | + # Need to generate the given stubs, with the correct import names |
| 34 | + for import_name in EXTRA_STUBS_NEEDED[lib]: |
| 35 | + rel_location = import_name.replace(".", os.sep) + ".pyi" |
| 36 | + |
| 37 | + # Writing an __init__.pyi file -> don't import from `pkg.__init__` |
| 38 | + if import_name.endswith(".__init__"): |
| 39 | + import_name = import_name[:-9] |
| 40 | + |
| 41 | + yield rel_location, import_name |
| 42 | + |
| 43 | + |
| 44 | +def write_stub(destination, import_name): |
| 45 | + # type: (Path, str) -> None |
| 46 | + # Create the parent directories if needed. |
| 47 | + if not destination.parent.exists(): |
| 48 | + destination.parent.mkdir() |
| 49 | + |
| 50 | + # Write `from ... import *` in the stub file. |
| 51 | + destination.write_text("from %s import *" % import_name) |
| 52 | + |
| 53 | + |
| 54 | +def generate_stubs(vendor_dir, libraries): |
| 55 | + # type: (Path, List[str]) -> None |
| 56 | + for lib in libraries: |
| 57 | + for rel_location, import_name in determine_stub_files(lib): |
| 58 | + destination = vendor_dir / rel_location |
| 59 | + write_stub(destination, import_name) |
0 commit comments