|
| 1 | +"""Utilities for extracting module names from file paths.""" |
| 2 | + |
| 3 | +import site |
| 4 | +import sys |
| 5 | +import sysconfig |
| 6 | +from pathlib import Path |
| 7 | +from typing import Iterable |
| 8 | +from typing import List |
| 9 | +from typing import Optional |
| 10 | +from typing import Tuple |
| 11 | + |
| 12 | +from typing_extensions import TypedDict |
| 13 | + |
| 14 | + |
| 15 | +class PathInfo(TypedDict): |
| 16 | + stdlib: Optional[Path] |
| 17 | + site_packages: List[Path] |
| 18 | + sys_path: List[Path] |
| 19 | + |
| 20 | + |
| 21 | +def get_python_path_info() -> PathInfo: |
| 22 | + """Get information about Python's search paths. |
| 23 | +
|
| 24 | + Returns: |
| 25 | + dict: Dictionary containing stdlib path, site-packages paths, and sys.path entries. |
| 26 | + """ |
| 27 | + libdest = sysconfig.get_config_var("LIBDEST") |
| 28 | + stdlib: Optional[Path] = Path(libdest) if libdest else None |
| 29 | + |
| 30 | + # Get site-packages directories |
| 31 | + site_packages: List[Path] = [Path(p) for p in site.getsitepackages()] |
| 32 | + |
| 33 | + # Get user site-packages |
| 34 | + user_site = site.getusersitepackages() |
| 35 | + if Path(user_site).exists(): |
| 36 | + site_packages.append(Path(user_site)) |
| 37 | + |
| 38 | + return { |
| 39 | + "stdlib": stdlib, |
| 40 | + "site_packages": site_packages, |
| 41 | + "sys_path": [Path(p) for p in sys.path if p], |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | +def _is_relative_to(path: Path, base: Path) -> bool: |
| 46 | + try: |
| 47 | + path.relative_to(base) |
| 48 | + return True |
| 49 | + except ValueError: |
| 50 | + return False |
| 51 | + |
| 52 | + |
| 53 | +def extract_module_name_and_type(filename: str, path_info: PathInfo) -> Tuple[str, str]: |
| 54 | + """Extract Python module name and type from file path. |
| 55 | +
|
| 56 | + Returns: |
| 57 | + tuple: (module_name, module_type) where module_type is one of: |
| 58 | + 'stdlib', 'site-packages', 'project', or 'unknown' |
| 59 | + """ |
| 60 | + if not filename: |
| 61 | + return ("unknown", "unknown") |
| 62 | + |
| 63 | + if filename.startswith("<frozen "): |
| 64 | + return (filename[len("<frozen ") : -1], "stdlib") |
| 65 | + |
| 66 | + file_path = Path(filename) |
| 67 | + |
| 68 | + for site_pkg in path_info["site_packages"]: |
| 69 | + if _is_relative_to(file_path, site_pkg): |
| 70 | + return (_path_to_module(file_path.relative_to(site_pkg)), "site-packages") |
| 71 | + |
| 72 | + if path_info["stdlib"] and _is_relative_to(file_path, path_info["stdlib"]): |
| 73 | + return (_path_to_module(file_path.relative_to(path_info["stdlib"])), "stdlib") |
| 74 | + |
| 75 | + for path_entry in path_info["sys_path"]: |
| 76 | + if _is_relative_to(file_path, path_entry): |
| 77 | + return (_path_to_module(file_path.relative_to(path_entry)), "project") |
| 78 | + |
| 79 | + # Fallback: use just the filename, not the full absolute path |
| 80 | + return (_path_to_module(Path(file_path.name)), "unknown") |
| 81 | + |
| 82 | + |
| 83 | +def _path_to_module(path: Path) -> str: |
| 84 | + if path.is_absolute(): |
| 85 | + raise ValueError(f"Expected a relative path, got: {path}") |
| 86 | + |
| 87 | + if path.name == "__init__.py": |
| 88 | + path = path.parent |
| 89 | + elif path.suffix == ".py": |
| 90 | + path = path.with_suffix("") |
| 91 | + |
| 92 | + return ".".join(path.parts) |
| 93 | + |
| 94 | + |
| 95 | +def get_module_for_stack( |
| 96 | + stack: Iterable[Tuple[str, str, int]], |
| 97 | + path_info: PathInfo, |
| 98 | +) -> str: |
| 99 | + """Find the top-level module of the closest non-stdlib frame in a stack. |
| 100 | +
|
| 101 | + Walks frames from leaf to root, returning the first non-stdlib module's |
| 102 | + top-level package name. Returns "__main__" if every frame is stdlib |
| 103 | + or the stack is empty. |
| 104 | + """ |
| 105 | + for frame in stack: |
| 106 | + module_name, module_type = extract_module_name_and_type(frame[1], path_info) |
| 107 | + if module_type != "stdlib": |
| 108 | + return module_name.split(".")[0] |
| 109 | + return "__main__" |
0 commit comments