1
0

pyi_generator.py 27 KB

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