pyi_generator.py 27 KB

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