diff --git a/scripts/create_baseline_stubs.py b/scripts/create_baseline_stubs.py index 8a3e6689b..b861f98c0 100755 --- a/scripts/create_baseline_stubs.py +++ b/scripts/create_baseline_stubs.py @@ -16,6 +16,9 @@ import subprocess import sys from typing import Optional, Tuple +if sys.version_info >= (3, 8): + from importlib.metadata import distribution + PYRIGHT_CONFIG = "pyrightconfig.stricter.json" @@ -116,11 +119,11 @@ def main() -> None: parser = argparse.ArgumentParser( description="""Generate baseline stubs automatically for an installed pip package using stubgen. Also run black and isort. If the name of - the project is different from the runtime Python package name, you must - also use --package (example: --package yaml PyYAML).""" + the project is different from the runtime Python package name, you may + need to use --package (example: --package yaml PyYAML).""" ) parser.add_argument("project", help="name of PyPI project for which to generate stubs under stubs/") - parser.add_argument("--package", help="generate stubs for this Python package (defaults to project)") + parser.add_argument("--package", help="generate stubs for this Python package (default is autodetected)") args = parser.parse_args() project = args.project package = args.package @@ -129,7 +132,18 @@ def main() -> None: sys.exit(f"Invalid character in project name: {project!r}") if not package: - package = project # TODO: infer from installed files + package = project # default + # Try to find which packages are provided by the project + # Use default if that fails or if several packages are found + # + # The importlib.metadata module is used for projects whose name is different + # from the runtime Python package name (example: PyYAML/yaml) + if sys.version_info >= (3, 8): + packages = [name for name in distribution(project).read_text("top_level.txt").split() if not name.startswith("_")] + if len(packages) == 1: + package = packages[0] + print(f'Using detected package "{package}" for project "{project}"', file=sys.stderr) + print("Suggestion: Try again with --package argument if that's not what you wanted", file=sys.stderr) if not os.path.isdir("stubs") or not os.path.isdir("stdlib"): sys.exit("Error: Current working directory must be the root of typeshed repository")