pyi_generator.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. """The pyi generator module."""
  2. import ast
  3. import contextlib
  4. import importlib
  5. import inspect
  6. import logging
  7. import re
  8. import subprocess
  9. import sys
  10. import textwrap
  11. import typing
  12. from inspect import getfullargspec
  13. from multiprocessing import Pool, cpu_count
  14. from pathlib import Path
  15. from types import ModuleType
  16. from typing import Any, Callable, Iterable, Type, get_args
  17. import black
  18. import black.mode
  19. from reflex.components.component import Component
  20. from reflex.utils import types as rx_types
  21. from reflex.vars import Var
  22. logger = logging.getLogger("pyi_generator")
  23. LAST_RUN_COMMIT_SHA_FILE = Path(".pyi_generator_last_run").resolve()
  24. INIT_FILE = Path("reflex/__init__.pyi").resolve()
  25. PWD = Path(".").resolve()
  26. GENERATOR_FILE = Path(__file__).resolve()
  27. GENERATOR_DIFF_FILE = Path(".pyi_generator_diff").resolve()
  28. EXCLUDED_FILES = [
  29. "__init__.py",
  30. "component.py",
  31. "bare.py",
  32. "foreach.py",
  33. "cond.py",
  34. "match.py",
  35. "multiselect.py",
  36. "literals.py",
  37. ]
  38. # These props exist on the base component, but should not be exposed in create methods.
  39. EXCLUDED_PROPS = [
  40. "alias",
  41. "children",
  42. "event_triggers",
  43. "library",
  44. "lib_dependencies",
  45. "tag",
  46. "is_default",
  47. "special_props",
  48. "_invalid_children",
  49. "_memoization_mode",
  50. "_valid_children",
  51. "_valid_parents",
  52. ]
  53. DEFAULT_TYPING_IMPORTS = {
  54. "overload",
  55. "Any",
  56. "Dict",
  57. # "List",
  58. "Literal",
  59. "Optional",
  60. "Union",
  61. }
  62. def _walk_files(path):
  63. """Walk all files in a path.
  64. This can be replaced with Path.walk() in python3.12.
  65. Args:
  66. path: The path to walk.
  67. Yields:
  68. The next file in the path.
  69. """
  70. for p in Path(path).iterdir():
  71. if p.is_dir():
  72. yield from _walk_files(p)
  73. continue
  74. yield p.resolve()
  75. def _relative_to_pwd(path: Path) -> Path:
  76. """Get the relative path of a path to the current working directory.
  77. Args:
  78. path: The path to get the relative path for.
  79. Returns:
  80. The relative path.
  81. """
  82. return path.relative_to(PWD)
  83. def _git_diff(args: list[str]) -> str:
  84. """Run a git diff command.
  85. Args:
  86. args: The args to pass to git diff.
  87. Returns:
  88. The output of the git diff command.
  89. """
  90. cmd = ["git", "diff", "--no-color", *args]
  91. return subprocess.run(cmd, capture_output=True, encoding="utf-8").stdout
  92. def _git_changed_files(args: list[str] | None = None) -> list[Path]:
  93. """Get the list of changed files for a git diff command.
  94. Args:
  95. args: The args to pass to git diff.
  96. Returns:
  97. The list of changed files.
  98. """
  99. if not args:
  100. args = []
  101. if "--name-only" not in args:
  102. args.insert(0, "--name-only")
  103. diff = _git_diff(args).splitlines()
  104. return [Path(file.strip()) for file in diff]
  105. def _get_changed_files() -> list[Path] | None:
  106. """Get the list of changed files since the last run of the generator.
  107. Returns:
  108. The list of changed files, or None if all files should be regenerated.
  109. """
  110. try:
  111. last_run_commit_sha = LAST_RUN_COMMIT_SHA_FILE.read_text().strip()
  112. except FileNotFoundError:
  113. logger.info(
  114. "pyi_generator.py last run could not be determined, regenerating all .pyi files"
  115. )
  116. return None
  117. changed_files = _git_changed_files([f"{last_run_commit_sha}..HEAD"])
  118. # get all unstaged changes
  119. changed_files.extend(_git_changed_files())
  120. if _relative_to_pwd(GENERATOR_FILE) not in changed_files:
  121. return changed_files
  122. logger.info("pyi_generator.py has changed, checking diff now")
  123. diff = "".join(_git_diff([GENERATOR_FILE.as_posix()]).splitlines()[2:])
  124. try:
  125. last_diff = GENERATOR_DIFF_FILE.read_text()
  126. if diff != last_diff:
  127. logger.info("pyi_generator.py has changed, regenerating all .pyi files")
  128. changed_files = None
  129. else:
  130. logger.info(
  131. "pyi_generator.py has not changed, only regenerating changed files"
  132. )
  133. except FileNotFoundError:
  134. logger.info(
  135. "pyi_generator.py diff could not be determined, regenerating all .pyi files"
  136. )
  137. changed_files = None
  138. GENERATOR_DIFF_FILE.write_text(diff)
  139. return changed_files
  140. def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
  141. """Resolve the type hint for value.
  142. Args:
  143. value: The type annotation as a str or actual types/aliases.
  144. type_hint_globals: The globals to use to resolving a type hint str.
  145. is_optional: Whether the type hint should be wrapped in Optional.
  146. Returns:
  147. The resolved type hint as a str.
  148. """
  149. res = ""
  150. args = get_args(value)
  151. if args:
  152. inner_container_type_args = (
  153. [repr(arg) for arg in args]
  154. if rx_types.is_literal(value)
  155. else [
  156. _get_type_hint(arg, type_hint_globals, is_optional=False)
  157. for arg in args
  158. if arg is not type(None)
  159. ]
  160. )
  161. res = f"{value.__name__}[{', '.join(inner_container_type_args)}]"
  162. if value.__name__ == "Var":
  163. # For Var types, Union with the inner args so they can be passed directly.
  164. types = [res] + [
  165. _get_type_hint(arg, type_hint_globals, is_optional=False)
  166. for arg in args
  167. if arg is not type(None)
  168. ]
  169. if len(types) > 1:
  170. res = ", ".join(types)
  171. res = f"Union[{res}]"
  172. elif isinstance(value, str):
  173. ev = eval(value, type_hint_globals)
  174. res = (
  175. _get_type_hint(ev, type_hint_globals, is_optional=False)
  176. if ev.__name__ == "Var"
  177. else value
  178. )
  179. else:
  180. res = value.__name__
  181. if is_optional and not res.startswith("Optional"):
  182. res = f"Optional[{res}]"
  183. return res
  184. def _generate_imports(typing_imports: Iterable[str]) -> list[ast.ImportFrom]:
  185. """Generate the import statements for the stub file.
  186. Args:
  187. typing_imports: The typing imports to include.
  188. Returns:
  189. The list of import statements.
  190. """
  191. return [
  192. ast.ImportFrom(
  193. module="typing",
  194. names=[ast.alias(name=imp) for imp in sorted(typing_imports)],
  195. ),
  196. *ast.parse( # type: ignore
  197. textwrap.dedent(
  198. """
  199. from reflex.vars import Var, BaseVar, ComputedVar
  200. from reflex.event import EventChain, EventHandler, EventSpec
  201. from reflex.style import Style"""
  202. )
  203. ).body,
  204. # *[
  205. # ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values])
  206. # for name, values in EXTRA_IMPORTS.items()
  207. # ],
  208. ]
  209. def _generate_docstrings(clzs: list[Type[Component]], props: list[str]) -> str:
  210. """Generate the docstrings for the create method.
  211. Args:
  212. clzs: The classes to generate docstrings for.
  213. props: The props to generate docstrings for.
  214. Returns:
  215. The docstring for the create method.
  216. """
  217. props_comments = {}
  218. comments = []
  219. for clz in clzs:
  220. for line in inspect.getsource(clz).splitlines():
  221. reached_functions = re.search("def ", line)
  222. if reached_functions:
  223. # We've reached the functions, so stop.
  224. break
  225. # Get comments for prop
  226. if line.strip().startswith("#"):
  227. comments.append(line)
  228. continue
  229. # Check if this line has a prop.
  230. match = re.search("\\w+:", line)
  231. if match is None:
  232. # This line doesn't have a var, so continue.
  233. continue
  234. # Get the prop.
  235. prop = match.group(0).strip(":")
  236. if prop in props:
  237. if not comments: # do not include undocumented props
  238. continue
  239. props_comments[prop] = [
  240. comment.strip().strip("#") for comment in comments
  241. ]
  242. comments.clear()
  243. clz = clzs[0]
  244. new_docstring = []
  245. for line in (clz.create.__doc__ or "").splitlines():
  246. if "**" in line:
  247. indent = line.split("**")[0]
  248. for nline in [
  249. f"{indent}{n}:{' '.join(c)}" for n, c in props_comments.items()
  250. ]:
  251. new_docstring.append(nline)
  252. new_docstring.append(line)
  253. return "\n".join(new_docstring)
  254. def _extract_func_kwargs_as_ast_nodes(
  255. func: Callable,
  256. type_hint_globals: dict[str, Any],
  257. ) -> list[tuple[ast.arg, ast.Constant | None]]:
  258. """Get the kwargs already defined on the function.
  259. Args:
  260. func: The function to extract kwargs from.
  261. type_hint_globals: The globals to use to resolving a type hint str.
  262. Returns:
  263. The list of kwargs as ast arg nodes.
  264. """
  265. spec = getfullargspec(func)
  266. kwargs = []
  267. for kwarg in spec.kwonlyargs:
  268. arg = ast.arg(arg=kwarg)
  269. if kwarg in spec.annotations:
  270. arg.annotation = ast.Name(
  271. id=_get_type_hint(spec.annotations[kwarg], type_hint_globals)
  272. )
  273. default = None
  274. if spec.kwonlydefaults is not None and kwarg in spec.kwonlydefaults:
  275. default = ast.Constant(value=spec.kwonlydefaults[kwarg])
  276. kwargs.append((arg, default))
  277. return kwargs
  278. def _extract_class_props_as_ast_nodes(
  279. func: Callable,
  280. clzs: list[Type],
  281. type_hint_globals: dict[str, Any],
  282. extract_real_default: bool = False,
  283. ) -> list[tuple[ast.arg, ast.Constant | None]]:
  284. """Get the props defined on the class and all parents.
  285. Args:
  286. func: The function that kwargs will be added to.
  287. clzs: The classes to extract props from.
  288. type_hint_globals: The globals to use to resolving a type hint str.
  289. extract_real_default: Whether to extract the real default value from the
  290. pydantic field definition.
  291. Returns:
  292. The list of props as ast arg nodes
  293. """
  294. spec = getfullargspec(func)
  295. all_props = []
  296. kwargs = []
  297. for target_class in clzs:
  298. # Import from the target class to ensure type hints are resolvable.
  299. exec(f"from {target_class.__module__} import *", type_hint_globals)
  300. for name, value in target_class.__annotations__.items():
  301. if (
  302. name in spec.kwonlyargs
  303. or name in EXCLUDED_PROPS
  304. or name in all_props
  305. or (isinstance(value, str) and "ClassVar" in value)
  306. ):
  307. continue
  308. all_props.append(name)
  309. default = None
  310. if extract_real_default:
  311. # TODO: This is not currently working since the default is not type compatible
  312. # with the annotation in some cases.
  313. with contextlib.suppress(AttributeError, KeyError):
  314. # Try to get default from pydantic field definition.
  315. default = target_class.__fields__[name].default
  316. if isinstance(default, Var):
  317. default = default._decode() # type: ignore
  318. kwargs.append(
  319. (
  320. ast.arg(
  321. arg=name,
  322. annotation=ast.Name(
  323. id=_get_type_hint(value, type_hint_globals)
  324. ),
  325. ),
  326. ast.Constant(value=default),
  327. )
  328. )
  329. return kwargs
  330. def _get_parent_imports(func):
  331. _imports = {"reflex.vars": ["Var"]}
  332. for type_hint in inspect.get_annotations(func).values():
  333. try:
  334. match = re.match(r"\w+\[([\w\d]+)\]", type_hint)
  335. except TypeError:
  336. continue
  337. if match:
  338. type_hint = match.group(1)
  339. if type_hint in importlib.import_module(func.__module__).__dir__():
  340. _imports.setdefault(func.__module__, []).append(type_hint)
  341. return _imports
  342. def _generate_component_create_functiondef(
  343. node: ast.FunctionDef | None,
  344. clz: type[Component],
  345. type_hint_globals: dict[str, Any],
  346. ) -> ast.FunctionDef:
  347. """Generate the create function definition for a Component.
  348. Args:
  349. node: The existing create functiondef node from the ast
  350. clz: The Component class to generate the create functiondef for.
  351. type_hint_globals: The globals to use to resolving a type hint str.
  352. Returns:
  353. The create functiondef node for the ast.
  354. """
  355. # add the imports needed by get_type_hint later
  356. type_hint_globals.update(
  357. {name: getattr(typing, name) for name in DEFAULT_TYPING_IMPORTS}
  358. )
  359. if clz.__module__ != clz.create.__module__:
  360. _imports = _get_parent_imports(clz.create)
  361. for name, values in _imports.items():
  362. exec(f"from {name} import {','.join(values)}", type_hint_globals)
  363. kwargs = _extract_func_kwargs_as_ast_nodes(clz.create, type_hint_globals)
  364. # kwargs associated with props defined in the class and its parents
  365. all_classes = [c for c in clz.__mro__ if issubclass(c, Component)]
  366. prop_kwargs = _extract_class_props_as_ast_nodes(
  367. clz.create, all_classes, type_hint_globals
  368. )
  369. all_props = [arg[0].arg for arg in prop_kwargs]
  370. kwargs.extend(prop_kwargs)
  371. # event handler kwargs
  372. kwargs.extend(
  373. (
  374. ast.arg(
  375. arg=trigger,
  376. annotation=ast.Name(
  377. id="Optional[Union[EventHandler, EventSpec, list, function, BaseVar]]"
  378. ),
  379. ),
  380. ast.Constant(value=None),
  381. )
  382. for trigger in sorted(clz().get_event_triggers().keys())
  383. )
  384. logger.debug(f"Generated {clz.__name__}.create method with {len(kwargs)} kwargs")
  385. create_args = ast.arguments(
  386. args=[ast.arg(arg="cls")],
  387. posonlyargs=[],
  388. vararg=ast.arg(arg="children"),
  389. kwonlyargs=[arg[0] for arg in kwargs],
  390. kw_defaults=[arg[1] for arg in kwargs],
  391. kwarg=ast.arg(arg="props"),
  392. defaults=[],
  393. )
  394. definition = ast.FunctionDef(
  395. name="create",
  396. args=create_args,
  397. body=[
  398. ast.Expr(
  399. value=ast.Constant(value=_generate_docstrings(all_classes, all_props))
  400. ),
  401. ast.Expr(
  402. value=ast.Ellipsis(),
  403. ),
  404. ],
  405. decorator_list=[
  406. ast.Name(id="overload"),
  407. *(
  408. node.decorator_list
  409. if node is not None
  410. else [ast.Name(id="classmethod")]
  411. ),
  412. ],
  413. lineno=node.lineno if node is not None else None,
  414. returns=ast.Constant(value=clz.__name__),
  415. )
  416. return definition
  417. class StubGenerator(ast.NodeTransformer):
  418. """A node transformer that will generate the stubs for a given module."""
  419. def __init__(self, module: ModuleType, classes: dict[str, Type[Component]]):
  420. """Initialize the stub generator.
  421. Args:
  422. module: The actual module object module to generate stubs for.
  423. classes: The actual Component class objects to generate stubs for.
  424. """
  425. super().__init__()
  426. # Dict mapping class name to actual class object.
  427. self.classes = classes
  428. # Track the last class node that was visited.
  429. self.current_class = None
  430. # These imports will be included in the AST of stub files.
  431. self.typing_imports = DEFAULT_TYPING_IMPORTS
  432. # Whether those typing imports have been inserted yet.
  433. self.inserted_imports = False
  434. # Collected import statements from the module.
  435. self.import_statements: list[str] = []
  436. # This dict is used when evaluating type hints.
  437. self.type_hint_globals = module.__dict__.copy()
  438. @staticmethod
  439. def _remove_docstring(
  440. node: ast.Module | ast.ClassDef | ast.FunctionDef,
  441. ) -> ast.Module | ast.ClassDef | ast.FunctionDef:
  442. """Removes any docstring in place.
  443. Args:
  444. node: The node to remove the docstring from.
  445. Returns:
  446. The modified node.
  447. """
  448. if (
  449. node.body
  450. and isinstance(node.body[0], ast.Expr)
  451. and isinstance(node.body[0].value, ast.Constant)
  452. ):
  453. node.body.pop(0)
  454. return node
  455. def visit_Module(self, node: ast.Module) -> ast.Module:
  456. """Visit a Module node and remove docstring from body.
  457. Args:
  458. node: The Module node to visit.
  459. Returns:
  460. The modified Module node.
  461. """
  462. self.generic_visit(node)
  463. return self._remove_docstring(node) # type: ignore
  464. def visit_Import(
  465. self, node: ast.Import | ast.ImportFrom
  466. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom]:
  467. """Collect import statements from the module.
  468. If this is the first import statement, insert the typing imports before it.
  469. Args:
  470. node: The import node to visit.
  471. Returns:
  472. The modified import node(s).
  473. """
  474. self.import_statements.append(ast.unparse(node))
  475. if not self.inserted_imports:
  476. self.inserted_imports = True
  477. return _generate_imports(self.typing_imports) + [node]
  478. return node
  479. def visit_ImportFrom(
  480. self, node: ast.ImportFrom
  481. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom] | None:
  482. """Visit an ImportFrom node.
  483. Remove any `from __future__ import *` statements, and hand off to visit_Import.
  484. Args:
  485. node: The ImportFrom node to visit.
  486. Returns:
  487. The modified ImportFrom node.
  488. """
  489. if node.module == "__future__":
  490. return None # ignore __future__ imports
  491. return self.visit_Import(node)
  492. def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
  493. """Visit a ClassDef node.
  494. Remove all assignments in the class body, and add a create functiondef
  495. if one does not exist.
  496. Args:
  497. node: The ClassDef node to visit.
  498. Returns:
  499. The modified ClassDef node.
  500. """
  501. exec("\n".join(self.import_statements), self.type_hint_globals)
  502. self.current_class = node.name
  503. self._remove_docstring(node)
  504. self.generic_visit(node) # Visit child nodes.
  505. if (
  506. not any(
  507. isinstance(child, ast.FunctionDef) and child.name == "create"
  508. for child in node.body
  509. )
  510. and self.current_class in self.classes
  511. ):
  512. # Add a new .create FunctionDef since one does not exist.
  513. node.body.append(
  514. _generate_component_create_functiondef(
  515. node=None,
  516. clz=self.classes[self.current_class],
  517. type_hint_globals=self.type_hint_globals,
  518. )
  519. )
  520. if not node.body:
  521. # We should never return an empty body.
  522. node.body.append(ast.Expr(value=ast.Ellipsis()))
  523. self.current_class = None
  524. return node
  525. def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
  526. """Visit a FunctionDef node.
  527. Special handling for `.create` functions to add type hints for all props
  528. defined on the component class.
  529. Remove all private functions and blank out the function body of the
  530. remaining public functions.
  531. Args:
  532. node: The FunctionDef node to visit.
  533. Returns:
  534. The modified FunctionDef node (or None).
  535. """
  536. if node.name == "create" and self.current_class in self.classes:
  537. node = _generate_component_create_functiondef(
  538. node, self.classes[self.current_class], self.type_hint_globals
  539. )
  540. else:
  541. if node.name.startswith("_"):
  542. return None # remove private methods
  543. # Blank out the function body for public functions.
  544. node.body = [ast.Expr(value=ast.Ellipsis())]
  545. return node
  546. def visit_Assign(self, node: ast.Assign) -> ast.Assign | None:
  547. """Remove non-annotated assignment statements.
  548. Args:
  549. node: The Assign node to visit.
  550. Returns:
  551. The modified Assign node (or None).
  552. """
  553. # Special case for assignments to `typing.Any` as fallback.
  554. if (
  555. node.value is not None
  556. and isinstance(node.value, ast.Name)
  557. and node.value.id == "Any"
  558. ):
  559. return node
  560. if self.current_class in self.classes:
  561. # Remove annotated assignments in Component classes (props)
  562. return None
  563. return node
  564. def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign | None:
  565. """Visit an AnnAssign node (Annotated assignment).
  566. Remove private target and remove the assignment value in the stub.
  567. Args:
  568. node: The AnnAssign node to visit.
  569. Returns:
  570. The modified AnnAssign node (or None).
  571. """
  572. # skip ClassVars
  573. if (
  574. isinstance(node.annotation, ast.Subscript)
  575. and isinstance(node.annotation.value, ast.Name)
  576. and node.annotation.value.id == "ClassVar"
  577. ):
  578. return node
  579. if isinstance(node.target, ast.Name) and node.target.id.startswith("_"):
  580. return None
  581. if self.current_class in self.classes:
  582. # Remove annotated assignments in Component classes (props)
  583. return None
  584. # Blank out assignments in type stubs.
  585. node.value = None
  586. return node
  587. class PyiGenerator:
  588. """A .pyi file generator that will scan all defined Component in Reflex and
  589. generate the approriate stub.
  590. """
  591. modules: list = []
  592. root: str = ""
  593. current_module: Any = {}
  594. def _write_pyi_file(self, module_path: Path, source: str):
  595. relpath = _relative_to_pwd(module_path)
  596. pyi_content = [
  597. f'"""Stub file for {relpath}"""',
  598. "# ------------------- DO NOT EDIT ----------------------",
  599. "# This file was generated by `scripts/pyi_generator.py`!",
  600. "# ------------------------------------------------------",
  601. "",
  602. ]
  603. for formatted_line in black.format_file_contents(
  604. src_contents=source,
  605. fast=True,
  606. mode=black.mode.Mode(is_pyi=True),
  607. ).splitlines():
  608. # Bit of a hack here, since the AST cannot represent comments.
  609. if "def create(" in formatted_line:
  610. pyi_content.append(formatted_line + " # type: ignore")
  611. elif "Figure" in formatted_line:
  612. pyi_content.append(formatted_line + " # type: ignore")
  613. else:
  614. pyi_content.append(formatted_line)
  615. pyi_content.append("") # add empty line at the end for formatting
  616. pyi_path = module_path.with_suffix(".pyi")
  617. pyi_path.write_text("\n".join(pyi_content))
  618. logger.info(f"Wrote {relpath}")
  619. def _scan_file(self, module_path: Path):
  620. # module_import = str(module_path.with_suffix("")).replace("/", ".")
  621. module_import = (
  622. _relative_to_pwd(module_path).with_suffix("").as_posix().replace("/", ".")
  623. )
  624. module = importlib.import_module(module_import)
  625. logger.debug(f"Read {module_path}")
  626. class_names = {
  627. name: obj
  628. for name, obj in vars(module).items()
  629. if inspect.isclass(obj)
  630. and issubclass(obj, Component)
  631. and obj != Component
  632. and inspect.getmodule(obj) == module
  633. }
  634. if not class_names:
  635. return
  636. new_tree = StubGenerator(module, class_names).visit(
  637. ast.parse(inspect.getsource(module))
  638. )
  639. self._write_pyi_file(module_path, ast.unparse(new_tree))
  640. def _scan_files_multiprocess(self, files: list[Path]):
  641. with Pool(processes=cpu_count()) as pool:
  642. pool.map(self._scan_file, files)
  643. def _scan_files(self, files: list[Path]):
  644. for file in files:
  645. self._scan_file(file)
  646. def scan_all(self, targets, changed_files: list[Path] | None = None):
  647. """Scan all targets for class inheriting Component and generate the .pyi files.
  648. Args:
  649. targets: the list of file/folders to scan.
  650. changed_files (optional): the list of changed files since the last run.
  651. """
  652. file_targets = []
  653. for target in targets:
  654. target_path = Path(target)
  655. if target_path.is_file() and target_path.suffix == ".py":
  656. file_targets.append(target_path)
  657. continue
  658. if not target_path.is_dir():
  659. continue
  660. for file_path in _walk_files(target_path):
  661. relative = _relative_to_pwd(file_path)
  662. if relative.name in EXCLUDED_FILES or file_path.suffix != ".py":
  663. continue
  664. if (
  665. changed_files is not None
  666. and _relative_to_pwd(file_path) not in changed_files
  667. ):
  668. continue
  669. file_targets.append(file_path)
  670. # check if pyi changed but not the source
  671. if changed_files is not None:
  672. for changed_file in changed_files:
  673. if changed_file.suffix != ".pyi":
  674. continue
  675. py_file_path = changed_file.with_suffix(".py")
  676. if not py_file_path.exists() and changed_file.exists():
  677. changed_file.unlink()
  678. if py_file_path in file_targets:
  679. continue
  680. subprocess.run(["git", "checkout", changed_file])
  681. if cpu_count() == 1 or len(file_targets) < 5:
  682. self._scan_files(file_targets)
  683. else:
  684. self._scan_files_multiprocess(file_targets)
  685. def generate_init():
  686. """Generate a pyi file for the main __init__.py."""
  687. from reflex import _MAPPING # type: ignore
  688. imports = [
  689. f"from {path if mod != path.rsplit('.')[-1] or mod == 'page' else '.'.join(path.rsplit('.')[:-1])} import {mod} as {mod}"
  690. for mod, path in _MAPPING.items()
  691. ]
  692. imports.append("")
  693. INIT_FILE.write_text("\n".join(imports))
  694. if __name__ == "__main__":
  695. logging.basicConfig(level=logging.DEBUG)
  696. logging.getLogger("blib2to3.pgen2.driver").setLevel(logging.INFO)
  697. targets = sys.argv[1:] if len(sys.argv) > 1 else ["reflex/components"]
  698. logger.info(f"Running .pyi generator for {targets}")
  699. changed_files = _get_changed_files()
  700. if changed_files is None:
  701. logger.info("Changed files could not be detected, regenerating all .pyi files")
  702. else:
  703. logger.info(f"Detected changed files: {changed_files}")
  704. gen = PyiGenerator()
  705. gen.scan_all(targets, changed_files)
  706. generate_init()
  707. current_commit_sha = subprocess.run(
  708. ["git", "rev-parse", "HEAD"], capture_output=True, encoding="utf-8"
  709. ).stdout.strip()
  710. LAST_RUN_COMMIT_SHA_FILE.write_text(current_commit_sha)