Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

3.2 KB
Raw Blame
# ruff: noqa: T201 allow print statements in this build script
"""Move enum classes from the generated posthog/schema.py into posthog/schema_enums.py.

Enums are leaf nodes in the schema graph (models reference enums, never the reverse),
so they can live in a module with zero pydantic import cost. schema.py re-imports them,
keeping `from posthog.schema import SomeEnum` working everywhere, while modules that
only need enums can import posthog.schema_enums without paying for ~900 pydantic model
builds. Runs as a post-generation step in bin/build-schema-python.sh; output must stay
byte-deterministic because CI regenerates and diffs.
"""

import ast
import pathlib

SCHEMA_PATH = pathlib.Path("posthog/schema.py")
ENUMS_PATH = pathlib.Path("posthog/schema_enums.py")

ENUM_BASES = {"Enum", "StrEnum", "IntEnum"}

HEADER = """# DO NOT EDIT THIS FILE DIRECTLY.
# This file is generated by bin/split-schema-enums.py from the enum classes
# in posthog/schema.py (itself generated from frontend/src/queries/schema/*.ts).
# RUN hogli build:schema TO REBUILD

from enum import Enum, IntEnum, StrEnum  # noqa: F401
"""


def base_name(node: ast.expr) -> str:
    if isinstance(node, ast.Name):
        return node.id
    if isinstance(node, ast.Attribute):
        return node.attr
    return ""


def main() -> None:
    src = SCHEMA_PATH.read_text()
    lines = src.splitlines(keepends=True)
    tree = ast.parse(src)

    enum_names: set[str] = set()
    enum_blocks: list[tuple[int, int, str]] = []  # (start_line, end_line, name) 1-based inclusive
    last_import_end = 0

    for node in tree.body:
        if isinstance(node, (ast.Import, ast.ImportFrom)):
            last_import_end = max(last_import_end, node.end_lineno or node.lineno)
            continue
        if not isinstance(node, ast.ClassDef):
            continue
        bases = {base_name(b) for b in node.bases}
        if bases & ENUM_BASES or bases & enum_names:
            enum_names.add(node.name)
            start = min([node.lineno] + [d.lineno for d in node.decorator_list])
            assert node.end_lineno is not None
            enum_blocks.append((start, node.end_lineno, node.name))

    if not enum_blocks:
        raise SystemExit("no enum classes found in posthog/schema.py — generator output changed?")

    enum_source = "\n\n".join("".join(lines[s - 1 : e]).strip("\n") for s, e, _ in enum_blocks)
    ENUMS_PATH.write_text(f"{HEADER}\n\n{enum_source}\n")

    # `X as X` marks an intentional re-export, so the `ruff check --fix` step that
    # follows in build-schema-python.sh does not strip names schema.py itself no
    # longer references.
    reexport = "from posthog.schema_enums import (\n"
    reexport += "".join(f"    {n} as {n},\n" for n in sorted(enum_names))
    reexport += ")\n"

    removed = {ln for s, e, _ in enum_blocks for ln in range(s, e + 1)}
    out: list[str] = []
    for i, line in enumerate(lines, start=1):
        if i in removed:
            continue
        out.append(line)
        if i == last_import_end:
            out.append("\n" + reexport)
    SCHEMA_PATH.write_text("".join(out))

    print(f"moved {len(enum_blocks)} enum classes to {ENUMS_PATH}")


if __name__ == "__main__":
    main()