Files
capnpc-py/src/capnp_stubgen/utils.py
T

42 lines
1.2 KiB
Python
Raw Normal View History

2026-07-09 15:06:39 +08:00
"""Utility functions for capnp-stubgen."""
import os
def filename_to_module_name(filename: str) -> str:
"""Convert a .capnp filename to the corresponding Python module name.
Example: ``path/to/my_file.capnp`` → ``my_file_capnp``
"""
base = os.path.basename(filename)
if base.endswith(".capnp"):
base = base[:-6]
return base + "_capnp"
def get_display_name(node: dict) -> str:
"""Extract the short display name from a node dict.
The node's ``displayName`` field contains a path like
``path/to/file.capnp:TypeName``. This removes the file prefix.
"""
name: str = node["displayName"]
prefix_len: int = node["displayNamePrefixLength"]
return name[prefix_len:]
def get_node_kind(node: dict) -> str:
"""Determine the kind of a node from its dict representation.
Returns one of: "file", "struct", "enum", "interface", "const", "annotation".
"""
for kind in ("file", "struct", "enum", "interface", "const", "annotation"):
if kind in node:
return kind
return "unknown"
def type_id_to_int(type_id: str) -> int:
"""Convert a type ID string (from dict) to an integer."""
return int(type_id)