custom_components.py 33 KB

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