py_entrypoints.py¶
clew/py_entrypoints.py
Python reachability seeds that no NAME pattern can express.
_nested
dict clew.py_entrypoints._nested(dict doc, tuple[str,...] keys)
Walk a nested TOML table path, returning a mapping.
Source · 14 lines
def _nested(doc: dict, keys: tuple[str, ...]) -> dict:
"""@brief Descend a nested TOML table path.
@return The mapping found, or {}.
@version 1
"""
node: Any = doc
for key in keys:
if not isinstance(node, dict):
return {}
node = node.get(key)
return node if isinstance(node, dict) else {}
Activity · 6 steps
Flows
_read_toml
dict clew.py_entrypoints._read_toml(Path path)
Parse a TOML file into a mapping, tolerating a bad file but not a missing parser.
Source · 28 lines
def _read_toml(path: Path) -> dict:
"""The tolerance here is deliberate and NARROW. A repo with no
`pyproject.toml`, or one with a syntax error in it, must not fail a build —
that is a property of the target, and `{}` is the right answer.
Having no TOML PARSER is not that. This used to catch `ImportError` in the
same clause, so on Python 3.10 — where `tomllib` is not stdlib — the absent
module was swallowed, logged as a warning and turned into `{}`, and the
pipeline built a graph missing every `pyproject.toml` entry point while
reporting success (gh#23). `require_toml_module` raises
`TomlParserUnavailableError`, which is deliberately NOT an `ImportError` so
it cannot be re-caught here by accident.
@brief Read a TOML document; {} on a bad file, raise with no parser.
@return Parsed mapping, or {} when the file is absent or malformed.
@version 2
"""
if not path.is_file():
return {}
toml = require_toml_module()
try:
with path.open("rb") as handle:
return toml.load(handle)
except (OSError, ValueError) as exc:
logger.warning("py entries: %s is unreadable (%s) — ignoring", path, exc)
return {}
Activity · 9 steps
Flows
console_script_targets
list[str] clew.py_entrypoints.console_script_targets(Path|str|None repo_root)
Read pyproject.toml and return its declared console-script targets.
Source · 11 lines
def console_script_targets(repo_root: Path | str | None) -> list[str]:
"""Absent or unparseable `pyproject.toml` yields nothing, which is the norm
for a C repo and must never fail a build.
@brief Read declared console-script entry points.
@return List of `module:function` targets.
@version 1
"""
return list(console_scripts(repo_root).values())
Activity · 1 steps
Requirements
console_scripts
dict[str, str] clew.py_entrypoints.console_scripts(Path|str|None repo_root)
Every declared console script, by name: PEP 621 and Poetry tables.
Source · 18 lines
def console_scripts(repo_root: Path | str | None) -> dict[str, str]:
"""ONE READER for the liveness seeds and the wiki's entry flows (2.0.0, D8): the wiki read
only PEP 621 `[project.scripts]`, missing every Poetry `[tool.poetry.scripts]` this reads.
@brief Read console scripts by name.
@return Mapping.
"""
if repo_root is None:
return {}
doc = _read_toml(Path(repo_root).expanduser() / "pyproject.toml")
found: dict[str, str] = {}
for table in _SCRIPT_TABLES:
for name, target in _nested(doc, table).items():
if isinstance(target, str):
found.setdefault(str(name), target)
return found
Activity · 9 steps
Requirements
Flows
harvest
Any clew.py_entrypoints._MainGuardHarvester.harvest(self, Any tree, bytes src_bytes)
Harvest one file's __main__ -guard callee names.
Source · 6 lines
def harvest(self, tree: Any, src_bytes: bytes) -> Any:
if not is_python_tree(tree):
return []
return harvest_main_guard_calls(tree, src_bytes)
Activity · 3 steps
Requirements
harvest_main_guard_calls
list[str] clew.py_entrypoints.harvest_main_guard_calls(Any tree, bytes src_bytes)
Harvest the function names called inside a file's __main__ guards.
Source · 26 lines
def harvest_main_guard_calls(tree: Any, src_bytes: bytes) -> list[str]:
"""Finds `if` statements whose condition compares `__name__` against the
`"__main__"` literal, then collects every call in the guard's body.
Matching the CONDITION rather than any `if` is what keeps this from seeding
arbitrary conditional calls; matching `__name__` by identifier rather than by
the literal's text alone is what keeps a module that merely mentions the
string `"__main__"` from qualifying.
@brief Collect calls under a module's `__main__` guard.
@return Callee names in the guard body.
@version 1
"""
names: list[str] = []
stack = [tree.root_node]
while stack:
node = stack.pop()
stack.extend(node.children)
if node.type != "if_statement" or not _is_main_guard(node, src_bytes):
continue
body = node.child_by_field_name("consequence")
if body is not None:
names.extend(_called_names(body, src_bytes))
return names
Activity · 11 steps
Requirements
main_guard_harvester
Harvester clew.py_entrypoints.main_guard_harvester()
The __main__ -guard seed stage's harvester.
Source · 10 lines
def main_guard_harvester() -> Harvester:
"""Public factory for gh#358's shared parse pass, which warms this stage with all
the others even though it runs last, inside the reachability seeding.
@brief Build this stage's harvester.
@version 1
"""
return _MainGuardHarvester()
Activity · 1 steps
Requirements
python_entry_seeds
set[int] clew.py_entrypoints.python_entry_seeds(Path db_path, Path repo_root, IndexCache|None cache=None)
Collect the structural Python reachability seeds for a build.
Called by _build_stages
Tested by
Calls _resolve_console_scripts, _resolve_guard_names, console_script_targets, main_guard_harvester, run_harvest
Source · 28 lines
def python_entry_seeds(
db_path: Path,
repo_root: Path,
cache: IndexCache | None = None,
) -> set[int]:
"""Runs before `mark_reachability` and hands it `extra_seeds`. Returns an
empty set — costing one cheap harvest pass — for a repo with no
`pyproject.toml` and no Python files, so a C/C++ build's seed set is
bit-identical to before.
@brief Compute Python entry-point seed rowids.
@return Seed rowids (empty for a non-Python codebase).
@version 4
"""
conn = sqlite3.connect(str(db_path))
scripts = _resolve_console_scripts(conn, console_script_targets(repo_root))
harvested = run_harvest(conn, repo_root, main_guard_harvester(), cache)
guards = _resolve_guard_names(conn, harvested)
conn.close()
seeds = scripts | guards
if seeds:
logger.info(
"py entries: %d reachability seeds (%d console_scripts, %d __main__ guards)",
len(seeds),
len(scripts),
len(guards),
)
return seeds1 more lines, not shown