1"""Shared utility for scanning Python source files for imported package names (ENH-2214, ENH-2216)."""

2

3 from __future__ import annotations

4

5 import re

6 from pathlib import Path

7

8_PY_IMPORT_RE = re.compile(r"^(?:import|from)\s+([A-Za-z_][A-Za-z0-9_]*)", re.MULTILINE)

9

10

11 def get_imported_packages(source_dirs: list[Path]) -> set[str]:

12 """Return unique top-level package names imported across all .py files in source_dirs.

13

14 Args:

15 source_dirs: Directories to scan recursively for .py files.

16

17 Returns:

18 Set of unique top-level package names (e.g., ``"requests"``, ``"anthropic"``).

19 """

20 packages: set[str] = set()

21 for source_dir in source_dirs:

22 if not source_dir.is_dir():

23 continue

24 for py_file in source_dir.rglob("*.py"):

25 try:

26 content = py_file.read_text(encoding="utf-8", errors="ignore")

27 except OSError:

28 continue

29 for m in _PY_IMPORT_RE.finditer(content):

30 packages.add(m.group(1))

31 return packages