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.

clew/py_entrypoints.py:269

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
lines 275–275node: Any = doclines 276–276◇ for key in keyslines 277–277◇ if not isinstance(node, dict)lines 278–278return {}lines 279–279node = node.get(key)lines 280–280return node if isinstance(node, dict) else {}

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.

clew/py_entrypoints.py:235

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
lines 252–252◇ if not path.is_file()lines 253–253return {}lines 254–254toml = require_toml_module()lines 255–255trylines 256–256with path.open("rb") as handlelines 257–257return toml.load(handle)lines 258–258except (OSError, ValueError) as exclines 259–259logger.warning("py entries: %s is unreadable (%s) — ignoring", path, exc)lines 260–260return {}

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.

clew/py_entrypoints.py:196

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
lines 204–204return list(console_scripts(repo_root).values())

Requirements

REQ-DDB-PIPE-004

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.

clew/py_entrypoints.py:212

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
lines 219–219◇ if repo_root is Nonelines 220–220return {}lines 221–221doc = _read_toml(Path(repo_root).expanduser() / "pyproject.toml")lines 222–222found: dict[str, str] = {}lines 223–223◇ for table in _SCRIPT_TABLESlines 224–224◇ for name, target in _nested(doc, table).items()lines 225–225◇ if isinstance(target, str)lines 226–226found.setdefault(str(name), target)lines 227–227return found

Requirements

REQ-DDB-PIPE-004

Flows

harvest

Any clew.py_entrypoints._MainGuardHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's __main__ -guard callee names.

clew/py_entrypoints.py:170

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
lines 171–171◇ if not is_python_tree(tree)lines 172–172return []lines 173–173return harvest_main_guard_calls(tree, src_bytes)

Requirements

REQ-DDB-PIPE-004

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.

clew/py_entrypoints.py:75

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
lines 88–88names: list[str] = []lines 89–89stack = [tree.root_node]lines 90–90◇ while stacklines 91–91node = stack.pop()lines 92–92stack.extend(node.children)lines 93–93◇ if node.type != "if_statement" or not _is_main_guard(node, src_bytes)lines 94–94continuelines 95–95body = node.child_by_field_name("consequence")lines 96–96◇ if body is not Nonelines 97–97names.extend(_called_names(body, src_bytes))lines 98–98return names

Requirements

REQ-DDB-PIPE-004

main_guard_harvester

Harvester clew.py_entrypoints.main_guard_harvester()

The __main__ -guard seed stage's harvester.

clew/py_entrypoints.py:180

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
lines 187–187return _MainGuardHarvester()

Requirements

REQ-DDB-PIPE-003

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.

clew/py_entrypoints.py:391

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 seeds

1 more lines, not shown

Activity · 9 steps
lines 405–405conn = sqlite3.connect(str(db_path))lines 406–406scripts = _resolve_console_scripts(conn, console_script_targets(repo_root))lines 407–407harvested = run_harvest(conn, repo_root, main_guard_harvester(), cache)lines 408–408guards = _resolve_guard_names(conn, harvested)lines 409–409conn.close()lines 410–410seeds = scripts | guardslines 411–411◇ if seedslines 412–417logger.info( "py entries: %d reachability seeds (%d console_scripts, %d __main__ guards)", len(seeds), len(scripts), len(guards), )lines 418–418return seeds

Requirements

REQ-DDB-PIPE-004