custom_components.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. """CLI for creating custom components."""
  2. from __future__ import annotations
  3. import os
  4. import re
  5. import subprocess
  6. import sys
  7. from collections import namedtuple
  8. from contextlib import contextmanager
  9. from pathlib import Path
  10. import httpx
  11. import tomlkit
  12. import typer
  13. from tomlkit.exceptions import NonExistentKey, TOMLKitError
  14. from reflex import constants
  15. from reflex.config import environment, get_config
  16. from reflex.constants import CustomComponents
  17. from reflex.utils import console
  18. custom_components_cli = typer.Typer()
  19. POST_CUSTOM_COMPONENTS_GALLERY_TIMEOUT = 15
  20. @contextmanager
  21. def set_directory(working_directory: str | Path):
  22. """Context manager that sets the working directory.
  23. Args:
  24. working_directory: The working directory to change to.
  25. Yields:
  26. Yield to the caller to perform operations in the working directory.
  27. """
  28. current_directory = Path.cwd()
  29. working_directory = Path(working_directory)
  30. try:
  31. os.chdir(working_directory)
  32. yield
  33. finally:
  34. os.chdir(current_directory)
  35. def _create_package_config(module_name: str, package_name: str):
  36. """Create a package config pyproject.toml file.
  37. Args:
  38. module_name: The name of the module.
  39. package_name: The name of the package typically constructed with `reflex-` prefix and a meaningful library name.
  40. """
  41. from reflex.compiler import templates
  42. pyproject = Path(CustomComponents.PYPROJECT_TOML)
  43. pyproject.write_text(
  44. templates.CUSTOM_COMPONENTS_PYPROJECT_TOML.render(
  45. module_name=module_name,
  46. package_name=package_name,
  47. reflex_version=constants.Reflex.VERSION,
  48. )
  49. )
  50. def _get_package_config(exit_on_fail: bool = True) -> dict:
  51. """Get the package configuration from the pyproject.toml file.
  52. Args:
  53. exit_on_fail: Whether to exit if the pyproject.toml file is not found.
  54. Returns:
  55. The package configuration.
  56. Raises:
  57. Exit: If the pyproject.toml file is not found and exit_on_fail is True.
  58. """
  59. pyproject = Path(CustomComponents.PYPROJECT_TOML)
  60. try:
  61. return dict(tomlkit.loads(pyproject.read_bytes()))
  62. except (OSError, TOMLKitError) as ex:
  63. console.error(f"Unable to read from {pyproject} due to {ex}")
  64. if exit_on_fail:
  65. raise typer.Exit(code=1) from ex
  66. raise
  67. def _create_readme(module_name: str, package_name: str):
  68. """Create a package README file.
  69. Args:
  70. module_name: The name of the module.
  71. package_name: The name of the python package to be published.
  72. """
  73. from reflex.compiler import templates
  74. readme = Path(CustomComponents.PACKAGE_README)
  75. readme.write_text(
  76. templates.CUSTOM_COMPONENTS_README.render(
  77. module_name=module_name,
  78. package_name=package_name,
  79. )
  80. )
  81. def _write_source_and_init_py(
  82. custom_component_src_dir: Path,
  83. component_class_name: str,
  84. module_name: str,
  85. ):
  86. """Write the source code and init file from templates for the custom component.
  87. Args:
  88. custom_component_src_dir: The name of the custom component source directory.
  89. component_class_name: The name of the component class.
  90. module_name: The name of the module.
  91. """
  92. from reflex.compiler import templates
  93. module_path = custom_component_src_dir / f"{module_name}.py"
  94. module_path.write_text(
  95. templates.CUSTOM_COMPONENTS_SOURCE.render(
  96. component_class_name=component_class_name, module_name=module_name
  97. )
  98. )
  99. init_path = custom_component_src_dir / CustomComponents.INIT_FILE
  100. init_path.write_text(
  101. templates.CUSTOM_COMPONENTS_INIT_FILE.render(module_name=module_name)
  102. )
  103. def _populate_demo_app(name_variants: NameVariants):
  104. """Populate the demo app that imports the custom components.
  105. Args:
  106. name_variants: the tuple including various names such as package name, class name needed for the project.
  107. """
  108. from reflex import constants
  109. from reflex.compiler import templates
  110. from reflex.reflex import _init
  111. demo_app_dir = Path(name_variants.demo_app_dir)
  112. demo_app_name = name_variants.demo_app_name
  113. console.info(f"Creating app for testing: {demo_app_dir!s}")
  114. demo_app_dir.mkdir(exist_ok=True)
  115. with set_directory(demo_app_dir):
  116. # We start with the blank template as basis.
  117. _init(name=demo_app_name, template=constants.Templates.DEFAULT)
  118. # Then overwrite the app source file with the one we want for testing custom components.
  119. # This source file is rendered using jinja template file.
  120. demo_file = Path(f"{demo_app_name}/{demo_app_name}.py")
  121. demo_file.write_text(
  122. templates.CUSTOM_COMPONENTS_DEMO_APP.render(
  123. custom_component_module_dir=name_variants.custom_component_module_dir,
  124. module_name=name_variants.module_name,
  125. )
  126. )
  127. # Append the custom component package to the requirements.txt file.
  128. with Path(f"{constants.RequirementsTxt.FILE}").open(mode="a") as f:
  129. f.write(f"{name_variants.package_name}\n")
  130. def _get_default_library_name_parts() -> list[str]:
  131. """Get the default library name. Based on the current directory name, remove any non-alphanumeric characters.
  132. Raises:
  133. Exit: If the current directory name is not suitable for python projects, and we cannot find a valid library name based off it.
  134. Returns:
  135. The parts of default library name.
  136. """
  137. current_dir_name = Path.cwd().name
  138. cleaned_dir_name = re.sub("[^0-9a-zA-Z-_]+", "", current_dir_name).lower()
  139. parts = [part for part in re.split("-|_", cleaned_dir_name) if part]
  140. if parts and parts[0] == constants.Reflex.MODULE_NAME:
  141. # If the directory name already starts with "reflex", remove it from the parts.
  142. parts = parts[1:]
  143. # If no parts left, cannot find a valid library name, exit.
  144. if not parts:
  145. # The folder likely has a name not suitable for python paths.
  146. console.error(
  147. f"Based on current directory name {current_dir_name}, the library name is {constants.Reflex.MODULE_NAME}. This package already exists. Please use --library-name to specify a different name."
  148. )
  149. raise typer.Exit(code=1)
  150. if not parts:
  151. # The folder likely has a name not suitable for python paths.
  152. console.error(
  153. f"Could not find a valid library name based on the current directory: got {current_dir_name}."
  154. )
  155. raise typer.Exit(code=1)
  156. return parts
  157. NameVariants = namedtuple(
  158. "NameVariants",
  159. [
  160. "library_name",
  161. "component_class_name",
  162. "package_name",
  163. "module_name",
  164. "custom_component_module_dir",
  165. "demo_app_dir",
  166. "demo_app_name",
  167. ],
  168. )
  169. def _validate_library_name(library_name: str | None) -> NameVariants:
  170. """Validate the library name.
  171. Args:
  172. library_name: The name of the library if picked otherwise None.
  173. Raises:
  174. Exit: If the library name is not suitable for python projects.
  175. Returns:
  176. A tuple containing the various names such as package name, class name, etc., needed for the project.
  177. """
  178. if library_name is not None and not re.match(
  179. r"^[a-zA-Z-]+[a-zA-Z0-9-]*$", library_name
  180. ):
  181. console.error(
  182. f"Please use only alphanumeric characters or dashes: got {library_name}"
  183. )
  184. raise typer.Exit(code=1)
  185. # If not specified, use the current directory name to form the module name.
  186. name_parts = (
  187. [part.lower() for part in library_name.split("-")]
  188. if library_name
  189. else _get_default_library_name_parts()
  190. )
  191. if not library_name:
  192. library_name = "-".join(name_parts)
  193. # Component class name is the camel case.
  194. component_class_name = "".join([part.capitalize() for part in name_parts])
  195. console.debug(f"Component class name: {component_class_name}")
  196. # Package name is commonly kebab case.
  197. package_name = f"reflex-{library_name}"
  198. console.debug(f"Package name: {package_name}")
  199. # Module name is the snake case.
  200. module_name = "_".join(name_parts)
  201. custom_component_module_dir = Path(f"reflex_{module_name}")
  202. console.debug(f"Custom component source directory: {custom_component_module_dir}")
  203. # Use the same name for the directory and the app.
  204. demo_app_dir = demo_app_name = f"{module_name}_demo"
  205. console.debug(f"Demo app directory: {demo_app_dir}")
  206. return NameVariants(
  207. library_name=library_name,
  208. component_class_name=component_class_name,
  209. package_name=package_name,
  210. module_name=module_name,
  211. custom_component_module_dir=custom_component_module_dir,
  212. demo_app_dir=demo_app_dir,
  213. demo_app_name=demo_app_name,
  214. )
  215. def _populate_custom_component_project(name_variants: NameVariants):
  216. """Populate the custom component source directory. This includes the pyproject.toml, README.md, and the code template for the custom component.
  217. Args:
  218. name_variants: the tuple including various names such as package name, class name needed for the project.
  219. """
  220. console.info(
  221. f"Populating pyproject.toml with package name: {name_variants.package_name}"
  222. )
  223. # write pyproject.toml, README.md, etc.
  224. _create_package_config(
  225. module_name=name_variants.library_name, package_name=name_variants.package_name
  226. )
  227. _create_readme(
  228. module_name=name_variants.library_name, package_name=name_variants.package_name
  229. )
  230. console.info(
  231. f"Initializing the component directory: {CustomComponents.SRC_DIR / name_variants.custom_component_module_dir}"
  232. )
  233. CustomComponents.SRC_DIR.mkdir(exist_ok=True)
  234. with set_directory(CustomComponents.SRC_DIR):
  235. module_dir = Path(name_variants.custom_component_module_dir)
  236. module_dir.mkdir(exist_ok=True, parents=True)
  237. _write_source_and_init_py(
  238. custom_component_src_dir=module_dir,
  239. component_class_name=name_variants.component_class_name,
  240. module_name=name_variants.module_name,
  241. )
  242. @custom_components_cli.command(name="init")
  243. def init(
  244. library_name: str | None = typer.Option(
  245. None,
  246. help="The name of your library. On PyPI, package will be published as `reflex-{library-name}`.",
  247. ),
  248. install: bool = typer.Option(
  249. True,
  250. help="Whether to install package from this local custom component in editable mode.",
  251. ),
  252. loglevel: constants.LogLevel | None = typer.Option(
  253. None, help="The log level to use."
  254. ),
  255. ):
  256. """Initialize a custom component.
  257. Args:
  258. library_name: The name of the library.
  259. install: Whether to install package from this local custom component in editable mode.
  260. loglevel: The log level to use.
  261. Raises:
  262. Exit: If the pyproject.toml already exists.
  263. """
  264. from reflex.utils import exec, prerequisites
  265. console.set_log_level(loglevel or get_config().loglevel)
  266. if CustomComponents.PYPROJECT_TOML.exists():
  267. console.error(f"A {CustomComponents.PYPROJECT_TOML} already exists. Aborting.")
  268. typer.Exit(code=1)
  269. # Show system info.
  270. exec.output_system_info()
  271. # Check the name follows the convention if picked.
  272. name_variants = _validate_library_name(library_name)
  273. console.rule(f"Initializing {name_variants.package_name} project")
  274. _populate_custom_component_project(name_variants)
  275. _populate_demo_app(name_variants)
  276. # Initialize the .gitignore.
  277. prerequisites.initialize_gitignore(
  278. gitignore_file=CustomComponents.FILE, files_to_ignore=CustomComponents.DEFAULTS
  279. )
  280. if install:
  281. package_name = name_variants.package_name
  282. console.rule(f"Installing {package_name} in editable mode.")
  283. if _pip_install_on_demand(package_name=".", install_args=["-e"]):
  284. console.info(f"Package {package_name} installed!")
  285. else:
  286. raise typer.Exit(code=1)
  287. console.success("Custom component initialized successfully!", bold=True)
  288. console.rule("Project Summary")
  289. console.print(
  290. f"[{CustomComponents.PACKAGE_README}]: Package description. Please add usage examples."
  291. )
  292. console.print(
  293. f"[{CustomComponents.PYPROJECT_TOML}]: Project configuration file. Please fill in details such as your name, email, homepage URL."
  294. )
  295. console.print(
  296. f"[{CustomComponents.SRC_DIR}/]: Custom component code template. Start by editing it with your component implementation."
  297. )
  298. console.print(
  299. f"[{name_variants.demo_app_dir}/]: Demo App. Add more code to this app and test."
  300. )
  301. def _pip_install_on_demand(
  302. package_name: str,
  303. install_args: list[str] | None = None,
  304. ) -> bool:
  305. """Install a package on demand.
  306. Args:
  307. package_name: The name of the package.
  308. install_args: The additional arguments for the pip install command.
  309. Returns:
  310. True if the package is installed successfully, False otherwise.
  311. """
  312. install_args = install_args or []
  313. install_cmds = [
  314. sys.executable,
  315. "-m",
  316. "pip",
  317. "install",
  318. *install_args,
  319. package_name,
  320. ]
  321. console.debug(f"Install package: {' '.join(install_cmds)}")
  322. return _run_commands_in_subprocess(install_cmds)
  323. def _run_commands_in_subprocess(cmds: list[str]) -> bool:
  324. """Run commands in a subprocess.
  325. Args:
  326. cmds: The commands to run.
  327. Returns:
  328. True if the command runs successfully, False otherwise.
  329. """
  330. console.debug(f"Running command: {' '.join(cmds)}")
  331. try:
  332. result = subprocess.run(cmds, capture_output=True, text=True, check=True)
  333. except subprocess.CalledProcessError as cpe:
  334. console.error(cpe.stdout)
  335. console.error(cpe.stderr)
  336. return False
  337. else:
  338. console.debug(result.stdout)
  339. return True
  340. def _make_pyi_files():
  341. """Create pyi files for the custom component."""
  342. from reflex.utils.pyi_generator import PyiGenerator
  343. package_name = _get_package_config()["project"]["name"]
  344. for dir, _, _ in os.walk(f"./{package_name}"):
  345. if "__pycache__" in dir:
  346. continue
  347. PyiGenerator().scan_all([dir])
  348. def _run_build():
  349. """Run the build command.
  350. Raises:
  351. Exit: If the build fails.
  352. """
  353. console.print("Building custom component...")
  354. _make_pyi_files()
  355. cmds = [sys.executable, "-m", "build", "."]
  356. if _run_commands_in_subprocess(cmds):
  357. console.info("Custom component built successfully!")
  358. else:
  359. raise typer.Exit(code=1)
  360. @custom_components_cli.command(name="build")
  361. def build(
  362. loglevel: constants.LogLevel | None = typer.Option(
  363. None, help="The log level to use."
  364. ),
  365. ):
  366. """Build a custom component. Must be run from the project root directory where the pyproject.toml is.
  367. Args:
  368. loglevel: The log level to use.
  369. """
  370. console.set_log_level(loglevel or get_config().loglevel)
  371. _run_build()
  372. def _validate_repository_name(repository: str | None) -> str:
  373. """Validate the repository name.
  374. Args:
  375. repository: The name of the repository.
  376. Returns:
  377. The name of the repository.
  378. Raises:
  379. Exit: If the repository name is not supported.
  380. """
  381. if repository is None:
  382. return "pypi"
  383. elif repository not in CustomComponents.REPO_URLS:
  384. console.error(
  385. f"Unsupported repository name. Allow {CustomComponents.REPO_URLS.keys()}, got {repository}"
  386. )
  387. raise typer.Exit(code=1)
  388. return repository
  389. def _validate_credentials(
  390. username: str | None, password: str | None, token: str | None
  391. ) -> tuple[str, str]:
  392. """Validate the credentials.
  393. Args:
  394. username: The username to use for authentication on python package repository.
  395. password: The password to use for authentication on python package repository.
  396. token: The token to use for authentication on python package repository.
  397. Raises:
  398. Exit: If the appropriate combination of credentials is not provided.
  399. Returns:
  400. The username and password.
  401. """
  402. if token is not None:
  403. if username is not None or password is not None:
  404. console.error("Cannot use token and username/password at the same time.")
  405. raise typer.Exit(code=1)
  406. username = "__token__"
  407. password = token
  408. elif username is None or password is None:
  409. console.error(
  410. "Must provide both username and password for authentication if not using a token."
  411. )
  412. raise typer.Exit(code=1)
  413. return username, password
  414. def _get_version_to_publish() -> str:
  415. """Get the version to publish from the pyproject.toml.
  416. Returns:
  417. The version to publish.
  418. """
  419. try:
  420. return _get_package_config()["project"]["version"]
  421. except NonExistentKey:
  422. # Try to get the version from dynamic sources
  423. import build.util
  424. return build.util.project_wheel_metadata(".", isolated=True)["version"]
  425. def _ensure_dist_dir(version_to_publish: str, build: bool):
  426. """Ensure the distribution directory and the expected files exist.
  427. Args:
  428. version_to_publish: The version to be published.
  429. build: Whether to build the package first.
  430. Raises:
  431. Exit: If the distribution directory does not exist, or the expected files are not found.
  432. """
  433. dist_dir = Path(CustomComponents.DIST_DIR)
  434. if build:
  435. # Need to check if the files here are for the version to be published.
  436. if dist_dir.exists():
  437. # Check if the distribution files are for the version to be published.
  438. needs_rebuild = False
  439. for suffix in CustomComponents.DISTRIBUTION_FILE_SUFFIXES:
  440. if not list(dist_dir.glob(f"*{version_to_publish}*{suffix}")):
  441. console.debug(
  442. f"Expected distribution file with suffix {suffix} for version {version_to_publish} not found in directory {dist_dir.name}"
  443. )
  444. needs_rebuild = True
  445. break
  446. else:
  447. needs_rebuild = True
  448. if not needs_rebuild:
  449. needs_rebuild = (
  450. console.ask(
  451. "Distribution files for the version to be published already exist. Do you want to rebuild?",
  452. choices=["y", "n"],
  453. default="n",
  454. )
  455. == "y"
  456. )
  457. if needs_rebuild:
  458. _run_build()
  459. # Check if the distribution directory exists.
  460. if not dist_dir.exists():
  461. console.error(f"Directory {dist_dir.name} does not exist. Please build first.")
  462. raise typer.Exit(code=1)
  463. # Check if the distribution directory is indeed a directory.
  464. if not dist_dir.is_dir():
  465. console.error(
  466. f"{dist_dir.name} is not a directory. If this is a file you added, move it and rebuild."
  467. )
  468. raise typer.Exit(code=1)
  469. # Check if the distribution files exist.
  470. for suffix in CustomComponents.DISTRIBUTION_FILE_SUFFIXES:
  471. if not list(dist_dir.glob(f"*{suffix}")):
  472. console.error(
  473. f"Expected distribution file with suffix {suffix} in directory {dist_dir.name}"
  474. )
  475. raise typer.Exit(code=1)
  476. @custom_components_cli.command(name="publish")
  477. def publish(
  478. repository: str | None = typer.Option(
  479. None,
  480. "-r",
  481. "--repository",
  482. help="The name of the repository. Defaults to pypi. Only supports pypi and testpypi (Test PyPI) for now.",
  483. ),
  484. token: str | None = typer.Option(
  485. None,
  486. "-t",
  487. "--token",
  488. help="The API token to use for authentication on python package repository. If token is provided, no username/password should be provided at the same time",
  489. ),
  490. username: str | None = typer.Option(
  491. environment.TWINE_USERNAME.get(),
  492. "-u",
  493. "--username",
  494. show_default="TWINE_USERNAME environment variable value if set",
  495. help="The username to use for authentication on python package repository. Username and password must both be provided.",
  496. ),
  497. password: str | None = typer.Option(
  498. environment.TWINE_PASSWORD.get(),
  499. "-p",
  500. "--password",
  501. show_default="TWINE_PASSWORD environment variable value if set",
  502. help="The password to use for authentication on python package repository. Username and password must both be provided.",
  503. ),
  504. build: bool = typer.Option(
  505. True,
  506. help="Whether to build the package before publishing. If the package is already built, set this to False.",
  507. ),
  508. share: bool = typer.Option(
  509. True,
  510. help="Whether to prompt to share more details on the published package. Only applicable when published to PyPI. Defaults to True.",
  511. ),
  512. validate_project_info: bool = typer.Option(
  513. True,
  514. help="Whether to interactively validate the project information in the pyproject.toml file.",
  515. ),
  516. loglevel: constants.LogLevel | None = typer.Option(
  517. None, help="The log level to use."
  518. ),
  519. ):
  520. """Publish a custom component. Must be run from the project root directory where the pyproject.toml is.
  521. Args:
  522. repository: The name of the Python package repository, such pypi, testpypi.
  523. token: The token to use for authentication on python package repository. If token is provided, no username/password should be provided at the same time.
  524. username: The username to use for authentication on python package repository.
  525. password: The password to use for authentication on python package repository.
  526. build: Whether to build the distribution files. Defaults to True.
  527. share: Whether to prompt to share more details on the published package. Defaults to True.
  528. validate_project_info: whether to interactively validate the project information in the pyproject.toml file. Defaults to True.
  529. loglevel: The log level to use.
  530. Raises:
  531. Exit: If arguments provided are not correct or the publish fails.
  532. """
  533. console.set_log_level(loglevel or get_config().loglevel)
  534. # Validate the repository name.
  535. repository = _validate_repository_name(repository)
  536. console.print(f"Publishing custom component to {repository}...")
  537. # Validate the credentials.
  538. username, password = _validate_credentials(username, password, token)
  539. # Minimal Validation of the pyproject.toml.
  540. _min_validate_project_info()
  541. # Get the version to publish from the pyproject.toml.
  542. version_to_publish = _get_version_to_publish()
  543. # Validate the distribution directory.
  544. _ensure_dist_dir(version_to_publish=version_to_publish, build=build)
  545. if validate_project_info and (
  546. console.ask(
  547. "Would you like to interactively review the package information?",
  548. choices=["y", "n"],
  549. default="y",
  550. )
  551. == "y"
  552. ):
  553. _validate_project_info()
  554. publish_cmds = [
  555. sys.executable,
  556. "-m",
  557. "twine",
  558. "upload",
  559. "--repository-url",
  560. CustomComponents.REPO_URLS[repository],
  561. "--username",
  562. username,
  563. "--password",
  564. password,
  565. "--non-interactive",
  566. f"{CustomComponents.DIST_DIR}/*{version_to_publish}*",
  567. ]
  568. if _run_commands_in_subprocess(publish_cmds):
  569. console.info("Custom component published successfully!")
  570. else:
  571. raise typer.Exit(1)
  572. # Only prompt to share more details on the published package if it is published to PyPI.
  573. if repository != "pypi" or not share:
  574. return
  575. # Ask user to share more details on the published package.
  576. if (
  577. console.ask(
  578. "Would you like to include your published component on our gallery?",
  579. choices=["y", "n"],
  580. default="y",
  581. )
  582. == "n"
  583. ):
  584. console.print(
  585. "If you decide to do this later, you can run `reflex component share` command. Thank you!"
  586. )
  587. return
  588. _collect_details_for_gallery()
  589. def _process_entered_list(input: str | None) -> list | None:
  590. """Process the user entered comma separated list into a list if applicable.
  591. Args:
  592. input: the user entered comma separated list
  593. Returns:
  594. The list of items or None.
  595. """
  596. return [t.strip() for t in (input or "").split(",") if t if input] or None
  597. def _min_validate_project_info():
  598. """Ensures minimal project information in the pyproject.toml file.
  599. Raises:
  600. Exit: If the pyproject.toml file is ill-formed.
  601. """
  602. pyproject_toml = _get_package_config()
  603. project = pyproject_toml.get("project")
  604. if project is None:
  605. console.error(
  606. f"The project section is not found in {CustomComponents.PYPROJECT_TOML}"
  607. )
  608. raise typer.Exit(code=1)
  609. if not project.get("name"):
  610. console.error(
  611. f"The project name is not found in {CustomComponents.PYPROJECT_TOML}"
  612. )
  613. raise typer.Exit(code=1)
  614. if not project.get("version") and "version" not in project.get("dynamic", []):
  615. console.error(
  616. f"The project version is not found in {CustomComponents.PYPROJECT_TOML}"
  617. )
  618. raise typer.Exit(code=1)
  619. def _validate_project_info():
  620. """Validate the project information in the pyproject.toml file.
  621. Raises:
  622. Exit: If the pyproject.toml file is ill-formed.
  623. """
  624. pyproject_toml = _get_package_config()
  625. project = pyproject_toml["project"]
  626. console.print(
  627. f"Double check the information before publishing: {project['name']} version {_get_version_to_publish()}"
  628. )
  629. console.print("Update or enter to keep the current information.")
  630. project["description"] = console.ask(
  631. "short description", default=project.get("description", "")
  632. )
  633. # PyPI only shows the first author.
  634. author = project.get("authors", [{}])[0]
  635. author["name"] = console.ask("Author Name", default=author.get("name", ""))
  636. author["email"] = console.ask("Author Email", default=author.get("email", ""))
  637. console.print(f"Current keywords are: {project.get('keywords') or []}")
  638. keyword_action = console.ask(
  639. "Keep, replace or append?", choices=["k", "r", "a"], default="k"
  640. )
  641. new_keywords = []
  642. if keyword_action == "r":
  643. new_keywords = (
  644. _process_entered_list(
  645. console.ask("Enter new set of keywords separated by commas")
  646. )
  647. or []
  648. )
  649. project["keywords"] = new_keywords
  650. elif keyword_action == "a":
  651. new_keywords = (
  652. _process_entered_list(
  653. console.ask("Enter new set of keywords separated by commas")
  654. )
  655. or []
  656. )
  657. project["keywords"] = project.get("keywords", []) + new_keywords
  658. if not project.get("urls"):
  659. project["urls"] = {}
  660. project["urls"]["homepage"] = console.ask(
  661. "homepage URL", default=project["urls"].get("homepage", "")
  662. )
  663. project["urls"]["source"] = console.ask(
  664. "source code URL", default=project["urls"].get("source", "")
  665. )
  666. pyproject_toml["project"] = project
  667. try:
  668. with CustomComponents.PYPROJECT_TOML.open("w") as f:
  669. tomlkit.dump(pyproject_toml, f)
  670. except (OSError, TOMLKitError) as ex:
  671. console.error(f"Unable to write to pyproject.toml due to {ex}")
  672. raise typer.Exit(code=1) from ex
  673. def _collect_details_for_gallery():
  674. """Helper to collect details on the custom component to be included in the gallery.
  675. Raises:
  676. Exit: If pyproject.toml file is ill-formed or the request to the backend services fails.
  677. """
  678. import reflex_cli.constants
  679. from reflex_cli.utils import hosting
  680. console.rule("Authentication with Reflex Services")
  681. console.print("First let's log in to Reflex backend services.")
  682. access_token, _ = hosting.authenticated_token()
  683. if not access_token:
  684. console.error(
  685. "Unable to authenticate with Reflex backend services. Make sure you are logged in."
  686. )
  687. raise typer.Exit(code=1)
  688. console.rule("Custom Component Information")
  689. params = {}
  690. package_name = None
  691. try:
  692. package_name = _get_package_config(exit_on_fail=False)["project"]["name"]
  693. except (TOMLKitError, KeyError) as ex:
  694. console.debug(
  695. f"Unable to read from pyproject.toml in current directory due to {ex}"
  696. )
  697. package_name = console.ask("[ Published python package name ]")
  698. console.print(f"[ Custom component package name ] : {package_name}")
  699. params["package_name"] = package_name
  700. post_custom_components_gallery_endpoint = (
  701. f"{reflex_cli.constants.Hosting.HOSTING_SERVICE}/custom-components/gallery"
  702. )
  703. # Check the backend services if the user is allowed to update information of this package is already shared.
  704. try:
  705. console.debug(
  706. f"Checking if user has permission to upsert information for {package_name} by POST."
  707. )
  708. # Send a POST request to achieve two things at once:
  709. # 1. Check if the package is already shared by the user. If not, the backend will return 403.
  710. # 2. If this package is not shared before, this request records the package name in the backend.
  711. response = httpx.post(
  712. post_custom_components_gallery_endpoint,
  713. headers={"Authorization": f"Bearer {access_token}"},
  714. data=params,
  715. )
  716. if response.status_code == httpx.codes.FORBIDDEN:
  717. console.error(
  718. f"{package_name} is owned by another user. Unable to update the information for it."
  719. )
  720. raise typer.Exit(code=1)
  721. response.raise_for_status()
  722. except httpx.HTTPError as he:
  723. console.error(f"Unable to complete request due to {he}.")
  724. raise typer.Exit(code=1) from he
  725. files = []
  726. if (image_file_and_extension := _get_file_from_prompt_in_loop()) is not None:
  727. files.append(
  728. ("files", (image_file_and_extension[1], image_file_and_extension[0]))
  729. )
  730. demo_url = None
  731. while True:
  732. demo_url = (
  733. console.ask(
  734. "[ Full URL of deployed demo app, e.g. `https://my-app.reflex.run` ] (enter to skip)"
  735. )
  736. or None
  737. )
  738. if _validate_url_with_protocol_prefix(demo_url):
  739. break
  740. if demo_url:
  741. params["demo_url"] = demo_url
  742. # Now send the post request to Reflex backend services.
  743. try:
  744. console.debug(f"Sending custom component data: {params}")
  745. response = httpx.post(
  746. post_custom_components_gallery_endpoint,
  747. headers={"Authorization": f"Bearer {access_token}"},
  748. data=params,
  749. files=files,
  750. timeout=POST_CUSTOM_COMPONENTS_GALLERY_TIMEOUT,
  751. )
  752. response.raise_for_status()
  753. except httpx.HTTPError as he:
  754. console.error(f"Unable to complete request due to {he}.")
  755. raise typer.Exit(code=1) from he
  756. console.info("Custom component information successfully shared!")
  757. def _validate_url_with_protocol_prefix(url: str | None) -> bool:
  758. """Validate the URL with protocol prefix. Empty string is acceptable.
  759. Args:
  760. url: the URL string to check.
  761. Returns:
  762. Whether the entered URL is acceptable.
  763. """
  764. return not url or (url.startswith("http://") or url.startswith("https://"))
  765. def _get_file_from_prompt_in_loop() -> tuple[bytes, str] | None:
  766. image_file = file_extension = None
  767. while image_file is None:
  768. image_filepath = Path(
  769. console.ask("Upload a preview image of your demo app (enter to skip)") # pyright: ignore [reportArgumentType]
  770. )
  771. if not image_filepath:
  772. break
  773. file_extension = image_filepath.suffix
  774. try:
  775. image_file = image_filepath.read_bytes()
  776. except OSError as ose:
  777. console.error(f"Unable to read the {file_extension} file due to {ose}")
  778. raise typer.Exit(code=1) from ose
  779. else:
  780. return image_file, file_extension
  781. console.debug(f"File extension detected: {file_extension}")
  782. return None
  783. @custom_components_cli.command(name="share")
  784. def share_more_detail(
  785. loglevel: constants.LogLevel | None = typer.Option(
  786. None, help="The log level to use."
  787. ),
  788. ):
  789. """Collect more details on the published package for gallery.
  790. Args:
  791. loglevel: The log level to use.
  792. """
  793. console.set_log_level(loglevel or get_config().loglevel)
  794. _collect_details_for_gallery()
  795. @custom_components_cli.command()
  796. def install(
  797. loglevel: constants.LogLevel | None = typer.Option(
  798. None, help="The log level to use."
  799. ),
  800. ):
  801. """Install package from this local custom component in editable mode.
  802. Args:
  803. loglevel: The log level to use.
  804. Raises:
  805. Exit: If unable to install the current directory in editable mode.
  806. """
  807. console.set_log_level(loglevel or get_config().loglevel)
  808. if _pip_install_on_demand(package_name=".", install_args=["-e"]):
  809. console.info("Package installed successfully!")
  810. else:
  811. raise typer.Exit(code=1)